TTS_10M / models /tts_engine.py
ViuAI's picture
Push audited codebase, regression tests (10/10 pass) & AUDIT.md
79b2661 verified
Raw History Blame Contribute Delete
12 kB
"""
Unified 10M Modern TTS Engine (Optimal Transport CFM + Vocos).
Combines Text Encoder, Duration Predictor, Mel Prior Alignment, and Flow Matching Vector Field.
Total Trainable Acoustic Parameter Count: ~8.17M (+ ~13.53M Vocos = ~21.70M).
"""
import math
import torch
import torch.nn as nn
from typing import Dict, Optional
from .text_encoder import TextEncoder
from .duration_predictor import DurationPredictor, maximum_path, expand_by_duration
from .flow_matching import CFMVectorField, OptimalTransportCFM
from .vocoder import VocosVocoder
from config import ModelConfig, TrainingConfig
class TTS10MEngine(nn.Module):
"""
Cutting-Edge ~10M Parameter TTS Architecture.
"""
def __init__(
self,
config: Optional[ModelConfig] = None,
train_config: Optional[TrainingConfig] = None,
):
super().__init__()
self.config = config or ModelConfig()
self.train_config = train_config or TrainingConfig()
# 1. Text Encoder (~2.76M params)
self.text_encoder = TextEncoder(
vocab_size=self.config.vocab_size,
dim=self.config.text_dim,
layers=self.config.text_layers,
heads=self.config.text_heads,
ffn_dim=self.config.text_ffn_dim,
dropout=self.config.dropout,
pad_token_id=self.config.pad_token_id,
)
# 2. Duration Predictor (~0.40M params)
self.duration_predictor = DurationPredictor(
in_dim=self.config.text_dim,
hidden_dim=self.config.duration_hidden_dim,
kernel_size=self.config.duration_kernel_size,
dropout=self.config.dropout,
)
# Differentiable Mel Prior Projection for Monotonic Alignment Search (MAS)
# Predicts coarse log-mel prior mu_text from h_text so MAS aligns against real mel_gt
# without representation collapse or frozen random weights.
self.prior_proj = nn.Linear(self.config.text_dim, self.config.mel_dim)
# 3. Flow Matching Vector Field (~4.98M params)
# Registered once inside self.cfm to avoid shared-tensor duplication in safetensors
vector_field = CFMVectorField(
mel_dim=self.config.mel_dim,
cond_dim=self.config.text_dim,
hidden_dim=self.config.cfm_hidden_dim,
num_blocks=self.config.cfm_num_blocks,
kernel_size=self.config.cfm_kernel_size,
time_dim=self.config.time_embed_dim,
)
# Flow Matching Module
self.cfm = OptimalTransportCFM(vector_field, sigma_min=self.config.sigma_min)
# Vocoder
self.vocoder = VocosVocoder()
@property
def vector_field(self) -> CFMVectorField:
return self.cfm.vf
def get_num_params(self) -> Dict[str, int]:
"""Returns parameter count of each component and total."""
text_params = sum(p.numel() for p in self.text_encoder.parameters() if p.requires_grad)
dur_params = sum(p.numel() for p in self.duration_predictor.parameters() if p.requires_grad)
prior_params = sum(p.numel() for p in self.prior_proj.parameters() if p.requires_grad)
cfm_params = sum(p.numel() for p in self.vector_field.parameters() if p.requires_grad)
total_trainable = text_params + dur_params + prior_params + cfm_params
return {
"text_encoder": text_params,
"duration_predictor": dur_params,
"prior_projection": prior_params,
"cfm_vector_field": cfm_params,
"total_acoustic_params": total_trainable,
}
def print_summary(self):
params = self.get_num_params()
print("\n" + "=" * 54)
print(" 10M TTS MODEL PARAMETERS SUMMARY ")
print("=" * 54)
print(f" Text Encoder (RoPE Transformer): {params['text_encoder']:,} (~{params['text_encoder']/1e6:.2f}M)")
print(f" Duration Predictor: {params['duration_predictor']:,} (~{params['duration_predictor']/1e6:.2f}M)")
print(f" Mel Prior Projection: {params['prior_projection']:,} (~{params['prior_projection']/1e6:.2f}M)")
print(f" OT-CFM Vector Field: {params['cfm_vector_field']:,} (~{params['cfm_vector_field']/1e6:.2f}M)")
print("-" * 54)
print(f" TOTAL TRAINABLE PARAMETERS: {params['total_acoustic_params']:,} (~{params['total_acoustic_params']/1e6:.2f}M)")
print("=" * 54 + "\n")
def forward_train(
self,
text_ids: torch.Tensor,
text_lengths: torch.Tensor,
mel_gt: torch.Tensor,
mel_lengths: torch.Tensor,
) -> Dict[str, torch.Tensor]:
"""
Training Forward Pass.
text_ids: (B, T_text)
text_lengths: (B,)
mel_gt: (B, n_mels, T_mel)
mel_lengths: (B,)
"""
B, T_text = text_ids.shape
_, C_mel, T_mel = mel_gt.shape
device = text_ids.device
# 1. Encode text
h_text = self.text_encoder(text_ids, text_lengths) # (B, T_text, text_dim)
# Masks
text_mask = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)
mel_mask = torch.arange(T_mel, device=device).unsqueeze(0) < mel_lengths.unsqueeze(1)
align_mask = text_mask.unsqueeze(2) & mel_mask.unsqueeze(1) # (B, T_text, T_mel)
# 2. Monotonic Alignment Search (MAS) in mel prior space
mu_text = self.prior_proj(h_text) # (B, T_text, mel_dim)
mel_t = mel_gt.transpose(1, 2) # (B, T_mel, mel_dim)
# Negative squared L2 distance (Gaussian log-likelihood up to constant)
with torch.no_grad(), torch.autocast(device.type, enabled=False):
mu_f32 = mu_text.float()
mel_f32 = mel_t.float()
s_mu = (mu_f32 ** 2).sum(dim=-1, keepdim=True) # (B, T_text, 1)
s_mel = (mel_f32 ** 2).sum(dim=-1).unsqueeze(1) # (B, 1, T_mel)
neg_cent = -0.5 * (s_mu + s_mel - 2.0 * torch.bmm(mu_f32, mel_f32.transpose(1, 2)))
align_path = maximum_path(neg_cent, align_mask) # (B, T_text, T_mel)
target_durations = align_path.sum(dim=-1) # (B, T_text)
# Differentiable Mel Prior Loss (trains prior_proj + text_encoder!)
mu_expanded = torch.bmm(mu_text.transpose(1, 2), align_path.to(mu_text.dtype)) # (B, mel_dim, T_mel)
mel_mask_3d = mel_mask.unsqueeze(1).float()
prior_loss = ((mu_expanded - mel_gt) ** 2 * mel_mask_3d).sum() / (
mel_mask_3d.sum() * C_mel
).clamp(min=1.0)
# 3. Duration loss (normalized strictly by valid token count)
log_dur_pred = self.duration_predictor(h_text, text_mask)
target_log_dur = torch.log(torch.clamp(target_durations, min=1.0))
text_mask_f = text_mask.to(log_dur_pred.dtype)
dur_loss = ((log_dur_pred - target_log_dur) ** 2 * text_mask_f).sum() / text_mask_f.sum().clamp(min=1.0)
# 4. Expand text representations to mel length using alignment
cond_mel = torch.bmm(h_text.transpose(1, 2), align_path.to(h_text.dtype)) # (B, C, T_mel)
# 5. Masked Flow Matching Loss (with CFG condition dropout)
cfm_loss = self.cfm.compute_loss(
mel_gt, cond_mel, mel_mask=mel_mask, p_uncond=self.config.p_uncond if self.training else 0.0
)
total_loss = (
self.train_config.cfm_loss_weight * cfm_loss
+ self.train_config.dur_loss_weight * dur_loss
+ self.train_config.prior_loss_weight * prior_loss
)
return {
"total_loss": total_loss,
"cfm_loss": cfm_loss,
"dur_loss": dur_loss,
"prior_loss": prior_loss,
}
@torch.no_grad()
def synthesize(
self,
text_ids: torch.Tensor,
text_lengths: Optional[torch.Tensor] = None,
num_steps: Optional[int] = None,
speed: float = 1.0,
cfg_scale: Optional[float] = None,
temperature: Optional[float] = None,
sway_sampling_coef: Optional[float] = None,
min_frames: int = 2,
return_waveform: bool = True,
generator: Optional[torch.Generator] = None,
) -> Dict[str, torch.Tensor]:
"""
Fast Inference Synthesis.
Solves ODE in 4-10 steps and decodes with Vocos.
text_ids: (B, T_text)
"""
if text_ids.ndim != 2 or text_ids.numel() == 0:
raise ValueError("text_ids must have shape (B, T_text) with T_text > 0.")
if not math.isfinite(speed) or speed <= 0:
raise ValueError(f"speed must be > 0, got {speed}")
self.eval()
B, T_text = text_ids.shape
device = text_ids.device
if text_lengths is not None and (text_lengths.shape != (B,) or text_lengths.device != device):
raise ValueError("text_lengths must have one entry per sequence on the same device.")
if text_lengths is None:
text_mask = text_ids != self.config.pad_token_id
text_lengths = text_mask.sum(dim=1)
else:
text_mask = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)
if ((text_lengths < 1) | (text_lengths > T_text)).any():
raise ValueError("Every sequence must have a valid positive text length.")
valid = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)
if not torch.equal(valid, text_ids != self.config.pad_token_id):
raise ValueError("Sequences must use right padding consistent with text_lengths.")
# 1. Encode text
h_text = self.text_encoder(text_ids, text_lengths=text_lengths) # (B, T_text, C)
# 2. Predict durations
log_dur = self.duration_predictor(h_text, mask=text_mask)
durations = torch.exp(log_dur) / speed
durations = torch.clamp(durations, min=float(max(1, min_frames)))
# 3. Expand text representations respecting text_mask
h_expanded, mel_lengths = expand_by_duration(
h_text, durations, text_mask=text_mask, return_lengths=True, min_frames=min_frames
)
cond = h_expanded.transpose(1, 2) # (B, C, T_mel)
T_mel = cond.shape[-1]
mel_mask = torch.arange(T_mel, device=device).unsqueeze(0) < mel_lengths.unsqueeze(1)
# 4. Solve Flow Matching ODE with Classifier-Free Guidance & Temperature Scaling
steps = num_steps if num_steps is not None else self.config.default_ode_steps
guidance = cfg_scale if cfg_scale is not None else self.config.default_cfg_scale
temp = temperature if temperature is not None else self.config.default_temperature
sway = sway_sampling_coef if sway_sampling_coef is not None else self.config.sway_sampling_coef
mel_pred = self.cfm.sample(
cond,
num_steps=steps,
method=self.config.ode_method,
mel_mask=mel_mask,
cfg_scale=guidance,
temperature=temp,
sway_sampling_coef=sway,
generator=generator,
)
result = {"mel": mel_pred, "mel_lengths": mel_lengths}
# 5. Decode to 24kHz waveform
if return_waveform:
# Vocos has temporal convolutions. Decode each unpadded utterance so
# an unrelated longer batch member cannot change its end or length.
waves = [self.vocoder.decode(mel_pred[i:i+1, :, :length]).squeeze(0)
for i, length in enumerate(mel_lengths.tolist())]
result["waveform_lengths"] = mel_lengths.new_tensor([w.numel() for w in waves])
result["waveform"] = nn.utils.rnn.pad_sequence(waves, batch_first=True)
return result