Merge branch 'main' into feat/moss-tts-nano

Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-04-21 17:50:21 -04:00
commit 3bd77d3f8f
611 files changed
+48775 -14783

No files matched your search

+182 -19
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import asyncio
import time
import uuid
from collections.abc import AsyncGenerator, Iterable, Mapping, Sequence
from typing import TYPE_CHECKING, Any
@@ -24,10 +25,12 @@ from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.tasks import SupportedTask
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.data import OmniACK, OmniSleepTask, OmniWakeTask
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.omni_base import OmniBase
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
if TYPE_CHECKING:
from vllm.inputs.preprocess import InputPreprocessor
@@ -40,6 +43,63 @@ logger = init_logger(__name__)
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
class AsyncEventResolver:
"""
A generic signal aggregator designed for synchronized handshakes in
distributed or multi-stage environments. Supports waiting for a specified
number (expected_count) of worker signals in both inline and multiprocess modes.
"""
def __init__(self, orchestrator=None):
self._pending_tasks: dict[str, dict] = {}
self.orchestrator = orchestrator
self._lock = asyncio.Lock()
def watch_task(self, task_id: str, expected_count: int = 1) -> asyncio.Future:
loop = asyncio.get_running_loop()
fut = loop.create_future()
self._pending_tasks[task_id] = {
"future": fut,
"expected_count": expected_count,
"received": [],
"start_time": time.time(),
}
return fut
async def resolve(self, ack: OmniACK):
tid = getattr(ack, "task_id", None)
if tid is None and isinstance(ack, dict):
tid = ack.get("task_id")
async with self._lock:
task_info = self._pending_tasks.get(tid)
if task_info is None:
logger.warning(f"Received stray ACK for task_id {tid}. Task might have timed out.")
return
task_info["received"].append(ack)
current_count = len(task_info["received"])
expected = task_info["expected_count"]
orchestrator = self.orchestrator
if orchestrator and hasattr(orchestrator, "metrics") and orchestrator.metrics:
freed = getattr(ack, "freed_bytes", 0)
if freed == 0 and isinstance(ack, dict):
freed = ack.get("freed_bytes", 0)
orchestrator.metrics.record_vram_reclaimed(freed)
logger.info(f"[Resolver] Task {tid} progress: {current_count}/{expected} ACKs received.")
if current_count >= expected:
self._pending_tasks.pop(tid)
fut = task_info["future"]
if not fut.done():
elapsed = time.time() - task_info["start_time"]
logger.info(f"[Resolver] Task {tid} completed successfully in {elapsed:.2f}s.")
fut.set_result(task_info["received"])
class AsyncOmni(EngineClient, OmniBase):
"""Asynchronous unified entry point for multi-stage pipelines using AsyncOmniEngine.
@@ -76,9 +136,8 @@ class AsyncOmni(EngineClient, OmniBase):
self._paused: bool = False
self._is_sleeping: bool = False
self.final_output_task: asyncio.Task | None = None
self.event_resolver = AsyncEventResolver(orchestrator=self)
self.config_path = self.engine.config_path
self.stage_configs = self.engine.stage_configs
self.tts_max_instructions_length = kwargs.get("tts_max_instructions_length", None)
self.input_processor = self.engine.input_processor
@@ -209,6 +268,13 @@ class AsyncOmni(EngineClient, OmniBase):
# Start final output dispatcher on the first call to generate()
self._final_output_handler()
# Expand sampling params for PD disaggregation (user may provide N-1 params)
if (
sampling_params_list is not None
and isinstance(sampling_params_list, Sequence)
and not isinstance(sampling_params_list, (str, bytes))
):
sampling_params_list = self._maybe_expand_sampling_params(list(sampling_params_list))
sampling_params_list = self.resolve_sampling_params_list(sampling_params_list)
# Track per-request metrics
@@ -228,20 +294,27 @@ class AsyncOmni(EngineClient, OmniBase):
req_state.metrics = metrics
self.request_states[request_id] = req_state
# PD disaggregation: modify prefill-stage sampling params per request
req_sp_list = list(sampling_params_list)
pd_pair = self._get_pd_separation_pair()
if pd_pair is not None:
p_id = pd_pair[0]
req_sp_list[p_id] = self._prepare_prefill_sampling_params(request_id, req_sp_list[p_id])
# Add request(s) to stage 0. For streaming inputs, submit
# chunks incrementally through streaming_update.
if isinstance(prompt, AsyncGenerator):
input_stream_task = await self._add_streaming_input_request(
request_id=request_id,
input_stream=prompt,
sampling_params_list=sampling_params_list,
sampling_params_list=req_sp_list,
final_stage_id=final_stage_id_for_e2e,
)
else:
await self.engine.add_request_async(
request_id=request_id,
prompt=prompt,
sampling_params_list=sampling_params_list,
sampling_params_list=req_sp_list,
final_stage_id=final_stage_id_for_e2e,
)
submit_ts = time.time()
@@ -296,7 +369,6 @@ class AsyncOmni(EngineClient, OmniBase):
if not stage0_params.skip_clone:
stage0_params = stage0_params.clone()
stage0_params.skip_clone = True
stage0_params.output_kind = RequestOutputKind.DELTA
has_submitted_first_chunk = False
@@ -421,6 +493,9 @@ class AsyncOmni(EngineClient, OmniBase):
stage_id = result.get("stage_id", 0)
if result.get("type") == "error" and result.get("fatal"):
raise EngineDeadError(result.get("error", ""))
# Check for errors
if "error" in result:
logger.error(
@@ -431,6 +506,8 @@ class AsyncOmni(EngineClient, OmniBase):
)
raise RuntimeError(result)
self._check_engine_output_error(result, request_id, stage_id)
# Process the result (constructs OmniRequestOutput)
output_to_yield = self._process_single_result(
result,
@@ -476,6 +553,22 @@ class AsyncOmni(EngineClient, OmniBase):
await asyncio.sleep(_FINAL_OUTPUT_IDLE_SLEEP_S)
continue
if isinstance(msg, dict) and msg.get("type") == "ack":
ack_data = msg.get("ack")
tid = getattr(ack_data, "task_id", "unknown")
logger.info(f"[{self._name}] Intercepted wrapped ACK for task {tid}")
await self.event_resolver.resolve(ack_data)
continue
if isinstance(msg, OmniACK):
logger.info(f"[{self._name}] Intercepted raw ACK object: {msg.task_id}")
await self.event_resolver.resolve(msg)
continue
if hasattr(msg, "task_id"):
tid = getattr(msg, "task_id")
logger.info(f"[{self._name}] Intercepted task-ID object: {tid}")
await self.event_resolver.resolve(msg)
continue
should_continue, _, stage_id, req_state = self._handle_output_message(msg)
if should_continue:
continue
@@ -487,6 +580,16 @@ class AsyncOmni(EngineClient, OmniBase):
except asyncio.CancelledError:
raise
except EngineDeadError as e:
logger.error("[AsyncOmni] Engine dead: %s", e)
for req_state in list(self.request_states.values()):
error_msg = {
"type": "error",
"error": str(e),
"fatal": True,
"request_id": req_state.request_id,
}
await req_state.queue.put(error_msg)
except Exception as e:
logger.exception("[AsyncOmni] final_output_loop failed.")
for req_state in list(self.request_states.values()):
@@ -642,21 +745,68 @@ class AsyncOmni(EngineClient, OmniBase):
logger.warning("[AsyncOmni] reset_prefix_cache not yet supported with Orchestrator process")
return True
async def sleep(self, level: int = 1, mode: PauseMode = "abort") -> None:
"""Sleep all stages.
async def sleep(
self, stage_ids: list[int] | None = None, level: int = 2, mode: PauseMode = "abort"
) -> list[OmniACK]:
self._final_output_handler()
if stage_ids is None:
stage_ids = list(range(len(self.engine.stage_clients)))
total_workers = 0
for sid in stage_ids:
client = self.engine.stage_clients[sid]
# During the Diffusion phase, regardless of the TP amount,
# currently only a summary ACK is reported at Rank 0.
if getattr(client, "stage_type", "") == "diffusion":
total_workers += 1
else:
config = self.engine.stage_vllm_configs[sid]
actual_tp = config.parallel_config.tensor_parallel_size if config else 1
total_workers += actual_tp
Best-effort: unsupported stages will emit a TODO result.
"""
task_id = str(uuid.uuid4())
self.event_resolver.watch_task(task_id, expected_count=total_workers)
logger.info(f"[{self._name}] Sleep initiated (Task: {task_id}). Awaiting {total_workers} ACKs...")
task = OmniSleepTask(level=level, task_id=task_id)
rpc_results = await self.collective_rpc(method="handle_sleep_task", args=(task,), stage_ids=stage_ids)
final_acks = []
for stage_res in rpc_results:
worker_acks = stage_res if isinstance(stage_res, list) else [stage_res]
for ack in worker_acks:
if ack is not None:
await self.event_resolver.resolve(ack)
final_acks.append(ack)
self._is_sleeping = True
await self.collective_rpc(method="sleep", args=(level,))
return final_acks
async def wake_up(self, tags: list[str] | None = None) -> None:
"""Wake up all stages.
Best-effort: unsupported stages will emit a TODO result.
"""
async def wake_up(self, stage_ids: list[int] | None = None, tags: list[str] | None = None) -> list[OmniACK]:
self._final_output_handler()
if stage_ids is None:
stage_ids = list(range(len(self.engine.stage_clients)))
total_workers = 0
for sid in stage_ids:
client = self.engine.stage_clients[sid]
if getattr(client, "stage_type", "") == "diffusion":
total_workers += 1
else:
config = self.engine.stage_vllm_configs[sid]
total_workers += config.parallel_config.tensor_parallel_size if config else 1
task_id = str(uuid.uuid4())
self.event_resolver.watch_task(task_id, expected_count=total_workers)
logger.info(f"[{self._name}] Wake-up initiated (Task: {task_id}). Awaiting {total_workers} ACKs...")
task = OmniWakeTask(tags=tags, task_id=task_id)
rpc_results = await self.collective_rpc(method="handle_wake_task", args=(task,), stage_ids=stage_ids)
final_acks = []
for stage_res in rpc_results:
worker_acks = stage_res if isinstance(stage_res, list) else [stage_res]
for ack in worker_acks:
if ack is not None:
await self.event_resolver.resolve(ack)
final_acks.append(ack)
current_omni_platform.synchronize()
await asyncio.sleep(0.1)
self._is_sleeping = False
await self.collective_rpc(method="wake_up", args=(tags,))
logger.info(f"[{self._name}] All {len(final_acks)}/{total_workers} workers reported WARM for task {task_id}.")
return final_acks
async def is_sleeping(self) -> bool:
"""Return whether all stages are sleeping.
@@ -706,12 +856,25 @@ class AsyncOmni(EngineClient, OmniBase):
@property
def is_running(self) -> bool:
"""Check if the engine is running."""
return self.final_output_task is not None and not self.final_output_task.done()
orchestrator_alive = self.engine.is_alive()
task_alive = self.final_output_task is not None and not self.final_output_task.done()
return orchestrator_alive and task_alive
@property
def errored(self) -> bool:
"""Whether orchestrator thread has stopped unexpectedly."""
return not self.engine.is_alive()
"""Whether the engine is in a non-recoverable error state.
Delegates to ``OmniBase.errored`` which checks the orchestrator
thread and all stage clients. Redeclared here to satisfy the
``EngineClient`` abstract-property requirement (Python's ABC
mechanism does not resolve abstract methods from sibling MRO
entries).
"""
return OmniBase.errored.fget(self) # type: ignore[union-attr]
@property
def _name(self) -> str:
return "AsyncOrchestrator"
@property
def is_stopped(self) -> bool:
@@ -1,233 +0,0 @@
"""CFG companion request tracker for the Omni orchestrator.
Encapsulates all bookkeeping for Classifier-Free Guidance companion
requests (prompt expansion, parent/companion ID mapping, completion
tracking, deferred forwarding, failure propagation, and timeouts)
so that ``Omni._run_generation`` stays clean.
"""
from __future__ import annotations
import copy
import logging
import os
import time
from collections.abc import Callable, Sequence
from typing import Any
from vllm_omni.distributed.omni_connectors.adapter import try_send_via_connector
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams
logger = logging.getLogger(__name__)
class CfgCompanionTracker:
"""Manages CFG companion request lifecycle in the orchestrator scheduling loop."""
def __init__(
self,
prompt_expand_func: Callable[..., Any] | None,
stage0_sampling_params: Any,
timeout_s: float | None = None,
) -> None:
self._expand_func = prompt_expand_func
self._sp0 = stage0_sampling_params
self._timeout_s = (
timeout_s if timeout_s is not None else float(os.environ.get("VLLM_CFG_PENDING_TIMEOUT_S", "120"))
)
self._companion_map: dict[str, dict[str, str]] = {} # parent -> {role: companion_id}
self._companion_ids: set[str] = set()
self._companion_to_parent: dict[str, str] = {} # companion -> parent
self._done: dict[str, set[str]] = {} # parent -> completed companion ids
self._pending_parents: dict[str, dict[str, Any]] = {} # parent -> deferred result
self._failed_parents: set[str] = set()
@property
def is_active(self) -> bool:
return bool(self._companion_ids)
@property
def num_companions(self) -> int:
return len(self._companion_ids)
@property
def stage0_sampling_params(self) -> Any:
return self._sp0
def expand_prompts(
self,
request_id_to_prompt: dict[str, Any],
) -> list[tuple[str, Any]]:
"""Expand user prompts into ``(companion_id, prompt)`` pairs via model-specific func."""
if not self._expand_func:
return []
pairs: list[tuple[str, Any]] = []
for rid, prompt in request_id_to_prompt.items():
expanded = self._expand_func(prompt, self._sp0)
if not expanded:
continue
role_map: dict[str, str] = {}
for ep in expanded:
cid = f"{rid}{ep.request_id_suffix}"
role_map[ep.role] = cid
self._companion_ids.add(cid)
self._companion_to_parent[cid] = rid
pairs.append((cid, ep.prompt))
self._companion_map[rid] = role_map
self._done[rid] = set()
logger.debug(
"CFG expansion: %d parent(s) -> %d companion(s)",
len(self._companion_map),
len(self._companion_ids),
)
return pairs
def is_companion(self, req_id: str) -> bool:
return req_id in self._companion_ids
def has_companions(self, parent_id: str) -> bool:
return parent_id in self._companion_map
def all_companions_done(self, parent_id: str) -> bool:
role_map = self._companion_map.get(parent_id, {})
done_set = self._done.get(parent_id, set())
return all(cid in done_set for cid in role_map.values())
def get_companion_request_ids(self, parent_id: str) -> dict[str, str]:
"""Return ``{role: companion_request_id}`` for a parent."""
return self._companion_map.get(parent_id, {})
def is_parent_failed(self, parent_id: str) -> bool:
return parent_id in self._failed_parents
# -- Lifecycle events --
def on_companion_error(self, companion_id: str) -> tuple[str | None, bool]:
"""Record failure. Returns ``(parent_id, parent_was_aborted)``."""
parent_id = self._companion_to_parent.get(companion_id)
if parent_id is None:
return None, False
self._failed_parents.add(parent_id)
logger.error("CFG companion %s failed; marking parent %s as failed", companion_id, parent_id)
aborted = parent_id in self._pending_parents
if aborted:
self._pending_parents.pop(parent_id, None)
return parent_id, aborted
def on_companion_completed(self, companion_id: str) -> str | None:
"""Mark done. Returns parent_id only if parent is pending and all companions finished."""
parent_id = self._companion_to_parent.get(companion_id)
if parent_id is None:
return None
self._done[parent_id].add(companion_id)
logger.debug("CFG companion %s completed (parent=%s)", companion_id, parent_id)
if parent_id in self._pending_parents and self.all_companions_done(parent_id):
return parent_id
return None
def consume_parent_failure(self, parent_id: str) -> None:
self._failed_parents.discard(parent_id)
# -- Deferred parent management --
def defer_parent(self, parent_id: str, engine_outputs: Any, stage_id: int) -> None:
"""Hold parent result while waiting for companions to finish."""
self._pending_parents[parent_id] = {
"engine_outputs": engine_outputs,
"stage_id": stage_id,
"pending_since": time.time(),
}
logger.debug("Parent %s deferred, waiting for CFG companions", parent_id)
def pop_pending_parent(self, parent_id: str) -> dict[str, Any] | None:
return self._pending_parents.pop(parent_id, None)
def check_timeouts(self) -> list[str]:
"""Return and remove parent IDs that exceeded the pending timeout."""
if not self._pending_parents:
return []
now = time.time()
timed_out: list[str] = []
for pid in list(self._pending_parents):
pending_since = self._pending_parents[pid].get("pending_since", now)
if now - pending_since > self._timeout_s:
self._pending_parents.pop(pid)
self._failed_parents.discard(pid)
timed_out.append(pid)
logger.error("Parent %s timed out waiting for CFG companions (>%.0fs)", pid, self._timeout_s)
return timed_out
# -- Forward parent with CFG KV --
def forward_parent_with_cfg(
self,
req_id: str,
parent_result: dict[str, Any],
stage_list: Sequence[Any],
connectors: dict[tuple[str, str], Any],
sampling_params_list: Sequence[OmniSamplingParams],
request_id_to_prompt: dict[str, Any],
final_stage_id_to_prompt: dict[str, int],
metrics: Any,
remaining_by_stage: list[int],
) -> bool:
"""Forward a parent request to the next stage with CFG KV request IDs attached."""
stage_id = parent_result["stage_id"]
next_stage_id = stage_id + 1
if next_stage_id > final_stage_id_to_prompt.get(req_id, 0):
return True
next_stage = stage_list[next_stage_id]
try:
with metrics.stage_postprocess_timer(stage_id, req_id):
next_inputs = next_stage.process_engine_inputs(
stage_list,
[request_id_to_prompt[req_id]],
source_outputs_override=parent_result["engine_outputs"],
)
except Exception as e:
logger.exception(
"Process engine inputs error for req %s at stage %d: %s",
req_id,
next_stage_id,
e,
)
return False
sp_next = copy.deepcopy(sampling_params_list[next_stage_id])
if isinstance(sp_next, OmniDiffusionSamplingParams):
sp_next.cfg_kv_request_ids = self.get_companion_request_ids(req_id)
logger.info(
"Attaching cfg_kv_request_ids=%s to request %s",
sp_next.cfg_kv_request_ids,
req_id,
)
connector_key = (str(stage_id), str(next_stage_id))
connector = connectors.get(connector_key)
sent_via_connector = False
if connector:
sent_via_connector = try_send_via_connector(
connector=connector,
stage_id=stage_id,
next_stage_id=next_stage_id,
req_id=req_id,
next_inputs=next_inputs,
sampling_params=sp_next,
original_prompt=request_id_to_prompt[req_id],
next_stage_queue_submit_fn=stage_list[next_stage_id].submit,
metrics=metrics,
)
if not sent_via_connector:
raise RuntimeError(
f"Failed to send CFG request {req_id} to stage-{next_stage_id} via connector. "
"Configure a connector for this edge or inspect connector logs for details."
)
logger.debug("Forwarded CFG-enabled request %s to stage-%d", req_id, next_stage_id)
remaining_by_stage[next_stage_id] += 1
return True
+142 -1
View File
@@ -1,4 +1,5 @@
import argparse
import os
from vllm.benchmarks.serve import add_cli_args
@@ -6,15 +7,149 @@ from vllm_omni.benchmarks.serve import main
from vllm_omni.entrypoints.cli.benchmark.base import OmniBenchmarkSubcommandBase
def add_daily_omni_cli_args(parser: argparse.ArgumentParser) -> None:
"""Add CLI arguments specific to Daily-Omni dataset.
This function should be called by the CLI entrypoint to add additional
arguments for daily-omni benchmark support.
Args:
parser: The ArgumentParser instance to extend
"""
# Daily-Omni specific arguments
daily_omni_group = parser.add_argument_group("Daily-Omni Dataset Options")
daily_omni_group.add_argument(
"--daily-omni-qa-json",
type=str,
default=None,
help="Path to local upstream qa.json. When set, QA rows are read from this file and "
"the HuggingFace dataset is not loaded (no network). Use with --daily-omni-video-dir "
"for fully offline runs. --dataset-path / Hub split flags are then ignored for QA loading.",
)
daily_omni_group.add_argument(
"--daily-omni-video-dir",
type=str,
default=None,
help="Root directory of extracted Daily-Omni videos (contents of Videos.tar: "
"each video_id in its own subdir with {video_id}_video.mp4). "
"When using file URLs, you MUST start the vLLM server with "
"--allowed-local-media-path set to this same directory (or a parent), "
"otherwise requests fail with 'Cannot load local files without "
"--allowed-local-media-path'.",
)
daily_omni_group.add_argument(
"--daily-omni-inline-local-video",
action="store_true",
default=False,
help="For local videos only: embed MP4 as base64 data URLs in benchmark "
"requests so the server does not need --allowed-local-media-path. "
"Increases request size and client memory; use for small --num-prompts. "
"When using --daily-omni-input-mode audio or all, local WAV files are "
"embedded the same way.",
)
daily_omni_group.add_argument(
"--daily-omni-input-mode",
type=str,
choices=["all", "visual", "audio"],
default="all",
help="Daily-Omni input protocol (mirrors upstream Lliar-liar/Daily-Omni "
"--input_mode). 'visual': video only (default). 'audio': WAV only, "
"requires {video_id}/{video_id}_audio.wav under --daily-omni-video-dir. "
"'all': video + WAV together. Sets mm_processor_kwargs.use_audio_in_video=false "
"and matches official separate video/audio streams.",
)
daily_omni_group.add_argument(
"--daily-omni-save-eval-items",
action="store_true",
default=False,
help="Include per-request Daily-Omni accuracy rows (gold/predicted/correct) "
"in the saved JSON under key daily_omni_eval_items. "
"Alternatively set env DAILY_OMNI_SAVE_EVAL_ITEMS=1.",
)
# Note: --dataset-name daily-omni via get_samples patch; use either Hub (--dataset-path
# liarliar/Daily-Omni) or local --daily-omni-qa-json (offline).
def add_seed_tts_cli_args(parser: argparse.ArgumentParser) -> None:
"""CLI for Seed-TTS zero-shot TTS benchmark (``--dataset-name seed-tts``)."""
g = parser.add_argument_group("Seed-TTS Dataset Options")
g.add_argument(
"--seed-tts-locale",
type=str,
choices=["en", "zh"],
default="en",
help="Which Seed-TTS split to load: en/meta.lst or zh/meta.lst under the dataset root.",
)
g.add_argument(
"--seed-tts-root",
type=str,
default=None,
help="Override root directory that contains en/ and zh/ (meta.lst + prompt-wavs). "
"If set, --dataset-path can still name the HF repo for logging; this path is used for files.",
)
g.add_argument(
"--seed-tts-file-ref-audio",
action="store_true",
default=False,
help="Send ref_audio as file:// URIs (smaller HTTP bodies). Requires the API server "
"to be started with --allowed-local-media-path covering the Seed-TTS dataset root. "
"Default is inline data:audio/wav;base64 so Qwen3-TTS works without that flag.",
)
g.add_argument(
"--seed-tts-inline-ref-audio",
action="store_true",
default=False,
help=argparse.SUPPRESS,
)
g.add_argument(
"--seed-tts-system-prompt",
type=str,
default=None,
help="Override chat system message for --backend openai-chat-omni (Qwen3-Omni TTS). "
"Default follows official Qwen3-Omni identity + zero-shot voice-clone instructions.",
)
g.add_argument(
"--seed-tts-wer-eval",
action="store_true",
default=False,
help="Keep synthesized audio as 24 kHz mono PCM for WER (works with "
"--backend openai-audio-speech or openai-chat-omni). Scoring follows "
"BytedanceSpeech/seed-tts-eval (Whisper-large-v3 / Paraformer-zh + jiwer). "
"Sets SEED_TTS_WER_EVAL=1. Install: pip install 'vllm-omni[seed-tts-eval]'. "
"Optional: SEED_TTS_EVAL_DEVICE, SEED_TTS_HF_WHISPER_MODEL.",
)
g.add_argument(
"--seed-tts-wer-save-items",
action="store_true",
default=False,
help="Include per-utterance ASR rows in the saved JSON under key seed_tts_wer_eval_items. "
"Or set SEED_TTS_WER_SAVE_ITEMS=1.",
)
class OmniBenchmarkServingSubcommand(OmniBenchmarkSubcommandBase):
"""The `serve` subcommand for vllm bench."""
name = "serve"
help = "Benchmark the online serving throughput."
help = "Benchmark the online serving throughput. Supports Daily-Omni and Seed-TTS datasets."
@classmethod
def add_cli_args(cls, parser: argparse.ArgumentParser) -> None:
add_cli_args(parser)
# Add Daily-Omni specific arguments
add_daily_omni_cli_args(parser)
add_seed_tts_cli_args(parser)
for action in parser._actions:
if action.dest == "dataset_name" and action.choices is not None:
extra = [c for c in ("daily-omni", "seed-tts") if c not in action.choices]
if extra:
action.choices = list(action.choices) + extra
# Update help messages for omni-specific features
for action in parser._actions:
if action.dest == "percentile_metrics":
action.help = (
@@ -48,4 +183,10 @@ class OmniBenchmarkServingSubcommand(OmniBenchmarkSubcommandBase):
@staticmethod
def cmd(args: argparse.Namespace) -> None:
if getattr(args, "daily_omni_save_eval_items", False):
os.environ["DAILY_OMNI_SAVE_EVAL_ITEMS"] = "1"
if getattr(args, "seed_tts_wer_eval", False):
os.environ["SEED_TTS_WER_EVAL"] = "1"
if getattr(args, "seed_tts_wer_save_items", False):
os.environ["SEED_TTS_WER_SAVE_ITEMS"] = "1"
main(args)
+51 -1
View File
@@ -9,6 +9,7 @@ import argparse
import json
import os
import signal
import sys
from types import FrameType
from typing import Any
@@ -21,6 +22,7 @@ from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm_omni.entrypoints.cli.logo import log_logo
from vllm_omni.entrypoints.openai.api_server import omni_run_server
from vllm_omni.entrypoints.utils import detect_explicit_cli_keys
logger = init_logger(__name__)
@@ -79,6 +81,9 @@ class OmniServeCommand(CLISubcommand):
"""The `serve` subcommand for the vLLM CLI."""
name = "serve"
# Parser stashed at subparser_init so ``cmd`` can resolve each user-typed
# flag to its real ``dest`` via the parser's action table.
_parser: FlexibleArgumentParser | None = None
@staticmethod
def cmd(args: argparse.Namespace) -> None:
@@ -90,6 +95,10 @@ class OmniServeCommand(CLISubcommand):
if hasattr(args, "model_tag") and args.model_tag is not None:
args.model = args.model_tag
# Stash the set of long-option keys the user actually typed so the
# stage-config factory can give YAML precedence over argparse defaults.
args._cli_explicit_keys = detect_explicit_cli_keys(sys.argv[1:], OmniServeCommand._parser)
if args.headless:
run_headless(args)
else:
@@ -130,6 +139,17 @@ class OmniServeCommand(CLISubcommand):
action="store_true",
help="Enable vLLM-Omni mode for multi-modal and diffusion models",
)
try:
omni_config_group.add_argument(
"--enable-sleep-mode",
action="store_true",
default=False,
help="Enable GPU memory pool for sleep mode.",
)
except argparse.ArgumentError:
pass
omni_config_group.add_argument(
"--task-type",
type=str,
@@ -138,11 +158,33 @@ class OmniServeCommand(CLISubcommand):
help="Default task type for TTS models (CustomVoice, VoiceDesign, or Base). "
"If not specified, will be inferred from model path.",
)
# TODO(@lishunyang12): deprecate once all models migrate to --deploy-config
omni_config_group.add_argument(
"--stage-configs-path",
type=str,
default=None,
help="Path to the stage configs file. If not specified, the stage configs will be loaded from the model.",
help="[Deprecated — will be removed in a future release] Path to a legacy "
"stage configs YAML (stage_args format). Prefer --deploy-config for new-format deploy YAMLs.",
)
omni_config_group.add_argument(
"--deploy-config",
type=str,
default=None,
help="Path to a deploy config YAML (new format with stages/engine_args). "
"Mutually exclusive with --stage-configs-path.",
)
omni_config_group.add_argument(
"--stage-overrides",
type=str,
default=None,
help="Per-stage JSON overrides. Example: "
'\'{"0": {"gpu_memory_utilization": 0.8}, "2": {"enforce_eager": true}}\'',
)
omni_config_group.add_argument(
"--async-chunk",
action=argparse.BooleanOptionalAction,
default=None,
help="Override the deploy YAML's ``async_chunk:`` bool. Unset leaves the YAML value in force.",
)
omni_config_group.add_argument(
"--stage-id",
@@ -406,6 +448,9 @@ class OmniServeCommand(CLISubcommand):
action="store_true",
help="Enable diffusion pipeline profiler to display stage durations.",
)
# Stash via type(self) so the docs hook (which execs this function in a
# sandboxed globals dict via ``DummySelf``) doesn't fail on a NameError.
type(self)._parser = serve_parser
return serve_parser
@@ -461,10 +506,15 @@ def run_headless(args: argparse.Namespace) -> None:
raise ValueError("headless mode requires worker_backend=multi_process")
args_dict = vars(args).copy()
# Preserve the explicit-keys set captured at parse time so per-stage yaml
# values (e.g. stage 1's ``gpu_memory_utilization: 0.5``) are not
# overwritten by argparse defaults for flags the user didn't type.
cli_explicit_keys = args_dict.pop("_cli_explicit_keys", None)
config_path, stage_configs = load_and_resolve_stage_configs(
model,
args_dict.get("stage_configs_path"),
args_dict,
cli_explicit_keys=cli_explicit_keys,
)
# Locate the stage config that matches stage_id.
+17 -1
View File
@@ -66,6 +66,13 @@ class Omni(OmniBase):
py_generator: bool = False,
use_tqdm: bool | Callable[..., tqdm] = True,
) -> Generator[OmniRequestOutput, None, None] | list[OmniRequestOutput]:
# Expand sampling params for PD disaggregation (user may provide N-1 params)
if (
sampling_params_list is not None
and isinstance(sampling_params_list, Sequence)
and not isinstance(sampling_params_list, (str, bytes))
):
sampling_params_list = self._maybe_expand_sampling_params(list(sampling_params_list))
sampling_params_list = self.resolve_sampling_params_list(sampling_params_list)
try:
if py_generator:
@@ -125,10 +132,17 @@ class Omni(OmniBase):
req_state.metrics = metrics
self.request_states[req_id] = req_state
# PD disaggregation: modify stage-0 (prefill) sampling params per request
req_sp_list = list(sampling_params_list)
pd_pair = self._get_pd_separation_pair()
if pd_pair is not None:
p_id = pd_pair[0]
req_sp_list[p_id] = self._prepare_prefill_sampling_params(req_id, req_sp_list[p_id])
self.engine.add_request(
request_id=req_id,
prompt=prompt,
sampling_params_list=sampling_params_list,
sampling_params_list=req_sp_list,
final_stage_id=final_stage_id,
)
submit_ts = time.time()
@@ -152,6 +166,8 @@ class Omni(OmniBase):
logger.warning("[Omni] Received output for unknown/finished request_id=%s", req_id)
continue
self._check_engine_output_error(msg, req_id, stage_id)
if req_state.metrics is None:
continue
output_to_yield = self._process_single_result(
+127 -7
View File
@@ -1,6 +1,8 @@
from __future__ import annotations
import argparse
import os
import sys
import time
import types
import weakref
@@ -10,11 +12,12 @@ from typing import TYPE_CHECKING, Any, Literal
import huggingface_hub
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.utils import get_final_stage_id_for_e2e
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import detect_explicit_cli_keys, get_final_stage_id_for_e2e
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.outputs import OmniRequestOutput
@@ -65,9 +68,51 @@ def omni_snapshot_download(model_id: str) -> str:
OutputMessageHandleResult = tuple[Literal[True], None, None, None] | tuple[Literal[False], str, int, ClientRequestState]
class OmniBase:
class OmniBase(PDDisaggregationMixin):
"""Shared runtime foundation for AsyncOmni and Omni."""
@classmethod
def from_cli_args(
cls,
args: argparse.Namespace,
*,
parser: argparse.ArgumentParser | None = None,
**overrides: Any,
) -> OmniBase:
"""Construct an ``Omni`` / ``AsyncOmni`` from an ``argparse.Namespace``.
Mirrors the ``EngineArgs.from_cli_args`` pattern used upstream and in
``OmniEngineArgs.from_cli_args``. This is the recommended entry point
for any argparse-based caller (offline scripts, tests, CI): it
expands ``vars(args)`` into kwargs and automatically captures which
flags the user typed on the command line so that argparse defaults
do not silently override deploy YAML values.
Passing ``parser`` is strongly recommended: without it, flag-to-dest
resolution falls back to a name-based heuristic that misidentifies
flags with ``dest=`` overrides, alias flags, and ``--disable-X`` /
``store_false`` pairs. See :func:`detect_explicit_cli_keys`.
Args:
args: Parsed argparse namespace from ``parser.parse_args()``.
parser: The argparse parser used to produce ``args``. When
provided, each user-typed flag is resolved to its real
``dest`` via the parser's action table.
**overrides: Extra keyword arguments that take precedence over
attributes on ``args``.
Example::
parser = FlexibleArgumentParser()
parser.add_argument("--model", required=True)
args = parser.parse_args()
omni = Omni.from_cli_args(args, parser=parser) # preferred
omni = Omni.from_cli_args(args, parser=parser, model="other")
"""
kwargs: dict[str, Any] = {**vars(args), **overrides}
kwargs["_cli_explicit_keys"] = detect_explicit_cli_keys(sys.argv[1:], parser)
return cls(**kwargs)
def __init__(
self,
model: str,
@@ -77,16 +122,24 @@ class OmniBase:
stage_init_timeout = kwargs.pop("stage_init_timeout", 300)
init_timeout = kwargs.pop("init_timeout", 600)
log_stats = kwargs.pop("log_stats", False)
async_chunk = kwargs.pop("async_chunk", False)
# NOTE: read-only lookup — must NOT pop. Popping here drops the key
# before it reaches ``StageConfigFactory._create_from_registry``, so
# ``--no-async-chunk`` (``async_chunk=False``) silently fails to
# override the deploy YAML's ``async_chunk: true`` default.
async_chunk = kwargs.get("async_chunk")
output_modalities = kwargs.pop("output_modalities", None)
diffusion_batch_size: int = kwargs.pop("diffusion_batch_size", 1)
if "log_requests" in kwargs:
raise TypeError("`log_requests` has been removed in Omni/AsyncOmni. Use `log_stats`.")
model = omni_snapshot_download(model)
self.__dict__["_name"] = self.__class__.__name__
self.model = model
self.log_stats = log_stats
self.async_chunk = async_chunk
# Provisional value (mirrors the CLI/caller kwarg); the engine resolves
# pipeline + deploy YAML + CLI precedence below and the final value is
# re-assigned from ``self.engine.async_chunk`` after init.
self.async_chunk = bool(async_chunk) if async_chunk is not None else False
self.output_modalities = output_modalities or []
self.tts_batch_max_items: int = kwargs.pop("tts_batch_max_items", 32)
@@ -104,7 +157,11 @@ class OmniBase:
self._weak_finalizer = weakref.finalize(self, _weak_shutdown_engine, self.engine)
et = time.time()
logger.info("[%s] AsyncOmniEngine initialized in %.2f seconds", self.__class__.__name__, et - st)
self.async_chunk = bool(self.async_chunk or getattr(self.engine, "async_chunk", False))
# Authoritative: ``AsyncOmniEngine`` resolves (pipeline + deploy YAML +
# CLI overrides) through ``StageConfigFactory`` and stores the final
# value on ``engine.async_chunk``; mirror it here so ``--no-async-chunk``
# (explicit ``False``) is not fallen-back-through by ``or``.
self.async_chunk = bool(getattr(self.engine, "async_chunk", False))
self.request_states: dict[str, ClientRequestState] = {}
@@ -125,17 +182,49 @@ class OmniBase:
model,
)
# PD disaggregation state (detects if a prefill/decode stage pair is configured)
self._init_pd_state()
@property
def num_stages(self) -> int:
return self.engine.num_stages
@property
def stage_configs(self) -> list:
"""Expose engine stage configs for PD disaggregation detection and validation."""
return self.engine.stage_configs
@property
def is_running(self) -> bool:
return self.engine.is_alive()
@property
def errored(self) -> bool:
"""Whether the engine is in a non-recoverable error state.
True when the orchestrator thread is dead **or** any stage client
has been marked dead (e.g. diffusion worker OOM / process death).
Checks both ``_engine_dead`` (StageDiffusionClient) and
``resources.engine_dead`` (StageEngineCoreClient / AsyncMPClient)
since the two client types store the flag differently.
"""
if not self.engine.is_alive():
return True
for stage_client in self.engine.stage_clients:
if getattr(stage_client, "_engine_dead", False):
return True
resources = getattr(stage_client, "resources", None)
if resources is not None and getattr(resources, "engine_dead", False):
return True
return False
def check_health(self) -> None:
if not self.engine.is_alive():
raise EngineDeadError("Orchestrator process is not alive")
for stage_client in self.engine.stage_clients:
if hasattr(stage_client, "check_health"):
stage_client.check_health()
def resolve_sampling_params_list(
self,
@@ -206,7 +295,10 @@ class OmniBase:
return True, None, None, None
if msg_type == "error":
raise RuntimeError(msg.get("error", "Orchestrator returned an error message"))
error_text = msg.get("error", "Orchestrator returned an error message")
if msg.get("fatal"):
raise EngineDeadError(error_text)
raise RuntimeError(error_text)
if msg_type != "output":
logger.warning("[%s] got unexpected msg type: %s", self.__class__.__name__, msg_type)
@@ -235,6 +327,34 @@ class OmniBase:
return False, req_id, stage_id, req_state
def _check_engine_output_error(
self,
result: dict[str, Any],
request_id: str,
stage_id: int,
) -> None:
"""Raise if ``engine_outputs`` carries an error field.
Raises :class:`EngineDeadError` when ``self.errored`` indicates the
engine is unrecoverable, otherwise raises :class:`EngineGenerateError`
(recoverable, single-request failure).
"""
engine_outputs = result.get("engine_outputs")
error_text = getattr(engine_outputs, "error", None)
if error_text is None:
return
logger.error(
"[%s] Stage error for req=%s stage-%s: %s",
self.__class__.__name__,
request_id,
stage_id,
error_text,
)
# NOTE: O(n_stages) check for every error.
if self.errored:
raise EngineDeadError(error_text)
raise EngineGenerateError(error_text)
def _process_single_result(
self,
result: dict[str, Any],
+424 -49
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import base64
import dataclasses
import io
import json
import multiprocessing
@@ -15,9 +16,11 @@ from argparse import Namespace
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from http import HTTPStatus
from numbers import Integral
from typing import Annotated, Any, Literal, cast
import httpx
import numpy as np
import vllm.envs as envs
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, WebSocket
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
@@ -29,7 +32,7 @@ from vllm import SamplingParams
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.anthropic.serving import AnthropicServingMessages
from vllm.entrypoints.chat_utils import load_chat_template
from vllm.entrypoints.launcher import serve_http
from vllm.entrypoints.launcher import serve_http, terminate_if_errored
from vllm.entrypoints.logger import RequestLogger
from vllm.entrypoints.mcp.tool_server import DemoToolServer, MCPToolServer, ToolServer
from vllm.entrypoints.openai.api_server import build_app as build_openai_app
@@ -48,11 +51,11 @@ from vllm.entrypoints.openai.engine.protocol import (
ModelCard,
ModelList,
ModelPermission,
RequestResponseMetadata,
)
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.openai.orca_metrics import metrics_header
from vllm.entrypoints.openai.realtime.connection import RealtimeConnection
from vllm.entrypoints.openai.realtime.serving import OpenAIServingRealtime
from vllm.entrypoints.openai.responses.serving import OpenAIServingResponses
from vllm.entrypoints.openai.server_utils import get_uvicorn_log_config
@@ -73,6 +76,7 @@ from vllm.entrypoints.serve.instrumentator.basic import base
from vllm.entrypoints.serve.render.serving import OpenAIServingRender
from vllm.entrypoints.serve.tokenize.serving import OpenAIServingTokenization
from vllm.entrypoints.utils import (
create_error_response,
load_aware_call,
process_lora_modules,
with_cancellation,
@@ -82,6 +86,7 @@ from vllm.tasks import POOLING_TASKS
from vllm.tool_parsers import ToolParserManager
from vllm.utils import random_uuid
from vllm.utils.system_utils import decorate_logs
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.errors import InvalidInputReferenceError
@@ -107,6 +112,7 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
VideoListResponse,
VideoResponse,
)
from vllm_omni.entrypoints.openai.realtime_connection import RealtimeConnection
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpeechHandler
@@ -120,6 +126,7 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParam
logger = init_logger(__name__)
router = APIRouter()
MAX_UINT32_SEED = 2**32 - 1
profiler_router = APIRouter()
@@ -196,6 +203,50 @@ def _remove_route_from_app(app, path: str, methods: set[str] | None = None):
app.routes.remove(route)
def _register_omni_exception_handlers(app) -> None:
"""Override upstream vLLM exception handlers with Omni-aware versions.
The upstream ``engine_error_handler`` is designed for ``AsyncLLM`` (single
EngineCore process). Omni uses a multi-stage orchestrator with different
health semantics, so we register our own handlers that:
- Log multi-stage diagnostic info (orchestrator liveness, per-stage health)
when an ``EngineDeadError`` is caught.
- Call ``terminate_if_errored``
- Return an OpenAI-compatible error JSON response.
"""
async def omni_engine_error_handler(
req: Request,
exc: EngineDeadError | EngineGenerateError,
):
request_id = req.state.request_metadata.request_id if hasattr(req.state, "request_metadata") else None
if req.app.state.args.log_error_stack:
logger.exception("Engine Exception caught. Request id: %s", request_id)
engine = req.app.state.engine_client
if isinstance(exc, EngineDeadError):
# Log Omni-specific diagnostic information for dead engines.
orchestrator_alive = engine.engine.is_alive() if hasattr(engine, "engine") else "N/A"
logger.error(
"EngineDeadError: orchestrator_alive=%s, errored=%s, request_id=%s",
orchestrator_alive,
engine.errored,
request_id,
)
terminate_if_errored(
server=req.app.state.server,
engine=engine,
)
err = create_error_response(exc)
return JSONResponse(err.model_dump(), status_code=err.error.code)
app.exception_handler(EngineGenerateError)(omni_engine_error_handler)
app.exception_handler(EngineDeadError)(omni_engine_error_handler)
class _DiffusionServingModels:
"""Minimal OpenAIServingModels implementation for diffusion-only servers.
@@ -305,6 +356,10 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
_remove_route_from_app(app, "/v1/models", {"GET"}) # Remove upstream /v1/models to use omni's handler
app.include_router(router)
# OMNI: Override upstream exception handlers with Omni-aware versions
# that understand the multi-stage orchestrator lifecycle.
_register_omni_exception_handlers(app)
await omni_init_app_state(engine_client, app.state, args)
# Conditionally register profiler endpoints based on stage YAML configs
@@ -835,6 +890,7 @@ async def omni_init_app_state(
state.enable_server_load_tracking = args.enable_server_load_tracking
state.server_load_metrics = 0
state.sleeping_stages = set()
def Omnivideo(request: Request) -> OmniOpenAIServingVideo | None:
@@ -874,6 +930,8 @@ async def create_chat_completion(request: ChatCompletionRequest, raw_request: Re
return base_server.create_error_response(message="The model does not support Chat Completions API")
try:
generator = await handler.create_chat_completion(request, raw_request)
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except Exception as e:
logger.exception("Chat completion failed: %s", e)
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
@@ -969,6 +1027,8 @@ async def create_speech(request: OpenAICreateSpeechRequest, raw_request: Request
status_code=result.error.code if result.error else 400,
)
return result
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except Exception as e:
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
@@ -1003,6 +1063,8 @@ async def create_speech_batch(request: BatchSpeechRequest, raw_request: Request)
status_code=result.error.code if result.error else 400,
)
return JSONResponse(content=result.model_dump())
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except ValueError as e:
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST.value, detail=str(e)) from e
except Exception as e:
@@ -1202,6 +1264,22 @@ async def streaming_speech(websocket: WebSocket):
@router.websocket("/v1/realtime")
async def realtime_websocket(websocket: WebSocket):
"""WebSocket endpoint for OpenAI-style realtime interactions."""
engine_client = getattr(websocket.app.state, "engine_client", None)
if engine_client is not None and getattr(engine_client, "async_chunk", False):
await websocket.accept()
await websocket.send_json(
{
"type": "error",
"error": (
"The /v1/realtime API is not supported when async_chunk is enabled on the server. "
"Use a stage configuration with async_chunk disabled and restart the server before using "
"this endpoint."
),
"code": "unsupported",
}
)
await websocket.close()
return
serving = getattr(websocket.app.state, "openai_serving_realtime", None)
if serving is None:
await websocket.accept()
@@ -1224,31 +1302,26 @@ _remove_route_from_router(router, "/health")
async def health(raw_request: Request) -> JSONResponse:
"""Health check endpoint that works for both LLM and diffusion modes.
Returns 200 OK if the server is healthy.
For LLM mode: delegates to engine_client health check
For diffusion mode: checks if diffusion_engine is running
Returns 200 OK if the server is healthy, 503 if the engine is dead.
Mirrors vLLM upstream's /health which catches EngineDeadError -> 503.
"""
# Check if we're in diffusion mode
diffusion_engine = getattr(raw_request.app.state, "diffusion_engine", None)
if diffusion_engine is not None:
# Diffusion mode health check
if hasattr(diffusion_engine, "is_running") and diffusion_engine.is_running:
return JSONResponse(content={"status": "healthy"})
engine_client = getattr(raw_request.app.state, "engine_client", None) or getattr(
raw_request.app.state, "diffusion_engine", None
)
if engine_client is None:
return JSONResponse(
content={"status": "unhealthy", "reason": "Diffusion engine is not running"},
content={"status": "unhealthy", "reason": "No engine initialized"},
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
)
# LLM mode - delegate to engine_client
engine_client = getattr(raw_request.app.state, "engine_client", None)
if engine_client is not None:
try:
await engine_client.check_health()
return JSONResponse(content={"status": "healthy"})
return JSONResponse(
content={"status": "unhealthy", "reason": "No engine initialized"},
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
)
except EngineDeadError:
return JSONResponse(
content={"status": "unhealthy"},
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
)
# Remove existing models endpoint if present (from vllm imports)
@@ -1303,14 +1376,64 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
# Get engine client (AsyncOmni) from app state
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
# Validate model field (warn if mismatch, don't error)
if request.model is not None and request.model != model_name:
logger.warning(
f"Model mismatch: request specifies '{request.model}' but "
f"server is running '{model_name}'. Using server model."
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail=(f"Model mismatch: request specifies '{request.model}' but server is running '{model_name}'."),
)
try:
# Unify request construction for any multi-stage pipeline to avoid
# divergence between /v1/images and /v1/chat/completions.
if len(stage_configs) > 1:
chat_handler = getattr(raw_request.app.state, "openai_serving_chat", None)
if chat_handler is None:
logger.warning("openai_serving_chat is not initialized for multi-stage /v1/images/generations")
raise HTTPException(
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
detail="openai_serving_chat is not initialized for multi-stage image generation.",
)
effective_seed = request.seed if request.seed is not None else random.randint(0, MAX_UINT32_SEED)
extra_body: dict[str, Any] = {
"seed": effective_seed,
"num_outputs_per_prompt": request.n,
}
if request.size is not None:
parse_size(request.size)
width, height = parse_size(request.size)
app_state_args = getattr(raw_request.app.state, "args", None)
_check_max_generated_image_size(app_state_args, width, height)
extra_body["size"] = request.size
if request.negative_prompt is not None:
extra_body["negative_prompt"] = request.negative_prompt
if request.num_inference_steps is not None:
extra_body["num_inference_steps"] = request.num_inference_steps
if request.guidance_scale is not None:
extra_body["guidance_scale"] = request.guidance_scale
if request.true_cfg_scale is not None:
extra_body["true_cfg_scale"] = request.true_cfg_scale
if request.generator_device is not None:
extra_body["generator_device"] = request.generator_device
if request.lora is not None:
# Keep /images validation semantics: invalid LoRA should fail with 400.
_parse_lora_request(request.lora)
extra_body["lora"] = request.lora
generation_result = await chat_handler.generate_diffusion_images(
prompt=request.prompt,
extra_body=extra_body,
request_id=f"img_gen-{random_uuid()}",
)
if isinstance(generation_result, ErrorResponse):
return JSONResponse(
status_code=generation_result.error.code if generation_result.error else 400,
content=generation_result.model_dump(),
)
flat_images, _, _ = generation_result
image_data = [ImageData(b64_json=encode_image_base64(img), revised_prompt=None) for img in flat_images]
return ImageGenerationResponse(created=int(time.time()), data=image_data)
# Build params - pass through user values directly
prompt: OmniTextPrompt = {"prompt": request.prompt}
if request.negative_prompt is not None:
@@ -1336,6 +1459,16 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
else:
size_str = "model default"
# Keep AR stage target grid in sync with requested output size.
# GLM-Image consumes target_h/target_w via mm_processor_kwargs.
if width is not None and height is not None:
prompt["mm_processor_kwargs"] = {
"target_h": height,
"target_w": width,
}
# Backward-compatible fallback for processors reading top-level fields.
prompt["height"] = height
prompt["width"] = width
app_state_args = getattr(raw_request.app.state, "args", None)
_check_max_generated_image_size(app_state_args, width, height)
@@ -1351,12 +1484,13 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
# This fixes issues where using the default global generator
# might produce blurry images in some environments.
_update_if_not_none(
gen_params, "seed", request.seed if request.seed is not None else random.randint(0, 2**32 - 1)
gen_params, "seed", request.seed if request.seed is not None else random.randint(0, MAX_UINT32_SEED)
)
_update_if_not_none(gen_params, "generator_device", request.generator_device)
_update_if_not_none(gen_params, "layers", request.layers)
request_id = f"img_gen-{random_uuid()}"
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
logger.info(f"Generating {request.n} image(s) {size_str}")
@@ -1388,8 +1522,9 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
data=image_data,
)
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except HTTPException:
# Re-raise HTTPExceptions as-is
raise
except ValueError as e:
logger.error(f"Validation error: {e}")
@@ -1425,6 +1560,9 @@ async def edit_images(
background: str | None = Form("auto"),
output_compression: Annotated[int, Form(ge=0, le=100)] = 100,
user: str | None = Form(None), # unused now
# vllm-omni extensions for image editing
mask_image: str | UploadFile | None = None,
reference_image: str | UploadFile | None = None,
# vllm-omni extensions for diffusion control
negative_prompt: str | None = Form(None),
num_inference_steps: int | None = Form(None),
@@ -1445,8 +1583,9 @@ async def edit_images(
# 1. get engine and model
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
if model is not None and model != model_name:
logger.warning(
f"Model mismatch: request specifies '{model}' but server is running '{model_name}'. Using server model."
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail=(f"Model mismatch: request specifies '{model}' but server is running '{model_name}'."),
)
# 2. get output format & compression
output_format = _choose_output_format(output_format, background)
@@ -1469,15 +1608,35 @@ async def edit_images(
input_images_list.extend(urls)
if not input_images_list:
raise HTTPException(status_code=422, detail="Field 'image' or 'url' is required")
pil_images = await _load_input_images(input_images_list)
if len(pil_images) > 1 and not _supports_multimodal_image_inputs(raw_request, engine_client):
# Reject oversized multi-image edit requests before fetching or decoding
# any inputs. This keeps over-limit URL requests from burning network,
# CPU, and memory on work that will be rejected anyway.
max_input_images = _get_max_edit_input_images(raw_request, engine_client)
if max_input_images is not None and len(input_images_list) > max_input_images:
detail = (
"Received multiple input images. Only a single image is supported by this model."
if max_input_images == 1
else (
f"Received {len(input_images_list)} input images. "
f"At most {max_input_images} images are supported by this model."
)
)
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail="Received multiple input images. Only a single image is supported by this model.",
detail=detail,
)
pil_images = await _load_input_images(input_images_list)
prompt["multi_modal_data"] = {}
prompt["multi_modal_data"]["image"] = pil_images
if mask_image is not None:
loaded = await _load_input_images([mask_image])
prompt["multi_modal_data"]["mask_image"] = loaded[0]
if reference_image is not None:
loaded = await _load_input_images([reference_image])
prompt["multi_modal_data"]["reference_image"] = loaded[0]
# 3 Build sample params
gen_params = OmniDiffusionSamplingParams()
# 3.0 Init with system default values
@@ -1537,6 +1696,18 @@ async def edit_images(
_check_max_generated_image_size(app_state_args, width, height, resolution)
size_str = f"{width}x{height}" if width is not None and height is not None else "auto"
# Keep AR stage target grid in sync with requested output size.
# GLM-Image consumes target_h/target_w via mm_processor_kwargs.
if width is not None and height is not None:
prompt["mm_processor_kwargs"] = {
"target_h": height,
"target_w": width,
}
# Backward-compatible fallback for processors reading top-level fields.
prompt["height"] = height
prompt["width"] = width
_update_if_not_none(gen_params, "width", width)
_update_if_not_none(gen_params, "height", height)
@@ -1549,13 +1720,14 @@ async def edit_images(
# a proper generator is initialized in the backend.
# This fixes issues where using the default global generator
# might produce blurry images in some environments.
_update_if_not_none(gen_params, "seed", seed if seed is not None else random.randint(0, 2**32 - 1))
_update_if_not_none(gen_params, "seed", seed if seed is not None else random.randint(0, MAX_UINT32_SEED))
_update_if_not_none(gen_params, "generator_device", generator_device)
_update_if_not_none(gen_params, "layers", layers)
_update_if_not_none(gen_params, "resolution", resolution)
# 4. Generate images using AsyncOmni (multi-stage mode)
request_id = f"img_edit-{random_uuid()}"
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
logger.info(f"Generating {n} image(s) {size_str}")
result = await _generate_with_async_omni(
engine_client=engine_client,
@@ -1587,8 +1759,9 @@ async def edit_images(
size=size_str,
)
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except HTTPException:
# Re-raise HTTPExceptions as-is
raise
except ValueError as e:
logger.error(f"Validation error: {e}")
@@ -1639,18 +1812,39 @@ def _get_engine_and_model(raw_request: Request):
return engine_client, model_name, normalized_stage_configs
def _supports_multimodal_image_inputs(raw_request: Request, engine_client: Any) -> bool:
def _get_diffusion_od_config(raw_request: Request, engine_client: Any) -> Any:
diffusion_engine = getattr(raw_request.app.state, "diffusion_engine", None) or engine_client
get_diffusion_od_config = getattr(diffusion_engine, "get_diffusion_od_config", None)
od_config = (
return (
get_diffusion_od_config() if callable(get_diffusion_od_config) else getattr(diffusion_engine, "od_config", None)
)
def _get_max_edit_input_images(raw_request: Request, engine_client: Any) -> int | None:
od_config = _get_diffusion_od_config(raw_request, engine_client)
if od_config is None:
# Preserve the existing compatibility behavior when the diffusion
# config is not exposed on the serving surface.
return True
return bool(getattr(od_config, "supports_multimodal_inputs", False))
return None
supports_multimodal_inputs = getattr(od_config, "supports_multimodal_inputs", None)
if not isinstance(supports_multimodal_inputs, bool):
# Older serving surfaces and mocked engines may expose a placeholder
# object instead of a real diffusion config. Treat that as "unknown"
# so existing single-image flows keep working.
return None
if not supports_multimodal_inputs:
return 1
max_input_images = getattr(od_config, "max_multimodal_image_inputs", None)
if max_input_images is None:
return None
if isinstance(max_input_images, bool) or not isinstance(max_input_images, Integral):
return None
if max_input_images < 1:
return None
return int(max_input_images)
def _get_lora_from_json_str(lora_body):
@@ -1767,6 +1961,34 @@ def _update_if_not_none(object: Any, key: str, val: Any) -> None:
setattr(object, key, val)
def _normalize_image(image: Any) -> Any:
"""Normalize a single image output to a PIL-compatible format."""
if isinstance(image, Image.Image):
return image
if not isinstance(image, np.ndarray):
raise ValueError(f"Unsupported image type: {type(image)}")
if not np.issubdtype(image.dtype, np.integer) and not np.issubdtype(image.dtype, np.floating):
raise ValueError(f"Unsupported dtype: {image.dtype}")
if isinstance(image, np.ndarray):
while image.ndim > 3:
image = image[0]
if image.min() < 0:
if image.min() < -1.01 or image.max() > 1.01:
logger.warning(
f"Image float range [{image.min():.2f}, {image.max():.2f}] outside expected [-1, 1]. "
f"Clipping to [-1, 1] before normalization."
)
image = np.clip(image, -1.0, 1.0) * 0.5 + 0.5
elif image.max() > 1.01:
logger.warning(
f"Image float range [{image.min():.2f}, {image.max():.2f}] outside expected [0, 1]. "
f"Clipping to [0, 1] before normalization."
)
image = (np.clip(image, 0.0, 1.0) * 255).astype(np.uint8)
image = Image.fromarray(image)
return image
def _extract_images_from_result(result: Any) -> list[Any]:
images = []
if hasattr(result, "images") and result.images:
@@ -1777,6 +1999,10 @@ def _extract_images_from_result(result: Any) -> list[Any]:
images = request_output["images"]
elif hasattr(request_output, "images") and request_output.images:
images = request_output.images
# Handle when generate more than one image
if images and isinstance(images[0], np.ndarray) and images[0].shape[0] > 1 and images[0].ndim == 5:
# Unwrap batch: (N, T, H, W, C) -> [img1, img2, ...]
images = list(images[0])
# Flatten nested lists (e.g., from layered models like Qwen-Image-Layered).
# Note: This only flattens one level deep. Deeper nesting is not supported.
flattened = []
@@ -1785,7 +2011,7 @@ def _extract_images_from_result(result: Any) -> list[Any]:
flattened.extend(img)
else:
flattened.append(img)
return flattened
return [_normalize_image(img) for img in flattened]
async def _load_input_images(
@@ -1955,6 +2181,48 @@ def video_response_from_request(model_name: str, req: VideoGenerationRequest) ->
return resp
def _status_code_for_video_failure(error: VideoError | None) -> int:
if error is None:
return HTTPStatus.INTERNAL_SERVER_ERROR.value
if isinstance(error.code, int):
if 400 <= error.code < 600:
return error.code
return HTTPStatus.INTERNAL_SERVER_ERROR.value
if error.code == "HTTPException":
status_text, _, _ = error.message.partition(":")
try:
status_code = int(status_text)
except ValueError:
return HTTPStatus.INTERNAL_SERVER_ERROR.value
if 400 <= status_code < 600:
return status_code
return HTTPStatus.INTERNAL_SERVER_ERROR.value
if error.code == "EngineDeadError":
return HTTPStatus.INTERNAL_SERVER_ERROR.value
if error.code == "EngineGenerateError":
return HTTPStatus.INTERNAL_SERVER_ERROR.value
return HTTPStatus.INTERNAL_SERVER_ERROR.value
def _video_error_from_exception(exc: Exception) -> VideoError:
if isinstance(exc, HTTPException):
message = str(exc.detail) if exc.detail else str(exc)
return VideoError(code=exc.status_code, message=message)
if isinstance(exc, (EngineGenerateError, EngineDeadError)):
err = create_error_response(exc)
return VideoError(code=err.error.code, message=err.error.message)
return VideoError(
code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
message=str(exc),
)
def _cleanup_video(video_id: str, output_path: str | None):
try:
if output_path is not None:
@@ -1968,6 +2236,7 @@ async def _run_video_generation_job(
request: VideoGenerationRequest,
video_id: str,
reference_image: ReferenceImage | None = None,
app_state: Any | None = None,
) -> None:
job = await VIDEO_STORE.get(video_id)
if job is None:
@@ -1998,17 +2267,36 @@ async def _run_video_generation_job(
"peak_memory_mb": peak_memory_mb,
},
)
except Exception as exc:
logger.exception("Video generation failed for id=%s", video_id)
except (EngineGenerateError, EngineDeadError) as exc:
logger.exception("Video generation failed (engine error) for id=%s", video_id)
_cleanup_video(video_id, output_path)
# TODO: It would be better to have a finite collection of errors to return rather than the exception name
await VIDEO_STORE.update_fields(
video_id,
{
"status": VideoGenerationStatus.FAILED,
"completed_at": int(time.time()),
"error": VideoError(code=type(exc).__name__, message=str(exc)),
"error": _video_error_from_exception(exc),
"inference_time_s": time.perf_counter() - started_at,
},
)
# Background tasks can't propagate exceptions to FastAPI handlers.
# Actively signal shutdown when the engine is dead.
if app_state is not None and isinstance(exc, EngineDeadError):
terminate_if_errored(
server=app_state.server,
engine=app_state.engine_client,
)
except Exception as exc:
logger.exception("Video generation failed for id=%s", video_id)
_cleanup_video(video_id, output_path)
await VIDEO_STORE.update_fields(
video_id,
{
"status": VideoGenerationStatus.FAILED,
"completed_at": int(time.time()),
"error": _video_error_from_exception(exc),
"inference_time_s": time.perf_counter() - started_at,
},
)
@@ -2042,6 +2330,10 @@ async def _parse_video_form(
true_cfg_scale: float | None = Form(default=None),
seed: int | None = Form(default=None),
negative_prompt: str | None = Form(default=None),
enable_frame_interpolation: bool = Form(default=False),
frame_interpolation_exp: int = Form(default=1, ge=1),
frame_interpolation_scale: float = Form(default=1.0, gt=0.0),
frame_interpolation_model_path: str | None = Form(default=None),
lora: str | None = Form(default=None),
extra_params: str | None = Form(default=None),
) -> tuple[VideoGenerationRequest, "OmniOpenAIServingVideo", str, ReferenceImage | None]:
@@ -2078,6 +2370,10 @@ async def _parse_video_form(
"true_cfg_scale": true_cfg_scale,
"seed": seed,
"negative_prompt": negative_prompt,
"enable_frame_interpolation": enable_frame_interpolation,
"frame_interpolation_exp": frame_interpolation_exp,
"frame_interpolation_scale": frame_interpolation_scale,
"frame_interpolation_model_path": frame_interpolation_model_path,
"lora": _parse_form_json(lora, expected_type=dict),
"extra_params": _parse_form_json(extra_params, expected_type=dict),
}
@@ -2095,10 +2391,12 @@ async def _parse_video_form(
app_model_name, app_stage_configs = _resolve_video_runtime_context(raw_request)
effective_model_name = handler.model_name or app_model_name or request.model or "unknown"
if request.model is not None and effective_model_name is not None and request.model != effective_model_name:
logger.warning(
"Model mismatch: request specifies '%s' but server is running '%s'. Using server model.",
request.model,
effective_model_name,
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail=(
f"Model mismatch: request specifies '{request.model}' but server is running "
f"'{effective_model_name}'."
),
)
handler.set_stage_configs_if_missing(app_stage_configs)
except HTTPException:
@@ -2129,6 +2427,7 @@ async def _parse_video_form(
},
)
async def create_video(
raw_request: Request,
ctx: tuple[VideoGenerationRequest, OmniOpenAIServingVideo, str, ReferenceImage | None] = Depends(_parse_video_form),
) -> VideoResponse:
"""Create an asynchronous video generation job.
@@ -2139,7 +2438,9 @@ async def create_video(
request, handler, effective_model_name, reference_image = ctx
ref = video_response_from_request(effective_model_name, request)
await VIDEO_STORE.upsert(ref.id, ref)
task = asyncio.create_task(_run_video_generation_job(handler, request, ref.id, reference_image))
task = asyncio.create_task(
_run_video_generation_job(handler, request, ref.id, reference_image, app_state=raw_request.app.state)
)
await VIDEO_TASKS.upsert(ref.id, task)
return ref
@@ -2154,6 +2455,7 @@ async def create_video(
},
)
async def create_video_sync(
raw_request: Request,
ctx: tuple[VideoGenerationRequest, OmniOpenAIServingVideo, str, ReferenceImage | None] = Depends(_parse_video_form),
) -> Response:
"""Synchronous video generation endpoint.
@@ -2167,6 +2469,7 @@ async def create_video_sync(
"""
request, handler, effective_model_name, reference_image = ctx
request_id = f"video_sync-{random_uuid()}"
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
started_at = time.perf_counter()
try:
video_bytes, stage_durations, peak_memory_mb = await asyncio.wait_for(
@@ -2178,6 +2481,8 @@ async def create_video_sync(
status_code=HTTPStatus.GATEWAY_TIMEOUT.value,
detail=f"Video generation timed out after {VIDEO_SYNC_TIMEOUT_S}s.",
)
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except HTTPException:
raise
except Exception as exc:
@@ -2238,8 +2543,8 @@ async def list_videos(
return VideoListResponse(data=jobs, has_more=has_more, first_id=first_id, last_id=last_id)
@router.get("/v1/videos/{video_id}")
async def retrieve_video(video_id: str) -> VideoResponse:
@router.get("/v1/videos/{video_id}", response_model=None)
async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
"""Retrieve metadata for a previously created video job.
Args:
@@ -2254,6 +2559,15 @@ async def retrieve_video(video_id: str) -> VideoResponse:
job = await VIDEO_STORE.get(video_id)
if job is None:
raise HTTPException(status_code=404, detail="Video not found")
if job.status == VideoGenerationStatus.FAILED:
status_code = _status_code_for_video_failure(job.error)
content = job.model_dump(mode="json")
if content.get("error") is not None:
content["error"]["code"] = status_code
return JSONResponse(
content=content,
status_code=status_code,
)
return job
@@ -2390,3 +2704,64 @@ async def stop_profile(raw_request: Request, request: ProfileRequest | None = No
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to stop profiler: {str(e)}"
)
class OmniSleepRequest(BaseModel):
stage_ids: list[int]
level: int = 2
class OmniWakeupRequest(BaseModel):
stage_ids: list[int]
@router.post("/v1/omni/sleep")
async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
engine_client = raw_request.app.state.engine_client
sleeping_set = raw_request.app.state.sleeping_stages
if not hasattr(engine_client, "sleep"):
raise HTTPException(status_code=501, detail="Engine does not support sleep")
acks = await engine_client.sleep(stage_ids=request.stage_ids, level=request.level)
for sid in request.stage_ids:
sleeping_set.add(sid)
return {"status": "SUCCESS", "acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) else a for a in acks]}
@router.post("/v1/omni/wakeup")
async def omni_wakeup(request: OmniWakeupRequest, raw_request: Request):
engine_client = raw_request.app.state.engine_client
sleeping_set = raw_request.app.state.sleeping_stages
if not any(sid in sleeping_set for sid in request.stage_ids):
return {"status": "SKIPPED", "reason": "Target stages are not sleeping."}
if not hasattr(engine_client, "wake_up"):
raise HTTPException(status_code=501, detail="Engine does not support wake_up")
acks = await engine_client.wake_up(stage_ids=request.stage_ids)
for sid in request.stage_ids:
if sid in sleeping_set:
sleeping_set.remove(sid)
return {"status": "SUCCESS", "acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) else a for a in acks]}
if __name__ == "__main__":
import argparse
import asyncio
from vllm.entrypoints.openai.cli_args import make_arg_parser
parser = argparse.ArgumentParser(description="vLLM-Omni OpenAI-Compatible REST API server")
parser = make_arg_parser(parser)
registered_flags = set()
for action in parser._actions:
registered_flags.update(action.option_strings)
if "--omni" not in registered_flags:
parser.add_argument("--omni", action="store_true", default=False, help="Enable vLLM-Omni mode.")
if "--enable-sleep-mode" not in registered_flags:
parser.add_argument(
"--enable-sleep-mode", action="store_true", default=False, help="Enable GPU memory pool for sleep mode."
)
args = parser.parse_args()
if not hasattr(args, "model_tag"):
setattr(args, "model_tag", args.model)
if hasattr(args, "model_tag") and args.model_tag is None:
args.model_tag = args.model
asyncio.run(omni_run_server(args))
@@ -150,6 +150,29 @@ class VideoGenerationRequest(BaseModel):
)
seed: int | None = Field(default=None, description="Random seed for reproducibility")
# vllm-omni extensions for post-generation frame interpolation.
enable_frame_interpolation: bool = Field(
default=False,
description="Enable post-generation RIFE frame interpolation before MP4 encoding.",
)
frame_interpolation_exp: int = Field(
default=1,
ge=1,
description="Interpolation exponent: 1=2x temporal resolution, 2=4x, etc.",
)
frame_interpolation_scale: float = Field(
default=1.0,
gt=0.0,
description="RIFE inference scale. Use 0.5 for high-resolution inputs to save memory.",
)
frame_interpolation_model_path: str | None = Field(
default=None,
description=(
"Local directory or Hugging Face repo ID containing RIFE flownet.pkl weights. "
"Defaults to elfgum/RIFE-4.22.lite."
),
)
# vllm-omni extension for per-request LoRA.
lora: dict[str, Any] | None = Field(
default=None,
@@ -212,7 +235,7 @@ class VideoGenerationResponse(BaseModel):
class VideoError(BaseModel):
code: str = Field(..., description="A machine-readable error code that was returned.")
code: int | str = Field(..., description="A machine-readable error code that was returned.")
message: str = Field(..., description="A human-readable description of the error that was returned.")
@@ -0,0 +1,193 @@
from __future__ import annotations
import asyncio
import base64
import json
from collections.abc import AsyncGenerator
from uuid import uuid4
import numpy as np
from vllm.entrypoints.openai.engine.protocol import UsageInfo
from vllm.entrypoints.openai.realtime.connection import RealtimeConnection as VllmRealtimeConnection
from vllm.entrypoints.openai.realtime.protocol import TranscriptionDelta, TranscriptionDone
from vllm.logger import init_logger
logger = init_logger(__name__)
class RealtimeConnection(VllmRealtimeConnection):
"""Omni realtime connection with audio-only server events.
Reuses upstream vLLM websocket/session lifecycle and only customizes
generation output handling to emit audio deltas.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Last audio buffer seen for this realtime generation (cumulative or concatenation
# of increments); used to turn server cumulative PCM into true deltas.
self._realtime_audio_ref: np.ndarray | None = None
async def start_generation(self):
await super().start_generation()
@staticmethod
def _tensor_to_numpy(value) -> np.ndarray | None:
if value is None:
return None
if isinstance(value, np.ndarray):
arr = value
elif hasattr(value, "detach"):
arr = value.detach().float().cpu().numpy()
else:
try:
arr = np.asarray(value)
except Exception:
return None
if arr.ndim > 1:
arr = arr.reshape(-1)
return arr.astype(np.float32, copy=False)
@staticmethod
def _numpy_audio_prefix_match(prev: np.ndarray, curr: np.ndarray) -> bool:
n = prev.shape[0]
if n == 0:
return True
if curr.shape[0] < n:
return False
return bool(np.allclose(curr[:n], prev, rtol=1e-3, atol=2e-4))
def _raw_waveform_to_deltas(self, arr: np.ndarray) -> list[np.ndarray]:
"""Convert one streaming PCM f32 chunk into incremental piece(s) for the client.
Some engine paths emit a growing cumulative waveform each step; others emit
true per-step deltas. We support both without duplicating audio on the client.
"""
if arr.size == 0:
return []
ref = self._realtime_audio_ref
if ref is None:
self._realtime_audio_ref = arr.copy()
return [arr]
if self._numpy_audio_prefix_match(ref, arr):
delta = arr[ref.shape[0] :]
self._realtime_audio_ref = arr.copy()
return [delta] if delta.size > 0 else []
# True per-step delta (not a prefix extension of what we have seen).
self._realtime_audio_ref = np.concatenate([ref, arr])
return [arr]
def _extract_audio_chunks(self, output) -> tuple[list[np.ndarray], int]:
mm = getattr(output, "multimodal_output", None)
if not isinstance(mm, dict):
return [], 24000
sr = mm.get("sr") or mm.get("sample_rate") or mm.get("audio_sample_rate") or 24000
key = "audio" if "audio" in mm else ("model_outputs" if "model_outputs" in mm else None)
if key is None:
return [], int(sr)
raw_audio = mm.get(key)
chunks: list[np.ndarray] = []
if isinstance(raw_audio, (list, tuple)):
if len(raw_audio) > 0:
arr = self._tensor_to_numpy(raw_audio[-1])
if arr is not None and arr.size > 0:
chunks.extend(self._raw_waveform_to_deltas(arr))
else:
arr = self._tensor_to_numpy(raw_audio)
if arr is not None and arr.size > 0:
chunks.extend(self._raw_waveform_to_deltas(arr))
return chunks, int(sr)
@staticmethod
def _pcm16_b64(audio_f32: np.ndarray) -> str:
clipped = np.clip(audio_f32, -1.0, 1.0)
pcm16 = (clipped * 32767.0).astype(np.int16)
return base64.b64encode(pcm16.tobytes()).decode("utf-8")
async def _run_generation(
self,
streaming_input_gen: AsyncGenerator,
input_stream: asyncio.Queue[list[int]],
):
request_id = f"rt-{self.connection_id}-{uuid4()}"
sent_audio = False
audio_done_sent = False
full_text = ""
sent_text_len = 0
prompt_token_ids_len = 0
completion_tokens_len = 0
self._realtime_audio_ref = None
try:
result_gen = self.serving.engine_client.generate(
prompt=streaming_input_gen,
request_id=request_id,
)
async for output in result_gen:
if output.outputs and len(output.outputs) > 0:
output0 = output.outputs[0]
token_ids = list(output0.token_ids)
if token_ids:
input_stream.put_nowait(token_ids)
# token_ids are cumulative per request
completion_tokens_len = len(token_ids)
if not prompt_token_ids_len and output.prompt_token_ids:
prompt_token_ids_len = len(output.prompt_token_ids)
cumulative_text = output0.text or ""
if cumulative_text:
if len(cumulative_text) >= sent_text_len:
delta_text = cumulative_text[sent_text_len:]
else:
delta_text = cumulative_text
sent_text_len = len(cumulative_text)
full_text = cumulative_text
else:
delta_text = ""
if delta_text:
await self.send(TranscriptionDelta(delta=delta_text))
audio_chunks, sample_rate = self._extract_audio_chunks(output)
for chunk in audio_chunks:
sent_audio = True
await self.send_json(
{
"type": "response.audio.delta",
"audio": self._pcm16_b64(chunk),
"format": "pcm16",
"sample_rate_hz": sample_rate,
}
)
if not self._is_connected:
break
usage = UsageInfo(
prompt_tokens=prompt_token_ids_len,
completion_tokens=completion_tokens_len,
total_tokens=prompt_token_ids_len + completion_tokens_len,
)
await self.send(TranscriptionDone(text=full_text, usage=usage))
if sent_audio:
await self.send_json({"type": "response.audio.done", "has_audio": True})
audio_done_sent = True
except Exception as e:
logger.exception("Error in generation: %s", e)
await self.send_error(str(e), "processing_error")
finally:
# Always send terminal event so clients don't hang forever.
if self._is_connected and not audio_done_sent:
try:
await self.send_json({"type": "response.audio.done", "has_audio": sent_audio})
except Exception:
logger.exception("Failed to send response.audio.done")
while not self.audio_queue.empty():
self.audio_queue.get_nowait()
async def send_json(self, payload: dict):
await self.websocket.send_text(json.dumps(payload))
+426 -52
View File
@@ -32,6 +32,7 @@ from vllm.entrypoints.chat_utils import (
get_history_tool_calls_cnt,
make_tool_call_id,
)
from vllm.entrypoints.launcher import terminate_if_errored
from vllm.entrypoints.openai.chat_completion.protocol import (
ChatCompletionNamedToolChoiceParam,
ChatCompletionRequest,
@@ -80,12 +81,14 @@ from vllm.tokenizers.mistral import (
from vllm.tool_parsers import ToolParser
from vllm.tool_parsers.mistral_tool_parser import MistralToolCall
from vllm.utils.collection_utils import as_list
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.image_api_utils import validate_layered_layers
from vllm_omni.entrypoints.openai.protocol import OmniChatCompletionStreamResponse
from vllm_omni.entrypoints.openai.protocol.audio import AudioResponse, CreateAudio
from vllm_omni.entrypoints.openai.utils import (
get_stage_type,
get_supported_speakers_from_hf_config,
parse_lora_request,
validate_requested_speaker,
@@ -294,6 +297,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
)
num_inference_steps = None
cfg_text_scale = None
cfg_img_scale = None
# Omni multistage image generation: Stage-0 (AR) should receive a clean
# text prompt (and optional conditioning image/size) so the model's own
# processor can construct the correct inputs.
@@ -301,20 +306,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
# effectively unconditioned and produce nonsense images.
if request.modalities and ("image" in request.modalities):
try:
messages_as_dicts: list[dict[str, Any]] = []
for msg in request.messages:
if hasattr(msg, "model_dump"):
messages_as_dicts.append(msg.model_dump())
elif isinstance(msg, dict):
messages_as_dicts.append(msg)
else:
messages_as_dicts.append(
{
"role": getattr(msg, "role", "user"),
"content": getattr(msg, "content", ""),
}
)
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images(messages_as_dicts)
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images_from_messages(
request.messages
)
if not extracted_prompt:
return self.create_error_response("No text prompt found in messages")
@@ -325,39 +319,33 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
extra_body = getattr(request, "extra_body", None)
if not extra_body:
extra_body = request.model_extra or {}
height = extra_body.get("height")
width = extra_body.get("width")
height, width = self._resolve_height_width_from_extra_body(extra_body)
num_inference_steps = extra_body.get("num_inference_steps")
if num_inference_steps is not None:
try:
num_inference_steps = int(num_inference_steps)
except Exception:
num_inference_steps = None
if "size" in extra_body:
try:
size_str = extra_body["size"]
if isinstance(size_str, str) and "x" in size_str.lower():
w, h = size_str.lower().split("x")
width, height = int(w), int(h)
except Exception:
pass
negative_prompt = extra_body.get("negative_prompt")
cfg_text_scale = extra_body.get("cfg_text_scale")
cfg_img_scale = extra_body.get("cfg_img_scale")
engine_prompt_image: dict[str, Any] | None = None
is_img2img = False
if reference_images:
# Best-effort decode first reference image for i2i.
try:
img_bytes = base64.b64decode(reference_images[0])
img = Image.open(BytesIO(img_bytes))
engine_prompt_image = {"img2img": img}
is_img2img = True
except Exception:
engine_prompt_image = None
# Override the prompts produced by chat-template preprocessing.
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
if is_img2img:
if engine_prompt_image:
tprompt["modalities"] = ["img2img"]
else:
tprompt["modalities"] = ["image"]
@@ -373,6 +361,13 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
tprompt["mm_processor_kwargs"] = mm_processor_kwargs
if engine_prompt_image is not None:
tprompt["multi_modal_data"] = engine_prompt_image
# Provide multi_modal_uuids so that newer vLLM versions
# can validate multi_modal_data / multi_modal_uuids
# consistency. After the multimodal processor consumes
# the image data, the uuids remain as a stable reference.
tprompt["multi_modal_uuids"] = {
k: [f"{request_id}-{k}-{i}"] for i, k in enumerate(engine_prompt_image)
}
engine_prompts = [tprompt]
# Store height/width for applying to diffusion stage sampling params later
@@ -397,14 +392,18 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
sampling_params_list = self._build_sampling_params_list_from_request(request)
# Apply user-specified overrides to diffusion stage(s) for image generation
if _image_gen_height is not None or _image_gen_width is not None or num_inference_steps is not None:
for idx, sp in enumerate(sampling_params_list):
if hasattr(sp, "height") and _image_gen_height is not None:
sp.height = _image_gen_height
if hasattr(sp, "width") and _image_gen_width is not None:
sp.width = _image_gen_width
if hasattr(sp, "num_inference_steps") and num_inference_steps is not None:
sp.num_inference_steps = num_inference_steps
for idx, sp in enumerate(sampling_params_list):
if hasattr(sp, "height") and _image_gen_height is not None:
sp.height = _image_gen_height
if hasattr(sp, "width") and _image_gen_width is not None:
sp.width = _image_gen_width
if hasattr(sp, "num_inference_steps") and num_inference_steps is not None:
sp.num_inference_steps = num_inference_steps
if hasattr(sp, "extra_args") and sp.extra_args is not None:
if cfg_text_scale is not None:
sp.extra_args["cfg_text_scale"] = cfg_text_scale
if cfg_img_scale is not None:
sp.extra_args["cfg_img_scale"] = cfg_img_scale
self._log_inputs(
request_id,
@@ -438,6 +437,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
tokenizer,
request_metadata,
reasoning_parser,
raw_request=raw_request,
)
try:
@@ -535,20 +535,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
# containing image tokens.
req_modalities = getattr(request, "modalities", [])
if req_modalities and ("image" in req_modalities):
messages_as_dicts: list[dict[str, Any]] = []
for msg in messages:
if hasattr(msg, "model_dump"):
messages_as_dicts.append(msg.model_dump())
elif isinstance(msg, dict):
messages_as_dicts.append(msg)
else:
messages_as_dicts.append(
{
"role": getattr(msg, "role", "user"),
"content": getattr(msg, "content", ""),
}
)
extracted_prompt, _ = self._extract_diffusion_prompt_and_images(messages_as_dicts)
extracted_prompt, _ = self._extract_diffusion_prompt_and_images_from_messages(messages)
if extracted_prompt:
engine_prompt["prompt"] = extracted_prompt
@@ -708,6 +695,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
Starts with YAML defaults and only overrides fields that the user
explicitly provided (non-None values) in the request.
For GLM-Image AR stage, if max_tokens is not in YAML and user provides
height/width in extra_body, computes max_tokens dynamically.
Args:
default_params: Default SamplingParams from stage config YAML.
request: The chat completion request containing user-provided values.
@@ -717,13 +707,64 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
"""
params = default_params.clone()
# Only apply fields explicitly provided by user, not protocol defaults.
# Pydantic v2 uses `model_fields_set`; keep v1 fallback for compatibility.
explicit_fields = getattr(request, "model_fields_set", None)
if explicit_fields is None:
explicit_fields = getattr(request, "__fields_set__", set())
for field_name in self._OPENAI_SAMPLING_FIELDS:
if field_name not in explicit_fields:
continue
value = getattr(request, field_name, None)
if value is not None:
if (value is not None and not isinstance(value, list)) or (isinstance(value, list) and len(value) > 0):
setattr(params, field_name, value)
# For GLM-Image: compute max_tokens from height/width with mode-aware
# budgeting (t2i vs i2i).
extra_body = getattr(request, "extra_body", {}) or {}
height, width = self._resolve_height_width_from_extra_body(extra_body)
# Best-effort mode detection from user messages.
# i2i requests include at least one reference image in message content.
_, reference_images = self._extract_diffusion_prompt_and_images_from_messages(request.messages)
ref_image_count = len(reference_images)
is_img2img = ref_image_count > 0
if height is not None and width is not None:
try:
from vllm_omni.model_executor.stage_input_processors.glm_image import compute_max_tokens
max_tokens = getattr(explicit_fields, "max_tokens", None)
if max_tokens is None:
max_tokens = compute_max_tokens(int(height), int(width), is_i2i=is_img2img)
params.max_tokens = max_tokens
# Keep target size in stage-0 sampling params so runner/model can
# build deterministic M-RoPE grids for t2i (no MM features).
extra_args = dict(getattr(params, "extra_args", {}) or {})
extra_args["target_h"] = int(height)
extra_args["target_w"] = int(width)
params.extra_args = extra_args
except (ImportError, ValueError, TypeError) as e:
logger.warning(f"Failed to compute max_tokens: {e}, using default if available")
else:
logger.info(
"[SamplingParams] Skip dynamic max_tokens (height=%s, width=%s, mode=%s, ref_images=%s)",
height,
width,
"i2i" if is_img2img else "t2i",
ref_image_count,
)
return params
@staticmethod
def _set_if_supported(obj: Any, **kwargs: Any) -> None:
for key, value in kwargs.items():
if value is not None and hasattr(obj, key):
setattr(obj, key, value)
def _build_sampling_params_list_from_request(
self,
request: ChatCompletionRequest,
@@ -787,6 +828,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
tokenizer: AnyTokenizer,
request_metadata: RequestResponseMetadata,
reasoning_parser: ReasoningParser | None = None,
raw_request: Request | None = None,
):
created_time = int(time.time())
chunk_object_type: Final = "chat.completion.chunk"
@@ -1499,6 +1541,21 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
delta=False,
)
except EngineDeadError as e:
logger.error(
"EngineDeadError during streaming for request %s: %s",
request_id,
e,
)
data = self.create_streaming_error_response(e)
yield f"data: {data}\n\n"
# Actively signal shutdown instead of waiting for the watchdog
# (5s polling interval).
if raw_request is not None:
terminate_if_errored(
server=raw_request.app.state.server,
engine=self.engine_client,
)
except Exception as e:
logger.exception("Error in chat completion stream generator.")
data = self.create_streaming_error_response(e)
@@ -1570,6 +1627,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
role,
reasoning_parser,
)
final_res = omni_outputs.request_output
elif omni_outputs.final_output_type == "audio":
choices_data = self._create_audio_choice(omni_outputs, role, request, stream=False)
elif omni_outputs.final_output_type == "image":
@@ -2048,6 +2106,254 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
return choices
# ==================== Diffusion Mode Methods ====================
def _build_multistage_generation_inputs(
self,
*,
engine: AsyncOmni,
prompt: str,
extra_body: dict[str, Any],
reference_images: list[Image.Image],
gen_params: OmniDiffusionSamplingParams,
) -> tuple[OmniTextPrompt, list[Any]]:
"""Build the shared multistage generation prompt and stage params."""
stage_configs = getattr(engine, "stage_configs", None) or []
default_params_list = list(getattr(engine, "default_sampling_params_list", []) or [])
height = gen_params.height
width = gen_params.width
seed = gen_params.seed
generator_device = gen_params.generator_device
num_outputs_per_prompt = gen_params.num_outputs_per_prompt
num_inference_steps = extra_body.get("num_inference_steps")
guidance_scale = extra_body.get("guidance_scale")
true_cfg_scale = extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale")
negative_prompt = extra_body.get("negative_prompt")
num_frames = extra_body.get("num_frames")
guidance_scale_2 = extra_body.get("guidance_scale_2")
lora_body = extra_body.get("lora")
layers = extra_body.get("layers")
resolution = extra_body.get("resolution")
engine_prompt_data: dict[str, Any] | None = None
modalities = ["image"]
if reference_images:
if len(reference_images) == 1:
engine_prompt_data = {"img2img": reference_images[0]}
modalities = ["img2img"]
else:
engine_prompt_data = {"image": reference_images}
engine_prompt: OmniTextPrompt = {"prompt": prompt}
engine_prompt["modalities"] = modalities
if negative_prompt is not None:
engine_prompt["negative_prompt"] = negative_prompt
mm_processor_kwargs: dict[str, Any] = {}
if height is not None:
mm_processor_kwargs["target_h"] = height
if width is not None:
mm_processor_kwargs["target_w"] = width
if mm_processor_kwargs:
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
if engine_prompt_data is not None:
engine_prompt["multi_modal_data"] = engine_prompt_data
comprehension_idx = None
for idx, stage in enumerate(stage_configs):
if getattr(stage, "is_comprehension", False):
comprehension_idx = idx
break
sampling_params_list: list[Any] = []
for idx, stage_cfg in enumerate(stage_configs):
stage_type = get_stage_type(stage_cfg)
if idx < len(default_params_list):
default_stage_params = default_params_list[idx]
if hasattr(default_stage_params, "clone"):
try:
default_stage_params = default_stage_params.clone()
except Exception:
pass
elif stage_type == "diffusion":
default_stage_params = gen_params.clone()
else:
default_stage_params = SamplingParams()
if (
comprehension_idx is not None
and idx == comprehension_idx
and seed is not None
and hasattr(default_stage_params, "seed")
):
default_stage_params.seed = seed
if stage_type == "diffusion":
self._set_if_supported(
default_stage_params,
height=height,
width=width,
seed=seed,
generator_device=generator_device,
num_outputs_per_prompt=num_outputs_per_prompt,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
true_cfg_scale=true_cfg_scale,
num_frames=num_frames,
guidance_scale_2=guidance_scale_2,
layers=layers,
resolution=resolution,
)
if lora_body and isinstance(lora_body, dict):
try:
lora_req, lora_scale = parse_lora_request(lora_body)
if lora_req is not None:
default_stage_params.lora_request = lora_req
if lora_scale is not None:
default_stage_params.lora_scale = lora_scale
except Exception as e: # pragma: no cover - safeguard
logger.warning("Failed to parse LoRA request: %s", e)
sampling_params_list.append(default_stage_params)
return engine_prompt, sampling_params_list
async def generate_diffusion_images(
self,
*,
prompt: str,
extra_body: dict[str, Any] | None = None,
reference_images: list[str] | None = None,
request_id: str | None = None,
) -> tuple[list[Image.Image], dict[str, Any], float] | ErrorResponse:
"""Generate diffusion images and return raw images plus generation stats."""
if request_id is None:
request_id = f"chatcmpl-{uuid.uuid4().hex[:16]}"
if extra_body is None:
extra_body = {}
if reference_images is None:
reference_images = []
engine = self._diffusion_engine if self._diffusion_engine is not None else self.engine_client
height = extra_body.get("height")
width = extra_body.get("width")
if "size" in extra_body:
try:
size_str = extra_body["size"]
if isinstance(size_str, str) and "x" in size_str.lower():
w, h = size_str.lower().split("x")
width, height = int(w), int(h)
except ValueError:
logger.warning("Invalid size format: %s", extra_body.get("size"))
seed = extra_body.get("seed")
generator_device = extra_body.get("generator_device")
negative_prompt = extra_body.get("negative_prompt")
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt", 1)
lora_body = extra_body.get("lora")
pil_images: list[Image.Image] = []
for img_b64 in reference_images:
try:
img_bytes = base64.b64decode(img_b64)
pil_images.append(Image.open(BytesIO(img_bytes)))
except Exception as e:
logger.warning("Failed to decode reference image: %s", e)
gen_params = OmniDiffusionSamplingParams(
height=height,
width=width,
num_outputs_per_prompt=num_outputs_per_prompt,
seed=seed,
)
self._set_if_supported(
gen_params,
generator_device=generator_device,
num_inference_steps=extra_body.get("num_inference_steps"),
guidance_scale=extra_body.get("guidance_scale"),
true_cfg_scale=extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale"),
num_frames=extra_body.get("num_frames"),
guidance_scale_2=extra_body.get("guidance_scale_2"),
layers=extra_body.get("layers"),
resolution=extra_body.get("resolution"),
)
if lora_body and isinstance(lora_body, dict):
try:
lora_req, lora_scale = parse_lora_request(lora_body)
if lora_req is not None:
gen_params.lora_request = lora_req
if lora_scale is not None:
gen_params.lora_scale = lora_scale
except Exception as e: # pragma: no cover - safeguard
logger.warning("Failed to parse LoRA request: %s", e)
gen_prompt: OmniTextPrompt = {
"prompt": prompt,
"negative_prompt": negative_prompt,
}
if pil_images:
if len(pil_images) == 1:
gen_prompt["multi_modal_data"] = {"image": pil_images[0]}
else:
od_config = getattr(engine, "od_config", None)
supports_multimodal_inputs = getattr(od_config, "supports_multimodal_inputs", False)
if od_config is None:
supports_multimodal_inputs = True
if supports_multimodal_inputs:
gen_prompt["multi_modal_data"] = {"image": pil_images}
else:
return self._create_error_response(
"Multiple input images are not supported by the current diffusion model. "
"For multi-image editing, start the server with Qwen-Image-Edit-2509 "
"and send multiple images in the user message content.",
status_code=400,
)
if isinstance(engine, AsyncOmni):
diffusion_engine = cast(AsyncOmni, engine)
stage_configs = getattr(diffusion_engine, "stage_configs", None) or []
if len(stage_configs) > 1:
engine_prompt, sampling_params_list = self._build_multistage_generation_inputs(
engine=diffusion_engine,
prompt=prompt,
extra_body=extra_body,
reference_images=pil_images,
gen_params=gen_params,
)
else:
engine_prompt = gen_prompt
sampling_params_list = [gen_params]
result = None
async for output in diffusion_engine.generate(
prompt=engine_prompt,
sampling_params_list=sampling_params_list,
request_id=request_id,
):
result = output
if result is None:
return self._create_error_response("No output generated from AsyncOmni", status_code=500)
else:
result = await engine.generate(
prompt=gen_prompt,
sampling_params=gen_params,
request_id=request_id,
)
images = getattr(result.request_output, "images", [])
stage_durations = result.stage_durations
peak_memory_mb = result.peak_memory_mb
flat_images: list[Image.Image] = []
for item in images:
if isinstance(item, list):
flat_images.extend(item)
else:
flat_images.append(item)
return flat_images, stage_durations, peak_memory_mb
async def _create_diffusion_chat_completion(
self,
request: ChatCompletionRequest,
@@ -2108,6 +2414,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
num_inference_steps = extra_body.get("num_inference_steps")
guidance_scale = extra_body.get("guidance_scale")
true_cfg_scale = extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale")
cfg_text_scale = extra_body.get("cfg_text_scale")
cfg_img_scale = extra_body.get("cfg_img_scale")
seed = extra_body.get("seed")
negative_prompt = extra_body.get("negative_prompt")
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt", 1)
@@ -2162,6 +2470,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
gen_params.guidance_scale = guidance_scale
if true_cfg_scale is not None:
gen_params.true_cfg_scale = true_cfg_scale
if cfg_text_scale is not None:
gen_params.extra_args["cfg_text_scale"] = cfg_text_scale
if cfg_img_scale is not None:
gen_params.extra_args["cfg_img_scale"] = cfg_img_scale
if num_frames is not None:
gen_params.num_frames = num_frames
if guidance_scale_2 is not None:
@@ -2182,7 +2494,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
except Exception as e: # pragma: no cover - safeguard
logger.warning("Failed to parse LoRA request: %s", e)
# Add reference image if provided
# Add reference image if provided (from messages content)
if pil_images:
if len(pil_images) == 1:
gen_prompt["multi_modal_data"] = {}
@@ -2206,10 +2518,30 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
# Generate image
diffusion_engine = cast(AsyncOmni, self._diffusion_engine)
stage_configs = list(getattr(diffusion_engine, "stage_configs", []) or [])
default_params_list = list(getattr(diffusion_engine, "default_sampling_params_list", []) or [])
sampling_params_list: list[Any] = []
for idx, stage_cfg in enumerate(stage_configs):
if get_stage_type(stage_cfg) == "diffusion":
sampling_params_list.append(gen_params)
continue
default_stage_params = default_params_list[idx] if idx < len(default_params_list) else SamplingParams()
if hasattr(default_stage_params, "clone"):
try:
default_stage_params = default_stage_params.clone()
except Exception as e:
logger.warning("Failed to clone default params for stage %d: %s", idx, e)
sampling_params_list.append(default_stage_params)
if not sampling_params_list:
sampling_params_list = [gen_params]
result = None
async for output in diffusion_engine.generate(
prompt=gen_prompt,
sampling_params_list=[gen_params], # Pass as single-stage params
sampling_params_list=sampling_params_list,
request_id=request_id,
):
result = output
@@ -2353,6 +2685,48 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
prompt = " ".join(prompt_parts).strip()
return prompt, images
def _extract_diffusion_prompt_and_images_from_messages(
self,
messages: list[Any],
) -> tuple[str, list[str]]:
"""Normalize mixed message types and extract prompt + reference images once."""
return self._extract_diffusion_prompt_and_images(self._messages_to_dicts(messages))
@staticmethod
def _messages_to_dicts(messages: list[Any]) -> list[dict[str, Any]]:
"""Normalize request messages to plain dicts."""
out: list[dict[str, Any]] = []
for msg in messages:
if hasattr(msg, "model_dump"):
out.append(msg.model_dump())
elif isinstance(msg, dict):
out.append(msg)
else:
out.append(
{
"role": getattr(msg, "role", "user"),
"content": getattr(msg, "content", ""),
}
)
return out
@staticmethod
def _resolve_height_width_from_extra_body(extra_body: dict[str, Any]) -> tuple[Any, Any]:
"""Extract generation height/width with optional size string fallback."""
height = extra_body.get("height")
width = extra_body.get("width")
if "size" in extra_body and (height is None or width is None):
try:
size_str = extra_body["size"]
if isinstance(size_str, str) and "x" in size_str.lower():
w, h = size_str.lower().split("x")
width, height = int(w), int(h)
except Exception:
pass
return height, width
def _create_error_response(
self,
message: str,
+159 -14
View File
@@ -17,12 +17,17 @@ import torch
from fastapi import Request, UploadFile
from fastapi.responses import Response, StreamingResponse
from transformers.utils.hub import cached_file
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.launcher import terminate_if_errored
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
RequestResponseMetadata,
)
from vllm.entrypoints.openai.engine.serving import OpenAIServing
from vllm.logger import init_logger
from vllm.multimodal.media import MediaConnector
from vllm.utils import random_uuid
from vllm.utils.async_utils import make_async
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.protocol.audio import (
@@ -49,6 +54,7 @@ _QWEN3_TTS_MODEL_STAGES = {"qwen3_tts"}
_FISH_TTS_MODEL_STAGES = {"fish_speech_slow_ar"}
_COSYVOICE3_TTS_MODEL_STAGES = {"cosyvoice3_talker"}
_OMNIVOICE_TTS_MODEL_STAGES = {"omnivoice_generator"}
_VOXCPM_TTS_MODEL_STAGES = {"latent_generator", "vae"}
_VOXCPM2_TTS_MODEL_STAGES = {"latent_generator"}
_MOSS_TTS_MODEL_STAGES = {"moss_tts_nano"}
_TTS_MODEL_STAGES: set[str] = (
@@ -57,6 +63,7 @@ _TTS_MODEL_STAGES: set[str] = (
| _FISH_TTS_MODEL_STAGES
| _COSYVOICE3_TTS_MODEL_STAGES
| _OMNIVOICE_TTS_MODEL_STAGES
| _VOXCPM_TTS_MODEL_STAGES
| _VOXCPM2_TTS_MODEL_STAGES
| _MOSS_TTS_MODEL_STAGES
)
@@ -216,6 +223,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"Re-upload voices after each restart if needed."
)
self._tts_tokenizer = None
self._voxcpm2_tokenizer = None
self._voxcpm2_split_map: dict[int, list[int]] = {}
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
@@ -284,6 +293,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if self._tts_stage is None:
return None
model_stage = getattr(self._tts_stage.engine_args, "model_stage", None)
model_arch = getattr(self._tts_stage.engine_args, "model_arch", None)
if model_arch == "VoxCPM2TalkerForConditionalGeneration":
return "voxcpm2"
if model_arch == "VoxCPMForConditionalGeneration":
return "voxcpm"
if model_stage in _QWEN3_TTS_MODEL_STAGES:
return "qwen3_tts"
if model_stage in _VOXTRAL_TTS_MODEL_STAGES:
@@ -298,6 +312,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return "voxcpm2"
if model_stage in _MOSS_TTS_MODEL_STAGES:
return "moss_tts_nano"
if model_stage in (_VOXCPM_TTS_MODEL_STAGES | _VOXCPM2_TTS_MODEL_STAGES):
has_vae_stage = any(
getattr(getattr(stage, "engine_args", None), "model_stage", None) == "vae"
for stage in self.engine_client.stage_configs
)
return "voxcpm" if has_vae_stage or model_stage == "vae" else "voxcpm2"
return None
def _compute_max_instructions_length(self) -> int:
@@ -322,6 +342,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def _load_supported_speakers(self) -> set[str]:
"""Load supported speakers (case-insensitive) from the model configuration."""
try:
if self._tts_model_type == "voxcpm":
return set()
if self._tts_model_type == "voxtral_tts":
config = self.engine_client.model_config.hf_config.audio_config
else:
@@ -381,6 +403,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def _estimate_prompt_len(self, tts_params: dict[str, Any]) -> int:
"""Estimate prompt length so the placeholder matches model-side embeddings."""
try:
if self._tts_model_type == "voxcpm":
return 1
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import (
Qwen3TTSTalkerForConditionalGeneration,
)
@@ -444,6 +468,25 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
logger.warning("Failed to estimate Fish Speech prompt length, using fallback 2048: %s", e)
return 2048
async def _build_voxcpm2_prompt(self, request: OpenAICreateSpeechRequest) -> dict[str, Any]:
"""Build prefill prompt for VoxCPM2 TTS (`prompt_token_ids` padded to full prefill length)."""
from vllm_omni.model_executor.models.voxcpm2.voxcpm2_talker import build_voxcpm2_prompt
self._voxcpm2_encode("") # lazy-init tokenizer + split_map
ref_audio = None
ref_sr = None
if request.ref_audio is not None:
ref_audio, ref_sr = await self._resolve_ref_audio(request.ref_audio)
return build_voxcpm2_prompt(
hf_config=self.engine_client.model_config.hf_config,
tokenizer=self._voxcpm2_tokenizer,
split_map=self._voxcpm2_split_map,
text=request.input,
ref_audio=ref_audio,
ref_sr=ref_sr,
ref_text=request.ref_text,
)
def _get_uploaded_audio_data(self, voice_name: str) -> str | None:
"""Get base64 encoded audio data for uploaded voice."""
voice_name_lower = voice_name.lower()
@@ -795,12 +838,33 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return self._validate_fish_tts_request(request)
if self._tts_model_type == "cosyvoice3":
return self._validate_cosyvoice3_request(request)
if self._tts_model_type == "voxcpm":
return self._validate_voxcpm_request(request)
if self._tts_model_type == "voxcpm2":
return None # VoxCPM2 accepts any text input
if self._tts_model_type == "moss_tts_nano":
return self._validate_moss_tts_request(request)
return self._validate_qwen_tts_request(request)
def _voxcpm2_encode(self, text: str) -> list[int]:
"""Tokenize text for VoxCPM2, splitting multichar Chinese tokens."""
from vllm_omni.model_executor.models.voxcpm2.voxcpm2_talker import (
build_cjk_split_map,
split_multichar_chinese,
)
if self._voxcpm2_tokenizer is None:
from transformers import AutoTokenizer
model_name = self.engine_client.model_config.model
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
self._voxcpm2_split_map = build_cjk_split_map(tokenizer)
self._voxcpm2_tokenizer = tokenizer
logger.info("VoxCPM2 serving: built multichar split map (%d entries)", len(self._voxcpm2_split_map))
ids = self._voxcpm2_tokenizer.encode(text, add_special_tokens=True)
return split_multichar_chinese(ids, self._voxcpm2_split_map)
def _validate_ref_audio_format(self, ref_audio: str) -> str | None:
"""Validate ref_audio is a supported URI format. Returns error or None."""
if not (
@@ -838,6 +902,43 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return None
def _validate_voxcpm_request(self, request: OpenAICreateSpeechRequest) -> str | None:
"""Validate VoxCPM request parameters. Returns error message or None."""
if not request.input or not request.input.strip():
return "Input text cannot be empty"
if request.voice is not None:
return "'voice' is not supported for VoxCPM"
if request.instructions is not None:
return "'instructions' is not supported for VoxCPM"
if request.language is not None:
return "'language' is not supported for VoxCPM"
if request.task_type not in (None, "Base"):
return "VoxCPM only supports plain TTS or voice cloning with ref_audio/ref_text"
if request.x_vector_only_mode is not None:
return "'x_vector_only_mode' is not supported for VoxCPM"
if request.speaker_embedding is not None:
return "'speaker_embedding' is not supported for VoxCPM"
if request.initial_codec_chunk_frames is not None:
return "'initial_codec_chunk_frames' is not supported for VoxCPM"
if request.ref_audio is not None:
fmt_err = self._validate_ref_audio_format(request.ref_audio)
if fmt_err:
return fmt_err
if not request.ref_text or not request.ref_text.strip():
return "Voice cloning requires 'ref_text' (transcript of the reference audio)"
elif request.ref_text is not None:
return "'ref_text' requires 'ref_audio' for VoxCPM voice cloning"
if request.max_new_tokens is not None:
if request.max_new_tokens < _TTS_MAX_NEW_TOKENS_MIN:
return f"max_new_tokens must be at least {_TTS_MAX_NEW_TOKENS_MIN}"
if request.max_new_tokens > _TTS_MAX_NEW_TOKENS_MAX:
return f"max_new_tokens cannot exceed {_TTS_MAX_NEW_TOKENS_MAX}"
return None
def _validate_qwen_tts_request(self, request: OpenAICreateSpeechRequest) -> str | None:
"""Validate Qwen TTS request parameters. Returns error message or None."""
# Infer Base task when ref_audio or ref_text is provided without explicit task_type.
@@ -1087,7 +1188,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
return wav_np.tolist(), sr
async def _generate_audio_chunks(self, generator, request_id: str, response_format: str = "pcm"):
async def _generate_audio_chunks(
self,
generator,
request_id: str,
response_format: str = "pcm",
raw_request: Request | None = None,
):
"""Generate audio chunks for streaming response.
Handles two audio output modes from the engine:
@@ -1162,6 +1269,19 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
except asyncio.CancelledError:
logger.info("Streaming request %s cancelled by client", request_id)
raise
except EngineDeadError as e:
logger.error(
"EngineDeadError during streaming speech for %s: %s",
request_id,
e,
)
# Actively signal shutdown rather than relying on the watchdog.
if raw_request is not None:
terminate_if_errored(
server=raw_request.app.state.server,
engine=self.engine_client,
)
raise
except Exception as e:
logger.exception("Streaming speech generation failed for %s: %s", request_id, e)
raise
@@ -1199,6 +1319,18 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
Processes each parameter if present, skips if not.
Values are wrapped in lists as required by the model.
"""
if self._tts_model_type == "voxcpm":
params: dict[str, Any] = {
"text": [request.input],
"cfg_value": [2.0],
"inference_timesteps": [10],
"min_len": [2],
"max_new_tokens": [request.max_new_tokens or 4096],
}
if request.ref_text is not None:
params["ref_text"] = [request.ref_text]
return params
params: dict[str, Any] = {}
# Text content (always required)
@@ -1424,6 +1556,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
async def _prepare_speech_generation(
self,
request: OpenAICreateSpeechRequest,
request_id: str | None = None,
) -> tuple[str, Any, dict[str, Any]]:
if self.engine_client.errored:
raise self.engine_client.dead_error
@@ -1467,14 +1600,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if request.instructions:
prompt["instruct"] = request.instructions
elif self._tts_model_type == "voxcpm2":
prompt = await self._build_voxcpm2_prompt(request)
tts_params = {}
additional: dict[str, Any] = {}
if request.ref_audio is not None:
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
additional["reference_audio"] = [[wav_list, sr]]
prompt = {"prompt": request.input}
if additional:
prompt["additional_information"] = additional
elif self._is_tts:
validation_error = self._validate_tts_request(request)
if validation_error:
@@ -1525,13 +1652,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
tts_params = {}
prompt = {"prompt": request.input}
request_id = f"speech-{random_uuid()}"
request_id = request_id or f"speech-{random_uuid()}"
if self._is_fish_speech:
model_type = "fish_speech"
elif self._tts_model_type == "voxtral_tts":
model_type = "voxtral_tts"
elif self._tts_model_type == "cosyvoice3":
model_type = "cosyvoice3"
elif self._tts_model_type == "voxcpm":
model_type = "voxcpm"
elif self._tts_model_type == "voxcpm2":
model_type = "voxcpm2"
elif self._is_tts:
@@ -1605,8 +1734,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
self,
request: OpenAICreateSpeechRequest,
base64_encode: bool = False,
request_id: str | None = None,
) -> tuple[bytes | str, str]:
request_id, generator, _ = await self._prepare_speech_generation(request)
request_id, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
final_output: OmniRequestOutput | None = None
async for res in generator:
@@ -1730,6 +1860,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
except asyncio.CancelledError:
return self._diffusion_error_response("Client disconnected")
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except ValueError as e:
return self._diffusion_error_response(str(e))
except Exception as e:
@@ -1775,6 +1907,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
logger.error("Error with model %s", error_check_ret)
return error_check_ret
request_id = f"speech-{random_uuid()}"
if raw_request:
raw_request.state.request_metadata = RequestResponseMetadata(
request_id=request_id,
)
try:
if request.stream:
# Determine response format and media type for streaming
@@ -1795,17 +1933,24 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
media_type = "audio/wav" if response_format == "wav" else "audio/pcm"
request_id, generator, _ = await self._prepare_speech_generation(request)
_, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
return StreamingResponse(
self._generate_audio_chunks(generator, request_id, response_format),
self._generate_audio_chunks(
generator,
request_id,
response_format,
raw_request=raw_request,
),
media_type=media_type,
)
audio_bytes, media_type = await self._generate_audio_bytes(request)
audio_bytes, media_type = await self._generate_audio_bytes(request, request_id=request_id)
return Response(content=audio_bytes, media_type=media_type)
except asyncio.CancelledError:
return self.create_error_response("Client disconnected")
except (EngineGenerateError, EngineDeadError):
raise # Propagate to the global Omni exception handler
except ValueError as e:
return self.create_error_response(e)
except Exception as e:
+21 -1
View File
@@ -113,6 +113,10 @@ class OmniOpenAIServingVideo:
if vp.fps is not None:
gen_params.fps = vp.fps
gen_params.frame_rate = float(vp.fps)
gen_params.enable_frame_interpolation = request.enable_frame_interpolation
gen_params.frame_interpolation_exp = request.frame_interpolation_exp
gen_params.frame_interpolation_scale = request.frame_interpolation_scale
gen_params.frame_interpolation_model_path = request.frame_interpolation_model_path
if request.num_inference_steps is not None:
gen_params.num_inference_steps = request.num_inference_steps
@@ -160,7 +164,7 @@ class OmniOpenAIServingVideo:
videos = self._extract_video_outputs(result)
audios = self._extract_audio_outputs(result, expected_count=len(videos))
audio_sample_rate = self._resolve_audio_sample_rate(result)
output_fps = vp.fps or self._resolve_fps(result) or 24
output_fps = (vp.fps or self._resolve_fps(result) or 24) * self._resolve_video_fps_multiplier(result)
return VideoGenerationArtifacts(
videos=videos,
audios=audios,
@@ -243,6 +247,22 @@ class OmniOpenAIServingVideo:
logger.info("Video response encoding (MP4 bytes): %.2f ms", _t_encode_ms)
return video_bytes, artifacts.stage_durations, artifacts.peak_memory_mb
@staticmethod
def _resolve_video_fps_multiplier(result: Any) -> int:
custom_output = getattr(result, "custom_output", None)
if isinstance(custom_output, dict):
multiplier = custom_output.get("video_fps_multiplier")
if multiplier is not None:
return int(multiplier)
request_output = getattr(result, "request_output", None)
if request_output is not None:
custom_output = getattr(request_output, "custom_output", None)
if isinstance(custom_output, dict):
multiplier = custom_output.get("video_fps_multiplier")
if multiplier is not None:
return int(multiplier)
return 1
@staticmethod
def _apply_lora(lora_body: Any, gen_params: OmniDiffusionSamplingParams) -> None:
try:
@@ -227,6 +227,9 @@ def _encode_video_bytes(
frames_np *= 255.0
frames_u8 = np.round(frames_np).astype(np.uint8)
# Ensure contiguous memory layout for faster PyAV muxing
frames_u8 = np.ascontiguousarray(frames_u8)
audio_np = _coerce_audio_to_numpy(audio) if audio is not None else None
return mux_video_audio_bytes(
+38 -19
View File
@@ -23,9 +23,19 @@ logger = logging.getLogger(__name__)
class PDDisaggregationMixin:
"""Mixin supplying PD disaggregation helpers to OmniBase."""
def _get_pd_separation_pair(self) -> tuple[int, int] | None:
"""PD prefill/decode indices when ``_init_pd_state`` ran; else ``None``.
Partial test doubles may skip ``OmniBase.__init__``; treat missing state as
no PD disaggregation instead of raising ``AttributeError``.
"""
return getattr(self, "_pd_separation_pair", None)
def _init_pd_state(self) -> None:
"""Initialise PD disaggregation state."""
self._pd_separation_pair: tuple[int, int] | None = self._detect_pd_separation()
self._pd_separation_pair: tuple[int, int] | None = self.detect_pd_separation_from_stage_configs(
self.stage_configs
)
self._pd_connector_info: dict[str, Any] | None = None
self._pd_kv_params_by_req: dict[str, dict[str, Any]] = {}
self._pd_kv_params_lock = threading.Lock()
@@ -40,11 +50,19 @@ class PDDisaggregationMixin:
d_id,
)
def _detect_pd_separation(self) -> tuple[int, int] | None:
"""Scan stage_list for a prefill/decode pair. Returns (p_id, d_id) or None."""
@staticmethod
def detect_pd_separation_from_stage_configs(stage_configs: list[Any]) -> tuple[int, int] | None:
"""Scan stage configs for a prefill/decode pair.
Returns:
(prefill_idx, decode_idx) if one pair exists, None if not found.
Raises:
ValueError: if multiple candidate PD pairs are found.
"""
prefill_by_id: dict[int, int] = {}
decode_indices: list[int] = []
for i, stage in enumerate(self.stage_list):
for i, stage in enumerate(stage_configs):
if getattr(stage, "is_prefill_only", False):
prefill_by_id[i] = i
sid = getattr(stage, "stage_id", i)
@@ -55,7 +73,7 @@ class PDDisaggregationMixin:
pd_pairs: list[tuple[int, int]] = []
for j in decode_indices:
source_ids = getattr(self.stage_list[j], "engine_input_source", [])
source_ids = getattr(stage_configs[j], "engine_input_source", [])
for src in source_ids:
if src in prefill_by_id:
pd_pairs.append((prefill_by_id[src], j))
@@ -107,10 +125,11 @@ class PDDisaggregationMixin:
def _validate_pd_separation_config(self) -> None:
"""Validate PD stage configurations are consistent."""
assert self._pd_separation_pair is not None
p_id, d_id = self._pd_separation_pair
p_stage = self.stage_list[p_id]
d_stage = self.stage_list[d_id]
pair = self._get_pd_separation_pair()
assert pair is not None
p_id, d_id = pair
p_stage = self.stage_configs[p_id]
d_stage = self.stage_configs[d_id]
def _get_kv_cfg(stage: "OmniStage") -> dict[str, Any]:
ea = stage.engine_args
@@ -158,11 +177,12 @@ class PDDisaggregationMixin:
def _get_pd_connector_info(self) -> dict[str, Any] | None:
"""Extract prefill engine KV connector info."""
if self._pd_separation_pair is None:
pair = self._get_pd_separation_pair()
if pair is None:
return None
p_id, _ = self._pd_separation_pair
p_stage = self.stage_list[p_id]
p_id, _ = pair
p_stage = self.stage_configs[p_id]
ea = p_stage.engine_args
kv_cfg = getattr(ea, "kv_transfer_config", None)
@@ -241,18 +261,17 @@ class PDDisaggregationMixin:
def _is_pd_routing(self, stage_id: int, next_stage_id: int) -> bool:
"""True when edge stage_id → next_stage_id is the prefill→decode boundary."""
return self._pd_separation_pair is not None and self._pd_separation_pair == (
stage_id,
next_stage_id,
)
pair = self._get_pd_separation_pair()
return pair is not None and pair == (stage_id, next_stage_id)
def _maybe_expand_sampling_params(self, sampling_params_list: list) -> list:
"""Auto-duplicate thinker SP for decode stage when user provides N-1 params."""
if self._pd_separation_pair is None:
pair = self._get_pd_separation_pair()
if pair is None:
return sampling_params_list
if len(sampling_params_list) != len(self.stage_list) - 1:
if len(sampling_params_list) != len(self.stage_configs) - 1:
return sampling_params_list
p_id, d_id = self._pd_separation_pair
p_id, d_id = pair
sp_list = list(sampling_params_list)
sp_list.insert(d_id, sp_list[p_id])
return sp_list
+176 -29
View File
@@ -1,3 +1,4 @@
import argparse
import os
import types
from collections import Counter
@@ -5,10 +6,12 @@ from dataclasses import fields, is_dataclass
from pathlib import Path
from typing import Any, get_args, get_origin
import yaml
from vllm.logger import init_logger
from vllm.transformers_utils.config import get_config, get_hf_file_to_dict
from vllm.transformers_utils.repo_utils import file_or_path_exists
from vllm_omni.config.stage_config import StageConfigFactory
from vllm_omni.config.yaml_util import create_config, load_yaml_config, merge_configs
from vllm_omni.entrypoints.stage_utils import _to_dict
from vllm_omni.platforms import current_omni_platform
@@ -23,6 +26,65 @@ _DIFFUSERS_CLASS_TO_CONFIG: dict[str, str] = {
}
def detect_explicit_cli_keys(
argv: list[str],
parser: argparse.ArgumentParser | None = None,
) -> set[str]:
"""Walk ``argv`` and return the set of ``dest`` attribute names the user
explicitly provided (e.g. ``--max-num-seqs 64`` → ``max_num_seqs``).
Used to distinguish user-typed CLI args from argparse default values so
deploy YAMLs are not silently overridden by parser defaults. Shared
across online (``vllm serve``) and offline (scripts, examples, tests,
CI) entry points — offline callers that parse CLI args via argparse
should invoke this on ``sys.argv[1:]`` and pass the result through to
``AsyncOmni`` / ``Omni`` via the ``_cli_explicit_keys`` kwarg.
When ``parser`` is provided, each token is looked up in the parser's
action table to find its real ``dest``. This correctly handles flags
with ``dest=`` overrides, alias flags (e.g. ``--usp`` /
``--ulysses-degree`` both mapping to ``ulysses_degree``), and
``--disable-foo`` / ``store_false`` patterns that map to a differently
named dest. Callers with access to an ``argparse.ArgumentParser`` should
always pass it.
When ``parser`` is ``None``, a name-based heuristic is used as a
fallback (hyphens → underscores, plus a ``no_`` prefix strip for
``argparse.BooleanOptionalAction``). This is correct for simple flags
but silently misidentifies ``--disable-X``-style flags and explicit
``dest=`` overrides, so prefer the parser-aware form.
"""
if parser is not None:
dest_map: dict[str, str] = {}
for action in parser._actions:
for opt in action.option_strings:
dest_map[opt] = action.dest
explicit: set[str] = set()
for tok in argv:
if not tok.startswith("--"):
continue
flag = tok.split("=", 1)[0]
dest = dest_map.get(flag)
if dest is not None:
explicit.add(dest)
return explicit
# Fallback: name-based heuristic (legacy path for callers without a parser).
explicit = set()
for tok in argv:
if not tok.startswith("--"):
continue
name = tok[2:].split("=", 1)[0]
if not name:
continue
attr = name.replace("-", "_")
explicit.add(attr)
# BooleanOptionalAction: --no-foo records as dest `foo`, not `no_foo`.
if attr.startswith("no_"):
explicit.add(attr[3:])
return explicit
def inject_omni_kv_config(stage: Any, omni_conn_cfg: dict[str, Any], omni_from: str, omni_to: str) -> None:
"""Inject connector configuration into stage engine arguments."""
# Prepare omni_kv_config dict
@@ -185,22 +247,25 @@ def _convert_dataclasses_to_dict(obj: Any) -> Any:
def _try_resolve_omni_model_type(model: str) -> str | None:
"""Try to resolve model_type for omni models with empty config.json.
Checks if any registered omni stage config file name matches a substring
in the model name (e.g. 'cosyvoice3' in 'FunAudioLLM/Fun-CosyVoice3-0.5B-2512').
When multiple configs match, the longest stem wins to avoid ambiguity
(e.g. 'bagel_single_stage' over 'bagel').
Searches both the legacy ``stage_configs/*.yaml`` directory and the
migrated ``deploy/*.yaml`` directory for a stem that substring-matches
the model path (e.g. ``cosyvoice3`` in
``FunAudioLLM/Fun-CosyVoice3-0.5B-2512``). The longest match wins so
``cosyvoice3`` beats ``cosyvoice`` and ``bagel_single_stage`` beats
``bagel``.
"""
stage_configs_dir = PROJECT_ROOT / "vllm_omni" / "model_executor" / "stage_configs"
if not stage_configs_dir.exists():
return None
model_lower = model.lower().replace("-", "").replace("_", "")
best_match: str | None = None
best_len = 0
for config_file in sorted(stage_configs_dir.glob("*.yaml")):
candidate = config_file.stem.replace("-", "").replace("_", "")
if candidate in model_lower and len(candidate) > best_len:
best_match = config_file.stem
best_len = len(candidate)
for subdir in ("model_executor/stage_configs", "deploy"):
config_dir = PROJECT_ROOT / "vllm_omni" / subdir
if not config_dir.exists():
continue
for config_file in sorted(config_dir.glob("*.yaml")):
candidate = config_file.stem.replace("-", "").replace("_", "")
if candidate and candidate in model_lower and len(candidate) > best_len:
best_match = config_file.stem
best_len = len(candidate)
return best_match
@@ -273,29 +338,59 @@ def resolve_model_config_path(model: str) -> str:
return str(stage_config_path)
def load_stage_configs_from_model(model: str, base_engine_args: dict | None = None) -> list:
def load_stage_configs_from_model(
model: str,
base_engine_args: dict | None = None,
deploy_config_path: str | None = None,
stage_overrides: dict[str, dict[str, Any]] | None = None,
cli_explicit_keys: set[str] | None = None,
) -> list:
"""Load stage configurations from model's default config file.
.. deprecated::
This is the legacy OmegaConf-based loading path. New code should use
``StageConfigFactory.create_from_model()`` instead. This function will
be removed once all callers are migrated (see PR series [2/N]).
For models registered in the pipeline registry (new path), uses
``StageConfigFactory.create_from_model()`` which merges
PipelineConfig + DeployConfig + CLI overrides.
Loads stage configurations based on the model type and device type.
First tries to load a device-specific YAML file from stage_configs/{device_type}/
directory. If not found, falls back to the default config file.
For other models (legacy path), loads stage configs from YAML.
Args:
model: Model name or path (used to determine model_type)
base_engine_args: Base engine args to merge as CLI overrides.
deploy_config_path: Optional explicit deploy config path.
stage_overrides: Per-stage overrides from --stage-overrides.
cli_explicit_keys: Set of CLI keys the user actually typed. When
provided, only these keys override deploy YAML; argparse defaults
stay subordinate to YAML. ``None`` means treat every kwarg as
explicit (programmatic ``Omni()`` calls).
Returns:
List of stage configuration dictionaries
Raises:
FileNotFoundError: If no stage config file exists for the model type
"""
if base_engine_args is None:
base_engine_args = {}
cli_overrides = _convert_dataclasses_to_dict(dict(base_engine_args))
# Per-stage JSON overrides are always explicit (the user typed --stage-overrides).
explicit = set(cli_explicit_keys) if cli_explicit_keys is not None else None
if stage_overrides:
for stage_id_str, overrides in stage_overrides.items():
for key, val in overrides.items():
stage_key = f"stage_{stage_id_str}_{key}"
cli_overrides[stage_key] = val
if explicit is not None:
explicit.add(stage_key)
stages = StageConfigFactory.create_from_model(
model,
cli_overrides=cli_overrides,
deploy_config_path=deploy_config_path,
cli_explicit_keys=explicit,
)
if stages is not None:
# Convert StageConfig objects to OmegaConf for backward compat
return [stage.to_omegaconf() for stage in stages]
# Legacy fallback: load from YAML
stage_config_path = resolve_model_config_path(model)
if stage_config_path is None:
return []
@@ -312,10 +407,9 @@ def load_stage_configs_from_yaml(
base_engine_args: dict | None = None,
prefer_stage_engine_args: bool = True,
) -> list:
"""Load stage configurations from a YAML file.
"""Load stage configurations from a YAML file (legacy OmegaConf path).
.. deprecated::
Legacy OmegaConf-based loader. Will be removed in PR series [2/N].
TODO(@lishunyang12): remove once all models use PipelineConfig + DeployConfig.
Args:
config_path: Path to the YAML configuration file
@@ -449,22 +543,75 @@ def load_and_resolve_stage_configs(
stage_configs_path: str | None,
kwargs: dict | None,
default_stage_cfg_factory: Any = None,
deploy_config_path: str | None = None,
stage_overrides: dict[str, dict[str, Any]] | None = None,
cli_explicit_keys: set[str] | None = 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
stage_configs_path: Optional path to legacy YAML (stage_args format)
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
deploy_config_path: Optional path to deploy YAML (new format).
Mutually exclusive with ``stage_configs_path``.
stage_overrides: Per-stage overrides from ``--stage-overrides`` JSON.
Keys are stage_id strings, values are dicts of overrides.
Returns:
Tuple of (config_path, stage_configs)
"""
if stage_configs_path is None:
if stage_configs_path is not None and deploy_config_path is not None:
raise ValueError(
"--stage-configs-path and --deploy-config are mutually exclusive: "
"they use different path resolution rules and loading paths. "
"Use --deploy-config for new-format YAMLs (preferred); "
"--stage-configs-path is kept only for the legacy `stage_args` format "
"and will be removed in a future release."
)
if stage_configs_path is not None and deploy_config_path is None:
if not os.path.exists(stage_configs_path):
raise FileNotFoundError(
f"--stage-configs-path {stage_configs_path!r} does not exist. "
"Legacy `stage_configs/` yamls were replaced by `vllm_omni/deploy/<model>.yaml`; "
"use --deploy-config. See docs/configuration/stage_configs.md."
)
with open(stage_configs_path, encoding="utf-8") as f:
_peek = yaml.safe_load(f) or {}
if "stages" in _peek and "stage_args" not in _peek:
deploy_config_path = stage_configs_path
stage_configs_path = None
else:
logger.warning(
"--stage-configs-path is deprecated; migrate %r and use --deploy-config.",
stage_configs_path,
)
if deploy_config_path is not None:
config_path = deploy_config_path
stage_configs = load_stage_configs_from_model(
model,
base_engine_args=kwargs,
deploy_config_path=deploy_config_path,
stage_overrides=stage_overrides,
cli_explicit_keys=cli_explicit_keys,
)
if not stage_configs:
if default_stage_cfg_factory is not None:
default_stage_cfg = default_stage_cfg_factory()
stage_configs = create_config(default_stage_cfg)
else:
stage_configs = []
elif stage_configs_path is None:
config_path = resolve_model_config_path(model)
stage_configs = load_stage_configs_from_model(model, base_engine_args=kwargs)
stage_configs = load_stage_configs_from_model(
model,
base_engine_args=kwargs,
stage_overrides=stage_overrides,
cli_explicit_keys=cli_explicit_keys,
)
if not stage_configs:
if default_stage_cfg_factory is not None:
default_stage_cfg = default_stage_cfg_factory()