Merge remote-tracking branch 'origin/main' into dev/vllm-align

This commit is contained in:
tzhouam committed 2026-02-25 08:15:55 +00:00
commit 22e01c416b
39 files changed
+2763 -518

No files matched your search

+12 -1
View File
@@ -38,7 +38,7 @@ from vllm_omni.outputs import OmniRequestOutput
logger = init_logger(__name__)
def _weak_close_cleanup_async(stage_list, stage_in_queues, ray_pg, output_handler):
def _weak_close_cleanup_async(stage_list, stage_in_queues, stage_out_queues, ray_pg, output_handler, zmq_ctx=None):
"""Weak reference cleanup function for AsyncOmni instances."""
if stage_list:
for q in stage_in_queues:
@@ -46,6 +46,13 @@ def _weak_close_cleanup_async(stage_list, stage_in_queues, ray_pg, output_handle
q.put_nowait(SHUTDOWN_TASK)
except Exception as e:
logger.warning(f"Failed to send shutdown signal to stage input queue: {e}")
close_fn = getattr(q, "close", None)
if callable(close_fn):
close_fn()
for q in stage_out_queues:
close_fn = getattr(q, "close", None)
if callable(close_fn):
close_fn()
for stage in stage_list:
try:
stage.stop_stage_worker()
@@ -55,6 +62,8 @@ def _weak_close_cleanup_async(stage_list, stage_in_queues, ray_pg, output_handle
# Cancel output handler
if output_handler is not None:
output_handler.cancel()
if zmq_ctx is not None:
zmq_ctx.term()
class AsyncOmni(OmniBase):
@@ -108,8 +117,10 @@ class AsyncOmni(OmniBase):
_weak_close_cleanup_async,
self.stage_list,
self._stage_in_queues,
self._stage_out_queues,
self._ray_pg,
self.output_handler,
self._zmq_ctx,
)
def _create_default_diffusion_stage_cfg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
+163 -1
View File
@@ -7,19 +7,37 @@ diffusion models (e.g., Qwen-Image) through the same CLI interface.
import argparse
import os
import signal
from typing import Any
import msgspec.msgpack
import uvloop
import zmq
from vllm.entrypoints.cli.types import CLISubcommand
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.utils import VLLM_SUBCMD_PARSER_EPILOG
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.utils.network_utils import make_zmq_socket
from vllm.v1.utils import get_engine_client_zmq_addr
from vllm_omni.distributed.omni_connectors import (
get_connectors_config_for_stage,
load_omni_transfer_config,
)
from vllm_omni.distributed.omni_connectors.utils.initialization import (
resolve_omni_kv_config_for_stage,
)
from vllm_omni.entrypoints.cli.logo import log_logo
from vllm_omni.entrypoints.omni import OmniBase, omni_snapshot_download
from vllm_omni.entrypoints.omni_stage import OmniStage
from vllm_omni.entrypoints.openai.api_server import omni_run_server
from vllm_omni.entrypoints.utils import inject_omni_kv_config
logger = init_logger(__name__)
HANDSHAKE_TIMEOUT_MINS = 5
DESCRIPTION = """Launch a local OpenAI-compatible API server to serve Omni models
via HTTP. Supports both multi-stage LLM models and diffusion models.
@@ -55,9 +73,15 @@ class OmniServeCommand(CLISubcommand):
if hasattr(args, "model_tag") and args.model_tag is not None:
args.model = args.model_tag
uvloop.run(omni_run_server(args))
if args.headless:
run_headless(args)
else:
uvloop.run(omni_run_server(args))
def validate(self, args: argparse.Namespace) -> None:
if args.stage_id is not None and (args.omni_master_address is None or args.omni_master_port is None):
raise ValueError("--stage-id requires both --omni-master-address and --omni-master-port to be set")
# Skip validation for diffusion models as they have different requirements
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
@@ -94,6 +118,12 @@ class OmniServeCommand(CLISubcommand):
default=None,
help="Path to the stage configs file. If not specified, the stage configs will be loaded from the model.",
)
omni_config_group.add_argument(
"--stage-id",
type=int,
default=None,
help="Select and launch a single stage by stage_id.",
)
omni_config_group.add_argument(
"--stage-init-timeout",
type=int,
@@ -142,6 +172,18 @@ class OmniServeCommand(CLISubcommand):
default=None,
help="The address of the Ray cluster to connect to.",
)
omni_config_group.add_argument(
"--omni-master-address",
"-oma",
type=str,
help="Hostname or IP address of the Omni orchestrator (master).",
)
omni_config_group.add_argument(
"--omni-master-port",
"-omp",
type=int,
help="Port of the Omni orchestrator (master).",
)
# Diffusion model specific arguments
omni_config_group.add_argument(
@@ -251,5 +293,125 @@ class OmniServeCommand(CLISubcommand):
return serve_parser
def _create_default_diffusion_stage_cfg(args: argparse.Namespace) -> list[dict[str, Any]]:
omni_base = OmniBase.__new__(OmniBase)
return omni_base._create_default_diffusion_stage_cfg(vars(args))
def run_headless(args: argparse.Namespace) -> None:
if args.api_server_count is not None and args.api_server_count > 1:
raise ValueError("api_server_count can't be set in headless mode")
if args.worker_backend != "multi_process":
raise ValueError("headless mode requires worker_backend=multi_process")
model = omni_snapshot_download(args.model)
omni_base = OmniBase.__new__(OmniBase)
args_dict = vars(args).copy()
args_dict["model"] = model
config_path, stage_configs = omni_base._resolve_stage_configs(model, args_dict)
single_stage_id = args.stage_id
if single_stage_id is None:
if len(stage_configs) != 1:
raise ValueError("--stage-id is required in headless mode for multi-stage configs")
single_stage_id = getattr(stage_configs[0], "stage_id", 0)
stage_config = None
for cfg in stage_configs:
if getattr(cfg, "stage_id", None) == single_stage_id:
stage_config = cfg
break
if stage_config is None:
raise ValueError(f"No stage matches stage_id={single_stage_id}.")
# TODO(wuhang): Support connectors config by cli
transfer_config = load_omni_transfer_config(config_path, default_shm_threshold=args.shm_threshold_bytes)
connectors_config = get_connectors_config_for_stage(transfer_config, single_stage_id)
omni_master_address = args.omni_master_address
omni_master_port = args.omni_master_port
# Perform handshake with orchestrator to get dynamically allocated endpoints
with zmq.Context() as zmq_ctx:
handshake_endpoint = get_engine_client_zmq_addr(
local_only=False, host=omni_master_address, port=omni_master_port
)
with make_zmq_socket(zmq_ctx, handshake_endpoint, zmq.REQ, bind=False, linger=5000) as handshake_socket:
# TODO(wuhang): Define protocol in python dataclass.
handshake_msg = {"type": "handshake", "stage_id": single_stage_id}
handshake_socket.send(msgspec.msgpack.encode(handshake_msg))
# Wait for response with timeout
if not handshake_socket.poll(timeout=HANDSHAKE_TIMEOUT_MINS * 60_000):
raise RuntimeError(
f"Handshake timeout ({HANDSHAKE_TIMEOUT_MINS} minutes) for stage-{single_stage_id} "
f"at {handshake_endpoint}"
)
try:
response = msgspec.msgpack.decode(handshake_socket.recv())
except msgspec.DecodeError as exc:
raise RuntimeError(
f"Handshake decode failed for stage-{single_stage_id} at {handshake_endpoint}: {exc}"
) from exc
except Exception as exc: # pragma: no cover - unexpected decode errors
raise RuntimeError(
f"Unexpected error decoding handshake for stage-{single_stage_id} at {handshake_endpoint}: {exc}"
) from exc
if not response["ok"]:
error_msg = response["error"]
raise RuntimeError(f"Handshake failed for stage-{single_stage_id}: {error_msg}")
in_endpoint, out_endpoint = response["in_endpoint"], response["out_endpoint"]
logger.info(
f"[Headless] Stage-{single_stage_id} received endpoints via handshake: "
f"in={in_endpoint}, out={out_endpoint}"
)
shutdown_requested = False
def signal_handler(signum, frame):
nonlocal shutdown_requested
if shutdown_requested:
return
shutdown_requested = True
raise SystemExit
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
stage = OmniStage(stage_config, stage_init_timeout=args.stage_init_timeout)
stage.attach_queues(in_endpoint, out_endpoint)
# Inject YAML-resolved connector config into omni_kv_config for in-engine usage.
try:
omni_conn_cfg, omni_from, omni_to = resolve_omni_kv_config_for_stage(transfer_config, single_stage_id)
if omni_conn_cfg:
inject_omni_kv_config(stage, omni_conn_cfg, omni_from, omni_to) # type: ignore
except Exception as e:
logger.debug("[Headless] Failed to inject omni connector config into stage-%s: %s", single_stage_id, e)
old_env = os.environ.get("VLLM_LOGGING_PREFIX")
os.environ["VLLM_LOGGING_PREFIX"] = f"[Stage-{single_stage_id}] {'' if old_env is None else old_env}"
try:
stage.init_stage_worker(
model,
is_async=True,
shm_threshold_bytes=int(args.shm_threshold_bytes),
batch_timeout=int(args.batch_timeout),
connectors_config=connectors_config,
worker_backend="multi_process",
ignore_runtime_config=True,
)
if stage._proc is not None:
stage._proc.join()
finally:
stage.stop_stage_worker()
def cmd_init() -> list[CLISubcommand]:
return [OmniServeCommand()]
+248 -33
View File
@@ -3,6 +3,7 @@
import json
import multiprocessing as mp
import os
import threading
import time
import uuid
import weakref
@@ -11,10 +12,14 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Literal, overload
import huggingface_hub
import msgspec.msgpack
import zmq
from omegaconf import OmegaConf
from tqdm.auto import tqdm
from vllm import SamplingParams
from vllm.logger import init_logger
from vllm.utils.network_utils import make_zmq_socket
from vllm.v1.utils import get_engine_client_zmq_addr
from vllm_omni.distributed.omni_connectors import (
get_stage_connector_config,
@@ -35,10 +40,9 @@ from vllm_omni.entrypoints.stage_utils import maybe_load_from_ipc as _load
from vllm_omni.entrypoints.utils import (
get_final_stage_id_for_e2e,
inject_omni_kv_config,
load_stage_configs_from_model,
load_stage_configs_from_yaml,
resolve_model_config_path,
load_and_resolve_stage_configs,
)
from vllm_omni.entrypoints.zmq_utils import ZmqQueue
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, OmniSamplingParams
from vllm_omni.metrics import OrchestratorAggregator, StageRequestStats
from vllm_omni.model_executor.model_loader.weight_utils import (
@@ -49,7 +53,16 @@ from vllm_omni.outputs import OmniRequestOutput
logger = init_logger(__name__)
def _weak_close_cleanup(stage_list, stage_in_queues, ray_pg):
def _weak_close_cleanup(
stage_list,
stage_in_queues,
stage_out_queues,
ray_pg,
zmq_ctx=None,
handshake_stop: threading.Event | None = None,
zmq_handshake_socket: zmq.Socket | None = None,
handshake_thread: threading.Thread | None = None,
):
"""Weak reference cleanup function for OmniBase instances."""
if stage_list:
for q in stage_in_queues:
@@ -57,6 +70,13 @@ def _weak_close_cleanup(stage_list, stage_in_queues, ray_pg):
q.put_nowait(SHUTDOWN_TASK)
except Exception as e:
logger.warning(f"Failed to send shutdown signal to stage input queue: {e}")
close_fn = getattr(q, "close", None)
if callable(close_fn):
close_fn()
for q in stage_out_queues:
close_fn = getattr(q, "close", None)
if callable(close_fn):
close_fn()
for stage in stage_list:
try:
stage.stop_stage_worker()
@@ -64,6 +84,20 @@ def _weak_close_cleanup(stage_list, stage_in_queues, ray_pg):
logger.warning(f"Failed to stop stage worker: {e}")
try_close_ray(ray_pg)
# Gracefully shutdown handshake server thread
if handshake_stop is not None:
handshake_stop.set()
if handshake_thread is not None:
handshake_thread.join(timeout=2.0)
if handshake_thread.is_alive():
logger.warning("Handshake server thread did not terminate gracefully within timeout")
# Close ZMQ resources after thread has exited
if zmq_handshake_socket is not None:
zmq_handshake_socket.close(0)
if zmq_ctx is not None:
zmq_ctx.term()
def _dummy_snapshot_download(model_id):
return model_id
@@ -125,12 +159,21 @@ class OmniBase:
# Stage management attributes
self.stage_list: list[OmniStage] = []
self._stage_in_queues: list[mp.Queue] = []
self._stage_out_queues: list[mp.Queue] = []
self._stage_in_queues: list[Any] = []
self._stage_out_queues: list[Any] = []
self._stages_ready: set[int] = set()
self._ray_pg = None
self._queue_cls = None
self._ctx = None
self._zmq_ctx: zmq.Context | None = None
self._zmq_master_address: str | None = None
self._zmq_master_port: int | None = None
self._zmq_handshake_socket: zmq.Socket | None = None
self._handshake_thread: threading.Thread | None = None
self._handshake_stop: threading.Event | None = None
self._handshake_endpoints: dict[int, tuple[str, str]] = {}
self._handshake_seen: set[int] = set() # Track which stage IDs have completed ZMQ handshake
self._single_stage_id: int | None = None # Optional: deploy only a specific stage ID
# Initialize stages - each stage will create appropriate instance based on stage_type
# Stage workers will automatically create OmniLLM or OmniDiffusion instances
@@ -206,35 +249,24 @@ class OmniBase:
default_stage_cfg[0]["engine_args"]["model_stage"] = "diffusion"
return default_stage_cfg
def _initialize_stages(self, model: str, kwargs: dict[str, Any]) -> None:
"""Initialize stage list management."""
stage_init_timeout = kwargs.get("stage_init_timeout", 20)
shm_threshold_bytes = kwargs.get("shm_threshold_bytes", 65536)
init_timeout = kwargs.get("init_timeout", 300)
worker_backend = kwargs.get("worker_backend", "multi_process")
ray_address = kwargs.get("ray_address", None)
batch_timeout = kwargs.get("batch_timeout", 10)
def _resolve_stage_configs(self, model: str, kwargs: dict[str, Any]) -> tuple[str, list[Any]]:
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
# TODO(wuhang):
# Remove kwargs as parameters in the future.
# Use dataclass directly for engine args.
stage_configs_path = kwargs.get("stage_configs_path", None)
log_stats = kwargs.get("log_stats", False)
### base engine args
tokenizer = kwargs.get("tokenizer", None)
base_engine_args = {"tokenizer": tokenizer} if tokenizer is not None else None
# Load stage configurations from YAML
if stage_configs_path is None:
self.config_path = resolve_model_config_path(model)
self.stage_configs = load_stage_configs_from_model(model, base_engine_args=base_engine_args)
if not self.stage_configs:
default_stage_cfg = self._create_default_diffusion_stage_cfg(kwargs)
self.stage_configs = OmegaConf.create(default_stage_cfg)
else:
self.config_path = stage_configs_path
self.stage_configs = load_stage_configs_from_yaml(stage_configs_path, base_engine_args=base_engine_args)
config_path, stage_configs = load_and_resolve_stage_configs(
model,
stage_configs_path,
kwargs,
default_stage_cfg_factory=lambda: self._create_default_diffusion_stage_cfg(kwargs),
)
# Inject diffusion LoRA-related knobs from kwargs if not present in the stage config.
for cfg in self.stage_configs:
for cfg in stage_configs:
try:
if getattr(cfg, "stage_type", None) != "diffusion":
continue
@@ -253,6 +285,27 @@ class OmniBase:
except Exception as e:
logger.warning("Failed to inject LoRA config for stage: %s", e)
return config_path, stage_configs
def _initialize_stages(self, model: str, kwargs: dict[str, Any]) -> None:
"""Initialize stage list management."""
stage_init_timeout = kwargs.get("stage_init_timeout", 20)
shm_threshold_bytes = kwargs.get("shm_threshold_bytes", 65536)
init_timeout = kwargs.get("init_timeout", 300)
worker_backend = kwargs.get("worker_backend", "multi_process")
ray_address = kwargs.get("ray_address", None)
batch_timeout = kwargs.get("batch_timeout", 10)
log_stats = kwargs.get("log_stats", False)
self._single_stage_id = kwargs.get("stage_id", None)
self._zmq_master_address = kwargs.get("omni_master_address", None)
if self._zmq_master_address is None:
self._zmq_master_address = "127.0.0.1"
logger.info("No omni_master_address provided, defaulting to localhost (127.0.0.1)")
self._zmq_master_port = kwargs.get("omni_master_port", None)
# Resolve stage configs shared by orchestrator/headless paths.
self.config_path, self.stage_configs = self._resolve_stage_configs(model, kwargs)
# Initialize connectors
self.omni_transfer_config, self.connectors = initialize_orchestrator_connectors(
self.config_path, worker_backend=worker_backend, shm_threshold_bytes=shm_threshold_bytes
@@ -281,7 +334,7 @@ class OmniBase:
self.stage_list = [st for _, st in results]
self.default_sampling_params_list = [st.default_sampling_params for st in self.stage_list]
self.output_modalities = [st.final_output_type for st in self.stage_list]
logger.debug(f"[{self._name}] Loaded {len(self.stage_list)} stages")
logger.info(f"[{self._name}] Loaded {len(self.stage_list)} stages")
if self.worker_backend == "ray":
self._queue_cls = get_ray_queue_class()
@@ -307,10 +360,34 @@ class OmniBase:
self._ray_pg = create_placement_group(
number_of_stages=len(self.stage_list), address=self.ray_address, strategy="PACK"
)
else:
# Initialize ZMQ context
if self._zmq_ctx is None:
self._zmq_ctx = zmq.Context()
# Allocate endpoints for each stage
total_stages = len(self.stage_configs)
self._handshake_endpoints = {}
for sid in range(total_stages):
in_endpoint = get_engine_client_zmq_addr(local_only=False, host=self._zmq_master_address)
out_endpoint = get_engine_client_zmq_addr(local_only=False, host=self._zmq_master_address)
self._handshake_endpoints[sid] = (in_endpoint, out_endpoint)
logger.debug(
f"[{self._name}] Allocated endpoints for stage-{sid}: in={in_endpoint}, out={out_endpoint}"
)
# Start handshake server
self.start_handshake_server()
for stage_id, stage in enumerate[OmniStage](self.stage_list):
in_q = self._queue_cls()
out_q = self._queue_cls()
if self.worker_backend == "ray":
in_q = self._queue_cls()
out_q = self._queue_cls()
else:
in_endpoint, out_endpoint = self._handshake_endpoints[stage_id]
in_q = ZmqQueue(self._zmq_ctx, zmq.PUSH, bind=in_endpoint)
out_q = ZmqQueue(self._zmq_ctx, zmq.PULL, bind=out_endpoint)
self._stage_in_queues.append(in_q)
self._stage_out_queues.append(out_q)
stage.attach_queues(in_q, out_q)
@@ -332,6 +409,12 @@ class OmniBase:
except Exception as e:
logger.debug("[Omni] Failed to inject omni connector config into stage-%s: %s", stage_id, e)
if self._single_stage_id is not None and stage_id != int(self._single_stage_id):
logger.info(
f"[{self._name}] Skipping initialization of stage-{stage_id} worker due to single_stage_id setting"
)
continue
stage.init_stage_worker(
model,
is_async=self.is_async,
@@ -341,6 +424,7 @@ class OmniBase:
connectors_config=stage_connectors_config,
worker_backend=self.worker_backend,
ray_placement_group=self._ray_pg,
ignore_runtime_config=True if self._single_stage_id is not None else False,
)
logger.debug(f"[{self._name}] Stage-{stage_id} process started")
@@ -351,6 +435,9 @@ class OmniBase:
def _wait_for_stages_ready(self, timeout: int = 120) -> None:
"""Wait for all stages to report readiness with optimized polling."""
if self._single_stage_id is not None and self.worker_backend != "ray":
timeout = self._wait_for_handshakes(timeout)
num_stages = len(self.stage_list)
deadline = time.time() + max(0, int(timeout))
@@ -501,6 +588,129 @@ class OmniBase:
if hasattr(self, "_weak_finalizer"):
self._weak_finalizer()
def _process_handshake_message(self, msg: Any) -> dict[str, Any]:
"""Process incoming handshake message and generate response.
Args:
msg: Decoded message from client
Returns:
Response dictionary with ok status and either endpoints or error
"""
if not isinstance(msg, dict) or msg.get("type") != "handshake":
return {"ok": False, "error": "invalid handshake payload"}
try:
stage_id = int(msg.get("stage_id"))
except (TypeError, ValueError) as e:
return {"ok": False, "error": f"invalid stage_id: {e}"}
endpoints = self._handshake_endpoints.get(stage_id)
if endpoints is None:
return {"ok": False, "error": f"unknown stage_id: {stage_id}"}
# Mark stage as seen and prepare success response
self._handshake_seen.add(stage_id)
in_endpoint, out_endpoint = endpoints
logger.info(
"[%s] Handshake received from stage-%s",
self._name,
stage_id,
)
return {
"ok": True,
"in_endpoint": in_endpoint,
"out_endpoint": out_endpoint,
}
def _run_handshake_server_loop(self) -> None:
"""Main loop for handshake server - polls for messages and responds."""
poller = zmq.Poller()
poller.register(self._zmq_handshake_socket, zmq.POLLIN)
try:
while not self._handshake_stop.is_set():
events = poller.poll(1000)
has_message = any(sock == self._zmq_handshake_socket and event == zmq.POLLIN for sock, event in events)
if not has_message:
continue
msg = msgspec.msgpack.decode(self._zmq_handshake_socket.recv())
response = msgspec.msgpack.encode(self._process_handshake_message(msg))
self._zmq_handshake_socket.send(response)
finally:
poller.unregister(self._zmq_handshake_socket)
def start_handshake_server(self) -> None:
"""Start the ZMQ handshake server.
The handshake server allows distributed stages to discover their
queue endpoints by querying the orchestrator with their stage_id.
Skips starting if the server is already running or ZMQ is not initialized.
"""
# Skip if already running or ZMQ not initialized
if self._handshake_thread is not None or self._zmq_ctx is None:
return
# Skip if master address/port not configured
if not self._zmq_master_address or self._zmq_master_port is None:
return
# Create server endpoint and socket
endpoint = get_engine_client_zmq_addr(
local_only=False, host=self._zmq_master_address, port=int(self._zmq_master_port)
)
self._handshake_stop = threading.Event()
self._zmq_handshake_socket = make_zmq_socket(self._zmq_ctx, endpoint, zmq.REP, bind=True, linger=5000)
# Start server thread
self._handshake_thread = threading.Thread(
target=self._run_handshake_server_loop, daemon=True, name="zmq-handshake-server"
)
self._handshake_thread.start()
def _wait_for_handshakes(self, timeout: int = 120) -> int:
"""Wait for handshakes from all expected stages.
Args:
timeout: Timeout in seconds for waiting for handshakes. Default is 120s.
Returns:
Remaining timeout in seconds after waiting for handshakes.
"""
total_stages = len(self.stage_configs)
expected = set(range(total_stages)) - {int(self._single_stage_id)}
if not expected:
return timeout
deadline = time.time() + max(0, int(timeout))
logger.info(f"[{self._name}] Waiting for handshakes from stages: {expected} (timeout: {timeout}s)")
# NOTE: _handshake_seen may be updated from the handshake server thread.
# It is intentionally used here without additional locking because:
# - _handshake_seen only ever grows (stages are added but never removed), and
# - we only check membership and set inclusion relative to `expected`.
# Under these monotonic semantics and the CPython GIL, concurrent reads/writes
# are safe for this usage and cannot violate correctness: we may observe a
# slightly stale view, but the loop condition remains valid and eventually
# becomes true once all expected stages have handshaked or the timeout elapses.
while not expected.issubset(self._handshake_seen) and time.time() < deadline:
time.sleep(1.0)
remaining_timeout = max(0, int(deadline - time.time()))
if not expected.issubset(self._handshake_seen):
missing = sorted(expected - self._handshake_seen)
logger.warning(
f"[{self._name}] Handshake timeout: {len(self._handshake_seen)}/{len(expected)} "
f"stages completed handshake. Missing stages: {missing}"
)
return remaining_timeout
@property
def _name(self) -> str:
return "OmniBase"
@@ -546,7 +756,12 @@ class Omni(OmniBase):
_weak_close_cleanup,
self.stage_list,
self._stage_in_queues,
self._stage_out_queues,
self._ray_pg,
self._zmq_ctx,
self._handshake_stop,
self._zmq_handshake_socket,
self._handshake_thread,
)
@overload
+2 -1
View File
@@ -24,6 +24,7 @@ from vllm_omni.engine.arg_utils import OmniEngineArgs
from vllm_omni.engine.input_processor import OmniInputProcessor, reinject_omni_fields
from vllm_omni.engine.output_processor import MultimodalOutputProcessor
from vllm_omni.entrypoints.utils import (
filter_dataclass_kwargs,
load_stage_configs_from_model,
load_stage_configs_from_yaml,
resolve_model_config_path,
@@ -153,7 +154,7 @@ class OmniLLM(LLM):
compilation_config=compilation_config_instance,
structured_outputs_config=structured_outputs_instance,
omni_kv_config=omni_kv_config,
**kwargs,
**filter_dataclass_kwargs(OmniEngineArgs, kwargs),
)
# Create the Engine (autoselects V0 vs V1)
+97 -26
View File
@@ -36,7 +36,7 @@ from vllm_omni.distributed.omni_connectors import build_stage_connectors
from vllm_omni.distributed.omni_connectors.adapter import try_recv_via_connector
from vllm_omni.distributed.omni_connectors.connectors.base import OmniConnectorBase
from vllm_omni.distributed.ray_utils.utils import kill_ray_actor, start_ray_actor
from vllm_omni.engine.arg_utils import AsyncOmniEngineArgs
from vllm_omni.engine.arg_utils import AsyncOmniEngineArgs, OmniEngineArgs
from vllm_omni.entrypoints.async_omni_diffusion import AsyncOmniDiffusion
from vllm_omni.entrypoints.async_omni_llm import AsyncOmniLLM
from vllm_omni.entrypoints.omni_diffusion import OmniDiffusion
@@ -49,7 +49,11 @@ from vllm_omni.entrypoints.stage_utils import (
maybe_dump_to_shm,
set_stage_devices,
)
from vllm_omni.entrypoints.utils import detect_pid_host
from vllm_omni.entrypoints.utils import detect_pid_host, filter_dataclass_kwargs
from vllm_omni.entrypoints.zmq_utils import (
ZmqQueue,
create_zmq_queue,
)
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, OmniSamplingParams, OmniTokensPrompt
from vllm_omni.metrics import count_tokens_from_outputs
from vllm_omni.outputs import OmniRequestOutput
@@ -204,7 +208,8 @@ def _resolve_worker_cls(engine_args: dict[str, Any]) -> None:
worker_type = engine_args.pop("worker_type", None)
if not worker_type:
return
if engine_args.get("worker_cls"):
worker_cls = engine_args.get("worker_cls")
if worker_cls is not None and worker_cls != "auto":
return
from vllm_omni.platforms import current_omni_platform
@@ -260,6 +265,12 @@ class OmniStage:
self.is_comprehension = getattr(stage_config, "is_comprehension", False)
# Support for different stage types: "llm" (default) or "diffusion"
self.stage_type: Literal["llm", "diffusion"] = getattr(stage_config, "stage_type", "llm")
if (
"stage_id" in stage_config.engine_args
and stage_config.engine_args.stage_id != self.stage_id
and self.stage_id is not None
):
stage_config.engine_args.stage_id = self.stage_id
if hasattr(stage_config, "custom_process_input_func"):
# Import the module specified in the config (already a full module path)
module_path, func_name = stage_config.custom_process_input_func.rsplit(".", 1)
@@ -282,8 +293,8 @@ class OmniStage:
except TypeError as error:
raise TypeError(f"Invalid default_sampling_params for stage {self.stage_id}: {error}") from error
# Runtime orchestration state (added)
self._in_q: mp.Queue | None = None
self._out_q: mp.Queue | None = None
self._in_q: mp.queues.Queue | ZmqQueue | str | None = None
self._out_q: mp.queues.Queue | ZmqQueue | str | None = None
self._proc: mp.Process | None = None
self._shm_threshold_bytes: int = 65536
self._stage_init_timeout: int = stage_init_timeout
@@ -345,12 +356,16 @@ class OmniStage:
self.engine_outputs = engine_outputs
# ----------------- New Orchestration APIs -----------------
def attach_queues(self, in_q: mp.Queue, out_q: mp.Queue) -> None:
def attach_queues(
self,
in_q: mp.queues.Queue | ZmqQueue | str | None,
out_q: mp.queues.Queue | ZmqQueue | str | None,
) -> None:
"""Attach input and output queues for IPC communication.
Args:
in_q: Input queue for receiving tasks from orchestrator
out_q: Output queue for sending results to orchestrator
in_q: Input queue for receiving tasks from orchestrator (queue object or endpoint string)
out_q: Output queue for sending results to orchestrator (queue object or endpoint string)
"""
self._in_q = in_q
self._out_q = out_q
@@ -397,6 +412,7 @@ class OmniStage:
batch_timeout: int = 10,
connectors_config: dict | None = None,
worker_backend: str = "multi_process",
ignore_runtime_config: bool = False,
**kwargs: Any,
) -> None:
"""Initialize and start the stage worker process.
@@ -412,6 +428,7 @@ class OmniStage:
batch_timeout: Timeout in seconds for batching requests
connectors_config: Configuration for stage connectors
worker_backend: Backend type ("multi_process" or "ray")
ignore_runtime_config: Whether to ignore runtime configuration (default: False)
**kwargs: Additional arguments (e.g. ray_placement_group)
Raises:
@@ -429,7 +446,10 @@ class OmniStage:
ctx = ctx or mp.get_context("spawn")
# Prepare lightweight dict config for worker
engine_args = _to_dict(self.engine_args)
runtime_cfg = _to_dict(getattr(self.stage_config, "runtime", {}))
if ignore_runtime_config:
runtime_cfg = {}
else:
runtime_cfg = _to_dict(getattr(self.stage_config, "runtime", {}))
stage_payload: dict[str, Any] = {
"stage_id": self.stage_id,
"engine_args": engine_args,
@@ -438,6 +458,8 @@ class OmniStage:
"connectors_config": connectors_config or {},
"stage_type": self.stage_type,
"engine_input_source": self.engine_input_source,
"final_output": self.final_output,
"final_output_type": self.final_output_type,
}
try:
old_env = os.environ.get("VLLM_LOGGING_PREFIX")
@@ -449,9 +471,10 @@ class OmniStage:
_stage_worker_async_entry,
ray_placement_group,
self.stage_id,
self,
model=model,
stage_payload=stage_payload,
in_q=self._in_q,
out_q=self._out_q,
batch_timeout=batch_timeout,
stage_init_timeout=self._stage_init_timeout,
)
@@ -472,9 +495,10 @@ class OmniStage:
self._proc = ctx.Process(
target=_stage_worker_async_entry,
args=(
self,
model,
stage_payload,
self._in_q.endpoint if isinstance(self._in_q, ZmqQueue) else self._in_q,
self._out_q.endpoint if isinstance(self._out_q, ZmqQueue) else self._out_q,
batch_timeout,
self._stage_init_timeout,
),
@@ -485,8 +509,8 @@ class OmniStage:
args=(
model,
stage_payload,
self._in_q,
self._out_q,
self._in_q.endpoint if isinstance(self._in_q, ZmqQueue) else self._in_q,
self._out_q.endpoint if isinstance(self._out_q, ZmqQueue) else self._out_q,
batch_timeout,
self._stage_init_timeout,
),
@@ -510,6 +534,13 @@ class OmniStage:
self._in_q.put_nowait(SHUTDOWN_TASK)
except Exception as e:
logger.warning("Failed to send shutdown to in_q: %s", e)
close_fn = getattr(self._in_q, "close", None)
if callable(close_fn):
close_fn()
if self._out_q is not None:
close_fn = getattr(self._out_q, "close", None)
if callable(close_fn):
close_fn()
if hasattr(self, "_ray_actor") and self._ray_actor:
kill_ray_actor(self._ray_actor)
@@ -632,8 +663,8 @@ class OmniStage:
def _stage_worker(
model: str,
stage_payload: dict[str, Any],
in_q: mp.Queue,
out_q: mp.Queue,
in_q: mp.queues.Queue | ZmqQueue | str,
out_q: mp.queues.Queue | ZmqQueue | str,
batch_timeout: int = 10,
stage_init_timeout: int = 300,
) -> None:
@@ -644,6 +675,8 @@ def _stage_worker(
import os as _os
import time as _time
import zmq
from vllm_omni.plugins import load_omni_general_plugins
load_omni_general_plugins()
@@ -670,6 +703,21 @@ def _stage_worker(
if stage_type != "diffusion":
_resolve_worker_cls(engine_args)
# Resolve ZMQ queue endpoints if needed
zmq_ctx = None
if isinstance(in_q, str) or isinstance(out_q, str):
zmq_ctx = zmq.Context()
if isinstance(in_q, str):
in_q = create_zmq_queue(zmq_ctx, in_q, zmq.PULL)
if isinstance(out_q, str):
out_q = create_zmq_queue(zmq_ctx, out_q, zmq.PUSH)
# When using ZMQ (cross-node IPC), disable SHM so data is sent inline.
shm_threshold_bytes = sys.maxsize
logger.info(
"[Stage-%s] ZMQ transport detected; disabling SHM IPC (shm_threshold_bytes set to maxsize)",
stage_id,
)
# Aggregates for running average
_agg_total_tokens = 0
_agg_total_gen_time_ms = 0.0
@@ -701,6 +749,7 @@ def _stage_worker(
engine_args["stage_connector_spec"] = stage_connector_spec
engine_args["stage_id"] = stage_id
if stage_type == "diffusion":
engine_args = filter_dataclass_kwargs(OmniDiffusionConfig, engine_args)
engine_args.pop("model_stage", None)
engine_args.pop("model", None)
stage_engine = OmniDiffusion(
@@ -710,6 +759,8 @@ def _stage_worker(
**engine_args,
)
else:
engine_args = filter_dataclass_kwargs(OmniEngineArgs, engine_args)
engine_args.pop("model", None)
# Default to LLM engine
stage_engine = OmniLLM(model=model, **engine_args)
@@ -1004,19 +1055,21 @@ def _stage_worker(
def _stage_worker_async_entry(
omni_stage: OmniStage,
model: str,
stage_payload: dict[str, Any],
in_q: mp.queues.Queue | ZmqQueue | str,
out_q: mp.queues.Queue | ZmqQueue | str,
batch_timeout: int = 10,
stage_init_timeout: int = 300,
) -> None:
asyncio.run(_stage_worker_async(omni_stage, model, stage_payload, batch_timeout, stage_init_timeout))
asyncio.run(_stage_worker_async(model, stage_payload, in_q, out_q, batch_timeout, stage_init_timeout))
async def _stage_worker_async(
omni_stage: OmniStage,
model: str,
stage_payload: dict[str, Any],
in_q: mp.queues.Queue | ZmqQueue | str,
out_q: mp.queues.Queue | ZmqQueue | str,
batch_timeout: int = 10,
stage_init_timeout: int = 300,
) -> None:
@@ -1026,6 +1079,8 @@ async def _stage_worker_async(
import os as _os
import time as _time
import zmq
from vllm_omni.plugins import load_omni_general_plugins
load_omni_general_plugins()
@@ -1045,12 +1100,26 @@ async def _stage_worker_async(
shm_threshold_bytes = int(stage_payload.get("shm_threshold_bytes", 65536))
connectors_config = stage_payload.get("connectors_config", {})
stage_type = stage_payload.get("stage_type", "llm")
final_output = stage_payload.get("final_output", False)
final_output_type = stage_payload.get("final_output_type", None)
if stage_type != "diffusion":
_resolve_worker_cls(engine_args)
in_q = omni_stage._in_q
out_q = omni_stage._out_q
# Resolve ZMQ queue endpoints if needed
zmq_ctx = None
if isinstance(in_q, str) or isinstance(out_q, str):
zmq_ctx = zmq.Context()
if isinstance(in_q, str):
in_q = create_zmq_queue(zmq_ctx, in_q, zmq.PULL)
if isinstance(out_q, str):
out_q = create_zmq_queue(zmq_ctx, out_q, zmq.PUSH)
# When using ZMQ (cross-node IPC), disable SHM so data is sent inline.
shm_threshold_bytes = sys.maxsize
logger.info(
"[Stage-%s] ZMQ transport detected; disabling SHM IPC (shm_threshold_bytes set to maxsize)",
stage_id,
)
# Aggregates for running average
_agg_total_tokens = 0
@@ -1099,6 +1168,7 @@ async def _stage_worker_async(
engine_args["stage_id"] = stage_id
if stage_type == "diffusion":
# For diffusion, we need to extract diffusion-specific config
engine_args = filter_dataclass_kwargs(OmniDiffusionConfig, engine_args)
od_config = _build_od_config(engine_args, model)
# Inject omni config for worker to access stage info
@@ -1115,6 +1185,8 @@ async def _stage_worker_async(
)
vllm_config = None # Diffusion doesn't use vllm_config
else:
engine_args = filter_dataclass_kwargs(AsyncOmniEngineArgs, engine_args)
engine_args.pop("model", None)
omni_engine_args = AsyncOmniEngineArgs(model=model, **engine_args)
usage_context = UsageContext.OPENAI_API_SERVER
vllm_config = omni_engine_args.create_engine_config(usage_context=usage_context)
@@ -1126,14 +1198,13 @@ async def _stage_worker_async(
engine_args.get("disable_log_stats", False) or getattr(omni_engine_args, "disable_log_stats", False)
),
)
omni_stage.set_async_engine(stage_engine)
if hasattr(omni_stage.async_engine, "log_stats") and omni_stage.async_engine.log_stats:
if hasattr(stage_engine, "log_stats") and stage_engine.log_stats:
async def _force_log():
try:
while True:
await asyncio.sleep(10.0)
await omni_stage.async_engine.do_log_stats()
await stage_engine.do_log_stats()
except asyncio.CancelledError:
pass
@@ -1330,7 +1401,7 @@ async def _stage_worker_async(
batch_request_ids, batch_request_outputs, _gen_ms_list, batch_metrics
):
try:
r_outputs = [output_strip(output, omni_stage)]
r_outputs = [output_strip(output, final_output, final_output_type)]
use_shm, payload = maybe_dump_to_shm(r_outputs, shm_threshold_bytes)
if use_shm:
out_q.put(
@@ -1416,7 +1487,7 @@ def make_stage_stats(_agg_total_tokens: int, _agg_total_gen_time_ms: float):
return StageStats(total_token=_agg_total_tokens, total_gen_time_ms=_agg_total_gen_time_ms)
def output_strip(r_output: RequestOutput | OmniRequestOutput, omni_stage: OmniStage):
def output_strip(r_output: RequestOutput | OmniRequestOutput, final_output: bool, final_output_type: str | None):
"""
Strip unnecessary multimodal outputs from stages results,
in order to:
@@ -1425,7 +1496,7 @@ def output_strip(r_output: RequestOutput | OmniRequestOutput, omni_stage: OmniSt
"""
# check multimodal data is required by stage output config.
if omni_stage.final_output and omni_stage.final_output_type != "text":
if final_output and final_output_type != "text":
return r_output
# If the request has already finished, should not be altered.
+203 -6
View File
@@ -1,8 +1,9 @@
import os
import types
from collections import Counter
from dataclasses import asdict, is_dataclass
from dataclasses import asdict, fields, is_dataclass
from pathlib import Path
from typing import Any
from typing import Any, get_args, get_origin
from omegaconf import OmegaConf
from vllm.logger import init_logger
@@ -68,6 +69,52 @@ def _try_get_class_name_from_diffusers_config(model: str) -> str | None:
return None
def _filter_dict_like_object(obj: dict | Any) -> dict:
"""Filter dict-like object by removing callables and recursively converting values.
Converts dict-like objects to regular dicts while filtering out callable values
that are incompatible with OmegaConf. Recursively processes values through
_convert_dataclasses_to_dict for nested object conversion.
Args:
obj: Dict or dict-like object to filter
Returns:
Regular dict with callables filtered out and values recursively converted
Raises:
TypeError: If obj doesn't support .items() method
ValueError: If dict conversion fails unexpectedly
"""
def _is_callable_value(value: Any) -> bool:
if callable(value):
return True
return isinstance(
value,
(
types.FunctionType,
types.MethodType,
types.BuiltinFunctionType,
types.BuiltinMethodType,
),
)
result = {}
filtered_keys = []
for k, v in obj.items():
if _is_callable_value(v):
filtered_keys.append(str(k))
else:
result[k] = _convert_dataclasses_to_dict(v)
if filtered_keys:
logger.warning(
f"Filtered out {len(filtered_keys)} callable object(s) from base_engine_args "
f"that are not compatible with OmegaConf: {filtered_keys}. "
)
return result
def _convert_dataclasses_to_dict(obj: Any) -> Any:
"""Recursively convert non-serializable objects to OmegaConf-compatible types.
@@ -75,6 +122,7 @@ def _convert_dataclasses_to_dict(obj: Any) -> Any:
- Dataclass objects with Literal type annotations (e.g., StructuredOutputsConfig)
- Counter objects (from collections or vllm.utils)
- Set objects
- Callable objects (functions, methods, etc.)
- Other non-primitive types
"""
# IMPORTANT: Check Counter BEFORE dict, since Counter is a subclass of dict
@@ -99,17 +147,21 @@ def _convert_dataclasses_to_dict(obj: Any) -> Any:
result = asdict(obj)
# Recursively process the result to convert any Counter objects
return _convert_dataclasses_to_dict(result)
# Handle dictionaries (recurse into values)
# Handle dictionaries (recurse into values) and filter out callables(cause error in OmegaConf.create)
# Note: This must come AFTER Counter check since Counter is a dict subclass
if isinstance(obj, dict):
return {k: _convert_dataclasses_to_dict(v) for k, v in obj.items()}
return _filter_dict_like_object(obj)
# Handle callable objects (functions, methods, etc.) - skip them
# Note: This comes after dict/list checks to avoid misclassifying dict-like objects
if callable(obj):
return None
# Handle lists and tuples (recurse into items)
if isinstance(obj, (list, tuple)):
return type(obj)(_convert_dataclasses_to_dict(item) for item in obj)
return type(obj)(_convert_dataclasses_to_dict(item) for item in obj if not callable(item))
# Try to convert any dict-like object (has keys/values methods) to dict
if hasattr(obj, "keys") and hasattr(obj, "values") and not isinstance(obj, (str, bytes)):
try:
return {k: _convert_dataclasses_to_dict(v) for k, v in obj.items()}
return _filter_dict_like_object(obj)
except (TypeError, ValueError, AttributeError):
# If conversion fails, return as-is
return obj
@@ -236,6 +288,40 @@ def load_stage_configs_from_yaml(config_path: str, base_engine_args: dict | None
return stage_args
def load_and_resolve_stage_configs(
model: str,
stage_configs_path: str | None,
kwargs: dict | None,
default_stage_cfg_factory: Any = None,
) -> tuple[str, list]:
"""Load stage configurations from model or YAML file with fallback to defaults.
Args:
model: Model name or path
stage_configs_path: Optional path to YAML file containing stage configurations
kwargs: Engine arguments to merge with stage configs
default_stage_cfg_factory: Optional callable that takes no args and returns
default stage config list when no configs are found
Returns:
Tuple of (config_path, stage_configs)
"""
if stage_configs_path is None:
config_path = resolve_model_config_path(model)
stage_configs = load_stage_configs_from_model(model, base_engine_args=kwargs)
if not stage_configs:
if default_stage_cfg_factory is not None:
default_stage_cfg = default_stage_cfg_factory()
stage_configs = OmegaConf.create(default_stage_cfg)
else:
stage_configs = []
else:
config_path = stage_configs_path
stage_configs = load_stage_configs_from_yaml(stage_configs_path, base_engine_args=kwargs)
return config_path, stage_configs
def get_final_stage_id_for_e2e(
output_modalities: list[str] | None, default_modalities: list[str], stage_list: list
) -> int:
@@ -282,6 +368,117 @@ def get_final_stage_id_for_e2e(
return final_stage_id_for_e2e
def filter_dataclass_kwargs(cls: Any, kwargs: dict) -> dict:
"""Filter kwargs to only include fields defined in the dataclass.
Args:
cls: Dataclass type
kwargs: Keyword arguments to filter
Returns:
Filtered keyword arguments containing only valid dataclass fields
"""
if not is_dataclass(cls):
raise ValueError(f"{cls} is not a dataclass")
if not isinstance(kwargs, dict):
raise ValueError("kwargs must be a dictionary")
def _filter_value(value: Any, annotation: Any) -> Any:
"""Recursively filter nested dict/list values based on dataclass annotations."""
if annotation is None:
return value
origin = get_origin(annotation)
if origin is None:
if isinstance(annotation, type) and is_dataclass(annotation) and isinstance(value, dict):
return filter_dataclass_kwargs(annotation, value)
return value
if origin in (list, tuple, set):
args = get_args(annotation)
inner = args[0] if args else None
if isinstance(value, (list, tuple, set)):
return type(value)(_filter_value(v, inner) for v in value)
return value
if origin is dict:
args = get_args(annotation)
val_type = args[1] if len(args) > 1 else None
if isinstance(value, dict):
return {k: _filter_value(v, val_type) for k, v in value.items()}
return value
if origin is types.UnionType or origin is getattr(types, "UnionType", None):
for arg in get_args(annotation):
if isinstance(arg, type) and is_dataclass(arg) and isinstance(value, dict):
return filter_dataclass_kwargs(arg, value)
# Try container-style filtering for union members
filtered = _filter_value(value, arg)
if filtered is not value:
return filtered
return value
return value
valid_fields = {f.name: f for f in fields(cls) if f.init}
filtered_kwargs = {}
for k, v in kwargs.items():
if k not in valid_fields:
continue
field = valid_fields[k]
filtered_kwargs[k] = _filter_value(v, field.type)
return filtered_kwargs
# TODO(wuhang): Remove after PR #1115.
def build_base_engine_args(source: Any) -> dict[str, Any] | None:
"""Build base engine args with tokenizer and parallel configuration.
Automatically detects whether source is a dict-like object or namespace object.
Args:
source: Source object (args namespace or kwargs dict) containing configuration.
Returns:
Dictionary containing tokenizer and parallel configuration overrides,
or None if no configuration is present.
"""
# Auto-detect source type: dict-like objects have 'get' method
is_dict_like = hasattr(source, "get") and callable(getattr(source, "get"))
# Extract tokenizer
if is_dict_like:
tokenizer = source.get("tokenizer", None)
else:
tokenizer = getattr(source, "tokenizer", None)
base_engine_args = {"tokenizer": tokenizer} if tokenizer is not None else None
# Extract parallel configuration
parallel_keys = [
"tensor_parallel_size",
"pipeline_parallel_size",
"data_parallel_size",
"data_parallel_size_local",
"data_parallel_backend",
"distributed_executor_backend",
]
if is_dict_like:
parallel_overrides = {k: source[k] for k in parallel_keys if k in source and source[k] is not None}
else:
parallel_overrides = {
k: getattr(source, k) for k in parallel_keys if hasattr(source, k) and getattr(source, k) is not None
}
if parallel_overrides:
base_engine_args = base_engine_args or {}
base_engine_args.update(parallel_overrides)
return base_engine_args
# The following code detects if the process is running in a container and if
# PID host is available. If so, we can use process-scoped memory tracking;
# otherwise we need sequential init locks.
+95
View File
@@ -0,0 +1,95 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ZMQ-based queue utilities for Omni IPC."""
from __future__ import annotations
import queue
from typing import Any
import zmq
from vllm.utils.network_utils import make_zmq_socket
class ZmqQueue:
"""Queue-like wrapper on a ZMQ socket."""
def __init__(
self,
ctx: zmq.Context,
socket_type: int,
*,
bind: str | None = None,
connect: str | None = None,
recv_timeout_ms: int | None = None,
send_timeout_ms: int | None = None,
) -> None:
# Determine path and bind mode
path = bind if bind is not None else connect
if path is None:
raise ValueError("Either bind or connect must be specified")
bind_mode = bind is not None
self._socket = make_zmq_socket(ctx, path, socket_type, bind=bind_mode, linger=5000)
# Reusable poller for efficient polling operations
self._poller = zmq.Poller()
self._poller.register(self._socket, zmq.POLLIN)
# Store default timeout settings
self._default_recv_timeout = recv_timeout_ms
self._default_send_timeout = send_timeout_ms
# Apply timeout settings if specified
if recv_timeout_ms is not None:
self._socket.rcvtimeo = recv_timeout_ms
if send_timeout_ms is not None:
self._socket.sndtimeo = send_timeout_ms
self.endpoint = path
def put(self, obj: Any) -> None:
"""Send an object to the queue. Blocks until sent or timeout."""
try:
self._socket.send_pyobj(obj)
except zmq.Again as e:
raise queue.Full() from e
def put_nowait(self, obj: Any) -> None:
"""Send an object to the queue without blocking."""
try:
self._socket.send_pyobj(obj, flags=zmq.NOBLOCK)
except zmq.Again as e:
raise queue.Full() from e
def get(self, timeout: float | None = None) -> Any:
"""Receive an object from the queue with optional timeout in seconds."""
if timeout is None:
return self._socket.recv_pyobj()
# Use the reusable poller for timeout handling
events = dict(self._poller.poll(int(timeout * 1000)))
if events.get(self._socket) == zmq.POLLIN:
return self._socket.recv_pyobj()
raise queue.Empty()
def get_nowait(self) -> Any:
"""Receive an object from the queue without blocking."""
try:
return self._socket.recv_pyobj(flags=zmq.NOBLOCK)
except zmq.Again as e:
raise queue.Empty() from e
def empty(self) -> bool:
"""Check if the queue is empty without blocking."""
events = dict(self._poller.poll(0))
return events.get(self._socket) != zmq.POLLIN
def close(self) -> None:
self._socket.close(0)
def create_zmq_queue(ctx: zmq.Context, endpoint: str, socket_type: int) -> ZmqQueue:
"""Create a ZmqQueue from an endpoint string and socket type."""
return ZmqQueue(ctx, socket_type, connect=endpoint)
@@ -15,7 +15,6 @@ from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import (
Qwen3OmniMoeThinkerConfig,
)
from vllm.config import VllmConfig
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding
from vllm.model_executor.models.interfaces import SupportsMRoPE, SupportsMultiModal, SupportsPP
@@ -355,13 +354,14 @@ class Qwen3OmniMoeForConditionalGeneration(
# ========== Stage 3: Code2Wav ==========
elif self.model_stage == "code2wav":
seq_token_counts: list[int] | None = kwargs.get("seq_token_counts")
# Extract codec codes from input
if input_ids.shape[0] % 16 == 0:
ubatch_slices = get_forward_context().ubatch_slices
if ubatch_slices is not None:
max_seq_len = max(ubatch_slices) // 16
batch_size = len(ubatch_slices)
split_codes = torch.split(input_ids, ubatch_slices, dim=0)
if seq_token_counts is not None:
max_seq_len = max(seq_token_counts) // 16
batch_size = len(seq_token_counts)
split_codes = torch.split(input_ids, seq_token_counts, dim=0)
codes = torch.zeros((batch_size, 16, max_seq_len), device=input_ids.device, dtype=input_ids.dtype)
for idx, code in enumerate(split_codes):
seq_len = code.shape[0] // 16
@@ -386,7 +386,7 @@ class Qwen3OmniMoeForConditionalGeneration(
codes = input_ids_flatten.reshape(1, 16, -1)
# Generate audio from codec codes
audio_tensors = self.generate_audio(codes, voice_type)
audio_tensors = self.generate_audio(codes, voice_type, seq_token_counts)
return audio_tensors
@@ -458,16 +458,22 @@ class Qwen3OmniMoeForConditionalGeneration(
# ==================== Audio Generation ====================
def generate_audio(self, code: torch.Tensor, voice_type: str) -> list[torch.Tensor]:
def generate_audio(
self,
code: torch.Tensor,
voice_type: str,
seq_token_counts: list[int] | None = None,
) -> list[torch.Tensor]:
"""
Generate audio waveform from codec codes.
Args:
code: [8, T] - 8-layer RVQ codec codes
code: [batch, num_quantizers, T] - RVQ codec codes
voice_type: Voice type (not used in Qwen3, kept for compatibility)
seq_token_counts: Token count for each request in batch
Returns:
audio_tensor: [1, waveform_len] - Audio waveform
list of audio waveforms
"""
code2wav_dev = self._module_device(self.code2wav)
@@ -491,6 +497,7 @@ class Qwen3OmniMoeForConditionalGeneration(
talker_codes,
chunk_size=25,
left_context_size=25,
seq_token_counts=seq_token_counts,
)
else:
# Use chunked decode for memory efficiency
@@ -498,6 +505,7 @@ class Qwen3OmniMoeForConditionalGeneration(
talker_codes,
chunk_size=300,
left_context_size=25,
seq_token_counts=seq_token_counts,
)
return audio_tensors
@@ -22,7 +22,6 @@ from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import (
SnakeBeta,
)
from vllm.config import VllmConfig # type: ignore
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger # type: ignore
from vllm.model_executor.models.utils import ( # type: ignore
AutoWeightsLoader,
@@ -163,6 +162,7 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
codes: torch.Tensor,
chunk_size: int = 300,
left_context_size: int = 25,
seq_token_counts: list[int] | None = None,
) -> list[torch.Tensor]:
"""
Decode long sequences in chunks to avoid OOM.
@@ -173,6 +173,7 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
codes: [batch, num_quantizers, seq_len] - num_quantizers-layer RVQ codes
chunk_size: Number of codec frames per chunk
left_context_size: Number of overlapping frames for context
seq_token_counts: Token count for each request in batch
Returns:
list[torch.Tensor]: Complete waveform decoded from the input
@@ -197,12 +198,10 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
start_index = end_index
ubatch_slices = get_forward_context().ubatch_slices
if ubatch_slices is not None:
code_seq_lens = [seq_len // self.config.num_quantizers for seq_len in ubatch_slices]
if seq_token_counts is not None:
code_seq_lens = [seq_len // self.config.num_quantizers for seq_len in seq_token_counts]
else:
# Fallback: assume all batch elements share the same sequence length.
# Create one entry per batch so that each element is processed.
code_seq_lens = [codes.shape[-1]] * codes.shape[0]
batch_wav = torch.cat(wavs, dim=-1)
wavs = []
@@ -216,6 +215,7 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
codes: torch.Tensor,
chunk_size: int = 25,
left_context_size: int = 25,
seq_token_counts: list[int] | None = None,
) -> list[torch.Tensor]:
"""
Decode long sequences in chunks to avoid OOM.
@@ -226,21 +226,19 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
codes: [batch, num_quantizers, seq_len] - num_quantizers-layer RVQ codes
chunk_size: Number of codec frames per chunk
left_context_size: Number of overlapping frames for context
seq_token_counts: Token count for each request in batch
Returns:
list[torch.Tensor]: Complete waveform decoded from the input
codes. For ``batch_size == 1``, this is a list containing a
single tensor with shape ``[1, waveform_len]``.
"""
# Decode chunk
wavs = []
batch_wav = self(codes)
ubatch_slices = get_forward_context().ubatch_slices
if ubatch_slices is not None:
code_seq_lens = [seq_len // self.config.num_quantizers for seq_len in ubatch_slices]
if seq_token_counts is not None:
code_seq_lens = [n // self.config.num_quantizers for n in seq_token_counts]
else:
# Fallback: assume all batch elements share the same sequence length.
# Create one entry per batch so that each element is processed.
code_seq_lens = [codes.shape[-1]] * codes.shape[0]
for idx, code_seq_len in enumerate(code_seq_lens):
# TODO: need to optimize algorithms, current only support
@@ -9,6 +9,7 @@ import torch
import torch.nn as nn
from transformers.utils.hub import cached_file
from vllm.config import VllmConfig
from vllm.forward_context import get_forward_context, is_forward_context_available
from vllm.logger import init_logger
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -116,6 +117,28 @@ class Qwen3TTSCode2Wav(nn.Module):
def compute_logits(self, hidden_states: torch.Tensor | OmniOutput, sampling_metadata: Any = None) -> None:
return None
def _split_request_ids(self, ids: torch.Tensor, seq_token_counts: list[int] | None = None) -> list[torch.Tensor]:
"""Split concatenated input_ids into per-request segments.
Uses seq_token_counts (injected by the runner via model_kwargs) when
available, falling back to forward-context ubatch_slices when
micro-batching is active. Returns [ids] for single-request batches.
"""
if seq_token_counts is not None and len(seq_token_counts) > 1:
boundaries = [0]
for count in seq_token_counts:
boundaries.append(boundaries[-1] + count)
n = ids.numel()
return [ids[boundaries[i] : min(boundaries[i + 1], n)] for i in range(len(seq_token_counts))]
if is_forward_context_available():
slices = get_forward_context().ubatch_slices
if slices is not None and len(slices) > 1 and not any(hasattr(s, "token_slice") for s in slices):
boundaries = [0]
for s in slices:
boundaries.append(boundaries[-1] + s)
return [ids[boundaries[i] : boundaries[i + 1]] for i in range(len(boundaries) - 1)]
return [ids]
@torch.no_grad()
def forward(
self,
@@ -124,98 +147,129 @@ class Qwen3TTSCode2Wav(nn.Module):
intermediate_tensors: Any = None,
inputs_embeds: torch.Tensor | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor]:
) -> OmniOutput:
"""Decode codec codes into audio waveform.
input_ids layout: [codec_context_frames, *flat_codes]
input_ids layout per request: [codec_context_frames, *flat_codes]
where flat_codes is codebook-major [q*F].
When batched, uses forward context ubatch_slices to split the
concatenated input_ids and decode via a single batched forward pass.
"""
tok = self._ensure_speech_tokenizer_loaded()
self._ensure_speech_tokenizer_loaded()
assert self._num_quantizers is not None
assert self._decode_upsample_rate is not None
assert self._output_sample_rate is not None
sr_val = self._output_sample_rate
empty_ret = (
torch.zeros((0,), dtype=torch.float32),
torch.tensor(sr_val, dtype=torch.int32),
)
if input_ids is None:
return empty_ret
tok = self._speech_tokenizer
q = int(self._num_quantizers)
ids = input_ids.reshape(-1).to(dtype=torch.long)
n_tokens = ids.numel()
upsample = int(self._decode_upsample_rate)
sr_val = int(self._output_sample_rate)
sr_tensor = torch.tensor(sr_val, dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32)
if n_tokens == 0:
return empty_ret
# input_ids[0] = codec_context_frames (prepended by stage_input_processor).
ctx_frames = int(ids[0].item())
ids = ids[1:]
n_tokens = ids.numel()
if n_tokens == 0:
return empty_ret
# Warmup / dummy_run: not divisible by num_quantizers.
if n_tokens % q != 0:
logger.warning(
"Code2Wav input_ids length %d not divisible by num_quantizers %d, "
"likely a warmup run; returning empty audio.",
n_tokens,
q,
if input_ids is None or input_ids.numel() == 0:
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": [empty], "sr": [sr_tensor]},
)
return empty_ret
total_frames = n_tokens // q
ids = input_ids.reshape(-1).to(dtype=torch.long)
request_ids_list = self._split_request_ids(ids, kwargs.get("seq_token_counts"))
# Reshape codebook-major flat [q*F] -> [q, F] -> [F, q] for SpeechTokenizer.
codes_fq = ids.reshape(q, total_frames).transpose(0, 1).contiguous()
# Parse each request: extract ctx_frames, validate, reshape codes.
# input_ids layout per request: [codec_context_frames, *flat_codes]
# where flat_codes is codebook-major [q*F].
parsed = [] # (ctx_frames, actual_frames)
valid_codes = []
valid_indices = []
for i, req_ids in enumerate(request_ids_list):
if req_ids.numel() < 2:
parsed.append((0, 0))
continue
ctx_frames = int(req_ids[0].item())
flat = req_ids[1:]
n = flat.numel()
# Warmup / dummy_run: not divisible by num_quantizers.
if n == 0 or n % q != 0:
if n > 0:
logger.warning(
"Code2Wav input_ids length %d not divisible by num_quantizers %d, "
"likely a warmup run; returning empty audio.",
n,
q,
)
parsed.append((0, 0))
continue
frames = n // q
# Reshape codebook-major flat [q*F] -> [q, F] -> [F, q] for SpeechTokenizer.
codes_fq = flat.reshape(q, frames).transpose(0, 1).contiguous()
parsed.append((ctx_frames, frames))
valid_codes.append({"audio_codes": codes_fq})
valid_indices.append(i)
if not self._logged_codec_stats and total_frames > 1:
num_req = len(request_ids_list)
if not valid_codes:
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={
"model_outputs": [empty] * num_req,
"sr": [sr_tensor] * num_req,
},
)
if not self._logged_codec_stats:
self._logged_codec_stats = True
try:
uniq = int(torch.unique(codes_fq).numel())
cmin = int(codes_fq.min().item())
cmax = int(codes_fq.max().item())
head = codes_fq[: min(2, total_frames), : min(8, q)].cpu().tolist()
c = valid_codes[0]["audio_codes"]
logger.info(
"Code2Wav codec: frames=%d q=%d uniq=%d range=[%d,%d] head=%s",
total_frames,
"Code2Wav codec: frames=%d q=%d uniq=%d range=[%d,%d] head=%s batch=%d",
c.shape[0],
q,
uniq,
cmin,
cmax,
head,
int(torch.unique(c).numel()),
int(c.min().item()),
int(c.max().item()),
c[: min(2, c.shape[0]), : min(8, q)].cpu().tolist(),
len(valid_codes),
)
except Exception:
pass
wavs, sr = tok.decode({"audio_codes": codes_fq})
if not wavs:
raise ValueError("SpeechTokenizer code2wav produced empty waveform list.")
audio_np = wavs[0].astype(np.float32, copy=False)
# Batched decode: single forward pass through SpeechTokenizer.
wavs, _ = tok.decode(valid_codes)
if len(wavs) != len(valid_codes):
raise RuntimeError(f"Code2Wav returned {len(wavs)} waveforms for {len(valid_codes)} requests")
# Trim left-context waveform samples (streaming sliding window).
if ctx_frames > 0:
upsample = self._decode_upsample_rate
if upsample is None or upsample <= 0:
raise ValueError(f"Invalid decode upsample rate: {upsample}")
cut = ctx_frames * upsample
if cut < audio_np.shape[0]:
audio_np = audio_np[cut:]
else:
logger.warning(
"Context trim %d >= decoded length %d; returning empty audio.",
cut,
audio_np.shape[0],
)
return empty_ret
# Build per-request outputs, trimming padding and left-context.
audios = [empty] * num_req
srs = [sr_tensor] * num_req
audio_tensor = torch.from_numpy(audio_np).to(dtype=torch.float32).reshape(-1)
sr_tensor = torch.tensor(int(sr), dtype=torch.int32)
return audio_tensor, sr_tensor
for j, idx in enumerate(valid_indices):
ctx_frames, actual_frames = parsed[idx]
audio_np = wavs[j].astype(np.float32, copy=False)
# Trim decoder padding (output may be longer due to batch padding).
expected_len = actual_frames * upsample
if audio_np.shape[0] > expected_len:
audio_np = audio_np[:expected_len]
# Trim left-context waveform samples (streaming sliding window).
if ctx_frames > 0:
cut = ctx_frames * upsample
if cut < audio_np.shape[0]:
audio_np = audio_np[cut:]
else:
logger.warning(
"Context trim %d >= decoded length %d; returning empty audio.",
cut,
audio_np.shape[0],
)
continue
if audio_np.shape[0] > 0:
audios[idx] = torch.from_numpy(audio_np).to(dtype=torch.float32).reshape(-1)
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audios, "sr": srs},
)
def make_omni_output(self, model_outputs: torch.Tensor | OmniOutput, **kwargs: Any) -> OmniOutput:
if isinstance(model_outputs, OmniOutput):
@@ -0,0 +1,105 @@
# Same as qwen3_tts.yaml with batched talker and code2wav.
# Stage 0: max_batch_size 4, stage 1: max_batch_size 4.
# max_batch_size must be a power of two to align with CUDA graph capture sizes
# (stage 0) and must match --batch-size in end2end.py / benchmark scripts.
async_chunk: true
stage_args:
- stage_id: 0
stage_type: llm
runtime:
devices: "0"
max_batch_size: 4
engine_args:
model_stage: qwen3_tts
model_arch: Qwen3TTSTalkerForConditionalGeneration
# Force stage-specific registered architecture.
hf_overrides:
architectures: [Qwen3TTSTalkerForConditionalGeneration]
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: false
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.3
distributed_executor_backend: "mp"
max_num_batched_tokens: 512
max_model_len: 4096
custom_process_next_stage_input_func: vllm_omni.model_executor.stage_input_processors.qwen3_tts.talker2code2wav_async_chunk
# Use named connector to apply runtime.connectors.extra.
output_connectors:
to_stage_1: connector_of_shared_memory
default_sampling_params:
temperature: 0.9
top_k: 50
max_tokens: 4096
seed: 42
detokenize: false
repetition_penalty: 1.05
stop_token_ids: [2150]
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
max_batch_size: 4
engine_args:
model_stage: code2wav
model_arch: Qwen3TTSCode2Wav
# Force stage-specific registered architecture.
hf_overrides:
architectures: [Qwen3TTSCode2Wav]
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.2
distributed_executor_backend: "mp"
# Must be divisible by num_code_groups and cover (left_context + chunk).
max_num_batched_tokens: 8192
# async_chunk appends windows per step; max_model_len must cover accumulated stream.
max_model_len: 32768
engine_input_source: [0]
final_output: true
final_output_type: audio
# Distributed connector configuration
input_connectors:
from_stage_0: connector_of_shared_memory
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 65536
seed: 42
detokenize: true
repetition_penalty: 1.0
runtime:
enabled: true
defaults:
window_size: -1
max_inflight: 1
connectors:
connector_of_shared_memory:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536
# Frame-aligned codec streaming transport.
codec_streaming: true
# Connector polling / timeout (unit: loop count, sleep interval in seconds).
connector_get_sleep_s: 0.01
connector_get_max_wait_first_chunk: 3000
connector_get_max_wait: 300
# Align with Omni: small chunks with sufficient context overlap.
codec_chunk_frames: 25
codec_left_context_frames: 25
edges:
- from: 0
to: 1
window_size: -1
-24
View File
@@ -192,15 +192,6 @@ class GPUARModelRunner(OmniGPUModelRunner):
num_encoder_reqs=len(scheduler_output.scheduled_encoder_inputs),
)
logger.debug(
"Running batch with cudagraph_mode: %s, batch_descriptor: %s, "
"should_ubatch: %s, num_tokens_across_dp: %s",
cudagraph_mode,
batch_desc,
should_ubatch,
num_tokens_across_dp,
)
num_tokens_padded = batch_desc.num_tokens
num_reqs_padded = batch_desc.num_reqs if batch_desc.num_reqs is not None else num_reqs
ubatch_slices, ubatch_slices_padded = maybe_create_ubatch_slices(
@@ -211,12 +202,6 @@ class GPUARModelRunner(OmniGPUModelRunner):
self.parallel_config.num_ubatches,
)
logger.debug(
"ubatch_slices: %s, ubatch_slices_padded: %s",
ubatch_slices,
ubatch_slices_padded,
)
pad_attn = cudagraph_mode == CUDAGraphMode.FULL
use_spec_decode = len(scheduler_output.scheduled_spec_decode_tokens) > 0
@@ -313,15 +298,6 @@ class GPUARModelRunner(OmniGPUModelRunner):
aux_hidden_states = None
hidden_states, multimodal_outputs = self.extract_multimodal_outputs(model_output)
if multimodal_outputs is not None:
keys_or_type = (
list(multimodal_outputs.keys())
if isinstance(multimodal_outputs, dict)
else type(multimodal_outputs)
)
logger.debug(f"[AR] execute_model: multimodal_outputs keys = {keys_or_type}")
else:
logger.debug("[AR] execute_model: multimodal_outputs is None")
if not self.broadcast_pp_output:
# Common case.
@@ -250,6 +250,9 @@ class GPUGenerationModelRunner(OmniGPUModelRunner):
intermediate_tensors,
)
# [Omni] Pass token counts per request for code2wav output slicing
model_kwargs["seq_token_counts"] = tokens
# Set cudagraph mode to none if calc_kv_scales is true.
# KV scales calculation involves dynamic operations that are incompatible
# with CUDA graph capture.
@@ -258,10 +261,6 @@ class GPUGenerationModelRunner(OmniGPUModelRunner):
# Mark KV scales as calculated after the first forward pass
self.calculate_kv_scales = False
if ubatch_slices_padded is None:
# reuse ubatch_slices_padded for code2wav batching
ubatch_slices_padded = tokens
# Run the model.
# Use persistent buffers for CUDA graphs.
# When spec decode is enabled, delay clearing connector metadata
-6
View File
@@ -1148,12 +1148,6 @@ class OmniGPUModelRunner(GPUModelRunner):
"""Inject omni-specific kwargs into forward and cache model output"""
model_kwargs_extra = self._build_model_kwargs_extra()
runtime_info = model_kwargs_extra.get("runtime_additional_information", [])
if runtime_info:
for i, info in enumerate(runtime_info):
if info:
logger.debug(f"[OMNI] req[{i}] runtime_additional_information keys: {list(info.keys())}")
model_output = super()._model_forward(
input_ids=input_ids,
positions=positions,