Refactor StageDiffusionClient and StageEngineCoreClient (#2006)

This commit is contained in:
chickeyton authored and GitHub committed 2026-04-03 08:05:19 +00:00
1 parent 7fb86d51cd
commit 563f73b78a
19 files changed
+1107 -769

No files matched your search

+14 -1
View File
@@ -31,6 +31,12 @@ def _tensor_to_shm(tensor: torch.Tensor) -> dict[str, Any]:
import numpy as np
tensor = tensor.detach().cpu().contiguous()
original_dtype = tensor.dtype
# NumPy does not support bfloat16; promote to float32 for the SHM
# transfer and record the original dtype so _tensor_from_shm can
# convert back. The round-trip is lossless for bfloat16 values.
if original_dtype == torch.bfloat16:
tensor = tensor.to(torch.float32)
arr = tensor.numpy()
nbytes = arr.nbytes
shm = shared_memory.SharedMemory(create=True, size=nbytes)
@@ -40,7 +46,7 @@ def _tensor_to_shm(tensor: torch.Tensor) -> dict[str, Any]:
"__tensor_shm__": True,
"name": shm.name,
"shape": list(tensor.shape),
"torch_dtype": str(tensor.dtype),
"torch_dtype": str(original_dtype),
"numpy_dtype": str(arr.dtype),
"nbytes": nbytes,
}
@@ -59,6 +65,13 @@ def _tensor_from_shm(handle: dict[str, Any]) -> torch.Tensor:
np_dtype = np.dtype(handle["numpy_dtype"])
arr = np.ndarray(handle["shape"], dtype=np_dtype, buffer=shm.buf[: handle["nbytes"]])
tensor = torch.from_numpy(arr.copy())
# Restore the original dtype if it differs from the numpy-compatible
# dtype used for the SHM transfer (e.g. bfloat16 → float32 → bfloat16).
torch_dtype_str = handle.get("torch_dtype", "")
if torch_dtype_str:
original_dtype = getattr(torch, torch_dtype_str.replace("torch.", ""), None)
if original_dtype is not None and tensor.dtype != original_dtype:
tensor = tensor.to(original_dtype)
finally:
shm.close()
shm.unlink()
+213 -105
View File
@@ -1,20 +1,30 @@
"""Stage Diffusion Client for vLLM-Omni multi-stage runtime.
Wraps AsyncOmniDiffusion to expose the same interface the Orchestrator
expects from any stage client.
Spawns StageDiffusionProc in a subprocess and communicates via ZMQ
(PUSH/PULL) to expose the same interface the Orchestrator expects
from any stage client.
"""
from __future__ import annotations
import asyncio
import time
import uuid
from dataclasses import fields, is_dataclass
from typing import TYPE_CHECKING, Any
import zmq
from vllm.logger import init_logger
from vllm_omni.diffusion.data import DiffusionRequestAbortedError
from vllm_omni.engine.stage_init_utils import StageMetadata
from vllm_omni.entrypoints.async_omni_diffusion import AsyncOmniDiffusion
from vllm_omni.diffusion.stage_diffusion_proc import (
complete_diffusion_handshake,
spawn_diffusion_proc,
)
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
from vllm_omni.engine.stage_init_utils import StageMetadata, terminate_alive_proc
from vllm_omni.outputs import OmniRequestOutput
if TYPE_CHECKING:
@@ -25,11 +35,12 @@ logger = init_logger(__name__)
class StageDiffusionClient:
"""Wraps AsyncOmniDiffusion for use inside the Orchestrator.
"""Communicates with StageDiffusionProc via ZMQ for use inside the Orchestrator.
Exposes the same attributes and async methods the Orchestrator
uses on StageEngineCoreClient, but routes execution through
DiffusionEngine instead of vLLM EngineCore.
a StageDiffusionProc subprocess instead of running the diffusion
engine in-process.
"""
stage_type: str = "diffusion"
@@ -48,56 +59,137 @@ class StageDiffusionClient:
self.custom_process_input_func = metadata.custom_process_input_func
self.engine_input_source = metadata.engine_input_source
self._engine = AsyncOmniDiffusion(model=model, od_config=od_config, batch_size=batch_size)
# 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)
self._proc = proc
# ZMQ sockets (sync) for communicating with the subprocess.
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._encoder = OmniMsgpackEncoder()
self._decoder = OmniMsgpackDecoder()
# Buffers for demultiplexing response messages.
self._output_queue: asyncio.Queue[OmniRequestOutput] = asyncio.Queue()
self._rpc_results: dict[str, Any] = {}
self._pending_rpcs: set[str] = set()
self._tasks: dict[str, asyncio.Task] = {}
self._shutting_down = False
logger.info("[StageDiffusionClient] Stage-%s initialized (batch_size=%d)", self.stage_id, batch_size)
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _drain_responses(self) -> None:
"""Non-blocking drain of all available responses from the subprocess."""
while True:
try:
raw = self._response_socket.recv(zmq.NOBLOCK)
except zmq.Again:
break
msg = self._decoder.decode(raw)
msg_type = msg.get("type")
if msg_type == "result":
self._output_queue.put_nowait(msg["output"])
elif msg_type == "rpc_result":
self._rpc_results[msg["rpc_id"]] = msg["result"]
elif msg_type == "error":
req_id = msg.get("request_id")
rpc_id = msg.get("rpc_id")
error_msg = msg.get("error")
logger.error(
"[StageDiffusionClient] Stage-%s subprocess error for %s: %s",
self.stage_id,
rpc_id or req_id,
error_msg,
)
# Route RPC errors so collective_rpc_async can unblock.
if rpc_id is not None and rpc_id in self._pending_rpcs:
self._rpc_results[rpc_id] = {
"error": True,
"reason": error_msg,
}
# Fields that are subprocess-local and cannot be serialized across
# process boundaries. They are recreated in the subprocess with
# their default values.
_NON_SERIALIZABLE_FIELDS = frozenset(
{
"generator", # torch.Generator — recreated from seed
"modules", # model components — loaded in subprocess
}
)
@staticmethod
def _sampling_params_to_dict(sampling_params: Any) -> dict[str, Any]:
"""Convert sampling params to a plain dict for serialization.
Uses ``dataclasses.fields`` + ``getattr`` instead of ``asdict``
to avoid deep-copying large tensors, and skips fields that
cannot cross process boundaries.
When a ``torch.Generator`` is present but ``seed`` is not set,
the generator's initial seed is extracted so the subprocess can
recreate an equivalent generator via ``diffusion_model_runner``.
"""
if is_dataclass(sampling_params) and not isinstance(sampling_params, type):
result = {
f.name: getattr(sampling_params, f.name)
for f in fields(sampling_params)
if f.name not in StageDiffusionClient._NON_SERIALIZABLE_FIELDS
}
elif not isinstance(sampling_params, dict):
raise TypeError(f"sampling_params is not a dict but {sampling_params.__class__.__name__}")
else:
result = {
k: v for k, v in sampling_params.items() if k not in StageDiffusionClient._NON_SERIALIZABLE_FIELDS
}
# Preserve the generator's seed across the process boundary so
# the subprocess can recreate deterministic random state.
if result.get("seed") is None:
generator = (
getattr(sampling_params, "generator", None)
if not isinstance(sampling_params, dict)
else sampling_params.get("generator")
)
if generator is not None:
if isinstance(generator, list) and generator:
generator = generator[0]
if hasattr(generator, "initial_seed"):
result["seed"] = generator.initial_seed()
return result
# ------------------------------------------------------------------
# Public API (matches the interface the Orchestrator expects)
# ------------------------------------------------------------------
async def add_request_async(
self,
request_id: str,
prompt: OmniPromptType,
sampling_params: OmniDiffusionSamplingParams,
) -> None:
task = asyncio.create_task(
self._run(request_id, prompt, sampling_params),
name=f"diffusion-{request_id}",
self._request_socket.send(
self._encoder.encode(
{
"type": "add_request",
"request_id": request_id,
"prompt": prompt,
"sampling_params": self._sampling_params_to_dict(sampling_params),
}
)
)
self._tasks[request_id] = task
async def _run(
self,
request_id: str,
prompt: OmniPromptType,
sampling_params: OmniDiffusionSamplingParams,
) -> None:
try:
result = await self._engine.generate(prompt, sampling_params, request_id)
await self._output_queue.put(result)
except asyncio.CancelledError:
logger.info(
"[StageDiffusionClient] Stage-%s req=%s cancelled",
self.stage_id,
request_id,
)
raise
except DiffusionRequestAbortedError as e:
logger.info(
"[StageDiffusionClient] Stage-%s req=%s aborted: %s",
self.stage_id,
request_id,
e,
)
except Exception as e:
logger.exception(
"[StageDiffusionClient] Stage-%s req=%s failed: %s",
self.stage_id,
request_id,
e,
)
finally:
self._tasks.pop(request_id, None)
# TODO(Long): Temporary solution to boost performance of diffusion stages.
# Remove this after scheduling algorithm is implemented
@@ -126,12 +218,16 @@ class StageDiffusionClient:
sampling_params: OmniDiffusionSamplingParams,
) -> None:
try:
result = await self._engine.generate_batch(
prompts,
sampling_params,
request_id,
self._request_socket.send(
self._encoder.encode(
{
"type": "add_batch_request",
"request_id": request_id,
"prompts": prompts,
"sampling_params": self._sampling_params_to_dict(sampling_params),
}
)
)
await self._output_queue.put(result)
except Exception as e:
logger.exception(
"[StageDiffusionClient] Stage-%s batch req=%s failed: %s",
@@ -142,18 +238,24 @@ class StageDiffusionClient:
finally:
self._tasks.pop(request_id, None)
def get_diffusion_output_async(self) -> OmniRequestOutput | None:
def get_diffusion_output_nowait(self) -> OmniRequestOutput | None:
self._drain_responses()
try:
return self._output_queue.get_nowait()
except asyncio.QueueEmpty:
if not self._shutting_down and self._proc is not None and not self._proc.is_alive():
raise RuntimeError(f"StageDiffusionProc died unexpectedly (exit code {self._proc.exitcode})")
return None
async def abort_requests_async(self, request_ids: list[str]) -> None:
for rid in request_ids:
task = self._tasks.pop(rid, None)
if task:
task.cancel()
await self._engine.abort(request_ids)
self._request_socket.send(
self._encoder.encode(
{
"type": "abort",
"request_ids": list(request_ids),
}
)
)
async def collective_rpc_async(
self,
@@ -162,60 +264,66 @@ class StageDiffusionClient:
args: tuple[Any, ...] = (),
kwargs: dict[str, Any] | None = None,
) -> Any:
"""Best-effort control RPC shim for diffusion stages.
TODO(AsyncOmni): add dedicated wrappers on AsyncOmniDiffusion for the
remaining control APIs instead of reaching into its underlying engine.
"""
kwargs = kwargs or {}
# Handle profile method: inject stage_id into profile_prefix for diffusion stages
"""Forward control RPCs to the diffusion subprocess."""
# Inject a default profile_prefix that includes stage_id when profiling.
if method == "profile":
target = getattr(self._engine, method, None)
if target is None:
return {
"supported": False,
"todo": True,
"reason": f"AsyncOmniDiffusion.{method} is not implemented",
}
# Extract is_start and profile_prefix from args
is_start = args[0] if args else True
profile_prefix = args[1] if len(args) > 1 else None
# Generate profile_prefix with stage_id if starting and no prefix provided
args_list = list(args)
is_start = args_list[0] if args_list else True
profile_prefix = args_list[1] if len(args_list) > 1 else None
if is_start and profile_prefix is None:
profile_prefix = f"stage_{self.stage_id}_diffusion_{int(time.time())}"
result = target(is_start, profile_prefix)
if timeout is not None:
return await asyncio.wait_for(result, timeout=timeout)
return await result
if len(args_list) > 1:
args_list[1] = profile_prefix
else:
args_list.append(profile_prefix)
args = tuple(args_list)
if method in {"add_lora", "remove_lora", "list_loras", "pin_lora"}:
target = getattr(self._engine, method, None)
if target is None:
return {
"supported": False,
"todo": True,
"reason": f"AsyncOmniDiffusion.{method} is not implemented",
kwargs = kwargs or {}
rpc_id = uuid.uuid4().hex
self._pending_rpcs.add(rpc_id)
self._request_socket.send(
self._encoder.encode(
{
"type": "collective_rpc",
"rpc_id": rpc_id,
"method": method,
"timeout": timeout,
"args": list(args),
"kwargs": kwargs,
}
result = target(*args, **kwargs)
if timeout is not None:
return await asyncio.wait_for(result, timeout=timeout)
return await result
# Fall back to collective RPC for other methods
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
self._engine._executor,
self._engine.engine.collective_rpc,
method,
timeout,
args,
kwargs,
None,
)
)
deadline = time.monotonic() + timeout if timeout else None
# Wait for the matching RPC response, buffering result messages.
try:
while True:
self._drain_responses()
if rpc_id in self._rpc_results:
return self._rpc_results.pop(rpc_id)
if self._proc is not None and not self._proc.is_alive():
raise RuntimeError(
f"StageDiffusionProc died while waiting for "
f"collective_rpc '{method}' (exit code {self._proc.exitcode})"
)
if deadline and time.monotonic() > deadline:
raise TimeoutError(f"collective_rpc_async '{method}' timed out after {timeout}s")
await asyncio.sleep(0.01)
finally:
self._pending_rpcs.discard(rpc_id)
def shutdown(self) -> None:
for task in self._tasks.values():
task.cancel()
self._tasks.clear()
self._engine.close()
self._shutting_down = True
try:
self._request_socket.send(self._encoder.encode({"type": "shutdown"}))
except Exception:
pass
if self._proc is not None and self._proc.is_alive():
self._proc.join(timeout=10)
terminate_alive_proc(self._proc)
self._request_socket.close(linger=0)
self._response_socket.close(linger=0)
self._zmq_ctx.term()
+604
View File
@@ -0,0 +1,604 @@
"""Subprocess entry point for the diffusion engine.
StageDiffusionProc runs DiffusionEngine in a child process,
communicating with StageDiffusionClient via ZMQ (PUSH/PULL).
"""
from __future__ import annotations
import asyncio
import signal
import time
from concurrent.futures import ThreadPoolExecutor
from multiprocessing.process import BaseProcess
from typing import TYPE_CHECKING, Any
import msgspec
import zmq
import zmq.asyncio
from vllm.logger import init_logger
from vllm.transformers_utils.config import get_hf_file_to_dict
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.utils import shutdown
from vllm_omni.diffusion.data import DiffusionRequestAbortedError, TransformerConfig
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
if TYPE_CHECKING:
from vllm_omni.diffusion.data import OmniDiffusionConfig
logger = init_logger(__name__)
_HANDSHAKE_POLL_TIMEOUT_S = 600
class StageDiffusionProc:
"""Subprocess entry point for diffusion inference.
Manages DiffusionEngine lifecycle, async request processing,
and ZMQ-based communication with StageDiffusionClient.
"""
def __init__(self, model: str, od_config: OmniDiffusionConfig) -> None:
self._model = model
self._od_config = od_config
self._engine: DiffusionEngine | None = None
self._executor: ThreadPoolExecutor | None = None
self._closed = False
# ------------------------------------------------------------------
# Initialization
# ------------------------------------------------------------------
def initialize(self) -> None:
"""Enrich config, create DiffusionEngine and thread pool."""
self._enrich_config()
self._engine = DiffusionEngine.make_engine(self._od_config)
self._executor = ThreadPoolExecutor(max_workers=1)
logger.info("StageDiffusionProc initialized with model: %s", self._model)
def _enrich_config(self) -> None:
"""Load model metadata from HuggingFace and populate od_config fields.
Diffusers-style models expose ``model_index.json`` with ``_class_name``.
Non-diffusers models (e.g. Bagel, NextStep) only have ``config.json``,
so we fall back to reading that and mapping model_type manually.
"""
od_config = self._od_config
try:
config_dict = get_hf_file_to_dict("model_index.json", od_config.model)
if config_dict is not None:
if od_config.model_class_name is None:
od_config.model_class_name = config_dict.get("_class_name", None)
od_config.update_multimodal_support()
tf_config_dict = get_hf_file_to_dict("transformer/config.json", od_config.model)
od_config.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
else:
raise FileNotFoundError("model_index.json not found")
except (AttributeError, OSError, ValueError, FileNotFoundError):
cfg = get_hf_file_to_dict("config.json", od_config.model)
if cfg is None:
raise ValueError(f"Could not find config.json or model_index.json for model {od_config.model}")
od_config.tf_model_config = TransformerConfig.from_dict(cfg)
model_type = cfg.get("model_type")
architectures = cfg.get("architectures") or []
if model_type == "bagel" or "BagelForConditionalGeneration" in architectures:
od_config.model_class_name = "BagelPipeline"
od_config.tf_model_config = TransformerConfig()
od_config.update_multimodal_support()
elif model_type == "nextstep":
if od_config.model_class_name is None:
od_config.model_class_name = "NextStep11Pipeline"
od_config.tf_model_config = TransformerConfig()
od_config.update_multimodal_support()
elif architectures and len(architectures) == 1:
od_config.model_class_name = architectures[0]
else:
raise
# ------------------------------------------------------------------
# Request processing
# ------------------------------------------------------------------
def _reconstruct_sampling_params(self, sampling_params_dict: dict) -> OmniDiffusionSamplingParams:
"""Reconstruct OmniDiffusionSamplingParams from a dict, handling LoRA."""
lora_req = sampling_params_dict.get("lora_request")
if lora_req is not None:
from vllm.lora.request import LoRARequest
if not isinstance(lora_req, LoRARequest):
sampling_params_dict["lora_request"] = msgspec.convert(lora_req, LoRARequest)
return OmniDiffusionSamplingParams(**sampling_params_dict)
async def _process_request(
self,
request_id: str,
prompt: Any,
sampling_params_dict: dict,
) -> OmniRequestOutput:
"""Build a diffusion request and run DiffusionEngine.step()."""
sampling_params = self._reconstruct_sampling_params(sampling_params_dict)
request = OmniDiffusionRequest(
prompts=[prompt],
sampling_params=sampling_params,
request_ids=[request_id],
)
loop = asyncio.get_running_loop()
results = await loop.run_in_executor(self._executor, self._engine.step, request)
result = results[0]
if not result.request_id:
result.request_id = request_id
return result
async def _process_batch_request(
self,
request_id: str,
prompts: list[Any],
sampling_params_dict: dict,
) -> OmniRequestOutput:
"""Build a batched diffusion request and run DiffusionEngine.step().
All prompts are processed in a single step() call. The per-prompt
results are merged into one :class:`OmniRequestOutput` whose
``images`` list contains every generated image, matching the
contract expected by the orchestrator and tests.
"""
sampling_params = self._reconstruct_sampling_params(sampling_params_dict)
request = OmniDiffusionRequest(
prompts=prompts,
sampling_params=sampling_params,
request_ids=[request_id] * len(prompts),
)
loop = asyncio.get_running_loop()
results = await loop.run_in_executor(self._executor, self._engine.step, request)
# Merge per-prompt results into a single combined output.
all_images: list = []
merged_mm: dict[str, Any] = {}
merged_metrics: dict[str, Any] = {}
merged_durations: dict[str, float] = {}
peak_mem = 0.0
latents = None
final_output_type = "image"
for r in results:
all_images.extend(r.images)
merged_mm.update(r._multimodal_output)
merged_metrics.update(r.metrics)
merged_durations.update(r.stage_durations)
peak_mem = max(peak_mem, r.peak_memory_mb)
if latents is None and r.latents is not None:
latents = r.latents
if r.final_output_type != "image":
final_output_type = r.final_output_type
return OmniRequestOutput.from_diffusion(
request_id=request_id,
images=all_images,
prompt=prompts[0] if len(prompts) == 1 else None,
metrics=merged_metrics,
latents=latents,
multimodal_output=merged_mm or None,
final_output_type=final_output_type,
stage_durations=merged_durations,
peak_memory_mb=peak_mem,
)
# ------------------------------------------------------------------
# Collective RPC dispatch
# ------------------------------------------------------------------
async def _handle_collective_rpc(
self,
method: str,
timeout: float | None,
args: tuple,
kwargs: dict,
) -> Any:
"""Dispatch collective RPC calls to DiffusionEngine.
LoRA methods remap arguments and post-process results to match
the contract that ``AsyncOmni`` provides.
"""
loop = asyncio.get_running_loop()
if method == "profile":
is_start = args[0] if args else True
profile_prefix = args[1] if len(args) > 1 else None
return await loop.run_in_executor(
self._executor,
self._engine.profile,
is_start,
profile_prefix,
)
if method == "add_lora":
# Reconstruct LoRARequest after IPC if needed.
lora_request = args[0] if args else kwargs.get("lora_request")
if lora_request is not None:
from vllm.lora.request import LoRARequest
if not isinstance(lora_request, LoRARequest):
lora_request = msgspec.convert(lora_request, LoRARequest)
results = await loop.run_in_executor(
self._executor,
self._engine.collective_rpc,
"add_lora",
timeout,
(),
{"lora_request": lora_request},
None,
)
return all(results) if isinstance(results, list) else results
if method == "remove_lora":
results = await loop.run_in_executor(
self._executor,
self._engine.collective_rpc,
"remove_lora",
timeout,
args,
kwargs or {},
None,
)
return all(results) if isinstance(results, list) else results
if method == "list_loras":
results = await loop.run_in_executor(
self._executor,
self._engine.collective_rpc,
"list_loras",
timeout,
(),
{},
None,
)
if not isinstance(results, list):
return results or []
merged: set[int] = set()
for part in results:
merged.update(part or [])
return sorted(merged)
if method == "pin_lora":
lora_id = args[0] if args else kwargs.get("adapter_id")
results = await loop.run_in_executor(
self._executor,
self._engine.collective_rpc,
"pin_lora",
timeout,
(),
{"adapter_id": lora_id},
None,
)
return all(results) if isinstance(results, list) else results
# Fall back to DiffusionEngine.collective_rpc for all other methods
# (e.g. worker extension RPCs like "test_extension_name").
return await loop.run_in_executor(
self._executor,
self._engine.collective_rpc,
method,
timeout,
args,
kwargs or {},
None,
)
# ------------------------------------------------------------------
# ZMQ event loop
# ------------------------------------------------------------------
async def run_loop(
self,
request_address: str,
response_address: str,
) -> None:
"""Async event loop handling ZMQ messages from StageDiffusionClient."""
ctx = zmq.asyncio.Context()
request_socket = ctx.socket(zmq.PULL)
request_socket.bind(request_address)
response_socket = ctx.socket(zmq.PUSH)
response_socket.bind(response_address)
encoder = OmniMsgpackEncoder()
decoder = OmniMsgpackDecoder()
tasks: dict[str, asyncio.Task] = {}
async def _dispatch_request(request_id: str, prompt: Any, sampling_params_dict: dict) -> None:
"""Process a single diffusion request and send the response."""
try:
result = await self._process_request(request_id, prompt, sampling_params_dict)
await response_socket.send(encoder.encode({"type": "result", "output": result}))
except DiffusionRequestAbortedError as e:
logger.info(
"request_id: %s aborted: %s",
request_id,
str(e),
)
except Exception as e:
logger.exception("Diffusion request %s failed: %s", request_id, e)
await response_socket.send(
encoder.encode(
{
"type": "error",
"request_id": request_id,
"error": str(e),
}
)
)
finally:
tasks.pop(request_id, None)
try:
while True:
raw = await request_socket.recv()
msg = decoder.decode(raw)
msg_type = msg.get("type")
if msg_type == "add_request":
request_id = msg["request_id"]
task = asyncio.create_task(
_dispatch_request(
request_id,
msg["prompt"],
msg["sampling_params"],
)
)
tasks[request_id] = task
elif msg_type == "add_batch_request":
request_id = msg["request_id"]
async def _dispatch_batch(rid: str, prompts: list, sp_dict: dict) -> None:
try:
result = await self._process_batch_request(rid, prompts, sp_dict)
await response_socket.send(encoder.encode({"type": "result", "output": result}))
except DiffusionRequestAbortedError as e:
logger.info(
"request_id: %s aborted: %s",
rid,
str(e),
)
except Exception as e:
logger.exception("Batch diffusion request %s failed: %s", rid, e)
await response_socket.send(
encoder.encode(
{
"type": "error",
"request_id": rid,
"error": str(e),
}
)
)
finally:
tasks.pop(rid, None)
task = asyncio.create_task(
_dispatch_batch(
request_id,
msg["prompts"],
msg["sampling_params"],
)
)
tasks[request_id] = task
elif msg_type == "abort":
for rid in msg.get("request_ids", []):
task = tasks.pop(rid, None)
if task:
task.cancel()
self._engine.abort(rid)
elif msg_type == "collective_rpc":
rpc_id = msg["rpc_id"]
try:
result = await self._handle_collective_rpc(
msg["method"],
msg.get("timeout"),
tuple(msg.get("args", ())),
msg.get("kwargs", {}),
)
await response_socket.send(
encoder.encode(
{
"type": "rpc_result",
"rpc_id": rpc_id,
"result": result,
}
)
)
except Exception as e:
logger.exception("Collective RPC %s failed: %s", msg["method"], e)
await response_socket.send(
encoder.encode(
{
"type": "error",
"rpc_id": rpc_id,
"error": str(e),
}
)
)
elif msg_type == "shutdown":
break
finally:
for task in tasks.values():
task.cancel()
if tasks:
await asyncio.gather(*tasks.values(), return_exceptions=True)
request_socket.close()
response_socket.close()
ctx.term()
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
def close(self) -> None:
"""Release engine and thread pool resources."""
if self._closed:
return
self._closed = True
if self._engine is not None:
try:
self._engine.close()
except Exception as e:
logger.warning("Error closing diffusion engine: %s", e)
if self._executor is not None:
try:
self._executor.shutdown(wait=False)
except Exception as e:
logger.warning("Error shutting down executor: %s", e)
# ------------------------------------------------------------------
# Subprocess entry point
# ------------------------------------------------------------------
@classmethod
def run_diffusion_proc(
cls,
model: str,
od_config: OmniDiffusionConfig,
handshake_address: str,
request_address: str,
response_address: str,
) -> None:
"""Entry point for the diffusion subprocess."""
shutdown_requested = False
def signal_handler(signum: int, frame: Any) -> None:
nonlocal shutdown_requested
if not shutdown_requested:
shutdown_requested = True
raise SystemExit()
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
proc = cls(model, od_config)
try:
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"}))
handshake_socket.close()
handshake_ctx.term()
# Run async event loop
asyncio.run(proc.run_loop(request_address, response_address))
except SystemExit:
logger.debug("StageDiffusionProc exiting.")
raise
except Exception:
logger.exception("StageDiffusionProc encountered a fatal error.")
raise
finally:
proc.close()
# -- Free functions for backward compatibility with StageDiffusionClient ------
def spawn_diffusion_proc(
model: str,
od_config: OmniDiffusionConfig,
) -> tuple[BaseProcess, str, str, str]:
"""Spawn a StageDiffusionProc subprocess.
Returns ``(proc, handshake_address, request_address, response_address)``.
"""
handshake_address = get_open_zmq_ipc_path()
request_address = get_open_zmq_ipc_path()
response_address = 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,
},
)
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 complete_diffusion_handshake(
proc: BaseProcess,
handshake_address: str,
) -> None:
"""Wait for the diffusion subprocess to signal READY.
On failure the process is terminated before re-raising.
"""
try:
_perform_diffusion_handshake(proc, handshake_address)
except Exception:
shutdown([proc])
raise
def _perform_diffusion_handshake(
proc: BaseProcess,
handshake_address: str,
) -> 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_POLL_TIMEOUT_S * 1000
while True:
events = dict(poller.poll(timeout=timeout_ms))
if not events:
raise TimeoutError("Timed out waiting for READY from StageDiffusionProc")
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})")