Merge main and preserve dispatch backlog across monitor windows
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
ea7de7e3de
769 files changed
+73802
-22805
No files matched your search
@@ -236,6 +236,7 @@ class AsyncOmni(AsyncOmniBase, EngineClient):
|
||||
req_state = ClientRequestState(
|
||||
request_id=request_id,
|
||||
external_request_id=external_request_id,
|
||||
final_stage_id=final_stage_id_for_e2e,
|
||||
)
|
||||
req_state.metrics = metrics
|
||||
req_state.request_arrival_ts = wall_start_ts
|
||||
|
||||
@@ -481,7 +481,22 @@ class AsyncOmniBase(OmniBase):
|
||||
if state is not None and rid not in delivered:
|
||||
queue = getattr(state, "queue", None)
|
||||
if queue is not None:
|
||||
await state.queue.put(self._synthetic_abort_output_message(rid))
|
||||
final_stage_id = getattr(state, "final_stage_id", None)
|
||||
if final_stage_id is None:
|
||||
final_stage_id = 0
|
||||
stage_metadata = getattr(self, "_stage_meta_list", ())
|
||||
final_output_type = (
|
||||
getattr(stage_metadata[final_stage_id], "final_output_type", None)
|
||||
if final_stage_id < len(stage_metadata)
|
||||
else None
|
||||
) or "text"
|
||||
await state.queue.put(
|
||||
self._synthetic_abort_output_message(
|
||||
rid,
|
||||
stage_id=final_stage_id,
|
||||
final_output_type=final_output_type,
|
||||
)
|
||||
)
|
||||
delivered.add(rid)
|
||||
for rid in request_ids:
|
||||
self._record_request_failure_once(rid, reason="client_abort")
|
||||
@@ -493,13 +508,18 @@ class AsyncOmniBase(OmniBase):
|
||||
logger.info("[AsyncOmni] Aborted request(s) %s", ",".join(request_ids))
|
||||
|
||||
@staticmethod
|
||||
def _synthetic_abort_output_message(request_id: str) -> OutputMessage:
|
||||
def _synthetic_abort_output_message(
|
||||
request_id: str,
|
||||
*,
|
||||
stage_id: int,
|
||||
final_output_type: str,
|
||||
) -> OutputMessage:
|
||||
"""Terminal abort OutputMessage used when the engine returned none."""
|
||||
engine_output = OmniRequestOutput(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=0,
|
||||
final_output_type="text",
|
||||
stage_id=stage_id,
|
||||
final_output_type=final_output_type,
|
||||
outputs=[
|
||||
CompletionOutput(
|
||||
index=0,
|
||||
@@ -514,7 +534,7 @@ class AsyncOmniBase(OmniBase):
|
||||
)
|
||||
return OutputMessage(
|
||||
request_id=request_id,
|
||||
stage_id=0,
|
||||
stage_id=stage_id,
|
||||
replica_id=None,
|
||||
engine_outputs=engine_output,
|
||||
metrics=None,
|
||||
|
||||
@@ -192,6 +192,78 @@ def add_daily_omni_cli_args(parser: argparse.ArgumentParser) -> None:
|
||||
)
|
||||
|
||||
|
||||
def add_videomme_cli_args(parser: argparse.ArgumentParser) -> None:
|
||||
"""Add CLI arguments specific to the Video-MME dataset."""
|
||||
group = parser.add_argument_group("Video-MME Dataset Options")
|
||||
group.add_argument(
|
||||
"--videomme-parquet",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to local Video-MME parquet "
|
||||
"(e.g. videomme/test-00000-of-00001.parquet). When set, Hub QA loading is skipped.",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-video-dir",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Directory containing extracted Video-MME videos (videoID.mp4). "
|
||||
"Typical layout after unzipping videos_chunked_*.zip: <root>/video/. "
|
||||
"When using file:// URLs, start the server with --allowed-local-media-path "
|
||||
"covering this directory.",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-subtitle-dir",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Directory containing Video-MME .srt subtitles (videoID.srt). Used only with --videomme-use-subtitle.",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-pack-mode",
|
||||
type=str,
|
||||
choices=["minicpm-frames", "minicpm-interleave", "video_url"],
|
||||
default="minicpm-frames",
|
||||
help="Multimodal packing. "
|
||||
"'minicpm-frames' (default): OmniEvalKit MiniCPM videomme recipe — sampled frames "
|
||||
"as image_url only (max_frames=96). "
|
||||
"'minicpm-interleave': OmniEvalKit videomme_short recipe — 1fps frame/audio pairs "
|
||||
"(max_frames=64). "
|
||||
"'video_url': single video_url part (models with native video input).",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-max-frames",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Override max sampled frames (OmniEvalKit defaults: 96 for minicpm-frames, 64 for minicpm-interleave).",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-duration",
|
||||
type=str,
|
||||
choices=["all", "short", "medium", "long"],
|
||||
default="all",
|
||||
help="Filter by Video-MME duration bucket (default: all).",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-use-subtitle",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Prepend subtitle text to the user prompt (Video-MME w/ subs setting).",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-inline-local-video",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Embed local frames/audio as base64 data URLs so the server does not need "
|
||||
"--allowed-local-media-path. Increases request size; use for small --num-prompts.",
|
||||
)
|
||||
group.add_argument(
|
||||
"--videomme-save-eval-items",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Include per-request Video-MME accuracy rows in the saved JSON under "
|
||||
"videomme_eval_items. Or set env VIDEOMME_SAVE_EVAL_ITEMS=1.",
|
||||
)
|
||||
|
||||
|
||||
def add_seed_tts_cli_args(parser: argparse.ArgumentParser) -> None:
|
||||
"""Add CLI arguments for Seed-TTS benchmarks."""
|
||||
group = parser.add_argument_group("Seed-TTS Dataset Options")
|
||||
@@ -266,6 +338,7 @@ _OMNI_BENCH_DATASET_CHOICES = (
|
||||
"seed-tts-design",
|
||||
"ttsd",
|
||||
"sound-effect",
|
||||
"videomme",
|
||||
)
|
||||
|
||||
|
||||
@@ -332,6 +405,7 @@ def update_omni_help(parser: argparse.ArgumentParser) -> None:
|
||||
def add_omni_args(parser: argparse.ArgumentParser) -> None:
|
||||
"""Register all vLLM-Omni serving benchmark arguments."""
|
||||
add_daily_omni_cli_args(parser)
|
||||
add_videomme_cli_args(parser)
|
||||
add_omniinteract_cli_args(parser)
|
||||
add_seed_tts_cli_args(parser)
|
||||
add_multi_stage_cli_args(parser)
|
||||
|
||||
@@ -8,13 +8,16 @@ Supports both multi-stage LLM models (e.g., Qwen2.5-Omni) and
|
||||
diffusion models (e.g., Qwen-Image) through the same CLI interface.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
from types import FrameType
|
||||
from typing import Any, cast
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import uvloop
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
@@ -22,11 +25,20 @@ from vllm.entrypoints.launchers.cli_args import make_arg_parser, validate_parsed
|
||||
from vllm.entrypoints.serve.utils.api_utils import VLLM_SUBCMD_PARSER_EPILOG
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.registry import resolve_native_single_file
|
||||
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 parse_stage_overrides
|
||||
from vllm_omni.entrypoints.openai.api_server import (
|
||||
omni_run_server,
|
||||
run_omni_api_server_worker_proc,
|
||||
)
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides, prepare_stage_config_inputs
|
||||
from vllm_omni.utils.tracking_parser import TrackingArgumentParser, TrackingNamespace
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.utils import APIServerProcessManager
|
||||
|
||||
from vllm_omni.engine.stage_runtime import StageEngineLaunch, StageRuntime
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
DESCRIPTION = """Launch a local OpenAI-compatible API server to serve Omni models
|
||||
@@ -141,6 +153,8 @@ class OmniServeCommand(CLISubcommand):
|
||||
|
||||
if args.headless:
|
||||
run_headless(args)
|
||||
elif (getattr(args, "api_server_count", None) or 1) > 1:
|
||||
run_multi_api_server_omni(args)
|
||||
else:
|
||||
uvloop.run(omni_run_server(args))
|
||||
|
||||
@@ -198,6 +212,39 @@ class OmniServeCommand(CLISubcommand):
|
||||
if getattr(args, "omni_replica_address", None) is not None and not args.headless:
|
||||
raise ValueError("--omni-replica-address requires --headless to be set")
|
||||
|
||||
api_server_count = getattr(args, "api_server_count", None)
|
||||
if api_server_count is not None and api_server_count < 1 and not args.headless:
|
||||
raise ValueError("--api-server-count must be >= 1 unless --headless is set")
|
||||
if args.headless and api_server_count is not None and api_server_count > 0:
|
||||
raise ValueError("--api-server-count cannot be used with --headless")
|
||||
if api_server_count is not None and api_server_count > 1:
|
||||
distributed_args = (
|
||||
"stage_id",
|
||||
"omni_master_address",
|
||||
"omni_master_port",
|
||||
"omni_replica_address",
|
||||
)
|
||||
if any(getattr(args, name, None) is not None for name in distributed_args):
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 cannot be combined with stage-based "
|
||||
"or distributed stage arguments (--stage-id/--omni-master-* / "
|
||||
"--omni-replica-address)"
|
||||
)
|
||||
if getattr(args, "omni_dp_size_local", 1) != 1:
|
||||
raise ValueError("--api-server-count > 1 requires --omni-dp-size-local=1")
|
||||
if getattr(args, "worker_backend", "multi_process") != "multi_process":
|
||||
raise ValueError("--api-server-count > 1 requires --worker-backend=multi_process")
|
||||
if getattr(args, "enable_fault_tolerance", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-fault-tolerance")
|
||||
if getattr(args, "enable_elastic_ep", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-elastic-ep")
|
||||
if getattr(args, "enable_sleep_mode", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-sleep-mode")
|
||||
from vllm import envs as vllm_envs
|
||||
|
||||
if getattr(vllm_envs, "VLLM_ALLOW_RUNTIME_LORA_UPDATING", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with VLLM_ALLOW_RUNTIME_LORA_UPDATING")
|
||||
|
||||
# --omni-dp-size-local is process-local. A value other than 1 only
|
||||
# makes sense when this process owns a stage (head or headless).
|
||||
omni_dp_size_local = getattr(args, "omni_dp_size_local", None)
|
||||
@@ -221,7 +268,6 @@ class OmniServeCommand(CLISubcommand):
|
||||
"data_parallel_rpc_port": "--data-parallel-rpc-port",
|
||||
"data_parallel_start_rank": "--data-parallel-start-rank",
|
||||
"data_parallel_backend": "--data-parallel-backend",
|
||||
"api_server_count": "--api-server-count",
|
||||
"enable_expert_parallel": "--enable-expert-parallel",
|
||||
}
|
||||
offenders = sorted(flag for dest, flag in prohibited_with_omni.items() if dest in explicit_cli_keys)
|
||||
@@ -260,7 +306,10 @@ class OmniServeCommand(CLISubcommand):
|
||||
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
|
||||
|
||||
model = getattr(args, "model_tag", None) or getattr(args, "model", None)
|
||||
if model and is_diffusion_model(model):
|
||||
native_single_file = resolve_native_single_file(getattr(args, "model_class_name", None))
|
||||
if model and ((native_single_file is not None and os.path.isfile(model)) or is_diffusion_model(model)):
|
||||
if api_server_count is not None and api_server_count > 1:
|
||||
raise ValueError("--api-server-count > 1 is not supported for diffusion models")
|
||||
logger.info("Detected diffusion model: %s", model)
|
||||
return
|
||||
validate_parsed_serve_args(args)
|
||||
@@ -589,6 +638,16 @@ class OmniServeCommand(CLISubcommand):
|
||||
'(e.g. \'{"num_inference_steps": 30, "guidance_scale": 7.5}\').'
|
||||
),
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--custom-pipeline-args",
|
||||
dest="custom_pipeline_args",
|
||||
type=json.loads,
|
||||
default=None,
|
||||
help=(
|
||||
"JSON object passed to native/custom diffusion pipelines. "
|
||||
'Only args containing "pipeline_class" trigger custom pipeline re-initialization.'
|
||||
),
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--usp",
|
||||
"--ulysses-degree",
|
||||
@@ -894,7 +953,8 @@ class OmniServeCommand(CLISubcommand):
|
||||
"--diffusion-kv-cache-dtype",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Diffusion attention KV cache dtype (e.g. fp8). Separate from vLLM --kv-cache-dtype.",
|
||||
help="Diffusion Q/K/V precision: fp8, mxfp8, mxfp4, or float (NPU). "
|
||||
"Separate from vLLM --kv-cache-dtype. Use --diffusion-attention-config for per-role fallback.",
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--diffusion-kv-cache-skip-steps",
|
||||
@@ -1027,6 +1087,207 @@ class OmniServeCommand(CLISubcommand):
|
||||
return serve_parser
|
||||
|
||||
|
||||
def _build_multi_api_stage_runtime(args: TrackingNamespace, num_api_servers: int) -> StageRuntime:
|
||||
"""Resolve the local EngineCore stages that the parent process owns."""
|
||||
from vllm_omni.config.resolver import resolve_omni_config
|
||||
from vllm_omni.engine.stage_runtime import StageRuntime
|
||||
|
||||
kwargs = args.get_explicit_kwargs_dict()
|
||||
model = kwargs.pop("model", None) or args.model
|
||||
|
||||
trust_remote_code = kwargs.get("trust_remote_code")
|
||||
if trust_remote_code is False:
|
||||
trust_remote_code = None
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
snapshot_model=True,
|
||||
)
|
||||
model = config_inputs.model
|
||||
kwargs = config_inputs.kwargs
|
||||
resolved = resolve_omni_config(
|
||||
model,
|
||||
cli_overrides=kwargs,
|
||||
trust_remote_code=config_inputs.trust_remote_code,
|
||||
deploy_config_path=config_inputs.deploy_config_path,
|
||||
stage_overrides=config_inputs.stage_overrides,
|
||||
strategy_config_path=config_inputs.strategy_config_path,
|
||||
)
|
||||
|
||||
config_path = resolved.config_path
|
||||
stage_configs = list(resolved.stage_configs)
|
||||
|
||||
sleep_stages = [
|
||||
int(getattr(stage_config, "stage_id", stage_index))
|
||||
for stage_index, stage_config in enumerate(stage_configs)
|
||||
if bool(
|
||||
getattr(
|
||||
getattr(stage_config, "model_config", getattr(stage_config, "engine_args", None)),
|
||||
"enable_sleep_mode",
|
||||
False,
|
||||
)
|
||||
)
|
||||
]
|
||||
if sleep_stages:
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 cannot be combined with sleep mode; "
|
||||
f"disable enable_sleep_mode for stage(s) {sleep_stages}"
|
||||
)
|
||||
|
||||
async_chunk = any(
|
||||
bool(
|
||||
getattr(
|
||||
getattr(stage, "connector_config", None),
|
||||
"async_chunk",
|
||||
getattr(getattr(stage, "engine_args", None), "async_chunk", False),
|
||||
)
|
||||
)
|
||||
for stage in stage_configs
|
||||
)
|
||||
return StageRuntime(
|
||||
stage_configs=stage_configs,
|
||||
model=model,
|
||||
config_path=config_path,
|
||||
stage_init_timeout=int(getattr(args, "stage_init_timeout", 300)),
|
||||
parallel_stage_init=bool(getattr(args, "parallel_stage_init", False)),
|
||||
async_chunk=async_chunk,
|
||||
tokenizer=getattr(args, "tokenizer", None),
|
||||
log_stats=not bool(getattr(args, "disable_log_stats", False)),
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_multi_api_server_completion(
|
||||
api_server_manager: APIServerProcessManager,
|
||||
engine_launch: StageEngineLaunch,
|
||||
) -> None:
|
||||
"""Wait until API workers complete or any shared stage engine fails."""
|
||||
from multiprocessing import connection
|
||||
|
||||
api_processes = list(api_server_manager.processes)
|
||||
engine_processes = [
|
||||
process
|
||||
for resources in engine_launch.resources
|
||||
if resources.manager is not None
|
||||
for process in resources.manager.processes
|
||||
]
|
||||
api_by_sentinel = {process.sentinel: process for process in api_processes}
|
||||
engine_by_sentinel = {process.sentinel: process for process in engine_processes}
|
||||
|
||||
while api_by_sentinel:
|
||||
ready = connection.wait([*api_by_sentinel, *engine_by_sentinel])
|
||||
for sentinel in ready:
|
||||
if sentinel in engine_by_sentinel:
|
||||
process = engine_by_sentinel[sentinel]
|
||||
raise RuntimeError(
|
||||
f"Shared stage engine process {process.name} (PID: {process.pid}) "
|
||||
f"exited with code {process.exitcode}"
|
||||
)
|
||||
process = api_by_sentinel.pop(sentinel)
|
||||
if process.exitcode != 0:
|
||||
raise RuntimeError(
|
||||
f"API server process {process.name} (PID: {process.pid}) exited with code {process.exitcode}"
|
||||
)
|
||||
|
||||
|
||||
def _start_api_server_process_manager(
|
||||
*,
|
||||
cleanup_timeout: float,
|
||||
**manager_kwargs: object,
|
||||
) -> APIServerProcessManager:
|
||||
"""Construct vLLM's manager with rollback for a partial ``__init__``.
|
||||
|
||||
``APIServerProcessManager`` starts workers one by one in ``__init__`` and
|
||||
installs its finalizer only after every ``Process.start`` succeeds. Keep a
|
||||
reference to the partially initialized object so workers started before a
|
||||
later failure are still terminated.
|
||||
"""
|
||||
from vllm.v1.utils import APIServerProcessManager, shutdown
|
||||
|
||||
manager = APIServerProcessManager.__new__(APIServerProcessManager)
|
||||
try:
|
||||
APIServerProcessManager.__init__(manager, **manager_kwargs)
|
||||
except BaseException:
|
||||
try:
|
||||
for pipe in getattr(manager, "_address_pipes", ()):
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
# A Process whose start() raised is still present in the upstream
|
||||
# manager's list, but calling is_alive() on it raises because it
|
||||
# has no Popen object. Only hand successfully started children to
|
||||
# vLLM's shutdown helper.
|
||||
started_processes = [process for process in getattr(manager, "processes", ()) if process.pid is not None]
|
||||
if started_processes:
|
||||
shutdown(started_processes, timeout=cleanup_timeout)
|
||||
except Exception:
|
||||
logger.exception("Failed to clean up partially started API server processes")
|
||||
raise
|
||||
return manager
|
||||
|
||||
|
||||
def run_multi_api_server_omni(args: TrackingNamespace) -> None:
|
||||
"""Launch API subprocesses that share one set of local stage engines."""
|
||||
from vllm.entrypoints.openai.api_server import setup_server
|
||||
from vllm.v1.metrics.prometheus import setup_multiprocess_prometheus
|
||||
|
||||
num_api_servers = int(args.api_server_count)
|
||||
if num_api_servers < 2:
|
||||
raise ValueError(f"api_server_count must be >= 2, got {num_api_servers}")
|
||||
|
||||
setup_multiprocess_prometheus()
|
||||
shutdown_requested = False
|
||||
|
||||
def signal_handler(signum: int, frame: FrameType | None) -> None:
|
||||
nonlocal shutdown_requested
|
||||
logger.debug("Received %d signal.", signum)
|
||||
if not shutdown_requested:
|
||||
shutdown_requested = True
|
||||
raise SystemExit
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
listen_address, sock = setup_server(args, reuse_port=True)
|
||||
stage_runtime = None
|
||||
api_server_manager = None
|
||||
engine_launch = None
|
||||
try:
|
||||
stage_runtime = _build_multi_api_stage_runtime(args, num_api_servers)
|
||||
with stage_runtime.launch_stage_engines(num_api_servers) as engine_launch:
|
||||
args._omni_stage_client_configs = engine_launch.client_configs
|
||||
primary_addresses = engine_launch.resources[0].addresses
|
||||
if primary_addresses is None:
|
||||
raise RuntimeError("Primary stage engine returned no addresses")
|
||||
timeout = float(getattr(args, "shutdown_timeout", 5) or 5)
|
||||
api_server_manager = _start_api_server_process_manager(
|
||||
cleanup_timeout=timeout,
|
||||
listen_address=listen_address,
|
||||
sock=sock,
|
||||
args=args,
|
||||
num_servers=num_api_servers,
|
||||
input_addresses=primary_addresses.inputs,
|
||||
output_addresses=primary_addresses.outputs,
|
||||
target_server_fn=run_omni_api_server_worker_proc,
|
||||
)
|
||||
engine_launch.watched_frontend_processes.extend(api_server_manager.processes)
|
||||
actual_inputs, actual_outputs = api_server_manager.gather_actual_addresses()
|
||||
primary_addresses.inputs = actual_inputs
|
||||
primary_addresses.outputs = actual_outputs
|
||||
|
||||
_wait_for_multi_api_server_completion(api_server_manager, engine_launch)
|
||||
finally:
|
||||
timeout = float(getattr(args, "shutdown_timeout", 5) or 5)
|
||||
if api_server_manager is not None:
|
||||
api_server_manager.shutdown(timeout=timeout)
|
||||
if engine_launch is not None:
|
||||
engine_launch.shutdown()
|
||||
if stage_runtime is not None:
|
||||
stage_runtime.shutdown()
|
||||
sock.close()
|
||||
if shutdown_requested:
|
||||
logger.info("Shared API server shutdown completed")
|
||||
|
||||
|
||||
def run_headless(args: TrackingNamespace) -> None:
|
||||
"""Run a single stage in headless mode.
|
||||
|
||||
@@ -1048,6 +1309,7 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
)
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
build_engine_args_dict,
|
||||
build_engine_args_dict_from_omni_stage_config,
|
||||
build_vllm_config,
|
||||
get_stage_connector_spec,
|
||||
inject_omni_kv_connector_config,
|
||||
@@ -1074,15 +1336,6 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
|
||||
# Filter down to a dict of things explicitly requested by the user
|
||||
args_dict = args.get_explicit_kwargs_dict()
|
||||
# This controls only the API-process WebSocket and is not a stage-engine option.
|
||||
args_dict.pop("robot_openpi_idle_timeout", None)
|
||||
# This CLI-only negative alias is consumed below when selecting the
|
||||
# launcher log_stats value; it is not a per-stage config override.
|
||||
args_dict.pop("disable_log_stats", None)
|
||||
|
||||
deploy_config_path = args_dict.pop("deploy_config", None)
|
||||
strategy_config_path = args_dict.pop("strategy_config", None)
|
||||
stage_overrides = args_dict.pop("stage_overrides", None)
|
||||
|
||||
# ``--replica-id`` is deprecated and ignored — replica ids are
|
||||
# auto-assigned by ``OmniMasterServer`` so headless processes carry
|
||||
@@ -1098,15 +1351,21 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
)
|
||||
args_dict.pop("replica_id")
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
args_dict,
|
||||
# store_true cannot express an explicit False: absent maps to None
|
||||
# ("not specified") so the deploy yaml's per-stage value applies.
|
||||
trust_remote_code=getattr(args, "trust_remote_code", None) or None,
|
||||
)
|
||||
args_dict = config_inputs.kwargs
|
||||
resolved = resolve_omni_config(
|
||||
model,
|
||||
trust_remote_code=config_inputs.trust_remote_code,
|
||||
cli_overrides=args_dict,
|
||||
deploy_config_path=deploy_config_path,
|
||||
stage_overrides=stage_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
deploy_config_path=config_inputs.deploy_config_path,
|
||||
stage_overrides=config_inputs.stage_overrides,
|
||||
strategy_config_path=config_inputs.strategy_config_path,
|
||||
)
|
||||
config_path = resolved.config_path
|
||||
stage_configs = list(resolved.stage_configs)
|
||||
@@ -1141,21 +1400,21 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
stage_connector_spec = get_stage_connector_spec(
|
||||
omni_transfer_config=omni_transfer_config,
|
||||
stage_id=stage_id,
|
||||
async_chunk=bool(stage_cfg.engine_args.get("async_chunk", False)),
|
||||
async_chunk=bool(
|
||||
getattr(getattr(stage_cfg, "connector_config", None), "async_chunk", None)
|
||||
if hasattr(stage_cfg, "connector_config")
|
||||
else stage_cfg.engine_args.get("async_chunk", False)
|
||||
),
|
||||
)
|
||||
|
||||
# ``runtime_cfg`` is mostly inherited from the parent's
|
||||
# CUDA_VISIBLE_DEVICES; when ``--omni-dp-size-local > 1`` we additionally
|
||||
# bracket each replica's spawn below with setup_stage_devices so they
|
||||
# don't all stack on cuda:0 (see ``per_replica_devices`` above).
|
||||
# Headless startup still supplies the legacy OmegaConf stage shape through
|
||||
# the stable adapter entry point. The implementation switches only when
|
||||
# RFC #4021 threads structured stage configs through the launch plan.
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_cfg,
|
||||
model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=getattr(args, "tokenizer", None),
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_cfg, model, stage_connector_spec=stage_connector_spec, cli_tokenizer=getattr(args, "tokenizer", None)
|
||||
)
|
||||
if hasattr(stage_cfg, "connector_config")
|
||||
else build_engine_args_dict(
|
||||
stage_cfg, model, stage_connector_spec=stage_connector_spec, cli_tokenizer=getattr(args, "tokenizer", None)
|
||||
)
|
||||
)
|
||||
|
||||
inject_omni_kv_connector_config(engine_args_dict, omni_kv_connector, stage_id)
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
|
||||
from vllm_omni.metrics import OrchestratorAggregator
|
||||
@@ -11,10 +14,12 @@ class ClientRequestState:
|
||||
request_id: str,
|
||||
external_request_id: str | None = None,
|
||||
queue: asyncio.Queue | None = None,
|
||||
final_stage_id: int | None = None,
|
||||
):
|
||||
self.request_id = request_id
|
||||
self.external_request_id = external_request_id
|
||||
self.stage_id: int | None = None
|
||||
self.final_stage_id: int | None = final_stage_id
|
||||
self.queue = queue if queue is not None else asyncio.Queue()
|
||||
self.metrics: OrchestratorAggregator | None = None
|
||||
# Request-scoped idempotency guard for Prometheus failure counters.
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
Everything that needed session state now lives engine-side
|
||||
(``vllm_omni.engine.duplex.realtime_commands`` for the command mapping,
|
||||
``vllm_omni.engine.duplex.realtime_events`` for the projection state). What is
|
||||
``vllm_omni.engine.duplex.realtime_events`` for the projection state), and the
|
||||
model-agnostic parsing both of those build on lives in
|
||||
``vllm_omni.protocol.realtime``. What is
|
||||
left here is the per-connection handshake policy (query-param defaults,
|
||||
autostart / resume-only rules, ``session.resume`` parsing), the wire defaults
|
||||
used to translate appends, and error rendering through the typed
|
||||
@@ -20,10 +22,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from vllm_omni.engine.duplex.commands import DuplexCommand, DuplexCommandError
|
||||
from vllm_omni.engine.duplex.events import error_event
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
RealtimeInputDefaults,
|
||||
translate_realtime_command,
|
||||
)
|
||||
from vllm_omni.engine.duplex.realtime_commands import translate_realtime_command
|
||||
from vllm_omni.protocol.duplex import RealtimeInputDefaults
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from starlette.websockets import WebSocket
|
||||
|
||||
@@ -36,7 +36,6 @@ from vllm_omni.engine.duplex.events import (
|
||||
SessionResyncRequired,
|
||||
)
|
||||
from vllm_omni.engine.duplex.messages import DuplexSessionError
|
||||
from vllm_omni.engine.duplex.realtime_commands import RealtimeInputDefaults
|
||||
from vllm_omni.entrypoints.duplex.realtime_input import RealtimeEnvelope, parse_resume_request
|
||||
from vllm_omni.entrypoints.duplex.session_attachment import (
|
||||
DuplexJournalGapError,
|
||||
@@ -52,6 +51,7 @@ from vllm_omni.entrypoints.duplex.websocket import (
|
||||
receive_text_with_timeout,
|
||||
)
|
||||
from vllm_omni.entrypoints.duplex_omni import DuplexOmni, DuplexSessionHandle
|
||||
from vllm_omni.protocol.duplex import RealtimeInputDefaults
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ async def _warmup_duplex_realtime(app, args, warmup_frames: int) -> None:
|
||||
# One silence unit as the engine-side plugin defines it (DuplexOmniEngine.plugin).
|
||||
plugin = getattr(getattr(app.state.engine_client, "engine", None), "plugin", None)
|
||||
frame_samples = int(getattr(plugin, "silence_continuation_samples", 16000))
|
||||
native_append = plugin.capabilities(max_sessions=1).supports_core_resumable_request if plugin else True
|
||||
silence = base64.b64encode(bytes(frame_samples * 4)).decode("ascii")
|
||||
from vllm_omni.clients.duplex import build_realtime_url
|
||||
|
||||
@@ -81,7 +82,7 @@ async def _warmup_duplex_realtime(app, args, warmup_frames: int) -> None:
|
||||
"output_audio_format": "pcm16",
|
||||
"idle_timeout_s": 60,
|
||||
"turn_detection": None,
|
||||
"extra_body": {"auto_response": True},
|
||||
"extra_body": {"auto_response": native_append},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -108,6 +109,8 @@ async def _warmup_duplex_realtime(app, args, warmup_frames: int) -> None:
|
||||
await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": silence}))
|
||||
sent += 1
|
||||
await asyncio.sleep(0.08)
|
||||
if not native_append:
|
||||
await ws.send(json.dumps({"type": "input_audio_buffer.commit", "final": True}))
|
||||
# Wait for the pipeline's first audio output so every stage ran.
|
||||
saw_audio = await _recv_until(lambda e: e.get("type") == "response.output_audio.delta", 30)
|
||||
# Close the session EXPLICITLY: a bare websocket close parks the
|
||||
|
||||
@@ -6,6 +6,7 @@ This module owns app construction, server startup, app-state initialization,
|
||||
and route bodies that have not yet moved to endpoint-owned modules."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import dataclasses
|
||||
import json
|
||||
import multiprocessing
|
||||
@@ -14,13 +15,17 @@ import os
|
||||
|
||||
# Image generation API imports
|
||||
import random
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
from argparse import Namespace
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
import uvloop
|
||||
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
|
||||
@@ -80,12 +85,14 @@ from vllm.renderers.online_renderer import OnlineRenderer
|
||||
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.utils.system_utils import decorate_logs, set_process_title
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.config.endpoint_policy import (
|
||||
shutdown_unsupported_routes,
|
||||
)
|
||||
from vllm_omni.engine.stage_init_utils import set_death_signal
|
||||
from vllm_omni.engine.stage_runtime import OmniClientConfig
|
||||
from vllm_omni.entrypoints.async_omni import ABORT_TIMEOUT_S, AsyncOmni
|
||||
from vllm_omni.entrypoints.duplex.serving import OmniDuplexSessionHandler
|
||||
from vllm_omni.entrypoints.duplex.warmup import _warmup_duplex_realtime
|
||||
@@ -121,6 +128,7 @@ from vllm_omni.entrypoints.openai.images.helpers import (
|
||||
_check_max_generated_image_size,
|
||||
_choose_output_format,
|
||||
_extract_images_from_result,
|
||||
_generated_size_str,
|
||||
_get_max_edit_input_images,
|
||||
_load_input_images,
|
||||
_update_if_not_none,
|
||||
@@ -161,6 +169,7 @@ from vllm_omni.entrypoints.openai.serving_rl_rollout import ServingRLRollout
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpeechHandler
|
||||
from vllm_omni.entrypoints.openai.serving_video import (
|
||||
LatentEditInput,
|
||||
OmniOpenAIServingVideo,
|
||||
ReferenceAudio,
|
||||
ReferenceImage,
|
||||
@@ -231,8 +240,55 @@ async def omni_run_server(args, **uvicorn_kwargs) -> None:
|
||||
await omni_run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
|
||||
|
||||
|
||||
async def omni_run_server_worker(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
|
||||
def run_omni_api_server_worker_proc(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
args: TrackingNamespace,
|
||||
client_config: dict[str, Any] | None = None,
|
||||
**uvicorn_kwargs: object,
|
||||
) -> None:
|
||||
"""Entrypoint used by vLLM's API server process manager."""
|
||||
set_death_signal(signal.SIGTERM)
|
||||
manager_config = client_config or {}
|
||||
client_index = int(manager_config.get("client_index", 0))
|
||||
all_client_configs = getattr(args, "_omni_stage_client_configs", None)
|
||||
if not all_client_configs or not 0 <= client_index < len(all_client_configs):
|
||||
raise RuntimeError(f"Missing Omni stage client configuration for API server {client_index}")
|
||||
|
||||
omni_client_config: OmniClientConfig = copy.deepcopy(all_client_configs[client_index])
|
||||
omni_client_config["client_count"] = int(manager_config.get("client_count", 1))
|
||||
omni_client_config["client_index"] = client_index
|
||||
|
||||
stage_addresses = omni_client_config["stage_addresses"]
|
||||
first_stage_id = min(stage_addresses)
|
||||
first_replica_id = min(stage_addresses[first_stage_id])
|
||||
first_addresses = stage_addresses[first_stage_id][first_replica_id]
|
||||
for key in ("input_address", "output_address", "actual_address_pipe", "tensor_queue"):
|
||||
if key in manager_config:
|
||||
first_addresses[key] = manager_config[key]
|
||||
|
||||
set_process_title("APIServer", str(client_index))
|
||||
decorate_logs("APIServer", skip_if_decorated=True)
|
||||
uvloop.run(
|
||||
omni_run_server_worker(
|
||||
listen_address,
|
||||
sock,
|
||||
args,
|
||||
client_config=omni_client_config,
|
||||
**uvicorn_kwargs,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def omni_run_server_worker(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
args: TrackingNamespace,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
**uvicorn_kwargs: object,
|
||||
) -> None:
|
||||
"""Run a single API server worker."""
|
||||
api_server_count = _resolve_api_server_count(args, client_config)
|
||||
|
||||
if args.tool_parser_plugin and len(args.tool_parser_plugin) > 3:
|
||||
ToolParserManager.import_tool_parser(args.tool_parser_plugin)
|
||||
@@ -272,6 +328,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
|
||||
# OMNI: Pass supported_tasks to build_app (required by upstream vLLM)
|
||||
app = build_openai_app(args, supported_tasks)
|
||||
app.state.api_server_count = api_server_count
|
||||
|
||||
# OMNI: Remove upstream routes that we override with omni-specific handlers
|
||||
remove_route_from_app(app, "/v1/chat/completions", {"POST"})
|
||||
@@ -347,6 +404,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
if scope["type"] == "http":
|
||||
scope.setdefault("state", {})
|
||||
scope["state"]["request_timestamp"] = time.time()
|
||||
|
||||
await self._inner(scope, receive, send)
|
||||
|
||||
# Startup duplex warmup (duplex_session.warmup_frames in the deploy
|
||||
@@ -405,7 +463,7 @@ async def build_async_omni(
|
||||
args: TrackingNamespace,
|
||||
*,
|
||||
disable_frontend_multiprocessing: bool | None = None,
|
||||
client_config: dict[str, Any] | None = None,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> AsyncIterator[EngineClient]:
|
||||
"""Build an AsyncOmni instance from command-line arguments.
|
||||
|
||||
@@ -436,25 +494,41 @@ async def build_async_omni(
|
||||
async with build_async_omni_from_stage_config(
|
||||
args,
|
||||
disable_frontend_multiprocessing=disable_frontend_multiprocessing,
|
||||
client_config=client_config,
|
||||
) as async_omni:
|
||||
yield async_omni
|
||||
|
||||
|
||||
def _is_duplex_model(model: str, kwargs: dict[str, Any]) -> bool:
|
||||
"""Whether ``model``'s pipeline declares a ``duplex_plugin`` (served by ``DuplexOmni``).
|
||||
|
||||
Resolution errors propagate: a duplex model whose pipeline or deploy
|
||||
config cannot be resolved must fail startup rather than silently start a
|
||||
turn-based server.
|
||||
"""
|
||||
def _should_serve_duplex(model: str, kwargs: dict[str, Any]) -> bool:
|
||||
"""Select the serving engine without changing the model's duplex capability."""
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
from vllm_omni.config.stage_config import _DEPLOY_DIR, resolve_deploy_yaml
|
||||
|
||||
pipeline_config = StageConfigFactory.get_pipeline_config(
|
||||
model=model,
|
||||
trust_remote_code=bool(kwargs.get("trust_remote_code")),
|
||||
deploy_config_path=kwargs.get("deploy_config"),
|
||||
)
|
||||
return bool(pipeline_config is not None and getattr(pipeline_config, "duplex_plugin", None))
|
||||
if pipeline_config is None or not getattr(pipeline_config, "duplex_plugin", None):
|
||||
return False
|
||||
|
||||
deploy_path = kwargs.get("deploy_config")
|
||||
if deploy_path is None:
|
||||
if pipeline_config.default_deploy_config_name is None:
|
||||
raise ValueError("A duplex-capable model requires a deploy config with session_mode: turn or duplex")
|
||||
deploy_path = _DEPLOY_DIR / pipeline_config.default_deploy_config_name
|
||||
else:
|
||||
deploy_path = Path(deploy_path)
|
||||
if not deploy_path.exists() and deploy_path.parent == Path("."):
|
||||
deploy_path = _DEPLOY_DIR / deploy_path
|
||||
|
||||
# Resolve base_config too, so the API and stage workers use the same mode.
|
||||
session_mode = resolve_deploy_yaml(deploy_path).get(
|
||||
"session_mode", getattr(pipeline_config, "default_session_mode", None)
|
||||
)
|
||||
if session_mode not in ("turn", "duplex"):
|
||||
raise ValueError("A duplex-capable model requires session_mode: turn or duplex in its deploy config")
|
||||
return session_mode == "duplex"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -462,6 +536,7 @@ async def build_async_omni_from_stage_config(
|
||||
args: TrackingNamespace,
|
||||
*,
|
||||
disable_frontend_multiprocessing: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> AsyncIterator[EngineClient]:
|
||||
"""Create AsyncOmni from stage configuration.
|
||||
|
||||
@@ -518,9 +593,9 @@ async def build_async_omni_from_stage_config(
|
||||
kwargs.pop("robot_openpi_idle_timeout", None)
|
||||
model = kwargs.pop("model", None) or args.model
|
||||
kwargs.setdefault("log_stats", not args.disable_log_stats)
|
||||
if _is_duplex_model(model, kwargs):
|
||||
# A duplex model is always served in duplex mode: sessions over
|
||||
# /v1/realtime?duplex=1, no turn-based HTTP routes.
|
||||
if client_config is not None:
|
||||
kwargs["client_config"] = client_config
|
||||
if _should_serve_duplex(model, kwargs):
|
||||
async_omni = DuplexOmni(model=model, **kwargs)
|
||||
else:
|
||||
async_omni = AsyncOmni(model=model, **kwargs)
|
||||
@@ -712,9 +787,7 @@ async def omni_init_app_state(
|
||||
state.stage_configs = engine_client.stage_configs if hasattr(engine_client, "stage_configs") else None
|
||||
model_name = served_model_names[0] if served_model_names else args.model
|
||||
|
||||
# Duplex mode: a duplex model is served through DuplexOmni only. Sessions
|
||||
# run over /v1/realtime?duplex=1; every turn-based HTTP route reports
|
||||
# "not available".
|
||||
# Initialize the API surface for the selected engine, not just the model.
|
||||
if isinstance(engine_client, DuplexOmni):
|
||||
await _init_duplex_app_state(engine_client, state, args, base_model_paths, vllm_config, request_logger)
|
||||
return
|
||||
@@ -1420,6 +1493,42 @@ async def list_voices(raw_request: Request):
|
||||
return JSONResponse(content={"voices": speakers, "uploaded_voices": uploaded_speakers})
|
||||
|
||||
|
||||
def _resolve_api_server_count(args: Namespace, client_config: OmniClientConfig | None) -> int:
|
||||
"""Resolve frontend topology once, from the launcher's client configuration."""
|
||||
requested = getattr(args, "api_server_count", None)
|
||||
actual = 1 if client_config is None else client_config.get("client_count")
|
||||
if type(actual) is not int or actual < 1:
|
||||
raise ValueError("API client configuration requires a positive integer client_count")
|
||||
if requested is not None and (type(requested) is not int or requested < 1 or requested != actual):
|
||||
raise ValueError("API server count does not match the frontend launch configuration")
|
||||
return actual
|
||||
|
||||
|
||||
def _reject_process_local_state_with_multiple_api_workers(raw_request: Request, operation: str) -> None:
|
||||
"""Reject access to frontend state that is not shared across API workers."""
|
||||
api_server_count = getattr(raw_request.app.state, "api_server_count", None)
|
||||
if type(api_server_count) is not int or api_server_count < 1:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="API worker topology is not initialized.",
|
||||
)
|
||||
if api_server_count > 1:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.CONFLICT.value,
|
||||
detail=(
|
||||
f"{operation} is not supported with --api-server-count > 1 because "
|
||||
"the operation uses process-local frontend state"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def _require_single_api_video_store(raw_request: Request) -> None:
|
||||
# VIDEO_STORE and VIDEO_TASKS are process-local, including reads and
|
||||
# cancellation. Keep this independent of the temporary diffusion launch
|
||||
# restriction: enabling multi-API diffusion alone cannot make jobs shared.
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Asynchronous video jobs")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/audio/voices",
|
||||
responses={
|
||||
@@ -1465,6 +1574,7 @@ async def upload_voice(
|
||||
Returns:
|
||||
JSON response with voice information
|
||||
"""
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Runtime voice upload")
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return _create_speech_error_json_response(
|
||||
@@ -1530,6 +1640,7 @@ async def delete_voice(name: str, raw_request: Request):
|
||||
Returns:
|
||||
JSON response indicating success or failure
|
||||
"""
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Runtime voice deletion")
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return _create_speech_error_json_response(
|
||||
@@ -1623,16 +1734,24 @@ async def streaming_video_output(websocket: WebSocket):
|
||||
@router.websocket("/v1/realtime")
|
||||
async def realtime_websocket(websocket: WebSocket):
|
||||
"""WebSocket endpoint for OpenAI-style realtime interactions."""
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
duplex_handler = getattr(websocket.app.state, "openai_serving_duplex", None)
|
||||
duplex_query = websocket.query_params.get("duplex")
|
||||
use_duplex_realtime = duplex_handler is not None and (
|
||||
duplex_query is None or (isinstance(duplex_query, str) and duplex_query.lower() in {"1", "true", "on"})
|
||||
)
|
||||
if use_duplex_realtime and duplex_handler is not None:
|
||||
if await _reject_multi_api_duplex(websocket):
|
||||
return
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
await duplex_handler.handle_realtime_session(websocket)
|
||||
return
|
||||
|
||||
if isinstance(duplex_query, str) and duplex_query.lower() in {"1", "true", "on"}:
|
||||
await websocket.accept()
|
||||
await websocket.send_json({"type": "error", "code": "unsupported", "error": "VAD realtime is not enabled"})
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
|
||||
serving = getattr(websocket.app.state, "openai_serving_realtime", None)
|
||||
if serving is None:
|
||||
await websocket.accept()
|
||||
@@ -1659,6 +1778,8 @@ async def _wait_for_duplex_warmup(websocket: WebSocket) -> None:
|
||||
@router.websocket("/v1/duplex")
|
||||
async def duplex_websocket(websocket: WebSocket):
|
||||
"""Alias of ``/v1/realtime?duplex=1``: the same Realtime duplex session protocol."""
|
||||
if await _reject_multi_api_duplex(websocket):
|
||||
return
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
handler = getattr(websocket.app.state, "openai_serving_duplex", None)
|
||||
if handler is None:
|
||||
@@ -1699,6 +1820,24 @@ async def realtime_robot_openpi(websocket: WebSocket):
|
||||
await connection.handle_connection()
|
||||
|
||||
|
||||
async def _reject_multi_api_duplex(websocket: WebSocket) -> bool:
|
||||
# Session credentials and replay state are local to each frontend; a shared
|
||||
# listening socket cannot route reconnects back to the session owner.
|
||||
count = getattr(websocket.app.state, "api_server_count", None)
|
||||
if count is None or (type(count) is int and count == 1):
|
||||
return False
|
||||
await websocket.accept()
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "error",
|
||||
"error": "Duplex sessions require a single API worker with initialized topology.",
|
||||
"code": "multi_api_duplex_unsupported",
|
||||
}
|
||||
)
|
||||
await websocket.close(code=1008)
|
||||
return True
|
||||
|
||||
|
||||
# RL Rollout serving (RFC #3747, P0)
|
||||
|
||||
|
||||
@@ -1864,8 +2003,9 @@ def _build_image_generation_response(
|
||||
peak_memory_mb=peak_memory_mb,
|
||||
),
|
||||
}
|
||||
if request.size is not None:
|
||||
response_kwargs["size"] = request.size
|
||||
size = _generated_size_str(images, request.size)
|
||||
if size is not None:
|
||||
response_kwargs["size"] = size
|
||||
response = ImageGenerationResponse(**response_kwargs)
|
||||
if request.response_format == ResponseFormat.FILE:
|
||||
return response.stream_response()
|
||||
@@ -1913,6 +2053,8 @@ async def generate_images(
|
||||
)
|
||||
|
||||
try:
|
||||
width: int | None = None
|
||||
height: int | None = None
|
||||
# Unify request construction for any multi-stage pipeline to avoid
|
||||
# divergence between /v1/images and /v1/chat/completions.
|
||||
if len(stage_configs) > 1:
|
||||
@@ -1930,7 +2072,6 @@ async def generate_images(
|
||||
"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)
|
||||
@@ -1984,7 +2125,7 @@ async def generate_images(
|
||||
)
|
||||
|
||||
# Build params - pass through user values directly
|
||||
prompt: OmniTextPrompt = {"prompt": request.prompt, "modalities": ["image"]}
|
||||
prompt = OmniTextPrompt(prompt=request.prompt, modalities=["image"])
|
||||
if request.negative_prompt is not None:
|
||||
prompt["negative_prompt"] = request.negative_prompt
|
||||
gen_params = OmniDiffusionSamplingParams(num_outputs_per_prompt=request.n)
|
||||
@@ -2000,12 +2141,11 @@ async def generate_images(
|
||||
if extra_args:
|
||||
gen_params.extra_args = extra_args
|
||||
# Parse per-request LoRA (compatible with chat's extra_body.lora shape).
|
||||
lora_request, lora_scale = _parse_lora_request(request.lora)
|
||||
lora_request, lora_scale = _parse_lora_request(request.lora) if request.lora is not None else (None, None)
|
||||
_update_if_not_none(gen_params, "lora_request", lora_request)
|
||||
_update_if_not_none(gen_params, "lora_scale", lora_scale)
|
||||
|
||||
# Parse and add size if provided
|
||||
width, height = None, None
|
||||
if request.size:
|
||||
width, height = parse_size(request.size)
|
||||
size_str = f"{width}x{height}"
|
||||
@@ -2171,9 +2311,9 @@ async def edit_images(
|
||||
try:
|
||||
# 2. Build prompt & images params
|
||||
cot_output = None
|
||||
prompt: OmniTextPrompt = {"prompt": prompt, "modalities": ["image"]}
|
||||
omni_prompt = OmniTextPrompt(prompt=prompt, modalities=["image"])
|
||||
if negative_prompt is not None:
|
||||
prompt["negative_prompt"] = negative_prompt
|
||||
omni_prompt["negative_prompt"] = negative_prompt
|
||||
input_images_list = []
|
||||
images = image or image_array
|
||||
urls = url or url_array
|
||||
@@ -2204,17 +2344,17 @@ async def edit_images(
|
||||
# Hunyuan-aware behavior. RGBA/P uploads otherwise diverge from offline.
|
||||
normalize_edit_images_rgb = bot_task is not None or sys_type is not None
|
||||
pil_images = await _load_input_images(input_images_list, normalize_rgb=normalize_edit_images_rgb)
|
||||
prompt["multi_modal_data"] = {}
|
||||
prompt["multi_modal_data"]["image"] = pil_images
|
||||
omni_prompt["multi_modal_data"] = {}
|
||||
omni_prompt["multi_modal_data"]["image"] = pil_images
|
||||
|
||||
if mask_image is not None:
|
||||
# Mask role is different (alpha channel matters); never normalize.
|
||||
loaded = await _load_input_images([mask_image], normalize_rgb=False)
|
||||
prompt["multi_modal_data"]["mask_image"] = loaded[0]
|
||||
omni_prompt["multi_modal_data"]["mask_image"] = loaded[0]
|
||||
|
||||
if reference_image is not None:
|
||||
loaded = await _load_input_images([reference_image], normalize_rgb=normalize_edit_images_rgb)
|
||||
prompt["multi_modal_data"]["reference_image"] = loaded[0]
|
||||
omni_prompt["multi_modal_data"]["reference_image"] = loaded[0]
|
||||
|
||||
# 3 Build sample params
|
||||
gen_params = OmniDiffusionSamplingParams()
|
||||
@@ -2280,16 +2420,18 @@ async def edit_images(
|
||||
# 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"] = {
|
||||
omni_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
|
||||
omni_prompt["height"] = height
|
||||
omni_prompt["width"] = width
|
||||
|
||||
_update_if_not_none(gen_params, "width", width)
|
||||
_update_if_not_none(gen_params, "height", height)
|
||||
gen_params.width_not_provided = size_was_auto
|
||||
gen_params.height_not_provided = size_was_auto
|
||||
|
||||
# 3.4 Add optional parameters ONLY if provided
|
||||
_update_if_not_none(gen_params, "num_inference_steps", num_inference_steps)
|
||||
@@ -2384,7 +2526,7 @@ async def edit_images(
|
||||
if return_stage_metrics is not None:
|
||||
extra_body["return_stage_metrics"] = return_stage_metrics
|
||||
|
||||
prompt_text = prompt.get("prompt", "")
|
||||
prompt_text = omni_prompt.get("prompt", "")
|
||||
generation_result = await chat_handler.generate_diffusion_images(
|
||||
prompt=prompt_text,
|
||||
extra_body=extra_body,
|
||||
@@ -2415,7 +2557,7 @@ async def edit_images(
|
||||
engine_client=engine_client,
|
||||
gen_params=gen_params,
|
||||
stage_configs=stage_configs,
|
||||
prompt=prompt,
|
||||
prompt=omni_prompt,
|
||||
request_id=request_id,
|
||||
)
|
||||
images = _extract_images_from_result(result)
|
||||
@@ -2423,6 +2565,8 @@ async def edit_images(
|
||||
peak_memory_mb = getattr(result, "peak_memory_mb", None)
|
||||
response_metrics = getattr(result, "metrics", None) if return_stage_metrics else None
|
||||
|
||||
if images is None:
|
||||
images = []
|
||||
logger.debug(f"Successfully generated {len(images)} image(s)")
|
||||
|
||||
# Encode images to base64
|
||||
@@ -2440,7 +2584,7 @@ async def edit_images(
|
||||
created=int(time.time()),
|
||||
data=image_data,
|
||||
output_format=output_format,
|
||||
size=size_str,
|
||||
size=_generated_size_str(images, size_str),
|
||||
cot_output=cot_output,
|
||||
metrics=_build_image_response_metrics(
|
||||
response_metrics=response_metrics,
|
||||
@@ -2466,6 +2610,7 @@ async def edit_images(
|
||||
|
||||
@router.post(
|
||||
"/v1/videos",
|
||||
dependencies=[Depends(_require_single_api_video_store)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"model": VideoResponse},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
@@ -2483,6 +2628,7 @@ async def create_video(
|
||||
ReferenceVideo | None,
|
||||
ReferenceAudio | None,
|
||||
str | None,
|
||||
LatentEditInput | None,
|
||||
] = Depends(_parse_video_form),
|
||||
) -> VideoResponse:
|
||||
"""Create an asynchronous video generation job.
|
||||
@@ -2498,6 +2644,7 @@ async def create_video(
|
||||
reference_video,
|
||||
reference_audio,
|
||||
control_path,
|
||||
latent_edit_input,
|
||||
) = ctx
|
||||
ref = video_response_from_request(effective_model_name, request)
|
||||
await VIDEO_STORE.upsert(ref.id, ref)
|
||||
@@ -2511,6 +2658,7 @@ async def create_video(
|
||||
reference_audio,
|
||||
control_path,
|
||||
app_state=raw_request.app.state,
|
||||
latent_edit_input=latent_edit_input,
|
||||
)
|
||||
)
|
||||
await VIDEO_TASKS.upsert(ref.id, task)
|
||||
@@ -2536,6 +2684,7 @@ async def create_video_sync(
|
||||
ReferenceVideo | None,
|
||||
ReferenceAudio | None,
|
||||
str | None,
|
||||
LatentEditInput | None,
|
||||
] = Depends(_parse_video_form),
|
||||
) -> Response:
|
||||
"""Synchronous video generation endpoint.
|
||||
@@ -2555,6 +2704,7 @@ async def create_video_sync(
|
||||
reference_video,
|
||||
reference_audio,
|
||||
control_path,
|
||||
latent_edit_input,
|
||||
) = ctx
|
||||
request_id = f"video_sync-{random_uuid()}"
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
@@ -2568,6 +2718,7 @@ async def create_video_sync(
|
||||
reference_image=reference_image,
|
||||
reference_video=reference_video,
|
||||
reference_audio=reference_audio,
|
||||
latent_edit_input=latent_edit_input,
|
||||
),
|
||||
timeout=VIDEO_SYNC_TIMEOUT_S,
|
||||
),
|
||||
@@ -2591,7 +2742,7 @@ async def create_video_sync(
|
||||
detail=f"Video generation failed: {str(exc)}",
|
||||
) from exc
|
||||
finally:
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path)
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path, latent_edit_input)
|
||||
inference_time_s = time.perf_counter() - started_at
|
||||
|
||||
return Response(
|
||||
@@ -2607,7 +2758,7 @@ async def create_video_sync(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/v1/videos", response_model=VideoListResponse)
|
||||
@router.get("/v1/videos", response_model=VideoListResponse, dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def list_videos(
|
||||
after: str | None = None,
|
||||
limit: int | None = Query(None, ge=0, le=100),
|
||||
@@ -2644,7 +2795,7 @@ 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}", response_model=None)
|
||||
@router.get("/v1/videos/{video_id}", response_model=None, dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
|
||||
"""Retrieve metadata for a previously created video job.
|
||||
|
||||
@@ -2672,7 +2823,7 @@ async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
|
||||
return job
|
||||
|
||||
|
||||
@router.delete("/v1/videos/{video_id}")
|
||||
@router.delete("/v1/videos/{video_id}", dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def delete_video(video_id: str, raw_request: Request) -> VideoDeleteResponse:
|
||||
"""Delete a stored video job and any generated output.
|
||||
|
||||
@@ -2742,7 +2893,7 @@ async def delete_video(video_id: str, raw_request: Request) -> VideoDeleteRespon
|
||||
return VideoDeleteResponse(id=job.id, deleted=True)
|
||||
|
||||
|
||||
@router.get("/v1/videos/{video_id}/content")
|
||||
@router.get("/v1/videos/{video_id}/content", dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def download_video(video_id: str) -> Response:
|
||||
"""Download the generated file for a completed video job.
|
||||
|
||||
@@ -2835,6 +2986,7 @@ async def stop_profile(raw_request: Request, request: ProfileRequest | None = No
|
||||
|
||||
@router.post("/v1/omni/sleep")
|
||||
async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Sleep")
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
sleeping_set = raw_request.app.state.sleeping_stages
|
||||
if not hasattr(engine_client, "sleep"):
|
||||
@@ -2842,11 +2994,15 @@ async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
|
||||
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]}
|
||||
return {
|
||||
"status": "SUCCESS",
|
||||
"acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) and not isinstance(a, type) else a for a in acks],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/v1/omni/wakeup")
|
||||
async def omni_wakeup(request: OmniWakeupRequest, raw_request: Request):
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Wakeup")
|
||||
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):
|
||||
@@ -2857,7 +3013,10 @@ async def omni_wakeup(request: OmniWakeupRequest, raw_request: Request):
|
||||
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]}
|
||||
return {
|
||||
"status": "SUCCESS",
|
||||
"acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) and not isinstance(a, type) else a for a in acks],
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -169,6 +169,14 @@ def _extract_images_from_result(result: Any) -> list[Any]:
|
||||
return [_normalize_image(img) for img in flattened]
|
||||
|
||||
|
||||
def _generated_size_str(images: list[Any], fallback: str | None) -> str | None:
|
||||
"""``"WxH"`` of the first generated image, or ``fallback`` when it is unknown."""
|
||||
size = getattr(images[0], "size", None) if images else None
|
||||
if isinstance(size, tuple) and len(size) == 2 and all(isinstance(value, Integral) for value in size):
|
||||
return f"{size[0]}x{size[1]}"
|
||||
return fallback
|
||||
|
||||
|
||||
async def _load_input_images(
|
||||
inputs: list[str],
|
||||
*,
|
||||
|
||||
@@ -248,10 +248,27 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
return obj.get(key, default)
|
||||
return getattr(obj, key, default)
|
||||
|
||||
@classmethod
|
||||
def _stage_model_metadata(cls, stage: Any) -> tuple[str | None, str | None]:
|
||||
"""Return ``(model_arch, model_stage)`` for typed or legacy stages."""
|
||||
model_config = cls._stage_get(stage, "model_config")
|
||||
model_arch = cls._stage_get(model_config, "model_arch")
|
||||
model_stage = cls._stage_get(stage, "model_stage")
|
||||
|
||||
topology = cls._stage_get(stage, "stage_pipeline_config")
|
||||
if model_stage is None:
|
||||
model_stage = cls._stage_get(topology, "model_stage")
|
||||
|
||||
engine_args = cls._stage_get(stage, "engine_args")
|
||||
if model_arch is None:
|
||||
model_arch = cls._stage_get(engine_args, "model_arch")
|
||||
if model_stage is None:
|
||||
model_stage = cls._stage_get(engine_args, "model_stage")
|
||||
return model_arch, model_stage
|
||||
|
||||
def _has_minicpmo45_stage(self) -> bool:
|
||||
for stage in getattr(self.engine_client, "stage_configs", []) or []:
|
||||
engine_args = self._stage_get(stage, "engine_args")
|
||||
model_arch = self._stage_get(engine_args, "model_arch")
|
||||
model_arch, _ = self._stage_model_metadata(stage)
|
||||
if model_arch == "MiniCPMO45OmniForConditionalGeneration":
|
||||
return True
|
||||
return False
|
||||
@@ -324,11 +341,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
if not hasattr(sp, "output_kind"):
|
||||
continue
|
||||
|
||||
engine_args = self._stage_get(stage, "engine_args")
|
||||
if self._stage_get(engine_args, "model_arch") != "MiniCPMO45OmniForConditionalGeneration":
|
||||
model_arch, model_stage = self._stage_model_metadata(stage)
|
||||
if model_arch != "MiniCPMO45OmniForConditionalGeneration":
|
||||
continue
|
||||
|
||||
model_stage = self._stage_get(engine_args, "model_stage")
|
||||
if model_stage == "llm":
|
||||
sp.output_kind = RequestOutputKind.FINAL_ONLY
|
||||
elif model_stage == "tts":
|
||||
@@ -802,6 +818,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
if _image_gen_height is not None and _image_gen_width is not None
|
||||
else None
|
||||
)
|
||||
self._apply_text_chat_ar_task_mode(sampling_params_list, request)
|
||||
# Apply user-specified overrides to diffusion stage(s) for image generation
|
||||
for idx, sp in enumerate(sampling_params_list):
|
||||
if idx == comprehension_idx:
|
||||
@@ -1377,6 +1394,34 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
and delta_message.tool_calls
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _apply_text_chat_ar_task_mode(
|
||||
sampling_params_list: list[Any],
|
||||
request: ChatCompletionRequest,
|
||||
) -> None:
|
||||
"""Mark AR stages of a text-only chat request as per-request comprehension.
|
||||
|
||||
A generation deployment (e.g. HunyuanImage3 AR+DiT with
|
||||
``engine_output_type="latent"``) also serves plain chat completions
|
||||
whose answer is text (I2T/T2T). Without a per-request marker the AR
|
||||
model sampler applies its image-generation stage transitions to those
|
||||
requests and leaks DiT scaffold tokens (``<recaption>``/``<answer>``/
|
||||
``<boi>``/``<img_size_*>``/``<cfg>``) into the text answer (#6088).
|
||||
|
||||
Sets ``extra_args["ar_task_mode"] = "comprehension"`` on every plain
|
||||
``SamplingParams`` stage when the request output is text-only. Does
|
||||
nothing for image/audio/video-output requests, never overrides an
|
||||
explicit caller-provided ``ar_task_mode``, and models that don't opt
|
||||
into reading extra_args are unaffected.
|
||||
"""
|
||||
if set(getattr(request, "modalities", None) or []) - {"text"}:
|
||||
return
|
||||
for sp in sampling_params_list:
|
||||
if isinstance(sp, SamplingParams) and not isinstance(sp, OmniDiffusionSamplingParams):
|
||||
extra_args = dict(getattr(sp, "extra_args", None) or {})
|
||||
extra_args.setdefault("ar_task_mode", "comprehension")
|
||||
sp.extra_args = extra_args
|
||||
|
||||
def _build_sampling_params_list_from_request(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
@@ -3126,13 +3171,6 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
if engine_prompt_data is not None:
|
||||
engine_prompt["multi_modal_data"] = engine_prompt_data
|
||||
# Provide multi_modal_uuids so that newer vLLM versions can
|
||||
# validate multi_modal_data / multi_modal_uuids consistency.
|
||||
# Generate one uuid per image when the value is a list (multi-image inputs).
|
||||
engine_prompt["multi_modal_uuids"] = {
|
||||
k: [f"img-{k}-{i}" for i in range(len(v))] if isinstance(v, list) else [f"img-{k}-0"]
|
||||
for k, v in engine_prompt_data.items()
|
||||
}
|
||||
|
||||
comprehension_idx = None
|
||||
for idx, stage in enumerate(stage_configs):
|
||||
|
||||
@@ -32,9 +32,11 @@ from vllm.entrypoints.launchers.launcher import terminate_if_errored
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.media import MediaConnector
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.config.stage_config import StagePipelineConfig
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin, StreamingAudioResampler
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
AudioResponse,
|
||||
@@ -75,6 +77,24 @@ _SPEECH_USAGE_TOTAL_TOKENS_HEADER = "X-VLLM-OMNI-TOTAL-TOKENS"
|
||||
_SPEECH_USAGE_INPUT_TEXT_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-TEXT-TOKENS"
|
||||
_SPEECH_USAGE_INPUT_AUDIO_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-AUDIO-TOKENS"
|
||||
|
||||
|
||||
def _stage_speech_metadata(stage: Any) -> tuple[str | None, str | None, str | None]:
|
||||
"""Return speech routing metadata from typed or legacy stage configs."""
|
||||
topology = getattr(stage, "stage_pipeline_config", None)
|
||||
if isinstance(topology, StagePipelineConfig):
|
||||
return (
|
||||
getattr(topology, "model_stage", None),
|
||||
getattr(getattr(stage, "model_config", None), "model_arch", None),
|
||||
getattr(stage, "worker_type", None),
|
||||
)
|
||||
engine_args = getattr(stage, "engine_args", None)
|
||||
return (
|
||||
getattr(engine_args, "model_stage", None),
|
||||
getattr(engine_args, "model_arch", None),
|
||||
getattr(engine_args, "worker_type", None),
|
||||
)
|
||||
|
||||
|
||||
# TTS Configuration
|
||||
#
|
||||
# The stage-key -> model-type mapping is NOT declared here: it is derived from
|
||||
@@ -90,8 +110,8 @@ _REF_AUDIO_MIN_DURATION = 1.0 # seconds
|
||||
_REF_AUDIO_MAX_DURATION = 30.0 # seconds
|
||||
_REF_AUDIO_METADATA_FETCH_ATTEMPTS = 3
|
||||
_REMOTE_REF_AUDIO_SCHEMES = frozenset({"http", "https", "data"})
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_ENTRIES = 256
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_BYTES = 256 * 1024 * 1024
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_ENTRIES = 1024
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_BYTES = 512 * 1024 * 1024
|
||||
_TTS_MAX_INSTRUCTIONS_LENGTH = 500
|
||||
_DEFAULT_VOICE_NAME = "default"
|
||||
|
||||
@@ -228,7 +248,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
self._max_uploaded_speakers = 1000
|
||||
self.uploaded_speakers: dict[str, dict[str, Any]] = {}
|
||||
self._ref_audio_data_url_cache: dict[str, str] = {}
|
||||
self._ref_audio_resolve_cache: OrderedDict[str, tuple[list[float], int, int, str]] = OrderedDict()
|
||||
self._ref_audio_resolve_cache: OrderedDict[str, tuple[np.ndarray, int, int, str]] = OrderedDict()
|
||||
self._ref_audio_resolve_cache_bytes = 0
|
||||
self._ref_audio_resolve_cache_max_entries = _REF_AUDIO_RESOLVE_CACHE_MAX_ENTRIES
|
||||
self._ref_audio_resolve_cache_max_bytes = _REF_AUDIO_RESOLVE_CACHE_MAX_BYTES
|
||||
@@ -471,12 +491,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"""Find and return the TTS stage config, or None if not found."""
|
||||
tts_stage_keys = all_tts_stage_keys()
|
||||
entry_stage_archs = tts_entry_stage_archs()
|
||||
all_stages = frozenset(stage.engine_args.model_stage for stage in self.engine_client.stage_configs)
|
||||
all_stages = frozenset(
|
||||
model_stage
|
||||
for stage in self.engine_client.stage_configs
|
||||
if (model_stage := _stage_speech_metadata(stage)[0]) is not None
|
||||
)
|
||||
for stage in self.engine_client.stage_configs:
|
||||
engine_args = stage.engine_args
|
||||
model_stage = engine_args.model_stage
|
||||
model_arch = getattr(engine_args, "model_arch", None)
|
||||
worker_type = getattr(engine_args, "worker_type", None)
|
||||
model_stage, model_arch, worker_type = _stage_speech_metadata(stage)
|
||||
if model_stage in tts_stage_keys:
|
||||
# Owning the stage key is not always enough: a model may be
|
||||
# speech-capable only in some deployment topologies. Ask the
|
||||
@@ -500,10 +521,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"""
|
||||
if self._tts_stage is None:
|
||||
return None
|
||||
return detect_tts_model_type(
|
||||
getattr(self._tts_stage.engine_args, "model_stage", None),
|
||||
getattr(self._tts_stage.engine_args, "model_arch", None),
|
||||
)
|
||||
return detect_tts_model_type(*_stage_speech_metadata(self._tts_stage)[:2])
|
||||
|
||||
def _compute_max_instructions_length(self) -> int:
|
||||
"""Compute max instructions length with precedence: CLI > stage config > default.
|
||||
@@ -517,7 +535,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
# 2. Try to get from TTS stage config
|
||||
if self._tts_stage is not None:
|
||||
tts_args = getattr(self._tts_stage, "tts_args", {})
|
||||
topology = getattr(self._tts_stage, "stage_pipeline_config", None)
|
||||
tts_args = (
|
||||
getattr(topology, "extras", {}).get("tts_args", {})
|
||||
if isinstance(topology, StagePipelineConfig)
|
||||
else getattr(self._tts_stage, "tts_args", {})
|
||||
)
|
||||
if "max_instructions_length" in tts_args:
|
||||
return tts_args["max_instructions_length"]
|
||||
|
||||
@@ -1199,7 +1222,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
allowed_local_media_path,
|
||||
)
|
||||
|
||||
def _finalize_fetched_ref_audio(self, wav_np: np.ndarray, sr: int) -> tuple[list[float], int, str, float]:
|
||||
def _finalize_fetched_ref_audio(self, wav_np: np.ndarray, sr: int) -> tuple[np.ndarray, int, str, float]:
|
||||
wav_np = np.asarray(wav_np, dtype=np.float32)
|
||||
if wav_np.ndim > 1:
|
||||
wav_np = np.mean(wav_np, axis=-1)
|
||||
@@ -1215,12 +1238,26 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
f"Reference audio too long ({duration:.1f}s). "
|
||||
f"Maximum {_REF_AUDIO_MAX_DURATION:.0f}s supported — use a shorter clip."
|
||||
)
|
||||
artifact_key = self._make_ref_audio_artifact_cache_key(wav_np, sr)
|
||||
return wav_np.tolist(), sr, artifact_key, duration
|
||||
# Own the buffer: a view could retain a much larger decoded allocation.
|
||||
waveform = np.array(wav_np, dtype=np.float32, order="C", copy=True)
|
||||
artifact_key = self._make_ref_audio_artifact_cache_key(waveform, sr)
|
||||
return waveform, sr, artifact_key, duration
|
||||
|
||||
async def _resolve_ref_audio(self, ref_audio_str: str) -> tuple[list[float], int, str]:
|
||||
"""Keep list-based consumers and their engine transport compatible.
|
||||
|
||||
Only the numeric array is cached; this temporary list belongs to the
|
||||
caller. Server-side reference encoders should use the array resolver.
|
||||
"""
|
||||
waveform, sr, cache_key = await self._resolve_ref_audio_array(ref_audio_str)
|
||||
return waveform.tolist(), sr, cache_key
|
||||
|
||||
async def _resolve_ref_audio_array(self, ref_audio_str: str) -> tuple[np.ndarray, int, str]:
|
||||
"""Resolve ref_audio to (wav_samples, sample_rate, cache_key).
|
||||
|
||||
The float32 array can be shared with the cache. Callers must not mutate
|
||||
it; copy before any in-place processing.
|
||||
|
||||
Delegates to upstream vLLM's MediaConnector which handles http(s)
|
||||
URLs, ``data:`` base64 URIs, and ``file:`` local paths (the latter
|
||||
gated by ``--allowed-local-media-path``).
|
||||
@@ -1243,7 +1280,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
else:
|
||||
allowed_path = getattr(self.model_config, "allowed_local_media_path", None)
|
||||
|
||||
wav_list: list[float] | None = None
|
||||
waveform: np.ndarray | None = None
|
||||
sr = 0
|
||||
artifact_key = ""
|
||||
post_key = ""
|
||||
@@ -1252,14 +1289,14 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
cached = self._ref_audio_resolve_cache.get(cache_key)
|
||||
if cached is not None:
|
||||
self._ref_audio_resolve_cache.move_to_end(cache_key)
|
||||
wav_list, sr, _, _ = cached
|
||||
waveform, sr, _, _ = cached
|
||||
logger.debug(
|
||||
"Resolved ref_audio from cache: samples=%d sr=%d duration_s=%.3f",
|
||||
len(wav_list),
|
||||
len(waveform),
|
||||
sr,
|
||||
len(wav_list) / sr if sr > 0 else 0.0,
|
||||
len(waveform) / sr if sr > 0 else 0.0,
|
||||
)
|
||||
return wav_list, sr, cache_key
|
||||
return waveform, sr, cache_key
|
||||
|
||||
if self._media_connector is None:
|
||||
model_config = self.model_config
|
||||
@@ -1271,21 +1308,21 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
fetch_start_s = time.perf_counter()
|
||||
wav_np, fetched_sr = await self._media_connector.fetch_audio_async(ref_audio_str)
|
||||
fetch_decode_ms = (time.perf_counter() - fetch_start_s) * 1000.0
|
||||
tolist_start_s = time.perf_counter()
|
||||
wav_list, sr, artifact_key, duration = self._finalize_fetched_ref_audio(wav_np, fetched_sr)
|
||||
tolist_ms = (time.perf_counter() - tolist_start_s) * 1000.0
|
||||
finalize_start_s = time.perf_counter()
|
||||
waveform, sr, artifact_key, duration = self._finalize_fetched_ref_audio(wav_np, fetched_sr)
|
||||
finalize_ms = (time.perf_counter() - finalize_start_s) * 1000.0
|
||||
logger.debug(
|
||||
"Resolved ref_audio: fetch_decode_ms=%.3f tolist_ms=%.3f samples=%d sr=%d duration_s=%.3f",
|
||||
"Resolved ref_audio: fetch_decode_ms=%.3f finalize_ms=%.3f samples=%d sr=%d duration_s=%.3f",
|
||||
fetch_decode_ms,
|
||||
tolist_ms,
|
||||
len(wav_list),
|
||||
finalize_ms,
|
||||
len(waveform),
|
||||
sr,
|
||||
duration,
|
||||
)
|
||||
post_key = await self._ref_audio_cache_key(ref_audio_str, allowed_path)
|
||||
if post_key == cache_key:
|
||||
self._put_resolved_ref_audio(cache_key, wav_list, sr, artifact_key)
|
||||
return wav_list, sr, cache_key
|
||||
self._put_resolved_ref_audio(cache_key, waveform, sr, artifact_key)
|
||||
return waveform, sr, cache_key
|
||||
logger.debug(
|
||||
"ref_audio metadata changed during fetch (attempt %d/%d); retrying",
|
||||
attempt + 1,
|
||||
@@ -1296,8 +1333,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"ref_audio file changed during fetch after %d attempts; skipping resolve cache",
|
||||
_REF_AUDIO_METADATA_FETCH_ATTEMPTS,
|
||||
)
|
||||
assert wav_list is not None and post_key
|
||||
return wav_list, sr, post_key
|
||||
assert waveform is not None and post_key
|
||||
return waveform, sr, post_key
|
||||
|
||||
@staticmethod
|
||||
def _make_ref_audio_artifact_cache_key(wav: np.ndarray, sr: int) -> str:
|
||||
@@ -1322,12 +1359,18 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
self._ref_audio_resolve_cache.move_to_end(cache_key)
|
||||
return cached[3]
|
||||
|
||||
def _put_resolved_ref_audio(self, cache_key: str, wav_list: list[float], sr: int, artifact_key: str) -> None:
|
||||
def _put_resolved_ref_audio(
|
||||
self, cache_key: str, waveform: np.ndarray | list[float], sr: int, artifact_key: str
|
||||
) -> None:
|
||||
if self._ref_audio_resolve_cache_max_entries <= 0 or self._ref_audio_resolve_cache_max_bytes <= 0:
|
||||
return
|
||||
# Approximate list[float] storage. CPython float objects add per-element
|
||||
# overhead, so max_entries remains the hard cache cap.
|
||||
size = len(wav_list) * 40
|
||||
# Keep the finalized ndarray's ownership and identity for the array
|
||||
# resolver. Legacy list callers are materialized into a compact array;
|
||||
# their Python list remains independent from cached storage.
|
||||
waveform = np.asarray(waveform, dtype=np.float32)
|
||||
if not waveform.flags.c_contiguous:
|
||||
waveform = np.ascontiguousarray(waveform)
|
||||
size = int(waveform.nbytes)
|
||||
if size > self._ref_audio_resolve_cache_max_bytes:
|
||||
return
|
||||
previous = self._ref_audio_resolve_cache.pop(cache_key, None)
|
||||
@@ -1335,7 +1378,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
self._ref_audio_resolve_cache_bytes -= previous[2]
|
||||
if previous[3] != artifact_key:
|
||||
self._discard_ref_audio_artifact_ready_if_unreferenced(previous[3])
|
||||
self._ref_audio_resolve_cache[cache_key] = (wav_list, int(sr), size, artifact_key)
|
||||
self._ref_audio_resolve_cache[cache_key] = (waveform, int(sr), size, artifact_key)
|
||||
self._ref_audio_resolve_cache_bytes += size
|
||||
while len(self._ref_audio_resolve_cache) > self._ref_audio_resolve_cache_max_entries:
|
||||
_, (_, _, old_size, old_artifact_key) = self._ref_audio_resolve_cache.popitem(last=False)
|
||||
@@ -1444,14 +1487,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
tts_params: dict[str, Any] | None = None,
|
||||
collect: dict | None = None,
|
||||
target_sample_rate: int | None = None,
|
||||
cumulative_audio: bool = False,
|
||||
):
|
||||
"""Generate audio chunks for streaming response.
|
||||
|
||||
Handles two audio output modes from the engine:
|
||||
- Cumulative mode (list): Engine returns growing list of chunks;
|
||||
we emit only the new tail on each iteration.
|
||||
- Per-step mode (tensor): Engine returns single tensor per iteration;
|
||||
we emit it directly.
|
||||
- Tensor mode: Emit each tensor directly, or only its new samples when
|
||||
cumulative_audio is set for requests that retain audio for alignment.
|
||||
|
||||
Args:
|
||||
generator: Async generator from the engine
|
||||
@@ -1462,6 +1506,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
Raw audio bytes for each chunk (with WAV header for first chunk if wav format)
|
||||
"""
|
||||
prev_count = 0
|
||||
emitted_samples = 0
|
||||
sample_rate_val = 24000
|
||||
first_chunk = True
|
||||
first_audio_chunk_s: float | None = None
|
||||
@@ -1563,6 +1608,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
)
|
||||
if chunk_np.ndim > 1:
|
||||
chunk_np = chunk_np.squeeze()
|
||||
if cumulative_audio and not isinstance(audio_val, list):
|
||||
total_samples = chunk_np.shape[-1]
|
||||
chunk_np = chunk_np[..., emitted_samples:]
|
||||
emitted_samples = total_samples
|
||||
if chunk_np.size == 0:
|
||||
continue
|
||||
if resampler is not None:
|
||||
chunk_np = resampler.process(chunk_np)
|
||||
if chunk_np.size == 0:
|
||||
@@ -1887,9 +1938,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
# chat-template markers (im_start_token_id 151644). A raw-text
|
||||
# prompt produces a 1-token placeholder that crashes the talker's
|
||||
# prefill/decode handoff. Reject early with an actionable message.
|
||||
stage_names = {
|
||||
getattr(getattr(s, "engine_args", None), "model_stage", None) for s in self.engine_client.stage_configs
|
||||
}
|
||||
stage_names = {_stage_speech_metadata(s)[0] for s in self.engine_client.stage_configs}
|
||||
if "talker" in stage_names:
|
||||
raise ValueError(
|
||||
"The /v1/audio/speech endpoint is only supported for "
|
||||
@@ -1957,6 +2006,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
from vllm_omni.model_executor.stage_input_processors.forced_aligner import TIMESTAMPS_MODALITY
|
||||
|
||||
output_modalities.append(TIMESTAMPS_MODALITY)
|
||||
if is_streaming_request:
|
||||
# The aligner consumes the terminal waveform, so retain earlier
|
||||
# audio chunks instead of draining them after each DELTA output.
|
||||
sampling_params_list = [
|
||||
sp.clone() if isinstance(sp, SamplingParams) else sp for sp in sampling_params_list
|
||||
]
|
||||
for sp in sampling_params_list:
|
||||
if isinstance(sp, SamplingParams):
|
||||
sp.output_kind = RequestOutputKind.CUMULATIVE
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
prompt=prompt,
|
||||
@@ -1990,6 +2048,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
tts_params: dict[str, Any] | None = None,
|
||||
collect: dict | None = None,
|
||||
target_sample_rate: int | None = None,
|
||||
cumulative_audio: bool = False,
|
||||
):
|
||||
"""Yield raw PCM byte chunks from the engine generator.
|
||||
|
||||
@@ -2009,6 +2068,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
tts_params=tts_params,
|
||||
collect=collect,
|
||||
target_sample_rate=target_sample_rate,
|
||||
cumulative_audio=cumulative_audio,
|
||||
)
|
||||
) as chunks:
|
||||
async for chunk in chunks:
|
||||
@@ -2024,6 +2084,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
request_id,
|
||||
tts_params=tts_params,
|
||||
target_sample_rate=request.sample_rate,
|
||||
cumulative_audio=request.word_timestamps,
|
||||
)
|
||||
) as chunks:
|
||||
async for chunk in chunks:
|
||||
|
||||
@@ -483,6 +483,7 @@ class OmniStreamingSpeechHandler:
|
||||
include_sample_rate=True,
|
||||
tts_params=tts_params,
|
||||
collect=collect,
|
||||
cumulative_audio=True,
|
||||
)
|
||||
) as stream:
|
||||
async for chunk, chunk_sample_rate in stream:
|
||||
|
||||
@@ -20,7 +20,7 @@ from vllm.engine.protocol import EngineClient
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import is_diffusion_request_started_output
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.model_metadata import DiffusionModelMetadata, get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.utils.media_utils import count_mp4_frames, normalize_preencode_batch_frames
|
||||
from vllm_omni.entrypoints.async_omni import ABORT_TIMEOUT_S, AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
@@ -53,6 +53,30 @@ logger = init_logger(__name__)
|
||||
|
||||
_VIDEO_RESPONSE_FRAME_CONVERSION_WORKERS = 8
|
||||
|
||||
|
||||
def _config_value(config: Any, key: str, default: Any = None) -> Any:
|
||||
if isinstance(config, Mapping):
|
||||
return config.get(key, default)
|
||||
return getattr(config, key, default)
|
||||
|
||||
|
||||
def _stage_diffusion_model_class_name(stage_config: Any) -> str | None:
|
||||
"""Resolve a stage's diffusion class across typed and legacy shapes."""
|
||||
diffusion_config = _config_value(stage_config, "diffusion_config")
|
||||
model_class_name = _config_value(diffusion_config, "model_class_name")
|
||||
if model_class_name:
|
||||
return str(model_class_name)
|
||||
|
||||
model_config = _config_value(stage_config, "model_config")
|
||||
model_arch = _config_value(model_config, "model_arch") or _config_value(stage_config, "model_arch")
|
||||
if model_arch:
|
||||
return str(model_arch)
|
||||
|
||||
engine_args = _config_value(stage_config, "engine_args", {})
|
||||
model_class_name = _config_value(engine_args, "model_class_name")
|
||||
return str(model_class_name) if model_class_name else None
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
@@ -80,6 +104,17 @@ class ReferenceAudio:
|
||||
cleanup_paths: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class LatentEditInput:
|
||||
"""Request-scoped source media and masks for latent-mask editing."""
|
||||
|
||||
source_video: str | None = None
|
||||
source_audio: str | None = None
|
||||
video_noise_mask: Any | None = None
|
||||
audio_noise_mask: Any | None = None
|
||||
cleanup_paths: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class VideoGenerationArtifacts:
|
||||
"""Normalized outputs and profiler metadata extracted from one request."""
|
||||
@@ -143,6 +178,15 @@ class OmniOpenAIServingVideo:
|
||||
return get_od_config()
|
||||
return getattr(self._engine_client, "od_config", None)
|
||||
|
||||
def _resolve_diffusion_metadata(
|
||||
self,
|
||||
) -> tuple[OmniDiffusionConfig | SimpleNamespace | None, tuple[DiffusionModelMetadata, ...]]:
|
||||
"""Resolve capability metadata from the runtime and diffusion stages."""
|
||||
od_config = self._resolve_diffusion_od_config()
|
||||
model_archs = [None if od_config is None else getattr(od_config, "model_class_name", None)]
|
||||
model_archs.extend(_stage_diffusion_model_class_name(stage) for stage in self.stage_configs or ())
|
||||
return od_config, tuple(get_diffusion_model_metadata(model_arch) for model_arch in model_archs)
|
||||
|
||||
def _resolve_video_generation_defaults(
|
||||
self,
|
||||
request: VideoGenerationRequest,
|
||||
@@ -187,30 +231,18 @@ class OmniOpenAIServingVideo:
|
||||
@property
|
||||
def supports_mixed_reference_inputs(self) -> bool:
|
||||
"""Return whether the configured diffusion model accepts mixed refs."""
|
||||
od_config = self._resolve_diffusion_od_config()
|
||||
od_config, metadata = self._resolve_diffusion_metadata()
|
||||
if od_config is None:
|
||||
return False
|
||||
|
||||
capability = getattr(od_config, "supports_mixed_reference_inputs", None)
|
||||
model_class_name = getattr(od_config, "model_class_name", None)
|
||||
model_archs = [model_class_name]
|
||||
for stage_config in self.stage_configs or ():
|
||||
stage_get = (
|
||||
stage_config.get if isinstance(stage_config, Mapping) else lambda key: getattr(stage_config, key, None)
|
||||
)
|
||||
engine_args = stage_get("engine_args") or {}
|
||||
model_archs.extend(
|
||||
(
|
||||
stage_get("model_arch"),
|
||||
engine_args.get("model_class_name")
|
||||
if isinstance(engine_args, Mapping)
|
||||
else getattr(engine_args, "model_class_name", None),
|
||||
)
|
||||
)
|
||||
metadata_capability = any(
|
||||
get_diffusion_model_metadata(model_arch).supports_mixed_reference_inputs for model_arch in model_archs
|
||||
)
|
||||
return capability is True or metadata_capability
|
||||
return capability is True or any(item.supports_mixed_reference_inputs for item in metadata)
|
||||
|
||||
@property
|
||||
def supports_latent_mask_editing(self) -> bool:
|
||||
"""Return whether the configured diffusion model accepts latent edits."""
|
||||
_, metadata = self._resolve_diffusion_metadata()
|
||||
return any(item.supports_latent_mask_editing for item in metadata)
|
||||
|
||||
@property
|
||||
def supported_control_upload_types(self) -> frozenset[str]:
|
||||
@@ -220,25 +252,11 @@ class OmniOpenAIServingVideo:
|
||||
generic video API isolated from model-specific controls unless a model
|
||||
explicitly opts into the ``control_path`` contract in metadata.
|
||||
"""
|
||||
od_config = self._resolve_diffusion_od_config()
|
||||
model_archs = [None if od_config is None else getattr(od_config, "model_class_name", None)]
|
||||
for stage_config in self.stage_configs or ():
|
||||
stage_get = (
|
||||
stage_config.get if isinstance(stage_config, Mapping) else lambda key: getattr(stage_config, key, None)
|
||||
)
|
||||
engine_args = stage_get("engine_args") or {}
|
||||
model_archs.extend(
|
||||
(
|
||||
stage_get("model_arch"),
|
||||
engine_args.get("model_class_name")
|
||||
if isinstance(engine_args, Mapping)
|
||||
else getattr(engine_args, "model_class_name", None),
|
||||
)
|
||||
)
|
||||
_, metadata = self._resolve_diffusion_metadata()
|
||||
|
||||
supported: set[str] = set()
|
||||
for model_arch in model_archs:
|
||||
supported.update(get_diffusion_model_metadata(model_arch).supported_control_upload_types)
|
||||
for item in metadata:
|
||||
supported.update(item.supported_control_upload_types)
|
||||
return frozenset(supported)
|
||||
|
||||
@classmethod
|
||||
@@ -269,6 +287,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_video: ReferenceVideo | None = None,
|
||||
reference_audio: ReferenceAudio | None = None,
|
||||
on_started: Callable[[], Awaitable[None]] | None = None,
|
||||
latent_edit_input: LatentEditInput | None = None,
|
||||
) -> VideoGenerationArtifacts:
|
||||
"""Run the generation pipeline and extract video/audio/profiler outputs."""
|
||||
prompt: OmniTextPrompt = OmniTextPrompt(prompt=request.prompt, modalities=["video"])
|
||||
@@ -349,6 +368,19 @@ class OmniOpenAIServingVideo:
|
||||
multi_modal_data["video"] = input_video
|
||||
if reference_audio is not None:
|
||||
multi_modal_data["audio"] = reference_audio.path
|
||||
if latent_edit_input is not None:
|
||||
multi_modal_data.update(
|
||||
{
|
||||
key: value
|
||||
for key, value in {
|
||||
"source_video": latent_edit_input.source_video,
|
||||
"source_audio": latent_edit_input.source_audio,
|
||||
"video_noise_mask": latent_edit_input.video_noise_mask,
|
||||
"audio_noise_mask": latent_edit_input.audio_noise_mask,
|
||||
}.items()
|
||||
if value is not None
|
||||
}
|
||||
)
|
||||
if multi_modal_data:
|
||||
prompt["multi_modal_data"] = multi_modal_data
|
||||
if vp.width is not None and vp.height is not None:
|
||||
@@ -487,6 +519,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_image: ReferenceImage | None = None,
|
||||
reference_video: ReferenceVideo | None = None,
|
||||
reference_audio: ReferenceAudio | None = None,
|
||||
latent_edit_input: LatentEditInput | None = None,
|
||||
) -> VideoGenerationResponse:
|
||||
artifacts = await self._run_and_extract(
|
||||
request,
|
||||
@@ -494,6 +527,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_image=reference_image,
|
||||
reference_video=reference_video,
|
||||
reference_audio=reference_audio,
|
||||
latent_edit_input=latent_edit_input,
|
||||
)
|
||||
|
||||
video_codec_options = {"preset": "ultrafast", "threads": "0"}
|
||||
@@ -539,6 +573,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_video: ReferenceVideo | None = None,
|
||||
reference_audio: ReferenceAudio | None = None,
|
||||
on_started: Callable[[], Awaitable[None]] | None = None,
|
||||
latent_edit_input: LatentEditInput | None = None,
|
||||
) -> tuple[bytes, dict[str, float], float, VideoAction | None, dict[str, object]]:
|
||||
"""Generate a video and return raw MP4 bytes, bypassing base64 encoding."""
|
||||
artifacts = await self._run_and_extract(
|
||||
@@ -548,6 +583,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_video=reference_video,
|
||||
reference_audio=reference_audio,
|
||||
on_started=on_started,
|
||||
latent_edit_input=latent_edit_input,
|
||||
)
|
||||
if len(artifacts.videos) > 1:
|
||||
logger.warning(
|
||||
|
||||
@@ -362,15 +362,41 @@ class OmniStreamingVideoOutputHandler:
|
||||
if not isinstance(event, dict):
|
||||
await self._send_error(websocket, "session.interaction requires event object", send_lock=send_lock)
|
||||
return
|
||||
|
||||
prompt = event.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt.strip():
|
||||
multi_modal_data = event.get("multi_modal_data")
|
||||
has_prompt = isinstance(prompt, str) and bool(prompt.strip())
|
||||
has_mm = isinstance(multi_modal_data, dict) and bool(multi_modal_data)
|
||||
if not has_prompt and not has_mm:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction requires a non-empty event.prompt",
|
||||
"session.interaction requires a non-empty event.prompt and/or non-empty event.multi_modal_data",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
if "prompt" in event and prompt is not None and not has_prompt:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction event.prompt must be a non-empty string when provided",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
if "multi_modal_data" in event and multi_modal_data is not None and not has_mm:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction event.multi_modal_data must be a non-empty object when provided",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
if has_mm:
|
||||
assert isinstance(multi_modal_data, dict)
|
||||
for modality, payload in multi_modal_data.items():
|
||||
if not isinstance(payload, dict):
|
||||
await self._send_error(
|
||||
websocket,
|
||||
f"session.interaction multi_modal_data[{modality!r}] must be an object",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
if "negative_prompt" in event and event["negative_prompt"] is not None:
|
||||
await self._send_error(
|
||||
@@ -380,9 +406,19 @@ class OmniStreamingVideoOutputHandler:
|
||||
)
|
||||
return
|
||||
|
||||
normalized_event: dict[str, Any] = {}
|
||||
if has_prompt:
|
||||
normalized_event["prompt"] = prompt
|
||||
if has_mm:
|
||||
normalized_event["multi_modal_data"] = multi_modal_data
|
||||
# Preserve other event fields that OmniInteractionEvent may carry.
|
||||
for key, value in event.items():
|
||||
if key not in normalized_event and key not in ("prompt", "multi_modal_data"):
|
||||
normalized_event[key] = value
|
||||
|
||||
normalized: OmniInteractionPrompt = {
|
||||
"event_id": event_id,
|
||||
"event": cast(OmniInteractionEvent, event),
|
||||
"event": cast(OmniInteractionEvent, normalized_event),
|
||||
}
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
if transition_chunks is not None:
|
||||
@@ -572,8 +608,11 @@ class OmniStreamingVideoOutputHandler:
|
||||
@staticmethod
|
||||
async def _decode_image_reference(request: VideoGenerationRequest) -> Image.Image | None:
|
||||
try:
|
||||
image_reference = request.image_reference
|
||||
if isinstance(image_reference, list):
|
||||
raise InvalidInputReferenceError("image_reference must be a single image reference.")
|
||||
media_data = await decode_input_reference(
|
||||
request.image_reference,
|
||||
image_reference,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -108,7 +108,6 @@ from vllm_omni.entrypoints.openai.tts_adapters import ( # noqa: E402,F401
|
||||
breeze_tts_2,
|
||||
cosyvoice3,
|
||||
covo_audio,
|
||||
dots_tts,
|
||||
fish_speech,
|
||||
gepard,
|
||||
glm_tts,
|
||||
|
||||
@@ -42,7 +42,11 @@ class AudexAdapter(ARTTSAdapter):
|
||||
|
||||
from vllm_omni.model_executor.models.audex.checkpoint import ensure_audex_snapshot
|
||||
|
||||
stage = getattr(getattr(self.ctx.server._tts_stage, "engine_args", None), "model_stage", None)
|
||||
stage_config = self.ctx.server._tts_stage
|
||||
topology = getattr(stage_config, "stage_pipeline_config", None)
|
||||
stage = getattr(topology, "model_stage", None)
|
||||
if stage is None:
|
||||
stage = getattr(getattr(stage_config, "engine_args", None), "model_stage", None)
|
||||
profile, folder = (
|
||||
("full", "checkpoint_folder_full") if stage == "audex_omni" else ("tts", "checkpoint_folder_audiogen")
|
||||
)
|
||||
|
||||
@@ -39,6 +39,21 @@ DEFAULT_TTS_LANGUAGES = frozenset(
|
||||
)
|
||||
|
||||
|
||||
def resolve_stage_model_path(engine_client: Any) -> str | None:
|
||||
"""Prefer typed stage model overrides, then legacy and served-model values."""
|
||||
stages = getattr(engine_client, "stage_configs", ()) or ()
|
||||
for stage in stages:
|
||||
model_path = getattr(getattr(stage, "model_config", None), "model", None)
|
||||
if model_path:
|
||||
return str(model_path)
|
||||
for stage in stages:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
return str(model_path)
|
||||
model_path = getattr(engine_client, "model", None)
|
||||
return str(model_path) if model_path else None
|
||||
|
||||
|
||||
def conditioning_cache_salt(request: "OpenAICreateSpeechRequest", tts_params: dict | None = None) -> str:
|
||||
"""Stable hash of the real Stage 0 conditioning for the prefix cache.
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
"""Breeze-TTS-2 serving adapter for synchronous full-payload generation."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import math
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
@@ -49,6 +51,7 @@ class BreezeTTS2Adapter(ARTTSAdapter):
|
||||
return set()
|
||||
|
||||
def _load_codec_frame_rate(self) -> float | None:
|
||||
assert self.ctx.engine_client is not None
|
||||
config = self.ctx.engine_client.model_config.hf_config
|
||||
codec = getattr(config, "codec_config", None)
|
||||
if isinstance(codec, dict):
|
||||
@@ -99,6 +102,14 @@ class BreezeTTS2Adapter(ARTTSAdapter):
|
||||
greedy_error = _validate_greedy_sampling(extra_params)
|
||||
if greedy_error is not None:
|
||||
return greedy_error
|
||||
repetition_penalty = extra_params.get("repetition_penalty")
|
||||
if repetition_penalty is not None:
|
||||
try:
|
||||
repetition_penalty = float(repetition_penalty)
|
||||
except (TypeError, ValueError):
|
||||
return "Breeze-TTS-2 repetition_penalty must be finite and positive"
|
||||
if not math.isfinite(repetition_penalty) or repetition_penalty <= 0:
|
||||
return "Breeze-TTS-2 repetition_penalty must be finite and positive"
|
||||
if request.max_new_tokens is not None:
|
||||
if request.max_new_tokens < self.max_new_tokens_min:
|
||||
return f"max_new_tokens must be at least {self.max_new_tokens_min}"
|
||||
@@ -210,7 +221,16 @@ class BreezeTTS2Adapter(ARTTSAdapter):
|
||||
request_id: str | None = None,
|
||||
) -> list:
|
||||
del prompt, request_id
|
||||
return apply_max_new_tokens(sampling_params_list, request)
|
||||
sampling_params_list = apply_max_new_tokens(sampling_params_list, request)
|
||||
repetition_penalty = (request.extra_params or {}).get("repetition_penalty")
|
||||
if repetition_penalty is not None:
|
||||
# The generic speech handler copies extra_params to extra_args;
|
||||
# promote this value so the worker receives sampling metadata.
|
||||
# Only this scalar changes; preserve the caller's params without
|
||||
# copying nested state or the unchanged codec-stage parameters.
|
||||
sampling_params_list = [copy.copy(sampling_params_list[0]), *sampling_params_list[1:]]
|
||||
sampling_params_list[0].repetition_penalty = float(repetition_penalty)
|
||||
return sampling_params_list
|
||||
|
||||
|
||||
def _validate_greedy_sampling(extra_params: dict[str, Any]) -> str | None:
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""dots.tts serving adapter."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from transformers import AutoTokenizer
|
||||
from vllm.utils.async_utils import make_async
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import ARTTSAdapter, PreparedRequest, apply_max_new_tokens
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
|
||||
|
||||
|
||||
@register_tts_adapter
|
||||
class DotsTTSAdapter(ARTTSAdapter):
|
||||
"""Adapter for dots.tts (AR ``engine_client`` backend).
|
||||
|
||||
The current integration supports text-only, no-reference speech synthesis.
|
||||
Voice cloning and reference-audio conditioning are not supported yet.
|
||||
"""
|
||||
|
||||
stage_keys = frozenset()
|
||||
model_archs = frozenset({"DotsTTSForConditionalGeneration"})
|
||||
name = "dots_tts"
|
||||
detect_priority = 5
|
||||
|
||||
def __init__(self, ctx):
|
||||
super().__init__(ctx)
|
||||
self.tokenizer = None
|
||||
self._build_prompt_async = None
|
||||
|
||||
def _build_prompt(self, text: str) -> dict:
|
||||
from vllm_omni.model_executor.models.dots_tts.dots_tts_prompt import build_dots_tts_prompt
|
||||
|
||||
if self.tokenizer is None:
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(
|
||||
self.ctx.engine_client.model_config.model,
|
||||
trust_remote_code=True,
|
||||
)
|
||||
return build_dots_tts_prompt(self.tokenizer, text)
|
||||
|
||||
def validate(self, request: "OpenAICreateSpeechRequest") -> str | None:
|
||||
if not request.input or not request.input.strip():
|
||||
return "Input text cannot be empty"
|
||||
|
||||
if request.voice not in (None, "default"):
|
||||
return "'voice' is not supported for dots.tts"
|
||||
|
||||
if request.ref_audio is not None:
|
||||
return "'ref_audio' is not supported for dots.tts"
|
||||
|
||||
if request.ref_text is not None:
|
||||
return "'ref_text' is not supported for dots.tts"
|
||||
|
||||
if request.speaker_embedding is not None:
|
||||
return "'speaker_embedding' is not supported for dots.tts"
|
||||
|
||||
if request.x_vector_only_mode is not None:
|
||||
return "'x_vector_only_mode' is not supported for dots.tts"
|
||||
return None
|
||||
|
||||
async def build(
|
||||
self, request: "OpenAICreateSpeechRequest", sampling_params_list: list, has_inline_ref_audio: bool
|
||||
) -> PreparedRequest:
|
||||
if self._build_prompt_async is None:
|
||||
self._build_prompt_async = make_async(
|
||||
self._build_prompt,
|
||||
executor=self.ctx.server._tts_executor,
|
||||
)
|
||||
prompt = await self._build_prompt_async(request.input)
|
||||
return PreparedRequest(prompt=prompt, tts_params={}, model_type="dots_tts")
|
||||
|
||||
def apply_sampling_overrides(
|
||||
self,
|
||||
sampling_params_list: list,
|
||||
request: "OpenAICreateSpeechRequest",
|
||||
prompt: dict | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> list:
|
||||
return apply_max_new_tokens(sampling_params_list, request)
|
||||
@@ -9,7 +9,13 @@ import numpy as np
|
||||
from vllm.inputs import tokens_input
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import ARTTSAdapter, PreparedRequest, apply_max_new_tokens
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
ARTTSAdapter,
|
||||
PreparedRequest,
|
||||
apply_max_new_tokens,
|
||||
conditioning_cache_salt,
|
||||
resolve_stage_model_path,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
|
||||
@@ -50,7 +56,7 @@ class HiggsAudioV2Adapter(ARTTSAdapter):
|
||||
prompt_token_ids = input_ids_to_python_list(inputs)
|
||||
return tokens_input(prompt_token_ids=prompt_token_ids)
|
||||
|
||||
wav_list, sr, _ = await self._resolve_ref_audio(request.ref_audio)
|
||||
wav_list, sr, cache_key = await self._resolve_ref_audio(request.ref_audio)
|
||||
wav = np.asarray(wav_list, dtype=np.float32)
|
||||
out = await asyncio.to_thread(
|
||||
build_voice_clone_prompt,
|
||||
@@ -70,7 +76,9 @@ class HiggsAudioV2Adapter(ARTTSAdapter):
|
||||
prompt["additional_information"] = {
|
||||
"audio_input_ids": out["audio_input_ids"],
|
||||
"audio_input_ids_mask": out["audio_input_ids_mask"],
|
||||
"ref_audio_cache_key": cache_key,
|
||||
}
|
||||
prompt["cache_salt"] = conditioning_cache_salt(request, prompt["additional_information"])
|
||||
return prompt
|
||||
|
||||
async def _resolve_higgs_audio_v2_processor(self):
|
||||
@@ -81,17 +89,7 @@ class HiggsAudioV2Adapter(ARTTSAdapter):
|
||||
|
||||
from transformers import AutoProcessor
|
||||
|
||||
model_path = None
|
||||
for stage in self.engine_client.stage_configs:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
break
|
||||
if model_path is None:
|
||||
# Fallback: the orchestrator stores the served model id on the engine
|
||||
# itself (set by AsyncOmniEngine.__init__). Stage-level engine_args
|
||||
# may not surface ``model`` when the deploy yaml doesn't set it per
|
||||
# stage (the CLI-passed model id is the single source of truth).
|
||||
model_path = getattr(self.engine_client, "model", None)
|
||||
model_path = resolve_stage_model_path(self.engine_client)
|
||||
if model_path is None:
|
||||
raise RuntimeError("higgs_audio_v2 serving could not resolve the model path from the engine stage configs")
|
||||
processor = AutoProcessor.from_pretrained(model_path)
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
PreparedRequest,
|
||||
apply_max_new_tokens,
|
||||
conditioning_cache_salt,
|
||||
resolve_stage_model_path,
|
||||
)
|
||||
|
||||
_REF_CODE_CACHE_MAX_ENTRIES = 256
|
||||
@@ -170,13 +171,7 @@ class HiggsAudioV3Adapter(ARTTSAdapter):
|
||||
HiggsAudioV3TokenizerAdapter,
|
||||
)
|
||||
|
||||
model_path = None
|
||||
for stage in self.engine_client.stage_configs:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
break
|
||||
if model_path is None:
|
||||
model_path = getattr(self.engine_client, "model", None)
|
||||
model_path = resolve_stage_model_path(self.engine_client)
|
||||
if model_path is None:
|
||||
raise RuntimeError("higgs_audio_v3 serving could not resolve model path")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
||||
|
||||
@@ -6,9 +6,14 @@ Both variants share the same build/validate flow (``_build_moss_tts_params``
|
||||
handles each); they are registered under distinct model-type names.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
from transformers.dynamic_module_utils import get_class_from_dynamic_module
|
||||
from vllm.inputs import tokens_input
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
@@ -18,10 +23,13 @@ from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
apply_max_new_tokens,
|
||||
conditioning_cache_salt,
|
||||
)
|
||||
from vllm_omni.model_executor.models.moss_tts.realtime_prompt import build_realtime_prompt
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
accumulate_nonstreaming: bool = False
|
||||
@@ -30,6 +38,7 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
super().__init__(ctx)
|
||||
self._moss_variant = None if self.name == "moss_tts_nano" else self._detect_moss_variant()
|
||||
self._moss_processor_cache = None
|
||||
self._moss_realtime_components_lock = threading.Lock()
|
||||
|
||||
@property
|
||||
def engine_client(self):
|
||||
@@ -44,7 +53,9 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
return self.ctx.server._speaker_cache
|
||||
|
||||
async def _resolve_ref_audio(self, ref_audio: str):
|
||||
return await self.ctx.server._resolve_ref_audio(ref_audio)
|
||||
if self._moss_variant is None: # Nano sends lists through engine IPC.
|
||||
return await self.ctx.server._resolve_ref_audio(ref_audio)
|
||||
return await self.ctx.server._resolve_ref_audio_array(ref_audio)
|
||||
|
||||
def _voice_created_at(self, voice: str) -> int:
|
||||
return self.ctx.server._voice_created_at(voice)
|
||||
@@ -63,7 +74,7 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
# inside the model package; this layer only supplies the processor and
|
||||
# the process-wide speaker cache.
|
||||
encoder = build_reference_encoder(
|
||||
self._get_moss_processor(),
|
||||
self._get_moss_realtime_components()[2] if self._moss_variant == "realtime" else self._get_moss_processor(),
|
||||
variant=cast(str, self._moss_variant),
|
||||
speaker_cache=self._speaker_cache,
|
||||
)
|
||||
@@ -137,13 +148,81 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
return "voice_generator"
|
||||
return "tts"
|
||||
|
||||
def _codec_stage_devices(self) -> str | None:
|
||||
"""Read the runtime ``devices`` entry of this pipeline's codec stage.
|
||||
|
||||
The codec (code2wav) stage is the final stage of every MOSS pipeline
|
||||
(``moss_tts_local_codec`` / ``moss_tts_codec``); prefer a stage whose
|
||||
``model_stage`` mentions "codec", else anchor on the last stage. The
|
||||
runtime mapping accepts the resolved ``runtime_config`` object, the
|
||||
omegaconf ``runtime`` mapping, and the legacy ``yaml_runtime`` dict.
|
||||
"""
|
||||
stages = list(getattr(self.engine_client, "stage_configs", None) or ())
|
||||
if not stages:
|
||||
return None
|
||||
codec_stages = [s for s in stages if "codec" in str(getattr(s, "model_stage", "") or "")]
|
||||
anchor = codec_stages[-1] if codec_stages else stages[-1]
|
||||
for attr in ("runtime_config", "runtime", "yaml_runtime"):
|
||||
runtime_cfg = getattr(anchor, attr, None)
|
||||
if runtime_cfg is None:
|
||||
continue
|
||||
devices = (
|
||||
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
|
||||
)
|
||||
if devices is not None and str(devices).strip():
|
||||
return str(devices)
|
||||
devices = getattr(anchor, "devices", None)
|
||||
return str(devices) if devices is not None and str(devices).strip() else None
|
||||
|
||||
def _resolve_ref_encoder_device(self):
|
||||
"""Pick the device of the API-process reference-audio encoder.
|
||||
|
||||
The encoder follows the code2wav stage onto its first GPU: the stage
|
||||
worker remaps its ``devices`` entry through ``CUDA_VISIBLE_DEVICES``
|
||||
and sees it as logical index 0, while replica launch restores the
|
||||
parent environment, so the same index names the same physical GPU in
|
||||
this process. When the stage pins no devices the stage worker and the
|
||||
encoder both default to the first visible GPU. Falls back to CPU when
|
||||
CUDA is unavailable or the stage device is not parseable.
|
||||
"""
|
||||
import torch # local to avoid pulling torch at module import time
|
||||
|
||||
if not torch.cuda.is_available():
|
||||
return torch.device("cpu")
|
||||
devices_str = self._codec_stage_devices()
|
||||
if devices_str is None:
|
||||
# No explicit pinning: the stage worker lands on the first visible
|
||||
# GPU (vLLM picks cuda:0 of the un-remapped environment).
|
||||
return torch.device("cuda", 0)
|
||||
first = devices_str.split(",")[0].strip()
|
||||
if not first:
|
||||
return torch.device("cuda", 0)
|
||||
if first == "cpu":
|
||||
return torch.device("cpu")
|
||||
if not first.isdigit():
|
||||
logger.warning("MOSS ref encoder: codec stage devices %r not parseable; keeping CPU", devices_str)
|
||||
return torch.device("cpu")
|
||||
index = int(first)
|
||||
device_count = torch.accelerator.device_count()
|
||||
if index >= device_count:
|
||||
logger.warning(
|
||||
"MOSS ref encoder: codec stage device cuda:%d out of range (%d visible); keeping CPU",
|
||||
index,
|
||||
device_count,
|
||||
)
|
||||
return torch.device("cpu")
|
||||
return torch.device("cuda", index)
|
||||
|
||||
def _get_moss_processor(self):
|
||||
"""Lazily load the upstream MOSS-TTS processor once per server.
|
||||
|
||||
Cached on ``self._moss_processor_cache``. The processor owns its own
|
||||
audio_tokenizer (~1.6 B params); we keep it on CPU so it doesn't
|
||||
compete with the talker (~8 GiB) and codec (~7 GiB) for our 96 GiB
|
||||
GPU — per-request ref-audio encoding is fast enough on CPU.
|
||||
audio_tokenizer (~1.6 B params) used for per-request reference-audio
|
||||
encoding; it is placed on the code2wav stage's GPU (see
|
||||
``_resolve_ref_encoder_device``) so cold encodes run on device instead
|
||||
of paying a CPU forward per request. Note this memory is charged to
|
||||
the API process, outside each stage's ``gpu_memory_utilization``
|
||||
budget — keep some headroom on the codec GPU.
|
||||
"""
|
||||
cached = getattr(self, "_moss_processor_cache", None)
|
||||
if cached is not None:
|
||||
@@ -153,10 +232,48 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
model_id = self.engine_client.model_config.model
|
||||
proc = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
||||
if hasattr(proc, "audio_tokenizer"):
|
||||
proc.audio_tokenizer = proc.audio_tokenizer.to("cpu").eval()
|
||||
device = self._resolve_ref_encoder_device()
|
||||
proc.audio_tokenizer = proc.audio_tokenizer.to(device).eval()
|
||||
logger.info("MOSS reference-audio encoder (audio_tokenizer) placed on %s", device)
|
||||
self._moss_processor_cache = proc
|
||||
return proc
|
||||
|
||||
def _get_moss_realtime_components(self):
|
||||
with self._moss_realtime_components_lock:
|
||||
cached = getattr(self, "_moss_realtime_components", None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
model_id = self.engine_client.model_config.model
|
||||
processor_cls = get_class_from_dynamic_module(
|
||||
"processing_mossttsrealtime.MossTTSRealtimeProcessor",
|
||||
model_id,
|
||||
)
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
||||
processor = processor_cls(tokenizer=tokenizer)
|
||||
hf_config = self.engine_client.model_config.hf_config
|
||||
codec_path = str(
|
||||
getattr(
|
||||
hf_config,
|
||||
"codec_model_name_or_path",
|
||||
getattr(
|
||||
hf_config,
|
||||
"audio_tokenizer_name_or_path",
|
||||
"OpenMOSS-Team/MOSS-Audio-Tokenizer",
|
||||
),
|
||||
)
|
||||
)
|
||||
codec = AutoModel.from_pretrained(
|
||||
codec_path,
|
||||
trust_remote_code=True,
|
||||
)
|
||||
# Reference encoding runs in the API process; follow the codec
|
||||
# (code2wav) stage's GPU like the processor path above.
|
||||
codec = codec.to(self._resolve_ref_encoder_device()).eval()
|
||||
cached = (tokenizer, processor, codec)
|
||||
self._moss_realtime_components = cached
|
||||
return cached
|
||||
|
||||
async def _build_moss_tts_params(
|
||||
self,
|
||||
request: "OpenAICreateSpeechRequest",
|
||||
@@ -196,24 +313,18 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
params["ref_audio_cache_key"] = cache_key
|
||||
return params
|
||||
|
||||
# ---- MOSS-TTS-Realtime: keep the old prompt_audio_array path ----
|
||||
# ``AutoProcessor.from_pretrained`` doesn't auto-discover
|
||||
# ``MossTTSRealtimeProcessor`` (no ``processor_config.json`` in the
|
||||
# snapshot), and Realtime's prompt format diverges from MossTTSDelay
|
||||
# (16-channel grid, separate per-step text feed). The
|
||||
# ``prompt_audio_array`` shape lines up well enough with what the
|
||||
# talker reads for short prompts; full Realtime support needs a
|
||||
# separate processor.from_module path which we don't wire here.
|
||||
if v == "realtime":
|
||||
params = {
|
||||
"text": [request.input or ""],
|
||||
"mode": ["voice_clone"],
|
||||
}
|
||||
tokenizer, processor, _ = await asyncio.to_thread(self._get_moss_realtime_components)
|
||||
references, realtime_resolve_keys = await self._encode_moss_references(
|
||||
request,
|
||||
has_inline_ref_audio=has_inline_ref_audio,
|
||||
two_speaker=False,
|
||||
)
|
||||
params = build_realtime_prompt(tokenizer, processor, request.input or "", references[0])
|
||||
if request.max_new_tokens is not None:
|
||||
params["max_new_frames"] = [request.max_new_tokens]
|
||||
wav_list, sr, cache_key = await self._resolve_ref_audio(cast(str, request.ref_audio))
|
||||
params["prompt_audio_array"] = [[wav_list, sr]]
|
||||
params["ref_audio_cache_key"] = cache_key
|
||||
if 0 in realtime_resolve_keys:
|
||||
params["ref_audio_cache_key"] = realtime_resolve_keys[0]
|
||||
return params
|
||||
|
||||
# ---- MossTTSDelay family (tts/ttsd/sound_effect/voice_generator)
|
||||
|
||||
@@ -99,9 +99,10 @@ class VoxtralTTSAdapter(ARTTSAdapter):
|
||||
) -> PreparedRequest:
|
||||
# Cache encoder_loaded property to avoid RPC call on every request with ref_audio
|
||||
if self._encoder_loaded is None:
|
||||
loaded = await self.ctx.server.engine_client.collective_rpc("encoder_loaded")
|
||||
# Flatten results before checking if encoder loaded property is set
|
||||
self._encoder_loaded = any(sum(loaded, []))
|
||||
result = await self.ctx.server.engine_client.collective_rpc("encoder_loaded")
|
||||
self._encoder_loaded = any(
|
||||
bool(x) for r in result if not isinstance(r, dict) for x in (r if isinstance(r, list) else [r])
|
||||
)
|
||||
|
||||
prompt = await self._build_prompt_async(request)
|
||||
return PreparedRequest(prompt=prompt, tts_params={}, model_type="voxtral_tts")
|
||||
|
||||
@@ -54,10 +54,12 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoResponse,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.serving_video import (
|
||||
LatentEditInput,
|
||||
OmniOpenAIServingVideo,
|
||||
ReferenceAudio,
|
||||
ReferenceImage,
|
||||
ReferenceVideo,
|
||||
_stage_diffusion_model_class_name,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.storage import STORAGE_MANAGER
|
||||
from vllm_omni.entrypoints.openai.stores import VIDEO_STORE
|
||||
@@ -92,6 +94,9 @@ CONTROL_REFERENCE_IMAGE_SUFFIXES = frozenset({".bmp", ".gif", ".jpg", ".jpeg", "
|
||||
CONTROL_REFERENCE_VIDEO_SUFFIXES = frozenset({".mkv", ".mov", ".mp4", ".webm"})
|
||||
CONTROL_REFERENCE_MAX_BYTES = 512 * 1024 * 1024
|
||||
|
||||
LATENT_EDIT_SOURCE_MAX_BYTES = 512 * 1024 * 1024
|
||||
LATENT_EDIT_MASK_FILE_MAX_BYTES = 8 * 1024 * 1024
|
||||
|
||||
VIDEO_SYNC_TIMEOUT_S = float(os.environ.get("VLLM_OMNI_VIDEO_SYNC_TIMEOUT", 600.0))
|
||||
|
||||
|
||||
@@ -125,6 +130,79 @@ def _parse_form_json(value: str | None, expected_type: type | None = None) -> An
|
||||
return parsed
|
||||
|
||||
|
||||
def _parse_latent_edit_mask_json(
|
||||
value: str,
|
||||
*,
|
||||
field_name: str,
|
||||
) -> Any:
|
||||
"""Decode one request mask; Stage 0 owns its semantic validation."""
|
||||
try:
|
||||
parsed = _parse_form_json(value)
|
||||
# Bound container nesting at the parsing boundary without duplicating
|
||||
# Stage 0's numeric, range, or shape validation.
|
||||
pending = [(parsed, 0)]
|
||||
while pending:
|
||||
item, depth = pending.pop()
|
||||
if not isinstance(item, (list, dict)):
|
||||
continue
|
||||
if depth >= 64:
|
||||
raise ValueError("JSON nesting exceeds 64 levels")
|
||||
children = item.values() if isinstance(item, dict) else item
|
||||
pending.extend((child, depth + 1) for child in children)
|
||||
return parsed
|
||||
except (RecursionError, ValueError) as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} contains invalid JSON or is nested too deeply.",
|
||||
) from exc
|
||||
|
||||
|
||||
async def _read_latent_edit_mask_json(
|
||||
value: UploadFile | None,
|
||||
*,
|
||||
field_name: str,
|
||||
) -> Any | None:
|
||||
"""Read a mask from a bounded UTF-8 JSON file part."""
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
declared_size = value.size
|
||||
if isinstance(declared_size, Integral) and int(declared_size) > LATENT_EDIT_MASK_FILE_MAX_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} JSON exceeds the {LATENT_EDIT_MASK_FILE_MAX_BYTES // (1024 * 1024)} MiB limit.",
|
||||
)
|
||||
|
||||
payload = await value.read(LATENT_EDIT_MASK_FILE_MAX_BYTES + 1)
|
||||
if len(payload) > LATENT_EDIT_MASK_FILE_MAX_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} JSON exceeds the {LATENT_EDIT_MASK_FILE_MAX_BYTES // (1024 * 1024)} MiB limit.",
|
||||
)
|
||||
try:
|
||||
text = payload.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} JSON file must be UTF-8 encoded.",
|
||||
) from exc
|
||||
if not text:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} JSON file must not be empty.",
|
||||
)
|
||||
parsed = _parse_latent_edit_mask_json(text, field_name=field_name)
|
||||
if parsed is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} JSON file must contain a mask value.",
|
||||
)
|
||||
return parsed
|
||||
finally:
|
||||
await value.close()
|
||||
|
||||
|
||||
def _config_get(config: Any, key: str, default: Any = None) -> Any:
|
||||
if isinstance(config, dict):
|
||||
return config.get(key, default)
|
||||
@@ -136,10 +214,6 @@ def _config_get(config: Any, key: str, default: Any = None) -> Any:
|
||||
return getattr(config, key, default)
|
||||
|
||||
|
||||
def _stage_engine_args(stage_cfg: Any) -> Any:
|
||||
return _config_get(stage_cfg, "engine_args", {}) or {}
|
||||
|
||||
|
||||
def _diffusion_model_classes(stage_configs: list[Any] | None) -> list[type]:
|
||||
if not stage_configs:
|
||||
return []
|
||||
@@ -150,7 +224,7 @@ def _diffusion_model_classes(stage_configs: list[Any] | None) -> list[type]:
|
||||
for stage_cfg in stage_configs:
|
||||
if get_stage_type(stage_cfg) != "diffusion":
|
||||
continue
|
||||
model_class_name = _config_get(_stage_engine_args(stage_cfg), "model_class_name")
|
||||
model_class_name = _stage_diffusion_model_class_name(stage_cfg)
|
||||
if not model_class_name:
|
||||
continue
|
||||
model_cls = DiffusionModelRegistry._try_load_model_cls(model_class_name)
|
||||
@@ -281,6 +355,7 @@ def _cleanup_video_references(
|
||||
reference_video: ReferenceVideo | None,
|
||||
reference_audio: ReferenceAudio | None,
|
||||
control_path: str | None = None,
|
||||
latent_edit_input: LatentEditInput | None = None,
|
||||
) -> None:
|
||||
if reference_video is not None:
|
||||
for path in reference_video.cleanup_paths:
|
||||
@@ -293,6 +368,10 @@ def _cleanup_video_references(
|
||||
os.unlink(path)
|
||||
if control_path is not None and os.path.exists(control_path):
|
||||
os.unlink(control_path)
|
||||
if latent_edit_input is not None:
|
||||
for path in latent_edit_input.cleanup_paths:
|
||||
if os.path.exists(path):
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def _unpack_video_generation_result(
|
||||
@@ -323,11 +402,12 @@ async def _run_video_generation_job(
|
||||
reference_audio: ReferenceAudio | None = None,
|
||||
control_path: str | None = None,
|
||||
app_state: Any | None = None,
|
||||
latent_edit_input: LatentEditInput | None = None,
|
||||
) -> None:
|
||||
job = await VIDEO_STORE.get(video_id)
|
||||
if job is None:
|
||||
logger.warning("Video job %s missing before generation task started; skipping", video_id)
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path)
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path, latent_edit_input)
|
||||
return
|
||||
|
||||
started_at = time.perf_counter()
|
||||
@@ -344,6 +424,7 @@ async def _run_video_generation_job(
|
||||
reference_video=reference_video,
|
||||
reference_audio=reference_audio,
|
||||
on_started=_mark_started,
|
||||
latent_edit_input=latent_edit_input,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -403,7 +484,7 @@ async def _run_video_generation_job(
|
||||
await VIDEO_STORE.pop(video_id)
|
||||
raise
|
||||
finally:
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path)
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path, latent_edit_input)
|
||||
|
||||
|
||||
async def _persist_uploaded_video_references(uploads: list[UploadFile]) -> list[str]:
|
||||
@@ -426,6 +507,47 @@ async def _persist_uploaded_video_references(uploads: list[UploadFile]) -> list[
|
||||
return paths
|
||||
|
||||
|
||||
async def _persist_uploaded_reference(
|
||||
upload: UploadFile,
|
||||
*,
|
||||
field_name: str,
|
||||
suffix: str,
|
||||
max_bytes: int,
|
||||
) -> str:
|
||||
"""Stream one bounded upload to request-scoped local storage."""
|
||||
declared_size = upload.size
|
||||
if isinstance(declared_size, Integral) and int(declared_size) > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} exceeds the {max_bytes // (1024 * 1024)} MiB size limit.",
|
||||
)
|
||||
|
||||
fd, path = tempfile.mkstemp(prefix=f"vllm_omni_{field_name}_", suffix=suffix)
|
||||
size = 0
|
||||
persisted = False
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as output:
|
||||
while chunk := await upload.read(min(1024 * 1024, max_bytes - size + 1)):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} exceeds the {max_bytes // (1024 * 1024)} MiB size limit.",
|
||||
)
|
||||
output.write(chunk)
|
||||
if size == 0:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"{field_name} must not be empty.",
|
||||
)
|
||||
persisted = True
|
||||
return path
|
||||
finally:
|
||||
if not persisted:
|
||||
with suppress(OSError):
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
async def _persist_uploaded_control_reference(
|
||||
upload: UploadFile,
|
||||
*,
|
||||
@@ -442,38 +564,70 @@ async def _persist_uploaded_control_reference(
|
||||
)
|
||||
if not suffix:
|
||||
suffix = ".png" if kind == "image" else ".mp4"
|
||||
return await _persist_uploaded_reference(
|
||||
upload,
|
||||
field_name="control_reference",
|
||||
suffix=suffix,
|
||||
max_bytes=max_bytes,
|
||||
)
|
||||
|
||||
declared_size = getattr(upload, "size", None)
|
||||
if isinstance(declared_size, Integral) and int(declared_size) > max_bytes:
|
||||
|
||||
async def _persist_latent_edit_source(
|
||||
upload: UploadFile,
|
||||
*,
|
||||
field_name: Literal["source_video", "source_audio"],
|
||||
max_bytes: int = LATENT_EDIT_SOURCE_MAX_BYTES,
|
||||
) -> str:
|
||||
"""Stream one latent-edit source upload to request-scoped storage."""
|
||||
suffix = Path(upload.filename or "").suffix.lower()
|
||||
if field_name == "source_video":
|
||||
allowed_suffixes = MINIMAX_H3_REFERENCE_VIDEO_SUFFIXES
|
||||
expected = "an MP4 or MOV file"
|
||||
else:
|
||||
allowed_suffixes = MINIMAX_H3_REFERENCE_AUDIO_SUFFIXES
|
||||
expected = "a WAV or MP3 file"
|
||||
if suffix not in allowed_suffixes:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"control_reference exceeds the {max_bytes // (1024 * 1024)} MiB size limit.",
|
||||
detail=f"{field_name} must be {expected}.",
|
||||
)
|
||||
|
||||
fd, path = tempfile.mkstemp(prefix="vllm_omni_control_reference_", suffix=suffix)
|
||||
size = 0
|
||||
persisted = False
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as output:
|
||||
while chunk := await upload.read(min(1024 * 1024, max_bytes - size + 1)):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=f"control_reference exceeds the {max_bytes // (1024 * 1024)} MiB size limit.",
|
||||
)
|
||||
output.write(chunk)
|
||||
if size == 0:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="control_reference must not be empty.",
|
||||
)
|
||||
persisted = True
|
||||
return path
|
||||
finally:
|
||||
if not persisted:
|
||||
with suppress(OSError):
|
||||
os.unlink(path)
|
||||
return await _persist_uploaded_reference(
|
||||
upload,
|
||||
field_name=field_name,
|
||||
suffix=suffix,
|
||||
max_bytes=max_bytes,
|
||||
)
|
||||
|
||||
|
||||
def _validate_latent_edit_inputs(
|
||||
handler: OmniOpenAIServingVideo,
|
||||
*,
|
||||
source_video: UploadFile | None,
|
||||
source_audio: UploadFile | None,
|
||||
video_noise_mask: Any | None,
|
||||
audio_noise_mask: Any | None,
|
||||
) -> bool:
|
||||
"""Validate cross-field latent-edit requirements before persisting files."""
|
||||
has_any_input = any(value is not None for value in (source_video, source_audio, video_noise_mask, audio_noise_mask))
|
||||
if not has_any_input:
|
||||
return False
|
||||
if not handler.supports_latent_mask_editing:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Latent-mask editing is not supported by this model.",
|
||||
)
|
||||
if video_noise_mask is None and audio_noise_mask is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Latent-mask editing requires at least one of video_noise_mask or audio_noise_mask.",
|
||||
)
|
||||
if source_audio is not None and audio_noise_mask is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="source_audio requires an audio_noise_mask upload.",
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _validate_control_upload(
|
||||
@@ -497,7 +651,7 @@ def _validate_control_upload(
|
||||
)
|
||||
|
||||
normalized_type = control_type.strip().lower()
|
||||
supported_types = frozenset(getattr(handler, "supported_control_upload_types", ()))
|
||||
supported_types = handler.supported_control_upload_types
|
||||
if normalized_type not in supported_types:
|
||||
supported = ", ".join(sorted(supported_types)) or "none"
|
||||
raise HTTPException(
|
||||
@@ -735,6 +889,10 @@ async def _parse_video_form(
|
||||
lora: str | None = Form(default=None),
|
||||
extra_params: str | None = Form(default=None),
|
||||
return_stage_metrics: bool | None = Form(default=None),
|
||||
source_video: UploadFile | None = File(default=None),
|
||||
source_audio: UploadFile | None = File(default=None),
|
||||
video_noise_mask: UploadFile | None = File(default=None),
|
||||
audio_noise_mask: UploadFile | None = File(default=None),
|
||||
) -> tuple[
|
||||
VideoGenerationRequest,
|
||||
"OmniOpenAIServingVideo",
|
||||
@@ -743,6 +901,7 @@ async def _parse_video_form(
|
||||
ReferenceVideo | None,
|
||||
ReferenceAudio | None,
|
||||
str | None,
|
||||
LatentEditInput | None,
|
||||
]:
|
||||
"""FastAPI dependency that parses video form data, validates inputs,
|
||||
resolves the handler, and decodes any reference image.
|
||||
@@ -754,6 +913,14 @@ async def _parse_video_form(
|
||||
parsed_image_reference = _parse_form_json(image_reference)
|
||||
parsed_video_reference = _parse_form_json(video_reference)
|
||||
parsed_audio_reference = _parse_form_json(audio_reference)
|
||||
parsed_video_noise_mask = await _read_latent_edit_mask_json(
|
||||
video_noise_mask,
|
||||
field_name="video_noise_mask",
|
||||
)
|
||||
parsed_audio_noise_mask = await _read_latent_edit_mask_json(
|
||||
audio_noise_mask,
|
||||
field_name="audio_noise_mask",
|
||||
)
|
||||
|
||||
if input_references and any(
|
||||
item is not None for item in (parsed_image_reference, parsed_video_reference, input_reference)
|
||||
@@ -838,6 +1005,14 @@ async def _parse_video_form(
|
||||
detail=f"Video generation setup failed: {str(e)}",
|
||||
)
|
||||
|
||||
has_latent_edit = _validate_latent_edit_inputs(
|
||||
handler,
|
||||
source_video=source_video,
|
||||
source_audio=source_audio,
|
||||
video_noise_mask=parsed_video_noise_mask,
|
||||
audio_noise_mask=parsed_audio_noise_mask,
|
||||
)
|
||||
|
||||
normalized_control_type = _validate_control_upload(handler, request, control_reference, control_type)
|
||||
if normalized_control_type is not None:
|
||||
# Make the selected transfer mode visible while choosing the model's
|
||||
@@ -845,7 +1020,7 @@ async def _parse_video_form(
|
||||
# until reference parsing succeeds, preserving failure cleanup.
|
||||
_attach_control_upload(request, normalized_control_type)
|
||||
|
||||
supports_mixed_reference_inputs = bool(getattr(handler, "supports_mixed_reference_inputs", False))
|
||||
supports_mixed_reference_inputs = handler.supports_mixed_reference_inputs
|
||||
if input_reference is not None:
|
||||
input_reference_bytes = await _read_upload_limited(
|
||||
input_reference,
|
||||
@@ -979,6 +1154,38 @@ async def _parse_video_form(
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path)
|
||||
raise
|
||||
|
||||
latent_edit_input: LatentEditInput | None = None
|
||||
if has_latent_edit:
|
||||
source_paths: list[str] = []
|
||||
try:
|
||||
source_video_path = None
|
||||
source_audio_path = None
|
||||
if source_video is not None:
|
||||
source_video_path = await _persist_latent_edit_source(
|
||||
source_video,
|
||||
field_name="source_video",
|
||||
)
|
||||
source_paths.append(source_video_path)
|
||||
if source_audio is not None:
|
||||
source_audio_path = await _persist_latent_edit_source(
|
||||
source_audio,
|
||||
field_name="source_audio",
|
||||
)
|
||||
source_paths.append(source_audio_path)
|
||||
latent_edit_input = LatentEditInput(
|
||||
source_video=source_video_path,
|
||||
source_audio=source_audio_path,
|
||||
video_noise_mask=parsed_video_noise_mask,
|
||||
audio_noise_mask=parsed_audio_noise_mask,
|
||||
cleanup_paths=tuple(source_paths),
|
||||
)
|
||||
except (asyncio.CancelledError, Exception):
|
||||
for path in source_paths:
|
||||
with suppress(OSError):
|
||||
os.unlink(path)
|
||||
_cleanup_video_references(reference_video, reference_audio, control_path)
|
||||
raise
|
||||
|
||||
return (
|
||||
request,
|
||||
handler,
|
||||
@@ -987,4 +1194,5 @@ async def _parse_video_form(
|
||||
reference_video,
|
||||
reference_audio,
|
||||
control_path,
|
||||
latent_edit_input,
|
||||
)
|
||||
@@ -103,6 +103,14 @@ class ServingRealtimeRobotOpenPI:
|
||||
for stage_config in getattr(engine_client, "stage_configs", []) or []:
|
||||
if getattr(stage_config, "stage_type", None) != "diffusion":
|
||||
continue
|
||||
# Typed diffusion stages keep model-owned OpenPI handshake
|
||||
# metadata in diffusion_config.model_config. The out-of-process
|
||||
# head only has this stage view because full od_config lives in
|
||||
# the worker.
|
||||
diffusion_config = getattr(stage_config, "diffusion_config", None)
|
||||
model_config = getattr(diffusion_config, "model_config", None)
|
||||
if model_config is not None:
|
||||
break
|
||||
engine_args = getattr(stage_config, "engine_args", None)
|
||||
model_config = getattr(engine_args, "model_config", None)
|
||||
if model_config is not None:
|
||||
@@ -186,6 +194,9 @@ class ServingRealtimeRobotOpenPI:
|
||||
# (e.g. a policy deploy yaml's ``extra_args``) and layer the OpenPI
|
||||
# protocol fields on top.
|
||||
seed = obs.pop("seed", None)
|
||||
# Nested so engine knobs cannot collide with robot-defined obs keys.
|
||||
sampling = obs.get("sampling_params") or {}
|
||||
robot_obs = {key: value for key, value in obs.items() if key != "sampling_params"}
|
||||
sampling_params = OmniDiffusionSamplingParams()
|
||||
for default_params in get_default_sampling_params_list(self.engine_client):
|
||||
if isinstance(default_params, OmniDiffusionSamplingParams):
|
||||
@@ -197,15 +208,16 @@ class ServingRealtimeRobotOpenPI:
|
||||
{
|
||||
"reset": reset,
|
||||
"session_id": session_id,
|
||||
"robot_obs": obs,
|
||||
"robot_obs": robot_obs,
|
||||
}
|
||||
)
|
||||
|
||||
prompt = obs.get("prompt", "")
|
||||
sampling_params = OmniDiffusionSamplingParams(
|
||||
seed=int(seed) if seed is not None else None,
|
||||
extra_args=extra_args,
|
||||
)
|
||||
if seed is not None:
|
||||
sampling_params.seed = int(seed)
|
||||
if "num_inference_steps" in sampling:
|
||||
sampling_params.num_inference_steps = sampling["num_inference_steps"]
|
||||
sampling_params.extra_args = extra_args
|
||||
return OmniDiffusionRequest(
|
||||
prompt=prompt,
|
||||
sampling_params=sampling_params,
|
||||
|
||||
@@ -4,18 +4,20 @@
|
||||
|
||||
|
||||
def _should_enable_profiler_endpoints(stage_configs: list | None) -> bool:
|
||||
"""Check if any stage has profiler_config set in its engine_args."""
|
||||
"""Check whether any typed or legacy stage enables a profiler."""
|
||||
if not stage_configs:
|
||||
return False
|
||||
for stage in stage_configs:
|
||||
engine_args = stage.get("engine_args") if isinstance(stage, dict) else getattr(stage, "engine_args", None)
|
||||
if engine_args is None:
|
||||
continue
|
||||
profiler_config = (
|
||||
engine_args.get("profiler_config")
|
||||
if isinstance(engine_args, dict)
|
||||
else getattr(engine_args, "profiler_config", None)
|
||||
stage.get("profiler_config") if isinstance(stage, dict) else getattr(stage, "profiler_config", None)
|
||||
)
|
||||
if profiler_config is None:
|
||||
engine_args = stage.get("engine_args") if isinstance(stage, dict) else getattr(stage, "engine_args", None)
|
||||
profiler_config = (
|
||||
engine_args.get("profiler_config")
|
||||
if isinstance(engine_args, dict)
|
||||
else getattr(engine_args, "profiler_config", None)
|
||||
)
|
||||
if profiler_config is not None:
|
||||
profiler = (
|
||||
profiler_config.get("profiler")
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import asdict, is_dataclass
|
||||
from multiprocessing import shared_memory as _shm
|
||||
from typing import Any
|
||||
|
||||
@@ -274,6 +278,8 @@ def _to_dict(x: Any) -> dict[str, Any]:
|
||||
try:
|
||||
if isinstance(x, dict):
|
||||
return dict(x)
|
||||
if is_dataclass(x) and not isinstance(x, type):
|
||||
return asdict(x)
|
||||
return _omega_to_dict(x)
|
||||
except Exception:
|
||||
try:
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
import json
|
||||
import os
|
||||
import types
|
||||
from dataclasses import fields, is_dataclass
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, fields, is_dataclass
|
||||
from typing import Any, get_args, get_origin
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from vllm_omni.config.config_factory import with_trust_remote_code_override
|
||||
from vllm_omni.entrypoints.stage_utils import _to_dict
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
|
||||
@@ -18,6 +20,13 @@ logger = init_logger(__name__)
|
||||
|
||||
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."""
|
||||
typed_connector_config = getattr(stage, "connector_config", None)
|
||||
if typed_connector_config is not None:
|
||||
omni_conf_dict = dict(typed_connector_config.omni_kv_config or {})
|
||||
omni_conf_dict.update(connector_config=omni_conn_cfg, omni_from_stage=omni_from, omni_to_stage=omni_to)
|
||||
typed_connector_config.omni_kv_config = omni_conf_dict
|
||||
return
|
||||
|
||||
# Prepare omni_kv_config dict
|
||||
omni_conf_dict = {}
|
||||
try:
|
||||
@@ -79,6 +88,64 @@ def parse_stage_overrides(value: Any) -> dict[str, dict[str, Any]] | None:
|
||||
return parsed
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StageConfigInputs:
|
||||
"""Normalized inputs shared by all stage-config loading paths."""
|
||||
|
||||
model: str
|
||||
kwargs: dict[str, Any]
|
||||
trust_remote_code: bool | None
|
||||
deploy_config_path: str | None
|
||||
stage_overrides: dict[str, dict[str, Any]] | None
|
||||
strategy_config_path: str | None
|
||||
|
||||
|
||||
def prepare_stage_config_inputs(
|
||||
model: str,
|
||||
kwargs: Mapping[str, Any],
|
||||
*,
|
||||
trust_remote_code: bool | None,
|
||||
snapshot_model: bool = False,
|
||||
) -> StageConfigInputs:
|
||||
"""Normalize model/config arguments before resolving stage configs.
|
||||
|
||||
The standard API worker, multi-API parent, and headless entrypoint must
|
||||
apply the same legacy-key filtering, trust-remote-code precedence, and
|
||||
config-file extraction before calling :func:`resolve_omni_config`.
|
||||
"""
|
||||
resolved_model = model
|
||||
if snapshot_model:
|
||||
# Keep model materialization at the CLI boundary for the parent-owned
|
||||
# launch path. The API worker's OmniBase has already done this work.
|
||||
from vllm_omni.entrypoints.omni_base import omni_snapshot_download
|
||||
|
||||
resolved_model = omni_snapshot_download(model)
|
||||
|
||||
resolved_kwargs = dict(kwargs)
|
||||
for legacy_arg in ("stage_configs_path", "stage_configs"):
|
||||
if legacy_arg in resolved_kwargs:
|
||||
raise ValueError(f"`{legacy_arg}` is no longer supported; use `deploy_config` instead.")
|
||||
# Frontend process count is not a stage engine override.
|
||||
resolved_kwargs.pop("api_server_count", None)
|
||||
resolved_kwargs.pop("disable_log_stats", None)
|
||||
if resolved_kwargs.get("diffusion_streaming_output") and resolved_kwargs.get("streaming_output") is None:
|
||||
resolved_kwargs["streaming_output"] = True
|
||||
resolved_kwargs.pop("model_tag", None)
|
||||
|
||||
resolved_kwargs = with_trust_remote_code_override(resolved_kwargs, trust_remote_code)
|
||||
deploy_config_path = resolved_kwargs.pop("deploy_config", None)
|
||||
strategy_config_path = resolved_kwargs.pop("strategy_config", None)
|
||||
stage_overrides = parse_stage_overrides(resolved_kwargs.pop("stage_overrides", None))
|
||||
return StageConfigInputs(
|
||||
model=resolved_model,
|
||||
kwargs=resolved_kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
deploy_config_path=deploy_config_path,
|
||||
stage_overrides=stage_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
)
|
||||
|
||||
|
||||
def get_final_stage_id_for_e2e(
|
||||
output_modalities: list[str] | None, default_modalities: list[str], stage_list: list
|
||||
) -> int:
|
||||
|
||||
Reference in new issue
Block a user