File size: 6,504 Bytes
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Murli V2.0 Optimal Transport Conditional Flow Matching (OT-CFM) + Midpoint/Euler ODE Solver.

Supports Sway Sampling (-1.0) and Classifier-Free Guidance (CFG) for high-fidelity 24kHz synthesis.

"""

from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F


class DiTOptimalTransportCFM(nn.Module):
    """OT-CFM Flow Matching wrapper around DiTVectorField."""

    def __init__(self, vector_field: nn.Module, sigma_min: float = 1e-4, cfg_drop_prob: float = 0.1):
        super().__init__()
        self.vector_field = vector_field
        self.sigma_min = sigma_min
        self.cfg_drop_prob = cfg_drop_prob

    def compute_loss(

        self,

        mel_target: torch.Tensor,

        aligned_text: torch.Tensor,

        aligned_prior: torch.Tensor,

        f0: torch.Tensor,

        energy: torch.Tensor,

        style_tokens: torch.Tensor,

        style_global: torch.Tensor,

        null_style_tokens: torch.Tensor,

        null_style_global: torch.Tensor,

        mel_mask: torch.Tensor,

    ) -> torch.Tensor:
        """

        OT linear flow between standard Gaussian x0 and target mel x1:

          x_t = (1 - (1 - sigma_min) * t) * x0 + t * x1

          u_t = x1 - (1 - sigma_min) * x0

        """
        bsz = mel_target.shape[0]
        device = mel_target.device
        dtype = mel_target.dtype

        t = torch.rand(bsz, device=device, dtype=dtype)
        # Apply Sway-biased training time sampling gently (more steps near t=0 and boundaries)
        t_view = t.view(bsz, 1, 1)

        x0 = torch.randn_like(mel_target)
        x_t = (1.0 - (1.0 - self.sigma_min) * t_view) * x0 + t_view * mel_target
        u_t = mel_target - (1.0 - self.sigma_min) * x0

        # Classifier-Free Guidance random dropout across text + style
        if self.training and self.cfg_drop_prob > 0:
            drop_mask = (torch.rand(bsz, device=device) < self.cfg_drop_prob)
            if drop_mask.any():
                aligned_text = torch.where(drop_mask[:, None, None], torch.zeros_like(aligned_text), aligned_text)
                aligned_prior = torch.where(drop_mask[:, None, None], torch.zeros_like(aligned_prior), aligned_prior)
                f0 = torch.where(drop_mask[:, None], torch.zeros_like(f0), f0)
                energy = torch.where(drop_mask[:, None], torch.zeros_like(energy), energy)
                style_tokens = torch.where(drop_mask[:, None, None], null_style_tokens, style_tokens)
                style_global = torch.where(drop_mask[:, None], null_style_global, style_global)

        v_pred = self.vector_field(
            x_t=x_t,
            t=t,
            aligned_text=aligned_text,
            aligned_prior=aligned_prior,
            f0=f0,
            energy=energy,
            style_tokens=style_tokens,
            style_global=style_global,
            mel_mask=mel_mask,
        )

        # Compute masked MSE strictly in FP32 over valid mel frames
        diff2 = (v_pred.float() - u_t.float()).pow(2) * mel_mask.unsqueeze(1).float()
        denom = (mel_mask.sum().clamp(min=1).float()) * float(mel_target.shape[1])
        return (diff2.sum() / denom).to(mel_target.dtype)

    @torch.no_grad()
    def sample(

        self,

        aligned_text: torch.Tensor,

        aligned_prior: torch.Tensor,

        f0: torch.Tensor,

        energy: torch.Tensor,

        style_tokens: torch.Tensor,

        style_global: torch.Tensor,

        null_style_tokens: torch.Tensor,

        null_style_global: torch.Tensor,

        mel_mask: torch.Tensor,

        num_steps: int = 32,

        method: str = "midpoint",

        cfg_scale: float = 1.8,

        temperature: float = 0.65,

        sway_sampling_coef: float = -1.0,

        generator: Optional[torch.Generator] = None,

    ) -> torch.Tensor:
        """Integrate ODE from noise x0 ~ N(0, temp^2 I) to clean mel spectrogram [B, M, T]."""
        if method not in ("midpoint", "euler"):
            raise ValueError(f"Unsupported solver: {method}")
        if num_steps < 1:
            raise ValueError(f"num_steps must be >= 1, got {num_steps}")

        bsz, n_mels, t_len = aligned_prior.shape
        device = aligned_prior.device
        dtype = aligned_prior.dtype

        x = torch.randn((bsz, n_mels, t_len), device=device, dtype=torch.float32, generator=generator) * temperature

        steps_grid = torch.linspace(0.0, 1.0, num_steps + 1, device=device, dtype=torch.float32)
        if sway_sampling_coef != 0.0:
            steps_grid = steps_grid + sway_sampling_coef * (torch.cos(torch.pi * 0.5 * steps_grid) - 1.0 + steps_grid)
            steps_grid = steps_grid.clamp(0.0, 1.0)
            steps_grid[0], steps_grid[-1] = 0.0, 1.0

        def velocity_cfg(x_cur: torch.Tensor, t_scalar: torch.Tensor) -> torch.Tensor:
            t_vec = t_scalar.to(dtype).expand(bsz)
            x_in = x_cur.to(dtype)
            v_cond = self.vector_field(
                x_t=x_in,
                t=t_vec,
                aligned_text=aligned_text,
                aligned_prior=aligned_prior,
                f0=f0,
                energy=energy,
                style_tokens=style_tokens,
                style_global=style_global,
                mel_mask=mel_mask,
            )
            if cfg_scale == 1.0:
                return v_cond.float()
            v_uncond = self.vector_field(
                x_t=x_in,
                t=t_vec,
                aligned_text=torch.zeros_like(aligned_text),
                aligned_prior=torch.zeros_like(aligned_prior),
                f0=torch.zeros_like(f0),
                energy=torch.zeros_like(energy),
                style_tokens=null_style_tokens,
                style_global=null_style_global,
                mel_mask=mel_mask,
            )
            return (v_uncond + cfg_scale * (v_cond - v_uncond)).float()

        for i in range(num_steps):
            t0 = steps_grid[i]
            t1 = steps_grid[i + 1]
            dt = t1 - t0
            if method == "midpoint" and i < num_steps - 1:
                v0 = velocity_cfg(x, t0)
                x_mid = x + 0.5 * dt * v0
                v_mid = velocity_cfg(x_mid, t0 + 0.5 * dt)
                x = x + dt * v_mid
            else:
                v0 = velocity_cfg(x, t0)
                x = x + dt * v0

        return (x * mel_mask.unsqueeze(1).float()).to(dtype)