[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

@@ -21,6 +21,7 @@ from .utils.kv_utils import (
build_rank_aware_send_keys,
get_kv_target_ranks,
get_local_tp_rank,
get_omni_replica_id,
get_tp_world_size,
kv_zmq_port,
merge_received_rank_shards,
@@ -415,7 +416,13 @@ class OmniKVTransferManager:
stage_int = int(self.config.from_stage) if self.config.from_stage is not None else 0
except (TypeError, ValueError):
stage_int = 0
zmq_port = kv_zmq_port(base_port, stage_int, self._tp_topo.local_rank)
replica_id = get_omni_replica_id()
zmq_port = kv_zmq_port(
base_port,
stage_int,
self._tp_topo.local_rank,
replica_id=replica_id,
)
if self.config.need_send_cache:
c_extra["role"] = "sender"
@@ -26,9 +26,17 @@ KV_TRANSFER_PORT_OFFSET = 100
# Port stride between TP ranks so each worker binds a unique ZMQ port
# when TP > 1. Must be larger than the maximum number of pipeline stages.
# Formula: zmq_port = base + KV_TRANSFER_PORT_OFFSET + rank * STRIDE + stage
# Formula:
# zmq_port = base + KV_TRANSFER_PORT_OFFSET
# + replica * KV_REPLICA_PORT_STRIDE
# + rank * KV_RANK_PORT_STRIDE
# + stage
KV_RANK_PORT_STRIDE = 16
# Port stride between Omni replicas of the same stage. This reserves a
# comfortably sized block per replica for TP-rank and stage offsets.
KV_REPLICA_PORT_STRIDE = 1024
def initialize_connectors_from_config(
config_path: str | Path | None = None,
@@ -16,7 +16,7 @@ from vllm.distributed.parallel_state import (
)
from vllm.logger import init_logger
from .initialization import KV_RANK_PORT_STRIDE, KV_TRANSFER_PORT_OFFSET
from .initialization import KV_RANK_PORT_STRIDE, KV_REPLICA_PORT_STRIDE, KV_TRANSFER_PORT_OFFSET
logger = init_logger(__name__)
@@ -94,20 +94,42 @@ def get_tp_world_size() -> int:
return 1
def get_omni_replica_id() -> int:
"""Return the Omni replica id for this worker process."""
try:
replica_id = int(os.environ.get("VLLM_OMNI_REPLICA_ID", "0"))
except (ValueError, TypeError):
return 0
return max(replica_id, 0)
# ------------------------------------------------------------------ #
# ZMQ port computation
# ------------------------------------------------------------------ #
def kv_zmq_port(base_port: int, from_stage: int, local_rank: int = 0) -> int:
def kv_zmq_port(
base_port: int,
from_stage: int,
local_rank: int = 0,
replica_id: int | None = None,
) -> int:
"""Compute the ZMQ port for a KV-transfer connector.
Each TP rank gets its own port so that TP > 1 deployments do not
cause ``EADDRINUSE`` when multiple sender workers bind on the same
host. The formula is backward-compatible: rank 0 produces the same
port as the previous ``base + OFFSET + stage`` formula.
Each Omni replica and TP rank gets its own port so multi-replica or
TP > 1 deployments do not cause ``EADDRINUSE`` when multiple sender
workers bind on the same host. The formula is backward-compatible:
replica 0 / rank 0 produces the previous ``base + OFFSET + stage`` port.
"""
return base_port + KV_TRANSFER_PORT_OFFSET + local_rank * KV_RANK_PORT_STRIDE + from_stage
replica = get_omni_replica_id() if replica_id is None else max(int(replica_id), 0)
return (
base_port
+ KV_TRANSFER_PORT_OFFSET
+ replica * KV_REPLICA_PORT_STRIDE
+ local_rank * KV_RANK_PORT_STRIDE
+ from_stage
)
# ------------------------------------------------------------------ #
@@ -8,18 +8,21 @@ from .load_balancer import (
RandomBalancer,
RoundRobinBalancer,
Task,
build_load_balancer_factory,
)
from .messages import InstanceEvent, InstanceInfo, InstanceList, StageStatus
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_coordinator import OmniCoordinator
from .runtime import OmniCoordinatorRuntime
__all__ = [
"OmniCoordinator",
"StageStatus",
"InstanceEvent",
"InstanceInfo",
"InstanceList",
"OmniCoordinatorRuntime",
"ReplicaStatus",
"ReplicaEvent",
"ReplicaInfo",
"ReplicaList",
"OmniCoordClientForStage",
"OmniCoordClientForHub",
"Task",
@@ -28,4 +31,5 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -6,17 +6,18 @@ 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
from .messages import InstanceInfo
from .messages import ReplicaInfo
class Task(TypedDict, total=False):
"""Task structure passed from async_omni (stage.submit(task)).
"""Task structure passed to ``StagePool.pick`` / ``LoadBalancer.select``.
Mirrors the dict built in AsyncOmni with request_id, engine_inputs,
sampling_params. Future load-balancing policies may use these fields.
Mirrors the dict built around a stage submission with request_id and any
payload-related fields a future load-balancing policy might inspect.
"""
request_id: str
@@ -28,10 +29,7 @@ class LoadBalancingPolicy(str, Enum):
"""Enumeration for load balancing policies.
These policies are used by :class:`LoadBalancer` implementations to route
tasks to a subset of available instances.
TODO(NumberWan): Map enum values to balancer classes when OmniCoordinator
integration lands. Tracked in https://github.com/vllm-project/vllm-omni/pull/2448
tasks to a subset of available replicas.
"""
RANDOM = "random"
@@ -42,74 +40,60 @@ class LoadBalancingPolicy(str, Enum):
class LoadBalancer(ABC):
"""Abstract base class for load balancers.
Subclasses implement :meth:`select` to choose an instance for a given task.
Subclasses implement :meth:`select` to choose a replica for a given task.
"""
@abstractmethod
def select(self, task: Task, instances: list[InstanceInfo]) -> int:
"""Route a task to one of the available instances.
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int:
"""Route a task to one of the available replicas.
Args:
task: The task to route. Not used by the random policy but reserved
for future strategies that may inspect task metadata.
instances: List of available instances to choose from.
replicas: List of available replicas to choose from.
Returns:
Index of the selected instance in ``instances``.
Index of the selected replica in ``replicas``.
Raises:
ValueError: If ``instances`` is empty.
ValueError: If ``replicas`` is empty.
"""
raise NotImplementedError
class RandomBalancer(LoadBalancer):
"""Load balancer that selects an instance uniformly at random.
"""Load balancer that selects a replica uniformly at random."""
It intentionally ignores the task payload and chooses a random index from
the provided instance list. More sophisticated policies (e.g. round-robin,
least-queue-length) can be implemented as additional subclasses of
:class:`LoadBalancer`.
"""
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
if not instances:
raise ValueError("instances must not be empty")
return random.randrange(len(instances))
return random.randrange(len(replicas))
class RoundRobinBalancer(LoadBalancer):
"""Load balancer that selects instances in a round-robin fashion.
"""Load balancer that selects replicas in a round-robin fashion.
This implementation keeps a running index modulo ``len(instances)``. It
therefore depends on the **order and stable meaning** of the ``instances``
This implementation keeps a running index modulo ``len(replicas)``. It
therefore depends on the **order and stable meaning** of the ``replicas``
list between calls. If the list length or ordering changes, the sequence
of picks may skip or repeat entries relative to a fixed set of backends.
When instance membership changes dynamically, callers should reset routing
state—for example by constructing a new ``RoundRobinBalancer`` or resetting
``_next_index``—similar to rebuilding ``itertools.cycle`` after mutating
the instance list (as in vLLM's disaggregated proxy examples).
Concurrency: ``select`` is synchronous and is expected to run on the
coordinator asyncio event loop thread without ``await`` inside this
method, so a single invocation is not interleaved with another on that
thread. A :class:`threading.Lock` still serializes updates to
``_next_index`` for callers that might invoke ``select`` from multiple
threads or alongside threaded infrastructure (e.g. ZMQ receive threads).
Concurrency: a ``threading.Lock`` serializes updates to ``_next_index``
for callers that invoke ``select`` from multiple threads or alongside
threaded infrastructure (e.g. ZMQ receive threads).
"""
def __init__(self, start_index: int = 0) -> None:
self._next_index = start_index
self._lock = threading.Lock()
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
if not instances:
raise ValueError("instances must not be empty")
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
n = len(instances)
n = len(replicas)
with self._lock:
idx = self._next_index % n
self._next_index = (self._next_index + 1) % n
@@ -117,27 +101,43 @@ class RoundRobinBalancer(LoadBalancer):
class LeastQueueLengthBalancer(LoadBalancer):
"""Select the instance with the smallest ``queue_length``.
"""Select the replica with the smallest ``queue_length``.
If multiple instances share the same minimum queue length, one of them is
If multiple replicas share the same minimum queue length, one of them is
chosen uniformly at random.
Raises:
ValueError: If any instance has a negative ``queue_length``.
ValueError: If any replica has a negative ``queue_length``.
"""
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
if not instances:
raise ValueError("instances must not be empty")
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
queue_lengths = [inst.queue_length for inst in instances]
queue_lengths = [rep.queue_length for rep in replicas]
if any(q < 0 for q in queue_lengths):
raise ValueError("queue_length must be non-negative for all instances")
raise ValueError("queue_length must be non-negative for all replicas")
min_q = min(queue_lengths)
candidates = [i for i, q in enumerate(queue_lengths) if q == min_q]
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,4 +145,5 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -7,55 +7,55 @@ from dataclasses import dataclass
from enum import Enum
class StageStatus(str, Enum):
"""Enumeration for stage instance status."""
class ReplicaStatus(str, Enum):
"""Enumeration for stage replica status."""
UP = "up" # Instance is ready and available
DOWN = "down" # Instance is shutdown gracefully
ERROR = "error" # Instance encountered an error or timeout
UP = "up" # Replica is ready and available
DOWN = "down" # Replica is shutdown gracefully
ERROR = "error" # Replica encountered an error or timeout
@dataclass
class InstanceEvent:
class ReplicaEvent:
"""Wire payload from OmniCoordClientForStage to OmniCoordinator.
Schema for Stage → Coordinator events over ZMQ:
input_addr, output_addr, stage_id, status, queue_length, event_type.
"""
input_addr: str # Stage instance input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage instance output ZMQ address (e.g., "tcp://host:port")
input_addr: str # Stage replica input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage replica output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID
event_type: str # "update" | "heartbeat"
status: StageStatus # Current status
status: ReplicaStatus # Current status
queue_length: int # Current queue length
@dataclass
class InstanceInfo:
"""Metadata for a single stage instance.
class ReplicaInfo:
"""Metadata for a single stage replica.
This type is stored in OmniCoordinator's internal registry and is also
published to hubs via :class:`InstanceList`.
published to hubs via :class:`ReplicaList`.
"""
input_addr: str # Stage instance input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage instance output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID of this instance
status: StageStatus # Current status of the instance
queue_length: int # Current queue length of this instance
input_addr: str # Stage replica input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage replica output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID of this replica
status: ReplicaStatus # Current status of the replica
queue_length: int # Current queue length of this replica
last_heartbeat: float # Timestamp of the last heartbeat received (seconds)
registered_at: float # Timestamp when the instance was registered (seconds)
registered_at: float # Timestamp when the replica was registered (seconds)
@dataclass
class InstanceList:
"""Container for instance list updates.
class ReplicaList:
"""Container for replica list updates.
OmniCoordinator publishes an :class:`InstanceList` whenever its view of
active instances changes. OmniCoordClientForHub caches the latest value
OmniCoordinator publishes a :class:`ReplicaList` whenever its view of
active replicas changes. OmniCoordClientForHub caches the latest value
and exposes it to AsyncOmni and the load balancer.
"""
instances: list[InstanceInfo]
replicas: list[ReplicaInfo]
timestamp: float # Time when the list was last updated (seconds)
@@ -9,16 +9,16 @@ from typing import Any
import zmq
from .messages import InstanceInfo, InstanceList, StageStatus
from .messages import ReplicaInfo, ReplicaList, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordClientForHub:
"""Client for AsyncOmni side to receive instance list updates.
"""Client for AsyncOmni side to receive replica list updates.
This client maintains a SUB socket connected to OmniCoordinator's PUB
endpoint and caches the latest :class:`InstanceList` in memory for use by
endpoint and caches the latest :class:`ReplicaList` in memory for use by
the load balancer and routing logic.
"""
@@ -28,7 +28,7 @@ class OmniCoordClientForHub:
self._ctx = zmq.Context()
self._lock = threading.Lock()
self._instance_list: InstanceList | None = None
self._replica_list: ReplicaList | None = None
self._closed = False
self._stop_event = threading.Event()
self._init_done = threading.Event()
@@ -41,29 +41,29 @@ class OmniCoordClientForHub:
if self._init_error:
raise RuntimeError(f"Failed to connect to coordinator at {self._coord_zmq_addr}") from self._init_error[0]
def _decode_instance_list(self, payload: dict[str, Any]) -> InstanceList:
"""Convert a JSON-decoded dict into an :class:`InstanceList`."""
instances_payload = payload.get("instances", [])
instances: list[InstanceInfo] = []
for inst in instances_payload:
instances.append(
InstanceInfo(
input_addr=inst["input_addr"],
output_addr=inst["output_addr"],
stage_id=int(inst["stage_id"]),
status=StageStatus(inst["status"]),
queue_length=int(inst["queue_length"]),
last_heartbeat=float(inst["last_heartbeat"]),
registered_at=float(inst["registered_at"]),
def _decode_replica_list(self, payload: dict[str, Any]) -> ReplicaList:
"""Convert a JSON-decoded dict into a :class:`ReplicaList`."""
replicas_payload = payload.get("replicas", [])
replicas: list[ReplicaInfo] = []
for rep in replicas_payload:
replicas.append(
ReplicaInfo(
input_addr=rep["input_addr"],
output_addr=rep["output_addr"],
stage_id=int(rep["stage_id"]),
status=ReplicaStatus(rep["status"]),
queue_length=int(rep["queue_length"]),
last_heartbeat=float(rep["last_heartbeat"]),
registered_at=float(rep["registered_at"]),
)
)
timestamp = float(payload.get("timestamp", time()))
return InstanceList(instances=instances, timestamp=timestamp)
return ReplicaList(replicas=replicas, timestamp=timestamp)
def _recv_loop(self) -> None:
"""Background loop that receives and caches instance lists."""
sub = None
"""Background loop that receives and caches replica lists."""
sub: zmq.Socket | None = None
try:
sub = self._ctx.socket(zmq.SUB)
sub.setsockopt(zmq.SUBSCRIBE, b"")
@@ -115,9 +115,9 @@ class OmniCoordClientForHub:
try:
payload = json.loads(data.decode("utf-8"))
inst_list = self._decode_instance_list(payload)
rep_list = self._decode_replica_list(payload)
with self._lock:
self._instance_list = inst_list
self._replica_list = rep_list
except (
json.JSONDecodeError,
KeyError,
@@ -125,7 +125,7 @@ class OmniCoordClientForHub:
TypeError,
AttributeError,
) as e:
logger.warning("Invalid instance list message, skipping: %s", e)
logger.warning("Invalid replica list message, skipping: %s", e)
finally:
try:
if sub is not None:
@@ -137,22 +137,22 @@ class OmniCoordClientForHub:
except zmq.ZMQError:
pass
def get_instance_list(self) -> InstanceList:
"""Return the latest cached :class:`InstanceList`.
def get_replica_list(self) -> ReplicaList:
"""Return the latest cached :class:`ReplicaList`.
If no update has been received yet, returns an empty list with
``timestamp=0.0``.
"""
with self._lock:
if self._instance_list is None:
return InstanceList(instances=[], timestamp=0.0)
return self._instance_list
if self._replica_list is None:
return ReplicaList(replicas=[], timestamp=0.0)
return self._replica_list
def get_instances_for_stage(self, stage_id: int) -> InstanceList:
"""Return instances filtered by ``stage_id``."""
base = self.get_instance_list()
filtered = [inst for inst in base.instances if inst.stage_id == stage_id]
return InstanceList(instances=filtered, timestamp=base.timestamp)
def get_replicas_for_stage(self, stage_id: int) -> ReplicaList:
"""Return replicas filtered by ``stage_id``."""
base = self.get_replica_list()
filtered = [rep for rep in base.replicas if rep.stage_id == stage_id]
return ReplicaList(replicas=filtered, timestamp=base.timestamp)
def close(self) -> None:
"""Close the SUB socket and stop the background thread."""
@@ -1,24 +1,26 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
import json
import logging
import threading
import time
from collections.abc import Callable
from dataclasses import asdict
import zmq
from .messages import InstanceEvent, StageStatus
from .messages import ReplicaEvent, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordClientForStage:
"""Client used by stage instances to send events to OmniCoordinator.
"""Client used by stage replicas to send events to OmniCoordinator.
This client maintains a DEALER socket connected to OmniCoordinator's
ROUTER endpoint and sends JSON-encoded events describing instance status.
ROUTER endpoint and sends JSON-encoded events describing replica status.
"""
def __init__(
@@ -42,13 +44,18 @@ class OmniCoordClientForStage:
self._socket.close()
raise RuntimeError(f"Failed to connect to coordinator at {self._coord_zmq_addr}: {e}") from e
self._status = StageStatus.UP
self._status = ReplicaStatus.UP
self._queue_length = 0
self._closed = False
self._closing = False
self._heartbeat_interval = 5.0
self._stop_event = threading.Event()
self._send_lock = threading.RLock()
# Optional hook invoked from the heartbeat thread before each
# heartbeat send. Stages set this to refresh ``queue_length`` (or any
# other field) just-in-time. Exceptions raised by the hook are
# suppressed and logged.
self._on_heartbeat: Callable[[], None] | None = None
self._send_event("update")
@@ -100,11 +107,13 @@ class OmniCoordClientForStage:
return False
def _send_event(self, event_type: str) -> None:
"""Send an InstanceEvent to OmniCoordinator.
"""Send a ReplicaEvent to OmniCoordinator.
Wire format: input_addr, output_addr, stage_id, status, queue_length, event_type.
For "update": includes status and queue_length from instance state.
For "heartbeat": status and queue_length are null.
For "update": includes status and queue_length from replica state.
For "heartbeat": includes the latest queue_length (refreshed by the
optional ``_on_heartbeat`` hook) so the coordinator can propagate
live load to load balancers between explicit ``update`` events.
On send failure (ZMQError / RuntimeError), attempts to reconnect up
to 3 times (5s sleep each) and retries the send once after a
@@ -114,7 +123,7 @@ class OmniCoordClientForStage:
if self._closed:
raise RuntimeError("Client already closed")
event = InstanceEvent(
event = ReplicaEvent(
input_addr=self._input_addr,
output_addr=self._output_addr,
stage_id=self._stage_id,
@@ -147,10 +156,10 @@ class OmniCoordClientForStage:
def update_info(
self,
status: StageStatus | None = None,
status: ReplicaStatus | None = None,
queue_length: int | None = None,
) -> None:
"""Update instance information and notify OmniCoordinator.
"""Update replica information and notify OmniCoordinator.
At least one of ``status`` or ``queue_length`` must be provided.
"""
@@ -174,6 +183,15 @@ class OmniCoordClientForStage:
if self._closed:
break
# Invoke the optional pre-heartbeat hook so callers (e.g. the
# engine subprocess) can refresh ``queue_length`` from live state
# before the heartbeat is sent. Exceptions are swallowed so a
# buggy hook never breaks the heartbeat loop.
hook = self._on_heartbeat
if hook is not None:
with contextlib.suppress(Exception):
hook()
try:
self._send_event("heartbeat")
except (RuntimeError, zmq.ZMQError) as e:
@@ -199,7 +217,7 @@ class OmniCoordClientForStage:
self._closing = True
# Mark status as DOWN and send one last update.
self._status = StageStatus.DOWN
self._status = ReplicaStatus.DOWN
try:
self._send_event("update")
except (RuntimeError, zmq.ZMQError):
@@ -11,22 +11,22 @@ from typing import Any
import zmq
from .messages import InstanceEvent, InstanceInfo, InstanceList, StageStatus
from .messages import ReplicaEvent, ReplicaInfo, ReplicaList, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordinator:
"""Coordinator for stage instances and hub clients.
"""Coordinator for stage replicas and hub clients.
This service receives instance events from :class:`OmniCoordClientForStage`
via a ZMQ ROUTER socket and publishes active instance lists to
This service receives replica events from :class:`OmniCoordClientForStage`
via a ZMQ ROUTER socket and publishes active replica lists to
:class:`OmniCoordClientForHub` via a PUB socket.
The coordinator maintains an in-memory registry of all known instances,
The coordinator maintains an in-memory registry of all known replicas,
including their status, queue length, and heartbeat timestamps. A
background thread periodically checks for heartbeat timeouts and marks
unhealthy instances as ``StageStatus.ERROR``.
unhealthy replicas as ``ReplicaStatus.ERROR``.
"""
def __init__(
@@ -40,7 +40,7 @@ class OmniCoordinator:
Args:
router_zmq_addr: ZMQ address to bind the ROUTER socket.
pub_zmq_addr: ZMQ address to bind the PUB socket.
heartbeat_timeout: Seconds before an instance is considered
heartbeat_timeout: Seconds before a replica is considered
unhealthy if no heartbeat / update is received.
"""
self._router_zmq_addr = router_zmq_addr
@@ -55,7 +55,7 @@ class OmniCoordinator:
self._pub = self._ctx.socket(zmq.PUB)
self._pub.bind(self._pub_zmq_addr)
self._instances: dict[str, InstanceInfo] = {}
self._replicas: dict[str, ReplicaInfo] = {}
self._lock = threading.Lock()
self._pub_lock = threading.Lock()
@@ -75,43 +75,43 @@ class OmniCoordinator:
self._periodic_thread = threading.Thread(target=self._periodic_loop, daemon=True)
self._periodic_thread.start()
def get_active_instances(self) -> InstanceList:
"""Return an :class:`InstanceList` of active (UP) instances only."""
def get_active_replicas(self) -> ReplicaList:
"""Return a :class:`ReplicaList` of active (UP) replicas only."""
with self._lock:
active = [inst for inst in self._instances.values() if inst.status == StageStatus.UP]
return InstanceList(instances=active, timestamp=time())
active = [rep for rep in self._replicas.values() if rep.status == ReplicaStatus.UP]
return ReplicaList(replicas=active, timestamp=time())
def add_new_instance(self, event: InstanceEvent) -> None:
"""Add a new instance based on an incoming event."""
def add_new_replica(self, event: ReplicaEvent) -> None:
"""Add a new replica based on an incoming event."""
with self._lock:
self._add_new_instance_locked(event)
self._add_new_replica_locked(event)
self._schedule_broadcast()
def update_instance_info(self, event: InstanceEvent) -> None:
"""Update an existing instance based on an incoming event."""
def update_replica_info(self, event: ReplicaEvent) -> None:
"""Update an existing replica based on an incoming event."""
with self._lock:
self._update_instance_info_locked(event)
self._update_replica_info_locked(event)
self._schedule_broadcast()
def remove_instance(self, event: InstanceEvent) -> None:
"""Mark an instance as removed / down based on an incoming event.
def remove_replica(self, event: ReplicaEvent) -> None:
"""Mark a replica as removed / down based on an incoming event.
This marks the instance's status as DOWN or ERROR (depending on the
This marks the replica's status as DOWN or ERROR (depending on the
event) but keeps it in the internal registry. It is removed from the
*active* instance list published to hubs.
*active* replica list published to hubs.
"""
with self._lock:
self._remove_instance_locked(event)
self._remove_replica_locked(event)
self._schedule_broadcast()
def publish_instance_list_update(self) -> bool:
"""Publish the current active instance list to all subscribers.
def publish_replica_list_update(self) -> bool:
"""Publish the current active replica list to all subscribers.
Returns:
True if the PUB send succeeded, False if it was dropped (e.g.
socket not ready when using ``zmq.NOBLOCK``).
"""
active_list = self.get_active_instances()
active_list = self.get_active_replicas()
payload = asdict(active_list)
data = json.dumps(payload).encode("utf-8")
@@ -133,12 +133,12 @@ class OmniCoordinator:
with self._pending_lock:
self._pending_broadcast = True
def _mark_instance_error_locked(self, info: InstanceInfo) -> None:
"""Mark instance as ERROR (e.g. after heartbeat timeout)."""
info.status = StageStatus.ERROR
def _mark_replica_error_locked(self, info: ReplicaInfo) -> None:
"""Mark replica as ERROR (e.g. after heartbeat timeout)."""
info.status = ReplicaStatus.ERROR
def _check_heartbeat_timeouts(self) -> None:
"""Mark instances as ERROR if their heartbeat has timed out."""
"""Mark replicas as ERROR if their heartbeat has timed out."""
now = time()
timed_out = False
gc_ttl = 600.0 # 10 minutes
@@ -146,17 +146,17 @@ class OmniCoordinator:
with self._lock:
to_delete: list[str] = []
for input_addr, info in self._instances.items():
if info.status == StageStatus.UP and now - info.last_heartbeat > self._heartbeat_timeout:
self._mark_instance_error_locked(info)
for input_addr, info in self._replicas.items():
if info.status == ReplicaStatus.UP and now - info.last_heartbeat > self._heartbeat_timeout:
self._mark_replica_error_locked(info)
timed_out = True
elif info.status in (StageStatus.DOWN, StageStatus.ERROR) and now - info.last_heartbeat > gc_ttl:
elif info.status in (ReplicaStatus.DOWN, ReplicaStatus.ERROR) and now - info.last_heartbeat > gc_ttl:
to_delete.append(input_addr)
for input_addr in to_delete:
del self._instances[input_addr]
del self._replicas[input_addr]
if timed_out:
# Instance liveness changed; request broadcast.
# Replica liveness changed; request broadcast.
self._schedule_broadcast()
def close(self) -> None:
@@ -187,22 +187,22 @@ class OmniCoordinator:
except zmq.ZMQError:
pass
def _parse_instance_event(self, data: dict[str, Any]) -> InstanceEvent | None:
"""Parse wire payload dict into InstanceEvent. Returns None if invalid."""
def _parse_replica_event(self, data: dict[str, Any]) -> ReplicaEvent | None:
"""Parse wire payload dict into ReplicaEvent. Returns None if invalid."""
try:
return InstanceEvent(
return ReplicaEvent(
input_addr=str(data["input_addr"]),
output_addr=str(data["output_addr"]),
stage_id=int(data["stage_id"]),
event_type=str(data["event_type"]),
status=StageStatus(data.get("status")),
status=ReplicaStatus(data.get("status")),
queue_length=data.get("queue_length"),
)
except (KeyError, ValueError, TypeError):
return None
def _recv_loop(self) -> None:
"""Background loop that receives and processes instance events."""
"""Background loop that receives and processes replica events."""
while self._running:
try:
frames = self._router.recv_multipart()
@@ -219,12 +219,12 @@ class OmniCoordinator:
payload = frames[-1]
try:
data = json.loads(payload.decode("utf-8"))
event = self._parse_instance_event(data)
event = self._parse_replica_event(data)
except json.JSONDecodeError as e:
logger.warning("Invalid JSON in instance event, dropping: %s", e)
logger.warning("Invalid JSON in replica event, dropping: %s", e)
continue
if event is None:
logger.warning("Malformed instance event, dropping")
logger.warning("Malformed replica event, dropping")
continue
self._handle_event(event)
@@ -234,7 +234,10 @@ class OmniCoordinator:
Heartbeat timeouts are checked on their original cadence, while all
broadcast requests are coalesced and flushed at most once per
``_publish_min_interval``.
``_publish_min_interval``. The heartbeat-check tick also schedules a
keepalive broadcast so late-joining hubs (which miss any PUB sends
that happened before their SUB connected) catch up within at most
``heartbeat_interval`` seconds.
"""
heartbeat_interval = max(1.0, min(self._heartbeat_timeout / 2.0, 5.0))
loop_interval = self._publish_min_interval
@@ -245,6 +248,13 @@ class OmniCoordinator:
if now - last_heartbeat_check >= heartbeat_interval:
self._check_heartbeat_timeouts()
# Keepalive broadcast: ZMQ PUB doesn't queue for late
# subscribers, so an OmniCoordClientForHub that connects
# after the initial UP events miss them entirely and would
# never see the current replica list otherwise. Scheduling a
# broadcast on every heartbeat tick caps that staleness at
# ``heartbeat_interval`` without flooding the wire.
self._schedule_broadcast()
last_heartbeat_check = now
with self._pending_lock:
@@ -256,43 +266,51 @@ class OmniCoordinator:
continue
# Publish outside lock. Clear pending only on success.
if self.publish_instance_list_update():
if self.publish_replica_list_update():
with self._pending_lock:
self._pending_broadcast = False
if self._stop_event.wait(timeout=loop_interval):
break
def _handle_event(self, event: InstanceEvent) -> None:
def _handle_event(self, event: ReplicaEvent) -> None:
"""Dispatch an incoming event to the appropriate handler."""
try:
input_addr = event.input_addr
# Heartbeat: only update last_heartbeat; if previously ERROR,
# promote back to UP and broadcast once.
# Heartbeat: refresh last_heartbeat and queue_length. The stage
# client refreshes queue_length just-in-time via its
# ``_on_heartbeat`` hook, so heartbeats are the only periodic
# source of live load for LeastQueueLengthBalancer; failing to
# propagate it here would let the policy route on stale data.
# If previously ERROR, promote back to UP and broadcast once.
if event.event_type == "heartbeat":
promote = False
queue_changed = False
with self._lock:
info = self._instances.get(input_addr)
info = self._replicas.get(input_addr)
if info is not None:
info.last_heartbeat = time()
if info.status == StageStatus.ERROR:
info.status = StageStatus.UP
if event.queue_length is not None and info.queue_length != event.queue_length:
info.queue_length = event.queue_length
queue_changed = True
if info.status == ReplicaStatus.ERROR:
info.status = ReplicaStatus.UP
promote = True
if promote:
if promote or queue_changed:
self._schedule_broadcast()
return
# Check-and-act under single lock to avoid TOCTOU race (duplicate
# registration when concurrent events arrive for the same instance).
# registration when concurrent events arrive for the same replica).
with self._lock:
if input_addr not in self._instances:
self._add_new_instance_locked(event)
if input_addr not in self._replicas:
self._add_new_replica_locked(event)
else:
if event.status == StageStatus.DOWN:
self._remove_instance_locked(event)
if event.status == ReplicaStatus.DOWN:
self._remove_replica_locked(event)
else:
self._update_instance_info_locked(event)
self._update_replica_info_locked(event)
# Any non-heartbeat state change that affects the active list
# is coalesced and flushed via the periodic loop.
@@ -300,7 +318,7 @@ class OmniCoordinator:
except (KeyError, ValueError, TypeError) as e:
logger.warning("Dropping malformed event: %s", e)
def _add_new_instance_locked(self, event: InstanceEvent) -> None:
def _add_new_replica_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
if not input_addr:
raise KeyError("input_addr required")
@@ -309,7 +327,7 @@ class OmniCoordinator:
raise KeyError("stage_id required and must be non-negative")
now = time()
info = InstanceInfo(
info = ReplicaInfo(
input_addr=input_addr,
output_addr=event.output_addr,
stage_id=stage_id,
@@ -318,11 +336,11 @@ class OmniCoordinator:
last_heartbeat=now,
registered_at=now,
)
self._instances[input_addr] = info
self._replicas[input_addr] = info
def _update_instance_info_locked(self, event: InstanceEvent) -> None:
def _update_replica_info_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
info = self._instances[input_addr]
info = self._replicas[input_addr]
if event.status is not None:
info.status = event.status
@@ -330,10 +348,10 @@ class OmniCoordinator:
if event.queue_length is not None:
info.queue_length = event.queue_length
def _remove_instance_locked(self, event: InstanceEvent) -> None:
def _remove_replica_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
info = self._instances.get(input_addr)
info = self._replicas.get(input_addr)
if info is None:
return
info.status = StageStatus.DOWN
info.status = ReplicaStatus.DOWN
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""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.
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.
"""
from __future__ import annotations
import logging
from vllm.utils.network_utils import get_open_ports_list
from .omni_coordinator import OmniCoordinator
logger = logging.getLogger(__name__)
class OmniCoordinatorRuntime:
"""Own one :class:`OmniCoordinator` and the two ports it binds.
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`.
"""
def __init__(
self,
*,
host: str,
heartbeat_timeout: float,
) -> None:
if not host:
raise ValueError("host must be a non-empty string")
if heartbeat_timeout <= 0:
raise ValueError("heartbeat_timeout must be positive")
router_port, pub_port = get_open_ports_list(count=2)
self.router_address: str = f"tcp://{host}:{router_port}"
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,
)
logger.info(
"[OmniCoordinatorRuntime] Started (router=%s pub=%s heartbeat_timeout=%.1fs)",
self.router_address,
self.pub_address,
heartbeat_timeout,
)
def close(self) -> None:
"""Tear down the underlying coordinator. Idempotent."""
if self._closed:
return
self._closed = True
try:
self._coordinator.close()
except Exception:
logger.exception("[OmniCoordinatorRuntime] coordinator close failed")