JotunnBurton commited on
Commit
f96eb4f
·
verified ·
1 Parent(s): b910c48

Delete models.py

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