Kikirilkov commited on
Commit
c885bbd
1 Parent(s): 7f366eb

Upload 2 files

Browse files
TTS/vocoder/models/deepmind_version.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from utils.display import *
5
+ from utils.dsp import *
6
+
7
+
8
+ class WaveRNN(nn.Module) :
9
+ def __init__(self, hidden_size=896, quantisation=256) :
10
+ super(WaveRNN, self).__init__()
11
+
12
+ self.hidden_size = hidden_size
13
+ self.split_size = hidden_size // 2
14
+
15
+ # The main matmul
16
+ self.R = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
17
+
18
+ # Output fc layers
19
+ self.O1 = nn.Linear(self.split_size, self.split_size)
20
+ self.O2 = nn.Linear(self.split_size, quantisation)
21
+ self.O3 = nn.Linear(self.split_size, self.split_size)
22
+ self.O4 = nn.Linear(self.split_size, quantisation)
23
+
24
+ # Input fc layers
25
+ self.I_coarse = nn.Linear(2, 3 * self.split_size, bias=False)
26
+ self.I_fine = nn.Linear(3, 3 * self.split_size, bias=False)
27
+
28
+ # biases for the gates
29
+ self.bias_u = nn.Parameter(torch.zeros(self.hidden_size))
30
+ self.bias_r = nn.Parameter(torch.zeros(self.hidden_size))
31
+ self.bias_e = nn.Parameter(torch.zeros(self.hidden_size))
32
+
33
+ # display num params
34
+ self.num_params()
35
+
36
+
37
+ def forward(self, prev_y, prev_hidden, current_coarse) :
38
+
39
+ # Main matmul - the projection is split 3 ways
40
+ R_hidden = self.R(prev_hidden)
41
+ R_u, R_r, R_e, = torch.split(R_hidden, self.hidden_size, dim=1)
42
+
43
+ # Project the prev input
44
+ coarse_input_proj = self.I_coarse(prev_y)
45
+ I_coarse_u, I_coarse_r, I_coarse_e = \
46
+ torch.split(coarse_input_proj, self.split_size, dim=1)
47
+
48
+ # Project the prev input and current coarse sample
49
+ fine_input = torch.cat([prev_y, current_coarse], dim=1)
50
+ fine_input_proj = self.I_fine(fine_input)
51
+ I_fine_u, I_fine_r, I_fine_e = \
52
+ torch.split(fine_input_proj, self.split_size, dim=1)
53
+
54
+ # concatenate for the gates
55
+ I_u = torch.cat([I_coarse_u, I_fine_u], dim=1)
56
+ I_r = torch.cat([I_coarse_r, I_fine_r], dim=1)
57
+ I_e = torch.cat([I_coarse_e, I_fine_e], dim=1)
58
+
59
+ # Compute all gates for coarse and fine
60
+ u = F.sigmoid(R_u + I_u + self.bias_u)
61
+ r = F.sigmoid(R_r + I_r + self.bias_r)
62
+ e = F.tanh(r * R_e + I_e + self.bias_e)
63
+ hidden = u * prev_hidden + (1. - u) * e
64
+
65
+ # Split the hidden state
66
+ hidden_coarse, hidden_fine = torch.split(hidden, self.split_size, dim=1)
67
+
68
+ # Compute outputs
69
+ out_coarse = self.O2(F.relu(self.O1(hidden_coarse)))
70
+ out_fine = self.O4(F.relu(self.O3(hidden_fine)))
71
+
72
+ return out_coarse, out_fine, hidden
73
+
74
+
75
+ def generate(self, seq_len):
76
+ with torch.no_grad():
77
+ # First split up the biases for the gates
78
+ b_coarse_u, b_fine_u = torch.split(self.bias_u, self.split_size)
79
+ b_coarse_r, b_fine_r = torch.split(self.bias_r, self.split_size)
80
+ b_coarse_e, b_fine_e = torch.split(self.bias_e, self.split_size)
81
+
82
+ # Lists for the two output seqs
83
+ c_outputs, f_outputs = [], []
84
+
85
+ # Some initial inputs
86
+ out_coarse = torch.LongTensor([0]).cuda()
87
+ out_fine = torch.LongTensor([0]).cuda()
88
+
89
+ # We'll meed a hidden state
90
+ hidden = self.init_hidden()
91
+
92
+ # Need a clock for display
93
+ start = time.time()
94
+
95
+ # Loop for generation
96
+ for i in range(seq_len) :
97
+
98
+ # Split into two hidden states
99
+ hidden_coarse, hidden_fine = \
100
+ torch.split(hidden, self.split_size, dim=1)
101
+
102
+ # Scale and concat previous predictions
103
+ out_coarse = out_coarse.unsqueeze(0).float() / 127.5 - 1.
104
+ out_fine = out_fine.unsqueeze(0).float() / 127.5 - 1.
105
+ prev_outputs = torch.cat([out_coarse, out_fine], dim=1)
106
+
107
+ # Project input
108
+ coarse_input_proj = self.I_coarse(prev_outputs)
109
+ I_coarse_u, I_coarse_r, I_coarse_e = \
110
+ torch.split(coarse_input_proj, self.split_size, dim=1)
111
+
112
+ # Project hidden state and split 6 ways
113
+ R_hidden = self.R(hidden)
114
+ R_coarse_u , R_fine_u, \
115
+ R_coarse_r, R_fine_r, \
116
+ R_coarse_e, R_fine_e = torch.split(R_hidden, self.split_size, dim=1)
117
+
118
+ # Compute the coarse gates
119
+ u = F.sigmoid(R_coarse_u + I_coarse_u + b_coarse_u)
120
+ r = F.sigmoid(R_coarse_r + I_coarse_r + b_coarse_r)
121
+ e = F.tanh(r * R_coarse_e + I_coarse_e + b_coarse_e)
122
+ hidden_coarse = u * hidden_coarse + (1. - u) * e
123
+
124
+ # Compute the coarse output
125
+ out_coarse = self.O2(F.relu(self.O1(hidden_coarse)))
126
+ posterior = F.softmax(out_coarse, dim=1)
127
+ distrib = torch.distributions.Categorical(posterior)
128
+ out_coarse = distrib.sample()
129
+ c_outputs.append(out_coarse)
130
+
131
+ # Project the [prev outputs and predicted coarse sample]
132
+ coarse_pred = out_coarse.float() / 127.5 - 1.
133
+ fine_input = torch.cat([prev_outputs, coarse_pred.unsqueeze(0)], dim=1)
134
+ fine_input_proj = self.I_fine(fine_input)
135
+ I_fine_u, I_fine_r, I_fine_e = \
136
+ torch.split(fine_input_proj, self.split_size, dim=1)
137
+
138
+ # Compute the fine gates
139
+ u = F.sigmoid(R_fine_u + I_fine_u + b_fine_u)
140
+ r = F.sigmoid(R_fine_r + I_fine_r + b_fine_r)
141
+ e = F.tanh(r * R_fine_e + I_fine_e + b_fine_e)
142
+ hidden_fine = u * hidden_fine + (1. - u) * e
143
+
144
+ # Compute the fine output
145
+ out_fine = self.O4(F.relu(self.O3(hidden_fine)))
146
+ posterior = F.softmax(out_fine, dim=1)
147
+ distrib = torch.distributions.Categorical(posterior)
148
+ out_fine = distrib.sample()
149
+ f_outputs.append(out_fine)
150
+
151
+ # Put the hidden state back together
152
+ hidden = torch.cat([hidden_coarse, hidden_fine], dim=1)
153
+
154
+ # Display progress
155
+ speed = (i + 1) / (time.time() - start)
156
+ stream('Gen: %i/%i -- Speed: %i', (i + 1, seq_len, speed))
157
+
158
+ coarse = torch.stack(c_outputs).squeeze(1).cpu().data.numpy()
159
+ fine = torch.stack(f_outputs).squeeze(1).cpu().data.numpy()
160
+ output = combine_signal(coarse, fine)
161
+
162
+ return output, coarse, fine
163
+
164
+ def init_hidden(self, batch_size=1) :
165
+ return torch.zeros(batch_size, self.hidden_size).cuda()
166
+
167
+ def num_params(self) :
168
+ parameters = filter(lambda p: p.requires_grad, self.parameters())
169
+ parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000
170
+ print('Trainable Parameters: %.3f million' % parameters)
TTS/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)