biosn2 commited on
Commit
76e0a28
·
verified ·
1 Parent(s): 3db3ccb

Upload indextts/BigVGAN/models.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. indextts/BigVGAN/models.py +451 -0
indextts/BigVGAN/models.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 NVIDIA CORPORATION.
2
+ # Licensed under the MIT license.
3
+
4
+ # Adapted from https://github.com/jik876/hifi-gan under the MIT license.
5
+ # LICENSE is in incl_licenses directory.
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from torch.nn import Conv1d, Conv2d, ConvTranspose1d
10
+ from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
11
+
12
+ import indextts.BigVGAN.activations as activations
13
+
14
+ from indextts.BigVGAN.ECAPA_TDNN import ECAPA_TDNN
15
+ from indextts.BigVGAN.utils import get_padding, init_weights
16
+
17
+ LRELU_SLOPE = 0.1
18
+
19
+
20
+ class AMPBlock1(torch.nn.Module):
21
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5), activation=None):
22
+ super(AMPBlock1, self).__init__()
23
+ self.h = h
24
+
25
+ self.convs1 = nn.ModuleList([
26
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
27
+ padding=get_padding(kernel_size, dilation[0]))),
28
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
29
+ padding=get_padding(kernel_size, dilation[1]))),
30
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
31
+ padding=get_padding(kernel_size, dilation[2])))
32
+ ])
33
+ self.convs1.apply(init_weights)
34
+
35
+ self.convs2 = nn.ModuleList([
36
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
37
+ padding=get_padding(kernel_size, 1))),
38
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
39
+ padding=get_padding(kernel_size, 1))),
40
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
41
+ padding=get_padding(kernel_size, 1)))
42
+ ])
43
+ self.convs2.apply(init_weights)
44
+
45
+ self.num_layers = len(self.convs1) + len(self.convs2) # total number of conv layers
46
+ if self.h.get("use_cuda_kernel", False):
47
+ from indextts.BigVGAN.alias_free_activation.cuda.activation1d import Activation1d
48
+ else:
49
+ from indextts.BigVGAN.alias_free_torch import Activation1d
50
+ if activation == 'snake': # periodic nonlinearity with snake function and anti-aliasing
51
+ self.activations = nn.ModuleList([
52
+ Activation1d(
53
+ activation=activations.Snake(channels, alpha_logscale=h.snake_logscale))
54
+ for _ in range(self.num_layers)
55
+ ])
56
+ elif activation == 'snakebeta': # periodic nonlinearity with snakebeta function and anti-aliasing
57
+ self.activations = nn.ModuleList([
58
+ Activation1d(
59
+ activation=activations.SnakeBeta(channels, alpha_logscale=h.snake_logscale))
60
+ for _ in range(self.num_layers)
61
+ ])
62
+ else:
63
+ raise NotImplementedError("activation incorrectly specified. check the config file and look for 'activation'.")
64
+
65
+ def forward(self, x):
66
+ acts1, acts2 = self.activations[::2], self.activations[1::2]
67
+ for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2):
68
+ xt = a1(x)
69
+ xt = c1(xt)
70
+ xt = a2(xt)
71
+ xt = c2(xt)
72
+ x = xt + x
73
+
74
+ return x
75
+
76
+ def remove_weight_norm(self):
77
+ for l in self.convs1:
78
+ remove_weight_norm(l)
79
+ for l in self.convs2:
80
+ remove_weight_norm(l)
81
+
82
+
83
+ class AMPBlock2(torch.nn.Module):
84
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3), activation=None):
85
+ super(AMPBlock2, self).__init__()
86
+ self.h = h
87
+
88
+ self.convs = nn.ModuleList([
89
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
90
+ padding=get_padding(kernel_size, dilation[0]))),
91
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
92
+ padding=get_padding(kernel_size, dilation[1])))
93
+ ])
94
+ self.convs.apply(init_weights)
95
+
96
+ self.num_layers = len(self.convs) # total number of conv layers
97
+ if self.h.get("use_cuda_kernel", False):
98
+ from indextts.BigVGAN.alias_free_activation.cuda.activation1d import Activation1d
99
+ else:
100
+ from indextts.BigVGAN.alias_free_torch import Activation1d
101
+
102
+ if activation == 'snake': # periodic nonlinearity with snake function and anti-aliasing
103
+ self.activations = nn.ModuleList([
104
+ Activation1d(
105
+ activation=activations.Snake(channels, alpha_logscale=h.snake_logscale))
106
+ for _ in range(self.num_layers)
107
+ ])
108
+ elif activation == 'snakebeta': # periodic nonlinearity with snakebeta function and anti-aliasing
109
+ self.activations = nn.ModuleList([
110
+ Activation1d(
111
+ activation=activations.SnakeBeta(channels, alpha_logscale=h.snake_logscale))
112
+ for _ in range(self.num_layers)
113
+ ])
114
+ else:
115
+ raise NotImplementedError("activation incorrectly specified. check the config file and look for 'activation'.")
116
+
117
+ def forward(self, x):
118
+ for c, a in zip(self.convs, self.activations):
119
+ xt = a(x)
120
+ xt = c(xt)
121
+ x = xt + x
122
+
123
+ return x
124
+
125
+ def remove_weight_norm(self):
126
+ for l in self.convs:
127
+ remove_weight_norm(l)
128
+
129
+
130
+ class BigVGAN(torch.nn.Module):
131
+ # this is our main BigVGAN model. Applies anti-aliased periodic activation for resblocks.
132
+ def __init__(self, h, use_cuda_kernel=False):
133
+ """
134
+ Args:
135
+ h (dict)
136
+ use_cuda_kernel (bool): whether to use custom cuda kernel for anti-aliased activation
137
+ """
138
+ super(BigVGAN, self).__init__()
139
+ self.h = h
140
+ self.h["use_cuda_kernel"] = use_cuda_kernel
141
+
142
+ self.num_kernels = len(h.resblock_kernel_sizes)
143
+ self.num_upsamples = len(h.upsample_rates)
144
+
145
+ self.feat_upsample = h.feat_upsample
146
+ self.cond_in_each_up_layer = h.cond_d_vector_in_each_upsampling_layer
147
+
148
+ # pre conv
149
+ self.conv_pre = weight_norm(Conv1d(h.gpt_dim, h.upsample_initial_channel, 7, 1, padding=3))
150
+
151
+ # define which AMPBlock to use. BigVGAN uses AMPBlock1 as default
152
+ resblock = AMPBlock1 if h.resblock == "1" else AMPBlock2
153
+
154
+ # transposed conv-based upsamplers. does not apply anti-aliasing
155
+ self.ups = nn.ModuleList()
156
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
157
+ self.ups.append(nn.ModuleList([
158
+ weight_norm(ConvTranspose1d(h.upsample_initial_channel // (2 ** i),
159
+ h.upsample_initial_channel // (2 ** (i + 1)),
160
+ k, u, padding=(k - u) // 2))
161
+ ]))
162
+
163
+ # residual blocks using anti-aliased multi-periodicity composition modules (AMP)
164
+ self.resblocks = nn.ModuleList()
165
+ for i in range(len(self.ups)):
166
+ ch = h.upsample_initial_channel // (2 ** (i + 1))
167
+ for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
168
+ self.resblocks.append(resblock(self.h, ch, k, d, activation=h.activation))
169
+ if use_cuda_kernel:
170
+ from indextts.BigVGAN.alias_free_activation.cuda.activation1d import Activation1d
171
+ else:
172
+ from indextts.BigVGAN.alias_free_torch import Activation1d
173
+
174
+ # post conv
175
+ if h.activation == "snake": # periodic nonlinearity with snake function and anti-aliasing
176
+ activation_post = activations.Snake(ch, alpha_logscale=h.snake_logscale)
177
+ self.activation_post = Activation1d(activation=activation_post)
178
+ elif h.activation == "snakebeta": # periodic nonlinearity with snakebeta function and anti-aliasing
179
+ activation_post = activations.SnakeBeta(ch, alpha_logscale=h.snake_logscale)
180
+ self.activation_post = Activation1d(activation=activation_post)
181
+ else:
182
+ raise NotImplementedError("activation incorrectly specified. check the config file and look for 'activation'.")
183
+
184
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
185
+
186
+ # weight initialization
187
+ for i in range(len(self.ups)):
188
+ self.ups[i].apply(init_weights)
189
+ self.conv_post.apply(init_weights)
190
+
191
+ self.speaker_encoder = ECAPA_TDNN(h.num_mels, lin_neurons=h.speaker_embedding_dim)
192
+ self.cond_layer = nn.Conv1d(h.speaker_embedding_dim, h.upsample_initial_channel, 1)
193
+ if self.cond_in_each_up_layer:
194
+ self.conds = nn.ModuleList()
195
+ for i in range(len(self.ups)):
196
+ ch = h.upsample_initial_channel // (2 ** (i + 1))
197
+ self.conds.append(nn.Conv1d(h.speaker_embedding_dim, ch, 1))
198
+
199
+ # self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
200
+
201
+ def forward(self, x, mel_ref, lens=None):
202
+ speaker_embedding = self.speaker_encoder(mel_ref, lens)
203
+ n_batch = x.size(0)
204
+ contrastive_loss = None
205
+ if n_batch * 2 == speaker_embedding.size(0):
206
+ spe_emb_chunk1, spe_emb_chunk2 = speaker_embedding[:n_batch, :, :], speaker_embedding[n_batch:, :, :]
207
+ contrastive_loss = self.cal_clip_loss(spe_emb_chunk1.squeeze(1), spe_emb_chunk2.squeeze(1), self.logit_scale.exp())
208
+
209
+ speaker_embedding = speaker_embedding[:n_batch, :, :]
210
+ speaker_embedding = speaker_embedding.transpose(1, 2)
211
+
212
+ # upsample feat
213
+ if self.feat_upsample:
214
+ x = torch.nn.functional.interpolate(
215
+ x.transpose(1, 2),
216
+ scale_factor=[4],
217
+ mode="linear",
218
+ ).squeeze(1)
219
+ else:
220
+ x = x.transpose(1, 2)
221
+
222
+ ### bigVGAN ###
223
+ # pre conv
224
+ x = self.conv_pre(x)
225
+
226
+ x = x + self.cond_layer(speaker_embedding)
227
+
228
+ for i in range(self.num_upsamples):
229
+ # upsampling
230
+ for i_up in range(len(self.ups[i])):
231
+ x = self.ups[i][i_up](x)
232
+
233
+ if self.cond_in_each_up_layer:
234
+ x = x + self.conds[i](speaker_embedding)
235
+
236
+ # AMP blocks
237
+ xs = None
238
+ for j in range(self.num_kernels):
239
+ if xs is None:
240
+ xs = self.resblocks[i * self.num_kernels + j](x)
241
+ else:
242
+ xs += self.resblocks[i * self.num_kernels + j](x)
243
+ x = xs / self.num_kernels
244
+
245
+ # post conv
246
+ x = self.activation_post(x)
247
+ x = self.conv_post(x)
248
+ x = torch.tanh(x)
249
+
250
+ return x, contrastive_loss
251
+
252
+ def remove_weight_norm(self):
253
+ print('Removing weight norm...')
254
+ for l in self.ups:
255
+ for l_i in l:
256
+ remove_weight_norm(l_i)
257
+ for l in self.resblocks:
258
+ l.remove_weight_norm()
259
+ remove_weight_norm(self.conv_pre)
260
+ remove_weight_norm(self.conv_post)
261
+
262
+ def cal_clip_loss(self, image_features, text_features, logit_scale):
263
+ device = image_features.device
264
+ logits_per_image, logits_per_text = self.get_logits(image_features, text_features, logit_scale)
265
+ labels = torch.arange(logits_per_image.shape[0], device=device, dtype=torch.long)
266
+ total_loss = (
267
+ F.cross_entropy(logits_per_image, labels) +
268
+ F.cross_entropy(logits_per_text, labels)
269
+ ) / 2
270
+ return total_loss
271
+
272
+ def get_logits(self, image_features, text_features, logit_scale):
273
+ logits_per_image = logit_scale * image_features @ text_features.T
274
+ logits_per_text = logit_scale * text_features @ image_features.T
275
+ return logits_per_image, logits_per_text
276
+
277
+
278
+ class DiscriminatorP(torch.nn.Module):
279
+ def __init__(self, h, period, kernel_size=5, stride=3, use_spectral_norm=False):
280
+ super(DiscriminatorP, self).__init__()
281
+ self.period = period
282
+ self.d_mult = h.discriminator_channel_mult
283
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
284
+ self.convs = nn.ModuleList([
285
+ norm_f(Conv2d(1, int(32 * self.d_mult), (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
286
+ norm_f(Conv2d(int(32 * self.d_mult), int(128 * self.d_mult), (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
287
+ norm_f(Conv2d(int(128 * self.d_mult), int(512 * self.d_mult), (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
288
+ norm_f(Conv2d(int(512 * self.d_mult), int(1024 * self.d_mult), (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
289
+ norm_f(Conv2d(int(1024 * self.d_mult), int(1024 * self.d_mult), (kernel_size, 1), 1, padding=(2, 0))),
290
+ ])
291
+ self.conv_post = norm_f(Conv2d(int(1024 * self.d_mult), 1, (3, 1), 1, padding=(1, 0)))
292
+
293
+ def forward(self, x):
294
+ fmap = []
295
+
296
+ # 1d to 2d
297
+ b, c, t = x.shape
298
+ if t % self.period != 0: # pad first
299
+ n_pad = self.period - (t % self.period)
300
+ x = F.pad(x, (0, n_pad), "reflect")
301
+ t = t + n_pad
302
+ x = x.view(b, c, t // self.period, self.period)
303
+
304
+ for l in self.convs:
305
+ x = l(x)
306
+ x = F.leaky_relu(x, LRELU_SLOPE)
307
+ fmap.append(x)
308
+ x = self.conv_post(x)
309
+ fmap.append(x)
310
+ x = torch.flatten(x, 1, -1)
311
+
312
+ return x, fmap
313
+
314
+
315
+ class MultiPeriodDiscriminator(torch.nn.Module):
316
+ def __init__(self, h):
317
+ super(MultiPeriodDiscriminator, self).__init__()
318
+ self.mpd_reshapes = h.mpd_reshapes
319
+ print("mpd_reshapes: {}".format(self.mpd_reshapes))
320
+ discriminators = [DiscriminatorP(h, rs, use_spectral_norm=h.use_spectral_norm) for rs in self.mpd_reshapes]
321
+ self.discriminators = nn.ModuleList(discriminators)
322
+
323
+ def forward(self, y, y_hat):
324
+ y_d_rs = []
325
+ y_d_gs = []
326
+ fmap_rs = []
327
+ fmap_gs = []
328
+ for i, d in enumerate(self.discriminators):
329
+ y_d_r, fmap_r = d(y)
330
+ y_d_g, fmap_g = d(y_hat)
331
+ y_d_rs.append(y_d_r)
332
+ fmap_rs.append(fmap_r)
333
+ y_d_gs.append(y_d_g)
334
+ fmap_gs.append(fmap_g)
335
+
336
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
337
+
338
+
339
+ class DiscriminatorR(nn.Module):
340
+ def __init__(self, cfg, resolution):
341
+ super().__init__()
342
+
343
+ self.resolution = resolution
344
+ assert len(self.resolution) == 3, \
345
+ "MRD layer requires list with len=3, got {}".format(self.resolution)
346
+ self.lrelu_slope = LRELU_SLOPE
347
+
348
+ norm_f = weight_norm if cfg.use_spectral_norm == False else spectral_norm
349
+ if hasattr(cfg, "mrd_use_spectral_norm"):
350
+ print("INFO: overriding MRD use_spectral_norm as {}".format(cfg.mrd_use_spectral_norm))
351
+ norm_f = weight_norm if cfg.mrd_use_spectral_norm == False else spectral_norm
352
+ self.d_mult = cfg.discriminator_channel_mult
353
+ if hasattr(cfg, "mrd_channel_mult"):
354
+ print("INFO: overriding mrd channel multiplier as {}".format(cfg.mrd_channel_mult))
355
+ self.d_mult = cfg.mrd_channel_mult
356
+
357
+ self.convs = nn.ModuleList([
358
+ norm_f(nn.Conv2d(1, int(32 * self.d_mult), (3, 9), padding=(1, 4))),
359
+ norm_f(nn.Conv2d(int(32 * self.d_mult), int(32 * self.d_mult), (3, 9), stride=(1, 2), padding=(1, 4))),
360
+ norm_f(nn.Conv2d(int(32 * self.d_mult), int(32 * self.d_mult), (3, 9), stride=(1, 2), padding=(1, 4))),
361
+ norm_f(nn.Conv2d(int(32 * self.d_mult), int(32 * self.d_mult), (3, 9), stride=(1, 2), padding=(1, 4))),
362
+ norm_f(nn.Conv2d(int(32 * self.d_mult), int(32 * self.d_mult), (3, 3), padding=(1, 1))),
363
+ ])
364
+ self.conv_post = norm_f(nn.Conv2d(int(32 * self.d_mult), 1, (3, 3), padding=(1, 1)))
365
+
366
+ def forward(self, x):
367
+ fmap = []
368
+
369
+ x = self.spectrogram(x)
370
+ x = x.unsqueeze(1)
371
+ for l in self.convs:
372
+ x = l(x)
373
+ x = F.leaky_relu(x, self.lrelu_slope)
374
+ fmap.append(x)
375
+ x = self.conv_post(x)
376
+ fmap.append(x)
377
+ x = torch.flatten(x, 1, -1)
378
+
379
+ return x, fmap
380
+
381
+ def spectrogram(self, x):
382
+ n_fft, hop_length, win_length = self.resolution
383
+ x = F.pad(x, (int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)), mode='reflect')
384
+ x = x.squeeze(1)
385
+ x = torch.stft(x, n_fft=n_fft, hop_length=hop_length, win_length=win_length, center=False, return_complex=True)
386
+ x = torch.view_as_real(x) # [B, F, TT, 2]
387
+ mag = torch.norm(x, p=2, dim=-1) # [B, F, TT]
388
+
389
+ return mag
390
+
391
+
392
+ class MultiResolutionDiscriminator(nn.Module):
393
+ def __init__(self, cfg, debug=False):
394
+ super().__init__()
395
+ self.resolutions = cfg.resolutions
396
+ assert len(self.resolutions) == 3, \
397
+ "MRD requires list of list with len=3, each element having a list with len=3. got {}".\
398
+ format(self.resolutions)
399
+ self.discriminators = nn.ModuleList(
400
+ [DiscriminatorR(cfg, resolution) for resolution in self.resolutions]
401
+ )
402
+
403
+ def forward(self, y, y_hat):
404
+ y_d_rs = []
405
+ y_d_gs = []
406
+ fmap_rs = []
407
+ fmap_gs = []
408
+
409
+ for i, d in enumerate(self.discriminators):
410
+ y_d_r, fmap_r = d(x=y)
411
+ y_d_g, fmap_g = d(x=y_hat)
412
+ y_d_rs.append(y_d_r)
413
+ fmap_rs.append(fmap_r)
414
+ y_d_gs.append(y_d_g)
415
+ fmap_gs.append(fmap_g)
416
+
417
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
418
+
419
+
420
+ def feature_loss(fmap_r, fmap_g):
421
+ loss = 0
422
+ for dr, dg in zip(fmap_r, fmap_g):
423
+ for rl, gl in zip(dr, dg):
424
+ loss += torch.mean(torch.abs(rl - gl))
425
+
426
+ return loss * 2
427
+
428
+
429
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
430
+ loss = 0
431
+ r_losses = []
432
+ g_losses = []
433
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
434
+ r_loss = torch.mean((1 - dr)**2)
435
+ g_loss = torch.mean(dg**2)
436
+ loss += (r_loss + g_loss)
437
+ r_losses.append(r_loss.item())
438
+ g_losses.append(g_loss.item())
439
+
440
+ return loss, r_losses, g_losses
441
+
442
+
443
+ def generator_loss(disc_outputs):
444
+ loss = 0
445
+ gen_losses = []
446
+ for dg in disc_outputs:
447
+ l = torch.mean((1 - dg)**2)
448
+ gen_losses.append(l)
449
+ loss += l
450
+
451
+ return loss, gen_losses