Merge origin/main into dev/vllm-align
Resolved conflicts: - vllm_omni/inputs/preprocess.py: took origin/main's elif mm_processor_kwargs branch, fixed undefined mm_uuids reference - vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code_predictor_vllm.py: took origin/main's NPU support Made-with: Cursor Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
commit
26744bcb35
240 files changed
+25869
-3091
No files matched your search
@@ -141,9 +141,20 @@ class AsyncOmni(OmniBase):
|
||||
sequence_parallel_size = kwargs.get("sequence_parallel_size")
|
||||
tensor_parallel_size = kwargs.get("tensor_parallel_size") or 1
|
||||
cfg_parallel_size = kwargs.get("cfg_parallel_size") or 1
|
||||
use_hsdp = kwargs.get("use_hsdp", False)
|
||||
hsdp_shard_size = kwargs.get("hsdp_shard_size", -1)
|
||||
hsdp_replicate_size = kwargs.get("hsdp_replicate_size", 1)
|
||||
if sequence_parallel_size is None:
|
||||
sequence_parallel_size = ulysses_degree * ring_degree
|
||||
num_devices = sequence_parallel_size * tensor_parallel_size * cfg_parallel_size
|
||||
|
||||
# Calculate num_devices: consider standalone HSDP
|
||||
other_parallel_size = sequence_parallel_size * tensor_parallel_size * cfg_parallel_size
|
||||
if use_hsdp and other_parallel_size == 1 and hsdp_shard_size > 0:
|
||||
# Standalone HSDP: num_devices is determined by HSDP dimensions
|
||||
num_devices = hsdp_shard_size * hsdp_replicate_size
|
||||
else:
|
||||
num_devices = other_parallel_size
|
||||
|
||||
for i in range(1, num_devices):
|
||||
devices += f",{i}"
|
||||
parallel_config = DiffusionParallelConfig(
|
||||
@@ -154,6 +165,9 @@ class AsyncOmni(OmniBase):
|
||||
ulysses_degree=ulysses_degree,
|
||||
ring_degree=ring_degree,
|
||||
cfg_parallel_size=cfg_parallel_size,
|
||||
use_hsdp=use_hsdp,
|
||||
hsdp_shard_size=hsdp_shard_size,
|
||||
hsdp_replicate_size=hsdp_replicate_size,
|
||||
)
|
||||
default_stage_cfg = [
|
||||
{
|
||||
@@ -528,12 +542,14 @@ class AsyncOmni(OmniBase):
|
||||
final_output_type=stage.final_output_type,
|
||||
request_output=engine_outputs,
|
||||
images=images,
|
||||
finished=finished,
|
||||
)
|
||||
else:
|
||||
output_to_yield = OmniRequestOutput(
|
||||
stage_id=stage_id,
|
||||
final_output_type=stage.final_output_type,
|
||||
request_output=engine_outputs,
|
||||
finished=finished,
|
||||
)
|
||||
# Mark last output time
|
||||
metrics.stage_last_ts[stage_id] = max(metrics.stage_last_ts[stage_id] or 0.0, time.time())
|
||||
|
||||
@@ -263,7 +263,7 @@ class AsyncOmniDiffusion:
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
|
||||
async def add_lora(self, lora_request: LoRARequest, lora_scale: float = 1.0) -> bool:
|
||||
async def add_lora(self, lora_request: LoRARequest) -> bool:
|
||||
"""Add a LoRA adapter"""
|
||||
loop = asyncio.get_event_loop()
|
||||
results = await loop.run_in_executor(
|
||||
@@ -272,7 +272,7 @@ class AsyncOmniDiffusion:
|
||||
"add_lora",
|
||||
None,
|
||||
(),
|
||||
{"lora_request": lora_request, "lora_scale": lora_scale},
|
||||
{"lora_request": lora_request},
|
||||
None,
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
@@ -310,3 +310,29 @@ class AsyncOmniDiffusion:
|
||||
None,
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
|
||||
async def start_profile(self, trace_filename: str | None = None) -> None:
|
||||
"""Start profiling for the diffusion model.
|
||||
|
||||
Args:
|
||||
trace_filename: Optional base filename for trace files.
|
||||
If None, a timestamp-based name will be generated.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
self._executor,
|
||||
self.engine.start_profile,
|
||||
trace_filename,
|
||||
)
|
||||
|
||||
async def stop_profile(self) -> dict:
|
||||
"""Stop profiling and return profiling results.
|
||||
|
||||
Returns:
|
||||
Dictionary containing paths to trace and table files.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
self._executor,
|
||||
self.engine.stop_profile,
|
||||
)
|
||||
@@ -6,6 +6,7 @@ diffusion models (e.g., Qwen-Image) through the same CLI interface.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
from typing import Any
|
||||
@@ -209,6 +210,36 @@ class OmniServeCommand(CLISubcommand):
|
||||
help="Ring Sequence Parallelism degree for diffusion models. "
|
||||
"Equivalent to setting DiffusionParallelConfig.ring_degree.",
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--quantization-config",
|
||||
type=json.loads,
|
||||
default=None,
|
||||
help=(
|
||||
"JSON string for diffusion quantization_config. "
|
||||
'Example: \'{"method":"gguf","gguf_model":"/path/to/model.gguf"}\'.'
|
||||
),
|
||||
)
|
||||
|
||||
# HSDP (Hybrid Sharded Data Parallel) parameters
|
||||
omni_config_group.add_argument(
|
||||
"--use-hsdp",
|
||||
dest="use_hsdp",
|
||||
action="store_true",
|
||||
help="Enable HSDP (Hybrid Sharded Data Parallel) for diffusion models. "
|
||||
"Shards model weights across GPUs to reduce per-GPU memory usage.",
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--hsdp-shard-size",
|
||||
type=int,
|
||||
default=-1,
|
||||
help="Number of GPUs to shard weights across. -1 = auto (world_size / replicate_size).",
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--hsdp-replicate-size",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of replica groups for HSDP. Each group holds a full sharded copy.",
|
||||
)
|
||||
|
||||
# Cache optimization parameters
|
||||
omni_config_group.add_argument(
|
||||
|
||||
@@ -285,6 +285,13 @@ class OmniBase:
|
||||
if lora_scale is not None:
|
||||
if not hasattr(cfg.engine_args, "lora_scale") or cfg.engine_args.lora_scale is None:
|
||||
cfg.engine_args.lora_scale = lora_scale
|
||||
quantization_config = kwargs.get("quantization_config")
|
||||
if quantization_config is not None:
|
||||
if (
|
||||
not hasattr(cfg.engine_args, "quantization_config")
|
||||
or cfg.engine_args.quantization_config is None
|
||||
):
|
||||
cfg.engine_args.quantization_config = quantization_config
|
||||
except Exception as e:
|
||||
logger.warning("Failed to inject LoRA config for stage: %s", e)
|
||||
|
||||
@@ -371,9 +378,13 @@ class OmniBase:
|
||||
# Allocate endpoints for each stage
|
||||
total_stages = len(self.stage_configs)
|
||||
self._handshake_endpoints = {}
|
||||
|
||||
# If --stage-id is not set, use local_only mode
|
||||
local_only = self._single_stage_id is None
|
||||
|
||||
for sid in range(total_stages):
|
||||
in_endpoint = get_engine_client_zmq_addr(local_only=False, host=self._zmq_master_address)
|
||||
out_endpoint = get_engine_client_zmq_addr(local_only=False, host=self._zmq_master_address)
|
||||
in_endpoint = get_engine_client_zmq_addr(local_only=local_only, host=self._zmq_master_address)
|
||||
out_endpoint = get_engine_client_zmq_addr(local_only=local_only, host=self._zmq_master_address)
|
||||
self._handshake_endpoints[sid] = (in_endpoint, out_endpoint)
|
||||
logger.debug(
|
||||
f"[{self._name}] Allocated endpoints for stage-{sid}: in={in_endpoint}, out={out_endpoint}"
|
||||
@@ -485,6 +496,22 @@ class OmniBase:
|
||||
|
||||
logger.warning(f"[{self._name}] Stage initialization timeout. Troubleshooting Steps:\n{formatted_suggestions}")
|
||||
|
||||
def _is_profiler_enabled(self, stage_id: int) -> bool:
|
||||
"""Check if profiler config is set for a given stage."""
|
||||
stage = self.stage_list[stage_id]
|
||||
# For diffusion stages, profiling is controlled by VLLM_TORCH_PROFILER_DIR env var
|
||||
if stage.stage_type == "diffusion":
|
||||
return True
|
||||
# For LLM stages, check if profiler_config is set in engine_args
|
||||
engine_args = getattr(stage.stage_config, "engine_args", None)
|
||||
if engine_args is None:
|
||||
return False
|
||||
profiler_config = getattr(engine_args, "profiler_config", None)
|
||||
if profiler_config is None:
|
||||
return False
|
||||
profiler = getattr(profiler_config, "profiler", None)
|
||||
return profiler is not None
|
||||
|
||||
def start_profile(self, stages: list[int] | None = None) -> None:
|
||||
"""Start profiling for specified stages.
|
||||
|
||||
@@ -509,6 +536,13 @@ class OmniBase:
|
||||
|
||||
for stage_id in stages:
|
||||
if stage_id < len(self.stage_list):
|
||||
if not self._is_profiler_enabled(stage_id):
|
||||
logger.info(
|
||||
"[%s] Skipping start_profile for stage-%s: profiler config not set",
|
||||
self._name,
|
||||
stage_id,
|
||||
)
|
||||
continue
|
||||
try:
|
||||
self.stage_list[stage_id].submit({"type": OmniStageTaskType.PROFILER_START})
|
||||
logger.info("[%s] Sent start_profile to stage-%s", self._name, stage_id)
|
||||
@@ -532,6 +566,13 @@ class OmniBase:
|
||||
|
||||
for stage_id in stages:
|
||||
if stage_id < len(self.stage_list):
|
||||
if not self._is_profiler_enabled(stage_id):
|
||||
logger.info(
|
||||
"[%s] Skipping stop_profile for stage-%s: profiler config not set",
|
||||
self._name,
|
||||
stage_id,
|
||||
)
|
||||
continue
|
||||
stage = self.stage_list[stage_id]
|
||||
|
||||
# Check if the stage object has our new bridge method
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from collections.abc import Sequence
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, TransformerConfig
|
||||
@@ -14,11 +12,6 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
# TODO configure logging properly
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniDiffusion:
|
||||
"""
|
||||
@@ -54,8 +47,9 @@ class OmniDiffusion:
|
||||
if engine_input_source is not None:
|
||||
self.od_config.omni_kv_config.setdefault("engine_input_source", engine_input_source)
|
||||
|
||||
# Detect model class and load config
|
||||
# Diffusers-style models expose `model_index.json` with `_class_name`.
|
||||
# Non-diffusers models (e.g. Bagel, NextStep) only have `config.json`,
|
||||
# Non-diffusers models (e.g. Bagel, NextStep, GLM-Image) only have `config.json`,
|
||||
# so we fall back to reading that and mapping model_type manually.
|
||||
try:
|
||||
config_dict = get_hf_file_to_dict(
|
||||
@@ -78,22 +72,27 @@ class OmniDiffusion:
|
||||
if cfg is None:
|
||||
raise ValueError(f"Could not find config.json or model_index.json for model {od_config.model}")
|
||||
|
||||
# Map model_type or architecture to pipeline class
|
||||
model_type = cfg.get("model_type")
|
||||
architectures = cfg.get("architectures") or []
|
||||
pipeline_class = None
|
||||
# Bagel/NextStep models don't have a model_index.json, so we set the pipeline class name manually
|
||||
if model_type == "bagel" or "BagelForConditionalGeneration" in architectures:
|
||||
od_config.model_class_name = "BagelPipeline"
|
||||
od_config.tf_model_config = TransformerConfig()
|
||||
od_config.update_multimodal_support()
|
||||
pipeline_class = "BagelPipeline"
|
||||
elif model_type == "nextstep":
|
||||
if od_config.model_class_name is None:
|
||||
od_config.model_class_name = "NextStep11Pipeline"
|
||||
od_config.tf_model_config = TransformerConfig()
|
||||
od_config.update_multimodal_support()
|
||||
pipeline_class = "NextStep11Pipeline"
|
||||
elif model_type == "glm-image" or "GlmImageForConditionalGeneration" in architectures:
|
||||
pipeline_class = "GlmImagePipeline"
|
||||
elif architectures and len(architectures) == 1:
|
||||
od_config.model_class_name = architectures[0]
|
||||
else:
|
||||
raise
|
||||
pipeline_class = architectures[0]
|
||||
|
||||
if pipeline_class is None:
|
||||
raise ValueError(f"Unknown model type: {model_type}, architectures: {architectures}")
|
||||
|
||||
od_config.model_class_name = pipeline_class
|
||||
od_config.tf_model_config = TransformerConfig()
|
||||
od_config.update_multimodal_support()
|
||||
|
||||
self.engine: DiffusionEngine = DiffusionEngine.make_engine(od_config)
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ from vllm_omni.entrypoints.omni_llm import OmniLLM
|
||||
from vllm_omni.entrypoints.stage_utils import (
|
||||
SHUTDOWN_TASK,
|
||||
OmniStageTaskType,
|
||||
_resolve_model_tokenizer_paths,
|
||||
_to_dict,
|
||||
is_profiler_task,
|
||||
maybe_dump_to_shm,
|
||||
@@ -247,7 +248,7 @@ class OmniStage:
|
||||
"""
|
||||
|
||||
def __init__(self, stage_config: Any, stage_init_timeout: int = 300):
|
||||
logger.info(f"[OmniStage] stage_config: {stage_config}")
|
||||
logger.debug(f"[OmniStage] stage_config: {stage_config}")
|
||||
self.stage_config = stage_config
|
||||
self.engine = None
|
||||
self.async_engine = None
|
||||
@@ -704,6 +705,9 @@ def _stage_worker(
|
||||
if stage_type != "diffusion":
|
||||
_resolve_worker_cls(engine_args)
|
||||
|
||||
# Handle non-standard model directory structures (e.g., tokenizer in root, model in subdir)
|
||||
model = _resolve_model_tokenizer_paths(model, engine_args)
|
||||
|
||||
# Resolve ZMQ queue endpoints if needed
|
||||
zmq_ctx = None
|
||||
if isinstance(in_q, str) or isinstance(out_q, str):
|
||||
@@ -929,8 +933,9 @@ def _stage_worker(
|
||||
_rx_bytes_by_rid[rid] = int(_rx_metrics.get("rx_transfer_bytes", 0))
|
||||
|
||||
batch_request_ids.append(rid)
|
||||
if isinstance(ein, (str, dict)):
|
||||
# Types like OmniTextPrompt, TextPrompt are TypedDict, essentially dict and enters this branch
|
||||
|
||||
if isinstance(ein, (dict, str)):
|
||||
# For diffusion stage-0, ein might be a string prompt directly
|
||||
batch_engine_inputs.append(ein)
|
||||
elif isinstance(ein, Sequence):
|
||||
batch_engine_inputs.extend(ein)
|
||||
@@ -1104,6 +1109,9 @@ async def _stage_worker_async(
|
||||
final_output = stage_payload.get("final_output", False)
|
||||
final_output_type = stage_payload.get("final_output_type", None)
|
||||
|
||||
# Handle non-standard model directory structures (e.g., tokenizer in root, model in subdir)
|
||||
model = _resolve_model_tokenizer_paths(model, engine_args)
|
||||
|
||||
if stage_type != "diffusion":
|
||||
_resolve_worker_cls(engine_args)
|
||||
|
||||
@@ -1218,16 +1226,15 @@ async def _stage_worker_async(
|
||||
await stage_engine.reset_mm_cache()
|
||||
logger.debug("[Stage-%s] Engine initialized", stage_id)
|
||||
|
||||
async def handle_profiler_task_async(task_type: OmniStageTaskType) -> None:
|
||||
async def handle_profiler_task_async(task_type: OmniStageTaskType) -> dict:
|
||||
"""Handle profiler task asynchronously for both LLM and diffusion stages."""
|
||||
if task_type == OmniStageTaskType.PROFILER_START:
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
# Sync call is safe here — diffusion profiling is lightweight
|
||||
profile_dir = os.environ.get("VLLM_TORCH_PROFILER_DIR", "./profiles")
|
||||
os.makedirs(profile_dir, exist_ok=True)
|
||||
trace_filename = f"stage_{stage_id}_diffusion_{int(time.time())}"
|
||||
stage_engine.start_profile(trace_filename=trace_filename)
|
||||
await stage_engine.start_profile(trace_filename=trace_filename)
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start diffusion profiler: %s", stage_id, e)
|
||||
@@ -1237,14 +1244,17 @@ async def _stage_worker_async(
|
||||
logger.info("[Stage-%s] vLLM profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start vLLM profiler: %s", stage_id, e)
|
||||
return {}
|
||||
|
||||
elif task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
result_data: dict = {}
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
trace_files = stage_engine.stop_profile()
|
||||
trace_files = await stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler stopped", stage_id)
|
||||
if trace_files:
|
||||
logger.info("Diffusion trace files: %s", trace_files)
|
||||
result_data = trace_files
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop diffusion profiler: %s", stage_id, e)
|
||||
else:
|
||||
@@ -1253,6 +1263,8 @@ async def _stage_worker_async(
|
||||
logger.info("[Stage-%s] vLLM profiler stopped", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop vLLM profiler: %s", stage_id, e)
|
||||
return result_data
|
||||
return {}
|
||||
|
||||
# Signal readiness to orchestrator and send vllm_config back to main process
|
||||
try:
|
||||
@@ -1354,7 +1366,10 @@ async def _stage_worker_async(
|
||||
rid = task["request_id"]
|
||||
asyncio.create_task(stage_engine.abort(rid))
|
||||
elif is_profiler_task(task_type):
|
||||
await handle_profiler_task_async(task_type)
|
||||
profiler_data = await handle_profiler_task_async(task_type)
|
||||
# Send result back to orchestrator for STOP command
|
||||
if task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
out_q.put({"type": "profiler_result", "data": profiler_data})
|
||||
else:
|
||||
asyncio.create_task(generation_single_request(task))
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import vllm.envs as envs
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from PIL import Image
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.datastructures import State
|
||||
from starlette.routing import Route
|
||||
from vllm import SamplingParams
|
||||
@@ -105,6 +106,30 @@ from vllm_omni.lora.utils import stable_lora_int_id
|
||||
|
||||
logger = init_logger(__name__)
|
||||
router = APIRouter()
|
||||
profiler_router = APIRouter()
|
||||
|
||||
|
||||
def _should_enable_profiler_endpoints(args: Namespace) -> bool:
|
||||
# Check upstream vLLM's profiler_config
|
||||
profiler_config = getattr(args, "profiler_config", None)
|
||||
if profiler_config is not None:
|
||||
# profiler_config exists, check if profiler is set
|
||||
profiler = getattr(profiler_config, "profiler", None)
|
||||
if profiler is not None:
|
||||
return True
|
||||
|
||||
# TODO: remove this env after refactoring torch profiler to CLI args
|
||||
env_value = os.environ.get("VLLM_TORCH_PROFILER_DIR")
|
||||
return env_value is not None
|
||||
|
||||
|
||||
class ProfileRequest(BaseModel):
|
||||
"""Request model for profiling endpoints."""
|
||||
|
||||
stages: list[int] | None = Field(
|
||||
default=None,
|
||||
description="List of stage IDs to profile. If None, profiles all stages.",
|
||||
)
|
||||
|
||||
|
||||
def _remove_route_from_router(
|
||||
@@ -227,6 +252,11 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
|
||||
await omni_init_app_state(engine_client, app.state, args)
|
||||
|
||||
# Conditionally register profiler endpoints based on config or env var
|
||||
if _should_enable_profiler_endpoints(args):
|
||||
logger.warning("Profiler endpoints are enabled. This should ONLY be used for local development!")
|
||||
app.include_router(profiler_router)
|
||||
|
||||
vllm_config = await engine_client.get_vllm_config()
|
||||
|
||||
# Check if pure diffusion mode (vllm_config will be None)
|
||||
@@ -1489,6 +1519,58 @@ def apply_stage_default_sampling_params(
|
||||
setattr(sampling_params, param_name, param_value)
|
||||
|
||||
|
||||
@profiler_router.post("/start_profile")
|
||||
async def start_profile(raw_request: Request, request: ProfileRequest | None = None):
|
||||
"""Start profiling for the engine.
|
||||
|
||||
Args:
|
||||
request: Optional request body with stages to profile.
|
||||
- stages: List of stage IDs to profile. If None, profiles all stages.
|
||||
|
||||
Example:
|
||||
POST /start_profile
|
||||
{"stages": [0, 1]} # Profile only stages 0 and 1
|
||||
"""
|
||||
try:
|
||||
stages = request.stages if request else None
|
||||
logger.info("Starting profiler for stages: %s", stages if stages else "all")
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
result = await engine_client.start_profile(stages=stages)
|
||||
logger.info("Profiler started.")
|
||||
return JSONResponse(content=result)
|
||||
except Exception as e:
|
||||
logger.exception("Failed to start profiler: %s", e)
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to start profiler: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@profiler_router.post("/stop_profile")
|
||||
async def stop_profile(raw_request: Request, request: ProfileRequest | None = None):
|
||||
"""Stop profiling for the engine.
|
||||
|
||||
Args:
|
||||
request: Optional request body with stages to stop profiling.
|
||||
- stages: List of stage IDs to stop profiling. If None, stops all stages.
|
||||
|
||||
Example:
|
||||
POST /stop_profile
|
||||
{"stages": [0, 1]} # Stop profiling only stages 0 and 1
|
||||
"""
|
||||
try:
|
||||
stages = request.stages if request else None
|
||||
logger.info("Stopping profiler for stages: %s", stages if stages else "all")
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
result = await engine_client.stop_profile(stages=stages)
|
||||
logger.info("Profiler stopped.")
|
||||
return JSONResponse(content=result)
|
||||
except Exception as e:
|
||||
logger.exception("Failed to stop profiler: %s", e)
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to stop profiler: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
async def _run_video_generation(
|
||||
request: VideoGenerationRequest,
|
||||
raw_request: Request,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class OpenAICreateSpeechRequest(BaseModel):
|
||||
@@ -22,6 +22,13 @@ class OpenAICreateSpeechRequest(BaseModel):
|
||||
le=4.0,
|
||||
)
|
||||
stream_format: Literal["sse", "audio"] | None = "audio"
|
||||
stream: bool = Field(
|
||||
default=False,
|
||||
description=(
|
||||
"If true, stream raw PCM audio chunks as they are decoded. "
|
||||
"Requires response_format='pcm'. Speed adjustment is not supported when streaming."
|
||||
),
|
||||
)
|
||||
|
||||
# Qwen3-TTS specific parameters
|
||||
task_type: Literal["CustomVoice", "VoiceDesign", "Base"] | None = Field(
|
||||
@@ -56,6 +63,22 @@ class OpenAICreateSpeechRequest(BaseModel):
|
||||
raise ValueError("'sse' is not a supported stream_format yet. Please use 'audio'.")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_streaming_constraints(self) -> "OpenAICreateSpeechRequest":
|
||||
if self.stream:
|
||||
if self.response_format != "pcm":
|
||||
raise ValueError(
|
||||
"Streaming (stream=true) requires response_format='pcm'. "
|
||||
f"Got response_format='{self.response_format}'."
|
||||
)
|
||||
if self.speed is None:
|
||||
self.speed = 1.0
|
||||
elif self.speed != 1.0:
|
||||
raise ValueError(
|
||||
"Speed adjustment is not supported when streaming (stream=true). Set speed=1.0 or omit it."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class CreateAudio(BaseModel):
|
||||
audio_tensor: np.ndarray
|
||||
|
||||
@@ -274,6 +274,80 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
output_modalities if output_modalities is not None else self.engine_client.output_modalities
|
||||
)
|
||||
|
||||
# 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.
|
||||
# If we pass pre-tokenized chat-template ids, GLM-Image can become
|
||||
# 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)
|
||||
if not extracted_prompt:
|
||||
return self.create_error_response("No text prompt found in messages")
|
||||
|
||||
extra_body = getattr(request, "extra_body", None) or {}
|
||||
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 Exception:
|
||||
pass
|
||||
negative_prompt = extra_body.get("negative_prompt")
|
||||
|
||||
engine_prompt_image: dict[str, Any] | None = None
|
||||
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 = {"image": img}
|
||||
except Exception:
|
||||
engine_prompt_image = None
|
||||
|
||||
# Override the prompts produced by chat-template preprocessing.
|
||||
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
|
||||
if negative_prompt is not None:
|
||||
tprompt["negative_prompt"] = negative_prompt
|
||||
# GLM-Image's _call_hf_processor expects target_h/target_w in mm_processor_kwargs
|
||||
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:
|
||||
tprompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
if engine_prompt_image is not None:
|
||||
tprompt["multi_modal_data"] = engine_prompt_image
|
||||
|
||||
engine_prompts = [tprompt]
|
||||
# Store height/width for applying to diffusion stage sampling params later
|
||||
_image_gen_height = height
|
||||
_image_gen_width = width
|
||||
except Exception as e:
|
||||
logger.warning("Failed to build image-generation prompt for omni multistage: %s", e)
|
||||
_image_gen_height = None
|
||||
_image_gen_width = None
|
||||
else:
|
||||
_image_gen_height = None
|
||||
_image_gen_width = None
|
||||
|
||||
# Schedule the request and get the result generator.
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = []
|
||||
try:
|
||||
@@ -284,6 +358,15 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# Use standard OpenAI API parameters for comprehension stage
|
||||
sampling_params_list = self._build_sampling_params_list_from_request(request)
|
||||
|
||||
# Apply user-specified height/width to diffusion stage(s) for image generation
|
||||
if _image_gen_height is not None or _image_gen_width is not None:
|
||||
for idx, sp in enumerate(sampling_params_list):
|
||||
# Diffusion stages typically have height/width attributes
|
||||
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
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
engine_prompt,
|
||||
@@ -407,6 +490,35 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
request=request
|
||||
)
|
||||
|
||||
# Preserve a clean text prompt for downstream stages (e.g., GLM-Image diffusion).
|
||||
# For /v1/chat/completions, `request_prompt` is often the rendered chat template.
|
||||
# Diffusion models generally want the raw user caption instead.
|
||||
output_modalities = getattr(self.engine_client, "output_modalities", None)
|
||||
if output_modalities and ("image" in output_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)
|
||||
if extracted_prompt:
|
||||
engine_prompt["prompt"] = extracted_prompt
|
||||
|
||||
mm_processor_kwargs = getattr(request, "mm_processor_kwargs", None)
|
||||
if mm_processor_kwargs is not None:
|
||||
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
|
||||
if hasattr(request, "cache_salt") and request.cache_salt is not None:
|
||||
engine_prompt["cache_salt"] = request.cache_salt
|
||||
|
||||
return conversation, [engine_prompt]
|
||||
|
||||
async def _inject_audio_from_video_urls(
|
||||
|
||||
@@ -2,6 +2,9 @@ import asyncio
|
||||
import base64
|
||||
import io
|
||||
import ipaddress
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import socket
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
@@ -10,14 +13,13 @@ from urllib.request import urlopen
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from vllm.entrypoints.openai.engine.serving import OpenAIServing
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils import random_uuid
|
||||
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
AudioResponse,
|
||||
CreateAudio,
|
||||
OpenAICreateSpeechRequest,
|
||||
)
|
||||
@@ -74,6 +76,40 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
|
||||
self._tts_tokenizer = None
|
||||
|
||||
# Load speech tokenizer codec parameters for prompt length estimation
|
||||
self._codec_frame_rate: float | None = self._load_codec_frame_rate()
|
||||
|
||||
def _load_codec_frame_rate(self) -> float | None:
|
||||
"""Load codec frame rate from speech tokenizer config for prompt length estimation."""
|
||||
try:
|
||||
model_path = self.engine_client.model_config.model
|
||||
st_config_path = os.path.join(model_path, "speech_tokenizer", "config.json")
|
||||
if os.path.exists(st_config_path):
|
||||
with open(st_config_path) as f:
|
||||
st_config = json.load(f)
|
||||
output_sr = st_config.get("output_sample_rate")
|
||||
downsample = st_config.get("encode_downsample_rate")
|
||||
if output_sr and downsample and downsample > 0:
|
||||
rate = float(output_sr) / float(downsample)
|
||||
logger.info(
|
||||
f"Loaded codec frame rate: {rate:.1f} Hz "
|
||||
f"(output_sample_rate={output_sr}, encode_downsample_rate={downsample})"
|
||||
)
|
||||
return rate
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load codec frame rate from speech tokenizer config: {e}")
|
||||
|
||||
# Fallback: try codec_frame_rate_hz from hf_config
|
||||
try:
|
||||
hf_config = self.engine_client.model_config.hf_config
|
||||
rate = getattr(hf_config, "codec_frame_rate_hz", None)
|
||||
if rate is not None:
|
||||
logger.info(f"Using codec frame rate from hf_config: {rate} Hz")
|
||||
return float(rate)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def _find_tts_stage(self):
|
||||
"""Find and return the TTS stage from the stage list, or None if not found."""
|
||||
stage_list = getattr(self.engine_client, "stage_list", None)
|
||||
@@ -121,6 +157,41 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
return set()
|
||||
|
||||
def _estimate_ref_code_len(self, ref_audio: object) -> int | None:
|
||||
"""Estimate ref_code length from ref_audio waveform without running the codec.
|
||||
|
||||
The codec produces one frame per (output_sample_rate / encode_downsample_rate)
|
||||
audio samples, so ref_code_len = ceil(duration_seconds * codec_frame_rate).
|
||||
"""
|
||||
if self._codec_frame_rate is None:
|
||||
return None
|
||||
try:
|
||||
# ref_audio comes from tts_params as [[wav_array, sr]] or similar nested structure
|
||||
item = ref_audio
|
||||
while isinstance(item, list) and item:
|
||||
if len(item) == 2 and isinstance(item[1], (int, float)):
|
||||
break
|
||||
item = item[0]
|
||||
if isinstance(item, list) and len(item) == 2:
|
||||
wav, sr = item
|
||||
elif isinstance(item, tuple) and len(item) == 2:
|
||||
wav, sr = item
|
||||
else:
|
||||
return None
|
||||
sr = int(sr)
|
||||
if hasattr(wav, "__len__"):
|
||||
n_samples = len(wav)
|
||||
elif hasattr(wav, "shape"):
|
||||
n_samples = wav.shape[-1] if wav.ndim > 1 else wav.shape[0]
|
||||
else:
|
||||
return None
|
||||
if sr <= 0 or n_samples <= 0:
|
||||
return None
|
||||
duration = n_samples / sr
|
||||
return math.ceil(duration * self._codec_frame_rate)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _estimate_prompt_len(self, tts_params: dict[str, Any]) -> int:
|
||||
"""Estimate prompt length so the placeholder matches model-side embeddings."""
|
||||
try:
|
||||
@@ -146,6 +217,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
tokenize_prompt=lambda t: self._tts_tokenizer(t, padding=False)["input_ids"],
|
||||
codec_language_id=getattr(talker_config, "codec_language_id", None),
|
||||
spk_is_dialect=getattr(talker_config, "spk_is_dialect", None),
|
||||
estimate_ref_code_len=self._estimate_ref_code_len,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to estimate TTS prompt length, using fallback 2048: %s", e)
|
||||
@@ -253,6 +325,85 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
wav_np, sr = await loop.run_in_executor(None, _fetch_sync)
|
||||
return wav_np.tolist(), sr
|
||||
|
||||
async def _generate_pcm_chunks(self, generator, request_id: str):
|
||||
"""Generate PCM audio chunks for streaming response.
|
||||
|
||||
Handles two audio output modes from the engine:
|
||||
- Cumulative mode (list): Engine returns growing list of chunks;
|
||||
we emit only the new tail on each iteration.
|
||||
- Per-step mode (tensor): Engine returns single tensor per iteration;
|
||||
we emit it directly.
|
||||
|
||||
Args:
|
||||
generator: Async generator from the engine
|
||||
request_id: Request identifier for logging
|
||||
|
||||
Yields:
|
||||
Raw PCM bytes for each audio chunk
|
||||
"""
|
||||
prev_count = 0
|
||||
sample_rate_val = 24000
|
||||
try:
|
||||
async for res in generator:
|
||||
audio_output, audio_key = self._extract_audio_output(res)
|
||||
if audio_key is None:
|
||||
continue
|
||||
|
||||
sr_raw = audio_output.get("sr")
|
||||
if sr_raw is not None:
|
||||
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
|
||||
sample_rate_val = sr_val.item() if hasattr(sr_val, "item") else int(sr_val)
|
||||
|
||||
audio_val = audio_output[audio_key]
|
||||
if isinstance(audio_val, list):
|
||||
# Cumulative mode: each update grows the list; emit only new tail.
|
||||
new_chunks = audio_val[prev_count:]
|
||||
prev_count = len(audio_val)
|
||||
else:
|
||||
# Per-step mode: each update is a single tensor; emit directly.
|
||||
if audio_val is not None:
|
||||
new_chunks = [audio_val]
|
||||
prev_count += 1
|
||||
else:
|
||||
new_chunks = []
|
||||
|
||||
for chunk_tensor in new_chunks:
|
||||
chunk_np = (
|
||||
chunk_tensor.float().detach().cpu().numpy() if hasattr(chunk_tensor, "float") else chunk_tensor
|
||||
)
|
||||
if chunk_np.ndim > 1:
|
||||
chunk_np = chunk_np.squeeze()
|
||||
audio_obj = CreateAudio(
|
||||
audio_tensor=chunk_np,
|
||||
sample_rate=sample_rate_val,
|
||||
response_format="pcm",
|
||||
speed=1.0,
|
||||
stream_format="audio",
|
||||
base64_encode=False,
|
||||
)
|
||||
yield self.create_audio(audio_obj).audio_data
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Streaming request %s cancelled by client", request_id)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception("Streaming speech generation failed for %s: %s", request_id, e)
|
||||
|
||||
@staticmethod
|
||||
def _extract_audio_output(res) -> tuple[dict | None, str | None]:
|
||||
"""Return (audio_output dict, audio key) or (None, None).
|
||||
|
||||
Returns the raw dict so callers can apply their own extraction strategy:
|
||||
streaming needs per-chunk delta slicing; non-streaming needs full concatenation.
|
||||
"""
|
||||
mm = getattr(res, "multimodal_output", None)
|
||||
if not mm:
|
||||
ro = getattr(res, "request_output", None)
|
||||
mm = getattr(ro, "multimodal_output", None) if ro else None
|
||||
if not mm:
|
||||
return None, None
|
||||
key = "audio" if "audio" in mm else ("model_outputs" if "model_outputs" in mm else None)
|
||||
return mm, key
|
||||
|
||||
def _build_tts_params(self, request: OpenAICreateSpeechRequest) -> dict[str, Any]:
|
||||
"""Build TTS parameters from request.
|
||||
|
||||
@@ -300,6 +451,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
else:
|
||||
params["max_new_tokens"] = [2048]
|
||||
|
||||
# VoiceDesign requires non_streaming_mode (match offline script behaviour).
|
||||
# CustomVoice and Base rely on the model default (True and False respectively).
|
||||
if params["task_type"][0] == "VoiceDesign":
|
||||
params["non_streaming_mode"] = [True]
|
||||
|
||||
return params
|
||||
|
||||
async def create_speech(
|
||||
@@ -323,9 +479,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
- ref_text: Transcript of reference audio (Base task)
|
||||
- x_vector_only_mode: Use speaker embedding only (Base task)
|
||||
|
||||
NOTE: Streaming audio generation is not currently supported.
|
||||
Streaming is supported via stream=True with response_format='pcm'.
|
||||
Each Code2Wav chunk is yielded as raw PCM bytes as soon as it is decoded.
|
||||
"""
|
||||
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
logger.error("Error with model %s", error_check_ret)
|
||||
@@ -343,23 +499,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if validation_error:
|
||||
return self.create_error_response(validation_error)
|
||||
|
||||
# Must use prompt_token_ids (not text prompt): the AR Talker
|
||||
# operates on codec tokens; text token IDs exceed codec vocab.
|
||||
# model.preprocess replaces all embeddings, so placeholder value
|
||||
# is irrelevant -- but length must match to avoid excess padding.
|
||||
tts_params = self._build_tts_params(request)
|
||||
|
||||
if request.ref_audio is not None:
|
||||
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
|
||||
tts_params["ref_audio"] = [[wav_list, sr]]
|
||||
|
||||
# Prompt length must match model-side embeddings; values are placeholders.
|
||||
ph_len = self._estimate_prompt_len(tts_params)
|
||||
prompt = {
|
||||
"prompt_token_ids": [1] * ph_len,
|
||||
"additional_information": tts_params,
|
||||
}
|
||||
prompt = {"prompt_token_ids": [1] * ph_len, "additional_information": tts_params}
|
||||
else:
|
||||
# Fallback for unsupported models
|
||||
tts_params = {}
|
||||
prompt = {"prompt": request.input}
|
||||
|
||||
@@ -379,6 +527,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
output_modalities=["audio"],
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
return StreamingResponse(
|
||||
self._generate_pcm_chunks(generator, request_id),
|
||||
media_type="audio/pcm",
|
||||
)
|
||||
|
||||
# Non-streaming: collect final output
|
||||
final_output: OmniRequestOutput | None = None
|
||||
async for res in generator:
|
||||
final_output = res
|
||||
@@ -386,55 +541,34 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if final_output is None:
|
||||
return self.create_error_response("No output generated from the model.")
|
||||
|
||||
# Extract audio from output
|
||||
# Audio can be in final_output.multimodal_output or final_output.request_output.multimodal_output
|
||||
# Support both "audio" and "model_outputs" keys for compatibility with different models
|
||||
audio_output = None
|
||||
if hasattr(final_output, "multimodal_output") and final_output.multimodal_output:
|
||||
audio_output = final_output.multimodal_output
|
||||
if not audio_output and hasattr(final_output, "request_output"):
|
||||
if final_output.request_output and hasattr(final_output.request_output, "multimodal_output"):
|
||||
audio_output = final_output.request_output.multimodal_output
|
||||
|
||||
# Check for audio data using either "audio" or "model_outputs" key
|
||||
audio_key = None
|
||||
if audio_output:
|
||||
if "audio" in audio_output:
|
||||
audio_key = "audio"
|
||||
elif "model_outputs" in audio_output:
|
||||
audio_key = "model_outputs"
|
||||
|
||||
if not audio_output or audio_key is None:
|
||||
audio_output, audio_key = self._extract_audio_output(final_output)
|
||||
if audio_key is None:
|
||||
return self.create_error_response("TTS model did not produce audio output.")
|
||||
|
||||
audio_tensor = audio_output[audio_key]
|
||||
sample_rate = audio_output.get("sr", 24000)
|
||||
if hasattr(sample_rate, "item"):
|
||||
sample_rate = sample_rate.item()
|
||||
sr_raw = audio_output.get("sr", 24000)
|
||||
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
|
||||
sample_rate = sr_val.item() if hasattr(sr_val, "item") else int(sr_val)
|
||||
|
||||
# Streaming accumulates chunks as a list; concat first.
|
||||
# async_chunk mode accumulates chunks as a list; concat first.
|
||||
if isinstance(audio_tensor, list):
|
||||
import torch
|
||||
|
||||
audio_tensor = torch.cat(audio_tensor, dim=-1)
|
||||
# Convert tensor to numpy
|
||||
if hasattr(audio_tensor, "float"):
|
||||
audio_tensor = audio_tensor.float().detach().cpu().numpy()
|
||||
|
||||
# Squeeze batch dimension if present, but preserve channel dimension for stereo
|
||||
if audio_tensor.ndim > 1:
|
||||
audio_tensor = audio_tensor.squeeze()
|
||||
|
||||
audio_obj = CreateAudio(
|
||||
audio_tensor=audio_tensor,
|
||||
sample_rate=int(sample_rate),
|
||||
sample_rate=sample_rate,
|
||||
response_format=request.response_format or "wav",
|
||||
speed=request.speed or 1.0,
|
||||
stream_format=request.stream_format,
|
||||
base64_encode=False,
|
||||
)
|
||||
|
||||
audio_response: AudioResponse = self.create_audio(audio_obj)
|
||||
audio_response = self.create_audio(audio_obj)
|
||||
return Response(content=audio_response.audio_data, media_type=audio_response.media_type)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
|
||||
@@ -302,3 +302,41 @@ def _to_dict(x: Any) -> dict[str, Any]:
|
||||
return dict(x)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_model_tokenizer_paths(
|
||||
model: str,
|
||||
engine_args: dict,
|
||||
) -> str:
|
||||
"""Resolve model and tokenizer paths for non-standard directory structures.
|
||||
|
||||
Some models (e.g., GLM-Image) have tokenizer in root and model in subdirectory.
|
||||
This function handles model_subdir and tokenizer_subdir engine_args.
|
||||
|
||||
Args:
|
||||
model: Base model path
|
||||
engine_args: Engine arguments (modified in-place to remove subdir args
|
||||
and set tokenizer if needed)
|
||||
|
||||
Returns:
|
||||
Resolved model path (may be subdirectory of original)
|
||||
"""
|
||||
import os
|
||||
|
||||
model_subdir = engine_args.pop("model_subdir", None)
|
||||
tokenizer_subdir = engine_args.pop("tokenizer_subdir", None)
|
||||
base_model_path = model
|
||||
|
||||
if model_subdir:
|
||||
model = os.path.join(model, model_subdir)
|
||||
logger.info(f"Using model subdirectory: {model}")
|
||||
|
||||
if tokenizer_subdir is not None:
|
||||
tokenizer_path = os.path.join(base_model_path, tokenizer_subdir) if tokenizer_subdir else base_model_path
|
||||
engine_args["tokenizer"] = tokenizer_path
|
||||
logger.info(f"Using tokenizer from: {tokenizer_path}")
|
||||
elif model_subdir and "tokenizer" not in engine_args:
|
||||
engine_args["tokenizer"] = base_model_path
|
||||
logger.info(f"Using tokenizer from base model path: {base_model_path}")
|
||||
|
||||
return model
|
||||
Reference in new issue
Block a user