Hev832 commited on
Commit
7d95823
1 Parent(s): 2352781

Upload 85 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. infer/lib/audio.py +51 -0
  2. infer/lib/infer_pack/attentions.py +459 -0
  3. infer/lib/infer_pack/commons.py +172 -0
  4. infer/lib/infer_pack/models.py +1443 -0
  5. infer/lib/infer_pack/models_onnx.py +825 -0
  6. infer/lib/infer_pack/modules.py +615 -0
  7. infer/lib/infer_pack/modules/F0Predictor/DioF0Predictor.py +91 -0
  8. infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py +16 -0
  9. infer/lib/infer_pack/modules/F0Predictor/HarvestF0Predictor.py +87 -0
  10. infer/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py +98 -0
  11. infer/lib/infer_pack/modules/F0Predictor/__init__.py +0 -0
  12. infer/lib/infer_pack/onnx_inference.py +149 -0
  13. infer/lib/infer_pack/transforms.py +207 -0
  14. infer/lib/jit/__init__.py +163 -0
  15. infer/lib/jit/get_hubert.py +342 -0
  16. infer/lib/jit/get_rmvpe.py +12 -0
  17. infer/lib/jit/get_synthesizer.py +38 -0
  18. infer/lib/rmvpe.py +670 -0
  19. infer/lib/slicer2.py +260 -0
  20. infer/lib/train/data_utils.py +517 -0
  21. infer/lib/train/losses.py +58 -0
  22. infer/lib/train/mel_processing.py +127 -0
  23. infer/lib/train/process_ckpt.py +261 -0
  24. infer/lib/train/utils.py +478 -0
  25. infer/lib/uvr5_pack/lib_v5/dataset.py +183 -0
  26. infer/lib/uvr5_pack/lib_v5/layers.py +118 -0
  27. infer/lib/uvr5_pack/lib_v5/layers_123812KB .py +118 -0
  28. infer/lib/uvr5_pack/lib_v5/layers_123821KB.py +118 -0
  29. infer/lib/uvr5_pack/lib_v5/layers_33966KB.py +126 -0
  30. infer/lib/uvr5_pack/lib_v5/layers_537227KB.py +126 -0
  31. infer/lib/uvr5_pack/lib_v5/layers_537238KB.py +126 -0
  32. infer/lib/uvr5_pack/lib_v5/layers_new.py +125 -0
  33. infer/lib/uvr5_pack/lib_v5/model_param_init.py +69 -0
  34. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr16000_hl512.json +19 -0
  35. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr32000_hl512.json +19 -0
  36. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr33075_hl384.json +19 -0
  37. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl1024.json +19 -0
  38. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl256.json +19 -0
  39. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512.json +19 -0
  40. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512_cut.json +19 -0
  41. infer/lib/uvr5_pack/lib_v5/modelparams/2band_32000.json +30 -0
  42. infer/lib/uvr5_pack/lib_v5/modelparams/2band_44100_lofi.json +30 -0
  43. infer/lib/uvr5_pack/lib_v5/modelparams/2band_48000.json +30 -0
  44. infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100.json +42 -0
  45. infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100_mid.json +43 -0
  46. infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100_msb2.json +43 -0
  47. infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100.json +54 -0
  48. infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_mid.json +55 -0
  49. infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_msb.json +55 -0
  50. infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_msb2.json +55 -0
infer/lib/audio.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform, os
2
+ import ffmpeg
3
+ import numpy as np
4
+ import av
5
+ from io import BytesIO
6
+
7
+
8
+ def wav2(i, o, format):
9
+ inp = av.open(i, "rb")
10
+ if format == "m4a":
11
+ format = "mp4"
12
+ out = av.open(o, "wb", format=format)
13
+ if format == "ogg":
14
+ format = "libvorbis"
15
+ if format == "mp4":
16
+ format = "aac"
17
+
18
+ ostream = out.add_stream(format)
19
+
20
+ for frame in inp.decode(audio=0):
21
+ for p in ostream.encode(frame):
22
+ out.mux(p)
23
+
24
+ for p in ostream.encode(None):
25
+ out.mux(p)
26
+
27
+ out.close()
28
+ inp.close()
29
+
30
+
31
+ def load_audio(file, sr):
32
+ try:
33
+ # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
34
+ # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
35
+ # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
36
+ file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车
37
+ out, _ = (
38
+ ffmpeg.input(file, threads=0)
39
+ .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
40
+ .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
41
+ )
42
+ except Exception as e:
43
+ raise RuntimeError(f"Failed to load audio: {e}")
44
+
45
+ return np.frombuffer(out, np.float32).flatten()
46
+
47
+
48
+ def clean_path(path_str):
49
+ if platform.system() == "Windows":
50
+ path_str = path_str.replace("/", "\\")
51
+ return path_str.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
infer/lib/infer_pack/attentions.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ from typing import Optional
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+
10
+ from infer.lib.infer_pack import commons, modules
11
+ from infer.lib.infer_pack.modules import LayerNorm
12
+
13
+
14
+ class Encoder(nn.Module):
15
+ def __init__(
16
+ self,
17
+ hidden_channels,
18
+ filter_channels,
19
+ n_heads,
20
+ n_layers,
21
+ kernel_size=1,
22
+ p_dropout=0.0,
23
+ window_size=10,
24
+ **kwargs
25
+ ):
26
+ super(Encoder, self).__init__()
27
+ self.hidden_channels = hidden_channels
28
+ self.filter_channels = filter_channels
29
+ self.n_heads = n_heads
30
+ self.n_layers = int(n_layers)
31
+ self.kernel_size = kernel_size
32
+ self.p_dropout = p_dropout
33
+ self.window_size = window_size
34
+
35
+ self.drop = nn.Dropout(p_dropout)
36
+ self.attn_layers = nn.ModuleList()
37
+ self.norm_layers_1 = nn.ModuleList()
38
+ self.ffn_layers = nn.ModuleList()
39
+ self.norm_layers_2 = nn.ModuleList()
40
+ for i in range(self.n_layers):
41
+ self.attn_layers.append(
42
+ MultiHeadAttention(
43
+ hidden_channels,
44
+ hidden_channels,
45
+ n_heads,
46
+ p_dropout=p_dropout,
47
+ window_size=window_size,
48
+ )
49
+ )
50
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
51
+ self.ffn_layers.append(
52
+ FFN(
53
+ hidden_channels,
54
+ hidden_channels,
55
+ filter_channels,
56
+ kernel_size,
57
+ p_dropout=p_dropout,
58
+ )
59
+ )
60
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
61
+
62
+ def forward(self, x, x_mask):
63
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
64
+ x = x * x_mask
65
+ zippep = zip(
66
+ self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2
67
+ )
68
+ for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep:
69
+ y = attn_layers(x, x, attn_mask)
70
+ y = self.drop(y)
71
+ x = norm_layers_1(x + y)
72
+
73
+ y = ffn_layers(x, x_mask)
74
+ y = self.drop(y)
75
+ x = norm_layers_2(x + y)
76
+ x = x * x_mask
77
+ return x
78
+
79
+
80
+ class Decoder(nn.Module):
81
+ def __init__(
82
+ self,
83
+ hidden_channels,
84
+ filter_channels,
85
+ n_heads,
86
+ n_layers,
87
+ kernel_size=1,
88
+ p_dropout=0.0,
89
+ proximal_bias=False,
90
+ proximal_init=True,
91
+ **kwargs
92
+ ):
93
+ super(Decoder, self).__init__()
94
+ self.hidden_channels = hidden_channels
95
+ self.filter_channels = filter_channels
96
+ self.n_heads = n_heads
97
+ self.n_layers = n_layers
98
+ self.kernel_size = kernel_size
99
+ self.p_dropout = p_dropout
100
+ self.proximal_bias = proximal_bias
101
+ self.proximal_init = proximal_init
102
+
103
+ self.drop = nn.Dropout(p_dropout)
104
+ self.self_attn_layers = nn.ModuleList()
105
+ self.norm_layers_0 = nn.ModuleList()
106
+ self.encdec_attn_layers = nn.ModuleList()
107
+ self.norm_layers_1 = nn.ModuleList()
108
+ self.ffn_layers = nn.ModuleList()
109
+ self.norm_layers_2 = nn.ModuleList()
110
+ for i in range(self.n_layers):
111
+ self.self_attn_layers.append(
112
+ MultiHeadAttention(
113
+ hidden_channels,
114
+ hidden_channels,
115
+ n_heads,
116
+ p_dropout=p_dropout,
117
+ proximal_bias=proximal_bias,
118
+ proximal_init=proximal_init,
119
+ )
120
+ )
121
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
122
+ self.encdec_attn_layers.append(
123
+ MultiHeadAttention(
124
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
125
+ )
126
+ )
127
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
128
+ self.ffn_layers.append(
129
+ FFN(
130
+ hidden_channels,
131
+ hidden_channels,
132
+ filter_channels,
133
+ kernel_size,
134
+ p_dropout=p_dropout,
135
+ causal=True,
136
+ )
137
+ )
138
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
139
+
140
+ def forward(self, x, x_mask, h, h_mask):
141
+ """
142
+ x: decoder input
143
+ h: encoder output
144
+ """
145
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
146
+ device=x.device, dtype=x.dtype
147
+ )
148
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
149
+ x = x * x_mask
150
+ for i in range(self.n_layers):
151
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
152
+ y = self.drop(y)
153
+ x = self.norm_layers_0[i](x + y)
154
+
155
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
156
+ y = self.drop(y)
157
+ x = self.norm_layers_1[i](x + y)
158
+
159
+ y = self.ffn_layers[i](x, x_mask)
160
+ y = self.drop(y)
161
+ x = self.norm_layers_2[i](x + y)
162
+ x = x * x_mask
163
+ return x
164
+
165
+
166
+ class MultiHeadAttention(nn.Module):
167
+ def __init__(
168
+ self,
169
+ channels,
170
+ out_channels,
171
+ n_heads,
172
+ p_dropout=0.0,
173
+ window_size=None,
174
+ heads_share=True,
175
+ block_length=None,
176
+ proximal_bias=False,
177
+ proximal_init=False,
178
+ ):
179
+ super(MultiHeadAttention, self).__init__()
180
+ assert channels % n_heads == 0
181
+
182
+ self.channels = channels
183
+ self.out_channels = out_channels
184
+ self.n_heads = n_heads
185
+ self.p_dropout = p_dropout
186
+ self.window_size = window_size
187
+ self.heads_share = heads_share
188
+ self.block_length = block_length
189
+ self.proximal_bias = proximal_bias
190
+ self.proximal_init = proximal_init
191
+ self.attn = None
192
+
193
+ self.k_channels = channels // n_heads
194
+ self.conv_q = nn.Conv1d(channels, channels, 1)
195
+ self.conv_k = nn.Conv1d(channels, channels, 1)
196
+ self.conv_v = nn.Conv1d(channels, channels, 1)
197
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
198
+ self.drop = nn.Dropout(p_dropout)
199
+
200
+ if window_size is not None:
201
+ n_heads_rel = 1 if heads_share else n_heads
202
+ rel_stddev = self.k_channels**-0.5
203
+ self.emb_rel_k = nn.Parameter(
204
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
205
+ * rel_stddev
206
+ )
207
+ self.emb_rel_v = nn.Parameter(
208
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
209
+ * rel_stddev
210
+ )
211
+
212
+ nn.init.xavier_uniform_(self.conv_q.weight)
213
+ nn.init.xavier_uniform_(self.conv_k.weight)
214
+ nn.init.xavier_uniform_(self.conv_v.weight)
215
+ if proximal_init:
216
+ with torch.no_grad():
217
+ self.conv_k.weight.copy_(self.conv_q.weight)
218
+ self.conv_k.bias.copy_(self.conv_q.bias)
219
+
220
+ def forward(
221
+ self, x: torch.Tensor, c: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
222
+ ):
223
+ q = self.conv_q(x)
224
+ k = self.conv_k(c)
225
+ v = self.conv_v(c)
226
+
227
+ x, _ = self.attention(q, k, v, mask=attn_mask)
228
+
229
+ x = self.conv_o(x)
230
+ return x
231
+
232
+ def attention(
233
+ self,
234
+ query: torch.Tensor,
235
+ key: torch.Tensor,
236
+ value: torch.Tensor,
237
+ mask: Optional[torch.Tensor] = None,
238
+ ):
239
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
240
+ b, d, t_s = key.size()
241
+ t_t = query.size(2)
242
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
243
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
244
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
245
+
246
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
247
+ if self.window_size is not None:
248
+ assert (
249
+ t_s == t_t
250
+ ), "Relative attention is only available for self-attention."
251
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
252
+ rel_logits = self._matmul_with_relative_keys(
253
+ query / math.sqrt(self.k_channels), key_relative_embeddings
254
+ )
255
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
256
+ scores = scores + scores_local
257
+ if self.proximal_bias:
258
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
259
+ scores = scores + self._attention_bias_proximal(t_s).to(
260
+ device=scores.device, dtype=scores.dtype
261
+ )
262
+ if mask is not None:
263
+ scores = scores.masked_fill(mask == 0, -1e4)
264
+ if self.block_length is not None:
265
+ assert (
266
+ t_s == t_t
267
+ ), "Local attention is only available for self-attention."
268
+ block_mask = (
269
+ torch.ones_like(scores)
270
+ .triu(-self.block_length)
271
+ .tril(self.block_length)
272
+ )
273
+ scores = scores.masked_fill(block_mask == 0, -1e4)
274
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
275
+ p_attn = self.drop(p_attn)
276
+ output = torch.matmul(p_attn, value)
277
+ if self.window_size is not None:
278
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
279
+ value_relative_embeddings = self._get_relative_embeddings(
280
+ self.emb_rel_v, t_s
281
+ )
282
+ output = output + self._matmul_with_relative_values(
283
+ relative_weights, value_relative_embeddings
284
+ )
285
+ output = (
286
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
287
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
288
+ return output, p_attn
289
+
290
+ def _matmul_with_relative_values(self, x, y):
291
+ """
292
+ x: [b, h, l, m]
293
+ y: [h or 1, m, d]
294
+ ret: [b, h, l, d]
295
+ """
296
+ ret = torch.matmul(x, y.unsqueeze(0))
297
+ return ret
298
+
299
+ def _matmul_with_relative_keys(self, x, y):
300
+ """
301
+ x: [b, h, l, d]
302
+ y: [h or 1, m, d]
303
+ ret: [b, h, l, m]
304
+ """
305
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
306
+ return ret
307
+
308
+ def _get_relative_embeddings(self, relative_embeddings, length: int):
309
+ max_relative_position = 2 * self.window_size + 1
310
+ # Pad first before slice to avoid using cond ops.
311
+ pad_length: int = max(length - (self.window_size + 1), 0)
312
+ slice_start_position = max((self.window_size + 1) - length, 0)
313
+ slice_end_position = slice_start_position + 2 * length - 1
314
+ if pad_length > 0:
315
+ padded_relative_embeddings = F.pad(
316
+ relative_embeddings,
317
+ # commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
318
+ [0, 0, pad_length, pad_length, 0, 0],
319
+ )
320
+ else:
321
+ padded_relative_embeddings = relative_embeddings
322
+ used_relative_embeddings = padded_relative_embeddings[
323
+ :, slice_start_position:slice_end_position
324
+ ]
325
+ return used_relative_embeddings
326
+
327
+ def _relative_position_to_absolute_position(self, x):
328
+ """
329
+ x: [b, h, l, 2*l-1]
330
+ ret: [b, h, l, l]
331
+ """
332
+ batch, heads, length, _ = x.size()
333
+ # Concat columns of pad to shift from relative to absolute indexing.
334
+ x = F.pad(
335
+ x,
336
+ # commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]])
337
+ [0, 1, 0, 0, 0, 0, 0, 0],
338
+ )
339
+
340
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
341
+ x_flat = x.view([batch, heads, length * 2 * length])
342
+ x_flat = F.pad(
343
+ x_flat,
344
+ # commons.convert_pad_shape([[0, 0], [0, 0], [0, int(length) - 1]])
345
+ [0, int(length) - 1, 0, 0, 0, 0],
346
+ )
347
+
348
+ # Reshape and slice out the padded elements.
349
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
350
+ :, :, :length, length - 1 :
351
+ ]
352
+ return x_final
353
+
354
+ def _absolute_position_to_relative_position(self, x):
355
+ """
356
+ x: [b, h, l, l]
357
+ ret: [b, h, l, 2*l-1]
358
+ """
359
+ batch, heads, length, _ = x.size()
360
+ # padd along column
361
+ x = F.pad(
362
+ x,
363
+ # commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, int(length) - 1]])
364
+ [0, int(length) - 1, 0, 0, 0, 0, 0, 0],
365
+ )
366
+ x_flat = x.view([batch, heads, int(length**2) + int(length * (length - 1))])
367
+ # add 0's in the beginning that will skew the elements after reshape
368
+ x_flat = F.pad(
369
+ x_flat,
370
+ # commons.convert_pad_shape([[0, 0], [0, 0], [int(length), 0]])
371
+ [length, 0, 0, 0, 0, 0],
372
+ )
373
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
374
+ return x_final
375
+
376
+ def _attention_bias_proximal(self, length: int):
377
+ """Bias for self-attention to encourage attention to close positions.
378
+ Args:
379
+ length: an integer scalar.
380
+ Returns:
381
+ a Tensor with shape [1, 1, length, length]
382
+ """
383
+ r = torch.arange(length, dtype=torch.float32)
384
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
385
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
386
+
387
+
388
+ class FFN(nn.Module):
389
+ def __init__(
390
+ self,
391
+ in_channels,
392
+ out_channels,
393
+ filter_channels,
394
+ kernel_size,
395
+ p_dropout=0.0,
396
+ activation: str = None,
397
+ causal=False,
398
+ ):
399
+ super(FFN, self).__init__()
400
+ self.in_channels = in_channels
401
+ self.out_channels = out_channels
402
+ self.filter_channels = filter_channels
403
+ self.kernel_size = kernel_size
404
+ self.p_dropout = p_dropout
405
+ self.activation = activation
406
+ self.causal = causal
407
+ self.is_activation = True if activation == "gelu" else False
408
+ # if causal:
409
+ # self.padding = self._causal_padding
410
+ # else:
411
+ # self.padding = self._same_padding
412
+
413
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
414
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
415
+ self.drop = nn.Dropout(p_dropout)
416
+
417
+ def padding(self, x: torch.Tensor, x_mask: torch.Tensor) -> torch.Tensor:
418
+ if self.causal:
419
+ padding = self._causal_padding(x * x_mask)
420
+ else:
421
+ padding = self._same_padding(x * x_mask)
422
+ return padding
423
+
424
+ def forward(self, x: torch.Tensor, x_mask: torch.Tensor):
425
+ x = self.conv_1(self.padding(x, x_mask))
426
+ if self.is_activation:
427
+ x = x * torch.sigmoid(1.702 * x)
428
+ else:
429
+ x = torch.relu(x)
430
+ x = self.drop(x)
431
+
432
+ x = self.conv_2(self.padding(x, x_mask))
433
+ return x * x_mask
434
+
435
+ def _causal_padding(self, x):
436
+ if self.kernel_size == 1:
437
+ return x
438
+ pad_l: int = self.kernel_size - 1
439
+ pad_r: int = 0
440
+ # padding = [[0, 0], [0, 0], [pad_l, pad_r]]
441
+ x = F.pad(
442
+ x,
443
+ # commons.convert_pad_shape(padding)
444
+ [pad_l, pad_r, 0, 0, 0, 0],
445
+ )
446
+ return x
447
+
448
+ def _same_padding(self, x):
449
+ if self.kernel_size == 1:
450
+ return x
451
+ pad_l: int = (self.kernel_size - 1) // 2
452
+ pad_r: int = self.kernel_size // 2
453
+ # padding = [[0, 0], [0, 0], [pad_l, pad_r]]
454
+ x = F.pad(
455
+ x,
456
+ # commons.convert_pad_shape(padding)
457
+ [pad_l, pad_r, 0, 0, 0, 0],
458
+ )
459
+ return x
infer/lib/infer_pack/commons.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ import math
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+
10
+ def init_weights(m, mean=0.0, std=0.01):
11
+ classname = m.__class__.__name__
12
+ if classname.find("Conv") != -1:
13
+ m.weight.data.normal_(mean, std)
14
+
15
+
16
+ def get_padding(kernel_size, dilation=1):
17
+ return int((kernel_size * dilation - dilation) / 2)
18
+
19
+
20
+ # def convert_pad_shape(pad_shape):
21
+ # l = pad_shape[::-1]
22
+ # pad_shape = [item for sublist in l for item in sublist]
23
+ # return pad_shape
24
+
25
+
26
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
27
+ """KL(P||Q)"""
28
+ kl = (logs_q - logs_p) - 0.5
29
+ kl += (
30
+ 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
31
+ )
32
+ return kl
33
+
34
+
35
+ def rand_gumbel(shape):
36
+ """Sample from the Gumbel distribution, protect from overflows."""
37
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
38
+ return -torch.log(-torch.log(uniform_samples))
39
+
40
+
41
+ def rand_gumbel_like(x):
42
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
43
+ return g
44
+
45
+
46
+ def slice_segments(x, ids_str, segment_size=4):
47
+ ret = torch.zeros_like(x[:, :, :segment_size])
48
+ for i in range(x.size(0)):
49
+ idx_str = ids_str[i]
50
+ idx_end = idx_str + segment_size
51
+ ret[i] = x[i, :, idx_str:idx_end]
52
+ return ret
53
+
54
+
55
+ def slice_segments2(x, ids_str, segment_size=4):
56
+ ret = torch.zeros_like(x[:, :segment_size])
57
+ for i in range(x.size(0)):
58
+ idx_str = ids_str[i]
59
+ idx_end = idx_str + segment_size
60
+ ret[i] = x[i, idx_str:idx_end]
61
+ return ret
62
+
63
+
64
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
65
+ b, d, t = x.size()
66
+ if x_lengths is None:
67
+ x_lengths = t
68
+ ids_str_max = x_lengths - segment_size + 1
69
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
70
+ ret = slice_segments(x, ids_str, segment_size)
71
+ return ret, ids_str
72
+
73
+
74
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
75
+ position = torch.arange(length, dtype=torch.float)
76
+ num_timescales = channels // 2
77
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
78
+ num_timescales - 1
79
+ )
80
+ inv_timescales = min_timescale * torch.exp(
81
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
82
+ )
83
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
84
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
85
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
86
+ signal = signal.view(1, channels, length)
87
+ return signal
88
+
89
+
90
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
91
+ b, channels, length = x.size()
92
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
93
+ return x + signal.to(dtype=x.dtype, device=x.device)
94
+
95
+
96
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
97
+ b, channels, length = x.size()
98
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
99
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
100
+
101
+
102
+ def subsequent_mask(length):
103
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
104
+ return mask
105
+
106
+
107
+ @torch.jit.script
108
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
109
+ n_channels_int = n_channels[0]
110
+ in_act = input_a + input_b
111
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
112
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
113
+ acts = t_act * s_act
114
+ return acts
115
+
116
+
117
+ # def convert_pad_shape(pad_shape):
118
+ # l = pad_shape[::-1]
119
+ # pad_shape = [item for sublist in l for item in sublist]
120
+ # return pad_shape
121
+
122
+
123
+ def convert_pad_shape(pad_shape: List[List[int]]) -> List[int]:
124
+ return torch.tensor(pad_shape).flip(0).reshape(-1).int().tolist()
125
+
126
+
127
+ def shift_1d(x):
128
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
129
+ return x
130
+
131
+
132
+ def sequence_mask(length: torch.Tensor, max_length: Optional[int] = None):
133
+ if max_length is None:
134
+ max_length = length.max()
135
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
136
+ return x.unsqueeze(0) < length.unsqueeze(1)
137
+
138
+
139
+ def generate_path(duration, mask):
140
+ """
141
+ duration: [b, 1, t_x]
142
+ mask: [b, 1, t_y, t_x]
143
+ """
144
+ device = duration.device
145
+
146
+ b, _, t_y, t_x = mask.shape
147
+ cum_duration = torch.cumsum(duration, -1)
148
+
149
+ cum_duration_flat = cum_duration.view(b * t_x)
150
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
151
+ path = path.view(b, t_x, t_y)
152
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
153
+ path = path.unsqueeze(1).transpose(2, 3) * mask
154
+ return path
155
+
156
+
157
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
158
+ if isinstance(parameters, torch.Tensor):
159
+ parameters = [parameters]
160
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
161
+ norm_type = float(norm_type)
162
+ if clip_value is not None:
163
+ clip_value = float(clip_value)
164
+
165
+ total_norm = 0
166
+ for p in parameters:
167
+ param_norm = p.grad.data.norm(norm_type)
168
+ total_norm += param_norm.item() ** norm_type
169
+ if clip_value is not None:
170
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
171
+ total_norm = total_norm ** (1.0 / norm_type)
172
+ return total_norm
infer/lib/infer_pack/models.py ADDED
@@ -0,0 +1,1443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import logging
3
+ from typing import Optional
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch import nn
10
+ from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
11
+ from torch.nn import functional as F
12
+ from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
13
+
14
+ from infer.lib.infer_pack import attentions, commons, modules
15
+ from infer.lib.infer_pack.commons import get_padding, init_weights
16
+
17
+ has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
18
+
19
+
20
+ class TextEncoder256(nn.Module):
21
+ def __init__(
22
+ self,
23
+ out_channels,
24
+ hidden_channels,
25
+ filter_channels,
26
+ n_heads,
27
+ n_layers,
28
+ kernel_size,
29
+ p_dropout,
30
+ f0=True,
31
+ ):
32
+ super(TextEncoder256, self).__init__()
33
+ self.out_channels = out_channels
34
+ self.hidden_channels = hidden_channels
35
+ self.filter_channels = filter_channels
36
+ self.n_heads = n_heads
37
+ self.n_layers = n_layers
38
+ self.kernel_size = kernel_size
39
+ self.p_dropout = float(p_dropout)
40
+ self.emb_phone = nn.Linear(256, hidden_channels)
41
+ self.lrelu = nn.LeakyReLU(0.1, inplace=True)
42
+ if f0 == True:
43
+ self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
44
+ self.encoder = attentions.Encoder(
45
+ hidden_channels,
46
+ filter_channels,
47
+ n_heads,
48
+ n_layers,
49
+ kernel_size,
50
+ float(p_dropout),
51
+ )
52
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
53
+
54
+ def forward(
55
+ self, phone: torch.Tensor, pitch: Optional[torch.Tensor], lengths: torch.Tensor
56
+ ):
57
+ if pitch is None:
58
+ x = self.emb_phone(phone)
59
+ else:
60
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
61
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
62
+ x = self.lrelu(x)
63
+ x = torch.transpose(x, 1, -1) # [b, h, t]
64
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
65
+ x.dtype
66
+ )
67
+ x = self.encoder(x * x_mask, x_mask)
68
+ stats = self.proj(x) * x_mask
69
+
70
+ m, logs = torch.split(stats, self.out_channels, dim=1)
71
+ return m, logs, x_mask
72
+
73
+
74
+ class TextEncoder768(nn.Module):
75
+ def __init__(
76
+ self,
77
+ out_channels,
78
+ hidden_channels,
79
+ filter_channels,
80
+ n_heads,
81
+ n_layers,
82
+ kernel_size,
83
+ p_dropout,
84
+ f0=True,
85
+ ):
86
+ super(TextEncoder768, self).__init__()
87
+ self.out_channels = out_channels
88
+ self.hidden_channels = hidden_channels
89
+ self.filter_channels = filter_channels
90
+ self.n_heads = n_heads
91
+ self.n_layers = n_layers
92
+ self.kernel_size = kernel_size
93
+ self.p_dropout = float(p_dropout)
94
+ self.emb_phone = nn.Linear(768, hidden_channels)
95
+ self.lrelu = nn.LeakyReLU(0.1, inplace=True)
96
+ if f0 == True:
97
+ self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
98
+ self.encoder = attentions.Encoder(
99
+ hidden_channels,
100
+ filter_channels,
101
+ n_heads,
102
+ n_layers,
103
+ kernel_size,
104
+ float(p_dropout),
105
+ )
106
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
107
+
108
+ def forward(self, phone: torch.Tensor, pitch: torch.Tensor, lengths: torch.Tensor):
109
+ if pitch is None:
110
+ x = self.emb_phone(phone)
111
+ else:
112
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
113
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
114
+ x = self.lrelu(x)
115
+ x = torch.transpose(x, 1, -1) # [b, h, t]
116
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
117
+ x.dtype
118
+ )
119
+ x = self.encoder(x * x_mask, x_mask)
120
+ stats = self.proj(x) * x_mask
121
+
122
+ m, logs = torch.split(stats, self.out_channels, dim=1)
123
+ return m, logs, x_mask
124
+
125
+
126
+ class ResidualCouplingBlock(nn.Module):
127
+ def __init__(
128
+ self,
129
+ channels,
130
+ hidden_channels,
131
+ kernel_size,
132
+ dilation_rate,
133
+ n_layers,
134
+ n_flows=4,
135
+ gin_channels=0,
136
+ ):
137
+ super(ResidualCouplingBlock, self).__init__()
138
+ self.channels = channels
139
+ self.hidden_channels = hidden_channels
140
+ self.kernel_size = kernel_size
141
+ self.dilation_rate = dilation_rate
142
+ self.n_layers = n_layers
143
+ self.n_flows = n_flows
144
+ self.gin_channels = gin_channels
145
+
146
+ self.flows = nn.ModuleList()
147
+ for i in range(n_flows):
148
+ self.flows.append(
149
+ modules.ResidualCouplingLayer(
150
+ channels,
151
+ hidden_channels,
152
+ kernel_size,
153
+ dilation_rate,
154
+ n_layers,
155
+ gin_channels=gin_channels,
156
+ mean_only=True,
157
+ )
158
+ )
159
+ self.flows.append(modules.Flip())
160
+
161
+ def forward(
162
+ self,
163
+ x: torch.Tensor,
164
+ x_mask: torch.Tensor,
165
+ g: Optional[torch.Tensor] = None,
166
+ reverse: bool = False,
167
+ ):
168
+ if not reverse:
169
+ for flow in self.flows:
170
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
171
+ else:
172
+ for flow in self.flows[::-1]:
173
+ x, _ = flow.forward(x, x_mask, g=g, reverse=reverse)
174
+ return x
175
+
176
+ def remove_weight_norm(self):
177
+ for i in range(self.n_flows):
178
+ self.flows[i * 2].remove_weight_norm()
179
+
180
+ def __prepare_scriptable__(self):
181
+ for i in range(self.n_flows):
182
+ for hook in self.flows[i * 2]._forward_pre_hooks.values():
183
+ if (
184
+ hook.__module__ == "torch.nn.utils.weight_norm"
185
+ and hook.__class__.__name__ == "WeightNorm"
186
+ ):
187
+ torch.nn.utils.remove_weight_norm(self.flows[i * 2])
188
+
189
+ return self
190
+
191
+
192
+ class PosteriorEncoder(nn.Module):
193
+ def __init__(
194
+ self,
195
+ in_channels,
196
+ out_channels,
197
+ hidden_channels,
198
+ kernel_size,
199
+ dilation_rate,
200
+ n_layers,
201
+ gin_channels=0,
202
+ ):
203
+ super(PosteriorEncoder, self).__init__()
204
+ self.in_channels = in_channels
205
+ self.out_channels = out_channels
206
+ self.hidden_channels = hidden_channels
207
+ self.kernel_size = kernel_size
208
+ self.dilation_rate = dilation_rate
209
+ self.n_layers = n_layers
210
+ self.gin_channels = gin_channels
211
+
212
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
213
+ self.enc = modules.WN(
214
+ hidden_channels,
215
+ kernel_size,
216
+ dilation_rate,
217
+ n_layers,
218
+ gin_channels=gin_channels,
219
+ )
220
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
221
+
222
+ def forward(
223
+ self, x: torch.Tensor, x_lengths: torch.Tensor, g: Optional[torch.Tensor] = None
224
+ ):
225
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
226
+ x.dtype
227
+ )
228
+ x = self.pre(x) * x_mask
229
+ x = self.enc(x, x_mask, g=g)
230
+ stats = self.proj(x) * x_mask
231
+ m, logs = torch.split(stats, self.out_channels, dim=1)
232
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
233
+ return z, m, logs, x_mask
234
+
235
+ def remove_weight_norm(self):
236
+ self.enc.remove_weight_norm()
237
+
238
+ def __prepare_scriptable__(self):
239
+ for hook in self.enc._forward_pre_hooks.values():
240
+ if (
241
+ hook.__module__ == "torch.nn.utils.weight_norm"
242
+ and hook.__class__.__name__ == "WeightNorm"
243
+ ):
244
+ torch.nn.utils.remove_weight_norm(self.enc)
245
+ return self
246
+
247
+
248
+ class Generator(torch.nn.Module):
249
+ def __init__(
250
+ self,
251
+ initial_channel,
252
+ resblock,
253
+ resblock_kernel_sizes,
254
+ resblock_dilation_sizes,
255
+ upsample_rates,
256
+ upsample_initial_channel,
257
+ upsample_kernel_sizes,
258
+ gin_channels=0,
259
+ ):
260
+ super(Generator, self).__init__()
261
+ self.num_kernels = len(resblock_kernel_sizes)
262
+ self.num_upsamples = len(upsample_rates)
263
+ self.conv_pre = Conv1d(
264
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
265
+ )
266
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
267
+
268
+ self.ups = nn.ModuleList()
269
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
270
+ self.ups.append(
271
+ weight_norm(
272
+ ConvTranspose1d(
273
+ upsample_initial_channel // (2**i),
274
+ upsample_initial_channel // (2 ** (i + 1)),
275
+ k,
276
+ u,
277
+ padding=(k - u) // 2,
278
+ )
279
+ )
280
+ )
281
+
282
+ self.resblocks = nn.ModuleList()
283
+ for i in range(len(self.ups)):
284
+ ch = upsample_initial_channel // (2 ** (i + 1))
285
+ for j, (k, d) in enumerate(
286
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
287
+ ):
288
+ self.resblocks.append(resblock(ch, k, d))
289
+
290
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
291
+ self.ups.apply(init_weights)
292
+
293
+ if gin_channels != 0:
294
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
295
+
296
+ def forward(self, x: torch.Tensor, g: Optional[torch.Tensor] = None):
297
+ x = self.conv_pre(x)
298
+ if g is not None:
299
+ x = x + self.cond(g)
300
+
301
+ for i in range(self.num_upsamples):
302
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
303
+ x = self.ups[i](x)
304
+ xs = None
305
+ for j in range(self.num_kernels):
306
+ if xs is None:
307
+ xs = self.resblocks[i * self.num_kernels + j](x)
308
+ else:
309
+ xs += self.resblocks[i * self.num_kernels + j](x)
310
+ x = xs / self.num_kernels
311
+ x = F.leaky_relu(x)
312
+ x = self.conv_post(x)
313
+ x = torch.tanh(x)
314
+
315
+ return x
316
+
317
+ def __prepare_scriptable__(self):
318
+ for l in self.ups:
319
+ for hook in l._forward_pre_hooks.values():
320
+ # The hook we want to remove is an instance of WeightNorm class, so
321
+ # normally we would do `if isinstance(...)` but this class is not accessible
322
+ # because of shadowing, so we check the module name directly.
323
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
324
+ if (
325
+ hook.__module__ == "torch.nn.utils.weight_norm"
326
+ and hook.__class__.__name__ == "WeightNorm"
327
+ ):
328
+ torch.nn.utils.remove_weight_norm(l)
329
+
330
+ for l in self.resblocks:
331
+ for hook in l._forward_pre_hooks.values():
332
+ if (
333
+ hook.__module__ == "torch.nn.utils.weight_norm"
334
+ and hook.__class__.__name__ == "WeightNorm"
335
+ ):
336
+ torch.nn.utils.remove_weight_norm(l)
337
+ return self
338
+
339
+ def remove_weight_norm(self):
340
+ for l in self.ups:
341
+ remove_weight_norm(l)
342
+ for l in self.resblocks:
343
+ l.remove_weight_norm()
344
+
345
+
346
+ class SineGen(torch.nn.Module):
347
+ """Definition of sine generator
348
+ SineGen(samp_rate, harmonic_num = 0,
349
+ sine_amp = 0.1, noise_std = 0.003,
350
+ voiced_threshold = 0,
351
+ flag_for_pulse=False)
352
+ samp_rate: sampling rate in Hz
353
+ harmonic_num: number of harmonic overtones (default 0)
354
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
355
+ noise_std: std of Gaussian noise (default 0.003)
356
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
357
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
358
+ Note: when flag_for_pulse is True, the first time step of a voiced
359
+ segment is always sin(torch.pi) or cos(0)
360
+ """
361
+
362
+ def __init__(
363
+ self,
364
+ samp_rate,
365
+ harmonic_num=0,
366
+ sine_amp=0.1,
367
+ noise_std=0.003,
368
+ voiced_threshold=0,
369
+ flag_for_pulse=False,
370
+ ):
371
+ super(SineGen, self).__init__()
372
+ self.sine_amp = sine_amp
373
+ self.noise_std = noise_std
374
+ self.harmonic_num = harmonic_num
375
+ self.dim = self.harmonic_num + 1
376
+ self.sampling_rate = samp_rate
377
+ self.voiced_threshold = voiced_threshold
378
+
379
+ def _f02uv(self, f0):
380
+ # generate uv signal
381
+ uv = torch.ones_like(f0)
382
+ uv = uv * (f0 > self.voiced_threshold)
383
+ if uv.device.type == "privateuseone": # for DirectML
384
+ uv = uv.float()
385
+ return uv
386
+
387
+ def forward(self, f0: torch.Tensor, upp: int):
388
+ """sine_tensor, uv = forward(f0)
389
+ input F0: tensor(batchsize=1, length, dim=1)
390
+ f0 for unvoiced steps should be 0
391
+ output sine_tensor: tensor(batchsize=1, length, dim)
392
+ output uv: tensor(batchsize=1, length, 1)
393
+ """
394
+ with torch.no_grad():
395
+ f0 = f0[:, None].transpose(1, 2)
396
+ f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
397
+ # fundamental component
398
+ f0_buf[:, :, 0] = f0[:, :, 0]
399
+ for idx in range(self.harmonic_num):
400
+ f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
401
+ idx + 2
402
+ ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
403
+ rad_values = (
404
+ f0_buf / self.sampling_rate
405
+ ) % 1 ###%1意味着n_har的乘积无法后处理优化
406
+ rand_ini = torch.rand(
407
+ f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
408
+ )
409
+ rand_ini[:, 0] = 0
410
+ rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
411
+ tmp_over_one = torch.cumsum(
412
+ rad_values, 1
413
+ ) # % 1 #####%1意味着后面的cumsum无法再优化
414
+ tmp_over_one *= upp
415
+ tmp_over_one = F.interpolate(
416
+ tmp_over_one.transpose(2, 1),
417
+ scale_factor=float(upp),
418
+ mode="linear",
419
+ align_corners=True,
420
+ ).transpose(2, 1)
421
+ rad_values = F.interpolate(
422
+ rad_values.transpose(2, 1), scale_factor=float(upp), mode="nearest"
423
+ ).transpose(
424
+ 2, 1
425
+ ) #######
426
+ tmp_over_one %= 1
427
+ tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
428
+ cumsum_shift = torch.zeros_like(rad_values)
429
+ cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
430
+ sine_waves = torch.sin(
431
+ torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * torch.pi
432
+ )
433
+ sine_waves = sine_waves * self.sine_amp
434
+ uv = self._f02uv(f0)
435
+ uv = F.interpolate(
436
+ uv.transpose(2, 1), scale_factor=float(upp), mode="nearest"
437
+ ).transpose(2, 1)
438
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
439
+ noise = noise_amp * torch.randn_like(sine_waves)
440
+ sine_waves = sine_waves * uv + noise
441
+ return sine_waves, uv, noise
442
+
443
+
444
+ class SourceModuleHnNSF(torch.nn.Module):
445
+ """SourceModule for hn-nsf
446
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
447
+ add_noise_std=0.003, voiced_threshod=0)
448
+ sampling_rate: sampling_rate in Hz
449
+ harmonic_num: number of harmonic above F0 (default: 0)
450
+ sine_amp: amplitude of sine source signal (default: 0.1)
451
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
452
+ note that amplitude of noise in unvoiced is decided
453
+ by sine_amp
454
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
455
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
456
+ F0_sampled (batchsize, length, 1)
457
+ Sine_source (batchsize, length, 1)
458
+ noise_source (batchsize, length 1)
459
+ uv (batchsize, length, 1)
460
+ """
461
+
462
+ def __init__(
463
+ self,
464
+ sampling_rate,
465
+ harmonic_num=0,
466
+ sine_amp=0.1,
467
+ add_noise_std=0.003,
468
+ voiced_threshod=0,
469
+ is_half=True,
470
+ ):
471
+ super(SourceModuleHnNSF, self).__init__()
472
+
473
+ self.sine_amp = sine_amp
474
+ self.noise_std = add_noise_std
475
+ self.is_half = is_half
476
+ # to produce sine waveforms
477
+ self.l_sin_gen = SineGen(
478
+ sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
479
+ )
480
+
481
+ # to merge source harmonics into a single excitation
482
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
483
+ self.l_tanh = torch.nn.Tanh()
484
+ # self.ddtype:int = -1
485
+
486
+ def forward(self, x: torch.Tensor, upp: int = 1):
487
+ # if self.ddtype ==-1:
488
+ # self.ddtype = self.l_linear.weight.dtype
489
+ sine_wavs, uv, _ = self.l_sin_gen(x, upp)
490
+ # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype)
491
+ # if self.is_half:
492
+ # sine_wavs = sine_wavs.half()
493
+ # sine_merge = self.l_tanh(self.l_linear(sine_wavs.to(x)))
494
+ # print(sine_wavs.dtype,self.ddtype)
495
+ # if sine_wavs.dtype != self.l_linear.weight.dtype:
496
+ sine_wavs = sine_wavs.to(dtype=self.l_linear.weight.dtype)
497
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
498
+ return sine_merge, None, None # noise, uv
499
+
500
+
501
+ class GeneratorNSF(torch.nn.Module):
502
+ def __init__(
503
+ self,
504
+ initial_channel,
505
+ resblock,
506
+ resblock_kernel_sizes,
507
+ resblock_dilation_sizes,
508
+ upsample_rates,
509
+ upsample_initial_channel,
510
+ upsample_kernel_sizes,
511
+ gin_channels,
512
+ sr,
513
+ is_half=False,
514
+ ):
515
+ super(GeneratorNSF, self).__init__()
516
+ self.num_kernels = len(resblock_kernel_sizes)
517
+ self.num_upsamples = len(upsample_rates)
518
+
519
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=math.prod(upsample_rates))
520
+ self.m_source = SourceModuleHnNSF(
521
+ sampling_rate=sr, harmonic_num=0, is_half=is_half
522
+ )
523
+ self.noise_convs = nn.ModuleList()
524
+ self.conv_pre = Conv1d(
525
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
526
+ )
527
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
528
+
529
+ self.ups = nn.ModuleList()
530
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
531
+ c_cur = upsample_initial_channel // (2 ** (i + 1))
532
+ self.ups.append(
533
+ weight_norm(
534
+ ConvTranspose1d(
535
+ upsample_initial_channel // (2**i),
536
+ upsample_initial_channel // (2 ** (i + 1)),
537
+ k,
538
+ u,
539
+ padding=(k - u) // 2,
540
+ )
541
+ )
542
+ )
543
+ if i + 1 < len(upsample_rates):
544
+ stride_f0 = math.prod(upsample_rates[i + 1 :])
545
+ self.noise_convs.append(
546
+ Conv1d(
547
+ 1,
548
+ c_cur,
549
+ kernel_size=stride_f0 * 2,
550
+ stride=stride_f0,
551
+ padding=stride_f0 // 2,
552
+ )
553
+ )
554
+ else:
555
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
556
+
557
+ self.resblocks = nn.ModuleList()
558
+ for i in range(len(self.ups)):
559
+ ch = upsample_initial_channel // (2 ** (i + 1))
560
+ for j, (k, d) in enumerate(
561
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
562
+ ):
563
+ self.resblocks.append(resblock(ch, k, d))
564
+
565
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
566
+ self.ups.apply(init_weights)
567
+
568
+ if gin_channels != 0:
569
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
570
+
571
+ self.upp = math.prod(upsample_rates)
572
+
573
+ self.lrelu_slope = modules.LRELU_SLOPE
574
+
575
+ def forward(self, x, f0, g: Optional[torch.Tensor] = None):
576
+ har_source, noi_source, uv = self.m_source(f0, self.upp)
577
+ har_source = har_source.transpose(1, 2)
578
+ x = self.conv_pre(x)
579
+ if g is not None:
580
+ x = x + self.cond(g)
581
+ # torch.jit.script() does not support direct indexing of torch modules
582
+ # That's why I wrote this
583
+ for i, (ups, noise_convs) in enumerate(zip(self.ups, self.noise_convs)):
584
+ if i < self.num_upsamples:
585
+ x = F.leaky_relu(x, self.lrelu_slope)
586
+ x = ups(x)
587
+ x_source = noise_convs(har_source)
588
+ x = x + x_source
589
+ xs: Optional[torch.Tensor] = None
590
+ l = [i * self.num_kernels + j for j in range(self.num_kernels)]
591
+ for j, resblock in enumerate(self.resblocks):
592
+ if j in l:
593
+ if xs is None:
594
+ xs = resblock(x)
595
+ else:
596
+ xs += resblock(x)
597
+ # This assertion cannot be ignored! \
598
+ # If ignored, it will cause torch.jit.script() compilation errors
599
+ assert isinstance(xs, torch.Tensor)
600
+ x = xs / self.num_kernels
601
+ x = F.leaky_relu(x)
602
+ x = self.conv_post(x)
603
+ x = torch.tanh(x)
604
+ return x
605
+
606
+ def remove_weight_norm(self):
607
+ for l in self.ups:
608
+ remove_weight_norm(l)
609
+ for l in self.resblocks:
610
+ l.remove_weight_norm()
611
+
612
+ def __prepare_scriptable__(self):
613
+ for l in self.ups:
614
+ for hook in l._forward_pre_hooks.values():
615
+ # The hook we want to remove is an instance of WeightNorm class, so
616
+ # normally we would do `if isinstance(...)` but this class is not accessible
617
+ # because of shadowing, so we check the module name directly.
618
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
619
+ if (
620
+ hook.__module__ == "torch.nn.utils.weight_norm"
621
+ and hook.__class__.__name__ == "WeightNorm"
622
+ ):
623
+ torch.nn.utils.remove_weight_norm(l)
624
+ for l in self.resblocks:
625
+ for hook in self.resblocks._forward_pre_hooks.values():
626
+ if (
627
+ hook.__module__ == "torch.nn.utils.weight_norm"
628
+ and hook.__class__.__name__ == "WeightNorm"
629
+ ):
630
+ torch.nn.utils.remove_weight_norm(l)
631
+ return self
632
+
633
+
634
+ sr2sr = {
635
+ "32k": 32000,
636
+ "40k": 40000,
637
+ "48k": 48000,
638
+ }
639
+
640
+
641
+ class SynthesizerTrnMs256NSFsid(nn.Module):
642
+ def __init__(
643
+ self,
644
+ spec_channels,
645
+ segment_size,
646
+ inter_channels,
647
+ hidden_channels,
648
+ filter_channels,
649
+ n_heads,
650
+ n_layers,
651
+ kernel_size,
652
+ p_dropout,
653
+ resblock,
654
+ resblock_kernel_sizes,
655
+ resblock_dilation_sizes,
656
+ upsample_rates,
657
+ upsample_initial_channel,
658
+ upsample_kernel_sizes,
659
+ spk_embed_dim,
660
+ gin_channels,
661
+ sr,
662
+ **kwargs
663
+ ):
664
+ super(SynthesizerTrnMs256NSFsid, self).__init__()
665
+ if isinstance(sr, str):
666
+ sr = sr2sr[sr]
667
+ self.spec_channels = spec_channels
668
+ self.inter_channels = inter_channels
669
+ self.hidden_channels = hidden_channels
670
+ self.filter_channels = filter_channels
671
+ self.n_heads = n_heads
672
+ self.n_layers = n_layers
673
+ self.kernel_size = kernel_size
674
+ self.p_dropout = float(p_dropout)
675
+ self.resblock = resblock
676
+ self.resblock_kernel_sizes = resblock_kernel_sizes
677
+ self.resblock_dilation_sizes = resblock_dilation_sizes
678
+ self.upsample_rates = upsample_rates
679
+ self.upsample_initial_channel = upsample_initial_channel
680
+ self.upsample_kernel_sizes = upsample_kernel_sizes
681
+ self.segment_size = segment_size
682
+ self.gin_channels = gin_channels
683
+ # self.hop_length = hop_length#
684
+ self.spk_embed_dim = spk_embed_dim
685
+ self.enc_p = TextEncoder256(
686
+ inter_channels,
687
+ hidden_channels,
688
+ filter_channels,
689
+ n_heads,
690
+ n_layers,
691
+ kernel_size,
692
+ float(p_dropout),
693
+ )
694
+ self.dec = GeneratorNSF(
695
+ inter_channels,
696
+ resblock,
697
+ resblock_kernel_sizes,
698
+ resblock_dilation_sizes,
699
+ upsample_rates,
700
+ upsample_initial_channel,
701
+ upsample_kernel_sizes,
702
+ gin_channels=gin_channels,
703
+ sr=sr,
704
+ is_half=kwargs["is_half"],
705
+ )
706
+ self.enc_q = PosteriorEncoder(
707
+ spec_channels,
708
+ inter_channels,
709
+ hidden_channels,
710
+ 5,
711
+ 1,
712
+ 16,
713
+ gin_channels=gin_channels,
714
+ )
715
+ self.flow = ResidualCouplingBlock(
716
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
717
+ )
718
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
719
+ logger.debug(
720
+ "gin_channels: "
721
+ + str(gin_channels)
722
+ + ", self.spk_embed_dim: "
723
+ + str(self.spk_embed_dim)
724
+ )
725
+
726
+ def remove_weight_norm(self):
727
+ self.dec.remove_weight_norm()
728
+ self.flow.remove_weight_norm()
729
+ if hasattr(self, "enc_q"):
730
+ self.enc_q.remove_weight_norm()
731
+
732
+ def __prepare_scriptable__(self):
733
+ for hook in self.dec._forward_pre_hooks.values():
734
+ # The hook we want to remove is an instance of WeightNorm class, so
735
+ # normally we would do `if isinstance(...)` but this class is not accessible
736
+ # because of shadowing, so we check the module name directly.
737
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
738
+ if (
739
+ hook.__module__ == "torch.nn.utils.weight_norm"
740
+ and hook.__class__.__name__ == "WeightNorm"
741
+ ):
742
+ torch.nn.utils.remove_weight_norm(self.dec)
743
+ for hook in self.flow._forward_pre_hooks.values():
744
+ if (
745
+ hook.__module__ == "torch.nn.utils.weight_norm"
746
+ and hook.__class__.__name__ == "WeightNorm"
747
+ ):
748
+ torch.nn.utils.remove_weight_norm(self.flow)
749
+ if hasattr(self, "enc_q"):
750
+ for hook in self.enc_q._forward_pre_hooks.values():
751
+ if (
752
+ hook.__module__ == "torch.nn.utils.weight_norm"
753
+ and hook.__class__.__name__ == "WeightNorm"
754
+ ):
755
+ torch.nn.utils.remove_weight_norm(self.enc_q)
756
+ return self
757
+
758
+ @torch.jit.ignore
759
+ def forward(
760
+ self,
761
+ phone: torch.Tensor,
762
+ phone_lengths: torch.Tensor,
763
+ pitch: torch.Tensor,
764
+ pitchf: torch.Tensor,
765
+ y: torch.Tensor,
766
+ y_lengths: torch.Tensor,
767
+ ds: Optional[torch.Tensor] = None,
768
+ ): # 这里ds是id,[bs,1]
769
+ # print(1,pitch.shape)#[bs,t]
770
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
771
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
772
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
773
+ z_p = self.flow(z, y_mask, g=g)
774
+ z_slice, ids_slice = commons.rand_slice_segments(
775
+ z, y_lengths, self.segment_size
776
+ )
777
+ # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
778
+ pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
779
+ # print(-2,pitchf.shape,z_slice.shape)
780
+ o = self.dec(z_slice, pitchf, g=g)
781
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
782
+
783
+ @torch.jit.export
784
+ def infer(
785
+ self,
786
+ phone: torch.Tensor,
787
+ phone_lengths: torch.Tensor,
788
+ pitch: torch.Tensor,
789
+ nsff0: torch.Tensor,
790
+ sid: torch.Tensor,
791
+ skip_head: Optional[torch.Tensor] = None,
792
+ return_length: Optional[torch.Tensor] = None,
793
+ ):
794
+ g = self.emb_g(sid).unsqueeze(-1)
795
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
796
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
797
+ if skip_head is not None and return_length is not None:
798
+ assert isinstance(skip_head, torch.Tensor)
799
+ assert isinstance(return_length, torch.Tensor)
800
+ head = int(skip_head.item())
801
+ length = int(return_length.item())
802
+ z_p = z_p[:, :, head : head + length]
803
+ x_mask = x_mask[:, :, head : head + length]
804
+ nsff0 = nsff0[:, head : head + length]
805
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
806
+ o = self.dec(z * x_mask, nsff0, g=g)
807
+ return o, x_mask, (z, z_p, m_p, logs_p)
808
+
809
+
810
+ class SynthesizerTrnMs768NSFsid(nn.Module):
811
+ def __init__(
812
+ self,
813
+ spec_channels,
814
+ segment_size,
815
+ inter_channels,
816
+ hidden_channels,
817
+ filter_channels,
818
+ n_heads,
819
+ n_layers,
820
+ kernel_size,
821
+ p_dropout,
822
+ resblock,
823
+ resblock_kernel_sizes,
824
+ resblock_dilation_sizes,
825
+ upsample_rates,
826
+ upsample_initial_channel,
827
+ upsample_kernel_sizes,
828
+ spk_embed_dim,
829
+ gin_channels,
830
+ sr,
831
+ **kwargs
832
+ ):
833
+ super(SynthesizerTrnMs768NSFsid, self).__init__()
834
+ if isinstance(sr, str):
835
+ sr = sr2sr[sr]
836
+ self.spec_channels = spec_channels
837
+ self.inter_channels = inter_channels
838
+ self.hidden_channels = hidden_channels
839
+ self.filter_channels = filter_channels
840
+ self.n_heads = n_heads
841
+ self.n_layers = n_layers
842
+ self.kernel_size = kernel_size
843
+ self.p_dropout = float(p_dropout)
844
+ self.resblock = resblock
845
+ self.resblock_kernel_sizes = resblock_kernel_sizes
846
+ self.resblock_dilation_sizes = resblock_dilation_sizes
847
+ self.upsample_rates = upsample_rates
848
+ self.upsample_initial_channel = upsample_initial_channel
849
+ self.upsample_kernel_sizes = upsample_kernel_sizes
850
+ self.segment_size = segment_size
851
+ self.gin_channels = gin_channels
852
+ # self.hop_length = hop_length#
853
+ self.spk_embed_dim = spk_embed_dim
854
+ self.enc_p = TextEncoder768(
855
+ inter_channels,
856
+ hidden_channels,
857
+ filter_channels,
858
+ n_heads,
859
+ n_layers,
860
+ kernel_size,
861
+ float(p_dropout),
862
+ )
863
+ self.dec = GeneratorNSF(
864
+ inter_channels,
865
+ resblock,
866
+ resblock_kernel_sizes,
867
+ resblock_dilation_sizes,
868
+ upsample_rates,
869
+ upsample_initial_channel,
870
+ upsample_kernel_sizes,
871
+ gin_channels=gin_channels,
872
+ sr=sr,
873
+ is_half=kwargs["is_half"],
874
+ )
875
+ self.enc_q = PosteriorEncoder(
876
+ spec_channels,
877
+ inter_channels,
878
+ hidden_channels,
879
+ 5,
880
+ 1,
881
+ 16,
882
+ gin_channels=gin_channels,
883
+ )
884
+ self.flow = ResidualCouplingBlock(
885
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
886
+ )
887
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
888
+ logger.debug(
889
+ "gin_channels: "
890
+ + str(gin_channels)
891
+ + ", self.spk_embed_dim: "
892
+ + str(self.spk_embed_dim)
893
+ )
894
+
895
+ def remove_weight_norm(self):
896
+ self.dec.remove_weight_norm()
897
+ self.flow.remove_weight_norm()
898
+ if hasattr(self, "enc_q"):
899
+ self.enc_q.remove_weight_norm()
900
+
901
+ def __prepare_scriptable__(self):
902
+ for hook in self.dec._forward_pre_hooks.values():
903
+ # The hook we want to remove is an instance of WeightNorm class, so
904
+ # normally we would do `if isinstance(...)` but this class is not accessible
905
+ # because of shadowing, so we check the module name directly.
906
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
907
+ if (
908
+ hook.__module__ == "torch.nn.utils.weight_norm"
909
+ and hook.__class__.__name__ == "WeightNorm"
910
+ ):
911
+ torch.nn.utils.remove_weight_norm(self.dec)
912
+ for hook in self.flow._forward_pre_hooks.values():
913
+ if (
914
+ hook.__module__ == "torch.nn.utils.weight_norm"
915
+ and hook.__class__.__name__ == "WeightNorm"
916
+ ):
917
+ torch.nn.utils.remove_weight_norm(self.flow)
918
+ if hasattr(self, "enc_q"):
919
+ for hook in self.enc_q._forward_pre_hooks.values():
920
+ if (
921
+ hook.__module__ == "torch.nn.utils.weight_norm"
922
+ and hook.__class__.__name__ == "WeightNorm"
923
+ ):
924
+ torch.nn.utils.remove_weight_norm(self.enc_q)
925
+ return self
926
+
927
+ @torch.jit.ignore
928
+ def forward(
929
+ self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
930
+ ): # 这里ds是id,[bs,1]
931
+ # print(1,pitch.shape)#[bs,t]
932
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
933
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
934
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
935
+ z_p = self.flow(z, y_mask, g=g)
936
+ z_slice, ids_slice = commons.rand_slice_segments(
937
+ z, y_lengths, self.segment_size
938
+ )
939
+ # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
940
+ pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
941
+ # print(-2,pitchf.shape,z_slice.shape)
942
+ o = self.dec(z_slice, pitchf, g=g)
943
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
944
+
945
+ @torch.jit.export
946
+ def infer(
947
+ self,
948
+ phone: torch.Tensor,
949
+ phone_lengths: torch.Tensor,
950
+ pitch: torch.Tensor,
951
+ nsff0: torch.Tensor,
952
+ sid: torch.Tensor,
953
+ skip_head: Optional[torch.Tensor] = None,
954
+ return_length: Optional[torch.Tensor] = None,
955
+ ):
956
+ g = self.emb_g(sid).unsqueeze(-1)
957
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
958
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
959
+ if skip_head is not None and return_length is not None:
960
+ assert isinstance(skip_head, torch.Tensor)
961
+ assert isinstance(return_length, torch.Tensor)
962
+ head = int(skip_head.item())
963
+ length = int(return_length.item())
964
+ z_p = z_p[:, :, head : head + length]
965
+ x_mask = x_mask[:, :, head : head + length]
966
+ nsff0 = nsff0[:, head : head + length]
967
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
968
+ o = self.dec(z * x_mask, nsff0, g=g)
969
+ return o, x_mask, (z, z_p, m_p, logs_p)
970
+
971
+
972
+ class SynthesizerTrnMs256NSFsid_nono(nn.Module):
973
+ def __init__(
974
+ self,
975
+ spec_channels,
976
+ segment_size,
977
+ inter_channels,
978
+ hidden_channels,
979
+ filter_channels,
980
+ n_heads,
981
+ n_layers,
982
+ kernel_size,
983
+ p_dropout,
984
+ resblock,
985
+ resblock_kernel_sizes,
986
+ resblock_dilation_sizes,
987
+ upsample_rates,
988
+ upsample_initial_channel,
989
+ upsample_kernel_sizes,
990
+ spk_embed_dim,
991
+ gin_channels,
992
+ sr=None,
993
+ **kwargs
994
+ ):
995
+ super(SynthesizerTrnMs256NSFsid_nono, self).__init__()
996
+ self.spec_channels = spec_channels
997
+ self.inter_channels = inter_channels
998
+ self.hidden_channels = hidden_channels
999
+ self.filter_channels = filter_channels
1000
+ self.n_heads = n_heads
1001
+ self.n_layers = n_layers
1002
+ self.kernel_size = kernel_size
1003
+ self.p_dropout = float(p_dropout)
1004
+ self.resblock = resblock
1005
+ self.resblock_kernel_sizes = resblock_kernel_sizes
1006
+ self.resblock_dilation_sizes = resblock_dilation_sizes
1007
+ self.upsample_rates = upsample_rates
1008
+ self.upsample_initial_channel = upsample_initial_channel
1009
+ self.upsample_kernel_sizes = upsample_kernel_sizes
1010
+ self.segment_size = segment_size
1011
+ self.gin_channels = gin_channels
1012
+ # self.hop_length = hop_length#
1013
+ self.spk_embed_dim = spk_embed_dim
1014
+ self.enc_p = TextEncoder256(
1015
+ inter_channels,
1016
+ hidden_channels,
1017
+ filter_channels,
1018
+ n_heads,
1019
+ n_layers,
1020
+ kernel_size,
1021
+ float(p_dropout),
1022
+ f0=False,
1023
+ )
1024
+ self.dec = Generator(
1025
+ inter_channels,
1026
+ resblock,
1027
+ resblock_kernel_sizes,
1028
+ resblock_dilation_sizes,
1029
+ upsample_rates,
1030
+ upsample_initial_channel,
1031
+ upsample_kernel_sizes,
1032
+ gin_channels=gin_channels,
1033
+ )
1034
+ self.enc_q = PosteriorEncoder(
1035
+ spec_channels,
1036
+ inter_channels,
1037
+ hidden_channels,
1038
+ 5,
1039
+ 1,
1040
+ 16,
1041
+ gin_channels=gin_channels,
1042
+ )
1043
+ self.flow = ResidualCouplingBlock(
1044
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
1045
+ )
1046
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
1047
+ logger.debug(
1048
+ "gin_channels: "
1049
+ + str(gin_channels)
1050
+ + ", self.spk_embed_dim: "
1051
+ + str(self.spk_embed_dim)
1052
+ )
1053
+
1054
+ def remove_weight_norm(self):
1055
+ self.dec.remove_weight_norm()
1056
+ self.flow.remove_weight_norm()
1057
+ if hasattr(self, "enc_q"):
1058
+ self.enc_q.remove_weight_norm()
1059
+
1060
+ def __prepare_scriptable__(self):
1061
+ for hook in self.dec._forward_pre_hooks.values():
1062
+ # The hook we want to remove is an instance of WeightNorm class, so
1063
+ # normally we would do `if isinstance(...)` but this class is not accessible
1064
+ # because of shadowing, so we check the module name directly.
1065
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
1066
+ if (
1067
+ hook.__module__ == "torch.nn.utils.weight_norm"
1068
+ and hook.__class__.__name__ == "WeightNorm"
1069
+ ):
1070
+ torch.nn.utils.remove_weight_norm(self.dec)
1071
+ for hook in self.flow._forward_pre_hooks.values():
1072
+ if (
1073
+ hook.__module__ == "torch.nn.utils.weight_norm"
1074
+ and hook.__class__.__name__ == "WeightNorm"
1075
+ ):
1076
+ torch.nn.utils.remove_weight_norm(self.flow)
1077
+ if hasattr(self, "enc_q"):
1078
+ for hook in self.enc_q._forward_pre_hooks.values():
1079
+ if (
1080
+ hook.__module__ == "torch.nn.utils.weight_norm"
1081
+ and hook.__class__.__name__ == "WeightNorm"
1082
+ ):
1083
+ torch.nn.utils.remove_weight_norm(self.enc_q)
1084
+ return self
1085
+
1086
+ @torch.jit.ignore
1087
+ def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
1088
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
1089
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
1090
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
1091
+ z_p = self.flow(z, y_mask, g=g)
1092
+ z_slice, ids_slice = commons.rand_slice_segments(
1093
+ z, y_lengths, self.segment_size
1094
+ )
1095
+ o = self.dec(z_slice, g=g)
1096
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
1097
+
1098
+ @torch.jit.export
1099
+ def infer(
1100
+ self,
1101
+ phone: torch.Tensor,
1102
+ phone_lengths: torch.Tensor,
1103
+ sid: torch.Tensor,
1104
+ skip_head: Optional[torch.Tensor] = None,
1105
+ return_length: Optional[torch.Tensor] = None,
1106
+ ):
1107
+ g = self.emb_g(sid).unsqueeze(-1)
1108
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
1109
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
1110
+ if skip_head is not None and return_length is not None:
1111
+ assert isinstance(skip_head, torch.Tensor)
1112
+ assert isinstance(return_length, torch.Tensor)
1113
+ head = int(skip_head.item())
1114
+ length = int(return_length.item())
1115
+ z_p = z_p[:, :, head : head + length]
1116
+ x_mask = x_mask[:, :, head : head + length]
1117
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
1118
+ o = self.dec(z * x_mask, g=g)
1119
+ return o, x_mask, (z, z_p, m_p, logs_p)
1120
+
1121
+
1122
+ class SynthesizerTrnMs768NSFsid_nono(nn.Module):
1123
+ def __init__(
1124
+ self,
1125
+ spec_channels,
1126
+ segment_size,
1127
+ inter_channels,
1128
+ hidden_channels,
1129
+ filter_channels,
1130
+ n_heads,
1131
+ n_layers,
1132
+ kernel_size,
1133
+ p_dropout,
1134
+ resblock,
1135
+ resblock_kernel_sizes,
1136
+ resblock_dilation_sizes,
1137
+ upsample_rates,
1138
+ upsample_initial_channel,
1139
+ upsample_kernel_sizes,
1140
+ spk_embed_dim,
1141
+ gin_channels,
1142
+ sr=None,
1143
+ **kwargs
1144
+ ):
1145
+ super(SynthesizerTrnMs768NSFsid_nono, self).__init__()
1146
+ self.spec_channels = spec_channels
1147
+ self.inter_channels = inter_channels
1148
+ self.hidden_channels = hidden_channels
1149
+ self.filter_channels = filter_channels
1150
+ self.n_heads = n_heads
1151
+ self.n_layers = n_layers
1152
+ self.kernel_size = kernel_size
1153
+ self.p_dropout = float(p_dropout)
1154
+ self.resblock = resblock
1155
+ self.resblock_kernel_sizes = resblock_kernel_sizes
1156
+ self.resblock_dilation_sizes = resblock_dilation_sizes
1157
+ self.upsample_rates = upsample_rates
1158
+ self.upsample_initial_channel = upsample_initial_channel
1159
+ self.upsample_kernel_sizes = upsample_kernel_sizes
1160
+ self.segment_size = segment_size
1161
+ self.gin_channels = gin_channels
1162
+ # self.hop_length = hop_length#
1163
+ self.spk_embed_dim = spk_embed_dim
1164
+ self.enc_p = TextEncoder768(
1165
+ inter_channels,
1166
+ hidden_channels,
1167
+ filter_channels,
1168
+ n_heads,
1169
+ n_layers,
1170
+ kernel_size,
1171
+ float(p_dropout),
1172
+ f0=False,
1173
+ )
1174
+ self.dec = Generator(
1175
+ inter_channels,
1176
+ resblock,
1177
+ resblock_kernel_sizes,
1178
+ resblock_dilation_sizes,
1179
+ upsample_rates,
1180
+ upsample_initial_channel,
1181
+ upsample_kernel_sizes,
1182
+ gin_channels=gin_channels,
1183
+ )
1184
+ self.enc_q = PosteriorEncoder(
1185
+ spec_channels,
1186
+ inter_channels,
1187
+ hidden_channels,
1188
+ 5,
1189
+ 1,
1190
+ 16,
1191
+ gin_channels=gin_channels,
1192
+ )
1193
+ self.flow = ResidualCouplingBlock(
1194
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
1195
+ )
1196
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
1197
+ logger.debug(
1198
+ "gin_channels: "
1199
+ + str(gin_channels)
1200
+ + ", self.spk_embed_dim: "
1201
+ + str(self.spk_embed_dim)
1202
+ )
1203
+
1204
+ def remove_weight_norm(self):
1205
+ self.dec.remove_weight_norm()
1206
+ self.flow.remove_weight_norm()
1207
+ if hasattr(self, "enc_q"):
1208
+ self.enc_q.remove_weight_norm()
1209
+
1210
+ def __prepare_scriptable__(self):
1211
+ for hook in self.dec._forward_pre_hooks.values():
1212
+ # The hook we want to remove is an instance of WeightNorm class, so
1213
+ # normally we would do `if isinstance(...)` but this class is not accessible
1214
+ # because of shadowing, so we check the module name directly.
1215
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
1216
+ if (
1217
+ hook.__module__ == "torch.nn.utils.weight_norm"
1218
+ and hook.__class__.__name__ == "WeightNorm"
1219
+ ):
1220
+ torch.nn.utils.remove_weight_norm(self.dec)
1221
+ for hook in self.flow._forward_pre_hooks.values():
1222
+ if (
1223
+ hook.__module__ == "torch.nn.utils.weight_norm"
1224
+ and hook.__class__.__name__ == "WeightNorm"
1225
+ ):
1226
+ torch.nn.utils.remove_weight_norm(self.flow)
1227
+ if hasattr(self, "enc_q"):
1228
+ for hook in self.enc_q._forward_pre_hooks.values():
1229
+ if (
1230
+ hook.__module__ == "torch.nn.utils.weight_norm"
1231
+ and hook.__class__.__name__ == "WeightNorm"
1232
+ ):
1233
+ torch.nn.utils.remove_weight_norm(self.enc_q)
1234
+ return self
1235
+
1236
+ @torch.jit.ignore
1237
+ def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
1238
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
1239
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
1240
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
1241
+ z_p = self.flow(z, y_mask, g=g)
1242
+ z_slice, ids_slice = commons.rand_slice_segments(
1243
+ z, y_lengths, self.segment_size
1244
+ )
1245
+ o = self.dec(z_slice, g=g)
1246
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
1247
+
1248
+ @torch.jit.export
1249
+ def infer(
1250
+ self,
1251
+ phone: torch.Tensor,
1252
+ phone_lengths: torch.Tensor,
1253
+ sid: torch.Tensor,
1254
+ skip_head: Optional[torch.Tensor] = None,
1255
+ return_length: Optional[torch.Tensor] = None,
1256
+ ):
1257
+ g = self.emb_g(sid).unsqueeze(-1)
1258
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
1259
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
1260
+ if skip_head is not None and return_length is not None:
1261
+ assert isinstance(skip_head, torch.Tensor)
1262
+ assert isinstance(return_length, torch.Tensor)
1263
+ head = int(skip_head.item())
1264
+ length = int(return_length.item())
1265
+ z_p = z_p[:, :, head : head + length]
1266
+ x_mask = x_mask[:, :, head : head + length]
1267
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
1268
+ o = self.dec(z * x_mask, g=g)
1269
+ return o, x_mask, (z, z_p, m_p, logs_p)
1270
+
1271
+
1272
+ class MultiPeriodDiscriminator(torch.nn.Module):
1273
+ def __init__(self, use_spectral_norm=False):
1274
+ super(MultiPeriodDiscriminator, self).__init__()
1275
+ periods = [2, 3, 5, 7, 11, 17]
1276
+ # periods = [3, 5, 7, 11, 17, 23, 37]
1277
+
1278
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1279
+ discs = discs + [
1280
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1281
+ ]
1282
+ self.discriminators = nn.ModuleList(discs)
1283
+
1284
+ def forward(self, y, y_hat):
1285
+ y_d_rs = [] #
1286
+ y_d_gs = []
1287
+ fmap_rs = []
1288
+ fmap_gs = []
1289
+ for i, d in enumerate(self.discriminators):
1290
+ y_d_r, fmap_r = d(y)
1291
+ y_d_g, fmap_g = d(y_hat)
1292
+ # for j in range(len(fmap_r)):
1293
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1294
+ y_d_rs.append(y_d_r)
1295
+ y_d_gs.append(y_d_g)
1296
+ fmap_rs.append(fmap_r)
1297
+ fmap_gs.append(fmap_g)
1298
+
1299
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1300
+
1301
+
1302
+ class MultiPeriodDiscriminatorV2(torch.nn.Module):
1303
+ def __init__(self, use_spectral_norm=False):
1304
+ super(MultiPeriodDiscriminatorV2, self).__init__()
1305
+ # periods = [2, 3, 5, 7, 11, 17]
1306
+ periods = [2, 3, 5, 7, 11, 17, 23, 37]
1307
+
1308
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1309
+ discs = discs + [
1310
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1311
+ ]
1312
+ self.discriminators = nn.ModuleList(discs)
1313
+
1314
+ def forward(self, y, y_hat):
1315
+ y_d_rs = [] #
1316
+ y_d_gs = []
1317
+ fmap_rs = []
1318
+ fmap_gs = []
1319
+ for i, d in enumerate(self.discriminators):
1320
+ y_d_r, fmap_r = d(y)
1321
+ y_d_g, fmap_g = d(y_hat)
1322
+ # for j in range(len(fmap_r)):
1323
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1324
+ y_d_rs.append(y_d_r)
1325
+ y_d_gs.append(y_d_g)
1326
+ fmap_rs.append(fmap_r)
1327
+ fmap_gs.append(fmap_g)
1328
+
1329
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1330
+
1331
+
1332
+ class DiscriminatorS(torch.nn.Module):
1333
+ def __init__(self, use_spectral_norm=False):
1334
+ super(DiscriminatorS, self).__init__()
1335
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1336
+ self.convs = nn.ModuleList(
1337
+ [
1338
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
1339
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
1340
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
1341
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
1342
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
1343
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
1344
+ ]
1345
+ )
1346
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
1347
+
1348
+ def forward(self, x):
1349
+ fmap = []
1350
+
1351
+ for l in self.convs:
1352
+ x = l(x)
1353
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1354
+ fmap.append(x)
1355
+ x = self.conv_post(x)
1356
+ fmap.append(x)
1357
+ x = torch.flatten(x, 1, -1)
1358
+
1359
+ return x, fmap
1360
+
1361
+
1362
+ class DiscriminatorP(torch.nn.Module):
1363
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
1364
+ super(DiscriminatorP, self).__init__()
1365
+ self.period = period
1366
+ self.use_spectral_norm = use_spectral_norm
1367
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1368
+ self.convs = nn.ModuleList(
1369
+ [
1370
+ norm_f(
1371
+ Conv2d(
1372
+ 1,
1373
+ 32,
1374
+ (kernel_size, 1),
1375
+ (stride, 1),
1376
+ padding=(get_padding(kernel_size, 1), 0),
1377
+ )
1378
+ ),
1379
+ norm_f(
1380
+ Conv2d(
1381
+ 32,
1382
+ 128,
1383
+ (kernel_size, 1),
1384
+ (stride, 1),
1385
+ padding=(get_padding(kernel_size, 1), 0),
1386
+ )
1387
+ ),
1388
+ norm_f(
1389
+ Conv2d(
1390
+ 128,
1391
+ 512,
1392
+ (kernel_size, 1),
1393
+ (stride, 1),
1394
+ padding=(get_padding(kernel_size, 1), 0),
1395
+ )
1396
+ ),
1397
+ norm_f(
1398
+ Conv2d(
1399
+ 512,
1400
+ 1024,
1401
+ (kernel_size, 1),
1402
+ (stride, 1),
1403
+ padding=(get_padding(kernel_size, 1), 0),
1404
+ )
1405
+ ),
1406
+ norm_f(
1407
+ Conv2d(
1408
+ 1024,
1409
+ 1024,
1410
+ (kernel_size, 1),
1411
+ 1,
1412
+ padding=(get_padding(kernel_size, 1), 0),
1413
+ )
1414
+ ),
1415
+ ]
1416
+ )
1417
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
1418
+
1419
+ def forward(self, x):
1420
+ fmap = []
1421
+
1422
+ # 1d to 2d
1423
+ b, c, t = x.shape
1424
+ if t % self.period != 0: # pad first
1425
+ n_pad = self.period - (t % self.period)
1426
+ if has_xpu and x.dtype == torch.bfloat16:
1427
+ x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(
1428
+ dtype=torch.bfloat16
1429
+ )
1430
+ else:
1431
+ x = F.pad(x, (0, n_pad), "reflect")
1432
+ t = t + n_pad
1433
+ x = x.view(b, c, t // self.period, self.period)
1434
+
1435
+ for l in self.convs:
1436
+ x = l(x)
1437
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1438
+ fmap.append(x)
1439
+ x = self.conv_post(x)
1440
+ fmap.append(x)
1441
+ x = torch.flatten(x, 1, -1)
1442
+
1443
+ return x, fmap
infer/lib/infer_pack/models_onnx.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 AvgPool1d, 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 infer.lib.infer_pack import attentions, commons, modules
14
+ from infer.lib.infer_pack.commons import get_padding, init_weights
15
+
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
+ return uv
319
+
320
+ def forward(self, f0, upp):
321
+ """sine_tensor, uv = forward(f0)
322
+ input F0: tensor(batchsize=1, length, dim=1)
323
+ f0 for unvoiced steps should be 0
324
+ output sine_tensor: tensor(batchsize=1, length, dim)
325
+ output uv: tensor(batchsize=1, length, 1)
326
+ """
327
+ with torch.no_grad():
328
+ f0 = f0[:, None].transpose(1, 2)
329
+ f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
330
+ # fundamental component
331
+ f0_buf[:, :, 0] = f0[:, :, 0]
332
+ for idx in np.arange(self.harmonic_num):
333
+ f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
334
+ idx + 2
335
+ ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
336
+ rad_values = (
337
+ f0_buf / self.sampling_rate
338
+ ) % 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(
345
+ rad_values, 1
346
+ ) # % 1 #####%1意味着后面的cumsum无法再优化
347
+ tmp_over_one *= upp
348
+ tmp_over_one = F.interpolate(
349
+ tmp_over_one.transpose(2, 1),
350
+ scale_factor=upp,
351
+ mode="linear",
352
+ align_corners=True,
353
+ ).transpose(2, 1)
354
+ rad_values = F.interpolate(
355
+ rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
356
+ ).transpose(
357
+ 2, 1
358
+ ) #######
359
+ tmp_over_one %= 1
360
+ tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
361
+ cumsum_shift = torch.zeros_like(rad_values)
362
+ cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
363
+ sine_waves = torch.sin(
364
+ torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
365
+ )
366
+ sine_waves = sine_waves * self.sine_amp
367
+ uv = self._f02uv(f0)
368
+ uv = F.interpolate(
369
+ uv.transpose(2, 1), scale_factor=upp, mode="nearest"
370
+ ).transpose(2, 1)
371
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
372
+ noise = noise_amp * torch.randn_like(sine_waves)
373
+ sine_waves = sine_waves * uv + noise
374
+ return sine_waves, uv, noise
375
+
376
+
377
+ class SourceModuleHnNSF(torch.nn.Module):
378
+ """SourceModule for hn-nsf
379
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
380
+ add_noise_std=0.003, voiced_threshod=0)
381
+ sampling_rate: sampling_rate in Hz
382
+ harmonic_num: number of harmonic above F0 (default: 0)
383
+ sine_amp: amplitude of sine source signal (default: 0.1)
384
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
385
+ note that amplitude of noise in unvoiced is decided
386
+ by sine_amp
387
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
388
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
389
+ F0_sampled (batchsize, length, 1)
390
+ Sine_source (batchsize, length, 1)
391
+ noise_source (batchsize, length 1)
392
+ uv (batchsize, length, 1)
393
+ """
394
+
395
+ def __init__(
396
+ self,
397
+ sampling_rate,
398
+ harmonic_num=0,
399
+ sine_amp=0.1,
400
+ add_noise_std=0.003,
401
+ voiced_threshod=0,
402
+ is_half=True,
403
+ ):
404
+ super(SourceModuleHnNSF, self).__init__()
405
+
406
+ self.sine_amp = sine_amp
407
+ self.noise_std = add_noise_std
408
+ self.is_half = is_half
409
+ # to produce sine waveforms
410
+ self.l_sin_gen = SineGen(
411
+ sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
412
+ )
413
+
414
+ # to merge source harmonics into a single excitation
415
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
416
+ self.l_tanh = torch.nn.Tanh()
417
+
418
+ def forward(self, x, upp=None):
419
+ sine_wavs, uv, _ = self.l_sin_gen(x, upp)
420
+ if self.is_half:
421
+ sine_wavs = sine_wavs.half()
422
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
423
+ return sine_merge, None, None # noise, uv
424
+
425
+
426
+ class GeneratorNSF(torch.nn.Module):
427
+ def __init__(
428
+ self,
429
+ initial_channel,
430
+ resblock,
431
+ resblock_kernel_sizes,
432
+ resblock_dilation_sizes,
433
+ upsample_rates,
434
+ upsample_initial_channel,
435
+ upsample_kernel_sizes,
436
+ gin_channels,
437
+ sr,
438
+ is_half=False,
439
+ ):
440
+ super(GeneratorNSF, self).__init__()
441
+ self.num_kernels = len(resblock_kernel_sizes)
442
+ self.num_upsamples = len(upsample_rates)
443
+
444
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
445
+ self.m_source = SourceModuleHnNSF(
446
+ sampling_rate=sr, harmonic_num=0, is_half=is_half
447
+ )
448
+ self.noise_convs = nn.ModuleList()
449
+ self.conv_pre = Conv1d(
450
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
451
+ )
452
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
453
+
454
+ self.ups = nn.ModuleList()
455
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
456
+ c_cur = upsample_initial_channel // (2 ** (i + 1))
457
+ self.ups.append(
458
+ weight_norm(
459
+ ConvTranspose1d(
460
+ upsample_initial_channel // (2**i),
461
+ upsample_initial_channel // (2 ** (i + 1)),
462
+ k,
463
+ u,
464
+ padding=(k - u) // 2,
465
+ )
466
+ )
467
+ )
468
+ if i + 1 < len(upsample_rates):
469
+ stride_f0 = np.prod(upsample_rates[i + 1 :])
470
+ self.noise_convs.append(
471
+ Conv1d(
472
+ 1,
473
+ c_cur,
474
+ kernel_size=stride_f0 * 2,
475
+ stride=stride_f0,
476
+ padding=stride_f0 // 2,
477
+ )
478
+ )
479
+ else:
480
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
481
+
482
+ self.resblocks = nn.ModuleList()
483
+ for i in range(len(self.ups)):
484
+ ch = upsample_initial_channel // (2 ** (i + 1))
485
+ for j, (k, d) in enumerate(
486
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
487
+ ):
488
+ self.resblocks.append(resblock(ch, k, d))
489
+
490
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
491
+ self.ups.apply(init_weights)
492
+
493
+ if gin_channels != 0:
494
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
495
+
496
+ self.upp = np.prod(upsample_rates)
497
+
498
+ def forward(self, x, f0, g=None):
499
+ har_source, noi_source, uv = self.m_source(f0, self.upp)
500
+ har_source = har_source.transpose(1, 2)
501
+ x = self.conv_pre(x)
502
+ if g is not None:
503
+ x = x + self.cond(g)
504
+
505
+ for i in range(self.num_upsamples):
506
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
507
+ x = self.ups[i](x)
508
+ x_source = self.noise_convs[i](har_source)
509
+ x = x + x_source
510
+ xs = None
511
+ for j in range(self.num_kernels):
512
+ if xs is None:
513
+ xs = self.resblocks[i * self.num_kernels + j](x)
514
+ else:
515
+ xs += self.resblocks[i * self.num_kernels + j](x)
516
+ x = xs / self.num_kernels
517
+ x = F.leaky_relu(x)
518
+ x = self.conv_post(x)
519
+ x = torch.tanh(x)
520
+ return x
521
+
522
+ def remove_weight_norm(self):
523
+ for l in self.ups:
524
+ remove_weight_norm(l)
525
+ for l in self.resblocks:
526
+ l.remove_weight_norm()
527
+
528
+
529
+ sr2sr = {
530
+ "32k": 32000,
531
+ "40k": 40000,
532
+ "48k": 48000,
533
+ }
534
+
535
+
536
+ class SynthesizerTrnMsNSFsidM(nn.Module):
537
+ def __init__(
538
+ self,
539
+ spec_channels,
540
+ segment_size,
541
+ inter_channels,
542
+ hidden_channels,
543
+ filter_channels,
544
+ n_heads,
545
+ n_layers,
546
+ kernel_size,
547
+ p_dropout,
548
+ resblock,
549
+ resblock_kernel_sizes,
550
+ resblock_dilation_sizes,
551
+ upsample_rates,
552
+ upsample_initial_channel,
553
+ upsample_kernel_sizes,
554
+ spk_embed_dim,
555
+ gin_channels,
556
+ sr,
557
+ version,
558
+ **kwargs,
559
+ ):
560
+ super().__init__()
561
+ if type(sr) == type("strr"):
562
+ sr = sr2sr[sr]
563
+ self.spec_channels = spec_channels
564
+ self.inter_channels = inter_channels
565
+ self.hidden_channels = hidden_channels
566
+ self.filter_channels = filter_channels
567
+ self.n_heads = n_heads
568
+ self.n_layers = n_layers
569
+ self.kernel_size = kernel_size
570
+ self.p_dropout = p_dropout
571
+ self.resblock = resblock
572
+ self.resblock_kernel_sizes = resblock_kernel_sizes
573
+ self.resblock_dilation_sizes = resblock_dilation_sizes
574
+ self.upsample_rates = upsample_rates
575
+ self.upsample_initial_channel = upsample_initial_channel
576
+ self.upsample_kernel_sizes = upsample_kernel_sizes
577
+ self.segment_size = segment_size
578
+ self.gin_channels = gin_channels
579
+ # self.hop_length = hop_length#
580
+ self.spk_embed_dim = spk_embed_dim
581
+ if version == "v1":
582
+ self.enc_p = TextEncoder256(
583
+ inter_channels,
584
+ hidden_channels,
585
+ filter_channels,
586
+ n_heads,
587
+ n_layers,
588
+ kernel_size,
589
+ p_dropout,
590
+ )
591
+ else:
592
+ self.enc_p = TextEncoder768(
593
+ inter_channels,
594
+ hidden_channels,
595
+ filter_channels,
596
+ n_heads,
597
+ n_layers,
598
+ kernel_size,
599
+ p_dropout,
600
+ )
601
+ self.dec = GeneratorNSF(
602
+ inter_channels,
603
+ resblock,
604
+ resblock_kernel_sizes,
605
+ resblock_dilation_sizes,
606
+ upsample_rates,
607
+ upsample_initial_channel,
608
+ upsample_kernel_sizes,
609
+ gin_channels=gin_channels,
610
+ sr=sr,
611
+ is_half=kwargs["is_half"],
612
+ )
613
+ self.enc_q = PosteriorEncoder(
614
+ spec_channels,
615
+ inter_channels,
616
+ hidden_channels,
617
+ 5,
618
+ 1,
619
+ 16,
620
+ gin_channels=gin_channels,
621
+ )
622
+ self.flow = ResidualCouplingBlock(
623
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
624
+ )
625
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
626
+ self.speaker_map = None
627
+ logger.debug(
628
+ f"gin_channels: {gin_channels}, self.spk_embed_dim: {self.spk_embed_dim}"
629
+ )
630
+
631
+ def remove_weight_norm(self):
632
+ self.dec.remove_weight_norm()
633
+ self.flow.remove_weight_norm()
634
+ self.enc_q.remove_weight_norm()
635
+
636
+ def construct_spkmixmap(self, n_speaker):
637
+ self.speaker_map = torch.zeros((n_speaker, 1, 1, self.gin_channels))
638
+ for i in range(n_speaker):
639
+ self.speaker_map[i] = self.emb_g(torch.LongTensor([[i]]))
640
+ self.speaker_map = self.speaker_map.unsqueeze(0)
641
+
642
+ def forward(self, phone, phone_lengths, pitch, nsff0, g, rnd, max_len=None):
643
+ if self.speaker_map is not None: # [N, S] * [S, B, 1, H]
644
+ g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
645
+ g = g * self.speaker_map # [N, S, B, 1, H]
646
+ g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
647
+ g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
648
+ else:
649
+ g = g.unsqueeze(0)
650
+ g = self.emb_g(g).transpose(1, 2)
651
+
652
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
653
+ z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask
654
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
655
+ o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
656
+ return o
657
+
658
+
659
+ class MultiPeriodDiscriminator(torch.nn.Module):
660
+ def __init__(self, use_spectral_norm=False):
661
+ super(MultiPeriodDiscriminator, self).__init__()
662
+ periods = [2, 3, 5, 7, 11, 17]
663
+ # periods = [3, 5, 7, 11, 17, 23, 37]
664
+
665
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
666
+ discs = discs + [
667
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
668
+ ]
669
+ self.discriminators = nn.ModuleList(discs)
670
+
671
+ def forward(self, y, y_hat):
672
+ y_d_rs = [] #
673
+ y_d_gs = []
674
+ fmap_rs = []
675
+ fmap_gs = []
676
+ for i, d in enumerate(self.discriminators):
677
+ y_d_r, fmap_r = d(y)
678
+ y_d_g, fmap_g = d(y_hat)
679
+ # for j in range(len(fmap_r)):
680
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
681
+ y_d_rs.append(y_d_r)
682
+ y_d_gs.append(y_d_g)
683
+ fmap_rs.append(fmap_r)
684
+ fmap_gs.append(fmap_g)
685
+
686
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
687
+
688
+
689
+ class MultiPeriodDiscriminatorV2(torch.nn.Module):
690
+ def __init__(self, use_spectral_norm=False):
691
+ super(MultiPeriodDiscriminatorV2, self).__init__()
692
+ # periods = [2, 3, 5, 7, 11, 17]
693
+ periods = [2, 3, 5, 7, 11, 17, 23, 37]
694
+
695
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
696
+ discs = discs + [
697
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
698
+ ]
699
+ self.discriminators = nn.ModuleList(discs)
700
+
701
+ def forward(self, y, y_hat):
702
+ y_d_rs = [] #
703
+ y_d_gs = []
704
+ fmap_rs = []
705
+ fmap_gs = []
706
+ for i, d in enumerate(self.discriminators):
707
+ y_d_r, fmap_r = d(y)
708
+ y_d_g, fmap_g = d(y_hat)
709
+ # for j in range(len(fmap_r)):
710
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
711
+ y_d_rs.append(y_d_r)
712
+ y_d_gs.append(y_d_g)
713
+ fmap_rs.append(fmap_r)
714
+ fmap_gs.append(fmap_g)
715
+
716
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
717
+
718
+
719
+ class DiscriminatorS(torch.nn.Module):
720
+ def __init__(self, use_spectral_norm=False):
721
+ super(DiscriminatorS, self).__init__()
722
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
723
+ self.convs = nn.ModuleList(
724
+ [
725
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
726
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
727
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
728
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
729
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
730
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
731
+ ]
732
+ )
733
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
734
+
735
+ def forward(self, x):
736
+ fmap = []
737
+
738
+ for l in self.convs:
739
+ x = l(x)
740
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
741
+ fmap.append(x)
742
+ x = self.conv_post(x)
743
+ fmap.append(x)
744
+ x = torch.flatten(x, 1, -1)
745
+
746
+ return x, fmap
747
+
748
+
749
+ class DiscriminatorP(torch.nn.Module):
750
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
751
+ super(DiscriminatorP, self).__init__()
752
+ self.period = period
753
+ self.use_spectral_norm = use_spectral_norm
754
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
755
+ self.convs = nn.ModuleList(
756
+ [
757
+ norm_f(
758
+ Conv2d(
759
+ 1,
760
+ 32,
761
+ (kernel_size, 1),
762
+ (stride, 1),
763
+ padding=(get_padding(kernel_size, 1), 0),
764
+ )
765
+ ),
766
+ norm_f(
767
+ Conv2d(
768
+ 32,
769
+ 128,
770
+ (kernel_size, 1),
771
+ (stride, 1),
772
+ padding=(get_padding(kernel_size, 1), 0),
773
+ )
774
+ ),
775
+ norm_f(
776
+ Conv2d(
777
+ 128,
778
+ 512,
779
+ (kernel_size, 1),
780
+ (stride, 1),
781
+ padding=(get_padding(kernel_size, 1), 0),
782
+ )
783
+ ),
784
+ norm_f(
785
+ Conv2d(
786
+ 512,
787
+ 1024,
788
+ (kernel_size, 1),
789
+ (stride, 1),
790
+ padding=(get_padding(kernel_size, 1), 0),
791
+ )
792
+ ),
793
+ norm_f(
794
+ Conv2d(
795
+ 1024,
796
+ 1024,
797
+ (kernel_size, 1),
798
+ 1,
799
+ padding=(get_padding(kernel_size, 1), 0),
800
+ )
801
+ ),
802
+ ]
803
+ )
804
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
805
+
806
+ def forward(self, x):
807
+ fmap = []
808
+
809
+ # 1d to 2d
810
+ b, c, t = x.shape
811
+ if t % self.period != 0: # pad first
812
+ n_pad = self.period - (t % self.period)
813
+ x = F.pad(x, (0, n_pad), "reflect")
814
+ t = t + n_pad
815
+ x = x.view(b, c, t // self.period, self.period)
816
+
817
+ for l in self.convs:
818
+ x = l(x)
819
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
820
+ fmap.append(x)
821
+ x = self.conv_post(x)
822
+ fmap.append(x)
823
+ x = torch.flatten(x, 1, -1)
824
+
825
+ return x, fmap
infer/lib/infer_pack/modules.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ from typing import Optional, Tuple
4
+
5
+ import numpy as np
6
+ import scipy
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
10
+ from torch.nn import functional as F
11
+ from torch.nn.utils import remove_weight_norm, weight_norm
12
+
13
+ from infer.lib.infer_pack import commons
14
+ from infer.lib.infer_pack.commons import get_padding, init_weights
15
+ from infer.lib.infer_pack.transforms import piecewise_rational_quadratic_transform
16
+
17
+ LRELU_SLOPE = 0.1
18
+
19
+
20
+ class LayerNorm(nn.Module):
21
+ def __init__(self, channels, eps=1e-5):
22
+ super(LayerNorm, self).__init__()
23
+ self.channels = channels
24
+ self.eps = eps
25
+
26
+ self.gamma = nn.Parameter(torch.ones(channels))
27
+ self.beta = nn.Parameter(torch.zeros(channels))
28
+
29
+ def forward(self, x):
30
+ x = x.transpose(1, -1)
31
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
32
+ return x.transpose(1, -1)
33
+
34
+
35
+ class ConvReluNorm(nn.Module):
36
+ def __init__(
37
+ self,
38
+ in_channels,
39
+ hidden_channels,
40
+ out_channels,
41
+ kernel_size,
42
+ n_layers,
43
+ p_dropout,
44
+ ):
45
+ super(ConvReluNorm, self).__init__()
46
+ self.in_channels = in_channels
47
+ self.hidden_channels = hidden_channels
48
+ self.out_channels = out_channels
49
+ self.kernel_size = kernel_size
50
+ self.n_layers = n_layers
51
+ self.p_dropout = float(p_dropout)
52
+ assert n_layers > 1, "Number of layers should be larger than 0."
53
+
54
+ self.conv_layers = nn.ModuleList()
55
+ self.norm_layers = nn.ModuleList()
56
+ self.conv_layers.append(
57
+ nn.Conv1d(
58
+ in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
59
+ )
60
+ )
61
+ self.norm_layers.append(LayerNorm(hidden_channels))
62
+ self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(float(p_dropout)))
63
+ for _ in range(n_layers - 1):
64
+ self.conv_layers.append(
65
+ nn.Conv1d(
66
+ hidden_channels,
67
+ hidden_channels,
68
+ kernel_size,
69
+ padding=kernel_size // 2,
70
+ )
71
+ )
72
+ self.norm_layers.append(LayerNorm(hidden_channels))
73
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
74
+ self.proj.weight.data.zero_()
75
+ self.proj.bias.data.zero_()
76
+
77
+ def forward(self, x, x_mask):
78
+ x_org = x
79
+ for i in range(self.n_layers):
80
+ x = self.conv_layers[i](x * x_mask)
81
+ x = self.norm_layers[i](x)
82
+ x = self.relu_drop(x)
83
+ x = x_org + self.proj(x)
84
+ return x * x_mask
85
+
86
+
87
+ class DDSConv(nn.Module):
88
+ """
89
+ Dialted and Depth-Separable Convolution
90
+ """
91
+
92
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
93
+ super(DDSConv, self).__init__()
94
+ self.channels = channels
95
+ self.kernel_size = kernel_size
96
+ self.n_layers = n_layers
97
+ self.p_dropout = float(p_dropout)
98
+
99
+ self.drop = nn.Dropout(float(p_dropout))
100
+ self.convs_sep = nn.ModuleList()
101
+ self.convs_1x1 = nn.ModuleList()
102
+ self.norms_1 = nn.ModuleList()
103
+ self.norms_2 = nn.ModuleList()
104
+ for i in range(n_layers):
105
+ dilation = kernel_size**i
106
+ padding = (kernel_size * dilation - dilation) // 2
107
+ self.convs_sep.append(
108
+ nn.Conv1d(
109
+ channels,
110
+ channels,
111
+ kernel_size,
112
+ groups=channels,
113
+ dilation=dilation,
114
+ padding=padding,
115
+ )
116
+ )
117
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
118
+ self.norms_1.append(LayerNorm(channels))
119
+ self.norms_2.append(LayerNorm(channels))
120
+
121
+ def forward(self, x, x_mask, g: Optional[torch.Tensor] = None):
122
+ if g is not None:
123
+ x = x + g
124
+ for i in range(self.n_layers):
125
+ y = self.convs_sep[i](x * x_mask)
126
+ y = self.norms_1[i](y)
127
+ y = F.gelu(y)
128
+ y = self.convs_1x1[i](y)
129
+ y = self.norms_2[i](y)
130
+ y = F.gelu(y)
131
+ y = self.drop(y)
132
+ x = x + y
133
+ return x * x_mask
134
+
135
+
136
+ class WN(torch.nn.Module):
137
+ def __init__(
138
+ self,
139
+ hidden_channels,
140
+ kernel_size,
141
+ dilation_rate,
142
+ n_layers,
143
+ gin_channels=0,
144
+ p_dropout=0,
145
+ ):
146
+ super(WN, self).__init__()
147
+ assert kernel_size % 2 == 1
148
+ self.hidden_channels = hidden_channels
149
+ self.kernel_size = (kernel_size,)
150
+ self.dilation_rate = dilation_rate
151
+ self.n_layers = n_layers
152
+ self.gin_channels = gin_channels
153
+ self.p_dropout = float(p_dropout)
154
+
155
+ self.in_layers = torch.nn.ModuleList()
156
+ self.res_skip_layers = torch.nn.ModuleList()
157
+ self.drop = nn.Dropout(float(p_dropout))
158
+
159
+ if gin_channels != 0:
160
+ cond_layer = torch.nn.Conv1d(
161
+ gin_channels, 2 * hidden_channels * n_layers, 1
162
+ )
163
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
164
+
165
+ for i in range(n_layers):
166
+ dilation = dilation_rate**i
167
+ padding = int((kernel_size * dilation - dilation) / 2)
168
+ in_layer = torch.nn.Conv1d(
169
+ hidden_channels,
170
+ 2 * hidden_channels,
171
+ kernel_size,
172
+ dilation=dilation,
173
+ padding=padding,
174
+ )
175
+ in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
176
+ self.in_layers.append(in_layer)
177
+
178
+ # last one is not necessary
179
+ if i < n_layers - 1:
180
+ res_skip_channels = 2 * hidden_channels
181
+ else:
182
+ res_skip_channels = hidden_channels
183
+
184
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
185
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
186
+ self.res_skip_layers.append(res_skip_layer)
187
+
188
+ def forward(
189
+ self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None
190
+ ):
191
+ output = torch.zeros_like(x)
192
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
193
+
194
+ if g is not None:
195
+ g = self.cond_layer(g)
196
+
197
+ for i, (in_layer, res_skip_layer) in enumerate(
198
+ zip(self.in_layers, self.res_skip_layers)
199
+ ):
200
+ x_in = in_layer(x)
201
+ if g is not None:
202
+ cond_offset = i * 2 * self.hidden_channels
203
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
204
+ else:
205
+ g_l = torch.zeros_like(x_in)
206
+
207
+ acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
208
+ acts = self.drop(acts)
209
+
210
+ res_skip_acts = res_skip_layer(acts)
211
+ if i < self.n_layers - 1:
212
+ res_acts = res_skip_acts[:, : self.hidden_channels, :]
213
+ x = (x + res_acts) * x_mask
214
+ output = output + res_skip_acts[:, self.hidden_channels :, :]
215
+ else:
216
+ output = output + res_skip_acts
217
+ return output * x_mask
218
+
219
+ def remove_weight_norm(self):
220
+ if self.gin_channels != 0:
221
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
222
+ for l in self.in_layers:
223
+ torch.nn.utils.remove_weight_norm(l)
224
+ for l in self.res_skip_layers:
225
+ torch.nn.utils.remove_weight_norm(l)
226
+
227
+ def __prepare_scriptable__(self):
228
+ if self.gin_channels != 0:
229
+ for hook in self.cond_layer._forward_pre_hooks.values():
230
+ if (
231
+ hook.__module__ == "torch.nn.utils.weight_norm"
232
+ and hook.__class__.__name__ == "WeightNorm"
233
+ ):
234
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
235
+ for l in self.in_layers:
236
+ for hook in l._forward_pre_hooks.values():
237
+ if (
238
+ hook.__module__ == "torch.nn.utils.weight_norm"
239
+ and hook.__class__.__name__ == "WeightNorm"
240
+ ):
241
+ torch.nn.utils.remove_weight_norm(l)
242
+ for l in self.res_skip_layers:
243
+ for hook in l._forward_pre_hooks.values():
244
+ if (
245
+ hook.__module__ == "torch.nn.utils.weight_norm"
246
+ and hook.__class__.__name__ == "WeightNorm"
247
+ ):
248
+ torch.nn.utils.remove_weight_norm(l)
249
+ return self
250
+
251
+
252
+ class ResBlock1(torch.nn.Module):
253
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
254
+ super(ResBlock1, self).__init__()
255
+ self.convs1 = nn.ModuleList(
256
+ [
257
+ weight_norm(
258
+ Conv1d(
259
+ channels,
260
+ channels,
261
+ kernel_size,
262
+ 1,
263
+ dilation=dilation[0],
264
+ padding=get_padding(kernel_size, dilation[0]),
265
+ )
266
+ ),
267
+ weight_norm(
268
+ Conv1d(
269
+ channels,
270
+ channels,
271
+ kernel_size,
272
+ 1,
273
+ dilation=dilation[1],
274
+ padding=get_padding(kernel_size, dilation[1]),
275
+ )
276
+ ),
277
+ weight_norm(
278
+ Conv1d(
279
+ channels,
280
+ channels,
281
+ kernel_size,
282
+ 1,
283
+ dilation=dilation[2],
284
+ padding=get_padding(kernel_size, dilation[2]),
285
+ )
286
+ ),
287
+ ]
288
+ )
289
+ self.convs1.apply(init_weights)
290
+
291
+ self.convs2 = nn.ModuleList(
292
+ [
293
+ weight_norm(
294
+ Conv1d(
295
+ channels,
296
+ channels,
297
+ kernel_size,
298
+ 1,
299
+ dilation=1,
300
+ padding=get_padding(kernel_size, 1),
301
+ )
302
+ ),
303
+ weight_norm(
304
+ Conv1d(
305
+ channels,
306
+ channels,
307
+ kernel_size,
308
+ 1,
309
+ dilation=1,
310
+ padding=get_padding(kernel_size, 1),
311
+ )
312
+ ),
313
+ weight_norm(
314
+ Conv1d(
315
+ channels,
316
+ channels,
317
+ kernel_size,
318
+ 1,
319
+ dilation=1,
320
+ padding=get_padding(kernel_size, 1),
321
+ )
322
+ ),
323
+ ]
324
+ )
325
+ self.convs2.apply(init_weights)
326
+ self.lrelu_slope = LRELU_SLOPE
327
+
328
+ def forward(self, x: torch.Tensor, x_mask: Optional[torch.Tensor] = None):
329
+ for c1, c2 in zip(self.convs1, self.convs2):
330
+ xt = F.leaky_relu(x, self.lrelu_slope)
331
+ if x_mask is not None:
332
+ xt = xt * x_mask
333
+ xt = c1(xt)
334
+ xt = F.leaky_relu(xt, self.lrelu_slope)
335
+ if x_mask is not None:
336
+ xt = xt * x_mask
337
+ xt = c2(xt)
338
+ x = xt + x
339
+ if x_mask is not None:
340
+ x = x * x_mask
341
+ return x
342
+
343
+ def remove_weight_norm(self):
344
+ for l in self.convs1:
345
+ remove_weight_norm(l)
346
+ for l in self.convs2:
347
+ remove_weight_norm(l)
348
+
349
+ def __prepare_scriptable__(self):
350
+ for l in self.convs1:
351
+ for hook in l._forward_pre_hooks.values():
352
+ if (
353
+ hook.__module__ == "torch.nn.utils.weight_norm"
354
+ and hook.__class__.__name__ == "WeightNorm"
355
+ ):
356
+ torch.nn.utils.remove_weight_norm(l)
357
+ for l in self.convs2:
358
+ for hook in l._forward_pre_hooks.values():
359
+ if (
360
+ hook.__module__ == "torch.nn.utils.weight_norm"
361
+ and hook.__class__.__name__ == "WeightNorm"
362
+ ):
363
+ torch.nn.utils.remove_weight_norm(l)
364
+ return self
365
+
366
+
367
+ class ResBlock2(torch.nn.Module):
368
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
369
+ super(ResBlock2, self).__init__()
370
+ self.convs = nn.ModuleList(
371
+ [
372
+ weight_norm(
373
+ Conv1d(
374
+ channels,
375
+ channels,
376
+ kernel_size,
377
+ 1,
378
+ dilation=dilation[0],
379
+ padding=get_padding(kernel_size, dilation[0]),
380
+ )
381
+ ),
382
+ weight_norm(
383
+ Conv1d(
384
+ channels,
385
+ channels,
386
+ kernel_size,
387
+ 1,
388
+ dilation=dilation[1],
389
+ padding=get_padding(kernel_size, dilation[1]),
390
+ )
391
+ ),
392
+ ]
393
+ )
394
+ self.convs.apply(init_weights)
395
+ self.lrelu_slope = LRELU_SLOPE
396
+
397
+ def forward(self, x, x_mask: Optional[torch.Tensor] = None):
398
+ for c in self.convs:
399
+ xt = F.leaky_relu(x, self.lrelu_slope)
400
+ if x_mask is not None:
401
+ xt = xt * x_mask
402
+ xt = c(xt)
403
+ x = xt + x
404
+ if x_mask is not None:
405
+ x = x * x_mask
406
+ return x
407
+
408
+ def remove_weight_norm(self):
409
+ for l in self.convs:
410
+ remove_weight_norm(l)
411
+
412
+ def __prepare_scriptable__(self):
413
+ for l in self.convs:
414
+ for hook in l._forward_pre_hooks.values():
415
+ if (
416
+ hook.__module__ == "torch.nn.utils.weight_norm"
417
+ and hook.__class__.__name__ == "WeightNorm"
418
+ ):
419
+ torch.nn.utils.remove_weight_norm(l)
420
+ return self
421
+
422
+
423
+ class Log(nn.Module):
424
+ def forward(
425
+ self,
426
+ x: torch.Tensor,
427
+ x_mask: torch.Tensor,
428
+ g: Optional[torch.Tensor] = None,
429
+ reverse: bool = False,
430
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
431
+ if not reverse:
432
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
433
+ logdet = torch.sum(-y, [1, 2])
434
+ return y, logdet
435
+ else:
436
+ x = torch.exp(x) * x_mask
437
+ return x
438
+
439
+
440
+ class Flip(nn.Module):
441
+ # torch.jit.script() Compiled functions \
442
+ # can't take variable number of arguments or \
443
+ # use keyword-only arguments with defaults
444
+ def forward(
445
+ self,
446
+ x: torch.Tensor,
447
+ x_mask: torch.Tensor,
448
+ g: Optional[torch.Tensor] = None,
449
+ reverse: bool = False,
450
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
451
+ x = torch.flip(x, [1])
452
+ if not reverse:
453
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
454
+ return x, logdet
455
+ else:
456
+ return x, torch.zeros([1], device=x.device)
457
+
458
+
459
+ class ElementwiseAffine(nn.Module):
460
+ def __init__(self, channels):
461
+ super(ElementwiseAffine, self).__init__()
462
+ self.channels = channels
463
+ self.m = nn.Parameter(torch.zeros(channels, 1))
464
+ self.logs = nn.Parameter(torch.zeros(channels, 1))
465
+
466
+ def forward(self, x, x_mask, reverse=False, **kwargs):
467
+ if not reverse:
468
+ y = self.m + torch.exp(self.logs) * x
469
+ y = y * x_mask
470
+ logdet = torch.sum(self.logs * x_mask, [1, 2])
471
+ return y, logdet
472
+ else:
473
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
474
+ return x
475
+
476
+
477
+ class ResidualCouplingLayer(nn.Module):
478
+ def __init__(
479
+ self,
480
+ channels,
481
+ hidden_channels,
482
+ kernel_size,
483
+ dilation_rate,
484
+ n_layers,
485
+ p_dropout=0,
486
+ gin_channels=0,
487
+ mean_only=False,
488
+ ):
489
+ assert channels % 2 == 0, "channels should be divisible by 2"
490
+ super(ResidualCouplingLayer, self).__init__()
491
+ self.channels = channels
492
+ self.hidden_channels = hidden_channels
493
+ self.kernel_size = kernel_size
494
+ self.dilation_rate = dilation_rate
495
+ self.n_layers = n_layers
496
+ self.half_channels = channels // 2
497
+ self.mean_only = mean_only
498
+
499
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
500
+ self.enc = WN(
501
+ hidden_channels,
502
+ kernel_size,
503
+ dilation_rate,
504
+ n_layers,
505
+ p_dropout=float(p_dropout),
506
+ gin_channels=gin_channels,
507
+ )
508
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
509
+ self.post.weight.data.zero_()
510
+ self.post.bias.data.zero_()
511
+
512
+ def forward(
513
+ self,
514
+ x: torch.Tensor,
515
+ x_mask: torch.Tensor,
516
+ g: Optional[torch.Tensor] = None,
517
+ reverse: bool = False,
518
+ ):
519
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
520
+ h = self.pre(x0) * x_mask
521
+ h = self.enc(h, x_mask, g=g)
522
+ stats = self.post(h) * x_mask
523
+ if not self.mean_only:
524
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
525
+ else:
526
+ m = stats
527
+ logs = torch.zeros_like(m)
528
+
529
+ if not reverse:
530
+ x1 = m + x1 * torch.exp(logs) * x_mask
531
+ x = torch.cat([x0, x1], 1)
532
+ logdet = torch.sum(logs, [1, 2])
533
+ return x, logdet
534
+ else:
535
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
536
+ x = torch.cat([x0, x1], 1)
537
+ return x, torch.zeros([1])
538
+
539
+ def remove_weight_norm(self):
540
+ self.enc.remove_weight_norm()
541
+
542
+ def __prepare_scriptable__(self):
543
+ for hook in self.enc._forward_pre_hooks.values():
544
+ if (
545
+ hook.__module__ == "torch.nn.utils.weight_norm"
546
+ and hook.__class__.__name__ == "WeightNorm"
547
+ ):
548
+ torch.nn.utils.remove_weight_norm(self.enc)
549
+ return self
550
+
551
+
552
+ class ConvFlow(nn.Module):
553
+ def __init__(
554
+ self,
555
+ in_channels,
556
+ filter_channels,
557
+ kernel_size,
558
+ n_layers,
559
+ num_bins=10,
560
+ tail_bound=5.0,
561
+ ):
562
+ super(ConvFlow, self).__init__()
563
+ self.in_channels = in_channels
564
+ self.filter_channels = filter_channels
565
+ self.kernel_size = kernel_size
566
+ self.n_layers = n_layers
567
+ self.num_bins = num_bins
568
+ self.tail_bound = tail_bound
569
+ self.half_channels = in_channels // 2
570
+
571
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
572
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
573
+ self.proj = nn.Conv1d(
574
+ filter_channels, self.half_channels * (num_bins * 3 - 1), 1
575
+ )
576
+ self.proj.weight.data.zero_()
577
+ self.proj.bias.data.zero_()
578
+
579
+ def forward(
580
+ self,
581
+ x: torch.Tensor,
582
+ x_mask: torch.Tensor,
583
+ g: Optional[torch.Tensor] = None,
584
+ reverse=False,
585
+ ):
586
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
587
+ h = self.pre(x0)
588
+ h = self.convs(h, x_mask, g=g)
589
+ h = self.proj(h) * x_mask
590
+
591
+ b, c, t = x0.shape
592
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
593
+
594
+ unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
595
+ unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
596
+ self.filter_channels
597
+ )
598
+ unnormalized_derivatives = h[..., 2 * self.num_bins :]
599
+
600
+ x1, logabsdet = piecewise_rational_quadratic_transform(
601
+ x1,
602
+ unnormalized_widths,
603
+ unnormalized_heights,
604
+ unnormalized_derivatives,
605
+ inverse=reverse,
606
+ tails="linear",
607
+ tail_bound=self.tail_bound,
608
+ )
609
+
610
+ x = torch.cat([x0, x1], 1) * x_mask
611
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
612
+ if not reverse:
613
+ return x, logdet
614
+ else:
615
+ return x
infer/lib/infer_pack/modules/F0Predictor/DioF0Predictor.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pyworld
3
+
4
+ from infer.lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
5
+
6
+
7
+ class DioF0Predictor(F0Predictor):
8
+ def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
9
+ self.hop_length = hop_length
10
+ self.f0_min = f0_min
11
+ self.f0_max = f0_max
12
+ self.sampling_rate = sampling_rate
13
+
14
+ def interpolate_f0(self, f0):
15
+ """
16
+ 对F0进行插值处理
17
+ """
18
+
19
+ data = np.reshape(f0, (f0.size, 1))
20
+
21
+ vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
22
+ vuv_vector[data > 0.0] = 1.0
23
+ vuv_vector[data <= 0.0] = 0.0
24
+
25
+ ip_data = data
26
+
27
+ frame_number = data.size
28
+ last_value = 0.0
29
+ for i in range(frame_number):
30
+ if data[i] <= 0.0:
31
+ j = i + 1
32
+ for j in range(i + 1, frame_number):
33
+ if data[j] > 0.0:
34
+ break
35
+ if j < frame_number - 1:
36
+ if last_value > 0.0:
37
+ step = (data[j] - data[i - 1]) / float(j - i)
38
+ for k in range(i, j):
39
+ ip_data[k] = data[i - 1] + step * (k - i + 1)
40
+ else:
41
+ for k in range(i, j):
42
+ ip_data[k] = data[j]
43
+ else:
44
+ for k in range(i, frame_number):
45
+ ip_data[k] = last_value
46
+ else:
47
+ ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
48
+ last_value = data[i]
49
+
50
+ return ip_data[:, 0], vuv_vector[:, 0]
51
+
52
+ def resize_f0(self, x, target_len):
53
+ source = np.array(x)
54
+ source[source < 0.001] = np.nan
55
+ target = np.interp(
56
+ np.arange(0, len(source) * target_len, len(source)) / target_len,
57
+ np.arange(0, len(source)),
58
+ source,
59
+ )
60
+ res = np.nan_to_num(target)
61
+ return res
62
+
63
+ def compute_f0(self, wav, p_len=None):
64
+ if p_len is None:
65
+ p_len = wav.shape[0] // self.hop_length
66
+ f0, t = pyworld.dio(
67
+ wav.astype(np.double),
68
+ fs=self.sampling_rate,
69
+ f0_floor=self.f0_min,
70
+ f0_ceil=self.f0_max,
71
+ frame_period=1000 * self.hop_length / self.sampling_rate,
72
+ )
73
+ f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
74
+ for index, pitch in enumerate(f0):
75
+ f0[index] = round(pitch, 1)
76
+ return self.interpolate_f0(self.resize_f0(f0, p_len))[0]
77
+
78
+ def compute_f0_uv(self, wav, p_len=None):
79
+ if p_len is None:
80
+ p_len = wav.shape[0] // self.hop_length
81
+ f0, t = pyworld.dio(
82
+ wav.astype(np.double),
83
+ fs=self.sampling_rate,
84
+ f0_floor=self.f0_min,
85
+ f0_ceil=self.f0_max,
86
+ frame_period=1000 * self.hop_length / self.sampling_rate,
87
+ )
88
+ f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
89
+ for index, pitch in enumerate(f0):
90
+ f0[index] = round(pitch, 1)
91
+ return self.interpolate_f0(self.resize_f0(f0, p_len))
infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class F0Predictor(object):
2
+ def compute_f0(self, wav, p_len):
3
+ """
4
+ input: wav:[signal_length]
5
+ p_len:int
6
+ output: f0:[signal_length//hop_length]
7
+ """
8
+ pass
9
+
10
+ def compute_f0_uv(self, wav, p_len):
11
+ """
12
+ input: wav:[signal_length]
13
+ p_len:int
14
+ output: f0:[signal_length//hop_length],uv:[signal_length//hop_length]
15
+ """
16
+ pass
infer/lib/infer_pack/modules/F0Predictor/HarvestF0Predictor.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pyworld
3
+
4
+ from infer.lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
5
+
6
+
7
+ class HarvestF0Predictor(F0Predictor):
8
+ def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
9
+ self.hop_length = hop_length
10
+ self.f0_min = f0_min
11
+ self.f0_max = f0_max
12
+ self.sampling_rate = sampling_rate
13
+
14
+ def interpolate_f0(self, f0):
15
+ """
16
+ 对F0进行插值处理
17
+ """
18
+
19
+ data = np.reshape(f0, (f0.size, 1))
20
+
21
+ vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
22
+ vuv_vector[data > 0.0] = 1.0
23
+ vuv_vector[data <= 0.0] = 0.0
24
+
25
+ ip_data = data
26
+
27
+ frame_number = data.size
28
+ last_value = 0.0
29
+ for i in range(frame_number):
30
+ if data[i] <= 0.0:
31
+ j = i + 1
32
+ for j in range(i + 1, frame_number):
33
+ if data[j] > 0.0:
34
+ break
35
+ if j < frame_number - 1:
36
+ if last_value > 0.0:
37
+ step = (data[j] - data[i - 1]) / float(j - i)
38
+ for k in range(i, j):
39
+ ip_data[k] = data[i - 1] + step * (k - i + 1)
40
+ else:
41
+ for k in range(i, j):
42
+ ip_data[k] = data[j]
43
+ else:
44
+ for k in range(i, frame_number):
45
+ ip_data[k] = last_value
46
+ else:
47
+ ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
48
+ last_value = data[i]
49
+
50
+ return ip_data[:, 0], vuv_vector[:, 0]
51
+
52
+ def resize_f0(self, x, target_len):
53
+ source = np.array(x)
54
+ source[source < 0.001] = np.nan
55
+ target = np.interp(
56
+ np.arange(0, len(source) * target_len, len(source)) / target_len,
57
+ np.arange(0, len(source)),
58
+ source,
59
+ )
60
+ res = np.nan_to_num(target)
61
+ return res
62
+
63
+ def compute_f0(self, wav, p_len=None):
64
+ if p_len is None:
65
+ p_len = wav.shape[0] // self.hop_length
66
+ f0, t = pyworld.harvest(
67
+ wav.astype(np.double),
68
+ fs=self.sampling_rate,
69
+ f0_ceil=self.f0_max,
70
+ f0_floor=self.f0_min,
71
+ frame_period=1000 * self.hop_length / self.sampling_rate,
72
+ )
73
+ f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.fs)
74
+ return self.interpolate_f0(self.resize_f0(f0, p_len))[0]
75
+
76
+ def compute_f0_uv(self, wav, p_len=None):
77
+ if p_len is None:
78
+ p_len = wav.shape[0] // self.hop_length
79
+ f0, t = pyworld.harvest(
80
+ wav.astype(np.double),
81
+ fs=self.sampling_rate,
82
+ f0_floor=self.f0_min,
83
+ f0_ceil=self.f0_max,
84
+ frame_period=1000 * self.hop_length / self.sampling_rate,
85
+ )
86
+ f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
87
+ return self.interpolate_f0(self.resize_f0(f0, p_len))
infer/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import parselmouth
3
+
4
+ from infer.lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
5
+
6
+
7
+ class PMF0Predictor(F0Predictor):
8
+ def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
9
+ self.hop_length = hop_length
10
+ self.f0_min = f0_min
11
+ self.f0_max = f0_max
12
+ self.sampling_rate = sampling_rate
13
+
14
+ def interpolate_f0(self, f0):
15
+ """
16
+ 对F0进行插值处理
17
+ """
18
+
19
+ data = np.reshape(f0, (f0.size, 1))
20
+
21
+ vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
22
+ vuv_vector[data > 0.0] = 1.0
23
+ vuv_vector[data <= 0.0] = 0.0
24
+
25
+ ip_data = data
26
+
27
+ frame_number = data.size
28
+ last_value = 0.0
29
+ for i in range(frame_number):
30
+ if data[i] <= 0.0:
31
+ j = i + 1
32
+ for j in range(i + 1, frame_number):
33
+ if data[j] > 0.0:
34
+ break
35
+ if j < frame_number - 1:
36
+ if last_value > 0.0:
37
+ step = (data[j] - data[i - 1]) / float(j - i)
38
+ for k in range(i, j):
39
+ ip_data[k] = data[i - 1] + step * (k - i + 1)
40
+ else:
41
+ for k in range(i, j):
42
+ ip_data[k] = data[j]
43
+ else:
44
+ for k in range(i, frame_number):
45
+ ip_data[k] = last_value
46
+ else:
47
+ ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
48
+ last_value = data[i]
49
+
50
+ return ip_data[:, 0], vuv_vector[:, 0]
51
+
52
+ def compute_f0(self, wav, p_len=None):
53
+ x = wav
54
+ if p_len is None:
55
+ p_len = x.shape[0] // self.hop_length
56
+ else:
57
+ assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
58
+ time_step = self.hop_length / self.sampling_rate * 1000
59
+ f0 = (
60
+ parselmouth.Sound(x, self.sampling_rate)
61
+ .to_pitch_ac(
62
+ time_step=time_step / 1000,
63
+ voicing_threshold=0.6,
64
+ pitch_floor=self.f0_min,
65
+ pitch_ceiling=self.f0_max,
66
+ )
67
+ .selected_array["frequency"]
68
+ )
69
+
70
+ pad_size = (p_len - len(f0) + 1) // 2
71
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
72
+ f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant")
73
+ f0, uv = self.interpolate_f0(f0)
74
+ return f0
75
+
76
+ def compute_f0_uv(self, wav, p_len=None):
77
+ x = wav
78
+ if p_len is None:
79
+ p_len = x.shape[0] // self.hop_length
80
+ else:
81
+ assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
82
+ time_step = self.hop_length / self.sampling_rate * 1000
83
+ f0 = (
84
+ parselmouth.Sound(x, self.sampling_rate)
85
+ .to_pitch_ac(
86
+ time_step=time_step / 1000,
87
+ voicing_threshold=0.6,
88
+ pitch_floor=self.f0_min,
89
+ pitch_ceiling=self.f0_max,
90
+ )
91
+ .selected_array["frequency"]
92
+ )
93
+
94
+ pad_size = (p_len - len(f0) + 1) // 2
95
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
96
+ f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant")
97
+ f0, uv = self.interpolate_f0(f0)
98
+ return f0, uv
infer/lib/infer_pack/modules/F0Predictor/__init__.py ADDED
File without changes
infer/lib/infer_pack/onnx_inference.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import librosa
2
+ import numpy as np
3
+ import onnxruntime
4
+ import soundfile
5
+
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class ContentVec:
12
+ def __init__(self, vec_path="pretrained/vec-768-layer-12.onnx", device=None):
13
+ logger.info("Load model(s) from {}".format(vec_path))
14
+ if device == "cpu" or device is None:
15
+ providers = ["CPUExecutionProvider"]
16
+ elif device == "cuda":
17
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
18
+ elif device == "dml":
19
+ providers = ["DmlExecutionProvider"]
20
+ else:
21
+ raise RuntimeError("Unsportted Device")
22
+ self.model = onnxruntime.InferenceSession(vec_path, providers=providers)
23
+
24
+ def __call__(self, wav):
25
+ return self.forward(wav)
26
+
27
+ def forward(self, wav):
28
+ feats = wav
29
+ if feats.ndim == 2: # double channels
30
+ feats = feats.mean(-1)
31
+ assert feats.ndim == 1, feats.ndim
32
+ feats = np.expand_dims(np.expand_dims(feats, 0), 0)
33
+ onnx_input = {self.model.get_inputs()[0].name: feats}
34
+ logits = self.model.run(None, onnx_input)[0]
35
+ return logits.transpose(0, 2, 1)
36
+
37
+
38
+ def get_f0_predictor(f0_predictor, hop_length, sampling_rate, **kargs):
39
+ if f0_predictor == "pm":
40
+ from lib.infer_pack.modules.F0Predictor.PMF0Predictor import PMF0Predictor
41
+
42
+ f0_predictor_object = PMF0Predictor(
43
+ hop_length=hop_length, sampling_rate=sampling_rate
44
+ )
45
+ elif f0_predictor == "harvest":
46
+ from lib.infer_pack.modules.F0Predictor.HarvestF0Predictor import (
47
+ HarvestF0Predictor,
48
+ )
49
+
50
+ f0_predictor_object = HarvestF0Predictor(
51
+ hop_length=hop_length, sampling_rate=sampling_rate
52
+ )
53
+ elif f0_predictor == "dio":
54
+ from lib.infer_pack.modules.F0Predictor.DioF0Predictor import DioF0Predictor
55
+
56
+ f0_predictor_object = DioF0Predictor(
57
+ hop_length=hop_length, sampling_rate=sampling_rate
58
+ )
59
+ else:
60
+ raise Exception("Unknown f0 predictor")
61
+ return f0_predictor_object
62
+
63
+
64
+ class OnnxRVC:
65
+ def __init__(
66
+ self,
67
+ model_path,
68
+ sr=40000,
69
+ hop_size=512,
70
+ vec_path="vec-768-layer-12",
71
+ device="cpu",
72
+ ):
73
+ vec_path = f"pretrained/{vec_path}.onnx"
74
+ self.vec_model = ContentVec(vec_path, device)
75
+ if device == "cpu" or device is None:
76
+ providers = ["CPUExecutionProvider"]
77
+ elif device == "cuda":
78
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
79
+ elif device == "dml":
80
+ providers = ["DmlExecutionProvider"]
81
+ else:
82
+ raise RuntimeError("Unsportted Device")
83
+ self.model = onnxruntime.InferenceSession(model_path, providers=providers)
84
+ self.sampling_rate = sr
85
+ self.hop_size = hop_size
86
+
87
+ def forward(self, hubert, hubert_length, pitch, pitchf, ds, rnd):
88
+ onnx_input = {
89
+ self.model.get_inputs()[0].name: hubert,
90
+ self.model.get_inputs()[1].name: hubert_length,
91
+ self.model.get_inputs()[2].name: pitch,
92
+ self.model.get_inputs()[3].name: pitchf,
93
+ self.model.get_inputs()[4].name: ds,
94
+ self.model.get_inputs()[5].name: rnd,
95
+ }
96
+ return (self.model.run(None, onnx_input)[0] * 32767).astype(np.int16)
97
+
98
+ def inference(
99
+ self,
100
+ raw_path,
101
+ sid,
102
+ f0_method="dio",
103
+ f0_up_key=0,
104
+ pad_time=0.5,
105
+ cr_threshold=0.02,
106
+ ):
107
+ f0_min = 50
108
+ f0_max = 1100
109
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
110
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
111
+ f0_predictor = get_f0_predictor(
112
+ f0_method,
113
+ hop_length=self.hop_size,
114
+ sampling_rate=self.sampling_rate,
115
+ threshold=cr_threshold,
116
+ )
117
+ wav, sr = librosa.load(raw_path, sr=self.sampling_rate)
118
+ org_length = len(wav)
119
+ if org_length / sr > 50.0:
120
+ raise RuntimeError("Reached Max Length")
121
+
122
+ wav16k = librosa.resample(wav, orig_sr=self.sampling_rate, target_sr=16000)
123
+ wav16k = wav16k
124
+
125
+ hubert = self.vec_model(wav16k)
126
+ hubert = np.repeat(hubert, 2, axis=2).transpose(0, 2, 1).astype(np.float32)
127
+ hubert_length = hubert.shape[1]
128
+
129
+ pitchf = f0_predictor.compute_f0(wav, hubert_length)
130
+ pitchf = pitchf * 2 ** (f0_up_key / 12)
131
+ pitch = pitchf.copy()
132
+ f0_mel = 1127 * np.log(1 + pitch / 700)
133
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
134
+ f0_mel_max - f0_mel_min
135
+ ) + 1
136
+ f0_mel[f0_mel <= 1] = 1
137
+ f0_mel[f0_mel > 255] = 255
138
+ pitch = np.rint(f0_mel).astype(np.int64)
139
+
140
+ pitchf = pitchf.reshape(1, len(pitchf)).astype(np.float32)
141
+ pitch = pitch.reshape(1, len(pitch))
142
+ ds = np.array([sid]).astype(np.int64)
143
+
144
+ rnd = np.random.randn(1, 192, hubert_length).astype(np.float32)
145
+ hubert_length = np.array([hubert_length]).astype(np.int64)
146
+
147
+ out_wav = self.forward(hubert, hubert_length, pitch, pitchf, ds, rnd).squeeze()
148
+ out_wav = np.pad(out_wav, (0, 2 * self.hop_size), "constant")
149
+ return out_wav[0:org_length]
infer/lib/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
infer/lib/jit/__init__.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import pickle
3
+ import time
4
+ import torch
5
+ from tqdm import tqdm
6
+ from collections import OrderedDict
7
+
8
+
9
+ def load_inputs(path, device, is_half=False):
10
+ parm = torch.load(path, map_location=torch.device("cpu"))
11
+ for key in parm.keys():
12
+ parm[key] = parm[key].to(device)
13
+ if is_half and parm[key].dtype == torch.float32:
14
+ parm[key] = parm[key].half()
15
+ elif not is_half and parm[key].dtype == torch.float16:
16
+ parm[key] = parm[key].float()
17
+ return parm
18
+
19
+
20
+ def benchmark(
21
+ model, inputs_path, device=torch.device("cpu"), epoch=1000, is_half=False
22
+ ):
23
+ parm = load_inputs(inputs_path, device, is_half)
24
+ total_ts = 0.0
25
+ bar = tqdm(range(epoch))
26
+ for i in bar:
27
+ start_time = time.perf_counter()
28
+ o = model(**parm)
29
+ total_ts += time.perf_counter() - start_time
30
+ print(f"num_epoch: {epoch} | avg time(ms): {(total_ts*1000)/epoch}")
31
+
32
+
33
+ def jit_warm_up(model, inputs_path, device=torch.device("cpu"), epoch=5, is_half=False):
34
+ benchmark(model, inputs_path, device, epoch=epoch, is_half=is_half)
35
+
36
+
37
+ def to_jit_model(
38
+ model_path,
39
+ model_type: str,
40
+ mode: str = "trace",
41
+ inputs_path: str = None,
42
+ device=torch.device("cpu"),
43
+ is_half=False,
44
+ ):
45
+ model = None
46
+ if model_type.lower() == "synthesizer":
47
+ from .get_synthesizer import get_synthesizer
48
+
49
+ model, _ = get_synthesizer(model_path, device)
50
+ model.forward = model.infer
51
+ elif model_type.lower() == "rmvpe":
52
+ from .get_rmvpe import get_rmvpe
53
+
54
+ model = get_rmvpe(model_path, device)
55
+ elif model_type.lower() == "hubert":
56
+ from .get_hubert import get_hubert_model
57
+
58
+ model = get_hubert_model(model_path, device)
59
+ model.forward = model.infer
60
+ else:
61
+ raise ValueError(f"No model type named {model_type}")
62
+ model = model.eval()
63
+ model = model.half() if is_half else model.float()
64
+ if mode == "trace":
65
+ assert not inputs_path
66
+ inputs = load_inputs(inputs_path, device, is_half)
67
+ model_jit = torch.jit.trace(model, example_kwarg_inputs=inputs)
68
+ elif mode == "script":
69
+ model_jit = torch.jit.script(model)
70
+ model_jit.to(device)
71
+ model_jit = model_jit.half() if is_half else model_jit.float()
72
+ # model = model.half() if is_half else model.float()
73
+ return (model, model_jit)
74
+
75
+
76
+ def export(
77
+ model: torch.nn.Module,
78
+ mode: str = "trace",
79
+ inputs: dict = None,
80
+ device=torch.device("cpu"),
81
+ is_half: bool = False,
82
+ ) -> dict:
83
+ model = model.half() if is_half else model.float()
84
+ model.eval()
85
+ if mode == "trace":
86
+ assert inputs is not None
87
+ model_jit = torch.jit.trace(model, example_kwarg_inputs=inputs)
88
+ elif mode == "script":
89
+ model_jit = torch.jit.script(model)
90
+ model_jit.to(device)
91
+ model_jit = model_jit.half() if is_half else model_jit.float()
92
+ buffer = BytesIO()
93
+ # model_jit=model_jit.cpu()
94
+ torch.jit.save(model_jit, buffer)
95
+ del model_jit
96
+ cpt = OrderedDict()
97
+ cpt["model"] = buffer.getvalue()
98
+ cpt["is_half"] = is_half
99
+ return cpt
100
+
101
+
102
+ def load(path: str):
103
+ with open(path, "rb") as f:
104
+ return pickle.load(f)
105
+
106
+
107
+ def save(ckpt: dict, save_path: str):
108
+ with open(save_path, "wb") as f:
109
+ pickle.dump(ckpt, f)
110
+
111
+
112
+ def rmvpe_jit_export(
113
+ model_path: str,
114
+ mode: str = "script",
115
+ inputs_path: str = None,
116
+ save_path: str = None,
117
+ device=torch.device("cpu"),
118
+ is_half=False,
119
+ ):
120
+ if not save_path:
121
+ save_path = model_path.rstrip(".pth")
122
+ save_path += ".half.jit" if is_half else ".jit"
123
+ if "cuda" in str(device) and ":" not in str(device):
124
+ device = torch.device("cuda:0")
125
+ from .get_rmvpe import get_rmvpe
126
+
127
+ model = get_rmvpe(model_path, device)
128
+ inputs = None
129
+ if mode == "trace":
130
+ inputs = load_inputs(inputs_path, device, is_half)
131
+ ckpt = export(model, mode, inputs, device, is_half)
132
+ ckpt["device"] = str(device)
133
+ save(ckpt, save_path)
134
+ return ckpt
135
+
136
+
137
+ def synthesizer_jit_export(
138
+ model_path: str,
139
+ mode: str = "script",
140
+ inputs_path: str = None,
141
+ save_path: str = None,
142
+ device=torch.device("cpu"),
143
+ is_half=False,
144
+ ):
145
+ if not save_path:
146
+ save_path = model_path.rstrip(".pth")
147
+ save_path += ".half.jit" if is_half else ".jit"
148
+ if "cuda" in str(device) and ":" not in str(device):
149
+ device = torch.device("cuda:0")
150
+ from .get_synthesizer import get_synthesizer
151
+
152
+ model, cpt = get_synthesizer(model_path, device)
153
+ assert isinstance(cpt, dict)
154
+ model.forward = model.infer
155
+ inputs = None
156
+ if mode == "trace":
157
+ inputs = load_inputs(inputs_path, device, is_half)
158
+ ckpt = export(model, mode, inputs, device, is_half)
159
+ cpt.pop("weight")
160
+ cpt["model"] = ckpt["model"]
161
+ cpt["device"] = device
162
+ save(cpt, save_path)
163
+ return cpt
infer/lib/jit/get_hubert.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+ from typing import Optional, Tuple
4
+ from fairseq.checkpoint_utils import load_model_ensemble_and_task
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ # from fairseq.data.data_utils import compute_mask_indices
10
+ from fairseq.utils import index_put
11
+
12
+
13
+ # @torch.jit.script
14
+ def pad_to_multiple(x, multiple, dim=-1, value=0):
15
+ # Inspired from https://github.com/lucidrains/local-attention/blob/master/local_attention/local_attention.py#L41
16
+ if x is None:
17
+ return None, 0
18
+ tsz = x.size(dim)
19
+ m = tsz / multiple
20
+ remainder = math.ceil(m) * multiple - tsz
21
+ if int(tsz % multiple) == 0:
22
+ return x, 0
23
+ pad_offset = (0,) * (-1 - dim) * 2
24
+
25
+ return F.pad(x, (*pad_offset, 0, remainder), value=value), remainder
26
+
27
+
28
+ def extract_features(
29
+ self,
30
+ x,
31
+ padding_mask=None,
32
+ tgt_layer=None,
33
+ min_layer=0,
34
+ ):
35
+ if padding_mask is not None:
36
+ x = index_put(x, padding_mask, 0)
37
+
38
+ x_conv = self.pos_conv(x.transpose(1, 2))
39
+ x_conv = x_conv.transpose(1, 2)
40
+ x = x + x_conv
41
+
42
+ if not self.layer_norm_first:
43
+ x = self.layer_norm(x)
44
+
45
+ # pad to the sequence length dimension
46
+ x, pad_length = pad_to_multiple(x, self.required_seq_len_multiple, dim=-2, value=0)
47
+ if pad_length > 0 and padding_mask is None:
48
+ padding_mask = x.new_zeros((x.size(0), x.size(1)), dtype=torch.bool)
49
+ padding_mask[:, -pad_length:] = True
50
+ else:
51
+ padding_mask, _ = pad_to_multiple(
52
+ padding_mask, self.required_seq_len_multiple, dim=-1, value=True
53
+ )
54
+ x = F.dropout(x, p=self.dropout, training=self.training)
55
+
56
+ # B x T x C -> T x B x C
57
+ x = x.transpose(0, 1)
58
+
59
+ layer_results = []
60
+ r = None
61
+ for i, layer in enumerate(self.layers):
62
+ dropout_probability = np.random.random() if self.layerdrop > 0 else 1
63
+ if not self.training or (dropout_probability > self.layerdrop):
64
+ x, (z, lr) = layer(
65
+ x, self_attn_padding_mask=padding_mask, need_weights=False
66
+ )
67
+ if i >= min_layer:
68
+ layer_results.append((x, z, lr))
69
+ if i == tgt_layer:
70
+ r = x
71
+ break
72
+
73
+ if r is not None:
74
+ x = r
75
+
76
+ # T x B x C -> B x T x C
77
+ x = x.transpose(0, 1)
78
+
79
+ # undo paddding
80
+ if pad_length > 0:
81
+ x = x[:, :-pad_length]
82
+
83
+ def undo_pad(a, b, c):
84
+ return (
85
+ a[:-pad_length],
86
+ b[:-pad_length] if b is not None else b,
87
+ c[:-pad_length],
88
+ )
89
+
90
+ layer_results = [undo_pad(*u) for u in layer_results]
91
+
92
+ return x, layer_results
93
+
94
+
95
+ def compute_mask_indices(
96
+ shape: Tuple[int, int],
97
+ padding_mask: Optional[torch.Tensor],
98
+ mask_prob: float,
99
+ mask_length: int,
100
+ mask_type: str = "static",
101
+ mask_other: float = 0.0,
102
+ min_masks: int = 0,
103
+ no_overlap: bool = False,
104
+ min_space: int = 0,
105
+ require_same_masks: bool = True,
106
+ mask_dropout: float = 0.0,
107
+ ) -> torch.Tensor:
108
+ """
109
+ Computes random mask spans for a given shape
110
+
111
+ Args:
112
+ shape: the the shape for which to compute masks.
113
+ should be of size 2 where first element is batch size and 2nd is timesteps
114
+ padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements
115
+ mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by
116
+ number of timesteps divided by length of mask span to mask approximately this percentage of all elements.
117
+ however due to overlaps, the actual number will be smaller (unless no_overlap is True)
118
+ mask_type: how to compute mask lengths
119
+ static = fixed size
120
+ uniform = sample from uniform distribution [mask_other, mask_length*2]
121
+ normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element
122
+ poisson = sample from possion distribution with lambda = mask length
123
+ min_masks: minimum number of masked spans
124
+ no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping
125
+ min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans
126
+ require_same_masks: if true, will randomly drop out masks until same amount of masks remains in each sample
127
+ mask_dropout: randomly dropout this percentage of masks in each example
128
+ """
129
+
130
+ bsz, all_sz = shape
131
+ mask = torch.full((bsz, all_sz), False)
132
+
133
+ all_num_mask = int(
134
+ # add a random number for probabilistic rounding
135
+ mask_prob * all_sz / float(mask_length)
136
+ + torch.rand([1]).item()
137
+ )
138
+
139
+ all_num_mask = max(min_masks, all_num_mask)
140
+
141
+ mask_idcs = []
142
+ for i in range(bsz):
143
+ if padding_mask is not None:
144
+ sz = all_sz - padding_mask[i].long().sum().item()
145
+ num_mask = int(mask_prob * sz / float(mask_length) + np.random.rand())
146
+ num_mask = max(min_masks, num_mask)
147
+ else:
148
+ sz = all_sz
149
+ num_mask = all_num_mask
150
+
151
+ if mask_type == "static":
152
+ lengths = torch.full([num_mask], mask_length)
153
+ elif mask_type == "uniform":
154
+ lengths = torch.randint(mask_other, mask_length * 2 + 1, size=[num_mask])
155
+ elif mask_type == "normal":
156
+ lengths = torch.normal(mask_length, mask_other, size=[num_mask])
157
+ lengths = [max(1, int(round(x))) for x in lengths]
158
+ else:
159
+ raise Exception("unknown mask selection " + mask_type)
160
+
161
+ if sum(lengths) == 0:
162
+ lengths[0] = min(mask_length, sz - 1)
163
+
164
+ if no_overlap:
165
+ mask_idc = []
166
+
167
+ def arrange(s, e, length, keep_length):
168
+ span_start = torch.randint(low=s, high=e - length, size=[1]).item()
169
+ mask_idc.extend(span_start + i for i in range(length))
170
+
171
+ new_parts = []
172
+ if span_start - s - min_space >= keep_length:
173
+ new_parts.append((s, span_start - min_space + 1))
174
+ if e - span_start - length - min_space > keep_length:
175
+ new_parts.append((span_start + length + min_space, e))
176
+ return new_parts
177
+
178
+ parts = [(0, sz)]
179
+ min_length = min(lengths)
180
+ for length in sorted(lengths, reverse=True):
181
+ t = [e - s if e - s >= length + min_space else 0 for s, e in parts]
182
+ lens = torch.asarray(t, dtype=torch.int)
183
+ l_sum = torch.sum(lens)
184
+ if l_sum == 0:
185
+ break
186
+ probs = lens / torch.sum(lens)
187
+ c = torch.multinomial(probs.float(), len(parts)).item()
188
+ s, e = parts.pop(c)
189
+ parts.extend(arrange(s, e, length, min_length))
190
+ mask_idc = torch.asarray(mask_idc)
191
+ else:
192
+ min_len = min(lengths)
193
+ if sz - min_len <= num_mask:
194
+ min_len = sz - num_mask - 1
195
+ mask_idc = torch.asarray(
196
+ random.sample([i for i in range(sz - min_len)], num_mask)
197
+ )
198
+ mask_idc = torch.asarray(
199
+ [
200
+ mask_idc[j] + offset
201
+ for j in range(len(mask_idc))
202
+ for offset in range(lengths[j])
203
+ ]
204
+ )
205
+
206
+ mask_idcs.append(torch.unique(mask_idc[mask_idc < sz]))
207
+
208
+ min_len = min([len(m) for m in mask_idcs])
209
+ for i, mask_idc in enumerate(mask_idcs):
210
+ if isinstance(mask_idc, torch.Tensor):
211
+ mask_idc = torch.asarray(mask_idc, dtype=torch.float)
212
+ if len(mask_idc) > min_len and require_same_masks:
213
+ mask_idc = torch.asarray(
214
+ random.sample([i for i in range(mask_idc)], min_len)
215
+ )
216
+ if mask_dropout > 0:
217
+ num_holes = int(round(len(mask_idc) * mask_dropout))
218
+ mask_idc = torch.asarray(
219
+ random.sample([i for i in range(mask_idc)], len(mask_idc) - num_holes)
220
+ )
221
+
222
+ mask[i, mask_idc.int()] = True
223
+
224
+ return mask
225
+
226
+
227
+ def apply_mask(self, x, padding_mask, target_list):
228
+ B, T, C = x.shape
229
+ torch.zeros_like(x)
230
+ if self.mask_prob > 0:
231
+ mask_indices = compute_mask_indices(
232
+ (B, T),
233
+ padding_mask,
234
+ self.mask_prob,
235
+ self.mask_length,
236
+ self.mask_selection,
237
+ self.mask_other,
238
+ min_masks=2,
239
+ no_overlap=self.no_mask_overlap,
240
+ min_space=self.mask_min_space,
241
+ )
242
+ mask_indices = mask_indices.to(x.device)
243
+ x[mask_indices] = self.mask_emb
244
+ else:
245
+ mask_indices = None
246
+
247
+ if self.mask_channel_prob > 0:
248
+ mask_channel_indices = compute_mask_indices(
249
+ (B, C),
250
+ None,
251
+ self.mask_channel_prob,
252
+ self.mask_channel_length,
253
+ self.mask_channel_selection,
254
+ self.mask_channel_other,
255
+ no_overlap=self.no_mask_channel_overlap,
256
+ min_space=self.mask_channel_min_space,
257
+ )
258
+ mask_channel_indices = (
259
+ mask_channel_indices.to(x.device).unsqueeze(1).expand(-1, T, -1)
260
+ )
261
+ x[mask_channel_indices] = 0
262
+
263
+ return x, mask_indices
264
+
265
+
266
+ def get_hubert_model(
267
+ model_path="assets/hubert/hubert_base.pt", device=torch.device("cpu")
268
+ ):
269
+ models, _, _ = load_model_ensemble_and_task(
270
+ [model_path],
271
+ suffix="",
272
+ )
273
+ hubert_model = models[0]
274
+ hubert_model = hubert_model.to(device)
275
+
276
+ def _apply_mask(x, padding_mask, target_list):
277
+ return apply_mask(hubert_model, x, padding_mask, target_list)
278
+
279
+ hubert_model.apply_mask = _apply_mask
280
+
281
+ def _extract_features(
282
+ x,
283
+ padding_mask=None,
284
+ tgt_layer=None,
285
+ min_layer=0,
286
+ ):
287
+ return extract_features(
288
+ hubert_model.encoder,
289
+ x,
290
+ padding_mask=padding_mask,
291
+ tgt_layer=tgt_layer,
292
+ min_layer=min_layer,
293
+ )
294
+
295
+ hubert_model.encoder.extract_features = _extract_features
296
+
297
+ hubert_model._forward = hubert_model.forward
298
+
299
+ def hubert_extract_features(
300
+ self,
301
+ source: torch.Tensor,
302
+ padding_mask: Optional[torch.Tensor] = None,
303
+ mask: bool = False,
304
+ ret_conv: bool = False,
305
+ output_layer: Optional[int] = None,
306
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
307
+ res = self._forward(
308
+ source,
309
+ padding_mask=padding_mask,
310
+ mask=mask,
311
+ features_only=True,
312
+ output_layer=output_layer,
313
+ )
314
+ feature = res["features"] if ret_conv else res["x"]
315
+ return feature, res["padding_mask"]
316
+
317
+ def _hubert_extract_features(
318
+ source: torch.Tensor,
319
+ padding_mask: Optional[torch.Tensor] = None,
320
+ mask: bool = False,
321
+ ret_conv: bool = False,
322
+ output_layer: Optional[int] = None,
323
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
324
+ return hubert_extract_features(
325
+ hubert_model, source, padding_mask, mask, ret_conv, output_layer
326
+ )
327
+
328
+ hubert_model.extract_features = _hubert_extract_features
329
+
330
+ def infer(source, padding_mask, output_layer: torch.Tensor):
331
+ output_layer = output_layer.item()
332
+ logits = hubert_model.extract_features(
333
+ source=source, padding_mask=padding_mask, output_layer=output_layer
334
+ )
335
+ feats = hubert_model.final_proj(logits[0]) if output_layer == 9 else logits[0]
336
+ return feats
337
+
338
+ hubert_model.infer = infer
339
+ # hubert_model.forward=infer
340
+ # hubert_model.forward
341
+
342
+ return hubert_model
infer/lib/jit/get_rmvpe.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_rmvpe(model_path="assets/rmvpe/rmvpe.pt", device=torch.device("cpu")):
5
+ from infer.lib.rmvpe import E2E
6
+
7
+ model = E2E(4, 1, (2, 2))
8
+ ckpt = torch.load(model_path, map_location=device)
9
+ model.load_state_dict(ckpt)
10
+ model.eval()
11
+ model = model.to(device)
12
+ return model
infer/lib/jit/get_synthesizer.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_synthesizer(pth_path, device=torch.device("cpu")):
5
+ from infer.lib.infer_pack.models import (
6
+ SynthesizerTrnMs256NSFsid,
7
+ SynthesizerTrnMs256NSFsid_nono,
8
+ SynthesizerTrnMs768NSFsid,
9
+ SynthesizerTrnMs768NSFsid_nono,
10
+ )
11
+
12
+ cpt = torch.load(pth_path, map_location=torch.device("cpu"))
13
+ # tgt_sr = cpt["config"][-1]
14
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
15
+ if_f0 = cpt.get("f0", 1)
16
+ version = cpt.get("version", "v1")
17
+ if version == "v1":
18
+ if if_f0 == 1:
19
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=False)
20
+ else:
21
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
22
+ elif version == "v2":
23
+ if if_f0 == 1:
24
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=False)
25
+ else:
26
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
27
+ del net_g.enc_q
28
+ # net_g.forward = net_g.infer
29
+ # ckpt = {}
30
+ # ckpt["config"] = cpt["config"]
31
+ # ckpt["f0"] = if_f0
32
+ # ckpt["version"] = version
33
+ # ckpt["info"] = cpt.get("info", "0epoch")
34
+ net_g.load_state_dict(cpt["weight"], strict=False)
35
+ net_g = net_g.float()
36
+ net_g.eval().to(device)
37
+ net_g.remove_weight_norm()
38
+ return net_g, cpt
infer/lib/rmvpe.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import os
3
+ from typing import List, Optional, Tuple
4
+ import numpy as np
5
+ import torch
6
+
7
+ from infer.lib import jit
8
+
9
+ try:
10
+ # Fix "Torch not compiled with CUDA enabled"
11
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
12
+
13
+ if torch.xpu.is_available():
14
+ from infer.modules.ipex import ipex_init
15
+
16
+ ipex_init()
17
+ except Exception: # pylint: disable=broad-exception-caught
18
+ pass
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from librosa.util import normalize, pad_center, tiny
22
+ from scipy.signal import get_window
23
+
24
+ import logging
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class STFT(torch.nn.Module):
30
+ def __init__(
31
+ self, filter_length=1024, hop_length=512, win_length=None, window="hann"
32
+ ):
33
+ """
34
+ This module implements an STFT using 1D convolution and 1D transpose convolutions.
35
+ This is a bit tricky so there are some cases that probably won't work as working
36
+ out the same sizes before and after in all overlap add setups is tough. Right now,
37
+ this code should work with hop lengths that are half the filter length (50% overlap
38
+ between frames).
39
+
40
+ Keyword Arguments:
41
+ filter_length {int} -- Length of filters used (default: {1024})
42
+ hop_length {int} -- Hop length of STFT (restrict to 50% overlap between frames) (default: {512})
43
+ win_length {[type]} -- Length of the window function applied to each frame (if not specified, it
44
+ equals the filter length). (default: {None})
45
+ window {str} -- Type of window to use (options are bartlett, hann, hamming, blackman, blackmanharris)
46
+ (default: {'hann'})
47
+ """
48
+ super(STFT, self).__init__()
49
+ self.filter_length = filter_length
50
+ self.hop_length = hop_length
51
+ self.win_length = win_length if win_length else filter_length
52
+ self.window = window
53
+ self.forward_transform = None
54
+ self.pad_amount = int(self.filter_length / 2)
55
+ fourier_basis = np.fft.fft(np.eye(self.filter_length))
56
+
57
+ cutoff = int((self.filter_length / 2 + 1))
58
+ fourier_basis = np.vstack(
59
+ [np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])]
60
+ )
61
+ forward_basis = torch.FloatTensor(fourier_basis)
62
+ inverse_basis = torch.FloatTensor(np.linalg.pinv(fourier_basis))
63
+
64
+ assert filter_length >= self.win_length
65
+ # get window and zero center pad it to filter_length
66
+ fft_window = get_window(window, self.win_length, fftbins=True)
67
+ fft_window = pad_center(fft_window, size=filter_length)
68
+ fft_window = torch.from_numpy(fft_window).float()
69
+
70
+ # window the bases
71
+ forward_basis *= fft_window
72
+ inverse_basis = (inverse_basis.T * fft_window).T
73
+
74
+ self.register_buffer("forward_basis", forward_basis.float())
75
+ self.register_buffer("inverse_basis", inverse_basis.float())
76
+ self.register_buffer("fft_window", fft_window.float())
77
+
78
+ def transform(self, input_data, return_phase=False):
79
+ """Take input data (audio) to STFT domain.
80
+
81
+ Arguments:
82
+ input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
83
+
84
+ Returns:
85
+ magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
86
+ num_frequencies, num_frames)
87
+ phase {tensor} -- Phase of STFT with shape (num_batch,
88
+ num_frequencies, num_frames)
89
+ """
90
+ input_data = F.pad(
91
+ input_data,
92
+ (self.pad_amount, self.pad_amount),
93
+ mode="reflect",
94
+ )
95
+ forward_transform = input_data.unfold(
96
+ 1, self.filter_length, self.hop_length
97
+ ).permute(0, 2, 1)
98
+ forward_transform = torch.matmul(self.forward_basis, forward_transform)
99
+ cutoff = int((self.filter_length / 2) + 1)
100
+ real_part = forward_transform[:, :cutoff, :]
101
+ imag_part = forward_transform[:, cutoff:, :]
102
+ magnitude = torch.sqrt(real_part**2 + imag_part**2)
103
+ if return_phase:
104
+ phase = torch.atan2(imag_part.data, real_part.data)
105
+ return magnitude, phase
106
+ else:
107
+ return magnitude
108
+
109
+ def inverse(self, magnitude, phase):
110
+ """Call the inverse STFT (iSTFT), given magnitude and phase tensors produced
111
+ by the ```transform``` function.
112
+
113
+ Arguments:
114
+ magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
115
+ num_frequencies, num_frames)
116
+ phase {tensor} -- Phase of STFT with shape (num_batch,
117
+ num_frequencies, num_frames)
118
+
119
+ Returns:
120
+ inverse_transform {tensor} -- Reconstructed audio given magnitude and phase. Of
121
+ shape (num_batch, num_samples)
122
+ """
123
+ cat = torch.cat(
124
+ [magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1
125
+ )
126
+ fold = torch.nn.Fold(
127
+ output_size=(1, (cat.size(-1) - 1) * self.hop_length + self.filter_length),
128
+ kernel_size=(1, self.filter_length),
129
+ stride=(1, self.hop_length),
130
+ )
131
+ inverse_transform = torch.matmul(self.inverse_basis, cat)
132
+ inverse_transform = fold(inverse_transform)[
133
+ :, 0, 0, self.pad_amount : -self.pad_amount
134
+ ]
135
+ window_square_sum = (
136
+ self.fft_window.pow(2).repeat(cat.size(-1), 1).T.unsqueeze(0)
137
+ )
138
+ window_square_sum = fold(window_square_sum)[
139
+ :, 0, 0, self.pad_amount : -self.pad_amount
140
+ ]
141
+ inverse_transform /= window_square_sum
142
+ return inverse_transform
143
+
144
+ def forward(self, input_data):
145
+ """Take input data (audio) to STFT domain and then back to audio.
146
+
147
+ Arguments:
148
+ input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
149
+
150
+ Returns:
151
+ reconstruction {tensor} -- Reconstructed audio given magnitude and phase. Of
152
+ shape (num_batch, num_samples)
153
+ """
154
+ self.magnitude, self.phase = self.transform(input_data, return_phase=True)
155
+ reconstruction = self.inverse(self.magnitude, self.phase)
156
+ return reconstruction
157
+
158
+
159
+ from time import time as ttime
160
+
161
+
162
+ class BiGRU(nn.Module):
163
+ def __init__(self, input_features, hidden_features, num_layers):
164
+ super(BiGRU, self).__init__()
165
+ self.gru = nn.GRU(
166
+ input_features,
167
+ hidden_features,
168
+ num_layers=num_layers,
169
+ batch_first=True,
170
+ bidirectional=True,
171
+ )
172
+
173
+ def forward(self, x):
174
+ return self.gru(x)[0]
175
+
176
+
177
+ class ConvBlockRes(nn.Module):
178
+ def __init__(self, in_channels, out_channels, momentum=0.01):
179
+ super(ConvBlockRes, self).__init__()
180
+ self.conv = nn.Sequential(
181
+ nn.Conv2d(
182
+ in_channels=in_channels,
183
+ out_channels=out_channels,
184
+ kernel_size=(3, 3),
185
+ stride=(1, 1),
186
+ padding=(1, 1),
187
+ bias=False,
188
+ ),
189
+ nn.BatchNorm2d(out_channels, momentum=momentum),
190
+ nn.ReLU(),
191
+ nn.Conv2d(
192
+ in_channels=out_channels,
193
+ out_channels=out_channels,
194
+ kernel_size=(3, 3),
195
+ stride=(1, 1),
196
+ padding=(1, 1),
197
+ bias=False,
198
+ ),
199
+ nn.BatchNorm2d(out_channels, momentum=momentum),
200
+ nn.ReLU(),
201
+ )
202
+ # self.shortcut:Optional[nn.Module] = None
203
+ if in_channels != out_channels:
204
+ self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
205
+
206
+ def forward(self, x: torch.Tensor):
207
+ if not hasattr(self, "shortcut"):
208
+ return self.conv(x) + x
209
+ else:
210
+ return self.conv(x) + self.shortcut(x)
211
+
212
+
213
+ class Encoder(nn.Module):
214
+ def __init__(
215
+ self,
216
+ in_channels,
217
+ in_size,
218
+ n_encoders,
219
+ kernel_size,
220
+ n_blocks,
221
+ out_channels=16,
222
+ momentum=0.01,
223
+ ):
224
+ super(Encoder, self).__init__()
225
+ self.n_encoders = n_encoders
226
+ self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
227
+ self.layers = nn.ModuleList()
228
+ self.latent_channels = []
229
+ for i in range(self.n_encoders):
230
+ self.layers.append(
231
+ ResEncoderBlock(
232
+ in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
233
+ )
234
+ )
235
+ self.latent_channels.append([out_channels, in_size])
236
+ in_channels = out_channels
237
+ out_channels *= 2
238
+ in_size //= 2
239
+ self.out_size = in_size
240
+ self.out_channel = out_channels
241
+
242
+ def forward(self, x: torch.Tensor):
243
+ concat_tensors: List[torch.Tensor] = []
244
+ x = self.bn(x)
245
+ for i, layer in enumerate(self.layers):
246
+ t, x = layer(x)
247
+ concat_tensors.append(t)
248
+ return x, concat_tensors
249
+
250
+
251
+ class ResEncoderBlock(nn.Module):
252
+ def __init__(
253
+ self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
254
+ ):
255
+ super(ResEncoderBlock, self).__init__()
256
+ self.n_blocks = n_blocks
257
+ self.conv = nn.ModuleList()
258
+ self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
259
+ for i in range(n_blocks - 1):
260
+ self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
261
+ self.kernel_size = kernel_size
262
+ if self.kernel_size is not None:
263
+ self.pool = nn.AvgPool2d(kernel_size=kernel_size)
264
+
265
+ def forward(self, x):
266
+ for i, conv in enumerate(self.conv):
267
+ x = conv(x)
268
+ if self.kernel_size is not None:
269
+ return x, self.pool(x)
270
+ else:
271
+ return x
272
+
273
+
274
+ class Intermediate(nn.Module): #
275
+ def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
276
+ super(Intermediate, self).__init__()
277
+ self.n_inters = n_inters
278
+ self.layers = nn.ModuleList()
279
+ self.layers.append(
280
+ ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
281
+ )
282
+ for i in range(self.n_inters - 1):
283
+ self.layers.append(
284
+ ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
285
+ )
286
+
287
+ def forward(self, x):
288
+ for i, layer in enumerate(self.layers):
289
+ x = layer(x)
290
+ return x
291
+
292
+
293
+ class ResDecoderBlock(nn.Module):
294
+ def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
295
+ super(ResDecoderBlock, self).__init__()
296
+ out_padding = (0, 1) if stride == (1, 2) else (1, 1)
297
+ self.n_blocks = n_blocks
298
+ self.conv1 = nn.Sequential(
299
+ nn.ConvTranspose2d(
300
+ in_channels=in_channels,
301
+ out_channels=out_channels,
302
+ kernel_size=(3, 3),
303
+ stride=stride,
304
+ padding=(1, 1),
305
+ output_padding=out_padding,
306
+ bias=False,
307
+ ),
308
+ nn.BatchNorm2d(out_channels, momentum=momentum),
309
+ nn.ReLU(),
310
+ )
311
+ self.conv2 = nn.ModuleList()
312
+ self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
313
+ for i in range(n_blocks - 1):
314
+ self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
315
+
316
+ def forward(self, x, concat_tensor):
317
+ x = self.conv1(x)
318
+ x = torch.cat((x, concat_tensor), dim=1)
319
+ for i, conv2 in enumerate(self.conv2):
320
+ x = conv2(x)
321
+ return x
322
+
323
+
324
+ class Decoder(nn.Module):
325
+ def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
326
+ super(Decoder, self).__init__()
327
+ self.layers = nn.ModuleList()
328
+ self.n_decoders = n_decoders
329
+ for i in range(self.n_decoders):
330
+ out_channels = in_channels // 2
331
+ self.layers.append(
332
+ ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
333
+ )
334
+ in_channels = out_channels
335
+
336
+ def forward(self, x: torch.Tensor, concat_tensors: List[torch.Tensor]):
337
+ for i, layer in enumerate(self.layers):
338
+ x = layer(x, concat_tensors[-1 - i])
339
+ return x
340
+
341
+
342
+ class DeepUnet(nn.Module):
343
+ def __init__(
344
+ self,
345
+ kernel_size,
346
+ n_blocks,
347
+ en_de_layers=5,
348
+ inter_layers=4,
349
+ in_channels=1,
350
+ en_out_channels=16,
351
+ ):
352
+ super(DeepUnet, self).__init__()
353
+ self.encoder = Encoder(
354
+ in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
355
+ )
356
+ self.intermediate = Intermediate(
357
+ self.encoder.out_channel // 2,
358
+ self.encoder.out_channel,
359
+ inter_layers,
360
+ n_blocks,
361
+ )
362
+ self.decoder = Decoder(
363
+ self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
364
+ )
365
+
366
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
367
+ x, concat_tensors = self.encoder(x)
368
+ x = self.intermediate(x)
369
+ x = self.decoder(x, concat_tensors)
370
+ return x
371
+
372
+
373
+ class E2E(nn.Module):
374
+ def __init__(
375
+ self,
376
+ n_blocks,
377
+ n_gru,
378
+ kernel_size,
379
+ en_de_layers=5,
380
+ inter_layers=4,
381
+ in_channels=1,
382
+ en_out_channels=16,
383
+ ):
384
+ super(E2E, self).__init__()
385
+ self.unet = DeepUnet(
386
+ kernel_size,
387
+ n_blocks,
388
+ en_de_layers,
389
+ inter_layers,
390
+ in_channels,
391
+ en_out_channels,
392
+ )
393
+ self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
394
+ if n_gru:
395
+ self.fc = nn.Sequential(
396
+ BiGRU(3 * 128, 256, n_gru),
397
+ nn.Linear(512, 360),
398
+ nn.Dropout(0.25),
399
+ nn.Sigmoid(),
400
+ )
401
+ else:
402
+ self.fc = nn.Sequential(
403
+ nn.Linear(3 * nn.N_MELS, nn.N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
404
+ )
405
+
406
+ def forward(self, mel):
407
+ # print(mel.shape)
408
+ mel = mel.transpose(-1, -2).unsqueeze(1)
409
+ x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
410
+ x = self.fc(x)
411
+ # print(x.shape)
412
+ return x
413
+
414
+
415
+ from librosa.filters import mel
416
+
417
+
418
+ class MelSpectrogram(torch.nn.Module):
419
+ def __init__(
420
+ self,
421
+ is_half,
422
+ n_mel_channels,
423
+ sampling_rate,
424
+ win_length,
425
+ hop_length,
426
+ n_fft=None,
427
+ mel_fmin=0,
428
+ mel_fmax=None,
429
+ clamp=1e-5,
430
+ ):
431
+ super().__init__()
432
+ n_fft = win_length if n_fft is None else n_fft
433
+ self.hann_window = {}
434
+ mel_basis = mel(
435
+ sr=sampling_rate,
436
+ n_fft=n_fft,
437
+ n_mels=n_mel_channels,
438
+ fmin=mel_fmin,
439
+ fmax=mel_fmax,
440
+ htk=True,
441
+ )
442
+ mel_basis = torch.from_numpy(mel_basis).float()
443
+ self.register_buffer("mel_basis", mel_basis)
444
+ self.n_fft = win_length if n_fft is None else n_fft
445
+ self.hop_length = hop_length
446
+ self.win_length = win_length
447
+ self.sampling_rate = sampling_rate
448
+ self.n_mel_channels = n_mel_channels
449
+ self.clamp = clamp
450
+ self.is_half = is_half
451
+
452
+ def forward(self, audio, keyshift=0, speed=1, center=True):
453
+ factor = 2 ** (keyshift / 12)
454
+ n_fft_new = int(np.round(self.n_fft * factor))
455
+ win_length_new = int(np.round(self.win_length * factor))
456
+ hop_length_new = int(np.round(self.hop_length * speed))
457
+ keyshift_key = str(keyshift) + "_" + str(audio.device)
458
+ if keyshift_key not in self.hann_window:
459
+ self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
460
+ audio.device
461
+ )
462
+ if "privateuseone" in str(audio.device):
463
+ if not hasattr(self, "stft"):
464
+ self.stft = STFT(
465
+ filter_length=n_fft_new,
466
+ hop_length=hop_length_new,
467
+ win_length=win_length_new,
468
+ window="hann",
469
+ ).to(audio.device)
470
+ magnitude = self.stft.transform(audio)
471
+ else:
472
+ fft = torch.stft(
473
+ audio,
474
+ n_fft=n_fft_new,
475
+ hop_length=hop_length_new,
476
+ win_length=win_length_new,
477
+ window=self.hann_window[keyshift_key],
478
+ center=center,
479
+ return_complex=True,
480
+ )
481
+ magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
482
+ if keyshift != 0:
483
+ size = self.n_fft // 2 + 1
484
+ resize = magnitude.size(1)
485
+ if resize < size:
486
+ magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
487
+ magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
488
+ mel_output = torch.matmul(self.mel_basis, magnitude)
489
+ if self.is_half == True:
490
+ mel_output = mel_output.half()
491
+ log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
492
+ return log_mel_spec
493
+
494
+
495
+ class RMVPE:
496
+ def __init__(self, model_path: str, is_half, device=None, use_jit=False):
497
+ self.resample_kernel = {}
498
+ self.resample_kernel = {}
499
+ self.is_half = is_half
500
+ if device is None:
501
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
502
+ self.device = device
503
+ self.mel_extractor = MelSpectrogram(
504
+ is_half, 128, 16000, 1024, 160, None, 30, 8000
505
+ ).to(device)
506
+ if "privateuseone" in str(device):
507
+ import onnxruntime as ort
508
+
509
+ ort_session = ort.InferenceSession(
510
+ "%s/rmvpe.onnx" % os.environ["rmvpe_root"],
511
+ providers=["DmlExecutionProvider"],
512
+ )
513
+ self.model = ort_session
514
+ else:
515
+ if str(self.device) == "cuda":
516
+ self.device = torch.device("cuda:0")
517
+
518
+ def get_jit_model():
519
+ jit_model_path = model_path.rstrip(".pth")
520
+ jit_model_path += ".half.jit" if is_half else ".jit"
521
+ reload = False
522
+ if os.path.exists(jit_model_path):
523
+ ckpt = jit.load(jit_model_path)
524
+ model_device = ckpt["device"]
525
+ if model_device != str(self.device):
526
+ reload = True
527
+ else:
528
+ reload = True
529
+
530
+ if reload:
531
+ ckpt = jit.rmvpe_jit_export(
532
+ model_path=model_path,
533
+ mode="script",
534
+ inputs_path=None,
535
+ save_path=jit_model_path,
536
+ device=device,
537
+ is_half=is_half,
538
+ )
539
+ model = torch.jit.load(BytesIO(ckpt["model"]), map_location=device)
540
+ return model
541
+
542
+ def get_default_model():
543
+ model = E2E(4, 1, (2, 2))
544
+ ckpt = torch.load(model_path, map_location="cpu")
545
+ model.load_state_dict(ckpt)
546
+ model.eval()
547
+ if is_half:
548
+ model = model.half()
549
+ else:
550
+ model = model.float()
551
+ return model
552
+
553
+ if use_jit:
554
+ if is_half and "cpu" in str(self.device):
555
+ logger.warning(
556
+ "Use default rmvpe model. \
557
+ Jit is not supported on the CPU for half floating point"
558
+ )
559
+ self.model = get_default_model()
560
+ else:
561
+ self.model = get_jit_model()
562
+ else:
563
+ self.model = get_default_model()
564
+
565
+ self.model = self.model.to(device)
566
+ cents_mapping = 20 * np.arange(360) + 1997.3794084376191
567
+ self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
568
+
569
+ def mel2hidden(self, mel):
570
+ with torch.no_grad():
571
+ n_frames = mel.shape[-1]
572
+ n_pad = 32 * ((n_frames - 1) // 32 + 1) - n_frames
573
+ if n_pad > 0:
574
+ mel = F.pad(mel, (0, n_pad), mode="constant")
575
+ if "privateuseone" in str(self.device):
576
+ onnx_input_name = self.model.get_inputs()[0].name
577
+ onnx_outputs_names = self.model.get_outputs()[0].name
578
+ hidden = self.model.run(
579
+ [onnx_outputs_names],
580
+ input_feed={onnx_input_name: mel.cpu().numpy()},
581
+ )[0]
582
+ else:
583
+ mel = mel.half() if self.is_half else mel.float()
584
+ hidden = self.model(mel)
585
+ return hidden[:, :n_frames]
586
+
587
+ def decode(self, hidden, thred=0.03):
588
+ cents_pred = self.to_local_average_cents(hidden, thred=thred)
589
+ f0 = 10 * (2 ** (cents_pred / 1200))
590
+ f0[f0 == 10] = 0
591
+ # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
592
+ return f0
593
+
594
+ def infer_from_audio(self, audio, thred=0.03):
595
+ # torch.cuda.synchronize()
596
+ # t0 = ttime()
597
+ if not torch.is_tensor(audio):
598
+ audio = torch.from_numpy(audio)
599
+ mel = self.mel_extractor(
600
+ audio.float().to(self.device).unsqueeze(0), center=True
601
+ )
602
+ # print(123123123,mel.device.type)
603
+ # torch.cuda.synchronize()
604
+ # t1 = ttime()
605
+ hidden = self.mel2hidden(mel)
606
+ # torch.cuda.synchronize()
607
+ # t2 = ttime()
608
+ # print(234234,hidden.device.type)
609
+ if "privateuseone" not in str(self.device):
610
+ hidden = hidden.squeeze(0).cpu().numpy()
611
+ else:
612
+ hidden = hidden[0]
613
+ if self.is_half == True:
614
+ hidden = hidden.astype("float32")
615
+
616
+ f0 = self.decode(hidden, thred=thred)
617
+ # torch.cuda.synchronize()
618
+ # t3 = ttime()
619
+ # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
620
+ return f0
621
+
622
+ def to_local_average_cents(self, salience, thred=0.05):
623
+ # t0 = ttime()
624
+ center = np.argmax(salience, axis=1) # 帧长#index
625
+ salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
626
+ # t1 = ttime()
627
+ center += 4
628
+ todo_salience = []
629
+ todo_cents_mapping = []
630
+ starts = center - 4
631
+ ends = center + 5
632
+ for idx in range(salience.shape[0]):
633
+ todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
634
+ todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
635
+ # t2 = ttime()
636
+ todo_salience = np.array(todo_salience) # 帧长,9
637
+ todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
638
+ product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
639
+ weight_sum = np.sum(todo_salience, 1) # 帧长
640
+ devided = product_sum / weight_sum # 帧长
641
+ # t3 = ttime()
642
+ maxx = np.max(salience, axis=1) # 帧长
643
+ devided[maxx <= thred] = 0
644
+ # t4 = ttime()
645
+ # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
646
+ return devided
647
+
648
+
649
+ if __name__ == "__main__":
650
+ import librosa
651
+ import soundfile as sf
652
+
653
+ audio, sampling_rate = sf.read(r"C:\Users\liujing04\Desktop\Z\冬之花clip1.wav")
654
+ if len(audio.shape) > 1:
655
+ audio = librosa.to_mono(audio.transpose(1, 0))
656
+ audio_bak = audio.copy()
657
+ if sampling_rate != 16000:
658
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
659
+ model_path = r"D:\BaiduNetdiskDownload\RVC-beta-v2-0727AMD_realtime\rmvpe.pt"
660
+ thred = 0.03 # 0.01
661
+ device = "cuda" if torch.cuda.is_available() else "cpu"
662
+ rmvpe = RMVPE(model_path, is_half=False, device=device)
663
+ t0 = ttime()
664
+ f0 = rmvpe.infer_from_audio(audio, thred=thred)
665
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
666
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
667
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
668
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
669
+ t1 = ttime()
670
+ logger.info("%s %.2f", f0.shape, t1 - t0)
infer/lib/slicer2.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ # This function is obtained from librosa.
5
+ def get_rms(
6
+ y,
7
+ frame_length=2048,
8
+ hop_length=512,
9
+ pad_mode="constant",
10
+ ):
11
+ padding = (int(frame_length // 2), int(frame_length // 2))
12
+ y = np.pad(y, padding, mode=pad_mode)
13
+
14
+ axis = -1
15
+ # put our new within-frame axis at the end for now
16
+ out_strides = y.strides + tuple([y.strides[axis]])
17
+ # Reduce the shape on the framing axis
18
+ x_shape_trimmed = list(y.shape)
19
+ x_shape_trimmed[axis] -= frame_length - 1
20
+ out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
21
+ xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
22
+ if axis < 0:
23
+ target_axis = axis - 1
24
+ else:
25
+ target_axis = axis + 1
26
+ xw = np.moveaxis(xw, -1, target_axis)
27
+ # Downsample along the target axis
28
+ slices = [slice(None)] * xw.ndim
29
+ slices[axis] = slice(0, None, hop_length)
30
+ x = xw[tuple(slices)]
31
+
32
+ # Calculate power
33
+ power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
34
+
35
+ return np.sqrt(power)
36
+
37
+
38
+ class Slicer:
39
+ def __init__(
40
+ self,
41
+ sr: int,
42
+ threshold: float = -40.0,
43
+ min_length: int = 5000,
44
+ min_interval: int = 300,
45
+ hop_size: int = 20,
46
+ max_sil_kept: int = 5000,
47
+ ):
48
+ if not min_length >= min_interval >= hop_size:
49
+ raise ValueError(
50
+ "The following condition must be satisfied: min_length >= min_interval >= hop_size"
51
+ )
52
+ if not max_sil_kept >= hop_size:
53
+ raise ValueError(
54
+ "The following condition must be satisfied: max_sil_kept >= hop_size"
55
+ )
56
+ min_interval = sr * min_interval / 1000
57
+ self.threshold = 10 ** (threshold / 20.0)
58
+ self.hop_size = round(sr * hop_size / 1000)
59
+ self.win_size = min(round(min_interval), 4 * self.hop_size)
60
+ self.min_length = round(sr * min_length / 1000 / self.hop_size)
61
+ self.min_interval = round(min_interval / self.hop_size)
62
+ self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
63
+
64
+ def _apply_slice(self, waveform, begin, end):
65
+ if len(waveform.shape) > 1:
66
+ return waveform[
67
+ :, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)
68
+ ]
69
+ else:
70
+ return waveform[
71
+ begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)
72
+ ]
73
+
74
+ # @timeit
75
+ def slice(self, waveform):
76
+ if len(waveform.shape) > 1:
77
+ samples = waveform.mean(axis=0)
78
+ else:
79
+ samples = waveform
80
+ if samples.shape[0] <= self.min_length:
81
+ return [waveform]
82
+ rms_list = get_rms(
83
+ y=samples, frame_length=self.win_size, hop_length=self.hop_size
84
+ ).squeeze(0)
85
+ sil_tags = []
86
+ silence_start = None
87
+ clip_start = 0
88
+ for i, rms in enumerate(rms_list):
89
+ # Keep looping while frame is silent.
90
+ if rms < self.threshold:
91
+ # Record start of silent frames.
92
+ if silence_start is None:
93
+ silence_start = i
94
+ continue
95
+ # Keep looping while frame is not silent and silence start has not been recorded.
96
+ if silence_start is None:
97
+ continue
98
+ # Clear recorded silence start if interval is not enough or clip is too short
99
+ is_leading_silence = silence_start == 0 and i > self.max_sil_kept
100
+ need_slice_middle = (
101
+ i - silence_start >= self.min_interval
102
+ and i - clip_start >= self.min_length
103
+ )
104
+ if not is_leading_silence and not need_slice_middle:
105
+ silence_start = None
106
+ continue
107
+ # Need slicing. Record the range of silent frames to be removed.
108
+ if i - silence_start <= self.max_sil_kept:
109
+ pos = rms_list[silence_start : i + 1].argmin() + silence_start
110
+ if silence_start == 0:
111
+ sil_tags.append((0, pos))
112
+ else:
113
+ sil_tags.append((pos, pos))
114
+ clip_start = pos
115
+ elif i - silence_start <= self.max_sil_kept * 2:
116
+ pos = rms_list[
117
+ i - self.max_sil_kept : silence_start + self.max_sil_kept + 1
118
+ ].argmin()
119
+ pos += i - self.max_sil_kept
120
+ pos_l = (
121
+ rms_list[
122
+ silence_start : silence_start + self.max_sil_kept + 1
123
+ ].argmin()
124
+ + silence_start
125
+ )
126
+ pos_r = (
127
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
128
+ + i
129
+ - self.max_sil_kept
130
+ )
131
+ if silence_start == 0:
132
+ sil_tags.append((0, pos_r))
133
+ clip_start = pos_r
134
+ else:
135
+ sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
136
+ clip_start = max(pos_r, pos)
137
+ else:
138
+ pos_l = (
139
+ rms_list[
140
+ silence_start : silence_start + self.max_sil_kept + 1
141
+ ].argmin()
142
+ + silence_start
143
+ )
144
+ pos_r = (
145
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
146
+ + i
147
+ - self.max_sil_kept
148
+ )
149
+ if silence_start == 0:
150
+ sil_tags.append((0, pos_r))
151
+ else:
152
+ sil_tags.append((pos_l, pos_r))
153
+ clip_start = pos_r
154
+ silence_start = None
155
+ # Deal with trailing silence.
156
+ total_frames = rms_list.shape[0]
157
+ if (
158
+ silence_start is not None
159
+ and total_frames - silence_start >= self.min_interval
160
+ ):
161
+ silence_end = min(total_frames, silence_start + self.max_sil_kept)
162
+ pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
163
+ sil_tags.append((pos, total_frames + 1))
164
+ # Apply and return slices.
165
+ if len(sil_tags) == 0:
166
+ return [waveform]
167
+ else:
168
+ chunks = []
169
+ if sil_tags[0][0] > 0:
170
+ chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
171
+ for i in range(len(sil_tags) - 1):
172
+ chunks.append(
173
+ self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0])
174
+ )
175
+ if sil_tags[-1][1] < total_frames:
176
+ chunks.append(
177
+ self._apply_slice(waveform, sil_tags[-1][1], total_frames)
178
+ )
179
+ return chunks
180
+
181
+
182
+ def main():
183
+ import os.path
184
+ from argparse import ArgumentParser
185
+
186
+ import librosa
187
+ import soundfile
188
+
189
+ parser = ArgumentParser()
190
+ parser.add_argument("audio", type=str, help="The audio to be sliced")
191
+ parser.add_argument(
192
+ "--out", type=str, help="Output directory of the sliced audio clips"
193
+ )
194
+ parser.add_argument(
195
+ "--db_thresh",
196
+ type=float,
197
+ required=False,
198
+ default=-40,
199
+ help="The dB threshold for silence detection",
200
+ )
201
+ parser.add_argument(
202
+ "--min_length",
203
+ type=int,
204
+ required=False,
205
+ default=5000,
206
+ help="The minimum milliseconds required for each sliced audio clip",
207
+ )
208
+ parser.add_argument(
209
+ "--min_interval",
210
+ type=int,
211
+ required=False,
212
+ default=300,
213
+ help="The minimum milliseconds for a silence part to be sliced",
214
+ )
215
+ parser.add_argument(
216
+ "--hop_size",
217
+ type=int,
218
+ required=False,
219
+ default=10,
220
+ help="Frame length in milliseconds",
221
+ )
222
+ parser.add_argument(
223
+ "--max_sil_kept",
224
+ type=int,
225
+ required=False,
226
+ default=500,
227
+ help="The maximum silence length kept around the sliced clip, presented in milliseconds",
228
+ )
229
+ args = parser.parse_args()
230
+ out = args.out
231
+ if out is None:
232
+ out = os.path.dirname(os.path.abspath(args.audio))
233
+ audio, sr = librosa.load(args.audio, sr=None, mono=False)
234
+ slicer = Slicer(
235
+ sr=sr,
236
+ threshold=args.db_thresh,
237
+ min_length=args.min_length,
238
+ min_interval=args.min_interval,
239
+ hop_size=args.hop_size,
240
+ max_sil_kept=args.max_sil_kept,
241
+ )
242
+ chunks = slicer.slice(audio)
243
+ if not os.path.exists(out):
244
+ os.makedirs(out)
245
+ for i, chunk in enumerate(chunks):
246
+ if len(chunk.shape) > 1:
247
+ chunk = chunk.T
248
+ soundfile.write(
249
+ os.path.join(
250
+ out,
251
+ f"%s_%d.wav"
252
+ % (os.path.basename(args.audio).rsplit(".", maxsplit=1)[0], i),
253
+ ),
254
+ chunk,
255
+ sr,
256
+ )
257
+
258
+
259
+ if __name__ == "__main__":
260
+ main()
infer/lib/train/data_utils.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import traceback
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.utils.data
10
+
11
+ from infer.lib.train.mel_processing import spectrogram_torch
12
+ from infer.lib.train.utils import load_filepaths_and_text, load_wav_to_torch
13
+
14
+
15
+ class TextAudioLoaderMultiNSFsid(torch.utils.data.Dataset):
16
+ """
17
+ 1) loads audio, text pairs
18
+ 2) normalizes text and converts them to sequences of integers
19
+ 3) computes spectrograms from audio files.
20
+ """
21
+
22
+ def __init__(self, audiopaths_and_text, hparams):
23
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
24
+ self.max_wav_value = hparams.max_wav_value
25
+ self.sampling_rate = hparams.sampling_rate
26
+ self.filter_length = hparams.filter_length
27
+ self.hop_length = hparams.hop_length
28
+ self.win_length = hparams.win_length
29
+ self.sampling_rate = hparams.sampling_rate
30
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
31
+ self.max_text_len = getattr(hparams, "max_text_len", 5000)
32
+ self._filter()
33
+
34
+ def _filter(self):
35
+ """
36
+ Filter text & store spec lengths
37
+ """
38
+ # Store spectrogram lengths for Bucketing
39
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
40
+ # spec_length = wav_length // hop_length
41
+ audiopaths_and_text_new = []
42
+ lengths = []
43
+ for audiopath, text, pitch, pitchf, dv in self.audiopaths_and_text:
44
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
45
+ audiopaths_and_text_new.append([audiopath, text, pitch, pitchf, dv])
46
+ lengths.append(os.path.getsize(audiopath) // (3 * self.hop_length))
47
+ self.audiopaths_and_text = audiopaths_and_text_new
48
+ self.lengths = lengths
49
+
50
+ def get_sid(self, sid):
51
+ sid = torch.LongTensor([int(sid)])
52
+ return sid
53
+
54
+ def get_audio_text_pair(self, audiopath_and_text):
55
+ # separate filename and text
56
+ file = audiopath_and_text[0]
57
+ phone = audiopath_and_text[1]
58
+ pitch = audiopath_and_text[2]
59
+ pitchf = audiopath_and_text[3]
60
+ dv = audiopath_and_text[4]
61
+
62
+ phone, pitch, pitchf = self.get_labels(phone, pitch, pitchf)
63
+ spec, wav = self.get_audio(file)
64
+ dv = self.get_sid(dv)
65
+
66
+ len_phone = phone.size()[0]
67
+ len_spec = spec.size()[-1]
68
+ # print(123,phone.shape,pitch.shape,spec.shape)
69
+ if len_phone != len_spec:
70
+ len_min = min(len_phone, len_spec)
71
+ # amor
72
+ len_wav = len_min * self.hop_length
73
+
74
+ spec = spec[:, :len_min]
75
+ wav = wav[:, :len_wav]
76
+
77
+ phone = phone[:len_min, :]
78
+ pitch = pitch[:len_min]
79
+ pitchf = pitchf[:len_min]
80
+
81
+ return (spec, wav, phone, pitch, pitchf, dv)
82
+
83
+ def get_labels(self, phone, pitch, pitchf):
84
+ phone = np.load(phone)
85
+ phone = np.repeat(phone, 2, axis=0)
86
+ pitch = np.load(pitch)
87
+ pitchf = np.load(pitchf)
88
+ n_num = min(phone.shape[0], 900) # DistributedBucketSampler
89
+ # print(234,phone.shape,pitch.shape)
90
+ phone = phone[:n_num, :]
91
+ pitch = pitch[:n_num]
92
+ pitchf = pitchf[:n_num]
93
+ phone = torch.FloatTensor(phone)
94
+ pitch = torch.LongTensor(pitch)
95
+ pitchf = torch.FloatTensor(pitchf)
96
+ return phone, pitch, pitchf
97
+
98
+ def get_audio(self, filename):
99
+ audio, sampling_rate = load_wav_to_torch(filename)
100
+ if sampling_rate != self.sampling_rate:
101
+ raise ValueError(
102
+ "{} SR doesn't match target {} SR".format(
103
+ sampling_rate, self.sampling_rate
104
+ )
105
+ )
106
+ audio_norm = audio
107
+ # audio_norm = audio / self.max_wav_value
108
+ # audio_norm = audio / np.abs(audio).max()
109
+
110
+ audio_norm = audio_norm.unsqueeze(0)
111
+ spec_filename = filename.replace(".wav", ".spec.pt")
112
+ if os.path.exists(spec_filename):
113
+ try:
114
+ spec = torch.load(spec_filename)
115
+ except:
116
+ logger.warning("%s %s", spec_filename, traceback.format_exc())
117
+ spec = spectrogram_torch(
118
+ audio_norm,
119
+ self.filter_length,
120
+ self.sampling_rate,
121
+ self.hop_length,
122
+ self.win_length,
123
+ center=False,
124
+ )
125
+ spec = torch.squeeze(spec, 0)
126
+ torch.save(spec, spec_filename, _use_new_zipfile_serialization=False)
127
+ else:
128
+ spec = spectrogram_torch(
129
+ audio_norm,
130
+ self.filter_length,
131
+ self.sampling_rate,
132
+ self.hop_length,
133
+ self.win_length,
134
+ center=False,
135
+ )
136
+ spec = torch.squeeze(spec, 0)
137
+ torch.save(spec, spec_filename, _use_new_zipfile_serialization=False)
138
+ return spec, audio_norm
139
+
140
+ def __getitem__(self, index):
141
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
142
+
143
+ def __len__(self):
144
+ return len(self.audiopaths_and_text)
145
+
146
+
147
+ class TextAudioCollateMultiNSFsid:
148
+ """Zero-pads model inputs and targets"""
149
+
150
+ def __init__(self, return_ids=False):
151
+ self.return_ids = return_ids
152
+
153
+ def __call__(self, batch):
154
+ """Collate's training batch from normalized text and aduio
155
+ PARAMS
156
+ ------
157
+ batch: [text_normalized, spec_normalized, wav_normalized]
158
+ """
159
+ # Right zero-pad all one-hot text sequences to max input length
160
+ _, ids_sorted_decreasing = torch.sort(
161
+ torch.LongTensor([x[0].size(1) for x in batch]), dim=0, descending=True
162
+ )
163
+
164
+ max_spec_len = max([x[0].size(1) for x in batch])
165
+ max_wave_len = max([x[1].size(1) for x in batch])
166
+ spec_lengths = torch.LongTensor(len(batch))
167
+ wave_lengths = torch.LongTensor(len(batch))
168
+ spec_padded = torch.FloatTensor(len(batch), batch[0][0].size(0), max_spec_len)
169
+ wave_padded = torch.FloatTensor(len(batch), 1, max_wave_len)
170
+ spec_padded.zero_()
171
+ wave_padded.zero_()
172
+
173
+ max_phone_len = max([x[2].size(0) for x in batch])
174
+ phone_lengths = torch.LongTensor(len(batch))
175
+ phone_padded = torch.FloatTensor(
176
+ len(batch), max_phone_len, batch[0][2].shape[1]
177
+ ) # (spec, wav, phone, pitch)
178
+ pitch_padded = torch.LongTensor(len(batch), max_phone_len)
179
+ pitchf_padded = torch.FloatTensor(len(batch), max_phone_len)
180
+ phone_padded.zero_()
181
+ pitch_padded.zero_()
182
+ pitchf_padded.zero_()
183
+ # dv = torch.FloatTensor(len(batch), 256)#gin=256
184
+ sid = torch.LongTensor(len(batch))
185
+
186
+ for i in range(len(ids_sorted_decreasing)):
187
+ row = batch[ids_sorted_decreasing[i]]
188
+
189
+ spec = row[0]
190
+ spec_padded[i, :, : spec.size(1)] = spec
191
+ spec_lengths[i] = spec.size(1)
192
+
193
+ wave = row[1]
194
+ wave_padded[i, :, : wave.size(1)] = wave
195
+ wave_lengths[i] = wave.size(1)
196
+
197
+ phone = row[2]
198
+ phone_padded[i, : phone.size(0), :] = phone
199
+ phone_lengths[i] = phone.size(0)
200
+
201
+ pitch = row[3]
202
+ pitch_padded[i, : pitch.size(0)] = pitch
203
+ pitchf = row[4]
204
+ pitchf_padded[i, : pitchf.size(0)] = pitchf
205
+
206
+ # dv[i] = row[5]
207
+ sid[i] = row[5]
208
+
209
+ return (
210
+ phone_padded,
211
+ phone_lengths,
212
+ pitch_padded,
213
+ pitchf_padded,
214
+ spec_padded,
215
+ spec_lengths,
216
+ wave_padded,
217
+ wave_lengths,
218
+ # dv
219
+ sid,
220
+ )
221
+
222
+
223
+ class TextAudioLoader(torch.utils.data.Dataset):
224
+ """
225
+ 1) loads audio, text pairs
226
+ 2) normalizes text and converts them to sequences of integers
227
+ 3) computes spectrograms from audio files.
228
+ """
229
+
230
+ def __init__(self, audiopaths_and_text, hparams):
231
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
232
+ self.max_wav_value = hparams.max_wav_value
233
+ self.sampling_rate = hparams.sampling_rate
234
+ self.filter_length = hparams.filter_length
235
+ self.hop_length = hparams.hop_length
236
+ self.win_length = hparams.win_length
237
+ self.sampling_rate = hparams.sampling_rate
238
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
239
+ self.max_text_len = getattr(hparams, "max_text_len", 5000)
240
+ self._filter()
241
+
242
+ def _filter(self):
243
+ """
244
+ Filter text & store spec lengths
245
+ """
246
+ # Store spectrogram lengths for Bucketing
247
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
248
+ # spec_length = wav_length // hop_length
249
+ audiopaths_and_text_new = []
250
+ lengths = []
251
+ for audiopath, text, dv in self.audiopaths_and_text:
252
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
253
+ audiopaths_and_text_new.append([audiopath, text, dv])
254
+ lengths.append(os.path.getsize(audiopath) // (3 * self.hop_length))
255
+ self.audiopaths_and_text = audiopaths_and_text_new
256
+ self.lengths = lengths
257
+
258
+ def get_sid(self, sid):
259
+ sid = torch.LongTensor([int(sid)])
260
+ return sid
261
+
262
+ def get_audio_text_pair(self, audiopath_and_text):
263
+ # separate filename and text
264
+ file = audiopath_and_text[0]
265
+ phone = audiopath_and_text[1]
266
+ dv = audiopath_and_text[2]
267
+
268
+ phone = self.get_labels(phone)
269
+ spec, wav = self.get_audio(file)
270
+ dv = self.get_sid(dv)
271
+
272
+ len_phone = phone.size()[0]
273
+ len_spec = spec.size()[-1]
274
+ if len_phone != len_spec:
275
+ len_min = min(len_phone, len_spec)
276
+ len_wav = len_min * self.hop_length
277
+ spec = spec[:, :len_min]
278
+ wav = wav[:, :len_wav]
279
+ phone = phone[:len_min, :]
280
+ return (spec, wav, phone, dv)
281
+
282
+ def get_labels(self, phone):
283
+ phone = np.load(phone)
284
+ phone = np.repeat(phone, 2, axis=0)
285
+ n_num = min(phone.shape[0], 900) # DistributedBucketSampler
286
+ phone = phone[:n_num, :]
287
+ phone = torch.FloatTensor(phone)
288
+ return phone
289
+
290
+ def get_audio(self, filename):
291
+ audio, sampling_rate = load_wav_to_torch(filename)
292
+ if sampling_rate != self.sampling_rate:
293
+ raise ValueError(
294
+ "{} SR doesn't match target {} SR".format(
295
+ sampling_rate, self.sampling_rate
296
+ )
297
+ )
298
+ audio_norm = audio
299
+ # audio_norm = audio / self.max_wav_value
300
+ # audio_norm = audio / np.abs(audio).max()
301
+
302
+ audio_norm = audio_norm.unsqueeze(0)
303
+ spec_filename = filename.replace(".wav", ".spec.pt")
304
+ if os.path.exists(spec_filename):
305
+ try:
306
+ spec = torch.load(spec_filename)
307
+ except:
308
+ logger.warning("%s %s", spec_filename, traceback.format_exc())
309
+ spec = spectrogram_torch(
310
+ audio_norm,
311
+ self.filter_length,
312
+ self.sampling_rate,
313
+ self.hop_length,
314
+ self.win_length,
315
+ center=False,
316
+ )
317
+ spec = torch.squeeze(spec, 0)
318
+ torch.save(spec, spec_filename, _use_new_zipfile_serialization=False)
319
+ else:
320
+ spec = spectrogram_torch(
321
+ audio_norm,
322
+ self.filter_length,
323
+ self.sampling_rate,
324
+ self.hop_length,
325
+ self.win_length,
326
+ center=False,
327
+ )
328
+ spec = torch.squeeze(spec, 0)
329
+ torch.save(spec, spec_filename, _use_new_zipfile_serialization=False)
330
+ return spec, audio_norm
331
+
332
+ def __getitem__(self, index):
333
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
334
+
335
+ def __len__(self):
336
+ return len(self.audiopaths_and_text)
337
+
338
+
339
+ class TextAudioCollate:
340
+ """Zero-pads model inputs and targets"""
341
+
342
+ def __init__(self, return_ids=False):
343
+ self.return_ids = return_ids
344
+
345
+ def __call__(self, batch):
346
+ """Collate's training batch from normalized text and aduio
347
+ PARAMS
348
+ ------
349
+ batch: [text_normalized, spec_normalized, wav_normalized]
350
+ """
351
+ # Right zero-pad all one-hot text sequences to max input length
352
+ _, ids_sorted_decreasing = torch.sort(
353
+ torch.LongTensor([x[0].size(1) for x in batch]), dim=0, descending=True
354
+ )
355
+
356
+ max_spec_len = max([x[0].size(1) for x in batch])
357
+ max_wave_len = max([x[1].size(1) for x in batch])
358
+ spec_lengths = torch.LongTensor(len(batch))
359
+ wave_lengths = torch.LongTensor(len(batch))
360
+ spec_padded = torch.FloatTensor(len(batch), batch[0][0].size(0), max_spec_len)
361
+ wave_padded = torch.FloatTensor(len(batch), 1, max_wave_len)
362
+ spec_padded.zero_()
363
+ wave_padded.zero_()
364
+
365
+ max_phone_len = max([x[2].size(0) for x in batch])
366
+ phone_lengths = torch.LongTensor(len(batch))
367
+ phone_padded = torch.FloatTensor(
368
+ len(batch), max_phone_len, batch[0][2].shape[1]
369
+ )
370
+ phone_padded.zero_()
371
+ sid = torch.LongTensor(len(batch))
372
+
373
+ for i in range(len(ids_sorted_decreasing)):
374
+ row = batch[ids_sorted_decreasing[i]]
375
+
376
+ spec = row[0]
377
+ spec_padded[i, :, : spec.size(1)] = spec
378
+ spec_lengths[i] = spec.size(1)
379
+
380
+ wave = row[1]
381
+ wave_padded[i, :, : wave.size(1)] = wave
382
+ wave_lengths[i] = wave.size(1)
383
+
384
+ phone = row[2]
385
+ phone_padded[i, : phone.size(0), :] = phone
386
+ phone_lengths[i] = phone.size(0)
387
+
388
+ sid[i] = row[3]
389
+
390
+ return (
391
+ phone_padded,
392
+ phone_lengths,
393
+ spec_padded,
394
+ spec_lengths,
395
+ wave_padded,
396
+ wave_lengths,
397
+ sid,
398
+ )
399
+
400
+
401
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
402
+ """
403
+ Maintain similar input lengths in a batch.
404
+ Length groups are specified by boundaries.
405
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
406
+
407
+ It removes samples which are not included in the boundaries.
408
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
409
+ """
410
+
411
+ def __init__(
412
+ self,
413
+ dataset,
414
+ batch_size,
415
+ boundaries,
416
+ num_replicas=None,
417
+ rank=None,
418
+ shuffle=True,
419
+ ):
420
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
421
+ self.lengths = dataset.lengths
422
+ self.batch_size = batch_size
423
+ self.boundaries = boundaries
424
+
425
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
426
+ self.total_size = sum(self.num_samples_per_bucket)
427
+ self.num_samples = self.total_size // self.num_replicas
428
+
429
+ def _create_buckets(self):
430
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
431
+ for i in range(len(self.lengths)):
432
+ length = self.lengths[i]
433
+ idx_bucket = self._bisect(length)
434
+ if idx_bucket != -1:
435
+ buckets[idx_bucket].append(i)
436
+
437
+ for i in range(len(buckets) - 1, -1, -1): #
438
+ if len(buckets[i]) == 0:
439
+ buckets.pop(i)
440
+ self.boundaries.pop(i + 1)
441
+
442
+ num_samples_per_bucket = []
443
+ for i in range(len(buckets)):
444
+ len_bucket = len(buckets[i])
445
+ total_batch_size = self.num_replicas * self.batch_size
446
+ rem = (
447
+ total_batch_size - (len_bucket % total_batch_size)
448
+ ) % total_batch_size
449
+ num_samples_per_bucket.append(len_bucket + rem)
450
+ return buckets, num_samples_per_bucket
451
+
452
+ def __iter__(self):
453
+ # deterministically shuffle based on epoch
454
+ g = torch.Generator()
455
+ g.manual_seed(self.epoch)
456
+
457
+ indices = []
458
+ if self.shuffle:
459
+ for bucket in self.buckets:
460
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
461
+ else:
462
+ for bucket in self.buckets:
463
+ indices.append(list(range(len(bucket))))
464
+
465
+ batches = []
466
+ for i in range(len(self.buckets)):
467
+ bucket = self.buckets[i]
468
+ len_bucket = len(bucket)
469
+ ids_bucket = indices[i]
470
+ num_samples_bucket = self.num_samples_per_bucket[i]
471
+
472
+ # add extra samples to make it evenly divisible
473
+ rem = num_samples_bucket - len_bucket
474
+ ids_bucket = (
475
+ ids_bucket
476
+ + ids_bucket * (rem // len_bucket)
477
+ + ids_bucket[: (rem % len_bucket)]
478
+ )
479
+
480
+ # subsample
481
+ ids_bucket = ids_bucket[self.rank :: self.num_replicas]
482
+
483
+ # batching
484
+ for j in range(len(ids_bucket) // self.batch_size):
485
+ batch = [
486
+ bucket[idx]
487
+ for idx in ids_bucket[
488
+ j * self.batch_size : (j + 1) * self.batch_size
489
+ ]
490
+ ]
491
+ batches.append(batch)
492
+
493
+ if self.shuffle:
494
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
495
+ batches = [batches[i] for i in batch_ids]
496
+ self.batches = batches
497
+
498
+ assert len(self.batches) * self.batch_size == self.num_samples
499
+ return iter(self.batches)
500
+
501
+ def _bisect(self, x, lo=0, hi=None):
502
+ if hi is None:
503
+ hi = len(self.boundaries) - 1
504
+
505
+ if hi > lo:
506
+ mid = (hi + lo) // 2
507
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
508
+ return mid
509
+ elif x <= self.boundaries[mid]:
510
+ return self._bisect(x, lo, mid)
511
+ else:
512
+ return self._bisect(x, mid + 1, hi)
513
+ else:
514
+ return -1
515
+
516
+ def __len__(self):
517
+ return self.num_samples // self.batch_size
infer/lib/train/losses.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def feature_loss(fmap_r, fmap_g):
5
+ loss = 0
6
+ for dr, dg in zip(fmap_r, fmap_g):
7
+ for rl, gl in zip(dr, dg):
8
+ rl = rl.float().detach()
9
+ gl = gl.float()
10
+ loss += torch.mean(torch.abs(rl - gl))
11
+
12
+ return loss * 2
13
+
14
+
15
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
16
+ loss = 0
17
+ r_losses = []
18
+ g_losses = []
19
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
20
+ dr = dr.float()
21
+ dg = dg.float()
22
+ r_loss = torch.mean((1 - dr) ** 2)
23
+ g_loss = torch.mean(dg**2)
24
+ loss += r_loss + g_loss
25
+ r_losses.append(r_loss.item())
26
+ g_losses.append(g_loss.item())
27
+
28
+ return loss, r_losses, g_losses
29
+
30
+
31
+ def generator_loss(disc_outputs):
32
+ loss = 0
33
+ gen_losses = []
34
+ for dg in disc_outputs:
35
+ dg = dg.float()
36
+ l = torch.mean((1 - dg) ** 2)
37
+ gen_losses.append(l)
38
+ loss += l
39
+
40
+ return loss, gen_losses
41
+
42
+
43
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
44
+ """
45
+ z_p, logs_q: [b, h, t_t]
46
+ m_p, logs_p: [b, h, t_t]
47
+ """
48
+ z_p = z_p.float()
49
+ logs_q = logs_q.float()
50
+ m_p = m_p.float()
51
+ logs_p = logs_p.float()
52
+ z_mask = z_mask.float()
53
+
54
+ kl = logs_p - logs_q - 0.5
55
+ kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)
56
+ kl = torch.sum(kl * z_mask)
57
+ l = kl / torch.sum(z_mask)
58
+ return l
infer/lib/train/mel_processing.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ MAX_WAV_VALUE = 32768.0
9
+
10
+
11
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
12
+ """
13
+ PARAMS
14
+ ------
15
+ C: compression factor
16
+ """
17
+ return torch.log(torch.clamp(x, min=clip_val) * C)
18
+
19
+
20
+ def dynamic_range_decompression_torch(x, C=1):
21
+ """
22
+ PARAMS
23
+ ------
24
+ C: compression factor used to compress
25
+ """
26
+ return torch.exp(x) / C
27
+
28
+
29
+ def spectral_normalize_torch(magnitudes):
30
+ return dynamic_range_compression_torch(magnitudes)
31
+
32
+
33
+ def spectral_de_normalize_torch(magnitudes):
34
+ return dynamic_range_decompression_torch(magnitudes)
35
+
36
+
37
+ # Reusable banks
38
+ mel_basis = {}
39
+ hann_window = {}
40
+
41
+
42
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
43
+ """Convert waveform into Linear-frequency Linear-amplitude spectrogram.
44
+
45
+ Args:
46
+ y :: (B, T) - Audio waveforms
47
+ n_fft
48
+ sampling_rate
49
+ hop_size
50
+ win_size
51
+ center
52
+ Returns:
53
+ :: (B, Freq, Frame) - Linear-frequency Linear-amplitude spectrogram
54
+ """
55
+
56
+ # Window - Cache if needed
57
+ global hann_window
58
+ dtype_device = str(y.dtype) + "_" + str(y.device)
59
+ wnsize_dtype_device = str(win_size) + "_" + dtype_device
60
+ if wnsize_dtype_device not in hann_window:
61
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
62
+ dtype=y.dtype, device=y.device
63
+ )
64
+
65
+ # Padding
66
+ y = torch.nn.functional.pad(
67
+ y.unsqueeze(1),
68
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
69
+ mode="reflect",
70
+ )
71
+ y = y.squeeze(1)
72
+
73
+ # Complex Spectrogram :: (B, T) -> (B, Freq, Frame, RealComplex=2)
74
+ spec = torch.stft(
75
+ y,
76
+ n_fft,
77
+ hop_length=hop_size,
78
+ win_length=win_size,
79
+ window=hann_window[wnsize_dtype_device],
80
+ center=center,
81
+ pad_mode="reflect",
82
+ normalized=False,
83
+ onesided=True,
84
+ return_complex=True,
85
+ )
86
+
87
+ # Linear-frequency Linear-amplitude spectrogram :: (B, Freq, Frame, RealComplex=2) -> (B, Freq, Frame)
88
+ spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + 1e-6)
89
+ return spec
90
+
91
+
92
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
93
+ # MelBasis - Cache if needed
94
+ global mel_basis
95
+ dtype_device = str(spec.dtype) + "_" + str(spec.device)
96
+ fmax_dtype_device = str(fmax) + "_" + dtype_device
97
+ if fmax_dtype_device not in mel_basis:
98
+ mel = librosa_mel_fn(
99
+ sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
100
+ )
101
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
102
+ dtype=spec.dtype, device=spec.device
103
+ )
104
+
105
+ # Mel-frequency Log-amplitude spectrogram :: (B, Freq=num_mels, Frame)
106
+ melspec = torch.matmul(mel_basis[fmax_dtype_device], spec)
107
+ melspec = spectral_normalize_torch(melspec)
108
+ return melspec
109
+
110
+
111
+ def mel_spectrogram_torch(
112
+ y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
113
+ ):
114
+ """Convert waveform into Mel-frequency Log-amplitude spectrogram.
115
+
116
+ Args:
117
+ y :: (B, T) - Waveforms
118
+ Returns:
119
+ melspec :: (B, Freq, Frame) - Mel-frequency Log-amplitude spectrogram
120
+ """
121
+ # Linear-frequency Linear-amplitude spectrogram :: (B, T) -> (B, Freq, Frame)
122
+ spec = spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center)
123
+
124
+ # Mel-frequency Log-amplitude spectrogram :: (B, Freq, Frame) -> (B, Freq=num_mels, Frame)
125
+ melspec = spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax)
126
+
127
+ return melspec
infer/lib/train/process_ckpt.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import traceback
4
+ from collections import OrderedDict
5
+
6
+ import torch
7
+
8
+ from i18n.i18n import I18nAuto
9
+
10
+ i18n = I18nAuto()
11
+
12
+
13
+ def savee(ckpt, sr, if_f0, name, epoch, version, hps):
14
+ try:
15
+ opt = OrderedDict()
16
+ opt["weight"] = {}
17
+ for key in ckpt.keys():
18
+ if "enc_q" in key:
19
+ continue
20
+ opt["weight"][key] = ckpt[key].half()
21
+ opt["config"] = [
22
+ hps.data.filter_length // 2 + 1,
23
+ 32,
24
+ hps.model.inter_channels,
25
+ hps.model.hidden_channels,
26
+ hps.model.filter_channels,
27
+ hps.model.n_heads,
28
+ hps.model.n_layers,
29
+ hps.model.kernel_size,
30
+ hps.model.p_dropout,
31
+ hps.model.resblock,
32
+ hps.model.resblock_kernel_sizes,
33
+ hps.model.resblock_dilation_sizes,
34
+ hps.model.upsample_rates,
35
+ hps.model.upsample_initial_channel,
36
+ hps.model.upsample_kernel_sizes,
37
+ hps.model.spk_embed_dim,
38
+ hps.model.gin_channels,
39
+ hps.data.sampling_rate,
40
+ ]
41
+ opt["info"] = "%sepoch" % epoch
42
+ opt["sr"] = sr
43
+ opt["f0"] = if_f0
44
+ opt["version"] = version
45
+ torch.save(opt, "assets/weights/%s.pth" % name)
46
+ return "Success."
47
+ except:
48
+ return traceback.format_exc()
49
+
50
+
51
+ def show_info(path):
52
+ try:
53
+ a = torch.load(path, map_location="cpu")
54
+ return "模型信息:%s\n采样率:%s\n模型是否输入音高引导:%s\n版本:%s" % (
55
+ a.get("info", "None"),
56
+ a.get("sr", "None"),
57
+ a.get("f0", "None"),
58
+ a.get("version", "None"),
59
+ )
60
+ except:
61
+ return traceback.format_exc()
62
+
63
+
64
+ def extract_small_model(path, name, sr, if_f0, info, version):
65
+ try:
66
+ ckpt = torch.load(path, map_location="cpu")
67
+ if "model" in ckpt:
68
+ ckpt = ckpt["model"]
69
+ opt = OrderedDict()
70
+ opt["weight"] = {}
71
+ for key in ckpt.keys():
72
+ if "enc_q" in key:
73
+ continue
74
+ opt["weight"][key] = ckpt[key].half()
75
+ if sr == "40k":
76
+ opt["config"] = [
77
+ 1025,
78
+ 32,
79
+ 192,
80
+ 192,
81
+ 768,
82
+ 2,
83
+ 6,
84
+ 3,
85
+ 0,
86
+ "1",
87
+ [3, 7, 11],
88
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
89
+ [10, 10, 2, 2],
90
+ 512,
91
+ [16, 16, 4, 4],
92
+ 109,
93
+ 256,
94
+ 40000,
95
+ ]
96
+ elif sr == "48k":
97
+ if version == "v1":
98
+ opt["config"] = [
99
+ 1025,
100
+ 32,
101
+ 192,
102
+ 192,
103
+ 768,
104
+ 2,
105
+ 6,
106
+ 3,
107
+ 0,
108
+ "1",
109
+ [3, 7, 11],
110
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
111
+ [10, 6, 2, 2, 2],
112
+ 512,
113
+ [16, 16, 4, 4, 4],
114
+ 109,
115
+ 256,
116
+ 48000,
117
+ ]
118
+ else:
119
+ opt["config"] = [
120
+ 1025,
121
+ 32,
122
+ 192,
123
+ 192,
124
+ 768,
125
+ 2,
126
+ 6,
127
+ 3,
128
+ 0,
129
+ "1",
130
+ [3, 7, 11],
131
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
132
+ [12, 10, 2, 2],
133
+ 512,
134
+ [24, 20, 4, 4],
135
+ 109,
136
+ 256,
137
+ 48000,
138
+ ]
139
+ elif sr == "32k":
140
+ if version == "v1":
141
+ opt["config"] = [
142
+ 513,
143
+ 32,
144
+ 192,
145
+ 192,
146
+ 768,
147
+ 2,
148
+ 6,
149
+ 3,
150
+ 0,
151
+ "1",
152
+ [3, 7, 11],
153
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
154
+ [10, 4, 2, 2, 2],
155
+ 512,
156
+ [16, 16, 4, 4, 4],
157
+ 109,
158
+ 256,
159
+ 32000,
160
+ ]
161
+ else:
162
+ opt["config"] = [
163
+ 513,
164
+ 32,
165
+ 192,
166
+ 192,
167
+ 768,
168
+ 2,
169
+ 6,
170
+ 3,
171
+ 0,
172
+ "1",
173
+ [3, 7, 11],
174
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
175
+ [10, 8, 2, 2],
176
+ 512,
177
+ [20, 16, 4, 4],
178
+ 109,
179
+ 256,
180
+ 32000,
181
+ ]
182
+ if info == "":
183
+ info = "Extracted model."
184
+ opt["info"] = info
185
+ opt["version"] = version
186
+ opt["sr"] = sr
187
+ opt["f0"] = int(if_f0)
188
+ torch.save(opt, "assets/weights/%s.pth" % name)
189
+ return "Success."
190
+ except:
191
+ return traceback.format_exc()
192
+
193
+
194
+ def change_info(path, info, name):
195
+ try:
196
+ ckpt = torch.load(path, map_location="cpu")
197
+ ckpt["info"] = info
198
+ if name == "":
199
+ name = os.path.basename(path)
200
+ torch.save(ckpt, "assets/weights/%s" % name)
201
+ return "Success."
202
+ except:
203
+ return traceback.format_exc()
204
+
205
+
206
+ def merge(path1, path2, alpha1, sr, f0, info, name, version):
207
+ try:
208
+
209
+ def extract(ckpt):
210
+ a = ckpt["model"]
211
+ opt = OrderedDict()
212
+ opt["weight"] = {}
213
+ for key in a.keys():
214
+ if "enc_q" in key:
215
+ continue
216
+ opt["weight"][key] = a[key]
217
+ return opt
218
+
219
+ ckpt1 = torch.load(path1, map_location="cpu")
220
+ ckpt2 = torch.load(path2, map_location="cpu")
221
+ cfg = ckpt1["config"]
222
+ if "model" in ckpt1:
223
+ ckpt1 = extract(ckpt1)
224
+ else:
225
+ ckpt1 = ckpt1["weight"]
226
+ if "model" in ckpt2:
227
+ ckpt2 = extract(ckpt2)
228
+ else:
229
+ ckpt2 = ckpt2["weight"]
230
+ if sorted(list(ckpt1.keys())) != sorted(list(ckpt2.keys())):
231
+ return "Fail to merge the models. The model architectures are not the same."
232
+ opt = OrderedDict()
233
+ opt["weight"] = {}
234
+ for key in ckpt1.keys():
235
+ # try:
236
+ if key == "emb_g.weight" and ckpt1[key].shape != ckpt2[key].shape:
237
+ min_shape0 = min(ckpt1[key].shape[0], ckpt2[key].shape[0])
238
+ opt["weight"][key] = (
239
+ alpha1 * (ckpt1[key][:min_shape0].float())
240
+ + (1 - alpha1) * (ckpt2[key][:min_shape0].float())
241
+ ).half()
242
+ else:
243
+ opt["weight"][key] = (
244
+ alpha1 * (ckpt1[key].float()) + (1 - alpha1) * (ckpt2[key].float())
245
+ ).half()
246
+ # except:
247
+ # pdb.set_trace()
248
+ opt["config"] = cfg
249
+ """
250
+ if(sr=="40k"):opt["config"] = [1025, 32, 192, 192, 768, 2, 6, 3, 0, "1", [3, 7, 11], [[1, 3, 5], [1, 3, 5], [1, 3, 5]], [10, 10, 2, 2], 512, [16, 16, 4, 4,4], 109, 256, 40000]
251
+ elif(sr=="48k"):opt["config"] = [1025, 32, 192, 192, 768, 2, 6, 3, 0, "1", [3, 7, 11], [[1, 3, 5], [1, 3, 5], [1, 3, 5]], [10,6,2,2,2], 512, [16, 16, 4, 4], 109, 256, 48000]
252
+ elif(sr=="32k"):opt["config"] = [513, 32, 192, 192, 768, 2, 6, 3, 0, "1", [3, 7, 11], [[1, 3, 5], [1, 3, 5], [1, 3, 5]], [10, 4, 2, 2, 2], 512, [16, 16, 4, 4,4], 109, 256, 32000]
253
+ """
254
+ opt["sr"] = sr
255
+ opt["f0"] = 1 if f0 == i18n("是") else 0
256
+ opt["version"] = version
257
+ opt["info"] = info
258
+ torch.save(opt, "assets/weights/%s.pth" % name)
259
+ return "Success."
260
+ except:
261
+ return traceback.format_exc()
infer/lib/train/utils.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import json
4
+ import logging
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import shutil
9
+
10
+ import numpy as np
11
+ import torch
12
+ from scipy.io.wavfile import read
13
+
14
+ MATPLOTLIB_FLAG = False
15
+
16
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
17
+ logger = logging
18
+
19
+
20
+ def load_checkpoint_d(checkpoint_path, combd, sbd, optimizer=None, load_opt=1):
21
+ assert os.path.isfile(checkpoint_path)
22
+ checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
23
+
24
+ ##################
25
+ def go(model, bkey):
26
+ saved_state_dict = checkpoint_dict[bkey]
27
+ if hasattr(model, "module"):
28
+ state_dict = model.module.state_dict()
29
+ else:
30
+ state_dict = model.state_dict()
31
+ new_state_dict = {}
32
+ for k, v in state_dict.items(): # 模型需要的shape
33
+ try:
34
+ new_state_dict[k] = saved_state_dict[k]
35
+ if saved_state_dict[k].shape != state_dict[k].shape:
36
+ logger.warning(
37
+ "shape-%s-mismatch. need: %s, get: %s",
38
+ k,
39
+ state_dict[k].shape,
40
+ saved_state_dict[k].shape,
41
+ ) #
42
+ raise KeyError
43
+ except:
44
+ # logger.info(traceback.format_exc())
45
+ logger.info("%s is not in the checkpoint", k) # pretrain缺失的
46
+ new_state_dict[k] = v # 模型自带的随机值
47
+ if hasattr(model, "module"):
48
+ model.module.load_state_dict(new_state_dict, strict=False)
49
+ else:
50
+ model.load_state_dict(new_state_dict, strict=False)
51
+ return model
52
+
53
+ go(combd, "combd")
54
+ model = go(sbd, "sbd")
55
+ #############
56
+ logger.info("Loaded model weights")
57
+
58
+ iteration = checkpoint_dict["iteration"]
59
+ learning_rate = checkpoint_dict["learning_rate"]
60
+ if (
61
+ optimizer is not None and load_opt == 1
62
+ ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch
63
+ # try:
64
+ optimizer.load_state_dict(checkpoint_dict["optimizer"])
65
+ # except:
66
+ # traceback.print_exc()
67
+ logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration))
68
+ return model, optimizer, learning_rate, iteration
69
+
70
+
71
+ # def load_checkpoint(checkpoint_path, model, optimizer=None):
72
+ # assert os.path.isfile(checkpoint_path)
73
+ # checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
74
+ # iteration = checkpoint_dict['iteration']
75
+ # learning_rate = checkpoint_dict['learning_rate']
76
+ # if optimizer is not None:
77
+ # optimizer.load_state_dict(checkpoint_dict['optimizer'])
78
+ # # print(1111)
79
+ # saved_state_dict = checkpoint_dict['model']
80
+ # # print(1111)
81
+ #
82
+ # if hasattr(model, 'module'):
83
+ # state_dict = model.module.state_dict()
84
+ # else:
85
+ # state_dict = model.state_dict()
86
+ # new_state_dict= {}
87
+ # for k, v in state_dict.items():
88
+ # try:
89
+ # new_state_dict[k] = saved_state_dict[k]
90
+ # except:
91
+ # logger.info("%s is not in the checkpoint" % k)
92
+ # new_state_dict[k] = v
93
+ # if hasattr(model, 'module'):
94
+ # model.module.load_state_dict(new_state_dict)
95
+ # else:
96
+ # model.load_state_dict(new_state_dict)
97
+ # logger.info("Loaded checkpoint '{}' (epoch {})" .format(
98
+ # checkpoint_path, iteration))
99
+ # return model, optimizer, learning_rate, iteration
100
+ def load_checkpoint(checkpoint_path, model, optimizer=None, load_opt=1):
101
+ assert os.path.isfile(checkpoint_path)
102
+ checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
103
+
104
+ saved_state_dict = checkpoint_dict["model"]
105
+ if hasattr(model, "module"):
106
+ state_dict = model.module.state_dict()
107
+ else:
108
+ state_dict = model.state_dict()
109
+ new_state_dict = {}
110
+ for k, v in state_dict.items(): # 模型需要的shape
111
+ try:
112
+ new_state_dict[k] = saved_state_dict[k]
113
+ if saved_state_dict[k].shape != state_dict[k].shape:
114
+ logger.warning(
115
+ "shape-%s-mismatch|need-%s|get-%s",
116
+ k,
117
+ state_dict[k].shape,
118
+ saved_state_dict[k].shape,
119
+ ) #
120
+ raise KeyError
121
+ except:
122
+ # logger.info(traceback.format_exc())
123
+ logger.info("%s is not in the checkpoint", k) # pretrain缺失的
124
+ new_state_dict[k] = v # 模型自带的随机值
125
+ if hasattr(model, "module"):
126
+ model.module.load_state_dict(new_state_dict, strict=False)
127
+ else:
128
+ model.load_state_dict(new_state_dict, strict=False)
129
+ logger.info("Loaded model weights")
130
+
131
+ iteration = checkpoint_dict["iteration"]
132
+ learning_rate = checkpoint_dict["learning_rate"]
133
+ if (
134
+ optimizer is not None and load_opt == 1
135
+ ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch
136
+ # try:
137
+ optimizer.load_state_dict(checkpoint_dict["optimizer"])
138
+ # except:
139
+ # traceback.print_exc()
140
+ logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration))
141
+ return model, optimizer, learning_rate, iteration
142
+
143
+
144
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
145
+ logger.info(
146
+ "Saving model and optimizer state at epoch {} to {}".format(
147
+ iteration, checkpoint_path
148
+ )
149
+ )
150
+ if hasattr(model, "module"):
151
+ state_dict = model.module.state_dict()
152
+ else:
153
+ state_dict = model.state_dict()
154
+ torch.save(
155
+ {
156
+ "model": state_dict,
157
+ "iteration": iteration,
158
+ "optimizer": optimizer.state_dict(),
159
+ "learning_rate": learning_rate,
160
+ },
161
+ checkpoint_path,
162
+ )
163
+
164
+
165
+ def save_checkpoint_d(combd, sbd, optimizer, learning_rate, iteration, checkpoint_path):
166
+ logger.info(
167
+ "Saving model and optimizer state at epoch {} to {}".format(
168
+ iteration, checkpoint_path
169
+ )
170
+ )
171
+ if hasattr(combd, "module"):
172
+ state_dict_combd = combd.module.state_dict()
173
+ else:
174
+ state_dict_combd = combd.state_dict()
175
+ if hasattr(sbd, "module"):
176
+ state_dict_sbd = sbd.module.state_dict()
177
+ else:
178
+ state_dict_sbd = sbd.state_dict()
179
+ torch.save(
180
+ {
181
+ "combd": state_dict_combd,
182
+ "sbd": state_dict_sbd,
183
+ "iteration": iteration,
184
+ "optimizer": optimizer.state_dict(),
185
+ "learning_rate": learning_rate,
186
+ },
187
+ checkpoint_path,
188
+ )
189
+
190
+
191
+ def summarize(
192
+ writer,
193
+ global_step,
194
+ scalars={},
195
+ histograms={},
196
+ images={},
197
+ audios={},
198
+ audio_sampling_rate=22050,
199
+ ):
200
+ for k, v in scalars.items():
201
+ writer.add_scalar(k, v, global_step)
202
+ for k, v in histograms.items():
203
+ writer.add_histogram(k, v, global_step)
204
+ for k, v in images.items():
205
+ writer.add_image(k, v, global_step, dataformats="HWC")
206
+ for k, v in audios.items():
207
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
208
+
209
+
210
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
211
+ f_list = glob.glob(os.path.join(dir_path, regex))
212
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
213
+ x = f_list[-1]
214
+ logger.debug(x)
215
+ return x
216
+
217
+
218
+ def plot_spectrogram_to_numpy(spectrogram):
219
+ global MATPLOTLIB_FLAG
220
+ if not MATPLOTLIB_FLAG:
221
+ import matplotlib
222
+
223
+ matplotlib.use("Agg")
224
+ MATPLOTLIB_FLAG = True
225
+ mpl_logger = logging.getLogger("matplotlib")
226
+ mpl_logger.setLevel(logging.WARNING)
227
+ import matplotlib.pylab as plt
228
+ import numpy as np
229
+
230
+ fig, ax = plt.subplots(figsize=(10, 2))
231
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
232
+ plt.colorbar(im, ax=ax)
233
+ plt.xlabel("Frames")
234
+ plt.ylabel("Channels")
235
+ plt.tight_layout()
236
+
237
+ fig.canvas.draw()
238
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
239
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
240
+ plt.close()
241
+ return data
242
+
243
+
244
+ def plot_alignment_to_numpy(alignment, info=None):
245
+ global MATPLOTLIB_FLAG
246
+ if not MATPLOTLIB_FLAG:
247
+ import matplotlib
248
+
249
+ matplotlib.use("Agg")
250
+ MATPLOTLIB_FLAG = True
251
+ mpl_logger = logging.getLogger("matplotlib")
252
+ mpl_logger.setLevel(logging.WARNING)
253
+ import matplotlib.pylab as plt
254
+ import numpy as np
255
+
256
+ fig, ax = plt.subplots(figsize=(6, 4))
257
+ im = ax.imshow(
258
+ alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
259
+ )
260
+ fig.colorbar(im, ax=ax)
261
+ xlabel = "Decoder timestep"
262
+ if info is not None:
263
+ xlabel += "\n\n" + info
264
+ plt.xlabel(xlabel)
265
+ plt.ylabel("Encoder timestep")
266
+ plt.tight_layout()
267
+
268
+ fig.canvas.draw()
269
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
270
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
271
+ plt.close()
272
+ return data
273
+
274
+
275
+ def load_wav_to_torch(full_path):
276
+ sampling_rate, data = read(full_path)
277
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
278
+
279
+
280
+ def load_filepaths_and_text(filename, split="|"):
281
+ with open(filename, encoding="utf-8") as f:
282
+ filepaths_and_text = [line.strip().split(split) for line in f]
283
+ return filepaths_and_text
284
+
285
+
286
+ def get_hparams(init=True):
287
+ """
288
+ todo:
289
+ 结尾七人组:
290
+ 保存频率、总epoch done
291
+ bs done
292
+ pretrainG、pretrainD done
293
+ 卡号:os.en["CUDA_VISIBLE_DEVICES"] done
294
+ if_latest done
295
+ 模型:if_f0 done
296
+ 采样率:自动选择config done
297
+ 是否缓存数据集进GPU:if_cache_data_in_gpu done
298
+
299
+ -m:
300
+ 自动决定training_files路径,改掉train_nsf_load_pretrain.py里的hps.data.training_files done
301
+ -c不要了
302
+ """
303
+ parser = argparse.ArgumentParser()
304
+ parser.add_argument(
305
+ "-se",
306
+ "--save_every_epoch",
307
+ type=int,
308
+ required=True,
309
+ help="checkpoint save frequency (epoch)",
310
+ )
311
+ parser.add_argument(
312
+ "-te", "--total_epoch", type=int, required=True, help="total_epoch"
313
+ )
314
+ parser.add_argument(
315
+ "-pg", "--pretrainG", type=str, default="", help="Pretrained Generator path"
316
+ )
317
+ parser.add_argument(
318
+ "-pd", "--pretrainD", type=str, default="", help="Pretrained Discriminator path"
319
+ )
320
+ parser.add_argument("-g", "--gpus", type=str, default="0", help="split by -")
321
+ parser.add_argument(
322
+ "-bs", "--batch_size", type=int, required=True, help="batch size"
323
+ )
324
+ parser.add_argument(
325
+ "-e", "--experiment_dir", type=str, required=True, help="experiment dir"
326
+ ) # -m
327
+ parser.add_argument(
328
+ "-sr", "--sample_rate", type=str, required=True, help="sample rate, 32k/40k/48k"
329
+ )
330
+ parser.add_argument(
331
+ "-sw",
332
+ "--save_every_weights",
333
+ type=str,
334
+ default="0",
335
+ help="save the extracted model in weights directory when saving checkpoints",
336
+ )
337
+ parser.add_argument(
338
+ "-v", "--version", type=str, required=True, help="model version"
339
+ )
340
+ parser.add_argument(
341
+ "-f0",
342
+ "--if_f0",
343
+ type=int,
344
+ required=True,
345
+ help="use f0 as one of the inputs of the model, 1 or 0",
346
+ )
347
+ parser.add_argument(
348
+ "-l",
349
+ "--if_latest",
350
+ type=int,
351
+ required=True,
352
+ help="if only save the latest G/D pth file, 1 or 0",
353
+ )
354
+ parser.add_argument(
355
+ "-c",
356
+ "--if_cache_data_in_gpu",
357
+ type=int,
358
+ required=True,
359
+ help="if caching the dataset in GPU memory, 1 or 0",
360
+ )
361
+
362
+ args = parser.parse_args()
363
+ name = args.experiment_dir
364
+ experiment_dir = os.path.join("./logs", args.experiment_dir)
365
+
366
+ config_save_path = os.path.join(experiment_dir, "config.json")
367
+ with open(config_save_path, "r") as f:
368
+ config = json.load(f)
369
+
370
+ hparams = HParams(**config)
371
+ hparams.model_dir = hparams.experiment_dir = experiment_dir
372
+ hparams.save_every_epoch = args.save_every_epoch
373
+ hparams.name = name
374
+ hparams.total_epoch = args.total_epoch
375
+ hparams.pretrainG = args.pretrainG
376
+ hparams.pretrainD = args.pretrainD
377
+ hparams.version = args.version
378
+ hparams.gpus = args.gpus
379
+ hparams.train.batch_size = args.batch_size
380
+ hparams.sample_rate = args.sample_rate
381
+ hparams.if_f0 = args.if_f0
382
+ hparams.if_latest = args.if_latest
383
+ hparams.save_every_weights = args.save_every_weights
384
+ hparams.if_cache_data_in_gpu = args.if_cache_data_in_gpu
385
+ hparams.data.training_files = "%s/filelist.txt" % experiment_dir
386
+ return hparams
387
+
388
+
389
+ def get_hparams_from_dir(model_dir):
390
+ config_save_path = os.path.join(model_dir, "config.json")
391
+ with open(config_save_path, "r") as f:
392
+ data = f.read()
393
+ config = json.loads(data)
394
+
395
+ hparams = HParams(**config)
396
+ hparams.model_dir = model_dir
397
+ return hparams
398
+
399
+
400
+ def get_hparams_from_file(config_path):
401
+ with open(config_path, "r") as f:
402
+ data = f.read()
403
+ config = json.loads(data)
404
+
405
+ hparams = HParams(**config)
406
+ return hparams
407
+
408
+
409
+ def check_git_hash(model_dir):
410
+ source_dir = os.path.dirname(os.path.realpath(__file__))
411
+ if not os.path.exists(os.path.join(source_dir, ".git")):
412
+ logger.warning(
413
+ "{} is not a git repository, therefore hash value comparison will be ignored.".format(
414
+ source_dir
415
+ )
416
+ )
417
+ return
418
+
419
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
420
+
421
+ path = os.path.join(model_dir, "githash")
422
+ if os.path.exists(path):
423
+ saved_hash = open(path).read()
424
+ if saved_hash != cur_hash:
425
+ logger.warning(
426
+ "git hash values are different. {}(saved) != {}(current)".format(
427
+ saved_hash[:8], cur_hash[:8]
428
+ )
429
+ )
430
+ else:
431
+ open(path, "w").write(cur_hash)
432
+
433
+
434
+ def get_logger(model_dir, filename="train.log"):
435
+ global logger
436
+ logger = logging.getLogger(os.path.basename(model_dir))
437
+ logger.setLevel(logging.DEBUG)
438
+
439
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
440
+ if not os.path.exists(model_dir):
441
+ os.makedirs(model_dir)
442
+ h = logging.FileHandler(os.path.join(model_dir, filename))
443
+ h.setLevel(logging.DEBUG)
444
+ h.setFormatter(formatter)
445
+ logger.addHandler(h)
446
+ return logger
447
+
448
+
449
+ class HParams:
450
+ def __init__(self, **kwargs):
451
+ for k, v in kwargs.items():
452
+ if type(v) == dict:
453
+ v = HParams(**v)
454
+ self[k] = v
455
+
456
+ def keys(self):
457
+ return self.__dict__.keys()
458
+
459
+ def items(self):
460
+ return self.__dict__.items()
461
+
462
+ def values(self):
463
+ return self.__dict__.values()
464
+
465
+ def __len__(self):
466
+ return len(self.__dict__)
467
+
468
+ def __getitem__(self, key):
469
+ return getattr(self, key)
470
+
471
+ def __setitem__(self, key, value):
472
+ return setattr(self, key, value)
473
+
474
+ def __contains__(self, key):
475
+ return key in self.__dict__
476
+
477
+ def __repr__(self):
478
+ return self.__dict__.__repr__()
infer/lib/uvr5_pack/lib_v5/dataset.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+ from tqdm import tqdm
8
+
9
+ from . import spec_utils
10
+
11
+
12
+ class VocalRemoverValidationSet(torch.utils.data.Dataset):
13
+ def __init__(self, patch_list):
14
+ self.patch_list = patch_list
15
+
16
+ def __len__(self):
17
+ return len(self.patch_list)
18
+
19
+ def __getitem__(self, idx):
20
+ path = self.patch_list[idx]
21
+ data = np.load(path)
22
+
23
+ X, y = data["X"], data["y"]
24
+
25
+ X_mag = np.abs(X)
26
+ y_mag = np.abs(y)
27
+
28
+ return X_mag, y_mag
29
+
30
+
31
+ def make_pair(mix_dir, inst_dir):
32
+ input_exts = [".wav", ".m4a", ".mp3", ".mp4", ".flac"]
33
+
34
+ X_list = sorted(
35
+ [
36
+ os.path.join(mix_dir, fname)
37
+ for fname in os.listdir(mix_dir)
38
+ if os.path.splitext(fname)[1] in input_exts
39
+ ]
40
+ )
41
+ y_list = sorted(
42
+ [
43
+ os.path.join(inst_dir, fname)
44
+ for fname in os.listdir(inst_dir)
45
+ if os.path.splitext(fname)[1] in input_exts
46
+ ]
47
+ )
48
+
49
+ filelist = list(zip(X_list, y_list))
50
+
51
+ return filelist
52
+
53
+
54
+ def train_val_split(dataset_dir, split_mode, val_rate, val_filelist):
55
+ if split_mode == "random":
56
+ filelist = make_pair(
57
+ os.path.join(dataset_dir, "mixtures"),
58
+ os.path.join(dataset_dir, "instruments"),
59
+ )
60
+
61
+ random.shuffle(filelist)
62
+
63
+ if len(val_filelist) == 0:
64
+ val_size = int(len(filelist) * val_rate)
65
+ train_filelist = filelist[:-val_size]
66
+ val_filelist = filelist[-val_size:]
67
+ else:
68
+ train_filelist = [
69
+ pair for pair in filelist if list(pair) not in val_filelist
70
+ ]
71
+ elif split_mode == "subdirs":
72
+ if len(val_filelist) != 0:
73
+ raise ValueError(
74
+ "The `val_filelist` option is not available in `subdirs` mode"
75
+ )
76
+
77
+ train_filelist = make_pair(
78
+ os.path.join(dataset_dir, "training/mixtures"),
79
+ os.path.join(dataset_dir, "training/instruments"),
80
+ )
81
+
82
+ val_filelist = make_pair(
83
+ os.path.join(dataset_dir, "validation/mixtures"),
84
+ os.path.join(dataset_dir, "validation/instruments"),
85
+ )
86
+
87
+ return train_filelist, val_filelist
88
+
89
+
90
+ def augment(X, y, reduction_rate, reduction_mask, mixup_rate, mixup_alpha):
91
+ perm = np.random.permutation(len(X))
92
+ for i, idx in enumerate(tqdm(perm)):
93
+ if np.random.uniform() < reduction_rate:
94
+ y[idx] = spec_utils.reduce_vocal_aggressively(
95
+ X[idx], y[idx], reduction_mask
96
+ )
97
+
98
+ if np.random.uniform() < 0.5:
99
+ # swap channel
100
+ X[idx] = X[idx, ::-1]
101
+ y[idx] = y[idx, ::-1]
102
+ if np.random.uniform() < 0.02:
103
+ # mono
104
+ X[idx] = X[idx].mean(axis=0, keepdims=True)
105
+ y[idx] = y[idx].mean(axis=0, keepdims=True)
106
+ if np.random.uniform() < 0.02:
107
+ # inst
108
+ X[idx] = y[idx]
109
+
110
+ if np.random.uniform() < mixup_rate and i < len(perm) - 1:
111
+ lam = np.random.beta(mixup_alpha, mixup_alpha)
112
+ X[idx] = lam * X[idx] + (1 - lam) * X[perm[i + 1]]
113
+ y[idx] = lam * y[idx] + (1 - lam) * y[perm[i + 1]]
114
+
115
+ return X, y
116
+
117
+
118
+ def make_padding(width, cropsize, offset):
119
+ left = offset
120
+ roi_size = cropsize - left * 2
121
+ if roi_size == 0:
122
+ roi_size = cropsize
123
+ right = roi_size - (width % roi_size) + left
124
+
125
+ return left, right, roi_size
126
+
127
+
128
+ def make_training_set(filelist, cropsize, patches, sr, hop_length, n_fft, offset):
129
+ len_dataset = patches * len(filelist)
130
+
131
+ X_dataset = np.zeros((len_dataset, 2, n_fft // 2 + 1, cropsize), dtype=np.complex64)
132
+ y_dataset = np.zeros((len_dataset, 2, n_fft // 2 + 1, cropsize), dtype=np.complex64)
133
+
134
+ for i, (X_path, y_path) in enumerate(tqdm(filelist)):
135
+ X, y = spec_utils.cache_or_load(X_path, y_path, sr, hop_length, n_fft)
136
+ coef = np.max([np.abs(X).max(), np.abs(y).max()])
137
+ X, y = X / coef, y / coef
138
+
139
+ l, r, roi_size = make_padding(X.shape[2], cropsize, offset)
140
+ X_pad = np.pad(X, ((0, 0), (0, 0), (l, r)), mode="constant")
141
+ y_pad = np.pad(y, ((0, 0), (0, 0), (l, r)), mode="constant")
142
+
143
+ starts = np.random.randint(0, X_pad.shape[2] - cropsize, patches)
144
+ ends = starts + cropsize
145
+ for j in range(patches):
146
+ idx = i * patches + j
147
+ X_dataset[idx] = X_pad[:, :, starts[j] : ends[j]]
148
+ y_dataset[idx] = y_pad[:, :, starts[j] : ends[j]]
149
+
150
+ return X_dataset, y_dataset
151
+
152
+
153
+ def make_validation_set(filelist, cropsize, sr, hop_length, n_fft, offset):
154
+ patch_list = []
155
+ patch_dir = "cs{}_sr{}_hl{}_nf{}_of{}".format(
156
+ cropsize, sr, hop_length, n_fft, offset
157
+ )
158
+ os.makedirs(patch_dir, exist_ok=True)
159
+
160
+ for i, (X_path, y_path) in enumerate(tqdm(filelist)):
161
+ basename = os.path.splitext(os.path.basename(X_path))[0]
162
+
163
+ X, y = spec_utils.cache_or_load(X_path, y_path, sr, hop_length, n_fft)
164
+ coef = np.max([np.abs(X).max(), np.abs(y).max()])
165
+ X, y = X / coef, y / coef
166
+
167
+ l, r, roi_size = make_padding(X.shape[2], cropsize, offset)
168
+ X_pad = np.pad(X, ((0, 0), (0, 0), (l, r)), mode="constant")
169
+ y_pad = np.pad(y, ((0, 0), (0, 0), (l, r)), mode="constant")
170
+
171
+ len_dataset = int(np.ceil(X.shape[2] / roi_size))
172
+ for j in range(len_dataset):
173
+ outpath = os.path.join(patch_dir, "{}_p{}.npz".format(basename, j))
174
+ start = j * roi_size
175
+ if not os.path.exists(outpath):
176
+ np.savez(
177
+ outpath,
178
+ X=X_pad[:, :, start : start + cropsize],
179
+ y=y_pad[:, :, start : start + cropsize],
180
+ )
181
+ patch_list.append(outpath)
182
+
183
+ return VocalRemoverValidationSet(patch_list)
infer/lib/uvr5_pack/lib_v5/layers.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.bottleneck = nn.Sequential(
104
+ Conv2DBNActiv(nin * 5, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
105
+ )
106
+
107
+ def forward(self, x):
108
+ _, _, h, w = x.size()
109
+ feat1 = F.interpolate(
110
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
111
+ )
112
+ feat2 = self.conv2(x)
113
+ feat3 = self.conv3(x)
114
+ feat4 = self.conv4(x)
115
+ feat5 = self.conv5(x)
116
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1)
117
+ bottle = self.bottleneck(out)
118
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_123812KB .py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.bottleneck = nn.Sequential(
104
+ Conv2DBNActiv(nin * 5, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
105
+ )
106
+
107
+ def forward(self, x):
108
+ _, _, h, w = x.size()
109
+ feat1 = F.interpolate(
110
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
111
+ )
112
+ feat2 = self.conv2(x)
113
+ feat3 = self.conv3(x)
114
+ feat4 = self.conv4(x)
115
+ feat5 = self.conv5(x)
116
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1)
117
+ bottle = self.bottleneck(out)
118
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_123821KB.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.bottleneck = nn.Sequential(
104
+ Conv2DBNActiv(nin * 5, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
105
+ )
106
+
107
+ def forward(self, x):
108
+ _, _, h, w = x.size()
109
+ feat1 = F.interpolate(
110
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
111
+ )
112
+ feat2 = self.conv2(x)
113
+ feat3 = self.conv3(x)
114
+ feat4 = self.conv4(x)
115
+ feat5 = self.conv5(x)
116
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1)
117
+ bottle = self.bottleneck(out)
118
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_33966KB.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16, 32, 64), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.conv6 = SeperableConv2DBNActiv(
104
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
105
+ )
106
+ self.conv7 = SeperableConv2DBNActiv(
107
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
108
+ )
109
+ self.bottleneck = nn.Sequential(
110
+ Conv2DBNActiv(nin * 7, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
111
+ )
112
+
113
+ def forward(self, x):
114
+ _, _, h, w = x.size()
115
+ feat1 = F.interpolate(
116
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
117
+ )
118
+ feat2 = self.conv2(x)
119
+ feat3 = self.conv3(x)
120
+ feat4 = self.conv4(x)
121
+ feat5 = self.conv5(x)
122
+ feat6 = self.conv6(x)
123
+ feat7 = self.conv7(x)
124
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5, feat6, feat7), dim=1)
125
+ bottle = self.bottleneck(out)
126
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_537227KB.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16, 32, 64), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.conv6 = SeperableConv2DBNActiv(
104
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
105
+ )
106
+ self.conv7 = SeperableConv2DBNActiv(
107
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
108
+ )
109
+ self.bottleneck = nn.Sequential(
110
+ Conv2DBNActiv(nin * 7, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
111
+ )
112
+
113
+ def forward(self, x):
114
+ _, _, h, w = x.size()
115
+ feat1 = F.interpolate(
116
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
117
+ )
118
+ feat2 = self.conv2(x)
119
+ feat3 = self.conv3(x)
120
+ feat4 = self.conv4(x)
121
+ feat5 = self.conv5(x)
122
+ feat6 = self.conv6(x)
123
+ feat7 = self.conv7(x)
124
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5, feat6, feat7), dim=1)
125
+ bottle = self.bottleneck(out)
126
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_537238KB.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class SeperableConv2DBNActiv(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
31
+ super(SeperableConv2DBNActiv, self).__init__()
32
+ self.conv = nn.Sequential(
33
+ nn.Conv2d(
34
+ nin,
35
+ nin,
36
+ kernel_size=ksize,
37
+ stride=stride,
38
+ padding=pad,
39
+ dilation=dilation,
40
+ groups=nin,
41
+ bias=False,
42
+ ),
43
+ nn.Conv2d(nin, nout, kernel_size=1, bias=False),
44
+ nn.BatchNorm2d(nout),
45
+ activ(),
46
+ )
47
+
48
+ def __call__(self, x):
49
+ return self.conv(x)
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
54
+ super(Encoder, self).__init__()
55
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
56
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
57
+
58
+ def __call__(self, x):
59
+ skip = self.conv1(x)
60
+ h = self.conv2(skip)
61
+
62
+ return h, skip
63
+
64
+
65
+ class Decoder(nn.Module):
66
+ def __init__(
67
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
68
+ ):
69
+ super(Decoder, self).__init__()
70
+ self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
71
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
72
+
73
+ def __call__(self, x, skip=None):
74
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
75
+ if skip is not None:
76
+ skip = spec_utils.crop_center(skip, x)
77
+ x = torch.cat([x, skip], dim=1)
78
+ h = self.conv(x)
79
+
80
+ if self.dropout is not None:
81
+ h = self.dropout(h)
82
+
83
+ return h
84
+
85
+
86
+ class ASPPModule(nn.Module):
87
+ def __init__(self, nin, nout, dilations=(4, 8, 16, 32, 64), activ=nn.ReLU):
88
+ super(ASPPModule, self).__init__()
89
+ self.conv1 = nn.Sequential(
90
+ nn.AdaptiveAvgPool2d((1, None)),
91
+ Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
92
+ )
93
+ self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
94
+ self.conv3 = SeperableConv2DBNActiv(
95
+ nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
96
+ )
97
+ self.conv4 = SeperableConv2DBNActiv(
98
+ nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
99
+ )
100
+ self.conv5 = SeperableConv2DBNActiv(
101
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
102
+ )
103
+ self.conv6 = SeperableConv2DBNActiv(
104
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
105
+ )
106
+ self.conv7 = SeperableConv2DBNActiv(
107
+ nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
108
+ )
109
+ self.bottleneck = nn.Sequential(
110
+ Conv2DBNActiv(nin * 7, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
111
+ )
112
+
113
+ def forward(self, x):
114
+ _, _, h, w = x.size()
115
+ feat1 = F.interpolate(
116
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
117
+ )
118
+ feat2 = self.conv2(x)
119
+ feat3 = self.conv3(x)
120
+ feat4 = self.conv4(x)
121
+ feat5 = self.conv5(x)
122
+ feat6 = self.conv6(x)
123
+ feat7 = self.conv7(x)
124
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5, feat6, feat7), dim=1)
125
+ bottle = self.bottleneck(out)
126
+ return bottle
infer/lib/uvr5_pack/lib_v5/layers_new.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ from . import spec_utils
6
+
7
+
8
+ class Conv2DBNActiv(nn.Module):
9
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
10
+ super(Conv2DBNActiv, self).__init__()
11
+ self.conv = nn.Sequential(
12
+ nn.Conv2d(
13
+ nin,
14
+ nout,
15
+ kernel_size=ksize,
16
+ stride=stride,
17
+ padding=pad,
18
+ dilation=dilation,
19
+ bias=False,
20
+ ),
21
+ nn.BatchNorm2d(nout),
22
+ activ(),
23
+ )
24
+
25
+ def __call__(self, x):
26
+ return self.conv(x)
27
+
28
+
29
+ class Encoder(nn.Module):
30
+ def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
31
+ super(Encoder, self).__init__()
32
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, stride, pad, activ=activ)
33
+ self.conv2 = Conv2DBNActiv(nout, nout, ksize, 1, pad, activ=activ)
34
+
35
+ def __call__(self, x):
36
+ h = self.conv1(x)
37
+ h = self.conv2(h)
38
+
39
+ return h
40
+
41
+
42
+ class Decoder(nn.Module):
43
+ def __init__(
44
+ self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
45
+ ):
46
+ super(Decoder, self).__init__()
47
+ self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
48
+ # self.conv2 = Conv2DBNActiv(nout, nout, ksize, 1, pad, activ=activ)
49
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
50
+
51
+ def __call__(self, x, skip=None):
52
+ x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
53
+
54
+ if skip is not None:
55
+ skip = spec_utils.crop_center(skip, x)
56
+ x = torch.cat([x, skip], dim=1)
57
+
58
+ h = self.conv1(x)
59
+ # h = self.conv2(h)
60
+
61
+ if self.dropout is not None:
62
+ h = self.dropout(h)
63
+
64
+ return h
65
+
66
+
67
+ class ASPPModule(nn.Module):
68
+ def __init__(self, nin, nout, dilations=(4, 8, 12), activ=nn.ReLU, dropout=False):
69
+ super(ASPPModule, self).__init__()
70
+ self.conv1 = nn.Sequential(
71
+ nn.AdaptiveAvgPool2d((1, None)),
72
+ Conv2DBNActiv(nin, nout, 1, 1, 0, activ=activ),
73
+ )
74
+ self.conv2 = Conv2DBNActiv(nin, nout, 1, 1, 0, activ=activ)
75
+ self.conv3 = Conv2DBNActiv(
76
+ nin, nout, 3, 1, dilations[0], dilations[0], activ=activ
77
+ )
78
+ self.conv4 = Conv2DBNActiv(
79
+ nin, nout, 3, 1, dilations[1], dilations[1], activ=activ
80
+ )
81
+ self.conv5 = Conv2DBNActiv(
82
+ nin, nout, 3, 1, dilations[2], dilations[2], activ=activ
83
+ )
84
+ self.bottleneck = Conv2DBNActiv(nout * 5, nout, 1, 1, 0, activ=activ)
85
+ self.dropout = nn.Dropout2d(0.1) if dropout else None
86
+
87
+ def forward(self, x):
88
+ _, _, h, w = x.size()
89
+ feat1 = F.interpolate(
90
+ self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
91
+ )
92
+ feat2 = self.conv2(x)
93
+ feat3 = self.conv3(x)
94
+ feat4 = self.conv4(x)
95
+ feat5 = self.conv5(x)
96
+ out = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1)
97
+ out = self.bottleneck(out)
98
+
99
+ if self.dropout is not None:
100
+ out = self.dropout(out)
101
+
102
+ return out
103
+
104
+
105
+ class LSTMModule(nn.Module):
106
+ def __init__(self, nin_conv, nin_lstm, nout_lstm):
107
+ super(LSTMModule, self).__init__()
108
+ self.conv = Conv2DBNActiv(nin_conv, 1, 1, 1, 0)
109
+ self.lstm = nn.LSTM(
110
+ input_size=nin_lstm, hidden_size=nout_lstm // 2, bidirectional=True
111
+ )
112
+ self.dense = nn.Sequential(
113
+ nn.Linear(nout_lstm, nin_lstm), nn.BatchNorm1d(nin_lstm), nn.ReLU()
114
+ )
115
+
116
+ def forward(self, x):
117
+ N, _, nbins, nframes = x.size()
118
+ h = self.conv(x)[:, 0] # N, nbins, nframes
119
+ h = h.permute(2, 0, 1) # nframes, N, nbins
120
+ h, _ = self.lstm(h)
121
+ h = self.dense(h.reshape(-1, h.size()[-1])) # nframes * N, nbins
122
+ h = h.reshape(nframes, N, 1, nbins)
123
+ h = h.permute(1, 2, 3, 0)
124
+
125
+ return h
infer/lib/uvr5_pack/lib_v5/model_param_init.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import pathlib
4
+
5
+ default_param = {}
6
+ default_param["bins"] = 768
7
+ default_param["unstable_bins"] = 9 # training only
8
+ default_param["reduction_bins"] = 762 # training only
9
+ default_param["sr"] = 44100
10
+ default_param["pre_filter_start"] = 757
11
+ default_param["pre_filter_stop"] = 768
12
+ default_param["band"] = {}
13
+
14
+
15
+ default_param["band"][1] = {
16
+ "sr": 11025,
17
+ "hl": 128,
18
+ "n_fft": 960,
19
+ "crop_start": 0,
20
+ "crop_stop": 245,
21
+ "lpf_start": 61, # inference only
22
+ "res_type": "polyphase",
23
+ }
24
+
25
+ default_param["band"][2] = {
26
+ "sr": 44100,
27
+ "hl": 512,
28
+ "n_fft": 1536,
29
+ "crop_start": 24,
30
+ "crop_stop": 547,
31
+ "hpf_start": 81, # inference only
32
+ "res_type": "sinc_best",
33
+ }
34
+
35
+
36
+ def int_keys(d):
37
+ r = {}
38
+ for k, v in d:
39
+ if k.isdigit():
40
+ k = int(k)
41
+ r[k] = v
42
+ return r
43
+
44
+
45
+ class ModelParameters(object):
46
+ def __init__(self, config_path=""):
47
+ if ".pth" == pathlib.Path(config_path).suffix:
48
+ import zipfile
49
+
50
+ with zipfile.ZipFile(config_path, "r") as zip:
51
+ self.param = json.loads(
52
+ zip.read("param.json"), object_pairs_hook=int_keys
53
+ )
54
+ elif ".json" == pathlib.Path(config_path).suffix:
55
+ with open(config_path, "r") as f:
56
+ self.param = json.loads(f.read(), object_pairs_hook=int_keys)
57
+ else:
58
+ self.param = default_param
59
+
60
+ for k in [
61
+ "mid_side",
62
+ "mid_side_b",
63
+ "mid_side_b2",
64
+ "stereo_w",
65
+ "stereo_n",
66
+ "reverse",
67
+ ]:
68
+ if not k in self.param:
69
+ self.param[k] = False
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr16000_hl512.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 16000,
8
+ "hl": 512,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 1024,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 16000,
17
+ "pre_filter_start": 1023,
18
+ "pre_filter_stop": 1024
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr32000_hl512.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 32000,
8
+ "hl": 512,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 1024,
12
+ "hpf_start": -1,
13
+ "res_type": "kaiser_fast"
14
+ }
15
+ },
16
+ "sr": 32000,
17
+ "pre_filter_start": 1000,
18
+ "pre_filter_stop": 1021
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr33075_hl384.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 33075,
8
+ "hl": 384,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 1024,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 33075,
17
+ "pre_filter_start": 1000,
18
+ "pre_filter_stop": 1021
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl1024.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 44100,
8
+ "hl": 1024,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 1024,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 44100,
17
+ "pre_filter_start": 1023,
18
+ "pre_filter_stop": 1024
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl256.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 256,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 44100,
8
+ "hl": 256,
9
+ "n_fft": 512,
10
+ "crop_start": 0,
11
+ "crop_stop": 256,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 44100,
17
+ "pre_filter_start": 256,
18
+ "pre_filter_stop": 256
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 44100,
8
+ "hl": 512,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 1024,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 44100,
17
+ "pre_filter_start": 1023,
18
+ "pre_filter_stop": 1024
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512_cut.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 1024,
3
+ "unstable_bins": 0,
4
+ "reduction_bins": 0,
5
+ "band": {
6
+ "1": {
7
+ "sr": 44100,
8
+ "hl": 512,
9
+ "n_fft": 2048,
10
+ "crop_start": 0,
11
+ "crop_stop": 700,
12
+ "hpf_start": -1,
13
+ "res_type": "sinc_best"
14
+ }
15
+ },
16
+ "sr": 44100,
17
+ "pre_filter_start": 1023,
18
+ "pre_filter_stop": 700
19
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/2band_32000.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 768,
3
+ "unstable_bins": 7,
4
+ "reduction_bins": 705,
5
+ "band": {
6
+ "1": {
7
+ "sr": 6000,
8
+ "hl": 66,
9
+ "n_fft": 512,
10
+ "crop_start": 0,
11
+ "crop_stop": 240,
12
+ "lpf_start": 60,
13
+ "lpf_stop": 118,
14
+ "res_type": "sinc_fastest"
15
+ },
16
+ "2": {
17
+ "sr": 32000,
18
+ "hl": 352,
19
+ "n_fft": 1024,
20
+ "crop_start": 22,
21
+ "crop_stop": 505,
22
+ "hpf_start": 44,
23
+ "hpf_stop": 23,
24
+ "res_type": "sinc_medium"
25
+ }
26
+ },
27
+ "sr": 32000,
28
+ "pre_filter_start": 710,
29
+ "pre_filter_stop": 731
30
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/2band_44100_lofi.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 512,
3
+ "unstable_bins": 7,
4
+ "reduction_bins": 510,
5
+ "band": {
6
+ "1": {
7
+ "sr": 11025,
8
+ "hl": 160,
9
+ "n_fft": 768,
10
+ "crop_start": 0,
11
+ "crop_stop": 192,
12
+ "lpf_start": 41,
13
+ "lpf_stop": 139,
14
+ "res_type": "sinc_fastest"
15
+ },
16
+ "2": {
17
+ "sr": 44100,
18
+ "hl": 640,
19
+ "n_fft": 1024,
20
+ "crop_start": 10,
21
+ "crop_stop": 320,
22
+ "hpf_start": 47,
23
+ "hpf_stop": 15,
24
+ "res_type": "sinc_medium"
25
+ }
26
+ },
27
+ "sr": 44100,
28
+ "pre_filter_start": 510,
29
+ "pre_filter_stop": 512
30
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/2band_48000.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 768,
3
+ "unstable_bins": 7,
4
+ "reduction_bins": 705,
5
+ "band": {
6
+ "1": {
7
+ "sr": 6000,
8
+ "hl": 66,
9
+ "n_fft": 512,
10
+ "crop_start": 0,
11
+ "crop_stop": 240,
12
+ "lpf_start": 60,
13
+ "lpf_stop": 240,
14
+ "res_type": "sinc_fastest"
15
+ },
16
+ "2": {
17
+ "sr": 48000,
18
+ "hl": 528,
19
+ "n_fft": 1536,
20
+ "crop_start": 22,
21
+ "crop_stop": 505,
22
+ "hpf_start": 82,
23
+ "hpf_stop": 22,
24
+ "res_type": "sinc_medium"
25
+ }
26
+ },
27
+ "sr": 48000,
28
+ "pre_filter_start": 710,
29
+ "pre_filter_stop": 731
30
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 768,
3
+ "unstable_bins": 5,
4
+ "reduction_bins": 733,
5
+ "band": {
6
+ "1": {
7
+ "sr": 11025,
8
+ "hl": 128,
9
+ "n_fft": 768,
10
+ "crop_start": 0,
11
+ "crop_stop": 278,
12
+ "lpf_start": 28,
13
+ "lpf_stop": 140,
14
+ "res_type": "polyphase"
15
+ },
16
+ "2": {
17
+ "sr": 22050,
18
+ "hl": 256,
19
+ "n_fft": 768,
20
+ "crop_start": 14,
21
+ "crop_stop": 322,
22
+ "hpf_start": 70,
23
+ "hpf_stop": 14,
24
+ "lpf_start": 283,
25
+ "lpf_stop": 314,
26
+ "res_type": "polyphase"
27
+ },
28
+ "3": {
29
+ "sr": 44100,
30
+ "hl": 512,
31
+ "n_fft": 768,
32
+ "crop_start": 131,
33
+ "crop_stop": 313,
34
+ "hpf_start": 154,
35
+ "hpf_stop": 141,
36
+ "res_type": "sinc_medium"
37
+ }
38
+ },
39
+ "sr": 44100,
40
+ "pre_filter_start": 757,
41
+ "pre_filter_stop": 768
42
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100_mid.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mid_side": true,
3
+ "bins": 768,
4
+ "unstable_bins": 5,
5
+ "reduction_bins": 733,
6
+ "band": {
7
+ "1": {
8
+ "sr": 11025,
9
+ "hl": 128,
10
+ "n_fft": 768,
11
+ "crop_start": 0,
12
+ "crop_stop": 278,
13
+ "lpf_start": 28,
14
+ "lpf_stop": 140,
15
+ "res_type": "polyphase"
16
+ },
17
+ "2": {
18
+ "sr": 22050,
19
+ "hl": 256,
20
+ "n_fft": 768,
21
+ "crop_start": 14,
22
+ "crop_stop": 322,
23
+ "hpf_start": 70,
24
+ "hpf_stop": 14,
25
+ "lpf_start": 283,
26
+ "lpf_stop": 314,
27
+ "res_type": "polyphase"
28
+ },
29
+ "3": {
30
+ "sr": 44100,
31
+ "hl": 512,
32
+ "n_fft": 768,
33
+ "crop_start": 131,
34
+ "crop_stop": 313,
35
+ "hpf_start": 154,
36
+ "hpf_stop": 141,
37
+ "res_type": "sinc_medium"
38
+ }
39
+ },
40
+ "sr": 44100,
41
+ "pre_filter_start": 757,
42
+ "pre_filter_stop": 768
43
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100_msb2.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mid_side_b2": true,
3
+ "bins": 640,
4
+ "unstable_bins": 7,
5
+ "reduction_bins": 565,
6
+ "band": {
7
+ "1": {
8
+ "sr": 11025,
9
+ "hl": 108,
10
+ "n_fft": 1024,
11
+ "crop_start": 0,
12
+ "crop_stop": 187,
13
+ "lpf_start": 92,
14
+ "lpf_stop": 186,
15
+ "res_type": "polyphase"
16
+ },
17
+ "2": {
18
+ "sr": 22050,
19
+ "hl": 216,
20
+ "n_fft": 768,
21
+ "crop_start": 0,
22
+ "crop_stop": 212,
23
+ "hpf_start": 68,
24
+ "hpf_stop": 34,
25
+ "lpf_start": 174,
26
+ "lpf_stop": 209,
27
+ "res_type": "polyphase"
28
+ },
29
+ "3": {
30
+ "sr": 44100,
31
+ "hl": 432,
32
+ "n_fft": 640,
33
+ "crop_start": 66,
34
+ "crop_stop": 307,
35
+ "hpf_start": 86,
36
+ "hpf_stop": 72,
37
+ "res_type": "kaiser_fast"
38
+ }
39
+ },
40
+ "sr": 44100,
41
+ "pre_filter_start": 639,
42
+ "pre_filter_stop": 640
43
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 768,
3
+ "unstable_bins": 7,
4
+ "reduction_bins": 668,
5
+ "band": {
6
+ "1": {
7
+ "sr": 11025,
8
+ "hl": 128,
9
+ "n_fft": 1024,
10
+ "crop_start": 0,
11
+ "crop_stop": 186,
12
+ "lpf_start": 37,
13
+ "lpf_stop": 73,
14
+ "res_type": "polyphase"
15
+ },
16
+ "2": {
17
+ "sr": 11025,
18
+ "hl": 128,
19
+ "n_fft": 512,
20
+ "crop_start": 4,
21
+ "crop_stop": 185,
22
+ "hpf_start": 36,
23
+ "hpf_stop": 18,
24
+ "lpf_start": 93,
25
+ "lpf_stop": 185,
26
+ "res_type": "polyphase"
27
+ },
28
+ "3": {
29
+ "sr": 22050,
30
+ "hl": 256,
31
+ "n_fft": 512,
32
+ "crop_start": 46,
33
+ "crop_stop": 186,
34
+ "hpf_start": 93,
35
+ "hpf_stop": 46,
36
+ "lpf_start": 164,
37
+ "lpf_stop": 186,
38
+ "res_type": "polyphase"
39
+ },
40
+ "4": {
41
+ "sr": 44100,
42
+ "hl": 512,
43
+ "n_fft": 768,
44
+ "crop_start": 121,
45
+ "crop_stop": 382,
46
+ "hpf_start": 138,
47
+ "hpf_stop": 123,
48
+ "res_type": "sinc_medium"
49
+ }
50
+ },
51
+ "sr": 44100,
52
+ "pre_filter_start": 740,
53
+ "pre_filter_stop": 768
54
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_mid.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bins": 768,
3
+ "unstable_bins": 7,
4
+ "mid_side": true,
5
+ "reduction_bins": 668,
6
+ "band": {
7
+ "1": {
8
+ "sr": 11025,
9
+ "hl": 128,
10
+ "n_fft": 1024,
11
+ "crop_start": 0,
12
+ "crop_stop": 186,
13
+ "lpf_start": 37,
14
+ "lpf_stop": 73,
15
+ "res_type": "polyphase"
16
+ },
17
+ "2": {
18
+ "sr": 11025,
19
+ "hl": 128,
20
+ "n_fft": 512,
21
+ "crop_start": 4,
22
+ "crop_stop": 185,
23
+ "hpf_start": 36,
24
+ "hpf_stop": 18,
25
+ "lpf_start": 93,
26
+ "lpf_stop": 185,
27
+ "res_type": "polyphase"
28
+ },
29
+ "3": {
30
+ "sr": 22050,
31
+ "hl": 256,
32
+ "n_fft": 512,
33
+ "crop_start": 46,
34
+ "crop_stop": 186,
35
+ "hpf_start": 93,
36
+ "hpf_stop": 46,
37
+ "lpf_start": 164,
38
+ "lpf_stop": 186,
39
+ "res_type": "polyphase"
40
+ },
41
+ "4": {
42
+ "sr": 44100,
43
+ "hl": 512,
44
+ "n_fft": 768,
45
+ "crop_start": 121,
46
+ "crop_stop": 382,
47
+ "hpf_start": 138,
48
+ "hpf_stop": 123,
49
+ "res_type": "sinc_medium"
50
+ }
51
+ },
52
+ "sr": 44100,
53
+ "pre_filter_start": 740,
54
+ "pre_filter_stop": 768
55
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_msb.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mid_side_b": true,
3
+ "bins": 768,
4
+ "unstable_bins": 7,
5
+ "reduction_bins": 668,
6
+ "band": {
7
+ "1": {
8
+ "sr": 11025,
9
+ "hl": 128,
10
+ "n_fft": 1024,
11
+ "crop_start": 0,
12
+ "crop_stop": 186,
13
+ "lpf_start": 37,
14
+ "lpf_stop": 73,
15
+ "res_type": "polyphase"
16
+ },
17
+ "2": {
18
+ "sr": 11025,
19
+ "hl": 128,
20
+ "n_fft": 512,
21
+ "crop_start": 4,
22
+ "crop_stop": 185,
23
+ "hpf_start": 36,
24
+ "hpf_stop": 18,
25
+ "lpf_start": 93,
26
+ "lpf_stop": 185,
27
+ "res_type": "polyphase"
28
+ },
29
+ "3": {
30
+ "sr": 22050,
31
+ "hl": 256,
32
+ "n_fft": 512,
33
+ "crop_start": 46,
34
+ "crop_stop": 186,
35
+ "hpf_start": 93,
36
+ "hpf_stop": 46,
37
+ "lpf_start": 164,
38
+ "lpf_stop": 186,
39
+ "res_type": "polyphase"
40
+ },
41
+ "4": {
42
+ "sr": 44100,
43
+ "hl": 512,
44
+ "n_fft": 768,
45
+ "crop_start": 121,
46
+ "crop_stop": 382,
47
+ "hpf_start": 138,
48
+ "hpf_stop": 123,
49
+ "res_type": "sinc_medium"
50
+ }
51
+ },
52
+ "sr": 44100,
53
+ "pre_filter_start": 740,
54
+ "pre_filter_stop": 768
55
+ }
infer/lib/uvr5_pack/lib_v5/modelparams/4band_44100_msb2.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mid_side_b": true,
3
+ "bins": 768,
4
+ "unstable_bins": 7,
5
+ "reduction_bins": 668,
6
+ "band": {
7
+ "1": {
8
+ "sr": 11025,
9
+ "hl": 128,
10
+ "n_fft": 1024,
11
+ "crop_start": 0,
12
+ "crop_stop": 186,
13
+ "lpf_start": 37,
14
+ "lpf_stop": 73,
15
+ "res_type": "polyphase"
16
+ },
17
+ "2": {
18
+ "sr": 11025,
19
+ "hl": 128,
20
+ "n_fft": 512,
21
+ "crop_start": 4,
22
+ "crop_stop": 185,
23
+ "hpf_start": 36,
24
+ "hpf_stop": 18,
25
+ "lpf_start": 93,
26
+ "lpf_stop": 185,
27
+ "res_type": "polyphase"
28
+ },
29
+ "3": {
30
+ "sr": 22050,
31
+ "hl": 256,
32
+ "n_fft": 512,
33
+ "crop_start": 46,
34
+ "crop_stop": 186,
35
+ "hpf_start": 93,
36
+ "hpf_stop": 46,
37
+ "lpf_start": 164,
38
+ "lpf_stop": 186,
39
+ "res_type": "polyphase"
40
+ },
41
+ "4": {
42
+ "sr": 44100,
43
+ "hl": 512,
44
+ "n_fft": 768,
45
+ "crop_start": 121,
46
+ "crop_stop": 382,
47
+ "hpf_start": 138,
48
+ "hpf_stop": 123,
49
+ "res_type": "sinc_medium"
50
+ }
51
+ },
52
+ "sr": 44100,
53
+ "pre_filter_start": 740,
54
+ "pre_filter_stop": 768
55
+ }