File size: 8,847 Bytes
5be0f71
 
b62c0da
5be0f71
 
 
 
 
 
b62c0da
 
 
5be0f71
 
 
 
 
 
 
 
 
 
 
b62c0da
5be0f71
b62c0da
5be0f71
b62c0da
5be0f71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b62c0da
5be0f71
 
 
 
 
 
 
b62c0da
5be0f71
 
b62c0da
5be0f71
 
 
 
 
 
 
 
 
b62c0da
 
 
5be0f71
 
b62c0da
 
 
 
 
 
 
5be0f71
b62c0da
5be0f71
 
b62c0da
5be0f71
 
b62c0da
 
5be0f71
b62c0da
 
 
5be0f71
 
 
b62c0da
 
5be0f71
b62c0da
 
 
5be0f71
 
 
 
 
 
b62c0da
5be0f71
 
 
 
 
 
b62c0da
 
 
 
 
e12ee9f
b62c0da
5be0f71
b62c0da
5be0f71
b62c0da
e12ee9f
5be0f71
 
 
b62c0da
 
 
e12ee9f
 
 
 
 
5be0f71
 
b62c0da
5be0f71
 
b62c0da
5be0f71
 
 
b62c0da
5be0f71
 
b62c0da
 
 
 
 
5be0f71
b62c0da
 
 
 
 
 
 
 
5be0f71
 
e12ee9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5be0f71
 
 
 
e12ee9f
5be0f71
b62c0da
e12ee9f
09457d0
 
79b2661
5be0f71
 
09457d0
 
5be0f71
 
79b2661
 
 
 
 
 
5be0f71
 
b62c0da
 
09457d0
79b2661
b62c0da
 
 
 
 
09457d0
 
b62c0da
5be0f71
09457d0
5be0f71
b62c0da
5be0f71
e12ee9f
5be0f71
b62c0da
 
5be0f71
e12ee9f
5be0f71
 
e12ee9f
5be0f71
b62c0da
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
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)

    @torch.no_grad()
    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)