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

istftnet.py 22 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
  1. import torch
  2. import torch.nn.functional as F
  3. import torch.nn as nn
  4. from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
  5. from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
  6. from .utils import init_weights, get_padding
  7. import math
  8. import random
  9. import numpy as np
  10. from scipy.signal import get_window
  11. LRELU_SLOPE = 0.1
  12. class AdaIN1d(nn.Module):
  13. def __init__(self, style_dim, num_features):
  14. super().__init__()
  15. self.norm = nn.InstanceNorm1d(num_features, affine=False)
  16. self.fc = nn.Linear(style_dim, num_features*2)
  17. def forward(self, x, s):
  18. h = self.fc(s)
  19. h = h.view(h.size(0), h.size(1), 1)
  20. gamma, beta = torch.chunk(h, chunks=2, dim=1)
  21. return (1 + gamma) * self.norm(x) + beta
  22. class AdaINResBlock1(torch.nn.Module):
  23. def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), style_dim=64):
  24. super(AdaINResBlock1, self).__init__()
  25. self.convs1 = nn.ModuleList([
  26. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
  27. padding=get_padding(kernel_size, dilation[0]))),
  28. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
  29. padding=get_padding(kernel_size, dilation[1]))),
  30. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
  31. padding=get_padding(kernel_size, dilation[2])))
  32. ])
  33. self.convs1.apply(init_weights)
  34. self.convs2 = nn.ModuleList([
  35. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
  36. padding=get_padding(kernel_size, 1))),
  37. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
  38. padding=get_padding(kernel_size, 1))),
  39. weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
  40. padding=get_padding(kernel_size, 1)))
  41. ])
  42. self.convs2.apply(init_weights)
  43. self.adain1 = nn.ModuleList([
  44. AdaIN1d(style_dim, channels),
  45. AdaIN1d(style_dim, channels),
  46. AdaIN1d(style_dim, channels),
  47. ])
  48. self.adain2 = nn.ModuleList([
  49. AdaIN1d(style_dim, channels),
  50. AdaIN1d(style_dim, channels),
  51. AdaIN1d(style_dim, channels),
  52. ])
  53. self.alpha1 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs1))])
  54. self.alpha2 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs2))])
  55. def forward(self, x, s):
  56. for c1, c2, n1, n2, a1, a2 in zip(self.convs1, self.convs2, self.adain1, self.adain2, self.alpha1, self.alpha2):
  57. xt = n1(x, s)
  58. xt = xt + (1 / a1) * (torch.sin(a1 * xt) ** 2) # Snake1D
  59. xt = c1(xt)
  60. xt = n2(xt, s)
  61. xt = xt + (1 / a2) * (torch.sin(a2 * xt) ** 2) # Snake1D
  62. xt = c2(xt)
  63. x = xt + x
  64. return x
  65. def remove_weight_norm(self):
  66. for l in self.convs1:
  67. remove_weight_norm(l)
  68. for l in self.convs2:
  69. remove_weight_norm(l)
  70. class TorchSTFT(torch.nn.Module):
  71. def __init__(self, filter_length=800, hop_length=200, win_length=800, window='hann'):
  72. super().__init__()
  73. self.filter_length = filter_length
  74. self.hop_length = hop_length
  75. self.win_length = win_length
  76. self.window = torch.from_numpy(get_window(window, win_length, fftbins=True).astype(np.float32))
  77. def transform(self, input_data):
  78. forward_transform = torch.stft(
  79. input_data,
  80. self.filter_length, self.hop_length, self.win_length, window=self.window.to(input_data.device),
  81. return_complex=True)
  82. return torch.abs(forward_transform), torch.angle(forward_transform)
  83. def inverse(self, magnitude, phase):
  84. inverse_transform = torch.istft(
  85. magnitude * torch.exp(phase * 1j),
  86. self.filter_length, self.hop_length, self.win_length, window=self.window.to(magnitude.device))
  87. return inverse_transform.unsqueeze(-2) # unsqueeze to stay consistent with conv_transpose1d implementation
  88. def forward(self, input_data):
  89. self.magnitude, self.phase = self.transform(input_data)
  90. reconstruction = self.inverse(self.magnitude, self.phase)
  91. return reconstruction
  92. class SineGen(torch.nn.Module):
  93. """ Definition of sine generator
  94. SineGen(samp_rate, harmonic_num = 0,
  95. sine_amp = 0.1, noise_std = 0.003,
  96. voiced_threshold = 0,
  97. flag_for_pulse=False)
  98. samp_rate: sampling rate in Hz
  99. harmonic_num: number of harmonic overtones (default 0)
  100. sine_amp: amplitude of sine-wavefrom (default 0.1)
  101. noise_std: std of Gaussian noise (default 0.003)
  102. voiced_thoreshold: F0 threshold for U/V classification (default 0)
  103. flag_for_pulse: this SinGen is used inside PulseGen (default False)
  104. Note: when flag_for_pulse is True, the first time step of a voiced
  105. segment is always sin(np.pi) or cos(0)
  106. """
  107. def __init__(self, samp_rate, upsample_scale, harmonic_num=0,
  108. sine_amp=0.1, noise_std=0.003,
  109. voiced_threshold=0,
  110. flag_for_pulse=False):
  111. super(SineGen, self).__init__()
  112. self.sine_amp = sine_amp
  113. self.noise_std = noise_std
  114. self.harmonic_num = harmonic_num
  115. self.dim = self.harmonic_num + 1
  116. self.sampling_rate = samp_rate
  117. self.voiced_threshold = voiced_threshold
  118. self.flag_for_pulse = flag_for_pulse
  119. self.upsample_scale = upsample_scale
  120. def _f02uv(self, f0):
  121. # generate uv signal
  122. uv = (f0 > self.voiced_threshold).type(torch.float32)
  123. return uv
  124. def _f02sine(self, f0_values):
  125. """ f0_values: (batchsize, length, dim)
  126. where dim indicates fundamental tone and overtones
  127. """
  128. # convert to F0 in rad. The interger part n can be ignored
  129. # because 2 * np.pi * n doesn't affect phase
  130. rad_values = (f0_values / self.sampling_rate) % 1
  131. # initial phase noise (no noise for fundamental component)
  132. rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \
  133. device=f0_values.device)
  134. rand_ini[:, 0] = 0
  135. rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
  136. # instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
  137. if not self.flag_for_pulse:
  138. # # for normal case
  139. # # To prevent torch.cumsum numerical overflow,
  140. # # it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1.
  141. # # Buffer tmp_over_one_idx indicates the time step to add -1.
  142. # # This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi
  143. # tmp_over_one = torch.cumsum(rad_values, 1) % 1
  144. # tmp_over_one_idx = (padDiff(tmp_over_one)) < 0
  145. # cumsum_shift = torch.zeros_like(rad_values)
  146. # cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
  147. # phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
  148. rad_values = torch.nn.functional.interpolate(rad_values.transpose(1, 2),
  149. scale_factor=1/self.upsample_scale,
  150. mode="linear").transpose(1, 2)
  151. # tmp_over_one = torch.cumsum(rad_values, 1) % 1
  152. # tmp_over_one_idx = (padDiff(tmp_over_one)) < 0
  153. # cumsum_shift = torch.zeros_like(rad_values)
  154. # cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
  155. phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
  156. phase = torch.nn.functional.interpolate(phase.transpose(1, 2) * self.upsample_scale,
  157. scale_factor=self.upsample_scale, mode="linear").transpose(1, 2)
  158. sines = torch.sin(phase)
  159. else:
  160. # If necessary, make sure that the first time step of every
  161. # voiced segments is sin(pi) or cos(0)
  162. # This is used for pulse-train generation
  163. # identify the last time step in unvoiced segments
  164. uv = self._f02uv(f0_values)
  165. uv_1 = torch.roll(uv, shifts=-1, dims=1)
  166. uv_1[:, -1, :] = 1
  167. u_loc = (uv < 1) * (uv_1 > 0)
  168. # get the instantanouse phase
  169. tmp_cumsum = torch.cumsum(rad_values, dim=1)
  170. # different batch needs to be processed differently
  171. for idx in range(f0_values.shape[0]):
  172. temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
  173. temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
  174. # stores the accumulation of i.phase within
  175. # each voiced segments
  176. tmp_cumsum[idx, :, :] = 0
  177. tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
  178. # rad_values - tmp_cumsum: remove the accumulation of i.phase
  179. # within the previous voiced segment.
  180. i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
  181. # get the sines
  182. sines = torch.cos(i_phase * 2 * np.pi)
  183. return sines
  184. def forward(self, f0):
  185. """ sine_tensor, uv = forward(f0)
  186. input F0: tensor(batchsize=1, length, dim=1)
  187. f0 for unvoiced steps should be 0
  188. output sine_tensor: tensor(batchsize=1, length, dim)
  189. output uv: tensor(batchsize=1, length, 1)
  190. """
  191. f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim,
  192. device=f0.device)
  193. # fundamental component
  194. fn = torch.multiply(f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device))
  195. # generate sine waveforms
  196. sine_waves = self._f02sine(fn) * self.sine_amp
  197. # generate uv signal
  198. # uv = torch.ones(f0.shape)
  199. # uv = uv * (f0 > self.voiced_threshold)
  200. uv = self._f02uv(f0)
  201. # noise: for unvoiced should be similar to sine_amp
  202. # std = self.sine_amp/3 -> max value ~ self.sine_amp
  203. # . for voiced regions is self.noise_std
  204. noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
  205. noise = noise_amp * torch.randn_like(sine_waves)
  206. # first: set the unvoiced part to 0 by uv
  207. # then: additive noise
  208. sine_waves = sine_waves * uv + noise
  209. return sine_waves, uv, noise
  210. class SourceModuleHnNSF(torch.nn.Module):
  211. """ SourceModule for hn-nsf
  212. SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
  213. add_noise_std=0.003, voiced_threshod=0)
  214. sampling_rate: sampling_rate in Hz
  215. harmonic_num: number of harmonic above F0 (default: 0)
  216. sine_amp: amplitude of sine source signal (default: 0.1)
  217. add_noise_std: std of additive Gaussian noise (default: 0.003)
  218. note that amplitude of noise in unvoiced is decided
  219. by sine_amp
  220. voiced_threshold: threhold to set U/V given F0 (default: 0)
  221. Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
  222. F0_sampled (batchsize, length, 1)
  223. Sine_source (batchsize, length, 1)
  224. noise_source (batchsize, length 1)
  225. uv (batchsize, length, 1)
  226. """
  227. def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
  228. add_noise_std=0.003, voiced_threshod=0):
  229. super(SourceModuleHnNSF, self).__init__()
  230. self.sine_amp = sine_amp
  231. self.noise_std = add_noise_std
  232. # to produce sine waveforms
  233. self.l_sin_gen = SineGen(sampling_rate, upsample_scale, harmonic_num,
  234. sine_amp, add_noise_std, voiced_threshod)
  235. # to merge source harmonics into a single excitation
  236. self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
  237. self.l_tanh = torch.nn.Tanh()
  238. def forward(self, x):
  239. """
  240. Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
  241. F0_sampled (batchsize, length, 1)
  242. Sine_source (batchsize, length, 1)
  243. noise_source (batchsize, length 1)
  244. """
  245. # source for harmonic branch
  246. with torch.no_grad():
  247. sine_wavs, uv, _ = self.l_sin_gen(x)
  248. sine_merge = self.l_tanh(self.l_linear(sine_wavs))
  249. # source for noise branch, in the same shape as uv
  250. noise = torch.randn_like(uv) * self.sine_amp / 3
  251. return sine_merge, noise, uv
  252. def padDiff(x):
  253. return F.pad(F.pad(x, (0,0,-1,1), 'constant', 0) - x, (0,0,0,-1), 'constant', 0)
  254. class Generator(torch.nn.Module):
  255. def __init__(self, style_dim, resblock_kernel_sizes, upsample_rates, upsample_initial_channel, resblock_dilation_sizes, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size):
  256. super(Generator, self).__init__()
  257. self.num_kernels = len(resblock_kernel_sizes)
  258. self.num_upsamples = len(upsample_rates)
  259. resblock = AdaINResBlock1
  260. self.m_source = SourceModuleHnNSF(
  261. sampling_rate=24000,
  262. upsample_scale=np.prod(upsample_rates) * gen_istft_hop_size,
  263. harmonic_num=8, voiced_threshod=10)
  264. self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * gen_istft_hop_size)
  265. self.noise_convs = nn.ModuleList()
  266. self.noise_res = nn.ModuleList()
  267. self.ups = nn.ModuleList()
  268. for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
  269. self.ups.append(weight_norm(
  270. ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
  271. k, u, padding=(k-u)//2)))
  272. self.resblocks = nn.ModuleList()
  273. for i in range(len(self.ups)):
  274. ch = upsample_initial_channel//(2**(i+1))
  275. for j, (k, d) in enumerate(zip(resblock_kernel_sizes,resblock_dilation_sizes)):
  276. self.resblocks.append(resblock(ch, k, d, style_dim))
  277. c_cur = upsample_initial_channel // (2 ** (i + 1))
  278. if i + 1 < len(upsample_rates): #
  279. stride_f0 = np.prod(upsample_rates[i + 1:])
  280. self.noise_convs.append(Conv1d(
  281. gen_istft_n_fft + 2, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=(stride_f0+1) // 2))
  282. self.noise_res.append(resblock(c_cur, 7, [1,3,5], style_dim))
  283. else:
  284. self.noise_convs.append(Conv1d(gen_istft_n_fft + 2, c_cur, kernel_size=1))
  285. self.noise_res.append(resblock(c_cur, 11, [1,3,5], style_dim))
  286. self.post_n_fft = gen_istft_n_fft
  287. self.conv_post = weight_norm(Conv1d(ch, self.post_n_fft + 2, 7, 1, padding=3))
  288. self.ups.apply(init_weights)
  289. self.conv_post.apply(init_weights)
  290. self.reflection_pad = torch.nn.ReflectionPad1d((1, 0))
  291. self.stft = TorchSTFT(filter_length=gen_istft_n_fft, hop_length=gen_istft_hop_size, win_length=gen_istft_n_fft)
  292. def forward(self, x, s, f0):
  293. with torch.no_grad():
  294. f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
  295. har_source, noi_source, uv = self.m_source(f0)
  296. har_source = har_source.transpose(1, 2).squeeze(1)
  297. har_spec, har_phase = self.stft.transform(har_source)
  298. har = torch.cat([har_spec, har_phase], dim=1)
  299. for i in range(self.num_upsamples):
  300. x = F.leaky_relu(x, LRELU_SLOPE)
  301. x_source = self.noise_convs[i](har)
  302. x_source = self.noise_res[i](x_source, s)
  303. x = self.ups[i](x)
  304. if i == self.num_upsamples - 1:
  305. x = self.reflection_pad(x)
  306. x = x + x_source
  307. xs = None
  308. for j in range(self.num_kernels):
  309. if xs is None:
  310. xs = self.resblocks[i*self.num_kernels+j](x, s)
  311. else:
  312. xs += self.resblocks[i*self.num_kernels+j](x, s)
  313. x = xs / self.num_kernels
  314. x = F.leaky_relu(x)
  315. x = self.conv_post(x)
  316. spec = torch.exp(x[:,:self.post_n_fft // 2 + 1, :])
  317. phase = torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
  318. return self.stft.inverse(spec, phase)
  319. def fw_phase(self, x, s):
  320. for i in range(self.num_upsamples):
  321. x = F.leaky_relu(x, LRELU_SLOPE)
  322. x = self.ups[i](x)
  323. xs = None
  324. for j in range(self.num_kernels):
  325. if xs is None:
  326. xs = self.resblocks[i*self.num_kernels+j](x, s)
  327. else:
  328. xs += self.resblocks[i*self.num_kernels+j](x, s)
  329. x = xs / self.num_kernels
  330. x = F.leaky_relu(x)
  331. x = self.reflection_pad(x)
  332. x = self.conv_post(x)
  333. spec = torch.exp(x[:,:self.post_n_fft // 2 + 1, :])
  334. phase = torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
  335. return spec, phase
  336. def remove_weight_norm(self):
  337. print('Removing weight norm...')
  338. for l in self.ups:
  339. remove_weight_norm(l)
  340. for l in self.resblocks:
  341. l.remove_weight_norm()
  342. remove_weight_norm(self.conv_pre)
  343. remove_weight_norm(self.conv_post)
  344. class AdainResBlk1d(nn.Module):
  345. def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2),
  346. upsample='none', dropout_p=0.0):
  347. super().__init__()
  348. self.actv = actv
  349. self.upsample_type = upsample
  350. self.upsample = UpSample1d(upsample)
  351. self.learned_sc = dim_in != dim_out
  352. self._build_weights(dim_in, dim_out, style_dim)
  353. self.dropout = nn.Dropout(dropout_p)
  354. if upsample == 'none':
  355. self.pool = nn.Identity()
  356. else:
  357. self.pool = weight_norm(nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1))
  358. def _build_weights(self, dim_in, dim_out, style_dim):
  359. self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
  360. self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1))
  361. self.norm1 = AdaIN1d(style_dim, dim_in)
  362. self.norm2 = AdaIN1d(style_dim, dim_out)
  363. if self.learned_sc:
  364. self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
  365. def _shortcut(self, x):
  366. x = self.upsample(x)
  367. if self.learned_sc:
  368. x = self.conv1x1(x)
  369. return x
  370. def _residual(self, x, s):
  371. x = self.norm1(x, s)
  372. x = self.actv(x)
  373. x = self.pool(x)
  374. x = self.conv1(self.dropout(x))
  375. x = self.norm2(x, s)
  376. x = self.actv(x)
  377. x = self.conv2(self.dropout(x))
  378. return x
  379. def forward(self, x, s):
  380. out = self._residual(x, s)
  381. out = (out + self._shortcut(x)) / math.sqrt(2)
  382. return out
  383. class UpSample1d(nn.Module):
  384. def __init__(self, layer_type):
  385. super().__init__()
  386. self.layer_type = layer_type
  387. def forward(self, x):
  388. if self.layer_type == 'none':
  389. return x
  390. else:
  391. return F.interpolate(x, scale_factor=2, mode='nearest')
  392. class Decoder(nn.Module):
  393. def __init__(self, dim_in=512, F0_channel=512, style_dim=64, dim_out=80,
  394. resblock_kernel_sizes = [3,7,11],
  395. upsample_rates = [10, 6],
  396. upsample_initial_channel=512,
  397. resblock_dilation_sizes=[[1,3,5], [1,3,5], [1,3,5]],
  398. upsample_kernel_sizes=[20, 12],
  399. gen_istft_n_fft=20, gen_istft_hop_size=5):
  400. super().__init__()
  401. self.decode = nn.ModuleList()
  402. self.encode = AdainResBlk1d(dim_in + 2, 1024, style_dim)
  403. self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
  404. self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
  405. self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
  406. self.decode.append(AdainResBlk1d(1024 + 2 + 64, 512, style_dim, upsample=True))
  407. self.F0_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
  408. self.N_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
  409. self.asr_res = nn.Sequential(
  410. weight_norm(nn.Conv1d(512, 64, kernel_size=1)),
  411. )
  412. self.generator = Generator(style_dim, resblock_kernel_sizes, upsample_rates,
  413. upsample_initial_channel, resblock_dilation_sizes,
  414. upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size)
  415. def forward(self, asr, F0_curve, N, s):
  416. if self.training:
  417. downlist = [0, 3, 7]
  418. F0_down = downlist[random.randint(0, 2)]
  419. downlist = [0, 3, 7, 15]
  420. N_down = downlist[random.randint(0, 3)]
  421. if F0_down:
  422. F0_curve = nn.functional.conv1d(F0_curve.unsqueeze(1), torch.ones(1, 1, F0_down).to('cuda'), padding=F0_down//2).squeeze(1) / F0_down
  423. if N_down:
  424. N = nn.functional.conv1d(N.unsqueeze(1), torch.ones(1, 1, N_down).to('cuda'), padding=N_down//2).squeeze(1) / N_down
  425. F0 = self.F0_conv(F0_curve.unsqueeze(1))
  426. N = self.N_conv(N.unsqueeze(1))
  427. x = torch.cat([asr, F0, N], axis=1)
  428. x = self.encode(x, s)
  429. asr_res = self.asr_res(asr)
  430. res = True
  431. for block in self.decode:
  432. if res:
  433. x = torch.cat([x, asr_res, F0, N], axis=1)
  434. x = block(x, s)
  435. if block.upsample_type != "none":
  436. res = False
  437. x = self.generator(x, s, F0_curve)
  438. return x
Tip!

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

Comments

Loading...