[TTS][SpeakerCacheManager] A global speaker cache manager for Voice Cloning (#2630)

Signed-off-by: JuanPZuluaga <juanz9312@gmal.com>
Co-authored-by: JuanPZuluaga <juanz9312@gmal.com>
This commit is contained in:
Juan Pablo ZuluagaandJuanPZuluaga authored and GitHub committed 2026-05-05 10:53:45 -04:00
1 parent a0918ce583
commit b64ab05d09
21 files changed
+1353 -1036

No files matched your search

@@ -41,6 +41,7 @@ from vllm_omni.model_executor.models.cosyvoice3.utils import (
extract_text_token,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.utils.speaker_cache import get_speaker_cache
logger = init_logger(__name__)
@@ -104,6 +105,7 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
providers=["CPUExecutionProvider"],
)
self._cached_model_dir = model_dir
self._speaker_cache = get_speaker_cache()
def _call_hf_processor(
self,
@@ -161,6 +163,28 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
)
device = "cpu"
# Speaker cache: skip 3 ONNX sessions on cache hit
voice_name = mm_kwargs.get("voice_name")
cache_key = None
if voice_name and isinstance(voice_name, str):
cache_key = self._speaker_cache.make_cache_key(
voice_name,
model_type="cosyvoice3",
created_at=int(mm_kwargs.get("voice_created_at") or 0),
)
cached = self._speaker_cache.get(cache_key)
if cached is not None:
ft = BatchFeature(
{
"input_ids": input_ids,
"speech_feat": cached["speech_feat"].clone(),
"speech_token": cached["speech_token"].clone(),
"speech_token_len": [cached["speech_token_len"].clone()],
"embedding": cached["embedding"].clone(),
}
)
return ft
speech_token, speech_token_len = extract_speech_token(audio, self.speech_tokenizer, device)
speech_feat, speech_feat_len = extract_speech_feat(audio, self.feat_extractor, device)
@@ -171,6 +195,18 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
embedding = extract_spk_embedding(audio, self.campplus_session, device)
# Cache the extracted artifacts for named speakers
if cache_key is not None:
self._speaker_cache.put(
cache_key,
{
"speech_feat": speech_feat.detach().cpu(),
"speech_token": speech_token.detach().cpu(),
"speech_token_len": speech_token_len.detach().cpu(),
"embedding": embedding.detach().cpu(),
},
)
ft = BatchFeature(
{
"input_ids": input_ids,
@@ -32,7 +32,7 @@ from vllm.model_executor.models.utils import PPMissingLayer, maybe_prefix
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.utils.voice_cache import VoiceEmbeddingCache
from vllm_omni.utils.speaker_cache import get_speaker_cache
from .configuration_fish_speech import FishSpeechConfig, FishSpeechFastARConfig, FishSpeechSlowARConfig
from .dac_encoder import _load_dac_codec, encode_reference_audio_codes
@@ -262,7 +262,7 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
self.register_buffer("_semantic_allowed_mask", semantic_mask, persistent=False)
# In-memory LRU cache for DAC-encoded reference audio codes.
self._voice_cache = VoiceEmbeddingCache()
self._speaker_cache = get_speaker_cache()
# Tokeniser (lazy).
self._tokenizer = None
@@ -539,37 +539,27 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
if not isinstance(ref_text, str) or not isinstance(text, str):
raise ValueError("Fish Speech structured voice clone requires string text and ref_text")
# --- Voice cache: reuse DAC codes for uploaded (named) voices ---
_voice_cache_key: str | None = None
_speaker_cache_key: tuple[str, str, int] | None = None
voice_name = info_dict.get("voice_name")
voice_created_at = info_dict.get("voice_created_at")
if isinstance(voice_name, str) and voice_name:
_created_at = float(voice_created_at) if voice_created_at is not None else 0.0
if _created_at <= 0:
logger.warning(
"Voice '%s' has no created_at timestamp; DAC code caching disabled for this request",
voice_name,
_speaker_cache_key = self._speaker_cache.make_cache_key(
voice_name,
model_type="fish_speech",
created_at=int(info_dict.get("voice_created_at") or 0),
)
_cached = self._speaker_cache.get(_speaker_cache_key)
if _cached is not None:
ref_codes_fq = _cached["ref_codes_fq"].to(
device=self.codebook_embeddings.weight.device,
dtype=torch.long,
)
else:
_voice_cache_key = self._voice_cache.make_cache_key(
voice_name,
xvec_only=False,
created_at=_created_at,
logger.debug("Speaker cache HIT for Fish Speech speaker '%s'", voice_name)
return self._apply_codebook_embeddings(
tokenizer,
text,
ref_text,
ref_codes_fq,
)
_cached = self._voice_cache.get(_voice_cache_key)
if _cached is not None:
ref_codes_fq = _cached["ref_codes_fq"].to(
device=self.codebook_embeddings.weight.device,
dtype=torch.long,
)
_voice_cache_key = None # hit → don't store again
logger.debug("Voice cache HIT for Fish Speech voice '%s'", voice_name)
return self._apply_codebook_embeddings(
tokenizer,
text,
ref_text,
ref_codes_fq,
)
if not isinstance(ref_audio_sr, int):
raise ValueError("Fish Speech structured voice clone requires integer ref_audio_sr")
@@ -590,12 +580,12 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
)
# Cache miss: store DAC codes for future reuse.
if _voice_cache_key is not None:
self._voice_cache.put(
_voice_cache_key,
if _speaker_cache_key is not None:
self._speaker_cache.put(
_speaker_cache_key,
{"ref_codes_fq": ref_codes_fq.detach().cpu()},
)
logger.debug("Voice cache STORE for Fish Speech voice '%s'", voice_name)
logger.debug("Speaker cache STORE for Fish Speech speaker '%s'", voice_name)
return self._apply_codebook_embeddings(tokenizer, text, ref_text, ref_codes_fq)
@@ -29,7 +29,7 @@ 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.audio import mel_filter_bank
from vllm_omni.utils.voice_cache import VoiceEmbeddingCache
from vllm_omni.utils.speaker_cache import get_speaker_cache
from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSSpeakerEncoderConfig, Qwen3TTSTalkerConfig
from .qwen3_tts_code_predictor_vllm import Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM
@@ -428,8 +428,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
self._tokenizer = None
self._speech_tokenizer: Qwen3TTSTokenizer | None = None
# In-memory LRU cache for voice extraction artifacts (Base voice clone).
self._voice_cache = VoiceEmbeddingCache()
self._speaker_cache = get_speaker_cache()
raw_subtalker_sampling = getattr(vllm_config.model_config, "subtalker_sampling_params", None)
self._subtalker_sampling_params: dict[str, Any] = (
dict(raw_subtalker_sampling) if isinstance(raw_subtalker_sampling, Mapping) else {}
@@ -1364,23 +1363,36 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
in_context_mode = not xvec_only
voice_clone_prompt = _normalize_voice_clone_prompt(info_dict.get("voice_clone_prompt"))
# Voice cache: only for uploaded voices (created_at > 0)
_voice_cache_key = None
# Speaker cache: only for uploaded (named) speakers
_speaker_cache_key = None
if voice_clone_prompt is None:
_speaker_list = info_dict.get("speaker")
if isinstance(_speaker_list, list) and _speaker_list:
_voice_name = str(_speaker_list[0]).lower()
_voice_created_at = float((info_dict.get("voice_created_at") or [0])[0])
if _voice_created_at > 0:
_voice_cache_key = self._voice_cache.make_cache_key(_voice_name, xvec_only, _voice_created_at)
_cached = self._voice_cache.get(_voice_cache_key) if _voice_cache_key is not None else None
# 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"
_voice_created_at = int((info_dict.get("voice_created_at") or [0])[0])
_speaker_cache_key = self._speaker_cache.make_cache_key(
_voice_name,
model_type=f"qwen3_tts_{_mode}",
created_at=_voice_created_at,
)
_cached = self._speaker_cache.get(_speaker_cache_key)
if _cached is not None:
# Transfer cached tensors to current device
ref_code_cached = _cached.get("ref_code")
ref_spk_embed_cached = _cached.get("ref_spk_embedding")
if isinstance(ref_code_cached, torch.Tensor):
ref_code_cached = ref_code_cached.to(device=input_ids.device)
if isinstance(ref_spk_embed_cached, torch.Tensor):
ref_spk_embed_cached = ref_spk_embed_cached.to(device=input_ids.device)
voice_clone_prompt = {
"ref_code": _cached.get("ref_code"),
"ref_spk_embedding": _cached.get("ref_spk_embedding"),
"ref_code": ref_code_cached,
"ref_spk_embedding": ref_spk_embed_cached,
"icl_mode": _cached.get("icl_mode"),
}
_voice_cache_key = None # hit -> don't store again
_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:
@@ -1432,9 +1444,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
speaker_embed = self._extract_speaker_embedding(wav_np, sr).view(1, 1, -1)
# Cache miss: store extraction result
if _voice_cache_key is not None and speaker_embed is not None:
self._voice_cache.put(
_voice_cache_key,
if _speaker_cache_key is not None and speaker_embed is not None:
self._speaker_cache.put(
_speaker_cache_key,
{
"ref_code": ref_code_prompt.detach().cpu()
if isinstance(ref_code_prompt, torch.Tensor)
@@ -34,6 +34,7 @@ from vllm.multimodal.audio import AudioResampler
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 .minicpm4_paged import MiniCPM4PagedForVoxCPM2, MiniCPM4PagedResidualLM
from .voxcpm2_import_utils import import_voxcpm2_core
@@ -446,6 +447,9 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
self._max_decode_steps = 2000
self._max_batch_size = getattr(vllm_config.scheduler_config, "max_num_seqs", 4)
# Speaker cache for ref_audio_feat across requests
self._speaker_cache = get_speaker_cache()
self._perf = _PerfTimer(enabled=_ENABLE_PROFILING)
self._cfm_buffers: _CFMBufferManager | None = None
self._enable_cuda_graph = True
@@ -1165,15 +1169,48 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
prompt_text = prompt_text[0] if prompt_text else None
state.prompt_cache = None
voice_name = info_dict.get("voice_name")
if isinstance(voice_name, list):
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):
try:
state.prompt_cache = self._build_prompt_cache(
ref_audio=ref_audio,
prompt_audio=prompt_audio,
prompt_text=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
)
except Exception as e:
logger.warning("build_prompt_cache failed: %s", e)
cached = self._speaker_cache.get(_cache_key)
if cached is not None:
state.prompt_cache = {
"mode": "reference",
"ref_audio_feat": cached["ref_audio_feat"].clone(),
}
logger.debug("Speaker cache HIT for VoxCPM2 speaker '%s'", voice_name)
if state.prompt_cache is None:
try:
state.prompt_cache = self._build_prompt_cache(
ref_audio=ref_audio,
prompt_audio=prompt_audio,
prompt_text=prompt_text,
)
if (
voice_name
and state.prompt_cache is not None
and state.prompt_cache.get("mode") == "reference"
and "ref_audio_feat" in state.prompt_cache
):
_key = self._speaker_cache.make_cache_key(
voice_name, model_type="voxcpm2", created_at=_created_at
)
self._speaker_cache.put(
_key, {"ref_audio_feat": state.prompt_cache["ref_audio_feat"].cpu()}
)
logger.debug("Speaker cache STORE for VoxCPM2 speaker '%s'", voice_name)
except Exception as e:
logger.warning("build_prompt_cache failed: %s; falling back to zero-shot", e)
state.prompt_cache = None
inputs = self._build_prefill_inputs(token_ids, dev, req_id)
tts = self.tts