File size: 10,813 Bytes
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Murli V1.5 Alignment, Duration, Log-F0 Pitch, Energy & ConvNeXt Mel Prior Module.

Fixes V1's flat monotone prosody (5.0/10) and weak nn.Linear prior (Prior Loss ~1.04).

Strictly computes MAS in FP32 with Numba parallel JIT + NumPy fallback.

"""

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), -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."""
    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_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 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 ProsodyAndAlignmentModule(nn.Module):
    """

    Single-speaker expressive Prosody + Alignment module:

    - Emotion embedding (neutral=0, happy, sad, angry, story, etc.)

    - ConvNeXt Mel Prior (replaces V1's weak nn.Linear)

    - Duration + Log-F0 + Energy predictors

    - Prosody projection back into expanded acoustic conditioning

    """

    def __init__(

        self,

        text_dim: int = 320,

        n_mels: int = 100,

        num_emotions: int = 8,

        kernel_size: int = 5,

        num_layers: int = 3,

    ):
        super().__init__()
        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)

        # Injects [log_f0, energy] back into expanded acoustic features [B, T_mel, D]
        self.prosody_proj = nn.Linear(2, text_dim)

    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,

        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]]:
        """

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

        Returns:

            cond_mel: [B, D, T_y] expanded conditioning with F0+Energy+Emotion

            prior_mel: [B, M, T_y] expanded prior mel

            losses: dict with prior_loss, dur_loss, f0_loss, energy_loss

        """
        emo = self.emotion_emb(emotion_ids)  # [B, D]
        text_with_emo = text_feats + emo.unsqueeze(1)
        prior_text = self.compute_prior(text_with_emo, text_mask)  # [B, T_x, M]

        # 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))
            )
            attn_mask = text_mask.unsqueeze(2) & mel_mask.unsqueeze(1)
            attn = maximum_path(-diff2, attn_mask)  # [B, T_x, T_y]

        # Prior loss against aligned target
        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
        )

        # Token-level durations from MAS path
        gt_dur = attn.sum(dim=2)  # [B, T_x]
        gt_log_dur = torch.log(gt_dur.clamp(min=1.0))

        # Average frame-level F0 and Energy per aligned token
        dur_safe = gt_dur.clamp(min=1.0)
        gt_f0_tok = torch.bmm(attn, f0_target.unsqueeze(-1)).squeeze(-1) / dur_safe
        gt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safe

        # Predictors (detach text_with_emo slightly or keep full grad for joint prosody)
        pred_log_dur = self.dur_predictor(text_feats, emo, mask=text_mask)
        pred_f0 = self.f0_predictor(text_feats, emo, mask=text_mask)
        pred_energy = self.energy_predictor(text_feats, emo, mask=text_mask)

        t_mask_f = text_mask.float()
        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") / denom
        f0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / denom
        energy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / denom

        # The acoustic decoder sees the same predicted prosody at training and inference.
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)
        token_cond = text_with_emo + self.prosody_proj(prosody_tok)
        cond = torch.bmm(attn.transpose(1, 2), token_cond)

        return cond.transpose(1, 2), prior_mel, {
            "prior_loss": prior_loss,
            "dur_loss": dur_loss,
            "f0_loss": f0_loss,
            "energy_loss": energy_loss,
        }

    def forward_infer(

        self,

        text_feats: torch.Tensor,

        text_mask: torch.Tensor,

        emotion_ids: torch.Tensor,

        speed: float = 0.92,

        min_frames: int = 2,

    ) -> Tuple[torch.Tensor, torch.Tensor]:
        """Inference expansion (PyTorch eager)."""
        emo = self.emotion_emb(emotion_ids)
        text_with_emo = text_feats + emo.unsqueeze(1)
        prior_text = self.compute_prior(text_with_emo, text_mask)

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

        pred_f0 = self.f0_predictor(text_feats, emo, mask=text_mask)
        pred_energy = self.energy_predictor(text_feats, emo, mask=text_mask)
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)  # [B, T_x, 2]

        token_cond = text_with_emo + self.prosody_proj(prosody_tok)
        cond_expanded = expand_by_durations(token_cond, durs)
        prior_expanded = expand_by_durations(prior_text, durs)
        return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)