Kangarroar commited on
Commit
fa83c9e
·
1 Parent(s): ab04d74

Delete network

Browse files
network/diff/__pycache__/candidate_decoder.cpython-38.pyc DELETED
Binary file (3.21 kB)
 
network/diff/__pycache__/diffusion.cpython-38.pyc DELETED
Binary file (11.2 kB)
 
network/diff/__pycache__/net.cpython-38.pyc DELETED
Binary file (4.61 kB)
 
network/diff/candidate_decoder.py DELETED
@@ -1,98 +0,0 @@
1
- from modules.fastspeech.tts_modules import FastspeechDecoder
2
- # from modules.fastspeech.fast_tacotron import DecoderRNN
3
- # from modules.fastspeech.speedy_speech.speedy_speech import ConvBlocks
4
- # from modules.fastspeech.conformer.conformer import ConformerDecoder
5
- import torch
6
- from torch.nn import functional as F
7
- import torch.nn as nn
8
- import math
9
- from utils.hparams import hparams
10
- from modules.commons.common_layers import Mish
11
- Linear = nn.Linear
12
-
13
- class SinusoidalPosEmb(nn.Module):
14
- def __init__(self, dim):
15
- super().__init__()
16
- self.dim = dim
17
-
18
- def forward(self, x):
19
- device = x.device
20
- half_dim = self.dim // 2
21
- emb = math.log(10000) / (half_dim - 1)
22
- emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
23
- emb = x[:, None] * emb[None, :]
24
- emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
25
- return emb
26
-
27
-
28
- def Conv1d(*args, **kwargs):
29
- layer = nn.Conv1d(*args, **kwargs)
30
- nn.init.kaiming_normal_(layer.weight)
31
- return layer
32
-
33
-
34
- class FFT(FastspeechDecoder): # unused, because DiffSinger only uses FastspeechEncoder
35
- # NOTE: this part of script is *isolated* from other scripts, which means
36
- # it may not be compatible with the current version.
37
-
38
- def __init__(self, hidden_size=None, num_layers=None, kernel_size=None, num_heads=None):
39
- super().__init__(hidden_size, num_layers, kernel_size, num_heads=num_heads)
40
- dim = hparams['residual_channels']
41
- self.input_projection = Conv1d(hparams['audio_num_mel_bins'], dim, 1)
42
- self.diffusion_embedding = SinusoidalPosEmb(dim)
43
- self.mlp = nn.Sequential(
44
- nn.Linear(dim, dim * 4),
45
- Mish(),
46
- nn.Linear(dim * 4, dim)
47
- )
48
- self.get_mel_out = Linear(hparams['hidden_size'], 80, bias=True)
49
- self.get_decode_inp = Linear(hparams['hidden_size'] + dim + dim,
50
- hparams['hidden_size']) # hs + dim + 80 -> hs
51
-
52
- def forward(self, spec, diffusion_step, cond, padding_mask=None, attn_mask=None, return_hiddens=False):
53
- """
54
- :param spec: [B, 1, 80, T]
55
- :param diffusion_step: [B, 1]
56
- :param cond: [B, M, T]
57
- :return:
58
- """
59
- x = spec[:, 0]
60
- x = self.input_projection(x).permute([0, 2, 1]) # [B, T, residual_channel]
61
- diffusion_step = self.diffusion_embedding(diffusion_step)
62
- diffusion_step = self.mlp(diffusion_step) # [B, dim]
63
- cond = cond.permute([0, 2, 1]) # [B, T, M]
64
-
65
- seq_len = cond.shape[1] # [T_mel]
66
- time_embed = diffusion_step[:, None, :] # [B, 1, dim]
67
- time_embed = time_embed.repeat([1, seq_len, 1]) # # [B, T, dim]
68
-
69
- decoder_inp = torch.cat([x, cond, time_embed], dim=-1) # [B, T, dim + H + dim]
70
- decoder_inp = self.get_decode_inp(decoder_inp) # [B, T, H]
71
- x = decoder_inp
72
-
73
- '''
74
- Required x: [B, T, C]
75
- :return: [B, T, C] or [L, B, T, C]
76
- '''
77
- padding_mask = x.abs().sum(-1).eq(0).data if padding_mask is None else padding_mask
78
- nonpadding_mask_TB = 1 - padding_mask.transpose(0, 1).float()[:, :, None] # [T, B, 1]
79
- if self.use_pos_embed:
80
- positions = self.pos_embed_alpha * self.embed_positions(x[..., 0])
81
- x = x + positions
82
- x = F.dropout(x, p=self.dropout, training=self.training)
83
- # B x T x C -> T x B x C
84
- x = x.transpose(0, 1) * nonpadding_mask_TB
85
- hiddens = []
86
- for layer in self.layers:
87
- x = layer(x, encoder_padding_mask=padding_mask, attn_mask=attn_mask) * nonpadding_mask_TB
88
- hiddens.append(x)
89
- if self.use_last_norm:
90
- x = self.layer_norm(x) * nonpadding_mask_TB
91
- if return_hiddens:
92
- x = torch.stack(hiddens, 0) # [L, T, B, C]
93
- x = x.transpose(1, 2) # [L, B, T, C]
94
- else:
95
- x = x.transpose(0, 1) # [B, T, C]
96
-
97
- x = self.get_mel_out(x).permute([0, 2, 1]) # [B, 80, T]
98
- return x[:, None, :, :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/diff/diffusion.py DELETED
@@ -1,332 +0,0 @@
1
- from collections import deque
2
- from functools import partial
3
- from inspect import isfunction
4
- import numpy as np
5
- import torch
6
- import torch.nn.functional as F
7
- from torch import nn
8
- from tqdm import tqdm
9
-
10
- from modules.fastspeech.fs2 import FastSpeech2
11
- # from modules.diffsinger_midi.fs2 import FastSpeech2MIDI
12
- from utils.hparams import hparams
13
- from training.train_pipeline import Batch2Loss
14
-
15
-
16
- def exists(x):
17
- return x is not None
18
-
19
-
20
- def default(val, d):
21
- if exists(val):
22
- return val
23
- return d() if isfunction(d) else d
24
-
25
-
26
- # gaussian diffusion trainer class
27
-
28
- def extract(a, t, x_shape):
29
- b, *_ = t.shape
30
- out = a.gather(-1, t)
31
- return out.reshape(b, *((1,) * (len(x_shape) - 1)))
32
-
33
-
34
- def noise_like(shape, device, repeat=False):
35
- repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
36
- noise = lambda: torch.randn(shape, device=device)
37
- return repeat_noise() if repeat else noise()
38
-
39
-
40
- def linear_beta_schedule(timesteps, max_beta=hparams.get('max_beta', 0.01)):
41
- """
42
- linear schedule
43
- """
44
- betas = np.linspace(1e-4, max_beta, timesteps)
45
- return betas
46
-
47
-
48
- def cosine_beta_schedule(timesteps, s=0.008):
49
- """
50
- cosine schedule
51
- as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
52
- """
53
- steps = timesteps + 1
54
- x = np.linspace(0, steps, steps)
55
- alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
56
- alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
57
- betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
58
- return np.clip(betas, a_min=0, a_max=0.999)
59
-
60
-
61
- beta_schedule = {
62
- "cosine": cosine_beta_schedule,
63
- "linear": linear_beta_schedule,
64
- }
65
-
66
-
67
- class GaussianDiffusion(nn.Module):
68
- def __init__(self, phone_encoder, out_dims, denoise_fn,
69
- timesteps=1000, K_step=1000, loss_type=hparams.get('diff_loss_type', 'l1'), betas=None, spec_min=None,
70
- spec_max=None):
71
- super().__init__()
72
- self.denoise_fn = denoise_fn
73
- # if hparams.get('use_midi') is not None and hparams['use_midi']:
74
- # self.fs2 = FastSpeech2MIDI(phone_encoder, out_dims)
75
- # else:
76
- self.fs2 = FastSpeech2(phone_encoder, out_dims)
77
- self.mel_bins = out_dims
78
-
79
- if exists(betas):
80
- betas = betas.detach().cpu().numpy() if isinstance(betas, torch.Tensor) else betas
81
- else:
82
- if 'schedule_type' in hparams.keys():
83
- betas = beta_schedule[hparams['schedule_type']](timesteps)
84
- else:
85
- betas = cosine_beta_schedule(timesteps)
86
-
87
- alphas = 1. - betas
88
- alphas_cumprod = np.cumprod(alphas, axis=0)
89
- alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
90
-
91
- timesteps, = betas.shape
92
- self.num_timesteps = int(timesteps)
93
- self.K_step = K_step
94
- self.loss_type = loss_type
95
-
96
- self.noise_list = deque(maxlen=4)
97
-
98
- to_torch = partial(torch.tensor, dtype=torch.float32)
99
-
100
- self.register_buffer('betas', to_torch(betas))
101
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
102
- self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
103
-
104
- # calculations for diffusion q(x_t | x_{t-1}) and others
105
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
106
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
107
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
108
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
109
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
110
-
111
- # calculations for posterior q(x_{t-1} | x_t, x_0)
112
- posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
113
- # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
114
- self.register_buffer('posterior_variance', to_torch(posterior_variance))
115
- # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
116
- self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
117
- self.register_buffer('posterior_mean_coef1', to_torch(
118
- betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
119
- self.register_buffer('posterior_mean_coef2', to_torch(
120
- (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
121
-
122
- self.register_buffer('spec_min', torch.FloatTensor(spec_min)[None, None, :hparams['keep_bins']])
123
- self.register_buffer('spec_max', torch.FloatTensor(spec_max)[None, None, :hparams['keep_bins']])
124
-
125
- def q_mean_variance(self, x_start, t):
126
- mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
127
- variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
128
- log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
129
- return mean, variance, log_variance
130
-
131
- def predict_start_from_noise(self, x_t, t, noise):
132
- return (
133
- extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
134
- extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
135
- )
136
-
137
- def q_posterior(self, x_start, x_t, t):
138
- posterior_mean = (
139
- extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
140
- extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
141
- )
142
- posterior_variance = extract(self.posterior_variance, t, x_t.shape)
143
- posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
144
- return posterior_mean, posterior_variance, posterior_log_variance_clipped
145
-
146
- def p_mean_variance(self, x, t, cond, clip_denoised: bool):
147
- noise_pred = self.denoise_fn(x, t, cond=cond)
148
- x_recon = self.predict_start_from_noise(x, t=t, noise=noise_pred)
149
-
150
- if clip_denoised:
151
- x_recon.clamp_(-1., 1.)
152
-
153
- model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
154
- return model_mean, posterior_variance, posterior_log_variance
155
-
156
- @torch.no_grad()
157
- def p_sample(self, x, t, cond, clip_denoised=True, repeat_noise=False):
158
- b, *_, device = *x.shape, x.device
159
- model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, cond=cond, clip_denoised=clip_denoised)
160
- noise = noise_like(x.shape, device, repeat_noise)
161
- # no noise when t == 0
162
- nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
163
- return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
164
-
165
- @torch.no_grad()
166
- def p_sample_plms(self, x, t, interval, cond, clip_denoised=True, repeat_noise=False):
167
- """
168
- Use the PLMS method from [Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778).
169
- """
170
-
171
- def get_x_pred(x, noise_t, t):
172
- a_t = extract(self.alphas_cumprod, t, x.shape)
173
- a_prev = extract(self.alphas_cumprod, torch.max(t-interval, torch.zeros_like(t)), x.shape)
174
- a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
175
-
176
- x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x - 1 / (a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
177
- x_pred = x + x_delta
178
-
179
- return x_pred
180
-
181
- noise_list = self.noise_list
182
- noise_pred = self.denoise_fn(x, t, cond=cond)
183
-
184
- if len(noise_list) == 0:
185
- x_pred = get_x_pred(x, noise_pred, t)
186
- noise_pred_prev = self.denoise_fn(x_pred, max(t-interval, 0), cond=cond)
187
- noise_pred_prime = (noise_pred + noise_pred_prev) / 2
188
- elif len(noise_list) == 1:
189
- noise_pred_prime = (3 * noise_pred - noise_list[-1]) / 2
190
- elif len(noise_list) == 2:
191
- noise_pred_prime = (23 * noise_pred - 16 * noise_list[-1] + 5 * noise_list[-2]) / 12
192
- elif len(noise_list) >= 3:
193
- noise_pred_prime = (55 * noise_pred - 59 * noise_list[-1] + 37 * noise_list[-2] - 9 * noise_list[-3]) / 24
194
-
195
- x_prev = get_x_pred(x, noise_pred_prime, t)
196
- noise_list.append(noise_pred)
197
-
198
- return x_prev
199
-
200
- def q_sample(self, x_start, t, noise=None):
201
- noise = default(noise, lambda: torch.randn_like(x_start))
202
- return (
203
- extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
204
- extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
205
- )
206
-
207
- def p_losses(self, x_start, t, cond, noise=None, nonpadding=None):
208
- noise = default(noise, lambda: torch.randn_like(x_start))
209
-
210
- x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
211
- x_recon = self.denoise_fn(x_noisy, t, cond)
212
-
213
- if self.loss_type == 'l1':
214
- if nonpadding is not None:
215
- loss = ((noise - x_recon).abs() * nonpadding.unsqueeze(1)).mean()
216
- else:
217
- # print('are you sure w/o nonpadding?')
218
- loss = (noise - x_recon).abs().mean()
219
-
220
- elif self.loss_type == 'l2':
221
- loss = F.mse_loss(noise, x_recon)
222
- else:
223
- raise NotImplementedError()
224
-
225
- return loss
226
-
227
- def forward(self, hubert, mel2ph=None, spk_embed=None,
228
- ref_mels=None, f0=None, uv=None, energy=None, infer=False, **kwargs):
229
- '''
230
- conditioning diffusion, use fastspeech2 encoder output as the condition
231
- '''
232
- ret = self.fs2(hubert, mel2ph, spk_embed, None, f0, uv, energy,
233
- skip_decoder=True, infer=infer, **kwargs)
234
- cond = ret['decoder_inp'].transpose(1, 2)
235
- b, *_, device = *hubert.shape, hubert.device
236
-
237
- if not infer:
238
- Batch2Loss.module4(
239
- self.p_losses,
240
- self.norm_spec(ref_mels), cond, ret, self.K_step, b, device
241
- )
242
- else:
243
- '''
244
- ret['fs2_mel'] = ret['mel_out']
245
- fs2_mels = ret['mel_out']
246
- t = self.K_step
247
- fs2_mels = self.norm_spec(fs2_mels)
248
- fs2_mels = fs2_mels.transpose(1, 2)[:, None, :, :]
249
- x = self.q_sample(x_start=fs2_mels, t=torch.tensor([t - 1], device=device).long())
250
- if hparams.get('gaussian_start') is not None and hparams['gaussian_start']:
251
- print('===> gaussion start.')
252
- shape = (cond.shape[0], 1, self.mel_bins, cond.shape[2])
253
- x = torch.randn(shape, device=device)
254
- '''
255
- if 'use_gt_mel' in kwargs.keys() and kwargs['use_gt_mel']:
256
- t =kwargs['add_noise_step']
257
- print('===>using ground truth mel as start, please make sure parameter "key==0" !')
258
- fs2_mels = ref_mels
259
- fs2_mels = self.norm_spec(fs2_mels)
260
- fs2_mels = fs2_mels.transpose(1, 2)[:, None, :, :]
261
- x = self.q_sample(x_start=fs2_mels, t=torch.tensor([t - 1], device=device).long())
262
- # for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
263
- # x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
264
- else:
265
- t = self.K_step
266
- #print('===> gaussion start.')
267
- shape = (cond.shape[0], 1, self.mel_bins, cond.shape[2])
268
- x = torch.randn(shape, device=device)
269
- if hparams.get('pndm_speedup') and hparams['pndm_speedup'] > 1:
270
- self.noise_list = deque(maxlen=4)
271
- iteration_interval =hparams['pndm_speedup']
272
- for i in tqdm(reversed(range(0, t, iteration_interval)), desc='sample time step',
273
- total=t // iteration_interval):
274
- x = self.p_sample_plms(x, torch.full((b,), i, device=device, dtype=torch.long), iteration_interval,
275
- cond)
276
- else:
277
- for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
278
- x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
279
- x = x[:, 0].transpose(1, 2)
280
- if mel2ph is not None: # for singing
281
- ret['mel_out'] = self.denorm_spec(x) * ((mel2ph > 0).float()[:, :, None])
282
- else:
283
- ret['mel_out'] = self.denorm_spec(x)
284
- return ret
285
-
286
- def norm_spec(self, x):
287
- return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
288
-
289
- def denorm_spec(self, x):
290
- return (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
291
-
292
- def cwt2f0_norm(self, cwt_spec, mean, std, mel2ph):
293
- return self.fs2.cwt2f0_norm(cwt_spec, mean, std, mel2ph)
294
-
295
- def out2mel(self, x):
296
- return x
297
-
298
-
299
- class OfflineGaussianDiffusion(GaussianDiffusion):
300
- def forward(self, txt_tokens, mel2ph=None, spk_embed=None,
301
- ref_mels=None, f0=None, uv=None, energy=None, infer=False, **kwargs):
302
- b, *_, device = *txt_tokens.shape, txt_tokens.device
303
-
304
- ret = self.fs2(txt_tokens, mel2ph, spk_embed, ref_mels, f0, uv, energy,
305
- skip_decoder=True, infer=True, **kwargs)
306
- cond = ret['decoder_inp'].transpose(1, 2)
307
- fs2_mels = ref_mels[1]
308
- ref_mels = ref_mels[0]
309
-
310
- if not infer:
311
- t = torch.randint(0, self.K_step, (b,), device=device).long()
312
- x = ref_mels
313
- x = self.norm_spec(x)
314
- x = x.transpose(1, 2)[:, None, :, :] # [B, 1, M, T]
315
- ret['diff_loss'] = self.p_losses(x, t, cond)
316
- else:
317
- t = self.K_step
318
- fs2_mels = self.norm_spec(fs2_mels)
319
- fs2_mels = fs2_mels.transpose(1, 2)[:, None, :, :]
320
-
321
- x = self.q_sample(x_start=fs2_mels, t=torch.tensor([t - 1], device=device).long())
322
-
323
- if hparams.get('gaussian_start') is not None and hparams['gaussian_start']:
324
- print('===> gaussion start.')
325
- shape = (cond.shape[0], 1, self.mel_bins, cond.shape[2])
326
- x = torch.randn(shape, device=device)
327
- for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
328
- x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
329
- x = x[:, 0].transpose(1, 2)
330
- ret['mel_out'] = self.denorm_spec(x)
331
-
332
- return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/diff/net.py DELETED
@@ -1,135 +0,0 @@
1
- import math
2
-
3
- import torch
4
- import torch.nn as nn
5
- import torch.nn.functional as F
6
-
7
- from math import sqrt
8
-
9
- from utils.hparams import hparams
10
- from modules.commons.common_layers import Mish
11
-
12
- Linear = nn.Linear
13
- ConvTranspose2d = nn.ConvTranspose2d
14
-
15
-
16
- class AttrDict(dict):
17
- def __init__(self, *args, **kwargs):
18
- super(AttrDict, self).__init__(*args, **kwargs)
19
- self.__dict__ = self
20
-
21
- def override(self, attrs):
22
- if isinstance(attrs, dict):
23
- self.__dict__.update(**attrs)
24
- elif isinstance(attrs, (list, tuple, set)):
25
- for attr in attrs:
26
- self.override(attr)
27
- elif attrs is not None:
28
- raise NotImplementedError
29
- return self
30
-
31
-
32
- class SinusoidalPosEmb(nn.Module):
33
- def __init__(self, dim):
34
- super().__init__()
35
- self.dim = dim
36
-
37
- def forward(self, x):
38
- device = x.device
39
- half_dim = self.dim // 2
40
- emb = math.log(10000) / (half_dim - 1)
41
- emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
42
- emb = x[:, None] * emb[None, :]
43
- emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
44
- return emb
45
-
46
-
47
- def Conv1d(*args, **kwargs):
48
- layer = nn.Conv1d(*args, **kwargs)
49
- nn.init.kaiming_normal_(layer.weight)
50
- return layer
51
-
52
-
53
- @torch.jit.script
54
- def silu(x):
55
- return x * torch.sigmoid(x)
56
-
57
-
58
- class ResidualBlock(nn.Module):
59
- def __init__(self, encoder_hidden, residual_channels, dilation):
60
- super().__init__()
61
- self.dilated_conv = Conv1d(residual_channels, 2 * residual_channels, 3, padding=dilation, dilation=dilation)
62
- self.diffusion_projection = Linear(residual_channels, residual_channels)
63
- self.conditioner_projection = Conv1d(encoder_hidden, 2 * residual_channels, 1)
64
- self.output_projection = Conv1d(residual_channels, 2 * residual_channels, 1)
65
-
66
- def forward(self, x, conditioner, diffusion_step):
67
- diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
68
- conditioner = self.conditioner_projection(conditioner)
69
- y = x + diffusion_step
70
-
71
- y = self.dilated_conv(y) + conditioner
72
-
73
- gate, filter = torch.chunk(y, 2, dim=1)
74
- # Using torch.split instead of torch.chunk to avoid using onnx::Slice
75
- # gate, filter = torch.split(y, torch.div(y.shape[1], 2), dim=1)
76
-
77
- y = torch.sigmoid(gate) * torch.tanh(filter)
78
-
79
- y = self.output_projection(y)
80
- residual, skip = torch.chunk(y, 2, dim=1)
81
- # Using torch.split instead of torch.chunk to avoid using onnx::Slice
82
- # residual, skip = torch.split(y, torch.div(y.shape[1], 2), dim=1)
83
-
84
- return (x + residual) / sqrt(2.0), skip
85
-
86
- class DiffNet(nn.Module):
87
- def __init__(self, in_dims=80):
88
- super().__init__()
89
- self.params = params = AttrDict(
90
- # Model params
91
- encoder_hidden=hparams['hidden_size'],
92
- residual_layers=hparams['residual_layers'],
93
- residual_channels=hparams['residual_channels'],
94
- dilation_cycle_length=hparams['dilation_cycle_length'],
95
- )
96
- self.input_projection = Conv1d(in_dims, params.residual_channels, 1)
97
- self.diffusion_embedding = SinusoidalPosEmb(params.residual_channels)
98
- dim = params.residual_channels
99
- self.mlp = nn.Sequential(
100
- nn.Linear(dim, dim * 4),
101
- Mish(),
102
- nn.Linear(dim * 4, dim)
103
- )
104
- self.residual_layers = nn.ModuleList([
105
- ResidualBlock(params.encoder_hidden, params.residual_channels, 2 ** (i % params.dilation_cycle_length))
106
- for i in range(params.residual_layers)
107
- ])
108
- self.skip_projection = Conv1d(params.residual_channels, params.residual_channels, 1)
109
- self.output_projection = Conv1d(params.residual_channels, in_dims, 1)
110
- nn.init.zeros_(self.output_projection.weight)
111
-
112
- def forward(self, spec, diffusion_step, cond):
113
- """
114
-
115
- :param spec: [B, 1, M, T]
116
- :param diffusion_step: [B, 1]
117
- :param cond: [B, M, T]
118
- :return:
119
- """
120
- x = spec[:, 0]
121
- x = self.input_projection(x) # x [B, residual_channel, T]
122
-
123
- x = F.relu(x)
124
- diffusion_step = self.diffusion_embedding(diffusion_step)
125
- diffusion_step = self.mlp(diffusion_step)
126
- skip = []
127
- for layer_id, layer in enumerate(self.residual_layers):
128
- x, skip_connection = layer(x, cond, diffusion_step)
129
- skip.append(skip_connection)
130
-
131
- x = torch.sum(torch.stack(skip), dim=0) / sqrt(len(self.residual_layers))
132
- x = self.skip_projection(x)
133
- x = F.relu(x)
134
- x = self.output_projection(x) # [B, 80, T]
135
- return x[:, None, :, :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/hubert/Hifi.txt DELETED
@@ -1 +0,0 @@
1
- fuck2023arianitesshitcelebrities
 
 
network/hubert/__pycache__/hubert_model.cpython-38.pyc DELETED
Binary file (9.56 kB)
 
network/hubert/__pycache__/vec_model.cpython-38.pyc DELETED
Binary file (1.89 kB)
 
network/hubert/hubert_model.py DELETED
@@ -1,276 +0,0 @@
1
- import copy
2
- import os
3
- import random
4
- from typing import Optional, Tuple
5
-
6
- import librosa
7
- import numpy as np
8
- import torch
9
- import torch.nn as nn
10
- import torch.nn.functional as t_func
11
- from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
12
-
13
- from utils import hparams
14
-
15
-
16
- class Hubert(nn.Module):
17
- def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
18
- super().__init__()
19
- self._mask = mask
20
- self.feature_extractor = FeatureExtractor()
21
- self.feature_projection = FeatureProjection()
22
- self.positional_embedding = PositionalConvEmbedding()
23
- self.norm = nn.LayerNorm(768)
24
- self.dropout = nn.Dropout(0.1)
25
- self.encoder = TransformerEncoder(
26
- nn.TransformerEncoderLayer(
27
- 768, 12, 3072, activation="gelu", batch_first=True
28
- ),
29
- 12,
30
- )
31
- self.proj = nn.Linear(768, 256)
32
-
33
- self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
34
- self.label_embedding = nn.Embedding(num_label_embeddings, 256)
35
-
36
- def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
37
- mask = None
38
- if self.training and self._mask:
39
- mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
40
- x[mask] = self.masked_spec_embed.to(x.dtype)
41
- return x, mask
42
-
43
- def encode(
44
- self, x: torch.Tensor, layer: Optional[int] = None
45
- ) -> Tuple[torch.Tensor, torch.Tensor]:
46
- x = self.feature_extractor(x)
47
- x = self.feature_projection(x.transpose(1, 2))
48
- x, mask = self.mask(x)
49
- x = x + self.positional_embedding(x)
50
- x = self.dropout(self.norm(x))
51
- x = self.encoder(x, output_layer=layer)
52
- return x, mask
53
-
54
- def logits(self, x: torch.Tensor) -> torch.Tensor:
55
- logits = torch.cosine_similarity(
56
- x.unsqueeze(2),
57
- self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
58
- dim=-1,
59
- )
60
- return logits / 0.1
61
-
62
- def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
63
- x, mask = self.encode(x)
64
- x = self.proj(x)
65
- logits = self.logits(x)
66
- return logits, mask
67
-
68
-
69
- class HubertSoft(Hubert):
70
- def __init__(self):
71
- super().__init__()
72
-
73
- # @torch.inference_mode()
74
- def units(self, wav: torch.Tensor) -> torch.Tensor:
75
- wav = torch.nn.functional.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
76
- x, _ = self.encode(wav)
77
- return self.proj(x)
78
-
79
- def forward(self, wav: torch.Tensor):
80
- return self.units(wav)
81
-
82
-
83
- class FeatureExtractor(nn.Module):
84
- def __init__(self):
85
- super().__init__()
86
- self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
87
- self.norm0 = nn.GroupNorm(512, 512)
88
- self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
89
- self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
90
- self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
91
- self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
92
- self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
93
- self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
94
-
95
- def forward(self, x: torch.Tensor) -> torch.Tensor:
96
- x = t_func.gelu(self.norm0(self.conv0(x)))
97
- x = t_func.gelu(self.conv1(x))
98
- x = t_func.gelu(self.conv2(x))
99
- x = t_func.gelu(self.conv3(x))
100
- x = t_func.gelu(self.conv4(x))
101
- x = t_func.gelu(self.conv5(x))
102
- x = t_func.gelu(self.conv6(x))
103
- return x
104
-
105
-
106
- class FeatureProjection(nn.Module):
107
- def __init__(self):
108
- super().__init__()
109
- self.norm = nn.LayerNorm(512)
110
- self.projection = nn.Linear(512, 768)
111
- self.dropout = nn.Dropout(0.1)
112
-
113
- def forward(self, x: torch.Tensor) -> torch.Tensor:
114
- x = self.norm(x)
115
- x = self.projection(x)
116
- x = self.dropout(x)
117
- return x
118
-
119
-
120
- class PositionalConvEmbedding(nn.Module):
121
- def __init__(self):
122
- super().__init__()
123
- self.conv = nn.Conv1d(
124
- 768,
125
- 768,
126
- kernel_size=128,
127
- padding=128 // 2,
128
- groups=16,
129
- )
130
- self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
131
-
132
- def forward(self, x: torch.Tensor) -> torch.Tensor:
133
- x = self.conv(x.transpose(1, 2))
134
- x = t_func.gelu(x[:, :, :-1])
135
- return x.transpose(1, 2)
136
-
137
-
138
- class TransformerEncoder(nn.Module):
139
- def __init__(
140
- self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
141
- ) -> None:
142
- super(TransformerEncoder, self).__init__()
143
- self.layers = nn.ModuleList(
144
- [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
145
- )
146
- self.num_layers = num_layers
147
-
148
- def forward(
149
- self,
150
- src: torch.Tensor,
151
- mask: torch.Tensor = None,
152
- src_key_padding_mask: torch.Tensor = None,
153
- output_layer: Optional[int] = None,
154
- ) -> torch.Tensor:
155
- output = src
156
- for layer in self.layers[:output_layer]:
157
- output = layer(
158
- output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
159
- )
160
- return output
161
-
162
-
163
- def _compute_mask(
164
- shape: Tuple[int, int],
165
- mask_prob: float,
166
- mask_length: int,
167
- device: torch.device,
168
- min_masks: int = 0,
169
- ) -> torch.Tensor:
170
- batch_size, sequence_length = shape
171
-
172
- if mask_length < 1:
173
- raise ValueError("`mask_length` has to be bigger than 0.")
174
-
175
- if mask_length > sequence_length:
176
- raise ValueError(
177
- f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
178
- )
179
-
180
- # compute number of masked spans in batch
181
- num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
182
- num_masked_spans = max(num_masked_spans, min_masks)
183
-
184
- # make sure num masked indices <= sequence_length
185
- if num_masked_spans * mask_length > sequence_length:
186
- num_masked_spans = sequence_length // mask_length
187
-
188
- # SpecAugment mask to fill
189
- mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
190
-
191
- # uniform distribution to sample from, make sure that offset samples are < sequence_length
192
- uniform_dist = torch.ones(
193
- (batch_size, sequence_length - (mask_length - 1)), device=device
194
- )
195
-
196
- # get random indices to mask
197
- mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
198
-
199
- # expand masked indices to masked spans
200
- mask_indices = (
201
- mask_indices.unsqueeze(dim=-1)
202
- .expand((batch_size, num_masked_spans, mask_length))
203
- .reshape(batch_size, num_masked_spans * mask_length)
204
- )
205
- offsets = (
206
- torch.arange(mask_length, device=device)[None, None, :]
207
- .expand((batch_size, num_masked_spans, mask_length))
208
- .reshape(batch_size, num_masked_spans * mask_length)
209
- )
210
- mask_idxs = mask_indices + offsets
211
-
212
- # scatter indices to mask
213
- mask = mask.scatter(1, mask_idxs, True)
214
-
215
- return mask
216
-
217
-
218
- def hubert_soft(
219
- path: str
220
- ) -> HubertSoft:
221
- r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
222
- Args:
223
- path (str): path of a pretrained model
224
- """
225
- dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
226
- hubert = HubertSoft()
227
- checkpoint = torch.load(path)
228
- consume_prefix_in_state_dict_if_present(checkpoint, "module.")
229
- hubert.load_state_dict(checkpoint)
230
- hubert.eval().to(dev)
231
- return hubert
232
-
233
-
234
- def get_units(hbt_soft, raw_wav_path, dev=torch.device('cuda')):
235
- wav, sr = librosa.load(raw_wav_path, sr=None)
236
- assert (sr >= 16000)
237
- if len(wav.shape) > 1:
238
- wav = librosa.to_mono(wav)
239
- if sr != 16000:
240
- wav16 = librosa.resample(wav, sr, 16000)
241
- else:
242
- wav16 = wav
243
- dev = torch.device("cuda" if (dev == torch.device('cuda') and torch.cuda.is_available()) else "cpu")
244
- torch.cuda.is_available() and torch.cuda.empty_cache()
245
- with torch.inference_mode():
246
- units = hbt_soft.units(torch.FloatTensor(wav16.astype(float)).unsqueeze(0).unsqueeze(0).to(dev))
247
- return units
248
-
249
-
250
- def get_end_file(dir_path, end):
251
- file_list = []
252
- for root, dirs, files in os.walk(dir_path):
253
- files = [f for f in files if f[0] != '.']
254
- dirs[:] = [d for d in dirs if d[0] != '.']
255
- for f_file in files:
256
- if f_file.endswith(end):
257
- file_list.append(os.path.join(root, f_file).replace("\\", "/"))
258
- return file_list
259
-
260
-
261
- if __name__ == '__main__':
262
- from pathlib import Path
263
-
264
- dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
265
- # hubert的模型路径
266
- hbt_model = hubert_soft(str(list(Path(hparams['hubert_path']).home().rglob('*.pt'))[0]))
267
- # 这个不用改,自动在根目录下所有wav的同文件夹生成其对应的npy
268
- file_lists = list(Path(hparams['raw_data_dir']).rglob('*.wav'))
269
- nums = len(file_lists)
270
- count = 0
271
- for wav_path in file_lists:
272
- npy_path = wav_path.with_suffix(".npy")
273
- npy_content = get_units(hbt_model, wav_path).cpu().numpy()[0]
274
- np.save(str(npy_path), npy_content)
275
- count += 1
276
- print(f"hubert process:{round(count * 100 / nums, 2)}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/hubert/vec_model.py DELETED
@@ -1,60 +0,0 @@
1
- from pathlib import Path
2
-
3
- import librosa
4
- import numpy as np
5
- import torch
6
-
7
-
8
-
9
- def load_model(vec_path):
10
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
- print("load model(s) from {}".format(vec_path))
12
- from fairseq import checkpoint_utils
13
- models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
14
- [vec_path],
15
- suffix="",
16
- )
17
- model = models[0]
18
- model = model.to(device)
19
- model.eval()
20
- return model
21
-
22
-
23
- def get_vec_units(con_model, audio_path, dev):
24
- audio, sampling_rate = librosa.load(audio_path)
25
- if len(audio.shape) > 1:
26
- audio = librosa.to_mono(audio.transpose(1, 0))
27
- if sampling_rate != 16000:
28
- audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
29
-
30
- feats = torch.from_numpy(audio).float()
31
- if feats.dim() == 2: # double channels
32
- feats = feats.mean(-1)
33
- assert feats.dim() == 1, feats.dim()
34
- feats = feats.view(1, -1)
35
- padding_mask = torch.BoolTensor(feats.shape).fill_(False)
36
- inputs = {
37
- "source": feats.to(dev),
38
- "padding_mask": padding_mask.to(dev),
39
- "output_layer": 9, # layer 9
40
- }
41
- with torch.no_grad():
42
- logits = con_model.extract_features(**inputs)
43
- feats = con_model.final_proj(logits[0])
44
- return feats
45
-
46
-
47
- if __name__ == '__main__':
48
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
- model_path = "../../checkpoints/checkpoint_best_legacy_500.pt" # checkpoint_best_legacy_500.pt
50
- vec_model = load_model(model_path)
51
- # 这个不用改,自动在根目录下所有wav的同文件夹生成其对应的npy
52
- file_lists = list(Path("../../data/vecfox").rglob('*.wav'))
53
- nums = len(file_lists)
54
- count = 0
55
- for wav_path in file_lists:
56
- npy_path = wav_path.with_suffix(".npy")
57
- npy_content = get_vec_units(vec_model, str(wav_path), device).cpu().numpy()[0]
58
- np.save(str(npy_path), npy_content)
59
- count += 1
60
- print(f"hubert process:{round(count * 100 / nums, 2)}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/vocoders/__init__.py DELETED
@@ -1,2 +0,0 @@
1
- from network.vocoders import hifigan
2
- from network.vocoders import nsf_hifigan
 
 
 
network/vocoders/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (219 Bytes)
 
network/vocoders/__pycache__/base_vocoder.cpython-38.pyc DELETED
Binary file (1.24 kB)
 
network/vocoders/__pycache__/hifigan.cpython-38.pyc DELETED
Binary file (2.9 kB)
 
network/vocoders/__pycache__/nsf_hifigan.cpython-38.pyc DELETED
Binary file (3.69 kB)
 
network/vocoders/__pycache__/pwg.cpython-38.pyc DELETED
Binary file (4.65 kB)
 
network/vocoders/__pycache__/vocoder_utils.cpython-38.pyc DELETED
Binary file (682 Bytes)
 
network/vocoders/base_vocoder.py DELETED
@@ -1,39 +0,0 @@
1
- import importlib
2
- VOCODERS = {}
3
-
4
-
5
- def register_vocoder(cls):
6
- VOCODERS[cls.__name__.lower()] = cls
7
- VOCODERS[cls.__name__] = cls
8
- return cls
9
-
10
-
11
- def get_vocoder_cls(hparams):
12
- if hparams['vocoder'] in VOCODERS:
13
- return VOCODERS[hparams['vocoder']]
14
- else:
15
- vocoder_cls = hparams['vocoder']
16
- pkg = ".".join(vocoder_cls.split(".")[:-1])
17
- cls_name = vocoder_cls.split(".")[-1]
18
- vocoder_cls = getattr(importlib.import_module(pkg), cls_name)
19
- return vocoder_cls
20
-
21
-
22
- class BaseVocoder:
23
- def spec2wav(self, mel):
24
- """
25
-
26
- :param mel: [T, 80]
27
- :return: wav: [T']
28
- """
29
-
30
- raise NotImplementedError
31
-
32
- @staticmethod
33
- def wav2spec(wav_fn):
34
- """
35
-
36
- :param wav_fn: str
37
- :return: wav, mel: [T, 80]
38
- """
39
- raise NotImplementedError
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/vocoders/hifigan.py DELETED
@@ -1,83 +0,0 @@
1
- import glob
2
- import json
3
- import os
4
- import re
5
-
6
- import librosa
7
- import torch
8
-
9
- import utils
10
- from modules.hifigan.hifigan import HifiGanGenerator
11
- from utils.hparams import hparams, set_hparams
12
- from network.vocoders.base_vocoder import register_vocoder
13
- from network.vocoders.pwg import PWG
14
- from network.vocoders.vocoder_utils import denoise
15
-
16
-
17
- def load_model(config_path, file_path):
18
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
- ext = os.path.splitext(file_path)[-1]
20
- if ext == '.pth':
21
- if '.yaml' in config_path:
22
- config = set_hparams(config_path, global_hparams=False)
23
- elif '.json' in config_path:
24
- config = json.load(open(config_path, 'r', encoding='utf-8'))
25
- model = torch.load(file_path, map_location="cpu")
26
- elif ext == '.ckpt':
27
- ckpt_dict = torch.load(file_path, map_location="cpu")
28
- if '.yaml' in config_path:
29
- config = set_hparams(config_path, global_hparams=False)
30
- state = ckpt_dict["state_dict"]["model_gen"]
31
- elif '.json' in config_path:
32
- config = json.load(open(config_path, 'r', encoding='utf-8'))
33
- state = ckpt_dict["generator"]
34
- model = HifiGanGenerator(config)
35
- model.load_state_dict(state, strict=True)
36
- model.remove_weight_norm()
37
- model = model.eval().to(device)
38
- print(f"| Loaded model parameters from {file_path}.")
39
- print(f"| HifiGAN device: {device}.")
40
- return model, config, device
41
-
42
-
43
- total_time = 0
44
-
45
-
46
- @register_vocoder
47
- class HifiGAN(PWG):
48
- def __init__(self):
49
- base_dir = hparams['vocoder_ckpt']
50
- config_path = f'{base_dir}/config.yaml'
51
- if os.path.exists(config_path):
52
- file_path = sorted(glob.glob(f'{base_dir}/model_ckpt_steps_*.*'), key=
53
- lambda x: int(re.findall(f'{base_dir}/model_ckpt_steps_(\d+).*', x.replace('\\','/'))[0]))[-1]
54
- print('| load HifiGAN: ', file_path)
55
- self.model, self.config, self.device = load_model(config_path=config_path, file_path=file_path)
56
- else:
57
- config_path = f'{base_dir}/config.json'
58
- ckpt = f'{base_dir}/generator_v1'
59
- if os.path.exists(config_path):
60
- self.model, self.config, self.device = load_model(config_path=config_path, file_path=file_path)
61
-
62
- def spec2wav(self, mel, **kwargs):
63
- device = self.device
64
- with torch.no_grad():
65
- c = torch.FloatTensor(mel).unsqueeze(0).transpose(2, 1).to(device)
66
- with utils.Timer('hifigan', print_time=hparams['profile_infer']):
67
- f0 = kwargs.get('f0')
68
- if f0 is not None and hparams.get('use_nsf'):
69
- f0 = torch.FloatTensor(f0[None, :]).to(device)
70
- y = self.model(c, f0).view(-1)
71
- else:
72
- y = self.model(c).view(-1)
73
- wav_out = y.cpu().numpy()
74
- if hparams.get('vocoder_denoise_c', 0.0) > 0:
75
- wav_out = denoise(wav_out, v=hparams['vocoder_denoise_c'])
76
- return wav_out
77
-
78
- # @staticmethod
79
- # def wav2spec(wav_fn, **kwargs):
80
- # wav, _ = librosa.core.load(wav_fn, sr=hparams['audio_sample_rate'])
81
- # wav_torch = torch.FloatTensor(wav)[None, :]
82
- # mel = mel_spectrogram(wav_torch, hparams).numpy()[0]
83
- # return wav, mel.T
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/vocoders/nsf_hifigan.py DELETED
@@ -1,92 +0,0 @@
1
- import os
2
- import torch
3
- from modules.nsf_hifigan.models import load_model, Generator
4
- from modules.nsf_hifigan.nvSTFT import load_wav_to_torch, STFT
5
- from utils.hparams import hparams
6
- from network.vocoders.base_vocoder import BaseVocoder, register_vocoder
7
-
8
- @register_vocoder
9
- class NsfHifiGAN(BaseVocoder):
10
- def __init__(self, device=None):
11
- if device is None:
12
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
13
- self.device = device
14
- model_path = hparams['vocoder_ckpt']
15
- if os.path.exists(model_path):
16
- print('| Load HifiGAN: ', model_path)
17
- self.model, self.h = load_model(model_path, device=self.device)
18
- else:
19
- print('Error: HifiGAN model file is not found!')
20
-
21
- def spec2wav_torch(self, mel, **kwargs): # mel: [B, T, bins]
22
- if self.h.sampling_rate != hparams['audio_sample_rate']:
23
- print('Mismatch parameters: hparams[\'audio_sample_rate\']=',hparams['audio_sample_rate'],'!=',self.h.sampling_rate,'(vocoder)')
24
- if self.h.num_mels != hparams['audio_num_mel_bins']:
25
- print('Mismatch parameters: hparams[\'audio_num_mel_bins\']=',hparams['audio_num_mel_bins'],'!=',self.h.num_mels,'(vocoder)')
26
- if self.h.n_fft != hparams['fft_size']:
27
- print('Mismatch parameters: hparams[\'fft_size\']=',hparams['fft_size'],'!=',self.h.n_fft,'(vocoder)')
28
- if self.h.win_size != hparams['win_size']:
29
- print('Mismatch parameters: hparams[\'win_size\']=',hparams['win_size'],'!=',self.h.win_size,'(vocoder)')
30
- if self.h.hop_size != hparams['hop_size']:
31
- print('Mismatch parameters: hparams[\'hop_size\']=',hparams['hop_size'],'!=',self.h.hop_size,'(vocoder)')
32
- if self.h.fmin != hparams['fmin']:
33
- print('Mismatch parameters: hparams[\'fmin\']=',hparams['fmin'],'!=',self.h.fmin,'(vocoder)')
34
- if self.h.fmax != hparams['fmax']:
35
- print('Mismatch parameters: hparams[\'fmax\']=',hparams['fmax'],'!=',self.h.fmax,'(vocoder)')
36
- with torch.no_grad():
37
- c = mel.transpose(2, 1) #[B, T, bins]
38
- #log10 to log mel
39
- c = 2.30259 * c
40
- f0 = kwargs.get('f0') #[B, T]
41
- if f0 is not None and hparams.get('use_nsf'):
42
- y = self.model(c, f0).view(-1)
43
- else:
44
- y = self.model(c).view(-1)
45
- return y
46
-
47
- def spec2wav(self, mel, **kwargs):
48
- if self.h.sampling_rate != hparams['audio_sample_rate']:
49
- print('Mismatch parameters: hparams[\'audio_sample_rate\']=',hparams['audio_sample_rate'],'!=',self.h.sampling_rate,'(vocoder)')
50
- if self.h.num_mels != hparams['audio_num_mel_bins']:
51
- print('Mismatch parameters: hparams[\'audio_num_mel_bins\']=',hparams['audio_num_mel_bins'],'!=',self.h.num_mels,'(vocoder)')
52
- if self.h.n_fft != hparams['fft_size']:
53
- print('Mismatch parameters: hparams[\'fft_size\']=',hparams['fft_size'],'!=',self.h.n_fft,'(vocoder)')
54
- if self.h.win_size != hparams['win_size']:
55
- print('Mismatch parameters: hparams[\'win_size\']=',hparams['win_size'],'!=',self.h.win_size,'(vocoder)')
56
- if self.h.hop_size != hparams['hop_size']:
57
- print('Mismatch parameters: hparams[\'hop_size\']=',hparams['hop_size'],'!=',self.h.hop_size,'(vocoder)')
58
- if self.h.fmin != hparams['fmin']:
59
- print('Mismatch parameters: hparams[\'fmin\']=',hparams['fmin'],'!=',self.h.fmin,'(vocoder)')
60
- if self.h.fmax != hparams['fmax']:
61
- print('Mismatch parameters: hparams[\'fmax\']=',hparams['fmax'],'!=',self.h.fmax,'(vocoder)')
62
- with torch.no_grad():
63
- c = torch.FloatTensor(mel).unsqueeze(0).transpose(2, 1).to(self.device)
64
- #log10 to log mel
65
- c = 2.30259 * c
66
- f0 = kwargs.get('f0')
67
- if f0 is not None and hparams.get('use_nsf'):
68
- f0 = torch.FloatTensor(f0[None, :]).to(self.device)
69
- y = self.model(c, f0).view(-1)
70
- else:
71
- y = self.model(c).view(-1)
72
- wav_out = y.cpu().numpy()
73
- return wav_out
74
-
75
- @staticmethod
76
- def wav2spec(inp_path, device=None):
77
- if device is None:
78
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
79
- sampling_rate = hparams['audio_sample_rate']
80
- num_mels = hparams['audio_num_mel_bins']
81
- n_fft = hparams['fft_size']
82
- win_size =hparams['win_size']
83
- hop_size = hparams['hop_size']
84
- fmin = hparams['fmin']
85
- fmax = hparams['fmax']
86
- stft = STFT(sampling_rate, num_mels, n_fft, win_size, hop_size, fmin, fmax)
87
- with torch.no_grad():
88
- wav_torch, _ = load_wav_to_torch(inp_path, target_sr=stft.target_sr)
89
- mel_torch = stft.get_mel(wav_torch.unsqueeze(0).to(device)).squeeze(0).T
90
- #log mel to log10 mel
91
- mel_torch = 0.434294 * mel_torch
92
- return wav_torch.cpu().numpy(), mel_torch.cpu().numpy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/vocoders/pwg.py DELETED
@@ -1,137 +0,0 @@
1
- import glob
2
- import re
3
- import librosa
4
- import torch
5
- import yaml
6
- from sklearn.preprocessing import StandardScaler
7
- from torch import nn
8
- from modules.parallel_wavegan.models import ParallelWaveGANGenerator
9
- from modules.parallel_wavegan.utils import read_hdf5
10
- from utils.hparams import hparams
11
- from utils.pitch_utils import f0_to_coarse
12
- from network.vocoders.base_vocoder import BaseVocoder, register_vocoder
13
- import numpy as np
14
-
15
-
16
- def load_pwg_model(config_path, checkpoint_path, stats_path):
17
- # load config
18
- with open(config_path, encoding='utf-8') as f:
19
- config = yaml.load(f, Loader=yaml.Loader)
20
-
21
- # setup
22
- if torch.cuda.is_available():
23
- device = torch.device("cuda")
24
- else:
25
- device = torch.device("cpu")
26
- model = ParallelWaveGANGenerator(**config["generator_params"])
27
-
28
- ckpt_dict = torch.load(checkpoint_path, map_location="cpu")
29
- if 'state_dict' not in ckpt_dict: # official vocoder
30
- model.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["model"]["generator"])
31
- scaler = StandardScaler()
32
- if config["format"] == "hdf5":
33
- scaler.mean_ = read_hdf5(stats_path, "mean")
34
- scaler.scale_ = read_hdf5(stats_path, "scale")
35
- elif config["format"] == "npy":
36
- scaler.mean_ = np.load(stats_path)[0]
37
- scaler.scale_ = np.load(stats_path)[1]
38
- else:
39
- raise ValueError("support only hdf5 or npy format.")
40
- else: # custom PWG vocoder
41
- fake_task = nn.Module()
42
- fake_task.model_gen = model
43
- fake_task.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["state_dict"], strict=False)
44
- scaler = None
45
-
46
- model.remove_weight_norm()
47
- model = model.eval().to(device)
48
- print(f"| Loaded model parameters from {checkpoint_path}.")
49
- print(f"| PWG device: {device}.")
50
- return model, scaler, config, device
51
-
52
-
53
- @register_vocoder
54
- class PWG(BaseVocoder):
55
- def __init__(self):
56
- if hparams['vocoder_ckpt'] == '': # load LJSpeech PWG pretrained model
57
- base_dir = 'wavegan_pretrained'
58
- ckpts = glob.glob(f'{base_dir}/checkpoint-*steps.pkl')
59
- ckpt = sorted(ckpts, key=
60
- lambda x: int(re.findall(f'{base_dir}/checkpoint-(\d+)steps.pkl', x)[0]))[-1]
61
- config_path = f'{base_dir}/config.yaml'
62
- print('| load PWG: ', ckpt)
63
- self.model, self.scaler, self.config, self.device = load_pwg_model(
64
- config_path=config_path,
65
- checkpoint_path=ckpt,
66
- stats_path=f'{base_dir}/stats.h5',
67
- )
68
- else:
69
- base_dir = hparams['vocoder_ckpt']
70
- print(base_dir)
71
- config_path = f'{base_dir}/config.yaml'
72
- ckpt = sorted(glob.glob(f'{base_dir}/model_ckpt_steps_*.ckpt'), key=
73
- lambda x: int(re.findall(f'{base_dir}/model_ckpt_steps_(\d+).ckpt', x)[0]))[-1]
74
- print('| load PWG: ', ckpt)
75
- self.scaler = None
76
- self.model, _, self.config, self.device = load_pwg_model(
77
- config_path=config_path,
78
- checkpoint_path=ckpt,
79
- stats_path=f'{base_dir}/stats.h5',
80
- )
81
-
82
- def spec2wav(self, mel, **kwargs):
83
- # start generation
84
- config = self.config
85
- device = self.device
86
- pad_size = (config["generator_params"]["aux_context_window"],
87
- config["generator_params"]["aux_context_window"])
88
- c = mel
89
- if self.scaler is not None:
90
- c = self.scaler.transform(c)
91
-
92
- with torch.no_grad():
93
- z = torch.randn(1, 1, c.shape[0] * config["hop_size"]).to(device)
94
- c = np.pad(c, (pad_size, (0, 0)), "edge")
95
- c = torch.FloatTensor(c).unsqueeze(0).transpose(2, 1).to(device)
96
- p = kwargs.get('f0')
97
- if p is not None:
98
- p = f0_to_coarse(p)
99
- p = np.pad(p, (pad_size,), "edge")
100
- p = torch.LongTensor(p[None, :]).to(device)
101
- y = self.model(z, c, p).view(-1)
102
- wav_out = y.cpu().numpy()
103
- return wav_out
104
-
105
- @staticmethod
106
- def wav2spec(wav_fn, return_linear=False):
107
- from preprocessing.data_gen_utils import process_utterance
108
- res = process_utterance(
109
- wav_fn, fft_size=hparams['fft_size'],
110
- hop_size=hparams['hop_size'],
111
- win_length=hparams['win_size'],
112
- num_mels=hparams['audio_num_mel_bins'],
113
- fmin=hparams['fmin'],
114
- fmax=hparams['fmax'],
115
- sample_rate=hparams['audio_sample_rate'],
116
- loud_norm=hparams['loud_norm'],
117
- min_level_db=hparams['min_level_db'],
118
- return_linear=return_linear, vocoder='pwg', eps=float(hparams.get('wav2spec_eps', 1e-10)))
119
- if return_linear:
120
- return res[0], res[1].T, res[2].T # [T, 80], [T, n_fft]
121
- else:
122
- return res[0], res[1].T
123
-
124
- @staticmethod
125
- def wav2mfcc(wav_fn):
126
- fft_size = hparams['fft_size']
127
- hop_size = hparams['hop_size']
128
- win_length = hparams['win_size']
129
- sample_rate = hparams['audio_sample_rate']
130
- wav, _ = librosa.core.load(wav_fn, sr=sample_rate)
131
- mfcc = librosa.feature.mfcc(y=wav, sr=sample_rate, n_mfcc=13,
132
- n_fft=fft_size, hop_length=hop_size,
133
- win_length=win_length, pad_mode="constant", power=1.0)
134
- mfcc_delta = librosa.feature.delta(mfcc, order=1)
135
- mfcc_delta_delta = librosa.feature.delta(mfcc, order=2)
136
- mfcc = np.concatenate([mfcc, mfcc_delta, mfcc_delta_delta]).T
137
- return mfcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
network/vocoders/vocoder_utils.py DELETED
@@ -1,15 +0,0 @@
1
- import librosa
2
-
3
- from utils.hparams import hparams
4
- import numpy as np
5
-
6
-
7
- def denoise(wav, v=0.1):
8
- spec = librosa.stft(y=wav, n_fft=hparams['fft_size'], hop_length=hparams['hop_size'],
9
- win_length=hparams['win_size'], pad_mode='constant')
10
- spec_m = np.abs(spec)
11
- spec_m = np.clip(spec_m - v, a_min=0, a_max=None)
12
- spec_a = np.angle(spec)
13
-
14
- return librosa.istft(spec_m * np.exp(1j * spec_a), hop_length=hparams['hop_size'],
15
- win_length=hparams['win_size'])