"""Trà Đá TTS network (inference only). Text (characters + tone stream) -> ConvNeXt encoder -> per-token duration -> frame-level condition -> conditional flow matching (CFM) over a 32-d, 25 Hz audio latent -> Vocos-style iSTFT decoder -> 24 kHz audio. All three parts take a 192-d CAM++ speaker embedding (the raw, un-normalised one).""" import math import torch import torch.nn as nn import torch.nn.functional as F SPK_DIM = 192 SPK_FEAT = 64 class ConvNeXtBlock(nn.Module): def __init__(self, dim, mult=3, cond_dim=0): super().__init__() self.dw = nn.Conv1d(dim, dim, 7, padding=3, groups=dim) self.norm = nn.LayerNorm(dim) self.pw1 = nn.Linear(dim, dim * mult) self.act = nn.GELU() self.pw2 = nn.Linear(dim * mult, dim) self.gamma = nn.Parameter(torch.ones(dim)) self.cond = nn.Linear(cond_dim, dim) if cond_dim else None def forward(self, x, c=None): # x [B,C,T], c [B,cond_dim] r = x x = self.norm(self.dw(x).transpose(1, 2)) x = (self.gamma * self.pw2(self.act(self.pw1(x)))).transpose(1, 2) if self.cond is not None and c is not None: x = x + self.cond(c).unsqueeze(-1) return r + x class TextEncoder(nn.Module): def __init__(self, n_symbols, n_tones, dim, n_blocks): super().__init__() self.emb = nn.Embedding(n_symbols, dim) self.tone_emb = nn.Embedding(n_tones, dim) self.blocks = nn.ModuleList([ConvNeXtBlock(dim, cond_dim=SPK_DIM) for _ in range(n_blocks)]) self.norm = nn.LayerNorm(dim) def forward(self, ids, tones, spk): # [B,N] -> [B,dim,N] x = (self.emb(ids) + self.tone_emb(tones)).transpose(1, 2) for b in self.blocks: x = b(x, spk) return self.norm(x.transpose(1, 2)).transpose(1, 2) class DurationPredictor(nn.Module): def __init__(self, dim, hid=160): super().__init__() self.spk = nn.Linear(SPK_DIM, dim) self.net = nn.Sequential(nn.Conv1d(dim, hid, 3, padding=1), nn.GELU(), nn.Dropout(0.0), nn.Conv1d(hid, hid, 3, padding=1), nn.GELU(), nn.Dropout(0.0), nn.Conv1d(hid, 1, 1)) def forward(self, h, spk): # -> log(1 + frames) per token [B,N] return self.net(h + self.spk(spk).unsqueeze(-1)).squeeze(1) def timestep_embed(t, dim=128): half = dim // 2 freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half) a = t[:, None] * freqs[None] return torch.cat([a.sin(), a.cos()], -1) class FlowDecoder(nn.Module): """Velocity network v(x_t, cond, t, spk) over the normalised latent. With interval=True (the 2-step "fast" model, IntMeanFlow-distilled) it also takes the end time r and predicts the AVERAGE velocity over [t, r], CFG baked in.""" def __init__(self, latent_dim, cond_dim, dim, n_blocks, interval=False): super().__init__() self.rmlp = nn.Sequential(nn.Linear(128, dim), nn.GELU(), nn.Linear(dim, dim)) if interval else None self.spk_in = nn.Linear(SPK_DIM, SPK_FEAT) self.inp = nn.Conv1d(latent_dim + cond_dim + SPK_FEAT, dim, 1) self.tmlp = nn.Sequential(nn.Linear(128, dim), nn.GELU(), nn.Linear(dim, dim)) self.spk_g = nn.Linear(SPK_DIM, dim) self.film = nn.Linear(SPK_DIM, 2 * dim) self.blocks = nn.ModuleList([ConvNeXtBlock(dim, cond_dim=dim) for _ in range(n_blocks)]) self.norm = nn.LayerNorm(dim) self.out = nn.Conv1d(dim, latent_dim, 1) def forward(self, xt, cond, t, spk, r=None): T = xt.size(-1) x = self.inp(torch.cat([xt, cond, self.spk_in(spk).unsqueeze(-1).expand(-1, -1, T)], 1)) scale, shift = self.film(spk).chunk(2, -1) x = x * (1 + scale).unsqueeze(-1) + shift.unsqueeze(-1) g = self.tmlp(timestep_embed(t)) + self.spk_g(spk) if self.rmlp is not None and r is not None: g = g + self.rmlp(timestep_embed(r)) for b in self.blocks: x = b(x, g) return self.out(self.norm(x.transpose(1, 2)).transpose(1, 2)) class ISTFTHead(nn.Module): def __init__(self, dim, n_fft): super().__init__() self.out = nn.Conv1d(dim, 2 * (n_fft // 2 + 1), 1) def forward(self, x): # -> magnitude, phase [B,F,T50] mag, phase = self.out(x).chunk(2, dim=1) return torch.exp(mag).clamp(max=1e2), phase class LatentDecoder(nn.Module): """32-d latent @25 Hz -> magnitude/phase @50 Hz (iSTFT n_fft 1920, hop 480 -> 24 kHz).""" def __init__(self, latent_dim, dim, n_blocks, n_fft): super().__init__() self.inp = nn.Conv1d(latent_dim, dim, 7, padding=3) self.up = nn.ConvTranspose1d(dim, dim, 4, stride=2, padding=1) self.blocks = nn.ModuleList([ConvNeXtBlock(dim) for _ in range(n_blocks)]) self.norm = nn.LayerNorm(dim) self.head = ISTFTHead(dim, n_fft) def forward(self, z): x = F.gelu(self.up(self.inp(z))) for b in self.blocks: x = b(x) return self.head(self.norm(x.transpose(1, 2)).transpose(1, 2)) class TradaTTSModel(nn.Module): def __init__(self, n_symbols, n_tones, latent_dim=32, enc_dim=256, enc_blocks=5, cfm_dim=352, cfm_blocks=6, dec_dim=160, dec_blocks=7, n_fft=1920, **_): super().__init__() self.enc = TextEncoder(n_symbols, n_tones, enc_dim, enc_blocks) self.dur = DurationPredictor(enc_dim) self.cfm = FlowDecoder(latent_dim, enc_dim, cfm_dim, cfm_blocks) self.decoder = LatentDecoder(latent_dim, dec_dim, dec_blocks, n_fft) self.register_buffer("latent_mean", torch.zeros(1, latent_dim, 1)) self.register_buffer("latent_std", torch.ones(1, latent_dim, 1)) def velocity_cfg(self, x, cond, t, spk, w): """Classifier-free guidance on the text condition: one batch-2 pass (cond / no-text).""" v = self.cfm(torch.cat([x, x]), torch.cat([cond, torch.zeros_like(cond)]), torch.cat([t, t]), torch.cat([spk, spk])) vc, vu = v[:1], v[1:] return vu + w * (vc - vu) def decode(self, z): """normalised latent -> magnitude, phase""" return self.decoder(z * self.latent_std + self.latent_mean)