[Feature] support to change the speaker of qwen3-omni (#1963)
Signed-off-by: Rein Yang <ruiruyang2@gmail.com>
This commit is contained in:
1 parent
d16be833e1
commit
3cdf28828e
18 files changed
+486
-533
No files matched your search
@@ -697,7 +697,7 @@ class Qwen2_5OmniForConditionalGeneration(
|
||||
|
||||
# TODO(Peiqi): add voice_type support
|
||||
req_input_ids, req_embeds = self._thinker_to_talker_prefill(
|
||||
voice_type=self.voice_type,
|
||||
speaker=self.voice_type,
|
||||
output_prompt_embeds=thinker_result.to(input_embeds.dtype).to(self._module_device(self.model)),
|
||||
output_token_ids=thinker_output_token_ids,
|
||||
thinker_prompt_embeds=prompt_embeds.to(input_embeds.dtype).to(self._module_device(self.model)),
|
||||
@@ -711,7 +711,7 @@ class Qwen2_5OmniForConditionalGeneration(
|
||||
|
||||
def _thinker_to_talker_prefill(
|
||||
self,
|
||||
voice_type: str,
|
||||
speaker: str,
|
||||
output_prompt_embeds,
|
||||
output_token_ids,
|
||||
thinker_prompt_embeds,
|
||||
@@ -726,7 +726,7 @@ class Qwen2_5OmniForConditionalGeneration(
|
||||
prompt_embeds = torch.cat(
|
||||
[
|
||||
thinker_prompt_embeds,
|
||||
self._get_embed_text_spk_token(voice_type) + self.embed_codec_pad_token,
|
||||
self._get_embed_text_spk_token(speaker) + self.embed_codec_pad_token,
|
||||
output_prompt_embeds[:1] + self.embed_codec_bos_token,
|
||||
],
|
||||
dim=0,
|
||||
|
||||
@@ -322,10 +322,6 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
if inputs_embeds is None and input_ids is not None:
|
||||
inputs_embeds = self.talker.embed_input_ids(input_ids)
|
||||
|
||||
# TODO(Peiqi): temporal hack here to support voice_type.
|
||||
if not hasattr(self, "voice_type"):
|
||||
self.voice_type = voice_type
|
||||
|
||||
# Run talker forward
|
||||
with torch.inference_mode():
|
||||
talker_hidden = self.talker.forward(
|
||||
@@ -377,7 +373,7 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
left_context_size.append(info["left_context_size"])
|
||||
else:
|
||||
logger.debug("No additional_information provided to code2wav stage.")
|
||||
audio_tensors = self.generate_audio(codes, voice_type, left_context_size, seq_token_counts)
|
||||
audio_tensors = self.generate_audio(codes, left_context_size, seq_token_counts)
|
||||
|
||||
return audio_tensors
|
||||
|
||||
@@ -457,7 +453,6 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
def generate_audio(
|
||||
self,
|
||||
code: torch.Tensor,
|
||||
voice_type: str,
|
||||
left_context_size: list[int] | None = None,
|
||||
seq_token_counts: list[int] | None = None,
|
||||
) -> list[torch.Tensor]:
|
||||
@@ -466,7 +461,6 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
|
||||
Args:
|
||||
code: [batch, num_quantizers, T] - RVQ codec codes
|
||||
voice_type: Voice type (not used in Qwen3, kept for compatibility)
|
||||
left_context_size: Left context size for streaming decode
|
||||
seq_token_counts: Token count for each request in batch
|
||||
|
||||
@@ -678,8 +672,16 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
def talker_preprocess_prefill(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: dict):
|
||||
# Containers to return per-request updates (e.g., code_predictor_hidden_per_request)
|
||||
update_dict: dict[str, dict] = {}
|
||||
# TODO(Peiqi): add voice_type support
|
||||
voice_type = self.voice_type
|
||||
|
||||
voice_type = info_dict.get("speaker")
|
||||
logger.info("talker_preprocess_prefill speaker: %s", voice_type)
|
||||
if voice_type is not None and isinstance(voice_type, (list, tuple)) and len(voice_type) > 0:
|
||||
voice_type = voice_type[0]
|
||||
if not isinstance(voice_type, str) or not voice_type.strip():
|
||||
# Fall back to model default; speaker is per-request.
|
||||
voice_type = self.default_tts_text_spk_type
|
||||
else:
|
||||
voice_type = str(voice_type).lower().strip()
|
||||
start_index = info_dict.get("num_processed_tokens", 0)
|
||||
end_index = start_index + input_embeds.shape[0]
|
||||
# Read thinker outputs for prefill
|
||||
|
||||
@@ -700,7 +700,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
info: dict[str, Any] = additional_information or {}
|
||||
text = _first(info.get("text"), "")
|
||||
language = _first(info.get("language"), "Auto")
|
||||
speaker = _first(info.get("speaker"), "")
|
||||
speaker = _first(info.get("speaker"), "").lower().strip()
|
||||
instruct = _first(info.get("instruct"), "")
|
||||
non_streaming_mode_raw = _first(info.get("non_streaming_mode"), None)
|
||||
|
||||
@@ -1438,11 +1438,14 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
)
|
||||
|
||||
elif task_type == "CustomVoice":
|
||||
speaker = (info_dict.get("speaker") or [""])[0]
|
||||
if not isinstance(speaker, str) or not speaker.strip():
|
||||
_speaker_raw = info_dict.get("speaker") or [""]
|
||||
speaker = (
|
||||
((_speaker_raw[0] if isinstance(_speaker_raw, (list, tuple)) else _speaker_raw) or "").lower().strip()
|
||||
)
|
||||
if not speaker:
|
||||
raise ValueError("CustomVoice requires additional_information.speaker.")
|
||||
spk_id_map = getattr(self.talker_config, "spk_id", None) or {}
|
||||
if speaker.lower() not in spk_id_map:
|
||||
if speaker not in spk_id_map:
|
||||
raise ValueError(f"Unsupported speaker: {speaker}")
|
||||
spk_id = spk_id_map[speaker.lower()]
|
||||
# Keep it at least 1D; embedding on a 0-d tensor can return 1D.
|
||||
|
||||
@@ -11,6 +11,12 @@ from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
from vllm_omni.model_executor.stage_input_processors.tts_utils import (
|
||||
extract_language_from_prompt,
|
||||
extract_language_from_request,
|
||||
extract_speaker_from_prompt,
|
||||
extract_speaker_from_request,
|
||||
)
|
||||
|
||||
|
||||
def _compute_talker_prompt_ids_length(info, device: torch.device | str = "cuda") -> int:
|
||||
@@ -115,6 +121,12 @@ def thinker2talker_async_chunk(
|
||||
"tts_pad_embed": pooling_output.get("tts_pad_embed").detach().cpu(),
|
||||
"finished": torch.tensor(is_finished, dtype=torch.bool),
|
||||
}
|
||||
speaker = extract_speaker_from_request(request)
|
||||
if speaker is not None:
|
||||
talker_additional_info["speaker"] = speaker
|
||||
language = extract_language_from_request(request)
|
||||
if language is not None:
|
||||
talker_additional_info["language"] = language
|
||||
if transfer_manager.request_payload.get(request_id) is None:
|
||||
if not is_finished:
|
||||
transfer_manager.request_payload[request_id] = talker_additional_info
|
||||
@@ -140,6 +152,13 @@ def thinker2talker_async_chunk(
|
||||
talker_additional_info = {
|
||||
"finished": torch.tensor(is_finished, dtype=torch.bool),
|
||||
}
|
||||
speaker = extract_speaker_from_request(request)
|
||||
if speaker is not None:
|
||||
talker_additional_info["speaker"] = speaker
|
||||
language = extract_language_from_request(request)
|
||||
if language is not None:
|
||||
talker_additional_info["language"] = language
|
||||
|
||||
if output_token_ids:
|
||||
talker_additional_info["override_keys"] = ["thinker_decode_embeddings", "thinker_output_token_ids"]
|
||||
talker_additional_info["thinker_decode_embeddings"] = pooling_output.get("0").detach().cpu()
|
||||
@@ -148,6 +167,7 @@ def thinker2talker_async_chunk(
|
||||
# When prefilling a chunked thinker, thinker_hidden_states needs to be updated.
|
||||
talker_additional_info["thinker_prefill_embeddings"] = pooling_output.get("0").detach().cpu()
|
||||
talker_additional_info["thinker_hidden_states"] = pooling_output.get("24").detach().cpu()
|
||||
|
||||
return talker_additional_info
|
||||
|
||||
|
||||
@@ -180,7 +200,7 @@ def thinker2talker(
|
||||
device = torch.device(current_platform.device_type)
|
||||
|
||||
# Process each thinker output
|
||||
for thinker_output in thinker_outputs:
|
||||
for i, thinker_output in enumerate(thinker_outputs):
|
||||
output = thinker_output.outputs[0]
|
||||
|
||||
info = {
|
||||
@@ -195,6 +215,12 @@ def thinker2talker(
|
||||
"tts_eos_embed": output.multimodal_output["tts_eos_embed"].detach().to(device=device, dtype=torch.float),
|
||||
"tts_pad_embed": output.multimodal_output["tts_pad_embed"].detach().to(device=device, dtype=torch.float),
|
||||
}
|
||||
speaker = extract_speaker_from_prompt(prompt, index=i)
|
||||
if speaker is not None:
|
||||
info["speaker"] = speaker
|
||||
language = extract_language_from_prompt(prompt, index=i)
|
||||
if language is not None:
|
||||
info["language"] = language
|
||||
|
||||
prompt_len = _compute_talker_prompt_ids_length(info, device=device)
|
||||
|
||||
|
||||
@@ -9,6 +9,12 @@ from vllm_omni.model_executor.stage_input_processors.chunk_size_utils import (
|
||||
compute_dynamic_initial_chunk_size,
|
||||
max_ic_for_chunk_size,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.tts_utils import (
|
||||
extract_language_from_prompt,
|
||||
extract_language_from_request,
|
||||
extract_speaker_from_prompt,
|
||||
extract_speaker_from_request,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -25,7 +31,7 @@ def talker2code2wav(
|
||||
|
||||
talker_outputs = _validate_stage_inputs(stage_list, engine_input_source)
|
||||
code2wav_inputs: list[OmniTokensPrompt] = []
|
||||
for talker_output in talker_outputs:
|
||||
for i, talker_output in enumerate(talker_outputs):
|
||||
output = talker_output.outputs[0]
|
||||
# audio_codes shape: [num_frames, Q] where Q=num_quantizers (16)
|
||||
audio_codes = output.multimodal_output["audio_codes"].to(torch.long)
|
||||
@@ -45,13 +51,24 @@ def talker2code2wav(
|
||||
ref_code_len = 0
|
||||
# Code2Wav expects codebook-major flat: [Q*num_frames]
|
||||
codec_codes = audio_codes.transpose(0, 1).cpu().reshape(-1).tolist()
|
||||
additional_information = {"left_context_size": [ref_code_len]} if ref_code_len > 0 else None
|
||||
additional_information: dict[str, Any] = {}
|
||||
if ref_code_len > 0:
|
||||
additional_information["left_context_size"] = [ref_code_len]
|
||||
# Propagate speaker and language from the original prompt so they are
|
||||
# available as runtime_additional_information in later pipeline stages,
|
||||
# consistent with qwen3-omni and qwen2.5-omni stage input processors.
|
||||
speaker = extract_speaker_from_prompt(prompt, index=i)
|
||||
if speaker is not None:
|
||||
additional_information["speaker"] = speaker
|
||||
language = extract_language_from_prompt(prompt, index=i)
|
||||
if language is not None:
|
||||
additional_information["language"] = language
|
||||
code2wav_inputs.append(
|
||||
OmniTokensPrompt(
|
||||
prompt_token_ids=codec_codes,
|
||||
multi_modal_data=None,
|
||||
mm_processor_kwargs=None,
|
||||
additional_information=additional_information,
|
||||
additional_information=additional_information if additional_information else None,
|
||||
)
|
||||
)
|
||||
return code2wav_inputs
|
||||
@@ -194,8 +211,18 @@ def talker2code2wav_async_chunk(
|
||||
num_frames = len(window_frames)
|
||||
code_predictor_codes = [window_frames[f][q] for q in range(num_quantizers) for f in range(num_frames)]
|
||||
|
||||
return {
|
||||
info: dict[str, Any] = {
|
||||
"code_predictor_codes": code_predictor_codes,
|
||||
"left_context_size": left_context_size,
|
||||
"finished": finished,
|
||||
}
|
||||
# Propagate speaker and language from the request so they are available
|
||||
# as runtime_additional_information in subsequent pipeline stages, consistent
|
||||
# with qwen3-omni and qwen2.5-omni stage input processors.
|
||||
speaker = extract_speaker_from_request(request)
|
||||
if speaker is not None:
|
||||
info["speaker"] = speaker
|
||||
language = extract_language_from_request(request)
|
||||
if language is not None:
|
||||
info["language"] = language
|
||||
return info
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# Copyright 2025 The Qwen team.
|
||||
"""Shared TTS utility functions for speaker and language extraction.
|
||||
|
||||
These utilities are model-agnostic and can be used by any TTS model stage
|
||||
processor (qwen3_omni, qwen2_5_omni, qwen3_tts, etc.).
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
# =============================================================================
|
||||
# Speaker helpers
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def extract_speaker_from_runtime_info(
|
||||
runtime_additional_information: list[dict[str, Any]] | None,
|
||||
) -> str | None:
|
||||
"""Extract speaker from per-request runtime info dicts.
|
||||
|
||||
Iterates through the list of per-request info dicts and returns the first
|
||||
non-empty speaker string found, normalized to lowercase.
|
||||
|
||||
Args:
|
||||
runtime_additional_information: List of per-request additional info
|
||||
dicts, as passed to the model's forward() method.
|
||||
|
||||
Returns:
|
||||
The speaker string (lowercase, stripped), or None if not present.
|
||||
"""
|
||||
if not runtime_additional_information:
|
||||
return None
|
||||
for info in runtime_additional_information:
|
||||
vt = info.get("speaker")
|
||||
if vt is None:
|
||||
continue
|
||||
if isinstance(vt, (list, tuple)) and len(vt) > 0:
|
||||
vt = vt[0]
|
||||
if isinstance(vt, str) and vt.strip():
|
||||
return vt.lower().strip()
|
||||
if vt is not None:
|
||||
return str(vt).lower().strip()
|
||||
return None
|
||||
|
||||
|
||||
def extract_speaker_from_request(request: Any) -> str | None:
|
||||
"""Extract speaker from a request's additional_information field.
|
||||
|
||||
Reads from the structured ``additional_information.entries["speaker"]``
|
||||
field used by the engine serialization layer.
|
||||
|
||||
Args:
|
||||
request: An OmniEngineCoreRequest (or compatible object) with an
|
||||
``additional_information`` attribute.
|
||||
|
||||
Returns:
|
||||
The speaker string (lowercase, stripped), or None if not present.
|
||||
"""
|
||||
additional_information = getattr(request, "additional_information", None)
|
||||
if additional_information is None:
|
||||
return None
|
||||
entries = getattr(additional_information, "entries", None)
|
||||
if not isinstance(entries, dict):
|
||||
return None
|
||||
entry = entries.get("speaker")
|
||||
if entry is None:
|
||||
return None
|
||||
list_data = getattr(entry, "list_data", None)
|
||||
if isinstance(list_data, list) and list_data:
|
||||
val = list_data[0]
|
||||
return val.lower().strip() if isinstance(val, str) else str(val).lower().strip()
|
||||
return None
|
||||
|
||||
|
||||
def extract_speaker_from_prompt(
|
||||
prompt: Any,
|
||||
index: int = 0,
|
||||
) -> list[str] | None:
|
||||
"""Extract speaker from a prompt's additional_information dict.
|
||||
|
||||
Used in non-async stage processors where the prompt is an
|
||||
OmniTokensPrompt / TextPrompt dict (or a list of them).
|
||||
|
||||
Args:
|
||||
prompt: A single prompt dict, or a list of prompt dicts.
|
||||
index: Which element to pick when prompt is a list.
|
||||
|
||||
Returns:
|
||||
The speaker as a list (for serialization compatibility), or None.
|
||||
"""
|
||||
if prompt is None:
|
||||
return None
|
||||
p = prompt[index] if isinstance(prompt, list) and index < len(prompt) else prompt
|
||||
if p is None:
|
||||
return None
|
||||
add_info = p.get("additional_information")
|
||||
if not isinstance(add_info, dict):
|
||||
return None
|
||||
speaker = add_info.get("speaker")
|
||||
if isinstance(speaker, list) and speaker:
|
||||
return speaker
|
||||
return None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Language helpers
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def extract_language_from_runtime_info(
|
||||
runtime_additional_information: list[dict[str, Any]] | None,
|
||||
) -> str | None:
|
||||
"""Extract language from per-request runtime info dicts.
|
||||
Args:
|
||||
runtime_additional_information: List of per-request additional info
|
||||
dicts, as passed to the model's forward() method.
|
||||
|
||||
Returns:
|
||||
The language string (e.g. "Chinese", "English", "Auto"), or None.
|
||||
"""
|
||||
if not runtime_additional_information:
|
||||
return None
|
||||
for info in runtime_additional_information:
|
||||
lang = info.get("language")
|
||||
if lang is None:
|
||||
continue
|
||||
if isinstance(lang, (list, tuple)) and len(lang) > 0:
|
||||
return lang
|
||||
if isinstance(lang, str) and lang.strip():
|
||||
return [lang.strip()]
|
||||
return None
|
||||
|
||||
|
||||
def extract_language_from_request(request: Any) -> str | None:
|
||||
"""Extract language from a request's additional_information field.
|
||||
|
||||
Args:
|
||||
request: An OmniEngineCoreRequest (or compatible object) with an
|
||||
``additional_information`` attribute.
|
||||
|
||||
Returns:
|
||||
The language string, or None if not present.
|
||||
"""
|
||||
additional_information = getattr(request, "additional_information", None)
|
||||
if additional_information is None:
|
||||
return None
|
||||
entries = getattr(additional_information, "entries", None)
|
||||
if not isinstance(entries, dict):
|
||||
return None
|
||||
entry = entries.get("language")
|
||||
if entry is None:
|
||||
return None
|
||||
list_data = getattr(entry, "list_data", None)
|
||||
if isinstance(list_data, list) and list_data:
|
||||
return list_data
|
||||
return None
|
||||
|
||||
|
||||
def extract_language_from_prompt(
|
||||
prompt: Any,
|
||||
index: int = 0,
|
||||
) -> list[str] | None:
|
||||
"""Extract language from a prompt's additional_information dict.
|
||||
Args:
|
||||
prompt: A single prompt dict, or a list of prompt dicts.
|
||||
index: Which element to pick when prompt is a list.
|
||||
|
||||
Returns:
|
||||
The language as a list (for serialization compatibility), or None.
|
||||
"""
|
||||
if prompt is None:
|
||||
return None
|
||||
p = prompt[index] if isinstance(prompt, list) and index < len(prompt) else prompt
|
||||
if p is None:
|
||||
return None
|
||||
add_info = p.get("additional_information")
|
||||
if not isinstance(add_info, dict):
|
||||
return None
|
||||
language = add_info.get("language")
|
||||
if isinstance(language, list) and language:
|
||||
return language
|
||||
return None
|
||||
Reference in new issue
Block a user