Eempostor commited on
Commit
48cbbeb
1 Parent(s): 5c41718

Upload 5 files

Browse files
lib/infer_libs/infer_pack/attentions.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from lib.infer.infer_libs.infer_pack import commons
7
+ from lib.infer.infer_libs.infer_pack.modules import LayerNorm
8
+
9
+
10
+ class Encoder(nn.Module):
11
+ def __init__(
12
+ self,
13
+ hidden_channels,
14
+ filter_channels,
15
+ n_heads,
16
+ n_layers,
17
+ kernel_size=1,
18
+ p_dropout=0.0,
19
+ window_size=10,
20
+ **kwargs
21
+ ):
22
+ super().__init__()
23
+ self.hidden_channels = hidden_channels
24
+ self.filter_channels = filter_channels
25
+ self.n_heads = n_heads
26
+ self.n_layers = n_layers
27
+ self.kernel_size = kernel_size
28
+ self.p_dropout = p_dropout
29
+ self.window_size = window_size
30
+
31
+ self.drop = nn.Dropout(p_dropout)
32
+ self.attn_layers = nn.ModuleList()
33
+ self.norm_layers_1 = nn.ModuleList()
34
+ self.ffn_layers = nn.ModuleList()
35
+ self.norm_layers_2 = nn.ModuleList()
36
+ for i in range(self.n_layers):
37
+ self.attn_layers.append(
38
+ MultiHeadAttention(
39
+ hidden_channels,
40
+ hidden_channels,
41
+ n_heads,
42
+ p_dropout=p_dropout,
43
+ window_size=window_size,
44
+ )
45
+ )
46
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
47
+ self.ffn_layers.append(
48
+ FFN(
49
+ hidden_channels,
50
+ hidden_channels,
51
+ filter_channels,
52
+ kernel_size,
53
+ p_dropout=p_dropout,
54
+ )
55
+ )
56
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
57
+
58
+ def forward(self, x, x_mask):
59
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
60
+ x = x * x_mask
61
+ for i in range(self.n_layers):
62
+ y = self.attn_layers[i](x, x, attn_mask)
63
+ y = self.drop(y)
64
+ x = self.norm_layers_1[i](x + y)
65
+
66
+ y = self.ffn_layers[i](x, x_mask)
67
+ y = self.drop(y)
68
+ x = self.norm_layers_2[i](x + y)
69
+ x = x * x_mask
70
+ return x
71
+
72
+
73
+ class Decoder(nn.Module):
74
+ def __init__(
75
+ self,
76
+ hidden_channels,
77
+ filter_channels,
78
+ n_heads,
79
+ n_layers,
80
+ kernel_size=1,
81
+ p_dropout=0.0,
82
+ proximal_bias=False,
83
+ proximal_init=True,
84
+ **kwargs
85
+ ):
86
+ super().__init__()
87
+ self.hidden_channels = hidden_channels
88
+ self.filter_channels = filter_channels
89
+ self.n_heads = n_heads
90
+ self.n_layers = n_layers
91
+ self.kernel_size = kernel_size
92
+ self.p_dropout = p_dropout
93
+ self.proximal_bias = proximal_bias
94
+ self.proximal_init = proximal_init
95
+
96
+ self.drop = nn.Dropout(p_dropout)
97
+ self.self_attn_layers = nn.ModuleList()
98
+ self.norm_layers_0 = nn.ModuleList()
99
+ self.encdec_attn_layers = nn.ModuleList()
100
+ self.norm_layers_1 = nn.ModuleList()
101
+ self.ffn_layers = nn.ModuleList()
102
+ self.norm_layers_2 = nn.ModuleList()
103
+ for i in range(self.n_layers):
104
+ self.self_attn_layers.append(
105
+ MultiHeadAttention(
106
+ hidden_channels,
107
+ hidden_channels,
108
+ n_heads,
109
+ p_dropout=p_dropout,
110
+ proximal_bias=proximal_bias,
111
+ proximal_init=proximal_init,
112
+ )
113
+ )
114
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
115
+ self.encdec_attn_layers.append(
116
+ MultiHeadAttention(
117
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
118
+ )
119
+ )
120
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
121
+ self.ffn_layers.append(
122
+ FFN(
123
+ hidden_channels,
124
+ hidden_channels,
125
+ filter_channels,
126
+ kernel_size,
127
+ p_dropout=p_dropout,
128
+ causal=True,
129
+ )
130
+ )
131
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
132
+
133
+ def forward(self, x, x_mask, h, h_mask):
134
+ """
135
+ x: decoder input
136
+ h: encoder output
137
+ """
138
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
139
+ device=x.device, dtype=x.dtype
140
+ )
141
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
142
+ x = x * x_mask
143
+ for i in range(self.n_layers):
144
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
145
+ y = self.drop(y)
146
+ x = self.norm_layers_0[i](x + y)
147
+
148
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
149
+ y = self.drop(y)
150
+ x = self.norm_layers_1[i](x + y)
151
+
152
+ y = self.ffn_layers[i](x, x_mask)
153
+ y = self.drop(y)
154
+ x = self.norm_layers_2[i](x + y)
155
+ x = x * x_mask
156
+ return x
157
+
158
+
159
+ class MultiHeadAttention(nn.Module):
160
+ def __init__(
161
+ self,
162
+ channels,
163
+ out_channels,
164
+ n_heads,
165
+ p_dropout=0.0,
166
+ window_size=None,
167
+ heads_share=True,
168
+ block_length=None,
169
+ proximal_bias=False,
170
+ proximal_init=False,
171
+ ):
172
+ super().__init__()
173
+ assert channels % n_heads == 0
174
+
175
+ self.channels = channels
176
+ self.out_channels = out_channels
177
+ self.n_heads = n_heads
178
+ self.p_dropout = p_dropout
179
+ self.window_size = window_size
180
+ self.heads_share = heads_share
181
+ self.block_length = block_length
182
+ self.proximal_bias = proximal_bias
183
+ self.proximal_init = proximal_init
184
+ self.attn = None
185
+
186
+ self.k_channels = channels // n_heads
187
+ self.conv_q = nn.Conv1d(channels, channels, 1)
188
+ self.conv_k = nn.Conv1d(channels, channels, 1)
189
+ self.conv_v = nn.Conv1d(channels, channels, 1)
190
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
191
+ self.drop = nn.Dropout(p_dropout)
192
+
193
+ if window_size is not None:
194
+ n_heads_rel = 1 if heads_share else n_heads
195
+ rel_stddev = self.k_channels**-0.5
196
+ self.emb_rel_k = nn.Parameter(
197
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
198
+ * rel_stddev
199
+ )
200
+ self.emb_rel_v = nn.Parameter(
201
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
202
+ * rel_stddev
203
+ )
204
+
205
+ nn.init.xavier_uniform_(self.conv_q.weight)
206
+ nn.init.xavier_uniform_(self.conv_k.weight)
207
+ nn.init.xavier_uniform_(self.conv_v.weight)
208
+ if proximal_init:
209
+ with torch.no_grad():
210
+ self.conv_k.weight.copy_(self.conv_q.weight)
211
+ self.conv_k.bias.copy_(self.conv_q.bias)
212
+
213
+ def forward(self, x, c, attn_mask=None):
214
+ q = self.conv_q(x)
215
+ k = self.conv_k(c)
216
+ v = self.conv_v(c)
217
+
218
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
219
+
220
+ x = self.conv_o(x)
221
+ return x
222
+
223
+ def attention(self, query, key, value, mask=None):
224
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
225
+ b, d, t_s, t_t = (*key.size(), query.size(2))
226
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
227
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
228
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
229
+
230
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
231
+ if self.window_size is not None:
232
+ assert (
233
+ t_s == t_t
234
+ ), "Relative attention is only available for self-attention."
235
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
236
+ rel_logits = self._matmul_with_relative_keys(
237
+ query / math.sqrt(self.k_channels), key_relative_embeddings
238
+ )
239
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
240
+ scores = scores + scores_local
241
+ if self.proximal_bias:
242
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
243
+ scores = scores + self._attention_bias_proximal(t_s).to(
244
+ device=scores.device, dtype=scores.dtype
245
+ )
246
+ if mask is not None:
247
+ scores = scores.masked_fill(mask == 0, -1e4)
248
+ if self.block_length is not None:
249
+ assert (
250
+ t_s == t_t
251
+ ), "Local attention is only available for self-attention."
252
+ block_mask = (
253
+ torch.ones_like(scores)
254
+ .triu(-self.block_length)
255
+ .tril(self.block_length)
256
+ )
257
+ scores = scores.masked_fill(block_mask == 0, -1e4)
258
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
259
+ p_attn = self.drop(p_attn)
260
+ output = torch.matmul(p_attn, value)
261
+ if self.window_size is not None:
262
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
263
+ value_relative_embeddings = self._get_relative_embeddings(
264
+ self.emb_rel_v, t_s
265
+ )
266
+ output = output + self._matmul_with_relative_values(
267
+ relative_weights, value_relative_embeddings
268
+ )
269
+ output = (
270
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
271
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
272
+ return output, p_attn
273
+
274
+ def _matmul_with_relative_values(self, x, y):
275
+ """
276
+ x: [b, h, l, m]
277
+ y: [h or 1, m, d]
278
+ ret: [b, h, l, d]
279
+ """
280
+ ret = torch.matmul(x, y.unsqueeze(0))
281
+ return ret
282
+
283
+ def _matmul_with_relative_keys(self, x, y):
284
+ """
285
+ x: [b, h, l, d]
286
+ y: [h or 1, m, d]
287
+ ret: [b, h, l, m]
288
+ """
289
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
290
+ return ret
291
+
292
+ def _get_relative_embeddings(self, relative_embeddings, length):
293
+ max_relative_position = 2 * self.window_size + 1
294
+ # Pad first before slice to avoid using cond ops.
295
+ pad_length = max(length - (self.window_size + 1), 0)
296
+ slice_start_position = max((self.window_size + 1) - length, 0)
297
+ slice_end_position = slice_start_position + 2 * length - 1
298
+ if pad_length > 0:
299
+ padded_relative_embeddings = F.pad(
300
+ relative_embeddings,
301
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
302
+ )
303
+ else:
304
+ padded_relative_embeddings = relative_embeddings
305
+ used_relative_embeddings = padded_relative_embeddings[
306
+ :, slice_start_position:slice_end_position
307
+ ]
308
+ return used_relative_embeddings
309
+
310
+ def _relative_position_to_absolute_position(self, x):
311
+ """
312
+ x: [b, h, l, 2*l-1]
313
+ ret: [b, h, l, l]
314
+ """
315
+ batch, heads, length, _ = x.size()
316
+ # Concat columns of pad to shift from relative to absolute indexing.
317
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
318
+
319
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
320
+ x_flat = x.view([batch, heads, length * 2 * length])
321
+ x_flat = F.pad(
322
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
323
+ )
324
+
325
+ # Reshape and slice out the padded elements.
326
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
327
+ :, :, :length, length - 1 :
328
+ ]
329
+ return x_final
330
+
331
+ def _absolute_position_to_relative_position(self, x):
332
+ """
333
+ x: [b, h, l, l]
334
+ ret: [b, h, l, 2*l-1]
335
+ """
336
+ batch, heads, length, _ = x.size()
337
+ # padd along column
338
+ x = F.pad(
339
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
340
+ )
341
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
342
+ # add 0's in the beginning that will skew the elements after reshape
343
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
344
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
345
+ return x_final
346
+
347
+ def _attention_bias_proximal(self, length):
348
+ """Bias for self-attention to encourage attention to close positions.
349
+ Args:
350
+ length: an integer scalar.
351
+ Returns:
352
+ a Tensor with shape [1, 1, length, length]
353
+ """
354
+ r = torch.arange(length, dtype=torch.float32)
355
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
356
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
357
+
358
+
359
+ class FFN(nn.Module):
360
+ def __init__(
361
+ self,
362
+ in_channels,
363
+ out_channels,
364
+ filter_channels,
365
+ kernel_size,
366
+ p_dropout=0.0,
367
+ activation=None,
368
+ causal=False,
369
+ ):
370
+ super().__init__()
371
+ self.in_channels = in_channels
372
+ self.out_channels = out_channels
373
+ self.filter_channels = filter_channels
374
+ self.kernel_size = kernel_size
375
+ self.p_dropout = p_dropout
376
+ self.activation = activation
377
+ self.causal = causal
378
+
379
+ if causal:
380
+ self.padding = self._causal_padding
381
+ else:
382
+ self.padding = self._same_padding
383
+
384
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
385
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
386
+ self.drop = nn.Dropout(p_dropout)
387
+
388
+ def forward(self, x, x_mask):
389
+ x = self.conv_1(self.padding(x * x_mask))
390
+ if self.activation == "gelu":
391
+ x = x * torch.sigmoid(1.702 * x)
392
+ else:
393
+ x = torch.relu(x)
394
+ x = self.drop(x)
395
+ x = self.conv_2(self.padding(x * x_mask))
396
+ return x * x_mask
397
+
398
+ def _causal_padding(self, x):
399
+ if self.kernel_size == 1:
400
+ return x
401
+ pad_l = self.kernel_size - 1
402
+ pad_r = 0
403
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
404
+ x = F.pad(x, commons.convert_pad_shape(padding))
405
+ return x
406
+
407
+ def _same_padding(self, x):
408
+ if self.kernel_size == 1:
409
+ return x
410
+ pad_l = (self.kernel_size - 1) // 2
411
+ pad_r = self.kernel_size // 2
412
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
413
+ x = F.pad(x, commons.convert_pad_shape(padding))
414
+ return x
lib/infer_libs/infer_pack/commons.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+
6
+ def init_weights(m, mean=0.0, std=0.01):
7
+ classname = m.__class__.__name__
8
+ if classname.find("Conv") != -1:
9
+ m.weight.data.normal_(mean, std)
10
+
11
+
12
+ def get_padding(kernel_size, dilation=1):
13
+ return int((kernel_size * dilation - dilation) / 2)
14
+
15
+
16
+ def convert_pad_shape(pad_shape):
17
+ l = pad_shape[::-1]
18
+ pad_shape = [item for sublist in l for item in sublist]
19
+ return pad_shape
20
+
21
+
22
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
23
+ """KL(P||Q)"""
24
+ kl = (logs_q - logs_p) - 0.5
25
+ kl += (
26
+ 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
27
+ )
28
+ return kl
29
+
30
+
31
+ def rand_gumbel(shape):
32
+ """Sample from the Gumbel distribution, protect from overflows."""
33
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
34
+ return -torch.log(-torch.log(uniform_samples))
35
+
36
+
37
+ def rand_gumbel_like(x):
38
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
39
+ return g
40
+
41
+
42
+ def slice_segments(x, ids_str, segment_size=4):
43
+ ret = torch.zeros_like(x[:, :, :segment_size])
44
+ for i in range(x.size(0)):
45
+ idx_str = ids_str[i]
46
+ idx_end = idx_str + segment_size
47
+ ret[i] = x[i, :, idx_str:idx_end]
48
+ return ret
49
+
50
+
51
+ def slice_segments2(x, ids_str, segment_size=4):
52
+ ret = torch.zeros_like(x[:, :segment_size])
53
+ for i in range(x.size(0)):
54
+ idx_str = ids_str[i]
55
+ idx_end = idx_str + segment_size
56
+ ret[i] = x[i, idx_str:idx_end]
57
+ return ret
58
+
59
+
60
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
61
+ b, d, t = x.size()
62
+ if x_lengths is None:
63
+ x_lengths = t
64
+ ids_str_max = x_lengths - segment_size + 1
65
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
66
+ ret = slice_segments(x, ids_str, segment_size)
67
+ return ret, ids_str
68
+
69
+
70
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
71
+ position = torch.arange(length, dtype=torch.float)
72
+ num_timescales = channels // 2
73
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
74
+ num_timescales - 1
75
+ )
76
+ inv_timescales = min_timescale * torch.exp(
77
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
78
+ )
79
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
80
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
81
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
82
+ signal = signal.view(1, channels, length)
83
+ return signal
84
+
85
+
86
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
87
+ b, channels, length = x.size()
88
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
89
+ return x + signal.to(dtype=x.dtype, device=x.device)
90
+
91
+
92
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
93
+ b, channels, length = x.size()
94
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
95
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
96
+
97
+
98
+ def subsequent_mask(length):
99
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
100
+ return mask
101
+
102
+
103
+ @torch.jit.script
104
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
105
+ n_channels_int = n_channels[0]
106
+ in_act = input_a + input_b
107
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
108
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
109
+ acts = t_act * s_act
110
+ return acts
111
+
112
+
113
+ def convert_pad_shape(pad_shape):
114
+ l = pad_shape[::-1]
115
+ pad_shape = [item for sublist in l for item in sublist]
116
+ return pad_shape
117
+
118
+
119
+ def shift_1d(x):
120
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
121
+ return x
122
+
123
+
124
+ def sequence_mask(length, max_length=None):
125
+ if max_length is None:
126
+ max_length = length.max()
127
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
128
+ return x.unsqueeze(0) < length.unsqueeze(1)
129
+
130
+
131
+ def generate_path(duration, mask):
132
+ """
133
+ duration: [b, 1, t_x]
134
+ mask: [b, 1, t_y, t_x]
135
+ """
136
+ device = duration.device
137
+
138
+ b, _, t_y, t_x = mask.shape
139
+ cum_duration = torch.cumsum(duration, -1)
140
+
141
+ cum_duration_flat = cum_duration.view(b * t_x)
142
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
143
+ path = path.view(b, t_x, t_y)
144
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
145
+ path = path.unsqueeze(1).transpose(2, 3) * mask
146
+ return path
147
+
148
+
149
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
150
+ if isinstance(parameters, torch.Tensor):
151
+ parameters = [parameters]
152
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
153
+ norm_type = float(norm_type)
154
+ if clip_value is not None:
155
+ clip_value = float(clip_value)
156
+
157
+ total_norm = 0
158
+ for p in parameters:
159
+ param_norm = p.grad.data.norm(norm_type)
160
+ total_norm += param_norm.item() ** norm_type
161
+ if clip_value is not None:
162
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
163
+ total_norm = total_norm ** (1.0 / norm_type)
164
+ return total_norm
lib/infer_libs/infer_pack/models.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import logging
3
+
4
+ logger = logging.getLogger(__name__)
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import Conv1d, Conv2d, ConvTranspose1d
10
+ from torch.nn import functional as F
11
+ from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
12
+
13
+ from lib.infer.infer_libs.infer_pack import attentions, commons, modules
14
+ from lib.infer.infer_libs.infer_pack.commons import get_padding, init_weights
15
+ has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
16
+
17
+ class TextEncoder256(nn.Module):
18
+ def __init__(
19
+ self,
20
+ out_channels,
21
+ hidden_channels,
22
+ filter_channels,
23
+ n_heads,
24
+ n_layers,
25
+ kernel_size,
26
+ p_dropout,
27
+ f0=True,
28
+ ):
29
+ super().__init__()
30
+ self.out_channels = out_channels
31
+ self.hidden_channels = hidden_channels
32
+ self.filter_channels = filter_channels
33
+ self.n_heads = n_heads
34
+ self.n_layers = n_layers
35
+ self.kernel_size = kernel_size
36
+ self.p_dropout = p_dropout
37
+ self.emb_phone = nn.Linear(256, hidden_channels)
38
+ self.lrelu = nn.LeakyReLU(0.1, inplace=True)
39
+ if f0 == True:
40
+ self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
41
+ self.encoder = attentions.Encoder(
42
+ hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
43
+ )
44
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
45
+
46
+ def forward(self, phone, pitch, lengths):
47
+ if pitch == None:
48
+ x = self.emb_phone(phone)
49
+ else:
50
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
51
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
52
+ x = self.lrelu(x)
53
+ x = torch.transpose(x, 1, -1) # [b, h, t]
54
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
55
+ x.dtype
56
+ )
57
+ x = self.encoder(x * x_mask, x_mask)
58
+ stats = self.proj(x) * x_mask
59
+
60
+ m, logs = torch.split(stats, self.out_channels, dim=1)
61
+ return m, logs, x_mask
62
+
63
+
64
+ class TextEncoder768(nn.Module):
65
+ def __init__(
66
+ self,
67
+ out_channels,
68
+ hidden_channels,
69
+ filter_channels,
70
+ n_heads,
71
+ n_layers,
72
+ kernel_size,
73
+ p_dropout,
74
+ f0=True,
75
+ ):
76
+ super().__init__()
77
+ self.out_channels = out_channels
78
+ self.hidden_channels = hidden_channels
79
+ self.filter_channels = filter_channels
80
+ self.n_heads = n_heads
81
+ self.n_layers = n_layers
82
+ self.kernel_size = kernel_size
83
+ self.p_dropout = p_dropout
84
+ self.emb_phone = nn.Linear(768, hidden_channels)
85
+ self.lrelu = nn.LeakyReLU(0.1, inplace=True)
86
+ if f0 == True:
87
+ self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
88
+ self.encoder = attentions.Encoder(
89
+ hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
90
+ )
91
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
92
+
93
+ def forward(self, phone, pitch, lengths):
94
+ if pitch == None:
95
+ x = self.emb_phone(phone)
96
+ else:
97
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
98
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
99
+ x = self.lrelu(x)
100
+ x = torch.transpose(x, 1, -1) # [b, h, t]
101
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
102
+ x.dtype
103
+ )
104
+ x = self.encoder(x * x_mask, x_mask)
105
+ stats = self.proj(x) * x_mask
106
+
107
+ m, logs = torch.split(stats, self.out_channels, dim=1)
108
+ return m, logs, x_mask
109
+
110
+
111
+ class ResidualCouplingBlock(nn.Module):
112
+ def __init__(
113
+ self,
114
+ channels,
115
+ hidden_channels,
116
+ kernel_size,
117
+ dilation_rate,
118
+ n_layers,
119
+ n_flows=4,
120
+ gin_channels=0,
121
+ ):
122
+ super().__init__()
123
+ self.channels = channels
124
+ self.hidden_channels = hidden_channels
125
+ self.kernel_size = kernel_size
126
+ self.dilation_rate = dilation_rate
127
+ self.n_layers = n_layers
128
+ self.n_flows = n_flows
129
+ self.gin_channels = gin_channels
130
+
131
+ self.flows = nn.ModuleList()
132
+ for i in range(n_flows):
133
+ self.flows.append(
134
+ modules.ResidualCouplingLayer(
135
+ channels,
136
+ hidden_channels,
137
+ kernel_size,
138
+ dilation_rate,
139
+ n_layers,
140
+ gin_channels=gin_channels,
141
+ mean_only=True,
142
+ )
143
+ )
144
+ self.flows.append(modules.Flip())
145
+
146
+ def forward(self, x, x_mask, g=None, reverse=False):
147
+ if not reverse:
148
+ for flow in self.flows:
149
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
150
+ else:
151
+ for flow in reversed(self.flows):
152
+ x = flow(x, x_mask, g=g, reverse=reverse)
153
+ return x
154
+
155
+ def remove_weight_norm(self):
156
+ for i in range(self.n_flows):
157
+ self.flows[i * 2].remove_weight_norm()
158
+
159
+
160
+ class PosteriorEncoder(nn.Module):
161
+ def __init__(
162
+ self,
163
+ in_channels,
164
+ out_channels,
165
+ hidden_channels,
166
+ kernel_size,
167
+ dilation_rate,
168
+ n_layers,
169
+ gin_channels=0,
170
+ ):
171
+ super().__init__()
172
+ self.in_channels = in_channels
173
+ self.out_channels = out_channels
174
+ self.hidden_channels = hidden_channels
175
+ self.kernel_size = kernel_size
176
+ self.dilation_rate = dilation_rate
177
+ self.n_layers = n_layers
178
+ self.gin_channels = gin_channels
179
+
180
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
181
+ self.enc = modules.WN(
182
+ hidden_channels,
183
+ kernel_size,
184
+ dilation_rate,
185
+ n_layers,
186
+ gin_channels=gin_channels,
187
+ )
188
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
189
+
190
+ def forward(self, x, x_lengths, g=None):
191
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
192
+ x.dtype
193
+ )
194
+ x = self.pre(x) * x_mask
195
+ x = self.enc(x, x_mask, g=g)
196
+ stats = self.proj(x) * x_mask
197
+ m, logs = torch.split(stats, self.out_channels, dim=1)
198
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
199
+ return z, m, logs, x_mask
200
+
201
+ def remove_weight_norm(self):
202
+ self.enc.remove_weight_norm()
203
+
204
+
205
+ class Generator(torch.nn.Module):
206
+ def __init__(
207
+ self,
208
+ initial_channel,
209
+ resblock,
210
+ resblock_kernel_sizes,
211
+ resblock_dilation_sizes,
212
+ upsample_rates,
213
+ upsample_initial_channel,
214
+ upsample_kernel_sizes,
215
+ gin_channels=0,
216
+ ):
217
+ super(Generator, self).__init__()
218
+ self.num_kernels = len(resblock_kernel_sizes)
219
+ self.num_upsamples = len(upsample_rates)
220
+ self.conv_pre = Conv1d(
221
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
222
+ )
223
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
224
+
225
+ self.ups = nn.ModuleList()
226
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
227
+ self.ups.append(
228
+ weight_norm(
229
+ ConvTranspose1d(
230
+ upsample_initial_channel // (2**i),
231
+ upsample_initial_channel // (2 ** (i + 1)),
232
+ k,
233
+ u,
234
+ padding=(k - u) // 2,
235
+ )
236
+ )
237
+ )
238
+
239
+ self.resblocks = nn.ModuleList()
240
+ for i in range(len(self.ups)):
241
+ ch = upsample_initial_channel // (2 ** (i + 1))
242
+ for j, (k, d) in enumerate(
243
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
244
+ ):
245
+ self.resblocks.append(resblock(ch, k, d))
246
+
247
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
248
+ self.ups.apply(init_weights)
249
+
250
+ if gin_channels != 0:
251
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
252
+
253
+ def forward(self, x, g=None):
254
+ x = self.conv_pre(x)
255
+ if g is not None:
256
+ x = x + self.cond(g)
257
+
258
+ for i in range(self.num_upsamples):
259
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
260
+ x = self.ups[i](x)
261
+ xs = None
262
+ for j in range(self.num_kernels):
263
+ if xs is None:
264
+ xs = self.resblocks[i * self.num_kernels + j](x)
265
+ else:
266
+ xs += self.resblocks[i * self.num_kernels + j](x)
267
+ x = xs / self.num_kernels
268
+ x = F.leaky_relu(x)
269
+ x = self.conv_post(x)
270
+ x = torch.tanh(x)
271
+
272
+ return x
273
+
274
+ def remove_weight_norm(self):
275
+ for l in self.ups:
276
+ remove_weight_norm(l)
277
+ for l in self.resblocks:
278
+ l.remove_weight_norm()
279
+
280
+
281
+ class SineGen(torch.nn.Module):
282
+ """Definition of sine generator
283
+ SineGen(samp_rate, harmonic_num = 0,
284
+ sine_amp = 0.1, noise_std = 0.003,
285
+ voiced_threshold = 0,
286
+ flag_for_pulse=False)
287
+ samp_rate: sampling rate in Hz
288
+ harmonic_num: number of harmonic overtones (default 0)
289
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
290
+ noise_std: std of Gaussian noise (default 0.003)
291
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
292
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
293
+ Note: when flag_for_pulse is True, the first time step of a voiced
294
+ segment is always sin(np.pi) or cos(0)
295
+ """
296
+
297
+ def __init__(
298
+ self,
299
+ samp_rate,
300
+ harmonic_num=0,
301
+ sine_amp=0.1,
302
+ noise_std=0.003,
303
+ voiced_threshold=0,
304
+ flag_for_pulse=False,
305
+ ):
306
+ super(SineGen, self).__init__()
307
+ self.sine_amp = sine_amp
308
+ self.noise_std = noise_std
309
+ self.harmonic_num = harmonic_num
310
+ self.dim = self.harmonic_num + 1
311
+ self.sampling_rate = samp_rate
312
+ self.voiced_threshold = voiced_threshold
313
+
314
+ def _f02uv(self, f0):
315
+ # generate uv signal
316
+ uv = torch.ones_like(f0)
317
+ uv = uv * (f0 > self.voiced_threshold)
318
+ if uv.device.type == "privateuseone": # for DirectML
319
+ uv = uv.float()
320
+ return uv
321
+
322
+ def forward(self, f0, upp):
323
+ """sine_tensor, uv = forward(f0)
324
+ input F0: tensor(batchsize=1, length, dim=1)
325
+ f0 for unvoiced steps should be 0
326
+ output sine_tensor: tensor(batchsize=1, length, dim)
327
+ output uv: tensor(batchsize=1, length, 1)
328
+ """
329
+ with torch.no_grad():
330
+ f0 = f0[:, None].transpose(1, 2)
331
+ f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
332
+ # fundamental component
333
+ f0_buf[:, :, 0] = f0[:, :, 0]
334
+ for idx in np.arange(self.harmonic_num):
335
+ f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
336
+ idx + 2
337
+ ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
338
+ rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
339
+ rand_ini = torch.rand(
340
+ f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
341
+ )
342
+ rand_ini[:, 0] = 0
343
+ rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
344
+ tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
345
+ tmp_over_one *= upp
346
+ tmp_over_one = F.interpolate(
347
+ tmp_over_one.transpose(2, 1),
348
+ scale_factor=upp,
349
+ mode="linear",
350
+ align_corners=True,
351
+ ).transpose(2, 1)
352
+ rad_values = F.interpolate(
353
+ rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
354
+ ).transpose(
355
+ 2, 1
356
+ ) #######
357
+ tmp_over_one %= 1
358
+ tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
359
+ cumsum_shift = torch.zeros_like(rad_values)
360
+ cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
361
+ sine_waves = torch.sin(
362
+ torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
363
+ )
364
+ sine_waves = sine_waves * self.sine_amp
365
+ uv = self._f02uv(f0)
366
+ uv = F.interpolate(
367
+ uv.transpose(2, 1), scale_factor=upp, mode="nearest"
368
+ ).transpose(2, 1)
369
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
370
+ noise = noise_amp * torch.randn_like(sine_waves)
371
+ sine_waves = sine_waves * uv + noise
372
+ return sine_waves, uv, noise
373
+
374
+
375
+ class SourceModuleHnNSF(torch.nn.Module):
376
+ """SourceModule for hn-nsf
377
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
378
+ add_noise_std=0.003, voiced_threshod=0)
379
+ sampling_rate: sampling_rate in Hz
380
+ harmonic_num: number of harmonic above F0 (default: 0)
381
+ sine_amp: amplitude of sine source signal (default: 0.1)
382
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
383
+ note that amplitude of noise in unvoiced is decided
384
+ by sine_amp
385
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
386
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
387
+ F0_sampled (batchsize, length, 1)
388
+ Sine_source (batchsize, length, 1)
389
+ noise_source (batchsize, length 1)
390
+ uv (batchsize, length, 1)
391
+ """
392
+
393
+ def __init__(
394
+ self,
395
+ sampling_rate,
396
+ harmonic_num=0,
397
+ sine_amp=0.1,
398
+ add_noise_std=0.003,
399
+ voiced_threshod=0,
400
+ is_half=True,
401
+ ):
402
+ super(SourceModuleHnNSF, self).__init__()
403
+
404
+ self.sine_amp = sine_amp
405
+ self.noise_std = add_noise_std
406
+ self.is_half = is_half
407
+ # to produce sine waveforms
408
+ self.l_sin_gen = SineGen(
409
+ sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
410
+ )
411
+
412
+ # to merge source harmonics into a single excitation
413
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
414
+ self.l_tanh = torch.nn.Tanh()
415
+
416
+ def forward(self, x, upp=None):
417
+ if hasattr(self, "ddtype") == False:
418
+ self.ddtype = self.l_linear.weight.dtype
419
+ sine_wavs, uv, _ = self.l_sin_gen(x, upp)
420
+ # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype)
421
+ # if self.is_half:
422
+ # sine_wavs = sine_wavs.half()
423
+ # sine_merge = self.l_tanh(self.l_linear(sine_wavs.to(x)))
424
+ # print(sine_wavs.dtype,self.ddtype)
425
+ if sine_wavs.dtype != self.ddtype:
426
+ sine_wavs = sine_wavs.to(self.ddtype)
427
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
428
+ return sine_merge, None, None # noise, uv
429
+
430
+
431
+ class GeneratorNSF(torch.nn.Module):
432
+ def __init__(
433
+ self,
434
+ initial_channel,
435
+ resblock,
436
+ resblock_kernel_sizes,
437
+ resblock_dilation_sizes,
438
+ upsample_rates,
439
+ upsample_initial_channel,
440
+ upsample_kernel_sizes,
441
+ gin_channels,
442
+ sr,
443
+ is_half=False,
444
+ ):
445
+ super(GeneratorNSF, self).__init__()
446
+ self.num_kernels = len(resblock_kernel_sizes)
447
+ self.num_upsamples = len(upsample_rates)
448
+
449
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
450
+ self.m_source = SourceModuleHnNSF(
451
+ sampling_rate=sr, harmonic_num=0, is_half=is_half
452
+ )
453
+ self.noise_convs = nn.ModuleList()
454
+ self.conv_pre = Conv1d(
455
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
456
+ )
457
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
458
+
459
+ self.ups = nn.ModuleList()
460
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
461
+ c_cur = upsample_initial_channel // (2 ** (i + 1))
462
+ self.ups.append(
463
+ weight_norm(
464
+ ConvTranspose1d(
465
+ upsample_initial_channel // (2**i),
466
+ upsample_initial_channel // (2 ** (i + 1)),
467
+ k,
468
+ u,
469
+ padding=(k - u) // 2,
470
+ )
471
+ )
472
+ )
473
+ if i + 1 < len(upsample_rates):
474
+ stride_f0 = np.prod(upsample_rates[i + 1 :])
475
+ self.noise_convs.append(
476
+ Conv1d(
477
+ 1,
478
+ c_cur,
479
+ kernel_size=stride_f0 * 2,
480
+ stride=stride_f0,
481
+ padding=stride_f0 // 2,
482
+ )
483
+ )
484
+ else:
485
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
486
+
487
+ self.resblocks = nn.ModuleList()
488
+ for i in range(len(self.ups)):
489
+ ch = upsample_initial_channel // (2 ** (i + 1))
490
+ for j, (k, d) in enumerate(
491
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
492
+ ):
493
+ self.resblocks.append(resblock(ch, k, d))
494
+
495
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
496
+ self.ups.apply(init_weights)
497
+
498
+ if gin_channels != 0:
499
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
500
+
501
+ self.upp = np.prod(upsample_rates)
502
+
503
+ def forward(self, x, f0, g=None):
504
+ har_source, noi_source, uv = self.m_source(f0, self.upp)
505
+ har_source = har_source.transpose(1, 2)
506
+ x = self.conv_pre(x)
507
+ if g is not None:
508
+ x = x + self.cond(g)
509
+
510
+ for i in range(self.num_upsamples):
511
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
512
+ x = self.ups[i](x)
513
+ x_source = self.noise_convs[i](har_source)
514
+ x = x + x_source
515
+ xs = None
516
+ for j in range(self.num_kernels):
517
+ if xs is None:
518
+ xs = self.resblocks[i * self.num_kernels + j](x)
519
+ else:
520
+ xs += self.resblocks[i * self.num_kernels + j](x)
521
+ x = xs / self.num_kernels
522
+ x = F.leaky_relu(x)
523
+ x = self.conv_post(x)
524
+ x = torch.tanh(x)
525
+ return x
526
+
527
+ def remove_weight_norm(self):
528
+ for l in self.ups:
529
+ remove_weight_norm(l)
530
+ for l in self.resblocks:
531
+ l.remove_weight_norm()
532
+
533
+
534
+ sr2sr = {
535
+ "32k": 32000,
536
+ "40k": 40000,
537
+ "48k": 48000,
538
+ }
539
+
540
+
541
+ class SynthesizerTrnMs256NSFsid(nn.Module):
542
+ def __init__(
543
+ self,
544
+ spec_channels,
545
+ segment_size,
546
+ inter_channels,
547
+ hidden_channels,
548
+ filter_channels,
549
+ n_heads,
550
+ n_layers,
551
+ kernel_size,
552
+ p_dropout,
553
+ resblock,
554
+ resblock_kernel_sizes,
555
+ resblock_dilation_sizes,
556
+ upsample_rates,
557
+ upsample_initial_channel,
558
+ upsample_kernel_sizes,
559
+ spk_embed_dim,
560
+ gin_channels,
561
+ sr,
562
+ **kwargs
563
+ ):
564
+ super().__init__()
565
+ if type(sr) == type("strr"):
566
+ sr = sr2sr[sr]
567
+ self.spec_channels = spec_channels
568
+ self.inter_channels = inter_channels
569
+ self.hidden_channels = hidden_channels
570
+ self.filter_channels = filter_channels
571
+ self.n_heads = n_heads
572
+ self.n_layers = n_layers
573
+ self.kernel_size = kernel_size
574
+ self.p_dropout = p_dropout
575
+ self.resblock = resblock
576
+ self.resblock_kernel_sizes = resblock_kernel_sizes
577
+ self.resblock_dilation_sizes = resblock_dilation_sizes
578
+ self.upsample_rates = upsample_rates
579
+ self.upsample_initial_channel = upsample_initial_channel
580
+ self.upsample_kernel_sizes = upsample_kernel_sizes
581
+ self.segment_size = segment_size
582
+ self.gin_channels = gin_channels
583
+ # self.hop_length = hop_length#
584
+ self.spk_embed_dim = spk_embed_dim
585
+ self.enc_p = TextEncoder256(
586
+ inter_channels,
587
+ hidden_channels,
588
+ filter_channels,
589
+ n_heads,
590
+ n_layers,
591
+ kernel_size,
592
+ p_dropout,
593
+ )
594
+ self.dec = GeneratorNSF(
595
+ inter_channels,
596
+ resblock,
597
+ resblock_kernel_sizes,
598
+ resblock_dilation_sizes,
599
+ upsample_rates,
600
+ upsample_initial_channel,
601
+ upsample_kernel_sizes,
602
+ gin_channels=gin_channels,
603
+ sr=sr,
604
+ is_half=kwargs["is_half"],
605
+ )
606
+ self.enc_q = PosteriorEncoder(
607
+ spec_channels,
608
+ inter_channels,
609
+ hidden_channels,
610
+ 5,
611
+ 1,
612
+ 16,
613
+ gin_channels=gin_channels,
614
+ )
615
+ self.flow = ResidualCouplingBlock(
616
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
617
+ )
618
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
619
+ logger.debug(
620
+ "gin_channels: "
621
+ + str(gin_channels)
622
+ + ", self.spk_embed_dim: "
623
+ + str(self.spk_embed_dim)
624
+ )
625
+
626
+ def remove_weight_norm(self):
627
+ self.dec.remove_weight_norm()
628
+ self.flow.remove_weight_norm()
629
+ self.enc_q.remove_weight_norm()
630
+
631
+ def forward(
632
+ self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
633
+ ): # 这里ds是id,[bs,1]
634
+ # print(1,pitch.shape)#[bs,t]
635
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
636
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
637
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
638
+ z_p = self.flow(z, y_mask, g=g)
639
+ z_slice, ids_slice = commons.rand_slice_segments(
640
+ z, y_lengths, self.segment_size
641
+ )
642
+ # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
643
+ pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
644
+ # print(-2,pitchf.shape,z_slice.shape)
645
+ o = self.dec(z_slice, pitchf, g=g)
646
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
647
+
648
+ def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
649
+ g = self.emb_g(sid).unsqueeze(-1)
650
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
651
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
652
+ if rate:
653
+ head = int(z_p.shape[2] * rate)
654
+ z_p = z_p[:, :, -head:]
655
+ x_mask = x_mask[:, :, -head:]
656
+ nsff0 = nsff0[:, -head:]
657
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
658
+ o = self.dec(z * x_mask, nsff0, g=g)
659
+ return o, x_mask, (z, z_p, m_p, logs_p)
660
+
661
+
662
+ class SynthesizerTrnMs768NSFsid(nn.Module):
663
+ def __init__(
664
+ self,
665
+ spec_channels,
666
+ segment_size,
667
+ inter_channels,
668
+ hidden_channels,
669
+ filter_channels,
670
+ n_heads,
671
+ n_layers,
672
+ kernel_size,
673
+ p_dropout,
674
+ resblock,
675
+ resblock_kernel_sizes,
676
+ resblock_dilation_sizes,
677
+ upsample_rates,
678
+ upsample_initial_channel,
679
+ upsample_kernel_sizes,
680
+ spk_embed_dim,
681
+ gin_channels,
682
+ sr,
683
+ **kwargs
684
+ ):
685
+ super().__init__()
686
+ if type(sr) == type("strr"):
687
+ sr = sr2sr[sr]
688
+ self.spec_channels = spec_channels
689
+ self.inter_channels = inter_channels
690
+ self.hidden_channels = hidden_channels
691
+ self.filter_channels = filter_channels
692
+ self.n_heads = n_heads
693
+ self.n_layers = n_layers
694
+ self.kernel_size = kernel_size
695
+ self.p_dropout = p_dropout
696
+ self.resblock = resblock
697
+ self.resblock_kernel_sizes = resblock_kernel_sizes
698
+ self.resblock_dilation_sizes = resblock_dilation_sizes
699
+ self.upsample_rates = upsample_rates
700
+ self.upsample_initial_channel = upsample_initial_channel
701
+ self.upsample_kernel_sizes = upsample_kernel_sizes
702
+ self.segment_size = segment_size
703
+ self.gin_channels = gin_channels
704
+ # self.hop_length = hop_length#
705
+ self.spk_embed_dim = spk_embed_dim
706
+ self.enc_p = TextEncoder768(
707
+ inter_channels,
708
+ hidden_channels,
709
+ filter_channels,
710
+ n_heads,
711
+ n_layers,
712
+ kernel_size,
713
+ p_dropout,
714
+ )
715
+ self.dec = GeneratorNSF(
716
+ inter_channels,
717
+ resblock,
718
+ resblock_kernel_sizes,
719
+ resblock_dilation_sizes,
720
+ upsample_rates,
721
+ upsample_initial_channel,
722
+ upsample_kernel_sizes,
723
+ gin_channels=gin_channels,
724
+ sr=sr,
725
+ is_half=kwargs["is_half"],
726
+ )
727
+ self.enc_q = PosteriorEncoder(
728
+ spec_channels,
729
+ inter_channels,
730
+ hidden_channels,
731
+ 5,
732
+ 1,
733
+ 16,
734
+ gin_channels=gin_channels,
735
+ )
736
+ self.flow = ResidualCouplingBlock(
737
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
738
+ )
739
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
740
+ logger.debug(
741
+ "gin_channels: "
742
+ + str(gin_channels)
743
+ + ", self.spk_embed_dim: "
744
+ + str(self.spk_embed_dim)
745
+ )
746
+
747
+ def remove_weight_norm(self):
748
+ self.dec.remove_weight_norm()
749
+ self.flow.remove_weight_norm()
750
+ self.enc_q.remove_weight_norm()
751
+
752
+ def forward(
753
+ self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
754
+ ): # 这里ds是id,[bs,1]
755
+ # print(1,pitch.shape)#[bs,t]
756
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
757
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
758
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
759
+ z_p = self.flow(z, y_mask, g=g)
760
+ z_slice, ids_slice = commons.rand_slice_segments(
761
+ z, y_lengths, self.segment_size
762
+ )
763
+ # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
764
+ pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
765
+ # print(-2,pitchf.shape,z_slice.shape)
766
+ o = self.dec(z_slice, pitchf, g=g)
767
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
768
+
769
+ def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
770
+ g = self.emb_g(sid).unsqueeze(-1)
771
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
772
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
773
+ if rate:
774
+ head = int(z_p.shape[2] * rate)
775
+ z_p = z_p[:, :, -head:]
776
+ x_mask = x_mask[:, :, -head:]
777
+ nsff0 = nsff0[:, -head:]
778
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
779
+ o = self.dec(z * x_mask, nsff0, g=g)
780
+ return o, x_mask, (z, z_p, m_p, logs_p)
781
+
782
+
783
+ class SynthesizerTrnMs256NSFsid_nono(nn.Module):
784
+ def __init__(
785
+ self,
786
+ spec_channels,
787
+ segment_size,
788
+ inter_channels,
789
+ hidden_channels,
790
+ filter_channels,
791
+ n_heads,
792
+ n_layers,
793
+ kernel_size,
794
+ p_dropout,
795
+ resblock,
796
+ resblock_kernel_sizes,
797
+ resblock_dilation_sizes,
798
+ upsample_rates,
799
+ upsample_initial_channel,
800
+ upsample_kernel_sizes,
801
+ spk_embed_dim,
802
+ gin_channels,
803
+ sr=None,
804
+ **kwargs
805
+ ):
806
+ super().__init__()
807
+ self.spec_channels = spec_channels
808
+ self.inter_channels = inter_channels
809
+ self.hidden_channels = hidden_channels
810
+ self.filter_channels = filter_channels
811
+ self.n_heads = n_heads
812
+ self.n_layers = n_layers
813
+ self.kernel_size = kernel_size
814
+ self.p_dropout = p_dropout
815
+ self.resblock = resblock
816
+ self.resblock_kernel_sizes = resblock_kernel_sizes
817
+ self.resblock_dilation_sizes = resblock_dilation_sizes
818
+ self.upsample_rates = upsample_rates
819
+ self.upsample_initial_channel = upsample_initial_channel
820
+ self.upsample_kernel_sizes = upsample_kernel_sizes
821
+ self.segment_size = segment_size
822
+ self.gin_channels = gin_channels
823
+ # self.hop_length = hop_length#
824
+ self.spk_embed_dim = spk_embed_dim
825
+ self.enc_p = TextEncoder256(
826
+ inter_channels,
827
+ hidden_channels,
828
+ filter_channels,
829
+ n_heads,
830
+ n_layers,
831
+ kernel_size,
832
+ p_dropout,
833
+ f0=False,
834
+ )
835
+ self.dec = Generator(
836
+ inter_channels,
837
+ resblock,
838
+ resblock_kernel_sizes,
839
+ resblock_dilation_sizes,
840
+ upsample_rates,
841
+ upsample_initial_channel,
842
+ upsample_kernel_sizes,
843
+ gin_channels=gin_channels,
844
+ )
845
+ self.enc_q = PosteriorEncoder(
846
+ spec_channels,
847
+ inter_channels,
848
+ hidden_channels,
849
+ 5,
850
+ 1,
851
+ 16,
852
+ gin_channels=gin_channels,
853
+ )
854
+ self.flow = ResidualCouplingBlock(
855
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
856
+ )
857
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
858
+ logger.debug(
859
+ "gin_channels: "
860
+ + str(gin_channels)
861
+ + ", self.spk_embed_dim: "
862
+ + str(self.spk_embed_dim)
863
+ )
864
+
865
+ def remove_weight_norm(self):
866
+ self.dec.remove_weight_norm()
867
+ self.flow.remove_weight_norm()
868
+ self.enc_q.remove_weight_norm()
869
+
870
+ def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
871
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
872
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
873
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
874
+ z_p = self.flow(z, y_mask, g=g)
875
+ z_slice, ids_slice = commons.rand_slice_segments(
876
+ z, y_lengths, self.segment_size
877
+ )
878
+ o = self.dec(z_slice, g=g)
879
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
880
+
881
+ def infer(self, phone, phone_lengths, sid, rate=None):
882
+ g = self.emb_g(sid).unsqueeze(-1)
883
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
884
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
885
+ if rate:
886
+ head = int(z_p.shape[2] * rate)
887
+ z_p = z_p[:, :, -head:]
888
+ x_mask = x_mask[:, :, -head:]
889
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
890
+ o = self.dec(z * x_mask, g=g)
891
+ return o, x_mask, (z, z_p, m_p, logs_p)
892
+
893
+
894
+ class SynthesizerTrnMs768NSFsid_nono(nn.Module):
895
+ def __init__(
896
+ self,
897
+ spec_channels,
898
+ segment_size,
899
+ inter_channels,
900
+ hidden_channels,
901
+ filter_channels,
902
+ n_heads,
903
+ n_layers,
904
+ kernel_size,
905
+ p_dropout,
906
+ resblock,
907
+ resblock_kernel_sizes,
908
+ resblock_dilation_sizes,
909
+ upsample_rates,
910
+ upsample_initial_channel,
911
+ upsample_kernel_sizes,
912
+ spk_embed_dim,
913
+ gin_channels,
914
+ sr=None,
915
+ **kwargs
916
+ ):
917
+ super().__init__()
918
+ self.spec_channels = spec_channels
919
+ self.inter_channels = inter_channels
920
+ self.hidden_channels = hidden_channels
921
+ self.filter_channels = filter_channels
922
+ self.n_heads = n_heads
923
+ self.n_layers = n_layers
924
+ self.kernel_size = kernel_size
925
+ self.p_dropout = p_dropout
926
+ self.resblock = resblock
927
+ self.resblock_kernel_sizes = resblock_kernel_sizes
928
+ self.resblock_dilation_sizes = resblock_dilation_sizes
929
+ self.upsample_rates = upsample_rates
930
+ self.upsample_initial_channel = upsample_initial_channel
931
+ self.upsample_kernel_sizes = upsample_kernel_sizes
932
+ self.segment_size = segment_size
933
+ self.gin_channels = gin_channels
934
+ # self.hop_length = hop_length#
935
+ self.spk_embed_dim = spk_embed_dim
936
+ self.enc_p = TextEncoder768(
937
+ inter_channels,
938
+ hidden_channels,
939
+ filter_channels,
940
+ n_heads,
941
+ n_layers,
942
+ kernel_size,
943
+ p_dropout,
944
+ f0=False,
945
+ )
946
+ self.dec = Generator(
947
+ inter_channels,
948
+ resblock,
949
+ resblock_kernel_sizes,
950
+ resblock_dilation_sizes,
951
+ upsample_rates,
952
+ upsample_initial_channel,
953
+ upsample_kernel_sizes,
954
+ gin_channels=gin_channels,
955
+ )
956
+ self.enc_q = PosteriorEncoder(
957
+ spec_channels,
958
+ inter_channels,
959
+ hidden_channels,
960
+ 5,
961
+ 1,
962
+ 16,
963
+ gin_channels=gin_channels,
964
+ )
965
+ self.flow = ResidualCouplingBlock(
966
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
967
+ )
968
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
969
+ logger.debug(
970
+ "gin_channels: "
971
+ + str(gin_channels)
972
+ + ", self.spk_embed_dim: "
973
+ + str(self.spk_embed_dim)
974
+ )
975
+
976
+ def remove_weight_norm(self):
977
+ self.dec.remove_weight_norm()
978
+ self.flow.remove_weight_norm()
979
+ self.enc_q.remove_weight_norm()
980
+
981
+ def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
982
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
983
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
984
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
985
+ z_p = self.flow(z, y_mask, g=g)
986
+ z_slice, ids_slice = commons.rand_slice_segments(
987
+ z, y_lengths, self.segment_size
988
+ )
989
+ o = self.dec(z_slice, g=g)
990
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
991
+
992
+ def infer(self, phone, phone_lengths, sid, rate=None):
993
+ g = self.emb_g(sid).unsqueeze(-1)
994
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
995
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
996
+ if rate:
997
+ head = int(z_p.shape[2] * rate)
998
+ z_p = z_p[:, :, -head:]
999
+ x_mask = x_mask[:, :, -head:]
1000
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
1001
+ o = self.dec(z * x_mask, g=g)
1002
+ return o, x_mask, (z, z_p, m_p, logs_p)
1003
+
1004
+
1005
+ class MultiPeriodDiscriminator(torch.nn.Module):
1006
+ def __init__(self, use_spectral_norm=False):
1007
+ super(MultiPeriodDiscriminator, self).__init__()
1008
+ periods = [2, 3, 5, 7, 11, 17]
1009
+ # periods = [3, 5, 7, 11, 17, 23, 37]
1010
+
1011
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1012
+ discs = discs + [
1013
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1014
+ ]
1015
+ self.discriminators = nn.ModuleList(discs)
1016
+
1017
+ def forward(self, y, y_hat):
1018
+ y_d_rs = [] #
1019
+ y_d_gs = []
1020
+ fmap_rs = []
1021
+ fmap_gs = []
1022
+ for i, d in enumerate(self.discriminators):
1023
+ y_d_r, fmap_r = d(y)
1024
+ y_d_g, fmap_g = d(y_hat)
1025
+ # for j in range(len(fmap_r)):
1026
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1027
+ y_d_rs.append(y_d_r)
1028
+ y_d_gs.append(y_d_g)
1029
+ fmap_rs.append(fmap_r)
1030
+ fmap_gs.append(fmap_g)
1031
+
1032
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1033
+
1034
+
1035
+ class MultiPeriodDiscriminatorV2(torch.nn.Module):
1036
+ def __init__(self, use_spectral_norm=False):
1037
+ super(MultiPeriodDiscriminatorV2, self).__init__()
1038
+ # periods = [2, 3, 5, 7, 11, 17]
1039
+ periods = [2, 3, 5, 7, 11, 17, 23, 37]
1040
+
1041
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1042
+ discs = discs + [
1043
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1044
+ ]
1045
+ self.discriminators = nn.ModuleList(discs)
1046
+
1047
+ def forward(self, y, y_hat):
1048
+ y_d_rs = [] #
1049
+ y_d_gs = []
1050
+ fmap_rs = []
1051
+ fmap_gs = []
1052
+ for i, d in enumerate(self.discriminators):
1053
+ y_d_r, fmap_r = d(y)
1054
+ y_d_g, fmap_g = d(y_hat)
1055
+ # for j in range(len(fmap_r)):
1056
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1057
+ y_d_rs.append(y_d_r)
1058
+ y_d_gs.append(y_d_g)
1059
+ fmap_rs.append(fmap_r)
1060
+ fmap_gs.append(fmap_g)
1061
+
1062
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1063
+
1064
+
1065
+ class DiscriminatorS(torch.nn.Module):
1066
+ def __init__(self, use_spectral_norm=False):
1067
+ super(DiscriminatorS, self).__init__()
1068
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1069
+ self.convs = nn.ModuleList(
1070
+ [
1071
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
1072
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
1073
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
1074
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
1075
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
1076
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
1077
+ ]
1078
+ )
1079
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
1080
+
1081
+ def forward(self, x):
1082
+ fmap = []
1083
+
1084
+ for l in self.convs:
1085
+ x = l(x)
1086
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1087
+ fmap.append(x)
1088
+ x = self.conv_post(x)
1089
+ fmap.append(x)
1090
+ x = torch.flatten(x, 1, -1)
1091
+
1092
+ return x, fmap
1093
+
1094
+
1095
+ class DiscriminatorP(torch.nn.Module):
1096
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
1097
+ super(DiscriminatorP, self).__init__()
1098
+ self.period = period
1099
+ self.use_spectral_norm = use_spectral_norm
1100
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1101
+ self.convs = nn.ModuleList(
1102
+ [
1103
+ norm_f(
1104
+ Conv2d(
1105
+ 1,
1106
+ 32,
1107
+ (kernel_size, 1),
1108
+ (stride, 1),
1109
+ padding=(get_padding(kernel_size, 1), 0),
1110
+ )
1111
+ ),
1112
+ norm_f(
1113
+ Conv2d(
1114
+ 32,
1115
+ 128,
1116
+ (kernel_size, 1),
1117
+ (stride, 1),
1118
+ padding=(get_padding(kernel_size, 1), 0),
1119
+ )
1120
+ ),
1121
+ norm_f(
1122
+ Conv2d(
1123
+ 128,
1124
+ 512,
1125
+ (kernel_size, 1),
1126
+ (stride, 1),
1127
+ padding=(get_padding(kernel_size, 1), 0),
1128
+ )
1129
+ ),
1130
+ norm_f(
1131
+ Conv2d(
1132
+ 512,
1133
+ 1024,
1134
+ (kernel_size, 1),
1135
+ (stride, 1),
1136
+ padding=(get_padding(kernel_size, 1), 0),
1137
+ )
1138
+ ),
1139
+ norm_f(
1140
+ Conv2d(
1141
+ 1024,
1142
+ 1024,
1143
+ (kernel_size, 1),
1144
+ 1,
1145
+ padding=(get_padding(kernel_size, 1), 0),
1146
+ )
1147
+ ),
1148
+ ]
1149
+ )
1150
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
1151
+
1152
+ def forward(self, x):
1153
+ fmap = []
1154
+
1155
+ # 1d to 2d
1156
+ b, c, t = x.shape
1157
+ if t % self.period != 0: # pad first
1158
+ n_pad = self.period - (t % self.period)
1159
+ if has_xpu and x.dtype == torch.bfloat16:
1160
+ x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(dtype=torch.bfloat16)
1161
+ else:
1162
+ x = F.pad(x, (0, n_pad), "reflect")
1163
+ t = t + n_pad
1164
+ x = x.view(b, c, t // self.period, self.period)
1165
+
1166
+ for l in self.convs:
1167
+ x = l(x)
1168
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1169
+ fmap.append(x)
1170
+ x = self.conv_post(x)
1171
+ fmap.append(x)
1172
+ x = torch.flatten(x, 1, -1)
1173
+
1174
+ return x, fmap
lib/infer_libs/infer_pack/modules.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import Conv1d
5
+ from torch.nn import functional as F
6
+ from torch.nn.utils import remove_weight_norm, weight_norm
7
+
8
+ from lib.infer.infer_libs.infer_pack import commons
9
+ from lib.infer.infer_libs.infer_pack.commons import get_padding, init_weights
10
+ from lib.infer.infer_libs.infer_pack.transforms import piecewise_rational_quadratic_transform
11
+
12
+ LRELU_SLOPE = 0.1
13
+
14
+
15
+ class LayerNorm(nn.Module):
16
+ def __init__(self, channels, eps=1e-5):
17
+ super().__init__()
18
+ self.channels = channels
19
+ self.eps = eps
20
+
21
+ self.gamma = nn.Parameter(torch.ones(channels))
22
+ self.beta = nn.Parameter(torch.zeros(channels))
23
+
24
+ def forward(self, x):
25
+ x = x.transpose(1, -1)
26
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
27
+ return x.transpose(1, -1)
28
+
29
+
30
+ class ConvReluNorm(nn.Module):
31
+ def __init__(
32
+ self,
33
+ in_channels,
34
+ hidden_channels,
35
+ out_channels,
36
+ kernel_size,
37
+ n_layers,
38
+ p_dropout,
39
+ ):
40
+ super().__init__()
41
+ self.in_channels = in_channels
42
+ self.hidden_channels = hidden_channels
43
+ self.out_channels = out_channels
44
+ self.kernel_size = kernel_size
45
+ self.n_layers = n_layers
46
+ self.p_dropout = p_dropout
47
+ assert n_layers > 1, "Number of layers should be larger than 0."
48
+
49
+ self.conv_layers = nn.ModuleList()
50
+ self.norm_layers = nn.ModuleList()
51
+ self.conv_layers.append(
52
+ nn.Conv1d(
53
+ in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
54
+ )
55
+ )
56
+ self.norm_layers.append(LayerNorm(hidden_channels))
57
+ self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
58
+ for _ in range(n_layers - 1):
59
+ self.conv_layers.append(
60
+ nn.Conv1d(
61
+ hidden_channels,
62
+ hidden_channels,
63
+ kernel_size,
64
+ padding=kernel_size // 2,
65
+ )
66
+ )
67
+ self.norm_layers.append(LayerNorm(hidden_channels))
68
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
69
+ self.proj.weight.data.zero_()
70
+ self.proj.bias.data.zero_()
71
+
72
+ def forward(self, x, x_mask):
73
+ x_org = x
74
+ for i in range(self.n_layers):
75
+ x = self.conv_layers[i](x * x_mask)
76
+ x = self.norm_layers[i](x)
77
+ x = self.relu_drop(x)
78
+ x = x_org + self.proj(x)
79
+ return x * x_mask
80
+
81
+
82
+ class DDSConv(nn.Module):
83
+ """
84
+ Dialted and Depth-Separable Convolution
85
+ """
86
+
87
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
88
+ super().__init__()
89
+ self.channels = channels
90
+ self.kernel_size = kernel_size
91
+ self.n_layers = n_layers
92
+ self.p_dropout = p_dropout
93
+
94
+ self.drop = nn.Dropout(p_dropout)
95
+ self.convs_sep = nn.ModuleList()
96
+ self.convs_1x1 = nn.ModuleList()
97
+ self.norms_1 = nn.ModuleList()
98
+ self.norms_2 = nn.ModuleList()
99
+ for i in range(n_layers):
100
+ dilation = kernel_size**i
101
+ padding = (kernel_size * dilation - dilation) // 2
102
+ self.convs_sep.append(
103
+ nn.Conv1d(
104
+ channels,
105
+ channels,
106
+ kernel_size,
107
+ groups=channels,
108
+ dilation=dilation,
109
+ padding=padding,
110
+ )
111
+ )
112
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
113
+ self.norms_1.append(LayerNorm(channels))
114
+ self.norms_2.append(LayerNorm(channels))
115
+
116
+ def forward(self, x, x_mask, g=None):
117
+ if g is not None:
118
+ x = x + g
119
+ for i in range(self.n_layers):
120
+ y = self.convs_sep[i](x * x_mask)
121
+ y = self.norms_1[i](y)
122
+ y = F.gelu(y)
123
+ y = self.convs_1x1[i](y)
124
+ y = self.norms_2[i](y)
125
+ y = F.gelu(y)
126
+ y = self.drop(y)
127
+ x = x + y
128
+ return x * x_mask
129
+
130
+
131
+ class WN(torch.nn.Module):
132
+ def __init__(
133
+ self,
134
+ hidden_channels,
135
+ kernel_size,
136
+ dilation_rate,
137
+ n_layers,
138
+ gin_channels=0,
139
+ p_dropout=0,
140
+ ):
141
+ super(WN, self).__init__()
142
+ assert kernel_size % 2 == 1
143
+ self.hidden_channels = hidden_channels
144
+ self.kernel_size = (kernel_size,)
145
+ self.dilation_rate = dilation_rate
146
+ self.n_layers = n_layers
147
+ self.gin_channels = gin_channels
148
+ self.p_dropout = p_dropout
149
+
150
+ self.in_layers = torch.nn.ModuleList()
151
+ self.res_skip_layers = torch.nn.ModuleList()
152
+ self.drop = nn.Dropout(p_dropout)
153
+
154
+ if gin_channels != 0:
155
+ cond_layer = torch.nn.Conv1d(
156
+ gin_channels, 2 * hidden_channels * n_layers, 1
157
+ )
158
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
159
+
160
+ for i in range(n_layers):
161
+ dilation = dilation_rate**i
162
+ padding = int((kernel_size * dilation - dilation) / 2)
163
+ in_layer = torch.nn.Conv1d(
164
+ hidden_channels,
165
+ 2 * hidden_channels,
166
+ kernel_size,
167
+ dilation=dilation,
168
+ padding=padding,
169
+ )
170
+ in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
171
+ self.in_layers.append(in_layer)
172
+
173
+ # last one is not necessary
174
+ if i < n_layers - 1:
175
+ res_skip_channels = 2 * hidden_channels
176
+ else:
177
+ res_skip_channels = hidden_channels
178
+
179
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
180
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
181
+ self.res_skip_layers.append(res_skip_layer)
182
+
183
+ def forward(self, x, x_mask, g=None, **kwargs):
184
+ output = torch.zeros_like(x)
185
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
186
+
187
+ if g is not None:
188
+ g = self.cond_layer(g)
189
+
190
+ for i in range(self.n_layers):
191
+ x_in = self.in_layers[i](x)
192
+ if g is not None:
193
+ cond_offset = i * 2 * self.hidden_channels
194
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
195
+ else:
196
+ g_l = torch.zeros_like(x_in)
197
+
198
+ acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
199
+ acts = self.drop(acts)
200
+
201
+ res_skip_acts = self.res_skip_layers[i](acts)
202
+ if i < self.n_layers - 1:
203
+ res_acts = res_skip_acts[:, : self.hidden_channels, :]
204
+ x = (x + res_acts) * x_mask
205
+ output = output + res_skip_acts[:, self.hidden_channels :, :]
206
+ else:
207
+ output = output + res_skip_acts
208
+ return output * x_mask
209
+
210
+ def remove_weight_norm(self):
211
+ if self.gin_channels != 0:
212
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
213
+ for l in self.in_layers:
214
+ torch.nn.utils.remove_weight_norm(l)
215
+ for l in self.res_skip_layers:
216
+ torch.nn.utils.remove_weight_norm(l)
217
+
218
+
219
+ class ResBlock1(torch.nn.Module):
220
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
221
+ super(ResBlock1, self).__init__()
222
+ self.convs1 = nn.ModuleList(
223
+ [
224
+ weight_norm(
225
+ Conv1d(
226
+ channels,
227
+ channels,
228
+ kernel_size,
229
+ 1,
230
+ dilation=dilation[0],
231
+ padding=get_padding(kernel_size, dilation[0]),
232
+ )
233
+ ),
234
+ weight_norm(
235
+ Conv1d(
236
+ channels,
237
+ channels,
238
+ kernel_size,
239
+ 1,
240
+ dilation=dilation[1],
241
+ padding=get_padding(kernel_size, dilation[1]),
242
+ )
243
+ ),
244
+ weight_norm(
245
+ Conv1d(
246
+ channels,
247
+ channels,
248
+ kernel_size,
249
+ 1,
250
+ dilation=dilation[2],
251
+ padding=get_padding(kernel_size, dilation[2]),
252
+ )
253
+ ),
254
+ ]
255
+ )
256
+ self.convs1.apply(init_weights)
257
+
258
+ self.convs2 = nn.ModuleList(
259
+ [
260
+ weight_norm(
261
+ Conv1d(
262
+ channels,
263
+ channels,
264
+ kernel_size,
265
+ 1,
266
+ dilation=1,
267
+ padding=get_padding(kernel_size, 1),
268
+ )
269
+ ),
270
+ weight_norm(
271
+ Conv1d(
272
+ channels,
273
+ channels,
274
+ kernel_size,
275
+ 1,
276
+ dilation=1,
277
+ padding=get_padding(kernel_size, 1),
278
+ )
279
+ ),
280
+ weight_norm(
281
+ Conv1d(
282
+ channels,
283
+ channels,
284
+ kernel_size,
285
+ 1,
286
+ dilation=1,
287
+ padding=get_padding(kernel_size, 1),
288
+ )
289
+ ),
290
+ ]
291
+ )
292
+ self.convs2.apply(init_weights)
293
+
294
+ def forward(self, x, x_mask=None):
295
+ for c1, c2 in zip(self.convs1, self.convs2):
296
+ xt = F.leaky_relu(x, LRELU_SLOPE)
297
+ if x_mask is not None:
298
+ xt = xt * x_mask
299
+ xt = c1(xt)
300
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
301
+ if x_mask is not None:
302
+ xt = xt * x_mask
303
+ xt = c2(xt)
304
+ x = xt + x
305
+ if x_mask is not None:
306
+ x = x * x_mask
307
+ return x
308
+
309
+ def remove_weight_norm(self):
310
+ for l in self.convs1:
311
+ remove_weight_norm(l)
312
+ for l in self.convs2:
313
+ remove_weight_norm(l)
314
+
315
+
316
+ class ResBlock2(torch.nn.Module):
317
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
318
+ super(ResBlock2, self).__init__()
319
+ self.convs = nn.ModuleList(
320
+ [
321
+ weight_norm(
322
+ Conv1d(
323
+ channels,
324
+ channels,
325
+ kernel_size,
326
+ 1,
327
+ dilation=dilation[0],
328
+ padding=get_padding(kernel_size, dilation[0]),
329
+ )
330
+ ),
331
+ weight_norm(
332
+ Conv1d(
333
+ channels,
334
+ channels,
335
+ kernel_size,
336
+ 1,
337
+ dilation=dilation[1],
338
+ padding=get_padding(kernel_size, dilation[1]),
339
+ )
340
+ ),
341
+ ]
342
+ )
343
+ self.convs.apply(init_weights)
344
+
345
+ def forward(self, x, x_mask=None):
346
+ for c in self.convs:
347
+ xt = F.leaky_relu(x, LRELU_SLOPE)
348
+ if x_mask is not None:
349
+ xt = xt * x_mask
350
+ xt = c(xt)
351
+ x = xt + x
352
+ if x_mask is not None:
353
+ x = x * x_mask
354
+ return x
355
+
356
+ def remove_weight_norm(self):
357
+ for l in self.convs:
358
+ remove_weight_norm(l)
359
+
360
+
361
+ class Log(nn.Module):
362
+ def forward(self, x, x_mask, reverse=False, **kwargs):
363
+ if not reverse:
364
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
365
+ logdet = torch.sum(-y, [1, 2])
366
+ return y, logdet
367
+ else:
368
+ x = torch.exp(x) * x_mask
369
+ return x
370
+
371
+
372
+ class Flip(nn.Module):
373
+ def forward(self, x, *args, reverse=False, **kwargs):
374
+ x = torch.flip(x, [1])
375
+ if not reverse:
376
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
377
+ return x, logdet
378
+ else:
379
+ return x
380
+
381
+
382
+ class ElementwiseAffine(nn.Module):
383
+ def __init__(self, channels):
384
+ super().__init__()
385
+ self.channels = channels
386
+ self.m = nn.Parameter(torch.zeros(channels, 1))
387
+ self.logs = nn.Parameter(torch.zeros(channels, 1))
388
+
389
+ def forward(self, x, x_mask, reverse=False, **kwargs):
390
+ if not reverse:
391
+ y = self.m + torch.exp(self.logs) * x
392
+ y = y * x_mask
393
+ logdet = torch.sum(self.logs * x_mask, [1, 2])
394
+ return y, logdet
395
+ else:
396
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
397
+ return x
398
+
399
+
400
+ class ResidualCouplingLayer(nn.Module):
401
+ def __init__(
402
+ self,
403
+ channels,
404
+ hidden_channels,
405
+ kernel_size,
406
+ dilation_rate,
407
+ n_layers,
408
+ p_dropout=0,
409
+ gin_channels=0,
410
+ mean_only=False,
411
+ ):
412
+ assert channels % 2 == 0, "channels should be divisible by 2"
413
+ super().__init__()
414
+ self.channels = channels
415
+ self.hidden_channels = hidden_channels
416
+ self.kernel_size = kernel_size
417
+ self.dilation_rate = dilation_rate
418
+ self.n_layers = n_layers
419
+ self.half_channels = channels // 2
420
+ self.mean_only = mean_only
421
+
422
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
423
+ self.enc = WN(
424
+ hidden_channels,
425
+ kernel_size,
426
+ dilation_rate,
427
+ n_layers,
428
+ p_dropout=p_dropout,
429
+ gin_channels=gin_channels,
430
+ )
431
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
432
+ self.post.weight.data.zero_()
433
+ self.post.bias.data.zero_()
434
+
435
+ def forward(self, x, x_mask, g=None, reverse=False):
436
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
437
+ h = self.pre(x0) * x_mask
438
+ h = self.enc(h, x_mask, g=g)
439
+ stats = self.post(h) * x_mask
440
+ if not self.mean_only:
441
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
442
+ else:
443
+ m = stats
444
+ logs = torch.zeros_like(m)
445
+
446
+ if not reverse:
447
+ x1 = m + x1 * torch.exp(logs) * x_mask
448
+ x = torch.cat([x0, x1], 1)
449
+ logdet = torch.sum(logs, [1, 2])
450
+ return x, logdet
451
+ else:
452
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
453
+ x = torch.cat([x0, x1], 1)
454
+ return x
455
+
456
+ def remove_weight_norm(self):
457
+ self.enc.remove_weight_norm()
458
+
459
+
460
+ class ConvFlow(nn.Module):
461
+ def __init__(
462
+ self,
463
+ in_channels,
464
+ filter_channels,
465
+ kernel_size,
466
+ n_layers,
467
+ num_bins=10,
468
+ tail_bound=5.0,
469
+ ):
470
+ super().__init__()
471
+ self.in_channels = in_channels
472
+ self.filter_channels = filter_channels
473
+ self.kernel_size = kernel_size
474
+ self.n_layers = n_layers
475
+ self.num_bins = num_bins
476
+ self.tail_bound = tail_bound
477
+ self.half_channels = in_channels // 2
478
+
479
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
480
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
481
+ self.proj = nn.Conv1d(
482
+ filter_channels, self.half_channels * (num_bins * 3 - 1), 1
483
+ )
484
+ self.proj.weight.data.zero_()
485
+ self.proj.bias.data.zero_()
486
+
487
+ def forward(self, x, x_mask, g=None, reverse=False):
488
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
489
+ h = self.pre(x0)
490
+ h = self.convs(h, x_mask, g=g)
491
+ h = self.proj(h) * x_mask
492
+
493
+ b, c, t = x0.shape
494
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
495
+
496
+ unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
497
+ unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
498
+ self.filter_channels
499
+ )
500
+ unnormalized_derivatives = h[..., 2 * self.num_bins :]
501
+
502
+ x1, logabsdet = piecewise_rational_quadratic_transform(
503
+ x1,
504
+ unnormalized_widths,
505
+ unnormalized_heights,
506
+ unnormalized_derivatives,
507
+ inverse=reverse,
508
+ tails="linear",
509
+ tail_bound=self.tail_bound,
510
+ )
511
+
512
+ x = torch.cat([x0, x1], 1) * x_mask
513
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
514
+ if not reverse:
515
+ return x, logdet
516
+ else:
517
+ return x
lib/infer_libs/infer_pack/transforms.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+ DEFAULT_MIN_BIN_WIDTH = 1e-3
6
+ DEFAULT_MIN_BIN_HEIGHT = 1e-3
7
+ DEFAULT_MIN_DERIVATIVE = 1e-3
8
+
9
+
10
+ def piecewise_rational_quadratic_transform(
11
+ inputs,
12
+ unnormalized_widths,
13
+ unnormalized_heights,
14
+ unnormalized_derivatives,
15
+ inverse=False,
16
+ tails=None,
17
+ tail_bound=1.0,
18
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
19
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
20
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
21
+ ):
22
+ if tails is None:
23
+ spline_fn = rational_quadratic_spline
24
+ spline_kwargs = {}
25
+ else:
26
+ spline_fn = unconstrained_rational_quadratic_spline
27
+ spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
28
+
29
+ outputs, logabsdet = spline_fn(
30
+ inputs=inputs,
31
+ unnormalized_widths=unnormalized_widths,
32
+ unnormalized_heights=unnormalized_heights,
33
+ unnormalized_derivatives=unnormalized_derivatives,
34
+ inverse=inverse,
35
+ min_bin_width=min_bin_width,
36
+ min_bin_height=min_bin_height,
37
+ min_derivative=min_derivative,
38
+ **spline_kwargs
39
+ )
40
+ return outputs, logabsdet
41
+
42
+
43
+ def searchsorted(bin_locations, inputs, eps=1e-6):
44
+ bin_locations[..., -1] += eps
45
+ return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
46
+
47
+
48
+ def unconstrained_rational_quadratic_spline(
49
+ inputs,
50
+ unnormalized_widths,
51
+ unnormalized_heights,
52
+ unnormalized_derivatives,
53
+ inverse=False,
54
+ tails="linear",
55
+ tail_bound=1.0,
56
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
57
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
58
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
59
+ ):
60
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
61
+ outside_interval_mask = ~inside_interval_mask
62
+
63
+ outputs = torch.zeros_like(inputs)
64
+ logabsdet = torch.zeros_like(inputs)
65
+
66
+ if tails == "linear":
67
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
68
+ constant = np.log(np.exp(1 - min_derivative) - 1)
69
+ unnormalized_derivatives[..., 0] = constant
70
+ unnormalized_derivatives[..., -1] = constant
71
+
72
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
73
+ logabsdet[outside_interval_mask] = 0
74
+ else:
75
+ raise RuntimeError("{} tails are not implemented.".format(tails))
76
+
77
+ (
78
+ outputs[inside_interval_mask],
79
+ logabsdet[inside_interval_mask],
80
+ ) = rational_quadratic_spline(
81
+ inputs=inputs[inside_interval_mask],
82
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
83
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
84
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
85
+ inverse=inverse,
86
+ left=-tail_bound,
87
+ right=tail_bound,
88
+ bottom=-tail_bound,
89
+ top=tail_bound,
90
+ min_bin_width=min_bin_width,
91
+ min_bin_height=min_bin_height,
92
+ min_derivative=min_derivative,
93
+ )
94
+
95
+ return outputs, logabsdet
96
+
97
+
98
+ def rational_quadratic_spline(
99
+ inputs,
100
+ unnormalized_widths,
101
+ unnormalized_heights,
102
+ unnormalized_derivatives,
103
+ inverse=False,
104
+ left=0.0,
105
+ right=1.0,
106
+ bottom=0.0,
107
+ top=1.0,
108
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
109
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
110
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
111
+ ):
112
+ if torch.min(inputs) < left or torch.max(inputs) > right:
113
+ raise ValueError("Input to a transform is not within its domain")
114
+
115
+ num_bins = unnormalized_widths.shape[-1]
116
+
117
+ if min_bin_width * num_bins > 1.0:
118
+ raise ValueError("Minimal bin width too large for the number of bins")
119
+ if min_bin_height * num_bins > 1.0:
120
+ raise ValueError("Minimal bin height too large for the number of bins")
121
+
122
+ widths = F.softmax(unnormalized_widths, dim=-1)
123
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
124
+ cumwidths = torch.cumsum(widths, dim=-1)
125
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
126
+ cumwidths = (right - left) * cumwidths + left
127
+ cumwidths[..., 0] = left
128
+ cumwidths[..., -1] = right
129
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
130
+
131
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
132
+
133
+ heights = F.softmax(unnormalized_heights, dim=-1)
134
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
135
+ cumheights = torch.cumsum(heights, dim=-1)
136
+ cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
137
+ cumheights = (top - bottom) * cumheights + bottom
138
+ cumheights[..., 0] = bottom
139
+ cumheights[..., -1] = top
140
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
141
+
142
+ if inverse:
143
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
144
+ else:
145
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
146
+
147
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
148
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
149
+
150
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
151
+ delta = heights / widths
152
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
153
+
154
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
155
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
156
+
157
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
158
+
159
+ if inverse:
160
+ a = (inputs - input_cumheights) * (
161
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
162
+ ) + input_heights * (input_delta - input_derivatives)
163
+ b = input_heights * input_derivatives - (inputs - input_cumheights) * (
164
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
165
+ )
166
+ c = -input_delta * (inputs - input_cumheights)
167
+
168
+ discriminant = b.pow(2) - 4 * a * c
169
+ assert (discriminant >= 0).all()
170
+
171
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
172
+ outputs = root * input_bin_widths + input_cumwidths
173
+
174
+ theta_one_minus_theta = root * (1 - root)
175
+ denominator = input_delta + (
176
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
177
+ * theta_one_minus_theta
178
+ )
179
+ derivative_numerator = input_delta.pow(2) * (
180
+ input_derivatives_plus_one * root.pow(2)
181
+ + 2 * input_delta * theta_one_minus_theta
182
+ + input_derivatives * (1 - root).pow(2)
183
+ )
184
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
185
+
186
+ return outputs, -logabsdet
187
+ else:
188
+ theta = (inputs - input_cumwidths) / input_bin_widths
189
+ theta_one_minus_theta = theta * (1 - theta)
190
+
191
+ numerator = input_heights * (
192
+ input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
193
+ )
194
+ denominator = input_delta + (
195
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
196
+ * theta_one_minus_theta
197
+ )
198
+ outputs = input_cumheights + numerator / denominator
199
+
200
+ derivative_numerator = input_delta.pow(2) * (
201
+ input_derivatives_plus_one * theta.pow(2)
202
+ + 2 * input_delta * theta_one_minus_theta
203
+ + input_derivatives * (1 - theta).pow(2)
204
+ )
205
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
206
+
207
+ return outputs, logabsdet