Python
added qwen3 tts support
DeepBeepMeep0a281020f359
diff --git a/README.md b/README.mdindex 25d9d37..94341c6 100644--- a/README.md+++ b/README.md@@ -26,6 +26,21 @@ WanGP supports the Wan (and derived models), Hunyuan Video, Flux, Qwen, Z-Image,## 🔥 Latest Updates :+### January 23th 2026: WanGP v10.50, Music for your Hearts++WanGP Special *TTS* (Text To Speech) Release:++- **Heart Mula**: *Suno* quality song with lyrics on your local PC. You can generate up to 4 min of music.++- **Qwen 3 TTS**: you can either do *Voice Cloning*, *Generate a Custom Voice based on a Prompt* or use a *Predefined Voice*++- **TTS Features**:+ - **Early stop** : you can abort a gen, while still keeping what has been generated (will work only for TTS models which are *Autoregressive Models*, no need to ask that for Image/Video gens which are *Diffusion Models*)+ - **Specialized Prompt Enhancers**: if you enter the prompt in Heart Mula *"a song about AI generation"*, *WanGP Prompt Enhancer* will generate the corresponding masterpiece for you. Likewise you can enhance "A speech about AI generation" when using Qwen3 TTS or ChatterBox.+ - **Custom Output folder for Audio Gens**: you can now choose a different folder for the *Audio Outputs*+ - **Default Memory Profile for Audio Models**: TTS models can get very slow if you use profile 4 (being autoregressive models, they will need to load all the layers one per one to generate one single audio token then rinse & repeat). On the other hand, they dont't need as much VRAM, so you can now define a more agressive profile (3+ for instance)++### January 20th 2026: WanGP v10.43, The Cost Saver*GPUs are expensive, RAM is expensive, SSD are expensive, sadly we live now in a GPU & RAM poor.*diff --git a/defaults/heartmula_oss_3b.json b/defaults/heartmula_oss_3b.jsonindex 1b2d4bf..4c196c3 100644--- a/defaults/heartmula_oss_3b.json+++ b/defaults/heartmula_oss_3b.json@@ -4,16 +4,11 @@"architecture": "heartmula_oss_3b","description": "HeartMuLa open music generation conditioned on lyrics and tags.","URLs": [- "heartmula_oss_3b_bf16.safetensors",- "heartmula_oss_3b_quanto_bf16_int8.safetensors"+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/heartmula_oss_3b_bf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/heartmula_oss_3b_quanto_bf16_int8.safetensors"]},"prompt": "[Verse]\nMorning light through the window pane\nI hum a tune to chase the rain\nSteady steps on a quiet street\nHeart and rhythm, gentle beat","alt_prompt": "piano,happy,wedding",- "negative_prompt": "",- "audio_prompt_type": "",- "repeat_generation": 1,- "video_length": 0,- "num_inference_steps": 0,"temperature": 1.0}diff --git a/defaults/qwen3_tts_base.json b/defaults/qwen3_tts_base.jsonnew file mode 100644index 0000000..4c547c2--- /dev/null+++ b/defaults/qwen3_tts_base.json@@ -0,0 +1,13 @@+{+ "model": {+ "name": "TTS Qwen3 Base (12Hz) 1.7B",+ "architecture": "qwen3_tts_base",+ "description": "Qwen3 Base voice clone model with reference audio.",+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_base_bf16.safetensors"+ ]+ },+ "prompt": "I checked the schedule twice, and everything lines up.",+ "alt_prompt": "",+ "duration_seconds": 30+}diff --git a/defaults/qwen3_tts_customvoice.json b/defaults/qwen3_tts_customvoice.jsonnew file mode 100644index 0000000..c161528--- /dev/null+++ b/defaults/qwen3_tts_customvoice.json@@ -0,0 +1,14 @@+{+ "model": {+ "name": "TTS Qwen3 CustomVoice(12Hz) 1.7B",+ "architecture": "qwen3_tts_customvoice",+ "description": "Qwen3 CustomVoice with fixed speaker presets and optional instruction control.",+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_customvoice_bf16.safetensors"+ ]+ },+ "prompt": "The lights are already on, so we can start whenever you are ready.",+ "alt_prompt": "calm, friendly, slightly husky",+ "model_mode": "serena",+ "duration_seconds": 30+}diff --git a/defaults/qwen3_tts_voicedesign.json b/defaults/qwen3_tts_voicedesign.jsonnew file mode 100644index 0000000..45f6ef3--- /dev/null+++ b/defaults/qwen3_tts_voicedesign.json@@ -0,0 +1,14 @@+{+ "model": {+ "name": "TTS Qwen3 VoiceDesign (12Hz) 1.7B",+ "architecture": "qwen3_tts_voicedesign",+ "description": "Qwen3 VoiceDesign with natural language voice instructions.",+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_voicedesign_bf16.safetensors"+ ]+ },+ "prompt": "I wish you a good day. Please keep the door closed. I am afraid AI haters are going to come in. Oh I am so afraid !",+ "alt_prompt": "Male speaks in an incredulous tone, but with a hint of panic beginning to creep into your voice.",+ "model_mode": "auto",+ "duration_seconds": 30+}diff --git a/models/TTS/HeartMula/pipeline.py b/models/TTS/HeartMula/pipeline.pyindex 54b2b7c..885f6cc 100644--- a/models/TTS/HeartMula/pipeline.py+++ b/models/TTS/HeartMula/pipeline.py@@ -100,6 +100,7 @@ class HeartMuLaPipeline:)self.version = versionself._interrupt = False+ self._early_stop = Falseself._parallel_number = 8 + 1self._muq_dim = 512@@ -217,6 +218,12 @@ class HeartMuLaPipeline:def _abort_requested(self) -> bool:return bool(self._interrupt)+ def _early_stop_requested(self) -> bool:+ return bool(self._early_stop)++ def request_early_stop(self) -> None:+ self._early_stop = True+def _read_text_or_file(self, value: str, label: str) -> str:if os.path.isfile(value):with open(value, encoding="utf-8") as fp:@@ -319,6 +326,7 @@ class HeartMuLaPipeline:if curr_token is None:return Noneframes.append(curr_token[0:1,])+ early_stop_now = self._early_stop_requested()def _pad_audio_token(token: torch.Tensor):padded_token = (@@ -348,39 +356,42 @@ class HeartMuLaPipeline:progress_unit="seconds",)- for i in tqdm(range(max_audio_frames)):- if self._abort_requested():- return None- curr_token, curr_token_mask = _pad_audio_token(curr_token)- curr_token = self.mula.generate_frame(- tokens=curr_token,- tokens_mask=curr_token_mask,- input_pos=prompt_pos[..., -1:] + i + 1,- temperature=temperature,- topk=topk,- cfg_scale=cfg_scale,- continuous_segments=None,- starts=None,- )- if curr_token is None:- return None- if torch.any(curr_token[0:1, :] >= self.gen_config.audio_eos_id):- break- frames.append(curr_token[0:1,])- if i % 10 == 0 and callback is not None:- generated_ms = len(frames) * frame_duration_ms- generated_seconds_int = min(- progress_total_seconds,- generated_ms // 1000,- )- callback(- step_idx=generated_seconds_int - 1,- override_num_inference_steps=progress_total_seconds,- denoising_extra=(- f"{generated_seconds_int}s/{progress_total_seconds}s"- ),- progress_unit="second",+ if not early_stop_now:+ for i in tqdm(range(max_audio_frames)):+ if self._abort_requested():+ return None+ curr_token, curr_token_mask = _pad_audio_token(curr_token)+ curr_token = self.mula.generate_frame(+ tokens=curr_token,+ tokens_mask=curr_token_mask,+ input_pos=prompt_pos[..., -1:] + i + 1,+ temperature=temperature,+ topk=topk,+ cfg_scale=cfg_scale,+ continuous_segments=None,+ starts=None,)+ if curr_token is None:+ return None+ if torch.any(curr_token[0:1, :] >= self.gen_config.audio_eos_id):+ break+ frames.append(curr_token[0:1,])+ if self._early_stop_requested():+ break+ if i % 10 == 0 and callback is not None:+ generated_ms = len(frames) * frame_duration_ms+ generated_seconds_int = min(+ progress_total_seconds,+ generated_ms // 1000,+ )+ callback(+ step_idx=generated_seconds_int - 1,+ override_num_inference_steps=progress_total_seconds,+ denoising_extra=(+ f"{generated_seconds_int}s/{progress_total_seconds}s"+ ),+ progress_unit="second",+ )frames = torch.stack(frames).permute(1, 2, 0).squeeze(0)return {"frames": frames}finally:@@ -419,6 +430,7 @@ class HeartMuLaPipeline:**kwargs,):self._interrupt = False+ self._early_stop = Falseseed = kwargs.get("seed")if seed is not None:try:diff --git a/models/TTS/qwen3/__init__.py b/models/TTS/qwen3/__init__.pynew file mode 100644index 0000000..e919117--- /dev/null+++ b/models/TTS/qwen3/__init__.py@@ -0,0 +1,4 @@+from .inference.qwen3_tts_model import Qwen3TTSModel, VoiceClonePromptItem+from .inference.qwen3_tts_tokenizer import Qwen3TTSTokenizer++__all__ = ["Qwen3TTSModel", "VoiceClonePromptItem", "Qwen3TTSTokenizer"]diff --git a/models/TTS/qwen3/configs/qwen3_tts_base.json b/models/TTS/qwen3/configs/qwen3_tts_base.jsonnew file mode 100644index 0000000..81b57e8--- /dev/null+++ b/models/TTS/qwen3/configs/qwen3_tts_base.json@@ -0,0 +1,167 @@+{+ "architectures": [+ "Qwen3TTSForConditionalGeneration"+ ],+ "assistant_token_id": 77091,+ "im_end_token_id": 151645,+ "im_start_token_id": 151644,+ "tts_bos_token_id": 151672,+ "tts_eos_token_id": 151673,+ "tts_pad_token_id": 151671,+ "model_type": "qwen3_tts",+ "tokenizer_type": "qwen3_tts_tokenizer_12hz",+ "tts_model_size": "1b7",+ "tts_model_type": "base",+ "speaker_encoder_config": {+ "enc_dim": 2048,+ "sample_rate": 24000+ },+ "talker_config": {+ "attention_bias": false,+ "attention_dropout": 0,+ "code_predictor_config": {+ "_name_or_path": "",+ "add_cross_attention": false,+ "architectures": null,+ "attention_bias": false,+ "attention_dropout": 0,+ "bad_words_ids": null,+ "begin_suppress_tokens": null,+ "bos_token_id": null,+ "chunk_size_feed_forward": 0,+ "cross_attention_hidden_size": null,+ "decoder_start_token_id": null,+ "diversity_penalty": 0.0,+ "do_sample": false,+ "early_stopping": false,+ "encoder_no_repeat_ngram_size": 0,+ "eos_token_id": null,+ "exponential_decay_length_penalty": null,+ "finetuning_task": null,+ "forced_bos_token_id": null,+ "forced_eos_token_id": null,+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 1024,+ "id2label": {+ "0": "LABEL_0",+ "1": "LABEL_1"+ },+ "initializer_range": 0.02,+ "intermediate_size": 3072,+ "is_decoder": false,+ "is_encoder_decoder": false,+ "label2id": {+ "LABEL_0": 0,+ "LABEL_1": 1+ },+ "layer_types": [+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention"+ ],+ "length_penalty": 1.0,+ "max_length": 20,+ "max_position_embeddings": 65536,+ "max_window_layers": 28,+ "min_length": 0,+ "model_type": "qwen3_tts_talker_code_predictor",+ "no_repeat_ngram_size": 0,+ "num_attention_heads": 16,+ "num_beam_groups": 1,+ "num_beams": 1,+ "num_code_groups": 16,+ "num_hidden_layers": 5,+ "num_key_value_heads": 8,+ "num_return_sequences": 1,+ "output_attentions": false,+ "output_hidden_states": false,+ "output_scores": false,+ "pad_token_id": null,+ "prefix": null,+ "problem_type": null,+ "pruned_heads": {},+ "remove_invalid_values": false,+ "repetition_penalty": 1.0,+ "return_dict": true,+ "return_dict_in_generate": false,+ "rms_norm_eps": 1e-06,+ "rope_scaling": null,+ "rope_theta": 1000000,+ "sep_token_id": null,+ "sliding_window": null,+ "suppress_tokens": null,+ "task_specific_params": null,+ "temperature": 1.0,+ "tf_legacy_loss": false,+ "tie_encoder_decoder": false,+ "tie_word_embeddings": false,+ "tokenizer_class": null,+ "top_k": 50,+ "top_p": 1.0,+ "dtype": null,+ "torchscript": false,+ "typical_p": 1.0,+ "use_bfloat16": false,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 2048+ },+ "codec_bos_id": 2149,+ "codec_eos_token_id": 2150,+ "codec_think_id": 2154,+ "codec_language_id": {+ "chinese": 2055,+ "english": 2050,+ "german": 2053,+ "italian": 2070,+ "portuguese": 2071,+ "spanish": 2054,+ "japanese": 2058,+ "korean": 2064,+ "french": 2061,+ "russian": 2069+ },+ "codec_nothink_id": 2155,+ "codec_pad_id": 2148,+ "codec_think_bos_id": 2156,+ "codec_think_eos_id": 2157,+ "spk_id": {+ },+ "spk_is_dialect": {+ },+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 2048,+ "initializer_range": 0.02,+ "intermediate_size": 6144,+ "max_position_embeddings": 32768,+ "model_type": "qwen3_tts_talker",+ "num_attention_heads": 16,+ "num_code_groups": 16,+ "num_hidden_layers": 28,+ "num_key_value_heads": 8,+ "position_id_per_seconds": 13,+ "rms_norm_eps": 1e-06,+ "rope_scaling": {+ "interleaved": true,+ "mrope_section": [+ 24,+ 20,+ 20+ ],+ "rope_type": "default",+ "type": "default"+ },+ "rope_theta": 1000000,+ "sliding_window": null,+ "text_hidden_size": 2048,+ "text_vocab_size": 151936,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 3072+ },+ "transformers_version": "4.57.3"+}diff --git a/models/TTS/qwen3/configs/qwen3_tts_customvoice.json b/models/TTS/qwen3/configs/qwen3_tts_customvoice.jsonnew file mode 100644index 0000000..95d74b2--- /dev/null+++ b/models/TTS/qwen3/configs/qwen3_tts_customvoice.json@@ -0,0 +1,183 @@+{+ "architectures": [+ "Qwen3TTSForConditionalGeneration"+ ],+ "assistant_token_id": 77091,+ "im_end_token_id": 151645,+ "im_start_token_id": 151644,+ "tts_bos_token_id": 151672,+ "tts_eos_token_id": 151673,+ "tts_pad_token_id": 151671,+ "model_type": "qwen3_tts",+ "tokenizer_type": "qwen3_tts_tokenizer_12hz",+ "tts_model_size": "1b7",+ "tts_model_type": "custom_voice",+ "talker_config": {+ "attention_bias": false,+ "attention_dropout": 0,+ "code_predictor_config": {+ "_name_or_path": "",+ "add_cross_attention": false,+ "architectures": null,+ "attention_bias": false,+ "attention_dropout": 0,+ "bad_words_ids": null,+ "begin_suppress_tokens": null,+ "bos_token_id": null,+ "chunk_size_feed_forward": 0,+ "cross_attention_hidden_size": null,+ "decoder_start_token_id": null,+ "diversity_penalty": 0.0,+ "do_sample": false,+ "early_stopping": false,+ "encoder_no_repeat_ngram_size": 0,+ "eos_token_id": null,+ "exponential_decay_length_penalty": null,+ "finetuning_task": null,+ "forced_bos_token_id": null,+ "forced_eos_token_id": null,+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 1024,+ "id2label": {+ "0": "LABEL_0",+ "1": "LABEL_1"+ },+ "initializer_range": 0.02,+ "intermediate_size": 3072,+ "is_decoder": false,+ "is_encoder_decoder": false,+ "label2id": {+ "LABEL_0": 0,+ "LABEL_1": 1+ },+ "layer_types": [+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention"+ ],+ "length_penalty": 1.0,+ "max_length": 20,+ "max_position_embeddings": 65536,+ "max_window_layers": 28,+ "min_length": 0,+ "model_type": "qwen3_tts_talker_code_predictor",+ "no_repeat_ngram_size": 0,+ "num_attention_heads": 16,+ "num_beam_groups": 1,+ "num_beams": 1,+ "num_code_groups": 16,+ "num_hidden_layers": 5,+ "num_key_value_heads": 8,+ "num_return_sequences": 1,+ "output_attentions": false,+ "output_hidden_states": false,+ "output_scores": false,+ "pad_token_id": null,+ "prefix": null,+ "problem_type": null,+ "pruned_heads": {},+ "remove_invalid_values": false,+ "repetition_penalty": 1.0,+ "return_dict": true,+ "return_dict_in_generate": false,+ "rms_norm_eps": 1e-06,+ "rope_scaling": null,+ "rope_theta": 1000000,+ "sep_token_id": null,+ "sliding_window": null,+ "suppress_tokens": null,+ "task_specific_params": null,+ "temperature": 1.0,+ "tf_legacy_loss": false,+ "tie_encoder_decoder": false,+ "tie_word_embeddings": false,+ "tokenizer_class": null,+ "top_k": 50,+ "top_p": 1.0,+ "dtype": null,+ "torchscript": false,+ "typical_p": 1.0,+ "use_bfloat16": false,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 2048+ },+ "codec_bos_id": 2149,+ "codec_eos_token_id": 2150,+ "codec_think_id": 2154,+ "codec_language_id": {+ "chinese": 2055,+ "english": 2050,+ "german": 2053,+ "italian": 2070,+ "portuguese": 2071,+ "spanish": 2054,+ "japanese": 2058,+ "korean": 2064,+ "french": 2061,+ "russian": 2069,+ "beijing_dialect": 2074,+ "sichuan_dialect": 2062+ },+ "codec_nothink_id": 2155,+ "codec_pad_id": 2148,+ "codec_think_bos_id": 2156,+ "codec_think_eos_id": 2157,+ "spk_id": {+ "serena": 3066,+ "vivian": 3065,+ "uncle_fu": 3010,+ "ryan": 3061,+ "aiden": 2861,+ "ono_anna": 2873,+ "sohee": 2864,+ "eric": 2875,+ "dylan": 2878+ },+ "spk_is_dialect": {+ "serena": false,+ "vivian": false,+ "uncle_fu": false,+ "ryan": false,+ "aiden": false,+ "ono_anna": false,+ "sohee": false,+ "eric": "sichuan_dialect",+ "dylan": "beijing_dialect"+ },+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 2048,+ "initializer_range": 0.02,+ "intermediate_size": 6144,+ "max_position_embeddings": 32768,+ "model_type": "qwen3_tts_talker",+ "num_attention_heads": 16,+ "num_code_groups": 16,+ "num_hidden_layers": 28,+ "num_key_value_heads": 8,+ "position_id_per_seconds": 13,+ "rms_norm_eps": 1e-06,+ "rope_scaling": {+ "interleaved": true,+ "mrope_section": [+ 24,+ 20,+ 20+ ],+ "rope_type": "default",+ "type": "default"+ },+ "rope_theta": 1000000,+ "sliding_window": null,+ "text_hidden_size": 2048,+ "text_vocab_size": 151936,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 3072+ },+ "transformers_version": "4.57.3"+}diff --git a/models/TTS/qwen3/configs/qwen3_tts_generation_config.json b/models/TTS/qwen3/configs/qwen3_tts_generation_config.jsonnew file mode 100644index 0000000..1872b16--- /dev/null+++ b/models/TTS/qwen3/configs/qwen3_tts_generation_config.json@@ -0,0 +1,12 @@+{+ "do_sample": true,+ "repetition_penalty": 1.05,+ "temperature": 0.9,+ "top_p": 1.0,+ "top_k": 50,+ "subtalker_dosample": true,+ "subtalker_temperature": 0.9,+ "subtalker_top_p": 1.0,+ "subtalker_top_k": 50,+ "max_new_tokens": 8192+}\ No newline at end of filediff --git a/models/TTS/qwen3/configs/qwen3_tts_voicedesign.json b/models/TTS/qwen3/configs/qwen3_tts_voicedesign.jsonnew file mode 100644index 0000000..2c2c027--- /dev/null+++ b/models/TTS/qwen3/configs/qwen3_tts_voicedesign.json@@ -0,0 +1,163 @@+{+ "architectures": [+ "Qwen3TTSForConditionalGeneration"+ ],+ "assistant_token_id": 77091,+ "im_end_token_id": 151645,+ "im_start_token_id": 151644,+ "tts_bos_token_id": 151672,+ "tts_eos_token_id": 151673,+ "tts_pad_token_id": 151671,+ "model_type": "qwen3_tts",+ "tokenizer_type": "qwen3_tts_tokenizer_12hz",+ "tts_model_size": "1b7",+ "tts_model_type": "voice_design",+ "talker_config": {+ "attention_bias": false,+ "attention_dropout": 0,+ "code_predictor_config": {+ "_name_or_path": "",+ "add_cross_attention": false,+ "architectures": null,+ "attention_bias": false,+ "attention_dropout": 0,+ "bad_words_ids": null,+ "begin_suppress_tokens": null,+ "bos_token_id": null,+ "chunk_size_feed_forward": 0,+ "cross_attention_hidden_size": null,+ "decoder_start_token_id": null,+ "diversity_penalty": 0.0,+ "do_sample": false,+ "early_stopping": false,+ "encoder_no_repeat_ngram_size": 0,+ "eos_token_id": null,+ "exponential_decay_length_penalty": null,+ "finetuning_task": null,+ "forced_bos_token_id": null,+ "forced_eos_token_id": null,+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 1024,+ "id2label": {+ "0": "LABEL_0",+ "1": "LABEL_1"+ },+ "initializer_range": 0.02,+ "intermediate_size": 3072,+ "is_decoder": false,+ "is_encoder_decoder": false,+ "label2id": {+ "LABEL_0": 0,+ "LABEL_1": 1+ },+ "layer_types": [+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention",+ "full_attention"+ ],+ "length_penalty": 1.0,+ "max_length": 20,+ "max_position_embeddings": 65536,+ "max_window_layers": 28,+ "min_length": 0,+ "model_type": "qwen3_tts_talker_code_predictor",+ "no_repeat_ngram_size": 0,+ "num_attention_heads": 16,+ "num_beam_groups": 1,+ "num_beams": 1,+ "num_code_groups": 16,+ "num_hidden_layers": 5,+ "num_key_value_heads": 8,+ "num_return_sequences": 1,+ "output_attentions": false,+ "output_hidden_states": false,+ "output_scores": false,+ "pad_token_id": null,+ "prefix": null,+ "problem_type": null,+ "pruned_heads": {},+ "remove_invalid_values": false,+ "repetition_penalty": 1.0,+ "return_dict": true,+ "return_dict_in_generate": false,+ "rms_norm_eps": 1e-06,+ "rope_scaling": null,+ "rope_theta": 1000000,+ "sep_token_id": null,+ "sliding_window": null,+ "suppress_tokens": null,+ "task_specific_params": null,+ "temperature": 1.0,+ "tf_legacy_loss": false,+ "tie_encoder_decoder": false,+ "tie_word_embeddings": false,+ "tokenizer_class": null,+ "top_k": 50,+ "top_p": 1.0,+ "dtype": null,+ "torchscript": false,+ "typical_p": 1.0,+ "use_bfloat16": false,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 2048+ },+ "codec_bos_id": 2149,+ "codec_eos_token_id": 2150,+ "codec_think_id": 2154,+ "codec_language_id": {+ "chinese": 2055,+ "english": 2050,+ "german": 2053,+ "italian": 2070,+ "portuguese": 2071,+ "spanish": 2054,+ "japanese": 2058,+ "korean": 2064,+ "french": 2061,+ "russian": 2069+ },+ "codec_nothink_id": 2155,+ "codec_pad_id": 2148,+ "codec_think_bos_id": 2156,+ "codec_think_eos_id": 2157,+ "spk_id": {+ },+ "spk_is_dialect": {+ },+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 2048,+ "initializer_range": 0.02,+ "intermediate_size": 6144,+ "max_position_embeddings": 32768,+ "model_type": "qwen3_tts_talker",+ "num_attention_heads": 16,+ "num_code_groups": 16,+ "num_hidden_layers": 28,+ "num_key_value_heads": 8,+ "position_id_per_seconds": 13,+ "rms_norm_eps": 1e-06,+ "rope_scaling": {+ "interleaved": true,+ "mrope_section": [+ 24,+ 20,+ 20+ ],+ "rope_type": "default",+ "type": "default"+ },+ "rope_theta": 1000000,+ "sliding_window": null,+ "text_hidden_size": 2048,+ "text_vocab_size": 151936,+ "use_cache": true,+ "use_sliding_window": false,+ "vocab_size": 3072+ },+ "transformers_version": "4.57.3"+}diff --git a/models/TTS/qwen3/core/__init__.py b/models/TTS/qwen3/core/__init__.pynew file mode 100644index 0000000..a29cf0c--- /dev/null+++ b/models/TTS/qwen3/core/__init__.py@@ -0,0 +1,2 @@+from .tokenizer_12hz.configuration_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Config+from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Modeldiff --git a/models/TTS/qwen3/core/models/__init__.py b/models/TTS/qwen3/core/models/__init__.pynew file mode 100644index 0000000..26e3d92--- /dev/null+++ b/models/TTS/qwen3/core/models/__init__.py@@ -0,0 +1,5 @@+from .configuration_qwen3_tts import Qwen3TTSConfig+from .modeling_qwen3_tts import Qwen3TTSForConditionalGeneration+from .processing_qwen3_tts import Qwen3TTSProcessor++__all__ = ["Qwen3TTSConfig", "Qwen3TTSForConditionalGeneration", "Qwen3TTSProcessor"]diff --git a/models/TTS/qwen3/core/models/configuration_qwen3_tts.py b/models/TTS/qwen3/core/models/configuration_qwen3_tts.pynew file mode 100644index 0000000..7961606--- /dev/null+++ b/models/TTS/qwen3/core/models/configuration_qwen3_tts.py@@ -0,0 +1,504 @@+# coding=utf-8+# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+from transformers.configuration_utils import PretrainedConfig, layer_type_validation+from transformers.modeling_rope_utils import rope_config_validation+from transformers.utils import logging++logger = logging.get_logger(__name__)+++class Qwen3TTSSpeakerEncoderConfig(PretrainedConfig):+ r"""+ This is the configuration class to store the configuration of a [`Qwen3TTSSpeakerEncoder`].+ It is used to instantiate a Qwen3TTS speaker encoder model according to the specified arguments, defining the model+ architecture. The architecture is based on the ECAPA-TDNN model.++ Args:+ mel_dim (`int`, *optional*, defaults to 128):+ The dimension of the input mel-spectrogram.+ enc_dim (`int`, *optional*, defaults to 192):+ The dimension of the final speaker embedding.+ enc_channels (`list[int]`, *optional*, defaults to `[512, 512, 512, 512, 1536]`):+ A list of output channels for each TDNN/SERes2Net layer in the encoder. The first channel size is for the initial TDNN layer,+ the intermediate ones for the `SqueezeExcitationRes2NetBlock` layers, and the last one for the multi-layer feature aggregation.+ enc_kernel_sizes (`list[int]`, *optional*, defaults to `[5, 3, 3, 3, 1]`):+ A list of kernel sizes for each layer in the encoder, corresponding to `enc_channels`.+ enc_dilations (`list[int]`, *optional*, defaults to `[1, 2, 3, 4, 1]`):+ A list of dilations for each layer in the encoder, corresponding to `enc_channels`.+ enc_attention_channels (`int`, *optional*, defaults to 128):+ The number of attention channels in the `AttentiveStatisticsPooling` layer.+ enc_res2net_scale (`int`, *optional*,defaults to 8):+ The scale of the `Res2NetBlock` in the encoder.+ enc_se_channels (`int`, *optional*, defaults to 128):+ The number of channels in the squeeze part of the `SqueezeExcitationBlock`.+ """+ def __init__(+ self,+ mel_dim=128,+ enc_dim=1024,+ enc_channels=[512, 512, 512, 512, 1536],+ enc_kernel_sizes=[5, 3, 3, 3, 1],+ enc_dilations=[1, 2, 3, 4, 1],+ enc_attention_channels=128,+ enc_res2net_scale=8,+ enc_se_channels=128,+ sample_rate=24000,+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.mel_dim = mel_dim+ self.enc_dim = enc_dim+ self.enc_channels = enc_channels+ self.enc_kernel_sizes = enc_kernel_sizes+ self.enc_dilations = enc_dilations+ self.enc_attention_channels = enc_attention_channels+ self.enc_res2net_scale = enc_res2net_scale+ self.enc_se_channels = enc_se_channels+ self.sample_rate = sample_rate+++class Qwen3TTSTalkerCodePredictorConfig(PretrainedConfig):+ r"""+ This is the configuration class to store the configuration of a [`Qwen3TTSTalkerCodePredictorModel`]. It is used to instantiate a+ Qwen3TTSTalkerCodePredictor model according to the specified arguments, defining the model architecture.++ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the+ documentation from [`PretrainedConfig`] for more information.+++ Args:+ vocab_size (`int`, *optional*, defaults to 151936):+ Vocabulary size of the Qwen3TTSTalkerCodePredictor model. Defines the number of different tokens that can be represented by the+ `inputs_ids` passed when calling [`Qwen3TTSTalkerCodePredictorModel`]+ hidden_size (`int`, *optional*, defaults to 4096):+ Dimension of the hidden representations.+ intermediate_size (`int`, *optional*, defaults to 22016):+ Dimension of the MLP representations.+ num_hidden_layers (`int`, *optional*, defaults to 32):+ Number of hidden layers in the Transformer encoder.+ num_attention_heads (`int`, *optional*, defaults to 32):+ Number of attention heads for each attention layer in the Transformer encoder.+ num_key_value_heads (`int`, *optional*, defaults to 32):+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed+ by meanpooling all the original heads within that group. For more details, check out [this+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.+ head_dim (`int`, *optional*, defaults to 128):+ The attention head dimension.+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):+ The non-linear activation function (function or string) in the decoder.+ max_position_embeddings (`int`, *optional*, defaults to 32768):+ The maximum sequence length that this model might ever be used with.+ initializer_range (`float`, *optional*, defaults to 0.02):+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):+ The epsilon used by the rms normalization layers.+ use_cache (`bool`, *optional*, defaults to `True`):+ Whether or not the model should return the last key/values attentions (not used by all models). Only+ relevant if `config.is_decoder=True`.+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):+ Whether the model's input and output word embeddings should be tied.+ rope_theta (`float`, *optional*, defaults to 10000.0):+ The base period of the RoPE embeddings.+ rope_scaling (`Dict`, *optional*):+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value+ accordingly.+ Expected contents:+ `rope_type` (`str`):+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',+ 'llama3'], with 'default' being the original RoPE implementation.+ `factor` (`float`, *optional*):+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *+ original maximum pre-trained length.+ `original_max_position_embeddings` (`int`, *optional*):+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during+ pretraining.+ `attention_factor` (`float`, *optional*):+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention+ computation. If unspecified, it defaults to value recommended by the implementation, using the+ `factor` field to infer the suggested value.+ `beta_fast` (`float`, *optional*):+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear+ ramp function. If unspecified, it defaults to 32.+ `beta_slow` (`float`, *optional*):+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear+ ramp function. If unspecified, it defaults to 1.+ `short_factor` (`list[float]`, *optional*):+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden+ size divided by the number of attention heads divided by 2+ `long_factor` (`list[float]`, *optional*):+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden+ size divided by the number of attention heads divided by 2+ `low_freq_factor` (`float`, *optional*):+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE+ `high_freq_factor` (`float`, *optional*):+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):+ Whether to use a bias in the query, key, value and output projection layers during self-attention.+ use_sliding_window (`bool`, *optional*, defaults to `False`):+ Whether to use sliding window attention.+ sliding_window (`int`, *optional*, defaults to 4096):+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.+ max_window_layers (`int`, *optional*, defaults to 28):+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any+ additional layer afterwards will use SWA (Sliding Window Attention).+ layer_types (`list`, *optional*):+ Attention pattern for each layer.+ attention_dropout (`float`, *optional*, defaults to 0.0):+ The dropout ratio for the attention probabilities.++ """++ model_type = "qwen3_tts_talker_code_predictor"+ keys_to_ignore_at_inference = ["past_key_values"]++ # Default tensor parallel plan for base model `Qwen3TTSTalkerCodePredictor`+ base_model_tp_plan = {+ "layers.*.self_attn.q_proj": "colwise",+ "layers.*.self_attn.k_proj": "colwise",+ "layers.*.self_attn.v_proj": "colwise",+ "layers.*.self_attn.o_proj": "rowwise",+ "layers.*.mlp.gate_proj": "colwise",+ "layers.*.mlp.up_proj": "colwise",+ "layers.*.mlp.down_proj": "rowwise",+ }+ base_model_pp_plan = {+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),+ "norm": (["hidden_states"], ["hidden_states"]),+ }++ def __init__(+ self,+ vocab_size=2048,+ hidden_size=1024,+ intermediate_size=3072,+ num_hidden_layers=5,+ num_attention_heads=16,+ num_key_value_heads=8,+ head_dim=128,+ hidden_act="silu",+ max_position_embeddings=32768,+ initializer_range=0.02,+ rms_norm_eps=0.000001,+ use_cache=True,+ tie_word_embeddings=False,+ rope_theta=10000,+ rope_scaling=None,+ attention_bias=False,+ use_sliding_window=False,+ sliding_window=4096,+ max_window_layers=28,+ layer_types=None,+ attention_dropout=0,+ num_code_groups=32,+ **kwargs,+ ):+ super().__init__(+ tie_word_embeddings=tie_word_embeddings,+ **kwargs,+ )+ self.vocab_size = vocab_size+ self.max_position_embeddings = max_position_embeddings+ self.hidden_size = hidden_size+ self.intermediate_size = intermediate_size+ self.num_hidden_layers = num_hidden_layers+ self.num_attention_heads = num_attention_heads+ self.use_sliding_window = use_sliding_window+ self.sliding_window = sliding_window if self.use_sliding_window else None+ self.max_window_layers = max_window_layers++ # for backward compatibility+ if num_key_value_heads is None:+ num_key_value_heads = num_attention_heads++ self.num_key_value_heads = num_key_value_heads+ self.head_dim = head_dim+ self.hidden_act = hidden_act+ self.initializer_range = initializer_range+ self.rms_norm_eps = rms_norm_eps+ self.use_cache = use_cache+ self.rope_theta = rope_theta+ self.rope_scaling = rope_scaling+ self.attention_bias = attention_bias+ self.attention_dropout = attention_dropout+ # Validate the correctness of rotary position embeddings parameters+ # BC: if there is a 'type' field, move it to 'rope_type'.+ if self.rope_scaling is not None and "type" in self.rope_scaling:+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]+ rope_config_validation(self)++ self.layer_types = layer_types+ if self.layer_types is None:+ self.layer_types = [+ "sliding_attention"+ if self.sliding_window is not None and i >= self.max_window_layers+ else "full_attention"+ for i in range(self.num_hidden_layers)+ ]+ layer_type_validation(self.layer_types)+ self.num_code_groups = num_code_groups+++class Qwen3TTSTalkerConfig(PretrainedConfig):+ r"""+ This is the configuration class to store the configuration of a [`Qwen3TTSTalkerModel`]. It is used to instantiate a+ Qwen3TTSTalker model according to the specified arguments, defining the model architecture.++ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the+ documentation from [`PretrainedConfig`] for more information.+++ Args:+ vocab_size (`int`, *optional*, defaults to 151936):+ Vocabulary size of the Qwen3TTSTalker model. Defines the number of different tokens that can be represented by the+ `inputs_ids` passed when calling [`Qwen3TTSTalkerModel`]+ hidden_size (`int`, *optional*, defaults to 2048):+ Dimension of the hidden representations.+ intermediate_size (`int`, *optional*, defaults to 6144):+ Dimension of the MLP representations.+ num_hidden_layers (`int`, *optional*, defaults to 24):+ Number of hidden layers in the Transformer encoder.+ num_attention_heads (`int`, *optional*, defaults to 32):+ Number of attention heads for each attention layer in the Transformer encoder.+ num_key_value_heads (`int`, *optional*, defaults to 4):+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed+ by meanpooling all the original heads within that group. For more details, check out [this+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.++ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):+ The non-linear activation function (function or string) in the decoder.+ max_position_embeddings (`int`, *optional*, defaults to 32768):+ The maximum sequence length that this model might ever be used with.+ initializer_range (`float`, *optional*, defaults to 0.02):+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):+ The epsilon used by the rms normalization layers.+ use_cache (`bool`, *optional*, defaults to `True`):+ Whether or not the model should return the last key/values attentions (not used by all models). Only+ relevant if `config.is_decoder=True`.+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):+ Whether the model's input and output word embeddings should be tied.+ rope_theta (`float`, *optional*, defaults to 10000.0):+ The base period of the RoPE embeddings.+ rope_scaling (`Dict`, *optional*):+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value+ accordingly.+ Expected contents:+ `rope_type` (`str`):+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',+ 'llama3'], with 'default' being the original RoPE implementation.+ `factor` (`float`, *optional*):+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *+ original maximum pre-trained length.+ `original_max_position_embeddings` (`int`, *optional*):+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during+ pretraining.+ `attention_factor` (`float`, *optional*):+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention+ computation. If unspecified, it defaults to value recommended by the implementation, using the+ `factor` field to infer the suggested value.+ `beta_fast` (`float`, *optional*):+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear+ ramp function. If unspecified, it defaults to 32.+ `beta_slow` (`float`, *optional*):+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear+ ramp function. If unspecified, it defaults to 1.+ `short_factor` (`list[float]`, *optional*):+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden+ size divided by the number of attention heads divided by 2+ `long_factor` (`list[float]`, *optional*):+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden+ size divided by the number of attention heads divided by 2+ `low_freq_factor` (`float`, *optional*):+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE+ `high_freq_factor` (`float`, *optional*):+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):+ Whether to use a bias in the query, key, value and output projection layers during self-attention.+ use_sliding_window (`bool`, *optional*, defaults to `False`):+ Whether to use sliding window attention.+ sliding_window (`int`, *optional*, defaults to 4096):+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.+ attention_dropout (`float`, *optional*, defaults to 0.0):+ The dropout ratio for the attention probabilities.+ """++ model_type = "qwen3_tts_talker"+ keys_to_ignore_at_inference = ["past_key_values"]++ # Default tensor parallel plan for base model `Qwen3TTSTalker`+ base_model_tp_plan = {+ "layers.*.self_attn.q_proj": "colwise",+ "layers.*.self_attn.k_proj": "colwise",+ "layers.*.self_attn.v_proj": "colwise",+ "layers.*.self_attn.o_proj": "rowwise",+ "layers.*.mlp.gate_proj": "colwise",+ "layers.*.mlp.up_proj": "colwise",+ "layers.*.mlp.down_proj": "rowwise",+ }+ base_model_pp_plan = {+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),+ "norm": (["hidden_states"], ["hidden_states"]),+ }+ sub_configs = {"code_predictor_config": Qwen3TTSTalkerCodePredictorConfig}++ def __init__(+ self,+ code_predictor_config=None,+ vocab_size=3072,+ hidden_size=1024,+ intermediate_size=2048,+ num_hidden_layers=20,+ num_attention_heads=16,+ num_key_value_heads=2,+ hidden_act="silu",+ max_position_embeddings=32768,+ initializer_range=0.02,+ rms_norm_eps=0.000001,+ use_cache=True,+ tie_word_embeddings=False,+ rope_theta=10000,+ rope_scaling=None,+ attention_bias=False,+ use_sliding_window=False,+ sliding_window=4096,+ attention_dropout=0,+ num_code_groups=32,+ text_hidden_size=2048,+ codec_eos_token_id=4198,+ codec_think_id=4202,+ codec_nothink_id=4203,+ codec_think_bos_id=4204,+ codec_think_eos_id=4205,+ codec_pad_id=4196,+ codec_bos_id=4197,+ spk_id=None,+ spk_is_dialect=None,+ codec_language_id=None,+ **kwargs,+ ):+ super().__init__(+ tie_word_embeddings=tie_word_embeddings,+ **kwargs,+ )+ self.vocab_size = vocab_size+ self.max_position_embeddings = max_position_embeddings+ self.hidden_size = hidden_size+ self.intermediate_size = intermediate_size+ self.num_hidden_layers = num_hidden_layers+ self.num_attention_heads = num_attention_heads+ self.use_sliding_window = use_sliding_window+ self.sliding_window = sliding_window if use_sliding_window else None++ self.num_key_value_heads = num_key_value_heads+ self.hidden_act = hidden_act+ self.initializer_range = initializer_range+ self.rms_norm_eps = rms_norm_eps+ self.use_cache = use_cache+ self.rope_theta = rope_theta+ self.rope_scaling = rope_scaling+ self.attention_bias = attention_bias+ self.attention_dropout = attention_dropout+ # Validate the correctness of rotary position embeddings parameters+ # BC: if there is a 'type' field, move it to 'rope_type'.+ if self.rope_scaling is not None and "type" in self.rope_scaling:+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]++ if code_predictor_config is None:+ code_predictor_config = {}+ self.code_predictor_config = Qwen3TTSTalkerCodePredictorConfig()+ logger.info("code_predictor_config is None. Initializing code_predictor model with default values")+ elif isinstance(code_predictor_config, Qwen3TTSTalkerCodePredictorConfig):+ self.code_predictor_config = code_predictor_config+ else:+ self.code_predictor_config = Qwen3TTSTalkerCodePredictorConfig(**code_predictor_config)+ self.num_code_groups = num_code_groups+ self.text_hidden_size = text_hidden_size+ self.codec_eos_token_id = codec_eos_token_id+ self.codec_think_id = codec_think_id+ self.codec_language_id = codec_language_id+ self.codec_nothink_id = codec_nothink_id+ self.codec_think_bos_id = codec_think_bos_id+ self.codec_think_eos_id = codec_think_eos_id+ self.codec_pad_id = codec_pad_id+ self.codec_bos_id = codec_bos_id+ self.spk_id = spk_id+ self.spk_is_dialect = spk_is_dialect+++class Qwen3TTSConfig(PretrainedConfig):+ """+ This is the configuration class to store the configuration of a [`Qwen3TTSForConditionalGeneration`].+ """++ model_type = "qwen3_tts"+ sub_configs = {+ "talker_config": Qwen3TTSTalkerConfig,+ "speaker_encoder_config": Qwen3TTSSpeakerEncoderConfig,+ }++ def __init__(+ self,+ talker_config=None,+ speaker_encoder_config=None,+ tokenizer_type=None,+ tts_model_size=None,+ tts_model_type=None,+ im_start_token_id=151644,+ im_end_token_id=151645,+ tts_pad_token_id=151671,+ tts_bos_token_id=151672,+ tts_eos_token_id=151673,+ **kwargs,+ ):+ super().__init__(**kwargs)++ if talker_config is None:+ talker_config = {}+ logger.info("talker_config is None. Initializing talker model with default values")+ if speaker_encoder_config is None:+ speaker_encoder_config = {}+ logger.info("speaker_encoder_config is None. Initializing talker model with default values")++ self.talker_config = Qwen3TTSTalkerConfig(**talker_config)+ self.speaker_encoder_config = Qwen3TTSSpeakerEncoderConfig(**speaker_encoder_config)++ self.tokenizer_type = tokenizer_type+ self.tts_model_size = tts_model_size+ self.tts_model_type = tts_model_type++ self.im_start_token_id = im_start_token_id+ self.im_end_token_id = im_end_token_id+ self.tts_pad_token_id = tts_pad_token_id+ self.tts_bos_token_id = tts_bos_token_id+ self.tts_eos_token_id = tts_eos_token_id+++__all__ = ["Qwen3TTSConfig", "Qwen3TTSTalkerConfig", "Qwen3TTSSpeakerEncoderConfig"]diff --git a/models/TTS/qwen3/core/models/modeling_qwen3_tts.py b/models/TTS/qwen3/core/models/modeling_qwen3_tts.pynew file mode 100644index 0000000..49eb473--- /dev/null+++ b/models/TTS/qwen3/core/models/modeling_qwen3_tts.py@@ -0,0 +1,2334 @@+# coding=utf-8+# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""PyTorch Qwen3TTS model."""++import json+import os+from dataclasses import dataclass+from typing import Callable, Optional++import huggingface_hub+import torch+from huggingface_hub import snapshot_download+from librosa.filters import mel as librosa_mel_fn+from torch import nn+from torch.nn import functional as F+from transformers.activations import ACT2FN+from transformers.cache_utils import Cache, DynamicCache+from transformers.generation import GenerationMixin+from transformers.integrations import use_kernel_forward_from_hub+from transformers.masking_utils import (create_causal_mask,+ create_sliding_window_causal_mask)+from transformers.modeling_flash_attention_utils import FlashAttentionKwargs+from transformers.modeling_layers import GradientCheckpointingLayer+from transformers.modeling_outputs import (BaseModelOutputWithPast,+ CausalLMOutputWithPast, ModelOutput)+from transformers.modeling_rope_utils import (ROPE_INIT_FUNCTIONS,+ dynamic_rope_update)+from transformers.modeling_utils import (ALL_ATTENTION_FUNCTIONS,+ PreTrainedModel)+from transformers.processing_utils import Unpack+from transformers.utils import can_return_tuple, logging+from transformers.utils.hub import cached_file++from ...inference.qwen3_tts_tokenizer import Qwen3TTSTokenizer+from .configuration_qwen3_tts import (Qwen3TTSConfig,+ Qwen3TTSSpeakerEncoderConfig,+ Qwen3TTSTalkerCodePredictorConfig,+ Qwen3TTSTalkerConfig)++logger = logging.get_logger(__name__)+++def _check_abort(module) -> None:+ checker = getattr(module, "_interrupt_check", None)+ if callable(checker) and checker():+ raise RuntimeError("Abort requested")+++def download_weights_from_hf_specific(+ model_name_or_path: str,+ cache_dir: str | None,+ allow_patterns: list[str],+ revision: str | None = None,+ ignore_patterns: str | list[str] | None = None,+) -> str:+ """Download model weights from Hugging Face Hub. Users can specify the+ allow_patterns to download only the necessary weights.++ Args:+ model_name_or_path (str): The model name or path.+ cache_dir (Optional[str]): The cache directory to store the model+ weights. If None, will use HF defaults.+ allow_patterns (list[str]): The allowed patterns for the+ weight files. Files matched by any of the patterns will be+ downloaded.+ revision (Optional[str]): The revision of the model.+ ignore_patterns (Optional[Union[str, list[str]]]): The patterns to+ filter out the weight files. Files matched by any of the patterns+ will be ignored.++ Returns:+ str: The path to the downloaded model weights.+ """+ assert len(allow_patterns) > 0+ local_only = huggingface_hub.constants.HF_HUB_OFFLINE++ for allow_pattern in allow_patterns:+ hf_folder = snapshot_download(+ model_name_or_path,+ allow_patterns=allow_pattern,+ ignore_patterns=ignore_patterns,+ cache_dir=cache_dir,+ revision=revision,+ local_files_only=local_only,+ )+ return hf_folder+++class Res2NetBlock(torch.nn.Module):+ def __init__(self, in_channels, out_channels, scale=8, kernel_size=3, dilation=1):+ super().__init__()++ in_channel = in_channels // scale+ hidden_channel = out_channels // scale++ self.blocks = nn.ModuleList(+ [+ TimeDelayNetBlock(+ in_channel,+ hidden_channel,+ kernel_size=kernel_size,+ dilation=dilation,+ )+ for i in range(scale - 1)+ ]+ )+ self.scale = scale++ def forward(self, hidden_states):+ outputs = []+ for i, hidden_part in enumerate(torch.chunk(hidden_states, self.scale, dim=1)):+ if i == 0:+ output_part = hidden_part+ elif i == 1:+ output_part = self.blocks[i - 1](hidden_part)+ else:+ output_part = self.blocks[i - 1](hidden_part + output_part)+ outputs.append(output_part)+ output = torch.cat(outputs, dim=1)+ return output+++class SqueezeExcitationBlock(nn.Module):+ def __init__(self, in_channels, se_channels, out_channels):+ super().__init__()++ self.conv1 = nn.Conv1d(+ in_channels=in_channels,+ out_channels=se_channels,+ kernel_size=1,+ padding="same",+ padding_mode="reflect",+ )+ self.relu = nn.ReLU(inplace=True)+ self.conv2 = nn.Conv1d(+ in_channels=se_channels,+ out_channels=out_channels,+ kernel_size=1,+ padding="same",+ padding_mode="reflect",+ )+ self.sigmoid = nn.Sigmoid()++ def forward(self, hidden_states):+ hidden_states_mean = hidden_states.mean(dim=2, keepdim=True)++ hidden_states_mean = self.relu(self.conv1(hidden_states_mean))+ hidden_states_mean = self.sigmoid(self.conv2(hidden_states_mean))++ return hidden_states * hidden_states_mean+++class AttentiveStatisticsPooling(nn.Module):+ """This class implements an attentive statistic pooling layer for each channel.+ It returns the concatenated mean and std of the input tensor.+ """++ def __init__(self, channels, attention_channels=128):+ super().__init__()++ self.eps = 1e-12+ self.tdnn = TimeDelayNetBlock(channels * 3, attention_channels, 1, 1)+ self.tanh = nn.Tanh()+ self.conv = nn.Conv1d(+ in_channels=attention_channels,+ out_channels=channels,+ kernel_size=1,+ padding="same",+ padding_mode="reflect",+ )++ def _length_to_mask(self, length, max_len=None, dtype=None, device=None):+ """Creates a binary mask for each sequence.++ Reference: https://discuss.pytorch.org/t/how-to-generate-variable-length-mask/23397/3++ Arguments+ ---------+ length : torch.LongTensor+ Containing the length of each sequence in the batch. Must be 1D.+ max_len : int+ Max length for the mask, also the size of the second dimension.+ dtype : torch.dtype, default: None+ The dtype of the generated mask.+ device: torch.device, default: None+ The device to put the mask variable.++ Returns+ -------+ mask : tensor+ The binary mask.+ """++ if max_len is None:+ max_len = length.max().long().item() # using arange to generate mask+ mask = torch.arange(max_len, device=length.device, dtype=length.dtype).expand(+ len(length), max_len+ ) < length.unsqueeze(1)++ mask = torch.as_tensor(mask, dtype=dtype, device=device)+ return mask++ def _compute_statistics(self, x, m, dim=2):+ mean = (m * x).sum(dim)+ std = torch.sqrt((m * (x - mean.unsqueeze(dim)).pow(2)).sum(dim).clamp(self.eps))+ return mean, std++ def forward(self, hidden_states):+ seq_length = hidden_states.shape[-1]+ lengths = torch.ones(hidden_states.shape[0], device=hidden_states.device)++ # Make binary mask of shape [N, 1, L]+ mask = self._length_to_mask(+ lengths * seq_length, max_len=seq_length, dtype=hidden_states.dtype, device=hidden_states.device+ )+ mask = mask.unsqueeze(1)++ # Expand the temporal context of the pooling layer by allowing the+ # self-attention to look at global properties of the utterance.+ total = mask.sum(dim=2, keepdim=True)++ mean, std = self._compute_statistics(hidden_states, mask / total)+ mean = mean.unsqueeze(2).repeat(1, 1, seq_length)+ std = std.unsqueeze(2).repeat(1, 1, seq_length)+ attention = torch.cat([hidden_states, mean, std], dim=1)++ # Apply layers+ attention = self.conv(self.tanh(self.tdnn(attention)))++ # Filter out zero-paddings+ attention = attention.masked_fill(mask == 0, float("-inf"))++ attention = F.softmax(attention, dim=2)+ mean, std = self._compute_statistics(hidden_states, attention)+ # Append mean and std of the batch+ pooled_stats = torch.cat((mean, std), dim=1)+ pooled_stats = pooled_stats.unsqueeze(2)++ return pooled_stats++class TimeDelayNetBlock(nn.Module):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size,+ dilation,+ ):+ super().__init__()+ self.conv = nn.Conv1d(+ in_channels=in_channels,+ out_channels=out_channels,+ kernel_size=kernel_size,+ dilation=dilation,+ padding="same",+ padding_mode="reflect",+ )+ self.activation = nn.ReLU()++ def forward(self, hidden_states: torch.Tensor):+ return self.activation(self.conv(hidden_states))++class SqueezeExcitationRes2NetBlock(nn.Module):+ """An implementation of building block in ECAPA-TDNN, i.e.,+ TDNN-Res2Net-TDNN-SqueezeExcitationBlock.+ """++ def __init__(+ self,+ in_channels,+ out_channels,+ res2net_scale=8,+ se_channels=128,+ kernel_size=1,+ dilation=1,+ ):+ super().__init__()+ self.out_channels = out_channels+ self.tdnn1 = TimeDelayNetBlock(+ in_channels,+ out_channels,+ kernel_size=1,+ dilation=1,+ )+ self.res2net_block = Res2NetBlock(out_channels, out_channels, res2net_scale, kernel_size, dilation)+ self.tdnn2 = TimeDelayNetBlock(+ out_channels,+ out_channels,+ kernel_size=1,+ dilation=1,+ )+ self.se_block = SqueezeExcitationBlock(out_channels, se_channels, out_channels)++ def forward(self, hidden_state):+ residual = hidden_state++ hidden_state = self.tdnn1(hidden_state)+ hidden_state = self.res2net_block(hidden_state)+ hidden_state = self.tdnn2(hidden_state)+ hidden_state = self.se_block(hidden_state)++ return hidden_state + residual+++class Qwen3TTSSpeakerEncoder(torch.nn.Module):+ """An implementation of the speaker embedding model in a paper.+ "ECAPA-TDNN: Emphasized Channel Attention, Propagation and Aggregation in+ TDNN Based Speaker Verification" (https://huggingface.co/papers/2005.07143).+ Use for Qwen3TTS extract speaker embedding.+ """++ def __init__(self, config: Qwen3TTSSpeakerEncoderConfig):+ super().__init__()+ if len(config.enc_channels) != len(config.enc_kernel_sizes) or len(config.enc_channels) != len(+ config.enc_dilations+ ):+ raise ValueError("enc_channels, enc_kernel_sizes and enc_dilations should have same length")+ self.channels = config.enc_channels+ self.blocks = nn.ModuleList()++ # The initial TDNN layer+ self.blocks.append(+ TimeDelayNetBlock(+ config.mel_dim,+ config.enc_channels[0],+ config.enc_kernel_sizes[0],+ config.enc_dilations[0],+ )+ )++ # SE-Res2Net layers+ for i in range(1, len(config.enc_channels) - 1):+ self.blocks.append(+ SqueezeExcitationRes2NetBlock(+ config.enc_channels[i - 1],+ config.enc_channels[i],+ res2net_scale=config.enc_res2net_scale,+ se_channels=config.enc_se_channels,+ kernel_size=config.enc_kernel_sizes[i],+ dilation=config.enc_dilations[i],+ )+ )++ # Multi-layer feature aggregation+ self.mfa = TimeDelayNetBlock(+ config.enc_channels[-1],+ config.enc_channels[-1],+ config.enc_kernel_sizes[-1],+ config.enc_dilations[-1],+ )++ # Attentive Statistical Pooling+ self.asp = AttentiveStatisticsPooling(+ config.enc_channels[-1],+ attention_channels=config.enc_attention_channels,+ )++ # Final linear transformation+ self.fc = nn.Conv1d(+ in_channels=config.enc_channels[-1] * 2,+ out_channels=config.enc_dim,+ kernel_size=1,+ padding="same",+ padding_mode="reflect",+ )++ def forward(self, hidden_states):+ # Minimize transpose for efficiency+ hidden_states = hidden_states.transpose(1, 2)++ hidden_states_list = []+ for layer in self.blocks:+ hidden_states = layer(hidden_states)+ hidden_states_list.append(hidden_states)++ # Multi-layer feature aggregation+ hidden_states = torch.cat(hidden_states_list[1:], dim=1)+ hidden_states = self.mfa(hidden_states)++ # Attentive Statistical Pooling+ hidden_states = self.asp(hidden_states)++ # Final linear transformation+ hidden_states = self.fc(hidden_states)++ hidden_states = hidden_states.squeeze(-1)+ return hidden_states+++def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):+ return torch.log(torch.clamp(x, min=clip_val) * C)++def mel_spectrogram(+ y: torch.Tensor,+ n_fft: int,+ num_mels: int,+ sampling_rate: int,+ hop_size: int,+ win_size: int,+ fmin: int,+ fmax: int = None,+ center: bool = False,+) -> torch.Tensor:+ """+ Calculate the mel spectrogram of an input signal.+ This function uses slaney norm for the librosa mel filterbank (using librosa.filters.mel) and uses Hann window for STFT (using torch.stft).++ Args:+ y (torch.Tensor): Input signal.+ n_fft (int): FFT size.+ num_mels (int): Number of mel bins.+ sampling_rate (int): Sampling rate of the input signal.+ hop_size (int): Hop size for STFT.+ win_size (int): Window size for STFT.+ fmin (int): Minimum frequency for mel filterbank.+ fmax (int): Maximum frequency for mel filterbank. If None, defaults to half the sampling rate (fmax = sr / 2.0) inside librosa_mel_fn+ center (bool): Whether to pad the input to center the frames. Default is False.++ Returns:+ torch.Tensor: Mel spectrogram.+ """+ if torch.min(y) < -1.0:+ print(f"[WARNING] Min value of input waveform signal is {torch.min(y)}")+ if torch.max(y) > 1.0:+ print(f"[WARNING] Max value of input waveform signal is {torch.max(y)}")++ device = y.device++ mel = librosa_mel_fn(+ sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax+ )++ mel_basis = torch.from_numpy(mel).float().to(device)+ hann_window = torch.hann_window(win_size).to(device)++ padding = (n_fft - hop_size) // 2+ y = torch.nn.functional.pad(+ y.unsqueeze(1), (padding, padding), mode="reflect"+ ).squeeze(1)++ spec = torch.stft(+ y,+ n_fft,+ hop_length=hop_size,+ win_length=win_size,+ window=hann_window,+ center=center,+ pad_mode="reflect",+ normalized=False,+ onesided=True,+ return_complex=True,+ )+ spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)++ mel_spec = torch.matmul(mel_basis, spec)+ mel_spec = dynamic_range_compression_torch(mel_spec)++ return mel_spec+++class Qwen3TTSPreTrainedModel(PreTrainedModel):+ config_class = Qwen3TTSConfig+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _no_split_modules = ["Qwen3TTSDecoderLayer"]+ _skip_keys_device_placement = "past_key_values"+ _supports_flash_attn_2 = True+ _supports_sdpa = True+ _supports_cache_class = True+ _supports_static_cache = False+ _supports_attention_backend = True++ def _init_weights(self, module):+ # important: this ported version of Qwen2.5OmniThinker isn't meant for training from scratch - only+ # inference and fine-tuning - so the proper init weights code has been removed+ std = self.config.initializer_range if hasattr(self.config, "initializer_range") else 0.02++ if isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv3d, nn.ConvTranspose1d)):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.bias is not None:+ module.bias.data.zero_()+ elif isinstance(module, nn.Embedding):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.padding_idx is not None:+ module.weight.data[module.padding_idx].zero_()+ elif isinstance(module, nn.LayerNorm):+ if module.weight is not None:+ module.weight.data.fill_(1.0)+ if module.bias is not None:+ module.bias.data.zero_()+++class Qwen3TTSTalkerTextPreTrainedModel(PreTrainedModel):+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _no_split_modules = []+ _skip_keys_device_placement = ["past_key_values"]+ _supports_flash_attn_3 = True+ _supports_flash_attn_2 = True+ _supports_sdpa = True+ _supports_flex_attn = True+ _supports_cache_class = True+ _supports_quantized_cache = True+ _supports_static_cache = False+ _supports_attention_backend = True++ def _init_weights(self, module):+ std = self.config.initializer_range+ if isinstance(module, nn.Linear):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.bias is not None:+ module.bias.data.zero_()+ elif isinstance(module, nn.Embedding):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.padding_idx is not None:+ module.weight.data[module.padding_idx].zero_()+ elif isinstance(module, Qwen3TTSRMSNorm):+ module.weight.data.fill_(1.0)+++class Qwen3TTSTalkerRotaryEmbedding(nn.Module):+ def __init__(self, config: Qwen3TTSTalkerConfig, device=None):+ super().__init__()+ # BC: "rope_type" was originally "type"+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))+ else:+ self.rope_type = "default"+ self.max_seq_len_cached = config.max_position_embeddings+ self.original_max_seq_len = config.max_position_embeddings++ self.config = config+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]++ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)+ self.register_buffer("inv_freq", inv_freq, persistent=False)+ self.original_inv_freq = self.inv_freq++ @torch.no_grad()+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)+ def forward(self, x, position_ids):+ # In contrast to other models, Qwen3TTSThinkerText has different position ids for the grids+ # So we expand the inv_freq to shape (3, ...)+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)++ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"+ with torch.autocast(device_type=device_type, enabled=False): # Force float32+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = emb.cos() * self.attention_scaling+ sin = emb.sin() * self.attention_scaling++ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)++class Qwen3TTSRotaryEmbedding(nn.Module):+ def __init__(self, config: Qwen3TTSConfig, device=None):+ super().__init__()+ # BC: "rope_type" was originally "type"+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))+ else:+ self.rope_type = "default"+ self.max_seq_len_cached = config.max_position_embeddings+ self.original_max_seq_len = config.max_position_embeddings++ self.config = config+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]++ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)+ self.register_buffer("inv_freq", inv_freq, persistent=False)+ self.original_inv_freq = self.inv_freq++ @torch.no_grad()+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)+ def forward(self, x, position_ids):+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)+ position_ids_expanded = position_ids[:, None, :].float()++ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"+ with torch.autocast(device_type=device_type, enabled=False): # Force float32+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = emb.cos() * self.attention_scaling+ sin = emb.sin() * self.attention_scaling++ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)+++@use_kernel_forward_from_hub("RMSNorm")+class Qwen3TTSRMSNorm(nn.Module):+ def __init__(self, hidden_size, eps=1e-6):+ """+ Qwen3TTSRMSNorm is equivalent to T5LayerNorm+ """+ super().__init__()+ self.weight = nn.Parameter(torch.ones(hidden_size))+ self.variance_epsilon = eps++ def forward(self, hidden_states):+ input_dtype = hidden_states.dtype+ hidden_states = hidden_states.to(torch.float32)+ variance = hidden_states.pow(2).mean(-1, keepdim=True)+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)+ return self.weight * hidden_states.to(input_dtype)++ def extra_repr(self):+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"++def rotate_half(x):+ """Rotates half the hidden dims of the input."""+ x1 = x[..., : x.shape[-1] // 2]+ x2 = x[..., x.shape[-1] // 2 :]+ return torch.cat((-x2, x1), dim=-1)+++def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:+ """+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)+ """+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape+ if n_rep == 1:+ return hidden_states+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)+++def eager_attention_forward(+ module: nn.Module,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attention_mask: Optional[torch.Tensor],+ scaling: float,+ dropout: float = 0.0,+ **kwargs,+):+ key_states = repeat_kv(key, module.num_key_value_groups)+ value_states = repeat_kv(value, module.num_key_value_groups)++ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling+ if attention_mask is not None:+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]+ attn_weights = attn_weights + causal_mask++ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)+ attn_output = torch.matmul(attn_weights, value_states)+ attn_output = attn_output.transpose(1, 2).contiguous()++ return attn_output, attn_weights+++def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, mrope_interleaved=False, unsqueeze_dim=1):+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).++ Explanation:+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no+ difference with modern LLMs.++ Args:+ q (`torch.Tensor`): The query tensor.+ k (`torch.Tensor`): The key tensor.+ cos (`torch.Tensor`): The cosine part of the rotary embedding.+ sin (`torch.Tensor`): The sine part of the rotary embedding.+ position_ids (`torch.Tensor`):+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be+ used to pass offsetted position ids when working with a KV-cache.+ mrope_section(`List(int)`):+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.+ unsqueeze_dim (`int`, *optional*, defaults to 1):+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.+ Returns:+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.+ """+ if mrope_interleaved:++ def apply_interleaved_rope(x, modality_num):+ x_t = x[0].clone()+ index_ranges = []+ for i, n in enumerate(mrope_section[1:], 1):+ beg_idx = i+ end_idx = n * modality_num+ index_ranges.append((beg_idx, end_idx))+ for beg_idx, end_idx in index_ranges:+ x_t[..., beg_idx:end_idx:modality_num] = x[beg_idx, ..., beg_idx:end_idx:modality_num]+ return x_t++ dim = cos.shape[-1]+ modality_num = len(mrope_section)+ cos = torch.cat([apply_interleaved_rope(cos[..., : dim // 2], modality_num)] * 2, dim=-1).unsqueeze(+ unsqueeze_dim+ )+ sin = torch.cat([apply_interleaved_rope(sin[..., : dim // 2], modality_num)] * 2, dim=-1).unsqueeze(+ unsqueeze_dim+ )+ else:+ mrope_section = mrope_section * 2+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(+ unsqueeze_dim+ )+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(+ unsqueeze_dim+ )++ q_embed = (q * cos) + (rotate_half(q) * sin)+ k_embed = (k * cos) + (rotate_half(k) * sin)+ return q_embed, k_embed+++class Qwen3TTSTalkerAttention(nn.Module):+ """Multi-headed attention from 'Attention Is All You Need' paper"""++ def __init__(self, config, layer_idx):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads+ self.scaling = self.head_dim**-0.5+ self.attention_dropout = config.attention_dropout+ self.is_causal = True++ self.q_proj = nn.Linear(+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias+ )+ self.k_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.v_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.o_proj = nn.Linear(+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias+ )+ self.q_norm = Qwen3TTSRMSNorm(+ self.head_dim, eps=config.rms_norm_eps+ ) # unlike olmo, only on the head dim!+ self.k_norm = Qwen3TTSRMSNorm(+ self.head_dim, eps=config.rms_norm_eps+ ) # thus post q_norm does not need reshape+ self.sliding_window = getattr(config, "sliding_window", None)+ self.rope_scaling = config.rope_scaling++ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: Optional[torch.Tensor],+ past_key_values: Optional[Cache] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:+ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)++ cos, sin = position_embeddings+ query_states, key_states = apply_multimodal_rotary_pos_emb(+ query_states, key_states, cos, sin, self.rope_scaling["mrope_section"], self.rope_scaling["interleaved"]+ )++ if past_key_values is not None:+ # sin and cos are specific to RoPE models; cache_position needed for the static cache+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)++ attention_interface: Callable = eager_attention_forward+ if self.config._attn_implementation != "eager":+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]++ attn_output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ sliding_window=self.sliding_window, # diff with Llama+ **kwargs,+ )++ attn_output = attn_output.reshape(*input_shape, -1).contiguous()+ attn_output = self.o_proj(attn_output)+ return attn_output, attn_weights+++class Qwen3TTSTalkerResizeMLP(nn.Module):+ def __init__(self, input_size: int, intermediate_size: int, output_size: int, act: str, bias=False):+ super().__init__()+ self.linear_fc1 = nn.Linear(input_size, intermediate_size, bias=bias)+ self.linear_fc2 = nn.Linear(intermediate_size, output_size, bias=bias)+ self.act_fn = ACT2FN[act]++ def forward(self, hidden_state):+ return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state)))+++@dataclass+class Qwen3TTSTalkerCodePredictorOutputWithPast(ModelOutput):+ r"""+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):+ Language modeling loss (for next-token prediction).+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)++ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see+ `past_key_values` input) to speed up sequential decoding.+ """++ loss: Optional[torch.FloatTensor] = None+ logits: torch.FloatTensor = None+ past_key_values: Optional[list[torch.FloatTensor]] = None+ hidden_states: Optional[tuple[torch.FloatTensor]] = None+ attentions: Optional[tuple[torch.FloatTensor]] = None+ generation_steps: Optional[int] = None+++class Qwen3TTSTalkerTextMLP(nn.Module):+ def __init__(self, config, intermediate_size=None):+ super().__init__()+ self.config = config+ self.hidden_size = config.hidden_size+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)+ self.act_fn = ACT2FN[config.hidden_act]++ def forward(self, x):+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))+ return down_proj+++def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):+ """Applies Rotary Position Embedding to the query and key tensors.++ Args:+ q (`torch.Tensor`): The query tensor.+ k (`torch.Tensor`): The key tensor.+ cos (`torch.Tensor`): The cosine part of the rotary embedding.+ sin (`torch.Tensor`): The sine part of the rotary embedding.+ position_ids (`torch.Tensor`, *optional*):+ Deprecated and unused.+ unsqueeze_dim (`int`, *optional*, defaults to 1):+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.+ Returns:+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.+ """+ cos = cos.unsqueeze(unsqueeze_dim)+ sin = sin.unsqueeze(unsqueeze_dim)+ q_embed = (q * cos) + (rotate_half(q) * sin)+ k_embed = (k * cos) + (rotate_half(k) * sin)+ return q_embed, k_embed+++class Qwen3TTSAttention(nn.Module):+ """Multi-headed attention from 'Attention Is All You Need' paper"""++ def __init__(self, config: Qwen3TTSConfig, layer_idx: int):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads+ self.scaling = self.head_dim**-0.5+ self.attention_dropout = config.attention_dropout+ self.is_causal = True++ self.q_proj = nn.Linear(+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias+ )+ self.k_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.v_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.o_proj = nn.Linear(+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias+ )+ self.q_norm = Qwen3TTSRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!+ self.k_norm = Qwen3TTSRMSNorm(+ self.head_dim, eps=config.rms_norm_eps+ ) # thus post q_norm does not need reshape+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None++ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: Optional[torch.Tensor],+ past_key_values: Optional[Cache] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:+ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)++ cos, sin = position_embeddings+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)++ if past_key_values is not None:+ # sin and cos are specific to RoPE models; cache_position needed for the static cache+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)++ attention_interface: Callable = eager_attention_forward+ if self.config._attn_implementation != "eager":+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]++ attn_output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ sliding_window=self.sliding_window, # diff with Llama+ **kwargs,+ )++ attn_output = attn_output.reshape(*input_shape, -1).contiguous()+ attn_output = self.o_proj(attn_output)+ return attn_output, attn_weights+++class Qwen3TTSDecoderLayer(GradientCheckpointingLayer):+ def __init__(self, config: Qwen3TTSConfig, layer_idx: int):+ super().__init__()+ self.hidden_size = config.hidden_size++ self.self_attn = Qwen3TTSAttention(config=config, layer_idx=layer_idx)++ self.mlp = Qwen3TTSTalkerTextMLP(config)+ self.input_layernorm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_attention_layernorm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.attention_type = config.layer_types[layer_idx]++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Cache] = None,+ output_attentions: Optional[bool] = False,+ use_cache: Optional[bool] = False,+ cache_position: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:+ residual = hidden_states+ hidden_states = self.input_layernorm(hidden_states)++ # Self Attention+ hidden_states, self_attn_weights = self.self_attn(+ hidden_states=hidden_states,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **kwargs,+ )+ hidden_states = residual + hidden_states++ # Fully Connected+ residual = hidden_states+ hidden_states = self.post_attention_layernorm(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = residual + hidden_states++ outputs = (hidden_states,)+ if output_attentions:+ outputs += (self_attn_weights,)++ return outputs+++class Qwen3TTSTalkerCodePredictorModel(Qwen3TTSPreTrainedModel):+ config_class = Qwen3TTSTalkerCodePredictorConfig+ base_model_prefix = "talker.code_predictor.model"++ def __init__(self, config: Qwen3TTSTalkerCodePredictorConfig, embedding_dim: int):+ super().__init__(config)+ self.padding_idx = config.pad_token_id+ self.vocab_size = config.vocab_size+ self.layers = nn.ModuleList(+ [Qwen3TTSDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.rotary_emb = Qwen3TTSRotaryEmbedding(config=config)+ self.gradient_checkpointing = False+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types+ self.codec_embedding = nn.ModuleList(+ [nn.Embedding(config.vocab_size, embedding_dim) for _ in range(config.num_code_groups - 1)]+ )++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.codec_embedding++ def set_input_embeddings(self, value):+ self.embed_tokens = value++ @can_return_tuple+ def forward(+ self,+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=None,+ inputs_embeds=None,+ use_cache=None,+ output_attentions=None,+ output_hidden_states=None,+ cache_position=None,+ generation_steps=None,+ **flash_attn_kwargs,+ ) -> BaseModelOutputWithPast:+ if input_ids is not None:+ raise ValueError("`input_ids` is expected to be `None`")+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ use_cache = use_cache if use_cache is not None else self.config.use_cache++ if (input_ids is None) ^ (inputs_embeds is not None):+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")++ if self.gradient_checkpointing and self.training and use_cache:+ logger.warning_once(+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."+ )+ use_cache = False++ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache+ if not isinstance(past_key_values, (type(None), Cache)):+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")++ if inputs_embeds is None:+ inputs_embeds = self.embed_tokens(input_ids)++ if use_cache and past_key_values is None:+ past_key_values = DynamicCache()++ if cache_position is None:+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0+ cache_position = torch.arange(+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device+ )++ if position_ids is None:+ position_ids = cache_position.unsqueeze(0)++ # It may already have been prepared by e.g. `generate`+ if not isinstance(causal_mask_mapping := attention_mask, dict):+ # Prepare mask arguments+ mask_kwargs = {+ "config": self.config,+ "input_embeds": inputs_embeds,+ "attention_mask": attention_mask,+ "cache_position": cache_position,+ "past_key_values": past_key_values,+ "position_ids": position_ids,+ }+ # Create the masks+ causal_mask_mapping = {+ "full_attention": create_causal_mask(**mask_kwargs),+ }+ # The sliding window alternating layers are not always activated depending on the config+ if self.has_sliding_layers:+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)++ hidden_states = inputs_embeds++ # create position embeddings to be shared across the decoder layers+ position_embeddings = self.rotary_emb(hidden_states, position_ids)++ # decoder layers+ all_hidden_states = () if output_hidden_states else None+ all_self_attns = () if output_attentions else None++ for decoder_layer in self.layers[: self.config.num_hidden_layers]:+ _check_abort(self)+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ layer_outputs = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_ids=position_ids,+ past_key_values=past_key_values,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **flash_attn_kwargs,+ )++ hidden_states = layer_outputs[0]++ if output_attentions:+ all_self_attns += (layer_outputs[1],)++ hidden_states = self.norm(hidden_states)++ # add hidden states from the last decoder layer+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ return BaseModelOutputWithPast(+ last_hidden_state=hidden_states,+ past_key_values=past_key_values if use_cache else None,+ hidden_states=all_hidden_states,+ attentions=all_self_attns,+ )+++class Qwen3TTSTalkerCodePredictorModelForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin):+ _tied_weights_keys = ["lm_head.weight"]+ _tp_plan = {"lm_head": "colwise_rep"}+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}+ config_class = Qwen3TTSTalkerCodePredictorConfig+ base_model_prefix = "talker.code_predictor"++ def __init__(self, config: Qwen3TTSTalkerCodePredictorConfig, talker_config: Qwen3TTSTalkerConfig):+ super().__init__(config)+ self.model = Qwen3TTSTalkerCodePredictorModel(config, talker_config.hidden_size)+ self.vocab_size = config.vocab_size+ self.lm_head = nn.ModuleList(+ [nn.Linear(config.hidden_size, config.vocab_size, bias=False) for _ in range(config.num_code_groups - 1)]+ )++ if config.hidden_size != talker_config.hidden_size:+ self.small_to_mtp_projection = torch.nn.Linear(talker_config.hidden_size, config.hidden_size, bias=True)+ else:+ self.small_to_mtp_projection = torch.nn.Identity()++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.model.get_input_embeddings()++ @property+ def device(self) -> torch.device:+ if torch.cuda.is_available():+ return torch.device("cuda")+ return super().device++ def set_input_embeddings(self, value):+ self.model.embed_tokens = value++ def get_output_embeddings(self):+ return self.lm_head++ def set_output_embeddings(self, new_embeddings):+ self.lm_head = new_embeddings++ def set_decoder(self, decoder):+ self.model = decoder++ def get_decoder(self):+ return self.model++ def forward_finetune(+ self,+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=None,+ inputs_embeds=None,+ labels=None,+ use_cache=None,+ output_attentions=None,+ output_hidden_states=None,+ cache_position=None,+ generation_steps=None,+ **kwargs,+ ) -> CausalLMOutputWithPast:+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )++ inputs_embeds = self.small_to_mtp_projection(inputs_embeds)++ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)+ outputs: BaseModelOutputWithPast = self.model(+ input_ids=None,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ cache_position=cache_position,+ **kwargs,+ )++ hidden_states = outputs.last_hidden_state++ logits = []+ for i in range(1, self.config.num_code_groups):+ logits.append(self.lm_head[i-1](hidden_states[:, i]))+ logits = torch.stack(logits, dim=1)++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)++ return Qwen3TTSTalkerCodePredictorOutputWithPast(+ loss=loss,+ logits=logits+ )++ @can_return_tuple+ def forward(+ self,+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=None,+ inputs_embeds=None,+ labels=None,+ use_cache=None,+ output_attentions=None,+ output_hidden_states=None,+ cache_position=None,+ generation_steps=None,+ **kwargs,+ ) -> CausalLMOutputWithPast:+ r"""+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.+ """+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )++ # Prefill stage+ if inputs_embeds is not None and inputs_embeds.shape[1] > 1:+ generation_steps = inputs_embeds.shape[1] - 2 # hidden & layer 0+ # Generation stage+ else:+ if input_ids is not None and input_ids.device != self.device:+ input_ids = input_ids.to(self.device)+ inputs_embeds = self.model.get_input_embeddings()[generation_steps - 1](input_ids)+ inputs_embeds = self.small_to_mtp_projection(inputs_embeds)++ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)+ outputs: BaseModelOutputWithPast = self.model(+ input_ids=None,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ cache_position=cache_position,+ **kwargs,+ )++ hidden_states = outputs.last_hidden_state+ logits = self.lm_head[generation_steps](hidden_states)++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)++ return Qwen3TTSTalkerCodePredictorOutputWithPast(+ loss=loss,+ logits=logits,+ past_key_values=outputs.past_key_values,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ generation_steps=generation_steps + 1,+ )++ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder=False, num_new_tokens=1):+ model_kwargs = super()._update_model_kwargs_for_generation(+ outputs, model_kwargs, is_encoder_decoder, num_new_tokens+ )+ model_kwargs["generation_steps"] = outputs.generation_steps+ return model_kwargs+++@dataclass+class Qwen3TTSTalkerOutputWithPast(ModelOutput):+ r"""+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):+ Language modeling loss (for next-token prediction).+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)++ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see+ `past_key_values` input) to speed up sequential decoding.+ """++ loss: Optional[torch.FloatTensor] = None+ logits: Optional[torch.FloatTensor] = None+ past_key_values: Optional[list[torch.FloatTensor]] = None+ hidden_states: Optional[tuple[torch.FloatTensor]] = None+ attentions: Optional[tuple[torch.FloatTensor]] = None+ past_hidden: Optional[torch.FloatTensor] = None+ generation_step: Optional[int] = None+ trailing_text_hidden: Optional[torch.FloatTensor] = None+ tts_pad_embed: Optional[torch.FloatTensor] = None+++class Qwen3TTSTalkerDecoderLayer(GradientCheckpointingLayer):+ def __init__(self, config, layer_idx):+ super().__init__()+ self.hidden_size = config.hidden_size+ self.self_attn = Qwen3TTSTalkerAttention(config, layer_idx)++ self.mlp = Qwen3TTSTalkerTextMLP(config, intermediate_size=config.intermediate_size)++ self.input_layernorm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_attention_layernorm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[tuple[torch.Tensor]] = None,+ output_attentions: Optional[bool] = False,+ use_cache: Optional[bool] = False,+ cache_position: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:+ """+ Args:+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size+ `(batch, sequence_length)` where padding elements are indicated by 0.+ output_attentions (`bool`, *optional*):+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under+ returned tensors for more detail.+ use_cache (`bool`, *optional*):+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding+ (see `past_key_values`).+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):+ Indices depicting the position of the input sequence tokens in the sequence.+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,+ with `head_dim` being the embedding dimension of each attention head.+ kwargs (`dict`, *optional*):+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code+ into the model+ """++ residual = hidden_states++ hidden_states = self.input_layernorm(hidden_states)++ # Self Attention+ hidden_states, self_attn_weights = self.self_attn(+ hidden_states=hidden_states,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **kwargs,+ )+ hidden_states = residual + hidden_states++ # Fully Connected+ residual = hidden_states+ hidden_states = self.post_attention_layernorm(hidden_states)++ hidden_states = self.mlp(hidden_states)++ hidden_states = residual + hidden_states++ outputs = (hidden_states,)++ if output_attentions:+ outputs += (self_attn_weights,)++ return outputs+++class Qwen3TTSTalkerModel(Qwen3TTSTalkerTextPreTrainedModel):+ config_class = Qwen3TTSTalkerConfig+ base_model_prefix = "talker.model"++ def __init__(self, config):+ super().__init__(config)+ self.padding_idx = config.pad_token_id+ self.vocab_size = config.vocab_size+ self.layers = nn.ModuleList(+ [Qwen3TTSTalkerDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = Qwen3TTSRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.rotary_emb = Qwen3TTSTalkerRotaryEmbedding(config)+ self.gradient_checkpointing = False+ self.codec_embedding = nn.Embedding(config.vocab_size, config.hidden_size)+ self.text_embedding = nn.Embedding(config.text_vocab_size, config.text_hidden_size)++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.codec_embedding++ def get_text_embeddings(self):+ return self.text_embedding++ def set_input_embeddings(self, value):+ self.embed_tokens = value++ @can_return_tuple+ def forward(+ self,+ input_ids: Optional[torch.LongTensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[list[torch.FloatTensor]] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ use_cache: Optional[bool] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],+ ) -> BaseModelOutputWithPast:+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ use_cache = use_cache if use_cache is not None else self.config.use_cache++ if (input_ids is None) ^ (inputs_embeds is not None):+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")++ if self.gradient_checkpointing and self.training:+ if use_cache:+ logger.warning_once(+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."+ )+ use_cache = False++ if use_cache and past_key_values is None:+ past_key_values = DynamicCache()++ if inputs_embeds is None:+ inputs_embeds = self.embed_tokens(input_ids)++ if cache_position is None:+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0+ cache_position = torch.arange(+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device+ )++ # the hard coded `3` is for temporal, height and width.+ if position_ids is None:+ position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)+ elif position_ids.ndim == 2:+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)++ if position_ids.ndim == 3 and position_ids.shape[0] == 4:+ text_position_ids = position_ids[0]+ position_ids = position_ids[1:]+ else:+ text_position_ids = position_ids[0]++ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask+ causal_mask = mask_function(+ config=self.config,+ input_embeds=inputs_embeds,+ attention_mask=attention_mask,+ cache_position=cache_position,+ past_key_values=past_key_values,+ position_ids=text_position_ids,+ )++ hidden_states = inputs_embeds++ # create position embeddings to be shared across the decoder layers+ position_embeddings = self.rotary_emb(hidden_states, position_ids)++ # decoder layers+ all_hidden_states = () if output_hidden_states else None+ all_self_attns = () if output_attentions else None++ for decoder_layer in self.layers:+ _check_abort(self)+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ layer_outputs = decoder_layer(+ hidden_states,+ attention_mask=causal_mask,+ position_ids=text_position_ids,+ past_key_values=past_key_values,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **flash_attn_kwargs,+ )++ hidden_states = layer_outputs[0]++ if output_attentions:+ all_self_attns += (layer_outputs[1],)++ hidden_states = self.norm(hidden_states)++ # add hidden states from the last decoder layer+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ return BaseModelOutputWithPast(+ last_hidden_state=hidden_states,+ past_key_values=past_key_values,+ hidden_states=all_hidden_states,+ attentions=all_self_attns,+ )+++class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel, GenerationMixin):+ _tied_weights_keys = ["lm_head.weight"]+ _tp_plan = {"lm_head": "colwise_rep"}+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}+ config_class = Qwen3TTSTalkerConfig+ base_model_prefix = "talker"++ def __init__(self, config: Qwen3TTSTalkerConfig):+ super().__init__(config)+ self.model = Qwen3TTSTalkerModel(config)+ self.vocab_size = config.vocab_size+ self.text_projection = Qwen3TTSTalkerResizeMLP(+ config.text_hidden_size, config.text_hidden_size, config.hidden_size, config.hidden_act, bias=True+ )++ self.codec_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)+ self.code_predictor = Qwen3TTSTalkerCodePredictorModelForConditionalGeneration(+ config=config.code_predictor_config,+ talker_config=config+ )+ self.rope_deltas = None++ # Initialize weights and apply final processing+ self.post_init()++ # TODO: hack, modular cannot inherit multiple classes++ def get_input_embeddings(self):+ return self.model.get_input_embeddings()++ def get_text_embeddings(self):+ return self.model.get_text_embeddings()++ @property+ def device(self) -> torch.device:+ if torch.cuda.is_available():+ return torch.device("cuda")+ return super().device++ def set_input_embeddings(self, value):+ self.model.embed_tokens = value++ def get_output_embeddings(self):+ return self.lm_head++ def set_output_embeddings(self, new_embeddings):+ self.lm_head = new_embeddings++ def set_decoder(self, decoder):+ self.model = decoder++ def get_decoder(self):+ return self.model++ def forward_sub_talker_finetune(self, codec_ids, talker_hidden_states):+ assert len(codec_ids.shape) == 2+ assert len(talker_hidden_states.shape) == 2+ assert codec_ids.shape[0] == talker_hidden_states.shape[0]+ assert talker_hidden_states.shape[1] == self.config.hidden_size+ assert codec_ids.shape[1] == self.config.num_code_groups++ sub_talker_inputs_embeds = [talker_hidden_states.unsqueeze(1)]++ for i in range(self.config.num_code_groups - 1):+ if i == 0:+ sub_talker_inputs_embeds.append(self.get_input_embeddings()(codec_ids[:, :1]))+ else:+ sub_talker_inputs_embeds.append(self.code_predictor.get_input_embeddings()[i-1](codec_ids[:, i:i+1]))+ sub_talker_inputs_embeds = torch.cat(sub_talker_inputs_embeds, dim=1)++ sub_talker_outputs = self.code_predictor.forward_finetune(inputs_embeds=sub_talker_inputs_embeds,+ labels=codec_ids[:, 1:])++ sub_talker_logits = sub_talker_outputs.logits+ sub_talker_loss = sub_talker_outputs.loss+ return sub_talker_logits, sub_talker_loss++ @can_return_tuple+ def forward(+ self,+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=None,+ inputs_embeds=None,+ labels=None,+ use_cache=None,+ output_attentions=None,+ output_hidden_states=None,+ cache_position=None,+ past_hidden=None,+ trailing_text_hidden=None,+ tts_pad_embed=None,+ generation_step=None,+ subtalker_dosample=None,+ subtalker_top_p=None,+ subtalker_top_k=None,+ subtalker_temperature=None,+ **kwargs,+ ) -> CausalLMOutputWithPast:+ r"""+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.+ ```"""+ # Prefill+ if inputs_embeds is not None and inputs_embeds.shape[1] > 1:+ generation_step = -1+ codec_ids = None+ # Generate+ else:+ _check_abort(self)+ last_id_hidden = self.get_input_embeddings()(input_ids)+ predictor_result = self.code_predictor.generate(+ inputs_embeds=torch.cat((past_hidden, last_id_hidden), dim=1),+ max_new_tokens=self.config.num_code_groups - 1,+ do_sample=subtalker_dosample,+ top_p=subtalker_top_p,+ top_k=subtalker_top_k,+ temperature=subtalker_temperature,+ output_hidden_states=True,+ return_dict_in_generate=True,+ )+ codec_ids = torch.cat((input_ids, predictor_result.sequences), dim=-1)+ codec_hiddens = torch.cat(+ [last_id_hidden]+ + [self.code_predictor.get_input_embeddings()[i](predictor_result.sequences[..., i:i+1]) for i in range(self.config.num_code_groups - 1)],+ dim=1,+ )+ inputs_embeds = codec_hiddens.sum(1, keepdim=True)++ if generation_step < trailing_text_hidden.shape[1]:+ inputs_embeds = inputs_embeds + trailing_text_hidden[:, generation_step].unsqueeze(1)+ else:+ inputs_embeds = inputs_embeds + tts_pad_embed+ if attention_mask is not None:+ if (+ cache_position is None+ or (cache_position is not None and cache_position[0] == 0)+ or self.rope_deltas is None+ ):+ delta0 = (1 - attention_mask).sum(dim=-1).unsqueeze(1)+ position_ids, rope_deltas = self.get_rope_index(+ attention_mask,+ )+ rope_deltas = rope_deltas - delta0+ self.rope_deltas = rope_deltas+ else:+ batch_size, seq_length = input_ids.shape+ delta = cache_position[0] + self.rope_deltas if cache_position is not None else 0+ position_ids = torch.arange(seq_length, device=input_ids.device)+ position_ids = position_ids.view(1, -1).expand(batch_size, -1)+ position_ids = position_ids.add(delta)+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)++ outputs: BaseModelOutputWithPast = self.model(+ input_ids=None,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ cache_position=cache_position,+ **kwargs,+ )++ hidden_states = outputs.last_hidden_state+ logits = self.codec_head(hidden_states)++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)+++ return Qwen3TTSTalkerOutputWithPast(+ loss=loss,+ logits=logits,+ past_key_values=outputs.past_key_values,+ hidden_states=(outputs.hidden_states, codec_ids),+ attentions=outputs.attentions,+ past_hidden=hidden_states[:, -1:, :],+ generation_step=generation_step + 1,+ trailing_text_hidden=trailing_text_hidden,+ tts_pad_embed=tts_pad_embed,+ )++ def get_rope_index(+ self,+ attention_mask: Optional[torch.Tensor] = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.++ Explanation:+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.++ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.+ Examples:+ input_ids: [T T T T T], here T is for text.+ temporal position_ids: [0, 1, 2, 3, 4]+ height position_ids: [0, 1, 2, 3, 4]+ width position_ids: [0, 1, 2, 3, 4]++ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part+ and 1D rotary position embedding for text part.+ Examples:+ Temporal (Time): 3 patches, representing different segments of the video in time.+ Height: 2 patches, dividing each frame vertically.+ Width: 2 patches, dividing each frame horizontally.+ We also have some important parameters:+ fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.+ interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.+ text temporal position_ids: [101, 102, 103, 104, 105]+ text height position_ids: [101, 102, 103, 104, 105]+ text width position_ids: [101, 102, 103, 104, 105]+ Here we calculate the text start position_ids as the max vision position_ids plus 1.++ Args:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide+ it.+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:++ - 1 for tokens that are **not masked**,+ - 0 for tokens that are **masked**.++ Returns:+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)+ """+ mrope_position_deltas = []++ position_ids = attention_mask.float().cumsum(-1) - 1+ position_ids.masked_fill_(attention_mask == 0, 1)+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]+ mrope_position_deltas = max_position_ids + 1 - torch.sum(attention_mask, dim=-1, keepdim=True)++ return position_ids, mrope_position_deltas++ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder=False, num_new_tokens=1):+ model_kwargs = super()._update_model_kwargs_for_generation(+ outputs, model_kwargs, is_encoder_decoder, num_new_tokens+ )+ model_kwargs["past_hidden"] = outputs.past_hidden+ model_kwargs["generation_step"] = outputs.generation_step+ model_kwargs["trailing_text_hidden"] = outputs.trailing_text_hidden+ model_kwargs["tts_pad_embed"] = outputs.tts_pad_embed+ return model_kwargs+++class Qwen3TTSForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin):+ config_class = Qwen3TTSConfig++ def __init__(self, config: Qwen3TTSConfig):+ super().__init__(config)+ self.config = config++ self.talker = Qwen3TTSTalkerForConditionalGeneration(self.config.talker_config)++ if config.tts_model_type == "base":+ self.speaker_encoder = Qwen3TTSSpeakerEncoder(self.config.speaker_encoder_config)+ else:+ self.speaker_encoder = None+ # Keep a second module so offload wrapper does not strip prefixes.+ self._load_guard = torch.nn.Identity()++ self.speech_tokenizer = None+ self.generate_config = None++ self.supported_speakers = self.config.talker_config.spk_id.keys()+ self.supported_languages = ["auto"]+ for language_id in self.config.talker_config.codec_language_id.keys():+ if "dialect" not in language_id:+ self.supported_languages.append(language_id)++ self.speaker_encoder_sample_rate = self.config.speaker_encoder_config.sample_rate+ self.tokenizer_type = self.config.tokenizer_type+ self.tts_model_size = self.config.tts_model_size+ self.tts_model_type = self.config.tts_model_type++ self.post_init()++ def load_speech_tokenizer(self, speech_tokenizer):+ self.speech_tokenizer = speech_tokenizer++ def load_generate_config(self, generate_config):+ self.generate_config = generate_config++ def get_supported_speakers(self):+ return self.supported_speakers++ def get_supported_languages(self):+ return self.supported_languages++ @classmethod+ def from_pretrained(+ cls,+ pretrained_model_name_or_path,+ *model_args,+ config=None,+ cache_dir=None,+ ignore_mismatched_sizes=False,+ force_download=False,+ local_files_only=False,+ token=None,+ revision="main",+ use_safetensors=None,+ weights_only=True,+ **kwargs,+ ):+ model = super().from_pretrained(+ pretrained_model_name_or_path,+ *model_args,+ config=config,+ cache_dir=cache_dir,+ ignore_mismatched_sizes=ignore_mismatched_sizes,+ force_download=force_download,+ local_files_only=local_files_only,+ token=token,+ revision=revision,+ use_safetensors=use_safetensors,+ weights_only=weights_only,+ **kwargs,+ )+ if not local_files_only and not os.path.isdir(pretrained_model_name_or_path):+ download_cache_dir = kwargs.get("cache_dir", cache_dir)+ download_revision = kwargs.get("revision", revision)+ download_weights_from_hf_specific(+ pretrained_model_name_or_path,+ cache_dir=download_cache_dir,+ allow_patterns=["speech_tokenizer/*"],+ revision=download_revision,+ )+ speech_tokenizer_path = cached_file(+ pretrained_model_name_or_path,+ "speech_tokenizer/config.json",+ subfolder=kwargs.pop("subfolder", None),+ cache_dir=kwargs.pop("cache_dir", None),+ force_download=kwargs.pop("force_download", False),+ proxies=kwargs.pop("proxies", None),+ resume_download=kwargs.pop("resume_download", None),+ local_files_only=kwargs.pop("local_files_only", False),+ token=kwargs.pop("use_auth_token", None),+ revision=kwargs.pop("revision", None),+ )+ if speech_tokenizer_path is None:+ raise ValueError(f"""{pretrained_model_name_or_path}/{speech_tokenizer_path} not exists""")+ speech_tokenizer_dir = os.path.dirname(speech_tokenizer_path)+ speech_tokenizer = Qwen3TTSTokenizer.from_pretrained(+ speech_tokenizer_dir,+ *model_args,+ **kwargs,+ )+ model.load_speech_tokenizer(speech_tokenizer)++ generate_config_path = cached_file(+ pretrained_model_name_or_path,+ "generation_config.json",+ subfolder=kwargs.pop("subfolder", None),+ cache_dir=kwargs.pop("cache_dir", None),+ force_download=kwargs.pop("force_download", False),+ proxies=kwargs.pop("proxies", None),+ resume_download=kwargs.pop("resume_download", None),+ local_files_only=kwargs.pop("local_files_only", False),+ token=kwargs.pop("use_auth_token", None),+ revision=kwargs.pop("revision", None),+ )+ with open(generate_config_path, "r", encoding="utf-8") as f:+ generate_config = json.load(f)+ model.load_generate_config(generate_config)++ return model++ @torch.inference_mode()+ def extract_speaker_embedding(self, audio, sr):+ assert sr == 24000, "Only support 24kHz audio"+ mels = mel_spectrogram(+ torch.from_numpy(audio).unsqueeze(0),+ n_fft=1024,+ num_mels=128,+ sampling_rate=24000,+ hop_size=256,+ win_size=1024,+ fmin=0,+ fmax=12000+ ).transpose(1, 2)+ speaker_embedding = self.speaker_encoder(mels.to(self.device).to(self.dtype))[0]+ return speaker_embedding++ @torch.inference_mode()+ def generate_speaker_prompt(+ self,+ voice_clone_prompt: list[dict]+ ):+ voice_clone_spk_embeds = []+ for index in range(len(voice_clone_prompt['ref_spk_embedding'])):+ _check_abort(self)+ ref_spk_embedding = voice_clone_prompt["ref_spk_embedding"][index].to(self.talker.dtype)+ voice_clone_spk_embeds.append(ref_spk_embedding)++ return voice_clone_spk_embeds++ def generate_icl_prompt(+ self,+ text_id: torch.Tensor,+ ref_id: torch.Tensor,+ ref_code: torch.Tensor,+ tts_pad_embed: torch.Tensor,+ tts_eos_embed: torch.Tensor,+ non_streaming_mode: bool,+ ):+ # text embed (ref id + text id + eos) 1 T1 D+ text_embed = self.talker.text_projection(+ self.talker.get_text_embeddings()(torch.cat([ref_id, text_id],+ dim=-1)))+ text_embed = torch.cat([text_embed, tts_eos_embed], dim=1)+ # codec embed (codec bos + codec) 1 T2 D+ codec_embed = []+ for i in range(self.talker.config.num_code_groups):+ if i == 0:+ codec_embed.append(self.talker.get_input_embeddings()(ref_code[:, :1]))+ else:+ codec_embed.append(self.talker.code_predictor.get_input_embeddings()[i-1](ref_code[:, i:i+1]))+ codec_embed = torch.cat(codec_embed, dim=1).sum(1).unsqueeze(0)+ codec_embed = torch.cat([self.talker.get_input_embeddings()(+ torch.tensor(+ [[+ self.config.talker_config.codec_bos_id,+ ]],+ device=text_id.device,+ dtype=text_id.dtype,+ )+ ), codec_embed], dim=1)+ # compute lens+ text_lens = text_embed.shape[1]+ codec_lens = codec_embed.shape[1]+ if non_streaming_mode:+ icl_input_embed = text_embed + self.talker.get_input_embeddings()(+ torch.tensor(+ [[+ self.config.talker_config.codec_pad_id,+ ] * text_lens],+ device=text_id.device,+ dtype=text_id.dtype,+ )+ )+ icl_input_embed = torch.cat([icl_input_embed, codec_embed + tts_pad_embed], dim=1)+ return icl_input_embed, tts_pad_embed+ else:+ if text_lens > codec_lens:+ return text_embed[:, :codec_lens] + codec_embed, text_embed[:, codec_lens:]+ else:+ text_embed = torch.cat([text_embed] + [tts_pad_embed] * (codec_lens - text_lens), dim=1)+ return text_embed + codec_embed, tts_pad_embed++ @torch.no_grad()+ def generate(+ self,+ input_ids: Optional[list[torch.Tensor]] = None,+ instruct_ids: Optional[list[torch.Tensor]] = None,+ ref_ids: Optional[list[torch.Tensor]] = None,+ voice_clone_prompt: list[dict] = None,+ languages: list[str] = None,+ speakers: list[str] = None,+ non_streaming_mode = False,+ max_new_tokens: int = 4096,+ do_sample: bool = True,+ top_k: int = 50,+ top_p: float = 1.0,+ temperature: float = 0.9,+ subtalker_dosample: bool = True,+ subtalker_top_k: int = 50,+ subtalker_top_p: float = 1.0,+ subtalker_temperature: float = 0.9,+ eos_token_id: Optional[int] = None,+ repetition_penalty: float = 1.05,+ **kwargs,+ ):+ _check_abort(self)+ talker_kwargs = {+ "max_new_tokens": max_new_tokens,+ "min_new_tokens": 0,+ "do_sample": do_sample,+ "top_k": top_k,+ "top_p": top_p,+ "temperature": temperature,+ "subtalker_dosample": subtalker_dosample,+ "subtalker_top_k": subtalker_top_k,+ "subtalker_top_p": subtalker_top_p,+ "subtalker_temperature": subtalker_temperature,+ "eos_token_id": eos_token_id+ if eos_token_id is not None+ else self.config.talker_config.codec_eos_token_id,+ "repetition_penalty": repetition_penalty,+ "output_hidden_states": True,+ "return_dict_in_generate": True,+ }+ for key in (+ "stopping_criteria",+ "logits_processor",+ "logits_warper",+ "output_scores",+ "output_attentions",+ "use_cache",+ "pad_token_id",+ ):+ if key in kwargs:+ talker_kwargs[key] = kwargs[key]++ talker_input_embeds = [[] for _ in range(len(input_ids))]++ voice_clone_spk_embeds = None+ # voice clone speaker prompt generate+ if voice_clone_prompt is not None:+ voice_clone_spk_embeds = self.generate_speaker_prompt(voice_clone_prompt)++ # instruct text prompt generate+ if instruct_ids is not None:+ for index, instruct_id in enumerate(instruct_ids):+ _check_abort(self)+ if instruct_id is not None:+ talker_input_embeds[index].append(self.talker.text_projection(+ self.talker.get_text_embeddings()(instruct_id)))++ # tts text prompt generate+ trailing_text_hiddens = []+ if speakers is None:+ speakers = [None] * len(input_ids)+ for index, (input_id, language, speaker) in enumerate(zip(input_ids, languages, speakers)):+ _check_abort(self)+ if voice_clone_spk_embeds is None:+ if speaker == "" or speaker == None: # Instruct create speaker+ speaker_embed = None+ else:+ if speaker.lower() not in self.config.talker_config.spk_id:+ raise NotImplementedError(f"Speaker {speaker} not implemented")+ else:+ spk_id = self.config.talker_config.spk_id[speaker.lower()]+ speaker_embed = self.talker.get_input_embeddings()(+ torch.tensor(+ spk_id,+ device=input_id.device,+ dtype=input_id.dtype,+ )+ )+ else:+ if voice_clone_prompt["x_vector_only_mode"][index] or voice_clone_prompt["icl_mode"][index]:+ speaker_embed = voice_clone_spk_embeds[index].to(input_id.device).to(self.talker.dtype)+ else:+ speaker_embed = None++ assert language is not None++ if language.lower() == "auto":+ language_id = None+ else:+ if language.lower() not in self.config.talker_config.codec_language_id:+ raise NotImplementedError(f"Language {language} not implemented")+ else:+ language_id = self.config.talker_config.codec_language_id[language.lower()]++ if (language.lower() in ["chinese", "auto"] and \+ speaker != "" and speaker is not None and \+ self.config.talker_config.spk_is_dialect[speaker.lower()] != False):+ dialect = self.config.talker_config.spk_is_dialect[speaker.lower()]+ language_id = self.config.talker_config.codec_language_id[dialect]++ tts_bos_embed, tts_eos_embed, tts_pad_embed = self.talker.text_projection(+ self.talker.get_text_embeddings()(+ torch.tensor(+ [[self.config.tts_bos_token_id, self.config.tts_eos_token_id, self.config.tts_pad_token_id]],+ device=input_id.device,+ dtype=input_id.dtype,+ )+ )+ ).chunk(3, dim=1) # 3 * [1 1 d]++ # codec: tag and speaker+ if language_id is None:+ codec_prefill_list = [[+ self.config.talker_config.codec_nothink_id,+ self.config.talker_config.codec_think_bos_id,+ self.config.talker_config.codec_think_eos_id,+ ]]+ else:+ codec_prefill_list = [[+ self.config.talker_config.codec_think_id,+ self.config.talker_config.codec_think_bos_id,+ language_id,+ self.config.talker_config.codec_think_eos_id,+ ]]++ codec_input_emebdding_0 = self.talker.get_input_embeddings()(+ torch.tensor(+ codec_prefill_list,+ device=input_id.device,+ dtype=input_id.dtype,+ )+ )+ codec_input_emebdding_1 = self.talker.get_input_embeddings()(+ torch.tensor(+ [[+ self.config.talker_config.codec_pad_id,+ self.config.talker_config.codec_bos_id,+ ]],+ device=input_id.device,+ dtype=input_id.dtype,+ )+ )+ if speaker_embed is None:+ codec_input_emebdding = torch.cat([codec_input_emebdding_0,+ codec_input_emebdding_1], dim=1)+ else:+ codec_input_emebdding = torch.cat([codec_input_emebdding_0,+ speaker_embed.view(1, 1, -1),+ codec_input_emebdding_1], dim=1)++ # Example assistant prefix.++ # <|im_start|>assistant\n+ _talker_input_embed_role = self.talker.text_projection(+ self.talker.get_text_embeddings()(input_id[:, :3])+ )++ # tts_pad * 4 + tts_bos+ _talker_input_embed = torch.cat((tts_pad_embed.expand(-1, codec_input_emebdding.shape[1] - 2, -1),+ tts_bos_embed,+ ), dim=1) + codec_input_emebdding[:, :-1]++ talker_input_embed = torch.cat((_talker_input_embed_role, _talker_input_embed), dim=1)++ if voice_clone_prompt is not None and voice_clone_prompt["ref_code"] is not None and voice_clone_prompt["icl_mode"][index]:+ icl_input_embed, trailing_text_hidden = self.generate_icl_prompt(+ text_id=input_id[:, 3:-5],+ ref_id=ref_ids[index][:, 3:-2],+ ref_code=voice_clone_prompt["ref_code"][index].to(input_id.device),+ tts_pad_embed=tts_pad_embed,+ tts_eos_embed=tts_eos_embed,+ non_streaming_mode=non_streaming_mode,+ )+ talker_input_embed = torch.cat([talker_input_embed, icl_input_embed], dim=1)+ else:+ # tts_text_first_token+ talker_input_embed = torch.cat([talker_input_embed,+ self.talker.text_projection(self.talker.get_text_embeddings()(input_id[:, 3:4])) + codec_input_emebdding[:, -1:]],+ dim=1)+ if non_streaming_mode:+ talker_input_embed = talker_input_embed[:, :-1] # drop the original text token+ talker_input_embed = torch.cat([talker_input_embed,+ torch.cat((self.talker.text_projection(+ self.talker.get_text_embeddings()(input_id[:, 3:-5])+ ), tts_eos_embed), dim=1) + self.talker.get_input_embeddings()(+ torch.tensor(+ [[+ self.config.talker_config.codec_pad_id,+ ] * (input_id[:, 3:-5].shape[1] + 1)],+ device=input_id.device,+ dtype=input_id.dtype,+ )+ ),+ tts_pad_embed + self.talker.get_input_embeddings()(+ torch.tensor(+ [[+ self.config.talker_config.codec_bos_id,+ ]],+ device=input_id.device,+ dtype=input_id.dtype,+ )+ )+ ], dim=1)+ trailing_text_hidden = tts_pad_embed+ else:+ # Example trailing text prompt.+ trailing_text_hidden = torch.cat((self.talker.text_projection(+ self.talker.get_text_embeddings()(input_id[:, 4:-5])+ ), tts_eos_embed), dim=1)+ talker_input_embeds[index].append(talker_input_embed)+ trailing_text_hiddens.append(trailing_text_hidden)++ for index, talker_input_embed in enumerate(talker_input_embeds):+ _check_abort(self)+ talker_input_embeds[index] = torch.cat([item for item in talker_input_embed if item is not None], dim=1)++ # for batch inferquence+ original_lengths = torch.tensor([t.shape[1] for t in talker_input_embeds])+ # left padding for talker input embeds+ sequences = [t.squeeze(0) for t in talker_input_embeds]+ sequences_reversed = [t.flip(dims=[0]) for t in sequences]+ padded_reversed = torch.nn.utils.rnn.pad_sequence(+ sequences_reversed,+ batch_first=True,+ padding_value=0.0+ )+ talker_input_embeds = padded_reversed.flip(dims=[1])+ # generate mask+ batch_size, max_len = talker_input_embeds.shape[0], talker_input_embeds.shape[1]+ indices = torch.arange(max_len).expand(batch_size, -1)+ num_pads = max_len - original_lengths+ talker_attention_mask = (indices >= num_pads.unsqueeze(1)).long().to(talker_input_embeds.device)+ # padding trailing text hiddens+ pad_embedding_vector = tts_pad_embed.squeeze()+ sequences_to_pad = [t.squeeze(0) for t in trailing_text_hiddens]+ trailing_text_original_lengths = [s.shape[0] for s in sequences_to_pad]+ padded_hiddens = torch.nn.utils.rnn.pad_sequence(+ sequences_to_pad,+ batch_first=True,+ padding_value=0.0+ )+ arange_tensor = torch.arange(max(trailing_text_original_lengths),+ device=padded_hiddens.device).expand(len(trailing_text_original_lengths), -1)+ lengths_tensor = torch.tensor(trailing_text_original_lengths, device=padded_hiddens.device).unsqueeze(1)+ padding_mask = arange_tensor >= lengths_tensor+ padded_hiddens[padding_mask] = pad_embedding_vector+ trailing_text_hiddens = padded_hiddens++ # forward+ target_device = torch.device("cuda") if torch.cuda.is_available() else talker_input_embeds.device++ _check_abort(self)+ talker_result = self.talker.generate(+ inputs_embeds=talker_input_embeds.to(target_device),+ attention_mask=talker_attention_mask.to(target_device),+ trailing_text_hidden=trailing_text_hiddens.to(target_device),+ tts_pad_embed=tts_pad_embed.to(target_device),+ **talker_kwargs,+ )++ talker_codes = torch.stack([hid[-1] for hid in talker_result.hidden_states if hid[-1] is not None], dim=1)+ talker_hidden_states = torch.cat([hid[0][-1][:, -1:] for hid in talker_result.hidden_states], dim=1)[:, :-1]++ first_codebook = talker_codes[:, :, 0]+ is_stop_token = (first_codebook == self.config.talker_config.codec_eos_token_id)+ stop_indices = torch.argmax(is_stop_token.int(), dim=1)+ has_stop_token = is_stop_token.any(dim=1)+ effective_lengths = torch.where(has_stop_token, stop_indices, talker_codes.shape[1])++ talker_codes_list = [talker_codes[i, :length, ] for i, length in enumerate(effective_lengths)]+ talker_hidden_states_list = [talker_hidden_states[i, :length, :] for i, length in enumerate(effective_lengths)]++ return talker_codes_list, talker_hidden_states_list++__all__ = [+ "Qwen3TTSForConditionalGeneration",+ "Qwen3TTSTalkerForConditionalGeneration",+ "Qwen3TTSPreTrainedModel",+ "Qwen3TTSTalkerModel",+]diff --git a/models/TTS/qwen3/core/models/processing_qwen3_tts.py b/models/TTS/qwen3/core/models/processing_qwen3_tts.pynew file mode 100644index 0000000..bed9bff--- /dev/null+++ b/models/TTS/qwen3/core/models/processing_qwen3_tts.py@@ -0,0 +1,106 @@+# coding=utf-8+# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+from transformers.feature_extraction_utils import BatchFeature+from transformers.processing_utils import ProcessingKwargs, ProcessorMixin+++class Qwen3TTSProcessorKwargs(ProcessingKwargs, total=False):+ _defaults = {+ "text_kwargs": {+ "padding": False,+ "padding_side": "left",+ }+ }++class Qwen3TTSProcessor(ProcessorMixin):+ r"""+ Constructs a Qwen3TTS processor.++ Args:+ tokenizer ([`Qwen2TokenizerFast`], *optional*):+ The text tokenizer.+ chat_template (`Optional[str]`, *optional*):+ The Jinja template to use for formatting the conversation. If not provided, the default chat template is used.+ """++ attributes = ["tokenizer"]+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")++ def __init__(+ self, tokenizer=None, chat_template=None+ ):+ super().__init__(tokenizer, chat_template=chat_template)++ def __call__(self, text=None, **kwargs) -> BatchFeature:+ """+ Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text`+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode+ the text.++ Args:+ text (`str`, `List[str]`, `List[List[str]]`):+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).+ """++ if text is None:+ raise ValueError("You need to specify either a `text` input to process.")++ output_kwargs = self._merge_kwargs(+ Qwen3TTSProcessorKwargs,+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,+ **kwargs,+ )+ if not isinstance(text, list):+ text = [text]++ texts_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])++ return BatchFeature(+ data={**texts_inputs},+ tensor_type=kwargs.get("return_tensors"),+ )++ def batch_decode(self, *args, **kwargs):+ """+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please+ refer to the docstring of this method for more information.+ """+ return self.tokenizer.batch_decode(*args, **kwargs)++ def decode(self, *args, **kwargs):+ """+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to+ the docstring of this method for more information.+ """+ return self.tokenizer.decode(*args, **kwargs)++ def apply_chat_template(self, conversations, chat_template=None, **kwargs):+ if isinstance(conversations[0], dict):+ conversations = [conversations]+ return super().apply_chat_template(conversations, chat_template, **kwargs)++ @property+ def model_input_names(self):+ tokenizer_input_names = self.tokenizer.model_input_names+ return list(+ dict.fromkeys(+ tokenizer_input_names+ )+ )+++__all__ = ["Qwen3TTSProcessor"]diff --git a/models/TTS/qwen3/core/tokenizer_12hz/__init__.py b/models/TTS/qwen3/core/tokenizer_12hz/__init__.pynew file mode 100644index 0000000..6166b02--- /dev/null+++ b/models/TTS/qwen3/core/tokenizer_12hz/__init__.py@@ -0,0 +1,4 @@+from .configuration_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Config+from .modeling_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Model++__all__ = ["Qwen3TTSTokenizerV2Config", "Qwen3TTSTokenizerV2Model"]diff --git a/models/TTS/qwen3/core/tokenizer_12hz/configuration_qwen3_tts_tokenizer_v2.py b/models/TTS/qwen3/core/tokenizer_12hz/configuration_qwen3_tts_tokenizer_v2.pynew file mode 100644index 0000000..82658a5--- /dev/null+++ b/models/TTS/qwen3/core/tokenizer_12hz/configuration_qwen3_tts_tokenizer_v2.py@@ -0,0 +1,172 @@+# coding=utf-8+# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Qwen3TTSTokenizerV2 model configuration"""++from transformers.configuration_utils import PretrainedConfig+from transformers.utils import logging++from transformers import MimiConfig+++logger = logging.get_logger(__name__)+++class Qwen3TTSTokenizerV2DecoderConfig(PretrainedConfig):+ r"""+ This is the configuration class to store the configuration of a [`Qwen3TTSTokenizerV2DecoderConfig`].++ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the+ documentation from [`PretrainedConfig`] for more information.++ Args:+ codebook_size (`int`, *optional*, defaults to 2048):+ Number of entries in each residual codebook used for acoustic token quantization.+ hidden_size (`int`, *optional*, defaults to 1024):+ Dimensionality of the hidden states and embeddings in the autoregressive transformer decoder.+ max_position_embeddings (`int`, *optional*, defaults to 8000):+ Maximum sequence length that the autoregressive decoder can handle. Determines positional embedding size.+ rope_theta (`float`, *optional*, defaults to 10000.0):+ The base period for rotary position embeddings (RoPE) applied to attention layers.+ num_attention_heads (`int`, *optional*, defaults to 16):+ Number of attention heads for each attention layer in the decoder.+ num_key_value_heads (`int`, *optional*, defaults to 16):+ Number of key and value attention heads used in grouped-query attention (if applicable).+ attention_bias (`bool`, *optional*, defaults to `False`):+ Whether to use bias in the attention projection layers.+ sliding_window (`int`, *optional*, defaults to 72):+ Window size for local attention mechanism, limiting attention context to improve efficiency.+ intermediate_size (`int`, *optional*, defaults to 3072):+ Dimensionality of the feed-forward (intermediate) layer in each transformer block.+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):+ The non-linear activation function used in the feed-forward layers. Supports `"silu"`, `"relu"`, `"gelu"`, etc.+ layer_scale_initial_scale (`float`, *optional*, defaults to 0.01):+ Initial value for LayerScale applied in transformer blocks, helping stabilize training.+ rms_norm_eps (`float`, *optional*, defaults to 1e-5):+ Epsilon value for RMS normalization layers to prevent division by zero.+ num_hidden_layers (`int`, *optional*, defaults to 8):+ Number of transformer blocks in the autoregressive decoder.+ num_quantizers (`int`, *optional*, defaults to 16):+ Number of residual vector quantizers used in the vocoder for fine-grained audio reconstruction.+ upsample_rates (`Tuple[int]`, *optional*, defaults to `(8, 5, 4, 3)`):+ Rate at which features are upsampled in the final waveform synthesis stage.+ upsampling_ratios (`Tuple[int]`, *optional*, defaults to `(2, 2)`):+ Ratios used in transposed convolutional layers to progressively upsample feature maps to waveform.+ decoder_dim (`int`, *optional*, defaults to 1536):+ Final dimensionality of the decoder's output before waveform generation.+ attention_dropout (`float`, *optional*, defaults to 0.0):+ Dropout probability applied to attention weights in the decoder.+ """++ def __init__(+ self,+ codebook_size=2048,+ hidden_size=1024,+ latent_dim=1024,+ max_position_embeddings=8000,+ rope_theta=10000,+ num_attention_heads=16,+ num_key_value_heads=16,+ attention_bias=False,+ sliding_window=72,+ intermediate_size=3072,+ hidden_act="silu",+ layer_scale_initial_scale=0.01,+ rms_norm_eps=1e-5,+ num_hidden_layers=8,+ num_quantizers=16,+ upsample_rates=(8, 5, 4, 3),+ upsampling_ratios=(2, 2),+ decoder_dim=1536,+ attention_dropout=0.0,+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.codebook_size = codebook_size+ self.hidden_size = hidden_size+ self.latent_dim = latent_dim+ self.max_position_embeddings = max_position_embeddings+ self.rope_theta = rope_theta+ self.num_attention_heads = num_attention_heads+ self.num_key_value_heads = num_key_value_heads+ self.attention_bias = attention_bias+ self.sliding_window = sliding_window+ self.intermediate_size = intermediate_size+ self.hidden_act = hidden_act+ self.layer_scale_initial_scale = layer_scale_initial_scale+ self.rms_norm_eps = rms_norm_eps+ self.num_hidden_layers = num_hidden_layers+ self.num_quantizers = num_quantizers+ self.upsample_rates = upsample_rates+ self.upsampling_ratios = upsampling_ratios+ self.decoder_dim = decoder_dim+ self.attention_dropout = attention_dropout++ @property+ def layer_types(self):+ """+ All layer in code2wav should be sliding attention+ """+ return ["sliding_attention"] * self.num_hidden_layers+++class Qwen3TTSTokenizerV2Config(PretrainedConfig):+ """+ This is the configuration class to store the configuration of a [`Qwen3TTSTokenizerV2Config`]. It is used to instantiate a Qwen3TTSTokenizerV2Model+ model according to the specified sub-models configurations, defining the model architecture.++ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the+ documentation from [`PretrainedConfig`] for more information.++ Args:+ encoder_config (`dict`, *optional*): Configuration of the underlying encoder sub-model.+ decoder_config (`dict`, *optional*): Configuration of the underlying decoder sub-model.+ """++ model_type = "qwen3_tts_tokenizer_12hz"+ sub_configs = {+ "encoder_config": MimiConfig,+ "decoder_config": Qwen3TTSTokenizerV2DecoderConfig,+ }++ def __init__(+ self,+ encoder_config=None,+ decoder_config=None,+ encoder_valid_num_quantizers=16,+ input_sample_rate=24000,+ output_sample_rate=24000,+ decode_upsample_rate=1920,+ encode_downsample_rate=1920,+ **kwargs,+ ):+ super().__init__(**kwargs)+ if encoder_config is None:+ encoder_config = {}+ logger.info("encoder_config is None. Initializing encoder with default values")+ if decoder_config is None:+ decoder_config = {}+ logger.info("decoder_config is None. Initializing decoder with default values")++ self.encoder_config = MimiConfig(**encoder_config)+ self.decoder_config = Qwen3TTSTokenizerV2DecoderConfig(**decoder_config)++ self.encoder_valid_num_quantizers = encoder_valid_num_quantizers+ self.input_sample_rate = input_sample_rate+ self.output_sample_rate = output_sample_rate+ self.decode_upsample_rate = decode_upsample_rate+ self.encode_downsample_rate = encode_downsample_rate+++__all__ = ["Qwen3TTSTokenizerV2Config", "Qwen3TTSTokenizerV2DecoderConfig"]diff --git a/models/TTS/qwen3/core/tokenizer_12hz/modeling_qwen3_tts_tokenizer_v2.py b/models/TTS/qwen3/core/tokenizer_12hz/modeling_qwen3_tts_tokenizer_v2.pynew file mode 100644index 0000000..6d1887b--- /dev/null+++ b/models/TTS/qwen3/core/tokenizer_12hz/modeling_qwen3_tts_tokenizer_v2.py@@ -0,0 +1,1041 @@+# coding=utf-8+# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""PyTorch Qwen3TTSTokenizerV2 model."""++import math+from dataclasses import dataclass+from typing import Callable, Optional, Union, List++import numpy as np+import torch+from torch import nn+from torch.nn import Parameter+from torch.nn import functional as F+from transformers import MimiConfig, MimiModel+from transformers.activations import ACT2FN+from transformers.cache_utils import Cache, DynamicCache+from transformers.integrations import use_kernel_forward_from_hub+from transformers.masking_utils import (+ create_causal_mask,+ create_sliding_window_causal_mask,+)+from transformers.modeling_flash_attention_utils import FlashAttentionKwargs+from transformers.modeling_layers import GradientCheckpointingLayer+from transformers.modeling_outputs import BaseModelOutputWithPast+from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update+from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel+from transformers.processing_utils import Unpack+from transformers.utils import ModelOutput, auto_docstring, logging+from transformers.utils.deprecation import deprecate_kwarg+try:+ from transformers.utils.generic import check_model_inputs+except ImportError:+ def check_model_inputs(*args, **kwargs):+ def decorator(func):+ return func+ return decorator++from .configuration_qwen3_tts_tokenizer_v2 import (+ Qwen3TTSTokenizerV2Config,+ Qwen3TTSTokenizerV2DecoderConfig,+)++logger = logging.get_logger(__name__)+++def _check_abort(module) -> None:+ checker = getattr(module, "_interrupt_check", None)+ if callable(checker) and checker():+ raise RuntimeError("Abort requested")+++@dataclass+@auto_docstring+class Qwen3TTSTokenizerV2EncoderOutput(ModelOutput):+ r"""+ audio_codes (`List[torch.LongTensor]`):+ Discret code embeddings computed using `model.encode`, each tensor has shape (codes_length_i, num_quantizers).+ """++ audio_codes: List[torch.LongTensor] = None+++@dataclass+@auto_docstring+class Qwen3TTSTokenizerV2DecoderOutput(ModelOutput):+ r"""+ audio_values (`List[torch.FloatTensor]`):+ Decoded audio values, obtained using the decoder part of Qwen3TTSTokenizerV1.+ Each tensor has shape (segment_length_i).+ """++ audio_values: List[torch.FloatTensor] = None+++def rotate_half(x):+ """Rotates half the hidden dims of the input."""+ x1 = x[..., : x.shape[-1] // 2]+ x2 = x[..., x.shape[-1] // 2 :]+ return torch.cat((-x2, x1), dim=-1)+++def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):+ """Applies Rotary Position Embedding to the query and key tensors.++ Args:+ q (`torch.Tensor`): The query tensor.+ k (`torch.Tensor`): The key tensor.+ cos (`torch.Tensor`): The cosine part of the rotary embedding.+ sin (`torch.Tensor`): The sine part of the rotary embedding.+ position_ids (`torch.Tensor`, *optional*):+ Deprecated and unused.+ unsqueeze_dim (`int`, *optional*, defaults to 1):+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.+ Returns:+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.+ """+ cos = cos.unsqueeze(unsqueeze_dim)+ sin = sin.unsqueeze(unsqueeze_dim)+ q_embed = (q * cos) + (rotate_half(q) * sin)+ k_embed = (k * cos) + (rotate_half(k) * sin)+ return q_embed, k_embed+++def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:+ """+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)+ """+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape+ if n_rep == 1:+ return hidden_states+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)+++def eager_attention_forward(+ module: nn.Module,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attention_mask: Optional[torch.Tensor],+ scaling: float,+ dropout: float = 0.0,+ **kwargs,+):+ key_states = repeat_kv(key, module.num_key_value_groups)+ value_states = repeat_kv(value, module.num_key_value_groups)++ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling+ if attention_mask is not None:+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]+ attn_weights = attn_weights + causal_mask++ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)+ attn_output = torch.matmul(attn_weights, value_states)+ attn_output = attn_output.transpose(1, 2).contiguous()++ return attn_output, attn_weights+++@auto_docstring+class Qwen3TTSTokenizerV2DecoderPreTrainedModel(PreTrainedModel):+ config: Qwen3TTSTokenizerV2DecoderConfig+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _skip_keys_device_placement = "past_key_values"+ _supports_flash_attn = True+ _supports_sdpa = True+ _can_compile_fullgraph = False+ _supports_attention_backend = True+++class Qwen3TTSTokenizerV2CausalConvNet(nn.Module):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size,+ dilation=1,+ stride=1,+ groups=1,+ ):+ super().__init__()+ self.conv = nn.Conv1d(+ in_channels,+ out_channels,+ kernel_size,+ stride=stride,+ dilation=dilation,+ groups=groups,+ )+ self.stride = stride+ self.kernel_size = (kernel_size - 1) * dilation + 1+ self.dilation = dilation+ self.padding = self.kernel_size - self.stride++ def _get_extra_padding_for_conv1d(self, hidden_state: torch.Tensor) -> int:+ length = hidden_state.shape[-1]+ n_frames = (length - self.kernel_size + self.padding) / self.stride + 1+ ideal_length = (math.ceil(n_frames) - 1) * self.stride + (self.kernel_size - self.padding)+ return ideal_length - length++ def forward(self, hidden_state):+ extra_padding = self._get_extra_padding_for_conv1d(hidden_state)+ hidden_state = F.pad(hidden_state, (self.padding, extra_padding), mode="constant", value=0)+ return self.conv(hidden_state).contiguous()+++class Qwen3TTSTokenizerV2CausalTransConvNet(nn.Module):+ def __init__(self, in_channels, out_channels, kernel_size, stride=1):+ super().__init__()+ self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride)++ pad = kernel_size - stride+ self.left_pad = math.ceil(pad)+ self.right_pad = pad = self.left_pad++ def forward(self, hidden_state):+ hidden_state = self.conv(hidden_state)+ hidden_state = hidden_state[..., self.left_pad : hidden_state.shape[-1] - self.right_pad]+ return hidden_state.contiguous()+++class Qwen3TTSTokenizerV2ConvNeXtBlock(nn.Module):+ def __init__(self, dim: int):+ super().__init__()+ self.dwconv = Qwen3TTSTokenizerV2CausalConvNet(+ dim,+ dim,+ kernel_size=7,+ groups=dim,+ dilation=1,+ )+ self.norm = nn.LayerNorm(dim, eps=1e-6)+ self.pwconv1 = nn.Linear(dim, 4 * dim)+ self.act = nn.GELU()+ self.pwconv2 = nn.Linear(4 * dim, dim)+ self.gamma = nn.Parameter(1e-6 * torch.ones(dim))++ def forward(self, hidden_states):+ input = hidden_states++ hidden_states = self.dwconv(hidden_states)+ hidden_states = hidden_states.permute(0, 2, 1)+ hidden_states = self.norm(hidden_states)+ hidden_states = self.pwconv1(hidden_states)+ hidden_states = self.act(hidden_states)+ hidden_states = self.pwconv2(hidden_states)++ hidden_states = self.gamma * hidden_states++ hidden_states = hidden_states.permute(0, 2, 1)++ hidden_states = input + hidden_states++ return hidden_states+++class Qwen3TTSTokenizerV2DecoderRotatoryEmbedding(nn.Module):+ inv_freq: torch.Tensor # fix linting for `register_buffer`++ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, device=None):+ super().__init__()+ # BC: "rope_type" was originally "type"+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))+ else:+ self.rope_type = "default"+ self.max_seq_len_cached = config.max_position_embeddings+ self.original_max_seq_len = config.max_position_embeddings++ self.config = config+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]++ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)+ self.register_buffer("inv_freq", inv_freq, persistent=False)+ self.original_inv_freq = self.inv_freq++ @torch.no_grad()+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)+ def forward(self, x, position_ids):+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)+ position_ids_expanded = position_ids[:, None, :].float()++ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"+ with torch.autocast(device_type=device_type, enabled=False): # Force float32+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = emb.cos() * self.attention_scaling+ sin = emb.sin() * self.attention_scaling++ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)+++class Qwen3TTSTokenizerV2DecoderAttention(nn.Module):+ """Multi-headed attention from 'Attention Is All You Need' paper"""++ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads+ self.scaling = self.head_dim**-0.5+ self.attention_dropout = config.attention_dropout+ self.is_causal = True++ self.q_proj = nn.Linear(+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias+ )+ self.k_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.v_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.o_proj = nn.Linear(+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias+ )+ self.q_norm = nn.Identity()+ self.k_norm = nn.Identity()+ self.sliding_window = config.sliding_window++ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")+ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: Optional[torch.Tensor],+ past_key_values: Optional[Cache] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:+ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)++ cos, sin = position_embeddings+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)++ if past_key_values is not None:+ # sin and cos are specific to RoPE models; cache_position needed for the static cache+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)++ attention_interface: Callable = eager_attention_forward+ if self.config._attn_implementation != "eager":+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]++ attn_output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ sliding_window=self.sliding_window, # diff with Llama+ **kwargs,+ )++ attn_output = attn_output.reshape(*input_shape, -1).contiguous()+ attn_output = self.o_proj(attn_output)+ return attn_output, attn_weights+++class Qwen3TTSTokenizerV2DecoderMlp(nn.Module):+ def __init__(self, config):+ super().__init__()+ self.config = config+ self.hidden_size = config.hidden_size+ self.intermediate_size = config.intermediate_size+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)+ self.act_fn = ACT2FN[config.hidden_act]++ def forward(self, x):+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))+ return down_proj+++@use_kernel_forward_from_hub("RMSNorm")+class Qwen3TTSTokenizerV2DecoderRMSNorm(nn.Module):+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:+ """+ Qwen3TTSTokenizerV2DecoderRMSNorm is equivalent to T5LayerNorm+ """+ super().__init__()+ self.weight = nn.Parameter(torch.ones(hidden_size))+ self.variance_epsilon = eps++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ input_dtype = hidden_states.dtype+ hidden_states = hidden_states.to(torch.float32)+ variance = hidden_states.pow(2).mean(-1, keepdim=True)+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)+ return self.weight * hidden_states.to(input_dtype)++ def extra_repr(self):+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"+++class Qwen3TTSTokenizerV2DecoderLayerScale(nn.Module):+ """Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).+ This rescales diagonally the residual outputs close to 0, with a learnt scale.+ """++ def __init__(self, config):+ super().__init__()+ channels = config.hidden_size+ initial_scale = config.layer_scale_initial_scale+ self.scale = nn.Parameter(torch.full((channels,), initial_scale, requires_grad=True))++ def forward(self, x: torch.Tensor):+ return self.scale * x+++class Qwen3TTSTokenizerV2DecoderTransformerLayer(GradientCheckpointingLayer):+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):+ super().__init__()+ self.hidden_size = config.hidden_size+ self.self_attn = Qwen3TTSTokenizerV2DecoderAttention(config, layer_idx)+ self.mlp = Qwen3TTSTokenizerV2DecoderMlp(config)+ self.input_layernorm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, config.rms_norm_eps)+ self.post_attention_layernorm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, config.rms_norm_eps)+ self.self_attn_layer_scale = Qwen3TTSTokenizerV2DecoderLayerScale(config)+ self.mlp_layer_scale = Qwen3TTSTokenizerV2DecoderLayerScale(config)+ self.attention_type = "sliding_attention"++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Cache] = None,+ use_cache: Optional[bool] = False,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs,+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:+ """+ Args:+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`+ attention_mask (`torch.FloatTensor`, *optional*):+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,+ query_sequence_length, key_sequence_length)` if default attention is used.+ output_attentions (`bool`, *optional*):+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under+ returned tensors for more detail.+ use_cache (`bool`, *optional*):+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding+ (see `past_key_values`).+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):+ Indices depicting the position of the input sequence tokens in the sequence+ kwargs (`dict`, *optional*):+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code+ into the model+ """+ residual = hidden_states++ hidden_states = self.input_layernorm(hidden_states)++ # Self Attention+ hidden_states, _ = self.self_attn(+ hidden_states=hidden_states,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ use_cache=use_cache,+ cache_position=cache_position,+ **kwargs,+ )+ hidden_states = residual + self.self_attn_layer_scale(hidden_states)++ # Fully Connected+ residual = hidden_states+ hidden_states = self.post_attention_layernorm(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = residual + self.mlp_layer_scale(hidden_states)++ return hidden_states+++@auto_docstring+class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTrainedModel):+ _can_record_outputs = {+ "hidden_states": Qwen3TTSTokenizerV2DecoderTransformerLayer,+ "attentions": Qwen3TTSTokenizerV2DecoderAttention,+ }++ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig):+ super().__init__(config)+ self.layers = nn.ModuleList(+ [Qwen3TTSTokenizerV2DecoderTransformerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.rotary_emb = Qwen3TTSTokenizerV2DecoderRotatoryEmbedding(config=config)+ self.gradient_checkpointing = False+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types+ self.window_size = config.sliding_window++ self.input_proj = nn.Linear(config.latent_dim, config.hidden_size)+ self.output_proj = nn.Linear(config.hidden_size, config.latent_dim)++ # Initialize weights and apply final processing+ self.post_init()++ @check_model_inputs()+ @auto_docstring+ def forward(+ self,+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=None,+ inputs_embeds=None,+ use_cache=None,+ cache_position=None,+ **kwargs,+ ) -> BaseModelOutputWithPast:+ if input_ids is not None:+ raise ValueError("input_ids is not expected")+ if (input_ids is None) ^ (inputs_embeds is not None):+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")++ if inputs_embeds is None:+ inputs_embeds = self.embed_tokens(input_ids)++ inputs_embeds = self.input_proj(inputs_embeds)++ if use_cache and past_key_values is None:+ past_key_values = DynamicCache(config=self.config)++ if cache_position is None:+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0+ cache_position = torch.arange(+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device+ )++ if position_ids is None:+ position_ids = cache_position.unsqueeze(0)++ # It may already have been prepared by e.g. `generate`+ if not isinstance(causal_mask_mapping := attention_mask, dict):+ # Prepare mask arguments+ mask_kwargs = {+ "config": self.config,+ "input_embeds": inputs_embeds,+ "attention_mask": attention_mask,+ "cache_position": cache_position,+ "past_key_values": past_key_values,+ "position_ids": position_ids,+ }+ # Create the masks+ causal_mask_mapping = {+ "full_attention": create_causal_mask(**mask_kwargs),+ }+ # The sliding window alternating layers are not always activated depending on the config+ if self.has_sliding_layers:+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)++ hidden_states = inputs_embeds++ # create position embeddings to be shared across the decoder layers+ position_embeddings = self.rotary_emb(hidden_states, position_ids)++ for decoder_layer in self.layers[: self.config.num_hidden_layers]:+ _check_abort(self)+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_ids=position_ids,+ past_key_values=past_key_values,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **kwargs,+ )++ hidden_states = self.norm(hidden_states)+ hidden_states = self.output_proj(hidden_states)+ return BaseModelOutputWithPast(+ last_hidden_state=hidden_states,+ past_key_values=past_key_values if use_cache else None,+ )+++class SnakeBeta(nn.Module):+ """+ A modified Snake function which uses separate parameters for the magnitude of the periodic components+ Shape:+ - Input: (B, C, T)+ - Output: (B, C, T), same shape as the input+ Parameters:+ - alpha - trainable parameter that controls frequency+ - beta - trainable parameter that controls magnitude+ References:+ - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:+ https://huggingface.co/papers/2006.08195+ """++ def __init__(self, in_features, alpha=1.0):+ super().__init__()+ self.in_features = in_features++ # initialize alpha+ self.alpha = Parameter(torch.zeros(in_features) * alpha)+ self.beta = Parameter(torch.zeros(in_features) * alpha)++ self.no_div_by_zero = 0.000000001++ def forward(self, hidden_states):+ """+ Forward pass of the function.+ Applies the function to the input elementwise.+ SnakeBeta := x + 1/b * sin^2(xa)+ """+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]+ beta = self.beta.unsqueeze(0).unsqueeze(-1)+ alpha = torch.exp(alpha)+ beta = torch.exp(beta)+ hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(+ torch.sin(hidden_states * alpha), 2+ )++ return hidden_states+++class Qwen3TTSTokenizerV2DecoderDecoderResidualUnit(nn.Module):+ def __init__(self, dim: int = 16, dilation: int = 1):+ super().__init__()++ self.act1 = SnakeBeta(dim)+ self.conv1 = Qwen3TTSTokenizerV2CausalConvNet(dim, dim, kernel_size=7, dilation=dilation)+ self.act2 = SnakeBeta(dim)+ self.conv2 = Qwen3TTSTokenizerV2CausalConvNet(dim, dim, kernel_size=1)++ def forward(self, hidden_state):+ residual = hidden_state++ hidden_state = self.act1(hidden_state)+ hidden_state = self.conv1(hidden_state)+ hidden_state = self.act2(hidden_state)+ hidden_state = self.conv2(hidden_state)+ return hidden_state + residual+++class Qwen3TTSTokenizerV2DecoderDecoderBlock(Qwen3TTSTokenizerV2DecoderPreTrainedModel):+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):+ super().__init__(config)+ in_dim = config.decoder_dim // 2**layer_idx+ out_dim = config.decoder_dim // 2 ** (layer_idx + 1)+ upsample_rate = config.upsample_rates[layer_idx]++ block = [+ SnakeBeta(in_dim),+ Qwen3TTSTokenizerV2CausalTransConvNet(in_dim, out_dim, 2 * upsample_rate, upsample_rate),+ ]++ for dilation in (1, 3, 9):+ block.append(Qwen3TTSTokenizerV2DecoderDecoderResidualUnit(out_dim, dilation))++ self.block = nn.ModuleList(block)++ def forward(self, hidden):+ for block in self.block:+ hidden = block(hidden)+ return hidden+++class EuclideanCodebook(nn.Module):+ def __init__(+ self,+ dim: int,+ codebook_size: int,+ epsilon: float = 1e-5,+ ):+ super().__init__()+ self.dim = dim+ self.codebook_size = codebook_size+ self.epsilon = epsilon++ self.cluster_usage = nn.Parameter(torch.ones(codebook_size))+ self.embedding_sum = nn.Parameter(torch.zeros(codebook_size, dim))++ def decode(self, codes: torch.Tensor) -> torch.Tensor:+ embedding = self.embedding_sum / self.cluster_usage.clamp(min=self.epsilon)[:, None]+ quantized = F.embedding(codes, embedding)+ return quantized+++class VectorQuantization(nn.Module):+ def __init__(+ self,+ dim: int,+ codebook_size: int,+ codebook_dim: Optional[int] = None,+ epsilon: float = 1e-5,+ ):+ super().__init__()+ if codebook_dim is None:+ codebook_dim = dim++ requires_projection = codebook_dim != dim++ self.project_out = (+ nn.Linear(codebook_dim, dim) if requires_projection else nn.Identity()+ )+ self.epsilon = epsilon+ self._codebook = EuclideanCodebook(+ dim=codebook_dim,+ codebook_size=codebook_size,+ epsilon=epsilon+ )+ self.codebook_size = codebook_size++ def decode(self, codes: torch.Tensor) -> torch.Tensor:+ quantized = self._codebook.decode(codes)+ quantized = self.project_out(quantized)+ quantized = quantized.transpose(1, 2)+ return quantized+++class ResidualVectorQuantization(nn.Module):+ def __init__(self, *, num_quantizers: int, **kwargs):+ super().__init__()+ self.layers = nn.ModuleList(+ [VectorQuantization(**kwargs) for _ in range(num_quantizers)]+ )++ def decode(self, codes: torch.Tensor) -> torch.Tensor:+ quantized = torch.zeros([1], device=codes.device)[0]+ for idx, layer_codes in enumerate(codes):+ layer = self.layers[idx]+ assert isinstance(layer, VectorQuantization)+ quantized = quantized + layer.decode(layer_codes)+ return quantized+++class ResidualVectorQuantizer(nn.Module):+ def __init__(+ self,+ dimension: int = 128,+ input_dimension: Optional[int] = None,+ output_dimension: Optional[int] = None,+ n_q: int = 8,+ q_dropout: bool = False,+ no_quantization_rate: float = 0.0,+ bins: int = 1024,+ decay: float = 0.99,+ force_projection: bool = False,+ ):+ super().__init__()+ self.max_n_q = n_q+ self.n_q = n_q+ self.q_dropout = q_dropout+ self.no_quantization_rate = no_quantization_rate+ self.dimension = dimension+ self.input_dimension = input_dimension or dimension+ self.output_dimension = output_dimension or dimension+ self.bins = bins+ self.decay = decay+ self.input_proj: torch.nn.Module+ self.output_proj: torch.nn.Module+ if self.input_dimension == self.dimension and not force_projection:+ self.input_proj = torch.nn.Identity()+ else:+ self.input_proj = torch.nn.Conv1d(+ self.input_dimension, self.dimension, 1, bias=False+ )+ if self.output_dimension == self.dimension and not force_projection:+ self.output_proj = torch.nn.Identity()+ else:+ self.output_proj = torch.nn.Conv1d(+ self.dimension, self.output_dimension, 1, bias=False+ )+ self.vq = ResidualVectorQuantization(+ dim=self.dimension,+ codebook_size=self.bins,+ num_quantizers=self.n_q+ )++ def decode(self, codes: torch.Tensor) -> torch.Tensor:+ codes = codes.transpose(0, 1)+ quantized = self.vq.decode(codes)+ quantized = self.output_proj(quantized)+ return quantized+++class SplitResidualVectorQuantizer(nn.Module):+ """Residual Vector Quantizer with separate projections for the first quantizer and the rest.++ Args:+ n_q (int): Number of residual vector quantizers used.+ n_semantic_q (int): Number of residual vector quantizers used for the semantic quantizer.+ **kwargs: Arguments to the constructor of `ResidualVectorQuantizer` that are shared between both.+ """++ def __init__(+ self,+ *,+ n_q: int = 8,+ n_q_semantic: int = 1,+ **kwargs,+ ):+ super().__init__()+ assert n_q > n_q_semantic, (+ f"Number of quantizers {n_q} must be larger "+ f"than the number of semantic quantizers {n_q_semantic}."+ )+ self.max_n_q = n_q+ self.n_q_semantic = n_q_semantic+ self.n_q_acoustic = n_q - n_q_semantic+ q_dropout = kwargs.pop("q_dropout", False)+ self.rvq_first = ResidualVectorQuantizer(+ n_q=n_q_semantic, force_projection=True, q_dropout=False, **kwargs+ )+ self.rvq_rest = ResidualVectorQuantizer(+ n_q=n_q - n_q_semantic,+ force_projection=True,+ q_dropout=q_dropout,+ **kwargs,+ )++ def decode(self, codes: torch.Tensor) -> torch.Tensor:+ """Decode the given codes to the quantized representation."""+ # codes is [B, K, T], with T frames, K nb of codebooks.+ quantized = self.rvq_first.decode(codes[:, : self.n_q_semantic])+ if codes.shape[1] > self.n_q_semantic:+ quantized += self.rvq_rest.decode(codes[:, self.n_q_semantic :])+ return quantized+++class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig):+ super().__init__(config)+ self.total_upsample = np.prod(config.upsample_rates + config.upsampling_ratios)+ self.pre_transformer = Qwen3TTSTokenizerV2DecoderTransformerModel._from_config(config)++ self.quantizer = SplitResidualVectorQuantizer(+ dimension=config.codebook_dim // 2,+ n_q=config.num_quantizers,+ n_q_semantic=1,+ bins=config.codebook_size,+ input_dimension=config.codebook_dim,+ output_dimension=config.codebook_dim,+ )++ self.pre_conv = Qwen3TTSTokenizerV2CausalConvNet(+ config.codebook_dim,+ config.latent_dim,+ kernel_size=3,+ )++ upsample = []+ for factor in config.upsampling_ratios:+ upsample.append(+ nn.ModuleList(+ [+ Qwen3TTSTokenizerV2CausalTransConvNet(config.latent_dim, config.latent_dim, factor, factor),+ Qwen3TTSTokenizerV2ConvNeXtBlock(config.latent_dim),+ ]+ )+ )+ self.upsample = nn.ModuleList(upsample)++ decoder = [Qwen3TTSTokenizerV2CausalConvNet(config.latent_dim, config.decoder_dim, 7)]+ for i in range(len(config.upsample_rates)):+ decoder.append(Qwen3TTSTokenizerV2DecoderDecoderBlock(config, i))+ output_dim = config.decoder_dim // 2 ** len(config.upsample_rates)+ decoder += [+ SnakeBeta(output_dim),+ Qwen3TTSTokenizerV2CausalConvNet(output_dim, 1, 7),+ ]+ self.decoder = nn.ModuleList(decoder)++ self.post_init()++ def forward(self, codes):+ if codes.shape[1] != self.config.num_quantizers:+ raise ValueError(f"Expected {self.config.num_quantizers} layer of codes, got {codes.shape[1]}")++ hidden = self.quantizer.decode(codes)+ hidden = self.pre_conv(hidden).transpose(1, 2)++ hidden = self.pre_transformer(inputs_embeds=hidden).last_hidden_state+ hidden = hidden.permute(0, 2, 1)+ for blocks in self.upsample:+ _check_abort(self)+ for block in blocks:+ hidden = block(hidden)+ wav = hidden+ for block in self.decoder:+ _check_abort(self)+ wav = block(wav)+ return wav.clamp(min=-1, max=1)++ def chunked_decode(self, codes, chunk_size=300, left_context_size=25):+ wavs = []+ start_index = 0+ while start_index < codes.shape[-1]:+ _check_abort(self)+ end_index = min(start_index + chunk_size, codes.shape[-1])+ context_size = left_context_size if start_index - left_context_size > 0 else start_index+ codes_chunk = codes[..., start_index - context_size : end_index]+ wav_chunk = self(codes_chunk)+ wavs.append(wav_chunk[..., context_size * self.total_upsample :])+ start_index = end_index+ return torch.cat(wavs, dim=-1)+++class Qwen3TTSTokenizerV2Encoder(MimiModel):+ def __init__(self, config: MimiConfig):+ super().__init__(config)+ self.config = config++ self.upsample = None+ self.decoder_transformer = None+ self.decoder = None++ self.post_init()+++@auto_docstring+class Qwen3TTSTokenizerV2PreTrainedModel(PreTrainedModel):+ config: Qwen3TTSTokenizerV2Config+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _skip_keys_device_placement = "past_key_values"+ _supports_flash_attn = True+ _supports_sdpa = True+ _can_compile_fullgraph = False+ _supports_attention_backend = True+++@auto_docstring(+ custom_intro="""+ The Qwen3TTSTokenizerV2 model.+ """+)+class Qwen3TTSTokenizerV2Model(Qwen3TTSTokenizerV2PreTrainedModel):+ def __init__(self, config: Qwen3TTSTokenizerV2Config):+ super().__init__(config)+ self.config = config++ self.encoder_valid_num_quantizers = config.encoder_valid_num_quantizers++ self.input_sample_rate = config.input_sample_rate+ self.output_sample_rate = config.output_sample_rate++ self.decode_upsample_rate = config.decode_upsample_rate+ self.encode_downsample_rate = config.encode_downsample_rate++ self.encoder = Qwen3TTSTokenizerV2Encoder._from_config(self.config.encoder_config)+ self.decoder = Qwen3TTSTokenizerV2Decoder._from_config(self.config.decoder_config)++ self.post_init()++ def get_model_type(self):+ return self.config.model_type++ def get_input_sample_rate(self):+ return self.input_sample_rate++ def get_output_sample_rate(self):+ return self.output_sample_rate++ def get_encode_downsample_rate(self):+ return self.encode_downsample_rate++ def get_decode_upsample_rate(self):+ return self.decode_upsample_rate++ def encode(+ self,+ input_values: torch.Tensor,+ padding_mask: Optional[torch.Tensor] = None,+ return_dict: Optional[bool] = None,+ ) -> Union[tuple[torch.Tensor, Optional[torch.Tensor]], Qwen3TTSTokenizerV2EncoderOutput]:+ """+ Encodes the input audio waveform into discrete codes.++ Args:+ input_values (`torch.Tensor` of shape `(batch_size, sequence_length)`):+ Float values of the input audio waveform.+ padding_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`):+ Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0+ for *masked*.+ return_dict (`bool`, *optional*):+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.+ """+ return_dict = return_dict if return_dict is not None else self.config.return_dict++ encoded_frames = self.encoder.encode(input_values=input_values.unsqueeze(1),+ return_dict=True)+ audio_codes = encoded_frames.audio_codes[:, :self.encoder_valid_num_quantizers]+ audio_codes = [code[..., :-(-mask.sum() // self.encode_downsample_rate)].transpose(0, 1) for code, mask in zip(audio_codes, padding_mask)]++ if not return_dict:+ return (+ audio_codes,+ )++ return Qwen3TTSTokenizerV2EncoderOutput(audio_codes)++ def decode(+ self,+ audio_codes: torch.Tensor,+ return_dict: Optional[bool] = None,+ ) -> Union[tuple[torch.Tensor, torch.Tensor], Qwen3TTSTokenizerV2DecoderOutput]:+ """+ Decodes the given frames into an output audio waveform.++ Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be+ trimmed.++ Args:+ audio_codes (`torch.LongTensor` of shape `(batch_size, codes_length, num_quantizers)`, *optional*):+ Discret code embeddings computed using `model.encode`.+ return_dict (`bool`, *optional*):+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.++ """+ return_dict = return_dict if return_dict is not None else self.config.return_dict++ audio_values = self.decoder.chunked_decode(audio_codes.transpose(1, 2)).squeeze(1)++ audio_lengths = (audio_codes[..., 0] > 0).sum(1) * self.decode_upsample_rate+ audio_values = [a[:l] for a, l in zip(audio_values, audio_lengths)]++ if not return_dict:+ return (+ audio_values,+ )++ return Qwen3TTSTokenizerV2DecoderOutput(audio_values)+++__all__ = ["Qwen3TTSTokenizerV2Model", "Qwen3TTSTokenizerV2PreTrainedModel"]diff --git a/models/TTS/qwen3/defs.py b/models/TTS/qwen3/defs.pynew file mode 100644index 0000000..ace8d7b--- /dev/null+++ b/models/TTS/qwen3/defs.py@@ -0,0 +1,276 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Optional+++QWEN3_TTS_VARIANTS = {+ "qwen3_tts_customvoice": {+ "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",+ "config_file": "qwen3_tts_customvoice.json",+ },+ "qwen3_tts_voicedesign": {+ "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign",+ "config_file": "qwen3_tts_voicedesign.json",+ },+ "qwen3_tts_base": {+ "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-Base",+ "config_file": "qwen3_tts_base.json",+ },+}++QWEN3_TTS_GENERATION_CONFIG = "qwen3_tts_generation_config.json"+_QWEN3_CONFIG_DIR = Path(__file__).resolve().parent / "configs"++QWEN3_TTS_TEXT_TOKENIZER_DIR = "qwen3_tts_text_tokenizer"+QWEN3_TTS_SPEECH_TOKENIZER_DIR = "qwen3_tts_tokenizer_12hz"+QWEN3_TTS_SPEECH_TOKENIZER_WEIGHTS = "qwen3_tts_tokenizer_12hz.safetensors"+QWEN3_TTS_REPO = "DeepBeepMeep/TTS"+QWEN3_TTS_TEXT_TOKENIZER_FILES = [+ "merges.txt",+ "vocab.json",+ "tokenizer_config.json",+ "preprocessor_config.json",+]+QWEN3_TTS_SPEECH_TOKENIZER_FILES = [+ "config.json",+ "configuration.json",+ "preprocessor_config.json",+ QWEN3_TTS_SPEECH_TOKENIZER_WEIGHTS,+]++QWEN3_TTS_LANG_FALLBACK = [+ "auto",+ "chinese",+ "english",+ "japanese",+ "korean",+ "german",+ "french",+ "russian",+ "portuguese",+ "spanish",+ "italian",+]+QWEN3_TTS_SPEAKER_FALLBACK = [+ "serena",+ "vivian",+ "uncle_fu",+ "ryan",+ "aiden",+ "ono_anna",+ "sohee",+ "eric",+ "dylan",+]+QWEN3_TTS_SPEAKER_META = {+ "vivian": {+ "style": "Bright, slightly edgy young female voice",+ "language": "Chinese",+ },+ "serena": {+ "style": "Warm, gentle young female voice",+ "language": "Chinese",+ },+ "uncle_fu": {+ "style": "Seasoned male voice with a low, mellow timbre",+ "language": "Chinese",+ },+ "dylan": {+ "style": "Youthful Beijing male voice with a clear, natural timbre",+ "language": "Chinese (Beijing Dialect)",+ },+ "eric": {+ "style": "Lively Chengdu male voice with a slightly husky brightness",+ "language": "Chinese (Sichuan Dialect)",+ },+ "ryan": {+ "style": "Dynamic male voice with strong rhythmic drive",+ "language": "English",+ },+ "aiden": {+ "style": "Sunny American male voice with a clear midrange",+ "language": "English",+ },+ "ono_anna": {+ "style": "Playful Japanese female voice with a light, nimble timbre",+ "language": "Japanese",+ },+ "sohee": {+ "style": "Warm Korean female voice with rich emotion",+ "language": "Korean",+ },+}+TTS_MONOLOGUE_PROMPT = (+ "You are a speechwriting assistant. Generate a single-speaker monologue "+ "for a text-to-speech model based on the user prompt. Output only the "+ "monologue text. Do not include explanations, bullet lists, or stage "+ "directions. Keep a consistent tone and point of view. Use natural, "+ "spoken sentences with clear punctuation for pauses. Aim for a short "+ "monologue (4-8 sentences) unless the prompt asks for a different length.\n\n"+ "Example:\n"+ "I never thought a small town would teach me so much about patience. "+ "Every morning the same faces pass the bakery window, and I know their "+ "stories without a word. The bell over the door rings, the coffee steams, "+ "and time slows down just enough to breathe. Some days I miss the noise of "+ "the city, but most days I am grateful for the quiet. It lets me hear "+ "myself think, and that has become its own kind of music."+)+QWEN3_TTS_DURATION_SLIDER = {+ "label": "Max duration (seconds)",+ "min": 1,+ "max": 240,+ "increment": 1,+ "default": 20,+}+++def _format_qwen3_label(value: str) -> str:+ return value.replace("_", " ").title()++def _format_qwen3_speaker_label(name: str) -> str:+ label = _format_qwen3_label(name)+ meta = QWEN3_TTS_SPEAKER_META.get(name.lower())+ if not meta:+ return label+ parts = []+ style = meta.get("style", "")+ language = meta.get("language", "")+ if style:+ parts.append(style)+ if language:+ parts.append(language)+ if not parts:+ return label+ return f"{label} ({'; '.join(parts)})"+++def get_qwen3_config_path(base_model_type: str) -> Optional[str]:+ variant = QWEN3_TTS_VARIANTS.get(base_model_type)+ if variant is None:+ return None+ config_path = _QWEN3_CONFIG_DIR / variant["config_file"]+ return str(config_path) if config_path.is_file() else None+++def get_qwen3_generation_config_path() -> Optional[str]:+ config_path = _QWEN3_CONFIG_DIR / QWEN3_TTS_GENERATION_CONFIG+ return str(config_path) if config_path.is_file() else None+++def load_qwen3_config(base_model_type: str) -> Optional[dict]:+ config_path = get_qwen3_config_path(base_model_type)+ if not config_path:+ return None+ with open(config_path, "r", encoding="utf-8") as handle:+ return json.load(handle)+++def get_qwen3_languages(base_model_type: str) -> list[str]:+ config = load_qwen3_config(base_model_type)+ if config is None:+ return list(QWEN3_TTS_LANG_FALLBACK)+ lang_map = config.get("talker_config", {}).get("codec_language_id", {})+ languages = [name for name in lang_map.keys() if "dialect" not in name.lower()]+ languages = ["auto"] + sorted({name.lower() for name in languages})+ return languages+++def get_qwen3_speakers(base_model_type: str) -> list[str]:+ config = load_qwen3_config(base_model_type)+ if config is None:+ return list(QWEN3_TTS_SPEAKER_FALLBACK)+ speakers = list(config.get("talker_config", {}).get("spk_id", {}).keys())+ speakers = sorted({name.lower() for name in speakers})+ return speakers or list(QWEN3_TTS_SPEAKER_FALLBACK)+++def get_qwen3_language_choices(base_model_type: str) -> list[tuple[str, str]]:+ return [(_format_qwen3_label(lang), lang) for lang in get_qwen3_languages(base_model_type)]+++def get_qwen3_speaker_choices(base_model_type: str) -> list[tuple[str, str]]:+ return [(_format_qwen3_speaker_label(name), name) for name in get_qwen3_speakers(base_model_type)]+++def get_qwen3_model_def(base_model_type: str) -> dict:+ common = {+ "audio_only": True,+ "image_outputs": False,+ "sliding_window": False,+ "guidance_max_phases": 0,+ "no_negative_prompt": True,+ "image_prompt_types_allowed": "",+ "supports_early_stop": True,+ "profiles_dir": [base_model_type],+ "duration_slider": dict(QWEN3_TTS_DURATION_SLIDER),+ "text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,+ "compile": False,+ }+ if base_model_type == "qwen3_tts_customvoice":+ speakers = get_qwen3_speakers(base_model_type)+ default_speaker = speakers[0] if speakers else ""+ return {+ **common,+ "model_modes": {+ "choices": get_qwen3_speaker_choices(base_model_type),+ "default": default_speaker,+ "label": "Speaker",+ },+ "alt_prompt": {+ "label": "Instruction (optional)",+ "placeholder": "calm, friendly, slightly husky",+ "lines": 2,+ },+ }+ if base_model_type == "qwen3_tts_voicedesign":+ return {+ **common,+ "model_modes": {+ "choices": get_qwen3_language_choices(base_model_type),+ "default": "auto",+ "label": "Language",+ },+ "alt_prompt": {+ "label": "Voice instruction",+ "placeholder": "young female, warm tone, clear articulation",+ "lines": 2,+ },+ }+ if base_model_type == "qwen3_tts_base":+ return {+ **common,+ "model_modes": {+ "choices": get_qwen3_language_choices(base_model_type),+ "default": "auto",+ "label": "Language",+ },+ "alt_prompt": {+ "label": "Reference transcript (optional)",+ "placeholder": "Okay. Yeah. I respect you, but you blew it.",+ "lines": 3,+ },+ "any_audio_prompt": True,+ "audio_guide_label": "Reference voice",+ }+ return common+++def get_qwen3_duration_default() -> int:+ return int(QWEN3_TTS_DURATION_SLIDER.get("default", 20))+++def get_qwen3_download_def(base_model_type: str) -> list[dict]:+ return [+ {+ "repoId": QWEN3_TTS_REPO,+ "sourceFolderList": [QWEN3_TTS_TEXT_TOKENIZER_DIR],+ "fileList": [QWEN3_TTS_TEXT_TOKENIZER_FILES],+ },+ {+ "repoId": QWEN3_TTS_REPO,+ "sourceFolderList": [QWEN3_TTS_SPEECH_TOKENIZER_DIR],+ "fileList": [QWEN3_TTS_SPEECH_TOKENIZER_FILES],+ },+ ]diff --git a/models/TTS/qwen3/inference/__init__.py b/models/TTS/qwen3/inference/__init__.pynew file mode 100644index 0000000..ef8d402--- /dev/null+++ b/models/TTS/qwen3/inference/__init__.py@@ -0,0 +1 @@+# Intentionally left minimal.diff --git a/models/TTS/qwen3/inference/qwen3_tts_model.py b/models/TTS/qwen3/inference/qwen3_tts_model.pynew file mode 100644index 0000000..3e2ab41--- /dev/null+++ b/models/TTS/qwen3/inference/qwen3_tts_model.py@@ -0,0 +1,884 @@+# coding=utf-8+# Copyright 2026 The Alibaba Qwen team.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import base64+import io+import urllib.request+from dataclasses import dataclass+from typing import Any, Dict, List, Optional, Tuple, Union+from urllib.parse import urlparse++import librosa+import numpy as np+import soundfile as sf+import torch+from transformers import AutoConfig, AutoModel, AutoProcessor++from ..core.models import Qwen3TTSConfig, Qwen3TTSForConditionalGeneration, Qwen3TTSProcessor++AudioLike = Union[+ str, # wav path, URL, base64+ np.ndarray, # waveform (requires sr)+ Tuple[np.ndarray, int], # (waveform, sr)+]++MaybeList = Union[Any, List[Any]]+++@dataclass+class VoiceClonePromptItem:+ """+ Container for one sample's voice-clone prompt information that can be fed to the model.++ Fields are aligned with `Qwen3TTSForConditionalGeneration.generate(..., voice_clone_prompt=...)`.+ """+ ref_code: Optional[torch.Tensor] # (T, Q) or (T,) depending on tokenizer 25Hz/12Hz+ ref_spk_embedding: torch.Tensor # (D,)+ x_vector_only_mode: bool+ icl_mode: bool+ ref_text: Optional[str] = None+++class Qwen3TTSModel:+ """+ A HuggingFace-style wrapper for Qwen3 TTS models (CustomVoice/VoiceDesign/Base) that provides:+ - from_pretrained() initialization via AutoModel/AutoProcessor+ - generation APIs for:+ * CustomVoice: generate_custom_voice()+ * VoiceDesign: generate_voice_design()+ * Base: generate_voice_clone() + create_voice_clone_prompt()+ - consistent output: (wavs: List[np.ndarray], sample_rate: int)++ Notes:+ - This wrapper expects the underlying model class to be `Qwen3TTSForConditionalGeneration`+ - Language / speaker validation is done via model methods:+ model.get_supported_languages(), model.get_supported_speakers()+ """++ def __init__(self, model: Qwen3TTSForConditionalGeneration, processor, generate_defaults: Optional[Dict[str, Any]] = None):+ self.model = model+ self.processor = processor+ self.generate_defaults = generate_defaults or {}++ self._device = None++ @classmethod+ def from_pretrained(+ cls,+ pretrained_model_name_or_path: str,+ **kwargs,+ ) -> "Qwen3TTSModel":+ """+ Load a Qwen3 TTS model and its processor in HuggingFace `from_pretrained` style.++ This method:+ 1) Loads config via AutoConfig (so your side can register model_type -> config/model).+ 2) Loads the model via AutoModel.from_pretrained(...), forwarding `kwargs` unchanged.+ 3) Loads the processor via AutoProcessor.from_pretrained(model_path).+ 4) Loads optional `generate_config.json` from the model directory/repo snapshot if present.++ Args:+ pretrained_model_name_or_path (str):+ HuggingFace repo id or local directory of the model.+ **kwargs:+ Forwarded as-is into `AutoModel.from_pretrained(...)`.+ Typical examples: device_map="cuda:0", dtype=torch.bfloat16, attn_implementation="flash_attention_2".++ Returns:+ Qwen3TTSModel:+ Wrapper instance containing `model`, `processor`, and generation defaults.+ """+ AutoConfig.register("qwen3_tts", Qwen3TTSConfig)+ AutoModel.register(Qwen3TTSConfig, Qwen3TTSForConditionalGeneration)+ AutoProcessor.register(Qwen3TTSConfig, Qwen3TTSProcessor)++ model = AutoModel.from_pretrained(pretrained_model_name_or_path, **kwargs)+ if not isinstance(model, Qwen3TTSForConditionalGeneration):+ raise TypeError(+ f"AutoModel returned {type(model)}, expected Qwen3TTSForConditionalGeneration. "+ )++ processor = AutoProcessor.from_pretrained(pretrained_model_name_or_path, fix_mistral_regex=True,)++ generate_defaults = model.generate_config+ return cls(model=model, processor=processor, generate_defaults=generate_defaults)++ def _supported_languages_set(self) -> Optional[set]:+ langs = getattr(self.model, "get_supported_languages", None)+ if callable(langs):+ v = langs()+ if v is None:+ return None+ return set([str(x).lower() for x in v])+ return None++ def _supported_speakers_set(self) -> Optional[set]:+ spks = getattr(self.model, "get_supported_speakers", None)+ if callable(spks):+ v = spks()+ if v is None:+ return None+ return set([str(x).lower() for x in v])+ return None++ def _validate_languages(self, languages: List[str]) -> None:+ """+ Validate that requested languages are supported by the model.++ Args:+ languages (List[str]): Language names for each sample.++ Raises:+ ValueError: If any language is not supported.+ """+ supported = self._supported_languages_set()+ if supported is None:+ return++ bad = []+ for lang in languages:+ if lang is None:+ bad.append(lang)+ continue+ if str(lang).lower() not in supported:+ bad.append(lang)+ if bad:+ raise ValueError(f"Unsupported languages: {bad}. Supported: {sorted(supported)}")++ def _validate_speakers(self, speakers: List[Optional[str]]) -> None:+ """+ Validate that requested speakers are supported by the Instruct model.++ Args:+ speakers (List[Optional[str]]): Speaker names for each sample.++ Raises:+ ValueError: If any speaker is not supported.+ """+ supported = self._supported_speakers_set()+ if supported is None:+ return++ bad = []+ for spk in speakers:+ if spk is None or spk == "":+ continue+ if str(spk).lower() not in supported:+ bad.append(spk)+ if bad:+ raise ValueError(f"Unsupported speakers: {bad}. Supported: {sorted(supported)}")++ def _is_probably_base64(self, s: str) -> bool:+ if s.startswith("data:audio"):+ return True+ if ("/" not in s and "\\" not in s) and len(s) > 256:+ return True+ return False++ def _is_url(self, s: str) -> bool:+ try:+ u = urlparse(s)+ return u.scheme in ("http", "https") and bool(u.netloc)+ except Exception:+ return False++ def _decode_base64_to_wav_bytes(self, b64: str) -> bytes:+ if "," in b64 and b64.strip().startswith("data:"):+ b64 = b64.split(",", 1)[1]+ return base64.b64decode(b64)++ def _load_audio_to_np(self, x: str) -> Tuple[np.ndarray, int]:+ if self._is_url(x):+ with urllib.request.urlopen(x) as resp:+ audio_bytes = resp.read()+ with io.BytesIO(audio_bytes) as f:+ audio, sr = sf.read(f, dtype="float32", always_2d=False)+ elif self._is_probably_base64(x):+ wav_bytes = self._decode_base64_to_wav_bytes(x)+ with io.BytesIO(wav_bytes) as f:+ audio, sr = sf.read(f, dtype="float32", always_2d=False)+ else:+ audio, sr = librosa.load(x, sr=None, mono=True)++ if audio.ndim > 1:+ audio = np.mean(audio, axis=-1)++ return audio.astype(np.float32), int(sr)++ def _normalize_audio_inputs(self, audios: Union[AudioLike, List[AudioLike]]) -> List[Tuple[np.ndarray, int]]:+ """+ Normalize audio inputs into a list of (waveform, sr).++ Supported forms:+ - str: wav path / URL / base64 audio string+ - (np.ndarray, sr): waveform + sampling rate+ - list of the above++ Args:+ audios:+ Audio input(s).++ Returns:+ List[Tuple[np.ndarray, int]]:+ List of (float32 waveform, original sr).++ Raises:+ ValueError: If a numpy waveform is provided without sr.+ """+ if isinstance(audios, list):+ items = audios+ else:+ items = [audios]++ out: List[Tuple[np.ndarray, int]] = []+ for a in items:+ if isinstance(a, str):+ out.append(self._load_audio_to_np(a))+ elif isinstance(a, tuple) and len(a) == 2 and isinstance(a[0], np.ndarray):+ out.append((a[0].astype(np.float32), int(a[1])))+ elif isinstance(a, np.ndarray):+ raise ValueError("For numpy waveform input, pass a tuple (audio, sr).")+ else:+ raise TypeError(f"Unsupported audio input type: {type(a)}")+ for i, a in enumerate(out):+ if a[0].ndim > 1:+ a[0] = np.mean(a[0], axis=-1).astype(np.float32)+ out[i] = (a[0], a[1])+ return out++ def _ensure_list(self, x: MaybeList) -> List[Any]:+ return x if isinstance(x, list) else [x]++ def _build_assistant_text(self, text: str) -> str:+ return f"<|im_start|>assistant\n{text}<|im_end|>\n<|im_start|>assistant\n"++ def _build_ref_text(self, text: str) -> str:+ return f"<|im_start|>assistant\n{text}<|im_end|>\n"++ def _build_instruct_text(self, instruct: str) -> str:+ return f"<|im_start|>user\n{instruct}<|im_end|>\n"++ def _get_device(self) -> torch.device:+ if torch.cuda.is_available():+ return torch.device("cuda")+ if self._device is not None:+ return self._device+ try:+ param = next(self.model.parameters())+ return param.device+ except StopIteration:+ return torch.device("cpu")++ def _tokenize_texts(self, texts: List[str]) -> List[torch.Tensor]:+ input_ids = []+ for text in texts:+ input = self.processor(text=text, return_tensors="pt", padding=True)+ device = self._get_device()+ input_id = input["input_ids"].to(device)+ input_id = input_id.unsqueeze(0) if input_id.dim() == 1 else input_id+ input_ids.append(input_id)+ return input_ids++ def _merge_generate_kwargs(+ self,+ do_sample: Optional[bool] = None,+ top_k: Optional[int] = None,+ top_p: Optional[float] = None,+ temperature: Optional[float] = None,+ repetition_penalty: Optional[float] = None,+ subtalker_dosample: Optional[bool] = None,+ subtalker_top_k: Optional[int] = None,+ subtalker_top_p: Optional[float] = None,+ subtalker_temperature: Optional[float] = None,+ max_new_tokens: Optional[int] = None,+ **kwargs,+ ) -> Dict[str, Any]:+ """+ Merge user-provided generation arguments with defaults from `generate_config.json`.++ Rule:+ - If the user explicitly passes a value (not None), use it.+ - Otherwise, use the value from generate_config.json if present.+ - Otherwise, fall back to the hard defaults.++ Args:+ do_sample, top_k, top_p, temperature, repetition_penalty,+ subtalker_dosample, subtalker_top_k, subtalker_top_p, subtalker_temperature, max_new_tokens:+ Common generation parameters.+ **kwargs:+ Other arguments forwarded to model.generate().++ Returns:+ Dict[str, Any]: Final kwargs to pass into model.generate().+ """+ hard_defaults = dict(+ do_sample=True,+ top_k=50,+ top_p=1.0,+ temperature=0.9,+ repetition_penalty=1.05,+ subtalker_dosample=True,+ subtalker_top_k=50,+ subtalker_top_p=1.0,+ subtalker_temperature=0.9,+ max_new_tokens=2048,+ )++ def pick(name: str, user_val: Any) -> Any:+ if user_val is not None:+ return user_val+ if name in self.generate_defaults:+ return self.generate_defaults[name]+ return hard_defaults[name]++ merged = dict(kwargs)+ merged.update(+ do_sample=pick("do_sample", do_sample),+ top_k=pick("top_k", top_k),+ top_p=pick("top_p", top_p),+ temperature=pick("temperature", temperature),+ repetition_penalty=pick("repetition_penalty", repetition_penalty),+ subtalker_dosample=pick("subtalker_dosample", subtalker_dosample),+ subtalker_top_k=pick("subtalker_top_k", subtalker_top_k),+ subtalker_top_p=pick("subtalker_top_p", subtalker_top_p),+ subtalker_temperature=pick("subtalker_temperature", subtalker_temperature),+ max_new_tokens=pick("max_new_tokens", max_new_tokens),+ )+ return merged++ # voice clone model+ @torch.inference_mode()+ def create_voice_clone_prompt(+ self,+ ref_audio: Union[AudioLike, List[AudioLike]],+ ref_text: Optional[Union[str, List[Optional[str]]]] = None,+ x_vector_only_mode: Union[bool, List[bool]] = False,+ ) -> List[VoiceClonePromptItem]:+ """+ Build voice-clone prompt items from reference audio (and optionally reference text) using Base model.++ Modes:+ - x_vector_only_mode=True:+ Only speaker embedding is used to clone voice; ref_text/ref_code are ignored.+ This is mutually exclusive with ICL.+ - x_vector_only_mode=False:+ ICL mode is enabled automatically (icl_mode=True). In this case ref_text is required,+ because the model continues/conditions on the reference text + reference speech codes.++ Batch behavior:+ - ref_audio can be a single item or a list.+ - ref_text and x_vector_only_mode can be scalars or lists.+ - If any of them are lists with length > 1, lengths must match.++ Audio input:+ - str: local wav path / URL / base64+ - (np.ndarray, sr): waveform + sampling rate++ Args:+ ref_audio:+ Reference audio(s) used to extract:+ - ref_code via `model.speech_tokenizer.encode(...)`+ - ref_spk_embedding via `model.extract_speaker_embedding(...)` (resampled to 24k)+ ref_text:+ Reference transcript(s). Required when x_vector_only_mode=False (ICL mode).+ x_vector_only_mode:+ Whether to use speaker embedding only. If False, ICL mode will be used.++ Returns:+ List[VoiceClonePromptItem]:+ List of prompt items that can be converted into `voice_clone_prompt` dict.++ Raises:+ ValueError:+ - If x_vector_only_mode=False but ref_text is missing.+ - If batch lengths mismatch.+ """+ if self.model.tts_model_type != "base":+ raise ValueError(+ f"model with \ntokenizer_type: {self.model.tokenizer_type}\n"+ f"tts_model_size: {self.model.tts_model_size}\n"+ f"tts_model_type: {self.model.tts_model_type}\n"+ "does not support create_voice_clone_prompt, Please check Model Card or Readme for more details."+ )++ ref_audio_list = self._ensure_list(ref_audio)+ ref_text_list = self._ensure_list(ref_text) if isinstance(ref_text, list) else ([ref_text] * len(ref_audio_list))+ xvec_list = self._ensure_list(x_vector_only_mode) if isinstance(x_vector_only_mode, list) else ([x_vector_only_mode] * len(ref_audio_list))++ if len(ref_text_list) != len(ref_audio_list) or len(xvec_list) != len(ref_audio_list):+ raise ValueError(+ f"Batch size mismatch: ref_audio={len(ref_audio_list)}, ref_text={len(ref_text_list)}, x_vector_only_mode={len(xvec_list)}"+ )++ normalized = self._normalize_audio_inputs(ref_audio_list)++ ref_wavs_for_code: List[np.ndarray] = []+ ref_sr_for_code: List[int] = []+ for wav, sr in normalized:+ ref_wavs_for_code.append(wav)+ ref_sr_for_code.append(sr)++ if len(set(ref_sr_for_code)) == 1:+ enc = self.model.speech_tokenizer.encode(ref_wavs_for_code, sr=ref_sr_for_code[0])+ ref_codes = enc.audio_codes+ else:+ ref_codes = []+ for wav, sr in normalized:+ ref_codes.append(self.model.speech_tokenizer.encode(wav, sr=sr).audio_codes[0])++ items: List[VoiceClonePromptItem] = []+ for i, ((wav, sr), code, rtext, xvec_only) in enumerate(zip(normalized, ref_codes, ref_text_list, xvec_list)):+ if not xvec_only:+ if rtext is None or rtext == "":+ raise ValueError(f"ref_text is required when x_vector_only_mode=False (ICL mode). Bad index={i}")++ wav_resample = wav+ if sr != self.model.speaker_encoder_sample_rate:+ wav_resample = librosa.resample(y=wav_resample.astype(np.float32),+ orig_sr=int(sr),+ target_sr=self.model.speaker_encoder_sample_rate)++ spk_emb = self.model.extract_speaker_embedding(audio=wav_resample,+ sr=self.model.speaker_encoder_sample_rate)++ items.append(+ VoiceClonePromptItem(+ ref_code=None if xvec_only else code,+ ref_spk_embedding=spk_emb,+ x_vector_only_mode=bool(xvec_only),+ icl_mode=bool(not xvec_only),+ ref_text=rtext,+ )+ )+ return items++ def _prompt_items_to_voice_clone_prompt(self, items: List[VoiceClonePromptItem]) -> Dict[str, Any]:+ return dict(+ ref_code=[it.ref_code for it in items],+ ref_spk_embedding=[it.ref_spk_embedding for it in items],+ x_vector_only_mode=[it.x_vector_only_mode for it in items],+ icl_mode=[it.icl_mode for it in items],+ )++ # voice clone model+ @torch.no_grad()+ def generate_voice_clone(+ self,+ text: Union[str, List[str]],+ language: Union[str, List[str]] = None,+ ref_audio: Optional[Union[AudioLike, List[AudioLike]]] = None,+ ref_text: Optional[Union[str, List[Optional[str]]]] = None,+ x_vector_only_mode: Union[bool, List[bool]] = False,+ voice_clone_prompt: Optional[Union[Dict[str, Any], List[VoiceClonePromptItem]]] = None,+ non_streaming_mode: bool = False,+ **kwargs,+ ) -> Tuple[List[np.ndarray], int]:+ """+ Voice clone speech using the Base model.++ You can provide either:+ - (ref_audio, ref_text, x_vector_only_mode) and let this method build the prompt, OR+ - `VoiceClonePromptItem` returned by `create_voice_clone_prompt`, OR+ - a list of `VoiceClonePromptItem` returned by `create_voice_clone_prompt`.++ `ref_audio` Supported forms:+ - str: wav path / URL / base64 audio string+ - (np.ndarray, sr): waveform + sampling rate+ - list of the above++ Input flexibility:+ - text/language can be scalar or list.+ - prompt can be single or batch.+ - If batch mode (len(text)>1), lengths must match.++ Args:+ text:+ Text(s) to synthesize.+ language:+ Language(s) for each sample.+ ref_audio:+ Reference audio(s) for prompt building. Required if voice_clone_prompt is not provided.+ ref_text:+ Reference text(s) used for ICL mode (required when x_vector_only_mode=False).+ x_vector_only_mode:+ If True, only speaker embedding is used (ignores ref_text/ref_code).+ If False, ICL mode is used automatically.+ voice_clone_prompt:+ list[VoiceClonePromptItem] from `create_voice_clone_prompt`.+ non_streaming_mode:+ Using non-streaming text input, this option currently only simulates streaming text input when set to `false`,+ rather than enabling true streaming input or streaming generation.+ do_sample:+ Whether to use sampling, recommended to be set to `true` for most use cases.+ top_k:+ Top-k sampling parameter.+ top_p:+ Top-p sampling parameter.+ temperature:+ Sampling temperature; higher => more random.+ repetition_penalty:+ Penalty to reduce repeated tokens/codes.+ subtalker_dosample:+ Sampling switch for the sub-talker (only valid for qwen3-tts-tokenizer-v2) if applicable.+ subtalker_top_k:+ Top-k for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_top_p:+ Top-p for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_temperature:+ Temperature for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ max_new_tokens:+ Maximum number of new codec tokens to generate.+ **kwargs:+ Any other keyword arguments supported by HuggingFace Transformers `generate()` can be passed.+ They will be forwarded to the underlying `Qwen3TTSForConditionalGeneration.generate(...)`.++ Returns:+ Tuple[List[np.ndarray], int]:+ (wavs, sample_rate)++ Raises:+ ValueError:+ If batch sizes mismatch or required prompt inputs are missing.+ """+ if self.model.tts_model_type != "base":+ raise ValueError(+ f"model with \ntokenizer_type: {self.model.tokenizer_type}\n"+ f"tts_model_size: {self.model.tts_model_size}\n"+ f"tts_model_type: {self.model.tts_model_type}\n"+ "does not support generate_voice_clone, Please check Model Card or Readme for more details."+ )++ texts = self._ensure_list(text)+ languages = self._ensure_list(language) if isinstance(language, list) else ([language] * len(texts) if language is not None else ["Auto"] * len(texts))+ if len(languages) == 1 and len(texts) > 1:+ languages = languages * len(texts)+ if len(texts) != len(languages):+ raise ValueError(f"Batch size mismatch: text={len(texts)}, language={len(languages)}")++ self._validate_languages(languages)++ if voice_clone_prompt is None:+ if ref_audio is None:+ raise ValueError("Either `voice_clone_prompt` or `ref_audio` must be provided.")+ prompt_items = self.create_voice_clone_prompt(ref_audio=ref_audio, ref_text=ref_text, x_vector_only_mode=x_vector_only_mode)+ if len(prompt_items) == 1 and len(texts) > 1:+ prompt_items = prompt_items * len(texts)+ if len(prompt_items) != len(texts):+ raise ValueError(f"Batch size mismatch: prompt={len(prompt_items)}, text={len(texts)}")+ voice_clone_prompt_dict = self._prompt_items_to_voice_clone_prompt(prompt_items)+ ref_texts_for_ids = [it.ref_text for it in prompt_items]+ else:+ if isinstance(voice_clone_prompt, list):+ prompt_items = voice_clone_prompt+ if len(prompt_items) == 1 and len(texts) > 1:+ prompt_items = prompt_items * len(texts)+ if len(prompt_items) != len(texts):+ raise ValueError(f"Batch size mismatch: prompt={len(prompt_items)}, text={len(texts)}")+ voice_clone_prompt_dict = self._prompt_items_to_voice_clone_prompt(prompt_items)+ ref_texts_for_ids = [it.ref_text for it in prompt_items]+ else:+ voice_clone_prompt_dict = voice_clone_prompt+ ref_texts_for_ids = None++ input_texts = [self._build_assistant_text(t) for t in texts]+ input_ids = self._tokenize_texts(input_texts)++ ref_ids = None+ if ref_texts_for_ids is not None:+ ref_ids = []+ for i, rt in enumerate(ref_texts_for_ids):+ if rt is None or rt == "":+ ref_ids.append(None)+ else:+ ref_tok = self._tokenize_texts([self._build_ref_text(rt)])[0]+ ref_ids.append(ref_tok)++ gen_kwargs = self._merge_generate_kwargs(**kwargs)++ talker_codes_list, _ = self.model.generate(+ input_ids=input_ids,+ ref_ids=ref_ids,+ voice_clone_prompt=voice_clone_prompt_dict,+ languages=languages,+ non_streaming_mode=non_streaming_mode,+ **gen_kwargs,+ )++ codes_for_decode = []+ for i, codes in enumerate(talker_codes_list):+ ref_code_list = voice_clone_prompt_dict.get("ref_code", None)+ if ref_code_list is not None and ref_code_list[i] is not None:+ codes_for_decode.append(torch.cat([ref_code_list[i].to(codes.device), codes], dim=0))+ else:+ codes_for_decode.append(codes)++ wavs_all, fs = self.model.speech_tokenizer.decode([{"audio_codes": c} for c in codes_for_decode])++ wavs_out: List[np.ndarray] = []+ for i, wav in enumerate(wavs_all):+ ref_code_list = voice_clone_prompt_dict.get("ref_code", None)+ if ref_code_list is not None and ref_code_list[i] is not None:+ ref_len = int(ref_code_list[i].shape[0])+ total_len = int(codes_for_decode[i].shape[0])+ cut = int(ref_len / max(total_len, 1) * wav.shape[0])+ wavs_out.append(wav[cut:])+ else:+ wavs_out.append(wav)++ return wavs_out, fs++ # voice design model+ @torch.no_grad()+ def generate_voice_design(+ self,+ text: Union[str, List[str]],+ instruct: Union[str, List[str]],+ language: Union[str, List[str]] = None,+ non_streaming_mode: bool = True,+ **kwargs,+ ) -> Tuple[List[np.ndarray], int]:+ """+ Generate speech with the VoiceDesign model using natural-language style instructions.++ Args:+ text:+ Text(s) to synthesize.+ language:+ Language(s) for each sample.+ instruct:+ Instruction(s) describing desired voice/style. Empty string is allowed (treated as no instruction).+ non_streaming_mode:+ Using non-streaming text input, this option currently only simulates streaming text input when set to `false`,+ rather than enabling true streaming input or streaming generation.+ do_sample:+ Whether to use sampling, recommended to be set to `true` for most use cases.+ top_k:+ Top-k sampling parameter.+ top_p:+ Top-p sampling parameter.+ temperature:+ Sampling temperature; higher => more random.+ repetition_penalty:+ Penalty to reduce repeated tokens/codes.+ subtalker_dosample:+ Sampling switch for the sub-talker (only valid for qwen3-tts-tokenizer-v2) if applicable.+ subtalker_top_k:+ Top-k for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_top_p:+ Top-p for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_temperature:+ Temperature for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ max_new_tokens:+ Maximum number of new codec tokens to generate.+ **kwargs:+ Any other keyword arguments supported by HuggingFace Transformers `generate()` can be passed.+ They will be forwarded to the underlying `Qwen3TTSForConditionalGeneration.generate(...)`.++ Returns:+ Tuple[List[np.ndarray], int]:+ (wavs, sample_rate)+ """+ if self.model.tts_model_type != "voice_design":+ raise ValueError(+ f"model with \ntokenizer_type: {self.model.tokenizer_type}\n"+ f"tts_model_size: {self.model.tts_model_size}\n"+ f"tts_model_type: {self.model.tts_model_type}\n"+ "does not support generate_voice_design, Please check Model Card or Readme for more details."+ )++ texts = self._ensure_list(text)+ languages = self._ensure_list(language) if isinstance(language, list) else ([language] * len(texts) if language is not None else ["Auto"] * len(texts))+ instructs = self._ensure_list(instruct)++ if len(languages) == 1 and len(texts) > 1:+ languages = languages * len(texts)+ if len(instructs) == 1 and len(texts) > 1:+ instructs = instructs * len(texts)++ if not (len(texts) == len(languages) == len(instructs)):+ raise ValueError(f"Batch size mismatch: text={len(texts)}, language={len(languages)}, instruct={len(instructs)}")++ self._validate_languages(languages)++ input_ids = self._tokenize_texts([self._build_assistant_text(t) for t in texts])++ instruct_ids: List[Optional[torch.Tensor]] = []+ for ins in instructs:+ if ins is None or ins == "":+ instruct_ids.append(None)+ else:+ instruct_ids.append(self._tokenize_texts([self._build_instruct_text(ins)])[0])++ gen_kwargs = self._merge_generate_kwargs(**kwargs)++ talker_codes_list, _ = self.model.generate(+ input_ids=input_ids,+ instruct_ids=instruct_ids,+ languages=languages,+ non_streaming_mode=non_streaming_mode,+ **gen_kwargs,+ )++ wavs, fs = self.model.speech_tokenizer.decode([{"audio_codes": c} for c in talker_codes_list])+ return wavs, fs++ # custom voice model+ @torch.no_grad()+ def generate_custom_voice(+ self,+ text: Union[str, List[str]],+ speaker: Union[str, List[str]],+ language: Union[str, List[str]] = None,+ instruct: Optional[Union[str, List[str]]] = None,+ non_streaming_mode: bool = True,+ **kwargs,+ ) -> Tuple[List[np.ndarray], int]:+ """+ Generate speech with the CustomVoice model using a predefined speaker id, optionally controlled by instruction text.++ Args:+ text:+ Text(s) to synthesize.+ language:+ Language(s) for each sample.+ speaker:+ Speaker name(s). Will be validated against `model.get_supported_speakers()` (case-insensitive).+ instruct:+ Optional instruction(s). If None, treated as empty (no instruction).+ non_streaming_mode:+ Using non-streaming text input, this option currently only simulates streaming text input when set to `false`,+ rather than enabling true streaming input or streaming generation.+ do_sample:+ Whether to use sampling, recommended to be set to `true` for most use cases.+ top_k:+ Top-k sampling parameter.+ top_p:+ Top-p sampling parameter.+ temperature:+ Sampling temperature; higher => more random.+ repetition_penalty:+ Penalty to reduce repeated tokens/codes.+ subtalker_dosample:+ Sampling switch for the sub-talker (only valid for qwen3-tts-tokenizer-v2) if applicable.+ subtalker_top_k:+ Top-k for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_top_p:+ Top-p for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ subtalker_temperature:+ Temperature for sub-talker sampling (only valid for qwen3-tts-tokenizer-v2).+ max_new_tokens:+ Maximum number of new codec tokens to generate.+ **kwargs:+ Any other keyword arguments supported by HuggingFace Transformers `generate()` can be passed.+ They will be forwarded to the underlying `Qwen3TTSForConditionalGeneration.generate(...)`.++ Returns:+ Tuple[List[np.ndarray], int]:+ (wavs, sample_rate)++ Raises:+ ValueError:+ If any speaker/language is unsupported or batch sizes mismatch.+ """+ if self.model.tts_model_type != "custom_voice":+ raise ValueError(+ f"model with \ntokenizer_type: {self.model.tokenizer_type}\n"+ f"tts_model_size: {self.model.tts_model_size}\n"+ f"tts_model_type: {self.model.tts_model_type}\n"+ "does not support generate_custom_voice, Please check Model Card or Readme for more details."+ )++ texts = self._ensure_list(text)+ languages = self._ensure_list(language) if isinstance(language, list) else ([language] * len(texts) if language is not None else ["Auto"] * len(texts))+ speakers = self._ensure_list(speaker)+ if self.model.tts_model_size in "0b6": # for 0b6 model, instruct is not supported+ instruct = None+ instructs = self._ensure_list(instruct) if isinstance(instruct, list) else ([instruct] * len(texts) if instruct is not None else [""] * len(texts))++ if len(languages) == 1 and len(texts) > 1:+ languages = languages * len(texts)+ if len(speakers) == 1 and len(texts) > 1:+ speakers = speakers * len(texts)+ if len(instructs) == 1 and len(texts) > 1:+ instructs = instructs * len(texts)++ if not (len(texts) == len(languages) == len(speakers) == len(instructs)):+ raise ValueError(+ f"Batch size mismatch: text={len(texts)}, language={len(languages)}, speaker={len(speakers)}, instruct={len(instructs)}"+ )++ self._validate_languages(languages)+ self._validate_speakers(speakers)++ input_ids = self._tokenize_texts([self._build_assistant_text(t) for t in texts])++ instruct_ids: List[Optional[torch.Tensor]] = []+ for ins in instructs:+ if ins is None or ins == "":+ instruct_ids.append(None)+ else:+ instruct_ids.append(self._tokenize_texts([self._build_instruct_text(ins)])[0])++ gen_kwargs = self._merge_generate_kwargs(**kwargs)++ talker_codes_list, _ = self.model.generate(+ input_ids=input_ids,+ instruct_ids=instruct_ids,+ languages=languages,+ speakers=speakers,+ non_streaming_mode=non_streaming_mode,+ **gen_kwargs,+ )++ wavs, fs = self.model.speech_tokenizer.decode([{"audio_codes": c} for c in talker_codes_list])+ return wavs, fs+++ def get_supported_speakers(self) -> Optional[List[str]]:+ """+ List supported speaker names for the current model.++ This is a convenience wrapper around `model.get_supported_speakers()`.+ If the underlying model does not expose speaker constraints (returns None),+ this method also returns None.++ Returns:+ Optional[List[str]]:+ - A sorted list of supported speaker names (lowercased), if available.+ - None if the model does not provide supported speakers.+ """+ supported = self._supported_speakers_set()+ if supported is None:+ return None+ return sorted(supported)+++ def get_supported_languages(self) -> Optional[List[str]]:+ """+ List supported language names for the current model.++ This is a convenience wrapper around `model.get_supported_languages()`.+ If the underlying model does not expose language constraints (returns None),+ this method also returns None.++ Returns:+ Optional[List[str]]:+ - A sorted list of supported language names (lowercased), if available.+ - None if the model does not provide supported languages.+ """+ supported = self._supported_languages_set()+ if supported is None:+ return None+ return sorted(supported)diff --git a/models/TTS/qwen3/inference/qwen3_tts_tokenizer.py b/models/TTS/qwen3/inference/qwen3_tts_tokenizer.pynew file mode 100644index 0000000..bc6f7b1--- /dev/null+++ b/models/TTS/qwen3/inference/qwen3_tts_tokenizer.py@@ -0,0 +1,465 @@+# coding=utf-8+# Copyright 2026 The Alibaba Qwen team.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import base64+import io+import json+import os+import urllib.request+from typing import List, Optional, Tuple, Union+from urllib.parse import urlparse++import librosa+import numpy as np+import soundfile as sf+import torch+from accelerate import init_empty_weights+from torch.nn.utils.rnn import pad_sequence+from transformers import AutoFeatureExtractor++from mmgp import offload+from ..core import (+ Qwen3TTSTokenizerV2Config,+ Qwen3TTSTokenizerV2Model,+)++AudioInput = Union[+ str, # wav path, or base64 string+ np.ndarray, # 1-D float array+ List[str],+ List[np.ndarray],+]+++class Qwen3TTSTokenizer:+ """+ A wrapper for Qwen3 TTS Tokenizer 25Hz/12Hz with HuggingFace-style loading.++ - from_pretrained(): loads speech tokenizer model via local configs and weights.+ - encode(): supports wav path(s), base64 audio string(s), numpy array(s).+ - decode(): accepts either the raw model encode output, or a minimal dict/list-of-dicts.++ Notes:+ - For numpy array input, you must pass `sr` so the audio can be resampled to model sample rate.+ - Returned audio is float32 numpy arrays and the output sample rate.+ """++ def __init__(self):+ self.model = None+ self.feature_extractor = None+ self.config = None+ self.device = None++ @staticmethod+ def _load_config(config_dir: str) -> Qwen3TTSTokenizerV2Config:+ config_path = os.path.join(config_dir, "config.json")+ if not os.path.isfile(config_path):+ raise FileNotFoundError(f"Missing tokenizer config: {config_path}")+ with open(config_path, "r", encoding="utf-8") as handle:+ config_dict = json.load(handle)+ return Qwen3TTSTokenizerV2Config(**config_dict)++ def _get_device(self) -> torch.device:+ if torch.cuda.is_available():+ return torch.device("cuda")+ if self.device is not None:+ return self.device+ if self.model is None:+ return torch.device("cpu")+ param = next(self.model.parameters(), None)+ return param.device if param is not None else torch.device("cpu")++ def _get_dtype(self) -> torch.dtype:+ if self.model is None:+ return torch.float32+ param = next(self.model.parameters(), None)+ return param.dtype if param is not None else torch.float32++ @classmethod+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs) -> "Qwen3TTSTokenizer":+ """+ Initialize tokenizer with HuggingFace `from_pretrained` style.++ Args:+ pretrained_model_name_or_path (str):+ Local directory containing config and feature extractor files, or a safetensors path.+ **kwargs (Any):+ Accepted: weights_path, dtype.++ Returns:+ Qwen3TTSTokenizer:+ Initialized instance with `model`, `feature_extractor`, `config`.+ """+ weights_path = kwargs.pop("weights_path", None)+ default_dtype = kwargs.pop("dtype", None)+ config_dir = pretrained_model_name_or_path++ if weights_path is None:+ if os.path.isfile(pretrained_model_name_or_path):+ weights_path = pretrained_model_name_or_path+ config_dir = os.path.dirname(pretrained_model_name_or_path)+ elif os.path.isdir(pretrained_model_name_or_path):+ for entry in os.listdir(pretrained_model_name_or_path):+ if entry.endswith(".safetensors") or entry.endswith(".sft"):+ weights_path = os.path.join(pretrained_model_name_or_path, entry)+ break++ if not weights_path:+ raise FileNotFoundError("Tokenizer weights_path is required for local loading.")+ return cls.from_local(config_dir, weights_path, default_dtype=default_dtype)++ @classmethod+ def from_local(+ cls,+ config_dir: str,+ weights_path: str,+ *,+ default_dtype: Optional[torch.dtype] = None,+ ) -> "Qwen3TTSTokenizer":+ inst = cls()+ inst.feature_extractor = AutoFeatureExtractor.from_pretrained(config_dir)+ config = inst._load_config(config_dir)+ with init_empty_weights():+ model = Qwen3TTSTokenizerV2Model(config)+ offload.load_model_data(+ model,+ weights_path,+ default_dtype=default_dtype,+ writable_tensors=False,+ )+ model.eval()+ model._offload_hooks = ["encode", "decode"]+ first_param = next(model.parameters(), None)+ if first_param is not None:+ model._model_dtype = first_param.dtype+ inst.model = model+ inst.config = model.config+ return inst++ def _is_probably_base64(self, s: str) -> bool:+ if s.startswith("data:audio"):+ return True+ # Heuristic: no filesystem path separators and long enough.+ if ("/" not in s and "\\" not in s) and len(s) > 256:+ return True+ return False++ def _is_url(self, s: str) -> bool:+ try:+ u = urlparse(s)+ return u.scheme in ("http", "https") and bool(u.netloc)+ except Exception:+ return False++ def _decode_base64_to_wav_bytes(self, b64: str) -> bytes:+ # Accept both "data:audio/wav;base64,...." and raw base64+ if "," in b64 and b64.strip().startswith("data:"):+ b64 = b64.split(",", 1)[1]+ return base64.b64decode(b64)++ def load_audio(+ self,+ x: str,+ target_sr: int,+ ) -> np.ndarray:+ """+ Load audio from wav path or base64 string, then resample to target_sr.++ Args:+ x (str):+ A wav file path, or a base64 audio string (raw or data URL).+ target_sr (int):+ Target sampling rate.++ Returns:+ np.ndarray:+ 1-D float32 waveform at target_sr.+ """+ if self._is_url(x):+ with urllib.request.urlopen(x) as resp:+ audio_bytes = resp.read()+ with io.BytesIO(audio_bytes) as f:+ audio, sr = sf.read(f, dtype="float32", always_2d=False)+ elif self._is_probably_base64(x):+ wav_bytes = self._decode_base64_to_wav_bytes(x)+ with io.BytesIO(wav_bytes) as f:+ audio, sr = sf.read(f, dtype="float32", always_2d=False)+ else:+ audio, sr = librosa.load(x, sr=None, mono=True)++ if audio.ndim > 1:+ audio = np.mean(audio, axis=-1)++ if sr != target_sr:+ audio = librosa.resample(y=audio, orig_sr=sr, target_sr=target_sr)++ return audio.astype(np.float32)++ def _normalize_audio_inputs(+ self,+ audios: AudioInput,+ sr: Optional[int],+ ) -> List[np.ndarray]:+ """+ Normalize all supported input types into a list of 1-D numpy float32 waveforms+ at `self.feature_extractor.sampling_rate`.++ Args:+ audios (AudioInput):+ - str: wav path OR base64 audio string+ - np.ndarray: raw waveform (sr must be provided)+ - list[str] / list[np.ndarray]+ sr (Optional[int]):+ Sampling rate for raw numpy input. Required if input is np.ndarray or list[np.ndarray].++ Returns:+ List[np.ndarray]:+ List of float32 waveforms resampled to model input SR.+ """+ target_sr = int(self.feature_extractor.sampling_rate)++ if isinstance(audios, (str, np.ndarray)):+ audios = [audios]++ if len(audios) == 0:+ return []++ if isinstance(audios[0], str):+ # wav path list or base64 list+ return [self.load_audio(x, target_sr=target_sr) for x in audios] # type: ignore[arg-type]++ # numpy list+ if sr is None:+ raise ValueError("For numpy waveform input, you must provide `sr` (original sampling rate).")++ out: List[np.ndarray] = []+ for a in audios: # type: ignore[assignment]+ if not isinstance(a, np.ndarray):+ raise TypeError("Mixed input types are not supported. Use all paths/base64 or all numpy arrays.")+ if a.ndim > 1:+ a = np.mean(a, axis=-1)+ if int(sr) != target_sr:+ a = librosa.resample(y=a.astype(np.float32), orig_sr=int(sr), target_sr=target_sr)+ out.append(a.astype(np.float32))+ return out++ def encode(+ self,+ audios: AudioInput,+ sr: Optional[int] = None,+ return_dict: bool = True,+ ):+ """+ Batch-encode audio into discrete codes (and optional conditioning, depending on 25Hz/12Hz).++ Args:+ audios (AudioInput):+ Supported forms:+ - np.ndarray: waveform (requires sr)+ - list[np.ndarray]: waveforms (requires sr)+ - str: wav path OR base64 audio string+ - list[str]: wav paths and/or base64 strings+ sr (Optional[int], default=None):+ Original sampling rate for numpy waveform input.+ return_dict (bool, default=True):+ Forwarded to model.encode(...). If True, returns ModelOutput.++ Returns:+ 25Hz:+ Qwen3TTSTokenizerV1EncoderOutput (if return_dict=True) with fields:+ - audio_codes: List[torch.LongTensor] each (codes_len,)+ - xvectors: List[torch.FloatTensor] each (xvector_dim,)+ - ref_mels: List[torch.FloatTensor] each (mel_len, mel_dim)+ 12Hz:+ Qwen3TTSTokenizerV2EncoderOutput (if return_dict=True) with fields:+ - audio_codes: List[torch.LongTensor] each (codes_len, num_quantizers)++ If return_dict=False, returns the raw tuple from model.encode.+ """+ wavs = self._normalize_audio_inputs(audios, sr=sr)++ inputs = self.feature_extractor(+ raw_audio=wavs,+ sampling_rate=int(self.feature_extractor.sampling_rate),+ return_tensors="pt",+ )+ device = self._get_device()+ dtype = self._get_dtype()+ inputs = inputs.to(device).to(dtype)++ with torch.inference_mode():+ # model.encode expects (B, T) and (B, T)+ enc = self.model.encode(+ inputs["input_values"].squeeze(1),+ inputs["padding_mask"].squeeze(1),+ return_dict=return_dict,+ )+ return enc++ def decode(+ self,+ encoded,+ ) -> Tuple[List[np.ndarray], int]:+ """+ Decode back to waveform.++ Usage:+ 1) Pass the raw output of `encode(...)` directly (recommended).+ - 25Hz: expects fields audio_codes, xvectors, ref_mels+ - 12Hz: expects field audio_codes+ 2) Pass a dict or list[dict] (minimal form) for custom pipelines:+ - 25Hz dict keys: {"audio_codes", "xvectors", "ref_mels"}+ - 12Hz dict keys: {"audio_codes"}+ Values can be torch tensors or numpy arrays.++ Args:+ encoded (Any):+ - ModelOutput returned by `encode()`, OR+ - dict, OR+ - list[dict]++ Returns:+ Tuple[List[np.ndarray], int]:+ - wavs: list of 1-D float32 numpy arrays+ - sample_rate: int, model output sampling rate+ """+ model_type = self.model.get_model_type()++ def _to_tensor(x, dtype=None):+ if isinstance(x, torch.Tensor):+ return x+ x = np.asarray(x)+ t = torch.from_numpy(x)+ if dtype is not None:+ t = t.to(dtype)+ return t++ # Normalize `encoded` into the same shapes as the official demo uses.+ if hasattr(encoded, "audio_codes"):+ # ModelOutput from encode()+ audio_codes_list = encoded.audio_codes+ xvectors_list = getattr(encoded, "xvectors", None)+ ref_mels_list = getattr(encoded, "ref_mels", None)+ elif isinstance(encoded, dict):+ audio_codes_list = encoded["audio_codes"]+ xvectors_list = encoded.get("xvectors", None)+ ref_mels_list = encoded.get("ref_mels", None)+ elif isinstance(encoded, list):+ # list of dicts+ audio_codes_list = [e["audio_codes"] for e in encoded]+ xvectors_list = [e["xvectors"] for e in encoded] if ("xvectors" in encoded[0]) else None+ ref_mels_list = [e["ref_mels"] for e in encoded] if ("ref_mels" in encoded[0]) else None+ else:+ raise TypeError("`encoded` must be an encode output, a dict, or a list of dicts.")++ # Ensure list form for per-sample tensors+ if isinstance(audio_codes_list, torch.Tensor):+ # Could be a single sample tensor or an already padded batch tensor.+ t = audio_codes_list+ if t.dim() == 1:+ # 25Hz single sample: (C,) -> (1, C)+ t = t.unsqueeze(0)+ elif t.dim() == 2:+ # 12Hz single sample: (C, Q) -> (1, C, Q)+ t = t.unsqueeze(0)+ audio_codes_padded = t.to(self._get_device())+ else:+ # List[Tensor/np]+ audio_codes_list = [_to_tensor(c, dtype=torch.long) for c in audio_codes_list]+ audio_codes_padded = pad_sequence(audio_codes_list, batch_first=True, padding_value=0).to(self._get_device())++ with torch.inference_mode():+ if model_type == "qwen3_tts_tokenizer_25hz":+ if xvectors_list is None or ref_mels_list is None:+ raise ValueError("25Hz decode requires `xvectors` and `ref_mels`.")++ dtype = self._get_dtype()+ device = self._get_device()+ if isinstance(xvectors_list, torch.Tensor):+ xvectors_batch = xvectors_list+ if xvectors_batch.dim() == 1: # (D,) -> (1, D)+ xvectors_batch = xvectors_batch.unsqueeze(0)+ xvectors_batch = xvectors_batch.to(device).to(dtype)+ else:+ xvectors_list = [_to_tensor(x, dtype=torch.float32) for x in xvectors_list]+ xvectors_batch = torch.stack(xvectors_list, dim=0).to(device).to(dtype)++ if isinstance(ref_mels_list, torch.Tensor):+ ref_mels_padded = ref_mels_list+ if ref_mels_padded.dim() == 2: # (T, M) -> (1, T, M)+ ref_mels_padded = ref_mels_padded.unsqueeze(0)+ ref_mels_padded = ref_mels_padded.to(device).to(dtype)+ else:+ ref_mels_list = [_to_tensor(m, dtype=torch.float32) for m in ref_mels_list]+ ref_mels_padded = pad_sequence(ref_mels_list, batch_first=True, padding_value=0).to(device).to(dtype)++ dec = self.model.decode(audio_codes_padded, xvectors_batch, ref_mels_padded, return_dict=True)+ wav_tensors = dec.audio_values++ elif model_type == "qwen3_tts_tokenizer_12hz":+ dec = self.model.decode(audio_codes_padded, return_dict=True)+ wav_tensors = dec.audio_values++ else:+ raise ValueError(f"Unknown model type: {model_type}")++ wavs = [w.to(torch.float32).detach().cpu().numpy() for w in wav_tensors]+ return wavs, int(self.model.get_output_sample_rate())++ def get_model_type(self) -> str:+ """+ Get the underlying tokenizer model type.++ Returns:+ str: Model type string from `self.model.config.model_type`+ (e.g. "qwen3_tts_tokenizer_25hz" / "qwen3_tts_tokenizer_12hz").+ """+ return self.model.get_model_type()++ def get_input_sample_rate(self) -> int:+ """+ Get the expected input sample rate for encoding.++ Returns:+ int: Input sample rate (Hz).+ """+ return int(self.model.get_input_sample_rate())++ def get_output_sample_rate(self) -> int:+ """+ Get the output sample rate for decoded waveforms.++ Returns:+ int: Output sample rate (Hz).+ """+ return int(self.model.get_output_sample_rate())++ def get_encode_downsample_rate(self) -> int:+ """+ Get the encoder downsample rate (waveform samples per code step).++ Returns:+ int: Encode downsample rate.+ """+ return int(self.model.get_encode_downsample_rate())++ def get_decode_upsample_rate(self) -> int:+ """+ Get the decoder upsample rate (waveform samples per code step).++ Returns:+ int: Decode upsample rate.+ """+ return int(self.model.get_decode_upsample_rate())diff --git a/models/TTS/qwen3/pipeline.py b/models/TTS/qwen3/pipeline.pynew file mode 100644index 0000000..e8e210c--- /dev/null+++ b/models/TTS/qwen3/pipeline.py@@ -0,0 +1,373 @@+from __future__ import annotations++import json+import math+import os+import random+from dataclasses import dataclass+from pathlib import Path+from typing import Optional++import numpy as np+import torch+from accelerate import init_empty_weights+from tqdm import tqdm+from transformers import Qwen2TokenizerFast+from transformers.generation import StoppingCriteria, StoppingCriteriaList++from mmgp import offload+from shared.utils import files_locator as fl++from . import defs as qwen3_defs+from .core.models.configuration_qwen3_tts import Qwen3TTSConfig+from .core.models.modeling_qwen3_tts import Qwen3TTSForConditionalGeneration+from .core.models.processing_qwen3_tts import Qwen3TTSProcessor+from .inference.qwen3_tts_model import Qwen3TTSModel+from .inference.qwen3_tts_tokenizer import Qwen3TTSTokenizer+++def _seed_everything(seed: int) -> None:+ random.seed(seed)+ np.random.seed(seed)+ torch.manual_seed(seed)+ torch.cuda.manual_seed_all(seed)+ torch.backends.cudnn.deterministic = True+ torch.backends.cudnn.benchmark = False+++def _read_text_or_file(value: Optional[str], label: str) -> str:+ if value is None:+ return ""+ if os.path.isfile(value):+ with open(value, encoding="utf-8") as handle:+ return handle.read()+ if not isinstance(value, str):+ raise ValueError(f"{label} must be a string, got {type(value)}")+ return value+++def _set_interrupt_check(module: torch.nn.Module, check_fn) -> None:+ module._interrupt_check = check_fn+ for child in module.modules():+ child._interrupt_check = check_fn+++class _AbortAndProgressCriteria(StoppingCriteria):+ def __init__(+ self,+ total_seconds: int,+ seconds_per_token: float,+ abort_check,+ callback,+ early_stop_check=None,+ ):+ self.total_seconds = max(1, int(total_seconds))+ self.seconds_per_token = max(0.0, float(seconds_per_token or 0.0))+ self.abort_check = abort_check+ self.early_stop_check = early_stop_check+ self.callback = callback+ self._last_length = None+ self._generated_tokens = 0+ self._reported_seconds = 0+ self._progress = tqdm(total=self.total_seconds, desc="Qwen3 TTS", unit="s")++ def update(self, token_delta: int) -> None:+ if token_delta <= 0:+ return+ self._generated_tokens += token_delta+ if self.seconds_per_token <= 0:+ return+ generated_seconds = int(self._generated_tokens * self.seconds_per_token)+ if generated_seconds <= self._reported_seconds:+ return+ generated_seconds = min(generated_seconds, self.total_seconds)+ delta = generated_seconds - self._reported_seconds+ self._reported_seconds = generated_seconds+ self._progress.update(delta)+ if self.callback is not None:+ self.callback(+ step_idx=self._reported_seconds - 1,+ override_num_inference_steps=self.total_seconds,+ denoising_extra=f"{self._reported_seconds}s/{self.total_seconds}s",+ progress_unit="seconds",+ )++ def close(self) -> None:+ self._progress.close()++ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:+ if self.early_stop_check is not None and self.early_stop_check():+ return True+ if self.abort_check():+ return True+ current_len = int(input_ids.shape[-1])+ if self._last_length is None:+ self._last_length = current_len+ return False+ delta = current_len - self._last_length+ self._last_length = current_len+ self.update(delta)+ return False+++@dataclass+class _Qwen3Assets:+ weights_path: str+ config_path: str+ generate_config_path: Optional[str]+ text_tokenizer_dir: str+ speech_tokenizer_dir: str+ speech_tokenizer_weights: str+++class Qwen3TTSPipeline:+ def __init__(+ self,+ model_weights_path: str,+ base_model_type: str,+ *,+ ckpt_root: Optional[Path] = None,+ device: Optional[torch.device] = None,+ ) -> None:+ self.device = device or torch.device("cpu")+ self.base_model_type = base_model_type+ self.ckpt_root = Path(ckpt_root) if ckpt_root is not None else Path(fl.get_download_location())+ self._interrupt = False+ self._early_stop = False++ assets = self._resolve_assets(model_weights_path)+ self.model = self._load_main_model(assets)+ self.speech_tokenizer = self._load_speech_tokenizer(assets)+ self.processor = self._load_text_processor(assets)++ self.model.load_speech_tokenizer(self.speech_tokenizer)+ self.tts = Qwen3TTSModel(+ model=self.model,+ processor=self.processor,+ generate_defaults=self.model.generate_config or {},+ )+ self.sample_rate = int(self.speech_tokenizer.get_output_sample_rate())++ _set_interrupt_check(self.model, self._abort_requested)+ _set_interrupt_check(self.speech_tokenizer.model, self._abort_requested)++ self.supported_speakers = sorted(self.tts.get_supported_speakers() or [])+ self.supported_languages = sorted(self.tts.get_supported_languages() or [])++ def _abort_requested(self) -> bool:+ return bool(self._interrupt)++ def _early_stop_requested(self) -> bool:+ return bool(self._early_stop)++ def request_early_stop(self) -> None:+ self._early_stop = True++ def _get_tokens_per_second(self) -> float:+ try:+ decode_rate = self.speech_tokenizer.get_decode_upsample_rate()+ output_sr = self.speech_tokenizer.get_output_sample_rate()+ if decode_rate and output_sr:+ return float(output_sr) / float(decode_rate)+ except Exception:+ pass+ pos_per_second = getattr(self.model.config.talker_config, "position_id_per_seconds", None)+ if pos_per_second:+ return float(pos_per_second)+ return 1.0++ def _get_seconds_per_token(self) -> float:+ tokens_per_second = self._get_tokens_per_second()+ if tokens_per_second <= 0:+ return 1.0+ return 1.0 / tokens_per_second++ def _resolve_assets(self, model_weights_path: str) -> _Qwen3Assets:+ weights_path = model_weights_path+ config_path = qwen3_defs.get_qwen3_config_path(self.base_model_type)+ generate_config_path = qwen3_defs.get_qwen3_generation_config_path()+ text_tokenizer_dir = fl.locate_folder(qwen3_defs.QWEN3_TTS_TEXT_TOKENIZER_DIR)+ speech_tokenizer_dir = fl.locate_folder(qwen3_defs.QWEN3_TTS_SPEECH_TOKENIZER_DIR)+ speech_weights = fl.locate_file(os.path.join(qwen3_defs.QWEN3_TTS_SPEECH_TOKENIZER_DIR, qwen3_defs.QWEN3_TTS_SPEECH_TOKENIZER_WEIGHTS))++ return _Qwen3Assets(+ weights_path=weights_path,+ config_path=config_path,+ generate_config_path=generate_config_path,+ text_tokenizer_dir=text_tokenizer_dir,+ speech_tokenizer_dir=speech_tokenizer_dir,+ speech_tokenizer_weights=speech_weights,+ )++ def _load_main_model(self, assets: _Qwen3Assets) -> Qwen3TTSForConditionalGeneration:+ with open(assets.config_path, "r", encoding="utf-8") as handle:+ config_dict = json.load(handle)+ config = Qwen3TTSConfig(**config_dict)+ with init_empty_weights():+ model = Qwen3TTSForConditionalGeneration(config)+ offload.load_model_data(+ model,+ assets.weights_path,+ default_dtype=None,+ writable_tensors=False,+ )+ model.eval()+ if assets.generate_config_path:+ with open(assets.generate_config_path, "r", encoding="utf-8") as handle:+ model.load_generate_config(json.load(handle))+ first_param = next(model.parameters(), None)+ if first_param is not None:+ model._model_dtype = first_param.dtype+ return model++ def _load_speech_tokenizer(self, assets: _Qwen3Assets) -> Qwen3TTSTokenizer:+ tokenizer = Qwen3TTSTokenizer.from_local(+ assets.speech_tokenizer_dir,+ assets.speech_tokenizer_weights,+ )+ return tokenizer++ def _load_text_processor(self, assets: _Qwen3Assets) -> Qwen3TTSProcessor:+ tokenizer = Qwen2TokenizerFast.from_pretrained(assets.text_tokenizer_dir)+ return Qwen3TTSProcessor(tokenizer=tokenizer)++ def _build_stopping_criteria(+ self,+ max_new_tokens: int,+ seconds_per_token: float,+ callback,+ total_seconds: Optional[int] = None,+ ):+ if total_seconds is None:+ total_seconds = max(1, int(math.ceil(max_new_tokens * seconds_per_token)))+ criteria = _AbortAndProgressCriteria(+ total_seconds,+ seconds_per_token,+ self._abort_requested,+ callback,+ early_stop_check=self._early_stop_requested,+ )+ if callback is not None:+ callback(+ step_idx=-1,+ override_num_inference_steps=criteria.total_seconds,+ denoising_extra=f"0s/{criteria.total_seconds}s",+ progress_unit="seconds",+ )+ return criteria, StoppingCriteriaList([criteria])++ def generate(+ self,+ input_prompt: str,+ model_mode: Optional[str],+ audio_guide: Optional[str],+ *,+ alt_prompt: Optional[str] = None,+ temperature: float = 0.9,+ seed: int = -1,+ callback=None,+ **kwargs,+ ):+ self._interrupt = False+ self._early_stop = False++ text = _read_text_or_file(input_prompt, "Prompt")+ if not text.strip():+ raise ValueError("Prompt text cannot be empty for Qwen3 TTS.")++ if seed is not None and int(seed) >= 0:+ _seed_everything(int(seed))++ duration_seconds = kwargs.get("duration_seconds", None)+ if duration_seconds is not None:+ try:+ duration_seconds = float(duration_seconds)+ except (TypeError, ValueError):+ duration_seconds = None++ seconds_per_token = self._get_seconds_per_token()+ total_seconds = None+ if duration_seconds is not None and duration_seconds > 0:+ tokens_per_second = self._get_tokens_per_second()+ max_new_tokens = max(1, int(math.ceil(duration_seconds * tokens_per_second)))+ total_seconds = max(1, int(math.ceil(duration_seconds)))+ else:+ max_new_tokens = kwargs.get("max_new_tokens")+ if max_new_tokens is None:+ sampling_steps = kwargs.get("sampling_steps")+ if sampling_steps:+ max_new_tokens = int(sampling_steps)+ if max_new_tokens is None:+ max_new_tokens = self.tts.generate_defaults.get("max_new_tokens", 2048)+ max_new_tokens = int(max_new_tokens)++ criteria, stopping = self._build_stopping_criteria(+ max_new_tokens,+ seconds_per_token,+ callback,+ total_seconds=total_seconds,+ )+ gen_kwargs = {+ "max_new_tokens": max_new_tokens,+ "temperature": float(temperature),+ "stopping_criteria": stopping,+ }++ try:+ if self.base_model_type == "qwen3_tts_customvoice":+ if not self.supported_speakers:+ raise ValueError("No supported speakers found for Qwen3 CustomVoice.")+ speaker = model_mode or self.supported_speakers[0]+ language = "auto"+ wavs, sr = self.tts.generate_custom_voice(+ text=text,+ language=language,+ speaker=speaker,+ instruct=_read_text_or_file(alt_prompt, "Instruction"),+ **gen_kwargs,+ )+ elif self.base_model_type == "qwen3_tts_voicedesign":+ language = (model_mode or "auto").lower()+ wavs, sr = self.tts.generate_voice_design(+ text=text,+ language=language,+ instruct=_read_text_or_file(alt_prompt, "Instruction"),+ **gen_kwargs,+ )+ elif self.base_model_type == "qwen3_tts_base":+ if not audio_guide:+ raise ValueError("Reference audio is required for Qwen3 Base voice clone.")+ language = (model_mode or "auto").lower()+ ref_text = _read_text_or_file(alt_prompt, "Reference transcript")+ x_vector_only_mode = not ref_text.strip()+ if x_vector_only_mode:+ ref_text = None+ wavs, sr = self.tts.generate_voice_clone(+ text=text,+ language=language,+ ref_audio=audio_guide,+ ref_text=ref_text,+ x_vector_only_mode=x_vector_only_mode,+ **gen_kwargs,+ )+ else:+ raise ValueError(f"Unknown Qwen3 TTS type: {self.base_model_type}")+ except RuntimeError as exc:+ if "Abort requested" in str(exc):+ return None+ raise+ finally:+ criteria.close()++ if self._abort_requested():+ return None++ wav = torch.from_numpy(wavs[0])+ return {"x": wav, "audio_sampling_rate": int(sr)}++ def release(self) -> None:+ for module in [self.model, getattr(self.speech_tokenizer, "model", None)]:+ if hasattr(module, "to"):+ module.to("cpu")+ self.model = None+ self.speech_tokenizer = Nonediff --git a/models/TTS/tts_handler.py b/models/TTS/tts_handler.pyindex bf84bb1..11b9143 100644--- a/models/TTS/tts_handler.py+++ b/models/TTS/tts_handler.py@@ -4,6 +4,7 @@ import gradio as grimport torchfrom shared.utils import files_locator as fl+from .qwen3 import defs as qwen3_defs_FALLBACK_SUPPORTED_LANGUAGES = {@@ -87,6 +88,7 @@ def _get_chatterbox_model_def():},"any_audio_prompt": True,"chatterbox_controls": True,+ "text_prompt_enhancer_instructions": qwen3_defs.TTS_MONOLOGUE_PROMPT,}@@ -98,6 +100,7 @@ def _get_heartmula_model_def():"guidance_max_phases": 0,"no_negative_prompt": True,"image_prompt_types_allowed": "",+ "supports_early_stop": True,"profiles_dir": ["heartmula_oss_3b"],"alt_prompt": {"label": "Keywords / Tags",@@ -276,7 +279,12 @@ def _get_yue_download_def(model_def):class family_handler:@staticmethoddef query_supported_types():- return ["chatterbox", "heartmula_oss_3b", "yue"]+ return [+ "chatterbox",+ "heartmula_oss_3b",+ "yue",+ *list(qwen3_defs.QWEN3_TTS_VARIANTS),+ ]@staticmethoddef query_family_maps():@@ -309,6 +317,8 @@ class family_handler:return _get_heartmula_model_def()if base_model_type == "yue":return _get_yue_model_def(model_def)+ if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:+ return qwen3_defs.get_qwen3_model_def(base_model_type)return _get_chatterbox_model_def()@staticmethod@@ -317,6 +327,8 @@ class family_handler:return _get_heartmula_download_def()if base_model_type == "yue":return _get_yue_download_def(model_def or {})+ if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:+ return qwen3_defs.get_qwen3_download_def(base_model_type)return _get_chatterbox_download_def()@staticmethod@@ -413,6 +425,33 @@ class family_handler:}return pipeline, pipe+ if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:+ from .qwen3.pipeline import Qwen3TTSPipeline++ weights_candidate = None+ if isinstance(model_filename, (list, tuple)):+ if len(model_filename) > 0:+ weights_candidate = model_filename[0]+ else:+ weights_candidate = model_filename+ weights_path = None+ if weights_candidate:+ weights_path = fl.locate_file(weights_candidate, error_if_none=False)+ if weights_path is None:+ weights_path = weights_candidate++ pipeline = Qwen3TTSPipeline(+ model_weights_path=weights_path,+ base_model_type=base_model_type,+ ckpt_root=ckpt_root,+ device=torch.device("cpu"),+ )++ pipe = {"transformer": pipeline.model}+ if getattr(pipeline, "speech_tokenizer", None) is not None:+ pipe["speech_tokenizer"] = pipeline.speech_tokenizer.model+ return pipeline, pipe+from .chatterbox.pipeline import ChatterboxPipelinepipeline = ChatterboxPipeline(ckpt_root=ckpt_root, device="cpu")@@ -437,6 +476,22 @@ class family_handler:defaults = {"audio_prompt_type": "",}+ elif base_model_type == "qwen3_tts_customvoice":+ speakers = qwen3_defs.get_qwen3_speakers(base_model_type)+ defaults = {+ "audio_prompt_type": "",+ "model_mode": speakers[0] if speakers else "",+ }+ elif base_model_type == "qwen3_tts_voicedesign":+ defaults = {+ "audio_prompt_type": "",+ "model_mode": "auto",+ }+ elif base_model_type == "qwen3_tts_base":+ defaults = {+ "audio_prompt_type": "A",+ "model_mode": "auto",+ }else:defaults = {"audio_prompt_type": "A",@@ -459,9 +514,7 @@ class family_handler:"num_inference_steps": 0,"negative_prompt": "","temperature": 1.0,- "multi_prompts_gen_type": 2,- "override_profile": 3.5,-+ "multi_prompts_gen_type": 2})return@@ -480,6 +533,59 @@ class family_handler:)return+ if base_model_type == "qwen3_tts_customvoice":+ speakers = qwen3_defs.get_qwen3_speakers(base_model_type)+ default_speaker = speakers[0] if speakers else ""+ ui_defaults.update(+ {+ "audio_prompt_type": "",+ "model_mode": default_speaker,+ "alt_prompt": "",+ "duration_seconds": qwen3_defs.get_qwen3_duration_default(),+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "temperature": 0.9,+ "multi_prompts_gen_type": 2,+ }+ )+ return++ if base_model_type == "qwen3_tts_voicedesign":+ ui_defaults.update(+ {+ "audio_prompt_type": "",+ "model_mode": "auto",+ "alt_prompt": "young female, warm tone, clear articulation",+ "duration_seconds": qwen3_defs.get_qwen3_duration_default(),+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "temperature": 0.9,+ "multi_prompts_gen_type": 2,+ }+ )+ return++ if base_model_type == "qwen3_tts_base":+ ui_defaults.update(+ {+ "audio_prompt_type": "A",+ "model_mode": "auto",+ "alt_prompt": "",+ "duration_seconds": qwen3_defs.get_qwen3_duration_default(),+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "temperature": 0.9,+ "multi_prompts_gen_type": 2,+ }+ )+ return+ui_defaults.update({"audio_prompt_type": "A",@@ -530,6 +636,29 @@ class family_handler:return "Yue base model does not support audio prompts. Please use Yue ICL."return None+ if base_model_type == "qwen3_tts_customvoice":+ if one_prompt is None or len(str(one_prompt).strip()) == 0:+ return "Prompt text cannot be empty for Qwen3 CustomVoice."+ speaker = inputs.get("model_mode", "")+ if not speaker:+ return "Please select a speaker for Qwen3 CustomVoice."+ speakers = qwen3_defs.get_qwen3_speakers(base_model_type)+ if speaker.lower() not in speakers:+ return f"Unsupported speaker '{speaker}'."+ return None++ if base_model_type == "qwen3_tts_voicedesign":+ if one_prompt is None or len(str(one_prompt).strip()) == 0:+ return "Prompt text cannot be empty for Qwen3 VoiceDesign."+ return None++ if base_model_type == "qwen3_tts_base":+ if one_prompt is None or len(str(one_prompt).strip()) == 0:+ return "Prompt text cannot be empty for Qwen3 Base voice clone."+ if inputs.get("audio_guide") is None:+ return "Qwen3 Base requires a reference audio clip."+ return None+if len(one_prompt) > 300:gr.Info("It is recommended to use a prompt that has less than 300 characters,"diff --git a/plugins/wan2gp-configuration/plugin.py b/plugins/wan2gp-configuration/plugin.pyindex 2c50ab5..9f1f362 100644--- a/plugins/wan2gp-configuration/plugin.py+++ b/plugins/wan2gp-configuration/plugin.py@@ -15,7 +15,9 @@ class ConfigTabPlugin(WAN2GPPlugin):self.request_global("server_config_filename")self.request_global("attention_mode")self.request_global("compile")- self.request_global("default_profile")+ self.request_global("default_profile_video")+ self.request_global("default_profile_image")+ self.request_global("default_profile_audio")self.request_global("vae_config")self.request_global("boost")self.request_global("preload_model_policy")@@ -29,6 +31,7 @@ class ConfigTabPlugin(WAN2GPPlugin):self.request_global("memory_profile_choices")self.request_global("save_path")self.request_global("image_save_path")+ self.request_global("audio_save_path")self.request_global("quit_application")self.request_global("release_model")self.request_global("get_sorted_dropdown")@@ -154,7 +157,21 @@ class ConfigTabPlugin(WAN2GPPlugin):self.depth_anything_v2_variant_choice = gr.Dropdown(choices=[("Large (more precise, slower)", "vitl"), ("Big (less precise, faster)", "vitb")], value=self.server_config.get("depth_anything_v2_variant", "vitl"), label="Depth Anything v2 VACE Preprocessor")self.vae_config_choice = gr.Dropdown(choices=[("Auto", 0), ("Disabled (fastest, high VRAM)", 1), ("256x256 Tiles (for >=8GB VRAM)", 2), ("128x128 Tiles (for >=6GB VRAM)", 3)], value=self.vae_config, label="VAE Tiling (to reduce VRAM usage)")self.boost_choice = gr.Dropdown(choices=[("ON", 1), ("OFF", 2)], value=self.boost, label="Boost (~10% speedup for ~1GB VRAM)")- self.profile_choice = gr.Dropdown(choices=self.memory_profile_choices, value=self.default_profile, label="Memory Profile (Advanced)")+ self.video_profile_choice = gr.Dropdown(+ choices=self.memory_profile_choices,+ value=self.default_profile_video,+ label="Default Memory Profile (Video)",+ )+ self.image_profile_choice = gr.Dropdown(+ choices=self.memory_profile_choices,+ value=self.default_profile_image,+ label="Default Memory Profile (Image)",+ )+ self.audio_profile_choice = gr.Dropdown(+ choices=self.memory_profile_choices,+ value=self.default_profile_audio,+ label="Default Memory Profile (Audio)",+ )self.preload_in_VRAM_choice = gr.Slider(0, 40000, value=self.server_config.get("preload_in_VRAM", 0), step=100, label="VRAM (MB) for Preloaded Models (0=profile default)")self.max_reserved_loras_choice = gr.Slider(-1,@@ -209,6 +226,7 @@ class ConfigTabPlugin(WAN2GPPlugin):)self.video_save_path_choice = gr.Textbox(label="Video Output Folder (requires restart)", value=self.save_path)self.image_save_path_choice = gr.Textbox(label="Image Output Folder (requires restart)", value=self.image_save_path)+ self.audio_save_path_choice = gr.Textbox(label="Audio Output Folder (requires restart)", value=self.audio_save_path)with gr.Tab("Notifications"):self.notification_sound_enabled_choice = gr.Dropdown(choices=[("On", 1), ("Off", 0)], value=self.server_config.get("notification_sound_enabled", 0), label="Notification Sound")@@ -227,11 +245,12 @@ class ConfigTabPlugin(WAN2GPPlugin):self.quantization_choice, self.transformer_dtype_policy_choice, self.mixed_precision_choice,self.text_encoder_quantization_choice, self.VAE_precision_choice, self.compile_choice,self.depth_anything_v2_variant_choice, self.vae_config_choice, self.boost_choice,- self.profile_choice, self.preload_in_VRAM_choice, self.max_reserved_loras_choice,+ self.video_profile_choice, self.image_profile_choice, self.audio_profile_choice,+ self.preload_in_VRAM_choice, self.max_reserved_loras_choice,self.enhancer_enabled_choice, self.enhancer_mode_choice, self.mmaudio_mode_choice, self.mmaudio_persistence_choice, self.rife_version_choice,self.video_output_codec_choice, self.image_output_codec_choice, self.audio_output_codec_choice,self.metadata_choice, self.embed_source_images_choice,- self.video_save_path_choice, self.image_save_path_choice,+ self.video_save_path_choice, self.image_save_path_choice, self.audio_save_path_choice,self.notification_sound_enabled_choice, self.notification_sound_volume_choice,self.resolution]@@ -276,11 +295,12 @@ class ConfigTabPlugin(WAN2GPPlugin):quantization_choice, transformer_dtype_policy_choice, mixed_precision_choice,text_encoder_quantization_choice, VAE_precision_choice, compile_choice,depth_anything_v2_variant_choice, vae_config_choice, boost_choice,- profile_choice, preload_in_VRAM_choice, max_reserved_loras_choice,+ video_profile_choice, image_profile_choice, audio_profile_choice,+ preload_in_VRAM_choice, max_reserved_loras_choice,enhancer_enabled_choice, enhancer_mode_choice, mmaudio_mode_choice, mmaudio_persistence_choice, rife_version_choice,video_output_codec_choice, image_output_codec_choice, audio_output_codec_choice,metadata_choice, embed_source_images_choice,- save_path_choice, image_save_path_choice,+ save_path_choice, image_save_path_choice, audio_save_path_choice,notification_sound_enabled_choice, notification_sound_volume_choice,last_resolution_choice) = args@@ -297,7 +317,9 @@ class ConfigTabPlugin(WAN2GPPlugin):new_server_config = {"attention_mode": attention_choice, "transformer_types": transformer_types_choices,"text_encoder_quantization": text_encoder_quantization_choice, "save_path": save_path_choice,- "image_save_path": image_save_path_choice, "compile": compile_choice, "profile": profile_choice,+ "image_save_path": image_save_path_choice, "audio_save_path": audio_save_path_choice,+ "compile": compile_choice, "profile": video_profile_choice,+ "video_profile": video_profile_choice, "image_profile": image_profile_choice, "audio_profile": audio_profile_choice,"vae_config": vae_config_choice, "vae_precision": VAE_precision_choice,"mixed_precision": mixed_precision_choice, "metadata_type": metadata_choice,"transformer_quantization": quantization_choice, "transformer_dtype_policy": transformer_dtype_policy_choice,@@ -340,7 +362,7 @@ class ConfigTabPlugin(WAN2GPPlugin):changes = [k for k, v in new_server_config.items() if v != old_server_config.get(k)]no_reload_keys = [- "attention_mode", "vae_config", "boost", "save_path", "image_save_path",+ "attention_mode", "vae_config", "boost", "save_path", "image_save_path", "audio_save_path","metadata_type", "clear_file_list", "fit_canvas", "depth_anything_v2_variant","notification_sound_enabled", "notification_sound_volume", "mmaudio_mode","mmaudio_persistence", "mmaudio_enabled", "rife_version",@@ -355,12 +377,16 @@ class ConfigTabPlugin(WAN2GPPlugin):self.set_global("three_levels_hierarchy", new_server_config["model_hierarchy_type"] == 1)self.set_global("attention_mode", new_server_config["attention_mode"])self.set_global("default_profile", new_server_config["profile"])+ self.set_global("default_profile_video", new_server_config["video_profile"])+ self.set_global("default_profile_image", new_server_config["image_profile"])+ self.set_global("default_profile_audio", new_server_config["audio_profile"])self.set_global("compile", new_server_config["compile"])self.set_global("text_encoder_quantization", new_server_config["text_encoder_quantization"])self.set_global("vae_config", new_server_config["vae_config"])self.set_global("boost", new_server_config["boost"])self.set_global("save_path", new_server_config["save_path"])self.set_global("image_save_path", new_server_config["image_save_path"])+ self.set_global("audio_save_path", new_server_config["audio_save_path"])self.set_global("preload_model_policy", new_server_config["preload_model_policy"])self.set_global("transformer_quantization", new_server_config["transformer_quantization"])self.set_global("transformer_dtype_policy", new_server_config["transformer_dtype_policy"])diff --git a/requirements.txt b/requirements.txtindex 46888d2..9783294 100644--- a/requirements.txt+++ b/requirements.txt@@ -59,9 +59,9 @@ pydantic==2.10.6# Math & modelingtorchdiffeq>=0.2.5tensordict>=0.6.1-mmgp==3.7.1+mmgp==3.7.2peft==0.15.0-vector-quantize-pytorch==1.27.15+vector-quantize-pytorchmatplotlibgguf==0.17.1diff --git a/shared/gradio/audio_gallery.py b/shared/gradio/audio_gallery.pyindex 9f0f265..a38e5eb 100644--- a/shared/gradio/audio_gallery.py+++ b/shared/gradio/audio_gallery.py@@ -6,6 +6,17 @@ import jsonimport uuid+def _get_selected_idx(audio_infos, selected_idx):+ selected_idx = int(selected_idx) if selected_idx is not None else 0+ if selected_idx >= len(audio_infos):+ selected_idx = len(audio_infos) -1+ elif selected_idx < 0:+ selected_idx = 0+ if len(audio_infos) == 0:+ selected_idx = -1+ return selected_idx++class AudioGallery:"""A custom Gradio component that displays an audio gallery with thumbnails.@@ -19,7 +30,7 @@ class AudioGallery:update_only: If True, only render the inner HTML/Audio (internal use)"""- def __init__(self, audio_paths=None, selected_index=0, max_thumbnails=10, height=400, label="Audio Gallery", update_only=False):+ def __init__(self, audio_paths=None, selected_index=-1, max_thumbnails=10, height=400, label="Audio Gallery", update_only=False):self.audio_paths = audio_paths or []self.selected_index = selected_indexself.max_thumbnails = max_thumbnails@@ -204,8 +215,8 @@ AG.tryInstall();else:selected_idx = 0- if not audio_infos or selected_idx >= len(audio_infos) or selected_idx < 0:- selected_idx = 0+ selected_idx = _get_selected_idx(audio_infos, selected_idx)+# Trigger id to notify the frontend to refresh (observed via MutationObserver on HTML rerender)refresh_id = str(uuid.uuid4())@@ -295,7 +306,7 @@ AG.tryInstall();self.refresh_trigger.change(fn=self._refresh_gallery,inputs=[self.refresh_trigger, self.state_paths, self.state_selected],- outputs=[self.audio_player, self.gallery_html],+ outputs=[self.audio_player, self.gallery_html, self.state_selected],show_progress="hidden",)@@ -329,25 +340,23 @@ AG.tryInstall();def _refresh_gallery(self, refresh_id, paths_json, selected_idx):"""Refresh gallery based on state (programmatic)."""if not refresh_id:- return self._render_from_state(paths_json, selected_idx)[:2]+ return self._render_from_state(paths_json, selected_idx)[:2], selected_idxtry:paths = json.loads(paths_json) if paths_json else []audio_infos = self._process_audio_paths(paths)if not audio_infos:- return None, self._create_gallery_html([], 0)+ return None, self._create_gallery_html([], 0), -1- selected_idx = int(selected_idx) if selected_idx is not None else 0- if selected_idx >= len(audio_infos) or selected_idx < 0:- selected_idx = 0+ selected_idx = _get_selected_idx(audio_infos, selected_idx)selected_path = audio_infos[selected_idx]["path"]gallery_html_content = self._create_gallery_html(audio_infos, selected_idx)- return selected_path, gallery_html_content+ return selected_path, gallery_html_content, selected_idxexcept Exception:- return None, self._create_gallery_html([], 0)+ return None, self._create_gallery_html([], 0), -1def _get_audio_duration(self, audio_path):"""Get audio duration in seconds. Returns formatted string."""@@ -638,10 +647,7 @@ AG.tryInstall();if not audio_infos:return None, self._create_gallery_html([], 0), paths_json, 0, ""- selected_idx = int(selected_idx) if selected_idx is not None else 0- if selected_idx >= len(audio_infos) or selected_idx < 0:- selected_idx = 0-+ selected_idx = _get_selected_idx(audio_infos, selected_idx)selected_path = audio_infos[selected_idx]["path"]gallery_html_content = self._create_gallery_html(audio_infos, selected_idx)diff --git a/wgp.py b/wgp.pyindex 958fb00..776df9c 100644--- a/wgp.py+++ b/wgp.py@@ -84,8 +84,8 @@ AUTOSAVE_PATH = AUTOSAVE_FILENAMEAUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAMECONFIG_FILENAME = "wgp_config.json"PROMPT_VARS_MAX = 10-target_mmgp_version = "3.7.1"-WanGP_version = "10.43"+target_mmgp_version = "3.7.2"+WanGP_version = "10.50"settings_version = 2.43max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -1543,11 +1543,26 @@ def autosave_queue():def finalize_generation_with_state(current_state):if not isinstance(current_state, dict) or 'gen' not in current_state:- return gr.update(), gr.update(interactive=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False, value=""), gr.update(), current_state-- gallery_update, audio_files_paths_update, audio_file_selected_update, audio_gallery_refresh_trigger_update, gallery_tabs_update, current_gallery_tab_update, abort_btn_update, gen_btn_update, add_queue_btn_update, current_gen_col_update, gen_info_update = finalize_generation(current_state)+ return (+ gr.update(),+ gr.update(),+ gr.update(),+ gr.update(),+ gr.update(),+ gr.update(),+ gr.update(interactive=True),+ gr.update(interactive=True),+ gr.update(visible=True),+ gr.update(visible=False),+ gr.update(visible=False),+ gr.update(visible=False, value=""),+ gr.update(),+ current_state,+ )++ gallery_tabs_update, current_gallery_tab_update, gallery_update, audio_files_paths_update, audio_file_selected_update, audio_gallery_refresh_trigger_update, abort_btn_update, earlystop_btn_update, gen_btn_update, add_queue_btn_update, current_gen_col_update, gen_info_update = finalize_generation(current_state)accordion_update = gr.Accordion(open=False) if len(get_gen_info(current_state).get("queue", [])) <= 1 else gr.update()- return gallery_update, audio_files_paths_update, audio_file_selected_update, audio_gallery_refresh_trigger_update, gallery_tabs_update, current_gallery_tab_update, abort_btn_update, gen_btn_update, add_queue_btn_update, current_gen_col_update, gen_info_update, accordion_update, current_state+ return gallery_tabs_update, current_gallery_tab_update, gallery_update, audio_files_paths_update, audio_file_selected_update, audio_gallery_refresh_trigger_update, abort_btn_update, earlystop_btn_update, gen_btn_update, add_queue_btn_update, current_gen_col_update, gen_info_update, accordion_update, current_statedef generate_queue_html(queue):if len(queue) <= 1:@@ -2120,6 +2135,9 @@ if not Path(config_load_filename).is_file():"max_reserved_loras": -1,"vae_config": 0,"profile" : profile_type.LowRAM_LowVRAM,+ "video_profile": profile_type.LowRAM_LowVRAM,+ "image_profile": profile_type.LowRAM_LowVRAM,+ "audio_profile": 3.5,"preload_model_policy": [],"UI_theme": "default","checkpoints_paths": fl.default_checkpoints_paths,@@ -2128,6 +2146,7 @@ if not Path(config_load_filename).is_file():"mmaudio_mode": 0,"mmaudio_persistence": 1,"rife_version": "v3",+ "audio_save_path": "outputs",}with open(server_config_filename, "w", encoding="utf-8") as writer:@@ -2183,6 +2202,26 @@ def get_mmaudio_settings(config):_normalize_mmaudio_config(server_config)+def _normalize_profile_defaults(config):+ if "profile" not in config:+ config["profile"] = profile_type.LowRAM_LowVRAM+ base_profile = config.get("profile", profile_type.LowRAM_LowVRAM)+ config.setdefault("video_profile", base_profile)+ config.setdefault("image_profile", base_profile)+ config.setdefault("audio_profile", 3.5)+ return config["video_profile"], config["image_profile"], config["audio_profile"]++def _normalize_output_paths(config):+ if "save_path" not in config:+ config["save_path"] = "outputs"+ if "image_save_path" not in config:+ config["image_save_path"] = config["save_path"]+ if "audio_save_path" not in config:+ config["audio_save_path"] = config["save_path"]++_normalize_profile_defaults(server_config)+_normalize_output_paths(server_config)+# Deprecated modelsfor path in ["wan2.1_Vace_1.3B_preview_bf16.safetensors", "sky_reels2_diffusion_forcing_1.3B_bf16.safetensors","sky_reels2_diffusion_forcing_720p_14B_bf16.safetensors","sky_reels2_diffusion_forcing_720p_14B_quanto_int8.safetensors", "sky_reels2_diffusion_forcing_720p_14B_quanto_fp16_int8.safetensors", "wan2.1_image2video_480p_14B_bf16.safetensors", "wan2.1_image2video_480p_14B_quanto_int8.safetensors",@@ -2706,8 +2745,11 @@ if len(args.attention)> 0:else:raise Exception(f"Unknown attention mode '{args.attention}'")-default_profile = force_profile_no if force_profile_no >=0 else server_config["profile"]-loaded_profile = -1+default_profile_video = force_profile_no if force_profile_no >= 0 else server_config["video_profile"]+default_profile_image = force_profile_no if force_profile_no >= 0 else server_config["image_profile"]+default_profile_audio = force_profile_no if force_profile_no >= 0 else server_config["audio_profile"]+default_profile = default_profile_video+loaded_profile = force_profile_no = -1compile = server_config.get("compile", "")boost = server_config.get("boost", 1)vae_config = server_config.get("vae_config", 0)@@ -2717,6 +2759,7 @@ if len(args.vae_config) > 0:reload_needed = Falsesave_path = server_config.get("save_path", os.path.join(os.getcwd(), "outputs"))image_save_path = server_config.get("image_save_path", os.path.join(os.getcwd(), "outputs"))+audio_save_path = server_config.get("audio_save_path", save_path)if not "video_output_codec" in server_config: server_config["video_output_codec"]= "libx264_8"if not "video_container" in server_config: server_config["video_container"]= "mp4"if not "embed_source_images" in server_config: server_config["embed_source_images"]= False@@ -3176,8 +3219,34 @@ def get_transformer_model(model, submodel_no = 1):else:raise Exception("no transformer found")-def compute_profile(override_profile):- return override_profile if override_profile != -1 else default_profile+def _normalize_output_type(output_type):+ if output_type is None:+ return "video"+ output_type = str(output_type).lower()+ if output_type not in ("video", "image", "audio"):+ return "video"+ return output_type++def get_default_profile(output_type):+ if force_profile_no >= 0:+ return force_profile_no+ output_type = _normalize_output_type(output_type)+ if output_type == "image":+ return default_profile_image+ if output_type == "audio":+ return default_profile_audio+ return default_profile_video++def compute_profile(override_profile, output_type="video"):+ return override_profile if override_profile != -1 else get_default_profile(output_type)++def get_output_type_for_model(model_type, image_mode=0):+ model_def = get_model_def(model_type)+ if model_def is not None and model_def.get("audio_only", False):+ return "audio"+ if image_mode and image_mode > 0:+ return "image"+ return "video"def init_pipe(pipe, kwargs, profile):preload =int(args.preload)@@ -3258,7 +3327,7 @@ def setup_prompt_enhancer(pipe, kwargs):-def load_models(model_type, override_profile = -1, **model_kwargs):+def load_models(model_type, override_profile = -1, output_type="video", **model_kwargs):global transformer_type, loaded_profilebase_model_type = get_base_model_type(model_type)model_def = get_model_def(model_type)@@ -3345,7 +3414,7 @@ def load_models(model_type, override_profile = -1, **model_kwargs):print(f"Loading Text Encoder '{text_encoder_filename}' ...")- profile = compute_profile(override_profile)+ profile = compute_profile(override_profile, output_type)torch.set_default_device('cpu')wan_model, pipe = model_type_handler.load_model(local_model_file_list, model_type, base_model_type, model_def, quantizeTransformer = quantizeTransformer, text_encoder_quantization = text_encoder_quantization,@@ -3381,7 +3450,10 @@ if not "P" in preload_model_policy:wan_model, offloadobj, transformer = None, None, Nonereload_needed = Trueelse:- wan_model, offloadobj = load_models(transformer_type)+ wan_model, offloadobj = load_models(+ transformer_type,+ output_type=get_output_type_for_model(transformer_type, 0),+ )if check_loras:transformer = get_transformer_model(wan_model)if hasattr(wan_model, "get_trans_lora"):@@ -3471,6 +3543,16 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_mprocess_status = gen.get("process_status", None)if process_status == "process:main": breakforce_refresh = True+ if gen.get("early_stop", False) and not gen.get("early_stop_forwarded", False):+ gen["early_stop_forwarded"] = True+ if hasattr(pipe, "request_early_stop"):+ pipe.request_early_stop()+ elif wan_model is not None and hasattr(wan_model, "request_early_stop"):+ wan_model.request_early_stop()+ elif hasattr(pipe, "_early_stop"):+ pipe._early_stop = True+ elif wan_model is not None and hasattr(wan_model, "_early_stop"):+ wan_model._early_stop = Truerefresh_id = gen.get("refresh", -1)if force_refresh or step_idx >= 0:pass@@ -3494,6 +3576,8 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_mif gen.get("abort", False):# pipe._interrupt = Truephase = "Aborting"+ elif gen.get("early_stop", False):+ phase = "Early Stop in progress"elif step_idx == num_inference_steps:phase = "VAE Decoding"else:@@ -3580,6 +3664,26 @@ def abort_generation(state):else:return gr.Button(interactive= True)+def early_stop_generation(state):+ gen = get_gen_info(state)+ gen["resume"] = True+ if "in_progress" in gen:+ queue = gen.get("queue", [])+ model_type = queue[0].get("params", {}).get("model_type") if queue else None+ model_def = get_model_def(model_type) if model_type else None+ if not model_def or not model_def.get("supports_early_stop", False):+ gr.Info("Early Stop is not supported for this model.")+ return gr.Button(interactive=True)+ if gen.get("early_stop", False):+ return gr.Button(interactive=False)+ gen["early_stop"] = True+ gen["early_stop_forwarded"] = False+ msg = "Early Stop in progress"+ gen["status"] = msg+ gr.Info(msg)+ return gr.Button(interactive=False)+ return gr.Button(interactive=True)+def pack_audio_gallery_state(audio_file_list, selected_index, refresh = True):return [json.dumps(audio_file_list), selected_index, time.time()]@@ -3593,20 +3697,31 @@ def refresh_gallery(state): #, msgfile_list = gen.get("file_list", None)choice = gen.get("selected",0)audio_file_list = gen.get("audio_file_list", None)- audio_choice = gen.get("audio_selected",0)+ audio_choice = gen.get("audio_selected",-1)header_text = gen.get("header_text", "")in_progress = "in_progress" in genif gen.get("last_selected", True) and file_list is not None:choice = max(len(file_list) - 1,0)if gen.get("audio_last_selected", True) and audio_file_list is not None:- audio_choice = max(len(audio_file_list) - 1,0)+ audio_choice = max(len(audio_file_list) - 1,-1)last_was_audio = gen.get("last_was_audio", False)queue = gen.get("queue", [])abort_interactive = not gen.get("abort", False)+ early_stop_interactive = not gen.get("early_stop", False)++ if gen.pop("refresh_tab", False):+ if last_was_audio:+ output_tabs = [gr.Tabs(selected= "audio"), 1]+ else:+ output_tabs = [gr.Tabs(selected= "video_images"), 0]+ else:+ output_tabs = [gr.update(), gr.update()]+if not in_progress or len(queue) == 0:- return gr.Gallery(value = file_list) if last_was_audio else gr.Gallery(selected_index=choice, value = file_list), gr.update() if last_was_audio else choice, *pack_audio_gallery_state(audio_file_list, audio_choice), gr.HTML("", visible= False), gr.Button(visible=True), gr.Button(visible=False), gr.Row(visible=False), gr.Row(visible=False), update_queue_data(queue), gr.Button(interactive= abort_interactive), gr.Button(visible= False)+ return *output_tabs, gr.Gallery(value = file_list) if last_was_audio else gr.Gallery(selected_index=choice, value = file_list), gr.update() if last_was_audio else choice, *pack_audio_gallery_state(audio_file_list, audio_choice), gr.HTML("", visible= False), gr.Button(visible=True), gr.Button(visible=False), gr.Row(visible=False), gr.Row(visible=False), update_queue_data(queue), gr.Button(interactive= abort_interactive), gr.Button(interactive= early_stop_interactive), gr.Button(visible= False)else:+ output_tabs = [gr.update(), gr.update()]task = queue[0]prompt = task["prompt"]params = task["params"]@@ -3668,10 +3783,11 @@ def refresh_gallery(state): #, msghtml_content = f"<TABLE WIDTH=100% ID=PINFO style='{table_style}'><TR style='height:140px'><TD width=100% style='{table_style}'>" + prompt + "</TD>" + thumbnails + "</TR></TABLE>"html_output = gr.HTML(html_content, visible= True)if last_was_audio:- audio_choice = max(0, audio_choice)+ audio_choice = max(-1, audio_choice)else:choice = max(0, choice)- return gr.Gallery(value = file_list) if last_was_audio else gr.Gallery(selected_index=choice, value = file_list), gr.update() if last_was_audio else choice, *pack_audio_gallery_state(audio_file_list, audio_choice), html_output, gr.Button(visible=False), gr.Button(visible=True), gr.Row(visible=True), gr.Row(visible= gen_buttons_visible), update_queue_data(queue), gr.Button(interactive= abort_interactive), gr.Button(visible= onemorewindow_visible)++ return *output_tabs, gr.Gallery(value = file_list) if last_was_audio else gr.Gallery(selected_index=choice, value = file_list), gr.update() if last_was_audio else choice, *pack_audio_gallery_state(audio_file_list, audio_choice), html_output, gr.Button(visible=False), gr.Button(visible=True), gr.Row(visible=True), gr.Row(visible= gen_buttons_visible), update_queue_data(queue), gr.Button(interactive= abort_interactive), gr.Button(interactive= early_stop_interactive), gr.Button(visible= onemorewindow_visible)@@ -3685,7 +3801,7 @@ def finalize_generation(state):choice = len(file_list) - 1audio_file_list = gen.get("audio_file_list", [])- audio_choice = gen.get("audio_selected", 0)+ audio_choice = gen.get("audio_selected", -1)if gen.get("audio_last_selected", True):audio_choice = len(audio_file_list) - 1@@ -3695,7 +3811,9 @@ def finalize_generation(state):time.sleep(0.2)global gen_in_progressgen_in_progress = False- return gr.update() if last_was_audio else gr.Gallery(selected_index=choice), *pack_audio_gallery_state(audio_file_list, audio_choice), gallery_tabs, 1 if last_was_audio else 0, gr.Button(interactive= True), gr.Button(visible= True), gr.Button(visible= False), gr.Column(visible= False), gr.HTML(visible= False, value="")+ gen["early_stop"] = False+ gen["early_stop_forwarded"] = False+ return gallery_tabs, 1 if last_was_audio else 0, gr.update() if last_was_audio else gr.Gallery(selected_index=choice), *pack_audio_gallery_state(audio_file_list, audio_choice), gr.Button(interactive= True), gr.Button(interactive= True), gr.Button(visible= True), gr.Button(visible= False), gr.Column(visible= False), gr.HTML(visible= False, value="")def get_default_video_info():return "Please Select an Video / Image"@@ -3740,7 +3858,7 @@ def select_audio(state, audio_files_paths, audio_file_selected):if audio_file_selected >= 0:choice = audio_file_selectedelse:- choice = min(len(audio_file_list)-1, gen.get("audio_selected",0)) if len(audio_file_list) > 0 else -1+ choice = min(len(audio_file_list)-1, gen.get("audio_selected",-1)) if len(audio_file_list) > 0 else -1set_file_choice(gen, audio_file_list, choice, audio_files=True )@@ -3815,7 +3933,7 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audif audio_file_selected >= 0:choice = audio_file_selectedelse:- choice = gen.get("audio_selected",0)+ choice = gen.get("audio_selected",-1)choice = min(len(audio_file_list)-1, choice)set_file_choice(gen, audio_file_list, choice, audio_files=True )files, settings_list = audio_file_list, audio_file_settings_list@@ -5041,7 +5159,7 @@ def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, multi_acquire_GPU_ressources(state, "prompt_enhancer", "Prompt Enhancer")if enhancer_offloadobj is None:- profile = compute_profile(override_profile)+ profile = compute_profile(override_profile, "video")mmgp_profile = init_pipe(pipe, kwargs, profile)setup_prompt_enhancer(pipe, kwargs)enhancer_offloadobj = offload.profile(pipe, profile_no= mmgp_profile, **kwargs)@@ -5375,6 +5493,8 @@ def generate_video(global wan_model, offloadobj, reload_neededgen = get_gen_info(state)+ gen["early_stop"] = False+ gen["early_stop_forwarded"] = Falsetorch.set_grad_enabled(False)if mode.startswith("edit_"):edit_video(send_cmd, state, mode, video_source, seed, temporal_upsampling, spatial_upsampling, film_grain_intensity, film_grain_saturation, MMAudio_setting, MMAudio_prompt, MMAudio_neg_prompt, repeat_generation, audio_source)@@ -5428,11 +5548,18 @@ def generate_video(old_vae_upsampling = None if reload_needed or wan_model is None or not hasattr(wan_model, "vae") or not hasattr(wan_model.vae, "upsampling_set") else wan_model.vae.upsampling_setreload_needed = reload_needed or old_vae_upsampling != new_vae_upsamplingif new_vae_upsampling: model_kwargs = {"VAE_upsampling": new_vae_upsampling}- if model_type != transformer_type or reload_needed or override_profile>0 and override_profile != loaded_profile or override_profile<0 and default_profile != loaded_profile:+ output_type = get_output_type_for_model(model_type, image_mode)+ profile = compute_profile(override_profile, output_type)+ if model_type != transformer_type or reload_needed or profile != loaded_profile:wan_model = Nonerelease_model()send_cmd("status", f"Loading model {get_model_name(model_type)}...")- wan_model, offloadobj = load_models(model_type, override_profile, **model_kwargs)+ wan_model, offloadobj = load_models(+ model_type,+ override_profile,+ output_type=output_type,+ **model_kwargs,+ )send_cmd("status", "Model loaded")reload_needed= Falseif args.test:@@ -5725,6 +5852,7 @@ def generate_video(torch.set_grad_enabled(False)os.makedirs(save_path, exist_ok=True)os.makedirs(image_save_path, exist_ok=True)+ os.makedirs(audio_save_path, exist_ok=True)gc.collect()torch.cuda.empty_cache()wan_model._interrupt = False@@ -6372,31 +6500,34 @@ def generate_video(save_prompt = original_prompts[0]if audio_only:extension = "wav"+ output_dir = audio_save_pathelif is_image:extension = "jpg"+ output_dir = image_save_pathelse:container = server_config.get("video_container", "mp4")- extension = container+ extension = container+ output_dir = save_pathinputs = get_function_arguments(generate_video, locals())if len(output_filename):from shared.utils.filename_formatter import FilenameFormatterfile_name = FilenameFormatter.format_filename(output_filename, inputs)file_name = f"{sanitize_file_name(truncate_for_filesystem(os.path.splitext(os.path.basename(file_name))[0])).strip()}.{extension}"- file_name = os.path.basename(get_available_filename(save_path, file_name))+ file_name = os.path.basename(get_available_filename(output_dir, file_name))else:file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt)).strip()}.{extension}"- video_path = os.path.join(save_path, file_name)+ video_path = os.path.join(output_dir, file_name)if BGRA_frames is not None:from models.wan.alpha.utils import write_zip_filewrite_zip_file(os.path.splitext(video_path)[0] + ".zip", BGRA_frames)BGRA_frames = Noneif audio_only:- audio_path = os.path.join(image_save_path, file_name)+ audio_path = os.path.join(output_dir, file_name)write_wav_file(audio_path, sample.squeeze(0), output_audio_sampling_rate)- video_path= audio_path- elif is_image:- image_path = os.path.join(image_save_path, file_name)+ video_path = audio_path+ elif is_image:+ image_path = os.path.join(output_dir, file_name)sample = sample.transpose(1,0) #c f h w -> f c h wnew_image_path = []for no, img in enumerate(sample):@@ -6628,7 +6759,7 @@ def process_tasks(state):audio_file_list = gen.get("audio_file_list", [])audio_file_settings_list = gen.get("audio_file_settings_list", [])- audio_choice = gen.get("audio_selected",0)+ audio_choice = gen.get("audio_selected",-1)gen["audio_file_list"], gen["audio_file_settings_list"], gen["audio_selected"] = truncate_list(audio_file_list, audio_file_settings_list, audio_choice)while True:@@ -6735,6 +6866,7 @@ def process_tasks(state):gen["status"] = dataelif cmd == "output":gen["preview"] = None+ gen["refresh_tab"] = Trueyield time.time() , time.time()elif cmd == "progress":gen["progress_args"] = data@@ -6754,6 +6886,9 @@ def process_tasks(state):yield time.time() , time.time()gen["status"] = status+ gen["early_stop"] = False+ gen["early_stop_forwarded"] = False+with lock:queue[:] = [item for item in queue if item['id'] != task_id]update_global_queue_ref(queue)@@ -7733,7 +7868,7 @@ def eject_audio_from_gallery(state, input_file_list, choice):extend_list = file_settings_list[choice + 1:]file_settings_list[:] = file_settings_list[:choice]file_settings_list.extend(extend_list)- choice = min(choice, len(file_list))+ choice = min(choice, len(file_list)-1)return *pack_audio_gallery_state(file_list, choice), gr.update() if len(file_list) >0 else get_default_video_info(), gr.Row(visible= len(file_list) > 0)@@ -8319,7 +8454,10 @@ def preload_model_when_switching(state):release_model()model_filename = get_model_name(model_type)yield f"Loading model {model_filename}..."- wan_model, offloadobj = load_models(model_type)+ wan_model, offloadobj = load_models(+ model_type,+ output_type=get_output_type_for_model(model_type, 0),+ )yield f"Model loaded"reload_needed= Falsereturn@@ -9489,7 +9627,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonduration_def.get("min", 30),duration_def.get("max", 240),value=ui_get("duration_seconds", duration_default),- step=duration_def.get("increment", 0.1),+ step=duration_def.get("increment", 1),label=duration_def.get("label", "Duration"),show_reset_button=False,)@@ -10054,6 +10192,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonpause_btn = gr.Button("Pause", visible = True, size='md', min_width=1)resume_btn = gr.Button("Resume", visible = False, size='md', min_width=1)abort_btn = gr.Button("Abort", visible = True, size='md', min_width=1)+ earlystop_btn = gr.Button("Early Stop", visible = True, size='md', min_width=1)with gr.Accordion("Queue Management", open=False) as queue_accordion:with gr.Row():queue_html = gr.HTML(@@ -10166,7 +10305,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonif tab_id == 'generate':output_trigger.change(refresh_gallery,inputs = [state],- outputs = [output, last_choice, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, gen_info, generate_btn, add_to_queue_btn, current_gen_column, current_gen_buttons_row, queue_html, abort_btn, onemorewindow_btn],+ outputs = [gallery_tabs, current_gallery_tab, output, last_choice, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, gen_info, generate_btn, add_to_queue_btn, current_gen_column, current_gen_buttons_row, queue_html, abort_btn, earlystop_btn, onemorewindow_btn],show_progress="hidden")@@ -10185,6 +10324,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonpause_btn.click(pause_generation, [state], [ pause_btn, resume_btn] )resume_btn.click(resume_generation, [state] )abort_btn.click(abort_generation, [state], [ abort_btn] ) #.then(refresh_gallery, inputs = [state, gen_info], outputs = [output, gen_info, queue_html] )+ earlystop_btn.click(early_stop_generation, [state], [ earlystop_btn] )onemoresample_btn.click(fn=one_more_sample,inputs=[state], outputs= [state])onemorewindow_btn.click(fn=one_more_window,inputs=[state], outputs= [state])@@ -10401,7 +10541,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonshow_progress="hidden",).then(finalize_generation,inputs= [state],- outputs= [output, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, gallery_tabs, current_gallery_tab, abort_btn, generate_btn, add_to_queue_btn, current_gen_column, gen_info]+ outputs= [gallery_tabs, current_gallery_tab, output, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, abort_btn, earlystop_btn, generate_btn, add_to_queue_btn, current_gen_column, gen_info]).then(fn=lambda s: gr.Accordion(open=False) if len(get_gen_info(s).get("queue", [])) <= 1 else gr.update(),inputs=[state],@@ -10434,7 +10574,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non).then(fn=finalize_generation_with_state,inputs=[state],- outputs=[output, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, gallery_tabs, current_gallery_tab, abort_btn, generate_btn, add_to_queue_btn, current_gen_column, gen_info, queue_accordion, state],+ outputs=[gallery_tabs, current_gallery_tab, output, audio_files_paths, audio_file_selected, audio_gallery_refresh_trigger, abort_btn, earlystop_btn, generate_btn, add_to_queue_btn, current_gen_column, gen_info, queue_accordion, state],trigger_mode="always_last").then(unload_model_if_needed,@@ -11043,9 +11183,11 @@ if __name__ == "__main__":os.makedirs(args.output_dir, exist_ok=True)server_config["save_path"] = args.output_dirserver_config["image_save_path"] = args.output_dir+ server_config["audio_save_path"] = args.output_dir# Keep module-level paths in sync (used by save_video / get_available_filename).save_path = args.output_dirimage_save_path = args.output_dir+ audio_save_path = args.output_dirprint(f"Output directory: {args.output_dir}")# Headless CLI runs: disable notification sounds to avoid pygame/sounddevice issues.@@ -11139,4 +11281,10 @@ if __name__ == "__main__":else:url = "http://" + server_namewebbrowser.open(url + ":" + str(server_port), new = 0, autoraise = True)- demo.launch(favicon_path="favicon.png", server_name=server_name, server_port=server_port, share=args.share, allowed_paths=list({save_path, image_save_path, "icons"}))+ demo.launch(+ favicon_path="favicon.png",+ server_name=server_name,+ server_port=server_port,+ share=args.share,+ allowed_paths=list({save_path, image_save_path, audio_save_path, "icons"}),+ )