[Enhancement] Engine runtime errors (#2426)

Signed-off-by: Daniel Huang <daniel1.huang@intel.com>
Signed-off-by: Daniel Huang <pilotflyer824@gmail.com>
Signed-off-by: bjf-frz <frz123db@gmail.com>
Co-authored-by: Chenguang Zheng <645327136@qq.com>
Co-authored-by: Zhou Taichang <tzhouam@connect.ust.hk>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: bjf-frz <frz123db@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-04-21 14:46:05 +08:00
1 parent c1ba86ab5b
commit 52b53367ef
23 files changed
+1597 -98

No files matched your search

+4 -1
View File
@@ -14,6 +14,7 @@ import numpy as np
import PIL.Image
import torch
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.data import (
DiffusionOutput,
@@ -122,7 +123,7 @@ class DiffusionEngine:
if output.aborted:
raise DiffusionRequestAbortedError(output.abort_message or "Diffusion request aborted.")
if output.error:
raise RuntimeError(f"{output.error}")
raise RuntimeError(output.error)
logger.info("Generation completed successfully.")
if output.output is None:
@@ -358,6 +359,8 @@ class DiffusionEngine:
sched_req_id = sched_output.scheduled_req_ids[0]
try:
runner_output = self.execute_fn(sched_output)
except EngineDeadError:
raise
except Exception as exc:
logger.error("Execution failed for diffusion request %s", sched_req_id, exc_info=True)
runner_output = RunnerOutput(
@@ -1,14 +1,18 @@
from __future__ import annotations
import multiprocessing as mp
import multiprocessing.connection
import threading
import time
import weakref
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import zmq
from vllm.distributed.device_communicators.shm_broadcast import MessageQueue
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.data import SHUTDOWN_MESSAGE, DiffusionOutput
from vllm_omni.diffusion.executor.abstract import DiffusionExecutor
@@ -22,6 +26,8 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
_DEQUEUE_TIMEOUT_S = 5.0
@dataclass
class BackgroundResources:
@@ -67,6 +73,8 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
def _init_executor(self) -> None:
self._processes: list[mp.Process] = []
self._closed = False
self.is_failed = False
self._failure_callbacks: list[Callable[[], None]] = []
num_workers = self.od_config.num_gpus
self.wake_events = [mp.Event() for _ in range(num_workers)]
@@ -87,6 +95,8 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
)
self._finalizer = weakref.finalize(self, self.resources)
self.start_worker_monitor()
def _init_broadcast_queue(self, num_workers: int) -> MessageQueue:
return MessageQueue(
n_reader=num_workers,
@@ -106,6 +116,23 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
if self._result_mq is None:
raise RuntimeError("Result queue not initialized")
def _dequeue_one_with_failure_polling(self, deadline: float | None, method: str) -> Any:
"""Block until one result message, polling ``is_failed`` between chunk timeouts."""
while True:
if deadline is None:
chunk_timeout = _DEQUEUE_TIMEOUT_S
else:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(f"RPC call to {method} timed out.")
chunk_timeout = min(_DEQUEUE_TIMEOUT_S, remaining)
try:
return self._result_mq.dequeue(timeout=chunk_timeout)
except (TimeoutError, zmq.error.Again):
if self.is_failed:
raise EngineDeadError()
continue
def _launch_workers(self, broadcast_handle, wake_events):
od_config = self.od_config
logger.info("Starting server...")
@@ -171,6 +198,49 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
return processes, result_handle
def start_worker_monitor(self) -> None:
# Monitors worker process liveness. If any die unexpectedly,
# logs an error, shuts down the executor and invokes the failure
# callback to inform the engine.
sentinels = [p.sentinel for p in self._processes]
if not sentinels:
return
def _monitor() -> None:
try:
finished = multiprocessing.connection.wait(sentinels)
except OSError:
return
if self._closed:
return
dead = [p.name for p in self._processes if p.sentinel in finished]
if dead:
logger.error(
"Diffusion worker(s) died unexpectedly: %s",
dead,
)
self.is_failed = True
self.shutdown()
for cb in self._failure_callbacks:
try:
cb()
except Exception:
logger.exception("failure_callback raised")
t = threading.Thread(target=_monitor, daemon=True, name="diffusion-worker-monitor")
t.start()
def register_failure_callback(
self,
callback: Callable[[], None],
) -> None:
"""Register a callback invoked when a worker process dies."""
self._failure_callbacks.append(callback)
def add_req(self, request: OmniDiffusionRequest) -> DiffusionOutput:
self._ensure_open()
rpc_request = {
@@ -293,27 +363,21 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
responses = []
for _ in range(num_responses):
dequeue_timeout = None if deadline is None else max(0, deadline - time.monotonic())
response = self._dequeue_one_with_failure_polling(deadline, method)
try:
response = self._result_mq.dequeue(timeout=dequeue_timeout)
unpack_diffusion_output_shm(response)
except Exception as e:
logger.warning("SHM unpack failed (data may already be inline): %s", e)
try:
unpack_diffusion_output_shm(response)
except Exception as e:
logger.warning("SHM unpack failed (data may already be inline): %s", e)
# Check if response indicates an error
if isinstance(response, dict) and response.get("status") == "error":
raise RuntimeError(
f"Worker failed with error '{response.get('error')}', "
"please check the stack trace above for the root cause"
)
# Check if response indicates an error
if isinstance(response, dict) and response.get("status") == "error":
raise RuntimeError(
f"Worker failed with error '{response.get('error')}', "
"please check the stack trace above for the root cause"
)
responses.append(response)
except zmq.error.Again as e:
raise TimeoutError(f"RPC call to {method} timed out.") from e
except TimeoutError as e:
raise TimeoutError(f"RPC call to {method} timed out.") from e
responses.append(response)
return responses[0] if unique_reply_rank is not None else responses
except Exception as e:
@@ -321,10 +385,13 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
raise
def check_health(self) -> None:
# Simple check if processes are alive
self._ensure_open()
if self.is_failed:
raise EngineDeadError()
for p in self._processes:
if not p.is_alive():
raise RuntimeError(f"Worker process {p.name} is dead")
self.is_failed = True
raise EngineDeadError(f"Worker process {p.name} is dead")
def shutdown(self) -> None:
self._closed = True
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from itertools import chain
from typing import Any
+83 -10
View File
@@ -8,15 +8,20 @@ from any stage client.
from __future__ import annotations
import asyncio
import multiprocessing.connection
import time
import uuid
import weakref
from dataclasses import fields, is_dataclass
from threading import Thread
from typing import TYPE_CHECKING, Any
import zmq
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.stage_diffusion_proc import (
StageDiffusionProc,
complete_diffusion_handshake,
spawn_diffusion_proc,
)
@@ -129,6 +134,12 @@ class StageDiffusionClient:
self._pending_rpcs: set[str] = set()
self._tasks: dict[str, asyncio.Task] = {}
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()
logger.info(
"[StageDiffusionClient] Stage-%s initialized (owns_process=%s, batch_size=%d)",
@@ -137,6 +148,37 @@ class StageDiffusionClient:
batch_size,
)
# ------------------------------------------------------------------
# Process monitor (mirrors vLLM's MPClient.start_engine_core_monitor)
# ------------------------------------------------------------------
def _start_proc_monitor(self) -> None:
"""Start a daemon thread that watches the subprocess sentinel.
When the subprocess dies without sending the ZMQ death sentinel
(e.g. SIGKILL, segfault), this thread sets ``_engine_dead`` so
subsequent calls raise ``EngineDeadError``.
"""
proc = self._proc
self_ref = weakref.ref(self)
def _monitor() -> None:
try:
multiprocessing.connection.wait([proc.sentinel])
except Exception:
return
client = self_ref()
if client is None or client._shutting_down or client._engine_dead:
return
client._engine_dead = True
logger.error(
"[StageDiffusionClient] Stage-%s StageDiffusionProc died unexpectedly (exit code %s).",
client.stage_id,
proc.exitcode,
)
Thread(target=_monitor, daemon=True, name="DiffusionProcMonitor").start()
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
@@ -149,6 +191,15 @@ class StageDiffusionClient:
except zmq.Again:
break
# Check for the death sentinel (raw bytes, not msgpack-encoded).
if raw == StageDiffusionProc.DIFFUSION_PROC_DEAD:
self._engine_dead = True
logger.error(
"[StageDiffusionClient] Stage-%s received DIFFUSION_PROC_DEAD sentinel from subprocess.",
self.stage_id,
)
break
msg = self._decoder.decode(raw)
msg_type = msg.get("type")
@@ -172,13 +223,10 @@ class StageDiffusionClient:
"error": True,
"reason": error_msg,
}
elif req_id is not None:
error_output = OmniRequestOutput.from_diffusion(
request_id=req_id,
images=[],
)
error_output.error = error_msg
self._output_queue.put_nowait(error_output)
# Route request errors as error outputs so the Orchestrator
# sees the request complete (instead of hanging forever).
if req_id is not None:
self._output_queue.put_nowait(OmniRequestOutput.from_error(req_id, error_msg))
# Fields that are subprocess-local and cannot be serialized across
# process boundaries. They are recreated in the subprocess with
@@ -242,6 +290,8 @@ class StageDiffusionClient:
sampling_params: OmniDiffusionSamplingParams,
kv_sender_info: dict[int, dict[str, Any]] | None = None,
) -> None:
if self._engine_dead:
raise EngineDeadError()
self._request_socket.send(
self._encoder.encode(
{
@@ -269,6 +319,8 @@ class StageDiffusionClient:
and the combined result is placed on the output queue with a single
*request_id*.
"""
if self._engine_dead:
raise EngineDeadError()
task = asyncio.create_task(
self._run_batch(
request_id,
@@ -306,6 +358,7 @@ class StageDiffusionClient:
request_id,
e,
)
await self._output_queue.put(OmniRequestOutput.from_error(request_id, str(e)))
finally:
self._tasks.pop(request_id, None)
@@ -314,7 +367,10 @@ class StageDiffusionClient:
try:
return self._output_queue.get_nowait()
except asyncio.QueueEmpty:
if self._engine_dead:
raise EngineDeadError()
if not self._shutting_down and self._owns_process and self._proc is not None and not self._proc.is_alive():
self._engine_dead = True
exitcode = self._proc.exitcode
# One final drain – the last ZMQ frame may have arrived
# between the first drain and the is_alive() check.
@@ -328,7 +384,7 @@ class StageDiffusionClient:
logger.warning("StageDiffusionProc was killed by signal %d; treating as external shutdown.", sig)
self._shutting_down = True
return None
raise RuntimeError(f"StageDiffusionProc died unexpectedly (exit code {exitcode})")
raise EngineDeadError(f"StageDiffusionProc died unexpectedly (exit code {exitcode})")
return None
async def abort_requests_async(self, request_ids: list[str]) -> None:
@@ -349,6 +405,9 @@ class StageDiffusionClient:
kwargs: dict[str, Any] | None = None,
) -> Any:
"""Forward control RPCs to the diffusion subprocess."""
if self._engine_dead:
raise EngineDeadError()
# Inject a default profile_prefix that includes stage_id when profiling.
if method == "profile":
args_list = list(args)
@@ -386,8 +445,9 @@ class StageDiffusionClient:
self._drain_responses()
if rpc_id in self._rpc_results:
return self._rpc_results.pop(rpc_id)
if self._owns_process and self._proc is not None and not self._proc.is_alive():
raise RuntimeError(
if self._engine_dead or (self._owns_process and self._proc is not None and not self._proc.is_alive()):
self._engine_dead = True
raise EngineDeadError(
f"StageDiffusionProc died while waiting for "
f"collective_rpc '{method}' (exit code {self._proc.exitcode})"
)
@@ -397,6 +457,19 @@ class StageDiffusionClient:
finally:
self._pending_rpcs.discard(rpc_id)
def check_health(self) -> None:
"""Raise ``EngineDeadError`` if the diffusion engine is dead.
Mirrors the ``check_health`` protocol on vLLM's ``EngineClient``.
"""
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():
self._engine_dead = True
raise EngineDeadError(
f"Stage-{self.stage_id} diffusion subprocess is not alive (exit code: {self._proc.exitcode})."
)
def shutdown(self) -> None:
self._shutting_down = True
try:
@@ -46,6 +46,8 @@ class StageDiffusionProc:
and ZMQ-based communication with StageDiffusionClient.
"""
DIFFUSION_PROC_DEAD = b"DIFFUSION_PROC_DEAD"
def __init__(self, model: str, od_config: OmniDiffusionConfig) -> None:
self._model = model
self._od_config = od_config
@@ -450,6 +452,16 @@ class StageDiffusionProc:
elif msg_type == "shutdown":
break
except Exception:
# Send the death sentinel so the client can detect the
# fatal failure promptly (mirrors EngineCoreProc._send_engine_dead).
try:
response_socket.setsockopt(zmq.LINGER, 4000)
await response_socket.send(StageDiffusionProc.DIFFUSION_PROC_DEAD)
except Exception:
logger.warning("Failed to send DIFFUSION_PROC_DEAD sentinel to client.")
raise
finally:
for task in tasks.values():
task.cancel()