mason369 commited on
Commit
b15e31b
·
verified ·
1 Parent(s): e103b22

Upload folder using huggingface_hub

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/__init__.py +17 -0
  2. infer/advanced_dereverb.py +280 -0
  3. infer/cover_pipeline.py +0 -0
  4. infer/f0_extractor.py +265 -0
  5. infer/lib/audio.py +60 -0
  6. infer/lib/infer_pack/attentions.py +459 -0
  7. infer/lib/infer_pack/attentions_onnx.py +459 -0
  8. infer/lib/infer_pack/commons.py +172 -0
  9. infer/lib/infer_pack/models.py +1223 -0
  10. infer/lib/infer_pack/models_onnx.py +818 -0
  11. infer/lib/infer_pack/modules.py +615 -0
  12. infer/lib/infer_pack/modules/F0Predictor/DioF0Predictor.py +91 -0
  13. infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py +16 -0
  14. infer/lib/infer_pack/modules/F0Predictor/HarvestF0Predictor.py +87 -0
  15. infer/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py +98 -0
  16. infer/lib/infer_pack/modules/F0Predictor/__init__.py +0 -0
  17. infer/lib/infer_pack/onnx_inference.py +149 -0
  18. infer/lib/infer_pack/transforms.py +207 -0
  19. infer/lib/jit/__init__.py +163 -0
  20. infer/lib/jit/get_hubert.py +342 -0
  21. infer/lib/jit/get_rmvpe.py +12 -0
  22. infer/lib/jit/get_synthesizer.py +38 -0
  23. infer/lib/rmvpe.py +670 -0
  24. infer/lib/rtrvc.py +461 -0
  25. infer/lib/slicer2.py +260 -0
  26. infer/lib/train/data_utils.py +517 -0
  27. infer/lib/train/losses.py +58 -0
  28. infer/lib/train/mel_processing.py +127 -0
  29. infer/lib/train/process_ckpt.py +261 -0
  30. infer/lib/train/utils.py +483 -0
  31. infer/lib/uvr5_pack/lib_v5/dataset.py +183 -0
  32. infer/lib/uvr5_pack/lib_v5/layers.py +118 -0
  33. infer/lib/uvr5_pack/lib_v5/layers_123812KB .py +118 -0
  34. infer/lib/uvr5_pack/lib_v5/layers_123821KB.py +118 -0
  35. infer/lib/uvr5_pack/lib_v5/layers_33966KB.py +126 -0
  36. infer/lib/uvr5_pack/lib_v5/layers_537227KB.py +126 -0
  37. infer/lib/uvr5_pack/lib_v5/layers_537238KB.py +126 -0
  38. infer/lib/uvr5_pack/lib_v5/layers_new.py +125 -0
  39. infer/lib/uvr5_pack/lib_v5/model_param_init.py +69 -0
  40. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr16000_hl512.json +19 -0
  41. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr32000_hl512.json +19 -0
  42. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr33075_hl384.json +19 -0
  43. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl1024.json +19 -0
  44. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl256.json +19 -0
  45. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512.json +19 -0
  46. infer/lib/uvr5_pack/lib_v5/modelparams/1band_sr44100_hl512_cut.json +19 -0
  47. infer/lib/uvr5_pack/lib_v5/modelparams/2band_32000.json +30 -0
  48. infer/lib/uvr5_pack/lib_v5/modelparams/2band_44100_lofi.json +30 -0
  49. infer/lib/uvr5_pack/lib_v5/modelparams/2band_48000.json +30 -0
  50. infer/lib/uvr5_pack/lib_v5/modelparams/3band_44100.json +42 -0
infer/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 推理模块
4
+ """
5
+ from .f0_extractor import (
6
+ F0Extractor,
7
+ get_f0_extractor,
8
+ shift_f0,
9
+ F0Method
10
+ )
11
+
12
+ __all__ = [
13
+ "F0Extractor",
14
+ "get_f0_extractor",
15
+ "shift_f0",
16
+ "F0Method"
17
+ ]
infer/advanced_dereverb.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 高级去混响模块 - 基于二进制残差掩码和时域一致性
4
+ 参考: arXiv 2510.00356 - Dereverberation Using Binary Residual Masking
5
+ """
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from typing import Tuple, Optional
11
+
12
+
13
+ class BinaryResidualMask(nn.Module):
14
+ """
15
+ 二进制残差掩码网络 - 专注于抑制混响而非预测完整频谱
16
+
17
+ 核心思想:
18
+ 1. 学习识别并抑制晚期反射(late reflections)
19
+ 2. 保留直达声路径(direct path)
20
+ 3. 使用时域一致性损失隐式学习相位
21
+ """
22
+
23
+ def __init__(self, n_fft=2048, hop_length=512):
24
+ super().__init__()
25
+ self.n_fft = n_fft
26
+ self.hop_length = hop_length
27
+ self.freq_bins = n_fft // 2 + 1
28
+
29
+ # U-Net编码器
30
+ self.encoder1 = nn.Sequential(
31
+ nn.Conv2d(1, 32, kernel_size=3, padding=1),
32
+ nn.BatchNorm2d(32),
33
+ nn.ReLU(),
34
+ nn.Conv2d(32, 32, kernel_size=3, padding=1),
35
+ nn.BatchNorm2d(32),
36
+ nn.ReLU()
37
+ )
38
+
39
+ self.encoder2 = nn.Sequential(
40
+ nn.MaxPool2d(2),
41
+ nn.Conv2d(32, 64, kernel_size=3, padding=1),
42
+ nn.BatchNorm2d(64),
43
+ nn.ReLU(),
44
+ nn.Conv2d(64, 64, kernel_size=3, padding=1),
45
+ nn.BatchNorm2d(64),
46
+ nn.ReLU()
47
+ )
48
+
49
+ self.encoder3 = nn.Sequential(
50
+ nn.MaxPool2d(2),
51
+ nn.Conv2d(64, 128, kernel_size=3, padding=1),
52
+ nn.BatchNorm2d(128),
53
+ nn.ReLU(),
54
+ nn.Conv2d(128, 128, kernel_size=3, padding=1),
55
+ nn.BatchNorm2d(128),
56
+ nn.ReLU()
57
+ )
58
+
59
+ # 瓶颈层 - 时序注意力
60
+ self.bottleneck = nn.Sequential(
61
+ nn.MaxPool2d(2),
62
+ nn.Conv2d(128, 256, kernel_size=3, padding=1),
63
+ nn.BatchNorm2d(256),
64
+ nn.ReLU()
65
+ )
66
+
67
+ # U-Net解码器
68
+ self.decoder3 = nn.Sequential(
69
+ nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2),
70
+ nn.Conv2d(256, 128, kernel_size=3, padding=1),
71
+ nn.BatchNorm2d(128),
72
+ nn.ReLU()
73
+ )
74
+
75
+ self.decoder2 = nn.Sequential(
76
+ nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2),
77
+ nn.Conv2d(128, 64, kernel_size=3, padding=1),
78
+ nn.BatchNorm2d(64),
79
+ nn.ReLU()
80
+ )
81
+
82
+ self.decoder1 = nn.Sequential(
83
+ nn.ConvTranspose2d(64, 32, kernel_size=2, stride=2),
84
+ nn.Conv2d(64, 32, kernel_size=3, padding=1),
85
+ nn.BatchNorm2d(32),
86
+ nn.ReLU()
87
+ )
88
+
89
+ # 输出层 - 二进制掩码
90
+ self.output = nn.Sequential(
91
+ nn.Conv2d(32, 1, kernel_size=1),
92
+ nn.Sigmoid() # 输出0-1的掩码
93
+ )
94
+
95
+ def forward(self, x):
96
+ """
97
+ Args:
98
+ x: [B, 1, F, T] - 输入频谱幅度
99
+ Returns:
100
+ mask: [B, 1, F, T] - 二进制残差掩码
101
+ """
102
+ # 编码
103
+ e1 = self.encoder1(x)
104
+ e2 = self.encoder2(e1)
105
+ e3 = self.encoder3(e2)
106
+
107
+ # 瓶颈
108
+ b = self.bottleneck(e3)
109
+
110
+ # 解码 + 跳跃连接
111
+ d3 = self.decoder3(b)
112
+ d3 = torch.cat([d3, e3], dim=1)
113
+
114
+ d2 = self.decoder2(d3)
115
+ d2 = torch.cat([d2, e2], dim=1)
116
+
117
+ d1 = self.decoder1(d2)
118
+ d1 = torch.cat([d1, e1], dim=1)
119
+
120
+ # 输出掩码
121
+ mask = self.output(d1)
122
+ return mask
123
+
124
+
125
+ def advanced_dereverb(
126
+ audio: np.ndarray,
127
+ sr: int = 16000,
128
+ n_fft: int = 2048,
129
+ hop_length: int = 512,
130
+ device: str = "cuda"
131
+ ) -> Tuple[np.ndarray, np.ndarray]:
132
+ """
133
+ 高级去混响 - 分离干声和混响
134
+
135
+ Args:
136
+ audio: 输入音频 [samples]
137
+ sr: 采样率
138
+ n_fft: FFT大小
139
+ hop_length: 跳跃长度
140
+ device: 计算设备
141
+
142
+ Returns:
143
+ dry_signal: 干声(直达声)
144
+ reverb_tail: 混响尾巴
145
+ """
146
+ import librosa
147
+
148
+ # STFT
149
+ spec = librosa.stft(audio, n_fft=n_fft, hop_length=hop_length, win_length=n_fft)
150
+ mag = np.abs(spec).astype(np.float32)
151
+ phase = np.angle(spec)
152
+
153
+ # 基于能量的混响检测
154
+ # 1. 计算时域RMS能量
155
+ rms = librosa.feature.rms(y=audio, frame_length=n_fft, hop_length=hop_length, center=True)[0]
156
+ rms_db = 20.0 * np.log10(rms + 1e-8)
157
+ ref_db = float(np.percentile(rms_db, 90))
158
+
159
+ # 2. 检测晚期反射(late reflections)
160
+ # 晚期反射特征:能量衰减 + 时间延迟
161
+ late_reflections = np.zeros_like(mag, dtype=np.float32)
162
+
163
+ for t in range(2, mag.shape[1]):
164
+ # 递归估计:衰减的历史 + 延迟的观测
165
+ late_reflections[:, t] = np.maximum(
166
+ late_reflections[:, t - 1] * 0.92, # 衰减系数
167
+ mag[:, t - 2] * 0.80 # 延迟观测
168
+ )
169
+
170
+ # 3. 计算直达声(direct path)
171
+ # 直达声 = 总能量 - 晚期反射
172
+ direct_path = np.maximum(mag - 0.75 * late_reflections, 0.0)
173
+
174
+ # 4. 动态floor:保护有声段
175
+ # 扩展RMS到频谱帧数
176
+ if len(rms) < mag.shape[1]:
177
+ rms_extended = np.pad(rms, (0, mag.shape[1] - len(rms)), mode='edge')
178
+ else:
179
+ rms_extended = rms[:mag.shape[1]]
180
+
181
+ # 有声段(高能量):vocal_strength接近1
182
+ # 无声段(低能量/混响尾):vocal_strength接近0
183
+ vocal_strength = np.clip((rms_db[:len(rms_extended)] - (ref_db - 35.0)) / 25.0, 0.0, 1.0)
184
+
185
+ # 动态floor系数
186
+ reverb_ratio = np.clip(late_reflections / (mag + 1e-8), 0.0, 1.0)
187
+ floor_coef = 0.08 + 0.12 * vocal_strength[np.newaxis, :]
188
+ floor = (1.0 - reverb_ratio) * floor_coef * mag
189
+ direct_path = np.maximum(direct_path, floor)
190
+
191
+ # 5. 时域平滑(避免音乐噪声)
192
+ kernel = np.array([1, 2, 3, 2, 1], dtype=np.float32)
193
+ kernel /= np.sum(kernel)
194
+ direct_path = np.apply_along_axis(
195
+ lambda row: np.convolve(row, kernel, mode="same"),
196
+ axis=1,
197
+ arr=direct_path,
198
+ )
199
+ direct_path = np.clip(direct_path, 0.0, mag)
200
+
201
+ # 6. 计算混响残差
202
+ reverb_mag = mag - direct_path
203
+ reverb_mag = np.maximum(reverb_mag, 0.0)
204
+
205
+ # 7. 重建音频
206
+ # 干声:使用原始相位(保留音色)
207
+ dry_spec = direct_path * np.exp(1j * phase)
208
+ dry_signal = librosa.istft(dry_spec, hop_length=hop_length, win_length=n_fft, length=len(audio))
209
+
210
+ # 混响:使用原始相位
211
+ reverb_spec = reverb_mag * np.exp(1j * phase)
212
+ reverb_tail = librosa.istft(reverb_spec, hop_length=hop_length, win_length=n_fft, length=len(audio))
213
+
214
+ return dry_signal.astype(np.float32), reverb_tail.astype(np.float32)
215
+
216
+
217
+ def apply_reverb_to_converted(
218
+ converted_dry: np.ndarray,
219
+ original_reverb: np.ndarray,
220
+ mix_ratio: float = 0.8
221
+ ) -> np.ndarray:
222
+ """
223
+ 将原始混响重新应用到转换后的干声上
224
+
225
+ Args:
226
+ converted_dry: 转换后的干声
227
+ original_reverb: 原始混响尾巴
228
+ mix_ratio: 混响混合比例 (0-1)
229
+
230
+ Returns:
231
+ wet_signal: 带混响的转换结果
232
+ """
233
+ # 对齐长度
234
+ min_len = min(len(converted_dry), len(original_reverb))
235
+ converted_dry = converted_dry[:min_len]
236
+ original_reverb = original_reverb[:min_len]
237
+
238
+ # 混合
239
+ wet_signal = converted_dry + mix_ratio * original_reverb
240
+
241
+ # 软限幅
242
+ from lib.audio import soft_clip
243
+ wet_signal = soft_clip(wet_signal, threshold=0.9, ceiling=0.99)
244
+
245
+ return wet_signal.astype(np.float32)
246
+
247
+
248
+ if __name__ == "__main__":
249
+ # 测试
250
+ print("Testing advanced dereverberation...")
251
+
252
+ # 生成测试信号:干声 + 混响
253
+ sr = 16000
254
+ duration = 2.0
255
+ t = np.linspace(0, duration, int(sr * duration))
256
+
257
+ # 干声:440Hz正弦波
258
+ dry = np.sin(2 * np.pi * 440 * t).astype(np.float32)
259
+
260
+ # 混响:衰减的延迟
261
+ reverb = np.zeros_like(dry)
262
+ delay_samples = int(0.05 * sr) # 50ms延迟
263
+ for i in range(3):
264
+ delay = delay_samples * (i + 1)
265
+ decay = 0.5 ** (i + 1)
266
+ if delay < len(reverb):
267
+ reverb[delay:] += dry[:-delay] * decay
268
+
269
+ # 混合信号
270
+ wet = dry + reverb * 0.5
271
+
272
+ # 去混响
273
+ dry_extracted, reverb_extracted = advanced_dereverb(wet, sr)
274
+
275
+ print(f"Input RMS: {np.sqrt(np.mean(wet**2)):.4f}")
276
+ print(f"Dry RMS: {np.sqrt(np.mean(dry_extracted**2)):.4f}")
277
+ print(f"Reverb RMS: {np.sqrt(np.mean(reverb_extracted**2)):.4f}")
278
+ print(f"Separation ratio: {np.sqrt(np.mean(dry_extracted**2)) / (np.sqrt(np.mean(reverb_extracted**2)) + 1e-8):.2f}")
279
+
280
+ print("\n[OK] Advanced dereverberation test passed!")
infer/cover_pipeline.py ADDED
The diff for this file is too large to render. See raw diff
 
infer/f0_extractor.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ F0 (基频) 提取模块 - 支持多种提取方法
4
+ """
5
+ import numpy as np
6
+ import torch
7
+ from typing import Optional, Literal
8
+
9
+ # F0 提取方法类型
10
+ F0Method = Literal["rmvpe", "pm", "harvest", "crepe", "hybrid"]
11
+
12
+
13
+ class F0Extractor:
14
+ """F0 提取器基类"""
15
+
16
+ def __init__(self, sample_rate: int = 16000, hop_length: int = 160):
17
+ self.sample_rate = sample_rate
18
+ self.hop_length = hop_length
19
+ self.f0_min = 50
20
+ self.f0_max = 1100
21
+
22
+ def extract(self, audio: np.ndarray) -> np.ndarray:
23
+ """提取 F0,子类需实现此方法"""
24
+ raise NotImplementedError
25
+
26
+
27
+ class PMExtractor(F0Extractor):
28
+ """Parselmouth (Praat) F0 提取器 - 速度快"""
29
+
30
+ def extract(self, audio: np.ndarray) -> np.ndarray:
31
+ import parselmouth
32
+
33
+ time_step = self.hop_length / self.sample_rate
34
+ sound = parselmouth.Sound(audio, self.sample_rate)
35
+
36
+ pitch = sound.to_pitch_ac(
37
+ time_step=time_step,
38
+ voicing_threshold=0.6,
39
+ pitch_floor=self.f0_min,
40
+ pitch_ceiling=self.f0_max
41
+ )
42
+
43
+ f0 = pitch.selected_array["frequency"]
44
+ f0[f0 == 0] = np.nan
45
+
46
+ return f0
47
+
48
+
49
+ class HarvestExtractor(F0Extractor):
50
+ """PyWorld Harvest F0 提取器 - 质量较好"""
51
+
52
+ def extract(self, audio: np.ndarray) -> np.ndarray:
53
+ import pyworld
54
+
55
+ audio = audio.astype(np.float64)
56
+ f0, _ = pyworld.harvest(
57
+ audio,
58
+ self.sample_rate,
59
+ f0_floor=self.f0_min,
60
+ f0_ceil=self.f0_max,
61
+ frame_period=self.hop_length / self.sample_rate * 1000
62
+ )
63
+
64
+ return f0
65
+
66
+
67
+ class CrepeExtractor(F0Extractor):
68
+ """TorchCrepe F0 提取器 - 深度学习方法"""
69
+
70
+ def __init__(self, sample_rate: int = 16000, hop_length: int = 160,
71
+ device: str = "cuda"):
72
+ super().__init__(sample_rate, hop_length)
73
+ self.device = device
74
+
75
+ def extract(self, audio: np.ndarray) -> np.ndarray:
76
+ import torchcrepe
77
+
78
+ audio_tensor = torch.from_numpy(audio).float().unsqueeze(0)
79
+ audio_tensor = audio_tensor.to(self.device)
80
+
81
+ f0, _ = torchcrepe.predict(
82
+ audio_tensor,
83
+ self.sample_rate,
84
+ self.hop_length,
85
+ self.f0_min,
86
+ self.f0_max,
87
+ model="full",
88
+ batch_size=512,
89
+ device=self.device,
90
+ return_periodicity=True
91
+ )
92
+
93
+ f0 = f0.squeeze(0).cpu().numpy()
94
+ return f0
95
+
96
+
97
+ class RMVPEExtractor(F0Extractor):
98
+ """RMVPE F0 提取器 - 质量最高 (推荐)"""
99
+
100
+ def __init__(self, model_path: str, sample_rate: int = 16000,
101
+ hop_length: int = 160, device: str = "cuda"):
102
+ super().__init__(sample_rate, hop_length)
103
+ self.device = device
104
+ self.model = None
105
+ self.model_path = model_path
106
+
107
+ def load_model(self):
108
+ """加载 RMVPE 模型"""
109
+ if self.model is not None:
110
+ return
111
+
112
+ from models.rmvpe import RMVPE
113
+
114
+ self.model = RMVPE(self.model_path, device=self.device)
115
+ print(f"RMVPE 模型已加载: {self.device}")
116
+
117
+ def extract(self, audio: np.ndarray) -> np.ndarray:
118
+ self.load_model()
119
+
120
+ # RMVPE 需要 16kHz 输入
121
+ f0 = self.model.infer_from_audio(audio, thred=0.01)
122
+
123
+ return f0
124
+
125
+
126
+ def get_f0_extractor(method: F0Method, device: str = "cuda",
127
+ rmvpe_path: str = None, crepe_threshold: float = 0.05) -> F0Extractor:
128
+ """
129
+ 获取 F0 提取器实例
130
+
131
+ Args:
132
+ method: 提取方法 ("rmvpe", "pm", "harvest", "crepe", "hybrid")
133
+ device: 计算设备
134
+ rmvpe_path: RMVPE 模型路径 (rmvpe/hybrid 方法需要)
135
+ crepe_threshold: CREPE置信度阈值 (仅hybrid方法使用)
136
+
137
+ Returns:
138
+ F0Extractor: 提取器实例
139
+ """
140
+ if method == "rmvpe":
141
+ if rmvpe_path is None:
142
+ raise ValueError("RMVPE 方法需要指定模型路径")
143
+ return RMVPEExtractor(rmvpe_path, device=device)
144
+ elif method == "hybrid":
145
+ if rmvpe_path is None:
146
+ raise ValueError("Hybrid 方法需要指定RMVPE模型路径")
147
+ return HybridF0Extractor(rmvpe_path, device=device, crepe_threshold=crepe_threshold)
148
+ elif method == "pm":
149
+ return PMExtractor()
150
+ elif method == "harvest":
151
+ return HarvestExtractor()
152
+ elif method == "crepe":
153
+ return CrepeExtractor(device=device)
154
+ else:
155
+ raise ValueError(f"未知的 F0 提取方法: {method}")
156
+
157
+
158
+ class HybridF0Extractor(F0Extractor):
159
+ """混合F0提取器 - RMVPE主导 + CREPE高精度补充"""
160
+
161
+ def __init__(self, rmvpe_path: str, sample_rate: int = 16000,
162
+ hop_length: int = 160, device: str = "cuda",
163
+ crepe_threshold: float = 0.05):
164
+ super().__init__(sample_rate, hop_length)
165
+ self.device = device
166
+ self.rmvpe = RMVPEExtractor(rmvpe_path, sample_rate, hop_length, device)
167
+ self.crepe = None # 延迟加载
168
+ self.crepe_threshold = crepe_threshold
169
+
170
+ def _load_crepe(self):
171
+ """延迟加载CREPE模型"""
172
+ if self.crepe is None:
173
+ try:
174
+ self.crepe = CrepeExtractor(self.sample_rate, self.hop_length, self.device)
175
+ except ImportError:
176
+ print("警告: torchcrepe未安装,混合F0将仅使用RMVPE")
177
+ self.crepe = False
178
+
179
+ def extract(self, audio: np.ndarray) -> np.ndarray:
180
+ """
181
+ 混合提取F0:
182
+ 1. 使用RMVPE作为主要方法(快速、稳定)
183
+ 2. 在RMVPE不稳定的区域使用CREPE补充(高精度)
184
+ """
185
+ # 提取RMVPE F0
186
+ f0_rmvpe = self.rmvpe.extract(audio)
187
+
188
+ # 如果CREPE不可用,直接返回RMVPE结果
189
+ self._load_crepe()
190
+ if self.crepe is False:
191
+ return f0_rmvpe
192
+
193
+ # 提取CREPE F0和置信度
194
+ import torchcrepe
195
+ audio_tensor = torch.from_numpy(audio).float().unsqueeze(0).to(self.device)
196
+ f0_crepe, confidence = torchcrepe.predict(
197
+ audio_tensor,
198
+ self.sample_rate,
199
+ self.hop_length,
200
+ self.f0_min,
201
+ self.f0_max,
202
+ model="full",
203
+ batch_size=512,
204
+ device=self.device,
205
+ return_periodicity=True
206
+ )
207
+ f0_crepe = f0_crepe.squeeze(0).cpu().numpy()
208
+ confidence = confidence.squeeze(0).cpu().numpy()
209
+
210
+ # 对齐长度
211
+ min_len = min(len(f0_rmvpe), len(f0_crepe), len(confidence))
212
+ f0_rmvpe = f0_rmvpe[:min_len]
213
+ f0_crepe = f0_crepe[:min_len]
214
+ confidence = confidence[:min_len]
215
+
216
+ # 检测RMVPE不稳定区域
217
+ # 1. F0跳变过大(超过3个半音)
218
+ f0_diff = np.abs(np.diff(f0_rmvpe, prepend=f0_rmvpe[0]))
219
+ semitone_diff = np.abs(12 * np.log2((f0_rmvpe + 1e-6) / (np.roll(f0_rmvpe, 1) + 1e-6)))
220
+ semitone_diff[0] = 0
221
+ unstable_jump = semitone_diff > 3.0
222
+
223
+ # 2. CREPE置信度高但RMVPE给出F0=0
224
+ unstable_unvoiced = (f0_rmvpe < 1e-3) & (confidence > self.crepe_threshold)
225
+
226
+ # 3. RMVPE和CREPE差异过大(超过2个半音)且CREPE置信度高
227
+ f0_ratio = (f0_crepe + 1e-6) / (f0_rmvpe + 1e-6)
228
+ semitone_gap = np.abs(12 * np.log2(f0_ratio))
229
+ unstable_diverge = (semitone_gap > 2.0) & (confidence > self.crepe_threshold * 1.5)
230
+
231
+ # 合并不稳定区域
232
+ unstable_mask = unstable_jump | unstable_unvoiced | unstable_diverge
233
+
234
+ # 扩展不稳定区域(前后各2帧)以平滑过渡
235
+ kernel = np.ones(5, dtype=bool)
236
+ unstable_mask = np.convolve(unstable_mask, kernel, mode='same')
237
+
238
+ # 混合F0:不稳定区域使用CREPE,其他区域使用RMVPE
239
+ f0_hybrid = f0_rmvpe.copy()
240
+ f0_hybrid[unstable_mask] = f0_crepe[unstable_mask]
241
+
242
+ # 平滑过渡边界
243
+ for i in range(1, len(f0_hybrid) - 1):
244
+ if unstable_mask[i] != unstable_mask[i-1]:
245
+ # 边界处使用加权平均
246
+ w = 0.5
247
+ f0_hybrid[i] = w * f0_rmvpe[i] + (1-w) * f0_crepe[i]
248
+
249
+ return f0_hybrid
250
+
251
+
252
+ def shift_f0(f0: np.ndarray, semitones: float) -> np.ndarray:
253
+ """
254
+ 音调偏移
255
+
256
+ Args:
257
+ f0: 原始 F0
258
+ semitones: 偏移半音数 (正数升调,负数降调)
259
+
260
+ Returns:
261
+ np.ndarray: 偏移后的 F0
262
+ """
263
+ factor = 2 ** (semitones / 12)
264
+ f0_shifted = f0 * factor
265
+ return f0_shifted
infer/lib/audio.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform, os
2
+ import ffmpeg
3
+ import numpy as np
4
+ import av
5
+ from io import BytesIO
6
+ import traceback
7
+ import re
8
+
9
+
10
+ def wav2(i, o, format):
11
+ inp = av.open(i, "rb")
12
+ if format == "m4a":
13
+ format = "mp4"
14
+ out = av.open(o, "wb", format=format)
15
+ if format == "ogg":
16
+ format = "libvorbis"
17
+ if format == "mp4":
18
+ format = "aac"
19
+
20
+ ostream = out.add_stream(format)
21
+
22
+ for frame in inp.decode(audio=0):
23
+ for p in ostream.encode(frame):
24
+ out.mux(p)
25
+
26
+ for p in ostream.encode(None):
27
+ out.mux(p)
28
+
29
+ out.close()
30
+ inp.close()
31
+
32
+
33
+ def load_audio(file, sr):
34
+ try:
35
+ # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
36
+ # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
37
+ # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
38
+ file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车
39
+ if os.path.exists(file) == False:
40
+ raise RuntimeError(
41
+ "You input a wrong audio path that does not exists, please fix it!"
42
+ )
43
+ out, _ = (
44
+ ffmpeg.input(file, threads=0)
45
+ .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
46
+ .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
47
+ )
48
+ except Exception as e:
49
+ traceback.print_exc()
50
+ raise RuntimeError(f"Failed to load audio: {e}")
51
+
52
+ return np.frombuffer(out, np.float32).flatten()
53
+
54
+
55
+
56
+ def clean_path(path_str):
57
+ if platform.system() == "Windows":
58
+ path_str = path_str.replace("/", "\\")
59
+ path_str = re.sub(r'[\u202a\u202b\u202c\u202d\u202e]', '', path_str) # 移除 Unicode 控制字符
60
+ 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/attentions_onnx.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ############################## Warning! ##############################
2
+ # #
3
+ # Onnx Export Not Support All Of Non-Torch Types #
4
+ # Include Python Built-in Types!!!!!!!!!!!!!!!!! #
5
+ # If You Want TO Change This File #
6
+ # Do Not Use All Of Non-Torch Types! #
7
+ # #
8
+ ############################## Warning! ##############################
9
+ import copy
10
+ import math
11
+ from typing import Optional
12
+
13
+ import numpy as np
14
+ import torch
15
+ from torch import nn
16
+ from torch.nn import functional as F
17
+
18
+ from infer.lib.infer_pack import commons, modules
19
+ from infer.lib.infer_pack.modules import LayerNorm
20
+
21
+
22
+ class Encoder(nn.Module):
23
+ def __init__(
24
+ self,
25
+ hidden_channels,
26
+ filter_channels,
27
+ n_heads,
28
+ n_layers,
29
+ kernel_size=1,
30
+ p_dropout=0.0,
31
+ window_size=10,
32
+ **kwargs
33
+ ):
34
+ super(Encoder, self).__init__()
35
+ self.hidden_channels = hidden_channels
36
+ self.filter_channels = filter_channels
37
+ self.n_heads = n_heads
38
+ self.n_layers = int(n_layers)
39
+ self.kernel_size = kernel_size
40
+ self.p_dropout = p_dropout
41
+ self.window_size = window_size
42
+
43
+ self.drop = nn.Dropout(p_dropout)
44
+ self.attn_layers = nn.ModuleList()
45
+ self.norm_layers_1 = nn.ModuleList()
46
+ self.ffn_layers = nn.ModuleList()
47
+ self.norm_layers_2 = nn.ModuleList()
48
+ for i in range(self.n_layers):
49
+ self.attn_layers.append(
50
+ MultiHeadAttention(
51
+ hidden_channels,
52
+ hidden_channels,
53
+ n_heads,
54
+ p_dropout=p_dropout,
55
+ window_size=window_size,
56
+ )
57
+ )
58
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
59
+ self.ffn_layers.append(
60
+ FFN(
61
+ hidden_channels,
62
+ hidden_channels,
63
+ filter_channels,
64
+ kernel_size,
65
+ p_dropout=p_dropout,
66
+ )
67
+ )
68
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
69
+
70
+ def forward(self, x, x_mask):
71
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
72
+ x = x * x_mask
73
+ zippep = zip(
74
+ self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2
75
+ )
76
+ for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep:
77
+ y = attn_layers(x, x, attn_mask)
78
+ y = self.drop(y)
79
+ x = norm_layers_1(x + y)
80
+
81
+ y = ffn_layers(x, x_mask)
82
+ y = self.drop(y)
83
+ x = norm_layers_2(x + y)
84
+ x = x * x_mask
85
+ return x
86
+
87
+
88
+ class Decoder(nn.Module):
89
+ def __init__(
90
+ self,
91
+ hidden_channels,
92
+ filter_channels,
93
+ n_heads,
94
+ n_layers,
95
+ kernel_size=1,
96
+ p_dropout=0.0,
97
+ proximal_bias=False,
98
+ proximal_init=True,
99
+ **kwargs
100
+ ):
101
+ super(Decoder, self).__init__()
102
+ self.hidden_channels = hidden_channels
103
+ self.filter_channels = filter_channels
104
+ self.n_heads = n_heads
105
+ self.n_layers = n_layers
106
+ self.kernel_size = kernel_size
107
+ self.p_dropout = p_dropout
108
+ self.proximal_bias = proximal_bias
109
+ self.proximal_init = proximal_init
110
+
111
+ self.drop = nn.Dropout(p_dropout)
112
+ self.self_attn_layers = nn.ModuleList()
113
+ self.norm_layers_0 = nn.ModuleList()
114
+ self.encdec_attn_layers = nn.ModuleList()
115
+ self.norm_layers_1 = nn.ModuleList()
116
+ self.ffn_layers = nn.ModuleList()
117
+ self.norm_layers_2 = nn.ModuleList()
118
+ for i in range(self.n_layers):
119
+ self.self_attn_layers.append(
120
+ MultiHeadAttention(
121
+ hidden_channels,
122
+ hidden_channels,
123
+ n_heads,
124
+ p_dropout=p_dropout,
125
+ proximal_bias=proximal_bias,
126
+ proximal_init=proximal_init,
127
+ )
128
+ )
129
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
130
+ self.encdec_attn_layers.append(
131
+ MultiHeadAttention(
132
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
133
+ )
134
+ )
135
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
136
+ self.ffn_layers.append(
137
+ FFN(
138
+ hidden_channels,
139
+ hidden_channels,
140
+ filter_channels,
141
+ kernel_size,
142
+ p_dropout=p_dropout,
143
+ causal=True,
144
+ )
145
+ )
146
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
147
+
148
+ def forward(self, x, x_mask, h, h_mask):
149
+ """
150
+ x: decoder input
151
+ h: encoder output
152
+ """
153
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
154
+ device=x.device, dtype=x.dtype
155
+ )
156
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
157
+ x = x * x_mask
158
+ for i in range(self.n_layers):
159
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
160
+ y = self.drop(y)
161
+ x = self.norm_layers_0[i](x + y)
162
+
163
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
164
+ y = self.drop(y)
165
+ x = self.norm_layers_1[i](x + y)
166
+
167
+ y = self.ffn_layers[i](x, x_mask)
168
+ y = self.drop(y)
169
+ x = self.norm_layers_2[i](x + y)
170
+ x = x * x_mask
171
+ return x
172
+
173
+
174
+ class MultiHeadAttention(nn.Module):
175
+ def __init__(
176
+ self,
177
+ channels,
178
+ out_channels,
179
+ n_heads,
180
+ p_dropout=0.0,
181
+ window_size=None,
182
+ heads_share=True,
183
+ block_length=None,
184
+ proximal_bias=False,
185
+ proximal_init=False,
186
+ ):
187
+ super(MultiHeadAttention, self).__init__()
188
+ assert channels % n_heads == 0
189
+
190
+ self.channels = channels
191
+ self.out_channels = out_channels
192
+ self.n_heads = n_heads
193
+ self.p_dropout = p_dropout
194
+ self.window_size = window_size
195
+ self.heads_share = heads_share
196
+ self.block_length = block_length
197
+ self.proximal_bias = proximal_bias
198
+ self.proximal_init = proximal_init
199
+ self.attn = None
200
+
201
+ self.k_channels = channels // n_heads
202
+ self.conv_q = nn.Conv1d(channels, channels, 1)
203
+ self.conv_k = nn.Conv1d(channels, channels, 1)
204
+ self.conv_v = nn.Conv1d(channels, channels, 1)
205
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
206
+ self.drop = nn.Dropout(p_dropout)
207
+
208
+ if window_size is not None:
209
+ n_heads_rel = 1 if heads_share else n_heads
210
+ rel_stddev = self.k_channels**-0.5
211
+ self.emb_rel_k = nn.Parameter(
212
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
213
+ * rel_stddev
214
+ )
215
+ self.emb_rel_v = nn.Parameter(
216
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
217
+ * rel_stddev
218
+ )
219
+
220
+ nn.init.xavier_uniform_(self.conv_q.weight)
221
+ nn.init.xavier_uniform_(self.conv_k.weight)
222
+ nn.init.xavier_uniform_(self.conv_v.weight)
223
+ if proximal_init:
224
+ with torch.no_grad():
225
+ self.conv_k.weight.copy_(self.conv_q.weight)
226
+ self.conv_k.bias.copy_(self.conv_q.bias)
227
+
228
+ def forward(
229
+ self, x: torch.Tensor, c: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
230
+ ):
231
+ q = self.conv_q(x)
232
+ k = self.conv_k(c)
233
+ v = self.conv_v(c)
234
+
235
+ x, _ = self.attention(q, k, v, mask=attn_mask)
236
+
237
+ x = self.conv_o(x)
238
+ return x
239
+
240
+ def attention(
241
+ self,
242
+ query: torch.Tensor,
243
+ key: torch.Tensor,
244
+ value: torch.Tensor,
245
+ mask: Optional[torch.Tensor] = None,
246
+ ):
247
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
248
+ b, d, t_s = key.size()
249
+ t_t = query.size(2)
250
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
251
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
252
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
253
+
254
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
255
+ if self.window_size is not None:
256
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
257
+ rel_logits = self._matmul_with_relative_keys(
258
+ query / math.sqrt(self.k_channels), key_relative_embeddings
259
+ )
260
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
261
+ scores = scores + scores_local
262
+ if self.proximal_bias:
263
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
264
+ scores = scores + self._attention_bias_proximal(t_s).to(
265
+ device=scores.device, dtype=scores.dtype
266
+ )
267
+ if mask is not None:
268
+ scores = scores.masked_fill(mask == 0, -1e4)
269
+ if self.block_length is not None:
270
+ assert (
271
+ t_s == t_t
272
+ ), "Local attention is only available for self-attention."
273
+ block_mask = (
274
+ torch.ones_like(scores)
275
+ .triu(-self.block_length)
276
+ .tril(self.block_length)
277
+ )
278
+ scores = scores.masked_fill(block_mask == 0, -1e4)
279
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
280
+ p_attn = self.drop(p_attn)
281
+ output = torch.matmul(p_attn, value)
282
+ if self.window_size is not None:
283
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
284
+ value_relative_embeddings = self._get_relative_embeddings(
285
+ self.emb_rel_v, t_s
286
+ )
287
+ output = output + self._matmul_with_relative_values(
288
+ relative_weights, value_relative_embeddings
289
+ )
290
+ output = (
291
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
292
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
293
+ return output, p_attn
294
+
295
+ def _matmul_with_relative_values(self, x, y):
296
+ """
297
+ x: [b, h, l, m]
298
+ y: [h or 1, m, d]
299
+ ret: [b, h, l, d]
300
+ """
301
+ ret = torch.matmul(x, y.unsqueeze(0))
302
+ return ret
303
+
304
+ def _matmul_with_relative_keys(self, x, y):
305
+ """
306
+ x: [b, h, l, d]
307
+ y: [h or 1, m, d]
308
+ ret: [b, h, l, m]
309
+ """
310
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
311
+ return ret
312
+
313
+ def _get_relative_embeddings(self, relative_embeddings, length):
314
+ max_relative_position = 2 * self.window_size + 1
315
+ # Pad first before slice to avoid using cond ops.
316
+
317
+ pad_length = torch.clamp(length - (self.window_size + 1), min=0)
318
+ slice_start_position = torch.clamp((self.window_size + 1) - length, min=0)
319
+ slice_end_position = slice_start_position + 2 * length - 1
320
+ padded_relative_embeddings = F.pad(
321
+ relative_embeddings,
322
+ # commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
323
+ [0, 0, pad_length, pad_length, 0, 0],
324
+ )
325
+ used_relative_embeddings = padded_relative_embeddings[
326
+ :, slice_start_position:slice_end_position
327
+ ]
328
+ return used_relative_embeddings
329
+
330
+ def _relative_position_to_absolute_position(self, x):
331
+ """
332
+ x: [b, h, l, 2*l-1]
333
+ ret: [b, h, l, l]
334
+ """
335
+ batch, heads, length, _ = x.size()
336
+ # Concat columns of pad to shift from relative to absolute indexing.
337
+ x = F.pad(
338
+ x,
339
+ # commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]])
340
+ [0, 1, 0, 0, 0, 0, 0, 0],
341
+ )
342
+
343
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
344
+ x_flat = x.view([batch, heads, length * 2 * length])
345
+ x_flat = F.pad(
346
+ x_flat,
347
+ [0, length - 1, 0, 0, 0, 0],
348
+ )
349
+
350
+ # Reshape and slice out the padded elements.
351
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
352
+ :, :, :length, length - 1 :
353
+ ]
354
+ return x_final
355
+
356
+ def _absolute_position_to_relative_position(self, x):
357
+ """
358
+ x: [b, h, l, l]
359
+ ret: [b, h, l, 2*l-1]
360
+ """
361
+ batch, heads, length, _ = x.size()
362
+ # padd along column
363
+ x = F.pad(
364
+ x,
365
+ [0, length - 1, 0, 0, 0, 0, 0, 0],
366
+ )
367
+ x_flat = x.view([batch, heads, length*length + length * (length - 1)])
368
+ # add 0's in the beginning that will skew the elements after reshape
369
+ x_flat = F.pad(
370
+ x_flat,
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):
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 = self.kernel_size - 1
439
+ pad_r = 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 = (self.kernel_size - 1) // 2
452
+ pad_r = 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,1223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from infer.lib.infer_pack import attentions, commons, modules
14
+ from infer.lib.infer_pack.commons import get_padding, init_weights
15
+
16
+ has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
17
+
18
+
19
+ class TextEncoder(nn.Module):
20
+ def __init__(
21
+ self,
22
+ in_channels,
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(TextEncoder, 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(in_channels, 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,
56
+ phone: torch.Tensor,
57
+ pitch: torch.Tensor,
58
+ lengths: torch.Tensor,
59
+ skip_head: Optional[torch.Tensor] = None,
60
+ ):
61
+ if pitch is None:
62
+ x = self.emb_phone(phone)
63
+ else:
64
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
65
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
66
+ x = self.lrelu(x)
67
+ x = torch.transpose(x, 1, -1) # [b, h, t]
68
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
69
+ x.dtype
70
+ )
71
+ x = self.encoder(x * x_mask, x_mask)
72
+ if skip_head is not None:
73
+ assert isinstance(skip_head, torch.Tensor)
74
+ head = int(skip_head.item())
75
+ x = x[:, :, head:]
76
+ x_mask = x_mask[:, :, head:]
77
+ stats = self.proj(x) * x_mask
78
+ m, logs = torch.split(stats, self.out_channels, dim=1)
79
+ return m, logs, x_mask
80
+
81
+
82
+ class ResidualCouplingBlock(nn.Module):
83
+ def __init__(
84
+ self,
85
+ channels,
86
+ hidden_channels,
87
+ kernel_size,
88
+ dilation_rate,
89
+ n_layers,
90
+ n_flows=4,
91
+ gin_channels=0,
92
+ ):
93
+ super(ResidualCouplingBlock, self).__init__()
94
+ self.channels = channels
95
+ self.hidden_channels = hidden_channels
96
+ self.kernel_size = kernel_size
97
+ self.dilation_rate = dilation_rate
98
+ self.n_layers = n_layers
99
+ self.n_flows = n_flows
100
+ self.gin_channels = gin_channels
101
+
102
+ self.flows = nn.ModuleList()
103
+ for i in range(n_flows):
104
+ self.flows.append(
105
+ modules.ResidualCouplingLayer(
106
+ channels,
107
+ hidden_channels,
108
+ kernel_size,
109
+ dilation_rate,
110
+ n_layers,
111
+ gin_channels=gin_channels,
112
+ mean_only=True,
113
+ )
114
+ )
115
+ self.flows.append(modules.Flip())
116
+
117
+ def forward(
118
+ self,
119
+ x: torch.Tensor,
120
+ x_mask: torch.Tensor,
121
+ g: Optional[torch.Tensor] = None,
122
+ reverse: bool = False,
123
+ ):
124
+ if not reverse:
125
+ for flow in self.flows:
126
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
127
+ else:
128
+ for flow in self.flows[::-1]:
129
+ x, _ = flow.forward(x, x_mask, g=g, reverse=reverse)
130
+ return x
131
+
132
+ def remove_weight_norm(self):
133
+ for i in range(self.n_flows):
134
+ self.flows[i * 2].remove_weight_norm()
135
+
136
+ def __prepare_scriptable__(self):
137
+ for i in range(self.n_flows):
138
+ for hook in self.flows[i * 2]._forward_pre_hooks.values():
139
+ if (
140
+ hook.__module__ == "torch.nn.utils.weight_norm"
141
+ and hook.__class__.__name__ == "WeightNorm"
142
+ ):
143
+ torch.nn.utils.remove_weight_norm(self.flows[i * 2])
144
+
145
+ return self
146
+
147
+
148
+ class PosteriorEncoder(nn.Module):
149
+ def __init__(
150
+ self,
151
+ in_channels,
152
+ out_channels,
153
+ hidden_channels,
154
+ kernel_size,
155
+ dilation_rate,
156
+ n_layers,
157
+ gin_channels=0,
158
+ ):
159
+ super(PosteriorEncoder, self).__init__()
160
+ self.in_channels = in_channels
161
+ self.out_channels = out_channels
162
+ self.hidden_channels = hidden_channels
163
+ self.kernel_size = kernel_size
164
+ self.dilation_rate = dilation_rate
165
+ self.n_layers = n_layers
166
+ self.gin_channels = gin_channels
167
+
168
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
169
+ self.enc = modules.WN(
170
+ hidden_channels,
171
+ kernel_size,
172
+ dilation_rate,
173
+ n_layers,
174
+ gin_channels=gin_channels,
175
+ )
176
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
177
+
178
+ def forward(
179
+ self, x: torch.Tensor, x_lengths: torch.Tensor, g: Optional[torch.Tensor] = None
180
+ ):
181
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
182
+ x.dtype
183
+ )
184
+ x = self.pre(x) * x_mask
185
+ x = self.enc(x, x_mask, g=g)
186
+ stats = self.proj(x) * x_mask
187
+ m, logs = torch.split(stats, self.out_channels, dim=1)
188
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
189
+ return z, m, logs, x_mask
190
+
191
+ def remove_weight_norm(self):
192
+ self.enc.remove_weight_norm()
193
+
194
+ def __prepare_scriptable__(self):
195
+ for hook in self.enc._forward_pre_hooks.values():
196
+ if (
197
+ hook.__module__ == "torch.nn.utils.weight_norm"
198
+ and hook.__class__.__name__ == "WeightNorm"
199
+ ):
200
+ torch.nn.utils.remove_weight_norm(self.enc)
201
+ return self
202
+
203
+
204
+ class Generator(torch.nn.Module):
205
+ def __init__(
206
+ self,
207
+ initial_channel,
208
+ resblock,
209
+ resblock_kernel_sizes,
210
+ resblock_dilation_sizes,
211
+ upsample_rates,
212
+ upsample_initial_channel,
213
+ upsample_kernel_sizes,
214
+ gin_channels=0,
215
+ ):
216
+ super(Generator, self).__init__()
217
+ self.num_kernels = len(resblock_kernel_sizes)
218
+ self.num_upsamples = len(upsample_rates)
219
+ self.conv_pre = Conv1d(
220
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
221
+ )
222
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
223
+
224
+ self.ups = nn.ModuleList()
225
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
226
+ self.ups.append(
227
+ weight_norm(
228
+ ConvTranspose1d(
229
+ upsample_initial_channel // (2**i),
230
+ upsample_initial_channel // (2 ** (i + 1)),
231
+ k,
232
+ u,
233
+ padding=(k - u) // 2,
234
+ )
235
+ )
236
+ )
237
+
238
+ self.resblocks = nn.ModuleList()
239
+ for i in range(len(self.ups)):
240
+ ch = upsample_initial_channel // (2 ** (i + 1))
241
+ for j, (k, d) in enumerate(
242
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
243
+ ):
244
+ self.resblocks.append(resblock(ch, k, d))
245
+
246
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
247
+ self.ups.apply(init_weights)
248
+
249
+ if gin_channels != 0:
250
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
251
+
252
+ def forward(
253
+ self,
254
+ x: torch.Tensor,
255
+ g: Optional[torch.Tensor] = None,
256
+ n_res: Optional[torch.Tensor] = None,
257
+ ):
258
+ if n_res is not None:
259
+ assert isinstance(n_res, torch.Tensor)
260
+ n = int(n_res.item())
261
+ if n != x.shape[-1]:
262
+ x = F.interpolate(x, size=n, mode="linear")
263
+ x = self.conv_pre(x)
264
+ if g is not None:
265
+ x = x + self.cond(g)
266
+
267
+ for i in range(self.num_upsamples):
268
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
269
+ x = self.ups[i](x)
270
+ xs = None
271
+ for j in range(self.num_kernels):
272
+ if xs is None:
273
+ xs = self.resblocks[i * self.num_kernels + j](x)
274
+ else:
275
+ xs += self.resblocks[i * self.num_kernels + j](x)
276
+ x = xs / self.num_kernels
277
+ x = F.leaky_relu(x)
278
+ x = self.conv_post(x)
279
+ x = torch.tanh(x)
280
+
281
+ return x
282
+
283
+ def __prepare_scriptable__(self):
284
+ for l in self.ups:
285
+ for hook in l._forward_pre_hooks.values():
286
+ # The hook we want to remove is an instance of WeightNorm class, so
287
+ # normally we would do `if isinstance(...)` but this class is not accessible
288
+ # because of shadowing, so we check the module name directly.
289
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
290
+ if (
291
+ hook.__module__ == "torch.nn.utils.weight_norm"
292
+ and hook.__class__.__name__ == "WeightNorm"
293
+ ):
294
+ torch.nn.utils.remove_weight_norm(l)
295
+
296
+ for l in self.resblocks:
297
+ for hook in l._forward_pre_hooks.values():
298
+ if (
299
+ hook.__module__ == "torch.nn.utils.weight_norm"
300
+ and hook.__class__.__name__ == "WeightNorm"
301
+ ):
302
+ torch.nn.utils.remove_weight_norm(l)
303
+ return self
304
+
305
+ def remove_weight_norm(self):
306
+ for l in self.ups:
307
+ remove_weight_norm(l)
308
+ for l in self.resblocks:
309
+ l.remove_weight_norm()
310
+
311
+
312
+ class SineGen(torch.nn.Module):
313
+ """Definition of sine generator
314
+ SineGen(samp_rate, harmonic_num = 0,
315
+ sine_amp = 0.1, noise_std = 0.003,
316
+ voiced_threshold = 0,
317
+ flag_for_pulse=False)
318
+ samp_rate: sampling rate in Hz
319
+ harmonic_num: number of harmonic overtones (default 0)
320
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
321
+ noise_std: std of Gaussian noise (default 0.003)
322
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
323
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
324
+ Note: when flag_for_pulse is True, the first time step of a voiced
325
+ segment is always sin(torch.pi) or cos(0)
326
+ """
327
+
328
+ def __init__(
329
+ self,
330
+ samp_rate,
331
+ harmonic_num=0,
332
+ sine_amp=0.1,
333
+ noise_std=0.003,
334
+ voiced_threshold=0,
335
+ flag_for_pulse=False,
336
+ ):
337
+ super(SineGen, self).__init__()
338
+ self.sine_amp = sine_amp
339
+ self.noise_std = noise_std
340
+ self.harmonic_num = harmonic_num
341
+ self.dim = self.harmonic_num + 1
342
+ self.sampling_rate = samp_rate
343
+ self.voiced_threshold = voiced_threshold
344
+
345
+ def _f02uv(self, f0):
346
+ # generate uv signal
347
+ uv = torch.ones_like(f0)
348
+ uv = uv * (f0 > self.voiced_threshold)
349
+ if uv.device.type == "privateuseone": # for DirectML
350
+ uv = uv.float()
351
+ return uv
352
+
353
+ def _f02sine(self, f0, upp):
354
+ """ f0: (batchsize, length, dim)
355
+ where dim indicates fundamental tone and overtones
356
+ """
357
+ a = torch.arange(1, upp + 1, dtype=f0.dtype, device=f0.device)
358
+ rad = f0 / self.sampling_rate * a
359
+ rad2 = torch.fmod(rad[:, :-1, -1:].float() + 0.5, 1.0) - 0.5
360
+ rad_acc = rad2.cumsum(dim=1).fmod(1.0).to(f0)
361
+ rad += F.pad(rad_acc, (0, 0, 1, 0), mode='constant')
362
+ rad = rad.reshape(f0.shape[0], -1, 1)
363
+ b = torch.arange(1, self.dim + 1, dtype=f0.dtype, device=f0.device).reshape(1, 1, -1)
364
+ rad *= b
365
+ rand_ini = torch.rand(1, 1, self.dim, device=f0.device)
366
+ rand_ini[..., 0] = 0
367
+ rad += rand_ini
368
+ sines = torch.sin(2 * np.pi * rad)
369
+ return sines
370
+
371
+ def forward(self, f0: torch.Tensor, upp: int):
372
+ """sine_tensor, uv = forward(f0)
373
+ input F0: tensor(batchsize=1, length, dim=1)
374
+ f0 for unvoiced steps should be 0
375
+ output sine_tensor: tensor(batchsize=1, length, dim)
376
+ output uv: tensor(batchsize=1, length, 1)
377
+ """
378
+ with torch.no_grad():
379
+ f0 = f0.unsqueeze(-1)
380
+ sine_waves = self._f02sine(f0, upp) * self.sine_amp
381
+ uv = self._f02uv(f0)
382
+ uv = F.interpolate(
383
+ uv.transpose(2, 1), scale_factor=float(upp), mode="nearest"
384
+ ).transpose(2, 1)
385
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
386
+ noise = noise_amp * torch.randn_like(sine_waves)
387
+ sine_waves = sine_waves * uv + noise
388
+ return sine_waves, uv, noise
389
+
390
+
391
+ class SourceModuleHnNSF(torch.nn.Module):
392
+ """SourceModule for hn-nsf
393
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
394
+ add_noise_std=0.003, voiced_threshod=0)
395
+ sampling_rate: sampling_rate in Hz
396
+ harmonic_num: number of harmonic above F0 (default: 0)
397
+ sine_amp: amplitude of sine source signal (default: 0.1)
398
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
399
+ note that amplitude of noise in unvoiced is decided
400
+ by sine_amp
401
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
402
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
403
+ F0_sampled (batchsize, length, 1)
404
+ Sine_source (batchsize, length, 1)
405
+ noise_source (batchsize, length 1)
406
+ uv (batchsize, length, 1)
407
+ """
408
+
409
+ def __init__(
410
+ self,
411
+ sampling_rate,
412
+ harmonic_num=0,
413
+ sine_amp=0.1,
414
+ add_noise_std=0.003,
415
+ voiced_threshod=0,
416
+ is_half=True,
417
+ ):
418
+ super(SourceModuleHnNSF, self).__init__()
419
+
420
+ self.sine_amp = sine_amp
421
+ self.noise_std = add_noise_std
422
+ self.is_half = is_half
423
+ # to produce sine waveforms
424
+ self.l_sin_gen = SineGen(
425
+ sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
426
+ )
427
+
428
+ # to merge source harmonics into a single excitation
429
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
430
+ self.l_tanh = torch.nn.Tanh()
431
+ # self.ddtype:int = -1
432
+
433
+ def forward(self, x: torch.Tensor, upp: int = 1):
434
+ # if self.ddtype ==-1:
435
+ # self.ddtype = self.l_linear.weight.dtype
436
+ sine_wavs, uv, _ = self.l_sin_gen(x, upp)
437
+ # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype)
438
+ # if self.is_half:
439
+ # sine_wavs = sine_wavs.half()
440
+ # sine_merge = self.l_tanh(self.l_linear(sine_wavs.to(x)))
441
+ # print(sine_wavs.dtype,self.ddtype)
442
+ # if sine_wavs.dtype != self.l_linear.weight.dtype:
443
+ sine_wavs = sine_wavs.to(dtype=self.l_linear.weight.dtype)
444
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
445
+ return sine_merge, None, None # noise, uv
446
+
447
+
448
+ class GeneratorNSF(torch.nn.Module):
449
+ def __init__(
450
+ self,
451
+ initial_channel,
452
+ resblock,
453
+ resblock_kernel_sizes,
454
+ resblock_dilation_sizes,
455
+ upsample_rates,
456
+ upsample_initial_channel,
457
+ upsample_kernel_sizes,
458
+ gin_channels,
459
+ sr,
460
+ is_half=False,
461
+ ):
462
+ super(GeneratorNSF, self).__init__()
463
+ self.num_kernels = len(resblock_kernel_sizes)
464
+ self.num_upsamples = len(upsample_rates)
465
+
466
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=math.prod(upsample_rates))
467
+ self.m_source = SourceModuleHnNSF(
468
+ sampling_rate=sr, harmonic_num=0, is_half=is_half
469
+ )
470
+ self.noise_convs = nn.ModuleList()
471
+ self.conv_pre = Conv1d(
472
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
473
+ )
474
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
475
+
476
+ self.ups = nn.ModuleList()
477
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
478
+ c_cur = upsample_initial_channel // (2 ** (i + 1))
479
+ self.ups.append(
480
+ weight_norm(
481
+ ConvTranspose1d(
482
+ upsample_initial_channel // (2**i),
483
+ upsample_initial_channel // (2 ** (i + 1)),
484
+ k,
485
+ u,
486
+ padding=(k - u) // 2,
487
+ )
488
+ )
489
+ )
490
+ if i + 1 < len(upsample_rates):
491
+ stride_f0 = math.prod(upsample_rates[i + 1 :])
492
+ self.noise_convs.append(
493
+ Conv1d(
494
+ 1,
495
+ c_cur,
496
+ kernel_size=stride_f0 * 2,
497
+ stride=stride_f0,
498
+ padding=stride_f0 // 2,
499
+ )
500
+ )
501
+ else:
502
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
503
+
504
+ self.resblocks = nn.ModuleList()
505
+ for i in range(len(self.ups)):
506
+ ch = upsample_initial_channel // (2 ** (i + 1))
507
+ for j, (k, d) in enumerate(
508
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
509
+ ):
510
+ self.resblocks.append(resblock(ch, k, d))
511
+
512
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
513
+ self.ups.apply(init_weights)
514
+
515
+ if gin_channels != 0:
516
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
517
+
518
+ self.upp = math.prod(upsample_rates)
519
+
520
+ self.lrelu_slope = modules.LRELU_SLOPE
521
+
522
+ def forward(
523
+ self,
524
+ x,
525
+ f0,
526
+ g: Optional[torch.Tensor] = None,
527
+ n_res: Optional[torch.Tensor] = None,
528
+ ):
529
+ har_source, noi_source, uv = self.m_source(f0, self.upp)
530
+ har_source = har_source.transpose(1, 2)
531
+ if n_res is not None:
532
+ assert isinstance(n_res, torch.Tensor)
533
+ n = int(n_res.item())
534
+ if n * self.upp != har_source.shape[-1]:
535
+ har_source = F.interpolate(har_source, size=n * self.upp, mode="linear")
536
+ if n != x.shape[-1]:
537
+ x = F.interpolate(x, size=n, mode="linear")
538
+ x = self.conv_pre(x)
539
+ if g is not None:
540
+ x = x + self.cond(g)
541
+ # torch.jit.script() does not support direct indexing of torch modules
542
+ # That's why I wrote this
543
+ for i, (ups, noise_convs) in enumerate(zip(self.ups, self.noise_convs)):
544
+ if i < self.num_upsamples:
545
+ x = F.leaky_relu(x, self.lrelu_slope)
546
+ x = ups(x)
547
+ x_source = noise_convs(har_source)
548
+ x = x + x_source
549
+ xs: Optional[torch.Tensor] = None
550
+ l = [i * self.num_kernels + j for j in range(self.num_kernels)]
551
+ for j, resblock in enumerate(self.resblocks):
552
+ if j in l:
553
+ if xs is None:
554
+ xs = resblock(x)
555
+ else:
556
+ xs += resblock(x)
557
+ # This assertion cannot be ignored! \
558
+ # If ignored, it will cause torch.jit.script() compilation errors
559
+ assert isinstance(xs, torch.Tensor)
560
+ x = xs / self.num_kernels
561
+ x = F.leaky_relu(x)
562
+ x = self.conv_post(x)
563
+ x = torch.tanh(x)
564
+
565
+ return x
566
+
567
+ def remove_weight_norm(self):
568
+ for l in self.ups:
569
+ remove_weight_norm(l)
570
+ for l in self.resblocks:
571
+ l.remove_weight_norm()
572
+
573
+ def __prepare_scriptable__(self):
574
+ for l in self.ups:
575
+ for hook in l._forward_pre_hooks.values():
576
+ # The hook we want to remove is an instance of WeightNorm class, so
577
+ # normally we would do `if isinstance(...)` but this class is not accessible
578
+ # because of shadowing, so we check the module name directly.
579
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
580
+ if (
581
+ hook.__module__ == "torch.nn.utils.weight_norm"
582
+ and hook.__class__.__name__ == "WeightNorm"
583
+ ):
584
+ torch.nn.utils.remove_weight_norm(l)
585
+ for l in self.resblocks:
586
+ for hook in self.resblocks._forward_pre_hooks.values():
587
+ if (
588
+ hook.__module__ == "torch.nn.utils.weight_norm"
589
+ and hook.__class__.__name__ == "WeightNorm"
590
+ ):
591
+ torch.nn.utils.remove_weight_norm(l)
592
+ return self
593
+
594
+
595
+ sr2sr = {
596
+ "32k": 32000,
597
+ "40k": 40000,
598
+ "48k": 48000,
599
+ }
600
+
601
+
602
+ class SynthesizerTrnMs256NSFsid(nn.Module):
603
+ def __init__(
604
+ self,
605
+ spec_channels,
606
+ segment_size,
607
+ inter_channels,
608
+ hidden_channels,
609
+ filter_channels,
610
+ n_heads,
611
+ n_layers,
612
+ kernel_size,
613
+ p_dropout,
614
+ resblock,
615
+ resblock_kernel_sizes,
616
+ resblock_dilation_sizes,
617
+ upsample_rates,
618
+ upsample_initial_channel,
619
+ upsample_kernel_sizes,
620
+ spk_embed_dim,
621
+ gin_channels,
622
+ sr,
623
+ **kwargs
624
+ ):
625
+ super(SynthesizerTrnMs256NSFsid, self).__init__()
626
+ if isinstance(sr, str):
627
+ sr = sr2sr[sr]
628
+ self.spec_channels = spec_channels
629
+ self.inter_channels = inter_channels
630
+ self.hidden_channels = hidden_channels
631
+ self.filter_channels = filter_channels
632
+ self.n_heads = n_heads
633
+ self.n_layers = n_layers
634
+ self.kernel_size = kernel_size
635
+ self.p_dropout = float(p_dropout)
636
+ self.resblock = resblock
637
+ self.resblock_kernel_sizes = resblock_kernel_sizes
638
+ self.resblock_dilation_sizes = resblock_dilation_sizes
639
+ self.upsample_rates = upsample_rates
640
+ self.upsample_initial_channel = upsample_initial_channel
641
+ self.upsample_kernel_sizes = upsample_kernel_sizes
642
+ self.segment_size = segment_size
643
+ self.gin_channels = gin_channels
644
+ # self.hop_length = hop_length#
645
+ self.spk_embed_dim = spk_embed_dim
646
+ self.enc_p = TextEncoder(
647
+ 256,
648
+ inter_channels,
649
+ hidden_channels,
650
+ filter_channels,
651
+ n_heads,
652
+ n_layers,
653
+ kernel_size,
654
+ float(p_dropout),
655
+ )
656
+ self.dec = GeneratorNSF(
657
+ inter_channels,
658
+ resblock,
659
+ resblock_kernel_sizes,
660
+ resblock_dilation_sizes,
661
+ upsample_rates,
662
+ upsample_initial_channel,
663
+ upsample_kernel_sizes,
664
+ gin_channels=gin_channels,
665
+ sr=sr,
666
+ is_half=kwargs["is_half"],
667
+ )
668
+ self.enc_q = PosteriorEncoder(
669
+ spec_channels,
670
+ inter_channels,
671
+ hidden_channels,
672
+ 5,
673
+ 1,
674
+ 16,
675
+ gin_channels=gin_channels,
676
+ )
677
+ self.flow = ResidualCouplingBlock(
678
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
679
+ )
680
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
681
+ logger.debug(
682
+ "gin_channels: "
683
+ + str(gin_channels)
684
+ + ", self.spk_embed_dim: "
685
+ + str(self.spk_embed_dim)
686
+ )
687
+
688
+ def remove_weight_norm(self):
689
+ self.dec.remove_weight_norm()
690
+ self.flow.remove_weight_norm()
691
+ if hasattr(self, "enc_q"):
692
+ self.enc_q.remove_weight_norm()
693
+
694
+ def __prepare_scriptable__(self):
695
+ for hook in self.dec._forward_pre_hooks.values():
696
+ # The hook we want to remove is an instance of WeightNorm class, so
697
+ # normally we would do `if isinstance(...)` but this class is not accessible
698
+ # because of shadowing, so we check the module name directly.
699
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
700
+ if (
701
+ hook.__module__ == "torch.nn.utils.weight_norm"
702
+ and hook.__class__.__name__ == "WeightNorm"
703
+ ):
704
+ torch.nn.utils.remove_weight_norm(self.dec)
705
+ for hook in self.flow._forward_pre_hooks.values():
706
+ if (
707
+ hook.__module__ == "torch.nn.utils.weight_norm"
708
+ and hook.__class__.__name__ == "WeightNorm"
709
+ ):
710
+ torch.nn.utils.remove_weight_norm(self.flow)
711
+ if hasattr(self, "enc_q"):
712
+ for hook in self.enc_q._forward_pre_hooks.values():
713
+ if (
714
+ hook.__module__ == "torch.nn.utils.weight_norm"
715
+ and hook.__class__.__name__ == "WeightNorm"
716
+ ):
717
+ torch.nn.utils.remove_weight_norm(self.enc_q)
718
+ return self
719
+
720
+ @torch.jit.ignore
721
+ def forward(
722
+ self,
723
+ phone: torch.Tensor,
724
+ phone_lengths: torch.Tensor,
725
+ pitch: torch.Tensor,
726
+ pitchf: torch.Tensor,
727
+ y: torch.Tensor,
728
+ y_lengths: torch.Tensor,
729
+ ds: Optional[torch.Tensor] = None,
730
+ ): # 这里ds是id,[bs,1]
731
+ # print(1,pitch.shape)#[bs,t]
732
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
733
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
734
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
735
+ z_p = self.flow(z, y_mask, g=g)
736
+ z_slice, ids_slice = commons.rand_slice_segments(
737
+ z, y_lengths, self.segment_size
738
+ )
739
+ # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
740
+ pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
741
+ # print(-2,pitchf.shape,z_slice.shape)
742
+ o = self.dec(z_slice, pitchf, g=g)
743
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
744
+
745
+ @torch.jit.export
746
+ def infer(
747
+ self,
748
+ phone: torch.Tensor,
749
+ phone_lengths: torch.Tensor,
750
+ pitch: torch.Tensor,
751
+ nsff0: torch.Tensor,
752
+ sid: torch.Tensor,
753
+ skip_head: Optional[torch.Tensor] = None,
754
+ return_length: Optional[torch.Tensor] = None,
755
+ return_length2: Optional[torch.Tensor] = None,
756
+ ):
757
+ g = self.emb_g(sid).unsqueeze(-1)
758
+ if skip_head is not None and return_length is not None:
759
+ assert isinstance(skip_head, torch.Tensor)
760
+ assert isinstance(return_length, torch.Tensor)
761
+ head = int(skip_head.item())
762
+ length = int(return_length.item())
763
+ flow_head = torch.clamp(skip_head - 24, min=0)
764
+ dec_head = head - int(flow_head.item())
765
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths, flow_head)
766
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
767
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
768
+ z = z[:, :, dec_head : dec_head + length]
769
+ x_mask = x_mask[:, :, dec_head : dec_head + length]
770
+ nsff0 = nsff0[:, head : head + length]
771
+ else:
772
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
773
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
774
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
775
+ o = self.dec(z * x_mask, nsff0, g=g, n_res=return_length2)
776
+ return o, x_mask, (z, z_p, m_p, logs_p)
777
+
778
+
779
+ class SynthesizerTrnMs768NSFsid(SynthesizerTrnMs256NSFsid):
780
+ def __init__(
781
+ self,
782
+ spec_channels,
783
+ segment_size,
784
+ inter_channels,
785
+ hidden_channels,
786
+ filter_channels,
787
+ n_heads,
788
+ n_layers,
789
+ kernel_size,
790
+ p_dropout,
791
+ resblock,
792
+ resblock_kernel_sizes,
793
+ resblock_dilation_sizes,
794
+ upsample_rates,
795
+ upsample_initial_channel,
796
+ upsample_kernel_sizes,
797
+ spk_embed_dim,
798
+ gin_channels,
799
+ sr,
800
+ **kwargs
801
+ ):
802
+ super(SynthesizerTrnMs768NSFsid, self).__init__(
803
+ spec_channels,
804
+ segment_size,
805
+ inter_channels,
806
+ hidden_channels,
807
+ filter_channels,
808
+ n_heads,
809
+ n_layers,
810
+ kernel_size,
811
+ p_dropout,
812
+ resblock,
813
+ resblock_kernel_sizes,
814
+ resblock_dilation_sizes,
815
+ upsample_rates,
816
+ upsample_initial_channel,
817
+ upsample_kernel_sizes,
818
+ spk_embed_dim,
819
+ gin_channels,
820
+ sr,
821
+ **kwargs
822
+ )
823
+ del self.enc_p
824
+ self.enc_p = TextEncoder(
825
+ 768,
826
+ inter_channels,
827
+ hidden_channels,
828
+ filter_channels,
829
+ n_heads,
830
+ n_layers,
831
+ kernel_size,
832
+ float(p_dropout),
833
+ )
834
+
835
+
836
+ class SynthesizerTrnMs256NSFsid_nono(nn.Module):
837
+ def __init__(
838
+ self,
839
+ spec_channels,
840
+ segment_size,
841
+ inter_channels,
842
+ hidden_channels,
843
+ filter_channels,
844
+ n_heads,
845
+ n_layers,
846
+ kernel_size,
847
+ p_dropout,
848
+ resblock,
849
+ resblock_kernel_sizes,
850
+ resblock_dilation_sizes,
851
+ upsample_rates,
852
+ upsample_initial_channel,
853
+ upsample_kernel_sizes,
854
+ spk_embed_dim,
855
+ gin_channels,
856
+ sr=None,
857
+ **kwargs
858
+ ):
859
+ super(SynthesizerTrnMs256NSFsid_nono, self).__init__()
860
+ self.spec_channels = spec_channels
861
+ self.inter_channels = inter_channels
862
+ self.hidden_channels = hidden_channels
863
+ self.filter_channels = filter_channels
864
+ self.n_heads = n_heads
865
+ self.n_layers = n_layers
866
+ self.kernel_size = kernel_size
867
+ self.p_dropout = float(p_dropout)
868
+ self.resblock = resblock
869
+ self.resblock_kernel_sizes = resblock_kernel_sizes
870
+ self.resblock_dilation_sizes = resblock_dilation_sizes
871
+ self.upsample_rates = upsample_rates
872
+ self.upsample_initial_channel = upsample_initial_channel
873
+ self.upsample_kernel_sizes = upsample_kernel_sizes
874
+ self.segment_size = segment_size
875
+ self.gin_channels = gin_channels
876
+ # self.hop_length = hop_length#
877
+ self.spk_embed_dim = spk_embed_dim
878
+ self.enc_p = TextEncoder(
879
+ 256,
880
+ inter_channels,
881
+ hidden_channels,
882
+ filter_channels,
883
+ n_heads,
884
+ n_layers,
885
+ kernel_size,
886
+ float(p_dropout),
887
+ f0=False,
888
+ )
889
+ self.dec = Generator(
890
+ inter_channels,
891
+ resblock,
892
+ resblock_kernel_sizes,
893
+ resblock_dilation_sizes,
894
+ upsample_rates,
895
+ upsample_initial_channel,
896
+ upsample_kernel_sizes,
897
+ gin_channels=gin_channels,
898
+ )
899
+ self.enc_q = PosteriorEncoder(
900
+ spec_channels,
901
+ inter_channels,
902
+ hidden_channels,
903
+ 5,
904
+ 1,
905
+ 16,
906
+ gin_channels=gin_channels,
907
+ )
908
+ self.flow = ResidualCouplingBlock(
909
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
910
+ )
911
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
912
+ logger.debug(
913
+ "gin_channels: "
914
+ + str(gin_channels)
915
+ + ", self.spk_embed_dim: "
916
+ + str(self.spk_embed_dim)
917
+ )
918
+
919
+ def remove_weight_norm(self):
920
+ self.dec.remove_weight_norm()
921
+ self.flow.remove_weight_norm()
922
+ if hasattr(self, "enc_q"):
923
+ self.enc_q.remove_weight_norm()
924
+
925
+ def __prepare_scriptable__(self):
926
+ for hook in self.dec._forward_pre_hooks.values():
927
+ # The hook we want to remove is an instance of WeightNorm class, so
928
+ # normally we would do `if isinstance(...)` but this class is not accessible
929
+ # because of shadowing, so we check the module name directly.
930
+ # https://github.com/pytorch/pytorch/blob/be0ca00c5ce260eb5bcec3237357f7a30cc08983/torch/nn/utils/__init__.py#L3
931
+ if (
932
+ hook.__module__ == "torch.nn.utils.weight_norm"
933
+ and hook.__class__.__name__ == "WeightNorm"
934
+ ):
935
+ torch.nn.utils.remove_weight_norm(self.dec)
936
+ for hook in self.flow._forward_pre_hooks.values():
937
+ if (
938
+ hook.__module__ == "torch.nn.utils.weight_norm"
939
+ and hook.__class__.__name__ == "WeightNorm"
940
+ ):
941
+ torch.nn.utils.remove_weight_norm(self.flow)
942
+ if hasattr(self, "enc_q"):
943
+ for hook in self.enc_q._forward_pre_hooks.values():
944
+ if (
945
+ hook.__module__ == "torch.nn.utils.weight_norm"
946
+ and hook.__class__.__name__ == "WeightNorm"
947
+ ):
948
+ torch.nn.utils.remove_weight_norm(self.enc_q)
949
+ return self
950
+
951
+ @torch.jit.ignore
952
+ def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
953
+ g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
954
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
955
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
956
+ z_p = self.flow(z, y_mask, g=g)
957
+ z_slice, ids_slice = commons.rand_slice_segments(
958
+ z, y_lengths, self.segment_size
959
+ )
960
+ o = self.dec(z_slice, g=g)
961
+ return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
962
+
963
+ @torch.jit.export
964
+ def infer(
965
+ self,
966
+ phone: torch.Tensor,
967
+ phone_lengths: torch.Tensor,
968
+ sid: torch.Tensor,
969
+ skip_head: Optional[torch.Tensor] = None,
970
+ return_length: Optional[torch.Tensor] = None,
971
+ return_length2: Optional[torch.Tensor] = None,
972
+ ):
973
+ g = self.emb_g(sid).unsqueeze(-1)
974
+ if skip_head is not None and return_length is not None:
975
+ assert isinstance(skip_head, torch.Tensor)
976
+ assert isinstance(return_length, torch.Tensor)
977
+ head = int(skip_head.item())
978
+ length = int(return_length.item())
979
+ flow_head = torch.clamp(skip_head - 24, min=0)
980
+ dec_head = head - int(flow_head.item())
981
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths, flow_head)
982
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
983
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
984
+ z = z[:, :, dec_head : dec_head + length]
985
+ x_mask = x_mask[:, :, dec_head : dec_head + length]
986
+ else:
987
+ m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
988
+ z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
989
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
990
+ o = self.dec(z * x_mask, g=g, n_res=return_length2)
991
+ return o, x_mask, (z, z_p, m_p, logs_p)
992
+
993
+
994
+ class SynthesizerTrnMs768NSFsid_nono(SynthesizerTrnMs256NSFsid_nono):
995
+ def __init__(
996
+ self,
997
+ spec_channels,
998
+ segment_size,
999
+ inter_channels,
1000
+ hidden_channels,
1001
+ filter_channels,
1002
+ n_heads,
1003
+ n_layers,
1004
+ kernel_size,
1005
+ p_dropout,
1006
+ resblock,
1007
+ resblock_kernel_sizes,
1008
+ resblock_dilation_sizes,
1009
+ upsample_rates,
1010
+ upsample_initial_channel,
1011
+ upsample_kernel_sizes,
1012
+ spk_embed_dim,
1013
+ gin_channels,
1014
+ sr=None,
1015
+ **kwargs
1016
+ ):
1017
+ super(SynthesizerTrnMs768NSFsid_nono, self).__init__(
1018
+ spec_channels,
1019
+ segment_size,
1020
+ inter_channels,
1021
+ hidden_channels,
1022
+ filter_channels,
1023
+ n_heads,
1024
+ n_layers,
1025
+ kernel_size,
1026
+ p_dropout,
1027
+ resblock,
1028
+ resblock_kernel_sizes,
1029
+ resblock_dilation_sizes,
1030
+ upsample_rates,
1031
+ upsample_initial_channel,
1032
+ upsample_kernel_sizes,
1033
+ spk_embed_dim,
1034
+ gin_channels,
1035
+ sr,
1036
+ **kwargs
1037
+ )
1038
+ del self.enc_p
1039
+ self.enc_p = TextEncoder(
1040
+ 768,
1041
+ inter_channels,
1042
+ hidden_channels,
1043
+ filter_channels,
1044
+ n_heads,
1045
+ n_layers,
1046
+ kernel_size,
1047
+ float(p_dropout),
1048
+ f0=False,
1049
+ )
1050
+
1051
+
1052
+ class MultiPeriodDiscriminator(torch.nn.Module):
1053
+ def __init__(self, use_spectral_norm=False):
1054
+ super(MultiPeriodDiscriminator, self).__init__()
1055
+ periods = [2, 3, 5, 7, 11, 17]
1056
+ # periods = [3, 5, 7, 11, 17, 23, 37]
1057
+
1058
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1059
+ discs = discs + [
1060
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1061
+ ]
1062
+ self.discriminators = nn.ModuleList(discs)
1063
+
1064
+ def forward(self, y, y_hat):
1065
+ y_d_rs = [] #
1066
+ y_d_gs = []
1067
+ fmap_rs = []
1068
+ fmap_gs = []
1069
+ for i, d in enumerate(self.discriminators):
1070
+ y_d_r, fmap_r = d(y)
1071
+ y_d_g, fmap_g = d(y_hat)
1072
+ # for j in range(len(fmap_r)):
1073
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1074
+ y_d_rs.append(y_d_r)
1075
+ y_d_gs.append(y_d_g)
1076
+ fmap_rs.append(fmap_r)
1077
+ fmap_gs.append(fmap_g)
1078
+
1079
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1080
+
1081
+
1082
+ class MultiPeriodDiscriminatorV2(torch.nn.Module):
1083
+ def __init__(self, use_spectral_norm=False):
1084
+ super(MultiPeriodDiscriminatorV2, self).__init__()
1085
+ # periods = [2, 3, 5, 7, 11, 17]
1086
+ periods = [2, 3, 5, 7, 11, 17, 23, 37]
1087
+
1088
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
1089
+ discs = discs + [
1090
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
1091
+ ]
1092
+ self.discriminators = nn.ModuleList(discs)
1093
+
1094
+ def forward(self, y, y_hat):
1095
+ y_d_rs = [] #
1096
+ y_d_gs = []
1097
+ fmap_rs = []
1098
+ fmap_gs = []
1099
+ for i, d in enumerate(self.discriminators):
1100
+ y_d_r, fmap_r = d(y)
1101
+ y_d_g, fmap_g = d(y_hat)
1102
+ # for j in range(len(fmap_r)):
1103
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1104
+ y_d_rs.append(y_d_r)
1105
+ y_d_gs.append(y_d_g)
1106
+ fmap_rs.append(fmap_r)
1107
+ fmap_gs.append(fmap_g)
1108
+
1109
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1110
+
1111
+
1112
+ class DiscriminatorS(torch.nn.Module):
1113
+ def __init__(self, use_spectral_norm=False):
1114
+ super(DiscriminatorS, self).__init__()
1115
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1116
+ self.convs = nn.ModuleList(
1117
+ [
1118
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
1119
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
1120
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
1121
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
1122
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
1123
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
1124
+ ]
1125
+ )
1126
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
1127
+
1128
+ def forward(self, x):
1129
+ fmap = []
1130
+
1131
+ for l in self.convs:
1132
+ x = l(x)
1133
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1134
+ fmap.append(x)
1135
+ x = self.conv_post(x)
1136
+ fmap.append(x)
1137
+ x = torch.flatten(x, 1, -1)
1138
+
1139
+ return x, fmap
1140
+
1141
+
1142
+ class DiscriminatorP(torch.nn.Module):
1143
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
1144
+ super(DiscriminatorP, self).__init__()
1145
+ self.period = period
1146
+ self.use_spectral_norm = use_spectral_norm
1147
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1148
+ self.convs = nn.ModuleList(
1149
+ [
1150
+ norm_f(
1151
+ Conv2d(
1152
+ 1,
1153
+ 32,
1154
+ (kernel_size, 1),
1155
+ (stride, 1),
1156
+ padding=(get_padding(kernel_size, 1), 0),
1157
+ )
1158
+ ),
1159
+ norm_f(
1160
+ Conv2d(
1161
+ 32,
1162
+ 128,
1163
+ (kernel_size, 1),
1164
+ (stride, 1),
1165
+ padding=(get_padding(kernel_size, 1), 0),
1166
+ )
1167
+ ),
1168
+ norm_f(
1169
+ Conv2d(
1170
+ 128,
1171
+ 512,
1172
+ (kernel_size, 1),
1173
+ (stride, 1),
1174
+ padding=(get_padding(kernel_size, 1), 0),
1175
+ )
1176
+ ),
1177
+ norm_f(
1178
+ Conv2d(
1179
+ 512,
1180
+ 1024,
1181
+ (kernel_size, 1),
1182
+ (stride, 1),
1183
+ padding=(get_padding(kernel_size, 1), 0),
1184
+ )
1185
+ ),
1186
+ norm_f(
1187
+ Conv2d(
1188
+ 1024,
1189
+ 1024,
1190
+ (kernel_size, 1),
1191
+ 1,
1192
+ padding=(get_padding(kernel_size, 1), 0),
1193
+ )
1194
+ ),
1195
+ ]
1196
+ )
1197
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
1198
+
1199
+ def forward(self, x):
1200
+ fmap = []
1201
+
1202
+ # 1d to 2d
1203
+ b, c, t = x.shape
1204
+ if t % self.period != 0: # pad first
1205
+ n_pad = self.period - (t % self.period)
1206
+ if has_xpu and x.dtype == torch.bfloat16:
1207
+ x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(
1208
+ dtype=torch.bfloat16
1209
+ )
1210
+ else:
1211
+ x = F.pad(x, (0, n_pad), "reflect")
1212
+ t = t + n_pad
1213
+ x = x.view(b, c, t // self.period, self.period)
1214
+
1215
+ for l in self.convs:
1216
+ x = l(x)
1217
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1218
+ fmap.append(x)
1219
+ x = self.conv_post(x)
1220
+ fmap.append(x)
1221
+ x = torch.flatten(x, 1, -1)
1222
+
1223
+ return x, fmap
infer/lib/infer_pack/models_onnx.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ############################## Warning! ##############################
2
+ # #
3
+ # Onnx Export Not Support All Of Non-Torch Types #
4
+ # Include Python Built-in Types!!!!!!!!!!!!!!!!! #
5
+ # If You Want TO Change This File #
6
+ # Do Not Use All Of Non-Torch Types! #
7
+ # #
8
+ ############################## Warning! ##############################
9
+
10
+ import math
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ import numpy as np
16
+ import torch
17
+ from torch import nn
18
+ from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
19
+ from torch.nn import functional as F
20
+ from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
21
+
22
+ from infer.lib.infer_pack import commons, modules
23
+ import infer.lib.infer_pack.attentions_onnx as attentions
24
+ from infer.lib.infer_pack.commons import get_padding, init_weights
25
+
26
+
27
+ class TextEncoder256(nn.Module):
28
+ def __init__(
29
+ self,
30
+ out_channels,
31
+ hidden_channels,
32
+ filter_channels,
33
+ n_heads,
34
+ n_layers,
35
+ kernel_size,
36
+ p_dropout,
37
+ f0=True,
38
+ ):
39
+ super().__init__()
40
+ self.out_channels = out_channels
41
+ self.hidden_channels = hidden_channels
42
+ self.filter_channels = filter_channels
43
+ self.n_heads = n_heads
44
+ self.n_layers = n_layers
45
+ self.kernel_size = kernel_size
46
+ self.p_dropout = p_dropout
47
+ self.emb_phone = nn.Linear(256, hidden_channels)
48
+ self.lrelu = nn.LeakyReLU(0.1, inplace=True)
49
+ if f0 == True:
50
+ self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
51
+ self.encoder = attentions.Encoder(
52
+ hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
53
+ )
54
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
55
+
56
+ def forward(self, phone, pitch, lengths):
57
+ if pitch == 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().__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 = 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, filter_channels, n_heads, n_layers, kernel_size, p_dropout
100
+ )
101
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
102
+
103
+ def forward(self, phone, pitch, lengths):
104
+ if pitch == None:
105
+ x = self.emb_phone(phone)
106
+ else:
107
+ x = self.emb_phone(phone) + self.emb_pitch(pitch)
108
+ x = x * math.sqrt(self.hidden_channels) # [b, t, h]
109
+ x = self.lrelu(x)
110
+ x = torch.transpose(x, 1, -1) # [b, h, t]
111
+ x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
112
+ x.dtype
113
+ )
114
+ x = self.encoder(x * x_mask, x_mask)
115
+ stats = self.proj(x) * x_mask
116
+
117
+ m, logs = torch.split(stats, self.out_channels, dim=1)
118
+ return m, logs, x_mask
119
+
120
+
121
+ class ResidualCouplingBlock(nn.Module):
122
+ def __init__(
123
+ self,
124
+ channels,
125
+ hidden_channels,
126
+ kernel_size,
127
+ dilation_rate,
128
+ n_layers,
129
+ n_flows=4,
130
+ gin_channels=0,
131
+ ):
132
+ super().__init__()
133
+ self.channels = channels
134
+ self.hidden_channels = hidden_channels
135
+ self.kernel_size = kernel_size
136
+ self.dilation_rate = dilation_rate
137
+ self.n_layers = n_layers
138
+ self.n_flows = n_flows
139
+ self.gin_channels = gin_channels
140
+
141
+ self.flows = nn.ModuleList()
142
+ for i in range(n_flows):
143
+ self.flows.append(
144
+ modules.ResidualCouplingLayer(
145
+ channels,
146
+ hidden_channels,
147
+ kernel_size,
148
+ dilation_rate,
149
+ n_layers,
150
+ gin_channels=gin_channels,
151
+ mean_only=True,
152
+ )
153
+ )
154
+ self.flows.append(modules.Flip())
155
+
156
+ def forward(self, x, x_mask, g=None, reverse=False):
157
+ if not reverse:
158
+ for flow in self.flows:
159
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
160
+ else:
161
+ for flow in reversed(self.flows):
162
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
163
+ return x
164
+
165
+ def remove_weight_norm(self):
166
+ for i in range(self.n_flows):
167
+ self.flows[i * 2].remove_weight_norm()
168
+
169
+
170
+ class PosteriorEncoder(nn.Module):
171
+ def __init__(
172
+ self,
173
+ in_channels,
174
+ out_channels,
175
+ hidden_channels,
176
+ kernel_size,
177
+ dilation_rate,
178
+ n_layers,
179
+ gin_channels=0,
180
+ ):
181
+ super().__init__()
182
+ self.in_channels = in_channels
183
+ self.out_channels = out_channels
184
+ self.hidden_channels = hidden_channels
185
+ self.kernel_size = kernel_size
186
+ self.dilation_rate = dilation_rate
187
+ self.n_layers = n_layers
188
+ self.gin_channels = gin_channels
189
+
190
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
191
+ self.enc = modules.WN(
192
+ hidden_channels,
193
+ kernel_size,
194
+ dilation_rate,
195
+ n_layers,
196
+ gin_channels=gin_channels,
197
+ )
198
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
199
+
200
+ def forward(self, x, x_lengths, g=None):
201
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
202
+ x.dtype
203
+ )
204
+ x = self.pre(x) * x_mask
205
+ x = self.enc(x, x_mask, g=g)
206
+ stats = self.proj(x) * x_mask
207
+ m, logs = torch.split(stats, self.out_channels, dim=1)
208
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
209
+ return z, m, logs, x_mask
210
+
211
+ def remove_weight_norm(self):
212
+ self.enc.remove_weight_norm()
213
+
214
+
215
+ class Generator(torch.nn.Module):
216
+ def __init__(
217
+ self,
218
+ initial_channel,
219
+ resblock,
220
+ resblock_kernel_sizes,
221
+ resblock_dilation_sizes,
222
+ upsample_rates,
223
+ upsample_initial_channel,
224
+ upsample_kernel_sizes,
225
+ gin_channels=0,
226
+ ):
227
+ super(Generator, self).__init__()
228
+ self.num_kernels = len(resblock_kernel_sizes)
229
+ self.num_upsamples = len(upsample_rates)
230
+ self.conv_pre = Conv1d(
231
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
232
+ )
233
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
234
+
235
+ self.ups = nn.ModuleList()
236
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
237
+ self.ups.append(
238
+ weight_norm(
239
+ ConvTranspose1d(
240
+ upsample_initial_channel // (2**i),
241
+ upsample_initial_channel // (2 ** (i + 1)),
242
+ k,
243
+ u,
244
+ padding=(k - u) // 2,
245
+ )
246
+ )
247
+ )
248
+
249
+ self.resblocks = nn.ModuleList()
250
+ for i in range(len(self.ups)):
251
+ ch = upsample_initial_channel // (2 ** (i + 1))
252
+ for j, (k, d) in enumerate(
253
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
254
+ ):
255
+ self.resblocks.append(resblock(ch, k, d))
256
+
257
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
258
+ self.ups.apply(init_weights)
259
+
260
+ if gin_channels != 0:
261
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
262
+
263
+ def forward(self, x, g=None):
264
+ x = self.conv_pre(x)
265
+ if g is not None:
266
+ x = x + self.cond(g)
267
+
268
+ for i in range(self.num_upsamples):
269
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
270
+ x = self.ups[i](x)
271
+ xs = None
272
+ for j in range(self.num_kernels):
273
+ if xs is None:
274
+ xs = self.resblocks[i * self.num_kernels + j](x)
275
+ else:
276
+ xs += self.resblocks[i * self.num_kernels + j](x)
277
+ x = xs / self.num_kernels
278
+ x = F.leaky_relu(x)
279
+ x = self.conv_post(x)
280
+ x = torch.tanh(x)
281
+
282
+ return x
283
+
284
+ def remove_weight_norm(self):
285
+ for l in self.ups:
286
+ remove_weight_norm(l)
287
+ for l in self.resblocks:
288
+ l.remove_weight_norm()
289
+
290
+
291
+ class SineGen(torch.nn.Module):
292
+ """Definition of sine generator
293
+ SineGen(samp_rate, harmonic_num = 0,
294
+ sine_amp = 0.1, noise_std = 0.003,
295
+ voiced_threshold = 0,
296
+ flag_for_pulse=False)
297
+ samp_rate: sampling rate in Hz
298
+ harmonic_num: number of harmonic overtones (default 0)
299
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
300
+ noise_std: std of Gaussian noise (default 0.003)
301
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
302
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
303
+ Note: when flag_for_pulse is True, the first time step of a voiced
304
+ segment is always sin(np.pi) or cos(0)
305
+ """
306
+
307
+ def __init__(
308
+ self,
309
+ samp_rate,
310
+ harmonic_num=0,
311
+ sine_amp=0.1,
312
+ noise_std=0.003,
313
+ voiced_threshold=0,
314
+ flag_for_pulse=False,
315
+ ):
316
+ super(SineGen, self).__init__()
317
+ self.sine_amp = sine_amp
318
+ self.noise_std = noise_std
319
+ self.harmonic_num = harmonic_num
320
+ self.dim = self.harmonic_num + 1
321
+ self.sampling_rate = samp_rate
322
+ self.voiced_threshold = voiced_threshold
323
+
324
+ def _f02uv(self, f0):
325
+ # generate uv signal
326
+ uv = torch.ones_like(f0)
327
+ uv = uv * (f0 > self.voiced_threshold)
328
+ if uv.device.type == "privateuseone": # for DirectML
329
+ uv = uv.float()
330
+ return uv
331
+
332
+ def _f02sine(self, f0, upp):
333
+ """ f0: (batchsize, length, dim)
334
+ where dim indicates fundamental tone and overtones
335
+ """
336
+ a = torch.arange(1, upp + 1, dtype=f0.dtype, device=f0.device)
337
+ rad = f0 / self.sampling_rate * a
338
+ rad2 = torch.fmod(rad[:, :-1, -1:].float() + 0.5, 1.0) - 0.5
339
+ rad_acc = rad2.cumsum(dim=1).fmod(1.0).to(f0)
340
+ rad += F.pad(rad_acc, (0, 0, 1, 0), mode='constant')
341
+ rad = rad.reshape(f0.shape[0], -1, 1)
342
+ b = torch.arange(1, self.dim + 1, dtype=f0.dtype, device=f0.device).reshape(1, 1, -1)
343
+ rad *= b
344
+ rand_ini = torch.rand(1, 1, self.dim, device=f0.device)
345
+ rand_ini[..., 0] = 0
346
+ rad += rand_ini
347
+ sines = torch.sin(2 * np.pi * rad)
348
+ return sines
349
+
350
+ def forward(self, f0: torch.Tensor, upp: int):
351
+ """sine_tensor, uv = forward(f0)
352
+ input F0: tensor(batchsize=1, length, dim=1)
353
+ f0 for unvoiced steps should be 0
354
+ output sine_tensor: tensor(batchsize=1, length, dim)
355
+ output uv: tensor(batchsize=1, length, 1)
356
+ """
357
+ with torch.no_grad():
358
+ f0 = f0.unsqueeze(-1)
359
+ sine_waves = self._f02sine(f0, upp) * self.sine_amp
360
+ uv = self._f02uv(f0)
361
+ uv = F.interpolate(
362
+ uv.transpose(2, 1), scale_factor=float(upp), mode="nearest"
363
+ ).transpose(2, 1)
364
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
365
+ noise = noise_amp * torch.randn_like(sine_waves)
366
+ sine_waves = sine_waves * uv + noise
367
+ return sine_waves, uv, noise
368
+
369
+
370
+ class SourceModuleHnNSF(torch.nn.Module):
371
+ """SourceModule for hn-nsf
372
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
373
+ add_noise_std=0.003, voiced_threshod=0)
374
+ sampling_rate: sampling_rate in Hz
375
+ harmonic_num: number of harmonic above F0 (default: 0)
376
+ sine_amp: amplitude of sine source signal (default: 0.1)
377
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
378
+ note that amplitude of noise in unvoiced is decided
379
+ by sine_amp
380
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
381
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
382
+ F0_sampled (batchsize, length, 1)
383
+ Sine_source (batchsize, length, 1)
384
+ noise_source (batchsize, length 1)
385
+ uv (batchsize, length, 1)
386
+ """
387
+
388
+ def __init__(
389
+ self,
390
+ sampling_rate,
391
+ harmonic_num=0,
392
+ sine_amp=0.1,
393
+ add_noise_std=0.003,
394
+ voiced_threshod=0,
395
+ is_half=True,
396
+ ):
397
+ super(SourceModuleHnNSF, self).__init__()
398
+
399
+ self.sine_amp = sine_amp
400
+ self.noise_std = add_noise_std
401
+ self.is_half = is_half
402
+ # to produce sine waveforms
403
+ self.l_sin_gen = SineGen(
404
+ sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
405
+ )
406
+
407
+ # to merge source harmonics into a single excitation
408
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
409
+ self.l_tanh = torch.nn.Tanh()
410
+
411
+ def forward(self, x, upp=None):
412
+ sine_wavs, uv, _ = self.l_sin_gen(x, upp)
413
+ if self.is_half:
414
+ sine_wavs = sine_wavs.half()
415
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
416
+ return sine_merge, None, None # noise, uv
417
+
418
+
419
+ class GeneratorNSF(torch.nn.Module):
420
+ def __init__(
421
+ self,
422
+ initial_channel,
423
+ resblock,
424
+ resblock_kernel_sizes,
425
+ resblock_dilation_sizes,
426
+ upsample_rates,
427
+ upsample_initial_channel,
428
+ upsample_kernel_sizes,
429
+ gin_channels,
430
+ sr,
431
+ is_half=False,
432
+ ):
433
+ super(GeneratorNSF, self).__init__()
434
+ self.num_kernels = len(resblock_kernel_sizes)
435
+ self.num_upsamples = len(upsample_rates)
436
+
437
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
438
+ self.m_source = SourceModuleHnNSF(
439
+ sampling_rate=sr, harmonic_num=0, is_half=is_half
440
+ )
441
+ self.noise_convs = nn.ModuleList()
442
+ self.conv_pre = Conv1d(
443
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
444
+ )
445
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
446
+
447
+ self.ups = nn.ModuleList()
448
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
449
+ c_cur = upsample_initial_channel // (2 ** (i + 1))
450
+ self.ups.append(
451
+ weight_norm(
452
+ ConvTranspose1d(
453
+ upsample_initial_channel // (2**i),
454
+ upsample_initial_channel // (2 ** (i + 1)),
455
+ k,
456
+ u,
457
+ padding=(k - u) // 2,
458
+ )
459
+ )
460
+ )
461
+ if i + 1 < len(upsample_rates):
462
+ stride_f0 = np.prod(upsample_rates[i + 1 :])
463
+ self.noise_convs.append(
464
+ Conv1d(
465
+ 1,
466
+ c_cur,
467
+ kernel_size=stride_f0 * 2,
468
+ stride=stride_f0,
469
+ padding=stride_f0 // 2,
470
+ )
471
+ )
472
+ else:
473
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
474
+
475
+ self.resblocks = nn.ModuleList()
476
+ for i in range(len(self.ups)):
477
+ ch = upsample_initial_channel // (2 ** (i + 1))
478
+ for j, (k, d) in enumerate(
479
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
480
+ ):
481
+ self.resblocks.append(resblock(ch, k, d))
482
+
483
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
484
+ self.ups.apply(init_weights)
485
+
486
+ if gin_channels != 0:
487
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
488
+
489
+ self.upp = np.prod(upsample_rates)
490
+
491
+ def forward(self, x, f0, g=None):
492
+ har_source, noi_source, uv = self.m_source(f0, self.upp)
493
+ har_source = har_source.transpose(1, 2)
494
+ x = self.conv_pre(x)
495
+ if g is not None:
496
+ x = x + self.cond(g)
497
+
498
+ for i in range(self.num_upsamples):
499
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
500
+ x = self.ups[i](x)
501
+ x_source = self.noise_convs[i](har_source)
502
+ x = x + x_source
503
+ xs = None
504
+ for j in range(self.num_kernels):
505
+ if xs is None:
506
+ xs = self.resblocks[i * self.num_kernels + j](x)
507
+ else:
508
+ xs += self.resblocks[i * self.num_kernels + j](x)
509
+ x = xs / self.num_kernels
510
+ x = F.leaky_relu(x)
511
+ x = self.conv_post(x)
512
+ x = torch.tanh(x)
513
+ return x
514
+
515
+ def remove_weight_norm(self):
516
+ for l in self.ups:
517
+ remove_weight_norm(l)
518
+ for l in self.resblocks:
519
+ l.remove_weight_norm()
520
+
521
+
522
+ sr2sr = {
523
+ "32k": 32000,
524
+ "40k": 40000,
525
+ "48k": 48000,
526
+ }
527
+
528
+
529
+ class SynthesizerTrnMsNSFsidM(nn.Module):
530
+ def __init__(
531
+ self,
532
+ spec_channels,
533
+ segment_size,
534
+ inter_channels,
535
+ hidden_channels,
536
+ filter_channels,
537
+ n_heads,
538
+ n_layers,
539
+ kernel_size,
540
+ p_dropout,
541
+ resblock,
542
+ resblock_kernel_sizes,
543
+ resblock_dilation_sizes,
544
+ upsample_rates,
545
+ upsample_initial_channel,
546
+ upsample_kernel_sizes,
547
+ spk_embed_dim,
548
+ gin_channels,
549
+ sr,
550
+ version,
551
+ **kwargs,
552
+ ):
553
+ super().__init__()
554
+ if type(sr) == type("strr"):
555
+ sr = sr2sr[sr]
556
+ self.spec_channels = spec_channels
557
+ self.inter_channels = inter_channels
558
+ self.hidden_channels = hidden_channels
559
+ self.filter_channels = filter_channels
560
+ self.n_heads = n_heads
561
+ self.n_layers = n_layers
562
+ self.kernel_size = kernel_size
563
+ self.p_dropout = p_dropout
564
+ self.resblock = resblock
565
+ self.resblock_kernel_sizes = resblock_kernel_sizes
566
+ self.resblock_dilation_sizes = resblock_dilation_sizes
567
+ self.upsample_rates = upsample_rates
568
+ self.upsample_initial_channel = upsample_initial_channel
569
+ self.upsample_kernel_sizes = upsample_kernel_sizes
570
+ self.segment_size = segment_size
571
+ self.gin_channels = gin_channels
572
+ # self.hop_length = hop_length#
573
+ self.spk_embed_dim = spk_embed_dim
574
+ if version == "v1":
575
+ self.enc_p = TextEncoder256(
576
+ inter_channels,
577
+ hidden_channels,
578
+ filter_channels,
579
+ n_heads,
580
+ n_layers,
581
+ kernel_size,
582
+ p_dropout,
583
+ )
584
+ else:
585
+ self.enc_p = TextEncoder768(
586
+ inter_channels,
587
+ hidden_channels,
588
+ filter_channels,
589
+ n_heads,
590
+ n_layers,
591
+ kernel_size,
592
+ p_dropout,
593
+ )
594
+ self.dec = GeneratorNSF(
595
+ inter_channels,
596
+ resblock,
597
+ resblock_kernel_sizes,
598
+ resblock_dilation_sizes,
599
+ upsample_rates,
600
+ upsample_initial_channel,
601
+ upsample_kernel_sizes,
602
+ gin_channels=gin_channels,
603
+ sr=sr,
604
+ is_half=kwargs["is_half"],
605
+ )
606
+ self.enc_q = PosteriorEncoder(
607
+ spec_channels,
608
+ inter_channels,
609
+ hidden_channels,
610
+ 5,
611
+ 1,
612
+ 16,
613
+ gin_channels=gin_channels,
614
+ )
615
+ self.flow = ResidualCouplingBlock(
616
+ inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
617
+ )
618
+ self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
619
+ self.speaker_map = None
620
+ logger.debug(
621
+ f"gin_channels: {gin_channels}, self.spk_embed_dim: {self.spk_embed_dim}"
622
+ )
623
+
624
+ def remove_weight_norm(self):
625
+ self.dec.remove_weight_norm()
626
+ self.flow.remove_weight_norm()
627
+ self.enc_q.remove_weight_norm()
628
+
629
+ def construct_spkmixmap(self, n_speaker):
630
+ self.speaker_map = torch.zeros((n_speaker, 1, 1, self.gin_channels))
631
+ for i in range(n_speaker):
632
+ self.speaker_map[i] = self.emb_g(torch.LongTensor([[i]]))
633
+ self.speaker_map = self.speaker_map.unsqueeze(0)
634
+
635
+ def forward(self, phone, phone_lengths, pitch, nsff0, g, rnd, max_len=None):
636
+ if self.speaker_map is not None: # [N, S] * [S, B, 1, H]
637
+ g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
638
+ g = g * self.speaker_map # [N, S, B, 1, H]
639
+ g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
640
+ g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
641
+ else:
642
+ g = g.unsqueeze(0)
643
+ g = self.emb_g(g).transpose(1, 2)
644
+
645
+ m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
646
+ z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask
647
+ z = self.flow(z_p, x_mask, g=g, reverse=True)
648
+ o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
649
+ return o
650
+
651
+
652
+ class MultiPeriodDiscriminator(torch.nn.Module):
653
+ def __init__(self, use_spectral_norm=False):
654
+ super(MultiPeriodDiscriminator, self).__init__()
655
+ periods = [2, 3, 5, 7, 11, 17]
656
+ # periods = [3, 5, 7, 11, 17, 23, 37]
657
+
658
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
659
+ discs = discs + [
660
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
661
+ ]
662
+ self.discriminators = nn.ModuleList(discs)
663
+
664
+ def forward(self, y, y_hat):
665
+ y_d_rs = [] #
666
+ y_d_gs = []
667
+ fmap_rs = []
668
+ fmap_gs = []
669
+ for i, d in enumerate(self.discriminators):
670
+ y_d_r, fmap_r = d(y)
671
+ y_d_g, fmap_g = d(y_hat)
672
+ # for j in range(len(fmap_r)):
673
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
674
+ y_d_rs.append(y_d_r)
675
+ y_d_gs.append(y_d_g)
676
+ fmap_rs.append(fmap_r)
677
+ fmap_gs.append(fmap_g)
678
+
679
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
680
+
681
+
682
+ class MultiPeriodDiscriminatorV2(torch.nn.Module):
683
+ def __init__(self, use_spectral_norm=False):
684
+ super(MultiPeriodDiscriminatorV2, self).__init__()
685
+ # periods = [2, 3, 5, 7, 11, 17]
686
+ periods = [2, 3, 5, 7, 11, 17, 23, 37]
687
+
688
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
689
+ discs = discs + [
690
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
691
+ ]
692
+ self.discriminators = nn.ModuleList(discs)
693
+
694
+ def forward(self, y, y_hat):
695
+ y_d_rs = [] #
696
+ y_d_gs = []
697
+ fmap_rs = []
698
+ fmap_gs = []
699
+ for i, d in enumerate(self.discriminators):
700
+ y_d_r, fmap_r = d(y)
701
+ y_d_g, fmap_g = d(y_hat)
702
+ # for j in range(len(fmap_r)):
703
+ # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
704
+ y_d_rs.append(y_d_r)
705
+ y_d_gs.append(y_d_g)
706
+ fmap_rs.append(fmap_r)
707
+ fmap_gs.append(fmap_g)
708
+
709
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
710
+
711
+
712
+ class DiscriminatorS(torch.nn.Module):
713
+ def __init__(self, use_spectral_norm=False):
714
+ super(DiscriminatorS, self).__init__()
715
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
716
+ self.convs = nn.ModuleList(
717
+ [
718
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
719
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
720
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
721
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
722
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
723
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
724
+ ]
725
+ )
726
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
727
+
728
+ def forward(self, x):
729
+ fmap = []
730
+
731
+ for l in self.convs:
732
+ x = l(x)
733
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
734
+ fmap.append(x)
735
+ x = self.conv_post(x)
736
+ fmap.append(x)
737
+ x = torch.flatten(x, 1, -1)
738
+
739
+ return x, fmap
740
+
741
+
742
+ class DiscriminatorP(torch.nn.Module):
743
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
744
+ super(DiscriminatorP, self).__init__()
745
+ self.period = period
746
+ self.use_spectral_norm = use_spectral_norm
747
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
748
+ self.convs = nn.ModuleList(
749
+ [
750
+ norm_f(
751
+ Conv2d(
752
+ 1,
753
+ 32,
754
+ (kernel_size, 1),
755
+ (stride, 1),
756
+ padding=(get_padding(kernel_size, 1), 0),
757
+ )
758
+ ),
759
+ norm_f(
760
+ Conv2d(
761
+ 32,
762
+ 128,
763
+ (kernel_size, 1),
764
+ (stride, 1),
765
+ padding=(get_padding(kernel_size, 1), 0),
766
+ )
767
+ ),
768
+ norm_f(
769
+ Conv2d(
770
+ 128,
771
+ 512,
772
+ (kernel_size, 1),
773
+ (stride, 1),
774
+ padding=(get_padding(kernel_size, 1), 0),
775
+ )
776
+ ),
777
+ norm_f(
778
+ Conv2d(
779
+ 512,
780
+ 1024,
781
+ (kernel_size, 1),
782
+ (stride, 1),
783
+ padding=(get_padding(kernel_size, 1), 0),
784
+ )
785
+ ),
786
+ norm_f(
787
+ Conv2d(
788
+ 1024,
789
+ 1024,
790
+ (kernel_size, 1),
791
+ 1,
792
+ padding=(get_padding(kernel_size, 1), 0),
793
+ )
794
+ ),
795
+ ]
796
+ )
797
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
798
+
799
+ def forward(self, x):
800
+ fmap = []
801
+
802
+ # 1d to 2d
803
+ b, c, t = x.shape
804
+ if t % self.period != 0: # pad first
805
+ n_pad = self.period - (t % self.period)
806
+ x = F.pad(x, (0, n_pad), "reflect")
807
+ t = t + n_pad
808
+ x = x.view(b, c, t // self.period, self.period)
809
+
810
+ for l in self.convs:
811
+ x = l(x)
812
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
813
+ fmap.append(x)
814
+ x = self.conv_post(x)
815
+ fmap.append(x)
816
+ x = torch.flatten(x, 1, -1)
817
+
818
+ 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"), weights_only=False)
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, weights_only=False)
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"), weights_only=False)
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", weights_only=False)
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/rtrvc.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import os
3
+ import sys
4
+ import traceback
5
+ from infer.lib import jit
6
+ from infer.lib.jit.get_synthesizer import get_synthesizer
7
+ from time import time as ttime
8
+ import fairseq
9
+ import faiss
10
+ import numpy as np
11
+ import parselmouth
12
+ import pyworld
13
+ import scipy.signal as signal
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import torchcrepe
18
+ from torchaudio.transforms import Resample
19
+
20
+ now_dir = os.getcwd()
21
+ sys.path.append(now_dir)
22
+ from multiprocessing import Manager as M
23
+
24
+ from configs.config import Config
25
+
26
+ # config = Config()
27
+
28
+ mm = M()
29
+
30
+
31
+ def printt(strr, *args):
32
+ if len(args) == 0:
33
+ print(strr)
34
+ else:
35
+ print(strr % args)
36
+
37
+
38
+ # config.device=torch.device("cpu")########强制cpu测试
39
+ # config.is_half=False########强制cpu测试
40
+ class RVC:
41
+ def __init__(
42
+ self,
43
+ key,
44
+ formant,
45
+ pth_path,
46
+ index_path,
47
+ index_rate,
48
+ n_cpu,
49
+ inp_q,
50
+ opt_q,
51
+ config: Config,
52
+ last_rvc=None,
53
+ ) -> None:
54
+ """
55
+ 初始化
56
+ """
57
+ try:
58
+ if config.dml == True:
59
+
60
+ def forward_dml(ctx, x, scale):
61
+ ctx.scale = scale
62
+ res = x.clone().detach()
63
+ return res
64
+
65
+ fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
66
+ # global config
67
+ self.config = config
68
+ self.inp_q = inp_q
69
+ self.opt_q = opt_q
70
+ # device="cpu"########强制cpu测试
71
+ self.device = config.device
72
+ self.f0_up_key = key
73
+ self.formant_shift = formant
74
+ self.f0_min = 50
75
+ self.f0_max = 1100
76
+ self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
77
+ self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
78
+ self.n_cpu = n_cpu
79
+ self.use_jit = self.config.use_jit
80
+ self.is_half = config.is_half
81
+
82
+ if index_rate != 0:
83
+ self.index = faiss.read_index(index_path)
84
+ self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
85
+ printt("Index search enabled")
86
+ self.pth_path: str = pth_path
87
+ self.index_path = index_path
88
+ self.index_rate = index_rate
89
+ self.cache_pitch: torch.Tensor = torch.zeros(
90
+ 1024, device=self.device, dtype=torch.long
91
+ )
92
+ self.cache_pitchf = torch.zeros(
93
+ 1024, device=self.device, dtype=torch.float32
94
+ )
95
+
96
+ self.resample_kernel = {}
97
+
98
+ if last_rvc is None:
99
+ models, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
100
+ ["assets/hubert/hubert_base.pt"],
101
+ suffix="",
102
+ )
103
+ hubert_model = models[0]
104
+ hubert_model = hubert_model.to(self.device)
105
+ if self.is_half:
106
+ hubert_model = hubert_model.half()
107
+ else:
108
+ hubert_model = hubert_model.float()
109
+ hubert_model.eval()
110
+ self.model = hubert_model
111
+ else:
112
+ self.model = last_rvc.model
113
+
114
+ self.net_g: nn.Module = None
115
+
116
+ def set_default_model():
117
+ self.net_g, cpt = get_synthesizer(self.pth_path, self.device)
118
+ self.tgt_sr = cpt["config"][-1]
119
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
120
+ self.if_f0 = cpt.get("f0", 1)
121
+ self.version = cpt.get("version", "v1")
122
+ if self.is_half:
123
+ self.net_g = self.net_g.half()
124
+ else:
125
+ self.net_g = self.net_g.float()
126
+
127
+ def set_jit_model():
128
+ jit_pth_path = self.pth_path.rstrip(".pth")
129
+ jit_pth_path += ".half.jit" if self.is_half else ".jit"
130
+ reload = False
131
+ if str(self.device) == "cuda":
132
+ self.device = torch.device("cuda:0")
133
+ if os.path.exists(jit_pth_path):
134
+ cpt = jit.load(jit_pth_path)
135
+ model_device = cpt["device"]
136
+ if model_device != str(self.device):
137
+ reload = True
138
+ else:
139
+ reload = True
140
+
141
+ if reload:
142
+ cpt = jit.synthesizer_jit_export(
143
+ self.pth_path,
144
+ "script",
145
+ None,
146
+ device=self.device,
147
+ is_half=self.is_half,
148
+ )
149
+
150
+ self.tgt_sr = cpt["config"][-1]
151
+ self.if_f0 = cpt.get("f0", 1)
152
+ self.version = cpt.get("version", "v1")
153
+ self.net_g = torch.jit.load(
154
+ BytesIO(cpt["model"]), map_location=self.device
155
+ )
156
+ self.net_g.infer = self.net_g.forward
157
+ self.net_g.eval().to(self.device)
158
+
159
+ def set_synthesizer():
160
+ if self.use_jit and not config.dml:
161
+ if self.is_half and "cpu" in str(self.device):
162
+ printt(
163
+ "Use default Synthesizer model. \
164
+ Jit is not supported on the CPU for half floating point"
165
+ )
166
+ set_default_model()
167
+ else:
168
+ set_jit_model()
169
+ else:
170
+ set_default_model()
171
+
172
+ if last_rvc is None or last_rvc.pth_path != self.pth_path:
173
+ set_synthesizer()
174
+ else:
175
+ self.tgt_sr = last_rvc.tgt_sr
176
+ self.if_f0 = last_rvc.if_f0
177
+ self.version = last_rvc.version
178
+ self.is_half = last_rvc.is_half
179
+ if last_rvc.use_jit != self.use_jit:
180
+ set_synthesizer()
181
+ else:
182
+ self.net_g = last_rvc.net_g
183
+
184
+ if last_rvc is not None and hasattr(last_rvc, "model_rmvpe"):
185
+ self.model_rmvpe = last_rvc.model_rmvpe
186
+ if last_rvc is not None and hasattr(last_rvc, "model_fcpe"):
187
+ self.device_fcpe = last_rvc.device_fcpe
188
+ self.model_fcpe = last_rvc.model_fcpe
189
+ except:
190
+ printt(traceback.format_exc())
191
+
192
+ def change_key(self, new_key):
193
+ self.f0_up_key = new_key
194
+
195
+ def change_formant(self, new_formant):
196
+ self.formant_shift = new_formant
197
+
198
+ def change_index_rate(self, new_index_rate):
199
+ if new_index_rate != 0 and self.index_rate == 0:
200
+ self.index = faiss.read_index(self.index_path)
201
+ self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
202
+ printt("Index search enabled")
203
+ self.index_rate = new_index_rate
204
+
205
+ def get_f0_post(self, f0):
206
+ if not torch.is_tensor(f0):
207
+ f0 = torch.from_numpy(f0)
208
+ f0 = f0.float().to(self.device).squeeze()
209
+ f0_mel = 1127 * torch.log(1 + f0 / 700)
210
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * 254 / (
211
+ self.f0_mel_max - self.f0_mel_min
212
+ ) + 1
213
+ f0_mel[f0_mel <= 1] = 1
214
+ f0_mel[f0_mel > 255] = 255
215
+ f0_coarse = torch.round(f0_mel).long()
216
+ return f0_coarse, f0
217
+
218
+ def get_f0(self, x, f0_up_key, n_cpu, method="harvest"):
219
+ n_cpu = int(n_cpu)
220
+ if method == "crepe":
221
+ return self.get_f0_crepe(x, f0_up_key)
222
+ if method == "rmvpe":
223
+ return self.get_f0_rmvpe(x, f0_up_key)
224
+ if method == "fcpe":
225
+ return self.get_f0_fcpe(x, f0_up_key)
226
+ x = x.cpu().numpy()
227
+ if method == "pm":
228
+ p_len = x.shape[0] // 160 + 1
229
+ f0_min = 65
230
+ l_pad = int(np.ceil(1.5 / f0_min * 16000))
231
+ r_pad = l_pad + 1
232
+ s = parselmouth.Sound(np.pad(x, (l_pad, r_pad)), 16000).to_pitch_ac(
233
+ time_step=0.01,
234
+ voicing_threshold=0.6,
235
+ pitch_floor=f0_min,
236
+ pitch_ceiling=1100,
237
+ )
238
+ assert np.abs(s.t1 - 1.5 / f0_min) < 0.001
239
+ f0 = s.selected_array["frequency"]
240
+ if len(f0) < p_len:
241
+ f0 = np.pad(f0, (0, p_len - len(f0)))
242
+ f0 = f0[:p_len]
243
+ f0 *= pow(2, f0_up_key / 12)
244
+ return self.get_f0_post(f0)
245
+ if n_cpu == 1:
246
+ f0, t = pyworld.harvest(
247
+ x.astype(np.double),
248
+ fs=16000,
249
+ f0_ceil=1100,
250
+ f0_floor=50,
251
+ frame_period=10,
252
+ )
253
+ f0 = signal.medfilt(f0, 3)
254
+ f0 *= pow(2, f0_up_key / 12)
255
+ return self.get_f0_post(f0)
256
+ f0bak = np.zeros(x.shape[0] // 160 + 1, dtype=np.float64)
257
+ length = len(x)
258
+ part_length = 160 * ((length // 160 - 1) // n_cpu + 1)
259
+ n_cpu = (length // 160 - 1) // (part_length // 160) + 1
260
+ ts = ttime()
261
+ res_f0 = mm.dict()
262
+ for idx in range(n_cpu):
263
+ tail = part_length * (idx + 1) + 320
264
+ if idx == 0:
265
+ self.inp_q.put((idx, x[:tail], res_f0, n_cpu, ts))
266
+ else:
267
+ self.inp_q.put(
268
+ (idx, x[part_length * idx - 320 : tail], res_f0, n_cpu, ts)
269
+ )
270
+ while 1:
271
+ res_ts = self.opt_q.get()
272
+ if res_ts == ts:
273
+ break
274
+ f0s = [i[1] for i in sorted(res_f0.items(), key=lambda x: x[0])]
275
+ for idx, f0 in enumerate(f0s):
276
+ if idx == 0:
277
+ f0 = f0[:-3]
278
+ elif idx != n_cpu - 1:
279
+ f0 = f0[2:-3]
280
+ else:
281
+ f0 = f0[2:]
282
+ f0bak[part_length * idx // 160 : part_length * idx // 160 + f0.shape[0]] = (
283
+ f0
284
+ )
285
+ f0bak = signal.medfilt(f0bak, 3)
286
+ f0bak *= pow(2, f0_up_key / 12)
287
+ return self.get_f0_post(f0bak)
288
+
289
+ def get_f0_crepe(self, x, f0_up_key):
290
+ if "privateuseone" in str(
291
+ self.device
292
+ ): ###不支持dml,cpu又太慢用不成,拿fcpe顶替
293
+ return self.get_f0(x, f0_up_key, 1, "fcpe")
294
+ # printt("using crepe,device:%s"%self.device)
295
+ f0, pd = torchcrepe.predict(
296
+ x.unsqueeze(0).float(),
297
+ 16000,
298
+ 160,
299
+ self.f0_min,
300
+ self.f0_max,
301
+ "full",
302
+ batch_size=512,
303
+ # device=self.device if self.device.type!="privateuseone" else "cpu",###crepe不用半精度全部是全精度所以不愁###cpu延迟高到没法用
304
+ device=self.device,
305
+ return_periodicity=True,
306
+ )
307
+ pd = torchcrepe.filter.median(pd, 3)
308
+ f0 = torchcrepe.filter.mean(f0, 3)
309
+ f0[pd < 0.1] = 0
310
+ f0 *= pow(2, f0_up_key / 12)
311
+ return self.get_f0_post(f0)
312
+
313
+ def get_f0_rmvpe(self, x, f0_up_key):
314
+ if hasattr(self, "model_rmvpe") == False:
315
+ from infer.lib.rmvpe import RMVPE
316
+
317
+ printt("Loading rmvpe model")
318
+ self.model_rmvpe = RMVPE(
319
+ "assets/rmvpe/rmvpe.pt",
320
+ is_half=self.is_half,
321
+ device=self.device,
322
+ use_jit=self.config.use_jit,
323
+ )
324
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
325
+ f0 *= pow(2, f0_up_key / 12)
326
+ return self.get_f0_post(f0)
327
+
328
+ def get_f0_fcpe(self, x, f0_up_key):
329
+ if hasattr(self, "model_fcpe") == False:
330
+ from torchfcpe import spawn_bundled_infer_model
331
+
332
+ printt("Loading fcpe model")
333
+ if "privateuseone" in str(self.device):
334
+ self.device_fcpe = "cpu"
335
+ else:
336
+ self.device_fcpe = self.device
337
+ self.model_fcpe = spawn_bundled_infer_model(self.device_fcpe)
338
+ f0 = self.model_fcpe.infer(
339
+ x.to(self.device_fcpe).unsqueeze(0).float(),
340
+ sr=16000,
341
+ decoder_mode="local_argmax",
342
+ threshold=0.006,
343
+ )
344
+ f0 *= pow(2, f0_up_key / 12)
345
+ return self.get_f0_post(f0)
346
+
347
+ def infer(
348
+ self,
349
+ input_wav: torch.Tensor,
350
+ block_frame_16k,
351
+ skip_head,
352
+ return_length,
353
+ f0method,
354
+ ) -> np.ndarray:
355
+ t1 = ttime()
356
+ with torch.no_grad():
357
+ if self.config.is_half:
358
+ feats = input_wav.half().view(1, -1)
359
+ else:
360
+ feats = input_wav.float().view(1, -1)
361
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
362
+ inputs = {
363
+ "source": feats,
364
+ "padding_mask": padding_mask,
365
+ "output_layer": 9 if self.version == "v1" else 12,
366
+ }
367
+ logits = self.model.extract_features(**inputs)
368
+ feats = (
369
+ self.model.final_proj(logits[0]) if self.version == "v1" else logits[0]
370
+ )
371
+ feats = torch.cat((feats, feats[:, -1:, :]), 1)
372
+ t2 = ttime()
373
+ try:
374
+ if hasattr(self, "index") and self.index_rate != 0:
375
+ npy = feats[0][skip_head // 2 :].cpu().numpy().astype("float32")
376
+ score, ix = self.index.search(npy, k=8)
377
+ if (ix >= 0).all():
378
+ weight = np.square(1 / score)
379
+ weight /= weight.sum(axis=1, keepdims=True)
380
+ npy = np.sum(
381
+ self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1
382
+ )
383
+ if self.config.is_half:
384
+ npy = npy.astype("float16")
385
+ feats[0][skip_head // 2 :] = (
386
+ torch.from_numpy(npy).unsqueeze(0).to(self.device)
387
+ * self.index_rate
388
+ + (1 - self.index_rate) * feats[0][skip_head // 2 :]
389
+ )
390
+ else:
391
+ printt(
392
+ "Invalid index. You MUST use added_xxxx.index but not trained_xxxx.index!"
393
+ )
394
+ else:
395
+ printt("Index search FAILED or disabled")
396
+ except:
397
+ traceback.print_exc()
398
+ printt("Index search FAILED")
399
+ t3 = ttime()
400
+ p_len = input_wav.shape[0] // 160
401
+ factor = pow(2, self.formant_shift / 12)
402
+ return_length2 = int(np.ceil(return_length * factor))
403
+ if self.if_f0 == 1:
404
+ f0_extractor_frame = block_frame_16k + 800
405
+ if f0method == "rmvpe":
406
+ f0_extractor_frame = 5120 * ((f0_extractor_frame - 1) // 5120 + 1) - 160
407
+ pitch, pitchf = self.get_f0(
408
+ input_wav[-f0_extractor_frame:], self.f0_up_key - self.formant_shift, self.n_cpu, f0method
409
+ )
410
+ shift = block_frame_16k // 160
411
+ self.cache_pitch[:-shift] = self.cache_pitch[shift:].clone()
412
+ self.cache_pitchf[:-shift] = self.cache_pitchf[shift:].clone()
413
+ self.cache_pitch[4 - pitch.shape[0] :] = pitch[3:-1]
414
+ self.cache_pitchf[4 - pitch.shape[0] :] = pitchf[3:-1]
415
+ cache_pitch = self.cache_pitch[None, -p_len:]
416
+ cache_pitchf = self.cache_pitchf[None, -p_len:] * return_length2 / return_length
417
+ t4 = ttime()
418
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
419
+ feats = feats[:, :p_len, :]
420
+ p_len = torch.LongTensor([p_len]).to(self.device)
421
+ sid = torch.LongTensor([0]).to(self.device)
422
+ skip_head = torch.LongTensor([skip_head])
423
+ return_length2 = torch.LongTensor([return_length2])
424
+ return_length = torch.LongTensor([return_length])
425
+ with torch.no_grad():
426
+ if self.if_f0 == 1:
427
+ infered_audio, _, _ = self.net_g.infer(
428
+ feats,
429
+ p_len,
430
+ cache_pitch,
431
+ cache_pitchf,
432
+ sid,
433
+ skip_head,
434
+ return_length,
435
+ return_length2,
436
+ )
437
+ else:
438
+ infered_audio, _, _ = self.net_g.infer(
439
+ feats, p_len, sid, skip_head, return_length, return_length2
440
+ )
441
+ infered_audio = infered_audio.squeeze(1).float()
442
+ upp_res = int(np.floor(factor * self.tgt_sr // 100))
443
+ if upp_res != self.tgt_sr // 100:
444
+ if upp_res not in self.resample_kernel:
445
+ self.resample_kernel[upp_res] = Resample(
446
+ orig_freq=upp_res,
447
+ new_freq=self.tgt_sr // 100,
448
+ dtype=torch.float32,
449
+ ).to(self.device)
450
+ infered_audio = self.resample_kernel[upp_res](
451
+ infered_audio[:, : return_length * upp_res]
452
+ )
453
+ t5 = ttime()
454
+ printt(
455
+ "Spent time: fea = %.3fs, index = %.3fs, f0 = %.3fs, model = %.3fs",
456
+ t2 - t1,
457
+ t3 - t2,
458
+ t4 - t3,
459
+ t5 - t4,
460
+ )
461
+ return infered_audio.squeeze()
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, weights_only=False)
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, weights_only=False)
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", weights_only=False)
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", weights_only=False)
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", weights_only=False)
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", weights_only=False)
220
+ ckpt2 = torch.load(path2, map_location="cpu", weights_only=False)
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,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", weights_only=False)
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", weights_only=False)
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
+ try:
282
+ with open(filename, encoding="utf-8") as f:
283
+ filepaths_and_text = [line.strip().split(split) for line in f]
284
+ except UnicodeDecodeError:
285
+ with open(filename) as f:
286
+ filepaths_and_text = [line.strip().split(split) for line in f]
287
+
288
+ return filepaths_and_text
289
+
290
+
291
+ def get_hparams(init=True):
292
+ """
293
+ todo:
294
+ 结尾七人���:
295
+ 保存频率、总epoch done
296
+ bs done
297
+ pretrainG、pretrainD done
298
+ 卡号:os.en["CUDA_VISIBLE_DEVICES"] done
299
+ if_latest done
300
+ 模型:if_f0 done
301
+ 采样率:自动选择config done
302
+ 是否缓存数据集进GPU:if_cache_data_in_gpu done
303
+
304
+ -m:
305
+ 自动决定training_files路径,改掉train_nsf_load_pretrain.py里的hps.data.training_files done
306
+ -c不要了
307
+ """
308
+ parser = argparse.ArgumentParser()
309
+ parser.add_argument(
310
+ "-se",
311
+ "--save_every_epoch",
312
+ type=int,
313
+ required=True,
314
+ help="checkpoint save frequency (epoch)",
315
+ )
316
+ parser.add_argument(
317
+ "-te", "--total_epoch", type=int, required=True, help="total_epoch"
318
+ )
319
+ parser.add_argument(
320
+ "-pg", "--pretrainG", type=str, default="", help="Pretrained Generator path"
321
+ )
322
+ parser.add_argument(
323
+ "-pd", "--pretrainD", type=str, default="", help="Pretrained Discriminator path"
324
+ )
325
+ parser.add_argument("-g", "--gpus", type=str, default="0", help="split by -")
326
+ parser.add_argument(
327
+ "-bs", "--batch_size", type=int, required=True, help="batch size"
328
+ )
329
+ parser.add_argument(
330
+ "-e", "--experiment_dir", type=str, required=True, help="experiment dir"
331
+ ) # -m
332
+ parser.add_argument(
333
+ "-sr", "--sample_rate", type=str, required=True, help="sample rate, 32k/40k/48k"
334
+ )
335
+ parser.add_argument(
336
+ "-sw",
337
+ "--save_every_weights",
338
+ type=str,
339
+ default="0",
340
+ help="save the extracted model in weights directory when saving checkpoints",
341
+ )
342
+ parser.add_argument(
343
+ "-v", "--version", type=str, required=True, help="model version"
344
+ )
345
+ parser.add_argument(
346
+ "-f0",
347
+ "--if_f0",
348
+ type=int,
349
+ required=True,
350
+ help="use f0 as one of the inputs of the model, 1 or 0",
351
+ )
352
+ parser.add_argument(
353
+ "-l",
354
+ "--if_latest",
355
+ type=int,
356
+ required=True,
357
+ help="if only save the latest G/D pth file, 1 or 0",
358
+ )
359
+ parser.add_argument(
360
+ "-c",
361
+ "--if_cache_data_in_gpu",
362
+ type=int,
363
+ required=True,
364
+ help="if caching the dataset in GPU memory, 1 or 0",
365
+ )
366
+
367
+ args = parser.parse_args()
368
+ name = args.experiment_dir
369
+ experiment_dir = os.path.join("./logs", args.experiment_dir)
370
+
371
+ config_save_path = os.path.join(experiment_dir, "config.json")
372
+ with open(config_save_path, "r") as f:
373
+ config = json.load(f)
374
+
375
+ hparams = HParams(**config)
376
+ hparams.model_dir = hparams.experiment_dir = experiment_dir
377
+ hparams.save_every_epoch = args.save_every_epoch
378
+ hparams.name = name
379
+ hparams.total_epoch = args.total_epoch
380
+ hparams.pretrainG = args.pretrainG
381
+ hparams.pretrainD = args.pretrainD
382
+ hparams.version = args.version
383
+ hparams.gpus = args.gpus
384
+ hparams.train.batch_size = args.batch_size
385
+ hparams.sample_rate = args.sample_rate
386
+ hparams.if_f0 = args.if_f0
387
+ hparams.if_latest = args.if_latest
388
+ hparams.save_every_weights = args.save_every_weights
389
+ hparams.if_cache_data_in_gpu = args.if_cache_data_in_gpu
390
+ hparams.data.training_files = "%s/filelist.txt" % experiment_dir
391
+ return hparams
392
+
393
+
394
+ def get_hparams_from_dir(model_dir):
395
+ config_save_path = os.path.join(model_dir, "config.json")
396
+ with open(config_save_path, "r") as f:
397
+ data = f.read()
398
+ config = json.loads(data)
399
+
400
+ hparams = HParams(**config)
401
+ hparams.model_dir = model_dir
402
+ return hparams
403
+
404
+
405
+ def get_hparams_from_file(config_path):
406
+ with open(config_path, "r") as f:
407
+ data = f.read()
408
+ config = json.loads(data)
409
+
410
+ hparams = HParams(**config)
411
+ return hparams
412
+
413
+
414
+ def check_git_hash(model_dir):
415
+ source_dir = os.path.dirname(os.path.realpath(__file__))
416
+ if not os.path.exists(os.path.join(source_dir, ".git")):
417
+ logger.warning(
418
+ "{} is not a git repository, therefore hash value comparison will be ignored.".format(
419
+ source_dir
420
+ )
421
+ )
422
+ return
423
+
424
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
425
+
426
+ path = os.path.join(model_dir, "githash")
427
+ if os.path.exists(path):
428
+ saved_hash = open(path).read()
429
+ if saved_hash != cur_hash:
430
+ logger.warning(
431
+ "git hash values are different. {}(saved) != {}(current)".format(
432
+ saved_hash[:8], cur_hash[:8]
433
+ )
434
+ )
435
+ else:
436
+ open(path, "w").write(cur_hash)
437
+
438
+
439
+ def get_logger(model_dir, filename="train.log"):
440
+ global logger
441
+ logger = logging.getLogger(os.path.basename(model_dir))
442
+ logger.setLevel(logging.DEBUG)
443
+
444
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
445
+ if not os.path.exists(model_dir):
446
+ os.makedirs(model_dir)
447
+ h = logging.FileHandler(os.path.join(model_dir, filename))
448
+ h.setLevel(logging.DEBUG)
449
+ h.setFormatter(formatter)
450
+ logger.addHandler(h)
451
+ return logger
452
+
453
+
454
+ class HParams:
455
+ def __init__(self, **kwargs):
456
+ for k, v in kwargs.items():
457
+ if type(v) == dict:
458
+ v = HParams(**v)
459
+ self[k] = v
460
+
461
+ def keys(self):
462
+ return self.__dict__.keys()
463
+
464
+ def items(self):
465
+ return self.__dict__.items()
466
+
467
+ def values(self):
468
+ return self.__dict__.values()
469
+
470
+ def __len__(self):
471
+ return len(self.__dict__)
472
+
473
+ def __getitem__(self, key):
474
+ return getattr(self, key)
475
+
476
+ def __setitem__(self, key, value):
477
+ return setattr(self, key, value)
478
+
479
+ def __contains__(self, key):
480
+ return key in self.__dict__
481
+
482
+ def __repr__(self):
483
+ 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
+ }