Merge branch 'main' into feat/moss-tts-nano
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
611 files changed
+48775
-14783
No files matched your search
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import base64
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import multiprocessing
|
||||
@@ -15,9 +16,11 @@ from argparse import Namespace
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from http import HTTPStatus
|
||||
from numbers import Integral
|
||||
from typing import Annotated, Any, Literal, cast
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
import vllm.envs as envs
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, WebSocket
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
|
||||
@@ -29,7 +32,7 @@ from vllm import SamplingParams
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.anthropic.serving import AnthropicServingMessages
|
||||
from vllm.entrypoints.chat_utils import load_chat_template
|
||||
from vllm.entrypoints.launcher import serve_http
|
||||
from vllm.entrypoints.launcher import serve_http, terminate_if_errored
|
||||
from vllm.entrypoints.logger import RequestLogger
|
||||
from vllm.entrypoints.mcp.tool_server import DemoToolServer, MCPToolServer, ToolServer
|
||||
from vllm.entrypoints.openai.api_server import build_app as build_openai_app
|
||||
@@ -48,11 +51,11 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
ModelCard,
|
||||
ModelList,
|
||||
ModelPermission,
|
||||
RequestResponseMetadata,
|
||||
)
|
||||
from vllm.entrypoints.openai.models.protocol import BaseModelPath
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.openai.orca_metrics import metrics_header
|
||||
from vllm.entrypoints.openai.realtime.connection import RealtimeConnection
|
||||
from vllm.entrypoints.openai.realtime.serving import OpenAIServingRealtime
|
||||
from vllm.entrypoints.openai.responses.serving import OpenAIServingResponses
|
||||
from vllm.entrypoints.openai.server_utils import get_uvicorn_log_config
|
||||
@@ -73,6 +76,7 @@ from vllm.entrypoints.serve.instrumentator.basic import base
|
||||
from vllm.entrypoints.serve.render.serving import OpenAIServingRender
|
||||
from vllm.entrypoints.serve.tokenize.serving import OpenAIServingTokenization
|
||||
from vllm.entrypoints.utils import (
|
||||
create_error_response,
|
||||
load_aware_call,
|
||||
process_lora_modules,
|
||||
with_cancellation,
|
||||
@@ -82,6 +86,7 @@ from vllm.tasks import POOLING_TASKS
|
||||
from vllm.tool_parsers import ToolParserManager
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.system_utils import decorate_logs
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.errors import InvalidInputReferenceError
|
||||
@@ -107,6 +112,7 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoListResponse,
|
||||
VideoResponse,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.realtime_connection import RealtimeConnection
|
||||
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpeechHandler
|
||||
@@ -120,6 +126,7 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParam
|
||||
logger = init_logger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
MAX_UINT32_SEED = 2**32 - 1
|
||||
profiler_router = APIRouter()
|
||||
|
||||
|
||||
@@ -196,6 +203,50 @@ def _remove_route_from_app(app, path: str, methods: set[str] | None = None):
|
||||
app.routes.remove(route)
|
||||
|
||||
|
||||
def _register_omni_exception_handlers(app) -> None:
|
||||
"""Override upstream vLLM exception handlers with Omni-aware versions.
|
||||
|
||||
The upstream ``engine_error_handler`` is designed for ``AsyncLLM`` (single
|
||||
EngineCore process). Omni uses a multi-stage orchestrator with different
|
||||
health semantics, so we register our own handlers that:
|
||||
|
||||
- Log multi-stage diagnostic info (orchestrator liveness, per-stage health)
|
||||
when an ``EngineDeadError`` is caught.
|
||||
- Call ``terminate_if_errored``
|
||||
- Return an OpenAI-compatible error JSON response.
|
||||
"""
|
||||
|
||||
async def omni_engine_error_handler(
|
||||
req: Request,
|
||||
exc: EngineDeadError | EngineGenerateError,
|
||||
):
|
||||
request_id = req.state.request_metadata.request_id if hasattr(req.state, "request_metadata") else None
|
||||
|
||||
if req.app.state.args.log_error_stack:
|
||||
logger.exception("Engine Exception caught. Request id: %s", request_id)
|
||||
|
||||
engine = req.app.state.engine_client
|
||||
if isinstance(exc, EngineDeadError):
|
||||
# Log Omni-specific diagnostic information for dead engines.
|
||||
orchestrator_alive = engine.engine.is_alive() if hasattr(engine, "engine") else "N/A"
|
||||
logger.error(
|
||||
"EngineDeadError: orchestrator_alive=%s, errored=%s, request_id=%s",
|
||||
orchestrator_alive,
|
||||
engine.errored,
|
||||
request_id,
|
||||
)
|
||||
|
||||
terminate_if_errored(
|
||||
server=req.app.state.server,
|
||||
engine=engine,
|
||||
)
|
||||
err = create_error_response(exc)
|
||||
return JSONResponse(err.model_dump(), status_code=err.error.code)
|
||||
|
||||
app.exception_handler(EngineGenerateError)(omni_engine_error_handler)
|
||||
app.exception_handler(EngineDeadError)(omni_engine_error_handler)
|
||||
|
||||
|
||||
class _DiffusionServingModels:
|
||||
"""Minimal OpenAIServingModels implementation for diffusion-only servers.
|
||||
|
||||
@@ -305,6 +356,10 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
_remove_route_from_app(app, "/v1/models", {"GET"}) # Remove upstream /v1/models to use omni's handler
|
||||
app.include_router(router)
|
||||
|
||||
# OMNI: Override upstream exception handlers with Omni-aware versions
|
||||
# that understand the multi-stage orchestrator lifecycle.
|
||||
_register_omni_exception_handlers(app)
|
||||
|
||||
await omni_init_app_state(engine_client, app.state, args)
|
||||
|
||||
# Conditionally register profiler endpoints based on stage YAML configs
|
||||
@@ -835,6 +890,7 @@ async def omni_init_app_state(
|
||||
|
||||
state.enable_server_load_tracking = args.enable_server_load_tracking
|
||||
state.server_load_metrics = 0
|
||||
state.sleeping_stages = set()
|
||||
|
||||
|
||||
def Omnivideo(request: Request) -> OmniOpenAIServingVideo | None:
|
||||
@@ -874,6 +930,8 @@ async def create_chat_completion(request: ChatCompletionRequest, raw_request: Re
|
||||
return base_server.create_error_response(message="The model does not support Chat Completions API")
|
||||
try:
|
||||
generator = await handler.create_chat_completion(request, raw_request)
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except Exception as e:
|
||||
logger.exception("Chat completion failed: %s", e)
|
||||
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
|
||||
@@ -969,6 +1027,8 @@ async def create_speech(request: OpenAICreateSpeechRequest, raw_request: Request
|
||||
status_code=result.error.code if result.error else 400,
|
||||
)
|
||||
return result
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
|
||||
|
||||
@@ -1003,6 +1063,8 @@ async def create_speech_batch(request: BatchSpeechRequest, raw_request: Request)
|
||||
status_code=result.error.code if result.error else 400,
|
||||
)
|
||||
return JSONResponse(content=result.model_dump())
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST.value, detail=str(e)) from e
|
||||
except Exception as e:
|
||||
@@ -1202,6 +1264,22 @@ async def streaming_speech(websocket: WebSocket):
|
||||
@router.websocket("/v1/realtime")
|
||||
async def realtime_websocket(websocket: WebSocket):
|
||||
"""WebSocket endpoint for OpenAI-style realtime interactions."""
|
||||
engine_client = getattr(websocket.app.state, "engine_client", None)
|
||||
if engine_client is not None and getattr(engine_client, "async_chunk", False):
|
||||
await websocket.accept()
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "error",
|
||||
"error": (
|
||||
"The /v1/realtime API is not supported when async_chunk is enabled on the server. "
|
||||
"Use a stage configuration with async_chunk disabled and restart the server before using "
|
||||
"this endpoint."
|
||||
),
|
||||
"code": "unsupported",
|
||||
}
|
||||
)
|
||||
await websocket.close()
|
||||
return
|
||||
serving = getattr(websocket.app.state, "openai_serving_realtime", None)
|
||||
if serving is None:
|
||||
await websocket.accept()
|
||||
@@ -1224,31 +1302,26 @@ _remove_route_from_router(router, "/health")
|
||||
async def health(raw_request: Request) -> JSONResponse:
|
||||
"""Health check endpoint that works for both LLM and diffusion modes.
|
||||
|
||||
Returns 200 OK if the server is healthy.
|
||||
For LLM mode: delegates to engine_client health check
|
||||
For diffusion mode: checks if diffusion_engine is running
|
||||
Returns 200 OK if the server is healthy, 503 if the engine is dead.
|
||||
Mirrors vLLM upstream's /health which catches EngineDeadError -> 503.
|
||||
"""
|
||||
# Check if we're in diffusion mode
|
||||
diffusion_engine = getattr(raw_request.app.state, "diffusion_engine", None)
|
||||
if diffusion_engine is not None:
|
||||
# Diffusion mode health check
|
||||
if hasattr(diffusion_engine, "is_running") and diffusion_engine.is_running:
|
||||
return JSONResponse(content={"status": "healthy"})
|
||||
engine_client = getattr(raw_request.app.state, "engine_client", None) or getattr(
|
||||
raw_request.app.state, "diffusion_engine", None
|
||||
)
|
||||
if engine_client is None:
|
||||
return JSONResponse(
|
||||
content={"status": "unhealthy", "reason": "Diffusion engine is not running"},
|
||||
content={"status": "unhealthy", "reason": "No engine initialized"},
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
)
|
||||
|
||||
# LLM mode - delegate to engine_client
|
||||
engine_client = getattr(raw_request.app.state, "engine_client", None)
|
||||
if engine_client is not None:
|
||||
try:
|
||||
await engine_client.check_health()
|
||||
return JSONResponse(content={"status": "healthy"})
|
||||
|
||||
return JSONResponse(
|
||||
content={"status": "unhealthy", "reason": "No engine initialized"},
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
)
|
||||
except EngineDeadError:
|
||||
return JSONResponse(
|
||||
content={"status": "unhealthy"},
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
)
|
||||
|
||||
|
||||
# Remove existing models endpoint if present (from vllm imports)
|
||||
@@ -1303,14 +1376,64 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
# Get engine client (AsyncOmni) from app state
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
|
||||
# Validate model field (warn if mismatch, don't error)
|
||||
if request.model is not None and request.model != model_name:
|
||||
logger.warning(
|
||||
f"Model mismatch: request specifies '{request.model}' but "
|
||||
f"server is running '{model_name}'. Using server model."
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=(f"Model mismatch: request specifies '{request.model}' but server is running '{model_name}'."),
|
||||
)
|
||||
|
||||
try:
|
||||
# Unify request construction for any multi-stage pipeline to avoid
|
||||
# divergence between /v1/images and /v1/chat/completions.
|
||||
if len(stage_configs) > 1:
|
||||
chat_handler = getattr(raw_request.app.state, "openai_serving_chat", None)
|
||||
if chat_handler is None:
|
||||
logger.warning("openai_serving_chat is not initialized for multi-stage /v1/images/generations")
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="openai_serving_chat is not initialized for multi-stage image generation.",
|
||||
)
|
||||
|
||||
effective_seed = request.seed if request.seed is not None else random.randint(0, MAX_UINT32_SEED)
|
||||
extra_body: dict[str, Any] = {
|
||||
"seed": effective_seed,
|
||||
"num_outputs_per_prompt": request.n,
|
||||
}
|
||||
if request.size is not None:
|
||||
parse_size(request.size)
|
||||
width, height = parse_size(request.size)
|
||||
app_state_args = getattr(raw_request.app.state, "args", None)
|
||||
_check_max_generated_image_size(app_state_args, width, height)
|
||||
extra_body["size"] = request.size
|
||||
if request.negative_prompt is not None:
|
||||
extra_body["negative_prompt"] = request.negative_prompt
|
||||
if request.num_inference_steps is not None:
|
||||
extra_body["num_inference_steps"] = request.num_inference_steps
|
||||
if request.guidance_scale is not None:
|
||||
extra_body["guidance_scale"] = request.guidance_scale
|
||||
if request.true_cfg_scale is not None:
|
||||
extra_body["true_cfg_scale"] = request.true_cfg_scale
|
||||
if request.generator_device is not None:
|
||||
extra_body["generator_device"] = request.generator_device
|
||||
if request.lora is not None:
|
||||
# Keep /images validation semantics: invalid LoRA should fail with 400.
|
||||
_parse_lora_request(request.lora)
|
||||
extra_body["lora"] = request.lora
|
||||
|
||||
generation_result = await chat_handler.generate_diffusion_images(
|
||||
prompt=request.prompt,
|
||||
extra_body=extra_body,
|
||||
request_id=f"img_gen-{random_uuid()}",
|
||||
)
|
||||
if isinstance(generation_result, ErrorResponse):
|
||||
return JSONResponse(
|
||||
status_code=generation_result.error.code if generation_result.error else 400,
|
||||
content=generation_result.model_dump(),
|
||||
)
|
||||
flat_images, _, _ = generation_result
|
||||
image_data = [ImageData(b64_json=encode_image_base64(img), revised_prompt=None) for img in flat_images]
|
||||
return ImageGenerationResponse(created=int(time.time()), data=image_data)
|
||||
|
||||
# Build params - pass through user values directly
|
||||
prompt: OmniTextPrompt = {"prompt": request.prompt}
|
||||
if request.negative_prompt is not None:
|
||||
@@ -1336,6 +1459,16 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
else:
|
||||
size_str = "model default"
|
||||
|
||||
# Keep AR stage target grid in sync with requested output size.
|
||||
# GLM-Image consumes target_h/target_w via mm_processor_kwargs.
|
||||
if width is not None and height is not None:
|
||||
prompt["mm_processor_kwargs"] = {
|
||||
"target_h": height,
|
||||
"target_w": width,
|
||||
}
|
||||
# Backward-compatible fallback for processors reading top-level fields.
|
||||
prompt["height"] = height
|
||||
prompt["width"] = width
|
||||
app_state_args = getattr(raw_request.app.state, "args", None)
|
||||
_check_max_generated_image_size(app_state_args, width, height)
|
||||
|
||||
@@ -1351,12 +1484,13 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
# This fixes issues where using the default global generator
|
||||
# might produce blurry images in some environments.
|
||||
_update_if_not_none(
|
||||
gen_params, "seed", request.seed if request.seed is not None else random.randint(0, 2**32 - 1)
|
||||
gen_params, "seed", request.seed if request.seed is not None else random.randint(0, MAX_UINT32_SEED)
|
||||
)
|
||||
_update_if_not_none(gen_params, "generator_device", request.generator_device)
|
||||
_update_if_not_none(gen_params, "layers", request.layers)
|
||||
|
||||
request_id = f"img_gen-{random_uuid()}"
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
|
||||
logger.info(f"Generating {request.n} image(s) {size_str}")
|
||||
|
||||
@@ -1388,8 +1522,9 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
data=image_data,
|
||||
)
|
||||
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except HTTPException:
|
||||
# Re-raise HTTPExceptions as-is
|
||||
raise
|
||||
except ValueError as e:
|
||||
logger.error(f"Validation error: {e}")
|
||||
@@ -1425,6 +1560,9 @@ async def edit_images(
|
||||
background: str | None = Form("auto"),
|
||||
output_compression: Annotated[int, Form(ge=0, le=100)] = 100,
|
||||
user: str | None = Form(None), # unused now
|
||||
# vllm-omni extensions for image editing
|
||||
mask_image: str | UploadFile | None = None,
|
||||
reference_image: str | UploadFile | None = None,
|
||||
# vllm-omni extensions for diffusion control
|
||||
negative_prompt: str | None = Form(None),
|
||||
num_inference_steps: int | None = Form(None),
|
||||
@@ -1445,8 +1583,9 @@ async def edit_images(
|
||||
# 1. get engine and model
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
if model is not None and model != model_name:
|
||||
logger.warning(
|
||||
f"Model mismatch: request specifies '{model}' but server is running '{model_name}'. Using server model."
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=(f"Model mismatch: request specifies '{model}' but server is running '{model_name}'."),
|
||||
)
|
||||
# 2. get output format & compression
|
||||
output_format = _choose_output_format(output_format, background)
|
||||
@@ -1469,15 +1608,35 @@ async def edit_images(
|
||||
input_images_list.extend(urls)
|
||||
if not input_images_list:
|
||||
raise HTTPException(status_code=422, detail="Field 'image' or 'url' is required")
|
||||
pil_images = await _load_input_images(input_images_list)
|
||||
if len(pil_images) > 1 and not _supports_multimodal_image_inputs(raw_request, engine_client):
|
||||
# Reject oversized multi-image edit requests before fetching or decoding
|
||||
# any inputs. This keeps over-limit URL requests from burning network,
|
||||
# CPU, and memory on work that will be rejected anyway.
|
||||
max_input_images = _get_max_edit_input_images(raw_request, engine_client)
|
||||
if max_input_images is not None and len(input_images_list) > max_input_images:
|
||||
detail = (
|
||||
"Received multiple input images. Only a single image is supported by this model."
|
||||
if max_input_images == 1
|
||||
else (
|
||||
f"Received {len(input_images_list)} input images. "
|
||||
f"At most {max_input_images} images are supported by this model."
|
||||
)
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Received multiple input images. Only a single image is supported by this model.",
|
||||
detail=detail,
|
||||
)
|
||||
pil_images = await _load_input_images(input_images_list)
|
||||
prompt["multi_modal_data"] = {}
|
||||
prompt["multi_modal_data"]["image"] = pil_images
|
||||
|
||||
if mask_image is not None:
|
||||
loaded = await _load_input_images([mask_image])
|
||||
prompt["multi_modal_data"]["mask_image"] = loaded[0]
|
||||
|
||||
if reference_image is not None:
|
||||
loaded = await _load_input_images([reference_image])
|
||||
prompt["multi_modal_data"]["reference_image"] = loaded[0]
|
||||
|
||||
# 3 Build sample params
|
||||
gen_params = OmniDiffusionSamplingParams()
|
||||
# 3.0 Init with system default values
|
||||
@@ -1537,6 +1696,18 @@ async def edit_images(
|
||||
_check_max_generated_image_size(app_state_args, width, height, resolution)
|
||||
|
||||
size_str = f"{width}x{height}" if width is not None and height is not None else "auto"
|
||||
|
||||
# Keep AR stage target grid in sync with requested output size.
|
||||
# GLM-Image consumes target_h/target_w via mm_processor_kwargs.
|
||||
if width is not None and height is not None:
|
||||
prompt["mm_processor_kwargs"] = {
|
||||
"target_h": height,
|
||||
"target_w": width,
|
||||
}
|
||||
# Backward-compatible fallback for processors reading top-level fields.
|
||||
prompt["height"] = height
|
||||
prompt["width"] = width
|
||||
|
||||
_update_if_not_none(gen_params, "width", width)
|
||||
_update_if_not_none(gen_params, "height", height)
|
||||
|
||||
@@ -1549,13 +1720,14 @@ async def edit_images(
|
||||
# a proper generator is initialized in the backend.
|
||||
# This fixes issues where using the default global generator
|
||||
# might produce blurry images in some environments.
|
||||
_update_if_not_none(gen_params, "seed", seed if seed is not None else random.randint(0, 2**32 - 1))
|
||||
_update_if_not_none(gen_params, "seed", seed if seed is not None else random.randint(0, MAX_UINT32_SEED))
|
||||
_update_if_not_none(gen_params, "generator_device", generator_device)
|
||||
_update_if_not_none(gen_params, "layers", layers)
|
||||
_update_if_not_none(gen_params, "resolution", resolution)
|
||||
|
||||
# 4. Generate images using AsyncOmni (multi-stage mode)
|
||||
request_id = f"img_edit-{random_uuid()}"
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
logger.info(f"Generating {n} image(s) {size_str}")
|
||||
result = await _generate_with_async_omni(
|
||||
engine_client=engine_client,
|
||||
@@ -1587,8 +1759,9 @@ async def edit_images(
|
||||
size=size_str,
|
||||
)
|
||||
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except HTTPException:
|
||||
# Re-raise HTTPExceptions as-is
|
||||
raise
|
||||
except ValueError as e:
|
||||
logger.error(f"Validation error: {e}")
|
||||
@@ -1639,18 +1812,39 @@ def _get_engine_and_model(raw_request: Request):
|
||||
return engine_client, model_name, normalized_stage_configs
|
||||
|
||||
|
||||
def _supports_multimodal_image_inputs(raw_request: Request, engine_client: Any) -> bool:
|
||||
def _get_diffusion_od_config(raw_request: Request, engine_client: Any) -> Any:
|
||||
diffusion_engine = getattr(raw_request.app.state, "diffusion_engine", None) or engine_client
|
||||
get_diffusion_od_config = getattr(diffusion_engine, "get_diffusion_od_config", None)
|
||||
od_config = (
|
||||
return (
|
||||
get_diffusion_od_config() if callable(get_diffusion_od_config) else getattr(diffusion_engine, "od_config", None)
|
||||
)
|
||||
|
||||
|
||||
def _get_max_edit_input_images(raw_request: Request, engine_client: Any) -> int | None:
|
||||
od_config = _get_diffusion_od_config(raw_request, engine_client)
|
||||
if od_config is None:
|
||||
# Preserve the existing compatibility behavior when the diffusion
|
||||
# config is not exposed on the serving surface.
|
||||
return True
|
||||
return bool(getattr(od_config, "supports_multimodal_inputs", False))
|
||||
return None
|
||||
|
||||
supports_multimodal_inputs = getattr(od_config, "supports_multimodal_inputs", None)
|
||||
if not isinstance(supports_multimodal_inputs, bool):
|
||||
# Older serving surfaces and mocked engines may expose a placeholder
|
||||
# object instead of a real diffusion config. Treat that as "unknown"
|
||||
# so existing single-image flows keep working.
|
||||
return None
|
||||
|
||||
if not supports_multimodal_inputs:
|
||||
return 1
|
||||
|
||||
max_input_images = getattr(od_config, "max_multimodal_image_inputs", None)
|
||||
if max_input_images is None:
|
||||
return None
|
||||
if isinstance(max_input_images, bool) or not isinstance(max_input_images, Integral):
|
||||
return None
|
||||
if max_input_images < 1:
|
||||
return None
|
||||
return int(max_input_images)
|
||||
|
||||
|
||||
def _get_lora_from_json_str(lora_body):
|
||||
@@ -1767,6 +1961,34 @@ def _update_if_not_none(object: Any, key: str, val: Any) -> None:
|
||||
setattr(object, key, val)
|
||||
|
||||
|
||||
def _normalize_image(image: Any) -> Any:
|
||||
"""Normalize a single image output to a PIL-compatible format."""
|
||||
if isinstance(image, Image.Image):
|
||||
return image
|
||||
if not isinstance(image, np.ndarray):
|
||||
raise ValueError(f"Unsupported image type: {type(image)}")
|
||||
if not np.issubdtype(image.dtype, np.integer) and not np.issubdtype(image.dtype, np.floating):
|
||||
raise ValueError(f"Unsupported dtype: {image.dtype}")
|
||||
if isinstance(image, np.ndarray):
|
||||
while image.ndim > 3:
|
||||
image = image[0]
|
||||
if image.min() < 0:
|
||||
if image.min() < -1.01 or image.max() > 1.01:
|
||||
logger.warning(
|
||||
f"Image float range [{image.min():.2f}, {image.max():.2f}] outside expected [-1, 1]. "
|
||||
f"Clipping to [-1, 1] before normalization."
|
||||
)
|
||||
image = np.clip(image, -1.0, 1.0) * 0.5 + 0.5
|
||||
elif image.max() > 1.01:
|
||||
logger.warning(
|
||||
f"Image float range [{image.min():.2f}, {image.max():.2f}] outside expected [0, 1]. "
|
||||
f"Clipping to [0, 1] before normalization."
|
||||
)
|
||||
image = (np.clip(image, 0.0, 1.0) * 255).astype(np.uint8)
|
||||
image = Image.fromarray(image)
|
||||
return image
|
||||
|
||||
|
||||
def _extract_images_from_result(result: Any) -> list[Any]:
|
||||
images = []
|
||||
if hasattr(result, "images") and result.images:
|
||||
@@ -1777,6 +1999,10 @@ def _extract_images_from_result(result: Any) -> list[Any]:
|
||||
images = request_output["images"]
|
||||
elif hasattr(request_output, "images") and request_output.images:
|
||||
images = request_output.images
|
||||
# Handle when generate more than one image
|
||||
if images and isinstance(images[0], np.ndarray) and images[0].shape[0] > 1 and images[0].ndim == 5:
|
||||
# Unwrap batch: (N, T, H, W, C) -> [img1, img2, ...]
|
||||
images = list(images[0])
|
||||
# Flatten nested lists (e.g., from layered models like Qwen-Image-Layered).
|
||||
# Note: This only flattens one level deep. Deeper nesting is not supported.
|
||||
flattened = []
|
||||
@@ -1785,7 +2011,7 @@ def _extract_images_from_result(result: Any) -> list[Any]:
|
||||
flattened.extend(img)
|
||||
else:
|
||||
flattened.append(img)
|
||||
return flattened
|
||||
return [_normalize_image(img) for img in flattened]
|
||||
|
||||
|
||||
async def _load_input_images(
|
||||
@@ -1955,6 +2181,48 @@ def video_response_from_request(model_name: str, req: VideoGenerationRequest) ->
|
||||
return resp
|
||||
|
||||
|
||||
def _status_code_for_video_failure(error: VideoError | None) -> int:
|
||||
if error is None:
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
|
||||
if isinstance(error.code, int):
|
||||
if 400 <= error.code < 600:
|
||||
return error.code
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
|
||||
if error.code == "HTTPException":
|
||||
status_text, _, _ = error.message.partition(":")
|
||||
try:
|
||||
status_code = int(status_text)
|
||||
except ValueError:
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
if 400 <= status_code < 600:
|
||||
return status_code
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
|
||||
if error.code == "EngineDeadError":
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
if error.code == "EngineGenerateError":
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR.value
|
||||
|
||||
|
||||
def _video_error_from_exception(exc: Exception) -> VideoError:
|
||||
if isinstance(exc, HTTPException):
|
||||
message = str(exc.detail) if exc.detail else str(exc)
|
||||
return VideoError(code=exc.status_code, message=message)
|
||||
|
||||
if isinstance(exc, (EngineGenerateError, EngineDeadError)):
|
||||
err = create_error_response(exc)
|
||||
return VideoError(code=err.error.code, message=err.error.message)
|
||||
|
||||
return VideoError(
|
||||
code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
|
||||
message=str(exc),
|
||||
)
|
||||
|
||||
|
||||
def _cleanup_video(video_id: str, output_path: str | None):
|
||||
try:
|
||||
if output_path is not None:
|
||||
@@ -1968,6 +2236,7 @@ async def _run_video_generation_job(
|
||||
request: VideoGenerationRequest,
|
||||
video_id: str,
|
||||
reference_image: ReferenceImage | None = None,
|
||||
app_state: Any | None = None,
|
||||
) -> None:
|
||||
job = await VIDEO_STORE.get(video_id)
|
||||
if job is None:
|
||||
@@ -1998,17 +2267,36 @@ async def _run_video_generation_job(
|
||||
"peak_memory_mb": peak_memory_mb,
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Video generation failed for id=%s", video_id)
|
||||
except (EngineGenerateError, EngineDeadError) as exc:
|
||||
logger.exception("Video generation failed (engine error) for id=%s", video_id)
|
||||
|
||||
_cleanup_video(video_id, output_path)
|
||||
# TODO: It would be better to have a finite collection of errors to return rather than the exception name
|
||||
await VIDEO_STORE.update_fields(
|
||||
video_id,
|
||||
{
|
||||
"status": VideoGenerationStatus.FAILED,
|
||||
"completed_at": int(time.time()),
|
||||
"error": VideoError(code=type(exc).__name__, message=str(exc)),
|
||||
"error": _video_error_from_exception(exc),
|
||||
"inference_time_s": time.perf_counter() - started_at,
|
||||
},
|
||||
)
|
||||
# Background tasks can't propagate exceptions to FastAPI handlers.
|
||||
# Actively signal shutdown when the engine is dead.
|
||||
if app_state is not None and isinstance(exc, EngineDeadError):
|
||||
terminate_if_errored(
|
||||
server=app_state.server,
|
||||
engine=app_state.engine_client,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Video generation failed for id=%s", video_id)
|
||||
|
||||
_cleanup_video(video_id, output_path)
|
||||
await VIDEO_STORE.update_fields(
|
||||
video_id,
|
||||
{
|
||||
"status": VideoGenerationStatus.FAILED,
|
||||
"completed_at": int(time.time()),
|
||||
"error": _video_error_from_exception(exc),
|
||||
"inference_time_s": time.perf_counter() - started_at,
|
||||
},
|
||||
)
|
||||
@@ -2042,6 +2330,10 @@ async def _parse_video_form(
|
||||
true_cfg_scale: float | None = Form(default=None),
|
||||
seed: int | None = Form(default=None),
|
||||
negative_prompt: str | None = Form(default=None),
|
||||
enable_frame_interpolation: bool = Form(default=False),
|
||||
frame_interpolation_exp: int = Form(default=1, ge=1),
|
||||
frame_interpolation_scale: float = Form(default=1.0, gt=0.0),
|
||||
frame_interpolation_model_path: str | None = Form(default=None),
|
||||
lora: str | None = Form(default=None),
|
||||
extra_params: str | None = Form(default=None),
|
||||
) -> tuple[VideoGenerationRequest, "OmniOpenAIServingVideo", str, ReferenceImage | None]:
|
||||
@@ -2078,6 +2370,10 @@ async def _parse_video_form(
|
||||
"true_cfg_scale": true_cfg_scale,
|
||||
"seed": seed,
|
||||
"negative_prompt": negative_prompt,
|
||||
"enable_frame_interpolation": enable_frame_interpolation,
|
||||
"frame_interpolation_exp": frame_interpolation_exp,
|
||||
"frame_interpolation_scale": frame_interpolation_scale,
|
||||
"frame_interpolation_model_path": frame_interpolation_model_path,
|
||||
"lora": _parse_form_json(lora, expected_type=dict),
|
||||
"extra_params": _parse_form_json(extra_params, expected_type=dict),
|
||||
}
|
||||
@@ -2095,10 +2391,12 @@ async def _parse_video_form(
|
||||
app_model_name, app_stage_configs = _resolve_video_runtime_context(raw_request)
|
||||
effective_model_name = handler.model_name or app_model_name or request.model or "unknown"
|
||||
if request.model is not None and effective_model_name is not None and request.model != effective_model_name:
|
||||
logger.warning(
|
||||
"Model mismatch: request specifies '%s' but server is running '%s'. Using server model.",
|
||||
request.model,
|
||||
effective_model_name,
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=(
|
||||
f"Model mismatch: request specifies '{request.model}' but server is running "
|
||||
f"'{effective_model_name}'."
|
||||
),
|
||||
)
|
||||
handler.set_stage_configs_if_missing(app_stage_configs)
|
||||
except HTTPException:
|
||||
@@ -2129,6 +2427,7 @@ async def _parse_video_form(
|
||||
},
|
||||
)
|
||||
async def create_video(
|
||||
raw_request: Request,
|
||||
ctx: tuple[VideoGenerationRequest, OmniOpenAIServingVideo, str, ReferenceImage | None] = Depends(_parse_video_form),
|
||||
) -> VideoResponse:
|
||||
"""Create an asynchronous video generation job.
|
||||
@@ -2139,7 +2438,9 @@ async def create_video(
|
||||
request, handler, effective_model_name, reference_image = ctx
|
||||
ref = video_response_from_request(effective_model_name, request)
|
||||
await VIDEO_STORE.upsert(ref.id, ref)
|
||||
task = asyncio.create_task(_run_video_generation_job(handler, request, ref.id, reference_image))
|
||||
task = asyncio.create_task(
|
||||
_run_video_generation_job(handler, request, ref.id, reference_image, app_state=raw_request.app.state)
|
||||
)
|
||||
await VIDEO_TASKS.upsert(ref.id, task)
|
||||
return ref
|
||||
|
||||
@@ -2154,6 +2455,7 @@ async def create_video(
|
||||
},
|
||||
)
|
||||
async def create_video_sync(
|
||||
raw_request: Request,
|
||||
ctx: tuple[VideoGenerationRequest, OmniOpenAIServingVideo, str, ReferenceImage | None] = Depends(_parse_video_form),
|
||||
) -> Response:
|
||||
"""Synchronous video generation endpoint.
|
||||
@@ -2167,6 +2469,7 @@ async def create_video_sync(
|
||||
"""
|
||||
request, handler, effective_model_name, reference_image = ctx
|
||||
request_id = f"video_sync-{random_uuid()}"
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
started_at = time.perf_counter()
|
||||
try:
|
||||
video_bytes, stage_durations, peak_memory_mb = await asyncio.wait_for(
|
||||
@@ -2178,6 +2481,8 @@ async def create_video_sync(
|
||||
status_code=HTTPStatus.GATEWAY_TIMEOUT.value,
|
||||
detail=f"Video generation timed out after {VIDEO_SYNC_TIMEOUT_S}s.",
|
||||
)
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -2238,8 +2543,8 @@ async def list_videos(
|
||||
return VideoListResponse(data=jobs, has_more=has_more, first_id=first_id, last_id=last_id)
|
||||
|
||||
|
||||
@router.get("/v1/videos/{video_id}")
|
||||
async def retrieve_video(video_id: str) -> VideoResponse:
|
||||
@router.get("/v1/videos/{video_id}", response_model=None)
|
||||
async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
|
||||
"""Retrieve metadata for a previously created video job.
|
||||
|
||||
Args:
|
||||
@@ -2254,6 +2559,15 @@ async def retrieve_video(video_id: str) -> VideoResponse:
|
||||
job = await VIDEO_STORE.get(video_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
if job.status == VideoGenerationStatus.FAILED:
|
||||
status_code = _status_code_for_video_failure(job.error)
|
||||
content = job.model_dump(mode="json")
|
||||
if content.get("error") is not None:
|
||||
content["error"]["code"] = status_code
|
||||
return JSONResponse(
|
||||
content=content,
|
||||
status_code=status_code,
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
@@ -2390,3 +2704,64 @@ async def stop_profile(raw_request: Request, request: ProfileRequest | None = No
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to stop profiler: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
class OmniSleepRequest(BaseModel):
|
||||
stage_ids: list[int]
|
||||
level: int = 2
|
||||
|
||||
|
||||
class OmniWakeupRequest(BaseModel):
|
||||
stage_ids: list[int]
|
||||
|
||||
|
||||
@router.post("/v1/omni/sleep")
|
||||
async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
sleeping_set = raw_request.app.state.sleeping_stages
|
||||
if not hasattr(engine_client, "sleep"):
|
||||
raise HTTPException(status_code=501, detail="Engine does not support sleep")
|
||||
acks = await engine_client.sleep(stage_ids=request.stage_ids, level=request.level)
|
||||
for sid in request.stage_ids:
|
||||
sleeping_set.add(sid)
|
||||
return {"status": "SUCCESS", "acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) else a for a in acks]}
|
||||
|
||||
|
||||
@router.post("/v1/omni/wakeup")
|
||||
async def omni_wakeup(request: OmniWakeupRequest, raw_request: Request):
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
sleeping_set = raw_request.app.state.sleeping_stages
|
||||
if not any(sid in sleeping_set for sid in request.stage_ids):
|
||||
return {"status": "SKIPPED", "reason": "Target stages are not sleeping."}
|
||||
if not hasattr(engine_client, "wake_up"):
|
||||
raise HTTPException(status_code=501, detail="Engine does not support wake_up")
|
||||
acks = await engine_client.wake_up(stage_ids=request.stage_ids)
|
||||
for sid in request.stage_ids:
|
||||
if sid in sleeping_set:
|
||||
sleeping_set.remove(sid)
|
||||
return {"status": "SUCCESS", "acks": [dataclasses.asdict(a) if dataclasses.is_dataclass(a) else a for a in acks]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
import asyncio
|
||||
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser
|
||||
|
||||
parser = argparse.ArgumentParser(description="vLLM-Omni OpenAI-Compatible REST API server")
|
||||
parser = make_arg_parser(parser)
|
||||
registered_flags = set()
|
||||
for action in parser._actions:
|
||||
registered_flags.update(action.option_strings)
|
||||
if "--omni" not in registered_flags:
|
||||
parser.add_argument("--omni", action="store_true", default=False, help="Enable vLLM-Omni mode.")
|
||||
if "--enable-sleep-mode" not in registered_flags:
|
||||
parser.add_argument(
|
||||
"--enable-sleep-mode", action="store_true", default=False, help="Enable GPU memory pool for sleep mode."
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if not hasattr(args, "model_tag"):
|
||||
setattr(args, "model_tag", args.model)
|
||||
if hasattr(args, "model_tag") and args.model_tag is None:
|
||||
args.model_tag = args.model
|
||||
asyncio.run(omni_run_server(args))
|
||||
@@ -150,6 +150,29 @@ class VideoGenerationRequest(BaseModel):
|
||||
)
|
||||
seed: int | None = Field(default=None, description="Random seed for reproducibility")
|
||||
|
||||
# vllm-omni extensions for post-generation frame interpolation.
|
||||
enable_frame_interpolation: bool = Field(
|
||||
default=False,
|
||||
description="Enable post-generation RIFE frame interpolation before MP4 encoding.",
|
||||
)
|
||||
frame_interpolation_exp: int = Field(
|
||||
default=1,
|
||||
ge=1,
|
||||
description="Interpolation exponent: 1=2x temporal resolution, 2=4x, etc.",
|
||||
)
|
||||
frame_interpolation_scale: float = Field(
|
||||
default=1.0,
|
||||
gt=0.0,
|
||||
description="RIFE inference scale. Use 0.5 for high-resolution inputs to save memory.",
|
||||
)
|
||||
frame_interpolation_model_path: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Local directory or Hugging Face repo ID containing RIFE flownet.pkl weights. "
|
||||
"Defaults to elfgum/RIFE-4.22.lite."
|
||||
),
|
||||
)
|
||||
|
||||
# vllm-omni extension for per-request LoRA.
|
||||
lora: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
@@ -212,7 +235,7 @@ class VideoGenerationResponse(BaseModel):
|
||||
|
||||
|
||||
class VideoError(BaseModel):
|
||||
code: str = Field(..., description="A machine-readable error code that was returned.")
|
||||
code: int | str = Field(..., description="A machine-readable error code that was returned.")
|
||||
message: str = Field(..., description="A human-readable description of the error that was returned.")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
from collections.abc import AsyncGenerator
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
from vllm.entrypoints.openai.engine.protocol import UsageInfo
|
||||
from vllm.entrypoints.openai.realtime.connection import RealtimeConnection as VllmRealtimeConnection
|
||||
from vllm.entrypoints.openai.realtime.protocol import TranscriptionDelta, TranscriptionDone
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class RealtimeConnection(VllmRealtimeConnection):
|
||||
"""Omni realtime connection with audio-only server events.
|
||||
|
||||
Reuses upstream vLLM websocket/session lifecycle and only customizes
|
||||
generation output handling to emit audio deltas.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# Last audio buffer seen for this realtime generation (cumulative or concatenation
|
||||
# of increments); used to turn server cumulative PCM into true deltas.
|
||||
self._realtime_audio_ref: np.ndarray | None = None
|
||||
|
||||
async def start_generation(self):
|
||||
await super().start_generation()
|
||||
|
||||
@staticmethod
|
||||
def _tensor_to_numpy(value) -> np.ndarray | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, np.ndarray):
|
||||
arr = value
|
||||
elif hasattr(value, "detach"):
|
||||
arr = value.detach().float().cpu().numpy()
|
||||
else:
|
||||
try:
|
||||
arr = np.asarray(value)
|
||||
except Exception:
|
||||
return None
|
||||
if arr.ndim > 1:
|
||||
arr = arr.reshape(-1)
|
||||
return arr.astype(np.float32, copy=False)
|
||||
|
||||
@staticmethod
|
||||
def _numpy_audio_prefix_match(prev: np.ndarray, curr: np.ndarray) -> bool:
|
||||
n = prev.shape[0]
|
||||
if n == 0:
|
||||
return True
|
||||
if curr.shape[0] < n:
|
||||
return False
|
||||
return bool(np.allclose(curr[:n], prev, rtol=1e-3, atol=2e-4))
|
||||
|
||||
def _raw_waveform_to_deltas(self, arr: np.ndarray) -> list[np.ndarray]:
|
||||
"""Convert one streaming PCM f32 chunk into incremental piece(s) for the client.
|
||||
|
||||
Some engine paths emit a growing cumulative waveform each step; others emit
|
||||
true per-step deltas. We support both without duplicating audio on the client.
|
||||
"""
|
||||
if arr.size == 0:
|
||||
return []
|
||||
ref = self._realtime_audio_ref
|
||||
if ref is None:
|
||||
self._realtime_audio_ref = arr.copy()
|
||||
return [arr]
|
||||
if self._numpy_audio_prefix_match(ref, arr):
|
||||
delta = arr[ref.shape[0] :]
|
||||
self._realtime_audio_ref = arr.copy()
|
||||
return [delta] if delta.size > 0 else []
|
||||
# True per-step delta (not a prefix extension of what we have seen).
|
||||
self._realtime_audio_ref = np.concatenate([ref, arr])
|
||||
return [arr]
|
||||
|
||||
def _extract_audio_chunks(self, output) -> tuple[list[np.ndarray], int]:
|
||||
mm = getattr(output, "multimodal_output", None)
|
||||
if not isinstance(mm, dict):
|
||||
return [], 24000
|
||||
|
||||
sr = mm.get("sr") or mm.get("sample_rate") or mm.get("audio_sample_rate") or 24000
|
||||
key = "audio" if "audio" in mm else ("model_outputs" if "model_outputs" in mm else None)
|
||||
if key is None:
|
||||
return [], int(sr)
|
||||
|
||||
raw_audio = mm.get(key)
|
||||
chunks: list[np.ndarray] = []
|
||||
if isinstance(raw_audio, (list, tuple)):
|
||||
if len(raw_audio) > 0:
|
||||
arr = self._tensor_to_numpy(raw_audio[-1])
|
||||
if arr is not None and arr.size > 0:
|
||||
chunks.extend(self._raw_waveform_to_deltas(arr))
|
||||
else:
|
||||
arr = self._tensor_to_numpy(raw_audio)
|
||||
if arr is not None and arr.size > 0:
|
||||
chunks.extend(self._raw_waveform_to_deltas(arr))
|
||||
return chunks, int(sr)
|
||||
|
||||
@staticmethod
|
||||
def _pcm16_b64(audio_f32: np.ndarray) -> str:
|
||||
clipped = np.clip(audio_f32, -1.0, 1.0)
|
||||
pcm16 = (clipped * 32767.0).astype(np.int16)
|
||||
return base64.b64encode(pcm16.tobytes()).decode("utf-8")
|
||||
|
||||
async def _run_generation(
|
||||
self,
|
||||
streaming_input_gen: AsyncGenerator,
|
||||
input_stream: asyncio.Queue[list[int]],
|
||||
):
|
||||
request_id = f"rt-{self.connection_id}-{uuid4()}"
|
||||
sent_audio = False
|
||||
audio_done_sent = False
|
||||
full_text = ""
|
||||
sent_text_len = 0
|
||||
prompt_token_ids_len = 0
|
||||
completion_tokens_len = 0
|
||||
self._realtime_audio_ref = None
|
||||
|
||||
try:
|
||||
result_gen = self.serving.engine_client.generate(
|
||||
prompt=streaming_input_gen,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
async for output in result_gen:
|
||||
if output.outputs and len(output.outputs) > 0:
|
||||
output0 = output.outputs[0]
|
||||
token_ids = list(output0.token_ids)
|
||||
if token_ids:
|
||||
input_stream.put_nowait(token_ids)
|
||||
# token_ids are cumulative per request
|
||||
completion_tokens_len = len(token_ids)
|
||||
if not prompt_token_ids_len and output.prompt_token_ids:
|
||||
prompt_token_ids_len = len(output.prompt_token_ids)
|
||||
cumulative_text = output0.text or ""
|
||||
if cumulative_text:
|
||||
if len(cumulative_text) >= sent_text_len:
|
||||
delta_text = cumulative_text[sent_text_len:]
|
||||
else:
|
||||
delta_text = cumulative_text
|
||||
sent_text_len = len(cumulative_text)
|
||||
full_text = cumulative_text
|
||||
else:
|
||||
delta_text = ""
|
||||
|
||||
if delta_text:
|
||||
await self.send(TranscriptionDelta(delta=delta_text))
|
||||
|
||||
audio_chunks, sample_rate = self._extract_audio_chunks(output)
|
||||
|
||||
for chunk in audio_chunks:
|
||||
sent_audio = True
|
||||
await self.send_json(
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"audio": self._pcm16_b64(chunk),
|
||||
"format": "pcm16",
|
||||
"sample_rate_hz": sample_rate,
|
||||
}
|
||||
)
|
||||
|
||||
if not self._is_connected:
|
||||
break
|
||||
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=prompt_token_ids_len,
|
||||
completion_tokens=completion_tokens_len,
|
||||
total_tokens=prompt_token_ids_len + completion_tokens_len,
|
||||
)
|
||||
await self.send(TranscriptionDone(text=full_text, usage=usage))
|
||||
|
||||
if sent_audio:
|
||||
await self.send_json({"type": "response.audio.done", "has_audio": True})
|
||||
audio_done_sent = True
|
||||
except Exception as e:
|
||||
logger.exception("Error in generation: %s", e)
|
||||
await self.send_error(str(e), "processing_error")
|
||||
finally:
|
||||
# Always send terminal event so clients don't hang forever.
|
||||
if self._is_connected and not audio_done_sent:
|
||||
try:
|
||||
await self.send_json({"type": "response.audio.done", "has_audio": sent_audio})
|
||||
except Exception:
|
||||
logger.exception("Failed to send response.audio.done")
|
||||
while not self.audio_queue.empty():
|
||||
self.audio_queue.get_nowait()
|
||||
|
||||
async def send_json(self, payload: dict):
|
||||
await self.websocket.send_text(json.dumps(payload))
|
||||
@@ -32,6 +32,7 @@ from vllm.entrypoints.chat_utils import (
|
||||
get_history_tool_calls_cnt,
|
||||
make_tool_call_id,
|
||||
)
|
||||
from vllm.entrypoints.launcher import terminate_if_errored
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionNamedToolChoiceParam,
|
||||
ChatCompletionRequest,
|
||||
@@ -80,12 +81,14 @@ from vllm.tokenizers.mistral import (
|
||||
from vllm.tool_parsers import ToolParser
|
||||
from vllm.tool_parsers.mistral_tool_parser import MistralToolCall
|
||||
from vllm.utils.collection_utils import as_list
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.image_api_utils import validate_layered_layers
|
||||
from vllm_omni.entrypoints.openai.protocol import OmniChatCompletionStreamResponse
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import AudioResponse, CreateAudio
|
||||
from vllm_omni.entrypoints.openai.utils import (
|
||||
get_stage_type,
|
||||
get_supported_speakers_from_hf_config,
|
||||
parse_lora_request,
|
||||
validate_requested_speaker,
|
||||
@@ -294,6 +297,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
)
|
||||
|
||||
num_inference_steps = None
|
||||
cfg_text_scale = None
|
||||
cfg_img_scale = None
|
||||
# Omni multistage image generation: Stage-0 (AR) should receive a clean
|
||||
# text prompt (and optional conditioning image/size) so the model's own
|
||||
# processor can construct the correct inputs.
|
||||
@@ -301,20 +306,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# effectively unconditioned and produce nonsense images.
|
||||
if request.modalities and ("image" in request.modalities):
|
||||
try:
|
||||
messages_as_dicts: list[dict[str, Any]] = []
|
||||
for msg in request.messages:
|
||||
if hasattr(msg, "model_dump"):
|
||||
messages_as_dicts.append(msg.model_dump())
|
||||
elif isinstance(msg, dict):
|
||||
messages_as_dicts.append(msg)
|
||||
else:
|
||||
messages_as_dicts.append(
|
||||
{
|
||||
"role": getattr(msg, "role", "user"),
|
||||
"content": getattr(msg, "content", ""),
|
||||
}
|
||||
)
|
||||
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images(messages_as_dicts)
|
||||
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images_from_messages(
|
||||
request.messages
|
||||
)
|
||||
if not extracted_prompt:
|
||||
return self.create_error_response("No text prompt found in messages")
|
||||
|
||||
@@ -325,39 +319,33 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
extra_body = getattr(request, "extra_body", None)
|
||||
if not extra_body:
|
||||
extra_body = request.model_extra or {}
|
||||
height = extra_body.get("height")
|
||||
width = extra_body.get("width")
|
||||
|
||||
height, width = self._resolve_height_width_from_extra_body(extra_body)
|
||||
|
||||
num_inference_steps = extra_body.get("num_inference_steps")
|
||||
if num_inference_steps is not None:
|
||||
try:
|
||||
num_inference_steps = int(num_inference_steps)
|
||||
except Exception:
|
||||
num_inference_steps = None
|
||||
if "size" in extra_body:
|
||||
try:
|
||||
size_str = extra_body["size"]
|
||||
if isinstance(size_str, str) and "x" in size_str.lower():
|
||||
w, h = size_str.lower().split("x")
|
||||
width, height = int(w), int(h)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
negative_prompt = extra_body.get("negative_prompt")
|
||||
cfg_text_scale = extra_body.get("cfg_text_scale")
|
||||
cfg_img_scale = extra_body.get("cfg_img_scale")
|
||||
|
||||
engine_prompt_image: dict[str, Any] | None = None
|
||||
is_img2img = False
|
||||
if reference_images:
|
||||
# Best-effort decode first reference image for i2i.
|
||||
try:
|
||||
img_bytes = base64.b64decode(reference_images[0])
|
||||
img = Image.open(BytesIO(img_bytes))
|
||||
engine_prompt_image = {"img2img": img}
|
||||
is_img2img = True
|
||||
except Exception:
|
||||
engine_prompt_image = None
|
||||
|
||||
# Override the prompts produced by chat-template preprocessing.
|
||||
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
|
||||
if is_img2img:
|
||||
if engine_prompt_image:
|
||||
tprompt["modalities"] = ["img2img"]
|
||||
else:
|
||||
tprompt["modalities"] = ["image"]
|
||||
@@ -373,6 +361,13 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
tprompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
if engine_prompt_image is not None:
|
||||
tprompt["multi_modal_data"] = engine_prompt_image
|
||||
# Provide multi_modal_uuids so that newer vLLM versions
|
||||
# can validate multi_modal_data / multi_modal_uuids
|
||||
# consistency. After the multimodal processor consumes
|
||||
# the image data, the uuids remain as a stable reference.
|
||||
tprompt["multi_modal_uuids"] = {
|
||||
k: [f"{request_id}-{k}-{i}"] for i, k in enumerate(engine_prompt_image)
|
||||
}
|
||||
|
||||
engine_prompts = [tprompt]
|
||||
# Store height/width for applying to diffusion stage sampling params later
|
||||
@@ -397,14 +392,18 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
sampling_params_list = self._build_sampling_params_list_from_request(request)
|
||||
|
||||
# Apply user-specified overrides to diffusion stage(s) for image generation
|
||||
if _image_gen_height is not None or _image_gen_width is not None or num_inference_steps is not None:
|
||||
for idx, sp in enumerate(sampling_params_list):
|
||||
if hasattr(sp, "height") and _image_gen_height is not None:
|
||||
sp.height = _image_gen_height
|
||||
if hasattr(sp, "width") and _image_gen_width is not None:
|
||||
sp.width = _image_gen_width
|
||||
if hasattr(sp, "num_inference_steps") and num_inference_steps is not None:
|
||||
sp.num_inference_steps = num_inference_steps
|
||||
for idx, sp in enumerate(sampling_params_list):
|
||||
if hasattr(sp, "height") and _image_gen_height is not None:
|
||||
sp.height = _image_gen_height
|
||||
if hasattr(sp, "width") and _image_gen_width is not None:
|
||||
sp.width = _image_gen_width
|
||||
if hasattr(sp, "num_inference_steps") and num_inference_steps is not None:
|
||||
sp.num_inference_steps = num_inference_steps
|
||||
if hasattr(sp, "extra_args") and sp.extra_args is not None:
|
||||
if cfg_text_scale is not None:
|
||||
sp.extra_args["cfg_text_scale"] = cfg_text_scale
|
||||
if cfg_img_scale is not None:
|
||||
sp.extra_args["cfg_img_scale"] = cfg_img_scale
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
@@ -438,6 +437,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
raw_request=raw_request,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -535,20 +535,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# containing image tokens.
|
||||
req_modalities = getattr(request, "modalities", [])
|
||||
if req_modalities and ("image" in req_modalities):
|
||||
messages_as_dicts: list[dict[str, Any]] = []
|
||||
for msg in messages:
|
||||
if hasattr(msg, "model_dump"):
|
||||
messages_as_dicts.append(msg.model_dump())
|
||||
elif isinstance(msg, dict):
|
||||
messages_as_dicts.append(msg)
|
||||
else:
|
||||
messages_as_dicts.append(
|
||||
{
|
||||
"role": getattr(msg, "role", "user"),
|
||||
"content": getattr(msg, "content", ""),
|
||||
}
|
||||
)
|
||||
extracted_prompt, _ = self._extract_diffusion_prompt_and_images(messages_as_dicts)
|
||||
extracted_prompt, _ = self._extract_diffusion_prompt_and_images_from_messages(messages)
|
||||
if extracted_prompt:
|
||||
engine_prompt["prompt"] = extracted_prompt
|
||||
|
||||
@@ -708,6 +695,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
Starts with YAML defaults and only overrides fields that the user
|
||||
explicitly provided (non-None values) in the request.
|
||||
|
||||
For GLM-Image AR stage, if max_tokens is not in YAML and user provides
|
||||
height/width in extra_body, computes max_tokens dynamically.
|
||||
|
||||
Args:
|
||||
default_params: Default SamplingParams from stage config YAML.
|
||||
request: The chat completion request containing user-provided values.
|
||||
@@ -717,13 +707,64 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
"""
|
||||
params = default_params.clone()
|
||||
|
||||
# Only apply fields explicitly provided by user, not protocol defaults.
|
||||
# Pydantic v2 uses `model_fields_set`; keep v1 fallback for compatibility.
|
||||
explicit_fields = getattr(request, "model_fields_set", None)
|
||||
if explicit_fields is None:
|
||||
explicit_fields = getattr(request, "__fields_set__", set())
|
||||
|
||||
for field_name in self._OPENAI_SAMPLING_FIELDS:
|
||||
if field_name not in explicit_fields:
|
||||
continue
|
||||
|
||||
value = getattr(request, field_name, None)
|
||||
if value is not None:
|
||||
if (value is not None and not isinstance(value, list)) or (isinstance(value, list) and len(value) > 0):
|
||||
setattr(params, field_name, value)
|
||||
|
||||
# For GLM-Image: compute max_tokens from height/width with mode-aware
|
||||
# budgeting (t2i vs i2i).
|
||||
extra_body = getattr(request, "extra_body", {}) or {}
|
||||
height, width = self._resolve_height_width_from_extra_body(extra_body)
|
||||
|
||||
# Best-effort mode detection from user messages.
|
||||
# i2i requests include at least one reference image in message content.
|
||||
_, reference_images = self._extract_diffusion_prompt_and_images_from_messages(request.messages)
|
||||
ref_image_count = len(reference_images)
|
||||
is_img2img = ref_image_count > 0
|
||||
|
||||
if height is not None and width is not None:
|
||||
try:
|
||||
from vllm_omni.model_executor.stage_input_processors.glm_image import compute_max_tokens
|
||||
|
||||
max_tokens = getattr(explicit_fields, "max_tokens", None)
|
||||
if max_tokens is None:
|
||||
max_tokens = compute_max_tokens(int(height), int(width), is_i2i=is_img2img)
|
||||
params.max_tokens = max_tokens
|
||||
# Keep target size in stage-0 sampling params so runner/model can
|
||||
# build deterministic M-RoPE grids for t2i (no MM features).
|
||||
extra_args = dict(getattr(params, "extra_args", {}) or {})
|
||||
extra_args["target_h"] = int(height)
|
||||
extra_args["target_w"] = int(width)
|
||||
params.extra_args = extra_args
|
||||
except (ImportError, ValueError, TypeError) as e:
|
||||
logger.warning(f"Failed to compute max_tokens: {e}, using default if available")
|
||||
else:
|
||||
logger.info(
|
||||
"[SamplingParams] Skip dynamic max_tokens (height=%s, width=%s, mode=%s, ref_images=%s)",
|
||||
height,
|
||||
width,
|
||||
"i2i" if is_img2img else "t2i",
|
||||
ref_image_count,
|
||||
)
|
||||
|
||||
return params
|
||||
|
||||
@staticmethod
|
||||
def _set_if_supported(obj: Any, **kwargs: Any) -> None:
|
||||
for key, value in kwargs.items():
|
||||
if value is not None and hasattr(obj, key):
|
||||
setattr(obj, key, value)
|
||||
|
||||
def _build_sampling_params_list_from_request(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
@@ -787,6 +828,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
tokenizer: AnyTokenizer,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
reasoning_parser: ReasoningParser | None = None,
|
||||
raw_request: Request | None = None,
|
||||
):
|
||||
created_time = int(time.time())
|
||||
chunk_object_type: Final = "chat.completion.chunk"
|
||||
@@ -1499,6 +1541,21 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
delta=False,
|
||||
)
|
||||
|
||||
except EngineDeadError as e:
|
||||
logger.error(
|
||||
"EngineDeadError during streaming for request %s: %s",
|
||||
request_id,
|
||||
e,
|
||||
)
|
||||
data = self.create_streaming_error_response(e)
|
||||
yield f"data: {data}\n\n"
|
||||
# Actively signal shutdown instead of waiting for the watchdog
|
||||
# (5s polling interval).
|
||||
if raw_request is not None:
|
||||
terminate_if_errored(
|
||||
server=raw_request.app.state.server,
|
||||
engine=self.engine_client,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Error in chat completion stream generator.")
|
||||
data = self.create_streaming_error_response(e)
|
||||
@@ -1570,6 +1627,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
role,
|
||||
reasoning_parser,
|
||||
)
|
||||
final_res = omni_outputs.request_output
|
||||
elif omni_outputs.final_output_type == "audio":
|
||||
choices_data = self._create_audio_choice(omni_outputs, role, request, stream=False)
|
||||
elif omni_outputs.final_output_type == "image":
|
||||
@@ -2048,6 +2106,254 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
return choices
|
||||
|
||||
# ==================== Diffusion Mode Methods ====================
|
||||
def _build_multistage_generation_inputs(
|
||||
self,
|
||||
*,
|
||||
engine: AsyncOmni,
|
||||
prompt: str,
|
||||
extra_body: dict[str, Any],
|
||||
reference_images: list[Image.Image],
|
||||
gen_params: OmniDiffusionSamplingParams,
|
||||
) -> tuple[OmniTextPrompt, list[Any]]:
|
||||
"""Build the shared multistage generation prompt and stage params."""
|
||||
stage_configs = getattr(engine, "stage_configs", None) or []
|
||||
default_params_list = list(getattr(engine, "default_sampling_params_list", []) or [])
|
||||
|
||||
height = gen_params.height
|
||||
width = gen_params.width
|
||||
seed = gen_params.seed
|
||||
generator_device = gen_params.generator_device
|
||||
num_outputs_per_prompt = gen_params.num_outputs_per_prompt
|
||||
num_inference_steps = extra_body.get("num_inference_steps")
|
||||
guidance_scale = extra_body.get("guidance_scale")
|
||||
true_cfg_scale = extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale")
|
||||
negative_prompt = extra_body.get("negative_prompt")
|
||||
num_frames = extra_body.get("num_frames")
|
||||
guidance_scale_2 = extra_body.get("guidance_scale_2")
|
||||
lora_body = extra_body.get("lora")
|
||||
layers = extra_body.get("layers")
|
||||
resolution = extra_body.get("resolution")
|
||||
|
||||
engine_prompt_data: dict[str, Any] | None = None
|
||||
modalities = ["image"]
|
||||
if reference_images:
|
||||
if len(reference_images) == 1:
|
||||
engine_prompt_data = {"img2img": reference_images[0]}
|
||||
modalities = ["img2img"]
|
||||
else:
|
||||
engine_prompt_data = {"image": reference_images}
|
||||
|
||||
engine_prompt: OmniTextPrompt = {"prompt": prompt}
|
||||
engine_prompt["modalities"] = modalities
|
||||
if negative_prompt is not None:
|
||||
engine_prompt["negative_prompt"] = negative_prompt
|
||||
|
||||
mm_processor_kwargs: dict[str, Any] = {}
|
||||
if height is not None:
|
||||
mm_processor_kwargs["target_h"] = height
|
||||
if width is not None:
|
||||
mm_processor_kwargs["target_w"] = width
|
||||
if mm_processor_kwargs:
|
||||
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
if engine_prompt_data is not None:
|
||||
engine_prompt["multi_modal_data"] = engine_prompt_data
|
||||
|
||||
comprehension_idx = None
|
||||
for idx, stage in enumerate(stage_configs):
|
||||
if getattr(stage, "is_comprehension", False):
|
||||
comprehension_idx = idx
|
||||
break
|
||||
|
||||
sampling_params_list: list[Any] = []
|
||||
for idx, stage_cfg in enumerate(stage_configs):
|
||||
stage_type = get_stage_type(stage_cfg)
|
||||
if idx < len(default_params_list):
|
||||
default_stage_params = default_params_list[idx]
|
||||
if hasattr(default_stage_params, "clone"):
|
||||
try:
|
||||
default_stage_params = default_stage_params.clone()
|
||||
except Exception:
|
||||
pass
|
||||
elif stage_type == "diffusion":
|
||||
default_stage_params = gen_params.clone()
|
||||
else:
|
||||
default_stage_params = SamplingParams()
|
||||
|
||||
if (
|
||||
comprehension_idx is not None
|
||||
and idx == comprehension_idx
|
||||
and seed is not None
|
||||
and hasattr(default_stage_params, "seed")
|
||||
):
|
||||
default_stage_params.seed = seed
|
||||
|
||||
if stage_type == "diffusion":
|
||||
self._set_if_supported(
|
||||
default_stage_params,
|
||||
height=height,
|
||||
width=width,
|
||||
seed=seed,
|
||||
generator_device=generator_device,
|
||||
num_outputs_per_prompt=num_outputs_per_prompt,
|
||||
num_inference_steps=num_inference_steps,
|
||||
guidance_scale=guidance_scale,
|
||||
true_cfg_scale=true_cfg_scale,
|
||||
num_frames=num_frames,
|
||||
guidance_scale_2=guidance_scale_2,
|
||||
layers=layers,
|
||||
resolution=resolution,
|
||||
)
|
||||
if lora_body and isinstance(lora_body, dict):
|
||||
try:
|
||||
lora_req, lora_scale = parse_lora_request(lora_body)
|
||||
if lora_req is not None:
|
||||
default_stage_params.lora_request = lora_req
|
||||
if lora_scale is not None:
|
||||
default_stage_params.lora_scale = lora_scale
|
||||
except Exception as e: # pragma: no cover - safeguard
|
||||
logger.warning("Failed to parse LoRA request: %s", e)
|
||||
|
||||
sampling_params_list.append(default_stage_params)
|
||||
|
||||
return engine_prompt, sampling_params_list
|
||||
|
||||
async def generate_diffusion_images(
|
||||
self,
|
||||
*,
|
||||
prompt: str,
|
||||
extra_body: dict[str, Any] | None = None,
|
||||
reference_images: list[str] | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> tuple[list[Image.Image], dict[str, Any], float] | ErrorResponse:
|
||||
"""Generate diffusion images and return raw images plus generation stats."""
|
||||
if request_id is None:
|
||||
request_id = f"chatcmpl-{uuid.uuid4().hex[:16]}"
|
||||
if extra_body is None:
|
||||
extra_body = {}
|
||||
if reference_images is None:
|
||||
reference_images = []
|
||||
|
||||
engine = self._diffusion_engine if self._diffusion_engine is not None else self.engine_client
|
||||
|
||||
height = extra_body.get("height")
|
||||
width = extra_body.get("width")
|
||||
if "size" in extra_body:
|
||||
try:
|
||||
size_str = extra_body["size"]
|
||||
if isinstance(size_str, str) and "x" in size_str.lower():
|
||||
w, h = size_str.lower().split("x")
|
||||
width, height = int(w), int(h)
|
||||
except ValueError:
|
||||
logger.warning("Invalid size format: %s", extra_body.get("size"))
|
||||
|
||||
seed = extra_body.get("seed")
|
||||
generator_device = extra_body.get("generator_device")
|
||||
negative_prompt = extra_body.get("negative_prompt")
|
||||
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt", 1)
|
||||
lora_body = extra_body.get("lora")
|
||||
|
||||
pil_images: list[Image.Image] = []
|
||||
for img_b64 in reference_images:
|
||||
try:
|
||||
img_bytes = base64.b64decode(img_b64)
|
||||
pil_images.append(Image.open(BytesIO(img_bytes)))
|
||||
except Exception as e:
|
||||
logger.warning("Failed to decode reference image: %s", e)
|
||||
|
||||
gen_params = OmniDiffusionSamplingParams(
|
||||
height=height,
|
||||
width=width,
|
||||
num_outputs_per_prompt=num_outputs_per_prompt,
|
||||
seed=seed,
|
||||
)
|
||||
self._set_if_supported(
|
||||
gen_params,
|
||||
generator_device=generator_device,
|
||||
num_inference_steps=extra_body.get("num_inference_steps"),
|
||||
guidance_scale=extra_body.get("guidance_scale"),
|
||||
true_cfg_scale=extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale"),
|
||||
num_frames=extra_body.get("num_frames"),
|
||||
guidance_scale_2=extra_body.get("guidance_scale_2"),
|
||||
layers=extra_body.get("layers"),
|
||||
resolution=extra_body.get("resolution"),
|
||||
)
|
||||
|
||||
if lora_body and isinstance(lora_body, dict):
|
||||
try:
|
||||
lora_req, lora_scale = parse_lora_request(lora_body)
|
||||
if lora_req is not None:
|
||||
gen_params.lora_request = lora_req
|
||||
if lora_scale is not None:
|
||||
gen_params.lora_scale = lora_scale
|
||||
except Exception as e: # pragma: no cover - safeguard
|
||||
logger.warning("Failed to parse LoRA request: %s", e)
|
||||
|
||||
gen_prompt: OmniTextPrompt = {
|
||||
"prompt": prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
}
|
||||
if pil_images:
|
||||
if len(pil_images) == 1:
|
||||
gen_prompt["multi_modal_data"] = {"image": pil_images[0]}
|
||||
else:
|
||||
od_config = getattr(engine, "od_config", None)
|
||||
supports_multimodal_inputs = getattr(od_config, "supports_multimodal_inputs", False)
|
||||
if od_config is None:
|
||||
supports_multimodal_inputs = True
|
||||
if supports_multimodal_inputs:
|
||||
gen_prompt["multi_modal_data"] = {"image": pil_images}
|
||||
else:
|
||||
return self._create_error_response(
|
||||
"Multiple input images are not supported by the current diffusion model. "
|
||||
"For multi-image editing, start the server with Qwen-Image-Edit-2509 "
|
||||
"and send multiple images in the user message content.",
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
if isinstance(engine, AsyncOmni):
|
||||
diffusion_engine = cast(AsyncOmni, engine)
|
||||
stage_configs = getattr(diffusion_engine, "stage_configs", None) or []
|
||||
if len(stage_configs) > 1:
|
||||
engine_prompt, sampling_params_list = self._build_multistage_generation_inputs(
|
||||
engine=diffusion_engine,
|
||||
prompt=prompt,
|
||||
extra_body=extra_body,
|
||||
reference_images=pil_images,
|
||||
gen_params=gen_params,
|
||||
)
|
||||
else:
|
||||
engine_prompt = gen_prompt
|
||||
sampling_params_list = [gen_params]
|
||||
|
||||
result = None
|
||||
async for output in diffusion_engine.generate(
|
||||
prompt=engine_prompt,
|
||||
sampling_params_list=sampling_params_list,
|
||||
request_id=request_id,
|
||||
):
|
||||
result = output
|
||||
if result is None:
|
||||
return self._create_error_response("No output generated from AsyncOmni", status_code=500)
|
||||
else:
|
||||
result = await engine.generate(
|
||||
prompt=gen_prompt,
|
||||
sampling_params=gen_params,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
images = getattr(result.request_output, "images", [])
|
||||
stage_durations = result.stage_durations
|
||||
peak_memory_mb = result.peak_memory_mb
|
||||
|
||||
flat_images: list[Image.Image] = []
|
||||
for item in images:
|
||||
if isinstance(item, list):
|
||||
flat_images.extend(item)
|
||||
else:
|
||||
flat_images.append(item)
|
||||
|
||||
return flat_images, stage_durations, peak_memory_mb
|
||||
|
||||
async def _create_diffusion_chat_completion(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
@@ -2108,6 +2414,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
num_inference_steps = extra_body.get("num_inference_steps")
|
||||
guidance_scale = extra_body.get("guidance_scale")
|
||||
true_cfg_scale = extra_body.get("true_cfg_scale") or extra_body.get("cfg_scale")
|
||||
cfg_text_scale = extra_body.get("cfg_text_scale")
|
||||
cfg_img_scale = extra_body.get("cfg_img_scale")
|
||||
seed = extra_body.get("seed")
|
||||
negative_prompt = extra_body.get("negative_prompt")
|
||||
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt", 1)
|
||||
@@ -2162,6 +2470,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
gen_params.guidance_scale = guidance_scale
|
||||
if true_cfg_scale is not None:
|
||||
gen_params.true_cfg_scale = true_cfg_scale
|
||||
if cfg_text_scale is not None:
|
||||
gen_params.extra_args["cfg_text_scale"] = cfg_text_scale
|
||||
if cfg_img_scale is not None:
|
||||
gen_params.extra_args["cfg_img_scale"] = cfg_img_scale
|
||||
if num_frames is not None:
|
||||
gen_params.num_frames = num_frames
|
||||
if guidance_scale_2 is not None:
|
||||
@@ -2182,7 +2494,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
except Exception as e: # pragma: no cover - safeguard
|
||||
logger.warning("Failed to parse LoRA request: %s", e)
|
||||
|
||||
# Add reference image if provided
|
||||
# Add reference image if provided (from messages content)
|
||||
if pil_images:
|
||||
if len(pil_images) == 1:
|
||||
gen_prompt["multi_modal_data"] = {}
|
||||
@@ -2206,10 +2518,30 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
|
||||
# Generate image
|
||||
diffusion_engine = cast(AsyncOmni, self._diffusion_engine)
|
||||
stage_configs = list(getattr(diffusion_engine, "stage_configs", []) or [])
|
||||
default_params_list = list(getattr(diffusion_engine, "default_sampling_params_list", []) or [])
|
||||
|
||||
sampling_params_list: list[Any] = []
|
||||
for idx, stage_cfg in enumerate(stage_configs):
|
||||
if get_stage_type(stage_cfg) == "diffusion":
|
||||
sampling_params_list.append(gen_params)
|
||||
continue
|
||||
|
||||
default_stage_params = default_params_list[idx] if idx < len(default_params_list) else SamplingParams()
|
||||
if hasattr(default_stage_params, "clone"):
|
||||
try:
|
||||
default_stage_params = default_stage_params.clone()
|
||||
except Exception as e:
|
||||
logger.warning("Failed to clone default params for stage %d: %s", idx, e)
|
||||
sampling_params_list.append(default_stage_params)
|
||||
|
||||
if not sampling_params_list:
|
||||
sampling_params_list = [gen_params]
|
||||
|
||||
result = None
|
||||
async for output in diffusion_engine.generate(
|
||||
prompt=gen_prompt,
|
||||
sampling_params_list=[gen_params], # Pass as single-stage params
|
||||
sampling_params_list=sampling_params_list,
|
||||
request_id=request_id,
|
||||
):
|
||||
result = output
|
||||
@@ -2353,6 +2685,48 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
prompt = " ".join(prompt_parts).strip()
|
||||
return prompt, images
|
||||
|
||||
def _extract_diffusion_prompt_and_images_from_messages(
|
||||
self,
|
||||
messages: list[Any],
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Normalize mixed message types and extract prompt + reference images once."""
|
||||
return self._extract_diffusion_prompt_and_images(self._messages_to_dicts(messages))
|
||||
|
||||
@staticmethod
|
||||
def _messages_to_dicts(messages: list[Any]) -> list[dict[str, Any]]:
|
||||
"""Normalize request messages to plain dicts."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for msg in messages:
|
||||
if hasattr(msg, "model_dump"):
|
||||
out.append(msg.model_dump())
|
||||
elif isinstance(msg, dict):
|
||||
out.append(msg)
|
||||
else:
|
||||
out.append(
|
||||
{
|
||||
"role": getattr(msg, "role", "user"),
|
||||
"content": getattr(msg, "content", ""),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _resolve_height_width_from_extra_body(extra_body: dict[str, Any]) -> tuple[Any, Any]:
|
||||
"""Extract generation height/width with optional size string fallback."""
|
||||
height = extra_body.get("height")
|
||||
width = extra_body.get("width")
|
||||
|
||||
if "size" in extra_body and (height is None or width is None):
|
||||
try:
|
||||
size_str = extra_body["size"]
|
||||
if isinstance(size_str, str) and "x" in size_str.lower():
|
||||
w, h = size_str.lower().split("x")
|
||||
width, height = int(w), int(h)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return height, width
|
||||
|
||||
def _create_error_response(
|
||||
self,
|
||||
message: str,
|
||||
|
||||
@@ -17,12 +17,17 @@ import torch
|
||||
from fastapi import Request, UploadFile
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from transformers.utils.hub import cached_file
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.launcher import terminate_if_errored
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
RequestResponseMetadata,
|
||||
)
|
||||
from vllm.entrypoints.openai.engine.serving import OpenAIServing
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.media import MediaConnector
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.async_utils import make_async
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
@@ -49,6 +54,7 @@ _QWEN3_TTS_MODEL_STAGES = {"qwen3_tts"}
|
||||
_FISH_TTS_MODEL_STAGES = {"fish_speech_slow_ar"}
|
||||
_COSYVOICE3_TTS_MODEL_STAGES = {"cosyvoice3_talker"}
|
||||
_OMNIVOICE_TTS_MODEL_STAGES = {"omnivoice_generator"}
|
||||
_VOXCPM_TTS_MODEL_STAGES = {"latent_generator", "vae"}
|
||||
_VOXCPM2_TTS_MODEL_STAGES = {"latent_generator"}
|
||||
_MOSS_TTS_MODEL_STAGES = {"moss_tts_nano"}
|
||||
_TTS_MODEL_STAGES: set[str] = (
|
||||
@@ -57,6 +63,7 @@ _TTS_MODEL_STAGES: set[str] = (
|
||||
| _FISH_TTS_MODEL_STAGES
|
||||
| _COSYVOICE3_TTS_MODEL_STAGES
|
||||
| _OMNIVOICE_TTS_MODEL_STAGES
|
||||
| _VOXCPM_TTS_MODEL_STAGES
|
||||
| _VOXCPM2_TTS_MODEL_STAGES
|
||||
| _MOSS_TTS_MODEL_STAGES
|
||||
)
|
||||
@@ -216,6 +223,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"Re-upload voices after each restart if needed."
|
||||
)
|
||||
self._tts_tokenizer = None
|
||||
self._voxcpm2_tokenizer = None
|
||||
self._voxcpm2_split_map: dict[int, list[int]] = {}
|
||||
|
||||
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
|
||||
|
||||
@@ -284,6 +293,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if self._tts_stage is None:
|
||||
return None
|
||||
model_stage = getattr(self._tts_stage.engine_args, "model_stage", None)
|
||||
model_arch = getattr(self._tts_stage.engine_args, "model_arch", None)
|
||||
if model_arch == "VoxCPM2TalkerForConditionalGeneration":
|
||||
return "voxcpm2"
|
||||
if model_arch == "VoxCPMForConditionalGeneration":
|
||||
return "voxcpm"
|
||||
if model_stage in _QWEN3_TTS_MODEL_STAGES:
|
||||
return "qwen3_tts"
|
||||
if model_stage in _VOXTRAL_TTS_MODEL_STAGES:
|
||||
@@ -298,6 +312,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
return "voxcpm2"
|
||||
if model_stage in _MOSS_TTS_MODEL_STAGES:
|
||||
return "moss_tts_nano"
|
||||
if model_stage in (_VOXCPM_TTS_MODEL_STAGES | _VOXCPM2_TTS_MODEL_STAGES):
|
||||
has_vae_stage = any(
|
||||
getattr(getattr(stage, "engine_args", None), "model_stage", None) == "vae"
|
||||
for stage in self.engine_client.stage_configs
|
||||
)
|
||||
return "voxcpm" if has_vae_stage or model_stage == "vae" else "voxcpm2"
|
||||
return None
|
||||
|
||||
def _compute_max_instructions_length(self) -> int:
|
||||
@@ -322,6 +342,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
def _load_supported_speakers(self) -> set[str]:
|
||||
"""Load supported speakers (case-insensitive) from the model configuration."""
|
||||
try:
|
||||
if self._tts_model_type == "voxcpm":
|
||||
return set()
|
||||
if self._tts_model_type == "voxtral_tts":
|
||||
config = self.engine_client.model_config.hf_config.audio_config
|
||||
else:
|
||||
@@ -381,6 +403,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
def _estimate_prompt_len(self, tts_params: dict[str, Any]) -> int:
|
||||
"""Estimate prompt length so the placeholder matches model-side embeddings."""
|
||||
try:
|
||||
if self._tts_model_type == "voxcpm":
|
||||
return 1
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import (
|
||||
Qwen3TTSTalkerForConditionalGeneration,
|
||||
)
|
||||
@@ -444,6 +468,25 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
logger.warning("Failed to estimate Fish Speech prompt length, using fallback 2048: %s", e)
|
||||
return 2048
|
||||
|
||||
async def _build_voxcpm2_prompt(self, request: OpenAICreateSpeechRequest) -> dict[str, Any]:
|
||||
"""Build prefill prompt for VoxCPM2 TTS (`prompt_token_ids` padded to full prefill length)."""
|
||||
from vllm_omni.model_executor.models.voxcpm2.voxcpm2_talker import build_voxcpm2_prompt
|
||||
|
||||
self._voxcpm2_encode("") # lazy-init tokenizer + split_map
|
||||
ref_audio = None
|
||||
ref_sr = None
|
||||
if request.ref_audio is not None:
|
||||
ref_audio, ref_sr = await self._resolve_ref_audio(request.ref_audio)
|
||||
return build_voxcpm2_prompt(
|
||||
hf_config=self.engine_client.model_config.hf_config,
|
||||
tokenizer=self._voxcpm2_tokenizer,
|
||||
split_map=self._voxcpm2_split_map,
|
||||
text=request.input,
|
||||
ref_audio=ref_audio,
|
||||
ref_sr=ref_sr,
|
||||
ref_text=request.ref_text,
|
||||
)
|
||||
|
||||
def _get_uploaded_audio_data(self, voice_name: str) -> str | None:
|
||||
"""Get base64 encoded audio data for uploaded voice."""
|
||||
voice_name_lower = voice_name.lower()
|
||||
@@ -795,12 +838,33 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
return self._validate_fish_tts_request(request)
|
||||
if self._tts_model_type == "cosyvoice3":
|
||||
return self._validate_cosyvoice3_request(request)
|
||||
if self._tts_model_type == "voxcpm":
|
||||
return self._validate_voxcpm_request(request)
|
||||
if self._tts_model_type == "voxcpm2":
|
||||
return None # VoxCPM2 accepts any text input
|
||||
if self._tts_model_type == "moss_tts_nano":
|
||||
return self._validate_moss_tts_request(request)
|
||||
return self._validate_qwen_tts_request(request)
|
||||
|
||||
def _voxcpm2_encode(self, text: str) -> list[int]:
|
||||
"""Tokenize text for VoxCPM2, splitting multichar Chinese tokens."""
|
||||
from vllm_omni.model_executor.models.voxcpm2.voxcpm2_talker import (
|
||||
build_cjk_split_map,
|
||||
split_multichar_chinese,
|
||||
)
|
||||
|
||||
if self._voxcpm2_tokenizer is None:
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
model_name = self.engine_client.model_config.model
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
||||
self._voxcpm2_split_map = build_cjk_split_map(tokenizer)
|
||||
self._voxcpm2_tokenizer = tokenizer
|
||||
logger.info("VoxCPM2 serving: built multichar split map (%d entries)", len(self._voxcpm2_split_map))
|
||||
|
||||
ids = self._voxcpm2_tokenizer.encode(text, add_special_tokens=True)
|
||||
return split_multichar_chinese(ids, self._voxcpm2_split_map)
|
||||
|
||||
def _validate_ref_audio_format(self, ref_audio: str) -> str | None:
|
||||
"""Validate ref_audio is a supported URI format. Returns error or None."""
|
||||
if not (
|
||||
@@ -838,6 +902,43 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
return None
|
||||
|
||||
def _validate_voxcpm_request(self, request: OpenAICreateSpeechRequest) -> str | None:
|
||||
"""Validate VoxCPM request parameters. Returns error message or None."""
|
||||
if not request.input or not request.input.strip():
|
||||
return "Input text cannot be empty"
|
||||
|
||||
if request.voice is not None:
|
||||
return "'voice' is not supported for VoxCPM"
|
||||
if request.instructions is not None:
|
||||
return "'instructions' is not supported for VoxCPM"
|
||||
if request.language is not None:
|
||||
return "'language' is not supported for VoxCPM"
|
||||
if request.task_type not in (None, "Base"):
|
||||
return "VoxCPM only supports plain TTS or voice cloning with ref_audio/ref_text"
|
||||
if request.x_vector_only_mode is not None:
|
||||
return "'x_vector_only_mode' is not supported for VoxCPM"
|
||||
if request.speaker_embedding is not None:
|
||||
return "'speaker_embedding' is not supported for VoxCPM"
|
||||
if request.initial_codec_chunk_frames is not None:
|
||||
return "'initial_codec_chunk_frames' is not supported for VoxCPM"
|
||||
|
||||
if request.ref_audio is not None:
|
||||
fmt_err = self._validate_ref_audio_format(request.ref_audio)
|
||||
if fmt_err:
|
||||
return fmt_err
|
||||
if not request.ref_text or not request.ref_text.strip():
|
||||
return "Voice cloning requires 'ref_text' (transcript of the reference audio)"
|
||||
elif request.ref_text is not None:
|
||||
return "'ref_text' requires 'ref_audio' for VoxCPM voice cloning"
|
||||
|
||||
if request.max_new_tokens is not None:
|
||||
if request.max_new_tokens < _TTS_MAX_NEW_TOKENS_MIN:
|
||||
return f"max_new_tokens must be at least {_TTS_MAX_NEW_TOKENS_MIN}"
|
||||
if request.max_new_tokens > _TTS_MAX_NEW_TOKENS_MAX:
|
||||
return f"max_new_tokens cannot exceed {_TTS_MAX_NEW_TOKENS_MAX}"
|
||||
|
||||
return None
|
||||
|
||||
def _validate_qwen_tts_request(self, request: OpenAICreateSpeechRequest) -> str | None:
|
||||
"""Validate Qwen TTS request parameters. Returns error message or None."""
|
||||
# Infer Base task when ref_audio or ref_text is provided without explicit task_type.
|
||||
@@ -1087,7 +1188,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
)
|
||||
return wav_np.tolist(), sr
|
||||
|
||||
async def _generate_audio_chunks(self, generator, request_id: str, response_format: str = "pcm"):
|
||||
async def _generate_audio_chunks(
|
||||
self,
|
||||
generator,
|
||||
request_id: str,
|
||||
response_format: str = "pcm",
|
||||
raw_request: Request | None = None,
|
||||
):
|
||||
"""Generate audio chunks for streaming response.
|
||||
|
||||
Handles two audio output modes from the engine:
|
||||
@@ -1162,6 +1269,19 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Streaming request %s cancelled by client", request_id)
|
||||
raise
|
||||
except EngineDeadError as e:
|
||||
logger.error(
|
||||
"EngineDeadError during streaming speech for %s: %s",
|
||||
request_id,
|
||||
e,
|
||||
)
|
||||
# Actively signal shutdown rather than relying on the watchdog.
|
||||
if raw_request is not None:
|
||||
terminate_if_errored(
|
||||
server=raw_request.app.state.server,
|
||||
engine=self.engine_client,
|
||||
)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception("Streaming speech generation failed for %s: %s", request_id, e)
|
||||
raise
|
||||
@@ -1199,6 +1319,18 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
Processes each parameter if present, skips if not.
|
||||
Values are wrapped in lists as required by the model.
|
||||
"""
|
||||
if self._tts_model_type == "voxcpm":
|
||||
params: dict[str, Any] = {
|
||||
"text": [request.input],
|
||||
"cfg_value": [2.0],
|
||||
"inference_timesteps": [10],
|
||||
"min_len": [2],
|
||||
"max_new_tokens": [request.max_new_tokens or 4096],
|
||||
}
|
||||
if request.ref_text is not None:
|
||||
params["ref_text"] = [request.ref_text]
|
||||
return params
|
||||
|
||||
params: dict[str, Any] = {}
|
||||
|
||||
# Text content (always required)
|
||||
@@ -1424,6 +1556,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
async def _prepare_speech_generation(
|
||||
self,
|
||||
request: OpenAICreateSpeechRequest,
|
||||
request_id: str | None = None,
|
||||
) -> tuple[str, Any, dict[str, Any]]:
|
||||
if self.engine_client.errored:
|
||||
raise self.engine_client.dead_error
|
||||
@@ -1467,14 +1600,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if request.instructions:
|
||||
prompt["instruct"] = request.instructions
|
||||
elif self._tts_model_type == "voxcpm2":
|
||||
prompt = await self._build_voxcpm2_prompt(request)
|
||||
tts_params = {}
|
||||
additional: dict[str, Any] = {}
|
||||
if request.ref_audio is not None:
|
||||
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
|
||||
additional["reference_audio"] = [[wav_list, sr]]
|
||||
prompt = {"prompt": request.input}
|
||||
if additional:
|
||||
prompt["additional_information"] = additional
|
||||
elif self._is_tts:
|
||||
validation_error = self._validate_tts_request(request)
|
||||
if validation_error:
|
||||
@@ -1525,13 +1652,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
tts_params = {}
|
||||
prompt = {"prompt": request.input}
|
||||
|
||||
request_id = f"speech-{random_uuid()}"
|
||||
request_id = request_id or f"speech-{random_uuid()}"
|
||||
if self._is_fish_speech:
|
||||
model_type = "fish_speech"
|
||||
elif self._tts_model_type == "voxtral_tts":
|
||||
model_type = "voxtral_tts"
|
||||
elif self._tts_model_type == "cosyvoice3":
|
||||
model_type = "cosyvoice3"
|
||||
elif self._tts_model_type == "voxcpm":
|
||||
model_type = "voxcpm"
|
||||
elif self._tts_model_type == "voxcpm2":
|
||||
model_type = "voxcpm2"
|
||||
elif self._is_tts:
|
||||
@@ -1605,8 +1734,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
self,
|
||||
request: OpenAICreateSpeechRequest,
|
||||
base64_encode: bool = False,
|
||||
request_id: str | None = None,
|
||||
) -> tuple[bytes | str, str]:
|
||||
request_id, generator, _ = await self._prepare_speech_generation(request)
|
||||
request_id, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
|
||||
|
||||
final_output: OmniRequestOutput | None = None
|
||||
async for res in generator:
|
||||
@@ -1730,6 +1860,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
except asyncio.CancelledError:
|
||||
return self._diffusion_error_response("Client disconnected")
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except ValueError as e:
|
||||
return self._diffusion_error_response(str(e))
|
||||
except Exception as e:
|
||||
@@ -1775,6 +1907,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
logger.error("Error with model %s", error_check_ret)
|
||||
return error_check_ret
|
||||
|
||||
request_id = f"speech-{random_uuid()}"
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
try:
|
||||
if request.stream:
|
||||
# Determine response format and media type for streaming
|
||||
@@ -1795,17 +1933,24 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
)
|
||||
|
||||
media_type = "audio/wav" if response_format == "wav" else "audio/pcm"
|
||||
request_id, generator, _ = await self._prepare_speech_generation(request)
|
||||
_, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
|
||||
return StreamingResponse(
|
||||
self._generate_audio_chunks(generator, request_id, response_format),
|
||||
self._generate_audio_chunks(
|
||||
generator,
|
||||
request_id,
|
||||
response_format,
|
||||
raw_request=raw_request,
|
||||
),
|
||||
media_type=media_type,
|
||||
)
|
||||
|
||||
audio_bytes, media_type = await self._generate_audio_bytes(request)
|
||||
audio_bytes, media_type = await self._generate_audio_bytes(request, request_id=request_id)
|
||||
return Response(content=audio_bytes, media_type=media_type)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
return self.create_error_response("Client disconnected")
|
||||
except (EngineGenerateError, EngineDeadError):
|
||||
raise # Propagate to the global Omni exception handler
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
except Exception as e:
|
||||
|
||||
@@ -113,6 +113,10 @@ class OmniOpenAIServingVideo:
|
||||
if vp.fps is not None:
|
||||
gen_params.fps = vp.fps
|
||||
gen_params.frame_rate = float(vp.fps)
|
||||
gen_params.enable_frame_interpolation = request.enable_frame_interpolation
|
||||
gen_params.frame_interpolation_exp = request.frame_interpolation_exp
|
||||
gen_params.frame_interpolation_scale = request.frame_interpolation_scale
|
||||
gen_params.frame_interpolation_model_path = request.frame_interpolation_model_path
|
||||
|
||||
if request.num_inference_steps is not None:
|
||||
gen_params.num_inference_steps = request.num_inference_steps
|
||||
@@ -160,7 +164,7 @@ class OmniOpenAIServingVideo:
|
||||
videos = self._extract_video_outputs(result)
|
||||
audios = self._extract_audio_outputs(result, expected_count=len(videos))
|
||||
audio_sample_rate = self._resolve_audio_sample_rate(result)
|
||||
output_fps = vp.fps or self._resolve_fps(result) or 24
|
||||
output_fps = (vp.fps or self._resolve_fps(result) or 24) * self._resolve_video_fps_multiplier(result)
|
||||
return VideoGenerationArtifacts(
|
||||
videos=videos,
|
||||
audios=audios,
|
||||
@@ -243,6 +247,22 @@ class OmniOpenAIServingVideo:
|
||||
logger.info("Video response encoding (MP4 bytes): %.2f ms", _t_encode_ms)
|
||||
return video_bytes, artifacts.stage_durations, artifacts.peak_memory_mb
|
||||
|
||||
@staticmethod
|
||||
def _resolve_video_fps_multiplier(result: Any) -> int:
|
||||
custom_output = getattr(result, "custom_output", None)
|
||||
if isinstance(custom_output, dict):
|
||||
multiplier = custom_output.get("video_fps_multiplier")
|
||||
if multiplier is not None:
|
||||
return int(multiplier)
|
||||
request_output = getattr(result, "request_output", None)
|
||||
if request_output is not None:
|
||||
custom_output = getattr(request_output, "custom_output", None)
|
||||
if isinstance(custom_output, dict):
|
||||
multiplier = custom_output.get("video_fps_multiplier")
|
||||
if multiplier is not None:
|
||||
return int(multiplier)
|
||||
return 1
|
||||
|
||||
@staticmethod
|
||||
def _apply_lora(lora_body: Any, gen_params: OmniDiffusionSamplingParams) -> None:
|
||||
try:
|
||||
|
||||
@@ -227,6 +227,9 @@ def _encode_video_bytes(
|
||||
frames_np *= 255.0
|
||||
frames_u8 = np.round(frames_np).astype(np.uint8)
|
||||
|
||||
# Ensure contiguous memory layout for faster PyAV muxing
|
||||
frames_u8 = np.ascontiguousarray(frames_u8)
|
||||
|
||||
audio_np = _coerce_audio_to_numpy(audio) if audio is not None else None
|
||||
|
||||
return mux_video_audio_bytes(
|
||||
|
||||
Reference in new issue
Block a user