CoolFace
Apppublic

Kit-Lemonfoot/vtuber_rvc_models

sourceHugging Facecreativeml-openrail-mupdated 2y agoView on Hugging Face
53likes
modules.py525 linesDownload Raw Back to infer_pack
1import copy
2import math
3import numpy as np
4import scipy
5import torch
6from torch import nn
7from torch.nn import functional as F
8
9from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10from torch.nn.utils import remove_weight_norm
11from torch.nn.utils.parametrizations import weight_norm
12
13
14from lib.infer_pack import commons
15from lib.infer_pack.commons import init_weights, get_padding
16from lib.infer_pack.transforms import piecewise_rational_quadratic_transform
17
18
19LRELU_SLOPE = 0.1
20
21
22class LayerNorm(nn.Module):
23    def __init__(self, channels, eps=1e-5):
24        super().__init__()
25        self.channels = channels
26        self.eps = eps
27
28        self.gamma = nn.Parameter(torch.ones(channels))
29        self.beta = nn.Parameter(torch.zeros(channels))
30
31    def forward(self, x):
32        x = x.transpose(1, -1)
33        x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
34        return x.transpose(1, -1)
35
36
37class ConvReluNorm(nn.Module):
38    def __init__(
39        self,
40        in_channels,
41        hidden_channels,
42        out_channels,
43        kernel_size,
44        n_layers,
45        p_dropout,
46    ):
47        super().__init__()
48        self.in_channels = in_channels
49        self.hidden_channels = hidden_channels
50        self.out_channels = out_channels
51        self.kernel_size = kernel_size
52        self.n_layers = n_layers
53        self.p_dropout = p_dropout
54        assert n_layers > 1, "Number of layers should be larger than 0."
55
56        self.conv_layers = nn.ModuleList()
57        self.norm_layers = nn.ModuleList()
58        self.conv_layers.append(
59            nn.Conv1d(
60                in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
61            )
62        )
63        self.norm_layers.append(LayerNorm(hidden_channels))
64        self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
65        for _ in range(n_layers - 1):
66            self.conv_layers.append(
67                nn.Conv1d(
68                    hidden_channels,
69                    hidden_channels,
70                    kernel_size,
71                    padding=kernel_size // 2,
72                )
73            )
74            self.norm_layers.append(LayerNorm(hidden_channels))
75        self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
76        self.proj.weight.data.zero_()
77        self.proj.bias.data.zero_()
78
79    def forward(self, x, x_mask):
80        x_org = x
81        for i in range(self.n_layers):
82            x = self.conv_layers[i](x * x_mask)
83            x = self.norm_layers[i](x)
84            x = self.relu_drop(x)
85        x = x_org + self.proj(x)
86        return x * x_mask
87
88
89class DDSConv(nn.Module):
90    """
91    Dialted and Depth-Separable Convolution
92    """
93
94    def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
95        super().__init__()
96        self.channels = channels
97        self.kernel_size = kernel_size
98        self.n_layers = n_layers
99        self.p_dropout = p_dropout
100
101        self.drop = nn.Dropout(p_dropout)
102        self.convs_sep = nn.ModuleList()
103        self.convs_1x1 = nn.ModuleList()
104        self.norms_1 = nn.ModuleList()
105        self.norms_2 = nn.ModuleList()
106        for i in range(n_layers):
107            dilation = kernel_size**i
108            padding = (kernel_size * dilation - dilation) // 2
109            self.convs_sep.append(
110                nn.Conv1d(
111                    channels,
112                    channels,
113                    kernel_size,
114                    groups=channels,
115                    dilation=dilation,
116                    padding=padding,
117                )
118            )
119            self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
120            self.norms_1.append(LayerNorm(channels))
121            self.norms_2.append(LayerNorm(channels))
122
123    def forward(self, x, x_mask, g=None):
124        if g is not None:
125            x = x + g
126        for i in range(self.n_layers):
127            y = self.convs_sep[i](x * x_mask)
128            y = self.norms_1[i](y)
129            y = F.gelu(y)
130            y = self.convs_1x1[i](y)
131            y = self.norms_2[i](y)
132            y = F.gelu(y)
133            y = self.drop(y)
134            x = x + y
135        return x * x_mask
136
137
138class WN(torch.nn.Module):
139    def __init__(
140        self,
141        hidden_channels,
142        kernel_size,
143        dilation_rate,
144        n_layers,
145        gin_channels=0,
146        p_dropout=0,
147    ):
148        super(WN, self).__init__()
149        assert kernel_size % 2 == 1
150        self.hidden_channels = hidden_channels
151        self.kernel_size = (kernel_size,)
152        self.dilation_rate = dilation_rate
153        self.n_layers = n_layers
154        self.gin_channels = gin_channels
155        self.p_dropout = p_dropout
156
157        self.in_layers = torch.nn.ModuleList()
158        self.res_skip_layers = torch.nn.ModuleList()
159        self.drop = nn.Dropout(p_dropout)
160
161        if gin_channels != 0:
162            cond_layer = torch.nn.Conv1d(
163                gin_channels, 2 * hidden_channels * n_layers, 1
164            )
165            self.cond_layer = torch.nn.utils.parametrizations.weight_norm(cond_layer, name="weight")
166
167        for i in range(n_layers):
168            dilation = dilation_rate**i
169            padding = int((kernel_size * dilation - dilation) / 2)
170            in_layer = torch.nn.Conv1d(
171                hidden_channels,
172                2 * hidden_channels,
173                kernel_size,
174                dilation=dilation,
175                padding=padding,
176            )
177            in_layer = torch.nn.utils.parametrizations.weight_norm(in_layer, name="weight")
178            self.in_layers.append(in_layer)
179
180            # last one is not necessary
181            if i < n_layers - 1:
182                res_skip_channels = 2 * hidden_channels
183            else:
184                res_skip_channels = hidden_channels
185
186            res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
187            res_skip_layer = torch.nn.utils.parametrizations.weight_norm(res_skip_layer, name="weight")
188            self.res_skip_layers.append(res_skip_layer)
189
190    def forward(self, x, x_mask, g=None, **kwargs):
191        output = torch.zeros_like(x)
192        n_channels_tensor = torch.IntTensor([self.hidden_channels])
193
194        if g is not None:
195            g = self.cond_layer(g)
196
197        for i in range(self.n_layers):
198            x_in = self.in_layers[i](x)
199            if g is not None:
200                cond_offset = i * 2 * self.hidden_channels
201                g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
202            else:
203                g_l = torch.zeros_like(x_in)
204
205            acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
206            acts = self.drop(acts)
207
208            res_skip_acts = self.res_skip_layers[i](acts)
209            if i < self.n_layers - 1:
210                res_acts = res_skip_acts[:, : self.hidden_channels, :]
211                x = (x + res_acts) * x_mask
212                output = output + res_skip_acts[:, self.hidden_channels :, :]
213            else:
214                output = output + res_skip_acts
215        return output * x_mask
216
217    def remove_weight_norm(self):
218        if self.gin_channels != 0:
219            torch.nn.utils.remove_weight_norm(self.cond_layer)
220        for l in self.in_layers:
221            torch.nn.utils.remove_weight_norm(l)
222        for l in self.res_skip_layers:
223            torch.nn.utils.remove_weight_norm(l)
224
225
226class ResBlock1(torch.nn.Module):
227    def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
228        super(ResBlock1, self).__init__()
229        self.convs1 = nn.ModuleList(
230            [
231                weight_norm(
232                    Conv1d(
233                        channels,
234                        channels,
235                        kernel_size,
236                        1,
237                        dilation=dilation[0],
238                        padding=get_padding(kernel_size, dilation[0]),
239                    )
240                ),
241                weight_norm(
242                    Conv1d(
243                        channels,
244                        channels,
245                        kernel_size,
246                        1,
247                        dilation=dilation[1],
248                        padding=get_padding(kernel_size, dilation[1]),
249                    )
250                ),
251                weight_norm(
252                    Conv1d(
253                        channels,
254                        channels,
255                        kernel_size,
256                        1,
257                        dilation=dilation[2],
258                        padding=get_padding(kernel_size, dilation[2]),
259                    )
260                ),
261            ]
262        )
263        self.convs1.apply(init_weights)
264
265        self.convs2 = nn.ModuleList(
266            [
267                weight_norm(
268                    Conv1d(
269                        channels,
270                        channels,
271                        kernel_size,
272                        1,
273                        dilation=1,
274                        padding=get_padding(kernel_size, 1),
275                    )
276                ),
277                weight_norm(
278                    Conv1d(
279                        channels,
280                        channels,
281                        kernel_size,
282                        1,
283                        dilation=1,
284                        padding=get_padding(kernel_size, 1),
285                    )
286                ),
287                weight_norm(
288                    Conv1d(
289                        channels,
290                        channels,
291                        kernel_size,
292                        1,
293                        dilation=1,
294                        padding=get_padding(kernel_size, 1),
295                    )
296                ),
297            ]
298        )
299        self.convs2.apply(init_weights)
300
301    def forward(self, x, x_mask=None):
302        for c1, c2 in zip(self.convs1, self.convs2):
303            xt = F.leaky_relu(x, LRELU_SLOPE)
304            if x_mask is not None:
305                xt = xt * x_mask
306            xt = c1(xt)
307            xt = F.leaky_relu(xt, LRELU_SLOPE)
308            if x_mask is not None:
309                xt = xt * x_mask
310            xt = c2(xt)
311            x = xt + x
312        if x_mask is not None:
313            x = x * x_mask
314        return x
315
316    def remove_weight_norm(self):
317        for l in self.convs1:
318            remove_weight_norm(l)
319        for l in self.convs2:
320            remove_weight_norm(l)
321
322
323class ResBlock2(torch.nn.Module):
324    def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
325        super(ResBlock2, self).__init__()
326        self.convs = nn.ModuleList(
327            [
328                weight_norm(
329                    Conv1d(
330                        channels,
331                        channels,
332                        kernel_size,
333                        1,
334                        dilation=dilation[0],
335                        padding=get_padding(kernel_size, dilation[0]),
336                    )
337                ),
338                weight_norm(
339                    Conv1d(
340                        channels,
341                        channels,
342                        kernel_size,
343                        1,
344                        dilation=dilation[1],
345                        padding=get_padding(kernel_size, dilation[1]),
346                    )
347                ),
348            ]
349        )
350        self.convs.apply(init_weights)
351
352    def forward(self, x, x_mask=None):
353        for c in self.convs:
354            xt = F.leaky_relu(x, LRELU_SLOPE)
355            if x_mask is not None:
356                xt = xt * x_mask
357            xt = c(xt)
358            x = xt + x
359        if x_mask is not None:
360            x = x * x_mask
361        return x
362
363    def remove_weight_norm(self):
364        for l in self.convs:
365            remove_weight_norm(l)
366
367
368class Log(nn.Module):
369    def forward(self, x, x_mask, reverse=False, **kwargs):
370        if not reverse:
371            y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
372            logdet = torch.sum(-y, [1, 2])
373            return y, logdet
374        else:
375            x = torch.exp(x) * x_mask
376            return x
377
378
379class Flip(nn.Module):
380    def forward(self, x, *args, reverse=False, **kwargs):
381        x = torch.flip(x, [1])
382        if not reverse:
383            logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
384            return x, logdet
385        else:
386            return x
387
388
389class ElementwiseAffine(nn.Module):
390    def __init__(self, channels):
391        super().__init__()
392        self.channels = channels
393        self.m = nn.Parameter(torch.zeros(channels, 1))
394        self.logs = nn.Parameter(torch.zeros(channels, 1))
395
396    def forward(self, x, x_mask, reverse=False, **kwargs):
397        if not reverse:
398            y = self.m + torch.exp(self.logs) * x
399            y = y * x_mask
400            logdet = torch.sum(self.logs * x_mask, [1, 2])
401            return y, logdet
402        else:
403            x = (x - self.m) * torch.exp(-self.logs) * x_mask
404            return x
405
406
407class ResidualCouplingLayer(nn.Module):
408    def __init__(
409        self,
410        channels,
411        hidden_channels,
412        kernel_size,
413        dilation_rate,
414        n_layers,
415        p_dropout=0,
416        gin_channels=0,
417        mean_only=False,
418    ):
419        assert channels % 2 == 0, "channels should be divisible by 2"
420        super().__init__()
421        self.channels = channels
422        self.hidden_channels = hidden_channels
423        self.kernel_size = kernel_size
424        self.dilation_rate = dilation_rate
425        self.n_layers = n_layers
426        self.half_channels = channels // 2
427        self.mean_only = mean_only
428
429        self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
430        self.enc = WN(
431            hidden_channels,
432            kernel_size,
433            dilation_rate,
434            n_layers,
435            p_dropout=p_dropout,
436            gin_channels=gin_channels,
437        )
438        self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
439        self.post.weight.data.zero_()
440        self.post.bias.data.zero_()
441
442    def forward(self, x, x_mask, g=None, reverse=False):
443        x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
444        h = self.pre(x0) * x_mask
445        h = self.enc(h, x_mask, g=g)
446        stats = self.post(h) * x_mask
447        if not self.mean_only:
448            m, logs = torch.split(stats, [self.half_channels] * 2, 1)
449        else:
450            m = stats
451            logs = torch.zeros_like(m)
452
453        if not reverse:
454            x1 = m + x1 * torch.exp(logs) * x_mask
455            x = torch.cat([x0, x1], 1)
456            logdet = torch.sum(logs, [1, 2])
457            return x, logdet
458        else:
459            x1 = (x1 - m) * torch.exp(-logs) * x_mask
460            x = torch.cat([x0, x1], 1)
461            return x
462
463    def remove_weight_norm(self):
464        self.enc.remove_weight_norm()
465
466
467class ConvFlow(nn.Module):
468    def __init__(
469        self,
470        in_channels,
471        filter_channels,
472        kernel_size,
473        n_layers,
474        num_bins=10,
475        tail_bound=5.0,
476    ):
477        super().__init__()
478        self.in_channels = in_channels
479        self.filter_channels = filter_channels
480        self.kernel_size = kernel_size
481        self.n_layers = n_layers
482        self.num_bins = num_bins
483        self.tail_bound = tail_bound
484        self.half_channels = in_channels // 2
485
486        self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
487        self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
488        self.proj = nn.Conv1d(
489            filter_channels, self.half_channels * (num_bins * 3 - 1), 1
490        )
491        self.proj.weight.data.zero_()
492        self.proj.bias.data.zero_()
493
494    def forward(self, x, x_mask, g=None, reverse=False):
495        x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
496        h = self.pre(x0)
497        h = self.convs(h, x_mask, g=g)
498        h = self.proj(h) * x_mask
499
500        b, c, t = x0.shape
501        h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2)  # [b, cx?, t] -> [b, c, t, ?]
502
503        unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
504        unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
505            self.filter_channels
506        )
507        unnormalized_derivatives = h[..., 2 * self.num_bins :]
508
509        x1, logabsdet = piecewise_rational_quadratic_transform(
510            x1,
511            unnormalized_widths,
512            unnormalized_heights,
513            unnormalized_derivatives,
514            inverse=reverse,
515            tails="linear",
516            tail_bound=self.tail_bound,
517        )
518
519        x = torch.cat([x0, x1], 1) * x_mask
520        logdet = torch.sum(logabsdet * x_mask, [1, 2])
521        if not reverse:
522            return x, logdet
523        else:
524            return x
525