TIMBOVILL commited on
Commit
5aaaff6
·
verified ·
1 Parent(s): 1fe81ef

Upload 6 files

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