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

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

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

Comments

Loading...