Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
prophesier
GitHub Repository: prophesier/diff-svc
Path: blob/main/modules/nsf_hifigan/models.py
694 views
1
import os
2
import json
3
from .env import AttrDict
4
import numpy as np
5
import torch
6
import torch.nn.functional as F
7
import torch.nn as nn
8
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
9
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
10
from .utils import init_weights, get_padding
11
12
LRELU_SLOPE = 0.1
13
14
def load_model(model_path, device='cuda'):
15
config_file = os.path.join(os.path.split(model_path)[0], 'config.json')
16
with open(config_file) as f:
17
data = f.read()
18
19
global h
20
json_config = json.loads(data)
21
h = AttrDict(json_config)
22
23
generator = Generator(h).to(device)
24
25
cp_dict = torch.load(model_path)
26
generator.load_state_dict(cp_dict['generator'])
27
generator.eval()
28
generator.remove_weight_norm()
29
del cp_dict
30
return generator, h
31
32
33
class ResBlock1(torch.nn.Module):
34
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
35
super(ResBlock1, self).__init__()
36
self.h = h
37
self.convs1 = nn.ModuleList([
38
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
39
padding=get_padding(kernel_size, dilation[0]))),
40
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
41
padding=get_padding(kernel_size, dilation[1]))),
42
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
43
padding=get_padding(kernel_size, dilation[2])))
44
])
45
self.convs1.apply(init_weights)
46
47
self.convs2 = nn.ModuleList([
48
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
49
padding=get_padding(kernel_size, 1))),
50
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
51
padding=get_padding(kernel_size, 1))),
52
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
53
padding=get_padding(kernel_size, 1)))
54
])
55
self.convs2.apply(init_weights)
56
57
def forward(self, x):
58
for c1, c2 in zip(self.convs1, self.convs2):
59
xt = F.leaky_relu(x, LRELU_SLOPE)
60
xt = c1(xt)
61
xt = F.leaky_relu(xt, LRELU_SLOPE)
62
xt = c2(xt)
63
x = xt + x
64
return x
65
66
def remove_weight_norm(self):
67
for l in self.convs1:
68
remove_weight_norm(l)
69
for l in self.convs2:
70
remove_weight_norm(l)
71
72
73
class ResBlock2(torch.nn.Module):
74
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
75
super(ResBlock2, self).__init__()
76
self.h = h
77
self.convs = nn.ModuleList([
78
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
79
padding=get_padding(kernel_size, dilation[0]))),
80
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
81
padding=get_padding(kernel_size, dilation[1])))
82
])
83
self.convs.apply(init_weights)
84
85
def forward(self, x):
86
for c in self.convs:
87
xt = F.leaky_relu(x, LRELU_SLOPE)
88
xt = c(xt)
89
x = xt + x
90
return x
91
92
def remove_weight_norm(self):
93
for l in self.convs:
94
remove_weight_norm(l)
95
96
97
class Generator(torch.nn.Module):
98
def __init__(self, h):
99
super(Generator, self).__init__()
100
self.h = h
101
self.num_kernels = len(h.resblock_kernel_sizes)
102
self.num_upsamples = len(h.upsample_rates)
103
self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3))
104
resblock = ResBlock1 if h.resblock == '1' else ResBlock2
105
106
self.ups = nn.ModuleList()
107
for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
108
self.ups.append(weight_norm(
109
ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
110
k, u, padding=(k-u)//2)))
111
112
self.resblocks = nn.ModuleList()
113
for i in range(len(self.ups)):
114
ch = h.upsample_initial_channel//(2**(i+1))
115
for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
116
self.resblocks.append(resblock(h, ch, k, d))
117
118
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
119
self.ups.apply(init_weights)
120
self.conv_post.apply(init_weights)
121
122
def forward(self, x):
123
x = self.conv_pre(x)
124
for i in range(self.num_upsamples):
125
x = F.leaky_relu(x, LRELU_SLOPE)
126
x = self.ups[i](x)
127
xs = None
128
for j in range(self.num_kernels):
129
if xs is None:
130
xs = self.resblocks[i*self.num_kernels+j](x)
131
else:
132
xs += self.resblocks[i*self.num_kernels+j](x)
133
x = xs / self.num_kernels
134
x = F.leaky_relu(x)
135
x = self.conv_post(x)
136
x = torch.tanh(x)
137
138
return x
139
140
def remove_weight_norm(self):
141
print('Removing weight norm...')
142
for l in self.ups:
143
remove_weight_norm(l)
144
for l in self.resblocks:
145
l.remove_weight_norm()
146
remove_weight_norm(self.conv_pre)
147
remove_weight_norm(self.conv_post)
148
class SineGen(torch.nn.Module):
149
""" Definition of sine generator
150
SineGen(samp_rate, harmonic_num = 0,
151
sine_amp = 0.1, noise_std = 0.003,
152
voiced_threshold = 0,
153
flag_for_pulse=False)
154
samp_rate: sampling rate in Hz
155
harmonic_num: number of harmonic overtones (default 0)
156
sine_amp: amplitude of sine-wavefrom (default 0.1)
157
noise_std: std of Gaussian noise (default 0.003)
158
voiced_thoreshold: F0 threshold for U/V classification (default 0)
159
flag_for_pulse: this SinGen is used inside PulseGen (default False)
160
Note: when flag_for_pulse is True, the first time step of a voiced
161
segment is always sin(np.pi) or cos(0)
162
"""
163
164
def __init__(self, samp_rate, harmonic_num=0,
165
sine_amp=0.1, noise_std=0.003,
166
voiced_threshold=0,
167
flag_for_pulse=False):
168
super(SineGen, self).__init__()
169
self.sine_amp = sine_amp
170
self.noise_std = noise_std
171
self.harmonic_num = harmonic_num
172
self.dim = self.harmonic_num + 1
173
self.sampling_rate = samp_rate
174
self.voiced_threshold = voiced_threshold
175
self.flag_for_pulse = flag_for_pulse
176
177
def _f02uv(self, f0):
178
# generate uv signal
179
uv = torch.ones_like(f0)
180
uv = uv * (f0 > self.voiced_threshold)
181
return uv
182
183
def _f02sine(self, f0_values):
184
""" f0_values: (batchsize, length, dim)
185
where dim indicates fundamental tone and overtones
186
"""
187
# convert to F0 in rad. The interger part n can be ignored
188
# because 2 * np.pi * n doesn't affect phase
189
rad_values = (f0_values / self.sampling_rate) % 1
190
191
# initial phase noise (no noise for fundamental component)
192
rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \
193
device=f0_values.device)
194
rand_ini[:, 0] = 0
195
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
196
197
# instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
198
if not self.flag_for_pulse:
199
# for normal case
200
201
# To prevent torch.cumsum numerical overflow,
202
# it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1.
203
# Buffer tmp_over_one_idx indicates the time step to add -1.
204
# This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi
205
tmp_over_one = torch.cumsum(rad_values, 1) % 1
206
tmp_over_one_idx = (tmp_over_one[:, 1:, :] -
207
tmp_over_one[:, :-1, :]) < 0
208
cumsum_shift = torch.zeros_like(rad_values)
209
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
210
211
sines = torch.sin(torch.cumsum(rad_values + cumsum_shift, dim=1)
212
* 2 * np.pi)
213
else:
214
# If necessary, make sure that the first time step of every
215
# voiced segments is sin(pi) or cos(0)
216
# This is used for pulse-train generation
217
218
# identify the last time step in unvoiced segments
219
uv = self._f02uv(f0_values)
220
uv_1 = torch.roll(uv, shifts=-1, dims=1)
221
uv_1[:, -1, :] = 1
222
u_loc = (uv < 1) * (uv_1 > 0)
223
224
# get the instantanouse phase
225
tmp_cumsum = torch.cumsum(rad_values, dim=1)
226
# different batch needs to be processed differently
227
for idx in range(f0_values.shape[0]):
228
temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
229
temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
230
# stores the accumulation of i.phase within
231
# each voiced segments
232
tmp_cumsum[idx, :, :] = 0
233
tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
234
235
# rad_values - tmp_cumsum: remove the accumulation of i.phase
236
# within the previous voiced segment.
237
i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
238
239
# get the sines
240
sines = torch.cos(i_phase * 2 * np.pi)
241
return sines
242
243
def forward(self, f0):
244
""" sine_tensor, uv = forward(f0)
245
input F0: tensor(batchsize=1, length, dim=1)
246
f0 for unvoiced steps should be 0
247
output sine_tensor: tensor(batchsize=1, length, dim)
248
output uv: tensor(batchsize=1, length, 1)
249
"""
250
with torch.no_grad():
251
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim,
252
device=f0.device)
253
# fundamental component
254
f0_buf[:, :, 0] = f0[:, :, 0]
255
for idx in np.arange(self.harmonic_num):
256
# idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
257
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (idx + 2)
258
259
# generate sine waveforms
260
sine_waves = self._f02sine(f0_buf) * self.sine_amp
261
262
# generate uv signal
263
# uv = torch.ones(f0.shape)
264
# uv = uv * (f0 > self.voiced_threshold)
265
uv = self._f02uv(f0)
266
267
# noise: for unvoiced should be similar to sine_amp
268
# std = self.sine_amp/3 -> max value ~ self.sine_amp
269
# . for voiced regions is self.noise_std
270
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
271
noise = noise_amp * torch.randn_like(sine_waves)
272
273
# first: set the unvoiced part to 0 by uv
274
# then: additive noise
275
sine_waves = sine_waves * uv + noise
276
return sine_waves, uv, noise
277
class SourceModuleHnNSF(torch.nn.Module):
278
""" SourceModule for hn-nsf
279
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
280
add_noise_std=0.003, voiced_threshod=0)
281
sampling_rate: sampling_rate in Hz
282
harmonic_num: number of harmonic above F0 (default: 0)
283
sine_amp: amplitude of sine source signal (default: 0.1)
284
add_noise_std: std of additive Gaussian noise (default: 0.003)
285
note that amplitude of noise in unvoiced is decided
286
by sine_amp
287
voiced_threshold: threhold to set U/V given F0 (default: 0)
288
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
289
F0_sampled (batchsize, length, 1)
290
Sine_source (batchsize, length, 1)
291
noise_source (batchsize, length 1)
292
uv (batchsize, length, 1)
293
"""
294
295
def __init__(self, sampling_rate, harmonic_num=0, sine_amp=0.1,
296
add_noise_std=0.003, voiced_threshod=0):
297
super(SourceModuleHnNSF, self).__init__()
298
299
self.sine_amp = sine_amp
300
self.noise_std = add_noise_std
301
302
# to produce sine waveforms
303
self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
304
sine_amp, add_noise_std, voiced_threshod)
305
306
# to merge source harmonics into a single excitation
307
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
308
self.l_tanh = torch.nn.Tanh()
309
310
def forward(self, x):
311
"""
312
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
313
F0_sampled (batchsize, length, 1)
314
Sine_source (batchsize, length, 1)
315
noise_source (batchsize, length 1)
316
"""
317
# source for harmonic branch
318
sine_wavs, uv, _ = self.l_sin_gen(x)
319
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
320
321
# source for noise branch, in the same shape as uv
322
noise = torch.randn_like(uv) * self.sine_amp / 3
323
return sine_merge, noise, uv
324
325
class Generator(torch.nn.Module):
326
def __init__(self, h):
327
super(Generator, self).__init__()
328
self.h = h
329
self.num_kernels = len(h.resblock_kernel_sizes)
330
self.num_upsamples = len(h.upsample_rates)
331
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(h.upsample_rates))
332
self.m_source = SourceModuleHnNSF(
333
sampling_rate=h.sampling_rate,
334
harmonic_num=8)
335
self.noise_convs = nn.ModuleList()
336
self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3))
337
resblock = ResBlock1 if h.resblock == '1' else ResBlock2
338
339
self.ups = nn.ModuleList()
340
for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
341
c_cur = h.upsample_initial_channel // (2 ** (i + 1))
342
self.ups.append(weight_norm(
343
ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
344
k, u, padding=(k-u)//2)))
345
if i + 1 < len(h.upsample_rates):#
346
stride_f0 = np.prod(h.upsample_rates[i + 1:])
347
self.noise_convs.append(Conv1d(
348
1, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=stride_f0 // 2))
349
else:
350
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
351
self.resblocks = nn.ModuleList()
352
for i in range(len(self.ups)):
353
ch = h.upsample_initial_channel//(2**(i+1))
354
for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
355
self.resblocks.append(resblock(h, ch, k, d))
356
357
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
358
self.ups.apply(init_weights)
359
self.conv_post.apply(init_weights)
360
361
def forward(self, x,f0):
362
# print(1,x.shape,f0.shape,f0[:, None].shape)
363
f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2)#bs,n,t
364
# print(2,f0.shape)
365
har_source, noi_source, uv = self.m_source(f0)
366
har_source = har_source.transpose(1, 2)
367
x = self.conv_pre(x)
368
# print(124,x.shape,har_source.shape)
369
for i in range(self.num_upsamples):
370
x = F.leaky_relu(x, LRELU_SLOPE)
371
# print(3,x.shape)
372
x = self.ups[i](x)
373
x_source = self.noise_convs[i](har_source)
374
# print(4,x_source.shape,har_source.shape,x.shape)
375
x = x + x_source
376
xs = None
377
for j in range(self.num_kernels):
378
if xs is None:
379
xs = self.resblocks[i*self.num_kernels+j](x)
380
else:
381
xs += self.resblocks[i*self.num_kernels+j](x)
382
x = xs / self.num_kernels
383
x = F.leaky_relu(x)
384
x = self.conv_post(x)
385
x = torch.tanh(x)
386
387
return x
388
389
def remove_weight_norm(self):
390
print('Removing weight norm...')
391
for l in self.ups:
392
remove_weight_norm(l)
393
for l in self.resblocks:
394
l.remove_weight_norm()
395
remove_weight_norm(self.conv_pre)
396
remove_weight_norm(self.conv_post)
397
398
class DiscriminatorP(torch.nn.Module):
399
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
400
super(DiscriminatorP, self).__init__()
401
self.period = period
402
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
403
self.convs = nn.ModuleList([
404
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
405
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
406
norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
407
norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
408
norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
409
])
410
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
411
412
def forward(self, x):
413
fmap = []
414
415
# 1d to 2d
416
b, c, t = x.shape
417
if t % self.period != 0: # pad first
418
n_pad = self.period - (t % self.period)
419
x = F.pad(x, (0, n_pad), "reflect")
420
t = t + n_pad
421
x = x.view(b, c, t // self.period, self.period)
422
423
for l in self.convs:
424
x = l(x)
425
x = F.leaky_relu(x, LRELU_SLOPE)
426
fmap.append(x)
427
x = self.conv_post(x)
428
fmap.append(x)
429
x = torch.flatten(x, 1, -1)
430
431
return x, fmap
432
433
434
class MultiPeriodDiscriminator(torch.nn.Module):
435
def __init__(self, periods=None):
436
super(MultiPeriodDiscriminator, self).__init__()
437
self.periods = periods if periods is not None else [2, 3, 5, 7, 11]
438
self.discriminators = nn.ModuleList()
439
for period in self.periods:
440
self.discriminators.append(DiscriminatorP(period))
441
442
def forward(self, y, y_hat):
443
y_d_rs = []
444
y_d_gs = []
445
fmap_rs = []
446
fmap_gs = []
447
for i, d in enumerate(self.discriminators):
448
y_d_r, fmap_r = d(y)
449
y_d_g, fmap_g = d(y_hat)
450
y_d_rs.append(y_d_r)
451
fmap_rs.append(fmap_r)
452
y_d_gs.append(y_d_g)
453
fmap_gs.append(fmap_g)
454
455
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
456
457
458
class DiscriminatorS(torch.nn.Module):
459
def __init__(self, use_spectral_norm=False):
460
super(DiscriminatorS, self).__init__()
461
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
462
self.convs = nn.ModuleList([
463
norm_f(Conv1d(1, 128, 15, 1, padding=7)),
464
norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
465
norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
466
norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
467
norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
468
norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
469
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
470
])
471
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
472
473
def forward(self, x):
474
fmap = []
475
for l in self.convs:
476
x = l(x)
477
x = F.leaky_relu(x, LRELU_SLOPE)
478
fmap.append(x)
479
x = self.conv_post(x)
480
fmap.append(x)
481
x = torch.flatten(x, 1, -1)
482
483
return x, fmap
484
485
486
class MultiScaleDiscriminator(torch.nn.Module):
487
def __init__(self):
488
super(MultiScaleDiscriminator, self).__init__()
489
self.discriminators = nn.ModuleList([
490
DiscriminatorS(use_spectral_norm=True),
491
DiscriminatorS(),
492
DiscriminatorS(),
493
])
494
self.meanpools = nn.ModuleList([
495
AvgPool1d(4, 2, padding=2),
496
AvgPool1d(4, 2, padding=2)
497
])
498
499
def forward(self, y, y_hat):
500
y_d_rs = []
501
y_d_gs = []
502
fmap_rs = []
503
fmap_gs = []
504
for i, d in enumerate(self.discriminators):
505
if i != 0:
506
y = self.meanpools[i-1](y)
507
y_hat = self.meanpools[i-1](y_hat)
508
y_d_r, fmap_r = d(y)
509
y_d_g, fmap_g = d(y_hat)
510
y_d_rs.append(y_d_r)
511
fmap_rs.append(fmap_r)
512
y_d_gs.append(y_d_g)
513
fmap_gs.append(fmap_g)
514
515
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
516
517
518
def feature_loss(fmap_r, fmap_g):
519
loss = 0
520
for dr, dg in zip(fmap_r, fmap_g):
521
for rl, gl in zip(dr, dg):
522
loss += torch.mean(torch.abs(rl - gl))
523
524
return loss*2
525
526
527
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
528
loss = 0
529
r_losses = []
530
g_losses = []
531
for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
532
r_loss = torch.mean((1-dr)**2)
533
g_loss = torch.mean(dg**2)
534
loss += (r_loss + g_loss)
535
r_losses.append(r_loss.item())
536
g_losses.append(g_loss.item())
537
538
return loss, r_losses, g_losses
539
540
541
def generator_loss(disc_outputs):
542
loss = 0
543
gen_losses = []
544
for dg in disc_outputs:
545
l = torch.mean((1-dg)**2)
546
gen_losses.append(l)
547
loss += l
548
549
return loss, gen_losses
550