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

Clean up previous raw files

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