File size: 11,720 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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""

Murli V2.0 Alignment, Duration, Pitch (F0), Energy & Mel Prior Module.

Strictly computes Monotonic Alignment Search (MAS) scores in FP32 to prevent overflow/underflow.

Explicit F0 & Energy predictors fix V1's flat monotone storytelling prosody.

"""

from typing import Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from models.layers import ConvNeXt1DBlock

try:
    from numba import njit, prange
except ImportError:
    njit = None
    prange = range


if njit is not None:
    @njit(parallel=True, cache=True)
    def _mas_batch_numba(path, val_np, t_xs, t_ys):
        for b in prange(val_np.shape[0]):
            tx = t_xs[b]
            ty = t_ys[b]
            q = np.full((tx, ty), -1e9, dtype=np.float32)
            q[0, 0] = val_np[b, 0, 0]
            for y in range(1, ty):
                lo = max(0, tx - (ty - y))
                hi = min(tx, y + 1)
                for x in range(lo, hi):
                    best = q[x, y - 1]
                    if x > 0 and q[x - 1, y - 1] > best:
                        best = q[x - 1, y - 1]
                    q[x, y] = best + val_np[b, x, y]
            x_cur = tx - 1
            for y in range(ty - 1, -1, -1):
                path[b, x_cur, y] = 1.0
                if x_cur > 0 and y > 0 and q[x_cur - 1, y - 1] >= q[x_cur, y - 1]:
                    x_cur -= 1
else:
    _mas_batch_numba = None


def maximum_path(value: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
    """

    Monotonic Alignment Search (MAS) strictly in FP32.

    Uses Numba parallel JIT when available with vectorized NumPy fallback.

    """
    bsz, _, _ = value.shape
    mask_bool = mask.bool()
    val_np = value.detach().float().cpu().numpy()
    mask_np = mask_bool.cpu().numpy()
    path = np.zeros_like(val_np, dtype=np.float32)

    t_xs = np.empty(bsz, dtype=np.int64)
    t_ys = np.empty(bsz, dtype=np.int64)
    for b in range(bsz):
        tx = int(mask_np[b, :, 0].sum()) if mask_np[b].any() else 0
        ty = int(mask_np[b, 0, :].sum()) if mask_np[b].any() else 0
        if tx <= 0 or ty <= 0 or tx > ty:
            raise ValueError(f"Sequence (T_text={tx}, T_mel={ty}) cannot be aligned monotonically (T_text > T_mel or empty).")
        t_xs[b] = tx
        t_ys[b] = ty

    if _mas_batch_numba is not None:
        _mas_batch_numba(path, val_np, t_xs, t_ys)
    else:
        for b in range(bsz):
            tx, ty = int(t_xs[b]), int(t_ys[b])
            v = val_np[b, :tx, :ty]
            q = np.full((tx, ty), -np.inf, dtype=np.float32)
            q[0, 0] = v[0, 0]
            for y in range(1, ty):
                lo, hi = max(0, tx - (ty - y)), min(tx, y + 1)
                stay = q[lo:hi, y - 1].copy()
                first_step = max(lo, 1)
                stay[first_step - lo :] = np.maximum(stay[first_step - lo :], q[first_step - 1 : hi - 1, y - 1])
                q[lo:hi, y] = stay + v[lo:hi, y]

            x_cur = tx - 1
            for y in range(ty - 1, -1, -1):
                path[b, x_cur, y] = 1.0
                if x_cur > 0 and y > 0:
                    if q[x_cur - 1, y - 1] >= q[x_cur, y - 1]:
                        x_cur -= 1

    return torch.from_numpy(path).to(value.device)


def expand_by_durations(hidden: torch.Tensor, durations: torch.Tensor, max_len: Optional[int] = None) -> torch.Tensor:
    """

    Expand [B, T_text, D] hidden features cleanly into [B, T_mel, D] using integer durations [B, T_text].

    """
    bsz, _, dim = hidden.shape
    d_int = durations.long().clamp(min=0)
    lengths = d_int.sum(dim=1)
    t_mel = max_len if max_len is not None else int(lengths.max().item())
    out = hidden.new_zeros(bsz, t_mel, dim)
    for b in range(bsz):
        expanded = torch.repeat_interleave(hidden[b], d_int[b], dim=0)
        keep = min(expanded.shape[0], t_mel)
        if keep > 0:
            out[b, :keep] = expanded[:keep]
    return out


class ScalarPredictor(nn.Module):
    """Predicts per-token or per-frame scalar curves (Duration, F0 pitch, Energy)."""

    def __init__(self, dim: int, kernel_size: int = 5, num_layers: int = 3):
        super().__init__()
        self.blocks = nn.ModuleList([ConvNeXt1DBlock(dim, kernel_size=kernel_size, mult=2) for _ in range(num_layers)])
        self.head = nn.Linear(dim, 1)

    def forward(self, x: torch.Tensor, style_emb: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        h = x + style_emb.unsqueeze(1)
        for blk in self.blocks:
            h = blk(h, mask=mask)
        out = self.head(h).squeeze(-1)
        if mask is not None:
            out = out * mask.to(out.dtype)
        return out


class ProsodyAndAlignmentModule(nn.Module):
    """

    Joint Duration, F0 Pitch, Energy, and Mel Prior module for Murli V2.0.

    Uses FP32 MAS alignment + style-conditioned ConvNeXt predictors.

    """

    def __init__(

        self,

        text_dim: int = 384,

        style_dim: int = 384,

        n_mels: int = 100,

        kernel_size: int = 5,

        num_layers: int = 4,

    ):
        super().__init__()
        self.prior_proj = nn.Sequential(
            ConvNeXt1DBlock(text_dim, kernel_size=5, mult=2),
            nn.Linear(text_dim, n_mels),
        )

        self.style_to_text = nn.Linear(style_dim, text_dim)
        self.dur_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)
        self.f0_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)
        self.energy_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)

    @property
    def prior_conv(self):
        return self.prior_proj[0]

    @property
    def prior_linear(self):
        return self.prior_proj[1]

    def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys,

                              unexpected_keys, error_msgs):
        for alias, target in (("prior_conv.", "prior_proj.0."), ("prior_linear.", "prior_proj.1.")):
            for key in list(state_dict):
                if key.startswith(prefix + alias):
                    canonical = prefix + target + key[len(prefix + alias):]
                    old = state_dict.pop(key)
                    if canonical in state_dict and not torch.equal(state_dict[canonical], old):
                        error_msgs.append(f"Inconsistent checkpoint aliases {key} and {canonical}")
                    state_dict.setdefault(canonical, old)
        super()._load_from_state_dict(state_dict, prefix, local_metadata, strict,
                                      missing_keys, unexpected_keys, error_msgs)

    def compute_prior(self, text_feats: torch.Tensor, text_mask: torch.Tensor) -> torch.Tensor:
        h = self.prior_conv(text_feats, mask=text_mask)
        return self.prior_linear(h) * text_mask.unsqueeze(-1).to(h.dtype)

    def forward_train(

        self,

        text_feats: torch.Tensor,

        text_mask: torch.Tensor,

        style_global: torch.Tensor,

        mel_target: torch.Tensor,

        mel_mask: torch.Tensor,

        f0_target: Optional[torch.Tensor] = None,

        energy_target: Optional[torch.Tensor] = None,

    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, dict]:
        """

        Aligns text_feats [B, T_x, D] with mel_target [B, M, T_y] via FP32 MAS,

        and computes duration, prior, F0, and energy supervision losses.

        """
        prior_text = self.compute_prior(text_feats, text_mask)  # [B, T_x, M]
        style_cond = self.style_to_text(style_global)

        # FP32 negative L2 distance score matrix [B, T_x, T_y]
        with torch.no_grad(), torch.autocast(device_type=mel_target.device.type, enabled=False):
            p_fp32 = prior_text.float()
            m_fp32 = mel_target.transpose(1, 2).float()  # [B, T_y, M]
            diff2 = (
                p_fp32.pow(2).sum(dim=-1, keepdim=True)
                + m_fp32.pow(2).sum(dim=-1).unsqueeze(1)
                - 2.0 * torch.bmm(p_fp32, m_fp32.transpose(1, 2))
            )
            joint_mask = text_mask.unsqueeze(-1) & mel_mask.unsqueeze(1)
            attn = maximum_path(-0.5 * diff2, joint_mask)  # [B, T_x, T_y]

        target_durs = attn.sum(dim=-1)  # [B, T_x]
        log_dur_pred = self.dur_predictor(text_feats, style_cond, mask=text_mask)
        log_dur_tgt = torch.log1p(target_durs.clamp(min=0.0))
        dur_loss = F.smooth_l1_loss(log_dur_pred[text_mask], log_dur_tgt[text_mask])

        # Expand aligned text features & mel prior to frame level [B, T_y, ...]
        aligned_text = torch.bmm(attn.transpose(1, 2), text_feats)
        aligned_prior = torch.bmm(attn.transpose(1, 2), prior_text).transpose(1, 2)  # [B, M, T_y]
        prior_loss = F.l1_loss(aligned_prior.transpose(1, 2)[mel_mask], mel_target.transpose(1, 2)[mel_mask])

        # Frame-level Pitch (log F0) & Energy predictors from aligned text + style
        pred_f0 = self.f0_predictor(aligned_text, style_cond, mask=mel_mask)
        pred_energy = self.energy_predictor(aligned_text, style_cond, mask=mel_mask)

        if f0_target is not None:
            f0_loss = F.smooth_l1_loss(pred_f0[mel_mask], f0_target[mel_mask])
        else:
            f0_loss = pred_f0.new_zeros(())

        if energy_target is not None:
            energy_loss = F.smooth_l1_loss(pred_energy[mel_mask], energy_target[mel_mask])
        else:
            energy_loss = pred_energy.new_zeros(())

        losses = {
            "dur_loss": dur_loss,
            "prior_loss": prior_loss,
            "f0_loss": f0_loss,
            "energy_loss": energy_loss,
        }
        return aligned_text, aligned_prior, pred_f0, pred_energy, losses

    @torch.no_grad()
    def infer_expand(

        self,

        text_feats: torch.Tensor,

        text_mask: torch.Tensor,

        style_global: torch.Tensor,

        speed: float = 1.0,

        min_frames: int = 2,

        pitch_shift: float = 0.0,

        energy_scale: float = 1.0,

    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        """Predict durations, expand text + prior, and predict frame F0 & energy for synthesis."""
        style_cond = self.style_to_text(style_global)
        log_durs = self.dur_predictor(text_feats, style_cond, mask=text_mask)
        if speed <= 0 or not np.isfinite(speed) or min_frames < 1:
            raise ValueError("speed must be positive and min_frames at least one")
        if not torch.isfinite(log_durs).all():
            raise ValueError("Model predicted nonfinite durations")
        durs = (torch.expm1(log_durs).clamp(min=0.0) / max(speed, 1e-3)).round().long()
        durs = torch.where(text_mask, durs.clamp(min=min_frames), torch.zeros_like(durs))

        mel_lens = durs.sum(dim=1)
        max_mel = int(mel_lens.max().item())
        mel_mask = torch.arange(max_mel, device=text_feats.device).unsqueeze(0) < mel_lens.unsqueeze(1)

        prior_text = self.compute_prior(text_feats, text_mask)
        aligned_text = expand_by_durations(text_feats, durs, max_len=max_mel)
        aligned_prior = expand_by_durations(prior_text, durs, max_len=max_mel).transpose(1, 2)

        pred_f0 = self.f0_predictor(aligned_text, style_cond, mask=mel_mask) + pitch_shift
        pred_energy = self.energy_predictor(aligned_text, style_cond, mask=mel_mask) * energy_scale
        return aligned_text, aligned_prior, pred_f0, pred_energy, mel_mask