File size: 12,460 Bytes
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
 
 
 
 
870eedf
 
42e63f8
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
8d10455
 
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
8d10455
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
 
870eedf
 
 
 
8d10455
 
870eedf
 
 
 
 
 
 
 
8d10455
 
 
870eedf
 
 
8d10455
 
 
 
 
870eedf
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
Murli V1.6 Alignment, Duration, Smooth Frame-Level F0 Pitch & Energy, and ConvNeXt Mel Prior.
Fixes V1.5's flat token-constant pitch staircase via a frame-level prosody refinement net,
and cleanly separates 3 studio voices (2 Male + 1 Female) via SpeakerEmbedding.
"""

from typing import Dict, 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), -np.inf, 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."""
    return _maximum_path_lengths(value, mask[:, :, 0].bool().sum(1), mask[:, 0, :].bool().sum(1))


def _maximum_path_lengths(value, text_lengths, mel_lengths):
    bsz = value.size(0)
    val_np = value.detach().float().cpu().numpy()
    path = np.zeros_like(val_np, dtype=np.float32)
    t_xs, t_ys = torch.stack((text_lengths, mel_lengths)).long().cpu().numpy()
    if np.any(t_xs <= 0) or np.any(t_ys <= 0) or np.any(t_xs > t_ys):
        raise ValueError("Each sample needs at least one token and at least one mel frame per token")

    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 and 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] 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):
    """ConvNeXt-V2 predictor for Duration, Log-F0 Pitch, and 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, cond_emb: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        h = x + cond_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 FrameProsodyRefiner(nn.Module):
    """Smooths expanded token F0/Energy into continuous frame-level pitch & energy contours."""

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

    def forward(
        self,
        expanded_h: torch.Tensor,
        coarse_prosody: torch.Tensor,
        prosody_proj: nn.Linear,
        mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        h = expanded_h + prosody_proj(coarse_prosody)
        for blk in self.blocks:
            h = blk(h, mask=mask)
        refined = coarse_prosody + self.head(h)
        if mask is not None:
            refined = refined * mask.unsqueeze(-1).to(refined.dtype)
        return refined


class ProsodyAndAlignmentModule(nn.Module):
    """
    Multi-speaker Expressive Prosody + Alignment module:
    - SpeakerEmbedding (0=SYSPIN Male, 1=Rasa Male, 2=IISc Female) + EmotionEmbedding
    - ConvNeXt Mel Prior + FP32 MAS
    - Token Duration / F0 / Energy predictors + FrameProsodyRefiner (no flat pitch staircase!)
    """

    def __init__(
        self,
        text_dim: int = 320,
        n_mels: int = 100,
        num_speakers: int = 4,
        num_emotions: int = 8,
        kernel_size: int = 5,
        num_layers: int = 3,
    ):
        super().__init__()
        self.speaker_emb = nn.Embedding(num_speakers, text_dim)
        self.emotion_emb = nn.Embedding(num_emotions, text_dim)

        self.prior_conv = ConvNeXt1DBlock(text_dim, kernel_size=5, mult=2)
        self.prior_linear = nn.Linear(text_dim, n_mels)

        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)

        self.prosody_proj = nn.Linear(2, text_dim)
        self.frame_prosody_net = FrameProsodyRefiner(text_dim, kernel_size=kernel_size)

    def compute_prior(self, text_with_style: torch.Tensor, text_mask: torch.Tensor) -> torch.Tensor:
        h = self.prior_conv(text_with_style, 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,
        speaker_ids: torch.Tensor,
        emotion_ids: torch.Tensor,
        mel_target: torch.Tensor,
        mel_mask: torch.Tensor,
        f0_target: torch.Tensor,
        energy_target: torch.Tensor,
    ) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, torch.Tensor]]:
        style = self.speaker_emb(speaker_ids) + self.emotion_emb(emotion_ids)  # [B, D]
        text_with_style = text_feats + style.unsqueeze(1)
        prior_text = self.compute_prior(text_with_style, text_mask)  # [B, T_x, M]

        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()
            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))
            )
            attn = _maximum_path_lengths(-diff2, text_mask.sum(1), mel_mask.sum(1))

        prior_mel = torch.bmm(attn.transpose(1, 2), prior_text).transpose(1, 2)  # [B, M, T_y]
        mel_mask_3d = mel_mask.unsqueeze(1).float()
        prior_loss = F.l1_loss(prior_mel * mel_mask_3d, mel_target * mel_mask_3d, reduction="sum") / (
            mel_mask_3d.sum() * mel_target.shape[1] + 1e-6
        )

        gt_dur = attn.sum(dim=2)
        gt_log_dur = torch.log(gt_dur.clamp(min=1.0))

        dur_safe = gt_dur.clamp(min=1.0)
        # Average F0 over voiced frames only so unvoiced frames inside a token do not drag pitch down
        vuv = (f0_target > 0.05).float()
        vuv_tok = torch.bmm(attn, vuv.unsqueeze(-1)).squeeze(-1).clamp(min=1.0)
        gt_f0_tok = torch.bmm(attn, (f0_target * vuv).unsqueeze(-1)).squeeze(-1) / vuv_tok
        gt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safe

        pred_log_dur = self.dur_predictor(text_feats, style, mask=text_mask)
        pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)
        pred_energy = self.energy_predictor(text_feats, style, mask=text_mask)

        t_mask_f = text_mask.float()
        t_denom = t_mask_f.sum().clamp(min=1.0)
        dur_loss = F.mse_loss(pred_log_dur * t_mask_f, gt_log_dur * t_mask_f, reduction="sum") / t_denom
        f0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / t_denom
        energy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / t_denom

        # Expand detached coarse prosody predictions and refine smoothly at frame resolution
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1).detach()  # [B, T_x, 2]
        expanded_h = torch.bmm(attn.transpose(1, 2), text_with_style)
        coarse_frame_prosody = torch.bmm(attn.transpose(1, 2), prosody_tok)
        refined_frame_prosody = self.frame_prosody_net(
            expanded_h, coarse_frame_prosody, self.prosody_proj, mask=mel_mask
        )

        target_frame_prosody = torch.stack([f0_target, energy_target], dim=-1)
        m_mask_2d = mel_mask.unsqueeze(-1).float()
        frame_prosody_loss = F.l1_loss(
            refined_frame_prosody * m_mask_2d, target_frame_prosody * m_mask_2d, reduction="sum"
        ) / (m_mask_2d.sum() * 2.0 + 1e-6)

        cond = (expanded_h + self.prosody_proj(refined_frame_prosody)) * mel_mask.unsqueeze(-1).to(expanded_h.dtype)
        return cond.transpose(1, 2), prior_mel, {
            "prior_loss": prior_loss,
            "dur_loss": dur_loss,
            "f0_loss": f0_loss,
            "energy_loss": energy_loss,
            "frame_prosody_loss": frame_prosody_loss,
        }

    def forward_infer(
        self,
        text_feats: torch.Tensor,
        text_mask: torch.Tensor,
        speaker_ids: torch.Tensor,
        emotion_ids: torch.Tensor,
        speed: float = 0.92,
        min_frames: int = 2,
        return_mask: bool = False,
    ):
        style = self.speaker_emb(speaker_ids) + self.emotion_emb(emotion_ids)
        text_with_style = text_feats + style.unsqueeze(1)
        prior_text = self.compute_prior(text_with_style, text_mask)

        log_dur = self.dur_predictor(text_feats, style, mask=text_mask).clamp(max=10.0)
        durs = torch.clamp(torch.round(torch.exp(log_dur) / max(speed, 1e-3)), min=min_frames, max=250).long()
        durs = durs * text_mask.long()

        pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)
        pred_energy = self.energy_predictor(text_feats, style, mask=text_mask)
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)

        expanded_h = expand_by_durations(text_with_style, durs)
        coarse_frame_prosody = expand_by_durations(prosody_tok, durs)
        mel_lengths = durs.sum(dim=1)
        t_mel = expanded_h.shape[1]
        mel_mask = torch.arange(t_mel, device=expanded_h.device).unsqueeze(0) < mel_lengths.unsqueeze(1)
        refined_frame_prosody = self.frame_prosody_net(
            expanded_h, coarse_frame_prosody, self.prosody_proj, mask=mel_mask
        )
        m_f = mel_mask.unsqueeze(-1).to(expanded_h.dtype)
        cond_expanded = (expanded_h + self.prosody_proj(refined_frame_prosody)) * m_f
        prior_expanded = expand_by_durations(prior_text, durs, max_len=t_mel) * m_f
        if return_mask:
            return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2), mel_mask
        return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)