keithhon commited on
Commit
03c3811
1 Parent(s): 848667e

Upload vocoder/models/fatchord_version.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vocoder/models/fatchord_version.py +434 -0
vocoder/models/fatchord_version.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from vocoder.distribution import sample_from_discretized_mix_logistic
5
+ from vocoder.display import *
6
+ from vocoder.audio import *
7
+
8
+
9
+ class ResBlock(nn.Module):
10
+ def __init__(self, dims):
11
+ super().__init__()
12
+ self.conv1 = nn.Conv1d(dims, dims, kernel_size=1, bias=False)
13
+ self.conv2 = nn.Conv1d(dims, dims, kernel_size=1, bias=False)
14
+ self.batch_norm1 = nn.BatchNorm1d(dims)
15
+ self.batch_norm2 = nn.BatchNorm1d(dims)
16
+
17
+ def forward(self, x):
18
+ residual = x
19
+ x = self.conv1(x)
20
+ x = self.batch_norm1(x)
21
+ x = F.relu(x)
22
+ x = self.conv2(x)
23
+ x = self.batch_norm2(x)
24
+ return x + residual
25
+
26
+
27
+ class MelResNet(nn.Module):
28
+ def __init__(self, res_blocks, in_dims, compute_dims, res_out_dims, pad):
29
+ super().__init__()
30
+ k_size = pad * 2 + 1
31
+ self.conv_in = nn.Conv1d(in_dims, compute_dims, kernel_size=k_size, bias=False)
32
+ self.batch_norm = nn.BatchNorm1d(compute_dims)
33
+ self.layers = nn.ModuleList()
34
+ for i in range(res_blocks):
35
+ self.layers.append(ResBlock(compute_dims))
36
+ self.conv_out = nn.Conv1d(compute_dims, res_out_dims, kernel_size=1)
37
+
38
+ def forward(self, x):
39
+ x = self.conv_in(x)
40
+ x = self.batch_norm(x)
41
+ x = F.relu(x)
42
+ for f in self.layers: x = f(x)
43
+ x = self.conv_out(x)
44
+ return x
45
+
46
+
47
+ class Stretch2d(nn.Module):
48
+ def __init__(self, x_scale, y_scale):
49
+ super().__init__()
50
+ self.x_scale = x_scale
51
+ self.y_scale = y_scale
52
+
53
+ def forward(self, x):
54
+ b, c, h, w = x.size()
55
+ x = x.unsqueeze(-1).unsqueeze(3)
56
+ x = x.repeat(1, 1, 1, self.y_scale, 1, self.x_scale)
57
+ return x.view(b, c, h * self.y_scale, w * self.x_scale)
58
+
59
+
60
+ class UpsampleNetwork(nn.Module):
61
+ def __init__(self, feat_dims, upsample_scales, compute_dims,
62
+ res_blocks, res_out_dims, pad):
63
+ super().__init__()
64
+ total_scale = np.cumproduct(upsample_scales)[-1]
65
+ self.indent = pad * total_scale
66
+ self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims, pad)
67
+ self.resnet_stretch = Stretch2d(total_scale, 1)
68
+ self.up_layers = nn.ModuleList()
69
+ for scale in upsample_scales:
70
+ k_size = (1, scale * 2 + 1)
71
+ padding = (0, scale)
72
+ stretch = Stretch2d(scale, 1)
73
+ conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)
74
+ conv.weight.data.fill_(1. / k_size[1])
75
+ self.up_layers.append(stretch)
76
+ self.up_layers.append(conv)
77
+
78
+ def forward(self, m):
79
+ aux = self.resnet(m).unsqueeze(1)
80
+ aux = self.resnet_stretch(aux)
81
+ aux = aux.squeeze(1)
82
+ m = m.unsqueeze(1)
83
+ for f in self.up_layers: m = f(m)
84
+ m = m.squeeze(1)[:, :, self.indent:-self.indent]
85
+ return m.transpose(1, 2), aux.transpose(1, 2)
86
+
87
+
88
+ class WaveRNN(nn.Module):
89
+ def __init__(self, rnn_dims, fc_dims, bits, pad, upsample_factors,
90
+ feat_dims, compute_dims, res_out_dims, res_blocks,
91
+ hop_length, sample_rate, mode='RAW'):
92
+ super().__init__()
93
+ self.mode = mode
94
+ self.pad = pad
95
+ if self.mode == 'RAW' :
96
+ self.n_classes = 2 ** bits
97
+ elif self.mode == 'MOL' :
98
+ self.n_classes = 30
99
+ else :
100
+ RuntimeError("Unknown model mode value - ", self.mode)
101
+
102
+ self.rnn_dims = rnn_dims
103
+ self.aux_dims = res_out_dims // 4
104
+ self.hop_length = hop_length
105
+ self.sample_rate = sample_rate
106
+
107
+ self.upsample = UpsampleNetwork(feat_dims, upsample_factors, compute_dims, res_blocks, res_out_dims, pad)
108
+ self.I = nn.Linear(feat_dims + self.aux_dims + 1, rnn_dims)
109
+ self.rnn1 = nn.GRU(rnn_dims, rnn_dims, batch_first=True)
110
+ self.rnn2 = nn.GRU(rnn_dims + self.aux_dims, rnn_dims, batch_first=True)
111
+ self.fc1 = nn.Linear(rnn_dims + self.aux_dims, fc_dims)
112
+ self.fc2 = nn.Linear(fc_dims + self.aux_dims, fc_dims)
113
+ self.fc3 = nn.Linear(fc_dims, self.n_classes)
114
+
115
+ self.step = nn.Parameter(torch.zeros(1).long(), requires_grad=False)
116
+ self.num_params()
117
+
118
+ def forward(self, x, mels):
119
+ self.step += 1
120
+ bsize = x.size(0)
121
+ if torch.cuda.is_available():
122
+ h1 = torch.zeros(1, bsize, self.rnn_dims).cuda()
123
+ h2 = torch.zeros(1, bsize, self.rnn_dims).cuda()
124
+ else:
125
+ h1 = torch.zeros(1, bsize, self.rnn_dims).cpu()
126
+ h2 = torch.zeros(1, bsize, self.rnn_dims).cpu()
127
+ mels, aux = self.upsample(mels)
128
+
129
+ aux_idx = [self.aux_dims * i for i in range(5)]
130
+ a1 = aux[:, :, aux_idx[0]:aux_idx[1]]
131
+ a2 = aux[:, :, aux_idx[1]:aux_idx[2]]
132
+ a3 = aux[:, :, aux_idx[2]:aux_idx[3]]
133
+ a4 = aux[:, :, aux_idx[3]:aux_idx[4]]
134
+
135
+ x = torch.cat([x.unsqueeze(-1), mels, a1], dim=2)
136
+ x = self.I(x)
137
+ res = x
138
+ x, _ = self.rnn1(x, h1)
139
+
140
+ x = x + res
141
+ res = x
142
+ x = torch.cat([x, a2], dim=2)
143
+ x, _ = self.rnn2(x, h2)
144
+
145
+ x = x + res
146
+ x = torch.cat([x, a3], dim=2)
147
+ x = F.relu(self.fc1(x))
148
+
149
+ x = torch.cat([x, a4], dim=2)
150
+ x = F.relu(self.fc2(x))
151
+ return self.fc3(x)
152
+
153
+ def generate(self, mels, batched, target, overlap, mu_law, progress_callback=None):
154
+ mu_law = mu_law if self.mode == 'RAW' else False
155
+ progress_callback = progress_callback or self.gen_display
156
+
157
+ self.eval()
158
+ output = []
159
+ start = time.time()
160
+ rnn1 = self.get_gru_cell(self.rnn1)
161
+ rnn2 = self.get_gru_cell(self.rnn2)
162
+
163
+ with torch.no_grad():
164
+ if torch.cuda.is_available():
165
+ mels = mels.cuda()
166
+ else:
167
+ mels = mels.cpu()
168
+ wave_len = (mels.size(-1) - 1) * self.hop_length
169
+ mels = self.pad_tensor(mels.transpose(1, 2), pad=self.pad, side='both')
170
+ mels, aux = self.upsample(mels.transpose(1, 2))
171
+
172
+ if batched:
173
+ mels = self.fold_with_overlap(mels, target, overlap)
174
+ aux = self.fold_with_overlap(aux, target, overlap)
175
+
176
+ b_size, seq_len, _ = mels.size()
177
+
178
+ if torch.cuda.is_available():
179
+ h1 = torch.zeros(b_size, self.rnn_dims).cuda()
180
+ h2 = torch.zeros(b_size, self.rnn_dims).cuda()
181
+ x = torch.zeros(b_size, 1).cuda()
182
+ else:
183
+ h1 = torch.zeros(b_size, self.rnn_dims).cpu()
184
+ h2 = torch.zeros(b_size, self.rnn_dims).cpu()
185
+ x = torch.zeros(b_size, 1).cpu()
186
+
187
+ d = self.aux_dims
188
+ aux_split = [aux[:, :, d * i:d * (i + 1)] for i in range(4)]
189
+
190
+ for i in range(seq_len):
191
+
192
+ m_t = mels[:, i, :]
193
+
194
+ a1_t, a2_t, a3_t, a4_t = (a[:, i, :] for a in aux_split)
195
+
196
+ x = torch.cat([x, m_t, a1_t], dim=1)
197
+ x = self.I(x)
198
+ h1 = rnn1(x, h1)
199
+
200
+ x = x + h1
201
+ inp = torch.cat([x, a2_t], dim=1)
202
+ h2 = rnn2(inp, h2)
203
+
204
+ x = x + h2
205
+ x = torch.cat([x, a3_t], dim=1)
206
+ x = F.relu(self.fc1(x))
207
+
208
+ x = torch.cat([x, a4_t], dim=1)
209
+ x = F.relu(self.fc2(x))
210
+
211
+ logits = self.fc3(x)
212
+
213
+ if self.mode == 'MOL':
214
+ sample = sample_from_discretized_mix_logistic(logits.unsqueeze(0).transpose(1, 2))
215
+ output.append(sample.view(-1))
216
+ if torch.cuda.is_available():
217
+ # x = torch.FloatTensor([[sample]]).cuda()
218
+ x = sample.transpose(0, 1).cuda()
219
+ else:
220
+ x = sample.transpose(0, 1)
221
+
222
+ elif self.mode == 'RAW' :
223
+ posterior = F.softmax(logits, dim=1)
224
+ distrib = torch.distributions.Categorical(posterior)
225
+
226
+ sample = 2 * distrib.sample().float() / (self.n_classes - 1.) - 1.
227
+ output.append(sample)
228
+ x = sample.unsqueeze(-1)
229
+ else:
230
+ raise RuntimeError("Unknown model mode value - ", self.mode)
231
+
232
+ if i % 100 == 0:
233
+ gen_rate = (i + 1) / (time.time() - start) * b_size / 1000
234
+ progress_callback(i, seq_len, b_size, gen_rate)
235
+
236
+ output = torch.stack(output).transpose(0, 1)
237
+ output = output.cpu().numpy()
238
+ output = output.astype(np.float64)
239
+
240
+ if batched:
241
+ output = self.xfade_and_unfold(output, target, overlap)
242
+ else:
243
+ output = output[0]
244
+
245
+ if mu_law:
246
+ output = decode_mu_law(output, self.n_classes, False)
247
+ if hp.apply_preemphasis:
248
+ output = de_emphasis(output)
249
+
250
+ # Fade-out at the end to avoid signal cutting out suddenly
251
+ fade_out = np.linspace(1, 0, 20 * self.hop_length)
252
+ output = output[:wave_len]
253
+ output[-20 * self.hop_length:] *= fade_out
254
+
255
+ self.train()
256
+
257
+ return output
258
+
259
+
260
+ def gen_display(self, i, seq_len, b_size, gen_rate):
261
+ pbar = progbar(i, seq_len)
262
+ msg = f'| {pbar} {i*b_size}/{seq_len*b_size} | Batch Size: {b_size} | Gen Rate: {gen_rate:.1f}kHz | '
263
+ stream(msg)
264
+
265
+ def get_gru_cell(self, gru):
266
+ gru_cell = nn.GRUCell(gru.input_size, gru.hidden_size)
267
+ gru_cell.weight_hh.data = gru.weight_hh_l0.data
268
+ gru_cell.weight_ih.data = gru.weight_ih_l0.data
269
+ gru_cell.bias_hh.data = gru.bias_hh_l0.data
270
+ gru_cell.bias_ih.data = gru.bias_ih_l0.data
271
+ return gru_cell
272
+
273
+ def pad_tensor(self, x, pad, side='both'):
274
+ # NB - this is just a quick method i need right now
275
+ # i.e., it won't generalise to other shapes/dims
276
+ b, t, c = x.size()
277
+ total = t + 2 * pad if side == 'both' else t + pad
278
+ if torch.cuda.is_available():
279
+ padded = torch.zeros(b, total, c).cuda()
280
+ else:
281
+ padded = torch.zeros(b, total, c).cpu()
282
+ if side == 'before' or side == 'both':
283
+ padded[:, pad:pad + t, :] = x
284
+ elif side == 'after':
285
+ padded[:, :t, :] = x
286
+ return padded
287
+
288
+ def fold_with_overlap(self, x, target, overlap):
289
+
290
+ ''' Fold the tensor with overlap for quick batched inference.
291
+ Overlap will be used for crossfading in xfade_and_unfold()
292
+
293
+ Args:
294
+ x (tensor) : Upsampled conditioning features.
295
+ shape=(1, timesteps, features)
296
+ target (int) : Target timesteps for each index of batch
297
+ overlap (int) : Timesteps for both xfade and rnn warmup
298
+
299
+ Return:
300
+ (tensor) : shape=(num_folds, target + 2 * overlap, features)
301
+
302
+ Details:
303
+ x = [[h1, h2, ... hn]]
304
+
305
+ Where each h is a vector of conditioning features
306
+
307
+ Eg: target=2, overlap=1 with x.size(1)=10
308
+
309
+ folded = [[h1, h2, h3, h4],
310
+ [h4, h5, h6, h7],
311
+ [h7, h8, h9, h10]]
312
+ '''
313
+
314
+ _, total_len, features = x.size()
315
+
316
+ # Calculate variables needed
317
+ num_folds = (total_len - overlap) // (target + overlap)
318
+ extended_len = num_folds * (overlap + target) + overlap
319
+ remaining = total_len - extended_len
320
+
321
+ # Pad if some time steps poking out
322
+ if remaining != 0:
323
+ num_folds += 1
324
+ padding = target + 2 * overlap - remaining
325
+ x = self.pad_tensor(x, padding, side='after')
326
+
327
+ if torch.cuda.is_available():
328
+ folded = torch.zeros(num_folds, target + 2 * overlap, features).cuda()
329
+ else:
330
+ folded = torch.zeros(num_folds, target + 2 * overlap, features).cpu()
331
+
332
+ # Get the values for the folded tensor
333
+ for i in range(num_folds):
334
+ start = i * (target + overlap)
335
+ end = start + target + 2 * overlap
336
+ folded[i] = x[:, start:end, :]
337
+
338
+ return folded
339
+
340
+ def xfade_and_unfold(self, y, target, overlap):
341
+
342
+ ''' Applies a crossfade and unfolds into a 1d array.
343
+
344
+ Args:
345
+ y (ndarry) : Batched sequences of audio samples
346
+ shape=(num_folds, target + 2 * overlap)
347
+ dtype=np.float64
348
+ overlap (int) : Timesteps for both xfade and rnn warmup
349
+
350
+ Return:
351
+ (ndarry) : audio samples in a 1d array
352
+ shape=(total_len)
353
+ dtype=np.float64
354
+
355
+ Details:
356
+ y = [[seq1],
357
+ [seq2],
358
+ [seq3]]
359
+
360
+ Apply a gain envelope at both ends of the sequences
361
+
362
+ y = [[seq1_in, seq1_target, seq1_out],
363
+ [seq2_in, seq2_target, seq2_out],
364
+ [seq3_in, seq3_target, seq3_out]]
365
+
366
+ Stagger and add up the groups of samples:
367
+
368
+ [seq1_in, seq1_target, (seq1_out + seq2_in), seq2_target, ...]
369
+
370
+ '''
371
+
372
+ num_folds, length = y.shape
373
+ target = length - 2 * overlap
374
+ total_len = num_folds * (target + overlap) + overlap
375
+
376
+ # Need some silence for the rnn warmup
377
+ silence_len = overlap // 2
378
+ fade_len = overlap - silence_len
379
+ silence = np.zeros((silence_len), dtype=np.float64)
380
+
381
+ # Equal power crossfade
382
+ t = np.linspace(-1, 1, fade_len, dtype=np.float64)
383
+ fade_in = np.sqrt(0.5 * (1 + t))
384
+ fade_out = np.sqrt(0.5 * (1 - t))
385
+
386
+ # Concat the silence to the fades
387
+ fade_in = np.concatenate([silence, fade_in])
388
+ fade_out = np.concatenate([fade_out, silence])
389
+
390
+ # Apply the gain to the overlap samples
391
+ y[:, :overlap] *= fade_in
392
+ y[:, -overlap:] *= fade_out
393
+
394
+ unfolded = np.zeros((total_len), dtype=np.float64)
395
+
396
+ # Loop to add up all the samples
397
+ for i in range(num_folds):
398
+ start = i * (target + overlap)
399
+ end = start + target + 2 * overlap
400
+ unfolded[start:end] += y[i]
401
+
402
+ return unfolded
403
+
404
+ def get_step(self) :
405
+ return self.step.data.item()
406
+
407
+ def checkpoint(self, model_dir, optimizer) :
408
+ k_steps = self.get_step() // 1000
409
+ self.save(model_dir.joinpath("checkpoint_%dk_steps.pt" % k_steps), optimizer)
410
+
411
+ def log(self, path, msg) :
412
+ with open(path, 'a') as f:
413
+ print(msg, file=f)
414
+
415
+ def load(self, path, optimizer) :
416
+ checkpoint = torch.load(path)
417
+ if "optimizer_state" in checkpoint:
418
+ self.load_state_dict(checkpoint["model_state"])
419
+ optimizer.load_state_dict(checkpoint["optimizer_state"])
420
+ else:
421
+ # Backwards compatibility
422
+ self.load_state_dict(checkpoint)
423
+
424
+ def save(self, path, optimizer) :
425
+ torch.save({
426
+ "model_state": self.state_dict(),
427
+ "optimizer_state": optimizer.state_dict(),
428
+ }, path)
429
+
430
+ def num_params(self, print_out=True):
431
+ parameters = filter(lambda p: p.requires_grad, self.parameters())
432
+ parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000
433
+ if print_out :
434
+ print('Trainable Parameters: %.3fM' % parameters)