Merge remote-tracking branch 'remotes/origin/main' into dev/rebase-v0170
Signed-off-by: Taichang Zhou <tzhouam@connect.ust.hk>
This commit is contained in:
commit
0940c5a05e
91 files changed
+5235
-729
No files matched your search
@@ -4,8 +4,8 @@ import asyncio
|
||||
import copy
|
||||
import time
|
||||
import weakref
|
||||
from collections.abc import AsyncGenerator, Iterable, Sequence
|
||||
from typing import Any
|
||||
from collections.abc import AsyncGenerator, Callable, Iterable, Sequence
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.inputs.preprocess import InputPreprocessor
|
||||
@@ -35,11 +35,20 @@ from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.metrics import OrchestratorAggregator
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
_R = TypeVar("_R")
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _weak_close_cleanup_async(stage_list, stage_in_queues, stage_out_queues, ray_pg, output_handler, zmq_ctx=None):
|
||||
def _weak_close_cleanup_async(
|
||||
stage_list, stage_in_queues, stage_out_queues, ray_pg, output_handler, zmq_ctx=None, inline_engine=None
|
||||
):
|
||||
"""Weak reference cleanup function for AsyncOmni instances."""
|
||||
if inline_engine is not None:
|
||||
try:
|
||||
inline_engine.close()
|
||||
except Exception as e:
|
||||
logger.warning("Failed to close inline diffusion engine: %s", e)
|
||||
if stage_list:
|
||||
for q in stage_in_queues:
|
||||
try:
|
||||
@@ -105,10 +114,17 @@ class AsyncOmni(OmniBase):
|
||||
self._pause_cond: asyncio.Condition = asyncio.Condition()
|
||||
self._paused: bool = False
|
||||
|
||||
# Sleep mode tracking
|
||||
self._is_sleeping: bool = False
|
||||
|
||||
# Request state tracking
|
||||
self.request_states: dict[str, ClientRequestState] = {}
|
||||
self.output_handler: asyncio.Task | None = None
|
||||
|
||||
# RPC results storage: {stage_id: {rpc_id: result}}
|
||||
# Used to avoid race condition between output_handler and collective_rpc
|
||||
self._rpc_results: dict[int, dict[str, dict[str, Any]]] = {}
|
||||
|
||||
super().__init__(model, **kwargs)
|
||||
|
||||
# Register weak reference cleanup (called on garbage collection)
|
||||
@@ -121,6 +137,7 @@ class AsyncOmni(OmniBase):
|
||||
self._ray_pg,
|
||||
self.output_handler,
|
||||
self._zmq_ctx,
|
||||
getattr(self, "_inline_engine", None),
|
||||
)
|
||||
|
||||
def _create_default_diffusion_stage_cfg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -193,6 +210,8 @@ class AsyncOmni(OmniBase):
|
||||
"enforce_eager": kwargs.get("enforce_eager", False),
|
||||
"diffusion_load_format": kwargs.get("diffusion_load_format", "default"),
|
||||
"custom_pipeline_args": kwargs.get("custom_pipeline_args", None),
|
||||
"worker_extension_cls": kwargs.get("worker_extension_cls", None),
|
||||
"enable_sleep_mode": kwargs.get("enable_sleep_mode", False),
|
||||
"enable_multithread_weight_load": kwargs.get("enable_multithread_weight_load", True),
|
||||
"num_weight_load_threads": kwargs.get("num_weight_load_threads", 4),
|
||||
},
|
||||
@@ -253,6 +272,26 @@ class AsyncOmni(OmniBase):
|
||||
self.io_processor = None
|
||||
self.model_config = None
|
||||
|
||||
def _setup_rpc_result_checkers(self) -> None:
|
||||
"""Override base class to use async-friendly RPC result checkers.
|
||||
|
||||
In the async path the output_handler task drains the output queues
|
||||
and stashes collective_rpc results into ``_rpc_results``. The
|
||||
checker therefore only needs to look there (no queue draining).
|
||||
"""
|
||||
for stage in self.stage_list:
|
||||
sid = stage.stage_id
|
||||
|
||||
def make_rpc_checker(stage_id: int):
|
||||
def rpc_checker(rpc_id: str) -> dict[str, Any] | None:
|
||||
if stage_id in self._rpc_results and rpc_id in self._rpc_results[stage_id]:
|
||||
return self._rpc_results[stage_id].pop(rpc_id)
|
||||
return None
|
||||
|
||||
return rpc_checker
|
||||
|
||||
stage._rpc_result_checker = make_rpc_checker(sid)
|
||||
|
||||
def shutdown(self):
|
||||
"""Shutdown, cleaning up the background proc and IPC.
|
||||
|
||||
@@ -299,6 +338,11 @@ class AsyncOmni(OmniBase):
|
||||
async with self._pause_cond:
|
||||
await self._pause_cond.wait_for(lambda: not self._paused)
|
||||
|
||||
if self._inline_diffusion:
|
||||
async for output in self._generate_inline(prompt, request_id, sampling_params_list, output_modalities):
|
||||
yield output
|
||||
return
|
||||
|
||||
logger.debug(f"[{self._name}] generate() called")
|
||||
try:
|
||||
# Start output handler on the first call to generate()
|
||||
@@ -390,6 +434,97 @@ class AsyncOmni(OmniBase):
|
||||
logger.info("[AsyncOrchestrator] Request %s aborted.", request_id)
|
||||
raise
|
||||
|
||||
async def _generate_inline(
|
||||
self,
|
||||
prompt: OmniPromptType,
|
||||
request_id: str,
|
||||
sampling_params_list: Sequence[OmniSamplingParams] | None = None,
|
||||
output_modalities: list[str] | None = None,
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
"""Generate using inline diffusion engine (no stage worker subprocess).
|
||||
|
||||
Eliminates Hop3 IPC overhead by running OmniDiffusion directly in the
|
||||
orchestrator process. The blocking generate() call is offloaded to a
|
||||
thread executor so the asyncio event loop remains responsive.
|
||||
"""
|
||||
_wall_start_ts = time.time()
|
||||
|
||||
if sampling_params_list is None:
|
||||
sampling_params_list = self.default_sampling_params_list
|
||||
sp0 = sampling_params_list[0]
|
||||
|
||||
stage = self.stage_list[0]
|
||||
final_stage_id_for_e2e = 0
|
||||
|
||||
metrics = OrchestratorAggregator(
|
||||
num_stages=1,
|
||||
log_stats=self.log_stats,
|
||||
wall_start_ts=_wall_start_ts,
|
||||
final_stage_id_for_e2e=final_stage_id_for_e2e,
|
||||
)
|
||||
metrics.stage_first_ts[0] = time.time()
|
||||
|
||||
logger.info(
|
||||
"[%s] Inline diffusion generate for request %s",
|
||||
self._name,
|
||||
request_id,
|
||||
)
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
results = await loop.run_in_executor(
|
||||
None,
|
||||
self._inline_engine.generate,
|
||||
prompt,
|
||||
sp0,
|
||||
[request_id],
|
||||
)
|
||||
|
||||
for result in results:
|
||||
images = getattr(result, "images", None) or []
|
||||
finished = getattr(result, "finished", True)
|
||||
|
||||
output_to_yield = OmniRequestOutput(
|
||||
stage_id=0,
|
||||
final_output_type=stage.final_output_type,
|
||||
request_output=result,
|
||||
images=images,
|
||||
finished=finished,
|
||||
)
|
||||
|
||||
metrics.stage_last_ts[0] = time.time()
|
||||
yield output_to_yield
|
||||
|
||||
try:
|
||||
metrics.on_finalize_request(
|
||||
final_stage_id_for_e2e,
|
||||
request_id,
|
||||
_wall_start_ts,
|
||||
)
|
||||
metrics.build_and_log_summary()
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"[%s] Failed to finalize inline metrics: %s",
|
||||
self._name,
|
||||
e,
|
||||
)
|
||||
|
||||
except (asyncio.CancelledError, GeneratorExit):
|
||||
logger.info(
|
||||
"[%s] Inline request %s cancelled.",
|
||||
self._name,
|
||||
request_id,
|
||||
)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"[%s] Inline diffusion failed for request %s: %s",
|
||||
self._name,
|
||||
request_id,
|
||||
e,
|
||||
)
|
||||
raise
|
||||
|
||||
async def _process_async_results(
|
||||
self,
|
||||
request_id: str,
|
||||
@@ -401,7 +536,10 @@ class AsyncOmni(OmniBase):
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
all_stages_finished = {stage_id: False for stage_id in range(final_stage_id_for_e2e + 1)}
|
||||
submit_flag = True
|
||||
_loop_iter = 0
|
||||
_last_progress_ts = time.time()
|
||||
while not all(all_stages_finished.values()):
|
||||
_loop_iter += 1
|
||||
for stage_id, stage in enumerate(self.stage_list[: final_stage_id_for_e2e + 1]):
|
||||
if all_stages_finished[stage_id]:
|
||||
continue
|
||||
@@ -410,6 +548,7 @@ class AsyncOmni(OmniBase):
|
||||
except asyncio.QueueEmpty:
|
||||
await asyncio.sleep(0.001)
|
||||
continue
|
||||
_last_progress_ts = time.time()
|
||||
engine_outputs, finished, output_to_yield = self._process_single_result(
|
||||
result,
|
||||
stage,
|
||||
@@ -418,11 +557,20 @@ class AsyncOmni(OmniBase):
|
||||
)
|
||||
if submit_flag and stage_id == 0:
|
||||
submit_flag = False
|
||||
prompt_token_ids = engine_outputs.prompt_token_ids
|
||||
prompt_token_ids = getattr(engine_outputs, "prompt_token_ids", None)
|
||||
if prompt_token_ids is None:
|
||||
prompt_token_ids = []
|
||||
engine_input = copy.deepcopy(prompt)
|
||||
next_prompt_len = max(1, compute_talker_prompt_ids_length(prompt_token_ids))
|
||||
try:
|
||||
next_prompt_len = max(1, compute_talker_prompt_ids_length(prompt_token_ids))
|
||||
except Exception:
|
||||
raise
|
||||
engine_input["prompt_token_ids"] = [0] * next_prompt_len
|
||||
engine_input["multi_modal_data"] = engine_input["mm_processor_kwargs"] = None
|
||||
for _mm_key in ("mm_kwargs", "mm_hashes", "mm_placeholders", "multi_modal_uuids"):
|
||||
engine_input.pop(_mm_key, None)
|
||||
if engine_input.get("type") == "multimodal":
|
||||
engine_input["type"] = "token"
|
||||
for i in range(1, len(self.stage_list)):
|
||||
task = {
|
||||
"request_id": request_id,
|
||||
@@ -525,6 +673,7 @@ class AsyncOmni(OmniBase):
|
||||
raise RuntimeError(result)
|
||||
|
||||
engine_outputs = _load(result, obj_key="engine_outputs", shm_key="engine_outputs_shm")
|
||||
|
||||
if isinstance(engine_outputs, list):
|
||||
engine_outputs = engine_outputs[0]
|
||||
|
||||
@@ -542,12 +691,17 @@ class AsyncOmni(OmniBase):
|
||||
images = engine_outputs.images
|
||||
|
||||
if stage.final_output_type == "image":
|
||||
# Propagate custom_output from inner diffusion output
|
||||
custom_output = {}
|
||||
if isinstance(engine_outputs, OmniRequestOutput):
|
||||
custom_output = engine_outputs.custom_output or {}
|
||||
output_to_yield = OmniRequestOutput(
|
||||
stage_id=stage_id,
|
||||
final_output_type=stage.final_output_type,
|
||||
request_output=engine_outputs,
|
||||
images=images,
|
||||
finished=finished,
|
||||
_custom_output=custom_output,
|
||||
)
|
||||
else:
|
||||
output_to_yield = OmniRequestOutput(
|
||||
@@ -597,6 +751,15 @@ class AsyncOmni(OmniBase):
|
||||
# so we wait for a short time and try again
|
||||
await asyncio.sleep(0.05)
|
||||
continue
|
||||
# Handle collective_rpc results separately to avoid
|
||||
# race condition with the polling in collective_rpc
|
||||
if result.get("type") == "collective_rpc_result":
|
||||
rpc_id = result.get("rpc_id")
|
||||
if rpc_id:
|
||||
if stage_id not in self._rpc_results:
|
||||
self._rpc_results[stage_id] = {}
|
||||
self._rpc_results[stage_id][rpc_id] = result
|
||||
continue
|
||||
req_id = result.get("request_id")
|
||||
req_state = request_states.get(req_id)
|
||||
if req_state is None:
|
||||
@@ -632,7 +795,8 @@ class AsyncOmni(OmniBase):
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
# Is None before the loop is started.
|
||||
if self._inline_diffusion:
|
||||
return self._inline_engine is not None
|
||||
return len(self._stage_in_queues) > 0
|
||||
|
||||
@property
|
||||
@@ -656,6 +820,10 @@ class AsyncOmni(OmniBase):
|
||||
return EngineDeadError()
|
||||
|
||||
async def abort(self, request_id: str | Iterable[str]) -> None:
|
||||
if self._inline_diffusion:
|
||||
if self._inline_engine is not None:
|
||||
self._inline_engine.engine.abort(request_id)
|
||||
return None
|
||||
abort_task = {"type": OmniStageTaskType.ABORT, "request_id": request_id}
|
||||
for stage in self.stage_list:
|
||||
stage.submit(abort_task)
|
||||
@@ -709,6 +877,8 @@ class AsyncOmni(OmniBase):
|
||||
OMNI: Required by upstream OpenAIServingModels.__init__ which
|
||||
accesses engine_client.renderer.
|
||||
"""
|
||||
if self.input_processor is None:
|
||||
return None
|
||||
return self.input_processor.renderer
|
||||
|
||||
async def do_log_stats(self) -> None:
|
||||
@@ -723,19 +893,73 @@ class AsyncOmni(OmniBase):
|
||||
async def reset_prefix_cache(self, reset_running_requests: bool = False) -> bool:
|
||||
pass
|
||||
|
||||
async def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[..., _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> list[_R]:
|
||||
"""Execute an RPC call on all stages asynchronously.
|
||||
|
||||
Args:
|
||||
method: Name of the method to execute or callable
|
||||
timeout: Optional timeout in seconds
|
||||
args: Positional arguments for the method
|
||||
kwargs: Keyword arguments for the method
|
||||
|
||||
Returns:
|
||||
List of results from each stage
|
||||
"""
|
||||
self._run_output_handler()
|
||||
# Run synchronous collective_rpc in thread pool to avoid blocking event loop
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
async def run_stage_rpc(stage: OmniStage) -> _R:
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
stage.collective_rpc,
|
||||
method,
|
||||
timeout,
|
||||
args,
|
||||
kwargs,
|
||||
)
|
||||
|
||||
# Run all stages concurrently
|
||||
results = await asyncio.gather(*[run_stage_rpc(stage) for stage in self.stage_list])
|
||||
return list(results)
|
||||
|
||||
async def sleep(self, level: int = 1) -> None:
|
||||
pass
|
||||
self._is_sleeping = True
|
||||
await self.collective_rpc(method="sleep", args=(level,))
|
||||
|
||||
async def wake_up(self, tags: list[str] | None = None) -> None:
|
||||
pass
|
||||
self._is_sleeping = False
|
||||
await self.collective_rpc(method="wake_up", args=(tags,))
|
||||
|
||||
async def is_sleeping(self) -> bool:
|
||||
"""Check whether the engine is sleeping"""
|
||||
return False
|
||||
return getattr(self, "_is_sleeping", False)
|
||||
|
||||
async def add_lora(self, lora_request: LoRARequest) -> bool:
|
||||
"""Load a new LoRA adapter into the engine for future requests."""
|
||||
return False
|
||||
result = await self.collective_rpc(method="add_lora", args=(lora_request,))
|
||||
return result[0][0]
|
||||
|
||||
async def remove_lora(self, adapter_id: int) -> bool:
|
||||
"""Remove a LoRA adapter from the engine."""
|
||||
result = await self.collective_rpc(method="remove_lora", args=(adapter_id,))
|
||||
return result[0][0]
|
||||
|
||||
async def list_loras(self) -> list[int]:
|
||||
"""List all loaded LoRA adapter IDs."""
|
||||
result = await self.collective_rpc(method="list_loras")
|
||||
return result[0][0]
|
||||
|
||||
async def pin_lora(self, adapter_id: int) -> bool:
|
||||
"""Pin a LoRA adapter so it is not evicted from the cache."""
|
||||
result = await self.collective_rpc(method="pin_lora", args=(adapter_id,))
|
||||
return result[0][0]
|
||||
|
||||
async def encode(
|
||||
self,
|
||||
|
||||
+198
-10
@@ -9,7 +9,7 @@ import uuid
|
||||
import weakref
|
||||
from collections.abc import Callable, Generator, Sequence
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Literal, overload
|
||||
from typing import Any, Literal, TypeVar, overload
|
||||
|
||||
import huggingface_hub
|
||||
import msgspec.msgpack
|
||||
@@ -40,18 +40,22 @@ from vllm_omni.entrypoints.omni_stage import OmniStage
|
||||
from vllm_omni.entrypoints.stage_utils import SHUTDOWN_TASK, OmniStageTaskType
|
||||
from vllm_omni.entrypoints.stage_utils import maybe_load_from_ipc as _load
|
||||
from vllm_omni.entrypoints.utils import (
|
||||
filter_dataclass_kwargs,
|
||||
get_final_stage_id_for_e2e,
|
||||
inject_omni_kv_config,
|
||||
load_and_resolve_stage_configs,
|
||||
)
|
||||
from vllm_omni.entrypoints.zmq_utils import ZmqQueue
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, OmniSamplingParams
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.metrics import OrchestratorAggregator, StageRequestStats
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
_R = TypeVar("_R")
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -177,6 +181,13 @@ class OmniBase:
|
||||
self._handshake_seen: set[int] = set() # Track which stage IDs have completed ZMQ handshake
|
||||
self._single_stage_id: int | None = None # Optional: deploy only a specific stage ID
|
||||
|
||||
# Sleep mode tracking
|
||||
self._is_sleeping: bool = False
|
||||
|
||||
# RPC results storage: {stage_id: {rpc_id: result}}
|
||||
# Used by collective_rpc to retrieve results collected from the output queue
|
||||
self._rpc_results: dict[int, dict[str, dict[str, Any]]] = {}
|
||||
|
||||
# Initialize stages - each stage will create appropriate instance based on stage_type
|
||||
# Stage workers will automatically create OmniLLM or OmniDiffusion instances
|
||||
# based on stage_type in YAML config (handled in omni_stage.py)
|
||||
@@ -304,6 +315,9 @@ class OmniBase:
|
||||
|
||||
def _initialize_stages(self, model: str, kwargs: dict[str, Any]) -> None:
|
||||
"""Initialize stage list management."""
|
||||
self._inline_diffusion = False
|
||||
self._inline_engine = None
|
||||
|
||||
stage_init_timeout = kwargs.get("stage_init_timeout", 20)
|
||||
shm_threshold_bytes = kwargs.get("shm_threshold_bytes", 65536)
|
||||
init_timeout = kwargs.get("init_timeout", 300)
|
||||
@@ -351,6 +365,13 @@ class OmniBase:
|
||||
self.output_modalities = [st.final_output_type for st in self.stage_list]
|
||||
logger.info(f"[{self._name}] Loaded {len(self.stage_list)} stages")
|
||||
|
||||
# Phase 1 optimization: for a single diffusion stage in async mode,
|
||||
# run the engine directly in the orchestrator process to eliminate
|
||||
# the stage worker subprocess and its IPC serialization overhead.
|
||||
if len(self.stage_list) == 1 and self.stage_list[0].stage_type == "diffusion" and self.is_async:
|
||||
self._init_inline_diffusion_engine(model, self.stage_configs[0], kwargs)
|
||||
return
|
||||
|
||||
if self.worker_backend == "ray":
|
||||
self._queue_cls = get_ray_queue_class()
|
||||
else:
|
||||
@@ -362,6 +383,71 @@ class OmniBase:
|
||||
self._start_stages(model)
|
||||
# Wait for all stages to report readiness before seeding
|
||||
self._wait_for_stages_ready(timeout=init_timeout)
|
||||
# Set up RPC result checkers so that collective_rpc works
|
||||
self._setup_rpc_result_checkers()
|
||||
|
||||
def _init_inline_diffusion_engine(
|
||||
self,
|
||||
model: str,
|
||||
stage_config: Any,
|
||||
kwargs: dict[str, Any],
|
||||
) -> None:
|
||||
"""Initialize diffusion engine directly in the orchestrator process.
|
||||
|
||||
For single-stage diffusion pipelines, this eliminates the stage worker
|
||||
subprocess and the associated Hop3 IPC serialization overhead.
|
||||
GPU workers for tensor parallelism are still spawned by the
|
||||
DiffusionExecutor as separate processes.
|
||||
"""
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.entrypoints.omni_diffusion import OmniDiffusion
|
||||
from vllm_omni.entrypoints.stage_utils import (
|
||||
_to_dict,
|
||||
load_func_from_config,
|
||||
set_stage_devices,
|
||||
)
|
||||
|
||||
stage_id = stage_config.stage_id
|
||||
engine_args = _to_dict(stage_config.engine_args)
|
||||
runtime_cfg = _to_dict(getattr(stage_config, "runtime", {}))
|
||||
|
||||
if os.environ.get("VLLM_WORKER_MULTIPROC_METHOD") != "spawn":
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
try:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
device_type = current_omni_platform.device_type
|
||||
set_stage_devices(stage_id, runtime_cfg.get("devices"), device_type=device_type)
|
||||
except Exception as e:
|
||||
logger.warning("Device setup for inline diffusion failed: %s", e)
|
||||
|
||||
engine_args = filter_dataclass_kwargs(OmniDiffusionConfig, engine_args)
|
||||
engine_args.pop("model_stage", None)
|
||||
engine_args.pop("model", None)
|
||||
|
||||
cfg_kv_collect_func = load_func_from_config(getattr(stage_config, "cfg_kv_collect_func", None))
|
||||
|
||||
self._inline_engine = OmniDiffusion(
|
||||
model=model,
|
||||
stage_id=stage_id,
|
||||
engine_input_source=getattr(stage_config, "engine_input_source", []),
|
||||
cfg_kv_collect_func=cfg_kv_collect_func,
|
||||
**engine_args,
|
||||
)
|
||||
self._inline_diffusion = True
|
||||
|
||||
# These attributes are normally set by AsyncOmni._wait_for_stages_ready
|
||||
# but we skip that for inline mode. Set them to None since there is no
|
||||
# LLM stage to provide them.
|
||||
self.input_processor = None
|
||||
self.io_processor = None
|
||||
self.model_config = None
|
||||
|
||||
logger.info(
|
||||
"[%s] Inline diffusion mode active – stage worker subprocess bypassed",
|
||||
self._name,
|
||||
)
|
||||
|
||||
def _is_async_chunk_enable(self, stage_args: list) -> bool:
|
||||
"""get async chunk flag"""
|
||||
@@ -517,6 +603,117 @@ class OmniBase:
|
||||
profiler = getattr(profiler_config, "profiler", None)
|
||||
return profiler is not None
|
||||
|
||||
def _setup_rpc_result_checkers(self) -> None:
|
||||
"""Set up RPC result checkers for all stages.
|
||||
|
||||
Each checker reads from the shared ``_rpc_results`` dict so that
|
||||
``OmniStage.collective_rpc`` can retrieve results that were
|
||||
collected by the orchestrator (or, in the sync path, by the
|
||||
stage-level checker that drains the output queue).
|
||||
|
||||
Uses a weak reference to ``self`` to avoid a circular reference
|
||||
(OmniBase → stage_list → OmniStage → closure → OmniBase) that
|
||||
would prevent the instance from being freed by reference counting.
|
||||
"""
|
||||
weak_self = weakref.ref(self)
|
||||
for stage in self.stage_list:
|
||||
sid = stage.stage_id
|
||||
|
||||
def make_rpc_checker(stage_id: int):
|
||||
def rpc_checker(rpc_id: str) -> dict[str, Any] | None:
|
||||
_self = weak_self()
|
||||
if _self is None:
|
||||
return None
|
||||
# First check the shared dict
|
||||
if stage_id in _self._rpc_results and rpc_id in _self._rpc_results[stage_id]:
|
||||
return _self._rpc_results[stage_id].pop(rpc_id)
|
||||
# In the sync path there is no background output handler,
|
||||
# so drain the output queue ourselves and stash any
|
||||
# non-RPC results back.
|
||||
out_q = _self._stage_out_queues[stage_id] if stage_id < len(_self._stage_out_queues) else None
|
||||
if out_q is not None:
|
||||
import queue as _queue
|
||||
|
||||
try:
|
||||
while True:
|
||||
item = out_q.get_nowait()
|
||||
if isinstance(item, dict) and item.get("type") == "collective_rpc_result":
|
||||
item_rpc_id = item.get("rpc_id")
|
||||
if item_rpc_id == rpc_id:
|
||||
return item
|
||||
# Stash for another caller
|
||||
if stage_id not in _self._rpc_results:
|
||||
_self._rpc_results[stage_id] = {}
|
||||
_self._rpc_results[stage_id][item_rpc_id] = item
|
||||
else:
|
||||
# Non-RPC item — put it back
|
||||
out_q.put(item)
|
||||
break
|
||||
except _queue.Empty:
|
||||
pass
|
||||
return None
|
||||
|
||||
return rpc_checker
|
||||
|
||||
stage._rpc_result_checker = make_rpc_checker(sid)
|
||||
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[..., _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> list[_R]:
|
||||
"""Execute an RPC call on all stage workers.
|
||||
|
||||
Args:
|
||||
method: Name of the worker method to execute, or a callable.
|
||||
timeout: Maximum time in seconds to wait for execution.
|
||||
args: Positional arguments to pass to the worker method.
|
||||
kwargs: Keyword arguments to pass to the worker method.
|
||||
|
||||
Returns:
|
||||
A list containing the results from each stage.
|
||||
"""
|
||||
results: list[_R] = []
|
||||
for stage in self.stage_list:
|
||||
results.append(
|
||||
stage.collective_rpc(
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def sleep(self, level: int = 1) -> None:
|
||||
"""Put the engine to sleep to free up resources.
|
||||
|
||||
Args:
|
||||
level: Sleep level (1 = light sleep, higher = deeper sleep).
|
||||
"""
|
||||
self._is_sleeping = True
|
||||
self.collective_rpc(method="sleep", args=(level,))
|
||||
|
||||
def wake_up(self, tags: list[str] | None = None) -> None:
|
||||
"""Wake the engine up from sleep.
|
||||
|
||||
Args:
|
||||
tags: Optional list of tags to selectively wake components.
|
||||
"""
|
||||
self._is_sleeping = False
|
||||
self.collective_rpc(method="wake_up", args=(tags,))
|
||||
|
||||
def is_sleeping(self) -> bool:
|
||||
"""Check whether the engine is sleeping."""
|
||||
return getattr(self, "_is_sleeping", False)
|
||||
|
||||
def add_lora(self, lora_request: LoRARequest) -> bool:
|
||||
"""Load a new LoRA adapter into the engine for future requests."""
|
||||
result = self.collective_rpc(method="add_lora", args=(lora_request,))
|
||||
return result[0][0]
|
||||
|
||||
def start_profile(self, stages: list[int] | None = None) -> None:
|
||||
"""Start profiling for specified stages.
|
||||
|
||||
@@ -1135,15 +1332,6 @@ class Omni(OmniBase):
|
||||
final_output_type=stage.final_output_type, # type: ignore[attr-defined]
|
||||
request_output=engine_outputs,
|
||||
)
|
||||
try:
|
||||
if stage.final_output_type == "text" or metrics.log_stats:
|
||||
output_to_yield.metrics = metrics.build_output_metrics(stage_id, req_id)
|
||||
except Exception as e:
|
||||
# Make metrics contract explicit on failure.
|
||||
output_to_yield.metrics = {}
|
||||
logger.exception(
|
||||
f"[{self._name}] Failed to attach output metrics for req {req_id} at stage {stage_id}: {e}",
|
||||
)
|
||||
|
||||
# Record audio generated frames (only when finished)
|
||||
try:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
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
|
||||
@@ -12,6 +14,8 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniDiffusion:
|
||||
"""
|
||||
@@ -108,6 +112,7 @@ class OmniDiffusion:
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
request_ids: list[str] = [],
|
||||
) -> list[OmniRequestOutput]:
|
||||
_t0 = time.perf_counter()
|
||||
if isinstance(prompts, (str, dict)):
|
||||
prompts = [prompts]
|
||||
else:
|
||||
@@ -118,7 +123,10 @@ class OmniDiffusion:
|
||||
request_ids.extend(f"{i + len(request_ids)}_{uuid.uuid4()}" for i in range(len(prompts) - len(request_ids)))
|
||||
|
||||
request = OmniDiffusionRequest(prompts, sampling_params, request_ids)
|
||||
return self._run_engine(request)
|
||||
result = self._run_engine(request)
|
||||
_t_ms = (time.perf_counter() - _t0) * 1000
|
||||
logger.info("OmniDiffusion.generate total: %.2f ms", _t_ms)
|
||||
return result
|
||||
|
||||
def _run_engine(self, request: OmniDiffusionRequest) -> list[OmniRequestOutput]:
|
||||
return self.engine.step(request)
|
||||
|
||||
@@ -15,10 +15,11 @@ import queue
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from collections.abc import Sequence
|
||||
import uuid
|
||||
from collections.abc import Callable, Sequence
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import fields
|
||||
from typing import Any, Literal, cast
|
||||
from typing import Any, Literal, TypeVar, cast
|
||||
|
||||
from vllm import PromptType, RequestOutput
|
||||
from vllm.inputs import TextPrompt
|
||||
@@ -60,6 +61,8 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, O
|
||||
from vllm_omni.metrics import count_tokens_from_outputs
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
_R = TypeVar("_R")
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -302,6 +305,10 @@ class OmniStage:
|
||||
self._proc: mp.Process | None = None
|
||||
self._shm_threshold_bytes: int = 65536
|
||||
self._stage_init_timeout: int = stage_init_timeout
|
||||
# Callback used by the orchestrator's output handler to stash
|
||||
# collective_rpc results so that ``collective_rpc`` can retrieve
|
||||
# them without competing for the output queue.
|
||||
self._rpc_result_checker: Callable[[str], dict | None] | None = None
|
||||
|
||||
def set_engine(self, engine: LLMEngine) -> None:
|
||||
"""Set the LLM engine for this stage.
|
||||
@@ -406,6 +413,71 @@ class OmniStage:
|
||||
logger.error(f"[Stage-{self.stage_id}] Timeout waiting for profiler results.")
|
||||
return {}
|
||||
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[..., _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> list[_R]:
|
||||
"""Execute an RPC call on all workers via the stage engine.
|
||||
|
||||
Args:
|
||||
method: Name of the worker method to execute, or a callable that
|
||||
is serialized and sent to all workers to execute.
|
||||
|
||||
If the method is a callable, it should accept an additional
|
||||
``self`` argument, in addition to the arguments passed in
|
||||
``args`` and ``kwargs``. The ``self`` argument will be the
|
||||
worker object.
|
||||
timeout: Maximum time in seconds to wait for execution. Raises a
|
||||
:class:`TimeoutError` on timeout. ``None`` means wait
|
||||
indefinitely.
|
||||
args: Positional arguments to pass to the worker method.
|
||||
kwargs: Keyword arguments to pass to the worker method.
|
||||
|
||||
Returns:
|
||||
A list containing the results from each worker.
|
||||
|
||||
Note:
|
||||
It is recommended to use this API to only pass control messages,
|
||||
and set up data-plane communication to pass data.
|
||||
"""
|
||||
assert self._in_q is not None and self._out_q is not None, "Queues must be attached before collective_rpc"
|
||||
|
||||
# Submit collective_rpc task to worker
|
||||
rpc_id = str(uuid.uuid4())
|
||||
self._in_q.put(
|
||||
{
|
||||
"type": OmniStageTaskType.COLLECTIVE_RPC,
|
||||
"rpc_id": rpc_id,
|
||||
"method": method,
|
||||
"timeout": timeout,
|
||||
"args": args,
|
||||
"kwargs": kwargs,
|
||||
}
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
while True:
|
||||
if timeout is not None and (time.time() - start_time) > timeout:
|
||||
raise TimeoutError(f"collective_rpc timed out after {timeout} seconds")
|
||||
|
||||
# Check if result was already collected by the orchestrator's
|
||||
# output handler (stored in a shared dict).
|
||||
result = None
|
||||
if self._rpc_result_checker is not None:
|
||||
result = self._rpc_result_checker(rpc_id)
|
||||
|
||||
if result is not None:
|
||||
if result.get("type") == "collective_rpc_result":
|
||||
if result.get("rpc_id") == rpc_id:
|
||||
if "error" in result:
|
||||
raise RuntimeError(f"collective_rpc failed: {result['error']}")
|
||||
return result["result"]
|
||||
|
||||
time.sleep(0.001) # Small sleep to avoid busy waiting
|
||||
|
||||
def init_stage_worker(
|
||||
self,
|
||||
model: str,
|
||||
@@ -538,14 +610,24 @@ class OmniStage:
|
||||
try:
|
||||
self._in_q.put_nowait(SHUTDOWN_TASK)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to send shutdown to in_q: %s", e)
|
||||
# Queue may already be closed by the weak-ref cleanup
|
||||
# (e.g. ZmqQueue socket closed) — this is expected.
|
||||
logger.debug("Failed to send shutdown to in_q: %s", e)
|
||||
close_fn = getattr(self._in_q, "close", None)
|
||||
if callable(close_fn):
|
||||
close_fn()
|
||||
try:
|
||||
close_fn()
|
||||
except Exception:
|
||||
pass
|
||||
self._in_q = None
|
||||
if self._out_q is not None:
|
||||
close_fn = getattr(self._out_q, "close", None)
|
||||
if callable(close_fn):
|
||||
close_fn()
|
||||
try:
|
||||
close_fn()
|
||||
except Exception:
|
||||
pass
|
||||
self._out_q = None
|
||||
|
||||
if hasattr(self, "_ray_actor") and self._ray_actor:
|
||||
kill_ray_actor(self._ray_actor)
|
||||
@@ -874,6 +956,40 @@ def _stage_worker(
|
||||
out_q.put({"type": "profiler_result", "data": profiler_data})
|
||||
continue
|
||||
|
||||
# Handle collective_rpc commands
|
||||
if task_type == OmniStageTaskType.COLLECTIVE_RPC:
|
||||
rpc_id = task.get("rpc_id")
|
||||
rpc_method = task.get("method")
|
||||
rpc_timeout = task.get("timeout")
|
||||
rpc_args = task.get("args", ())
|
||||
rpc_kwargs = task.get("kwargs") or {}
|
||||
try:
|
||||
rpc_result = stage_engine.collective_rpc(
|
||||
method=rpc_method,
|
||||
timeout=rpc_timeout,
|
||||
args=rpc_args,
|
||||
kwargs=rpc_kwargs,
|
||||
)
|
||||
out_q.put(
|
||||
{
|
||||
"type": "collective_rpc_result",
|
||||
"rpc_id": rpc_id,
|
||||
"stage_id": stage_id,
|
||||
"result": rpc_result,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("[Stage-%s] collective_rpc failed: %s", stage_id, e)
|
||||
out_q.put(
|
||||
{
|
||||
"type": "collective_rpc_result",
|
||||
"rpc_id": rpc_id,
|
||||
"stage_id": stage_id,
|
||||
"error": str(e),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
batch_tasks: list[dict[str, Any]] = [task]
|
||||
tasks_failed_to_add_to_batch: list[dict[str, Any]] = []
|
||||
start_time = _time.time()
|
||||
@@ -1003,7 +1119,6 @@ def _stage_worker(
|
||||
gen_outputs.extend(results)
|
||||
_gen_t1 = _time.time()
|
||||
_gen_ms = (_gen_t1 - _gen_t0) * 1000.0
|
||||
logger.debug(f"Generate done: batch={len(batch_tasks)}, req_ids={batch_request_ids}, gen_ms={_gen_ms:.1f}")
|
||||
|
||||
# Group outputs per request id with fallback
|
||||
req_to_outputs: dict[Any, list[Any]] = {rid: [] for rid in batch_request_ids}
|
||||
@@ -1043,6 +1158,10 @@ def _stage_worker(
|
||||
_metrics.stage_stats = None
|
||||
try:
|
||||
use_shm, payload = maybe_dump_to_shm(r_outputs, shm_threshold_bytes)
|
||||
except Exception:
|
||||
use_shm, payload = False, r_outputs
|
||||
|
||||
try:
|
||||
if use_shm:
|
||||
out_q.put(
|
||||
{
|
||||
@@ -1070,10 +1189,6 @@ def _stage_worker(
|
||||
"metrics": _metrics,
|
||||
}
|
||||
)
|
||||
logger.debug(
|
||||
"Enqueued result for request %s to downstream",
|
||||
rid,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Failed on batch %s: %s", batch_request_ids, e)
|
||||
_tb = traceback.format_exc()
|
||||
@@ -1402,6 +1517,54 @@ async def _stage_worker_async(
|
||||
# Send result back to orchestrator for STOP command
|
||||
if task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
out_q.put({"type": "profiler_result", "data": profiler_data})
|
||||
elif task_type == OmniStageTaskType.COLLECTIVE_RPC:
|
||||
rpc_id = task.get("rpc_id")
|
||||
rpc_method = task.get("method")
|
||||
rpc_timeout = task.get("timeout")
|
||||
rpc_args = task.get("args", ())
|
||||
rpc_kwargs = task.get("kwargs") or {}
|
||||
try:
|
||||
if stage_type == "diffusion":
|
||||
# DiffusionEngine.collective_rpc is synchronous
|
||||
loop = asyncio.get_event_loop()
|
||||
rpc_result = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: stage_engine.engine.collective_rpc(
|
||||
method=rpc_method,
|
||||
timeout=rpc_timeout,
|
||||
args=rpc_args,
|
||||
kwargs=rpc_kwargs,
|
||||
),
|
||||
)
|
||||
else:
|
||||
rpc_result = await cast(AsyncLLM, stage_engine).collective_rpc(
|
||||
method=rpc_method,
|
||||
timeout=rpc_timeout,
|
||||
args=rpc_args,
|
||||
kwargs=rpc_kwargs,
|
||||
)
|
||||
out_q.put(
|
||||
{
|
||||
"type": "collective_rpc_result",
|
||||
"rpc_id": rpc_id,
|
||||
"stage_id": stage_id,
|
||||
"result": rpc_result,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"[Stage-%s] collective_rpc failed: %s",
|
||||
stage_id,
|
||||
e,
|
||||
)
|
||||
out_q.put(
|
||||
{
|
||||
"type": "collective_rpc_result",
|
||||
"rpc_id": rpc_id,
|
||||
"stage_id": stage_id,
|
||||
"error": str(e),
|
||||
}
|
||||
)
|
||||
else:
|
||||
asyncio.create_task(generation_single_request(task))
|
||||
|
||||
@@ -1555,10 +1718,16 @@ def output_strip(r_output: RequestOutput | OmniRequestOutput, final_output: bool
|
||||
if mm_output is not None:
|
||||
r_output.multimodal_output = {}
|
||||
|
||||
custom_out = getattr(r_output, "_custom_output", None)
|
||||
if custom_out is not None:
|
||||
r_output._custom_output = {}
|
||||
|
||||
outputs = getattr(r_output, "outputs", None)
|
||||
if outputs is not None:
|
||||
for out in outputs:
|
||||
if getattr(out, "multimodal_output", None):
|
||||
out.multimodal_output = {}
|
||||
if getattr(out, "_custom_output", None):
|
||||
out._custom_output = {}
|
||||
|
||||
return r_output
|
||||
@@ -882,8 +882,113 @@ async def list_voices(raw_request: Request):
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Speech API")
|
||||
|
||||
# Get all speakers (both model built-in and uploaded)
|
||||
speakers = sorted(handler.supported_speakers) if handler.supported_speakers else []
|
||||
return JSONResponse(content={"voices": speakers})
|
||||
|
||||
# Get uploaded speakers details
|
||||
uploaded_speakers = []
|
||||
if hasattr(handler, "uploaded_speakers"):
|
||||
for voice_name, info in handler.uploaded_speakers.items():
|
||||
uploaded_speakers.append(
|
||||
{
|
||||
"name": info.get("name", voice_name),
|
||||
"consent": info.get("consent", ""),
|
||||
"created_at": info.get("created_at", 0),
|
||||
"file_size": info.get("file_size", 0),
|
||||
"mime_type": info.get("mime_type", ""),
|
||||
}
|
||||
)
|
||||
|
||||
return JSONResponse(content={"voices": speakers, "uploaded_voices": uploaded_speakers})
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/audio/voices",
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"model": dict},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
async def upload_voice(
|
||||
raw_request: Request,
|
||||
audio_sample: UploadFile = File(...),
|
||||
consent: str = Form(...),
|
||||
name: str = Form(...),
|
||||
):
|
||||
"""Upload a new voice sample for voice cloning.
|
||||
|
||||
Uploads an audio file that can be used as a reference for voice cloning
|
||||
in Base task TTS requests. The voice can then be referenced by name
|
||||
in subsequent TTS requests.
|
||||
|
||||
Args:
|
||||
audio_sample: Audio file (max 10MB)
|
||||
consent: Consent recording ID
|
||||
name: Name for the new voice
|
||||
raw_request: Raw FastAPI request
|
||||
|
||||
Returns:
|
||||
JSON response with voice information
|
||||
"""
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Speech API")
|
||||
|
||||
try:
|
||||
# Upload the voice
|
||||
result = await handler.upload_voice(audio_sample, consent, name)
|
||||
|
||||
return JSONResponse(content={"success": True, "voice": result})
|
||||
|
||||
except ValueError as e:
|
||||
return base(raw_request).create_error_response(message=str(e))
|
||||
except Exception as e:
|
||||
logger.exception(f"Failed to upload voice: {e}")
|
||||
return base(raw_request).create_error_response(message=f"Failed to upload voice: {str(e)}")
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/v1/audio/voices/{name}",
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"model": dict},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
async def delete_voice(name: str, raw_request: Request):
|
||||
"""Delete an uploaded voice.
|
||||
|
||||
Deletes the voice sample and associated metadata. Also removes any
|
||||
cached voice clone prompts for this voice.
|
||||
|
||||
Args:
|
||||
name: Name of the voice to delete
|
||||
raw_request: Raw FastAPI request
|
||||
|
||||
Returns:
|
||||
JSON response indicating success or failure
|
||||
"""
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Speech API")
|
||||
|
||||
try:
|
||||
# Delete the voice
|
||||
success = await handler.delete_voice(name)
|
||||
if not success:
|
||||
return JSONResponse(
|
||||
content={"success": False, "error": f"Voice '{name}' not found"},
|
||||
status_code=HTTPStatus.NOT_FOUND.value,
|
||||
)
|
||||
|
||||
return JSONResponse(content={"success": True, "message": f"Voice '{name}' deleted successfully"})
|
||||
|
||||
except ValueError as e:
|
||||
return base(raw_request).create_error_response(message=str(e))
|
||||
except Exception as e:
|
||||
logger.exception(f"Failed to delete voice '{name}': {e}")
|
||||
return base(raw_request).create_error_response(message=f"Failed to delete voice: {str(e)}")
|
||||
|
||||
|
||||
# Health and Model endpoints for diffusion mode
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
Metadata manager for voice samples and cache information.
|
||||
|
||||
Provides a unified interface for managing metadata.json with
|
||||
concurrency safety and data consistency across multiple processes.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MetadataManager:
|
||||
"""
|
||||
Manages metadata for uploaded speakers and cache information.
|
||||
|
||||
Features:
|
||||
1. Single source of truth for metadata
|
||||
2. Concurrency safety with threading locks
|
||||
3. Atomic read-modify-write operations
|
||||
4. Merge updates to preserve fields from different components
|
||||
"""
|
||||
|
||||
def __init__(self, metadata_file: Path):
|
||||
"""
|
||||
Initialize the metadata manager.
|
||||
|
||||
Args:
|
||||
metadata_file: Path to metadata.json file
|
||||
"""
|
||||
self.metadata_file = metadata_file
|
||||
self._lock = threading.Lock() # For intra-process concurrency
|
||||
self._metadata = self._load_from_disk()
|
||||
|
||||
# Create lock file for cross-process synchronization
|
||||
self.lock_file = metadata_file.with_suffix(".lock")
|
||||
self.lock_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _load_from_disk(self) -> dict[str, Any]:
|
||||
"""Load metadata from disk."""
|
||||
if not self.metadata_file.exists():
|
||||
return {"uploaded_speakers": {}}
|
||||
|
||||
try:
|
||||
with open(self.metadata_file) as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load metadata from {self.metadata_file}: {e}")
|
||||
return {"uploaded_speakers": {}}
|
||||
|
||||
def _save_to_disk(self, metadata: dict[str, Any]) -> bool:
|
||||
"""Save metadata to disk."""
|
||||
try:
|
||||
self.metadata_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = self.metadata_file.with_suffix(".tmp")
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(metadata, f, indent=2)
|
||||
tmp.replace(self.metadata_file)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save metadata to {self.metadata_file}: {e}")
|
||||
return False
|
||||
|
||||
# ================================
|
||||
# Core fix: single flock overwrites RMW
|
||||
# ================================
|
||||
def _update_with_file_lock(
|
||||
self, update_fn: Callable[[dict[str, Any]], dict[str, Any] | None]
|
||||
) -> dict[str, Any] | None:
|
||||
lock_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR)
|
||||
try:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX)
|
||||
|
||||
metadata = self._load_from_disk()
|
||||
result = update_fn(metadata)
|
||||
if result is None:
|
||||
return None
|
||||
|
||||
if not self._save_to_disk(metadata):
|
||||
return None
|
||||
|
||||
self._metadata = metadata
|
||||
return result
|
||||
finally:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
||||
os.close(lock_fd)
|
||||
|
||||
def get_uploaded_speakers(self) -> dict[str, dict[str, Any]]:
|
||||
"""Get all uploaded speakers."""
|
||||
# Read directly from disk to ensure getting the latest data
|
||||
metadata = self._load_from_disk()
|
||||
return metadata.get("uploaded_speakers", {}).copy()
|
||||
|
||||
def get_speaker(self, speaker_key: str) -> dict[str, Any] | None:
|
||||
"""Get specific speaker information."""
|
||||
# Read directly from disk to ensure getting the latest data
|
||||
metadata = self._load_from_disk()
|
||||
speakers = metadata.get("uploaded_speakers", {})
|
||||
return speakers.get(speaker_key, {}).copy() if speaker_key in speakers else None
|
||||
|
||||
def update_speaker(self, speaker_key: str, updates: dict[str, Any]) -> bool:
|
||||
"""
|
||||
Update speaker information with merge semantics.
|
||||
|
||||
Uses file locking for cross-process atomic operations.
|
||||
"""
|
||||
with self._lock:
|
||||
|
||||
def _update(metadata: dict[str, Any]):
|
||||
speakers = metadata.setdefault("uploaded_speakers", {})
|
||||
entry = speakers.get(speaker_key, {})
|
||||
entry.update(updates)
|
||||
speakers[speaker_key] = entry
|
||||
return True
|
||||
|
||||
return self._update_with_file_lock(_update) is not None
|
||||
|
||||
def create_speaker(self, speaker_key: str, speaker_data: dict[str, Any]) -> bool:
|
||||
"""
|
||||
Create a new speaker entry.
|
||||
|
||||
Uses file locking for cross-process atomic operations.
|
||||
"""
|
||||
with self._lock:
|
||||
|
||||
def _create(metadata: dict[str, Any]):
|
||||
speakers = metadata.setdefault("uploaded_speakers", {})
|
||||
if speaker_key in speakers:
|
||||
logger.warning(f"Speaker {speaker_key} already exists")
|
||||
return None
|
||||
speakers[speaker_key] = speaker_data
|
||||
return True
|
||||
|
||||
return self._update_with_file_lock(_create) is not None
|
||||
|
||||
def update_cache_info(self, speaker_key: str, cache_file_path: Path, status: str = "ready") -> bool:
|
||||
"""
|
||||
Update cache information for a speaker.
|
||||
"""
|
||||
updates = {
|
||||
"cache_status": status,
|
||||
"cache_file": str(cache_file_path),
|
||||
"cache_generated_at": time.time(),
|
||||
}
|
||||
return self.update_speaker(speaker_key, updates)
|
||||
|
||||
def delete_speaker(self, speaker_key: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
Delete a speaker from metadata and clean up associated files.
|
||||
|
||||
Uses file locking for cross-process atomic operations.
|
||||
|
||||
Args:
|
||||
speaker_key: Speaker name (lowercase)
|
||||
base_dir: Base directory for file validation (optional)
|
||||
|
||||
Returns:
|
||||
dict: Deleted speaker information if successful, None if speaker doesn't exist or error
|
||||
"""
|
||||
with self._lock:
|
||||
|
||||
def _delete(metadata: dict[str, Any]):
|
||||
speakers = metadata.get("uploaded_speakers", {})
|
||||
if speaker_key not in speakers:
|
||||
logger.warning(f"Speaker {speaker_key} not found in metadata")
|
||||
return None
|
||||
|
||||
speaker_info = speakers.pop(speaker_key)
|
||||
|
||||
# Clean up associated files
|
||||
deleted_files = self._cleanup_speaker_files(speaker_info)
|
||||
if deleted_files:
|
||||
logger.info(f"Deleted {len(deleted_files)} files for speaker {speaker_key}: {deleted_files}")
|
||||
|
||||
return speaker_info
|
||||
|
||||
return self._update_with_file_lock(_delete)
|
||||
|
||||
def _cleanup_speaker_files(self, speaker_info: dict[str, Any]) -> list[str]:
|
||||
"""
|
||||
Clean up files associated with a speaker.
|
||||
|
||||
Args:
|
||||
speaker_info: Speaker information dictionary
|
||||
base_dir: Base directory for file validation (optional)
|
||||
|
||||
Returns:
|
||||
list: List of successfully deleted file paths
|
||||
"""
|
||||
deleted_files = []
|
||||
|
||||
# Helper function to safely delete a file
|
||||
def safe_delete(file_path_str: str, description: str) -> bool:
|
||||
if not file_path_str:
|
||||
return False
|
||||
|
||||
try:
|
||||
file_path = Path(file_path_str)
|
||||
|
||||
# Check if file exists
|
||||
if not file_path.exists():
|
||||
logger.debug(f"{description} not found: {file_path}")
|
||||
return False
|
||||
|
||||
# Delete the file
|
||||
file_path.unlink()
|
||||
logger.info(f"Deleted {description}: {file_path}")
|
||||
deleted_files.append(str(file_path))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete {description} {file_path_str}: {e}")
|
||||
return False
|
||||
|
||||
# Delete audio file
|
||||
audio_file = speaker_info.get("file_path")
|
||||
if audio_file:
|
||||
safe_delete(audio_file, "audio file")
|
||||
|
||||
# Delete cache file
|
||||
cache_file = speaker_info.get("cache_file")
|
||||
if cache_file:
|
||||
safe_delete(cache_file, "cache file")
|
||||
|
||||
return deleted_files
|
||||
|
||||
def reload_from_disk(self) -> bool:
|
||||
"""Force reload metadata from disk (useful for external changes)."""
|
||||
with self._lock:
|
||||
try:
|
||||
self._metadata = self._load_from_disk()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to reload metadata from disk: {e}")
|
||||
return False
|
||||
@@ -1,24 +1,23 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import ipaddress
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import socket
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import urlopen
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from fastapi import Request
|
||||
from fastapi import Request, UploadFile
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
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_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.metadata_manager import MetadataManager
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
CreateAudio,
|
||||
OpenAICreateSpeechRequest,
|
||||
@@ -27,19 +26,6 @@ from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_REF_AUDIO_TIMEOUT_S = 15
|
||||
_REF_AUDIO_MAX_BYTES = 50 * 1024 * 1024 # 50 MB
|
||||
_REF_AUDIO_BLOCKED_NETWORKS = [
|
||||
ipaddress.ip_network("127.0.0.0/8"),
|
||||
ipaddress.ip_network("10.0.0.0/8"),
|
||||
ipaddress.ip_network("172.16.0.0/12"),
|
||||
ipaddress.ip_network("192.168.0.0/16"),
|
||||
ipaddress.ip_network("169.254.0.0/16"),
|
||||
ipaddress.ip_network("::1/128"),
|
||||
ipaddress.ip_network("fc00::/7"),
|
||||
ipaddress.ip_network("fe80::/10"),
|
||||
]
|
||||
|
||||
# TTS Configuration (currently supports Qwen3-TTS)
|
||||
_TTS_MODEL_STAGES: set[str] = {"qwen3_tts"}
|
||||
_TTS_LANGUAGES: set[str] = {
|
||||
@@ -60,9 +46,52 @@ _TTS_MAX_NEW_TOKENS_MIN = 1
|
||||
_TTS_MAX_NEW_TOKENS_MAX = 4096
|
||||
|
||||
|
||||
def _sanitize_filename(filename: str) -> str:
|
||||
"""Sanitize filename to prevent path traversal attacks.
|
||||
|
||||
Only allows alphanumeric characters, underscores, hyphens, and dots.
|
||||
Replaces any other characters with underscores.
|
||||
"""
|
||||
# Remove any path components
|
||||
filename = os.path.basename(filename)
|
||||
# Replace any non-alphanumeric, underscore, hyphen, or dot with underscore
|
||||
sanitized = re.sub(r"[^a-zA-Z0-9_.\-]", "_", filename)
|
||||
# Ensure filename is not empty
|
||||
if not sanitized:
|
||||
sanitized = "file"
|
||||
# Limit length to prevent potential issues
|
||||
if len(sanitized) > 255:
|
||||
sanitized = sanitized[:255]
|
||||
return sanitized
|
||||
|
||||
|
||||
def _validate_path_within_directory(file_path: Path, directory: Path) -> bool:
|
||||
"""Validate that file_path is within the specified directory.
|
||||
|
||||
Prevents path traversal attacks by ensuring the resolved path
|
||||
is within the target directory.
|
||||
"""
|
||||
try:
|
||||
# Resolve both paths to absolute paths
|
||||
file_path_resolved = file_path.resolve()
|
||||
directory_resolved = directory.resolve()
|
||||
# Check if file_path is within directory
|
||||
return directory_resolved in file_path_resolved.parents or directory_resolved == file_path_resolved
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# Initialize uploaded speakers storage
|
||||
speech_voice_samples_dir = os.environ.get("SPEECH_VOICE_SAMPLES", "/tmp/voice_samples")
|
||||
self.uploaded_speakers_dir = Path(speech_voice_samples_dir)
|
||||
self.uploaded_speakers_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.metadata_file = self.uploaded_speakers_dir / "metadata.json"
|
||||
|
||||
# Initialize metadata manager
|
||||
self.metadata_manager = MetadataManager(self.metadata_file)
|
||||
|
||||
# Find and cache the TTS stage (if any) during initialization
|
||||
self._tts_stage = self._find_tts_stage()
|
||||
@@ -73,9 +102,16 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
# Load supported speakers
|
||||
self.supported_speakers = self._load_supported_speakers()
|
||||
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
|
||||
# Load uploaded speakers
|
||||
self.uploaded_speakers = self.metadata_manager.get_uploaded_speakers()
|
||||
|
||||
# Merge supported speakers with uploaded speakers
|
||||
self.supported_speakers.update(self.uploaded_speakers.keys())
|
||||
self._tts_tokenizer = None
|
||||
|
||||
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
|
||||
logger.info(f"Loaded {len(self.uploaded_speakers)} uploaded speakers")
|
||||
|
||||
# Load speech tokenizer codec parameters for prompt length estimation
|
||||
self._codec_frame_rate: float | None = self._load_codec_frame_rate()
|
||||
|
||||
@@ -223,6 +259,191 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
logger.warning("Failed to estimate TTS prompt length, using fallback 2048: %s", e)
|
||||
return 2048
|
||||
|
||||
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()
|
||||
if voice_name_lower not in self.uploaded_speakers:
|
||||
return None
|
||||
|
||||
speaker_info = self.uploaded_speakers[voice_name_lower]
|
||||
file_path = Path(speaker_info["file_path"])
|
||||
|
||||
if not file_path.exists():
|
||||
logger.warning(f"Audio file not found for voice {voice_name}: {file_path}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Read audio file
|
||||
with open(file_path, "rb") as f:
|
||||
audio_bytes = f.read()
|
||||
|
||||
# Encode to base64
|
||||
audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
|
||||
|
||||
# Get MIME type from file extension
|
||||
mime_type = speaker_info.get("mime_type", "audio/wav")
|
||||
|
||||
# Return as data URL
|
||||
return f"data:{mime_type};base64,{audio_b64}"
|
||||
except Exception as e:
|
||||
logger.error(f"Could not read audio file for voice {voice_name}: {e}")
|
||||
return None
|
||||
|
||||
async def upload_voice(self, audio_file: UploadFile, consent: str, name: str) -> dict:
|
||||
"""Upload a new voice sample."""
|
||||
# Validate file size (max 10MB)
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
|
||||
audio_file.file.seek(0, 2) # Seek to end
|
||||
file_size = audio_file.file.tell()
|
||||
audio_file.file.seek(0) # Reset to beginning
|
||||
|
||||
if file_size > MAX_FILE_SIZE:
|
||||
raise ValueError(f"File size exceeds maximum limit of 10MB. Got {file_size} bytes.")
|
||||
|
||||
# Detect MIME type from filename if content_type is generic
|
||||
mime_type = audio_file.content_type
|
||||
if mime_type == "application/octet-stream":
|
||||
# Simple MIME type detection based on file extension
|
||||
filename_lower = audio_file.filename.lower()
|
||||
if filename_lower.endswith(".wav"):
|
||||
mime_type = "audio/wav"
|
||||
elif filename_lower.endswith((".mp3", ".mpeg")):
|
||||
mime_type = "audio/mpeg"
|
||||
elif filename_lower.endswith(".flac"):
|
||||
mime_type = "audio/flac"
|
||||
elif filename_lower.endswith(".ogg"):
|
||||
mime_type = "audio/ogg"
|
||||
elif filename_lower.endswith(".aac"):
|
||||
mime_type = "audio/aac"
|
||||
elif filename_lower.endswith(".webm"):
|
||||
mime_type = "audio/webm"
|
||||
elif filename_lower.endswith(".mp4"):
|
||||
mime_type = "audio/mp4"
|
||||
else:
|
||||
mime_type = "audio/wav" # Default
|
||||
|
||||
# Validate MIME type
|
||||
allowed_mime_types = {
|
||||
"audio/mpeg",
|
||||
"audio/wav",
|
||||
"audio/x-wav",
|
||||
"audio/ogg",
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
"audio/webm",
|
||||
"audio/mp4",
|
||||
}
|
||||
|
||||
if mime_type not in allowed_mime_types:
|
||||
raise ValueError(f"Unsupported MIME type: {mime_type}. Allowed: {allowed_mime_types}")
|
||||
|
||||
# Normalize voice name
|
||||
voice_name_lower = name.lower()
|
||||
|
||||
# Check if voice already exists
|
||||
if voice_name_lower in self.uploaded_speakers:
|
||||
raise ValueError(f"Voice '{name}' already exists")
|
||||
|
||||
# Sanitize name and consent to prevent path traversal
|
||||
sanitized_name = _sanitize_filename(name)
|
||||
sanitized_consent = _sanitize_filename(consent)
|
||||
|
||||
# Generate filename with sanitized inputs
|
||||
timestamp = int(time.time())
|
||||
file_suffix = Path(audio_file.filename).suffix
|
||||
file_ext = file_suffix[1:] if file_suffix and len(file_suffix) > 1 else "wav"
|
||||
# Sanitize file extension as well
|
||||
sanitized_ext = _sanitize_filename(file_ext)
|
||||
if not sanitized_ext or sanitized_ext == "file":
|
||||
sanitized_ext = "wav"
|
||||
|
||||
filename = f"{sanitized_name}_{sanitized_consent}_{timestamp}.{sanitized_ext}"
|
||||
file_path = self.uploaded_speakers_dir / filename
|
||||
|
||||
# Double-check that the path is within the upload directory
|
||||
if not _validate_path_within_directory(file_path, self.uploaded_speakers_dir):
|
||||
raise ValueError("Invalid file path: potential path traversal attack detected")
|
||||
|
||||
# Save audio file
|
||||
try:
|
||||
with open(file_path, "wb") as f:
|
||||
content = await audio_file.read()
|
||||
f.write(content)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to save audio file: {e}")
|
||||
|
||||
# Create speaker data
|
||||
speaker_data = {
|
||||
"name": name,
|
||||
"consent": consent,
|
||||
"file_path": str(file_path),
|
||||
"created_at": timestamp,
|
||||
"mime_type": mime_type,
|
||||
"original_filename": audio_file.filename,
|
||||
"file_size": file_size,
|
||||
"cache_status": "pending", # The initial cache state is pending.
|
||||
"cache_file": None, # The initial cache file is empty.
|
||||
"cache_generated_at": None, # The initial cache generation time is empty.
|
||||
}
|
||||
|
||||
# Save metadata using metadata manager (concurrency safe)
|
||||
success = self.metadata_manager.create_speaker(voice_name_lower, speaker_data)
|
||||
if not success:
|
||||
# Clean up the saved file if metadata creation failed
|
||||
try:
|
||||
file_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise ValueError(f"Failed to create metadata for voice '{name}' (possibly already exists)")
|
||||
|
||||
# Update in-memory cache
|
||||
self.uploaded_speakers[voice_name_lower] = speaker_data
|
||||
self.supported_speakers.add(voice_name_lower)
|
||||
|
||||
logger.info(f"Uploaded new voice '{name}' with consent ID '{consent}'")
|
||||
|
||||
# Return voice information without exposing the server file path
|
||||
return {
|
||||
"name": name,
|
||||
"consent": consent,
|
||||
"created_at": timestamp,
|
||||
"mime_type": mime_type,
|
||||
"file_size": file_size,
|
||||
}
|
||||
|
||||
async def delete_voice(self, name: str) -> bool:
|
||||
"""
|
||||
Delete an uploaded voice.
|
||||
|
||||
Args:
|
||||
name: Voice name to delete
|
||||
|
||||
Returns:
|
||||
bool: True if successful, False if voice doesn't exist
|
||||
"""
|
||||
voice_name_lower = name.lower()
|
||||
|
||||
# Check if voice exists in memory cache
|
||||
if voice_name_lower not in self.uploaded_speakers:
|
||||
logger.warning(f"Voice '{name}' not found in memory cache")
|
||||
return False
|
||||
|
||||
# Delete from metadata manager with file cleanup
|
||||
# Pass base_dir for path validation
|
||||
deleted_info = self.metadata_manager.delete_speaker(voice_name_lower)
|
||||
if not deleted_info:
|
||||
logger.error(f"Failed to delete voice '{name}' from metadata")
|
||||
return False
|
||||
|
||||
# Update in-memory cache
|
||||
if voice_name_lower in self.uploaded_speakers:
|
||||
del self.uploaded_speakers[voice_name_lower]
|
||||
if voice_name_lower in self.supported_speakers:
|
||||
self.supported_speakers.remove(voice_name_lower)
|
||||
|
||||
logger.info(f"Deleted voice '{name}' and associated files")
|
||||
return True
|
||||
|
||||
def _is_tts_model(self) -> bool:
|
||||
"""Check if the current model is a supported TTS model."""
|
||||
stage_list = getattr(self.engine_client, "stage_list", None)
|
||||
@@ -265,19 +486,48 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
# Validate Base task requirements
|
||||
if task_type == "Base":
|
||||
if request.ref_audio is None:
|
||||
return "Base task requires 'ref_audio' for voice cloning"
|
||||
# Validate ref_audio format
|
||||
if not (request.ref_audio.startswith(("http://", "https://")) or request.ref_audio.startswith("data:")):
|
||||
return "ref_audio must be a URL (http/https) or base64 data URL (data:...)"
|
||||
# In-context voice cloning (default) requires non-empty ref_text.
|
||||
# x_vector_only_mode skips in-context and only uses speaker embedding.
|
||||
if not request.x_vector_only_mode:
|
||||
if not request.ref_text or not request.ref_text.strip():
|
||||
return (
|
||||
"Base task requires non-empty 'ref_text' (transcript of "
|
||||
"the reference audio) unless 'x_vector_only_mode' is enabled"
|
||||
)
|
||||
if request.voice is None:
|
||||
if request.ref_audio is None:
|
||||
return "Base task requires 'ref_audio' for voice cloning"
|
||||
# Validate ref_audio format (include file:// from upstream)
|
||||
if not (
|
||||
request.ref_audio.startswith(("http://", "https://"))
|
||||
or request.ref_audio.startswith("data:")
|
||||
or request.ref_audio.startswith("file://")
|
||||
):
|
||||
return "ref_audio must be a URL (http/https), base64 data URL (data:...), or file URI (file://...)"
|
||||
# In-context voice cloning (default) requires non-empty ref_text.
|
||||
# x_vector_only_mode skips in-context and only uses speaker embedding.
|
||||
if not request.x_vector_only_mode:
|
||||
if not request.ref_text or not request.ref_text.strip():
|
||||
return (
|
||||
"Base task requires non-empty 'ref_text' (transcript of "
|
||||
"the reference audio) unless 'x_vector_only_mode' is enabled"
|
||||
)
|
||||
else:
|
||||
# voice is not None
|
||||
voice_lower = request.voice.lower()
|
||||
if voice_lower in self.uploaded_speakers:
|
||||
# Check if audio file exists for uploaded speaker
|
||||
speaker_info = self.uploaded_speakers[voice_lower]
|
||||
file_path = Path(speaker_info["file_path"])
|
||||
if not file_path.exists():
|
||||
return f"Audio file for uploaded speaker '{request.voice}' not found on disk"
|
||||
else:
|
||||
# need ref_audio for built-in speaker
|
||||
if request.ref_audio is None:
|
||||
return (
|
||||
f"Base task with built-in speaker '{request.voice}' requires 'ref_audio' for voice cloning"
|
||||
)
|
||||
# Validate ref_audio format for built-in speaker
|
||||
if not (
|
||||
request.ref_audio.startswith(("http://", "https://"))
|
||||
or request.ref_audio.startswith("data:")
|
||||
or request.ref_audio.startswith("file://")
|
||||
):
|
||||
return (
|
||||
"ref_audio must be a URL (http/https), base64 data URL (data:...), or file URI (file://...)"
|
||||
)
|
||||
|
||||
# Validate cross-parameter dependencies
|
||||
if task_type != "Base":
|
||||
@@ -303,44 +553,23 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def _resolve_ref_audio(ref_audio_str: str) -> tuple[list[float], int]:
|
||||
"""Resolve ref_audio URL/base64 to (wav_samples, sample_rate)."""
|
||||
parsed = urlparse(ref_audio_str)
|
||||
async def _resolve_ref_audio(self, ref_audio_str: str) -> tuple[list[float], int]:
|
||||
"""Resolve ref_audio to (wav_samples, sample_rate).
|
||||
|
||||
def _check_ssrf(url: str) -> None:
|
||||
host = urlparse(url).hostname
|
||||
if not host:
|
||||
raise ValueError("ref_audio URL must include a hostname")
|
||||
for info in socket.getaddrinfo(host, None):
|
||||
ip_str = str(info[4][0]).split("%", 1)[0]
|
||||
addr = ipaddress.ip_address(ip_str)
|
||||
if any(addr in net for net in _REF_AUDIO_BLOCKED_NETWORKS):
|
||||
raise ValueError(f"ref_audio URL resolves to blocked address: {addr}")
|
||||
|
||||
def _fetch_sync() -> tuple[np.ndarray, int]:
|
||||
if parsed.scheme in ("http", "https"):
|
||||
_check_ssrf(ref_audio_str)
|
||||
with urlopen(ref_audio_str, timeout=_REF_AUDIO_TIMEOUT_S) as resp:
|
||||
data = resp.read(_REF_AUDIO_MAX_BYTES + 1)
|
||||
if len(data) > _REF_AUDIO_MAX_BYTES:
|
||||
raise ValueError(f"ref_audio URL exceeds {_REF_AUDIO_MAX_BYTES} bytes")
|
||||
buf = io.BytesIO(data)
|
||||
elif ref_audio_str.startswith("data:"):
|
||||
b64 = ref_audio_str
|
||||
if "," in b64:
|
||||
b64 = b64.split(",", 1)[1]
|
||||
buf = io.BytesIO(base64.b64decode(b64))
|
||||
else:
|
||||
raise ValueError("ref_audio must be an http(s) URL or data: base64 URI")
|
||||
audio, sr = sf.read(buf, dtype="float32", always_2d=False)
|
||||
if isinstance(audio, np.ndarray) and audio.ndim > 1:
|
||||
audio = np.mean(audio, axis=-1)
|
||||
return np.asarray(audio, dtype=np.float32), int(sr)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
wav_np, sr = await loop.run_in_executor(None, _fetch_sync)
|
||||
return wav_np.tolist(), sr
|
||||
Delegates to upstream vLLM's MediaConnector which handles http(s)
|
||||
URLs, ``data:`` base64 URIs, and ``file:`` local paths (the latter
|
||||
gated by ``--allowed-local-media-path``).
|
||||
"""
|
||||
model_config = self.model_config
|
||||
connector = MediaConnector(
|
||||
allowed_local_media_path=model_config.allowed_local_media_path,
|
||||
allowed_media_domains=model_config.allowed_media_domains,
|
||||
)
|
||||
wav_np, sr = await connector.fetch_audio_async(ref_audio_str)
|
||||
wav_np = np.asarray(wav_np, dtype=np.float32)
|
||||
if wav_np.ndim > 1:
|
||||
wav_np = np.mean(wav_np, axis=-1)
|
||||
return wav_np.tolist(), int(sr)
|
||||
|
||||
async def _generate_pcm_chunks(self, generator, request_id: str):
|
||||
"""Generate PCM audio chunks for streaming response.
|
||||
@@ -447,6 +676,17 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
# Speaker (voice)
|
||||
if request.voice is not None:
|
||||
params["speaker"] = [request.voice]
|
||||
|
||||
# If voice is an uploaded speaker and no ref_audio provided, auto-set it
|
||||
if request.voice.lower() in self.uploaded_speakers and request.ref_audio is None:
|
||||
audio_data = self._get_uploaded_audio_data(request.voice)
|
||||
if audio_data:
|
||||
params["ref_audio"] = [audio_data]
|
||||
params["x_vector_only_mode"] = [True]
|
||||
logger.info(f"Auto-set ref_audio for uploaded voice: {request.voice}")
|
||||
else:
|
||||
raise ValueError(f"Audio file for uploaded voice '{request.voice}' is missing or corrupted")
|
||||
|
||||
elif params["task_type"][0] == "CustomVoice":
|
||||
params["speaker"] = ["Vivian"] # Default for CustomVoice
|
||||
|
||||
|
||||
@@ -141,6 +141,7 @@ class OmniOpenAIServingVideo:
|
||||
)
|
||||
|
||||
result = await self._run_generation(prompt, gen_params, request_id, raw_request)
|
||||
_t_encode_start = time.perf_counter()
|
||||
videos = self._extract_video_outputs(result)
|
||||
audios = self._extract_audio_outputs(result, expected_count=len(videos))
|
||||
output_fps = fps or 24
|
||||
@@ -161,6 +162,8 @@ class OmniOpenAIServingVideo:
|
||||
)
|
||||
for idx, video in enumerate(videos)
|
||||
]
|
||||
_t_encode_ms = (time.perf_counter() - _t_encode_start) * 1000
|
||||
logger.info("Video response encoding (MP4+base64): %.2f ms", _t_encode_ms)
|
||||
return VideoGenerationResponse(created=int(time.time()), data=video_data)
|
||||
|
||||
def _resolve_model_name(self, raw_request: Request | None) -> str | None:
|
||||
|
||||
@@ -36,6 +36,7 @@ class OmniStageTaskType(enum.Enum):
|
||||
SHUTDOWN = "shutdown"
|
||||
PROFILER_START = "profiler_start"
|
||||
PROFILER_STOP = "profiler_stop"
|
||||
COLLECTIVE_RPC = "collective_rpc"
|
||||
|
||||
|
||||
SHUTDOWN_TASK = {"type": OmniStageTaskType.SHUTDOWN}
|
||||
|
||||
Reference in new issue
Block a user