File size: 6,871 Bytes
5be0f71
 
b62c0da
5be0f71
 
b62c0da
5be0f71
 
b62c0da
 
 
5be0f71
2bfb9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5be0f71
 
 
b62c0da
 
 
 
5be0f71
 
 
b62c0da
2bfb9e5
b62c0da
 
 
 
 
2bfb9e5
 
5be0f71
b62c0da
 
79b2661
 
2bfb9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b62c0da
2bfb9e5
 
 
 
 
b62c0da
 
5be0f71
 
 
 
b62c0da
5be0f71
 
 
 
 
b62c0da
5be0f71
 
b62c0da
5be0f71
b62c0da
5be0f71
 
b62c0da
5be0f71
 
b62c0da
 
5be0f71
b62c0da
 
 
 
5be0f71
b62c0da
 
5be0f71
b62c0da
 
 
5be0f71
 
 
 
 
 
b62c0da
 
 
 
 
395c268
b62c0da
5be0f71
 
 
b62c0da
395c268
5be0f71
 
 
b62c0da
 
5be0f71
b62c0da
79b2661
 
b62c0da
 
 
 
 
 
 
79b2661
 
 
 
 
 
b62c0da
 
5be0f71
b62c0da
 
 
5be0f71
 
b62c0da
 
 
 
 
5be0f71
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
"""
Monotonic Alignment Search (MAS) & Duration Predictor.
Guarantees strictly monotonic text-to-audio alignment without padding corruption.
"""

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

from .convnext import ChannelLayerNorm1d

try:
    from numba import njit, prange
    _HAS_NUMBA = True
except ImportError:
    _HAS_NUMBA = False


if _HAS_NUMBA:
    @njit(parallel=True, cache=True)
    def _maximum_path_numba(path_np, neg_cent_np, t_lens, m_lens):
        B = neg_cent_np.shape[0]
        for b in prange(B):
            t_len = t_lens[b]
            m_len = m_lens[b]
            value = np.full((t_len, m_len), -np.inf, dtype=np.float32)
            value[0, 0] = neg_cent_np[b, 0, 0]
            for t in range(1, m_len):
                s_max = min(t + 1, t_len)
                for s in range(s_max):
                    v_stay = value[s, t - 1]
                    v_prev = value[s - 1, t - 1] if s > 0 else -np.inf
                    v_best = v_stay if v_stay >= v_prev else v_prev
                    value[s, t] = v_best + neg_cent_np[b, s, t]
            s = t_len - 1
            for t in range(m_len - 1, -1, -1):
                path_np[b, s, t] = 1.0
                if s > 0 and (t == 0 or value[s - 1, t - 1] >= value[s, t - 1]):
                    s -= 1


def maximum_path(neg_cent: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
    """
    Monotonic Alignment Search (Dynamic Programming) on valid unpadded sub-matrices.
    neg_cent: (B, T_text, T_mel) log-likelihood / negative distance between text & mel frames
    mask: (B, T_text, T_mel) binary/bool mask indicating valid (non-padded) positions
    Returns: hard alignment matrix (B, T_text, T_mel) with 1s strictly on valid frames.
    """
    device = neg_cent.device
    dtype = neg_cent.dtype

    neg_cent_np = np.ascontiguousarray(neg_cent.detach().float().cpu().numpy())
    mask_np = mask.detach().cpu().numpy() > 0

    B, T_text, T_mel = neg_cent_np.shape
    path_np = np.zeros((B, T_text, T_mel), dtype=np.float32)

    t_lens = np.empty(B, dtype=np.int64)
    m_lens = np.empty(B, dtype=np.int64)
    for b in range(B):
        t_len = int(mask_np[b, :, 0].sum()) if T_mel > 0 else 0
        m_len = int(mask_np[b, 0, :].sum()) if T_text > 0 else 0
        if t_len <= 0 or m_len < t_len:
            raise ValueError(f"Sample {b} cannot be aligned: {t_len} tokens and {m_len} mel frames.")
        t_lens[b] = t_len
        m_lens[b] = m_len

    if _HAS_NUMBA and B > 0:
        _maximum_path_numba(path_np, neg_cent_np, t_lens, m_lens)
    else:
        for b in range(B):
            t_len = int(t_lens[b])
            m_len = int(m_lens[b])
            cent = neg_cent_np[b, :t_len, :m_len]
            value = np.full((t_len, m_len), -np.inf, dtype=np.float32)
            value[0, 0] = cent[0, 0]

            for t in range(1, m_len):
                s_max = min(t + 1, t_len)
                v_stay = value[:s_max, t - 1]
                v_prev = np.empty(s_max, dtype=np.float32)
                v_prev[0] = -np.inf
                if s_max > 1:
                    v_prev[1:] = value[: s_max - 1, t - 1]
                value[:s_max, t] = np.maximum(v_stay, v_prev) + cent[:s_max, t]

            s = t_len - 1
            for t in range(m_len - 1, -1, -1):
                path_np[b, s, t] = 1.0
                if s > 0 and (t == 0 or value[s - 1, t - 1] >= value[s, t - 1]):
                    s -= 1

    return torch.from_numpy(path_np).to(device=device, dtype=dtype)


class DurationPredictor(nn.Module):
    """
    Lightweight ~0.4M parameter Duration Predictor.
    Predicts log-durations for each input text token.
    """
    def __init__(self, in_dim: int = 256, hidden_dim: int = 256, kernel_size: int = 3, dropout: float = 0.1):
        super().__init__()
        self.conv1 = nn.Conv1d(in_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)
        self.norm1 = ChannelLayerNorm1d(hidden_dim)
        self.act1 = nn.GELU()
        self.drop1 = nn.Dropout(dropout)

        self.conv2 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)
        self.norm2 = ChannelLayerNorm1d(hidden_dim)
        self.act2 = nn.GELU()
        self.drop2 = nn.Dropout(dropout)

        self.proj = nn.Conv1d(hidden_dim, 1, kernel_size=1)

    def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        # x: (B, T, C), mask: (B, T) bool
        h = x.transpose(1, 2)
        mask_3d = mask.unsqueeze(1).to(h.dtype) if mask is not None else None
        if mask_3d is not None:
            h = h * mask_3d

        h = self.drop1(self.act1(self.norm1(self.conv1(h))))
        if mask_3d is not None:
            h = h * mask_3d
        h = self.drop2(self.act2(self.norm2(self.conv2(h))))
        if mask_3d is not None:
            h = h * mask_3d

        log_dur = self.proj(h).squeeze(1)  # (B, T)
        if mask is not None:
            log_dur = log_dur.masked_fill(~mask, 0.0)
        return log_dur


def expand_by_duration(
    h: torch.Tensor,
    durations: torch.Tensor,
    text_mask: Optional[torch.Tensor] = None,
    return_lengths: bool = False,
    min_frames: int = 2,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
    """
    Expands text representations h of shape (B, T_text, C)
    into mel frame length (B, T_mel, C) based on durations.
    Respects text_mask so padded tokens expand to 0 frames.
    min_frames >= 2 prevents 10ms single-frame syllable dropping.
    """
    B, T_text, C = h.shape
    expanded_list = []
    mel_lengths = []

    for b in range(B):
        if text_mask is not None:
            h_b = h[b, text_mask[b]]
            dur_raw = durations[b, text_mask[b]]
        else:
            h_b = h[b]
            dur_raw = durations[b]

        if h_b.shape[0] == 0:
            expanded_b = h_b.new_zeros((0, C))
        else:
            if not torch.isfinite(dur_raw).all():
                raise ValueError("Duration predictor produced a non-finite frame count.")
            rounded = dur_raw.round().clamp(min=max(1, min_frames))
            if rounded.sum().item() > 32768:
                raise ValueError("Predicted utterance exceeds 32768 mel frames. Split the text or increase speed.")
            dur_b = rounded.long()
            expanded_b = torch.repeat_interleave(h_b, dur_b, dim=0)

        expanded_list.append(expanded_b)
        mel_lengths.append(expanded_b.shape[0])

    max_len = max(mel_lengths) if mel_lengths else 0
    padded = torch.zeros(B, max_len, C, device=h.device, dtype=h.dtype)
    for b in range(B):
        if mel_lengths[b] > 0:
            padded[b, : mel_lengths[b]] = expanded_list[b]

    if return_lengths:
        return padded, torch.tensor(mel_lengths, device=h.device, dtype=torch.long)
    return padded