Plana-Archive commited on
Commit
7f0f7eb
·
verified ·
1 Parent(s): 382a899

Clean up previous raw files

Browse files
Files changed (1) hide show
  1. Zero-CPU/models_jp_extra.py +0 -1072
Zero-CPU/models_jp_extra.py DELETED
@@ -1,1072 +0,0 @@
1
- import math
2
- import torch
3
- from torch import nn
4
- from torch.nn import functional as F
5
-
6
- import commons
7
- import modules
8
- import attentions
9
- import monotonic_align
10
-
11
- from torch.nn import Conv1d, ConvTranspose1d, Conv2d
12
- from torch.nn.utils import remove_weight_norm
13
- from torch.nn.utils.parametrizations import spectral_norm, weight_norm
14
-
15
- from commons import init_weights, get_padding
16
- from text import symbols, num_tones, num_languages
17
-
18
-
19
- class DurationDiscriminator(nn.Module): # vits2
20
- def __init__(
21
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
22
- ):
23
- super().__init__()
24
-
25
- self.in_channels = in_channels
26
- self.filter_channels = filter_channels
27
- self.kernel_size = kernel_size
28
- self.p_dropout = p_dropout
29
- self.gin_channels = gin_channels
30
-
31
- self.drop = nn.Dropout(p_dropout)
32
- self.conv_1 = nn.Conv1d(
33
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
34
- )
35
- self.norm_1 = modules.LayerNorm(filter_channels)
36
- self.conv_2 = nn.Conv1d(
37
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
38
- )
39
- self.norm_2 = modules.LayerNorm(filter_channels)
40
- self.dur_proj = nn.Conv1d(1, filter_channels, 1)
41
-
42
- self.LSTM = nn.LSTM(
43
- 2 * filter_channels, filter_channels, batch_first=True, bidirectional=True
44
- )
45
-
46
- if gin_channels != 0:
47
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
48
-
49
- self.output_layer = nn.Sequential(
50
- nn.Linear(2 * filter_channels, 1), nn.Sigmoid()
51
- )
52
-
53
- def forward_probability(self, x, dur):
54
- dur = self.dur_proj(dur)
55
- x = torch.cat([x, dur], dim=1)
56
- x = x.transpose(1, 2)
57
- x, _ = self.LSTM(x)
58
- output_prob = self.output_layer(x)
59
- return output_prob
60
-
61
- def forward(self, x, x_mask, dur_r, dur_hat, g=None):
62
- x = torch.detach(x)
63
- if g is not None:
64
- g = torch.detach(g)
65
- x = x + self.cond(g)
66
- x = self.conv_1(x * x_mask)
67
- x = torch.relu(x)
68
- x = self.norm_1(x)
69
- x = self.drop(x)
70
- x = self.conv_2(x * x_mask)
71
- x = torch.relu(x)
72
- x = self.norm_2(x)
73
- x = self.drop(x)
74
-
75
- output_probs = []
76
- for dur in [dur_r, dur_hat]:
77
- output_prob = self.forward_probability(x, dur)
78
- output_probs.append(output_prob)
79
-
80
- return output_probs
81
-
82
-
83
- class TransformerCouplingBlock(nn.Module):
84
- def __init__(
85
- self,
86
- channels,
87
- hidden_channels,
88
- filter_channels,
89
- n_heads,
90
- n_layers,
91
- kernel_size,
92
- p_dropout,
93
- n_flows=4,
94
- gin_channels=0,
95
- share_parameter=False,
96
- ):
97
- super().__init__()
98
- self.channels = channels
99
- self.hidden_channels = hidden_channels
100
- self.kernel_size = kernel_size
101
- self.n_layers = n_layers
102
- self.n_flows = n_flows
103
- self.gin_channels = gin_channels
104
-
105
- self.flows = nn.ModuleList()
106
-
107
- self.wn = (
108
- attentions.FFT(
109
- hidden_channels,
110
- filter_channels,
111
- n_heads,
112
- n_layers,
113
- kernel_size,
114
- p_dropout,
115
- isflow=True,
116
- gin_channels=self.gin_channels,
117
- )
118
- if share_parameter
119
- else None
120
- )
121
-
122
- for i in range(n_flows):
123
- self.flows.append(
124
- modules.TransformerCouplingLayer(
125
- channels,
126
- hidden_channels,
127
- kernel_size,
128
- n_layers,
129
- n_heads,
130
- p_dropout,
131
- filter_channels,
132
- mean_only=True,
133
- wn_sharing_parameter=self.wn,
134
- gin_channels=self.gin_channels,
135
- )
136
- )
137
- self.flows.append(modules.Flip())
138
-
139
- def forward(self, x, x_mask, g=None, reverse=False):
140
- if not reverse:
141
- for flow in self.flows:
142
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
143
- else:
144
- for flow in reversed(self.flows):
145
- x = flow(x, x_mask, g=g, reverse=reverse)
146
- return x
147
-
148
-
149
- class StochasticDurationPredictor(nn.Module):
150
- def __init__(
151
- self,
152
- in_channels,
153
- filter_channels,
154
- kernel_size,
155
- p_dropout,
156
- n_flows=4,
157
- gin_channels=0,
158
- ):
159
- super().__init__()
160
- filter_channels = in_channels # it needs to be removed from future version.
161
- self.in_channels = in_channels
162
- self.filter_channels = filter_channels
163
- self.kernel_size = kernel_size
164
- self.p_dropout = p_dropout
165
- self.n_flows = n_flows
166
- self.gin_channels = gin_channels
167
-
168
- self.log_flow = modules.Log()
169
- self.flows = nn.ModuleList()
170
- self.flows.append(modules.ElementwiseAffine(2))
171
- for i in range(n_flows):
172
- self.flows.append(
173
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
174
- )
175
- self.flows.append(modules.Flip())
176
-
177
- self.post_pre = nn.Conv1d(1, filter_channels, 1)
178
- self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
179
- self.post_convs = modules.DDSConv(
180
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
181
- )
182
- self.post_flows = nn.ModuleList()
183
- self.post_flows.append(modules.ElementwiseAffine(2))
184
- for i in range(4):
185
- self.post_flows.append(
186
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
187
- )
188
- self.post_flows.append(modules.Flip())
189
-
190
- self.pre = nn.Conv1d(in_channels, filter_channels, 1)
191
- self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
192
- self.convs = modules.DDSConv(
193
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
194
- )
195
- if gin_channels != 0:
196
- self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
197
-
198
- def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
199
- x = torch.detach(x)
200
- x = self.pre(x)
201
- if g is not None:
202
- g = torch.detach(g)
203
- x = x + self.cond(g)
204
- x = self.convs(x, x_mask)
205
- x = self.proj(x) * x_mask
206
-
207
- if not reverse:
208
- flows = self.flows
209
- assert w is not None
210
-
211
- logdet_tot_q = 0
212
- h_w = self.post_pre(w)
213
- h_w = self.post_convs(h_w, x_mask)
214
- h_w = self.post_proj(h_w) * x_mask
215
- e_q = (
216
- torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
217
- * x_mask
218
- )
219
- z_q = e_q
220
- for flow in self.post_flows:
221
- z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
222
- logdet_tot_q += logdet_q
223
- z_u, z1 = torch.split(z_q, [1, 1], 1)
224
- u = torch.sigmoid(z_u) * x_mask
225
- z0 = (w - u) * x_mask
226
- logdet_tot_q += torch.sum(
227
- (F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
228
- )
229
- logq = (
230
- torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
231
- - logdet_tot_q
232
- )
233
-
234
- logdet_tot = 0
235
- z0, logdet = self.log_flow(z0, x_mask)
236
- logdet_tot += logdet
237
- z = torch.cat([z0, z1], 1)
238
- for flow in flows:
239
- z, logdet = flow(z, x_mask, g=x, reverse=reverse)
240
- logdet_tot = logdet_tot + logdet
241
- nll = (
242
- torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
243
- - logdet_tot
244
- )
245
- return nll + logq # [b]
246
- else:
247
- flows = list(reversed(self.flows))
248
- flows = flows[:-2] + [flows[-1]] # remove a useless vflow
249
- z = (
250
- torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
251
- * noise_scale
252
- )
253
- for flow in flows:
254
- z = flow(z, x_mask, g=x, reverse=reverse)
255
- z0, z1 = torch.split(z, [1, 1], 1)
256
- logw = z0
257
- return logw
258
-
259
-
260
- class DurationPredictor(nn.Module):
261
- def __init__(
262
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
263
- ):
264
- super().__init__()
265
-
266
- self.in_channels = in_channels
267
- self.filter_channels = filter_channels
268
- self.kernel_size = kernel_size
269
- self.p_dropout = p_dropout
270
- self.gin_channels = gin_channels
271
-
272
- self.drop = nn.Dropout(p_dropout)
273
- self.conv_1 = nn.Conv1d(
274
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
275
- )
276
- self.norm_1 = modules.LayerNorm(filter_channels)
277
- self.conv_2 = nn.Conv1d(
278
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
279
- )
280
- self.norm_2 = modules.LayerNorm(filter_channels)
281
- self.proj = nn.Conv1d(filter_channels, 1, 1)
282
-
283
- if gin_channels != 0:
284
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
285
-
286
- def forward(self, x, x_mask, g=None):
287
- x = torch.detach(x)
288
- if g is not None:
289
- g = torch.detach(g)
290
- x = x + self.cond(g)
291
- x = self.conv_1(x * x_mask)
292
- x = torch.relu(x)
293
- x = self.norm_1(x)
294
- x = self.drop(x)
295
- x = self.conv_2(x * x_mask)
296
- x = torch.relu(x)
297
- x = self.norm_2(x)
298
- x = self.drop(x)
299
- x = self.proj(x * x_mask)
300
- return x * x_mask
301
-
302
-
303
- class Bottleneck(nn.Sequential):
304
- def __init__(self, in_dim, hidden_dim):
305
- c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
306
- c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
307
- super().__init__(*[c_fc1, c_fc2])
308
-
309
-
310
- class Block(nn.Module):
311
- def __init__(self, in_dim, hidden_dim) -> None:
312
- super().__init__()
313
- self.norm = nn.LayerNorm(in_dim)
314
- self.mlp = MLP(in_dim, hidden_dim)
315
-
316
- def forward(self, x: torch.Tensor) -> torch.Tensor:
317
- x = x + self.mlp(self.norm(x))
318
- return x
319
-
320
-
321
- class MLP(nn.Module):
322
- def __init__(self, in_dim, hidden_dim):
323
- super().__init__()
324
- self.c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
325
- self.c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
326
- self.c_proj = nn.Linear(hidden_dim, in_dim, bias=False)
327
-
328
- def forward(self, x: torch.Tensor):
329
- x = F.silu(self.c_fc1(x)) * self.c_fc2(x)
330
- x = self.c_proj(x)
331
- return x
332
-
333
-
334
- class TextEncoder(nn.Module):
335
- def __init__(
336
- self,
337
- n_vocab,
338
- out_channels,
339
- hidden_channels,
340
- filter_channels,
341
- n_heads,
342
- n_layers,
343
- kernel_size,
344
- p_dropout,
345
- gin_channels=0,
346
- ):
347
- super().__init__()
348
- self.n_vocab = n_vocab
349
- self.out_channels = out_channels
350
- self.hidden_channels = hidden_channels
351
- self.filter_channels = filter_channels
352
- self.n_heads = n_heads
353
- self.n_layers = n_layers
354
- self.kernel_size = kernel_size
355
- self.p_dropout = p_dropout
356
- self.gin_channels = gin_channels
357
- self.emb = nn.Embedding(len(symbols), hidden_channels)
358
- nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
359
- self.tone_emb = nn.Embedding(num_tones, hidden_channels)
360
- nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
361
- self.language_emb = nn.Embedding(num_languages, hidden_channels)
362
- nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
363
- self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
364
-
365
- # Remove emo_vq since it's not working well.
366
- self.style_proj = nn.Linear(256, hidden_channels)
367
-
368
- self.encoder = attentions.Encoder(
369
- hidden_channels,
370
- filter_channels,
371
- n_heads,
372
- n_layers,
373
- kernel_size,
374
- p_dropout,
375
- gin_channels=self.gin_channels,
376
- )
377
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
378
-
379
- def forward(self, x, x_lengths, tone, language, bert, style_vec, g=None):
380
- bert_emb = self.bert_proj(bert).transpose(1, 2)
381
- style_emb = self.style_proj(style_vec.unsqueeze(1))
382
- x = (
383
- self.emb(x)
384
- + self.tone_emb(tone)
385
- + self.language_emb(language)
386
- + bert_emb
387
- + style_emb
388
- ) * math.sqrt(
389
- self.hidden_channels
390
- ) # [b, t, h]
391
- x = torch.transpose(x, 1, -1) # [b, h, t]
392
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
393
- x.dtype
394
- )
395
-
396
- x = self.encoder(x * x_mask, x_mask, g=g)
397
- stats = self.proj(x) * x_mask
398
-
399
- m, logs = torch.split(stats, self.out_channels, dim=1)
400
- return x, m, logs, x_mask
401
-
402
-
403
- class ResidualCouplingBlock(nn.Module):
404
- def __init__(
405
- self,
406
- channels,
407
- hidden_channels,
408
- kernel_size,
409
- dilation_rate,
410
- n_layers,
411
- n_flows=4,
412
- gin_channels=0,
413
- ):
414
- super().__init__()
415
- self.channels = channels
416
- self.hidden_channels = hidden_channels
417
- self.kernel_size = kernel_size
418
- self.dilation_rate = dilation_rate
419
- self.n_layers = n_layers
420
- self.n_flows = n_flows
421
- self.gin_channels = gin_channels
422
-
423
- self.flows = nn.ModuleList()
424
- for i in range(n_flows):
425
- self.flows.append(
426
- modules.ResidualCouplingLayer(
427
- channels,
428
- hidden_channels,
429
- kernel_size,
430
- dilation_rate,
431
- n_layers,
432
- gin_channels=gin_channels,
433
- mean_only=True,
434
- )
435
- )
436
- self.flows.append(modules.Flip())
437
-
438
- def forward(self, x, x_mask, g=None, reverse=False):
439
- if not reverse:
440
- for flow in self.flows:
441
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
442
- else:
443
- for flow in reversed(self.flows):
444
- x = flow(x, x_mask, g=g, reverse=reverse)
445
- return x
446
-
447
-
448
- class PosteriorEncoder(nn.Module):
449
- def __init__(
450
- self,
451
- in_channels,
452
- out_channels,
453
- hidden_channels,
454
- kernel_size,
455
- dilation_rate,
456
- n_layers,
457
- gin_channels=0,
458
- ):
459
- super().__init__()
460
- self.in_channels = in_channels
461
- self.out_channels = out_channels
462
- self.hidden_channels = hidden_channels
463
- self.kernel_size = kernel_size
464
- self.dilation_rate = dilation_rate
465
- self.n_layers = n_layers
466
- self.gin_channels = gin_channels
467
-
468
- self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
469
- self.enc = modules.WN(
470
- hidden_channels,
471
- kernel_size,
472
- dilation_rate,
473
- n_layers,
474
- gin_channels=gin_channels,
475
- )
476
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
477
-
478
- def forward(self, x, x_lengths, g=None):
479
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
480
- x.dtype
481
- )
482
- x = self.pre(x) * x_mask
483
- x = self.enc(x, x_mask, g=g)
484
- stats = self.proj(x) * x_mask
485
- m, logs = torch.split(stats, self.out_channels, dim=1)
486
- z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
487
- return z, m, logs, x_mask
488
-
489
-
490
- class Generator(torch.nn.Module):
491
- def __init__(
492
- self,
493
- initial_channel,
494
- resblock,
495
- resblock_kernel_sizes,
496
- resblock_dilation_sizes,
497
- upsample_rates,
498
- upsample_initial_channel,
499
- upsample_kernel_sizes,
500
- gin_channels=0,
501
- ):
502
- super(Generator, self).__init__()
503
- self.num_kernels = len(resblock_kernel_sizes)
504
- self.num_upsamples = len(upsample_rates)
505
- self.conv_pre = Conv1d(
506
- initial_channel, upsample_initial_channel, 7, 1, padding=3
507
- )
508
- resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
509
-
510
- self.ups = nn.ModuleList()
511
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
512
- self.ups.append(
513
- weight_norm(
514
- ConvTranspose1d(
515
- upsample_initial_channel // (2**i),
516
- upsample_initial_channel // (2 ** (i + 1)),
517
- k,
518
- u,
519
- padding=(k - u) // 2,
520
- )
521
- )
522
- )
523
-
524
- self.resblocks = nn.ModuleList()
525
- for i in range(len(self.ups)):
526
- ch = upsample_initial_channel // (2 ** (i + 1))
527
- for j, (k, d) in enumerate(
528
- zip(resblock_kernel_sizes, resblock_dilation_sizes)
529
- ):
530
- self.resblocks.append(resblock(ch, k, d))
531
-
532
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
533
- self.ups.apply(init_weights)
534
-
535
- if gin_channels != 0:
536
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
537
-
538
- def forward(self, x, g=None):
539
- x = self.conv_pre(x)
540
- if g is not None:
541
- x = x + self.cond(g)
542
-
543
- for i in range(self.num_upsamples):
544
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
545
- x = self.ups[i](x)
546
- xs = None
547
- for j in range(self.num_kernels):
548
- if xs is None:
549
- xs = self.resblocks[i * self.num_kernels + j](x)
550
- else:
551
- xs += self.resblocks[i * self.num_kernels + j](x)
552
- x = xs / self.num_kernels
553
- x = F.leaky_relu(x)
554
- x = self.conv_post(x)
555
- x = torch.tanh(x)
556
-
557
- return x
558
-
559
- def remove_weight_norm(self):
560
- print("Removing weight norm...")
561
- for layer in self.ups:
562
- remove_weight_norm(layer)
563
- for layer in self.resblocks:
564
- layer.remove_weight_norm()
565
-
566
-
567
- class DiscriminatorP(torch.nn.Module):
568
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
569
- super(DiscriminatorP, self).__init__()
570
- self.period = period
571
- self.use_spectral_norm = use_spectral_norm
572
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
573
- self.convs = nn.ModuleList(
574
- [
575
- norm_f(
576
- Conv2d(
577
- 1,
578
- 32,
579
- (kernel_size, 1),
580
- (stride, 1),
581
- padding=(get_padding(kernel_size, 1), 0),
582
- )
583
- ),
584
- norm_f(
585
- Conv2d(
586
- 32,
587
- 128,
588
- (kernel_size, 1),
589
- (stride, 1),
590
- padding=(get_padding(kernel_size, 1), 0),
591
- )
592
- ),
593
- norm_f(
594
- Conv2d(
595
- 128,
596
- 512,
597
- (kernel_size, 1),
598
- (stride, 1),
599
- padding=(get_padding(kernel_size, 1), 0),
600
- )
601
- ),
602
- norm_f(
603
- Conv2d(
604
- 512,
605
- 1024,
606
- (kernel_size, 1),
607
- (stride, 1),
608
- padding=(get_padding(kernel_size, 1), 0),
609
- )
610
- ),
611
- norm_f(
612
- Conv2d(
613
- 1024,
614
- 1024,
615
- (kernel_size, 1),
616
- 1,
617
- padding=(get_padding(kernel_size, 1), 0),
618
- )
619
- ),
620
- ]
621
- )
622
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
623
-
624
- def forward(self, x):
625
- fmap = []
626
-
627
- # 1d to 2d
628
- b, c, t = x.shape
629
- if t % self.period != 0: # pad first
630
- n_pad = self.period - (t % self.period)
631
- x = F.pad(x, (0, n_pad), "reflect")
632
- t = t + n_pad
633
- x = x.view(b, c, t // self.period, self.period)
634
-
635
- for layer in self.convs:
636
- x = layer(x)
637
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
638
- fmap.append(x)
639
- x = self.conv_post(x)
640
- fmap.append(x)
641
- x = torch.flatten(x, 1, -1)
642
-
643
- return x, fmap
644
-
645
-
646
- class DiscriminatorS(torch.nn.Module):
647
- def __init__(self, use_spectral_norm=False):
648
- super(DiscriminatorS, self).__init__()
649
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
650
- self.convs = nn.ModuleList(
651
- [
652
- norm_f(Conv1d(1, 16, 15, 1, padding=7)),
653
- norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
654
- norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
655
- norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
656
- norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
657
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
658
- ]
659
- )
660
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
661
-
662
- def forward(self, x):
663
- fmap = []
664
-
665
- for layer in self.convs:
666
- x = layer(x)
667
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
668
- fmap.append(x)
669
- x = self.conv_post(x)
670
- fmap.append(x)
671
- x = torch.flatten(x, 1, -1)
672
-
673
- return x, fmap
674
-
675
-
676
- class MultiPeriodDiscriminator(torch.nn.Module):
677
- def __init__(self, use_spectral_norm=False):
678
- super(MultiPeriodDiscriminator, self).__init__()
679
- periods = [2, 3, 5, 7, 11]
680
-
681
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
682
- discs = discs + [
683
- DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
684
- ]
685
- self.discriminators = nn.ModuleList(discs)
686
-
687
- def forward(self, y, y_hat):
688
- y_d_rs = []
689
- y_d_gs = []
690
- fmap_rs = []
691
- fmap_gs = []
692
- for i, d in enumerate(self.discriminators):
693
- y_d_r, fmap_r = d(y)
694
- y_d_g, fmap_g = d(y_hat)
695
- y_d_rs.append(y_d_r)
696
- y_d_gs.append(y_d_g)
697
- fmap_rs.append(fmap_r)
698
- fmap_gs.append(fmap_g)
699
-
700
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
701
-
702
-
703
- class WavLMDiscriminator(nn.Module):
704
- """docstring for Discriminator."""
705
-
706
- def __init__(
707
- self, slm_hidden=768, slm_layers=13, initial_channel=64, use_spectral_norm=False
708
- ):
709
- super(WavLMDiscriminator, self).__init__()
710
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
711
- self.pre = norm_f(
712
- Conv1d(slm_hidden * slm_layers, initial_channel, 1, 1, padding=0)
713
- )
714
-
715
- self.convs = nn.ModuleList(
716
- [
717
- norm_f(
718
- nn.Conv1d(
719
- initial_channel, initial_channel * 2, kernel_size=5, padding=2
720
- )
721
- ),
722
- norm_f(
723
- nn.Conv1d(
724
- initial_channel * 2,
725
- initial_channel * 4,
726
- kernel_size=5,
727
- padding=2,
728
- )
729
- ),
730
- norm_f(
731
- nn.Conv1d(initial_channel * 4, initial_channel * 4, 5, 1, padding=2)
732
- ),
733
- ]
734
- )
735
-
736
- self.conv_post = norm_f(Conv1d(initial_channel * 4, 1, 3, 1, padding=1))
737
-
738
- def forward(self, x):
739
- x = self.pre(x)
740
-
741
- fmap = []
742
- for l in self.convs:
743
- x = l(x)
744
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
745
- fmap.append(x)
746
- x = self.conv_post(x)
747
- x = torch.flatten(x, 1, -1)
748
-
749
- return x
750
-
751
-
752
- class ReferenceEncoder(nn.Module):
753
- """
754
- inputs --- [N, Ty/r, n_mels*r] mels
755
- outputs --- [N, ref_enc_gru_size]
756
- """
757
-
758
- def __init__(self, spec_channels, gin_channels=0):
759
- super().__init__()
760
- self.spec_channels = spec_channels
761
- ref_enc_filters = [32, 32, 64, 64, 128, 128]
762
- K = len(ref_enc_filters)
763
- filters = [1] + ref_enc_filters
764
- convs = [
765
- weight_norm(
766
- nn.Conv2d(
767
- in_channels=filters[i],
768
- out_channels=filters[i + 1],
769
- kernel_size=(3, 3),
770
- stride=(2, 2),
771
- padding=(1, 1),
772
- )
773
- )
774
- for i in range(K)
775
- ]
776
- self.convs = nn.ModuleList(convs)
777
- # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) # noqa: E501
778
-
779
- out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
780
- self.gru = nn.GRU(
781
- input_size=ref_enc_filters[-1] * out_channels,
782
- hidden_size=256 // 2,
783
- batch_first=True,
784
- )
785
- self.proj = nn.Linear(128, gin_channels)
786
-
787
- def forward(self, inputs, mask=None):
788
- N = inputs.size(0)
789
- out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
790
- for conv in self.convs:
791
- out = conv(out)
792
- # out = wn(out)
793
- out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
794
-
795
- out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
796
- T = out.size(1)
797
- N = out.size(0)
798
- out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
799
-
800
- self.gru.flatten_parameters()
801
- memory, out = self.gru(out) # out --- [1, N, 128]
802
-
803
- return self.proj(out.squeeze(0))
804
-
805
- def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
806
- for i in range(n_convs):
807
- L = (L - kernel_size + 2 * pad) // stride + 1
808
- return L
809
-
810
-
811
- class SynthesizerTrn(nn.Module):
812
- """
813
- Synthesizer for Training
814
- """
815
-
816
- def __init__(
817
- self,
818
- n_vocab,
819
- spec_channels,
820
- segment_size,
821
- inter_channels,
822
- hidden_channels,
823
- filter_channels,
824
- n_heads,
825
- n_layers,
826
- kernel_size,
827
- p_dropout,
828
- resblock,
829
- resblock_kernel_sizes,
830
- resblock_dilation_sizes,
831
- upsample_rates,
832
- upsample_initial_channel,
833
- upsample_kernel_sizes,
834
- n_speakers=256,
835
- gin_channels=256,
836
- use_sdp=True,
837
- n_flow_layer=4,
838
- n_layers_trans_flow=6,
839
- flow_share_parameter=False,
840
- use_transformer_flow=True,
841
- **kwargs
842
- ):
843
- super().__init__()
844
- self.n_vocab = n_vocab
845
- self.spec_channels = spec_channels
846
- self.inter_channels = inter_channels
847
- self.hidden_channels = hidden_channels
848
- self.filter_channels = filter_channels
849
- self.n_heads = n_heads
850
- self.n_layers = n_layers
851
- self.kernel_size = kernel_size
852
- self.p_dropout = p_dropout
853
- self.resblock = resblock
854
- self.resblock_kernel_sizes = resblock_kernel_sizes
855
- self.resblock_dilation_sizes = resblock_dilation_sizes
856
- self.upsample_rates = upsample_rates
857
- self.upsample_initial_channel = upsample_initial_channel
858
- self.upsample_kernel_sizes = upsample_kernel_sizes
859
- self.segment_size = segment_size
860
- self.n_speakers = n_speakers
861
- self.gin_channels = gin_channels
862
- self.n_layers_trans_flow = n_layers_trans_flow
863
- self.use_spk_conditioned_encoder = kwargs.get(
864
- "use_spk_conditioned_encoder", True
865
- )
866
- self.use_sdp = use_sdp
867
- self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
868
- self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
869
- self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
870
- self.current_mas_noise_scale = self.mas_noise_scale_initial
871
- if self.use_spk_conditioned_encoder and gin_channels > 0:
872
- self.enc_gin_channels = gin_channels
873
- self.enc_p = TextEncoder(
874
- n_vocab,
875
- inter_channels,
876
- hidden_channels,
877
- filter_channels,
878
- n_heads,
879
- n_layers,
880
- kernel_size,
881
- p_dropout,
882
- gin_channels=self.enc_gin_channels,
883
- )
884
- self.dec = Generator(
885
- inter_channels,
886
- resblock,
887
- resblock_kernel_sizes,
888
- resblock_dilation_sizes,
889
- upsample_rates,
890
- upsample_initial_channel,
891
- upsample_kernel_sizes,
892
- gin_channels=gin_channels,
893
- )
894
- self.enc_q = PosteriorEncoder(
895
- spec_channels,
896
- inter_channels,
897
- hidden_channels,
898
- 5,
899
- 1,
900
- 16,
901
- gin_channels=gin_channels,
902
- )
903
- if use_transformer_flow:
904
- self.flow = TransformerCouplingBlock(
905
- inter_channels,
906
- hidden_channels,
907
- filter_channels,
908
- n_heads,
909
- n_layers_trans_flow,
910
- 5,
911
- p_dropout,
912
- n_flow_layer,
913
- gin_channels=gin_channels,
914
- share_parameter=flow_share_parameter,
915
- )
916
- else:
917
- self.flow = ResidualCouplingBlock(
918
- inter_channels,
919
- hidden_channels,
920
- 5,
921
- 1,
922
- n_flow_layer,
923
- gin_channels=gin_channels,
924
- )
925
- self.sdp = StochasticDurationPredictor(
926
- hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
927
- )
928
- self.dp = DurationPredictor(
929
- hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
930
- )
931
-
932
- if n_speakers >= 1:
933
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
934
- else:
935
- self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
936
-
937
- def forward(
938
- self,
939
- x,
940
- x_lengths,
941
- y,
942
- y_lengths,
943
- sid,
944
- tone,
945
- language,
946
- bert,
947
- style_vec,
948
- ):
949
- if self.n_speakers > 0:
950
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
951
- else:
952
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
953
- x, m_p, logs_p, x_mask = self.enc_p(
954
- x, x_lengths, tone, language, bert, style_vec, g=g
955
- )
956
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
957
- z_p = self.flow(z, y_mask, g=g)
958
-
959
- with torch.no_grad():
960
- # negative cross-entropy
961
- s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
962
- neg_cent1 = torch.sum(
963
- -0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
964
- ) # [b, 1, t_s]
965
- neg_cent2 = torch.matmul(
966
- -0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
967
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
968
- neg_cent3 = torch.matmul(
969
- z_p.transpose(1, 2), (m_p * s_p_sq_r)
970
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
971
- neg_cent4 = torch.sum(
972
- -0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
973
- ) # [b, 1, t_s]
974
- neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
975
- if self.use_noise_scaled_mas:
976
- epsilon = (
977
- torch.std(neg_cent)
978
- * torch.randn_like(neg_cent)
979
- * self.current_mas_noise_scale
980
- )
981
- neg_cent = neg_cent + epsilon
982
-
983
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
984
- attn = (
985
- monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))
986
- .unsqueeze(1)
987
- .detach()
988
- )
989
-
990
- w = attn.sum(2)
991
-
992
- l_length_sdp = self.sdp(x, x_mask, w, g=g)
993
- l_length_sdp = l_length_sdp / torch.sum(x_mask)
994
-
995
- logw_ = torch.log(w + 1e-6) * x_mask
996
- logw = self.dp(x, x_mask, g=g)
997
- # logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
998
- l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
999
- x_mask
1000
- ) # for averaging
1001
- # l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
1002
-
1003
- l_length = l_length_dp + l_length_sdp
1004
-
1005
- # expand prior
1006
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
1007
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
1008
-
1009
- z_slice, ids_slice = commons.rand_slice_segments(
1010
- z, y_lengths, self.segment_size
1011
- )
1012
- o = self.dec(z_slice, g=g)
1013
- return (
1014
- o,
1015
- l_length,
1016
- attn,
1017
- ids_slice,
1018
- x_mask,
1019
- y_mask,
1020
- (z, z_p, m_p, logs_p, m_q, logs_q),
1021
- (x, logw, logw_), # , logw_sdp),
1022
- g,
1023
- )
1024
-
1025
- def infer(
1026
- self,
1027
- x,
1028
- x_lengths,
1029
- sid,
1030
- tone,
1031
- language,
1032
- bert,
1033
- style_vec,
1034
- noise_scale=0.667,
1035
- length_scale=1,
1036
- noise_scale_w=0.8,
1037
- max_len=None,
1038
- sdp_ratio=0,
1039
- y=None,
1040
- ):
1041
- # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
1042
- # g = self.gst(y)
1043
- if self.n_speakers > 0:
1044
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
1045
- else:
1046
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
1047
- x, m_p, logs_p, x_mask = self.enc_p(
1048
- x, x_lengths, tone, language, bert, style_vec, g=g
1049
- )
1050
- logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
1051
- sdp_ratio
1052
- ) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
1053
- w = torch.exp(logw) * x_mask * length_scale
1054
- w_ceil = torch.ceil(w)
1055
- y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
1056
- y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
1057
- x_mask.dtype
1058
- )
1059
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
1060
- attn = commons.generate_path(w_ceil, attn_mask)
1061
-
1062
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
1063
- 1, 2
1064
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1065
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
1066
- 1, 2
1067
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1068
-
1069
- z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
1070
- z = self.flow(z_p, y_mask, g=g, reverse=True)
1071
- o = self.dec((z * y_mask)[:, :, :max_len], g=g)
1072
- return o, attn, y_mask, (z, z_p, m_p, logs_p)