[New Model] Support IndexTTS 2.5 (#5957)

Signed-off-by: Sysy <1370724210@qq.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
Sy03andYueqian Lin authored and GitHub committed 2026-08-11 23:00:35 +00:00
1 parent 1ff2753469
commit 58007c0084
77 files changed
+7123 -519

No files matched your search

@@ -68,6 +68,6 @@ class MyModel(nn.Module):
x = self.models["gpt_layer"](x)
return x
def enable_torch_compile(self):
def enable_torch_compile(self, mode: str = "default"):
if "cfm" in self.models:
self.models["cfm"].enable_torch_compile()
self.models["cfm"].enable_torch_compile(mode=mode)
@@ -163,7 +163,18 @@ class DiT(torch.nn.Module):
def setup_caches(self, max_batch_size, max_seq_length):
self.transformer.setup_caches(max_batch_size, max_seq_length, use_kv_cache=False)
def forward(self, x, prompt_x, x_lens, t, style, cond, mask_content=False, pre_mask=None):
def forward(
self,
x,
prompt_x,
x_lens,
t,
style,
cond,
mask_content=False,
pre_mask=None,
unpad_data: tuple[torch.Tensor, torch.Tensor] | None = None,
):
"""
x (torch.Tensor): random noise
prompt_x (torch.Tensor): reference mel + zero mel
@@ -226,10 +237,16 @@ class DiT(torch.nn.Module):
input_pos = self.input_pos[: x_in.size(1)] # (T,) range(0,1863)
# Route through per-shape CUDA graph runner if enabled.
graph_runner = getattr(self, "_cuda_graph_runner", None)
if graph_runner is not None:
if graph_runner is not None and unpad_data is None:
x_res = graph_runner(x_in, t1.unsqueeze(1), input_pos, x_mask_expanded)
else:
x_res = self.transformer(x_in, t1.unsqueeze(1), input_pos, x_mask_expanded) # [2, 1863, 512]
x_res = self.transformer(
x_in,
t1.unsqueeze(1),
input_pos,
x_mask_expanded,
unpad_data=unpad_data,
) # [2, 1863, 512]
x_res = x_res[:, 1:] if self.time_as_token else x_res
x_res = x_res[:, 1:] if self.style_as_token else x_res
@@ -8,6 +8,41 @@ import torch
from vllm_omni.model_executor.models.indextts2.s2mel.modules.diffusion_transformer import DiT
def build_cfm_unpad_data(
lengths: list[int],
*,
padded_length: int,
token_offset: int,
repeat_for_cfg: bool,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Build row-major FlashAttention unpadding metadata for one CFM group."""
if not lengths:
raise ValueError("CFM unpad data requires at least one sequence length")
if token_offset < 0:
raise ValueError(f"CFM unpad token offset must be non-negative: {token_offset}")
if any(length < 0 or length > padded_length for length in lengths):
raise ValueError(f"CFM unpad lengths out of range: lengths={lengths} padded={padded_length}")
if max(lengths) != padded_length:
raise ValueError(f"CFM unpad group must contain its padded max: lengths={lengths} padded={padded_length}")
valid_lengths = [length + token_offset for length in lengths]
if repeat_for_cfg:
valid_lengths = [*valid_lengths, *valid_lengths]
padded_stride = padded_length + token_offset
indices = torch.cat(
[
torch.arange(valid_length, device=device, dtype=torch.int64) + row * padded_stride
for row, valid_length in enumerate(valid_lengths)
]
)
cumulative_lengths = [0]
for valid_length in valid_lengths:
cumulative_lengths.append(cumulative_lengths[-1] + valid_length)
cu_seqlens = torch.tensor(cumulative_lengths, device=device, dtype=torch.int32)
return indices, cu_seqlens
class BASECFM(torch.nn.Module, ABC):
def __init__(
self,
@@ -26,7 +61,20 @@ class BASECFM(torch.nn.Module, ABC):
self.zero_prompt_speech_token = False
@torch.inference_mode()
def inference(self, mu, x_lens, prompt, style, f0, n_timesteps, temperature=1.0, inference_cfg_rate=0.5):
def inference(
self,
mu,
x_lens,
prompt,
style,
f0,
n_timesteps,
temperature=1.0,
inference_cfg_rate=0.5,
initial_noise=None,
prompt_lens=None,
unpad_data: tuple[torch.Tensor, torch.Tensor] | None = None,
):
"""Forward diffusion
Args:
@@ -47,11 +95,48 @@ class BASECFM(torch.nn.Module, ABC):
shape: (batch_size, 80, mel_timesteps)
"""
B, T = mu.size(0), mu.size(1)
z = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype) * temperature
expected_noise_shape = (B, self.in_channels, T)
if initial_noise is None:
z = torch.randn(
expected_noise_shape,
device=mu.device,
dtype=mu.dtype,
)
else:
if tuple(initial_noise.shape) != expected_noise_shape:
raise ValueError(
"CFM initial noise shape mismatch: "
f"expected={expected_noise_shape}, got={tuple(initial_noise.shape)}"
)
z = initial_noise.to(device=mu.device, dtype=mu.dtype)
z = z * temperature
t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
return self.solve_euler(z, x_lens, prompt, mu, style, f0, t_span, inference_cfg_rate)
return self.solve_euler(
z,
x_lens,
prompt,
mu,
style,
f0,
t_span,
inference_cfg_rate,
prompt_lens=prompt_lens,
unpad_data=unpad_data,
)
def solve_euler(self, x, x_lens, prompt, mu, style, f0, t_span, inference_cfg_rate=0.5):
def solve_euler(
self,
x,
x_lens,
prompt,
mu,
style,
f0,
t_span,
inference_cfg_rate=0.5,
prompt_lens=None,
unpad_data: tuple[torch.Tensor, torch.Tensor] | None = None,
):
"""
Fixed euler solver for ODEs.
Args:
@@ -82,19 +167,35 @@ class BASECFM(torch.nn.Module, ABC):
out = self.estimator(*args, **kw)
return out.float()
prompt_len = prompt.size(-1)
batch = x.shape[0]
if prompt_lens is None:
prompt_lens = torch.full(
(batch,),
prompt.size(-1),
device=x.device,
dtype=torch.long,
)
else:
prompt_lens = prompt_lens.to(device=x.device, dtype=torch.long).reshape(-1)
if prompt_lens.shape != (batch,):
raise ValueError(f"CFM prompt length/batch mismatch: lengths={prompt_lens.numel()} batch={batch}")
prompt_positions = torch.arange(prompt.size(-1), device=x.device)
prompt_mask = prompt_positions.unsqueeze(0) < prompt_lens.unsqueeze(1)
x_positions = torch.arange(x.size(-1), device=x.device)
noise_prefix_mask = x_positions.unsqueeze(0) < prompt_lens.unsqueeze(1)
prompt_x = torch.zeros_like(x)
prompt_x[..., :prompt_len] = prompt[..., :prompt_len]
x[..., :prompt_len] = 0
prompt_x[..., : prompt.size(-1)] = prompt * prompt_mask.unsqueeze(1).to(prompt.dtype)
x.masked_fill_(noise_prefix_mask.unsqueeze(1), 0)
if self.zero_prompt_speech_token:
mu[..., :prompt_len] = 0
mu = mu.masked_fill(noise_prefix_mask.unsqueeze(-1), 0)
# Precompute mask once — T and x_lens are constant across all ODE steps.
# x_mask [B, 1, T] broadcasts to [2B, 1, T] when CFG doubles batch.
pre_mask = self._precompute_mask(x, x_lens)
if inference_cfg_rate > 0:
batch = x.shape[0]
cfg_prompt_x = prompt_x.new_zeros((2 * batch, *prompt_x.shape[1:]))
cfg_prompt_x[:batch].copy_(prompt_x)
cfg_style = style.new_zeros((2 * batch, *style.shape[1:]))
@@ -120,16 +221,26 @@ class BASECFM(torch.nn.Module, ABC):
cfg_style,
cfg_mu,
pre_mask=cfg_pre_mask,
unpad_data=unpad_data,
)
dphi_dt, cfg_dphi_dt = stacked_dphi_dt.chunk(2, dim=0)
dphi_dt = (1.0 + inference_cfg_rate) * dphi_dt - inference_cfg_rate * cfg_dphi_dt
else:
dphi_dt = _run_estimator(x, prompt_x, x_lens, t.unsqueeze(0), style, mu, pre_mask=pre_mask)
dphi_dt = _run_estimator(
x,
prompt_x,
x_lens,
t.unsqueeze(0),
style,
mu,
pre_mask=pre_mask,
unpad_data=unpad_data,
)
x = x + dt * dphi_dt
t = t + dt
x[:, :, :prompt_len] = 0
x.masked_fill_(noise_prefix_mask.unsqueeze(1), 0)
return x
@@ -180,7 +291,7 @@ class CFM(BASECFM):
raise NotImplementedError(f"Unknown diffusion type {args.dit_type}")
self._compiled = False
def enable_torch_compile(self):
def enable_torch_compile(self, mode: str = "default"):
"""Enable torch.compile optimization for the estimator model.
This method applies torch.compile to the estimator (DiT model) for significant
@@ -191,6 +302,7 @@ class CFM(BASECFM):
torch._inductor.config.reorder_for_compute_comm_overlap = True
self.estimator = torch.compile(
self._eager_estimator,
mode=mode,
fullgraph=True,
dynamic=True,
)
@@ -116,6 +116,7 @@ class Transformer(nn.Module):
context: Tensor | None = None,
context_input_pos: Tensor | None = None,
cross_attention_mask: Tensor | None = None,
unpad_data: tuple[Tensor, Tensor] | None = None,
) -> Tensor:
assert self.freqs_cis is not None, "Caches must be initialized first"
if mask is None: # in case of non-causal model
@@ -135,7 +136,18 @@ class Transformer(nn.Module):
skip_in_x = skip_in_x_list.pop(-1)
else:
skip_in_x = None
x = layer(x, c, input_pos, freqs_cis, mask, context, context_freqs_cis, cross_attention_mask, skip_in_x)
x = layer(
x,
c,
input_pos,
freqs_cis,
mask,
context,
context_freqs_cis,
cross_attention_mask,
skip_in_x,
unpad_data=unpad_data,
)
if self.uvit_skip_connection and i in self.layers_emit_skip:
skip_in_x_list.append(x)
x = self.norm(x, c)
@@ -169,11 +181,18 @@ class TransformerBlock(nn.Module):
context_freqs_cis: Tensor | None = None,
cross_attention_mask: Tensor | None = None,
skip_in_x: Tensor | None = None,
unpad_data: tuple[Tensor, Tensor] | None = None,
) -> Tensor:
c = None if self.time_as_token else c
if self.uvit_skip_connection and skip_in_x is not None:
x = self.skip_in_linear(torch.cat([x, skip_in_x], dim=-1))
h = x + self.attention(self.attention_norm(x, c), freqs_cis, mask, input_pos)
h = x + self.attention(
self.attention_norm(x, c),
freqs_cis,
mask,
input_pos,
unpad_data=unpad_data,
)
out = h + self.feed_forward(self.ffn_norm(h, c))
return out
@@ -218,6 +237,7 @@ class Attention(nn.Module):
input_pos: Tensor | None = None,
context: Tensor | None = None,
context_freqs_cis: Tensor | None = None,
unpad_data: tuple[Tensor, Tensor] | None = None,
) -> Tensor:
bsz, seqlen, _ = x.shape
@@ -252,7 +272,37 @@ class Attention(nn.Module):
# building AttentionMetadata entirely — this avoids the backend's
# `torch.any(~mask)` D2H sync per ODE step and keeps the forward
# CUDA-graph capturable.
if getattr(self, "_assume_full_mask", False):
full_mask_state = getattr(self, "_assume_full_mask", None)
packed_varlen = (
unpad_data is not None
and context is None
and q.device.type == "cuda"
and q.dtype != torch.float32
and hasattr(getattr(self.diff_attn, "attention", None), "_forward_varlen_packed")
)
if packed_varlen:
indices, cu_seqlens = unpad_data
packed_q = q.flatten(0, 1).index_select(0, indices).unsqueeze(0)
packed_k = k.flatten(0, 1).index_select(0, indices).unsqueeze(0)
packed_v = v.flatten(0, 1).index_select(0, indices).unsqueeze(0)
packed_metadata = AttentionMetadata(
extra={
"cu_seqlens_q": cu_seqlens,
"cu_seqlens_k": cu_seqlens,
"max_seqlen_q": seqlen,
"max_seqlen_k": seqlen,
}
)
packed_y = self.diff_attn(
packed_q,
packed_k,
packed_v,
attn_metadata=packed_metadata,
)
flat_y = torch.zeros_like(q.flatten(0, 1))
flat_y.index_copy_(0, indices, packed_y.squeeze(0))
y = flat_y.view_as(q)
elif full_mask_state is True:
attn_metadata = None
else:
attn_mask = mask
@@ -260,8 +310,15 @@ class Attention(nn.Module):
# (B, 1, T, T) → (B, T) — take the first query row;
# all query positions share the same padding pattern.
attn_mask = attn_mask[:, 0, 0, :]
attn_metadata = AttentionMetadata(attn_mask=attn_mask) if attn_mask is not None else None
y = self.diff_attn(q, k, v, attn_metadata=attn_metadata)
attn_metadata = (
AttentionMetadata(
attn_mask=attn_mask,
)
if attn_mask is not None
else None
)
if not packed_varlen:
y = self.diff_attn(q, k, v, attn_metadata=attn_metadata)
y = y.flatten(2, 3)
y = self.wo(y)
@@ -3,6 +3,7 @@
import torch
from torch import nn
from torch.nn import functional as F
from vllm_omni.model_executor.models.indextts2.s2mel.modules.encodec import SConv1d
@@ -53,14 +54,82 @@ class WN(torch.nn.Module):
res_skip_layer = conv1d_type(hidden_channels, res_skip_channels, 1, norm="weight_norm", causal=causal)
self.res_skip_layers.append(res_skip_layer)
# The vectorized ragged path rebuilds logical right-reflect values in
# place and therefore requires each row to be strictly longer than the
# widest right padding. The decoder keeps shorter rows on the original
# exact-length singleton path, preserving SConv1d's existing behavior.
self.ragged_min_length = 1 + max(
((layer.conv.conv.kernel_size[0] - 1) * layer.conv.conv.dilation[0] + 1 - layer.conv.conv.stride[0]) // 2
for layer in self.in_layers
)
@staticmethod
def _logical_reflect_in_layer(
in_layer: SConv1d,
x: torch.Tensor,
logical_lengths: torch.Tensor,
) -> torch.Tensor:
"""Run a WaveNet input convolution at each row's logical boundary.
``SConv1d`` reflects at the physical tensor boundary. In a padded
request batch, shorter rows end before that boundary, so their right
reflection values must be rebuilt before the convolution. This path is
intentionally WaveNet-specific: its input layers are non-causal,
reflect-padded, stride-one convolutions. The decoder keeps rows that
are not strictly longer than the right reflection width on the
original singleton path.
"""
conv = in_layer.conv.conv
stride = conv.stride[0]
dilation = conv.dilation[0]
effective_kernel = (conv.kernel_size[0] - 1) * dilation + 1
if in_layer.causal or in_layer.pad_mode != "reflect" or stride != 1:
raise RuntimeError(
"Ragged WaveNet batching requires non-causal reflect-padded stride-one input convolutions"
)
padding_total = effective_kernel - stride
padding_right = padding_total // 2
padding_left = padding_total - padding_right
padded = F.pad(x, (padding_left, padding_right), mode="reflect")
if padding_right:
offsets = torch.arange(
padding_right,
device=x.device,
dtype=torch.long,
).unsqueeze(0)
lengths = logical_lengths.to(device=x.device, dtype=torch.long).reshape(-1, 1)
source_positions = padding_left + lengths - 2 - offsets
target_positions = padding_left + lengths + offsets
source_indices = source_positions.unsqueeze(1).expand(-1, x.shape[1], -1)
target_indices = target_positions.unsqueeze(1).expand(-1, x.shape[1], -1)
reflected = torch.gather(padded, dim=2, index=source_indices)
padded.scatter_(dim=2, index=target_indices, src=reflected)
return in_layer.conv(padded)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
logical_lengths = None
if getattr(self, "_assume_full_mask", None) is False:
# Under CFG, x_mask has already been repeated from B to 2B in the
# same [conditional rows, unconditional rows] order as x.
logical_lengths = x_mask[:, 0, :].sum(dim=-1)
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if logical_lengths is None:
x_in = self.in_layers[i](x)
else:
x_in = self._logical_reflect_in_layer(
self.in_layers[i],
x,
logical_lengths,
)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]