Download models/flow_matching.py from ViuAI/TTS_10M: direct link, hf CLI and curl.
- Browser
- Download file 8.85 kB
-
https://huggingface.co/ViuAI/TTS_10M/resolve/main/models/flow_matching.py
- Command line
-
hf download hf://ViuAI/TTS_10M/models/flow_matching.py
-
curl -L -o flow_matching.py https://huggingface.co/ViuAI/TTS_10M/resolve/main/models/flow_matching.py
8.85 kB
| """ | |
| Optimal Transport Conditional Flow Matching (OT-CFM) Engine. | |
| State-of-the-Art Generative Speech Framework (2024-2026). | |
| Straight-line ODE trajectories enable crystal-clear audio synthesis in just 4-10 steps. | |
| """ | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| from typing import Optional | |
| from .convnext import ConvNeXtV2Block1D, ChannelLayerNorm1d | |
| class SinusoidalTimeEmbedding(nn.Module): | |
| """Sinusoidal time-step embeddings for continuous time t in [0, 1].""" | |
| def __init__(self, dim: int): | |
| super().__init__() | |
| self.dim = dim | |
| def forward(self, t: torch.Tensor) -> torch.Tensor: | |
| # t: (B,) | |
| half_dim = self.dim // 2 | |
| emb = math.log(10000) / max(half_dim - 1, 1) | |
| emb = torch.exp(torch.arange(half_dim, device=t.device, dtype=torch.float32) * -emb) | |
| emb = t.float()[:, None] * emb[None, :] | |
| emb = torch.cat((emb.sin(), emb.cos()), dim=-1) | |
| return emb.to(t.dtype) # (B, dim) | |
| class CFMVectorField(nn.Module): | |
| """ | |
| Vector Field Estimator v_theta(x_t, t, condition). | |
| Uses ConvNeXt-V2 1D Backbone (~5.0M params) with time & text conditioning. | |
| """ | |
| def __init__( | |
| self, | |
| mel_dim: int = 100, | |
| cond_dim: int = 256, | |
| hidden_dim: int = 256, | |
| num_blocks: int = 8, | |
| kernel_size: int = 7, | |
| time_dim: int = 128, | |
| ): | |
| super().__init__() | |
| self.mel_dim = mel_dim | |
| self.hidden_dim = hidden_dim | |
| # Time embedding MLP | |
| self.time_embed = nn.Sequential( | |
| SinusoidalTimeEmbedding(time_dim), | |
| nn.Linear(time_dim, hidden_dim), | |
| nn.GELU(), | |
| nn.Linear(hidden_dim, hidden_dim), | |
| ) | |
| # Input projection (Mel + Condition) | |
| self.in_proj = nn.Conv1d(mel_dim + cond_dim, hidden_dim, kernel_size=1) | |
| # ConvNeXt-V2 Blocks with Time Conditioning Projections | |
| self.blocks = nn.ModuleList([ | |
| ConvNeXtV2Block1D(hidden_dim, kernel_size=kernel_size) | |
| for _ in range(num_blocks) | |
| ]) | |
| self.time_projs = nn.ModuleList([ | |
| nn.Linear(hidden_dim, hidden_dim) | |
| for _ in range(num_blocks) | |
| ]) | |
| # Output projection back to Mel dimension (mel_dim channels) | |
| self.final_norm = ChannelLayerNorm1d(hidden_dim) | |
| self.out_proj = nn.Conv1d(hidden_dim, mel_dim, kernel_size=1) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| t: torch.Tensor, | |
| cond: torch.Tensor, | |
| mask: Optional[torch.Tensor] = None, | |
| ) -> torch.Tensor: | |
| """ | |
| x: (B, mel_dim, T) - current noisy state at time t | |
| t: (B,) - continuous time in [0, 1] | |
| cond: (B, cond_dim, T) - expanded text condition | |
| mask: Optional (B, 1, T) float/bool mask | |
| """ | |
| t_emb = self.time_embed(t) # (B, hidden_dim) | |
| feat = torch.cat([x, cond], dim=1) # (B, mel_dim + cond_dim, T) | |
| h = self.in_proj(feat) # (B, hidden_dim, T) | |
| if mask is not None: | |
| h = h * mask | |
| for block, t_proj in zip(self.blocks, self.time_projs): | |
| t_scale = t_proj(t_emb).unsqueeze(-1) # (B, hidden_dim, 1) | |
| h = h + t_scale | |
| h = block(h, mask=mask) | |
| h = self.final_norm(h) | |
| v = self.out_proj(h) # (B, mel_dim, T) | |
| if mask is not None: | |
| v = v * mask | |
| return v | |
| class OptimalTransportCFM(nn.Module): | |
| """ | |
| Optimal Transport Conditional Flow Matching (OT-CFM) Module. | |
| Computes masked training loss and performs ultrafast ODE sampling. | |
| """ | |
| def __init__(self, vector_field: CFMVectorField, sigma_min: float = 1e-4): | |
| super().__init__() | |
| self.vf = vector_field | |
| self.sigma_min = sigma_min | |
| def compute_loss( | |
| self, | |
| x1: torch.Tensor, | |
| cond: torch.Tensor, | |
| mel_mask: Optional[torch.Tensor] = None, | |
| p_uncond: float = 0.0, | |
| ) -> torch.Tensor: | |
| """ | |
| x1: Ground truth target Mel spectrogram (B, mel_dim, T) | |
| cond: Text condition (B, cond_dim, T) | |
| mel_mask: Optional (B, T) bool mask for valid frames | |
| p_uncond: Probability of dropping condition for Classifier-Free Guidance | |
| """ | |
| B, C, T = x1.shape | |
| device = x1.device | |
| mask_3d = mel_mask.unsqueeze(1).to(x1.dtype) if mel_mask is not None else None | |
| # Classifier-Free Guidance: randomly zero condition for p_uncond fraction of batch | |
| if p_uncond > 0.0: | |
| keep_mask = (torch.rand(B, 1, 1, device=device) >= p_uncond).to(cond.dtype) | |
| cond = cond * keep_mask | |
| # 1. Sample continuous time t uniformly in [0, 1] | |
| t = torch.rand(B, device=device, dtype=x1.dtype) | |
| # 2. Sample prior noise x0 ~ N(0, I) | |
| x0 = torch.randn_like(x1) | |
| # 3. Compute OT straight-line trajectory: x_t = (1 - (1 - sigma_min)*t)*x0 + t*x1 | |
| t_expand = t[:, None, None] | |
| xt = (1.0 - (1.0 - self.sigma_min) * t_expand) * x0 + t_expand * x1 | |
| # 4. Target vector field: u_t(x1 | x0) = x1 - (1 - sigma_min)*x0 | |
| ut = x1 - (1.0 - self.sigma_min) * x0 | |
| if mask_3d is not None: | |
| xt = xt * mask_3d | |
| cond = cond * mask_3d | |
| # 5. Predict vector field with neural network | |
| vt = self.vf(xt, t, cond, mask=mask_3d) | |
| # 6. Masked Mean Squared Error (MSE) Loss | |
| sq_err = (vt - ut) ** 2 | |
| if mask_3d is not None: | |
| loss = (sq_err * mask_3d).sum() / (mask_3d.sum() * C).clamp(min=1.0) | |
| else: | |
| loss = sq_err.mean() | |
| return loss | |
| def _eval_vf( | |
| self, | |
| x: torch.Tensor, | |
| t: torch.Tensor, | |
| cond: torch.Tensor, | |
| mask_3d: Optional[torch.Tensor], | |
| cfg_scale: float, | |
| ) -> torch.Tensor: | |
| if cfg_scale == 1.0: | |
| return self.vf(x, t, cond, mask=mask_3d) | |
| x_cat = torch.cat([x, x], dim=0) | |
| t_cat = torch.cat([t, t], dim=0) | |
| cond_cat = torch.cat([torch.zeros_like(cond), cond], dim=0) | |
| mask_cat = torch.cat([mask_3d, mask_3d], dim=0) if mask_3d is not None else None | |
| v_uncond, v_cond = self.vf(x_cat, t_cat, cond_cat, mask=mask_cat).chunk(2, dim=0) | |
| return v_uncond + cfg_scale * (v_cond - v_uncond) | |
| def sample( | |
| self, | |
| cond: torch.Tensor, | |
| num_steps: int = 16, | |
| method: str = "midpoint", | |
| mel_mask: Optional[torch.Tensor] = None, | |
| cfg_scale: float = 1.0, | |
| temperature: float = 0.667, | |
| sway_sampling_coef: float = -1.0, | |
| generator: Optional[torch.Generator] = None, | |
| ) -> torch.Tensor: | |
| """ | |
| Ultrafast ODE sampling from t=0 (noise) to t=1 (mel spectrogram) with optional CFG, | |
| temperature scaling (removes background hiss), and Sway Sampling (F5-TTS). | |
| cond: (B, cond_dim, T) | |
| """ | |
| if not isinstance(num_steps, int) or num_steps < 1 or method not in ("midpoint", "euler"): | |
| raise ValueError("Sampling requires positive integer num_steps and method 'midpoint' or 'euler'.") | |
| if not all(math.isfinite(v) for v in (temperature, cfg_scale, sway_sampling_coef)) or temperature < 0: | |
| raise ValueError("Sampling parameters must be finite and temperature non-negative.") | |
| if not -1.0 <= sway_sampling_coef <= 1.0 / (math.pi / 2.0 - 1.0): | |
| raise ValueError("Sway coefficient would reverse the integration time grid.") | |
| B, _, T = cond.shape | |
| device = cond.device | |
| mask_3d = mel_mask.unsqueeze(1).to(cond.dtype) if mel_mask is not None else None | |
| # Start at scaled noise x0 ~ N(0, temperature^2 * I) | |
| x = torch.randn(B, self.vf.mel_dim, T, device=device, dtype=cond.dtype, generator=generator) * temperature | |
| if mask_3d is not None: | |
| x = x * mask_3d | |
| cond = cond * mask_3d | |
| t_steps = torch.linspace(0.0, 1.0, num_steps + 1, device=device, dtype=cond.dtype) | |
| if sway_sampling_coef != 0.0: | |
| t_steps = t_steps + sway_sampling_coef * (torch.cos(math.pi / 2.0 * t_steps) - 1.0 + t_steps) | |
| for i in range(num_steps): | |
| dt = (t_steps[i + 1] - t_steps[i]).item() | |
| t_curr = t_steps[i].repeat(B) | |
| if method == "midpoint": | |
| v1 = self._eval_vf(x, t_curr, cond, mask_3d, cfg_scale) | |
| x_mid = x + 0.5 * dt * v1 | |
| if mask_3d is not None: | |
| x_mid = x_mid * mask_3d | |
| t_mid = (t_steps[i] + 0.5 * dt).repeat(B) | |
| v2 = self._eval_vf(x_mid, t_mid, cond, mask_3d, cfg_scale) | |
| x = x + dt * v2 | |
| else: | |
| v = self._eval_vf(x, t_curr, cond, mask_3d, cfg_scale) | |
| x = x + dt * v | |
| if mask_3d is not None: | |
| x = x * mask_3d | |
| return x # (B, mel_dim, T) | |