Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

models.py 26 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
  1. # coding:utf-8
  2. import os
  3. import os.path as osp
  4. import copy
  5. import math
  6. import numpy as np
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.functional as F
  10. from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
  11. from Utils.ASR.models import ASRCNN
  12. from Utils.JDC.model import JDCNet
  13. from Modules.diffusion.sampler import KDiffusion, LogNormalDistribution
  14. from Modules.diffusion.modules import Transformer1d, StyleTransformer1d
  15. from Modules.diffusion.diffusion import AudioDiffusionConditional
  16. from Modules.discriminators import MultiPeriodDiscriminator, MultiResSpecDiscriminator, WavLMDiscriminator
  17. from munch import Munch
  18. import yaml
  19. class LearnedDownSample(nn.Module):
  20. def __init__(self, layer_type, dim_in):
  21. super().__init__()
  22. self.layer_type = layer_type
  23. if self.layer_type == 'none':
  24. self.conv = nn.Identity()
  25. elif self.layer_type == 'timepreserve':
  26. self.conv = spectral_norm(
  27. nn.Conv2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in, padding=(1, 0)))
  28. elif self.layer_type == 'half':
  29. self.conv = spectral_norm(
  30. nn.Conv2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in, padding=1))
  31. else:
  32. raise RuntimeError(
  33. 'Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
  34. def forward(self, x):
  35. return self.conv(x)
  36. class LearnedUpSample(nn.Module):
  37. def __init__(self, layer_type, dim_in):
  38. super().__init__()
  39. self.layer_type = layer_type
  40. if self.layer_type == 'none':
  41. self.conv = nn.Identity()
  42. elif self.layer_type == 'timepreserve':
  43. self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in,
  44. output_padding=(1, 0), padding=(1, 0))
  45. elif self.layer_type == 'half':
  46. self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in,
  47. output_padding=1, padding=1)
  48. else:
  49. raise RuntimeError(
  50. 'Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
  51. def forward(self, x):
  52. return self.conv(x)
  53. class DownSample(nn.Module):
  54. def __init__(self, layer_type):
  55. super().__init__()
  56. self.layer_type = layer_type
  57. def forward(self, x):
  58. if self.layer_type == 'none':
  59. return x
  60. elif self.layer_type == 'timepreserve':
  61. return F.avg_pool2d(x, (2, 1))
  62. elif self.layer_type == 'half':
  63. if x.shape[-1] % 2 != 0:
  64. x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1)
  65. return F.avg_pool2d(x, 2)
  66. else:
  67. raise RuntimeError(
  68. 'Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
  69. class UpSample(nn.Module):
  70. def __init__(self, layer_type):
  71. super().__init__()
  72. self.layer_type = layer_type
  73. def forward(self, x):
  74. if self.layer_type == 'none':
  75. return x
  76. elif self.layer_type == 'timepreserve':
  77. return F.interpolate(x, scale_factor=(2, 1), mode='nearest')
  78. elif self.layer_type == 'half':
  79. return F.interpolate(x, scale_factor=2, mode='nearest')
  80. else:
  81. raise RuntimeError(
  82. 'Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
  83. class ResBlk(nn.Module):
  84. def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2),
  85. normalize=False, downsample='none'):
  86. super().__init__()
  87. self.actv = actv
  88. self.normalize = normalize
  89. self.downsample = DownSample(downsample)
  90. self.downsample_res = LearnedDownSample(downsample, dim_in)
  91. self.learned_sc = dim_in != dim_out
  92. self._build_weights(dim_in, dim_out)
  93. def _build_weights(self, dim_in, dim_out):
  94. self.conv1 = spectral_norm(nn.Conv2d(dim_in, dim_in, 3, 1, 1))
  95. self.conv2 = spectral_norm(nn.Conv2d(dim_in, dim_out, 3, 1, 1))
  96. if self.normalize:
  97. self.norm1 = nn.InstanceNorm2d(dim_in, affine=True)
  98. self.norm2 = nn.InstanceNorm2d(dim_in, affine=True)
  99. if self.learned_sc:
  100. self.conv1x1 = spectral_norm(nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False))
  101. def _shortcut(self, x):
  102. if self.learned_sc:
  103. x = self.conv1x1(x)
  104. if self.downsample:
  105. x = self.downsample(x)
  106. return x
  107. def _residual(self, x):
  108. if self.normalize:
  109. x = self.norm1(x)
  110. x = self.actv(x)
  111. x = self.conv1(x)
  112. x = self.downsample_res(x)
  113. if self.normalize:
  114. x = self.norm2(x)
  115. x = self.actv(x)
  116. x = self.conv2(x)
  117. return x
  118. def forward(self, x):
  119. x = self._shortcut(x) + self._residual(x)
  120. return x / math.sqrt(2) # unit variance
  121. class StyleEncoder(nn.Module):
  122. def __init__(self, dim_in=48, style_dim=48, max_conv_dim=384):
  123. super().__init__()
  124. blocks = []
  125. blocks += [spectral_norm(nn.Conv2d(1, dim_in, 3, 1, 1))]
  126. repeat_num = 4
  127. for _ in range(repeat_num):
  128. dim_out = min(dim_in * 2, max_conv_dim)
  129. blocks += [ResBlk(dim_in, dim_out, downsample='half')]
  130. dim_in = dim_out
  131. blocks += [nn.LeakyReLU(0.2)]
  132. blocks += [spectral_norm(nn.Conv2d(dim_out, dim_out, 5, 1, 0))]
  133. blocks += [nn.AdaptiveAvgPool2d(1)]
  134. blocks += [nn.LeakyReLU(0.2)]
  135. self.shared = nn.Sequential(*blocks)
  136. self.unshared = nn.Linear(dim_out, style_dim)
  137. def forward(self, x):
  138. # print(x.shape)
  139. h = self.shared(x)
  140. h = h.view(h.size(0), -1)
  141. s = self.unshared(h)
  142. return s
  143. class LinearNorm(torch.nn.Module):
  144. def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
  145. super(LinearNorm, self).__init__()
  146. self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
  147. torch.nn.init.xavier_uniform_(
  148. self.linear_layer.weight,
  149. gain=torch.nn.init.calculate_gain(w_init_gain))
  150. def forward(self, x):
  151. return self.linear_layer(x)
  152. class Discriminator2d(nn.Module):
  153. def __init__(self, dim_in=48, num_domains=1, max_conv_dim=384, repeat_num=4):
  154. super().__init__()
  155. blocks = []
  156. blocks += [spectral_norm(nn.Conv2d(1, dim_in, 3, 1, 1))]
  157. for lid in range(repeat_num):
  158. dim_out = min(dim_in * 2, max_conv_dim)
  159. blocks += [ResBlk(dim_in, dim_out, downsample='half')]
  160. dim_in = dim_out
  161. blocks += [nn.LeakyReLU(0.2)]
  162. blocks += [spectral_norm(nn.Conv2d(dim_out, dim_out, 5, 1, 0))]
  163. blocks += [nn.LeakyReLU(0.2)]
  164. blocks += [nn.AdaptiveAvgPool2d(1)]
  165. blocks += [spectral_norm(nn.Conv2d(dim_out, num_domains, 1, 1, 0))]
  166. self.main = nn.Sequential(*blocks)
  167. def get_feature(self, x):
  168. features = []
  169. for l in self.main:
  170. x = l(x)
  171. features.append(x)
  172. out = features[-1]
  173. out = out.view(out.size(0), -1) # (batch, num_domains)
  174. return out, features
  175. def forward(self, x):
  176. out, features = self.get_feature(x)
  177. out = out.squeeze() # (batch)
  178. return out, features
  179. class ResBlk1d(nn.Module):
  180. def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2),
  181. normalize=False, downsample='none', dropout_p=0.2):
  182. super().__init__()
  183. self.actv = actv
  184. self.normalize = normalize
  185. self.downsample_type = downsample
  186. self.learned_sc = dim_in != dim_out
  187. self._build_weights(dim_in, dim_out)
  188. self.dropout_p = dropout_p
  189. if self.downsample_type == 'none':
  190. self.pool = nn.Identity()
  191. else:
  192. self.pool = weight_norm(nn.Conv1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1))
  193. def _build_weights(self, dim_in, dim_out):
  194. self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_in, 3, 1, 1))
  195. self.conv2 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
  196. if self.normalize:
  197. self.norm1 = nn.InstanceNorm1d(dim_in, affine=True)
  198. self.norm2 = nn.InstanceNorm1d(dim_in, affine=True)
  199. if self.learned_sc:
  200. self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
  201. def downsample(self, x):
  202. if self.downsample_type == 'none':
  203. return x
  204. else:
  205. if x.shape[-1] % 2 != 0:
  206. x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1)
  207. return F.avg_pool1d(x, 2)
  208. def _shortcut(self, x):
  209. if self.learned_sc:
  210. x = self.conv1x1(x)
  211. x = self.downsample(x)
  212. return x
  213. def _residual(self, x):
  214. if self.normalize:
  215. x = self.norm1(x)
  216. x = self.actv(x)
  217. x = F.dropout(x, p=self.dropout_p, training=self.training)
  218. x = self.conv1(x)
  219. x = self.pool(x)
  220. if self.normalize:
  221. x = self.norm2(x)
  222. x = self.actv(x)
  223. x = F.dropout(x, p=self.dropout_p, training=self.training)
  224. x = self.conv2(x)
  225. return x
  226. def forward(self, x):
  227. x = self._shortcut(x) + self._residual(x)
  228. return x / math.sqrt(2) # unit variance
  229. class LayerNorm(nn.Module):
  230. def __init__(self, channels, eps=1e-5):
  231. super().__init__()
  232. self.channels = channels
  233. self.eps = eps
  234. self.gamma = nn.Parameter(torch.ones(channels))
  235. self.beta = nn.Parameter(torch.zeros(channels))
  236. def forward(self, x):
  237. x = x.transpose(1, -1)
  238. x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
  239. return x.transpose(1, -1)
  240. class TextEncoder(nn.Module):
  241. def __init__(self, channels, kernel_size, depth, n_symbols, actv=nn.LeakyReLU(0.2)):
  242. super().__init__()
  243. self.embedding = nn.Embedding(n_symbols, channels)
  244. padding = (kernel_size - 1) // 2
  245. self.cnn = nn.ModuleList()
  246. for _ in range(depth):
  247. self.cnn.append(nn.Sequential(
  248. weight_norm(nn.Conv1d(channels, channels, kernel_size=kernel_size, padding=padding)),
  249. LayerNorm(channels),
  250. actv,
  251. nn.Dropout(0.2),
  252. ))
  253. # self.cnn = nn.Sequential(*self.cnn)
  254. self.lstm = nn.LSTM(channels, channels // 2, 1, batch_first=True, bidirectional=True)
  255. def forward(self, x, input_lengths, m):
  256. x = self.embedding(x) # [B, T, emb]
  257. x = x.transpose(1, 2) # [B, emb, T]
  258. m = m.to(input_lengths.device).unsqueeze(1)
  259. x.masked_fill_(m, 0.0)
  260. for c in self.cnn:
  261. x = c(x)
  262. x.masked_fill_(m, 0.0)
  263. x = x.transpose(1, 2) # [B, T, chn]
  264. input_lengths = input_lengths.cpu().numpy()
  265. x = nn.utils.rnn.pack_padded_sequence(
  266. x, input_lengths, batch_first=True, enforce_sorted=False)
  267. self.lstm.flatten_parameters()
  268. x, _ = self.lstm(x)
  269. x, _ = nn.utils.rnn.pad_packed_sequence(
  270. x, batch_first=True)
  271. x = x.transpose(-1, -2)
  272. x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]])
  273. x_pad[:, :, :x.shape[-1]] = x
  274. x = x_pad.to(x.device)
  275. x.masked_fill_(m, 0.0)
  276. return x
  277. def inference(self, x):
  278. x = self.embedding(x)
  279. x = x.transpose(1, 2)
  280. x = self.cnn(x)
  281. x = x.transpose(1, 2)
  282. self.lstm.flatten_parameters()
  283. x, _ = self.lstm(x)
  284. return x
  285. def length_to_mask(self, lengths):
  286. mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
  287. mask = torch.gt(mask + 1, lengths.unsqueeze(1))
  288. return mask
  289. class AdaIN1d(nn.Module):
  290. def __init__(self, style_dim, num_features):
  291. super().__init__()
  292. self.norm = nn.InstanceNorm1d(num_features, affine=False)
  293. self.fc = nn.Linear(style_dim, num_features * 2)
  294. def forward(self, x, s):
  295. h = self.fc(s)
  296. h = h.view(h.size(0), h.size(1), 1)
  297. gamma, beta = torch.chunk(h, chunks=2, dim=1)
  298. return (1 + gamma) * self.norm(x) + beta
  299. class UpSample1d(nn.Module):
  300. def __init__(self, layer_type):
  301. super().__init__()
  302. self.layer_type = layer_type
  303. def forward(self, x):
  304. if self.layer_type == 'none':
  305. return x
  306. else:
  307. return F.interpolate(x, scale_factor=2, mode='nearest')
  308. class AdainResBlk1d(nn.Module):
  309. def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2),
  310. upsample='none', dropout_p=0.0):
  311. super().__init__()
  312. self.actv = actv
  313. self.upsample_type = upsample
  314. self.upsample = UpSample1d(upsample)
  315. self.learned_sc = dim_in != dim_out
  316. self._build_weights(dim_in, dim_out, style_dim)
  317. self.dropout = nn.Dropout(dropout_p)
  318. if upsample == 'none':
  319. self.pool = nn.Identity()
  320. else:
  321. self.pool = weight_norm(
  322. nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1))
  323. def _build_weights(self, dim_in, dim_out, style_dim):
  324. self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
  325. self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1))
  326. self.norm1 = AdaIN1d(style_dim, dim_in)
  327. self.norm2 = AdaIN1d(style_dim, dim_out)
  328. if self.learned_sc:
  329. self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
  330. def _shortcut(self, x):
  331. x = self.upsample(x)
  332. if self.learned_sc:
  333. x = self.conv1x1(x)
  334. return x
  335. def _residual(self, x, s):
  336. x = self.norm1(x, s)
  337. x = self.actv(x)
  338. x = self.pool(x)
  339. x = self.conv1(self.dropout(x))
  340. x = self.norm2(x, s)
  341. x = self.actv(x)
  342. x = self.conv2(self.dropout(x))
  343. return x
  344. def forward(self, x, s):
  345. out = self._residual(x, s)
  346. out = (out + self._shortcut(x)) / math.sqrt(2)
  347. return out
  348. class AdaLayerNorm(nn.Module):
  349. def __init__(self, style_dim, channels, eps=1e-5):
  350. super().__init__()
  351. self.channels = channels
  352. self.eps = eps
  353. self.fc = nn.Linear(style_dim, channels * 2)
  354. def forward(self, x, s):
  355. x = x.transpose(-1, -2)
  356. x = x.transpose(1, -1)
  357. h = self.fc(s)
  358. # Problem is here
  359. h = h.view(h.size(0), h.size(1), 1)
  360. gamma, beta = torch.chunk(h, chunks=2, dim=1)
  361. gamma, beta = gamma.transpose(1, -1), beta.transpose(1, -1)
  362. x = F.layer_norm(x, (self.channels,), eps=self.eps)
  363. x = (1 + gamma) * x + beta
  364. return x.transpose(1, -1).transpose(-1, -2)
  365. class ProsodyPredictor(nn.Module):
  366. def __init__(self, style_dim, d_hid, nlayers, max_dur=50, dropout=0.1):
  367. super().__init__()
  368. self.text_encoder = DurationEncoder(sty_dim=style_dim,
  369. d_model=d_hid,
  370. nlayers=nlayers,
  371. dropout=dropout)
  372. self.lstm = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
  373. self.duration_proj = LinearNorm(d_hid, max_dur)
  374. self.shared = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
  375. self.F0 = nn.ModuleList()
  376. self.F0.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
  377. self.F0.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
  378. self.F0.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
  379. self.N = nn.ModuleList()
  380. self.N.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
  381. self.N.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
  382. self.N.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
  383. self.F0_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
  384. self.N_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
  385. def forward(self, texts, style, text_lengths, alignment, m):
  386. # Problem is here
  387. d = self.text_encoder(texts, style, text_lengths, m)
  388. batch_size = d.shape[0]
  389. text_size = d.shape[1]
  390. # predict duration
  391. input_lengths = text_lengths.cpu().numpy()
  392. x = nn.utils.rnn.pack_padded_sequence(
  393. d, input_lengths, batch_first=True, enforce_sorted=False)
  394. m = m.to(text_lengths.device).unsqueeze(1)
  395. self.lstm.flatten_parameters()
  396. x, _ = self.lstm(x)
  397. x, _ = nn.utils.rnn.pad_packed_sequence(
  398. x, batch_first=True)
  399. x_pad = torch.zeros([x.shape[0], m.shape[-1], x.shape[-1]])
  400. x_pad[:, :x.shape[1], :] = x
  401. x = x_pad.to(x.device)
  402. duration = self.duration_proj(nn.functional.dropout(x, 0.5, training=self.training))
  403. en = (d.transpose(-1, -2) @ alignment)
  404. return duration.squeeze(-1), en
  405. def F0Ntrain(self, x, s):
  406. x, _ = self.shared(x.transpose(-1, -2))
  407. F0 = x.transpose(-1, -2)
  408. for block in self.F0:
  409. F0 = block(F0, s)
  410. F0 = self.F0_proj(F0)
  411. N = x.transpose(-1, -2)
  412. for block in self.N:
  413. N = block(N, s)
  414. N = self.N_proj(N)
  415. return F0.squeeze(1), N.squeeze(1)
  416. def length_to_mask(self, lengths):
  417. mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
  418. mask = torch.gt(mask + 1, lengths.unsqueeze(1))
  419. return mask
  420. class DurationEncoder(nn.Module):
  421. def __init__(self, sty_dim, d_model, nlayers, dropout=0.1):
  422. super().__init__()
  423. self.lstms = nn.ModuleList()
  424. for _ in range(nlayers):
  425. self.lstms.append(nn.LSTM(d_model + sty_dim,
  426. d_model // 2,
  427. num_layers=1,
  428. batch_first=True,
  429. bidirectional=True,
  430. dropout=dropout))
  431. self.lstms.append(AdaLayerNorm(sty_dim, d_model))
  432. self.dropout = dropout
  433. self.d_model = d_model
  434. self.sty_dim = sty_dim
  435. def forward(self, x, style, text_lengths, m):
  436. masks = m.to(text_lengths.device)
  437. x = x.permute(2, 0, 1)
  438. s = style.expand(x.shape[0], x.shape[1], -1)
  439. x = torch.cat([x, s], axis=-1)
  440. x.masked_fill_(masks.unsqueeze(-1).transpose(0, 1), 0.0)
  441. x = x.transpose(0, 1)
  442. input_lengths = text_lengths.cpu().numpy()
  443. x = x.transpose(-1, -2)
  444. for block in self.lstms:
  445. if isinstance(block, AdaLayerNorm):
  446. # Problem is here
  447. x = block(x.transpose(-1, -2), style).transpose(-1, -2)
  448. x = torch.cat([x, s.permute(1, -1, 0)], axis=1)
  449. x.masked_fill_(masks.unsqueeze(-1).transpose(-1, -2), 0.0)
  450. else:
  451. x = x.transpose(-1, -2)
  452. x = nn.utils.rnn.pack_padded_sequence(
  453. x, input_lengths, batch_first=True, enforce_sorted=False)
  454. block.flatten_parameters()
  455. x, _ = block(x)
  456. x, _ = nn.utils.rnn.pad_packed_sequence(
  457. x, batch_first=True)
  458. x = F.dropout(x, p=self.dropout, training=self.training)
  459. x = x.transpose(-1, -2)
  460. x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]])
  461. x_pad[:, :, :x.shape[-1]] = x
  462. x = x_pad.to(x.device)
  463. return x.transpose(-1, -2)
  464. def inference(self, x, style):
  465. x = self.embedding(x.transpose(-1, -2)) * math.sqrt(self.d_model)
  466. style = style.expand(x.shape[0], x.shape[1], -1)
  467. x = torch.cat([x, style], axis=-1)
  468. src = self.pos_encoder(x)
  469. output = self.transformer_encoder(src).transpose(0, 1)
  470. return output
  471. def length_to_mask(self, lengths):
  472. mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
  473. mask = torch.gt(mask + 1, lengths.unsqueeze(1))
  474. return mask
  475. def load_F0_models(path):
  476. # load F0 model
  477. F0_model = JDCNet(num_class=1, seq_len=192)
  478. params = torch.load(path, map_location='cpu')['net']
  479. F0_model.load_state_dict(params)
  480. _ = F0_model.train()
  481. return F0_model
  482. def load_ASR_models(ASR_MODEL_PATH, ASR_MODEL_CONFIG):
  483. # load ASR model
  484. def _load_config(path):
  485. with open(path) as f:
  486. config = yaml.safe_load(f)
  487. model_config = config['model_params']
  488. return model_config
  489. def _load_model(model_config, model_path):
  490. model = ASRCNN(**model_config)
  491. params = torch.load(model_path, map_location='cpu')['model']
  492. model.load_state_dict(params)
  493. return model
  494. asr_model_config = _load_config(ASR_MODEL_CONFIG)
  495. asr_model = _load_model(asr_model_config, ASR_MODEL_PATH)
  496. _ = asr_model.train()
  497. return asr_model
  498. def build_model(args, text_aligner, pitch_extractor, bert):
  499. assert args.decoder.type in ['istftnet', 'hifigan'], 'Decoder type unknown'
  500. if args.decoder.type == "istftnet":
  501. from Modules.istftnet import Decoder
  502. decoder = Decoder(dim_in=args.hidden_dim, style_dim=args.style_dim, dim_out=args.n_mels,
  503. resblock_kernel_sizes=args.decoder.resblock_kernel_sizes,
  504. upsample_rates=args.decoder.upsample_rates,
  505. upsample_initial_channel=args.decoder.upsample_initial_channel,
  506. resblock_dilation_sizes=args.decoder.resblock_dilation_sizes,
  507. upsample_kernel_sizes=args.decoder.upsample_kernel_sizes,
  508. gen_istft_n_fft=args.decoder.gen_istft_n_fft,
  509. gen_istft_hop_size=args.decoder.gen_istft_hop_size)
  510. else:
  511. from Modules.hifigan import Decoder
  512. decoder = Decoder(dim_in=args.hidden_dim, style_dim=args.style_dim, dim_out=args.n_mels,
  513. resblock_kernel_sizes=args.decoder.resblock_kernel_sizes,
  514. upsample_rates=args.decoder.upsample_rates,
  515. upsample_initial_channel=args.decoder.upsample_initial_channel,
  516. resblock_dilation_sizes=args.decoder.resblock_dilation_sizes,
  517. upsample_kernel_sizes=args.decoder.upsample_kernel_sizes)
  518. text_encoder = TextEncoder(channels=args.hidden_dim, kernel_size=5, depth=args.n_layer, n_symbols=args.n_token)
  519. predictor = ProsodyPredictor(style_dim=args.style_dim, d_hid=args.hidden_dim, nlayers=args.n_layer,
  520. max_dur=args.max_dur, dropout=args.dropout)
  521. style_encoder = StyleEncoder(dim_in=args.dim_in, style_dim=args.style_dim,
  522. max_conv_dim=args.hidden_dim) # acoustic style encoder
  523. predictor_encoder = StyleEncoder(dim_in=args.dim_in, style_dim=args.style_dim,
  524. max_conv_dim=args.hidden_dim) # prosodic style encoder
  525. # define diffusion model
  526. if args.multispeaker:
  527. transformer = StyleTransformer1d(channels=args.style_dim * 2,
  528. context_embedding_features=bert.config.hidden_size,
  529. context_features=args.style_dim * 2,
  530. **args.diffusion.transformer)
  531. else:
  532. transformer = Transformer1d(channels=args.style_dim * 2,
  533. context_embedding_features=bert.config.hidden_size,
  534. **args.diffusion.transformer)
  535. diffusion = AudioDiffusionConditional(
  536. in_channels=1,
  537. embedding_max_length=bert.config.max_position_embeddings,
  538. embedding_features=bert.config.hidden_size,
  539. embedding_mask_proba=args.diffusion.embedding_mask_proba, # Conditional dropout of batch elements,
  540. channels=args.style_dim * 2,
  541. context_features=args.style_dim * 2,
  542. )
  543. diffusion.diffusion = KDiffusion(
  544. net=diffusion.unet,
  545. sigma_distribution=LogNormalDistribution(mean=args.diffusion.dist.mean, std=args.diffusion.dist.std),
  546. sigma_data=args.diffusion.dist.sigma_data,
  547. # a placeholder, will be changed dynamically when start training diffusion model
  548. dynamic_threshold=0.0
  549. )
  550. diffusion.diffusion.net = transformer
  551. diffusion.unet = transformer
  552. nets = Munch(
  553. bert=bert,
  554. bert_encoder=nn.Linear(bert.config.hidden_size, args.hidden_dim),
  555. predictor=predictor,
  556. decoder=decoder,
  557. text_encoder=text_encoder,
  558. predictor_encoder=predictor_encoder,
  559. style_encoder=style_encoder,
  560. diffusion=diffusion,
  561. text_aligner=text_aligner,
  562. pitch_extractor=pitch_extractor,
  563. mpd=MultiPeriodDiscriminator(),
  564. msd=MultiResSpecDiscriminator(),
  565. # slm discriminator head
  566. wd=WavLMDiscriminator(args.slm.hidden, args.slm.nlayers, args.slm.initial_channel),
  567. )
  568. return nets
  569. def load_checkpoint(model, optimizer, path, load_only_params=True, ignore_modules=[]):
  570. state = torch.load(path, map_location='cpu')
  571. params = state['net']
  572. # for key in model:
  573. # from collections import OrderedDict
  574. # new_state_dict = OrderedDict()
  575. # for k,v in params[key].items(): # Fix for non-distributed training
  576. # if not k.startswith("module"):
  577. # #print(f"load_checkpoint: {k}")
  578. # name = 'module.' + k
  579. # else:
  580. # name = k
  581. # new_state_dict[name] = v
  582. # if key in ['mpd', 'msd', 'wd']:
  583. # new_state_dict = params[key]
  584. # if key in params and key not in ignore_modules:
  585. # print('%s loaded' % key)
  586. # model[key].load_state_dict(new_state_dict)
  587. # #model[key].load_state_dict(params[key], strict=False)
  588. for key in model:
  589. if key in params and key not in ignore_modules:
  590. print('%s loaded' % key)
  591. model[key].load_state_dict(params[key], strict=False)
  592. _ = [model[key].eval() for key in model]
  593. if not load_only_params:
  594. epoch = state["epoch"]
  595. iters = state["iters"]
  596. optimizer.load_state_dict(state["optimizer"])
  597. else:
  598. epoch = 0
  599. iters = 0
  600. return model, optimizer, epoch, iters
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...