Skip to content
Python

add non flash mode for index tts2 cg

DeepBeepMeep83431a4c1f25
diff --git a/README.md b/README.md
index 6da8e90..7afc055 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen,
## 🔥 Latest Updates :
-### February 19th 2026: WanGP v10.95, Breaking the Sound Barrier, Mach 2
+### February 19th 2026: WanGP v10.951, Breaking the Sound Barrier, Mach 2
Here comes the (last ?) missing bit in WanGP of the *Text To Speech* offering: **emotions**
There isnt many TTS models around that let you express emotions, so I hope you will forgive me for adding an old TTS model (6 months old!) in WanGP: **Index TTS 2**.
@@ -56,6 +56,8 @@ You can also set manually which emotion you expect with [] tags, here is one exa
[happy] By chance I discovered this wonderful App, and now everything is different.
[anger] I have a new voice and now everybody will have no choice but to listen to my words !!!
```
+You can mix emotions *[sadness,disgust]* or if you want to precise the weight of one or several emotions *[sadness=0.7,disgust]* (in any case total of weights is 1)
+
Remember two speakers mode requires to insert *"Speaker 1:"* & *"Speaker 2:"* to indicate who is talking.
There is only one snag: Index TTS 2 supports only English & Chinese. But dont' panic ! not all is lost. There is a workaround:
diff --git a/models/TTS/index_tts2/accel/attention.py b/models/TTS/index_tts2/accel/attention.py
index 2946c5d..41d54b3 100644
--- a/models/TTS/index_tts2/accel/attention.py
+++ b/models/TTS/index_tts2/accel/attention.py
@@ -1,11 +1,24 @@
from dataclasses import dataclass
import torch
-import triton
-import triton.language as tl
-from flash_attn import flash_attn_varlen_func, flash_attn_with_kvcache
+import torch.nn.functional as F
from torch import nn
+try:
+ import triton
+ import triton.language as tl
+except Exception:
+ triton = None
+ tl = None
+
+try:
+ from flash_attn import flash_attn_varlen_func, flash_attn_with_kvcache
+except Exception:
+ flash_attn_varlen_func = None
+ flash_attn_with_kvcache = None
+
+_SDPA_FALLBACK_NOTICE_SHOWN = False
+
@dataclass
class ForwardContext:
@@ -22,6 +35,10 @@ class ForwardContext:
_FORWARD_CONTEXT = ForwardContext()
+def flash_attn2_available():
+ return flash_attn_varlen_func is not None and flash_attn_with_kvcache is not None
+
+
def get_forward_context():
return _FORWARD_CONTEXT
@@ -54,36 +71,37 @@ def reset_forward_context():
_FORWARD_CONTEXT = ForwardContext()
-def store_kvcache_kernel(
- key_ptr,
- key_stride,
- value_ptr,
- value_stride,
- k_cache_ptr,
- v_cache_ptr,
- slot_mapping_ptr,
- D: tl.constexpr,
-):
- BLOCK_SIZE: tl.constexpr = 2048
- idx = tl.program_id(0)
- slot = tl.load(slot_mapping_ptr + idx)
- if slot == -1:
- return
- d_offset = 0
- while d_offset < D:
- cur_block_size = min(BLOCK_SIZE, D - d_offset)
- key_offsets = idx * key_stride + d_offset + tl.arange(0, BLOCK_SIZE)
- value_offsets = idx * value_stride + d_offset + tl.arange(0, BLOCK_SIZE)
- cache_offsets = slot * D + d_offset + tl.arange(0, BLOCK_SIZE)
+if triton is not None:
+ @triton.jit
+ def store_kvcache_kernel(
+ key_ptr,
+ key_stride,
+ value_ptr,
+ value_stride,
+ k_cache_ptr,
+ v_cache_ptr,
+ slot_mapping_ptr,
+ D: tl.constexpr,
+ ):
+ BLOCK_SIZE: tl.constexpr = 2048
+ idx = tl.program_id(0)
+ slot = tl.load(slot_mapping_ptr + idx)
+ if slot == -1:
+ return
+ d_offset = 0
+ while d_offset < D:
+ cur_block_size = min(BLOCK_SIZE, D - d_offset)
+ key_offsets = idx * key_stride + d_offset + tl.arange(0, BLOCK_SIZE)
+ value_offsets = idx * value_stride + d_offset + tl.arange(0, BLOCK_SIZE)
+ cache_offsets = slot * D + d_offset + tl.arange(0, BLOCK_SIZE)
- mask = tl.arange(0, BLOCK_SIZE) < cur_block_size
- key = tl.load(key_ptr + key_offsets, mask=mask, other=0.0)
- value = tl.load(value_ptr + value_offsets, mask=mask, other=0.0)
- tl.store(k_cache_ptr + cache_offsets, key, mask=mask)
- tl.store(v_cache_ptr + cache_offsets, value, mask=mask)
+ mask = tl.arange(0, BLOCK_SIZE) < cur_block_size
+ key = tl.load(key_ptr + key_offsets, mask=mask, other=0.0)
+ value = tl.load(value_ptr + value_offsets, mask=mask, other=0.0)
+ tl.store(k_cache_ptr + cache_offsets, key, mask=mask)
+ tl.store(v_cache_ptr + cache_offsets, value, mask=mask)
- d_offset += BLOCK_SIZE
+ d_offset += BLOCK_SIZE
def store_kvcache(
@@ -95,13 +113,23 @@ def store_kvcache(
):
N, num_heads, head_dim = key.shape
D = num_heads * head_dim
+ assert slot_mapping.numel() == N
+ if triton is None:
+ flat_slots = slot_mapping.to(device=key.device, dtype=torch.long)
+ valid = flat_slots >= 0
+ if not bool(valid.any().item()):
+ return
+ src_idx = torch.nonzero(valid, as_tuple=False).squeeze(1)
+ dst_idx = flat_slots.index_select(0, src_idx)
+ flat_k_cache = k_cache.view(-1, num_heads, head_dim)
+ flat_v_cache = v_cache.view(-1, num_heads, head_dim)
+ flat_k_cache.index_copy_(0, dst_idx, key.index_select(0, src_idx))
+ flat_v_cache.index_copy_(0, dst_idx, value.index_select(0, src_idx))
+ return
assert key.stride(-1) == 1 and value.stride(-1) == 1
assert key.stride(1) == head_dim and value.stride(1) == head_dim
assert k_cache.stride(1) == D and v_cache.stride(1) == D
- assert slot_mapping.numel() == N
- store_kvcache_kernel[(N,)](
- key, key.stride(0), value, value.stride(0), k_cache, v_cache, slot_mapping, D
- )
+ store_kvcache_kernel[(N,)](key, key.stride(0), value, value.stride(0), k_cache, v_cache, slot_mapping, D)
class Attention(nn.Module):
@@ -118,6 +146,106 @@ class Attention(nn.Module):
self.scale = scale
self.num_kv_heads = num_kv_heads
self.k_cache = self.v_cache = torch.tensor([])
+ self._flash_attn2_available = flash_attn2_available()
+
+ @staticmethod
+ def _to_int(value):
+ return int(value.item()) if torch.is_tensor(value) else int(value)
+
+ @staticmethod
+ def _gather_cache_tokens(cache: torch.Tensor, block_table: torch.Tensor, token_count: int):
+ if token_count <= 0:
+ return cache.new_empty((0, cache.shape[2], cache.shape[3]))
+ block_size = int(cache.shape[1])
+ token_idx = torch.arange(token_count, device=cache.device, dtype=torch.long)
+ block_idx = torch.div(token_idx, block_size, rounding_mode="floor")
+ token_offset = torch.remainder(token_idx, block_size)
+ block_ids = block_table.index_select(0, block_idx).to(torch.long)
+ return cache[block_ids, token_offset]
+
+ def _sdpa(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, prefix_len: int = 0, causal: bool = True):
+ if q.numel() == 0:
+ return q
+ q_ = q.transpose(0, 1).unsqueeze(0)
+ k_ = k.transpose(0, 1).unsqueeze(0)
+ v_ = v.transpose(0, 1).unsqueeze(0)
+ q_len, k_len = int(q.shape[0]), int(k.shape[0])
+ use_causal = bool(causal and prefix_len == 0)
+ attn_mask = None
+ if causal and prefix_len > 0:
+ q_idx = torch.arange(q_len, device=q.device, dtype=torch.long) + int(prefix_len)
+ k_idx = torch.arange(k_len, device=q.device, dtype=torch.long)
+ attn_mask = (k_idx.unsqueeze(0) <= q_idx.unsqueeze(1)).view(1, 1, q_len, k_len)
+ use_causal = False
+ out = F.scaled_dot_product_attention(q_, k_, v_, attn_mask=attn_mask, dropout_p=0.0, is_causal=use_causal)
+ return out.squeeze(0).transpose(0, 1).contiguous()
+
+ def _sdpa_prefill(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, context: ForwardContext, k_cache: torch.Tensor, v_cache: torch.Tensor):
+ if context.cu_seqlens_q is None or context.cu_seqlens_k is None:
+ return self._sdpa(q, k, v, prefix_len=max(0, int(k.shape[0]) - int(q.shape[0])), causal=True)
+ num_seqs = int(context.cu_seqlens_q.numel()) - 1
+ outs = []
+ for i in range(num_seqs):
+ q_start = self._to_int(context.cu_seqlens_q[i])
+ q_end = self._to_int(context.cu_seqlens_q[i + 1])
+ q_len = q_end - q_start
+ if q_len <= 0:
+ continue
+ q_i = q[q_start:q_end]
+ if context.block_tables is None:
+ k_start = self._to_int(context.cu_seqlens_k[i])
+ k_end = self._to_int(context.cu_seqlens_k[i + 1])
+ k_i = k[k_start:k_end]
+ v_i = v[k_start:k_end]
+ k_len = k_end - k_start
+ else:
+ k_len = self._to_int(context.cu_seqlens_k[i + 1]) - self._to_int(context.cu_seqlens_k[i])
+ block_table = context.block_tables[i]
+ k_i = self._gather_cache_tokens(k_cache, block_table, k_len)
+ v_i = self._gather_cache_tokens(v_cache, block_table, k_len)
+ prefix_len = max(0, k_len - q_len)
+ outs.append(self._sdpa(q_i, k_i, v_i, prefix_len=prefix_len, causal=True))
+ if not outs:
+ return q.new_empty((0, self.num_heads, self.head_dim))
+ return torch.cat(outs, dim=0)
+
+ def _sdpa_decode(self, q: torch.Tensor, context: ForwardContext, k_cache: torch.Tensor, v_cache: torch.Tensor):
+ if context.context_lens is None or context.block_tables is None:
+ return q
+ batch = int(context.context_lens.shape[0])
+ if batch <= 0:
+ return q
+ q_total = int(q.shape[0])
+ if q_total % batch != 0:
+ raise RuntimeError(f"Invalid decode shape: q_tokens={q_total}, batch={batch}")
+ q_per_seq = q_total // batch
+ num_table_blocks = int(context.block_tables.shape[1])
+ if num_table_blocks <= 0:
+ return torch.zeros_like(q)
+ block_size = int(k_cache.shape[1])
+ max_tokens = num_table_blocks * block_size
+ device = q.device
+ token_idx = torch.arange(max_tokens, device=device, dtype=torch.long)
+ block_idx = torch.div(token_idx, block_size, rounding_mode="floor")
+ token_offset = torch.remainder(token_idx, block_size)
+ block_ids = context.block_tables.index_select(1, block_idx)
+ valid_blocks = block_ids >= 0
+ safe_block_ids = torch.clamp(block_ids, min=0).to(torch.long)
+ k_all = k_cache[safe_block_ids, token_offset]
+ v_all = v_cache[safe_block_ids, token_offset]
+ q_all = q.view(batch, q_per_seq, self.num_heads, self.head_dim)
+ k_all = k_all.transpose(1, 2).contiguous()
+ v_all = v_all.transpose(1, 2).contiguous()
+ q_all = q_all.transpose(1, 2).contiguous()
+ valid_len = token_idx.unsqueeze(0) < context.context_lens.to(device=device, dtype=torch.long).unsqueeze(1)
+ base_mask = valid_blocks & valid_len
+ q_steps = torch.arange(q_per_seq, device=device, dtype=torch.long).view(1, q_per_seq, 1)
+ q_pos = context.context_lens.to(device=device, dtype=torch.long).view(batch, 1, 1) - q_per_seq + q_steps
+ causal_mask = token_idx.view(1, 1, max_tokens) <= q_pos
+ attn_mask = (base_mask.view(batch, 1, 1, max_tokens) & causal_mask).expand(batch, self.num_heads, q_per_seq, max_tokens)
+ out = F.scaled_dot_product_attention(q_all, k_all, v_all, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
+ out = out.transpose(1, 2).contiguous().view(q_total, self.num_heads, self.head_dim)
+ return out
def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor):
context = get_forward_context()
@@ -126,29 +254,38 @@ class Attention(nn.Module):
if k_cache.numel() and v_cache.numel() and context.slot_mapping is not None:
store_kvcache(k, v, k_cache, v_cache, context.slot_mapping)
+ if self._flash_attn2_available:
+ if context.is_prefill:
+ if context.block_tables is not None:
+ k, v = k_cache, v_cache
+ o = flash_attn_varlen_func(
+ q,
+ k,
+ v,
+ max_seqlen_q=context.max_seqlen_q,
+ cu_seqlens_q=context.cu_seqlens_q,
+ max_seqlen_k=context.max_seqlen_k,
+ cu_seqlens_k=context.cu_seqlens_k,
+ softmax_scale=self.scale,
+ causal=True,
+ block_table=context.block_tables,
+ )
+ else:
+ o = flash_attn_with_kvcache(
+ q.unsqueeze(1),
+ k_cache,
+ v_cache,
+ cache_seqlens=context.context_lens,
+ block_table=context.block_tables,
+ softmax_scale=self.scale,
+ causal=True,
+ )
+ return o
+
+ global _SDPA_FALLBACK_NOTICE_SHOWN
+ if not _SDPA_FALLBACK_NOTICE_SHOWN:
+ print("[IndexTTS2][accel] flash_attn not found. Using SDPA fallback for attention.")
+ _SDPA_FALLBACK_NOTICE_SHOWN = True
if context.is_prefill:
- if context.block_tables is not None:
- k, v = k_cache, v_cache
- o = flash_attn_varlen_func(
- q,
- k,
- v,
- max_seqlen_q=context.max_seqlen_q,
- cu_seqlens_q=context.cu_seqlens_q,
- max_seqlen_k=context.max_seqlen_k,
- cu_seqlens_k=context.cu_seqlens_k,
- softmax_scale=self.scale,
- causal=True,
- block_table=context.block_tables,
- )
- else:
- o = flash_attn_with_kvcache(
- q.unsqueeze(1),
- k_cache,
- v_cache,
- cache_seqlens=context.context_lens,
- block_table=context.block_tables,
- softmax_scale=self.scale,
- causal=True,
- )
- return o
+ return self._sdpa_prefill(q, k, v, context, k_cache, v_cache)
+ return self._sdpa_decode(q, context, k_cache, v_cache)
diff --git a/models/TTS/index_tts2/gpt/model_v2.py b/models/TTS/index_tts2/gpt/model_v2.py
index cc275d3..cf5abf7 100644
--- a/models/TTS/index_tts2/gpt/model_v2.py
+++ b/models/TTS/index_tts2/gpt/model_v2.py
@@ -462,7 +462,7 @@ class UnifiedVoice(nn.Module):
train_solo_embeddings=False, use_mel_codes_as_input=True,
checkpointing=True, types=1,
condition_num_latent=32, condition_type="perceiver", condition_module=None, emo_condition_module=None, use_accel=False,
- gpt_build_fp16=True, gpt_build_meta=True):
+ gpt_build_fp16=True, gpt_build_meta=True, force_no_flash2=False):
"""
Args:
layers: Number of layers in transformer stack.
@@ -577,7 +577,9 @@ class UnifiedVoice(nn.Module):
module.weight.data.normal_(mean=0.0, std=.02)
self.use_accel = use_accel
+ self.force_no_flash2 = bool(force_no_flash2)
self.accel_engine = None # Will be initialized in post_init_gpt2_config
+ self.accel_flash2_available = False
@staticmethod
def _install_layernorm_input_dtype_guard(module):
@@ -614,13 +616,15 @@ class UnifiedVoice(nn.Module):
)
if self.use_accel and torch.cuda.is_available():
- # Check if flash attention is available
- try:
- import flash_attn
- except ImportError:
- raise ImportError("flash_attn is required for acceleration but not installed. Please install from https://github.com/Dao-AILab/flash-attention/releases/")
-
from ..accel import GPT2AccelModel, AccelInferenceEngine
+ from ..accel.attention import flash_attn2_available
+
+ self.accel_flash2_available = bool(flash_attn2_available() and (not self.force_no_flash2))
+ if not self.accel_flash2_available:
+ if self.force_no_flash2:
+ print("[IndexTTS2][accel] flash_attn forced off by pipeline flag; using SDPA fallback.")
+ else:
+ print("[IndexTTS2][accel] flash_attn is unavailable at load time; using SDPA fallback.")
# Create accel model
accel_gpt = GPT2AccelModel(gpt_config)
@@ -649,7 +653,9 @@ class UnifiedVoice(nn.Module):
num_blocks=16, # Reduce to save memory (16*256 = 4096 tokens capacity)
use_cuda_graph=True,
)
- print("acceleration engine initialized")
+ backend = "flash2" if self.accel_flash2_available else "sdpa"
+ cg_state = "on"
+ print(f"[IndexTTS2][accel] acceleration engine initialized (backend={backend}, cuda_graph={cg_state})")
self.inference_model = GPT2InferenceModel(
gpt_config,
self.gpt,
diff --git a/models/TTS/index_tts2/infer_v2.py b/models/TTS/index_tts2/infer_v2.py
index 62daf89..9da5d21 100644
--- a/models/TTS/index_tts2/infer_v2.py
+++ b/models/TTS/index_tts2/infer_v2.py
@@ -66,6 +66,7 @@ class IndexTTS2:
self, cfg_path="checkpoints/config.yaml", model_dir="checkpoints", use_fp16=False, device=None,
use_cuda_kernel=None,use_deepspeed=False, use_accel=False, use_torch_compile=False, show_load_logs=False,
lm_decoder_engine="legacy",
+ force_no_flash2=False,
):
"""
Args:
@@ -109,6 +110,7 @@ class IndexTTS2:
self.dtype = torch.float16 if self.use_fp16 else None
self.stop_mel_token = self.cfg.gpt.stop_mel_token
self.use_accel = use_accel
+ self.force_no_flash2 = bool(force_no_flash2)
self.use_torch_compile = use_torch_compile
qwen_emo_dir = self.cfg.qwen_emo_path
@@ -139,7 +141,7 @@ class IndexTTS2:
modelClass=UnifiedVoice,
forcedConfigPath=gpt_config_path,
default_dtype=torch.float16 if self.use_fp16 else torch.float32,
- configKwargs={"use_accel": self.use_accel, "gpt_build_fp16": self.use_fp16, "gpt_build_meta": True},
+ configKwargs={"use_accel": self.use_accel, "gpt_build_fp16": self.use_fp16, "gpt_build_meta": True, "force_no_flash2": self.force_no_flash2},
)
self.gpt = self.gpt.to("cpu")
if self.use_fp16:
diff --git a/models/TTS/index_tts2/pipeline.py b/models/TTS/index_tts2/pipeline.py
index 4ed3d44..db6e542 100644
--- a/models/TTS/index_tts2/pipeline.py
+++ b/models/TTS/index_tts2/pipeline.py
@@ -31,6 +31,8 @@ _AUTO_SPLIT_TOKENS_PER_SECOND = 6.0
_MEL_TOKENS_PER_SOUND_TOKEN = 1.72
_MIN_CG_SOUND_SECONDS = 10.0
_CG_SOUND_TOKENS_PER_TEXT_TOKEN = 29.67
+# Local dev toggle: set to True to simulate FlashAttention2 unavailable.
+_FORCE_NO_FLASH2 = False
def _read_text_or_file(value: Optional[str], label: str) -> str:
@@ -93,9 +95,16 @@ class IndexTTS2Pipeline:
use_torch_compile=False,
show_load_logs=self.show_load_logs,
lm_decoder_engine=self.lm_decoder_engine,
+ force_no_flash2=_FORCE_NO_FLASH2,
)
engine = "cg" if self.lm_decoder_engine in ("cg", "cudagraph") else "legacy"
- print(f"[IndexTTS2] LM Engine='{engine}'")
+ flash_status = "n/a"
+ if engine == "cg":
+ if getattr(self.model.gpt, "accel_engine", None) is None:
+ flash_status = "disabled"
+ else:
+ flash_status = "on" if getattr(self.model.gpt, "accel_flash2_available", False) else "off(sdpa)"
+ print(f"[IndexTTS2] LM Engine='{engine}', flash2={flash_status}")
self.sample_rate = 22050
self._mark_model_dtypes()
diff --git a/models/TTS/index_tts2/s2mel/dac/__init__.py b/models/TTS/index_tts2/s2mel/dac/__init__.py
index 51205ef..d0788e8 100644
--- a/models/TTS/index_tts2/s2mel/dac/__init__.py
+++ b/models/TTS/index_tts2/s2mel/dac/__init__.py
@@ -3,14 +3,7 @@ __version__ = "1.0.0"
# preserved here for legacy reasons
__model_version__ = "latest"
-import audiotools
-
-audiotools.ml.BaseModel.INTERN += ["dac.**"]
-audiotools.ml.BaseModel.EXTERN += ["einops"]
-
-
from . import nn
from . import model
-from . import utils
from .model import DAC
from .model import DACFile
diff --git a/models/TTS/index_tts2/s2mel/dac/model/base.py b/models/TTS/index_tts2/s2mel/dac/model/base.py
index 546b3cb..1fb14a8 100644
--- a/models/TTS/index_tts2/s2mel/dac/model/base.py
+++ b/models/TTS/index_tts2/s2mel/dac/model/base.py
@@ -6,7 +6,7 @@ from typing import Union
import numpy as np
import torch
import tqdm
-from audiotools import AudioSignal
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal
from torch import nn
SUPPORTED_VERSIONS = ["1.0.0"]
diff --git a/models/TTS/index_tts2/s2mel/dac/model/dac.py b/models/TTS/index_tts2/s2mel/dac/model/dac.py
index 9b4955f..a2a49b1 100644
--- a/models/TTS/index_tts2/s2mel/dac/model/dac.py
+++ b/models/TTS/index_tts2/s2mel/dac/model/dac.py
@@ -4,8 +4,7 @@ from typing import Union
import numpy as np
import torch
-from audiotools import AudioSignal
-from audiotools.ml import BaseModel
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal, BaseModel
from torch import nn
from .base import CodecMixin
diff --git a/models/TTS/index_tts2/s2mel/dac/model/discriminator.py b/models/TTS/index_tts2/s2mel/dac/model/discriminator.py
index 9d9018d..6a23c79 100644
--- a/models/TTS/index_tts2/s2mel/dac/model/discriminator.py
+++ b/models/TTS/index_tts2/s2mel/dac/model/discriminator.py
@@ -1,9 +1,7 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
-from audiotools import AudioSignal
-from audiotools import ml
-from audiotools import STFTParams
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal, STFTParams, ml
from einops import rearrange
from torch.nn.utils import weight_norm
diff --git a/models/TTS/index_tts2/s2mel/dac/nn/loss.py b/models/TTS/index_tts2/s2mel/dac/nn/loss.py
index 9bb3dd6..672e0cc 100644
--- a/models/TTS/index_tts2/s2mel/dac/nn/loss.py
+++ b/models/TTS/index_tts2/s2mel/dac/nn/loss.py
@@ -3,8 +3,7 @@ from typing import List
import torch
import torch.nn.functional as F
-from audiotools import AudioSignal
-from audiotools import STFTParams
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal, STFTParams
from torch import nn
diff --git a/models/TTS/index_tts2/s2mel/dac/utils/__init__.py b/models/TTS/index_tts2/s2mel/dac/utils/__init__.py
index 8865b4c..caa5e9b 100644
--- a/models/TTS/index_tts2/s2mel/dac/utils/__init__.py
+++ b/models/TTS/index_tts2/s2mel/dac/utils/__init__.py
@@ -1,7 +1,7 @@
from pathlib import Path
import argbind
-from audiotools import ml
+from models.TTS.index_tts2.utils.audiotools_lite import ml
from ... import dac as dac
diff --git a/models/TTS/index_tts2/s2mel/dac/utils/decode.py b/models/TTS/index_tts2/s2mel/dac/utils/decode.py
index 450a1d1..e811b3c 100644
--- a/models/TTS/index_tts2/s2mel/dac/utils/decode.py
+++ b/models/TTS/index_tts2/s2mel/dac/utils/decode.py
@@ -4,7 +4,6 @@ from pathlib import Path
import argbind
import numpy as np
import torch
-from audiotools import AudioSignal
from tqdm import tqdm
from .. import DACFile
diff --git a/models/TTS/index_tts2/s2mel/dac/utils/encode.py b/models/TTS/index_tts2/s2mel/dac/utils/encode.py
index c86946c..752623a 100644
--- a/models/TTS/index_tts2/s2mel/dac/utils/encode.py
+++ b/models/TTS/index_tts2/s2mel/dac/utils/encode.py
@@ -5,8 +5,7 @@ from pathlib import Path
import argbind
import numpy as np
import torch
-from audiotools import AudioSignal
-from audiotools.core import util
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal, find_audio
from tqdm import tqdm
from . import load_model
@@ -63,7 +62,7 @@ def encode(
# Find all audio files in input path
input = Path(input)
- audio_files = util.find_audio(input)
+ audio_files = find_audio(input)
output = Path(output)
output.mkdir(parents=True, exist_ok=True)
diff --git a/models/TTS/index_tts2/utils/audiotools_lite.py b/models/TTS/index_tts2/utils/audiotools_lite.py
new file mode 100644
index 0000000..d496083
--- /dev/null
+++ b/models/TTS/index_tts2/utils/audiotools_lite.py
@@ -0,0 +1,305 @@
+from __future__ import annotations
+
+"""
+IndexTTS2 local audiotools compatibility layer.
+
+This file provides a minimal API subset used by IndexTTS2 and is based on
+behavior from the upstream Descript projects:
+- https://github.com/descriptinc/audiotools (tag: 0.7.4)
+- https://github.com/descriptinc/descript-audio-codec
+
+Upstream package metadata credits authors Prem Seetharaman and Lucas Gestin.
+Upstream audiotools is licensed under MIT (see upstream LICENSE file).
+"""
+
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+import torchaudio
+from torch import nn
+
+
+_AUDIO_EXTENSIONS = {
+ ".wav",
+ ".flac",
+ ".mp3",
+ ".ogg",
+ ".m4a",
+ ".aac",
+ ".wma",
+ ".opus",
+}
+
+
+def find_audio(path: Union[str, Path]) -> list[Path]:
+ input_path = Path(path)
+ if input_path.is_file():
+ return [input_path] if input_path.suffix.lower() in _AUDIO_EXTENSIONS else []
+ if not input_path.exists():
+ return []
+ audio_files = [p for p in input_path.rglob("*") if p.is_file() and p.suffix.lower() in _AUDIO_EXTENSIONS]
+ return sorted(audio_files)
+
+
+@dataclass
+class STFTParams:
+ window_length: int
+ hop_length: int
+ match_stride: bool = False
+ window_type: Optional[str] = None
+
+
+def _get_window(window_type: Optional[str], window_length: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ name = (window_type or "hann").lower()
+ if name in {"hann", "hann_window"}:
+ return torch.hann_window(window_length, device=device, dtype=dtype)
+ if name in {"hamming", "hamming_window"}:
+ return torch.hamming_window(window_length, device=device, dtype=dtype)
+ return torch.hann_window(window_length, device=device, dtype=dtype)
+
+
+class AudioSignal:
+ def __init__(
+ self,
+ data: Union[str, Path, torch.Tensor],
+ sample_rate: Optional[int] = None,
+ stft_params: Optional[STFTParams] = None,
+ ):
+ if isinstance(data, (str, Path)):
+ waveform, sr = torchaudio.load(str(data))
+ self.audio_data = waveform.unsqueeze(0)
+ self.sample_rate = int(sr)
+ else:
+ tensor = torch.as_tensor(data)
+ if tensor.ndim == 1:
+ tensor = tensor.unsqueeze(0).unsqueeze(0)
+ elif tensor.ndim == 2:
+ tensor = tensor.unsqueeze(0)
+ elif tensor.ndim != 3:
+ raise ValueError(f"Expected 1D/2D/3D audio tensor, got shape {tuple(tensor.shape)}")
+ if sample_rate is None:
+ raise ValueError("sample_rate is required when constructing AudioSignal from tensors")
+ self.audio_data = tensor
+ self.sample_rate = int(sample_rate)
+
+ if not torch.is_floating_point(self.audio_data):
+ self.audio_data = self.audio_data.float()
+
+ default_hop = max(1, int(self.sample_rate * 0.01))
+ default_win = max(16, default_hop * 4)
+ self.stft_params = stft_params or STFTParams(window_length=default_win, hop_length=default_hop)
+ self.magnitude = None
+
+ @property
+ def device(self) -> torch.device:
+ return self.audio_data.device
+
+ @property
+ def shape(self):
+ return self.audio_data.shape
+
+ @property
+ def signal_length(self) -> int:
+ return int(self.audio_data.shape[-1])
+
+ @property
+ def signal_duration(self) -> float:
+ return float(self.signal_length) / float(self.sample_rate)
+
+ def clone(self) -> "AudioSignal":
+ return AudioSignal(self.audio_data.clone(), self.sample_rate, stft_params=self.stft_params)
+
+ def __getitem__(self, item) -> "AudioSignal":
+ tensor = self.audio_data.__getitem__(item)
+ if tensor.ndim == 1:
+ tensor = tensor.unsqueeze(0).unsqueeze(0)
+ elif tensor.ndim == 2:
+ tensor = tensor.unsqueeze(1)
+ elif tensor.ndim != 3:
+ raise ValueError(f"Unsupported indexed shape {tuple(tensor.shape)}")
+ return AudioSignal(tensor, self.sample_rate, stft_params=self.stft_params)
+
+ def to(self, device: Union[str, torch.device]) -> "AudioSignal":
+ self.audio_data = self.audio_data.to(device)
+ return self
+
+ def zero_pad(self, left: int, right: int) -> "AudioSignal":
+ padded = F.pad(self.audio_data, (int(left), int(right)))
+ return AudioSignal(padded, self.sample_rate, stft_params=self.stft_params)
+
+ def resample(self, target_sample_rate: int) -> "AudioSignal":
+ target_sample_rate = int(target_sample_rate)
+ if target_sample_rate == self.sample_rate:
+ return self
+ batch, channels, samples = self.audio_data.shape
+ flat = self.audio_data.reshape(batch * channels, samples)
+ resampled = torchaudio.functional.resample(flat, self.sample_rate, target_sample_rate)
+ self.audio_data = resampled.reshape(batch, channels, -1)
+ self.sample_rate = target_sample_rate
+ self.magnitude = None
+ return self
+
+ def ffmpeg_resample(self, target_sample_rate: int) -> "AudioSignal":
+ return self.resample(target_sample_rate)
+
+ def loudness(self) -> torch.Tensor:
+ rms = torch.sqrt(torch.mean(self.audio_data.float() ** 2) + 1e-12)
+ db = 20.0 * torch.log10(rms.clamp_min(1e-7))
+ return db.detach().cpu()
+
+ def ffmpeg_loudness(self) -> torch.Tensor:
+ return self.loudness()
+
+ def normalize(self, target_db: Union[float, torch.Tensor]) -> "AudioSignal":
+ target = float(torch.as_tensor(target_db).detach().cpu().item())
+ current = float(self.loudness().item())
+ gain = 10 ** ((target - current) / 20.0)
+ self.audio_data = self.audio_data * gain
+ self.magnitude = None
+ return self
+
+ def ensure_max_of_audio(self, max_value: float = 0.99) -> "AudioSignal":
+ peak = self.audio_data.abs().amax()
+ if torch.isfinite(peak) and peak.item() > max_value:
+ self.audio_data = self.audio_data * (max_value / peak)
+ return self
+
+ def stft(
+ self,
+ window_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ window_type: Optional[str] = None,
+ ) -> torch.Tensor:
+ params = self.stft_params
+ win_length = int(window_length or params.window_length)
+ hop = int(hop_length or params.hop_length)
+ window = _get_window(window_type or params.window_type, win_length, self.device, self.audio_data.dtype)
+ batch, channels, samples = self.audio_data.shape
+ flat = self.audio_data.reshape(batch * channels, samples)
+ spec = torch.stft(
+ flat,
+ n_fft=win_length,
+ hop_length=hop,
+ win_length=win_length,
+ window=window,
+ center=True,
+ return_complex=True,
+ )
+ spec = spec.reshape(batch, channels, spec.shape[-2], spec.shape[-1])
+ self.magnitude = spec.abs()
+ return spec
+
+ def mel_spectrogram(
+ self,
+ n_mels: int,
+ mel_fmin: float = 0.0,
+ mel_fmax: Optional[float] = None,
+ window_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ window_type: Optional[str] = None,
+ ) -> torch.Tensor:
+ params = self.stft_params
+ win_length = int(window_length or params.window_length)
+ hop = int(hop_length or params.hop_length)
+ window_fn = torch.hann_window
+ if (window_type or params.window_type or "").lower() in {"hamming", "hamming_window"}:
+ window_fn = torch.hamming_window
+ mel = torchaudio.transforms.MelSpectrogram(
+ sample_rate=self.sample_rate,
+ n_fft=win_length,
+ win_length=win_length,
+ hop_length=hop,
+ f_min=float(mel_fmin),
+ f_max=None if mel_fmax is None else float(mel_fmax),
+ n_mels=int(n_mels),
+ power=2.0,
+ center=True,
+ window_fn=window_fn,
+ ).to(self.device)
+ batch, channels, samples = self.audio_data.shape
+ flat = self.audio_data.reshape(batch * channels, samples)
+ mels = mel(flat)
+ return mels.reshape(batch, channels, mels.shape[-2], mels.shape[-1])
+
+ def write(self, path: Union[str, Path]) -> Path:
+ out_path = Path(path)
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ waveform = self.audio_data[0].detach().cpu()
+ torchaudio.save(str(out_path), waveform, self.sample_rate)
+ return out_path
+
+ @classmethod
+ def load_from_file_with_ffmpeg(cls, path: Union[str, Path]) -> "AudioSignal":
+ return cls(path)
+
+
+class BaseModel(nn.Module):
+ INTERN = []
+ EXTERN = []
+
+ @property
+ def device(self) -> torch.device:
+ try:
+ return next(self.parameters()).device
+ except StopIteration:
+ return torch.device("cpu")
+
+ @classmethod
+ def _extract_state_dict(cls, checkpoint):
+ if isinstance(checkpoint, dict):
+ for key in ("state_dict", "model", "generator", "weights"):
+ value = checkpoint.get(key)
+ if isinstance(value, dict):
+ return value
+ if checkpoint and all(torch.is_tensor(v) for v in checkpoint.values()):
+ return checkpoint
+ raise RuntimeError("Unsupported checkpoint format for BaseModel.load")
+
+ @classmethod
+ def _clean_state_dict(cls, state_dict):
+ cleaned = {}
+ for key, value in state_dict.items():
+ if key.startswith("module."):
+ key = key[len("module.") :]
+ cleaned[key] = value
+ return cleaned
+
+ @classmethod
+ def load(cls, path: Union[str, Path]):
+ checkpoint = torch.load(path, map_location="cpu")
+ state_dict = cls._clean_state_dict(cls._extract_state_dict(checkpoint))
+ model = cls()
+ model.load_state_dict(state_dict, strict=False)
+ model.eval()
+ return model
+
+
+class Accelerator:
+ def __init__(self, *args, **kwargs):
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+ def prepare(self, *objects):
+ if len(objects) == 1:
+ return objects[0]
+ return objects
+
+ @staticmethod
+ def unwrap_model(model):
+ return model
+
+
+ml = SimpleNamespace(BaseModel=BaseModel, Accelerator=Accelerator)
+
+
+__all__ = [
+ "AudioSignal",
+ "STFTParams",
+ "BaseModel",
+ "Accelerator",
+ "ml",
+ "find_audio",
+]
diff --git a/models/TTS/index_tts2/utils/maskgct/models/codec/facodec/facodec_trainer.py b/models/TTS/index_tts2/utils/maskgct/models/codec/facodec/facodec_trainer.py
index 5141934..cba9835 100644
--- a/models/TTS/index_tts2/utils/maskgct/models/codec/facodec/facodec_trainer.py
+++ b/models/TTS/index_tts2/utils/maskgct/models/codec/facodec/facodec_trainer.py
@@ -35,7 +35,7 @@ from ......s2mel.dac.nn.loss import (
L1Loss,
FocalLoss,
)
-from audiotools import AudioSignal
+from models.TTS.index_tts2.utils.audiotools_lite import AudioSignal
from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
diff --git a/requirements.txt b/requirements.txt
index 5eebb27..e0070da 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -55,8 +55,6 @@ facexlib==0.3.0
taichi
vector_quantize_pytorch==1.27.19
-# Audio
-descript-audiotools==0.7.2
# chumpy wheel hosted on GitHub to avoid sdist build isolation issue
chumpy @ https://github.com/deepbeepmeep/chumpy/releases/download/v0.71/chumpy-0.71-py3-none-any.whl
diff --git a/wgp.py b/wgp.py
index 9851335..9604aa6 100644
--- a/wgp.py
+++ b/wgp.py
@@ -94,7 +94,7 @@ AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.7.5"
-WanGP_version = "10.91"
+WanGP_version = "10.951"
settings_version = 2.52
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None