Python
qwen3 tts boosted & multi speakers
DeepBeepMeep765e7325e54f
diff --git a/README.md b/README.mdindex e1d9ced..d8006c3 100644--- a/README.md+++ b/README.md@@ -33,6 +33,25 @@ WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen,## 🔥 Latest Updates :+### February 16th 2026: WanGP v10.9, Breaking the Sound Barrier+With this new release of WanGP you should have best TTS (Text To Speech) experience you can find:++- **Qwen3 TTS Powered Up**:+ - with new *Cuda Graph* optimized mode, speech generation is up to *4x faster*, in some occasion generating 1s of speech may take less than 1s !+ - with int8 quantization, the Qwen3 TTS can work at full speed with only 6 GB of VRAM+ - New **Two Speakers Mode** with **Two Cloned Voices** can generate dialogues much with smoother transitions than with *Kugel Audio*++- **Heart Mula Powered Up**:+ - with new *Cuda Graph* optimized mode, song generation is up to 6x faster++- **Ace Step 1.5 Powered Up**:+ - WanGP version offers an exclusive support for *vllm* & *int8 quantization* for LM (that is fast LM & low VRAM at the same time)+ - you will only need 10GB of RAM and 6 GB oF VRAM, to run Ace Step with all its features++Also you now have a choice of multiple *Prompt Enhancements* for *Qwen3 TTS* & *Kugel Audio*: *Prompt Enhancer* can now generate for you either a *Monologue* or a *Dialogue between two Speakers*++Please note that to use the new *Cuda Graph*, mode you will need to select either *vllm* or *cuda graph* in *Configuration / Performance / Language Models Decoder Engine*. Profiles 1,3 or 3+ will need to be enabled for the corresponding Model. vllm is a powered up version of cuda graph that may not always work with all GPUs. But don't worry if it is not available for your GPU there will be an automatic fallback to cuda graph.+### February 12th 2026: WanGP v10.84, Easy Metal- **Ace Step 1.5 Turbo Super Charged**: all the best features of *Ace Step 1.5* are now in *WanGP* and are *Fast* & *Easy* to use:diff --git a/defaults/kugelaudio_0_open.json b/defaults/kugelaudio_0_open.jsonindex aa0e491..37b5d80 100644--- a/defaults/kugelaudio_0_open.json+++ b/defaults/kugelaudio_0_open.json@@ -2,7 +2,7 @@"model": {"name": "TTS KugelAudio 0 Open 7B","architecture": "kugelaudio_0_open",- "description": "KugelAudio open-source text-to-speech with optional voice cloning. You can create a dialogue between two people by providing two audio sources and by starting lines alternatively with 'Speaker 0: ' or 'Speaker 1: '. You may observe Accelerated Speech with long speeches, use Manual Split (one empty line) or Auto Split to avoid this effect.",+ "description": "KugelAudio open-source text-to-speech with optional voice cloning. You can create a dialogue between two People by providing two audio sources and by starting lines alternatively with 'Speaker 0: ' or 'Speaker 1: '. You may observe Accelerated Speech with long speeches, use Manual Split (one empty line) or Auto Split to avoid this effect.","URLs": ["https://huggingface.co/DeepBeepMeep/TTS/resolve/main/kugelaudio_0_open_bf16.safetensors","https://huggingface.co/DeepBeepMeep/TTS/resolve/main/kugelaudio_0_open_quanto_bf16_int8.safetensors"diff --git a/defaults/qwen3_tts_base.json b/defaults/qwen3_tts_base.jsonindex 4c547c2..ddd6c37 100644--- a/defaults/qwen3_tts_base.json+++ b/defaults/qwen3_tts_base.json@@ -2,12 +2,13 @@"model": {"name": "TTS Qwen3 Base (12Hz) 1.7B","architecture": "qwen3_tts_base",- "description": "Qwen3 Base voice clone model with reference audio.",+ "description": "Qwen3 Base voice clone model with reference audio. Use Manual Split (one empty line) or Auto Split to reduce VRAM requirements for very long speeches.","URLs": [- "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_base_bf16.safetensors"+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_base_bf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_base_quanto_bf16_int8.safetensors"]},"prompt": "I checked the schedule twice, and everything lines up.","alt_prompt": "","duration_seconds": 30-}+}\ No newline at end of filediff --git a/defaults/qwen3_tts_customvoice.json b/defaults/qwen3_tts_customvoice.jsonindex e9d73dc..5c031ce 100644--- a/defaults/qwen3_tts_customvoice.json+++ b/defaults/qwen3_tts_customvoice.json@@ -2,13 +2,14 @@"model": {"name": "TTS Qwen3 Custom Voice (12Hz) 1.7B","architecture": "qwen3_tts_customvoice",- "description": "Qwen3 Custom Voice with fixed speaker presets and optional instruction control.",+ "description": "Qwen3 Custom Voice with fixed speaker presets and optional instruction control. Use Manual Split (one empty line) or Auto Split to reduce VRAM requirements for very long speeches.","URLs": [- "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_customvoice_bf16.safetensors"+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_customvoice_bf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_customvoice_quanto_bf16_int8.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-}+}\ No newline at end of filediff --git a/defaults/qwen3_tts_voicedesign.json b/defaults/qwen3_tts_voicedesign.jsonindex 851485f..8638047 100644--- a/defaults/qwen3_tts_voicedesign.json+++ b/defaults/qwen3_tts_voicedesign.json@@ -4,11 +4,12 @@"architecture": "qwen3_tts_voicedesign","description": "Qwen3 Voice Design with natural language voice instructions.","URLs": [- "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_voicedesign_bf16.safetensors"+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_voicedesign_bf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_voicedesign_quanto_bf16_int8.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-}+}\ No newline at end of filediff --git a/models/TTS/kugelaudio_handler.py b/models/TTS/kugelaudio_handler.pyindex ccd6eb5..590099f 100644--- a/models/TTS/kugelaudio_handler.py+++ b/models/TTS/kugelaudio_handler.py@@ -5,7 +5,7 @@ import torchfrom shared.utils import files_locator as fl-from .prompt_enhancers import TTS_MONOLOGUE_OR_DIALOGUE_PROMPT+from .prompt_enhancers import TTS_MONOLOGUE_PROMPT, TTS_QWEN3_DIALOGUE_PROMPTKUGELAUDIO_REPO_ID = "DeepBeepMeep/TTS"@@ -91,8 +91,19 @@ def _get_kugelaudio_model_def():"letters_filter": "AB","default": "",},- "text_prompt_enhancer_instructions": TTS_MONOLOGUE_OR_DIALOGUE_PROMPT,- "prompt_enhancer_button_label": "Write Speech",+ "text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,+ "text_prompt_enhancer_instructions1": TTS_QWEN3_DIALOGUE_PROMPT,+ "text_prompt_enhancer_max_tokens": 512,+ "text_prompt_enhancer_max_tokens1": 512,+ "prompt_enhancer_def": {+ "selection": ["T", "T1"],+ "labels": {+ "T": "A Speech based on current Prompt",+ "T1": "A Dialogue between two People based on current Prompt",+ },+ "default": "T",+ },+ "prompt_enhancer_button_label": "Write","compile": ["transformer"],}diff --git a/models/TTS/prompt_enhancers.py b/models/TTS/prompt_enhancers.pyindex 586de57..16b22be 100644--- a/models/TTS/prompt_enhancers.py+++ b/models/TTS/prompt_enhancers.py@@ -18,6 +18,22 @@ TTS_MONOLOGUE_PROMPT = ("myself think, and that has become its own kind of music.")+TTS_QWEN3_DIALOGUE_PROMPT = (+ "You are a dialogue-writing assistant for a text-to-speech model. "+ "Generate a two-speaker dialogue based on the user prompt.\n\n"+ "Output rules:\n"+ "- Output only dialogue lines, no explanations, lists, or stage directions.\n"+ "- Every line must start with either \"Speaker 0:\" or \"Speaker 1:\".\n"+ "- Use natural spoken language with clear punctuation.\n"+ "- Keep alternating speakers unless the prompt asks otherwise.\n"+ "- Write a compact dialogue (6-14 lines) unless the user asks for a different length.\n\n"+ "Example:\n"+ "Speaker 0: We should leave before the rain gets heavier.\n"+ "Speaker 1: Give me one minute, I still need my jacket.\n"+ "Speaker 0: One minute, then we run for the bus.\n"+ "Speaker 1: Deal, and if we miss it, coffee is on me."+)+TTS_MONOLOGUE_OR_DIALOGUE_PROMPT = ("You are a speechwriting assistant. Generate either a single-speaker monologue ""or a multi-speaker dialogue for a text-to-speech model based on the user prompt. "diff --git a/models/TTS/qwen3/core/models/cudagraph_hooks.py b/models/TTS/qwen3/core/models/cudagraph_hooks.pynew file mode 100644index 0000000..32facfd--- /dev/null+++ b/models/TTS/qwen3/core/models/cudagraph_hooks.py@@ -0,0 +1,320 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Callable++import torch+from transformers.cache_utils import StaticCache++from shared.llm_engines.cudagraph_kit import AutoRegressiveCudaGraphKit++if TYPE_CHECKING:+ from .configuration_qwen3_tts import Qwen3TTSTalkerCodePredictorConfig, Qwen3TTSTalkerConfig+ from .modeling_qwen3_tts import Qwen3TTSTalkerForConditionalGeneration+++class Qwen3TTSCudaGraphHooks:+ def __init__(self, talker: "Qwen3TTSTalkerForConditionalGeneration") -> None:+ self.talker = talker+ self._enabled = False+ self._kit: AutoRegressiveCudaGraphKit | None = None+ self._talker_cache: StaticCache | None = None+ self._subtalker_cache: StaticCache | None = None+ self._max_batch_size = 0+ self._max_talker_tokens = 0+ self._max_subtalker_tokens = 0+ self._last_prepare_reused = False++ self._talker_decode_cache_position: torch.Tensor | None = None+ self._subtalker_decode_cache_position: torch.Tensor | None = None+ self._talker_decode_attention_mask: torch.Tensor | None = None+ self._subtalker_decode_attention_mask: torch.Tensor | None = None+ self._talker_decode_position_ids: torch.Tensor | None = None+ self._subtalker_decode_position_ids: torch.Tensor | None = None++ def set_lm_decoder_engine(self, lm_decoder_engine: str | None) -> None:+ engine = str(lm_decoder_engine or "legacy").strip().lower()+ self._enabled = engine in ("cg", "cudagraph")+ if not self._enabled:+ self.release()++ def is_enabled(self) -> bool:+ return bool(self._enabled)++ def is_active(self) -> bool:+ return (+ self._kit is not None+ and self._talker_cache is not None+ and self._subtalker_cache is not None+ and self._max_talker_tokens > 0+ and self._max_subtalker_tokens > 0+ )++ def last_prepare_reused(self) -> bool:+ return bool(self._last_prepare_reused)++ def prepare(+ self,+ *,+ max_batch_size: int,+ max_talker_tokens: int,+ max_subtalker_tokens: int,+ talker_config: "Qwen3TTSTalkerConfig",+ subtalker_config: "Qwen3TTSTalkerCodePredictorConfig",+ ) -> None:+ self._last_prepare_reused = False+ if not self._enabled:+ return+ if max_batch_size <= 0 or max_talker_tokens <= 0 or max_subtalker_tokens <= 0:+ raise ValueError("Qwen3 CUDA graph capacities must be > 0.")++ first_param = next(self.talker.parameters(), None)+ if first_param is None or first_param.device.type != "cuda":+ return++ if (+ self._talker_cache is not None+ and self._subtalker_cache is not None+ and self._kit is not None+ and self._max_batch_size >= int(max_batch_size)+ and self._max_talker_tokens >= int(max_talker_tokens)+ and self._max_subtalker_tokens >= int(max_subtalker_tokens)+ ):+ self._last_prepare_reused = True+ self.reset_talker_cache()+ self.reset_subtalker_cache()+ self._ensure_runtime_tensors(first_param.device)+ return++ self.release()+ self._kit = AutoRegressiveCudaGraphKit("qwen3_tts")+ self._max_batch_size = int(max_batch_size)+ self._max_talker_tokens = int(max_talker_tokens)+ self._max_subtalker_tokens = int(max_subtalker_tokens)+ self._talker_cache = StaticCache(+ config=talker_config,+ max_batch_size=self._max_batch_size,+ max_cache_len=self._max_talker_tokens,+ device=first_param.device,+ dtype=first_param.dtype,+ )+ self._subtalker_cache = StaticCache(+ config=subtalker_config,+ max_batch_size=self._max_batch_size,+ max_cache_len=self._max_subtalker_tokens,+ device=first_param.device,+ dtype=first_param.dtype,+ )+ self._ensure_runtime_tensors(first_param.device)++ def release(self) -> None:+ if self._kit is not None:+ self._kit.release()+ self._kit = None+ self._talker_cache = None+ self._subtalker_cache = None+ self._max_batch_size = 0+ self._max_talker_tokens = 0+ self._max_subtalker_tokens = 0+ self._last_prepare_reused = False+ self._talker_decode_cache_position = None+ self._subtalker_decode_cache_position = None+ self._talker_decode_attention_mask = None+ self._subtalker_decode_attention_mask = None+ self._talker_decode_position_ids = None+ self._subtalker_decode_position_ids = None++ def _ensure_runtime_tensors(self, device: torch.device) -> None:+ if self._max_batch_size <= 0:+ return+ if self._talker_decode_cache_position is None or self._talker_decode_cache_position.device != device:+ self._talker_decode_cache_position = torch.zeros(1, dtype=torch.long, device=device)+ if self._subtalker_decode_cache_position is None or self._subtalker_decode_cache_position.device != device:+ self._subtalker_decode_cache_position = torch.zeros(1, dtype=torch.long, device=device)+ if (+ self._talker_decode_attention_mask is None+ or self._talker_decode_attention_mask.device != device+ or self._talker_decode_attention_mask.shape != (self._max_batch_size, self._max_talker_tokens)+ ):+ self._talker_decode_attention_mask = torch.zeros(+ (self._max_batch_size, self._max_talker_tokens), dtype=torch.long, device=device+ )+ if (+ self._subtalker_decode_attention_mask is None+ or self._subtalker_decode_attention_mask.device != device+ or self._subtalker_decode_attention_mask.shape != (self._max_batch_size, self._max_subtalker_tokens)+ ):+ self._subtalker_decode_attention_mask = torch.zeros(+ (self._max_batch_size, self._max_subtalker_tokens), dtype=torch.long, device=device+ )+ if (+ self._talker_decode_position_ids is None+ or self._talker_decode_position_ids.device != device+ or self._talker_decode_position_ids.shape != (3, self._max_batch_size, 1)+ ):+ self._talker_decode_position_ids = torch.zeros((3, self._max_batch_size, 1), dtype=torch.long, device=device)+ if (+ self._subtalker_decode_position_ids is None+ or self._subtalker_decode_position_ids.device != device+ or self._subtalker_decode_position_ids.shape != (self._max_batch_size, 1)+ ):+ self._subtalker_decode_position_ids = torch.zeros((self._max_batch_size, 1), dtype=torch.long, device=device)++ def _check_batch_size(self, batch_size: int) -> None:+ if int(batch_size) > self._max_batch_size:+ raise RuntimeError(+ f"Qwen3 CUDA graph batch size {int(batch_size)} exceeds prepared capacity {self._max_batch_size}."+ )++ def reset_talker_cache(self) -> None:+ if self._talker_cache is not None:+ self._talker_cache.reset()++ def reset_subtalker_cache(self) -> None:+ if self._subtalker_cache is not None:+ self._subtalker_cache.reset()++ def get_talker_cache(self) -> StaticCache | None:+ return self._talker_cache++ def get_subtalker_cache(self) -> StaticCache | None:+ return self._subtalker_cache++ def is_talker_cache(self, cache_obj) -> bool:+ return cache_obj is self._talker_cache and cache_obj is not None++ def is_subtalker_cache(self, cache_obj) -> bool:+ return cache_obj is self._subtalker_cache and cache_obj is not None++ def _copy_attention_mask(+ self,+ source_mask: torch.Tensor | None,+ dest_mask: torch.Tensor,+ *,+ cache_position: int,+ max_tokens: int,+ batch_size: int,+ ) -> torch.Tensor:+ if source_mask is None:+ current_len = min(max_tokens, cache_position + 1)+ dest_mask.zero_()+ dest_mask[:batch_size, :current_len] = 1+ return dest_mask[:batch_size]+ if source_mask.dim() != 2:+ raise RuntimeError(f"Expected 2D attention mask for CUDA graph decode, got shape={tuple(source_mask.shape)}.")+ if int(source_mask.shape[0]) != batch_size:+ raise RuntimeError(+ f"Attention mask batch {int(source_mask.shape[0])} does not match decode batch {batch_size}."+ )+ current_len = int(source_mask.shape[1])+ if current_len > max_tokens:+ raise RuntimeError(+ f"Attention mask length {current_len} exceeds CUDA graph cache capacity {max_tokens}."+ )+ dest_mask.zero_()+ mask = source_mask.to(device=dest_mask.device, dtype=dest_mask.dtype)+ dest_mask[:batch_size, :current_len].copy_(mask)+ return dest_mask[:batch_size]++ def run_talker_decode(+ self,+ decode_fn: Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], object],+ *,+ inputs_embeds: torch.Tensor,+ attention_mask: torch.Tensor | None,+ position_ids: torch.Tensor,+ cache_position: torch.Tensor,+ ):+ if not self.is_active():+ raise RuntimeError("Qwen3 talker CUDA graph decode called while CUDA graph is inactive.")+ if int(inputs_embeds.shape[1]) != 1:+ raise RuntimeError(f"Qwen3 talker CUDA graph decode expects seq_len=1, got {int(inputs_embeds.shape[1])}.")+ if int(position_ids.shape[-1]) != 1:+ raise RuntimeError(+ f"Qwen3 talker CUDA graph decode expects position_ids with last dim=1, got {tuple(position_ids.shape)}."+ )+ absolute_pos = int(cache_position.reshape(-1)[0].item())+ if absolute_pos < 0 or absolute_pos >= self._max_talker_tokens:+ raise RuntimeError(+ f"Qwen3 talker decode position {absolute_pos} exceeds CUDA graph cache capacity {self._max_talker_tokens}."+ )+ batch_size = int(inputs_embeds.shape[0])+ self._check_batch_size(batch_size)+ self._ensure_runtime_tensors(inputs_embeds.device)+ assert self._talker_decode_cache_position is not None+ assert self._talker_decode_attention_mask is not None+ assert self._talker_decode_position_ids is not None+ static_cache_position = self._talker_decode_cache_position.fill_(absolute_pos)+ static_attention_mask = self._copy_attention_mask(+ attention_mask,+ self._talker_decode_attention_mask,+ cache_position=absolute_pos,+ max_tokens=self._max_talker_tokens,+ batch_size=batch_size,+ )+ static_position_ids = self._talker_decode_position_ids[:3, :batch_size]+ static_position_ids.copy_(position_ids.to(device=static_position_ids.device, dtype=static_position_ids.dtype))+ try:+ return self._kit.run("talker_decode", decode_fn, inputs_embeds, static_attention_mask, static_position_ids, static_cache_position)+ except Exception as exc:+ self.release()+ raise RuntimeError(f"Qwen3 talker CUDA graph decode failed: {exc}") from exc++ def run_subtalker_decode(+ self,+ decode_fn: Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], object],+ *,+ inputs_embeds: torch.Tensor,+ attention_mask: torch.Tensor | None,+ position_ids: torch.Tensor | None,+ cache_position: torch.Tensor,+ generation_step: int,+ ):+ if not self.is_active():+ raise RuntimeError("Qwen3 subtalker CUDA graph decode called while CUDA graph is inactive.")+ if int(inputs_embeds.shape[1]) != 1:+ raise RuntimeError(+ f"Qwen3 subtalker CUDA graph decode expects seq_len=1, got {int(inputs_embeds.shape[1])}."+ )+ absolute_pos = int(cache_position.reshape(-1)[0].item())+ if absolute_pos < 0 or absolute_pos >= self._max_subtalker_tokens:+ raise RuntimeError(+ f"Qwen3 subtalker decode position {absolute_pos} exceeds CUDA graph cache capacity {self._max_subtalker_tokens}."+ )+ batch_size = int(inputs_embeds.shape[0])+ self._check_batch_size(batch_size)+ self._ensure_runtime_tensors(inputs_embeds.device)+ assert self._subtalker_decode_cache_position is not None+ assert self._subtalker_decode_attention_mask is not None+ assert self._subtalker_decode_position_ids is not None+ static_cache_position = self._subtalker_decode_cache_position.fill_(absolute_pos)+ static_attention_mask = self._copy_attention_mask(+ attention_mask,+ self._subtalker_decode_attention_mask,+ cache_position=absolute_pos,+ max_tokens=self._max_subtalker_tokens,+ batch_size=batch_size,+ )+ static_position_ids = self._subtalker_decode_position_ids[:batch_size]+ if position_ids is None:+ static_position_ids.fill_(absolute_pos)+ else:+ if position_ids.dim() == 1:+ position_ids = position_ids.unsqueeze(-1)+ if position_ids.dim() != 2 or int(position_ids.shape[-1]) != 1:+ raise RuntimeError(+ f"Qwen3 subtalker CUDA graph decode expects position_ids shape [batch, 1], got {tuple(position_ids.shape)}."+ )+ static_position_ids.copy_(position_ids.to(device=static_position_ids.device, dtype=static_position_ids.dtype))+ runner_name = "subtalker_decode"+ try:+ return self._kit.run(+ runner_name,+ decode_fn,+ inputs_embeds,+ static_attention_mask,+ static_position_ids,+ static_cache_position,+ )+ except Exception as exc:+ self.release()+ raise RuntimeError(f"Qwen3 subtalker CUDA graph decode failed: {exc}") from excdiff --git a/models/TTS/qwen3/core/models/modeling_qwen3_tts.py b/models/TTS/qwen3/core/models/modeling_qwen3_tts.pyindex 49eb473..f4f9197 100644--- a/models/TTS/qwen3/core/models/modeling_qwen3_tts.py+++ b/models/TTS/qwen3/core/models/modeling_qwen3_tts.py@@ -26,7 +26,7 @@ from librosa.filters import mel as librosa_mel_fnfrom torch import nnfrom torch.nn import functional as Ffrom transformers.activations import ACT2FN-from transformers.cache_utils import Cache, DynamicCache+from transformers.cache_utils import Cache, DynamicCache, StaticCachefrom transformers.generation import GenerationMixinfrom transformers.integrations import use_kernel_forward_from_hubfrom transformers.masking_utils import (create_causal_mask,@@ -48,6 +48,7 @@ from .configuration_qwen3_tts import (Qwen3TTSConfig,Qwen3TTSSpeakerEncoderConfig,Qwen3TTSTalkerCodePredictorConfig,Qwen3TTSTalkerConfig)+from .cudagraph_hooks import Qwen3TTSCudaGraphHookslogger = logging.get_logger(__name__)@@ -58,6 +59,52 @@ def _check_abort(module) -> None:raise RuntimeError("Abort requested")+def _apply_repetition_penalty_inplace(logits: torch.Tensor, generated_ids: torch.Tensor, repetition_penalty: float) -> None:+ penalty = float(repetition_penalty)+ if penalty == 1.0 or generated_ids.numel() == 0:+ return+ for batch_idx in range(logits.shape[0]):+ token_ids = torch.unique(generated_ids[batch_idx]).to(dtype=torch.long)+ token_logits = logits[batch_idx, token_ids]+ logits[batch_idx, token_ids] = torch.where(token_logits < 0, token_logits * penalty, token_logits / penalty)+++def _sample_from_logits(+ logits: torch.Tensor,+ *,+ do_sample: bool,+ top_k: int,+ top_p: float,+ temperature: float,+) -> torch.Tensor:+ if not do_sample:+ return torch.argmax(logits, dim=-1)++ scores = logits / max(float(temperature), 1e-5)++ top_k = int(top_k or 0)+ if top_k > 0 and top_k < scores.shape[-1]:+ topk_values, _ = torch.topk(scores, top_k, dim=-1)+ min_values = topk_values[:, -1].unsqueeze(-1)+ scores = scores.masked_fill(scores < min_values, float("-inf"))++ top_p = float(top_p)+ if 0.0 < top_p < 1.0:+ sorted_scores, sorted_indices = torch.sort(scores, descending=True, dim=-1)+ sorted_probs = torch.softmax(sorted_scores, dim=-1)+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)+ remove_mask = cumulative_probs > top_p+ remove_mask[:, 1:] = remove_mask[:, :-1].clone()+ remove_mask[:, 0] = False+ sorted_scores = sorted_scores.masked_fill(remove_mask, float("-inf"))+ filtered_scores = torch.full_like(scores, float("-inf"))+ filtered_scores.scatter_(1, sorted_indices, sorted_scores)+ scores = filtered_scores++ probs = torch.softmax(scores, dim=-1)+ return torch.multinomial(probs, num_samples=1).squeeze(-1)++def download_weights_from_hf_specific(model_name_or_path: str,cache_dir: str | None,@@ -1184,6 +1231,10 @@ class Qwen3TTSTalkerCodePredictorModelForConditionalGeneration(Qwen3TTSPreTraine# Initialize weights and apply final processingself.post_init()+ self._cuda_graph_hooks = None++ def set_cuda_graph_hooks(self, hooks: Qwen3TTSCudaGraphHooks | None) -> None:+ self._cuda_graph_hooks = hooksdef get_input_embeddings(self):return self.model.get_input_embeddings()@@ -1297,20 +1348,60 @@ class Qwen3TTSTalkerCodePredictorModelForConditionalGeneration(Qwen3TTSPreTraineinput_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,+ cg_attention_mask = None if isinstance(attention_mask, dict) else attention_mask+ cuda_graph_hooks = self._cuda_graph_hooks+ use_cg_decode = (+ cuda_graph_hooks is not None+ and cuda_graph_hooks.is_active()+ and inputs_embeds is not None+ and inputs_embeds.shape[1] == 1+ and cuda_graph_hooks.is_subtalker_cache(past_key_values)+ and cache_position is not None)+ if use_cg_decode:+ generation_step = int(generation_steps if generation_steps is not None else 0)++ def _subtalker_decode_step(+ decode_inputs_embeds: torch.Tensor,+ decode_attention_mask: torch.Tensor,+ decode_position_ids: torch.Tensor,+ decode_cache_position: torch.Tensor,+ ) -> BaseModelOutputWithPast:+ return self.model(+ input_ids=None,+ attention_mask=decode_attention_mask,+ position_ids=decode_position_ids,+ past_key_values=past_key_values,+ inputs_embeds=decode_inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ cache_position=decode_cache_position,+ **kwargs,+ )++ outputs: BaseModelOutputWithPast = cuda_graph_hooks.run_subtalker_decode(+ _subtalker_decode_step,+ inputs_embeds=inputs_embeds,+ attention_mask=cg_attention_mask,+ position_ids=position_ids,+ cache_position=cache_position,+ generation_step=generation_step,+ )+ else:+ # 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_statelogits = self.lm_head[generation_steps](hidden_states)@@ -1328,6 +1419,82 @@ class Qwen3TTSTalkerCodePredictorModelForConditionalGeneration(Qwen3TTSPreTrainegeneration_steps=generation_steps + 1,)+ @torch.no_grad()+ def generate_stepwise(+ self,+ *,+ inputs_embeds: torch.Tensor,+ max_new_tokens: int,+ do_sample: bool,+ top_k: int,+ top_p: float,+ temperature: float,+ past_key_values=None,+ use_cache: bool = True,+ ) -> torch.Tensor:+ _check_abort(self)+ device = inputs_embeds.device+ batch_size = int(inputs_embeds.shape[0])+ max_new_tokens = int(max_new_tokens)+ if max_new_tokens <= 0:+ return torch.empty((batch_size, 0), dtype=torch.long, device=device)++ prefill_len = int(inputs_embeds.shape[1])+ cache_position = torch.arange(prefill_len, device=device, dtype=torch.long)+ outputs = self.forward(+ input_ids=None,+ attention_mask=None,+ position_ids=None,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=False,+ output_hidden_states=False,+ cache_position=cache_position,+ generation_steps=None,+ )++ logits = outputs.logits[:, -1, :]+ next_token = _sample_from_logits(+ logits,+ do_sample=bool(do_sample),+ top_k=int(top_k),+ top_p=float(top_p),+ temperature=float(temperature),+ )+ sequences = torch.empty((batch_size, max_new_tokens), dtype=torch.long, device=device)+ sequences[:, 0] = next_token+ generation_steps = 1+ decode_position = torch.empty(1, dtype=torch.long, device=device)++ for step_idx in range(1, max_new_tokens):+ _check_abort(self)+ decode_position.fill_(prefill_len + step_idx - 1)+ outputs = self.forward(+ input_ids=next_token.unsqueeze(-1),+ attention_mask=None,+ position_ids=None,+ past_key_values=past_key_values,+ inputs_embeds=None,+ use_cache=use_cache,+ output_attentions=False,+ output_hidden_states=False,+ cache_position=decode_position,+ generation_steps=generation_steps,+ )+ logits = outputs.logits[:, -1, :]+ next_token = _sample_from_logits(+ logits,+ do_sample=bool(do_sample),+ top_k=int(top_k),+ top_p=float(top_p),+ temperature=float(temperature),+ )+ sequences[:, step_idx] = next_token+ generation_steps += 1++ return sequences+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@@ -1599,7 +1766,10 @@ class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel,config=config.code_predictor_config,talker_config=config)+ self._cuda_graph_hooks = Qwen3TTSCudaGraphHooks(self)+ self.code_predictor.set_cuda_graph_hooks(self._cuda_graph_hooks)self.rope_deltas = None+ self._prefill_attention_mask = None# Initialize weights and apply final processingself.post_init()@@ -1632,6 +1802,170 @@ class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel,def get_decoder(self):return self.model++ def set_lm_decoder_engine(self, lm_decoder_engine: str | None) -> None:+ self._cuda_graph_hooks.set_lm_decoder_engine(lm_decoder_engine)++ def prepare_decode_cuda_graph(self, *, max_batch_size: int, max_talker_tokens: int, max_subtalker_tokens: int) -> None:+ self._cuda_graph_hooks.prepare(+ max_batch_size=max_batch_size,+ max_talker_tokens=max_talker_tokens,+ max_subtalker_tokens=max_subtalker_tokens,+ talker_config=self.config,+ subtalker_config=self.config.code_predictor_config,+ )++ def release_decode_cuda_graph(self) -> None:+ self._cuda_graph_hooks.release()++ def is_decode_cuda_graph_active(self) -> bool:+ return self._cuda_graph_hooks.is_active()++ def is_decode_cuda_graph_enabled(self) -> bool:+ return self._cuda_graph_hooks.is_enabled()++ def decode_cuda_graph_last_prepare_reused(self) -> bool:+ return self._cuda_graph_hooks.last_prepare_reused()++ def get_decode_talker_cache(self):+ return self._cuda_graph_hooks.get_talker_cache()++ @torch.no_grad()+ def generate_stepwise(+ self,+ *,+ inputs_embeds: torch.Tensor,+ attention_mask: torch.Tensor,+ trailing_text_hidden: torch.Tensor,+ tts_pad_embed: torch.Tensor,+ max_new_tokens: int,+ do_sample: bool,+ top_k: int,+ top_p: float,+ temperature: float,+ subtalker_dosample: bool,+ subtalker_top_k: int,+ subtalker_top_p: float,+ subtalker_temperature: float,+ eos_token_id: int,+ repetition_penalty: float,+ past_key_values=None,+ use_cache: bool = True,+ stopping_criteria=None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ _check_abort(self)+ device = inputs_embeds.device+ batch_size = int(inputs_embeds.shape[0])+ max_new_tokens = int(max_new_tokens)+ if max_new_tokens <= 0:+ empty_codes = torch.empty((batch_size, 0, self.config.num_code_groups), dtype=torch.long, device=device)+ empty_hidden = torch.empty((batch_size, 0, self.config.hidden_size), dtype=inputs_embeds.dtype, device=device)+ return empty_codes, empty_hidden++ prompt_len = int(inputs_embeds.shape[1])+ cache_position = torch.arange(prompt_len, device=device, dtype=torch.long)+ outputs = self.forward(+ input_ids=None,+ attention_mask=attention_mask,+ position_ids=None,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ labels=None,+ use_cache=use_cache,+ output_attentions=False,+ output_hidden_states=False,+ cache_position=cache_position,+ past_hidden=None,+ generation_step=None,+ trailing_text_hidden=trailing_text_hidden,+ tts_pad_embed=tts_pad_embed,+ subtalker_dosample=subtalker_dosample,+ subtalker_top_k=subtalker_top_k,+ subtalker_top_p=subtalker_top_p,+ subtalker_temperature=subtalker_temperature,+ )++ running_attention_mask = torch.zeros(+ (batch_size, prompt_len + max_new_tokens),+ dtype=attention_mask.dtype,+ device=device,+ )+ running_attention_mask[:, :prompt_len].copy_(attention_mask)+ logits = outputs.logits[:, -1, :]+ past_hidden = outputs.past_hidden+ generation_step = outputs.generation_step+ finished = torch.zeros((batch_size,), dtype=torch.bool, device=device)+ generated_code0 = torch.empty((batch_size, max_new_tokens), dtype=torch.long, device=device)+ codec_steps = []+ hidden_steps = []+ decode_position = torch.empty(1, dtype=torch.long, device=device)++ for step_idx in range(max_new_tokens):+ _check_abort(self)+ step_logits = logits.clone()+ if float(repetition_penalty) != 1.0 and step_idx > 0:+ history = generated_code0[:, :step_idx]+ _apply_repetition_penalty_inplace(step_logits, history, float(repetition_penalty))+ next_token = _sample_from_logits(+ step_logits,+ do_sample=bool(do_sample),+ top_k=int(top_k),+ top_p=float(top_p),+ temperature=float(temperature),+ )+ if eos_token_id is not None:+ eos_fill = torch.full_like(next_token, int(eos_token_id))+ next_token = torch.where(finished, eos_fill, next_token)+ generated_code0[:, step_idx] = next_token+ finished = finished | (next_token == int(eos_token_id))++ current_len = prompt_len + step_idx + 1+ running_attention_mask[:, current_len - 1].fill_(1)+ decode_position.fill_(prompt_len + step_idx)+ outputs = self.forward(+ input_ids=next_token.unsqueeze(-1),+ attention_mask=running_attention_mask[:, :current_len],+ position_ids=None,+ past_key_values=past_key_values,+ inputs_embeds=None,+ labels=None,+ use_cache=use_cache,+ output_attentions=False,+ output_hidden_states=False,+ cache_position=decode_position,+ past_hidden=past_hidden,+ generation_step=generation_step,+ trailing_text_hidden=trailing_text_hidden,+ tts_pad_embed=tts_pad_embed,+ subtalker_dosample=subtalker_dosample,+ subtalker_top_k=subtalker_top_k,+ subtalker_top_p=subtalker_top_p,+ subtalker_temperature=subtalker_temperature,+ )++ codec_ids = outputs.hidden_states[-1] if outputs.hidden_states is not None else None+ if codec_ids is not None:+ codec_steps.append(codec_ids)+ hidden_steps.append(outputs.past_hidden)++ logits = outputs.logits[:, -1, :]+ past_hidden = outputs.past_hidden+ generation_step = outputs.generation_step++ if stopping_criteria is not None:+ generated_ids = generated_code0[:, : step_idx + 1]+ if stopping_criteria(generated_ids, step_logits):+ break+ if bool(torch.all(finished)):+ break++ if codec_steps:+ talker_codes = torch.stack(codec_steps, dim=1)+ talker_hidden_states = torch.cat(hidden_steps, dim=1)+ else:+ talker_codes = torch.empty((batch_size, 0, self.config.num_code_groups), dtype=torch.long, device=device)+ talker_hidden_states = torch.empty((batch_size, 0, self.config.hidden_size), dtype=inputs_embeds.dtype, device=device)+ return talker_codes, talker_hidden_statesdef forward_sub_talker_finetune(self, codec_ids, talker_hidden_states):assert len(codec_ids.shape) == 2@@ -1693,20 +2027,36 @@ class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel,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)+ use_stepwise_subtalker = self._cuda_graph_hooks.is_active()+ if use_stepwise_subtalker:+ self._cuda_graph_hooks.reset_subtalker_cache()+ sub_cache = self._cuda_graph_hooks.get_subtalker_cache()+ predictor_sequences = self.code_predictor.generate_stepwise(+ 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,+ past_key_values=sub_cache,+ use_cache=sub_cache is not None,+ )+ else:+ 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,+ )+ predictor_sequences = predictor_result.sequences+ codec_ids = torch.cat((input_ids, predictor_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)],+ + [self.code_predictor.get_input_embeddings()[i](predictor_sequences[..., i:i+1]) for i in range(self.config.num_code_groups - 1)],dim=1,)inputs_embeds = codec_hiddens.sum(1, keepdim=True)@@ -1716,15 +2066,41 @@ class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel,else:inputs_embeds = inputs_embeds + tts_pad_embedif attention_mask is not None:+ decode_attention_mask_2d = attention_mask if attention_mask.dim() == 2 else None+ if decode_attention_mask_2d is None and self._prefill_attention_mask is not None:+ current_len = (+ int(cache_position.reshape(-1)[0].item()) + 1+ if cache_position is not None+ else int(self._prefill_attention_mask.shape[1])+ )+ prefill_mask = self._prefill_attention_mask.to(device=inputs_embeds.device)+ if current_len > int(prefill_mask.shape[1]):+ pad = torch.ones(+ (prefill_mask.shape[0], current_len - int(prefill_mask.shape[1])),+ dtype=prefill_mask.dtype,+ device=prefill_mask.device,+ )+ decode_attention_mask_2d = torch.cat([prefill_mask, pad], dim=1)+ else:+ decode_attention_mask_2d = prefill_mask[:, :current_len]if (cache_position is Noneor (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_attention_mask = decode_attention_mask_2d+ if rope_attention_mask is None or rope_attention_mask.dim() != 2:+ batch_size = int(inputs_embeds.shape[0]) if inputs_embeds is not None else int(input_ids.shape[0])+ seq_len = int(cache_position[-1].item()) + 1 if cache_position is not None else 1+ rope_attention_mask = torch.ones((batch_size, seq_len), dtype=torch.long, device=inputs_embeds.device)+ else:+ rope_attention_mask = rope_attention_mask.to(device=inputs_embeds.device)++ if rope_attention_mask.dtype == torch.bool:+ delta0 = (~rope_attention_mask).to(dtype=torch.long).sum(dim=-1).unsqueeze(1)+ else:+ delta0 = (1 - rope_attention_mask).sum(dim=-1).unsqueeze(1)+ position_ids, rope_deltas = self.get_rope_index(rope_attention_mask)rope_deltas = rope_deltas - delta0self.rope_deltas = rope_deltaselse:@@ -1734,19 +2110,61 @@ class Qwen3TTSTalkerForConditionalGeneration(Qwen3TTSTalkerTextPreTrainedModel,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,+ cg_attention_mask = attention_mask if attention_mask.dim() == 2 else decode_attention_mask_2d+ else:+ decode_attention_mask_2d = None+ cg_attention_mask = attention_mask+ use_cg_decode = (+ self._cuda_graph_hooks.is_active()+ and inputs_embeds is not None+ and inputs_embeds.shape[1] == 1+ and position_ids is not None+ and not isinstance(cg_attention_mask, dict)+ and (cg_attention_mask is None or cg_attention_mask.dim() == 2)+ and self._cuda_graph_hooks.is_talker_cache(past_key_values)+ and cache_position is not None)+ if use_cg_decode:++ def _talker_decode_step(+ decode_inputs_embeds: torch.Tensor,+ decode_attention_mask: torch.Tensor,+ decode_position_ids: torch.Tensor,+ decode_cache_position: torch.Tensor,+ ) -> BaseModelOutputWithPast:+ return self.model(+ input_ids=None,+ attention_mask=decode_attention_mask,+ position_ids=decode_position_ids,+ past_key_values=past_key_values,+ inputs_embeds=decode_inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ cache_position=decode_cache_position,+ **kwargs,+ )++ outputs: BaseModelOutputWithPast = self._cuda_graph_hooks.run_talker_decode(+ _talker_decode_step,+ inputs_embeds=inputs_embeds,+ attention_mask=cg_attention_mask,+ position_ids=position_ids,+ cache_position=cache_position,+ )+ else:+ 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_statelogits = self.codec_head(hidden_states)@@ -1872,6 +2290,19 @@ class Qwen3TTSForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin)def load_generate_config(self, generate_config):self.generate_config = generate_config++ def set_lm_decoder_engine(self, lm_decoder_engine: str | None) -> None:+ self.talker.set_lm_decoder_engine(lm_decoder_engine)++ def prepare_decode_cuda_graph(self, *, max_batch_size: int, max_talker_tokens: int, max_subtalker_tokens: int) -> None:+ self.talker.prepare_decode_cuda_graph(+ max_batch_size=max_batch_size,+ max_talker_tokens=max_talker_tokens,+ max_subtalker_tokens=max_subtalker_tokens,+ )++ def release_decode_cuda_graph(self) -> None:+ self.talker.release_decode_cuda_graph()def get_supported_speakers(self):return self.supported_speakers@@ -2061,9 +2492,17 @@ class Qwen3TTSForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin)subtalker_temperature: float = 0.9,eos_token_id: Optional[int] = None,repetition_penalty: float = 1.05,+ release_decode_graph_on_exit: bool = True,+ cg_max_talker_tokens: Optional[int] = None,+ cg_max_subtalker_tokens: Optional[int] = None,**kwargs,):_check_abort(self)+ talker_eos_token_id = (+ int(eos_token_id)+ if eos_token_id is not None+ else int(self.config.talker_config.codec_eos_token_id)+ )talker_kwargs = {"max_new_tokens": max_new_tokens,"min_new_tokens": 0,@@ -2071,13 +2510,11 @@ class Qwen3TTSForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin)"top_k": top_k,"top_p": top_p,"temperature": temperature,- "subtalker_dosample": subtalker_dosample,+ "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,+ "eos_token_id": talker_eos_token_id,"repetition_penalty": repetition_penalty,"output_hidden_states": True,"return_dict_in_generate": True,@@ -2302,18 +2739,71 @@ class Qwen3TTSForConditionalGeneration(Qwen3TTSPreTrainedModel, GenerationMixin)# forwardtarget_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,+ batch_size = int(talker_input_embeds.shape[0])+ prompt_len = int(talker_input_embeds.shape[1])+ max_talker_tokens = int(prompt_len + max(1, int(max_new_tokens)))+ if cg_max_talker_tokens is not None:+ max_talker_tokens = max(max_talker_tokens, int(cg_max_talker_tokens))+ max_subtalker_tokens = int(max(2, int(self.talker.config.num_code_groups) + 1))+ if cg_max_subtalker_tokens is not None:+ max_subtalker_tokens = max(max_subtalker_tokens, int(cg_max_subtalker_tokens))+ self.prepare_decode_cuda_graph(+ max_batch_size=batch_size,+ max_talker_tokens=max_talker_tokens,+ max_subtalker_tokens=max_subtalker_tokens,)+ graph_active = self.talker.is_decode_cuda_graph_active()+ if self.talker.is_decode_cuda_graph_enabled():+ prepare_status = "reused" if self.talker.decode_cuda_graph_last_prepare_reused() else "new"+ state = "active" if graph_active else "inactive"+ if state == "inactive" or prepare_status == "new":+ print(f"[Qwen3TTS][cg] decode graph {state} ({prepare_status})")++ talker_cache = self.talker.get_decode_talker_cache()+ use_stepwise_talker = bool(graph_active and talker_cache is not None)+ if use_stepwise_talker:+ self.talker.rope_deltas = None- 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]+ _check_abort(self)+ try:+ self.talker._prefill_attention_mask = talker_attention_mask.to(target_device)+ if use_stepwise_talker:+ talker_codes, talker_hidden_states = self.talker.generate_stepwise(+ 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),+ max_new_tokens=int(max_new_tokens),+ do_sample=bool(do_sample),+ top_k=int(top_k),+ top_p=float(top_p),+ temperature=float(temperature),+ subtalker_dosample=bool(subtalker_dosample),+ subtalker_top_k=int(subtalker_top_k),+ subtalker_top_p=float(subtalker_top_p),+ subtalker_temperature=float(subtalker_temperature),+ eos_token_id=talker_eos_token_id,+ repetition_penalty=float(repetition_penalty),+ past_key_values=talker_cache,+ use_cache=True,+ stopping_criteria=kwargs.get("stopping_criteria"),+ )+ else:+ if "use_cache" in kwargs:+ talker_kwargs["use_cache"] = kwargs["use_cache"]+ 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]+ finally:+ self.talker._prefill_attention_mask = None+ if bool(release_decode_graph_on_exit):+ self.release_decode_cuda_graph()first_codebook = talker_codes[:, :, 0]is_stop_token = (first_codebook == self.config.talker_config.codec_eos_token_id)diff --git a/models/TTS/qwen3/pipeline.py b/models/TTS/qwen3/pipeline.pyindex a5e6803..e0194d7 100644--- a/models/TTS/qwen3/pipeline.py+++ b/models/TTS/qwen3/pipeline.py@@ -4,6 +4,7 @@ import jsonimport mathimport osimport random+import refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Optional@@ -22,7 +23,7 @@ from .. import qwen3_handler as qwen3_defsfrom .core.models.configuration_qwen3_tts import Qwen3TTSConfigfrom .core.models.modeling_qwen3_tts import Qwen3TTSForConditionalGenerationfrom .core.models.processing_qwen3_tts import Qwen3TTSProcessor-from .inference.qwen3_tts_model import Qwen3TTSModel+from .inference.qwen3_tts_model import Qwen3TTSModel, VoiceClonePromptItemfrom .inference.qwen3_tts_tokenizer import Qwen3TTSTokenizer@@ -52,6 +53,10 @@ def _set_interrupt_check(module: torch.nn.Module, check_fn) -> None:child._interrupt_check = check_fn+def _is_abort_exception(exc: Exception) -> bool:+ return "Abort requested" in str(exc)++class _AbortAndProgressCriteria(StoppingCriteria):def __init__(self,@@ -128,9 +133,11 @@ class Qwen3TTSPipeline:*,ckpt_root: Optional[Path] = None,device: Optional[torch.device] = None,+ lm_decoder_engine: Optional[str] = None,) -> None:self.device = device or torch.device("cpu")self.base_model_type = base_model_type+ self.lm_decoder_engine = str(lm_decoder_engine or "legacy").strip().lower()self.ckpt_root = Path(ckpt_root) if ckpt_root is not None else Path(fl.get_download_location())self._interrupt = Falseself._early_stop = False@@ -141,6 +148,7 @@ class Qwen3TTSPipeline:self.processor = self._load_text_processor(assets)self.model.load_speech_tokenizer(self.speech_tokenizer)+ self.model.set_lm_decoder_engine(self.lm_decoder_engine)self.tts = Qwen3TTSModel(model=self.model,processor=self.processor,@@ -153,6 +161,8 @@ class Qwen3TTSPipeline:self.supported_speakers = sorted(self.tts.get_supported_speakers() or [])self.supported_languages = sorted(self.tts.get_supported_languages() or [])+ engine = "cg" if self.lm_decoder_engine == "cg" else "legacy"+ print(f"[Qwen3TTS] LM Engine='{engine}'")def _abort_requested(self) -> bool:return bool(self._interrupt)@@ -182,6 +192,122 @@ class Qwen3TTSPipeline:return 1.0return 1.0 / tokens_per_second+ def _resolve_max_new_tokens(self, duration_seconds: Optional[float], kwargs: dict) -> int:+ if duration_seconds is not None and duration_seconds > 0:+ tokens = int(round(float(duration_seconds) * self._get_tokens_per_second()))+ return max(1, tokens)+ 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)+ try:+ return max(1, int(max_new_tokens))+ except (TypeError, ValueError):+ return 2048++ def _resolve_auto_split_seconds(self, kwargs: dict) -> Optional[float]:+ custom_settings = kwargs.get("custom_settings", None)+ if not isinstance(custom_settings, dict):+ return None+ raw_value = custom_settings.get(qwen3_defs.QWEN3_TTS_AUTO_SPLIT_SETTING_ID, None)+ if raw_value is None:+ return None+ if isinstance(raw_value, str):+ raw_value = raw_value.strip()+ if len(raw_value) == 0:+ return None+ try:+ if isinstance(raw_value, bool):+ return None+ value = float(raw_value)+ except (TypeError, ValueError):+ return None+ return value if value > 0 else None++ def _resolve_cut_char_index(self, text: str, token_limit: Optional[int]) -> Optional[int]:+ if token_limit is None or token_limit <= 0 or len(text) == 0:+ return None+ tokenizer = getattr(self.processor, "tokenizer", None)+ if tokenizer is None:+ return None+ try:+ encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)+ offsets = encoded.get("offset_mapping", None) if isinstance(encoded, dict) else None+ if offsets is None and hasattr(encoded, "offset_mapping"):+ offsets = encoded.offset_mapping+ if offsets is None or len(offsets) <= token_limit:+ return None+ cut_char = offsets[token_limit][0]+ if isinstance(cut_char, (list, tuple)):+ cut_char = cut_char[0]+ cut_char = int(cut_char)+ return min(len(text), max(1, cut_char))+ except Exception:+ try:+ token_ids = tokenizer.encode(text, add_special_tokens=False)+ except Exception:+ return None+ if token_ids is None or len(token_ids) <= token_limit:+ return None+ try:+ prefix = tokenizer.decode(+ token_ids[:token_limit],+ skip_special_tokens=False,+ clean_up_tokenization_spaces=False,+ )+ except Exception:+ return None+ return min(len(text), max(1, len(prefix)))++ def _find_split_index_before_cut(self, text: str, cut_index: int) -> int:+ safe_cut = min(len(text), max(1, int(cut_index)))+ prefix = text[:safe_cut]+ dot_idx = prefix.rfind(".")+ newline_idx = prefix.rfind("\n")+ best_idx = max(dot_idx, newline_idx)+ if best_idx >= 0:+ return best_idx + 1+ space_idx = prefix.rfind(" ")+ if space_idx >= 0:+ return space_idx + 1+ return safe_cut++ def _split_text_sequence(self, text: str, auto_split_tokens: Optional[int]) -> list[str]:+ normalized = str(text or "").replace("\r\n", "\n").replace("\r", "\n")+ normalized = re.sub(r"\n(?:[ \t]*\n)+", "\n\n", normalized)+ manual_blocks = re.split(r"\n\s*\n", normalized)+ segments = []+ for block in manual_blocks:+ remaining = block.strip()+ if len(remaining) == 0:+ continue+ if auto_split_tokens is None or auto_split_tokens <= 0:+ segments.append(remaining)+ continue+ while len(remaining) > 0:+ cut_index = self._resolve_cut_char_index(remaining, auto_split_tokens)+ if cut_index is None:+ segments.append(remaining.strip())+ break+ split_index = self._find_split_index_before_cut(remaining, cut_index)+ if split_index <= 0:+ split_index = min(len(remaining), max(1, cut_index))+ piece = remaining[:split_index].strip()+ if len(piece) == 0:+ split_index = min(len(remaining), max(1, cut_index))+ piece = remaining[:split_index].strip()+ if len(piece) == 0:+ split_index = 1+ piece = remaining[:1]+ segments.append(piece)+ remaining = remaining[split_index:].lstrip()+ if len(segments) == 0 and len(normalized.strip()) > 0:+ segments.append(normalized.strip())+ return segments+def _resolve_assets(self, model_weights_path: str) -> _Qwen3Assets:weights_path = model_weights_pathconfig_path = qwen3_defs.get_qwen3_config_path(self.base_model_type)@@ -256,6 +382,294 @@ class Qwen3TTSPipeline:)return criteria, StoppingCriteriaList([criteria])+ @staticmethod+ def _normalize_audio_prompt_type(value) -> str:+ mode = str(value or "A").strip().upper()+ if mode not in ("A", "AB"):+ raise ValueError(f"Unsupported audio prompt mode '{mode}'. Use 'A' (one speaker) or 'AB' (two speakers).")+ return mode++ @staticmethod+ def _parse_two_speaker_dialogue(text: str) -> list[tuple[int, str]]:+ speaker_matches = list(re.finditer(r"Speaker\s*(\d+)\s*:\s*", text, flags=re.IGNORECASE))+ if not speaker_matches:+ raise ValueError("Two-speaker mode requires prompt lines using Speaker 0: and Speaker 1:.")+ invalid_ids = sorted({match.group(1) for match in speaker_matches if match.group(1) not in ("0", "1")})+ if invalid_ids:+ raise ValueError("Only Speaker 0: and Speaker 1: are supported in two-speaker mode.")+ seen_ids = {match.group(1) for match in speaker_matches}+ if "0" not in seen_ids or "1" not in seen_ids:+ raise ValueError("Two-speaker mode requires prompt lines using both Speaker 0: and Speaker 1:.")++ segments: list[tuple[int, str]] = []+ for index, match in enumerate(speaker_matches):+ start = match.end()+ end = speaker_matches[index + 1].start() if index + 1 < len(speaker_matches) else len(text)+ segment_text = text[start:end].strip()+ if segment_text:+ segments.append((int(match.group(1)), segment_text))+ if not segments:+ raise ValueError("No dialogue text found after Speaker tags.")+ return segments++ @staticmethod+ def _resolve_two_speaker_ref_scripts(raw_ref_text: str) -> tuple[list[Optional[str]], list[bool]]:+ normalized = str(raw_ref_text or "").replace("\r\n", "\n").replace("\r", "\n")+ lines = [line.strip() for line in normalized.split("\n") if line.strip()]+ if not lines:+ return [None, None], [True, True]++ first = lines[0] if len(lines) > 0 else None+ second = lines[1] if len(lines) > 1 else None+ speaker_ref_texts = [first, second]+ speaker_xvector_only = [text is None for text in speaker_ref_texts]+ return speaker_ref_texts, speaker_xvector_only++ def _estimate_two_speaker_prompt_tokens(+ self,+ *,+ dialogue_segments: list[tuple[int, str]],+ speaker_prompts: dict[int, VoiceClonePromptItem],+ ) -> int:+ max_prompt_tokens = 1+ for speaker_id, segment_text in dialogue_segments:+ assistant_text = f"<|im_start|>assistant\n{segment_text}<|im_end|>\n<|im_start|>assistant\n"+ encoded = self.processor(text=[assistant_text], return_tensors="pt")+ input_token_length = int(encoded["input_ids"].shape[-1])+ prompt_item = speaker_prompts[speaker_id]+ ref_token_length = 0+ if prompt_item.ref_text:+ ref_encoded = self.processor(text=[f"<|im_start|>assistant\n{prompt_item.ref_text}<|im_end|>\n"], return_tensors="pt")+ ref_token_length = int(ref_encoded["input_ids"].shape[-1])+ ref_code_length = int(prompt_item.ref_code.shape[0]) if prompt_item.ref_code is not None else 0+ max_prompt_tokens = max(max_prompt_tokens, input_token_length + ref_token_length + ref_code_length + 64)+ return max_prompt_tokens++ def _generate_base_two_speaker(+ self,+ *,+ text: str,+ language: str,+ audio_guide: str,+ audio_guide2: str,+ speaker_ref_texts: list[Optional[str]],+ speaker_xvector_only: list[bool],+ max_new_tokens: int,+ duration_seconds: Optional[float],+ total_seconds: Optional[int],+ temperature: float,+ top_k: Optional[int],+ pause_seconds: float,+ auto_split_tokens: Optional[int],+ callback,+ ):+ dialogue_segments_raw = self._parse_two_speaker_dialogue(text)+ dialogue_segments: list[tuple[int, str]] = []+ for speaker_id, segment_text in dialogue_segments_raw:+ split_segments = self._split_text_sequence(segment_text, auto_split_tokens)+ for one_segment in split_segments:+ if len(one_segment.strip()) > 0:+ dialogue_segments.append((speaker_id, one_segment.strip()))+ if len(dialogue_segments) == 0:+ return None+ try:+ prompt_items = self.tts.create_voice_clone_prompt(+ ref_audio=[audio_guide, audio_guide2],+ ref_text=speaker_ref_texts,+ x_vector_only_mode=speaker_xvector_only,+ )+ except RuntimeError as exc:+ if _is_abort_exception(exc):+ return None+ raise+ speaker_prompts = {0: prompt_items[0], 1: prompt_items[1]}++ keep_shared_graph = self.lm_decoder_engine == "cg"+ shared_gen_kwargs = {}+ if keep_shared_graph:+ max_prompt_tokens = self._estimate_two_speaker_prompt_tokens(+ dialogue_segments=dialogue_segments,+ speaker_prompts=speaker_prompts,+ )+ shared_gen_kwargs["cg_max_talker_tokens"] = int(max_prompt_tokens + max_new_tokens)+ shared_gen_kwargs["cg_max_subtalker_tokens"] = int(max(2, int(self.model.talker.config.num_code_groups) + 1))+ shared_gen_kwargs["release_decode_graph_on_exit"] = False++ try:+ pause_seconds = float(pause_seconds)+ except (TypeError, ValueError):+ pause_seconds = 0.5+ pause_seconds = max(0.0, min(10.0, pause_seconds))+ pause_samples_default = int(round(pause_seconds * self.sample_rate))++ tokens_per_second = self._get_tokens_per_second()+ seconds_per_token = self._get_seconds_per_token()+ max_total_samples = int(round(duration_seconds * self.sample_rate)) if duration_seconds is not None and duration_seconds > 0 else None+ max_total_seconds = float(duration_seconds) if duration_seconds is not None and duration_seconds > 0 else None+ per_segment_token_limit = int(max_new_tokens)+ if auto_split_tokens is not None and auto_split_tokens > 0:+ per_segment_token_limit = max(1, min(per_segment_token_limit, int(auto_split_tokens)))++ generated_segments = []+ elapsed_seconds = 0.0++ try:+ for segment_index, (speaker_id, segment_text) in enumerate(dialogue_segments):+ if self._abort_requested():+ return None+ if max_total_seconds is not None and elapsed_seconds >= max_total_seconds:+ break+ if self._early_stop_requested():+ break++ segment_seconds_left = None+ if max_total_seconds is not None:+ segment_seconds_left = max(0.0, max_total_seconds - elapsed_seconds)+ if segment_seconds_left <= 0:+ break+ duration_cap = max(1, int(math.ceil(segment_seconds_left * tokens_per_second)))+ segment_max_new_tokens = max(1, min(per_segment_token_limit, duration_cap))+ else:+ segment_max_new_tokens = per_segment_token_limit++ progress_offset_seconds = int(elapsed_seconds)++ def _offset_callback(step_idx=None, override_num_inference_steps=None, denoising_extra=None, progress_unit=None):+ if callback is None:+ return+ local_step = -1+ if step_idx is not None:+ try:+ local_step = int(step_idx)+ except Exception:+ local_step = -1+ if local_step < 0:+ global_step = max(-1, progress_offset_seconds - 1)+ else:+ global_step = progress_offset_seconds + local_step+ if total_seconds is not None:+ progress_total = int(total_seconds)+ else:+ try:+ local_total = int(override_num_inference_steps)+ except Exception:+ local_total = max(1, int(math.ceil(segment_max_new_tokens * seconds_per_token)))+ progress_total = max(1, progress_offset_seconds + local_total)+ segment_info = f"Segment {segment_index + 1}/{len(dialogue_segments)}"+ extra_info = f"{denoising_extra} | {segment_info}" if denoising_extra else segment_info+ callback(+ step_idx=global_step,+ override_num_inference_steps=progress_total,+ denoising_extra=extra_info,+ progress_unit=progress_unit or "seconds",+ )++ criteria, stopping = self._build_stopping_criteria(+ segment_max_new_tokens,+ seconds_per_token,+ _offset_callback,+ total_seconds=int(math.ceil(segment_seconds_left)) if segment_seconds_left is not None else None,+ )+ prompt_item = speaker_prompts[speaker_id]+ voice_clone_prompt_dict = self.tts._prompt_items_to_voice_clone_prompt([prompt_item])+ input_ids = self.tts._tokenize_texts([self.tts._build_assistant_text(segment_text)])+ ref_ids = None+ if prompt_item.ref_text is not None and prompt_item.ref_text != "":+ ref_ids = [self.tts._tokenize_texts([self.tts._build_ref_text(prompt_item.ref_text)])[0]]+ segment_kwargs = self.tts._merge_generate_kwargs(+ max_new_tokens=int(segment_max_new_tokens),+ temperature=float(temperature),+ top_k=int(top_k) if top_k is not None else None,+ stopping_criteria=stopping,+ **shared_gen_kwargs,+ )++ try:+ talker_codes_list, _ = self.model.generate(+ input_ids=input_ids,+ ref_ids=ref_ids,+ voice_clone_prompt=voice_clone_prompt_dict,+ languages=[language],+ non_streaming_mode=False,+ **segment_kwargs,+ )+ except RuntimeError as exc:+ if _is_abort_exception(exc):+ return None+ raise+ finally:+ criteria.close()++ if self._abort_requested():+ return None+ if not talker_codes_list:+ if self._early_stop_requested() and generated_segments:+ break+ return None++ talker_codes = talker_codes_list[0]++ has_next = segment_index + 1 < len(dialogue_segments)+ append_pause_after = has_next and dialogue_segments[segment_index + 1][0] != speaker_id+ generated_segments.append(+ {+ "codes": talker_codes,+ "append_pause_after": append_pause_after,+ }+ )++ elapsed_seconds += float(talker_codes.shape[0]) / float(tokens_per_second)+ if append_pause_after:+ elapsed_seconds += pause_seconds+ if max_total_seconds is not None and elapsed_seconds >= max_total_seconds:+ break+ if self._early_stop_requested():+ break+ finally:+ if keep_shared_graph:+ self.model.release_decode_cuda_graph()++ if self._abort_requested():+ return None+ if not generated_segments:+ return None++ wavs_all, sr = self.model.speech_tokenizer.decode([{"audio_codes": item["codes"]} for item in generated_segments])+ audio_segments = []+ elapsed_samples = 0+ for index, item in enumerate(generated_segments):+ wav = wavs_all[index]+ segment_audio = torch.from_numpy(wav)+ if max_total_samples is not None and elapsed_samples + int(segment_audio.shape[-1]) > max_total_samples:+ keep_samples = max_total_samples - elapsed_samples+ if keep_samples <= 0:+ break+ segment_audio = segment_audio[:keep_samples]+ if int(segment_audio.shape[-1]) > 0:+ audio_segments.append(segment_audio)+ elapsed_samples += int(segment_audio.shape[-1])++ if max_total_samples is not None and elapsed_samples >= max_total_samples:+ break+ if not bool(item["append_pause_after"]):+ continue+ pause_samples = pause_samples_default+ if pause_samples <= 0:+ continue+ if max_total_samples is not None:+ pause_samples = min(pause_samples, max_total_samples - elapsed_samples)+ if pause_samples <= 0:+ continue+ audio_segments.append(torch.zeros((pause_samples,), dtype=segment_audio.dtype, device=segment_audio.device))+ elapsed_samples += pause_samples+ if max_total_samples is not None and elapsed_samples >= max_total_samples:+ break++ if not audio_segments:+ return None+ output_audio = torch.cat(audio_segments, dim=-1)+ return {"x": output_audio, "audio_sampling_rate": int(sr)}+def generate(self,input_prompt: str,@@ -286,20 +700,209 @@ class Qwen3TTSPipeline:duration_seconds = Noneseconds_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)+ max_new_tokens = self._resolve_max_new_tokens(duration_seconds, kwargs)+ total_seconds = max(1, int(math.ceil(duration_seconds))) if duration_seconds is not None and duration_seconds > 0 else None++ top_k = kwargs.get("top_k", None)+ if top_k is not None:+ try:+ top_k = int(top_k)+ except (TypeError, ValueError):+ top_k = None+ audio_prompt_type = self._normalize_audio_prompt_type(kwargs.get("audio_prompt_type", "A"))+ audio_guide2 = kwargs.get("audio_guide2", None)+ pause_seconds = kwargs.get("pause_seconds", 0.5)+ auto_split_seconds = self._resolve_auto_split_seconds(kwargs)+ auto_split_tokens = (+ max(1, int(round(auto_split_seconds * self._get_tokens_per_second())))+ if auto_split_seconds is not None+ else None+ )++ if self.base_model_type == "qwen3_tts_base" and audio_prompt_type == "AB":+ if not audio_guide:+ raise ValueError("Speaker 0 reference audio is required for Qwen3 Base voice clone.")+ if not audio_guide2:+ raise ValueError("Speaker 1 reference audio is required for two-speaker Qwen3 Base mode.")+ language = (model_mode or "auto").lower()+ ref_text = _read_text_or_file(alt_prompt, "Reference transcript(s)")+ speaker_ref_texts, speaker_xvector_only = self._resolve_two_speaker_ref_scripts(ref_text)+ return self._generate_base_two_speaker(+ text=text,+ language=language,+ audio_guide=audio_guide,+ audio_guide2=audio_guide2,+ speaker_ref_texts=speaker_ref_texts,+ speaker_xvector_only=speaker_xvector_only,+ max_new_tokens=max_new_tokens,+ duration_seconds=duration_seconds,+ total_seconds=total_seconds,+ temperature=float(temperature),+ top_k=top_k,+ pause_seconds=pause_seconds,+ auto_split_tokens=auto_split_tokens,+ callback=callback,+ )++ text_segments = self._split_text_sequence(text, auto_split_tokens)+ if len(text_segments) > 1:+ if self.base_model_type == "qwen3_tts_customvoice":+ if not self.supported_speakers:+ raise ValueError("No supported speakers found for Qwen3 CustomVoice.")+ segment_speaker = model_mode or self.supported_speakers[0]+ segment_language = "auto"+ segment_instruct = _read_text_or_file(alt_prompt, "Instruction")+ elif self.base_model_type == "qwen3_tts_voicedesign":+ segment_language = (model_mode or "auto").lower()+ segment_instruct = _read_text_or_file(alt_prompt, "Instruction")+ elif self.base_model_type == "qwen3_tts_base":+ if not audio_guide:+ raise ValueError("Reference audio is required for Qwen3 Base voice clone.")+ segment_language = (model_mode or "auto").lower()+ segment_ref_text = _read_text_or_file(alt_prompt, "Reference transcript")+ segment_x_vector_only_mode = not segment_ref_text.strip()+ if segment_x_vector_only_mode:+ segment_ref_text = None+ try:+ segment_voice_clone_prompt_item = self.tts.create_voice_clone_prompt(+ ref_audio=audio_guide,+ ref_text=segment_ref_text,+ x_vector_only_mode=segment_x_vector_only_mode,+ )[0]+ except RuntimeError as exc:+ if _is_abort_exception(exc):+ return None+ raise+ else:+ raise ValueError(f"Unknown Qwen3 TTS type: {self.base_model_type}")++ audio_segments = []+ elapsed_seconds = 0.0+ elapsed_samples = 0+ max_total_samples = int(round(duration_seconds * self.sample_rate)) if duration_seconds is not None and duration_seconds > 0 else None+ max_total_seconds = float(duration_seconds) if duration_seconds is not None and duration_seconds > 0 else None+ per_segment_token_limit = int(max_new_tokens)+ if auto_split_tokens is not None and auto_split_tokens > 0:+ per_segment_token_limit = max(1, min(per_segment_token_limit, int(auto_split_tokens)))+ sr_last = int(self.sample_rate)++ try:+ for segment_index, segment_text in enumerate(text_segments):+ if self._abort_requested():+ return None+ if self._early_stop_requested():+ break++ segment_seconds_left = None+ if max_total_seconds is not None:+ segment_seconds_left = max(0.0, max_total_seconds - elapsed_seconds)+ if segment_seconds_left <= 0:+ break+ duration_cap = max(1, int(math.ceil(segment_seconds_left * self._get_tokens_per_second())))+ segment_max_new_tokens = max(1, min(per_segment_token_limit, duration_cap))+ else:+ segment_max_new_tokens = per_segment_token_limit++ progress_offset_seconds = int(elapsed_seconds)++ def _offset_callback(step_idx=None, override_num_inference_steps=None, denoising_extra=None, progress_unit=None):+ if callback is None:+ return+ local_step = -1+ if step_idx is not None:+ try:+ local_step = int(step_idx)+ except Exception:+ local_step = -1+ if local_step < 0:+ global_step = max(-1, progress_offset_seconds - 1)+ else:+ global_step = progress_offset_seconds + local_step+ if total_seconds is not None:+ progress_total = int(total_seconds)+ else:+ try:+ local_total = int(override_num_inference_steps)+ except Exception:+ local_total = max(1, int(math.ceil(segment_max_new_tokens * seconds_per_token)))+ progress_total = max(1, progress_offset_seconds + local_total)+ segment_info = f"Segment {segment_index + 1}/{len(text_segments)}"+ extra_info = f"{denoising_extra} | {segment_info}" if denoising_extra else segment_info+ callback(+ step_idx=global_step,+ override_num_inference_steps=progress_total,+ denoising_extra=extra_info,+ progress_unit=progress_unit or "seconds",+ )++ criteria, stopping = self._build_stopping_criteria(+ segment_max_new_tokens,+ seconds_per_token,+ _offset_callback,+ total_seconds=int(math.ceil(segment_seconds_left)) if segment_seconds_left is not None else None,+ )+ segment_gen_kwargs = {+ "max_new_tokens": int(segment_max_new_tokens),+ "temperature": float(temperature),+ "stopping_criteria": stopping,+ }+ if top_k is not None:+ segment_gen_kwargs["top_k"] = top_k++ try:+ if self.base_model_type == "qwen3_tts_customvoice":+ wavs, sr = self.tts.generate_custom_voice(+ text=segment_text,+ language=segment_language,+ speaker=segment_speaker,+ instruct=segment_instruct,+ **segment_gen_kwargs,+ )+ elif self.base_model_type == "qwen3_tts_voicedesign":+ wavs, sr = self.tts.generate_voice_design(+ text=segment_text,+ language=segment_language,+ instruct=segment_instruct,+ **segment_gen_kwargs,+ )+ else:+ wavs, sr = self.tts.generate_voice_clone(+ text=segment_text,+ language=segment_language,+ voice_clone_prompt=[segment_voice_clone_prompt_item],+ **segment_gen_kwargs,+ )+ except RuntimeError as exc:+ if _is_abort_exception(exc):+ return None+ raise+ finally:+ criteria.close()++ if self._abort_requested():+ return None+ if not wavs:+ return None+ sr_last = int(sr)+ segment_audio = torch.from_numpy(wavs[0])+ if max_total_samples is not None and elapsed_samples + int(segment_audio.shape[-1]) > max_total_samples:+ keep_samples = max_total_samples - elapsed_samples+ if keep_samples <= 0:+ break+ segment_audio = segment_audio[:keep_samples]+ if int(segment_audio.shape[-1]) > 0:+ audio_segments.append(segment_audio)+ elapsed_samples += int(segment_audio.shape[-1])+ elapsed_seconds += float(segment_audio.shape[-1]) / float(sr_last)+ if max_total_samples is not None and elapsed_samples >= max_total_samples:+ break+ finally:+ if self.base_model_type == "qwen3_tts_base" and self.lm_decoder_engine == "cg":+ self.model.release_decode_cuda_graph()++ if len(audio_segments) == 0:+ return None+ return {"x": torch.cat(audio_segments, dim=-1), "audio_sampling_rate": sr_last}criteria, stopping = self._build_stopping_criteria(max_new_tokens,@@ -312,12 +915,8 @@ class Qwen3TTSPipeline:"temperature": float(temperature),"stopping_criteria": stopping,}- top_k = kwargs.get("top_k", None)if top_k is not None:- try:- gen_kwargs["top_k"] = int(top_k)- except (TypeError, ValueError):- pass+ gen_kwargs["top_k"] = top_ktry:if self.base_model_type == "qwen3_tts_customvoice":@@ -359,7 +958,7 @@ class Qwen3TTSPipeline:else:raise ValueError(f"Unknown Qwen3 TTS type: {self.base_model_type}")except RuntimeError as exc:- if "Abort requested" in str(exc):+ if _is_abort_exception(exc):return Noneraisefinally:@@ -372,6 +971,8 @@ class Qwen3TTSPipeline:return {"x": wav, "audio_sampling_rate": int(sr)}def release(self) -> None:+ if self.model is not None and hasattr(self.model, "release_decode_cuda_graph"):+ self.model.release_decode_cuda_graph()for module in [self.model, getattr(self.speech_tokenizer, "model", None)]:if hasattr(module, "to"):module.to("cpu")diff --git a/models/TTS/qwen3_handler.py b/models/TTS/qwen3_handler.pyindex b617387..57a3958 100644--- a/models/TTS/qwen3_handler.py+++ b/models/TTS/qwen3_handler.py@@ -1,5 +1,6 @@import jsonimport os+import refrom pathlib import Pathfrom typing import Optional@@ -7,7 +8,7 @@ import torchfrom shared.utils import files_locator as fl-from .prompt_enhancers import TTS_MONOLOGUE_PROMPT+from .prompt_enhancers import TTS_MONOLOGUE_PROMPT, TTS_QWEN3_DIALOGUE_PROMPTQWEN3_TTS_VARIANTS = {@@ -110,10 +111,30 @@ QWEN3_TTS_SPEAKER_META = {QWEN3_TTS_DURATION_SLIDER = {"label": "Max duration (seconds)","min": 1,- "max": 240,+ "max": 600,"increment": 1,"default": 20,}+QWEN3_TTS_AUDIO_PROMPT_TYPE_SOURCES = {+ "selection": ["A", "AB"],+ "labels": {+ "A": "Voice cloning (1 speaker)",+ "AB": "Dialogue (2 speakers)",+ },+ "letters_filter": "AB",+ "default": "A",+}+QWEN3_TTS_AUTO_SPLIT_SETTING_ID = "auto_split_every_s"+QWEN3_TTS_AUTO_SPLIT_MIN_SECONDS = 5.0+QWEN3_TTS_AUTO_SPLIT_MAX_SECONDS = 90.0+QWEN3_TTS_CUSTOM_SETTINGS = [+ {+ "id": QWEN3_TTS_AUTO_SPLIT_SETTING_ID,+ "label": "Auto Split Every s (5-90, optional), may reduce VRAM requiremens for very long speeches.",+ "name": "Auto Split Every s",+ "type": "float",+ },+]def _format_qwen3_label(value: str) -> str:@@ -200,9 +221,19 @@ def get_qwen3_model_def(base_model_type: str) -> dict:"duration_slider": dict(QWEN3_TTS_DURATION_SLIDER),"top_k_slider": True,"text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,- "prompt_enhancer_button_label": "Write Speech",+ "text_prompt_enhancer_max_tokens": 512,+ "prompt_enhancer_button_label": "Write","compile": False,"parent_model_type": "qwen3_tts_base",+ "lm_engines": ["cg"],+ "prompt_enhancer_def": {+ "selection": ["T", "T1"] if base_model_type == "qwen3_tts_base" else ["T"],+ "labels": {+ "T": "A Speech based on current Prompt",+ "T1": "A Dialogue between two People based on current Prompt",+ },+ "default": "T",+ },}if base_model_type == "qwen3_tts_customvoice":speakers = get_qwen3_speakers(base_model_type)@@ -243,12 +274,20 @@ def get_qwen3_model_def(base_model_type: str) -> dict:"label": "Language",},"alt_prompt": {- "label": "Reference transcript (optional)",- "placeholder": "Okay. Yeah. I respect you, but you blew it.",+ "label": "Reference transcript(s) (optional, two-speaker: one per line)",+ "placeholder": "Speaker 0 reference transcript\nSpeaker 1 reference transcript","lines": 3,},+ "pause_between_sentences": True,+ "preserve_empty_prompt_lines": True,"any_audio_prompt": True,- "audio_guide_label": "Reference voice",+ "audio_prompt_choices": True,+ "audio_prompt_type_sources": dict(QWEN3_TTS_AUDIO_PROMPT_TYPE_SOURCES),+ "custom_settings": [one.copy() for one in QWEN3_TTS_CUSTOM_SETTINGS],+ "text_prompt_enhancer_instructions1": TTS_QWEN3_DIALOGUE_PROMPT,+ "text_prompt_enhancer_max_tokens1": 512,+ "audio_guide_label": "Speaker 0 reference voice",+ "audio_guide2_label": "Speaker 1 reference voice",}return common@@ -325,6 +364,7 @@ class family_handler:submodel_no_list=None,text_encoder_filename=None,profile=0,+ lm_decoder_engine="legacy",**kwargs,):from .qwen3.pipeline import Qwen3TTSPipeline@@ -347,11 +387,28 @@ class family_handler:base_model_type=base_model_type,ckpt_root=ckpt_root,device=torch.device("cpu"),+ lm_decoder_engine=lm_decoder_engine,)+ if str(lm_decoder_engine).strip().lower() in ("cg", "cudagraph"):+ pipeline.model._budget = 0+ talker = getattr(pipeline.model, "talker", None)+ if talker is not None:+ talker._budget = 0+ code_predictor = getattr(talker, "code_predictor", None)+ if code_predictor is not None:+ code_predictor._budget = 0pipe = {"transformer": pipeline.model}if getattr(pipeline, "speech_tokenizer", None) is not None:pipe["speech_tokenizer"] = pipeline.speech_tokenizer.model+ if save_quantized and weights_path:+ from wgp import save_quantized_model++ config_path = get_qwen3_config_path(base_model_type)+ if config_path is None:+ config_candidate = os.path.join("qwen3", "configs", f"{base_model_type}.json")+ config_path = fl.locate_file(config_candidate, error_if_none=False) or config_candidate+ save_quantized_model(pipeline.model, model_type, weights_path, dtype or torch.bfloat16, config_path)return pipeline, pipe@staticmethod@@ -374,6 +431,7 @@ class family_handler:defaults = {"audio_prompt_type": "A","model_mode": "auto",+ "pause_seconds": 0.5,}else:defaults = {@@ -382,6 +440,10 @@ class family_handler:}for key, value in defaults.items():ui_defaults.setdefault(key, value)+ if base_model_type == "qwen3_tts_base":+ audio_prompt_type = str(ui_defaults.get("audio_prompt_type", "A") or "A").upper()+ if audio_prompt_type not in ("A", "AB"):+ ui_defaults["audio_prompt_type"] = "A"if settings_version < 2.44:if model_def.get("top_k_slider", False):@@ -434,6 +496,7 @@ class family_handler:"model_mode": "auto","alt_prompt": "","duration_seconds": get_qwen3_duration_default(),+ "pause_seconds": 0.5,"repeat_generation": 1,"video_length": 0,"num_inference_steps": 0,@@ -465,8 +528,71 @@ class family_handler: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."+ audio_prompt_type = str(inputs.get("audio_prompt_type", "A") or "A").upper()+ if audio_prompt_type not in ("A", "AB"):+ return "Unsupported audio prompt mode for Qwen3 Base. Use one speaker or two speakers."if inputs.get("audio_guide") is None:- return "Qwen3 Base requires a reference audio clip."+ return "Qwen3 Base requires Speaker 0 reference audio."+ prompt_text = str(one_prompt)+ has_speaker_syntax = re.search(r"Speaker\s*\d+\s*:", prompt_text, flags=re.IGNORECASE) is not None+ if audio_prompt_type == "AB":+ if inputs.get("audio_guide2") is None:+ return "Two-speaker mode requires Speaker 1 reference audio."+ speaker_matches = list(re.finditer(r"Speaker\s*(\d+)\s*:", prompt_text, flags=re.IGNORECASE))+ if not speaker_matches:+ return "Two-speaker mode requires prompt lines using Speaker 0: and Speaker 1:."+ invalid_ids = sorted({m.group(1) for m in speaker_matches if m.group(1) not in ("0", "1")})+ if invalid_ids:+ return "Only Speaker 0: and Speaker 1: are supported in two-speaker mode."+ has_speaker_0 = any(m.group(1) == "0" for m in speaker_matches)+ has_speaker_1 = any(m.group(1) == "1" for m in speaker_matches)+ if not has_speaker_0 or not has_speaker_1:+ return "Two-speaker mode requires prompt lines using both Speaker 0: and Speaker 1:."+ elif has_speaker_syntax:+ return "Speaker-tag dialogue requires two-speaker mode (set audio prompt mode to Dialogue)."return Nonereturn None++ @staticmethod+ def validate_generative_settings(base_model_type, model_def, inputs):+ if base_model_type != "qwen3_tts_base":+ return None+ custom_settings = inputs.get("custom_settings", None)+ if custom_settings is None:+ return None+ if not isinstance(custom_settings, dict):+ return "Custom settings must be a dictionary."++ raw_value = custom_settings.get(QWEN3_TTS_AUTO_SPLIT_SETTING_ID, None)+ if raw_value is None:+ return None+ if isinstance(raw_value, str):+ raw_value = raw_value.strip()+ if len(raw_value) == 0:+ custom_settings.pop(QWEN3_TTS_AUTO_SPLIT_SETTING_ID, None)+ inputs["custom_settings"] = custom_settings if len(custom_settings) > 0 else None+ return None++ try:+ if isinstance(raw_value, bool):+ raise ValueError()+ auto_split_seconds = float(raw_value)+ except Exception:+ return (+ f"Auto Split Every s must be a number between "+ f"{int(QWEN3_TTS_AUTO_SPLIT_MIN_SECONDS)} and {int(QWEN3_TTS_AUTO_SPLIT_MAX_SECONDS)} seconds."+ )++ if (+ auto_split_seconds < QWEN3_TTS_AUTO_SPLIT_MIN_SECONDS+ or auto_split_seconds > QWEN3_TTS_AUTO_SPLIT_MAX_SECONDS+ ):+ return (+ f"Auto Split Every s must be between "+ f"{int(QWEN3_TTS_AUTO_SPLIT_MIN_SECONDS)} and {int(QWEN3_TTS_AUTO_SPLIT_MAX_SECONDS)} seconds."+ )++ custom_settings[QWEN3_TTS_AUTO_SPLIT_SETTING_ID] = auto_split_seconds+ inputs["custom_settings"] = custom_settings+ return Nonediff --git a/requirements.txt b/requirements.txtindex a42a9b4..6b63a7d 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,4 +1,5 @@--extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-13-nightly/pypi/simple/+mmgp==3.7.5# Core AI stackdiffusers==0.36.0transformers==4.54.0 #4.53.1@@ -67,7 +68,6 @@ pydantic==2.10.6# Math & modelingtorchdiffeq>=0.2.5tensordict>=0.6.1-mmgp==3.7.4peft==0.17.0 # 0.15.0vector-quantize-pytorchmatplotlibdiff --git a/shared/kernels/quanto_int8_triton.py b/shared/kernels/quanto_int8_triton.pyindex c060927..23d950f 100644--- a/shared/kernels/quanto_int8_triton.py+++ b/shared/kernels/quanto_int8_triton.py@@ -109,6 +109,15 @@ def _parse_version(ver: str) -> tuple[int, int]:return (0, 0)+def _is_stream_capturing() -> bool:+ if not torch.cuda.is_available():+ return False+ try:+ return bool(torch.cuda.is_current_stream_capturing())+ except Exception:+ return False++def _env_int(name: str, default: int) -> int:try:return int(os.environ.get(name, str(default)))@@ -821,6 +830,16 @@ def _select_triton_int8_config(cached = _AUTOTUNE_SESSION_CACHE.get(session_key)if cached is not None:return cached+ if _is_stream_capturing():+ _load_autotune_cache()+ slot_key = _autotune_slot_cache_key(device_index, kernel_kind, slot_id)+ cached_cfg = _AUTOTUNE_CONFIG_CACHE.get(slot_key)+ if cached_cfg is not None and _config_compatible_with_baseline(kernel_kind, baseline, cached_cfg):+ _AUTOTUNE_SESSION_CACHE[session_key] = cached_cfg+ return cached_cfg+ # During graph capture we must avoid autotune/probing allocations. Do not populate+ # session cache with the baseline fallback, so a later non-capture call can autotune.+ return baselineautotune_enabled = _env_flag(_ENV_AUTOTUNE_ENABLE, "1")max_m = _env_int(_ENV_AUTOTUNE_MAX_M, -1)diff --git a/wgp.py b/wgp.pyindex 3cc3acc..d82d2e5 100644--- a/wgp.py+++ b/wgp.py@@ -93,8 +93,8 @@ AUTOSAVE_ERROR_FILENAME = "error_queue.zip"AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAMECONFIG_FILENAME = "wgp_config.json"PROMPT_VARS_MAX = 10-target_mmgp_version = "3.7.4"-WanGP_version = "10.84"+target_mmgp_version = "3.7.5"+WanGP_version = "10.9"settings_version = 2.51max_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@@ -3659,6 +3659,9 @@ def load_models(model_type, override_profile = -1, output_type="video", **model_profile = compute_profile(override_profile, output_type)lm_decoder_engine_obtained = resolve_lm_decoder_engine(lm_decoder_engine, model_def.get("lm_engines", []) )+ if lm_decoder_engine_obtained in ("cg", "vllm") and int(profile) not in [ 1, 3]:+ print(f"Unable to use LM Engine '{lm_decoder_engine_obtained}' as it requires a Memory Profile such as 1,3 or 3+ that loads entirely the Main Models in VRAM. Switching to Legacy LM Engine...")+ lm_decoder_engine_obtained = "legacy"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,@@ -5384,23 +5387,29 @@ class DynamicClass:return self.assign(**dict)def process_prompt_enhancer(model_def, prompt_enhancer, original_prompts, image_start, original_image_refs, is_image, audio_only, seed, prompt_enhancer_instructions = None ):-+ prompt_enhancer_mode = str(prompt_enhancer or "")prompt_enhancer_instructions = model_def.get("image_prompt_enhancer_instructions" if is_image else "video_prompt_enhancer_instructions", None)text_encoder_max_tokens = model_def.get("image_prompt_enhancer_max_tokens" if is_image else "video_prompt_enhancer_max_tokens", 256)- if not "I" in prompt_enhancer:- prompt_enhancer_instructions = model_def.get("text_prompt_enhancer_instructions", prompt_enhancer_instructions)- text_encoder_max_tokens = model_def.get("text_prompt_enhancer_max_tokens", text_encoder_max_tokens)+ if "I" not in prompt_enhancer_mode:+ prompt_profile_id = "0"+ prompt_profile_match = re.search(r"\d", prompt_enhancer_mode)+ if prompt_profile_match is not None:+ prompt_profile_id = prompt_profile_match.group(0)+ prompt_instructions_key = "text_prompt_enhancer_instructions" if prompt_profile_id == "0" else f"text_prompt_enhancer_instructions{prompt_profile_id}"+ prompt_max_tokens_key = "text_prompt_enhancer_max_tokens" if prompt_profile_id == "0" else f"text_prompt_enhancer_max_tokens{prompt_profile_id}"+ prompt_enhancer_instructions = model_def.get(prompt_instructions_key, model_def.get("text_prompt_enhancer_instructions", prompt_enhancer_instructions))+ text_encoder_max_tokens = model_def.get(prompt_max_tokens_key, model_def.get("text_prompt_enhancer_max_tokens", text_encoder_max_tokens))from shared.prompt_enhancer.prompt_enhance_utils import generate_cinematic_promptprompt_images = []- if "I" in prompt_enhancer:+ if "I" in prompt_enhancer_mode:if image_start != None:if not isinstance(image_start, list): image_start= [image_start]prompt_images += image_startif original_image_refs != None:prompt_images += original_image_refs[:1]prompt_images = [Image.open(img) if isinstance(img,str) else img for img in prompt_images]- if len(original_prompts) == 0 and not "T" in prompt_enhancer:+ if len(original_prompts) == 0 and "T" not in prompt_enhancer_mode:return Noneelse:import secrets@@ -5416,7 +5425,7 @@ def process_prompt_enhancer(model_def, prompt_enhancer, original_prompts, imageprompt_enhancer_image_caption_processor,prompt_enhancer_llm_model,prompt_enhancer_llm_tokenizer,- original_prompts if "T" in prompt_enhancer else ["an image"],+ original_prompts if "T" in prompt_enhancer_mode else ["an image"],prompt_images if len(prompt_images) > 0 else None,video_prompt = not is_image,text_prompt = audio_only,@@ -9971,23 +9980,64 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonwizard_variables_var = gr.Text(wizard_variables, visible = False)with gr.Row(visible= server_config.get("enhancer_enabled", 0) > 0 ) as prompt_enhancer_row:on_demand_prompt_enhancer = server_config.get("enhancer_mode", 0) == 1- prompt_enhancer_choices_allowed = model_def.get("prompt_enhancer_choices_allowed", ["T"] if audio_only else ["T", "I", "TI"])prompt_enhancer_value = ui_get("prompt_enhancer")prompt_enhancer_btn_label = str(model_def.get("prompt_enhancer_button_label", "Enhance Prompt"))prompt_enhancer_btn = gr.Button( value =prompt_enhancer_btn_label, visible= on_demand_prompt_enhancer, size="lg", elem_classes="btn_centered")- prompt_enhancer_choices= ([] if on_demand_prompt_enhancer else [("Disabled", "")])- if "T" in prompt_enhancer_choices_allowed:- prompt_enhancer_choices += [("Based on Text Prompt Content", "T")]- if "I" in prompt_enhancer_choices_allowed:- prompt_enhancer_choices += [("Based on Images Prompts Content (such as Start Image and Reference Images)", "I")]- if "TI" in prompt_enhancer_choices_allowed:- prompt_enhancer_choices += [("Based on both Text Prompt and Images Prompts Content", "TI")]-- if len(prompt_enhancer_value) == 0 and on_demand_prompt_enhancer: prompt_enhancer_value = prompt_enhancer_choices[0][1]+ prompt_enhancer_choices = [] if on_demand_prompt_enhancer else [("Disabled", "")]+ prompt_enhancer_default = ""+ prompt_enhancer_default_labels = {+ "T": "Based on Text Prompt Content",+ "I": "Based on Images Prompts Content (such as Start Image and Reference Images)",+ "TI": "Based on both Text Prompt and Images Prompts Content",+ }+ prompt_enhancer_def = model_def.get("prompt_enhancer_def")+ if isinstance(prompt_enhancer_def, dict):+ prompt_enhancer_selection = prompt_enhancer_def.get("selection", [])+ if isinstance(prompt_enhancer_selection, str):+ prompt_enhancer_selection = [prompt_enhancer_selection]+ if not isinstance(prompt_enhancer_selection, list):+ prompt_enhancer_selection = []+ prompt_enhancer_labels_override = prompt_enhancer_def.get("labels", {})+ if not isinstance(prompt_enhancer_labels_override, dict):+ prompt_enhancer_labels_override = {}+ for selection_value in prompt_enhancer_selection:+ selection_value = str(selection_value).strip()+ if len(selection_value) == 0:+ continue+ display_label = prompt_enhancer_labels_override.get(selection_value, prompt_enhancer_default_labels.get(selection_value, selection_value))+ prompt_enhancer_choices.append((str(display_label), selection_value))+ prompt_enhancer_default = str(prompt_enhancer_def.get("default", "")).strip()+ else:+ prompt_enhancer_choices_allowed = model_def.get("prompt_enhancer_choices_allowed", ["T"] if audio_only else ["T", "I", "TI"])+ if isinstance(prompt_enhancer_choices_allowed, str):+ prompt_enhancer_choices_allowed = [prompt_enhancer_choices_allowed]+ if not isinstance(prompt_enhancer_choices_allowed, list):+ prompt_enhancer_choices_allowed = []+ for selection_value in prompt_enhancer_choices_allowed:+ selection_value = str(selection_value).strip()+ if len(selection_value) == 0:+ continue+ display_label = prompt_enhancer_default_labels.get(selection_value, selection_value)+ prompt_enhancer_choices.append((display_label, selection_value))++ prompt_enhancer_values = [value for _, value in prompt_enhancer_choices]+ if prompt_enhancer_value not in prompt_enhancer_values:+ if prompt_enhancer_default in prompt_enhancer_values:+ prompt_enhancer_value = prompt_enhancer_default+ elif len(prompt_enhancer_values) > 0:+ prompt_enhancer_value = prompt_enhancer_values[0]+ else:+ prompt_enhancer_value = ""+ elif len(prompt_enhancer_value) == 0 and on_demand_prompt_enhancer and len(prompt_enhancer_values) > 0:+ if prompt_enhancer_default in prompt_enhancer_values:+ prompt_enhancer_value = prompt_enhancer_default+ else:+ prompt_enhancer_value = prompt_enhancer_values[0]+prompt_enhancer = gr.Dropdown(choices=prompt_enhancer_choices,value=prompt_enhancer_value,- label="Enhance Prompt using a LLM", scale = 5,+ label=model_def.get("prompt_enhancer_button_label", "Enhance Prompt using a LLM") , scale = 5,visible= True, show_label= not on_demand_prompt_enhancer,)alt_prompt_def = model_def.get("alt_prompt", None)