[Model] Aura support - Non async chunk path (#4257)
Signed-off-by: Rein Yang <ruiruyang2@gmail.com> Signed-off-by: R2-Y <ruiruyang2@gmail.com>
This commit is contained in:
1 parent
1292c47804
commit
afbcc51672
30 files changed
+2958
-26
No files matched your search
@@ -44,6 +44,10 @@ _OMNI_PIPELINES: dict[str, tuple[str, str]] = {
|
||||
"vllm_omni.model_executor.models.qwen3_omni.pipeline",
|
||||
"QWEN3_OMNI_PIPELINE",
|
||||
),
|
||||
"aura_omni": (
|
||||
"vllm_omni.model_executor.models.aura_omni.pipeline",
|
||||
"AURA_OMNI_PIPELINE",
|
||||
),
|
||||
"qwen3_tts": (
|
||||
"vllm_omni.model_executor.models.qwen3_tts.pipeline",
|
||||
"QWEN3_TTS_PIPELINE",
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# AURA Omni deploy profile: Qwen3-ASR -> AURA/Qwen3-VL -> Qwen3-TTS Talker -> Code2Wav.
|
||||
#
|
||||
# Pass `--deploy-config vllm_omni/deploy/aura_omni.yaml` and point the parent
|
||||
# `--model` at any local placeholder repo if needed; each stage overrides its
|
||||
# own model below.
|
||||
pipeline: aura_omni
|
||||
# AURA has a semantic ASR -> AURA -> TTS dependency. Do not prewarm downstream
|
||||
# stages before AURA text is converted into Qwen3-TTS metadata by aura2tts.
|
||||
async_chunk: false
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
codec_chunk_frames: 25
|
||||
codec_left_context_frames: 72
|
||||
initial_codec_chunk_frames: 1
|
||||
decode_cudagraph_capture_sizes: [25, 73, 97, 169, 325]
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 8
|
||||
gpu_memory_utilization: 0.1
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: true
|
||||
async_scheduling: true
|
||||
max_model_len: 8192
|
||||
max_num_batched_tokens: 4096
|
||||
devices: "0"
|
||||
model: Qwen/Qwen3-ASR-1.7B
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 256
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 4
|
||||
gpu_memory_utilization: 0.4
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: true
|
||||
async_scheduling: true
|
||||
max_model_len: 262144
|
||||
max_num_batched_tokens: 15360
|
||||
devices: "0"
|
||||
model: aurateam/AURA
|
||||
default_sampling_params:
|
||||
temperature: 0.5
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 256
|
||||
repetition_penalty: 1.0
|
||||
|
||||
- stage_id: 2
|
||||
max_num_seqs: 8
|
||||
gpu_memory_utilization: 0.2
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 512
|
||||
max_model_len: 4096
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_3: connector_of_shared_memory
|
||||
# model: Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice
|
||||
model: Qwen/Qwen3-TTS-12Hz-1.7B-Base
|
||||
default_sampling_params:
|
||||
temperature: 0.9
|
||||
top_k: 50
|
||||
max_tokens: 4096
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
subtalker_sampling_params:
|
||||
do_sample: true
|
||||
temperature: 0.9
|
||||
top_k: 50
|
||||
top_p: 1.0
|
||||
|
||||
- stage_id: 3
|
||||
max_num_seqs: 8
|
||||
gpu_memory_utilization: 0.2
|
||||
enforce_eager: false
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 65536
|
||||
max_model_len: 65536
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_2: connector_of_shared_memory
|
||||
# model: Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice
|
||||
model: Qwen/Qwen3-TTS-12Hz-1.7B-Base
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
stages:
|
||||
- stage_id: 2
|
||||
enforce_eager: true
|
||||
@@ -20,6 +20,7 @@ import janus
|
||||
import torch
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
@@ -52,6 +53,68 @@ from vllm_omni.outputs import OmniRequestOutput
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _build_terminal_empty_output(
|
||||
request_id: str,
|
||||
*,
|
||||
final_output_type: str | None,
|
||||
audio_sample_rate: int = 24000,
|
||||
) -> RequestOutput:
|
||||
"""Build a terminal empty output when no downstream stage input exists."""
|
||||
completion = CompletionOutput(
|
||||
index=0,
|
||||
text="",
|
||||
token_ids=[],
|
||||
cumulative_logprob=None,
|
||||
logprobs=None,
|
||||
finish_reason="stop",
|
||||
stop_reason=None,
|
||||
)
|
||||
if final_output_type == "audio":
|
||||
completion.multimodal_output = {
|
||||
"audio": torch.zeros((0,), dtype=torch.float32),
|
||||
"sr": audio_sample_rate,
|
||||
}
|
||||
return RequestOutput(
|
||||
request_id=request_id,
|
||||
prompt=None,
|
||||
prompt_token_ids=[],
|
||||
prompt_logprobs=None,
|
||||
outputs=[completion],
|
||||
finished=True,
|
||||
)
|
||||
|
||||
|
||||
def _coerce_int_scalar(value: Any) -> int:
|
||||
if value is None:
|
||||
return 0
|
||||
if isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
coerced = _coerce_int_scalar(item)
|
||||
if coerced > 0:
|
||||
return coerced
|
||||
return 0
|
||||
if hasattr(value, "item"):
|
||||
value = value.item()
|
||||
try:
|
||||
coerced = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return coerced if coerced > 0 else 0
|
||||
|
||||
|
||||
def _infer_stage_audio_sample_rate(stage_pool: StagePool, default: int = 24000) -> int:
|
||||
"""Infer the final audio stage sample rate from stage metadata when possible."""
|
||||
sample_rate_attrs = ("audio_sample_rate", "sample_rate", "sampling_rate", "output_sample_rate", "sr")
|
||||
stage_client = getattr(stage_pool, "stage_client", None)
|
||||
stage_config = getattr(stage_pool, "_stage_vllm_config", None)
|
||||
for source in (stage_client, stage_config):
|
||||
for attr in sample_rate_attrs:
|
||||
sample_rate = _coerce_int_scalar(getattr(source, attr, None))
|
||||
if sample_rate > 0:
|
||||
return sample_rate
|
||||
return default
|
||||
|
||||
|
||||
def build_engine_core_request_from_tokens(
|
||||
request_id: str,
|
||||
prompt: dict[str, Any],
|
||||
@@ -180,6 +243,7 @@ class Orchestrator:
|
||||
self._init_metrics_state(stage_pools, running_counter, transfer_emitter, log_stats=log_stats)
|
||||
|
||||
self._cfg_tracker = CfgCompanionTracker()
|
||||
self._stage_input_processors: dict[int, Any] = {}
|
||||
|
||||
self._shutdown_event = asyncio.Event()
|
||||
self._stages_shutdown = False
|
||||
@@ -884,6 +948,77 @@ class Orchestrator:
|
||||
def _next_stage_already_submitted(self, stage_id: int, req_state: OrchestratorRequestState) -> bool:
|
||||
return (stage_id + 1) in req_state.stage_submit_ts
|
||||
|
||||
def _get_stage_input_processor(self, stage_id: int) -> Any:
|
||||
processor = self._stage_input_processors.get(stage_id)
|
||||
if processor is None:
|
||||
from vllm_omni.engine.stage_init_utils import build_stage0_input_processor
|
||||
|
||||
processor = build_stage0_input_processor(self.stage_pools[stage_id].stage_vllm_config)
|
||||
self._stage_input_processors[stage_id] = processor
|
||||
return processor
|
||||
|
||||
def _upgrade_processed_stage_request(self, request: Any, raw_prompt: Any) -> Any:
|
||||
prompt_embeds = getattr(request, "prompt_embeds", None)
|
||||
additional_information = None
|
||||
|
||||
if isinstance(raw_prompt, dict):
|
||||
if prompt_embeds is None:
|
||||
raw_prompt_embeds = raw_prompt.get("prompt_embeds")
|
||||
if isinstance(raw_prompt_embeds, torch.Tensor):
|
||||
prompt_embeds = raw_prompt_embeds
|
||||
additional_information = serialize_additional_information(
|
||||
raw_prompt.get("additional_information"),
|
||||
log_prefix="Orchestrator stage input",
|
||||
)
|
||||
|
||||
if prompt_embeds is None and additional_information is None:
|
||||
return request
|
||||
|
||||
return OmniEngineCoreRequest.from_request(
|
||||
request,
|
||||
prompt_embeds=prompt_embeds,
|
||||
additional_information=additional_information,
|
||||
)
|
||||
|
||||
def _next_stage_input_is_tokens(self, next_input: Any) -> bool:
|
||||
return isinstance(next_input, dict) and "prompt_token_ids" in next_input
|
||||
|
||||
def _build_next_stage_request(
|
||||
self,
|
||||
req_id: str,
|
||||
next_stage_id: int,
|
||||
next_input: Any,
|
||||
params: SamplingParams | PoolingParams,
|
||||
*,
|
||||
mm_features: list | None = None,
|
||||
resumable: bool = False,
|
||||
) -> Any:
|
||||
next_pool = self.stage_pools[next_stage_id]
|
||||
if self._next_stage_input_is_tokens(next_input):
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
prompt=next_input,
|
||||
params=params,
|
||||
model_config=next_pool.stage_vllm_config.model_config,
|
||||
mm_features=mm_features,
|
||||
resumable=resumable,
|
||||
)
|
||||
request.external_req_id = request.request_id
|
||||
return request
|
||||
|
||||
processor = self._get_stage_input_processor(next_stage_id)
|
||||
request = processor.process_inputs(
|
||||
request_id=req_id,
|
||||
prompt=next_input,
|
||||
params=params,
|
||||
supported_tasks=("generate",),
|
||||
arrival_time=_time.time(),
|
||||
resumable=resumable,
|
||||
)
|
||||
request = self._upgrade_processed_stage_request(request, next_input)
|
||||
request.external_req_id = req_id
|
||||
return request
|
||||
|
||||
async def _handle_cfg_companion_ready(self, req_id: str) -> None:
|
||||
"""Mark a CFG companion as done; if all companions are done, flush deferred parent."""
|
||||
parent_id = self._cfg_tracker.on_companion_completed(req_id)
|
||||
@@ -1207,22 +1342,64 @@ class Orchestrator:
|
||||
)
|
||||
raise
|
||||
|
||||
if not next_inputs:
|
||||
if not getattr(output, "finished", False):
|
||||
logger.debug(
|
||||
"[Orchestrator] req=%s stage-%s produced no inputs for stage-%s; waiting for more outputs",
|
||||
req_id,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
)
|
||||
return
|
||||
|
||||
final_stage_id = req_state.final_stage_id
|
||||
final_pool = self.stage_pools[final_stage_id]
|
||||
final_output_type = getattr(final_pool.stage_client, "final_output_type", None)
|
||||
terminal_output = _build_terminal_empty_output(
|
||||
req_id,
|
||||
final_output_type=final_output_type,
|
||||
audio_sample_rate=_infer_stage_audio_sample_rate(final_pool),
|
||||
)
|
||||
submit_ts = _time.time()
|
||||
req_state.stage_submit_ts[final_stage_id] = submit_ts
|
||||
logger.info(
|
||||
"[Orchestrator] req=%s stage-%s produced no terminal inputs for stage-%s; "
|
||||
"returning empty %s output from final stage-%s",
|
||||
req_id,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
final_output_type or "text",
|
||||
final_stage_id,
|
||||
)
|
||||
await self.output_async_queue.put(
|
||||
OutputMessage(
|
||||
request_id=req_id,
|
||||
stage_id=final_stage_id,
|
||||
replica_id=0,
|
||||
engine_outputs=terminal_output,
|
||||
metrics=None,
|
||||
finished=True,
|
||||
stage_submit_ts=submit_ts,
|
||||
)
|
||||
)
|
||||
await self._cleanup_request_ids([req_id, *self._cfg_tracker.cleanup_parent(req_id)])
|
||||
return
|
||||
|
||||
# Build and submit requests for each input
|
||||
for next_input in next_inputs:
|
||||
# Only AR thinker stages consume encoder mm_features; downstream
|
||||
# (talker/code2wav/…) must not see them (avoids encoder-cache misses).
|
||||
model_stage = getattr(getattr(next_pool.stage_vllm_config, "model_config", None), "model_stage", None)
|
||||
mm_features = req_state.mm_features if model_stage == "thinker" else None
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
prompt=next_input,
|
||||
request = self._build_next_stage_request(
|
||||
req_id,
|
||||
next_logical,
|
||||
next_input,
|
||||
params=params,
|
||||
model_config=next_pool.stage_vllm_config.model_config,
|
||||
mm_features=mm_features,
|
||||
resumable=next_stage_resumable,
|
||||
)
|
||||
|
||||
request.external_req_id = request.request_id
|
||||
if already_submitted:
|
||||
await next_pool.submit_update(req_id, req_state, request)
|
||||
else:
|
||||
|
||||
@@ -698,6 +698,7 @@ def build_engine_args_dict(
|
||||
stage_id = stage_config.stage_id
|
||||
|
||||
engine_args_dict = _to_dict(engine_args)
|
||||
model = engine_args_dict.pop("model", None) or model
|
||||
stage_defines_tokenizer = (
|
||||
engine_args_dict.get("tokenizer") is not None or engine_args_dict.get("tokenizer_subdir") is not None
|
||||
)
|
||||
|
||||
@@ -74,6 +74,7 @@ from vllm.entrypoints.serve.utils.api_utils import should_include_usage
|
||||
from vllm.entrypoints.serve.utils.tool_calls_utils import maybe_filter_parallel_tool_calls
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.media.connector import MediaConnector
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.renderers import BaseRenderer, merge_kwargs
|
||||
@@ -104,6 +105,7 @@ from vllm_omni.entrypoints.openai.protocol.images import (
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.stage_params import (
|
||||
build_stage_sampling_params_list,
|
||||
clone_sampling_params,
|
||||
get_default_sampling_params_list,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.utils import (
|
||||
@@ -122,6 +124,10 @@ from vllm_omni.utils.audio import audio_chunk_pcm_bytes, audio_chunk_sample_rate
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
async def _identity_async(value: Any) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
"""OpenAI-compatible chat serving for both LLM and Diffusion models.
|
||||
|
||||
@@ -654,6 +660,13 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
default_mm_processor_kwargs=getattr(request, "mm_processor_kwargs", None),
|
||||
)
|
||||
|
||||
deferred_multi_modal_data: dict[str, Any] | None = None
|
||||
if self._needs_multistage_multimodal_split():
|
||||
messages, deferred_multi_modal_data = await self._prepare_multistage_multimodal_inputs(
|
||||
messages,
|
||||
request,
|
||||
)
|
||||
|
||||
(conversation,), (engine_prompt,) = await renderer.render_chat_async(
|
||||
[messages],
|
||||
chat_params,
|
||||
@@ -698,18 +711,25 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
if hasattr(request, "cache_salt") and request.cache_salt is not None:
|
||||
engine_prompt["cache_salt"] = request.cache_salt
|
||||
|
||||
additional_information = getattr(request, "additional_information", None)
|
||||
if isinstance(additional_information, dict):
|
||||
prompt_additional_information = self._ensure_prompt_additional_information(engine_prompt)
|
||||
prompt_additional_information.update(additional_information)
|
||||
|
||||
if deferred_multi_modal_data:
|
||||
prompt_additional_information = self._ensure_prompt_additional_information(engine_prompt)
|
||||
prompt_additional_information["deferred_multi_modal_data"] = deferred_multi_modal_data
|
||||
|
||||
speaker = getattr(request, "voice", None) or getattr(request, "speaker", None)
|
||||
normalized = validate_requested_speaker(speaker, self._get_supported_speakers())
|
||||
if normalized is not None:
|
||||
if "additional_information" not in engine_prompt or engine_prompt["additional_information"] is None:
|
||||
engine_prompt["additional_information"] = {}
|
||||
engine_prompt["additional_information"]["speaker"] = [normalized]
|
||||
prompt_additional_information = self._ensure_prompt_additional_information(engine_prompt)
|
||||
prompt_additional_information["speaker"] = [normalized]
|
||||
|
||||
language = getattr(request, "language", None)
|
||||
if language is not None and isinstance(language, str) and language.strip():
|
||||
if "additional_information" not in engine_prompt or engine_prompt["additional_information"] is None:
|
||||
engine_prompt["additional_information"] = {}
|
||||
engine_prompt["additional_information"]["language"] = [language.strip()]
|
||||
prompt_additional_information = self._ensure_prompt_additional_information(engine_prompt)
|
||||
prompt_additional_information["language"] = [language.strip()]
|
||||
|
||||
# Style instruction — used by Ming-flash-omni instruct TTS path
|
||||
# (ming_task="instruct"). For the omni speech path the thinker2talker
|
||||
@@ -717,20 +737,263 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# which hardcodes instruction=None.
|
||||
instructions = getattr(request, "instructions", None)
|
||||
if instructions is not None and isinstance(instructions, str) and instructions.strip():
|
||||
if "additional_information" not in engine_prompt or engine_prompt["additional_information"] is None:
|
||||
engine_prompt["additional_information"] = {}
|
||||
engine_prompt["additional_information"]["instruction"] = instructions.strip()
|
||||
prompt_additional_information = self._ensure_prompt_additional_information(engine_prompt)
|
||||
prompt_additional_information["instruction"] = instructions.strip()
|
||||
|
||||
return conversation, [engine_prompt]
|
||||
|
||||
@staticmethod
|
||||
def _ensure_prompt_additional_information(engine_prompt: dict[str, Any]) -> dict[str, Any]:
|
||||
additional_information = engine_prompt.get("additional_information")
|
||||
if not isinstance(additional_information, dict):
|
||||
additional_information = {}
|
||||
engine_prompt["additional_information"] = additional_information
|
||||
return additional_information
|
||||
|
||||
def _needs_multistage_multimodal_split(self) -> bool:
|
||||
return bool(self._deferred_multimodal_modalities())
|
||||
|
||||
def _deferred_multimodal_modalities(self) -> set[str]:
|
||||
stage_configs = list(getattr(self.engine_client, "stage_configs", []) or [])
|
||||
if len(stage_configs) < 2:
|
||||
return set()
|
||||
|
||||
first_stage_modalities = self._stage_input_modalities(stage_configs[0])
|
||||
if not first_stage_modalities:
|
||||
return set()
|
||||
|
||||
downstream_modalities: set[str] = set()
|
||||
for stage in stage_configs[1:]:
|
||||
downstream_modalities.update(self._stage_input_modalities(stage))
|
||||
return downstream_modalities - first_stage_modalities
|
||||
|
||||
@staticmethod
|
||||
def _stage_input_modalities(stage: Any) -> set[str]:
|
||||
engine_args = getattr(stage, "engine_args", None)
|
||||
explicit = (
|
||||
getattr(stage, "input_modalities", None)
|
||||
or getattr(stage, "modalities", None)
|
||||
or getattr(engine_args, "input_modalities", None)
|
||||
or getattr(engine_args, "modalities", None)
|
||||
)
|
||||
if explicit:
|
||||
return {str(modality) for modality in as_list(explicit)}
|
||||
|
||||
model_stage = str(getattr(engine_args, "model_stage", None) or getattr(stage, "model_stage", "")).lower()
|
||||
if model_stage in {"asr", "stt"} or model_stage.endswith("_asr"):
|
||||
return {"audio"}
|
||||
if any(name in model_stage for name in ("vision", "vl", "aura")):
|
||||
return {"image", "video"}
|
||||
if any(name in model_stage for name in ("tts", "talker", "code2wav")):
|
||||
return set()
|
||||
|
||||
if getattr(stage, "requires_multimodal_data", False):
|
||||
return {"audio", "image", "video"}
|
||||
return set()
|
||||
|
||||
async def _prepare_multistage_multimodal_inputs(
|
||||
self,
|
||||
messages: list[ChatCompletionMessageParam],
|
||||
request: ChatLikeRequest | ResponsesRequest,
|
||||
) -> tuple[list[ChatCompletionMessageParam], dict[str, Any] | None]:
|
||||
"""Hide modalities unsupported by stage 0 and stash them for downstream stages."""
|
||||
deferred_modalities = self._deferred_multimodal_modalities()
|
||||
deferred_parts: dict[str, list[Any]] = {modality: [] for modality in deferred_modalities}
|
||||
stripped_messages: list[ChatCompletionMessageParam] = []
|
||||
|
||||
for message in messages:
|
||||
content = message.get("content") if isinstance(message, dict) else None
|
||||
if not isinstance(content, list):
|
||||
stripped_messages.append(message)
|
||||
continue
|
||||
|
||||
stripped_content: list[Any] = []
|
||||
changed = False
|
||||
for part in content:
|
||||
modality, payload = self._deferred_multimodal_part(part, deferred_modalities)
|
||||
if modality is not None:
|
||||
if payload is not None:
|
||||
deferred_parts.setdefault(modality, []).append(payload)
|
||||
changed = True
|
||||
continue
|
||||
stripped_content.append(part)
|
||||
|
||||
if changed:
|
||||
stripped_message = dict(message)
|
||||
stripped_message["content"] = stripped_content
|
||||
stripped_messages.append(cast(ChatCompletionMessageParam, stripped_message))
|
||||
else:
|
||||
stripped_messages.append(message)
|
||||
|
||||
deferred_parts = {modality: parts for modality, parts in deferred_parts.items() if parts}
|
||||
if not deferred_parts:
|
||||
return messages, None
|
||||
|
||||
media_connector = MediaConnector(
|
||||
media_io_kwargs=getattr(request, "media_io_kwargs", None),
|
||||
allowed_local_media_path=getattr(self.model_config, "allowed_local_media_path", "") or "",
|
||||
allowed_media_domains=getattr(self.model_config, "allowed_media_domains", None),
|
||||
)
|
||||
multi_modal_data: dict[str, Any] = {}
|
||||
for modality, parts in deferred_parts.items():
|
||||
multi_modal_data[modality] = await self._materialize_deferred_multimodal_parts(
|
||||
media_connector,
|
||||
modality,
|
||||
parts,
|
||||
)
|
||||
return stripped_messages, multi_modal_data
|
||||
|
||||
@staticmethod
|
||||
def _deferred_multimodal_part(part: Any, deferred_modalities: set[str]) -> tuple[str | None, Any | None]:
|
||||
if not isinstance(part, dict):
|
||||
return None, None
|
||||
part_type = part.get("type")
|
||||
if part_type in {"video_url", "video"} and "video" in deferred_modalities:
|
||||
video = part.get("video_url", part.get("video"))
|
||||
if isinstance(video, dict):
|
||||
video = video.get("url")
|
||||
return "video", video
|
||||
if part_type in {"image_url", "image_pil", "image"} and "image" in deferred_modalities:
|
||||
image = part.get("image_pil", part.get("image_url", part.get("image")))
|
||||
if isinstance(image, dict):
|
||||
image = image.get("url")
|
||||
return "image", image
|
||||
if part_type in {"audio_url", "input_audio", "audio"} and "audio" in deferred_modalities:
|
||||
audio = part.get("audio_url", part.get("input_audio", part.get("audio")))
|
||||
if isinstance(audio, dict):
|
||||
audio = audio.get("url") or audio.get("data")
|
||||
return "audio", audio
|
||||
return None, None
|
||||
|
||||
@staticmethod
|
||||
async def _materialize_deferred_multimodal_parts(
|
||||
media_connector: MediaConnector,
|
||||
modality: str,
|
||||
parts: list[Any],
|
||||
) -> list[Any]:
|
||||
if modality == "video":
|
||||
return list(await asyncio.gather(*(media_connector.fetch_video_async(part) for part in parts)))
|
||||
if modality == "image":
|
||||
fetch_image = getattr(media_connector, "fetch_image_async", None)
|
||||
if fetch_image is None:
|
||||
return parts
|
||||
return list(
|
||||
await asyncio.gather(
|
||||
*(fetch_image(part) if isinstance(part, str) else _identity_async(part) for part in parts)
|
||||
)
|
||||
)
|
||||
if modality == "audio":
|
||||
fetch_audio = getattr(media_connector, "fetch_audio_async", None)
|
||||
if fetch_audio is None:
|
||||
return parts
|
||||
return list(
|
||||
await asyncio.gather(
|
||||
*(fetch_audio(part) if isinstance(part, str) else _identity_async(part) for part in parts)
|
||||
)
|
||||
)
|
||||
return parts
|
||||
|
||||
async def _inject_audio_from_video_urls(
|
||||
self,
|
||||
messages: list[ChatCompletionMessageParam],
|
||||
) -> list[ChatCompletionMessageParam]:
|
||||
"""Pre-extract audio from video URLs and inject as audio_url content items.
|
||||
|
||||
When use_audio_in_video=True, the qwen2_5_omni_thinker multimodal
|
||||
processor requires that the number of audio items equals the number of
|
||||
video items (it subtracts mm_counts["video"] from mm_counts["audio"]).
|
||||
The client only sends video_url items; this method adds the matching
|
||||
audio_url items on the server side before the renderer processes them.
|
||||
"""
|
||||
import io
|
||||
|
||||
from vllm_omni.entrypoints.chat_utils import extract_audio_from_video_async
|
||||
|
||||
new_messages: list[ChatCompletionMessageParam] = []
|
||||
for msg in messages:
|
||||
content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", None)
|
||||
if not isinstance(content, list):
|
||||
new_messages.append(msg)
|
||||
continue
|
||||
|
||||
video_urls = [
|
||||
part.get("video_url", {}).get("url")
|
||||
for part in content
|
||||
if isinstance(part, dict) and part.get("type") == "video_url" and part.get("video_url", {}).get("url")
|
||||
]
|
||||
|
||||
if not video_urls:
|
||||
new_messages.append(msg)
|
||||
continue
|
||||
|
||||
audios = await asyncio.gather(*(extract_audio_from_video_async(u) for u in video_urls))
|
||||
|
||||
audio_items: list[dict] = []
|
||||
for audio_array, sample_rate in audios:
|
||||
buf = io.BytesIO()
|
||||
if soundfile is not None:
|
||||
soundfile.write(buf, audio_array, samplerate=int(sample_rate), format="WAV")
|
||||
else:
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
|
||||
audio_np = np.asarray(audio_array, dtype=np.float32)
|
||||
sr = int(sample_rate)
|
||||
num_channels = 1
|
||||
bits_per_sample = 32
|
||||
num_frames = len(audio_np)
|
||||
data_size = num_frames * num_channels * (bits_per_sample // 8)
|
||||
# Write minimal RIFF/WAV header
|
||||
buf.write(b"RIFF")
|
||||
buf.write(struct.pack("<I", 36 + data_size))
|
||||
buf.write(b"WAVE")
|
||||
buf.write(b"fmt ")
|
||||
buf.write(
|
||||
struct.pack(
|
||||
"<IHHIIHH",
|
||||
16,
|
||||
3,
|
||||
num_channels,
|
||||
sr,
|
||||
sr * num_channels * (bits_per_sample // 8),
|
||||
num_channels * (bits_per_sample // 8),
|
||||
bits_per_sample,
|
||||
)
|
||||
)
|
||||
buf.write(b"data")
|
||||
buf.write(struct.pack("<I", data_size))
|
||||
buf.write(audio_np.tobytes())
|
||||
|
||||
audio_b64 = base64.b64encode(buf.getvalue()).decode()
|
||||
audio_items.append(
|
||||
{
|
||||
"type": "audio_url",
|
||||
"audio_url": {"url": f"data:audio/wav;base64,{audio_b64}"},
|
||||
}
|
||||
)
|
||||
|
||||
new_content = list(content) + audio_items
|
||||
if isinstance(msg, dict):
|
||||
new_msg = {**msg, "content": new_content}
|
||||
else:
|
||||
new_msg = msg.model_copy(update={"content": new_content})
|
||||
new_messages.append(new_msg)
|
||||
|
||||
return new_messages
|
||||
|
||||
def _to_sampling_params_list(self, sampling_params_list: list[dict]) -> list[Any]:
|
||||
"""Convert request dicts to stage-typed sampling params objects.
|
||||
|
||||
For diffusion stages, build ``OmniDiffusionSamplingParams`` so
|
||||
downstream ``StageDiffusionClient._sampling_params_to_dict`` (which
|
||||
requires a dataclass) works. For LLM stages build ``SamplingParams``.
|
||||
If callers provide params for fewer stages than the native pipeline has
|
||||
(for example AURA has three semantic models but four engine stages),
|
||||
append cloned deploy defaults for the omitted tail stages.
|
||||
"""
|
||||
stage_configs = list(getattr(self.engine_client, "stage_configs", []) or [])
|
||||
default_params_list = list(getattr(self.engine_client, "default_sampling_params_list", []) or [])
|
||||
final_sampling_params_list: list[Any] = []
|
||||
for idx, sampling_params in enumerate(sampling_params_list):
|
||||
stage_type = get_stage_type(stage_configs[idx]) if idx < len(stage_configs) else "llm"
|
||||
@@ -750,6 +1013,11 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
final_sampling_params_list.append(target_cls(**as_dict))
|
||||
else:
|
||||
raise ValueError(f"Invalid sampling params: {sampling_params}")
|
||||
for idx in range(len(final_sampling_params_list), len(stage_configs)):
|
||||
if idx < len(default_params_list):
|
||||
final_sampling_params_list.append(clone_sampling_params(default_params_list[idx]))
|
||||
else:
|
||||
final_sampling_params_list.append(SamplingParams())
|
||||
return final_sampling_params_list
|
||||
|
||||
def _get_comprehension_stage_index(self) -> int:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AURA Omni pipeline topology.
|
||||
|
||||
Semantic modules:
|
||||
1. Qwen3-ASR: microphone audio -> transcript text
|
||||
2. AURA/Qwen3-VL: transcript + video -> text or <|silent|>
|
||||
3. Qwen3-TTS: response text -> audio
|
||||
|
||||
The Qwen3-TTS module is represented as two native engine stages, Talker and
|
||||
Code2Wav, to reuse the existing vLLM-Omni implementation without wrapping or
|
||||
duplicating codec streaming behavior.
|
||||
"""
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
|
||||
_AURA_PROC = "vllm_omni.model_executor.stage_input_processors.aura_omni"
|
||||
_QWEN3_TTS_PROC = "vllm_omni.model_executor.stage_input_processors.qwen3_tts"
|
||||
|
||||
|
||||
AURA_OMNI_PIPELINE = PipelineConfig(
|
||||
model_type="aura_omni",
|
||||
model_arch="Qwen3ASRForConditionalGeneration",
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="asr",
|
||||
execution_type=StageExecutionType.LLM_AR,
|
||||
input_sources=(),
|
||||
owns_tokenizer=True,
|
||||
requires_multimodal_data=True,
|
||||
engine_output_type="text",
|
||||
model_arch="Qwen3ASRForConditionalGeneration",
|
||||
sampling_constraints={"detokenize": True},
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=1,
|
||||
model_stage="aura",
|
||||
execution_type=StageExecutionType.LLM_AR,
|
||||
input_sources=(0,),
|
||||
final_output=True,
|
||||
final_output_type="text",
|
||||
owns_tokenizer=True,
|
||||
requires_multimodal_data=True,
|
||||
engine_output_type="text",
|
||||
model_arch="AuraQwen3VLForConditionalGeneration",
|
||||
custom_process_input_func=f"{_AURA_PROC}.asr2aura",
|
||||
sampling_constraints={"detokenize": True},
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=2,
|
||||
model_stage="qwen3_tts",
|
||||
execution_type=StageExecutionType.LLM_AR,
|
||||
input_sources=(1,),
|
||||
owns_tokenizer=True,
|
||||
engine_output_type="latent",
|
||||
model_arch="Qwen3TTSTalkerForConditionalGeneration",
|
||||
custom_process_input_func=f"{_AURA_PROC}.aura2tts",
|
||||
custom_process_next_stage_input_func=f"{_QWEN3_TTS_PROC}.talker2code2wav_full_payload",
|
||||
async_chunk_process_next_stage_input_func=f"{_QWEN3_TTS_PROC}.talker2code2wav_async_chunk",
|
||||
sampling_constraints={
|
||||
"detokenize": False,
|
||||
"stop_token_ids": [2150],
|
||||
},
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=3,
|
||||
model_stage="code2wav",
|
||||
execution_type=StageExecutionType.LLM_GENERATION,
|
||||
input_sources=(2,),
|
||||
final_output=True,
|
||||
final_output_type="audio",
|
||||
engine_output_type="audio",
|
||||
model_arch="Qwen3TTSCode2Wav",
|
||||
sync_process_input_func=f"{_QWEN3_TTS_PROC}.talker2code2wav_token_only",
|
||||
sampling_constraints={"detokenize": True},
|
||||
extras={"tts_args": {"max_instructions_length": 500}},
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AURA-compatible Qwen3-VL wrapper.
|
||||
|
||||
AURA ships Qwen3-VL weights with a repository-local ``configuration_qwen3_vl``
|
||||
module in ``auto_map``. With ``trust_remote_code=True``, Transformers therefore
|
||||
returns a remote ``Qwen3VLConfig`` class. The model structure is still Qwen3-VL,
|
||||
but vLLM's stock multimodal processor checks for the upstream Transformers
|
||||
``Qwen3VLConfig`` type exactly. This wrapper keeps the stock model and processor
|
||||
logic, while accepting structurally-compatible remote Qwen3-VL configs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm.model_executor.models.qwen3_vl import (
|
||||
Qwen3VLConfig,
|
||||
Qwen3VLDummyInputsBuilder,
|
||||
Qwen3VLForConditionalGeneration,
|
||||
Qwen3VLMultiModalProcessor,
|
||||
Qwen3VLProcessingInfo,
|
||||
Qwen3VLProcessor,
|
||||
)
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
|
||||
class AuraQwen3VLProcessingInfo(Qwen3VLProcessingInfo):
|
||||
def get_hf_config(self) -> Any:
|
||||
try:
|
||||
return self.ctx.get_hf_config(Qwen3VLConfig)
|
||||
except TypeError:
|
||||
config = self.ctx.get_hf_config()
|
||||
if (
|
||||
getattr(config, "model_type", None) == "qwen3_vl"
|
||||
and hasattr(config, "vision_config")
|
||||
and hasattr(config, "text_config")
|
||||
):
|
||||
return config
|
||||
raise
|
||||
|
||||
def get_hf_processor(self, **kwargs: object) -> Any:
|
||||
# AURA's config advertises `processing_qwen3_vl.py` in auto_map, but
|
||||
# the checkpoint snapshot does not include that file. Force the
|
||||
# upstream processor class while still allowing AURA's remote config.
|
||||
return self.ctx.get_hf_processor(
|
||||
Qwen3VLProcessor,
|
||||
use_fast=kwargs.pop("use_fast", True),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
Qwen3VLMultiModalProcessor,
|
||||
info=AuraQwen3VLProcessingInfo,
|
||||
dummy_inputs=Qwen3VLDummyInputsBuilder,
|
||||
)
|
||||
class AuraQwen3VLForConditionalGeneration(Qwen3VLForConditionalGeneration):
|
||||
pass
|
||||
@@ -30,7 +30,7 @@ from vllm_omni.utils.speaker_cache import (
|
||||
)
|
||||
|
||||
from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSSpeakerEncoderConfig, Qwen3TTSTalkerConfig
|
||||
from .prompt_embeds_builder import Qwen3TTSPromptEmbedsBuilder
|
||||
from .prompt_embeds_builder import PRECOMPUTED_TEXT_IDS_KEY, Qwen3TTSPromptEmbedsBuilder
|
||||
from .qwen3_tts_code_predictor_vllm import Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM
|
||||
from .tokenizer_12hz.configuration_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Config
|
||||
from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Encoder
|
||||
@@ -40,6 +40,19 @@ logger = init_logger(__name__)
|
||||
_TRAILING_TEXT_COMPACT_MIN_FRAMES = 64
|
||||
|
||||
|
||||
def _has_tts_text_conditioning(info_dict: dict[str, Any], hidden_states: Any | None = None) -> bool:
|
||||
text_list = info_dict.get("text")
|
||||
if isinstance(text_list, list) and bool(text_list) and bool(text_list[0]):
|
||||
return True
|
||||
if PRECOMPUTED_TEXT_IDS_KEY in info_dict:
|
||||
return True
|
||||
if isinstance(hidden_states, dict):
|
||||
tail = hidden_states.get("trailing_text")
|
||||
if isinstance(tail, torch.Tensor):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Components ported from the HuggingFace Qwen3-TTS reference implementation.
|
||||
# Only the classes actually needed by the vLLM AR Talker are kept here.
|
||||
@@ -625,9 +638,8 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
except Exception:
|
||||
is_prefill = span_len > 1
|
||||
|
||||
text_list = info_dict.get("text")
|
||||
if not isinstance(text_list, list) or not text_list or not text_list[0]:
|
||||
raise ValueError("Missing additional_information.text for Qwen3-TTS AR talker.")
|
||||
if not _has_tts_text_conditioning(info_dict, hs):
|
||||
raise ValueError("Missing Qwen3-TTS text conditioning: provide `text` or precomputed text token ids.")
|
||||
|
||||
task_type = (info_dict.get("task_type") or ["CustomVoice"])[0]
|
||||
codec_streaming_val = meta.get("codec_streaming")
|
||||
@@ -650,7 +662,6 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
if is_prefill:
|
||||
# Prefill (prompt embeddings)
|
||||
prompt_embeds_cpu = embed.get("prefill")
|
||||
|
||||
# First prefill round: prompt_embeds_cpu is not yet populated.
|
||||
# Subsequent prefill rounds (multi-chunk): prompt_embeds_cpu is a Tensor stored by the first round.
|
||||
is_first_prefill = not isinstance(prompt_embeds_cpu, torch.Tensor) or prompt_embeds_cpu.ndim != 2
|
||||
@@ -808,9 +819,8 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
hs = payload.get("hidden_states", {})
|
||||
meta = payload.get("meta", {})
|
||||
|
||||
text_list = info_dict.get("text")
|
||||
if not isinstance(text_list, list) or not text_list or not text_list[0]:
|
||||
raise ValueError("Missing additional_information.text for Qwen3-TTS AR talker.")
|
||||
if not _has_tts_text_conditioning(info_dict, hs):
|
||||
raise ValueError("Missing Qwen3-TTS text conditioning: provide `text` or precomputed text token ids.")
|
||||
|
||||
task_type = (info_dict.get("task_type") or ["CustomVoice"])[0]
|
||||
codec_streaming_val = meta.get("codec_streaming")
|
||||
|
||||
@@ -343,6 +343,11 @@ _OMNI_MODELS = {
|
||||
"minicpmo_4_5_omni_tts",
|
||||
"MiniCPMO45OmniTTSForConditionalGeneration",
|
||||
),
|
||||
"AuraQwen3VLForConditionalGeneration": (
|
||||
"aura_omni",
|
||||
"qwen3_vl",
|
||||
"AuraQwen3VLForConditionalGeneration",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Stage processors for the AURA Omni pipeline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
from vllm_omni.model_executor.models.qwen3_tts.prompt_embeds_builder import (
|
||||
PRECOMPUTED_TEXT_IDS_KEY,
|
||||
)
|
||||
|
||||
DEFAULT_AURA_SYSTEM_PROMPT = (
|
||||
"You are receiving a live video stream where the final frame is the present moment. "
|
||||
"Respond only when a response is needed based on the user's message or the visual context. "
|
||||
"Otherwise, output '<|silent|>' to signify silence. Respond in Chinese."
|
||||
)
|
||||
|
||||
SILENT_TEXT = "<|silent|>"
|
||||
QWEN_IM_START_ID = 151644
|
||||
QWEN_IM_END_ID = 151645
|
||||
QWEN_ASSISTANT_ID = 77091
|
||||
QWEN_NEWLINE_ID = 198
|
||||
QWEN_ASSISTANT_PREFIX_IDS = [QWEN_IM_START_ID, QWEN_ASSISTANT_ID, QWEN_NEWLINE_ID]
|
||||
QWEN_ASSISTANT_SUFFIX_IDS = [
|
||||
QWEN_IM_END_ID,
|
||||
QWEN_NEWLINE_ID,
|
||||
QWEN_IM_START_ID,
|
||||
QWEN_ASSISTANT_ID,
|
||||
QWEN_NEWLINE_ID,
|
||||
]
|
||||
DEFAULT_QWEN3_TTS_REF_AUDIO = "vllm-omni/tests/assets/qwen3_tts/clone_2.wav"
|
||||
DEFAULT_QWEN3_TTS_REF_TEXT = (
|
||||
"Okay. Yeah. I resent you. I love you. I respect you. But you know what? You blew it! And thanks to you."
|
||||
)
|
||||
|
||||
|
||||
def default_qwen3_tts_ref_audio_path() -> str:
|
||||
"""Return absolute path to the bundled ``clone_2.wav`` reference asset."""
|
||||
bundled = Path(__file__).resolve().parents[3] / "tests" / "assets" / "qwen3_tts" / "clone_2.wav"
|
||||
if bundled.is_file():
|
||||
return str(bundled)
|
||||
return DEFAULT_QWEN3_TTS_REF_AUDIO
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[Any]:
|
||||
if value is None:
|
||||
return []
|
||||
return value if isinstance(value, list) else [value]
|
||||
|
||||
|
||||
def _as_prompt_dict(prompt_item: Any) -> dict[str, Any]:
|
||||
return prompt_item if isinstance(prompt_item, dict) else {}
|
||||
|
||||
|
||||
def _first_value(value: Any, default: Any = None) -> Any:
|
||||
if isinstance(value, list):
|
||||
return value[0] if value else default
|
||||
return default if value is None else value
|
||||
|
||||
|
||||
def _first_bool(value: Any, default: bool = False) -> bool:
|
||||
value = _first_value(value, default)
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _normalize_qwen3_tts_speaker(speaker: Any) -> Any:
|
||||
if not isinstance(speaker, str):
|
||||
return speaker
|
||||
speaker = speaker.strip()
|
||||
if not speaker:
|
||||
return speaker
|
||||
if "_" in speaker:
|
||||
return speaker
|
||||
return speaker[0].upper() + speaker[1:].lower()
|
||||
|
||||
|
||||
def _extract_output(source_output: Any) -> Any:
|
||||
outputs = getattr(source_output, "outputs", None)
|
||||
if isinstance(outputs, list) and outputs:
|
||||
return outputs[0]
|
||||
return source_output
|
||||
|
||||
|
||||
def _extract_text(source_output: Any) -> str:
|
||||
output = _extract_output(source_output)
|
||||
cumulative_text = getattr(output, "cumulative_text", None)
|
||||
if isinstance(cumulative_text, str) and cumulative_text:
|
||||
return cumulative_text
|
||||
text = getattr(output, "text", None)
|
||||
if isinstance(text, str):
|
||||
return text
|
||||
mm = getattr(output, "multimodal_output", None)
|
||||
if isinstance(mm, dict):
|
||||
for key in ("text", "transcript", "asr_text"):
|
||||
value = mm.get(key)
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
if isinstance(value, list) and value and isinstance(value[0], str):
|
||||
return value[0]
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_token_ids(source_output: Any) -> list[int]:
|
||||
output = _extract_output(source_output)
|
||||
token_ids = getattr(output, "cumulative_token_ids", None)
|
||||
if isinstance(token_ids, list):
|
||||
return [int(token_id) for token_id in token_ids if isinstance(token_id, int)]
|
||||
return []
|
||||
|
||||
|
||||
def _trim_aura_response_token_ids(token_ids: list[int]) -> list[int]:
|
||||
ids = list(token_ids)
|
||||
if ids[: len(QWEN_ASSISTANT_PREFIX_IDS)] == QWEN_ASSISTANT_PREFIX_IDS:
|
||||
ids = ids[len(QWEN_ASSISTANT_PREFIX_IDS) :]
|
||||
if QWEN_IM_END_ID in ids:
|
||||
ids = ids[: ids.index(QWEN_IM_END_ID)]
|
||||
while ids and ids[-1] in {QWEN_IM_START_ID, QWEN_IM_END_ID, QWEN_NEWLINE_ID}:
|
||||
ids.pop()
|
||||
return ids
|
||||
|
||||
|
||||
def _qwen3_tts_assistant_token_ids_from_aura(source_output: Any) -> list[int]:
|
||||
content_ids = _trim_aura_response_token_ids(_extract_token_ids(source_output))
|
||||
if not content_ids:
|
||||
return []
|
||||
return QWEN_ASSISTANT_PREFIX_IDS + content_ids + QWEN_ASSISTANT_SUFFIX_IDS
|
||||
|
||||
|
||||
def _source_prompt_by_request_id(source_outputs: list[Any], prompt: Any) -> dict[str, dict[str, Any]]:
|
||||
prompts = _as_list(prompt)
|
||||
return {
|
||||
str(getattr(source_output, "request_id", idx)): _as_prompt_dict(prompt_item)
|
||||
for idx, (source_output, prompt_item) in enumerate(zip(source_outputs, prompts))
|
||||
}
|
||||
|
||||
|
||||
def _vision_placeholder(multi_modal_data: dict[str, Any]) -> str:
|
||||
if "video" in multi_modal_data:
|
||||
return "<|vision_start|><|video_pad|><|vision_end|>"
|
||||
if "image" in multi_modal_data:
|
||||
return "<|vision_start|><|image_pad|><|vision_end|>"
|
||||
return ""
|
||||
|
||||
|
||||
def _vision_multimodal_data(multi_modal_data: dict[str, Any]) -> dict[str, Any]:
|
||||
return {key: value for key, value in multi_modal_data.items() if key in {"image", "video"}}
|
||||
|
||||
|
||||
def _aura_prompt(system_prompt: str, transcript: str, multi_modal_data: dict[str, Any]) -> str:
|
||||
vision = _vision_placeholder(multi_modal_data)
|
||||
query = transcript.strip()
|
||||
user_body = f"{vision}{query}" if query else vision
|
||||
return (
|
||||
f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
|
||||
f"<|im_start|>user\n{user_body}<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
)
|
||||
|
||||
|
||||
def asr2aura(
|
||||
source_outputs: list[Any],
|
||||
prompt: Any = None,
|
||||
requires_multimodal_data: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Build AURA Qwen3-VL prompts from ASR transcripts and original video payloads."""
|
||||
prompt_by_request_id = _source_prompt_by_request_id(source_outputs, prompt)
|
||||
next_inputs: list[dict[str, Any]] = []
|
||||
for idx, source_output in enumerate(source_outputs):
|
||||
src_prompt = prompt_by_request_id.get(str(getattr(source_output, "request_id", idx)), {})
|
||||
additional_info = src_prompt.get("additional_information") or {}
|
||||
system_prompt = _first_value(additional_info.get("aura_system_prompt"), DEFAULT_AURA_SYSTEM_PROMPT)
|
||||
transcript = _extract_text(source_output)
|
||||
multi_modal_data = {}
|
||||
source_multi_modal_data = src_prompt.get("multi_modal_data") or {}
|
||||
if isinstance(source_multi_modal_data, dict):
|
||||
multi_modal_data.update(source_multi_modal_data)
|
||||
deferred_multi_modal_data = additional_info.get("deferred_multi_modal_data") or {}
|
||||
if isinstance(deferred_multi_modal_data, dict):
|
||||
multi_modal_data.update(deferred_multi_modal_data)
|
||||
multi_modal_data = _vision_multimodal_data(multi_modal_data)
|
||||
|
||||
next_input: dict[str, Any] = {
|
||||
"prompt": _aura_prompt(str(system_prompt), transcript, multi_modal_data),
|
||||
}
|
||||
if requires_multimodal_data:
|
||||
next_input["multi_modal_data"] = multi_modal_data
|
||||
if src_prompt.get("mm_processor_kwargs") is not None:
|
||||
next_input["mm_processor_kwargs"] = src_prompt.get("mm_processor_kwargs")
|
||||
next_inputs.append(next_input)
|
||||
return next_inputs
|
||||
|
||||
|
||||
def _estimate_ref_code_len_from_ref_audio(ref_audio: Any) -> int | None:
|
||||
"""Estimate Qwen3-TTS ref_code length from a ref-audio payload.
|
||||
|
||||
For Qwen3-TTS 12Hz models, code length is approximately:
|
||||
ceil(duration_seconds * 12.5)
|
||||
i.e. one codec frame per 1920 samples at 24kHz.
|
||||
"""
|
||||
|
||||
codec_frame_rate = 24000.0 / 1920.0
|
||||
|
||||
# Unwrap common list wrappers.
|
||||
item = ref_audio
|
||||
while isinstance(item, list) and item:
|
||||
item = item[0]
|
||||
|
||||
# Accept tuple/list like (wav, sr).
|
||||
if isinstance(item, (tuple, list)) and len(item) == 2 and isinstance(item[1], (int, float)):
|
||||
wav, sr = item
|
||||
sr_i = int(sr)
|
||||
if sr_i <= 0:
|
||||
return None
|
||||
if hasattr(wav, "__len__"):
|
||||
n_samples = len(wav)
|
||||
elif hasattr(wav, "shape"):
|
||||
shape = getattr(wav, "shape", None)
|
||||
if not shape:
|
||||
return None
|
||||
n_samples = shape[-1] if len(shape) > 1 else shape[0]
|
||||
else:
|
||||
return None
|
||||
if n_samples <= 0:
|
||||
return None
|
||||
return max(1, int(math.ceil((float(n_samples) / float(sr_i)) * codec_frame_rate)))
|
||||
|
||||
# Accept file path (wav only).
|
||||
if isinstance(item, str) and item:
|
||||
audio_path = item
|
||||
if not os.path.isfile(audio_path) or not audio_path.lower().endswith(".wav"):
|
||||
return None
|
||||
try:
|
||||
info = sf.info(audio_path)
|
||||
n_frames = int(info.frames)
|
||||
sr = int(info.samplerate)
|
||||
if n_frames <= 0 or sr <= 0:
|
||||
return None
|
||||
return max(1, int(math.ceil((float(n_frames) / float(sr)) * codec_frame_rate)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _estimate_tts_prompt_len_from_token_ids(
|
||||
token_ids: list[int],
|
||||
*,
|
||||
task_type: str = "Base",
|
||||
language: str = "Chinese",
|
||||
instruct: str = "",
|
||||
x_vector_only_mode: bool = False,
|
||||
non_streaming_mode: bool | None = None,
|
||||
ref_code_len: int | None = None,
|
||||
) -> int:
|
||||
"""Estimate Talker prefill length from prompt structure.
|
||||
|
||||
This mirrors Qwen3-TTS prompt assembly at length level:
|
||||
prompt_len = instruct_len + role_len + codec_prefix_len + text/icl term
|
||||
"""
|
||||
|
||||
# Official defaults: Base -> streaming, others -> non-streaming.
|
||||
if non_streaming_mode is None:
|
||||
non_streaming_mode = task_type in ("CustomVoice", "VoiceDesign")
|
||||
|
||||
# We do not have tokenizer here; use char length as a monotonic proxy.
|
||||
instruct_len = len(instruct.strip()) if isinstance(instruct, str) else 0
|
||||
assistant_len = max(0, len(token_ids))
|
||||
|
||||
# role_len = 3; codec_prefix_len = (prefill_len + speaker_len + 2) - 1
|
||||
# prefill_len = 4 when language_id exists else 3. Use non-auto language as
|
||||
# the language-id-present proxy.
|
||||
has_language_id = isinstance(language, str) and language.strip().lower() != "auto"
|
||||
prefill_len = 4 if has_language_id else 3
|
||||
speaker_len = 1 if task_type in ("CustomVoice", "Base") else 0
|
||||
base_len = instruct_len + 3 + (prefill_len + speaker_len + 2 - 1)
|
||||
if task_type in ("CustomVoice", "VoiceDesign"):
|
||||
if non_streaming_mode:
|
||||
prompt_len = base_len + max(0, assistant_len - 6)
|
||||
else:
|
||||
prompt_len = base_len + 1
|
||||
return max(32, min(4096, int(prompt_len)))
|
||||
|
||||
if task_type == "Base":
|
||||
in_context_mode = not bool(x_vector_only_mode)
|
||||
if in_context_mode and ref_code_len is not None:
|
||||
codec_lens = 1 + int(ref_code_len)
|
||||
if non_streaming_mode:
|
||||
# Exact non-streaming ICL needs ref_ids token length; unavailable
|
||||
# in this processor. Keep a conservative upper estimate.
|
||||
prompt_len = base_len + codec_lens + max(0, assistant_len - 8) + 1
|
||||
else:
|
||||
# Streaming ICL exact length term: 1 + ref_code_len
|
||||
prompt_len = base_len + codec_lens
|
||||
else:
|
||||
# Base x-vector-only (or missing ref_code length) follows CV shape.
|
||||
if non_streaming_mode:
|
||||
prompt_len = base_len + max(0, assistant_len - 6)
|
||||
else:
|
||||
prompt_len = base_len + 1
|
||||
return max(32, min(4096, int(prompt_len)))
|
||||
|
||||
# Defensive fallback for unknown task types.
|
||||
return max(32, min(4096, int(base_len + max(assistant_len, 1))))
|
||||
|
||||
|
||||
def aura2tts(
|
||||
source_outputs: list[Any],
|
||||
prompt: Any = None,
|
||||
requires_multimodal_data: bool = False,
|
||||
) -> list[OmniTokensPrompt]:
|
||||
"""Convert AURA text output into Qwen3-TTS Talker requests."""
|
||||
del requires_multimodal_data
|
||||
prompt_by_request_id = _source_prompt_by_request_id(source_outputs, prompt)
|
||||
next_inputs: list[OmniTokensPrompt] = []
|
||||
for idx, source_output in enumerate(source_outputs):
|
||||
text = _extract_text(source_output).strip()
|
||||
if not text or text == SILENT_TEXT:
|
||||
continue
|
||||
|
||||
src_prompt = prompt_by_request_id.get(str(getattr(source_output, "request_id", idx)), {})
|
||||
additional_info = src_prompt.get("additional_information") or {}
|
||||
task_type = _first_value(additional_info.get("tts_task_type"), "Base")
|
||||
language = _first_value(additional_info.get("tts_language"), "English")
|
||||
instruct = _first_value(additional_info.get("tts_instruct"), "")
|
||||
x_vector_only_mode = _first_bool(additional_info.get("tts_x_vector_only_mode"), False)
|
||||
non_streaming_mode_raw = _first_value(additional_info.get("tts_non_streaming_mode"), None)
|
||||
non_streaming_mode = non_streaming_mode_raw if isinstance(non_streaming_mode_raw, bool) else None
|
||||
ref_code_len_raw = _first_value(additional_info.get("tts_ref_code_length"), None)
|
||||
ref_code_len = int(ref_code_len_raw) if isinstance(ref_code_len_raw, int) else None
|
||||
ref_audio = None
|
||||
ref_text = None
|
||||
if task_type == "Base" and not x_vector_only_mode and ref_code_len is None:
|
||||
ref_audio = _first_value(additional_info.get("tts_ref_audio"), None)
|
||||
ref_code_len = _estimate_ref_code_len_from_ref_audio(ref_audio)
|
||||
|
||||
assistant_token_ids_for_len = _qwen3_tts_assistant_token_ids_from_aura(source_output)
|
||||
pass_token_ids = _first_bool(additional_info.get("tts_pass_token_ids"), False)
|
||||
tts_info = {
|
||||
"task_type": [task_type],
|
||||
"language": [language],
|
||||
"instruct": [instruct],
|
||||
"max_new_tokens": [int(_first_value(additional_info.get("tts_max_new_tokens"), 2048))],
|
||||
}
|
||||
if pass_token_ids and assistant_token_ids_for_len:
|
||||
tts_info[PRECOMPUTED_TEXT_IDS_KEY] = [assistant_token_ids_for_len]
|
||||
else:
|
||||
tts_info["text"] = [text]
|
||||
if ref_code_len is not None:
|
||||
tts_info["ref_code_length"] = [int(ref_code_len)]
|
||||
prompt_len = _estimate_tts_prompt_len_from_token_ids(
|
||||
assistant_token_ids_for_len if assistant_token_ids_for_len else [0] * max(0, len(text)),
|
||||
task_type=str(task_type),
|
||||
language=str(language),
|
||||
instruct=str(instruct),
|
||||
x_vector_only_mode=x_vector_only_mode,
|
||||
non_streaming_mode=non_streaming_mode,
|
||||
ref_code_len=ref_code_len,
|
||||
)
|
||||
|
||||
if task_type == "Base":
|
||||
ref_audio = ref_audio or _first_value(additional_info.get("tts_ref_audio"), None)
|
||||
ref_text = _first_value(additional_info.get("tts_ref_text"), None)
|
||||
if not ref_audio or not ref_text:
|
||||
raise ValueError("AURA Base TTS requires tts_ref_audio and tts_ref_text.")
|
||||
x_vector_only_mode = _first_bool(additional_info.get("tts_x_vector_only_mode"), False)
|
||||
tts_info["ref_audio"] = [ref_audio]
|
||||
tts_info["ref_text"] = [ref_text]
|
||||
tts_info["x_vector_only_mode"] = [x_vector_only_mode]
|
||||
elif task_type == "CustomVoice":
|
||||
tts_info["speaker"] = [
|
||||
_normalize_qwen3_tts_speaker(_first_value(additional_info.get("tts_speaker"), "Vivian"))
|
||||
]
|
||||
next_inputs.append(
|
||||
OmniTokensPrompt(
|
||||
prompt_token_ids=[0] * prompt_len,
|
||||
additional_information=tts_info,
|
||||
multi_modal_data=None,
|
||||
mm_processor_kwargs=None,
|
||||
)
|
||||
)
|
||||
return next_inputs
|
||||
@@ -1,4 +1,5 @@
|
||||
import contextlib
|
||||
import inspect
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
@@ -48,6 +49,30 @@ else:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _filter_mrope_kwargs_for_model(model: object, kwargs: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return only M-RoPE kwargs accepted by the model implementation."""
|
||||
method = getattr(model, "get_mrope_input_positions")
|
||||
try:
|
||||
signature = inspect.signature(method)
|
||||
except (TypeError, ValueError):
|
||||
return kwargs
|
||||
|
||||
if any(param.kind == inspect.Parameter.VAR_KEYWORD for param in signature.parameters.values()):
|
||||
return kwargs
|
||||
|
||||
accepted = {
|
||||
name
|
||||
for name, param in signature.parameters.items()
|
||||
if name not in {"self", "input_tokens"}
|
||||
and param.kind
|
||||
in {
|
||||
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
||||
inspect.Parameter.KEYWORD_ONLY,
|
||||
}
|
||||
}
|
||||
return {key: value for key, value in kwargs.items() if key in accepted}
|
||||
|
||||
|
||||
class OmniGPUModelRunner(GPUModelRunner):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -338,7 +363,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
kwargs["target_w"] = target_w
|
||||
req_state.mrope_positions, req_state.mrope_position_delta = self.model.get_mrope_input_positions(
|
||||
req_state.prompt_token_ids,
|
||||
**kwargs,
|
||||
**_filter_mrope_kwargs_for_model(self.model, kwargs),
|
||||
)
|
||||
else:
|
||||
req_state.mrope_positions, req_state.mrope_position_delta = MRotaryEmbedding.get_input_positions_tensor(
|
||||
|
||||
Reference in new issue
Block a user