[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

+86 -64
View File
@@ -1,8 +1,7 @@
"""Stage Diffusion Client for vLLM-Omni multi-stage runtime.
Spawns StageDiffusionProc in a subprocess and communicates via ZMQ
(PUSH/PULL) to expose the same interface the Orchestrator expects
from any stage client.
Owns the frontend-side ZMQ sockets for StageDiffusionProc and exposes the
interface the Orchestrator expects from a stage client.
"""
from __future__ import annotations
@@ -23,15 +22,14 @@ from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.stage_diffusion_proc import (
StageDiffusionProc,
complete_diffusion_handshake,
spawn_diffusion_proc,
StageDiffusionProcManager,
)
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
from vllm_omni.engine.stage_client import StageClientBase
from vllm_omni.engine.stage_init_utils import StageMetadata, terminate_alive_proc
from vllm_omni.engine.stage_init_utils import StageMetadata
from vllm_omni.outputs import OmniRequestOutput
if TYPE_CHECKING:
@@ -54,8 +52,17 @@ def create_diffusion_client(
from vllm_omni.diffusion.inline_stage_diffusion_client import InlineStageDiffusionClient
return InlineStageDiffusionClient(model, od_config, metadata, batch_size=batch_size)
return StageDiffusionClient(
model, od_config, metadata, stage_init_timeout=stage_init_timeout, batch_size=batch_size
proc_manager = StageDiffusionProcManager(
model=model,
od_config=od_config,
stage_init_timeout=stage_init_timeout,
)
return StageDiffusionClient.from_addresses(
metadata,
request_address=proc_manager.addresses.inputs[0],
response_address=proc_manager.addresses.outputs[0],
proc_manager=proc_manager,
batch_size=batch_size,
)
@@ -74,16 +81,20 @@ class StageDiffusionClient(StageClientBase):
def __init__(
self,
model: str,
od_config: OmniDiffusionConfig,
metadata: StageMetadata,
stage_init_timeout: int,
request_address: str,
response_address: str,
*,
proc_manager: StageDiffusionProcManager | None = None,
batch_size: int = 1,
) -> None:
# Spawn StageDiffusionProc subprocess and wait for READY.
proc, handshake_address, request_address, response_address = spawn_diffusion_proc(model, od_config)
complete_diffusion_handshake(proc, handshake_address, stage_init_timeout)
self._initialize_client(metadata, request_address, response_address, proc=proc, batch_size=batch_size)
self._initialize_client(
metadata,
request_address,
response_address,
proc_manager=proc_manager,
batch_size=batch_size,
)
@classmethod
def from_addresses(
@@ -92,19 +103,17 @@ class StageDiffusionClient(StageClientBase):
request_address: str,
response_address: str,
*,
proc: Any = None,
proc_manager: StageDiffusionProcManager | None = None,
batch_size: int = 1,
) -> StageDiffusionClient:
"""Create a client for an already-running diffusion subprocess."""
client = cls.__new__(cls)
client._initialize_client(
return cls(
metadata,
request_address,
response_address,
proc=proc,
proc_manager=proc_manager,
batch_size=batch_size,
)
return client
def _initialize_client(
self,
@@ -112,37 +121,12 @@ class StageDiffusionClient(StageClientBase):
request_address: str,
response_address: str,
*,
proc: Any,
proc_manager: StageDiffusionProcManager | None = None,
batch_size: int,
) -> None:
self.stage_id = metadata.stage_id
self.replica_id = metadata.replica_id
self.final_output = metadata.final_output
self.final_output_type = metadata.final_output_type
self.model_stage = getattr(metadata, "model_stage", None)
self.default_sampling_params = metadata.default_sampling_params
self.requires_multimodal_data = getattr(metadata, "requires_multimodal_data", False)
self.custom_process_input_func = getattr(metadata, "custom_process_input_func", None)
self.engine_input_source = getattr(metadata, "engine_input_source", [])
self._proc = proc
self._owns_process = proc is not None
# Expose the ZMQ addresses on the instance so callers (e.g.
# ``StagePool._client_input_addr``) can identify the diffusion
# replica by its bound address.
self.request_address = request_address
self.response_address = response_address
self._zmq_ctx = zmq.Context()
self._request_socket = self._zmq_ctx.socket(zmq.PUSH)
self._request_socket.connect(request_address)
self._response_socket = self._zmq_ctx.socket(zmq.PULL)
self._response_socket.connect(response_address)
self._response_poller = zmq.asyncio.Poller()
self._response_poller.register(self._response_socket, zmq.POLLIN)
self._encoder = OmniMsgpackEncoder()
self._decoder = OmniMsgpackDecoder()
self._set_stage_metadata(metadata)
self._proc_manager = proc_manager
self._connect_transport(request_address, response_address)
self._output_queue: asyncio.Queue[OmniRequestOutput] = asyncio.Queue()
self._rpc_results: dict[str, Any] = {}
@@ -151,19 +135,48 @@ class StageDiffusionClient(StageClientBase):
self._shutting_down = False
self._engine_dead: bool = False
# Background thread to detect silent process death (SIGKILL, segfault)
# where the subprocess cannot send the ZMQ death sentinel.
# Mirrors MPClient.start_engine_core_monitor() in vLLM.
self._start_proc_monitor()
if self._proc_manager is not None:
self._start_proc_monitor()
logger.info(
"[StageDiffusionClient] stage-%s [rep-%s] initialized (owns_process=%s, batch_size=%d)",
self.stage_id,
self.replica_id,
self._owns_process,
self._proc_manager is not None,
batch_size,
)
def _set_stage_metadata(self, metadata: StageMetadata) -> None:
self.stage_id = metadata.stage_id
self.replica_id = metadata.replica_id
self.final_output = metadata.final_output
self.final_output_type = metadata.final_output_type
self.model_stage = metadata.model_stage
self.default_sampling_params = metadata.default_sampling_params
self.prompt_expand_func = metadata.prompt_expand_func
self.requires_multimodal_data = getattr(metadata, "requires_multimodal_data", False)
self.custom_process_input_func = getattr(metadata, "custom_process_input_func", None)
self.engine_input_source = getattr(metadata, "engine_input_source", [])
def _connect_transport(self, request_address: str, response_address: str) -> None:
# Expose the ZMQ addresses on the instance so callers (e.g.
# ``StagePool._client_input_addr``) can identify the diffusion
# replica by its bound address.
self.request_address = request_address
self.response_address = response_address
self._zmq_ctx = zmq.Context()
self._request_socket = self._zmq_ctx.socket(zmq.PUSH)
self._request_socket.bind(request_address)
self._response_socket = self._zmq_ctx.socket(zmq.PULL)
self._response_socket.bind(response_address)
self._response_poller = zmq.asyncio.Poller()
self._response_poller.register(self._response_socket, zmq.POLLIN)
self._encoder = OmniMsgpackEncoder()
self._decoder = OmniMsgpackDecoder()
# ------------------------------------------------------------------
# Process monitor (mirrors vLLM's MPClient.start_engine_core_monitor)
# ------------------------------------------------------------------
@@ -175,7 +188,10 @@ class StageDiffusionClient(StageClientBase):
(e.g. SIGKILL, segfault), this thread sets ``_engine_dead`` so
subsequent calls raise ``EngineDeadError``.
"""
proc = self._proc
# Background thread to detect silent process death (SIGKILL, segfault)
# where the subprocess cannot send the ZMQ death sentinel.
# Mirrors MPClient.start_engine_core_monitor() in vLLM.
proc = self._proc_manager.proc
self_ref = weakref.ref(self)
def _monitor() -> None:
@@ -413,9 +429,12 @@ class StageDiffusionClient(StageClientBase):
if self._shutting_down:
return None
raise EngineDeadError()
if not self._shutting_down and self._owns_process and self._proc is not None and not self._proc.is_alive():
if self._proc_manager is None:
return None
proc = self._proc_manager.proc
if not self._shutting_down and not proc.is_alive():
self._engine_dead = True
exitcode = self._proc.exitcode
exitcode = proc.exitcode
# One final drain – the last ZMQ frame may have arrived
# between the first drain and the is_alive() check.
self._drain_responses()
@@ -490,11 +509,12 @@ class StageDiffusionClient(StageClientBase):
result = self._rpc_results.pop(rpc_id, None)
if result is not None:
return result
if self._engine_dead or (self._owns_process and self._proc is not None and not self._proc.is_alive()):
proc = self._proc_manager.proc
if self._engine_dead or not proc.is_alive():
self._engine_dead = True
raise EngineDeadError(
f"StageDiffusionProc died while waiting for "
f"collective_rpc '{method}' (exit code {self._proc.exitcode})"
f"collective_rpc '{method}' (exit code {proc.exitcode})"
)
if deadline is not None and time.monotonic() > deadline:
raise TimeoutError(f"collective_rpc_async '{method}' timed out after {timeout}s")
@@ -518,10 +538,13 @@ class StageDiffusionClient(StageClientBase):
"""
if self._engine_dead:
raise EngineDeadError(f"Stage-{self.stage_id} diffusion subprocess is dead")
if self._proc is not None and not self._proc.is_alive():
if self._proc_manager is None:
return
proc = self._proc_manager.proc
if not proc.is_alive():
self._engine_dead = True
raise EngineDeadError(
f"Stage-{self.stage_id} diffusion subprocess is not alive (exit code: {self._proc.exitcode})."
f"Stage-{self.stage_id} diffusion subprocess is not alive (exit code: {proc.exitcode})."
)
def shutdown(self) -> None:
@@ -531,9 +554,8 @@ class StageDiffusionClient(StageClientBase):
except Exception:
pass
if self._owns_process and self._proc is not None and self._proc.is_alive():
self._proc.join(timeout=10)
terminate_alive_proc(self._proc)
if self._proc_manager is not None and self._proc_manager.proc.is_alive():
self._proc_manager.shutdown(timeout=10)
self._request_socket.close(linger=0)
self._response_socket.close(linger=0)
+185 -104
View File
@@ -8,10 +8,10 @@ from __future__ import annotations
import asyncio
import contextlib
import multiprocessing.connection
import signal
import time
from concurrent.futures import ThreadPoolExecutor
from multiprocessing.process import BaseProcess
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
import msgspec
@@ -22,6 +22,8 @@ from PIL import Image
from vllm.logger import init_logger
from vllm.utils.network_utils import get_open_zmq_ipc_path, zmq_socket_ctx
from vllm.utils.system_utils import get_mp_context
from vllm.v1.engine.core import EngineCoreProc
from vllm.v1.engine.utils import CoreEngine, EngineZmqAddresses, wait_for_engine_startup
from vllm.v1.utils import shutdown
from vllm_omni.diffusion.data import DiffusionRequestAbortedError
@@ -360,10 +362,10 @@ class StageDiffusionProc:
ctx = zmq.asyncio.Context()
request_socket = ctx.socket(zmq.PULL)
request_socket.bind(request_address)
request_socket.connect(request_address)
response_socket = ctx.socket(zmq.PUSH)
response_socket.bind(response_address)
response_socket.connect(response_address)
encoder = OmniMsgpackEncoder()
decoder = OmniMsgpackDecoder()
@@ -612,15 +614,51 @@ class StageDiffusionProc:
# Subprocess entry point
# ------------------------------------------------------------------
@staticmethod
def _open_startup_handshake(
handshake_address: str,
*,
local_client: bool,
headless: bool,
) -> tuple[zmq.Context, zmq.Socket, EngineZmqAddresses]:
ctx = zmq.Context()
socket = ctx.socket(zmq.DEALER)
socket.setsockopt(zmq.IDENTITY, (0).to_bytes(2, "little"))
socket.connect(handshake_address)
addresses = EngineCoreProc.startup_handshake(
socket,
local_client=local_client,
headless=headless,
parallel_config=None,
)
return ctx, socket, addresses
@staticmethod
def _send_startup_ready(
handshake_socket: zmq.Socket,
*,
local_client: bool,
headless: bool,
) -> None:
handshake_socket.send(
msgspec.msgpack.encode(
{
"status": "READY",
"local": local_client,
"headless": headless,
}
)
)
@classmethod
def run_diffusion_proc(
cls,
model: str,
od_config: OmniDiffusionConfig,
handshake_address: str,
request_address: str,
response_address: str,
*,
local_client: bool,
headless: bool,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
@@ -651,21 +689,32 @@ class StageDiffusionProc:
proc = cls(model, od_config)
coord_client: OmniCoordClientForStage | None = None
handshake_ctx: zmq.Context | None = None
handshake_socket: zmq.Socket | None = None
try:
handshake_ctx, handshake_socket, addresses = cls._open_startup_handshake(
handshake_address,
local_client=local_client,
headless=headless,
)
request_address = addresses.inputs[0]
response_address = addresses.outputs[0]
proc.initialize()
# Send READY via handshake socket
handshake_ctx = zmq.Context()
handshake_socket = handshake_ctx.socket(zmq.DEALER)
handshake_socket.connect(handshake_address)
handshake_socket.send(msgspec.msgpack.encode({"status": "READY"}))
cls._send_startup_ready(
handshake_socket,
local_client=local_client,
headless=headless,
)
handshake_socket.close()
handshake_ctx.term()
handshake_socket = None
handshake_ctx = None
# Wire OmniCoordClientForStage *after* READY so that the head
# has bound its head-side request/response sockets — the
# address pair we report is the same pair this proc binds to
# (request/response addresses passed in).
# Wire OmniCoordClientForStage *after* READY. The address pair is
# owned by the frontend client; this proc connects to it as the
# backend runtime.
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")
@@ -688,7 +737,6 @@ class StageDiffusionProc:
omni_coordinator_address,
)
# Run async event loop
asyncio.run(proc.run_loop(request_address, response_address))
except SystemExit:
@@ -698,105 +746,138 @@ class StageDiffusionProc:
logger.exception("StageDiffusionProc encountered a fatal error.")
raise
finally:
if handshake_socket is not None:
handshake_socket.close(linger=0)
if handshake_ctx is not None:
handshake_ctx.term()
if coord_client is not None:
with contextlib.suppress(RuntimeError):
coord_client.close()
proc.close()
# -- Free functions for backward compatibility with StageDiffusionClient ------
class StageDiffusionProcManager:
"""Owns a StageDiffusionProc subprocess.
def spawn_diffusion_proc(
model: str,
od_config: OmniDiffusionConfig,
handshake_address: str | None = None,
request_address: str | None = None,
response_address: str | None = None,
*,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
) -> tuple[BaseProcess, str, str, str]:
"""Spawn a StageDiffusionProc subprocess.
Returns ``(proc, handshake_address, request_address, response_address)``.
Pass ``omni_coordinator_address`` / ``omni_stage_id`` / ``omni_replica_id``
to have the subprocess publish heartbeats to an OmniCoordinator.
Mirrors the small process-lifecycle surface used by vLLM's
CoreEngineProcManager while keeping diffusion's custom wire protocol.
"""
handshake_address = handshake_address or get_open_zmq_ipc_path()
request_address = request_address or get_open_zmq_ipc_path()
response_address = response_address or get_open_zmq_ipc_path()
ctx = get_mp_context()
proc = ctx.Process(
target=StageDiffusionProc.run_diffusion_proc,
name="StageDiffusionProc",
kwargs={
"model": model,
"od_config": od_config,
"handshake_address": handshake_address,
"request_address": request_address,
"response_address": response_address,
"omni_coordinator_address": omni_coordinator_address,
"omni_stage_id": omni_stage_id,
"omni_replica_id": omni_replica_id,
},
)
proc.start()
# Wait for the process to become alive before returning.
deadline = time.monotonic() + 10
while not proc.is_alive():
if proc.exitcode is not None:
raise RuntimeError(f"StageDiffusionProc failed to start (exit code {proc.exitcode})")
if time.monotonic() > deadline:
raise TimeoutError("StageDiffusionProc did not become alive within 10s")
time.sleep(0.01)
return proc, handshake_address, request_address, response_address
def __init__(
self,
*,
model: str,
od_config: OmniDiffusionConfig,
stage_init_timeout: int,
handshake_address: str | None = None,
addresses: EngineZmqAddresses | None = None,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
) -> None:
handshake_address = handshake_address or get_open_zmq_ipc_path()
addresses = addresses or EngineZmqAddresses(
inputs=[get_open_zmq_ipc_path()],
outputs=[get_open_zmq_ipc_path()],
)
ctx = get_mp_context()
proc = ctx.Process(
target=StageDiffusionProc.run_diffusion_proc,
name="StageDiffusionProc",
kwargs={
"model": model,
"od_config": od_config,
"handshake_address": handshake_address,
"local_client": True,
"headless": False,
"omni_coordinator_address": omni_coordinator_address,
"omni_stage_id": omni_stage_id,
"omni_replica_id": omni_replica_id,
},
)
proc.start()
self.proc = proc
self.addresses = addresses
self.manager_stopped = False
self.failed_proc_name: str | None = None
def complete_diffusion_handshake(
proc: BaseProcess,
handshake_address: str,
handshake_timeout: int,
) -> None:
"""Wait for the diffusion subprocess to signal READY.
self._wait_until_started(handshake_address, stage_init_timeout)
On failure the process is terminated before re-raising.
"""
try:
_perform_diffusion_handshake(proc, handshake_address, handshake_timeout)
except Exception:
shutdown([proc])
raise
@classmethod
def launch_headless(
cls,
*,
model: str,
od_config: OmniDiffusionConfig,
handshake_address: str,
addresses: EngineZmqAddresses,
omni_coordinator_address: str | None,
omni_stage_id: int,
omni_replica_id: int,
) -> StageDiffusionProcManager:
"""Launch a headless diffusion backend that connects to head-owned sockets."""
self = cls.__new__(cls)
ctx = get_mp_context()
proc = ctx.Process(
target=StageDiffusionProc.run_diffusion_proc,
name="StageDiffusionProc",
kwargs={
"model": model,
"od_config": od_config,
"handshake_address": handshake_address,
"local_client": False,
"headless": True,
"omni_coordinator_address": omni_coordinator_address,
"omni_stage_id": omni_stage_id,
"omni_replica_id": omni_replica_id,
},
)
proc.start()
self.proc = proc
self.addresses = addresses
self.manager_stopped = False
self.failed_proc_name = None
return self
def _perform_diffusion_handshake(
proc: BaseProcess,
handshake_address: str,
handshake_timeout: int,
) -> None:
"""Run the handshake with the diffusion 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)
timeout_ms = handshake_timeout * 1000
while True:
events = dict(poller.poll(timeout=timeout_ms))
if not events:
raise TimeoutError(
f"Timed out waiting for READY from StageDiffusionProc after {handshake_timeout}s. "
f"This typically indicates model loading or warmup is taking too long. "
f"Consider increasing `stage_init_timeout` for large models."
def _wait_until_started(self, handshake_address: str, stage_init_timeout: int) -> None:
try:
with zmq_socket_ctx(handshake_address, zmq.ROUTER, bind=True) as handshake_socket:
wait_for_engine_startup(
handshake_socket,
self.addresses,
[CoreEngine(index=0, local=True)],
SimpleNamespace(
data_parallel_size_local=1,
data_parallel_hybrid_lb=False,
data_parallel_external_lb=False,
),
False,
None,
self,
None,
)
if handshake_socket in events:
identity, raw = handshake_socket.recv_multipart()
msg = msgspec.msgpack.decode(raw)
if msg.get("status") == "READY":
return
raise RuntimeError(f"Expected READY, got: {msg}")
if proc.exitcode is not None:
raise RuntimeError(f"StageDiffusionProc died during handshake (exit code {proc.exitcode})")
except Exception:
shutdown([self.proc])
raise
def shutdown(self, timeout: float | None = None) -> None:
self.manager_stopped = True
shutdown([self.proc], timeout=timeout)
def sentinels(self) -> list[int]:
return [self.proc.sentinel]
def finished_procs(self) -> dict[str, int]:
if self.proc.exitcode is None:
return {}
return {self.proc.name: self.proc.exitcode}
def monitor_engine_liveness(self) -> None:
try:
multiprocessing.connection.wait([self.proc.sentinel])
except Exception:
return
if self.proc.exitcode not in (None, 0) and not self.manager_stopped:
self.failed_proc_name = self.proc.name
self.shutdown()