layers.py 8.09 KB
Newer Older
liugh5's avatar
liugh5 committed
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
289
290
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import weight_norm, remove_weight_norm
from torch.distributions.uniform import Uniform
from torch.distributions.normal import Normal
from kantts.models.utils import init_weights


def get_padding(kernel_size, dilation=1):
    return int((kernel_size * dilation - dilation) / 2)


class Conv1d(torch.nn.Module):
    def __init__(
        self,
        in_channels,
        out_channels,
        kernel_size,
        stride=1,
        padding=0,
        dilation=1,
        groups=1,
        bias=True,
        padding_mode="zeros",
    ):
        super(Conv1d, self).__init__()
        self.conv1d = weight_norm(
            nn.Conv1d(
                in_channels,
                out_channels,
                kernel_size,
                stride,
                padding=padding,
                dilation=dilation,
                groups=groups,
                bias=bias,
                padding_mode=padding_mode,
            )
        )
        self.conv1d.apply(init_weights)

    def forward(self, x):
        x = self.conv1d(x)
        return x

    def remove_weight_norm(self):
        remove_weight_norm(self.conv1d)


class CausalConv1d(torch.nn.Module):
    def __init__(
        self,
        in_channels,
        out_channels,
        kernel_size,
        stride=1,
        padding=0,
        dilation=1,
        groups=1,
        bias=True,
        padding_mode="zeros",
    ):
        super(CausalConv1d, self).__init__()
        self.pad = (kernel_size - 1) * dilation
        self.conv1d = weight_norm(
            nn.Conv1d(
                in_channels,
                out_channels,
                kernel_size,
                stride,
                padding=0,
                dilation=dilation,
                groups=groups,
                bias=bias,
                padding_mode=padding_mode,
            )
        )
        self.conv1d.apply(init_weights)

    def forward(self, x):  # bdt
        x = F.pad(
            x, (self.pad, 0, 0, 0, 0, 0), "constant"
        )  # described starting from the last dimension and moving forward.
        #  x = F.pad(x, (self.pad, self.pad, 0, 0, 0, 0), "constant")
        x = self.conv1d(x)[:, :, : x.size(2)]
        return x

    def remove_weight_norm(self):
        remove_weight_norm(self.conv1d)


class ConvTranspose1d(torch.nn.Module):
    def __init__(
        self,
        in_channels,
        out_channels,
        kernel_size,
        stride,
        padding=0,
        output_padding=0,
    ):
        super(ConvTranspose1d, self).__init__()
        self.deconv = weight_norm(
            nn.ConvTranspose1d(
                in_channels,
                out_channels,
                kernel_size,
                stride,
                padding=padding,
                output_padding=0,
            )
        )
        self.deconv.apply(init_weights)

    def forward(self, x):
        return self.deconv(x)

    def remove_weight_norm(self):
        remove_weight_norm(self.deconv)


#  FIXME: HACK to get shape right
class CausalConvTranspose1d(torch.nn.Module):
    """CausalConvTranspose1d module with customized initialization."""

    def __init__(
        self,
        in_channels,
        out_channels,
        kernel_size,
        stride,
        padding=0,
        output_padding=0,
    ):
        """Initialize CausalConvTranspose1d module."""
        super(CausalConvTranspose1d, self).__init__()
        self.deconv = weight_norm(
            nn.ConvTranspose1d(
                in_channels,
                out_channels,
                kernel_size,
                stride,
                padding=0,
                output_padding=0,
            )
        )
        self.stride = stride
        self.deconv.apply(init_weights)
        self.pad = kernel_size - stride

    def forward(self, x):
        """Calculate forward propagation.
        Args:
            x (Tensor): Input tensor (B, in_channels, T_in).
        Returns:
            Tensor: Output tensor (B, out_channels, T_out).
        """
        #  x = F.pad(x, (self.pad, 0, 0, 0, 0, 0), "constant")
        return self.deconv(x)[:, :, : -self.pad]
        #  return self.deconv(x)

    def remove_weight_norm(self):
        remove_weight_norm(self.deconv)


class ResidualBlock(torch.nn.Module):
    def __init__(
        self,
        channels,
        kernel_size=3,
        dilation=(1, 3, 5),
        nonlinear_activation="LeakyReLU",
        nonlinear_activation_params={"negative_slope": 0.1},
        causal=False,
    ):
        super(ResidualBlock, self).__init__()
        assert kernel_size % 2 == 1, "Kernal size must be odd number."
        conv_cls = CausalConv1d if causal else Conv1d
        self.convs1 = nn.ModuleList(
            [
                conv_cls(
                    channels,
                    channels,
                    kernel_size,
                    1,
                    dilation=dilation[i],
                    padding=get_padding(kernel_size, dilation[i]),
                )
                for i in range(len(dilation))
            ]
        )

        self.convs2 = nn.ModuleList(
            [
                conv_cls(
                    channels,
                    channels,
                    kernel_size,
                    1,
                    dilation=1,
                    padding=get_padding(kernel_size, 1),
                )
                for i in range(len(dilation))
            ]
        )

        self.activation = getattr(torch.nn, nonlinear_activation)(
            **nonlinear_activation_params
        )

    def forward(self, x):
        for c1, c2 in zip(self.convs1, self.convs2):
            xt = self.activation(x)
            xt = c1(xt)
            xt = self.activation(xt)
            xt = c2(xt)
            x = xt + x
        return x

    def remove_weight_norm(self):
        for layer in self.convs1:
            layer.remove_weight_norm()
        for layer in self.convs2:
            layer.remove_weight_norm()


class SourceModule(torch.nn.Module):
    def __init__(
        self, nb_harmonics, upsample_ratio, sampling_rate, alpha=0.1, sigma=0.003
    ):
        super(SourceModule, self).__init__()

        self.nb_harmonics = nb_harmonics
        self.upsample_ratio = upsample_ratio
        self.sampling_rate = sampling_rate
        self.alpha = alpha
        self.sigma = sigma

        self.ffn = nn.Sequential(
            weight_norm(nn.Conv1d(self.nb_harmonics + 1, 1, kernel_size=1, stride=1)),
            nn.Tanh(),
        )

    def forward(self, pitch, uv):
        """
        :param pitch: [B, 1, frame_len], Hz
        :param uv: [B, 1, frame_len] vuv flag
        :return: [B, 1, sample_len]
        """
        with torch.no_grad():
            pitch_samples = F.interpolate(
                pitch, scale_factor=(self.upsample_ratio), mode="nearest"
            )
            uv_samples = F.interpolate(
                uv, scale_factor=(self.upsample_ratio), mode="nearest"
            )

            F_mat = torch.zeros(
                (pitch_samples.size(0), self.nb_harmonics + 1, pitch_samples.size(-1))
            ).to(pitch_samples.device)
            for i in range(self.nb_harmonics + 1):
                F_mat[:, i : i + 1, :] = pitch_samples * (i + 1) / self.sampling_rate

            theta_mat = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
            u_dist = Uniform(low=-np.pi, high=np.pi)
            phase_vec = u_dist.sample(
                sample_shape=(pitch.size(0), self.nb_harmonics + 1, 1)
            ).to(F_mat.device)
            phase_vec[:, 0, :] = 0

            n_dist = Normal(loc=0.0, scale=self.sigma)
            noise = n_dist.sample(
                sample_shape=(
                    pitch_samples.size(0),
                    self.nb_harmonics + 1,
                    pitch_samples.size(-1),
                )
            ).to(F_mat.device)

            e_voice = self.alpha * torch.sin(theta_mat + phase_vec) + noise
            e_unvoice = self.alpha / 3 / self.sigma * noise

            e = e_voice * uv_samples + e_unvoice * (1 - uv_samples)

        return self.ffn(e)

    def remove_weight_norm(self):
        remove_weight_norm(self.ffn[0])