[Feature] Add precomputed custom voices and Qwen3-TTS ref-context cache (#3492)
Signed-off-by: Sy03 <1370724210@qq.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Dan250124 <416947747@qq.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
23 files changed
+2362
-145
No files matched your search
@@ -757,6 +757,14 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
ref_audio_list = info_dict.get("ref_audio")
|
||||
if not isinstance(ref_audio_list, list) or not ref_audio_list:
|
||||
continue
|
||||
cache_key_from_serving = first_value(info_dict.get(REF_AUDIO_CACHE_KEY))
|
||||
if isinstance(cache_key_from_serving, str) and cache_key_from_serving:
|
||||
cached = self.get_ref_audio_artifacts(cache_key_from_serving)
|
||||
if cached is not None:
|
||||
cached_ref_code = coerce_ref_code_tensor(cached.get("ref_code"), device=device)
|
||||
if isinstance(cached_ref_code, torch.Tensor):
|
||||
info_dict.setdefault("codes", {})[PRECOMPUTED_REF_CODE_KEY] = cached_ref_code
|
||||
continue
|
||||
try:
|
||||
wav, sr = self.normalize_ref_audio(ref_audio_list[0])
|
||||
except Exception:
|
||||
@@ -1029,6 +1037,19 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
xvec_only = bool((info_dict.get("x_vector_only_mode") or [False])[0])
|
||||
in_context_mode = not xvec_only
|
||||
voice_clone_prompt = _normalize_voice_clone_prompt(info_dict.get("voice_clone_prompt"))
|
||||
if voice_clone_prompt is not None and "icl_mode" in voice_clone_prompt:
|
||||
icl_flag = _as_singleton(voice_clone_prompt.get("icl_mode"))
|
||||
if isinstance(icl_flag, bool):
|
||||
in_context_mode = icl_flag
|
||||
xvec_only = not in_context_mode
|
||||
prompt_has_ref_code = voice_clone_prompt is not None and self._has_ref_code_like(
|
||||
voice_clone_prompt.get("ref_code")
|
||||
)
|
||||
prompt_spk = voice_clone_prompt.get("ref_spk_embedding") if voice_clone_prompt is not None else None
|
||||
prompt_has_speaker = isinstance(prompt_spk, torch.Tensor) or (
|
||||
isinstance(prompt_spk, (list, np.ndarray)) and len(prompt_spk) > 0
|
||||
)
|
||||
needs_ref_audio_cache_key = not (prompt_has_speaker and (not in_context_mode or prompt_has_ref_code))
|
||||
ref_audio_wav: np.ndarray | None = None
|
||||
ref_audio_sr: int | None = None
|
||||
|
||||
@@ -1056,7 +1077,8 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
# from ref_audio: x_vector_only_mode, precomputed ref_code
|
||||
# with no ref_spk_embedding, voice_clone_prompt.icl_mode=False.
|
||||
ref_audio_cache_key = info_dict.pop(REF_AUDIO_CACHE_KEY, None)
|
||||
if not (isinstance(ref_audio_cache_key, str) and ref_audio_cache_key):
|
||||
ref_audio_cache_key = first_value(ref_audio_cache_key)
|
||||
if needs_ref_audio_cache_key and not (isinstance(ref_audio_cache_key, str) and ref_audio_cache_key):
|
||||
normalized = info_dict.get(NORMALIZED_REF_AUDIO_KEY)
|
||||
wav_peek: np.ndarray | None = None
|
||||
sr_peek: int | None = None
|
||||
@@ -1075,13 +1097,25 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
cached_artifacts = None
|
||||
if isinstance(ref_audio_cache_key, str) and ref_audio_cache_key:
|
||||
cached_artifacts = self.get_ref_audio_artifacts(ref_audio_cache_key)
|
||||
ref_audio_list = info_dict.get("ref_audio")
|
||||
has_ref_audio_payload = isinstance(ref_audio_list, list) and bool(ref_audio_list)
|
||||
artifact_only = (
|
||||
isinstance(ref_audio_cache_key, str) and bool(ref_audio_cache_key) and not has_ref_audio_payload
|
||||
)
|
||||
if artifact_only and cached_artifacts is None:
|
||||
raise RuntimeError(
|
||||
"Qwen3-TTS ref_audio artifact cache miss for artifact-only request; "
|
||||
"retry with ref_audio or precompute a custom voice profile."
|
||||
)
|
||||
|
||||
# Speaker cache: only for uploaded (named) speakers
|
||||
_speaker_cache_key = None
|
||||
_cache_lookup_voice = None
|
||||
if voice_clone_prompt is None and self._speaker_cache is not None:
|
||||
_speaker_list = info_dict.get("speaker")
|
||||
if isinstance(_speaker_list, list) and _speaker_list:
|
||||
_voice_name = str(_speaker_list[0]).lower()
|
||||
_cache_lookup_voice = _voice_name
|
||||
# Per-mode namespace — xvec and icl produce different artifacts
|
||||
# for the same voice, so they must not share a cache slot.
|
||||
_mode = "xvec" if xvec_only else "icl"
|
||||
@@ -1103,15 +1137,18 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
"ref_code": ref_code_cached,
|
||||
"ref_spk_embedding": ref_spk_embed_cached,
|
||||
"icl_mode": _cached.get("icl_mode"),
|
||||
"ref_text": _cached.get("ref_text"),
|
||||
}
|
||||
_speaker_cache_key = None # hit → don't store again
|
||||
|
||||
# Official implementation may pass `voice_clone_prompt.icl_mode`.
|
||||
if voice_clone_prompt is not None and "icl_mode" in voice_clone_prompt:
|
||||
icl_flag = _as_singleton(voice_clone_prompt.get("icl_mode"))
|
||||
if isinstance(icl_flag, bool):
|
||||
in_context_mode = icl_flag
|
||||
xvec_only = not in_context_mode
|
||||
if voice_clone_prompt is None and _speaker_cache_key is not None:
|
||||
ref_audio_list = info_dict.get("ref_audio")
|
||||
if not isinstance(ref_audio_list, list) or not ref_audio_list:
|
||||
raise ValueError(
|
||||
f"Qwen3-TTS speaker '{_cache_lookup_voice}' was requested without ref_audio, "
|
||||
"but no precomputed cache entry was loaded"
|
||||
)
|
||||
|
||||
ref_code = None
|
||||
if voice_clone_prompt is not None:
|
||||
ref_code = _as_singleton(voice_clone_prompt.get("ref_code"))
|
||||
@@ -1136,6 +1173,8 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
if isinstance(cached_ref_code, torch.Tensor):
|
||||
ref_code_t = cached_ref_code
|
||||
ref_code_len = int(ref_code_t.shape[0])
|
||||
if ref_code_t is None and in_context_mode and artifact_only:
|
||||
raise RuntimeError("Qwen3-TTS ref_audio artifact cache entry is missing ref_code.")
|
||||
if ref_code_t is None and in_context_mode:
|
||||
# Compute ref_code from ref_audio if not provided.
|
||||
wav_np, sr = _get_ref_audio()
|
||||
@@ -1161,6 +1200,8 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
.to(device=input_ids.device, dtype=torch.bfloat16)
|
||||
.view(1, 1, -1)
|
||||
)
|
||||
elif artifact_only:
|
||||
raise RuntimeError("Qwen3-TTS ref_audio artifact cache entry is missing ref_spk_embedding.")
|
||||
else:
|
||||
wav_np, sr = _get_ref_audio()
|
||||
speaker_embed = self.extract_speaker_embedding(wav_np, sr).view(1, 1, -1)
|
||||
@@ -1207,6 +1248,8 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
)
|
||||
if ref_ids is None:
|
||||
ref_text = _as_singleton(info_dict.get("ref_text"))
|
||||
if (not isinstance(ref_text, str) or not ref_text.strip()) and voice_clone_prompt is not None:
|
||||
ref_text = _as_singleton(voice_clone_prompt.get("ref_text"))
|
||||
if isinstance(ref_text, str) and ref_text.strip():
|
||||
ref_ids = tok(
|
||||
build_ref_text(ref_text),
|
||||
@@ -1489,6 +1532,13 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
except Exception:
|
||||
ref_code_len = None
|
||||
|
||||
if ref_code_len is None:
|
||||
ref_code_length = _first(info.get("ref_code_length"), None)
|
||||
try:
|
||||
if ref_code_length is not None:
|
||||
ref_code_len = int(ref_code_length) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
ref_code_len = None
|
||||
if ref_code_len is None and estimate_ref_code_len is not None:
|
||||
ref_code_len = estimate_ref_code_len(info.get("ref_audio"))
|
||||
if ref_code_len is None:
|
||||
@@ -1511,6 +1561,10 @@ class Qwen3TTSPromptEmbedsBuilder:
|
||||
|
||||
if ref_ids is None:
|
||||
ref_text = _first(info.get("ref_text"), "")
|
||||
if (not isinstance(ref_text, str) or not ref_text.strip()) and isinstance(
|
||||
voice_clone_prompt, dict
|
||||
):
|
||||
ref_text = _first(voice_clone_prompt.get("ref_text"), "")
|
||||
if not isinstance(ref_text, str) or not ref_text.strip():
|
||||
raise ValueError(
|
||||
"Base in-context non-streaming requires `ref_text` or tokenized `ref_ids`."
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections import Counter
|
||||
from collections import Counter, OrderedDict
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
@@ -24,6 +24,9 @@ from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import (
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_REF_CONTEXT_CACHE_MAX_ENTRIES = 4096
|
||||
_REF_CONTEXT_CACHE_MAX_BYTES = 64 * 1024 * 1024
|
||||
|
||||
|
||||
def _codec_ids_from_payload_or_input(
|
||||
input_ids: torch.Tensor,
|
||||
@@ -100,6 +103,10 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
self._output_sample_rate = int(tok_config.output_sample_rate)
|
||||
self._total_upsample = int(self.decoder.total_upsample)
|
||||
self._decoder_sliding_window = int(getattr(dec_config, "sliding_window", 0) or 0)
|
||||
self._ref_context_cache: OrderedDict[str, torch.Tensor] = OrderedDict()
|
||||
self._ref_context_cache_bytes = 0
|
||||
self._ref_context_cache_max_entries = _REF_CONTEXT_CACHE_MAX_ENTRIES
|
||||
self._ref_context_cache_max_bytes = _REF_CONTEXT_CACHE_MAX_BYTES
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
|
||||
# This stage ignores token embeddings. Keep a stable dummy embedding for vLLM runner.
|
||||
@@ -205,6 +212,49 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
self._batch_stats_actual_frames.update(actual_frames)
|
||||
self._batch_stats_bucket_groups[(group_size, bucket_frames)] += 1
|
||||
|
||||
@staticmethod
|
||||
def _tensor_nbytes(tensor: torch.Tensor) -> int:
|
||||
return int(tensor.numel() * tensor.element_size())
|
||||
|
||||
def _evict_ref_context_cache_if_needed(self) -> None:
|
||||
evicted = 0
|
||||
while len(self._ref_context_cache) > self._ref_context_cache_max_entries:
|
||||
_, cached = self._ref_context_cache.popitem(last=False)
|
||||
self._ref_context_cache_bytes -= self._tensor_nbytes(cached)
|
||||
evicted += 1
|
||||
while self._ref_context_cache_bytes > self._ref_context_cache_max_bytes and len(self._ref_context_cache) > 1:
|
||||
_, cached = self._ref_context_cache.popitem(last=False)
|
||||
self._ref_context_cache_bytes -= self._tensor_nbytes(cached)
|
||||
evicted += 1
|
||||
if evicted:
|
||||
logger.debug(
|
||||
"Evicted %d Qwen3-TTS ref context cache entries; entries=%d bytes=%d",
|
||||
evicted,
|
||||
len(self._ref_context_cache),
|
||||
self._ref_context_cache_bytes,
|
||||
)
|
||||
|
||||
def _cache_ref_context(self, request_id: str, tensor: torch.Tensor) -> None:
|
||||
previous = self._ref_context_cache.pop(request_id, None)
|
||||
if previous is not None:
|
||||
self._ref_context_cache_bytes -= self._tensor_nbytes(previous)
|
||||
cached = tensor.detach().contiguous()
|
||||
self._ref_context_cache[request_id] = cached
|
||||
self._ref_context_cache.move_to_end(request_id)
|
||||
self._ref_context_cache_bytes += self._tensor_nbytes(cached)
|
||||
self._evict_ref_context_cache_if_needed()
|
||||
|
||||
def _get_ref_context(self, request_id: str) -> torch.Tensor | None:
|
||||
cached = self._ref_context_cache.get(request_id)
|
||||
if cached is not None:
|
||||
self._ref_context_cache.move_to_end(request_id)
|
||||
return cached
|
||||
|
||||
def _pop_ref_context(self, request_id: str) -> None:
|
||||
cached = self._ref_context_cache.pop(request_id, None)
|
||||
if cached is not None:
|
||||
self._ref_context_cache_bytes -= self._tensor_nbytes(cached)
|
||||
|
||||
def log_decode_batch_stats(self) -> None:
|
||||
if not self._batch_stats_enabled or self._batch_stats_requests == 0:
|
||||
return
|
||||
@@ -268,6 +318,32 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
valid_codes_qf: list[torch.Tensor] = []
|
||||
valid_indices: list[int] = []
|
||||
left_context_size = [0] * len(request_ids_list)
|
||||
ref_context_size = [0] * len(request_ids_list)
|
||||
ref_context_request_ids: list[str | None] = [None] * len(request_ids_list)
|
||||
ref_context_included = [False] * len(request_ids_list)
|
||||
finished_flags = [False] * len(request_ids_list)
|
||||
|
||||
def _meta_int(value: Any) -> int:
|
||||
if isinstance(value, list):
|
||||
value = value[0] if value else 0
|
||||
if isinstance(value, torch.Tensor):
|
||||
value = value.reshape(-1)[0].item() if value.numel() > 0 else 0
|
||||
return int(value or 0)
|
||||
|
||||
def _meta_str(value: Any) -> str | None:
|
||||
if isinstance(value, list):
|
||||
value = value[0] if value else None
|
||||
if value is None:
|
||||
return None
|
||||
return str(value)
|
||||
|
||||
def _meta_bool(value: Any) -> bool:
|
||||
if isinstance(value, list):
|
||||
value = value[0] if value else False
|
||||
if isinstance(value, torch.Tensor):
|
||||
return bool(value.reshape(-1)[0].item()) if value.numel() > 0 else False
|
||||
return bool(value)
|
||||
|
||||
if runtime_infos:
|
||||
for i, info in enumerate(runtime_infos):
|
||||
if i >= len(left_context_size):
|
||||
@@ -276,7 +352,15 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
continue
|
||||
meta = info.get("meta", {})
|
||||
if "left_context_size" in meta:
|
||||
left_context_size[i] = meta["left_context_size"]
|
||||
left_context_size[i] = _meta_int(meta["left_context_size"])
|
||||
if "ref_context_size" in meta:
|
||||
ref_context_size[i] = _meta_int(meta["ref_context_size"])
|
||||
if "ref_context_request_id" in meta:
|
||||
ref_context_request_ids[i] = _meta_str(meta["ref_context_request_id"])
|
||||
if "ref_context_included" in meta:
|
||||
ref_context_included[i] = _meta_bool(meta["ref_context_included"])
|
||||
if "finished" in meta:
|
||||
finished_flags[i] = _meta_bool(meta["finished"])
|
||||
for i, req_ids in enumerate(request_ids_list):
|
||||
runtime_info = runtime_infos[i] if i < len(runtime_infos) else None
|
||||
req_ids = _codec_ids_from_payload_or_input(req_ids, runtime_info)
|
||||
@@ -284,6 +368,7 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
parsed.append((0, 0))
|
||||
continue
|
||||
ctx_frames = left_context_size[i]
|
||||
ref_ctx_frames = ref_context_size[i]
|
||||
flat = req_ids
|
||||
n = flat.numel()
|
||||
if n == 0 or n % q != 0:
|
||||
@@ -302,6 +387,25 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
frames = n // q
|
||||
# [q*F] -> [Q, F] for direct decoder call (decoder expects [B, Q, F])
|
||||
codes_qf = flat.reshape(q, frames)
|
||||
ref_req_id = ref_context_request_ids[i]
|
||||
if ref_req_id is not None and ref_ctx_frames > 0:
|
||||
if ref_context_included[i]:
|
||||
if frames < ref_ctx_frames:
|
||||
raise ValueError(
|
||||
"Qwen3-TTS ref context metadata says ref prefix is included, "
|
||||
f"but frames={frames} < ref_context_size={ref_ctx_frames}"
|
||||
)
|
||||
self._cache_ref_context(ref_req_id, codes_qf[:, :ref_ctx_frames])
|
||||
else:
|
||||
cached_ref = self._get_ref_context(ref_req_id)
|
||||
if cached_ref is None:
|
||||
raise ValueError(
|
||||
"Missing Qwen3-TTS ref context cache for "
|
||||
f"request {ref_req_id!r}; first chunk must include ref_code"
|
||||
)
|
||||
cached_ref = cached_ref.to(device=codes_qf.device, dtype=codes_qf.dtype)
|
||||
codes_qf = torch.cat((cached_ref, codes_qf), dim=1)
|
||||
frames = int(codes_qf.shape[1])
|
||||
parsed.append((ctx_frames, frames))
|
||||
valid_codes_qf.append(codes_qf)
|
||||
valid_indices.append(i)
|
||||
@@ -443,6 +547,10 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
if wav.shape[0] > 0:
|
||||
audios[idx] = wav.to(dtype=torch.float32).reshape(-1)
|
||||
|
||||
for req_id, finished in zip(ref_context_request_ids, finished_flags, strict=False):
|
||||
if req_id is not None and finished:
|
||||
self._pop_ref_context(req_id)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": audios, "sr": srs},
|
||||
|
||||
@@ -23,7 +23,11 @@ from vllm.sequence import IntermediateTensors
|
||||
|
||||
from vllm_omni.data_entry_keys import OmniPayload
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.utils.speaker_cache import get_speaker_cache
|
||||
from vllm_omni.utils.speaker_cache import (
|
||||
get_speaker_cache,
|
||||
iter_custom_voice_profiles,
|
||||
load_validated_profile_tensors,
|
||||
)
|
||||
|
||||
from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSSpeakerEncoderConfig, Qwen3TTSTalkerConfig
|
||||
from .prompt_embeds_builder import Qwen3TTSPromptEmbedsBuilder
|
||||
@@ -441,6 +445,46 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
encode_ref_audio_batch=self._encode_ref_audio_batch,
|
||||
speaker_cache=self._speaker_cache,
|
||||
)
|
||||
self._load_custom_voice_profiles()
|
||||
|
||||
# -------------------- custom voice profiles --------------------
|
||||
|
||||
def _load_custom_voice_profiles(self) -> None:
|
||||
"""Preload offline Qwen3-TTS custom voice profiles into speaker cache."""
|
||||
custom_voice_dir = getattr(self.config, "custom_voice_dir", None)
|
||||
if not custom_voice_dir:
|
||||
return
|
||||
|
||||
expected_dim = int(getattr(self.config.speaker_encoder_config, "enc_dim", 0) or 0)
|
||||
loaded = 0
|
||||
for profile in iter_custom_voice_profiles(custom_voice_dir, expected_model_type="qwen3_tts"):
|
||||
tensors = load_validated_profile_tensors(
|
||||
profile,
|
||||
expected_model_type="qwen3_tts",
|
||||
qwen3_embedding_dim=expected_dim,
|
||||
)
|
||||
if tensors is None:
|
||||
continue
|
||||
|
||||
speaker_embedding = tensors["speaker_embedding"].reshape(-1).contiguous().cpu()
|
||||
mode = str(profile.get("mode") or "xvec").lower()
|
||||
ref_code = tensors.get("ref_code")
|
||||
artifacts: dict[str, Any] = {
|
||||
"ref_spk_embedding": speaker_embedding,
|
||||
"ref_code": ref_code.contiguous().cpu() if isinstance(ref_code, torch.Tensor) else None,
|
||||
"icl_mode": mode == "icl",
|
||||
"ref_text": profile.get("ref_text"),
|
||||
}
|
||||
key = self._speaker_cache.make_cache_key(
|
||||
profile["voice_name_lower"],
|
||||
model_type=f"qwen3_tts_{mode}",
|
||||
created_at=0,
|
||||
)
|
||||
self._speaker_cache.put(key, artifacts)
|
||||
loaded += 1
|
||||
|
||||
if loaded:
|
||||
logger.info("Loaded %d precomputed Qwen3-TTS custom voice profile(s) from %s", loaded, custom_voice_dir)
|
||||
|
||||
# -------------------- vLLM required hooks --------------------
|
||||
|
||||
|
||||
@@ -35,7 +35,11 @@ from vllm.platforms import current_platform
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.utils.speaker_cache import get_speaker_cache
|
||||
from vllm_omni.utils.speaker_cache import (
|
||||
get_speaker_cache,
|
||||
iter_custom_voice_profiles,
|
||||
load_validated_profile_tensors,
|
||||
)
|
||||
|
||||
from .minicpm4_paged import MiniCPM4PagedForVoxCPM2, MiniCPM4PagedResidualLM
|
||||
from .voxcpm2_import_utils import import_voxcpm2_core
|
||||
@@ -97,6 +101,7 @@ def build_voxcpm2_prompt(
|
||||
ref_audio: Any | None = None,
|
||||
ref_sr: int | None = None,
|
||||
ref_text: str | None = None,
|
||||
voice_profile: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build a VoxCPM2 prefill prompt whose ``prompt_token_ids`` length matches
|
||||
the talker-side prefill length.
|
||||
@@ -110,7 +115,24 @@ def build_voxcpm2_prompt(
|
||||
ids = ids[1:]
|
||||
prefill_len = len(ids) + 1 # + audio_start
|
||||
additional: dict[str, Any] = {"text_token_ids": [ids]}
|
||||
if ref_audio is not None:
|
||||
if voice_profile is not None and ref_audio is None:
|
||||
mode = str(voice_profile.get("mode") or "reference").lower()
|
||||
ref_audio_feat_len = int(voice_profile.get("ref_audio_feat_len") or 0)
|
||||
audio_feat_len = int(voice_profile.get("audio_feat_len") or 0)
|
||||
prompt_text = voice_profile.get("prompt_text") or voice_profile.get("ref_text")
|
||||
additional["voice_profile"] = dict(voice_profile)
|
||||
|
||||
if mode in ("reference", "ref_continuation"):
|
||||
prefill_len += ref_audio_feat_len + 2 # ref_start / ref_end
|
||||
if mode in ("continuation", "ref_continuation"):
|
||||
if isinstance(prompt_text, str) and prompt_text:
|
||||
additional["prompt_text"] = [prompt_text]
|
||||
prompt_ids = split_multichar_chinese(tokenizer.encode(prompt_text, add_special_tokens=True), split_map)
|
||||
if prompt_ids and prompt_ids[0] == bos:
|
||||
prompt_ids = prompt_ids[1:]
|
||||
prefill_len += len(prompt_ids)
|
||||
prefill_len += audio_feat_len
|
||||
elif ref_audio is not None:
|
||||
vae = hf_config.audio_vae_config
|
||||
patch_samples = hf_config.patch_size * math.prod(vae["encoder_rates"])
|
||||
ref_len = math.ceil(math.ceil(len(ref_audio) * vae["sample_rate"] / ref_sr) / patch_samples)
|
||||
@@ -450,6 +472,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
|
||||
|
||||
# Speaker cache for ref_audio_feat across requests
|
||||
self._speaker_cache = get_speaker_cache()
|
||||
self._load_custom_voice_profiles()
|
||||
|
||||
self._perf = _PerfTimer(enabled=_ENABLE_PROFILING)
|
||||
self._cfm_buffers: _CFMBufferManager | None = None
|
||||
@@ -472,6 +495,51 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
|
||||
# one-shot by design: fires at most once per process to avoid log spam.
|
||||
self._active_state_warned = False
|
||||
|
||||
# -------------------- custom voice profiles --------------------
|
||||
|
||||
@staticmethod
|
||||
def _clone_prompt_cache(cache: dict[str, Any]) -> dict[str, Any]:
|
||||
cloned: dict[str, Any] = {}
|
||||
for key, value in cache.items():
|
||||
cloned[key] = value.clone() if isinstance(value, torch.Tensor) else value
|
||||
return cloned
|
||||
|
||||
def _load_custom_voice_profiles(self) -> None:
|
||||
"""Preload offline VoxCPM2 prompt caches into the shared speaker cache."""
|
||||
custom_voice_dir = getattr(self.config, "custom_voice_dir", None)
|
||||
if not custom_voice_dir:
|
||||
return
|
||||
|
||||
loaded = 0
|
||||
for profile in iter_custom_voice_profiles(custom_voice_dir, expected_model_type="voxcpm2"):
|
||||
tensors = load_validated_profile_tensors(profile, expected_model_type="voxcpm2")
|
||||
if tensors is None:
|
||||
continue
|
||||
|
||||
ref_audio_feat = tensors.get("ref_audio_feat")
|
||||
audio_feat = tensors.get("audio_feat")
|
||||
mode = str(profile.get("mode") or "").lower()
|
||||
|
||||
prompt_cache: dict[str, Any] = {"mode": mode}
|
||||
if ref_audio_feat is not None:
|
||||
prompt_cache["ref_audio_feat"] = ref_audio_feat.contiguous().cpu()
|
||||
if audio_feat is not None:
|
||||
prompt_cache["audio_feat"] = audio_feat.contiguous().cpu()
|
||||
prompt_text = profile.get("prompt_text") or profile.get("ref_text")
|
||||
if isinstance(prompt_text, str) and prompt_text:
|
||||
prompt_cache["prompt_text"] = prompt_text
|
||||
|
||||
key = self._speaker_cache.make_cache_key(
|
||||
profile["voice_name_lower"],
|
||||
model_type="voxcpm2",
|
||||
created_at=0,
|
||||
)
|
||||
self._speaker_cache.put(key, prompt_cache)
|
||||
loaded += 1
|
||||
|
||||
if loaded:
|
||||
logger.info("Loaded %d precomputed VoxCPM2 custom voice profile(s) from %s", loaded, custom_voice_dir)
|
||||
|
||||
@property
|
||||
def tts(self) -> nn.Module:
|
||||
return self._tts
|
||||
@@ -1161,6 +1229,10 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
|
||||
prompt_audio = prompt_audio[0] if prompt_audio else None
|
||||
if isinstance(prompt_text, list):
|
||||
prompt_text = prompt_text[0] if prompt_text else None
|
||||
voice_profile = info_dict.get("voice_profile")
|
||||
if isinstance(voice_profile, list):
|
||||
voice_profile = voice_profile[0] if voice_profile else None
|
||||
requires_precomputed_cache = isinstance(voice_profile, dict)
|
||||
|
||||
state.prompt_cache = None
|
||||
voice_name = info_dict.get("voice_name")
|
||||
@@ -1168,20 +1240,29 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
|
||||
voice_name = voice_name[0] if voice_name else None
|
||||
_created_at = int(info_dict.get("voice_created_at") or 0)
|
||||
|
||||
if ref_audio or (prompt_audio and prompt_text):
|
||||
# Check speaker cache for reference-only mode
|
||||
if voice_name and ref_audio and not prompt_audio:
|
||||
_cache_key = self._speaker_cache.make_cache_key(
|
||||
voice_name, model_type="voxcpm2", created_at=_created_at
|
||||
)
|
||||
cached = self._speaker_cache.get(_cache_key)
|
||||
if cached is not None:
|
||||
if voice_name:
|
||||
_cache_key = self._speaker_cache.make_cache_key(
|
||||
voice_name, model_type="voxcpm2", created_at=_created_at
|
||||
)
|
||||
cached = self._speaker_cache.get(_cache_key)
|
||||
if cached is not None:
|
||||
if "mode" in cached:
|
||||
state.prompt_cache = self._clone_prompt_cache(cached)
|
||||
elif "ref_audio_feat" in cached:
|
||||
state.prompt_cache = {
|
||||
"mode": "reference",
|
||||
"ref_audio_feat": cached["ref_audio_feat"].clone(),
|
||||
}
|
||||
logger.debug("Speaker cache HIT for VoxCPM2 speaker '%s'", voice_name)
|
||||
logger.debug("Speaker cache HIT for VoxCPM2 speaker '%s'", voice_name)
|
||||
|
||||
if state.prompt_cache is None and requires_precomputed_cache:
|
||||
requested_mode = voice_profile.get("mode") if isinstance(voice_profile, dict) else None
|
||||
raise ValueError(
|
||||
f"Precomputed VoxCPM2 voice '{voice_name}' was accepted by serving but is not loaded "
|
||||
f"in the model cache (voice_created_at={_created_at}, mode={requested_mode})"
|
||||
)
|
||||
|
||||
if state.prompt_cache is None and (ref_audio or (prompt_audio and prompt_text)):
|
||||
if state.prompt_cache is None:
|
||||
try:
|
||||
state.prompt_cache = self._build_prompt_cache(
|
||||
|
||||
Reference in new issue
Block a user