Spaces:
Running
Running
同步官方仓库的更新
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +14 -16
- cluster/__init__.py +0 -29
- cluster/kmeans.py +0 -201
- cluster/train_cluster.py +0 -84
- configs/config.json +0 -0
- diffusion/data_loaders.py +0 -284
- diffusion/diffusion.py +0 -317
- diffusion/diffusion_onnx.py +0 -612
- diffusion/dpm_solver_pytorch.py +0 -1201
- diffusion/how to export onnx.md +0 -4
- diffusion/infer_gt_mel.py +0 -74
- diffusion/logger/__init__.py +0 -0
- diffusion/logger/saver.py +0 -150
- diffusion/logger/utils.py +0 -126
- diffusion/onnx_export.py +0 -226
- diffusion/solver.py +0 -195
- diffusion/unit2mel.py +0 -147
- diffusion/vocoder.py +0 -94
- diffusion/wavenet.py +0 -108
- inference/infer_tool.py +46 -133
- inference/infer_tool_grad.py +5 -9
- inference/slicer.py +2 -2
- inference_main.py +0 -181
- models.py +97 -33
- modules/DSConv.py +76 -0
- modules/F0Predictor/CrepeF0Predictor.py +5 -2
- modules/F0Predictor/DioF0Predictor.py +23 -34
- modules/F0Predictor/FCPEF0Predictor.py +109 -0
- modules/F0Predictor/HarvestF0Predictor.py +22 -34
- modules/F0Predictor/PMF0Predictor.py +23 -34
- modules/F0Predictor/RMVPEF0Predictor.py +107 -0
- modules/F0Predictor/crepe.py +11 -11
- modules/F0Predictor/fcpe/__init__.py +3 -0
- modules/F0Predictor/fcpe/model.py +262 -0
- modules/F0Predictor/fcpe/nvSTFT.py +133 -0
- modules/F0Predictor/fcpe/pcmer.py +369 -0
- modules/F0Predictor/rmvpe/__init__.py +10 -0
- modules/F0Predictor/rmvpe/constants.py +9 -0
- modules/F0Predictor/rmvpe/deepunet.py +190 -0
- modules/F0Predictor/rmvpe/inference.py +57 -0
- modules/F0Predictor/rmvpe/model.py +67 -0
- modules/F0Predictor/rmvpe/seq.py +20 -0
- modules/F0Predictor/rmvpe/spec.py +67 -0
- modules/F0Predictor/rmvpe/utils.py +107 -0
- modules/attentions.py +21 -7
- modules/commons.py +6 -11
- modules/enhancer.py +4 -2
- modules/losses.py +1 -4
- modules/mel_processing.py +9 -38
- modules/modules.py +86 -72
app.py
CHANGED
@@ -11,7 +11,9 @@ from scipy.io import wavfile
|
|
11 |
import tempfile
|
12 |
import edge_tts
|
13 |
import utils
|
14 |
-
import
|
|
|
|
|
15 |
|
16 |
from inference.infer_tool import Svc
|
17 |
|
@@ -67,9 +69,7 @@ def create_fn(model, spk):
|
|
67 |
input_text = re.sub(r"[\n\,\(\) ]", "", input_text)
|
68 |
voice = tts_voice[gender]
|
69 |
ratestr = "+{:.0%}".format(tts_rate) if tts_rate >= 0 else "{:.0%}".format(tts_rate)
|
70 |
-
communicate = edge_tts.Communicate(text=input_text,
|
71 |
-
voice=voice,
|
72 |
-
rate=ratestr)
|
73 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
74 |
temp_path = tmp_file.name
|
75 |
await communicate.save(temp_path)
|
@@ -100,10 +100,12 @@ if __name__ == '__main__':
|
|
100 |
models.append((name, cover, create_fn(model, name)))
|
101 |
with gr.Blocks() as app:
|
102 |
gr.Markdown(
|
103 |
-
"
|
104 |
-
|
105 |
-
|
106 |
-
|
|
|
|
|
107 |
)
|
108 |
with gr.Tabs():
|
109 |
for (name, cover, (svc_fn, tts_fn)) in models:
|
@@ -112,8 +114,8 @@ if __name__ == '__main__':
|
|
112 |
with gr.Column():
|
113 |
with gr.Row():
|
114 |
vc_transform = gr.Number(label="音高调整 (正负半音,12为1个八度)", value=0)
|
115 |
-
f0_predictor = gr.Radio(label="f0预测器 (
|
116 |
-
choices=['crepe', 'harvest', '
|
117 |
auto_f0 = gr.Checkbox(label="自动音高预测 (文本转语音或讲话可选,会导致唱歌跑调)",
|
118 |
value=False)
|
119 |
with gr.Tabs():
|
@@ -132,13 +134,9 @@ if __name__ == '__main__':
|
|
132 |
tts_submit = gr.Button("生成", variant="primary")
|
133 |
|
134 |
with gr.Column():
|
135 |
-
gr.
|
136 |
-
'<div align="center">'
|
137 |
-
f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else ""
|
138 |
-
'</div>'
|
139 |
-
)
|
140 |
vc_output = gr.Audio(label="输出音频")
|
141 |
svc_submit.click(svc_fn, [svc_input, vc_transform, auto_f0, f0_predictor], vc_output)
|
142 |
tts_submit.click(tts_fn, [tts_input, gender, tts_rate, vc_transform, auto_f0, f0_predictor],
|
143 |
vc_output)
|
144 |
-
app.queue(
|
|
|
11 |
import tempfile
|
12 |
import edge_tts
|
13 |
import utils
|
14 |
+
import matplotlib
|
15 |
+
|
16 |
+
matplotlib.use('TkAgg')
|
17 |
|
18 |
from inference.infer_tool import Svc
|
19 |
|
|
|
69 |
input_text = re.sub(r"[\n\,\(\) ]", "", input_text)
|
70 |
voice = tts_voice[gender]
|
71 |
ratestr = "+{:.0%}".format(tts_rate) if tts_rate >= 0 else "{:.0%}".format(tts_rate)
|
72 |
+
communicate = edge_tts.Communicate(text=input_text, voice=voice, rate=ratestr)
|
|
|
|
|
73 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
74 |
temp_path = tmp_file.name
|
75 |
await communicate.save(temp_path)
|
|
|
100 |
models.append((name, cover, create_fn(model, name)))
|
101 |
with gr.Blocks() as app:
|
102 |
gr.Markdown(
|
103 |
+
"""
|
104 |
+
# <center> 圣安地列斯角色语音生成
|
105 |
+
## <center> 模型作者:B站[Cyber蝈蝈总](https://space.bilibili.com/37706580)
|
106 |
+
#### <center> 罪恶都市人物AI语音请移步[GTAVC](https://huggingface.co/spaces/GroveStreet/GTAVC_SOVITS)
|
107 |
+
<center> 使用此资源创作的作品请标出处,CJ有两个模型,carl1更清晰,carl2音域广
|
108 |
+
"""
|
109 |
)
|
110 |
with gr.Tabs():
|
111 |
for (name, cover, (svc_fn, tts_fn)) in models:
|
|
|
114 |
with gr.Column():
|
115 |
with gr.Row():
|
116 |
vc_transform = gr.Number(label="音高调整 (正负半音,12为1个八度)", value=0)
|
117 |
+
f0_predictor = gr.Radio(label="f0预测器 (推荐rmvpe)",
|
118 |
+
choices=['crepe', 'harvest', 'rmvpe'], value='rmvpe')
|
119 |
auto_f0 = gr.Checkbox(label="自动音高预测 (文本转语音或讲话可选,会导致唱歌跑调)",
|
120 |
value=False)
|
121 |
with gr.Tabs():
|
|
|
134 |
tts_submit = gr.Button("生成", variant="primary")
|
135 |
|
136 |
with gr.Column():
|
137 |
+
gr.Image(value=os.path.join(os.path.dirname(__file__), cover), height=300, width=300)
|
|
|
|
|
|
|
|
|
138 |
vc_output = gr.Audio(label="输出音频")
|
139 |
svc_submit.click(svc_fn, [svc_input, vc_transform, auto_f0, f0_predictor], vc_output)
|
140 |
tts_submit.click(tts_fn, [tts_input, gender, tts_rate, vc_transform, auto_f0, f0_predictor],
|
141 |
vc_output)
|
142 |
+
app.queue(default_concurrency_limit=1, api_open=args.api).launch(share=args.share)
|
cluster/__init__.py
DELETED
@@ -1,29 +0,0 @@
|
|
1 |
-
import numpy as np
|
2 |
-
import torch
|
3 |
-
from sklearn.cluster import KMeans
|
4 |
-
|
5 |
-
def get_cluster_model(ckpt_path):
|
6 |
-
checkpoint = torch.load(ckpt_path)
|
7 |
-
kmeans_dict = {}
|
8 |
-
for spk, ckpt in checkpoint.items():
|
9 |
-
km = KMeans(ckpt["n_features_in_"])
|
10 |
-
km.__dict__["n_features_in_"] = ckpt["n_features_in_"]
|
11 |
-
km.__dict__["_n_threads"] = ckpt["_n_threads"]
|
12 |
-
km.__dict__["cluster_centers_"] = ckpt["cluster_centers_"]
|
13 |
-
kmeans_dict[spk] = km
|
14 |
-
return kmeans_dict
|
15 |
-
|
16 |
-
def get_cluster_result(model, x, speaker):
|
17 |
-
"""
|
18 |
-
x: np.array [t, 256]
|
19 |
-
return cluster class result
|
20 |
-
"""
|
21 |
-
return model[speaker].predict(x)
|
22 |
-
|
23 |
-
def get_cluster_center_result(model, x,speaker):
|
24 |
-
"""x: np.array [t, 256]"""
|
25 |
-
predict = model[speaker].predict(x)
|
26 |
-
return model[speaker].cluster_centers_[predict]
|
27 |
-
|
28 |
-
def get_center(model, x,speaker):
|
29 |
-
return model[speaker].cluster_centers_[x]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cluster/kmeans.py
DELETED
@@ -1,201 +0,0 @@
|
|
1 |
-
import math,pdb
|
2 |
-
import torch,pynvml
|
3 |
-
from torch.nn.functional import normalize
|
4 |
-
from time import time
|
5 |
-
import numpy as np
|
6 |
-
# device=torch.device("cuda:0")
|
7 |
-
def _kpp(data: torch.Tensor, k: int, sample_size: int = -1):
|
8 |
-
""" Picks k points in the data based on the kmeans++ method.
|
9 |
-
|
10 |
-
Parameters
|
11 |
-
----------
|
12 |
-
data : torch.Tensor
|
13 |
-
Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
|
14 |
-
data, rank 2 multidimensional data, in which case one
|
15 |
-
row is one observation.
|
16 |
-
k : int
|
17 |
-
Number of samples to generate.
|
18 |
-
sample_size : int
|
19 |
-
sample data to avoid memory overflow during calculation
|
20 |
-
|
21 |
-
Returns
|
22 |
-
-------
|
23 |
-
init : ndarray
|
24 |
-
A 'k' by 'N' containing the initial centroids.
|
25 |
-
|
26 |
-
References
|
27 |
-
----------
|
28 |
-
.. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
|
29 |
-
careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
|
30 |
-
on Discrete Algorithms, 2007.
|
31 |
-
.. [2] scipy/cluster/vq.py: _kpp
|
32 |
-
"""
|
33 |
-
batch_size=data.shape[0]
|
34 |
-
if batch_size>sample_size:
|
35 |
-
data = data[torch.randint(0, batch_size,[sample_size], device=data.device)]
|
36 |
-
dims = data.shape[1] if len(data.shape) > 1 else 1
|
37 |
-
init = torch.zeros((k, dims)).to(data.device)
|
38 |
-
r = torch.distributions.uniform.Uniform(0, 1)
|
39 |
-
for i in range(k):
|
40 |
-
if i == 0:
|
41 |
-
init[i, :] = data[torch.randint(data.shape[0], [1])]
|
42 |
-
else:
|
43 |
-
D2 = torch.cdist(init[:i, :][None, :], data[None, :], p=2)[0].amin(dim=0)
|
44 |
-
probs = D2 / torch.sum(D2)
|
45 |
-
cumprobs = torch.cumsum(probs, dim=0)
|
46 |
-
init[i, :] = data[torch.searchsorted(cumprobs, r.sample([1]).to(data.device))]
|
47 |
-
return init
|
48 |
-
class KMeansGPU:
|
49 |
-
'''
|
50 |
-
Kmeans clustering algorithm implemented with PyTorch
|
51 |
-
|
52 |
-
Parameters:
|
53 |
-
n_clusters: int,
|
54 |
-
Number of clusters
|
55 |
-
|
56 |
-
max_iter: int, default: 100
|
57 |
-
Maximum number of iterations
|
58 |
-
|
59 |
-
tol: float, default: 0.0001
|
60 |
-
Tolerance
|
61 |
-
|
62 |
-
verbose: int, default: 0
|
63 |
-
Verbosity
|
64 |
-
|
65 |
-
mode: {'euclidean', 'cosine'}, default: 'euclidean'
|
66 |
-
Type of distance measure
|
67 |
-
|
68 |
-
init_method: {'random', 'point', '++'}
|
69 |
-
Type of initialization
|
70 |
-
|
71 |
-
minibatch: {None, int}, default: None
|
72 |
-
Batch size of MinibatchKmeans algorithm
|
73 |
-
if None perform full KMeans algorithm
|
74 |
-
|
75 |
-
Attributes:
|
76 |
-
centroids: torch.Tensor, shape: [n_clusters, n_features]
|
77 |
-
cluster centroids
|
78 |
-
'''
|
79 |
-
def __init__(self, n_clusters, max_iter=200, tol=1e-4, verbose=0, mode="euclidean",device=torch.device("cuda:0")):
|
80 |
-
self.n_clusters = n_clusters
|
81 |
-
self.max_iter = max_iter
|
82 |
-
self.tol = tol
|
83 |
-
self.verbose = verbose
|
84 |
-
self.mode = mode
|
85 |
-
self.device=device
|
86 |
-
pynvml.nvmlInit()
|
87 |
-
gpu_handle = pynvml.nvmlDeviceGetHandleByIndex(device.index)
|
88 |
-
info = pynvml.nvmlDeviceGetMemoryInfo(gpu_handle)
|
89 |
-
self.minibatch=int(33e6/self.n_clusters*info.free/ 1024 / 1024 / 1024)
|
90 |
-
print("free_mem/GB:",info.free/ 1024 / 1024 / 1024,"minibatch:",self.minibatch)
|
91 |
-
|
92 |
-
@staticmethod
|
93 |
-
def cos_sim(a, b):
|
94 |
-
"""
|
95 |
-
Compute cosine similarity of 2 sets of vectors
|
96 |
-
|
97 |
-
Parameters:
|
98 |
-
a: torch.Tensor, shape: [m, n_features]
|
99 |
-
|
100 |
-
b: torch.Tensor, shape: [n, n_features]
|
101 |
-
"""
|
102 |
-
return normalize(a, dim=-1) @ normalize(b, dim=-1).transpose(-2, -1)
|
103 |
-
|
104 |
-
@staticmethod
|
105 |
-
def euc_sim(a, b):
|
106 |
-
"""
|
107 |
-
Compute euclidean similarity of 2 sets of vectors
|
108 |
-
Parameters:
|
109 |
-
a: torch.Tensor, shape: [m, n_features]
|
110 |
-
b: torch.Tensor, shape: [n, n_features]
|
111 |
-
"""
|
112 |
-
return 2 * a @ b.transpose(-2, -1) -(a**2).sum(dim=1)[..., :, None] - (b**2).sum(dim=1)[..., None, :]
|
113 |
-
|
114 |
-
def max_sim(self, a, b):
|
115 |
-
"""
|
116 |
-
Compute maximum similarity (or minimum distance) of each vector
|
117 |
-
in a with all of the vectors in b
|
118 |
-
Parameters:
|
119 |
-
a: torch.Tensor, shape: [m, n_features]
|
120 |
-
b: torch.Tensor, shape: [n, n_features]
|
121 |
-
"""
|
122 |
-
if self.mode == 'cosine':
|
123 |
-
sim_func = self.cos_sim
|
124 |
-
elif self.mode == 'euclidean':
|
125 |
-
sim_func = self.euc_sim
|
126 |
-
sim = sim_func(a, b)
|
127 |
-
max_sim_v, max_sim_i = sim.max(dim=-1)
|
128 |
-
return max_sim_v, max_sim_i
|
129 |
-
|
130 |
-
def fit_predict(self, X):
|
131 |
-
"""
|
132 |
-
Combination of fit() and predict() methods.
|
133 |
-
This is faster than calling fit() and predict() seperately.
|
134 |
-
Parameters:
|
135 |
-
X: torch.Tensor, shape: [n_samples, n_features]
|
136 |
-
centroids: {torch.Tensor, None}, default: None
|
137 |
-
if given, centroids will be initialized with given tensor
|
138 |
-
if None, centroids will be randomly chosen from X
|
139 |
-
Return:
|
140 |
-
labels: torch.Tensor, shape: [n_samples]
|
141 |
-
|
142 |
-
mini_=33kk/k*remain
|
143 |
-
mini=min(mini_,fea_shape)
|
144 |
-
offset=log2(k/1000)*1.5
|
145 |
-
kpp_all=min(mini_*10/offset,fea_shape)
|
146 |
-
kpp_sample=min(mini_/12/offset,fea_shape)
|
147 |
-
"""
|
148 |
-
assert isinstance(X, torch.Tensor), "input must be torch.Tensor"
|
149 |
-
assert X.dtype in [torch.half, torch.float, torch.double], "input must be floating point"
|
150 |
-
assert X.ndim == 2, "input must be a 2d tensor with shape: [n_samples, n_features] "
|
151 |
-
# print("verbose:%s"%self.verbose)
|
152 |
-
|
153 |
-
offset = np.power(1.5,np.log(self.n_clusters / 1000))/np.log(2)
|
154 |
-
with torch.no_grad():
|
155 |
-
batch_size= X.shape[0]
|
156 |
-
# print(self.minibatch, int(self.minibatch * 10 / offset), batch_size)
|
157 |
-
start_time = time()
|
158 |
-
if (self.minibatch*10//offset< batch_size):
|
159 |
-
x = X[torch.randint(0, batch_size,[int(self.minibatch*10/offset)])].to(self.device)
|
160 |
-
else:
|
161 |
-
x = X.to(self.device)
|
162 |
-
# print(x.device)
|
163 |
-
self.centroids = _kpp(x, self.n_clusters, min(int(self.minibatch/12/offset),batch_size))
|
164 |
-
del x
|
165 |
-
torch.cuda.empty_cache()
|
166 |
-
# self.centroids = self.centroids.to(self.device)
|
167 |
-
num_points_in_clusters = torch.ones(self.n_clusters, device=self.device, dtype=X.dtype)#全1
|
168 |
-
closest = None#[3098036]#int64
|
169 |
-
if(self.minibatch>=batch_size//2 and self.minibatch<batch_size):
|
170 |
-
X = X[torch.randint(0, batch_size,[self.minibatch])].to(self.device)
|
171 |
-
elif(self.minibatch>=batch_size):
|
172 |
-
X=X.to(self.device)
|
173 |
-
for i in range(self.max_iter):
|
174 |
-
iter_time = time()
|
175 |
-
if self.minibatch<batch_size//2:#可用minibatch数太小,每次都得从内存倒腾到显存
|
176 |
-
x = X[torch.randint(0, batch_size, [self.minibatch])].to(self.device)
|
177 |
-
else:#否则直接全部缓存
|
178 |
-
x = X
|
179 |
-
|
180 |
-
closest = self.max_sim(a=x, b=self.centroids)[1].to(torch.int16)#[3098036]#int64#0~999
|
181 |
-
matched_clusters, counts = closest.unique(return_counts=True)#int64#1k
|
182 |
-
expanded_closest = closest[None].expand(self.n_clusters, -1)#[1000, 3098036]#int16#0~999
|
183 |
-
mask = (expanded_closest==torch.arange(self.n_clusters, device=self.device)[:, None]).to(X.dtype)#==后者是int64*1000
|
184 |
-
c_grad = mask @ x / mask.sum(-1)[..., :, None]
|
185 |
-
c_grad[c_grad!=c_grad] = 0 # remove NaNs
|
186 |
-
error = (c_grad - self.centroids).pow(2).sum()
|
187 |
-
if self.minibatch is not None:
|
188 |
-
lr = 1/num_points_in_clusters[:,None] * 0.9 + 0.1
|
189 |
-
else:
|
190 |
-
lr = 1
|
191 |
-
matched_clusters=matched_clusters.long()
|
192 |
-
num_points_in_clusters[matched_clusters] += counts#IndexError: tensors used as indices must be long, byte or bool tensors
|
193 |
-
self.centroids = self.centroids * (1-lr) + c_grad * lr
|
194 |
-
if self.verbose >= 2:
|
195 |
-
print('iter:', i, 'error:', error.item(), 'time spent:', round(time()-iter_time, 4))
|
196 |
-
if error <= self.tol:
|
197 |
-
break
|
198 |
-
|
199 |
-
if self.verbose >= 1:
|
200 |
-
print(f'used {i+1} iterations ({round(time()-start_time, 4)}s) to cluster {batch_size} items into {self.n_clusters} clusters')
|
201 |
-
return closest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cluster/train_cluster.py
DELETED
@@ -1,84 +0,0 @@
|
|
1 |
-
import time,pdb
|
2 |
-
import tqdm
|
3 |
-
from time import time as ttime
|
4 |
-
import os
|
5 |
-
from pathlib import Path
|
6 |
-
import logging
|
7 |
-
import argparse
|
8 |
-
from kmeans import KMeansGPU
|
9 |
-
import torch
|
10 |
-
import numpy as np
|
11 |
-
from sklearn.cluster import KMeans,MiniBatchKMeans
|
12 |
-
|
13 |
-
logging.basicConfig(level=logging.INFO)
|
14 |
-
logger = logging.getLogger(__name__)
|
15 |
-
from time import time as ttime
|
16 |
-
import pynvml,torch
|
17 |
-
|
18 |
-
def train_cluster(in_dir, n_clusters, use_minibatch=True, verbose=False,use_gpu=False):#gpu_minibatch真拉,虽然库支持但是也不考虑
|
19 |
-
logger.info(f"Loading features from {in_dir}")
|
20 |
-
features = []
|
21 |
-
nums = 0
|
22 |
-
for path in tqdm.tqdm(in_dir.glob("*.soft.pt")):
|
23 |
-
# for name in os.listdir(in_dir):
|
24 |
-
# path="%s/%s"%(in_dir,name)
|
25 |
-
features.append(torch.load(path,map_location="cpu").squeeze(0).numpy().T)
|
26 |
-
# print(features[-1].shape)
|
27 |
-
features = np.concatenate(features, axis=0)
|
28 |
-
print(nums, features.nbytes/ 1024**2, "MB , shape:",features.shape, features.dtype)
|
29 |
-
features = features.astype(np.float32)
|
30 |
-
logger.info(f"Clustering features of shape: {features.shape}")
|
31 |
-
t = time.time()
|
32 |
-
if(use_gpu==False):
|
33 |
-
if use_minibatch:
|
34 |
-
kmeans = MiniBatchKMeans(n_clusters=n_clusters,verbose=verbose, batch_size=4096, max_iter=80).fit(features)
|
35 |
-
else:
|
36 |
-
kmeans = KMeans(n_clusters=n_clusters,verbose=verbose).fit(features)
|
37 |
-
else:
|
38 |
-
kmeans = KMeansGPU(n_clusters=n_clusters, mode='euclidean', verbose=2 if verbose else 0,max_iter=500,tol=1e-2)#
|
39 |
-
features=torch.from_numpy(features)#.to(device)
|
40 |
-
labels = kmeans.fit_predict(features)#
|
41 |
-
|
42 |
-
print(time.time()-t, "s")
|
43 |
-
|
44 |
-
x = {
|
45 |
-
"n_features_in_": kmeans.n_features_in_ if use_gpu==False else features.shape[1],
|
46 |
-
"_n_threads": kmeans._n_threads if use_gpu==False else 4,
|
47 |
-
"cluster_centers_": kmeans.cluster_centers_ if use_gpu==False else kmeans.centroids.cpu().numpy(),
|
48 |
-
}
|
49 |
-
print("end")
|
50 |
-
|
51 |
-
return x
|
52 |
-
|
53 |
-
if __name__ == "__main__":
|
54 |
-
parser = argparse.ArgumentParser()
|
55 |
-
parser.add_argument('--dataset', type=Path, default="./dataset/44k",
|
56 |
-
help='path of training data directory')
|
57 |
-
parser.add_argument('--output', type=Path, default="logs/44k",
|
58 |
-
help='path of model output directory')
|
59 |
-
parser.add_argument('--gpu',action='store_true', default=False ,
|
60 |
-
help='to use GPU')
|
61 |
-
|
62 |
-
|
63 |
-
args = parser.parse_args()
|
64 |
-
|
65 |
-
checkpoint_dir = args.output
|
66 |
-
dataset = args.dataset
|
67 |
-
use_gpu = args.gpu
|
68 |
-
n_clusters = 10000
|
69 |
-
|
70 |
-
ckpt = {}
|
71 |
-
for spk in os.listdir(dataset):
|
72 |
-
if os.path.isdir(dataset/spk):
|
73 |
-
print(f"train kmeans for {spk}...")
|
74 |
-
in_dir = dataset/spk
|
75 |
-
x = train_cluster(in_dir, n_clusters,use_minibatch=False,verbose=False,use_gpu=use_gpu)
|
76 |
-
ckpt[spk] = x
|
77 |
-
|
78 |
-
checkpoint_path = checkpoint_dir / f"kmeans_{n_clusters}.pt"
|
79 |
-
checkpoint_path.parent.mkdir(exist_ok=True, parents=True)
|
80 |
-
torch.save(
|
81 |
-
ckpt,
|
82 |
-
checkpoint_path,
|
83 |
-
)
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
configs/config.json
DELETED
File without changes
|
diffusion/data_loaders.py
DELETED
@@ -1,284 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import random
|
3 |
-
import re
|
4 |
-
import numpy as np
|
5 |
-
import librosa
|
6 |
-
import torch
|
7 |
-
import random
|
8 |
-
from utils import repeat_expand_2d
|
9 |
-
from tqdm import tqdm
|
10 |
-
from torch.utils.data import Dataset
|
11 |
-
|
12 |
-
def traverse_dir(
|
13 |
-
root_dir,
|
14 |
-
extensions,
|
15 |
-
amount=None,
|
16 |
-
str_include=None,
|
17 |
-
str_exclude=None,
|
18 |
-
is_pure=False,
|
19 |
-
is_sort=False,
|
20 |
-
is_ext=True):
|
21 |
-
|
22 |
-
file_list = []
|
23 |
-
cnt = 0
|
24 |
-
for root, _, files in os.walk(root_dir):
|
25 |
-
for file in files:
|
26 |
-
if any([file.endswith(f".{ext}") for ext in extensions]):
|
27 |
-
# path
|
28 |
-
mix_path = os.path.join(root, file)
|
29 |
-
pure_path = mix_path[len(root_dir)+1:] if is_pure else mix_path
|
30 |
-
|
31 |
-
# amount
|
32 |
-
if (amount is not None) and (cnt == amount):
|
33 |
-
if is_sort:
|
34 |
-
file_list.sort()
|
35 |
-
return file_list
|
36 |
-
|
37 |
-
# check string
|
38 |
-
if (str_include is not None) and (str_include not in pure_path):
|
39 |
-
continue
|
40 |
-
if (str_exclude is not None) and (str_exclude in pure_path):
|
41 |
-
continue
|
42 |
-
|
43 |
-
if not is_ext:
|
44 |
-
ext = pure_path.split('.')[-1]
|
45 |
-
pure_path = pure_path[:-(len(ext)+1)]
|
46 |
-
file_list.append(pure_path)
|
47 |
-
cnt += 1
|
48 |
-
if is_sort:
|
49 |
-
file_list.sort()
|
50 |
-
return file_list
|
51 |
-
|
52 |
-
|
53 |
-
def get_data_loaders(args, whole_audio=False):
|
54 |
-
data_train = AudioDataset(
|
55 |
-
filelists = args.data.training_files,
|
56 |
-
waveform_sec=args.data.duration,
|
57 |
-
hop_size=args.data.block_size,
|
58 |
-
sample_rate=args.data.sampling_rate,
|
59 |
-
load_all_data=args.train.cache_all_data,
|
60 |
-
whole_audio=whole_audio,
|
61 |
-
extensions=args.data.extensions,
|
62 |
-
n_spk=args.model.n_spk,
|
63 |
-
spk=args.spk,
|
64 |
-
device=args.train.cache_device,
|
65 |
-
fp16=args.train.cache_fp16,
|
66 |
-
use_aug=True)
|
67 |
-
loader_train = torch.utils.data.DataLoader(
|
68 |
-
data_train ,
|
69 |
-
batch_size=args.train.batch_size if not whole_audio else 1,
|
70 |
-
shuffle=True,
|
71 |
-
num_workers=args.train.num_workers if args.train.cache_device=='cpu' else 0,
|
72 |
-
persistent_workers=(args.train.num_workers > 0) if args.train.cache_device=='cpu' else False,
|
73 |
-
pin_memory=True if args.train.cache_device=='cpu' else False
|
74 |
-
)
|
75 |
-
data_valid = AudioDataset(
|
76 |
-
filelists = args.data.validation_files,
|
77 |
-
waveform_sec=args.data.duration,
|
78 |
-
hop_size=args.data.block_size,
|
79 |
-
sample_rate=args.data.sampling_rate,
|
80 |
-
load_all_data=args.train.cache_all_data,
|
81 |
-
whole_audio=True,
|
82 |
-
spk=args.spk,
|
83 |
-
extensions=args.data.extensions,
|
84 |
-
n_spk=args.model.n_spk)
|
85 |
-
loader_valid = torch.utils.data.DataLoader(
|
86 |
-
data_valid,
|
87 |
-
batch_size=1,
|
88 |
-
shuffle=False,
|
89 |
-
num_workers=0,
|
90 |
-
pin_memory=True
|
91 |
-
)
|
92 |
-
return loader_train, loader_valid
|
93 |
-
|
94 |
-
|
95 |
-
class AudioDataset(Dataset):
|
96 |
-
def __init__(
|
97 |
-
self,
|
98 |
-
filelists,
|
99 |
-
waveform_sec,
|
100 |
-
hop_size,
|
101 |
-
sample_rate,
|
102 |
-
spk,
|
103 |
-
load_all_data=True,
|
104 |
-
whole_audio=False,
|
105 |
-
extensions=['wav'],
|
106 |
-
n_spk=1,
|
107 |
-
device='cpu',
|
108 |
-
fp16=False,
|
109 |
-
use_aug=False,
|
110 |
-
):
|
111 |
-
super().__init__()
|
112 |
-
|
113 |
-
self.waveform_sec = waveform_sec
|
114 |
-
self.sample_rate = sample_rate
|
115 |
-
self.hop_size = hop_size
|
116 |
-
self.filelists = filelists
|
117 |
-
self.whole_audio = whole_audio
|
118 |
-
self.use_aug = use_aug
|
119 |
-
self.data_buffer={}
|
120 |
-
self.pitch_aug_dict = {}
|
121 |
-
# np.load(os.path.join(self.path_root, 'pitch_aug_dict.npy'), allow_pickle=True).item()
|
122 |
-
if load_all_data:
|
123 |
-
print('Load all the data filelists:', filelists)
|
124 |
-
else:
|
125 |
-
print('Load the f0, volume data filelists:', filelists)
|
126 |
-
with open(filelists,"r") as f:
|
127 |
-
self.paths = f.read().splitlines()
|
128 |
-
for name_ext in tqdm(self.paths, total=len(self.paths)):
|
129 |
-
name = os.path.splitext(name_ext)[0]
|
130 |
-
path_audio = name_ext
|
131 |
-
duration = librosa.get_duration(filename = path_audio, sr = self.sample_rate)
|
132 |
-
|
133 |
-
path_f0 = name_ext + ".f0.npy"
|
134 |
-
f0,_ = np.load(path_f0,allow_pickle=True)
|
135 |
-
f0 = torch.from_numpy(np.array(f0,dtype=float)).float().unsqueeze(-1).to(device)
|
136 |
-
|
137 |
-
path_volume = name_ext + ".vol.npy"
|
138 |
-
volume = np.load(path_volume)
|
139 |
-
volume = torch.from_numpy(volume).float().unsqueeze(-1).to(device)
|
140 |
-
|
141 |
-
path_augvol = name_ext + ".aug_vol.npy"
|
142 |
-
aug_vol = np.load(path_augvol)
|
143 |
-
aug_vol = torch.from_numpy(aug_vol).float().unsqueeze(-1).to(device)
|
144 |
-
|
145 |
-
if n_spk is not None and n_spk > 1:
|
146 |
-
spk_name = name_ext.split("/")[-2]
|
147 |
-
spk_id = spk[spk_name] if spk_name in spk else 0
|
148 |
-
if spk_id < 0 or spk_id >= n_spk:
|
149 |
-
raise ValueError(' [x] Muiti-speaker traing error : spk_id must be a positive integer from 0 to n_spk-1 ')
|
150 |
-
else:
|
151 |
-
spk_id = 0
|
152 |
-
spk_id = torch.LongTensor(np.array([spk_id])).to(device)
|
153 |
-
|
154 |
-
if load_all_data:
|
155 |
-
'''
|
156 |
-
audio, sr = librosa.load(path_audio, sr=self.sample_rate)
|
157 |
-
if len(audio.shape) > 1:
|
158 |
-
audio = librosa.to_mono(audio)
|
159 |
-
audio = torch.from_numpy(audio).to(device)
|
160 |
-
'''
|
161 |
-
path_mel = name_ext + ".mel.npy"
|
162 |
-
mel = np.load(path_mel)
|
163 |
-
mel = torch.from_numpy(mel).to(device)
|
164 |
-
|
165 |
-
path_augmel = name_ext + ".aug_mel.npy"
|
166 |
-
aug_mel,keyshift = np.load(path_augmel, allow_pickle=True)
|
167 |
-
aug_mel = np.array(aug_mel,dtype=float)
|
168 |
-
aug_mel = torch.from_numpy(aug_mel).to(device)
|
169 |
-
self.pitch_aug_dict[name_ext] = keyshift
|
170 |
-
|
171 |
-
path_units = name_ext + ".soft.pt"
|
172 |
-
units = torch.load(path_units).to(device)
|
173 |
-
units = units[0]
|
174 |
-
units = repeat_expand_2d(units,f0.size(0)).transpose(0,1)
|
175 |
-
|
176 |
-
if fp16:
|
177 |
-
mel = mel.half()
|
178 |
-
aug_mel = aug_mel.half()
|
179 |
-
units = units.half()
|
180 |
-
|
181 |
-
self.data_buffer[name_ext] = {
|
182 |
-
'duration': duration,
|
183 |
-
'mel': mel,
|
184 |
-
'aug_mel': aug_mel,
|
185 |
-
'units': units,
|
186 |
-
'f0': f0,
|
187 |
-
'volume': volume,
|
188 |
-
'aug_vol': aug_vol,
|
189 |
-
'spk_id': spk_id
|
190 |
-
}
|
191 |
-
else:
|
192 |
-
path_augmel = name_ext + ".aug_mel.npy"
|
193 |
-
aug_mel,keyshift = np.load(path_augmel, allow_pickle=True)
|
194 |
-
self.pitch_aug_dict[name_ext] = keyshift
|
195 |
-
self.data_buffer[name_ext] = {
|
196 |
-
'duration': duration,
|
197 |
-
'f0': f0,
|
198 |
-
'volume': volume,
|
199 |
-
'aug_vol': aug_vol,
|
200 |
-
'spk_id': spk_id
|
201 |
-
}
|
202 |
-
|
203 |
-
|
204 |
-
def __getitem__(self, file_idx):
|
205 |
-
name_ext = self.paths[file_idx]
|
206 |
-
data_buffer = self.data_buffer[name_ext]
|
207 |
-
# check duration. if too short, then skip
|
208 |
-
if data_buffer['duration'] < (self.waveform_sec + 0.1):
|
209 |
-
return self.__getitem__( (file_idx + 1) % len(self.paths))
|
210 |
-
|
211 |
-
# get item
|
212 |
-
return self.get_data(name_ext, data_buffer)
|
213 |
-
|
214 |
-
def get_data(self, name_ext, data_buffer):
|
215 |
-
name = os.path.splitext(name_ext)[0]
|
216 |
-
frame_resolution = self.hop_size / self.sample_rate
|
217 |
-
duration = data_buffer['duration']
|
218 |
-
waveform_sec = duration if self.whole_audio else self.waveform_sec
|
219 |
-
|
220 |
-
# load audio
|
221 |
-
idx_from = 0 if self.whole_audio else random.uniform(0, duration - waveform_sec - 0.1)
|
222 |
-
start_frame = int(idx_from / frame_resolution)
|
223 |
-
units_frame_len = int(waveform_sec / frame_resolution)
|
224 |
-
aug_flag = random.choice([True, False]) and self.use_aug
|
225 |
-
'''
|
226 |
-
audio = data_buffer.get('audio')
|
227 |
-
if audio is None:
|
228 |
-
path_audio = os.path.join(self.path_root, 'audio', name) + '.wav'
|
229 |
-
audio, sr = librosa.load(
|
230 |
-
path_audio,
|
231 |
-
sr = self.sample_rate,
|
232 |
-
offset = start_frame * frame_resolution,
|
233 |
-
duration = waveform_sec)
|
234 |
-
if len(audio.shape) > 1:
|
235 |
-
audio = librosa.to_mono(audio)
|
236 |
-
# clip audio into N seconds
|
237 |
-
audio = audio[ : audio.shape[-1] // self.hop_size * self.hop_size]
|
238 |
-
audio = torch.from_numpy(audio).float()
|
239 |
-
else:
|
240 |
-
audio = audio[start_frame * self.hop_size : (start_frame + units_frame_len) * self.hop_size]
|
241 |
-
'''
|
242 |
-
# load mel
|
243 |
-
mel_key = 'aug_mel' if aug_flag else 'mel'
|
244 |
-
mel = data_buffer.get(mel_key)
|
245 |
-
if mel is None:
|
246 |
-
mel = name_ext + ".mel.npy"
|
247 |
-
mel = np.load(mel)
|
248 |
-
mel = mel[start_frame : start_frame + units_frame_len]
|
249 |
-
mel = torch.from_numpy(mel).float()
|
250 |
-
else:
|
251 |
-
mel = mel[start_frame : start_frame + units_frame_len]
|
252 |
-
|
253 |
-
# load f0
|
254 |
-
f0 = data_buffer.get('f0')
|
255 |
-
aug_shift = 0
|
256 |
-
if aug_flag:
|
257 |
-
aug_shift = self.pitch_aug_dict[name_ext]
|
258 |
-
f0_frames = 2 ** (aug_shift / 12) * f0[start_frame : start_frame + units_frame_len]
|
259 |
-
|
260 |
-
# load units
|
261 |
-
units = data_buffer.get('units')
|
262 |
-
if units is None:
|
263 |
-
path_units = name_ext + ".soft.pt"
|
264 |
-
units = torch.load(path_units)
|
265 |
-
units = units[0]
|
266 |
-
units = repeat_expand_2d(units,f0.size(0)).transpose(0,1)
|
267 |
-
|
268 |
-
units = units[start_frame : start_frame + units_frame_len]
|
269 |
-
|
270 |
-
# load volume
|
271 |
-
vol_key = 'aug_vol' if aug_flag else 'volume'
|
272 |
-
volume = data_buffer.get(vol_key)
|
273 |
-
volume_frames = volume[start_frame : start_frame + units_frame_len]
|
274 |
-
|
275 |
-
# load spk_id
|
276 |
-
spk_id = data_buffer.get('spk_id')
|
277 |
-
|
278 |
-
# load shift
|
279 |
-
aug_shift = torch.from_numpy(np.array([[aug_shift]])).float()
|
280 |
-
|
281 |
-
return dict(mel=mel, f0=f0_frames, volume=volume_frames, units=units, spk_id=spk_id, aug_shift=aug_shift, name=name, name_ext=name_ext)
|
282 |
-
|
283 |
-
def __len__(self):
|
284 |
-
return len(self.paths)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/diffusion.py
DELETED
@@ -1,317 +0,0 @@
|
|
1 |
-
from collections import deque
|
2 |
-
from functools import partial
|
3 |
-
from inspect import isfunction
|
4 |
-
import torch.nn.functional as F
|
5 |
-
import librosa.sequence
|
6 |
-
import numpy as np
|
7 |
-
import torch
|
8 |
-
from torch import nn
|
9 |
-
from tqdm import tqdm
|
10 |
-
|
11 |
-
|
12 |
-
def exists(x):
|
13 |
-
return x is not None
|
14 |
-
|
15 |
-
|
16 |
-
def default(val, d):
|
17 |
-
if exists(val):
|
18 |
-
return val
|
19 |
-
return d() if isfunction(d) else d
|
20 |
-
|
21 |
-
|
22 |
-
def extract(a, t, x_shape):
|
23 |
-
b, *_ = t.shape
|
24 |
-
out = a.gather(-1, t)
|
25 |
-
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
26 |
-
|
27 |
-
|
28 |
-
def noise_like(shape, device, repeat=False):
|
29 |
-
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
30 |
-
noise = lambda: torch.randn(shape, device=device)
|
31 |
-
return repeat_noise() if repeat else noise()
|
32 |
-
|
33 |
-
|
34 |
-
def linear_beta_schedule(timesteps, max_beta=0.02):
|
35 |
-
"""
|
36 |
-
linear schedule
|
37 |
-
"""
|
38 |
-
betas = np.linspace(1e-4, max_beta, timesteps)
|
39 |
-
return betas
|
40 |
-
|
41 |
-
|
42 |
-
def cosine_beta_schedule(timesteps, s=0.008):
|
43 |
-
"""
|
44 |
-
cosine schedule
|
45 |
-
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
|
46 |
-
"""
|
47 |
-
steps = timesteps + 1
|
48 |
-
x = np.linspace(0, steps, steps)
|
49 |
-
alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
|
50 |
-
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
51 |
-
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
|
52 |
-
return np.clip(betas, a_min=0, a_max=0.999)
|
53 |
-
|
54 |
-
|
55 |
-
beta_schedule = {
|
56 |
-
"cosine": cosine_beta_schedule,
|
57 |
-
"linear": linear_beta_schedule,
|
58 |
-
}
|
59 |
-
|
60 |
-
|
61 |
-
class GaussianDiffusion(nn.Module):
|
62 |
-
def __init__(self,
|
63 |
-
denoise_fn,
|
64 |
-
out_dims=128,
|
65 |
-
timesteps=1000,
|
66 |
-
k_step=1000,
|
67 |
-
max_beta=0.02,
|
68 |
-
spec_min=-12,
|
69 |
-
spec_max=2):
|
70 |
-
super().__init__()
|
71 |
-
self.denoise_fn = denoise_fn
|
72 |
-
self.out_dims = out_dims
|
73 |
-
betas = beta_schedule['linear'](timesteps, max_beta=max_beta)
|
74 |
-
|
75 |
-
alphas = 1. - betas
|
76 |
-
alphas_cumprod = np.cumprod(alphas, axis=0)
|
77 |
-
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
78 |
-
|
79 |
-
timesteps, = betas.shape
|
80 |
-
self.num_timesteps = int(timesteps)
|
81 |
-
self.k_step = k_step
|
82 |
-
|
83 |
-
self.noise_list = deque(maxlen=4)
|
84 |
-
|
85 |
-
to_torch = partial(torch.tensor, dtype=torch.float32)
|
86 |
-
|
87 |
-
self.register_buffer('betas', to_torch(betas))
|
88 |
-
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
89 |
-
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
90 |
-
|
91 |
-
# calculations for diffusion q(x_t | x_{t-1}) and others
|
92 |
-
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
93 |
-
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
94 |
-
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
95 |
-
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
96 |
-
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
97 |
-
|
98 |
-
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
99 |
-
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
|
100 |
-
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
101 |
-
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
102 |
-
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
103 |
-
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
104 |
-
self.register_buffer('posterior_mean_coef1', to_torch(
|
105 |
-
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
106 |
-
self.register_buffer('posterior_mean_coef2', to_torch(
|
107 |
-
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
108 |
-
|
109 |
-
self.register_buffer('spec_min', torch.FloatTensor([spec_min])[None, None, :out_dims])
|
110 |
-
self.register_buffer('spec_max', torch.FloatTensor([spec_max])[None, None, :out_dims])
|
111 |
-
|
112 |
-
def q_mean_variance(self, x_start, t):
|
113 |
-
mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
114 |
-
variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
|
115 |
-
log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
116 |
-
return mean, variance, log_variance
|
117 |
-
|
118 |
-
def predict_start_from_noise(self, x_t, t, noise):
|
119 |
-
return (
|
120 |
-
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
121 |
-
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
122 |
-
)
|
123 |
-
|
124 |
-
def q_posterior(self, x_start, x_t, t):
|
125 |
-
posterior_mean = (
|
126 |
-
extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
127 |
-
extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
128 |
-
)
|
129 |
-
posterior_variance = extract(self.posterior_variance, t, x_t.shape)
|
130 |
-
posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
|
131 |
-
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
132 |
-
|
133 |
-
def p_mean_variance(self, x, t, cond):
|
134 |
-
noise_pred = self.denoise_fn(x, t, cond=cond)
|
135 |
-
x_recon = self.predict_start_from_noise(x, t=t, noise=noise_pred)
|
136 |
-
|
137 |
-
x_recon.clamp_(-1., 1.)
|
138 |
-
|
139 |
-
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
140 |
-
return model_mean, posterior_variance, posterior_log_variance
|
141 |
-
|
142 |
-
@torch.no_grad()
|
143 |
-
def p_sample(self, x, t, cond, clip_denoised=True, repeat_noise=False):
|
144 |
-
b, *_, device = *x.shape, x.device
|
145 |
-
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, cond=cond)
|
146 |
-
noise = noise_like(x.shape, device, repeat_noise)
|
147 |
-
# no noise when t == 0
|
148 |
-
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
149 |
-
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
150 |
-
|
151 |
-
@torch.no_grad()
|
152 |
-
def p_sample_plms(self, x, t, interval, cond, clip_denoised=True, repeat_noise=False):
|
153 |
-
"""
|
154 |
-
Use the PLMS method from
|
155 |
-
[Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778).
|
156 |
-
"""
|
157 |
-
|
158 |
-
def get_x_pred(x, noise_t, t):
|
159 |
-
a_t = extract(self.alphas_cumprod, t, x.shape)
|
160 |
-
a_prev = extract(self.alphas_cumprod, torch.max(t - interval, torch.zeros_like(t)), x.shape)
|
161 |
-
a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
|
162 |
-
|
163 |
-
x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x - 1 / (
|
164 |
-
a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
|
165 |
-
x_pred = x + x_delta
|
166 |
-
|
167 |
-
return x_pred
|
168 |
-
|
169 |
-
noise_list = self.noise_list
|
170 |
-
noise_pred = self.denoise_fn(x, t, cond=cond)
|
171 |
-
|
172 |
-
if len(noise_list) == 0:
|
173 |
-
x_pred = get_x_pred(x, noise_pred, t)
|
174 |
-
noise_pred_prev = self.denoise_fn(x_pred, max(t - interval, 0), cond=cond)
|
175 |
-
noise_pred_prime = (noise_pred + noise_pred_prev) / 2
|
176 |
-
elif len(noise_list) == 1:
|
177 |
-
noise_pred_prime = (3 * noise_pred - noise_list[-1]) / 2
|
178 |
-
elif len(noise_list) == 2:
|
179 |
-
noise_pred_prime = (23 * noise_pred - 16 * noise_list[-1] + 5 * noise_list[-2]) / 12
|
180 |
-
else:
|
181 |
-
noise_pred_prime = (55 * noise_pred - 59 * noise_list[-1] + 37 * noise_list[-2] - 9 * noise_list[-3]) / 24
|
182 |
-
|
183 |
-
x_prev = get_x_pred(x, noise_pred_prime, t)
|
184 |
-
noise_list.append(noise_pred)
|
185 |
-
|
186 |
-
return x_prev
|
187 |
-
|
188 |
-
def q_sample(self, x_start, t, noise=None):
|
189 |
-
noise = default(noise, lambda: torch.randn_like(x_start))
|
190 |
-
return (
|
191 |
-
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
192 |
-
extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
|
193 |
-
)
|
194 |
-
|
195 |
-
def p_losses(self, x_start, t, cond, noise=None, loss_type='l2'):
|
196 |
-
noise = default(noise, lambda: torch.randn_like(x_start))
|
197 |
-
|
198 |
-
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
199 |
-
x_recon = self.denoise_fn(x_noisy, t, cond)
|
200 |
-
|
201 |
-
if loss_type == 'l1':
|
202 |
-
loss = (noise - x_recon).abs().mean()
|
203 |
-
elif loss_type == 'l2':
|
204 |
-
loss = F.mse_loss(noise, x_recon)
|
205 |
-
else:
|
206 |
-
raise NotImplementedError()
|
207 |
-
|
208 |
-
return loss
|
209 |
-
|
210 |
-
def forward(self,
|
211 |
-
condition,
|
212 |
-
gt_spec=None,
|
213 |
-
infer=True,
|
214 |
-
infer_speedup=10,
|
215 |
-
method='dpm-solver',
|
216 |
-
k_step=300,
|
217 |
-
use_tqdm=True):
|
218 |
-
"""
|
219 |
-
conditioning diffusion, use fastspeech2 encoder output as the condition
|
220 |
-
"""
|
221 |
-
cond = condition.transpose(1, 2)
|
222 |
-
b, device = condition.shape[0], condition.device
|
223 |
-
|
224 |
-
if not infer:
|
225 |
-
spec = self.norm_spec(gt_spec)
|
226 |
-
t = torch.randint(0, self.k_step, (b,), device=device).long()
|
227 |
-
norm_spec = spec.transpose(1, 2)[:, None, :, :] # [B, 1, M, T]
|
228 |
-
return self.p_losses(norm_spec, t, cond=cond)
|
229 |
-
else:
|
230 |
-
shape = (cond.shape[0], 1, self.out_dims, cond.shape[2])
|
231 |
-
|
232 |
-
if gt_spec is None:
|
233 |
-
t = self.k_step
|
234 |
-
x = torch.randn(shape, device=device)
|
235 |
-
else:
|
236 |
-
t = k_step
|
237 |
-
norm_spec = self.norm_spec(gt_spec)
|
238 |
-
norm_spec = norm_spec.transpose(1, 2)[:, None, :, :]
|
239 |
-
x = self.q_sample(x_start=norm_spec, t=torch.tensor([t - 1], device=device).long())
|
240 |
-
|
241 |
-
if method is not None and infer_speedup > 1:
|
242 |
-
if method == 'dpm-solver':
|
243 |
-
from .dpm_solver_pytorch import NoiseScheduleVP, model_wrapper, DPM_Solver
|
244 |
-
# 1. Define the noise schedule.
|
245 |
-
noise_schedule = NoiseScheduleVP(schedule='discrete', betas=self.betas[:t])
|
246 |
-
|
247 |
-
# 2. Convert your discrete-time `model` to the continuous-time
|
248 |
-
# noise prediction model. Here is an example for a diffusion model
|
249 |
-
# `model` with the noise prediction type ("noise") .
|
250 |
-
def my_wrapper(fn):
|
251 |
-
def wrapped(x, t, **kwargs):
|
252 |
-
ret = fn(x, t, **kwargs)
|
253 |
-
if use_tqdm:
|
254 |
-
self.bar.update(1)
|
255 |
-
return ret
|
256 |
-
|
257 |
-
return wrapped
|
258 |
-
|
259 |
-
model_fn = model_wrapper(
|
260 |
-
my_wrapper(self.denoise_fn),
|
261 |
-
noise_schedule,
|
262 |
-
model_type="noise", # or "x_start" or "v" or "score"
|
263 |
-
model_kwargs={"cond": cond}
|
264 |
-
)
|
265 |
-
|
266 |
-
# 3. Define dpm-solver and sample by singlestep DPM-Solver.
|
267 |
-
# (We recommend singlestep DPM-Solver for unconditional sampling)
|
268 |
-
# You can adjust the `steps` to balance the computation
|
269 |
-
# costs and the sample quality.
|
270 |
-
dpm_solver = DPM_Solver(model_fn, noise_schedule)
|
271 |
-
|
272 |
-
steps = t // infer_speedup
|
273 |
-
if use_tqdm:
|
274 |
-
self.bar = tqdm(desc="sample time step", total=steps)
|
275 |
-
x = dpm_solver.sample(
|
276 |
-
x,
|
277 |
-
steps=steps,
|
278 |
-
order=3,
|
279 |
-
skip_type="time_uniform",
|
280 |
-
method="singlestep",
|
281 |
-
)
|
282 |
-
if use_tqdm:
|
283 |
-
self.bar.close()
|
284 |
-
elif method == 'pndm':
|
285 |
-
self.noise_list = deque(maxlen=4)
|
286 |
-
if use_tqdm:
|
287 |
-
for i in tqdm(
|
288 |
-
reversed(range(0, t, infer_speedup)), desc='sample time step',
|
289 |
-
total=t // infer_speedup,
|
290 |
-
):
|
291 |
-
x = self.p_sample_plms(
|
292 |
-
x, torch.full((b,), i, device=device, dtype=torch.long),
|
293 |
-
infer_speedup, cond=cond
|
294 |
-
)
|
295 |
-
else:
|
296 |
-
for i in reversed(range(0, t, infer_speedup)):
|
297 |
-
x = self.p_sample_plms(
|
298 |
-
x, torch.full((b,), i, device=device, dtype=torch.long),
|
299 |
-
infer_speedup, cond=cond
|
300 |
-
)
|
301 |
-
else:
|
302 |
-
raise NotImplementedError(method)
|
303 |
-
else:
|
304 |
-
if use_tqdm:
|
305 |
-
for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
|
306 |
-
x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
|
307 |
-
else:
|
308 |
-
for i in reversed(range(0, t)):
|
309 |
-
x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
|
310 |
-
x = x.squeeze(1).transpose(1, 2) # [B, T, M]
|
311 |
-
return self.denorm_spec(x)
|
312 |
-
|
313 |
-
def norm_spec(self, x):
|
314 |
-
return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
|
315 |
-
|
316 |
-
def denorm_spec(self, x):
|
317 |
-
return (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/diffusion_onnx.py
DELETED
@@ -1,612 +0,0 @@
|
|
1 |
-
from collections import deque
|
2 |
-
from functools import partial
|
3 |
-
from inspect import isfunction
|
4 |
-
import torch.nn.functional as F
|
5 |
-
import librosa.sequence
|
6 |
-
import numpy as np
|
7 |
-
from torch.nn import Conv1d
|
8 |
-
from torch.nn import Mish
|
9 |
-
import torch
|
10 |
-
from torch import nn
|
11 |
-
from tqdm import tqdm
|
12 |
-
import math
|
13 |
-
|
14 |
-
|
15 |
-
def exists(x):
|
16 |
-
return x is not None
|
17 |
-
|
18 |
-
|
19 |
-
def default(val, d):
|
20 |
-
if exists(val):
|
21 |
-
return val
|
22 |
-
return d() if isfunction(d) else d
|
23 |
-
|
24 |
-
|
25 |
-
def extract(a, t):
|
26 |
-
return a[t].reshape((1, 1, 1, 1))
|
27 |
-
|
28 |
-
|
29 |
-
def noise_like(shape, device, repeat=False):
|
30 |
-
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
31 |
-
noise = lambda: torch.randn(shape, device=device)
|
32 |
-
return repeat_noise() if repeat else noise()
|
33 |
-
|
34 |
-
|
35 |
-
def linear_beta_schedule(timesteps, max_beta=0.02):
|
36 |
-
"""
|
37 |
-
linear schedule
|
38 |
-
"""
|
39 |
-
betas = np.linspace(1e-4, max_beta, timesteps)
|
40 |
-
return betas
|
41 |
-
|
42 |
-
|
43 |
-
def cosine_beta_schedule(timesteps, s=0.008):
|
44 |
-
"""
|
45 |
-
cosine schedule
|
46 |
-
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
|
47 |
-
"""
|
48 |
-
steps = timesteps + 1
|
49 |
-
x = np.linspace(0, steps, steps)
|
50 |
-
alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
|
51 |
-
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
52 |
-
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
|
53 |
-
return np.clip(betas, a_min=0, a_max=0.999)
|
54 |
-
|
55 |
-
|
56 |
-
beta_schedule = {
|
57 |
-
"cosine": cosine_beta_schedule,
|
58 |
-
"linear": linear_beta_schedule,
|
59 |
-
}
|
60 |
-
|
61 |
-
|
62 |
-
def extract_1(a, t):
|
63 |
-
return a[t].reshape((1, 1, 1, 1))
|
64 |
-
|
65 |
-
|
66 |
-
def predict_stage0(noise_pred, noise_pred_prev):
|
67 |
-
return (noise_pred + noise_pred_prev) / 2
|
68 |
-
|
69 |
-
|
70 |
-
def predict_stage1(noise_pred, noise_list):
|
71 |
-
return (noise_pred * 3
|
72 |
-
- noise_list[-1]) / 2
|
73 |
-
|
74 |
-
|
75 |
-
def predict_stage2(noise_pred, noise_list):
|
76 |
-
return (noise_pred * 23
|
77 |
-
- noise_list[-1] * 16
|
78 |
-
+ noise_list[-2] * 5) / 12
|
79 |
-
|
80 |
-
|
81 |
-
def predict_stage3(noise_pred, noise_list):
|
82 |
-
return (noise_pred * 55
|
83 |
-
- noise_list[-1] * 59
|
84 |
-
+ noise_list[-2] * 37
|
85 |
-
- noise_list[-3] * 9) / 24
|
86 |
-
|
87 |
-
|
88 |
-
class SinusoidalPosEmb(nn.Module):
|
89 |
-
def __init__(self, dim):
|
90 |
-
super().__init__()
|
91 |
-
self.dim = dim
|
92 |
-
self.half_dim = dim // 2
|
93 |
-
self.emb = 9.21034037 / (self.half_dim - 1)
|
94 |
-
self.emb = torch.exp(torch.arange(self.half_dim) * torch.tensor(-self.emb)).unsqueeze(0)
|
95 |
-
self.emb = self.emb.cpu()
|
96 |
-
|
97 |
-
def forward(self, x):
|
98 |
-
emb = self.emb * x
|
99 |
-
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
|
100 |
-
return emb
|
101 |
-
|
102 |
-
|
103 |
-
class ResidualBlock(nn.Module):
|
104 |
-
def __init__(self, encoder_hidden, residual_channels, dilation):
|
105 |
-
super().__init__()
|
106 |
-
self.residual_channels = residual_channels
|
107 |
-
self.dilated_conv = Conv1d(residual_channels, 2 * residual_channels, 3, padding=dilation, dilation=dilation)
|
108 |
-
self.diffusion_projection = nn.Linear(residual_channels, residual_channels)
|
109 |
-
self.conditioner_projection = Conv1d(encoder_hidden, 2 * residual_channels, 1)
|
110 |
-
self.output_projection = Conv1d(residual_channels, 2 * residual_channels, 1)
|
111 |
-
|
112 |
-
def forward(self, x, conditioner, diffusion_step):
|
113 |
-
diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
|
114 |
-
conditioner = self.conditioner_projection(conditioner)
|
115 |
-
y = x + diffusion_step
|
116 |
-
y = self.dilated_conv(y) + conditioner
|
117 |
-
|
118 |
-
gate, filter_1 = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
|
119 |
-
|
120 |
-
y = torch.sigmoid(gate) * torch.tanh(filter_1)
|
121 |
-
y = self.output_projection(y)
|
122 |
-
|
123 |
-
residual, skip = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
|
124 |
-
|
125 |
-
return (x + residual) / 1.41421356, skip
|
126 |
-
|
127 |
-
|
128 |
-
class DiffNet(nn.Module):
|
129 |
-
def __init__(self, in_dims, n_layers, n_chans, n_hidden):
|
130 |
-
super().__init__()
|
131 |
-
self.encoder_hidden = n_hidden
|
132 |
-
self.residual_layers = n_layers
|
133 |
-
self.residual_channels = n_chans
|
134 |
-
self.input_projection = Conv1d(in_dims, self.residual_channels, 1)
|
135 |
-
self.diffusion_embedding = SinusoidalPosEmb(self.residual_channels)
|
136 |
-
dim = self.residual_channels
|
137 |
-
self.mlp = nn.Sequential(
|
138 |
-
nn.Linear(dim, dim * 4),
|
139 |
-
Mish(),
|
140 |
-
nn.Linear(dim * 4, dim)
|
141 |
-
)
|
142 |
-
self.residual_layers = nn.ModuleList([
|
143 |
-
ResidualBlock(self.encoder_hidden, self.residual_channels, 1)
|
144 |
-
for i in range(self.residual_layers)
|
145 |
-
])
|
146 |
-
self.skip_projection = Conv1d(self.residual_channels, self.residual_channels, 1)
|
147 |
-
self.output_projection = Conv1d(self.residual_channels, in_dims, 1)
|
148 |
-
nn.init.zeros_(self.output_projection.weight)
|
149 |
-
|
150 |
-
def forward(self, spec, diffusion_step, cond):
|
151 |
-
x = spec.squeeze(0)
|
152 |
-
x = self.input_projection(x) # x [B, residual_channel, T]
|
153 |
-
x = F.relu(x)
|
154 |
-
# skip = torch.randn_like(x)
|
155 |
-
diffusion_step = diffusion_step.float()
|
156 |
-
diffusion_step = self.diffusion_embedding(diffusion_step)
|
157 |
-
diffusion_step = self.mlp(diffusion_step)
|
158 |
-
|
159 |
-
x, skip = self.residual_layers[0](x, cond, diffusion_step)
|
160 |
-
# noinspection PyTypeChecker
|
161 |
-
for layer in self.residual_layers[1:]:
|
162 |
-
x, skip_connection = layer.forward(x, cond, diffusion_step)
|
163 |
-
skip = skip + skip_connection
|
164 |
-
x = skip / math.sqrt(len(self.residual_layers))
|
165 |
-
x = self.skip_projection(x)
|
166 |
-
x = F.relu(x)
|
167 |
-
x = self.output_projection(x) # [B, 80, T]
|
168 |
-
return x.unsqueeze(1)
|
169 |
-
|
170 |
-
|
171 |
-
class AfterDiffusion(nn.Module):
|
172 |
-
def __init__(self, spec_max, spec_min, v_type='a'):
|
173 |
-
super().__init__()
|
174 |
-
self.spec_max = spec_max
|
175 |
-
self.spec_min = spec_min
|
176 |
-
self.type = v_type
|
177 |
-
|
178 |
-
def forward(self, x):
|
179 |
-
x = x.squeeze(1).permute(0, 2, 1)
|
180 |
-
mel_out = (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
|
181 |
-
if self.type == 'nsf-hifigan-log10':
|
182 |
-
mel_out = mel_out * 0.434294
|
183 |
-
return mel_out.transpose(2, 1)
|
184 |
-
|
185 |
-
|
186 |
-
class Pred(nn.Module):
|
187 |
-
def __init__(self, alphas_cumprod):
|
188 |
-
super().__init__()
|
189 |
-
self.alphas_cumprod = alphas_cumprod
|
190 |
-
|
191 |
-
def forward(self, x_1, noise_t, t_1, t_prev):
|
192 |
-
a_t = extract(self.alphas_cumprod, t_1).cpu()
|
193 |
-
a_prev = extract(self.alphas_cumprod, t_prev).cpu()
|
194 |
-
a_t_sq, a_prev_sq = a_t.sqrt().cpu(), a_prev.sqrt().cpu()
|
195 |
-
x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x_1 - 1 / (
|
196 |
-
a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
|
197 |
-
x_pred = x_1 + x_delta.cpu()
|
198 |
-
|
199 |
-
return x_pred
|
200 |
-
|
201 |
-
|
202 |
-
class GaussianDiffusion(nn.Module):
|
203 |
-
def __init__(self,
|
204 |
-
out_dims=128,
|
205 |
-
n_layers=20,
|
206 |
-
n_chans=384,
|
207 |
-
n_hidden=256,
|
208 |
-
timesteps=1000,
|
209 |
-
k_step=1000,
|
210 |
-
max_beta=0.02,
|
211 |
-
spec_min=-12,
|
212 |
-
spec_max=2):
|
213 |
-
super().__init__()
|
214 |
-
self.denoise_fn = DiffNet(out_dims, n_layers, n_chans, n_hidden)
|
215 |
-
self.out_dims = out_dims
|
216 |
-
self.mel_bins = out_dims
|
217 |
-
self.n_hidden = n_hidden
|
218 |
-
betas = beta_schedule['linear'](timesteps, max_beta=max_beta)
|
219 |
-
|
220 |
-
alphas = 1. - betas
|
221 |
-
alphas_cumprod = np.cumprod(alphas, axis=0)
|
222 |
-
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
223 |
-
timesteps, = betas.shape
|
224 |
-
self.num_timesteps = int(timesteps)
|
225 |
-
self.k_step = k_step
|
226 |
-
|
227 |
-
self.noise_list = deque(maxlen=4)
|
228 |
-
|
229 |
-
to_torch = partial(torch.tensor, dtype=torch.float32)
|
230 |
-
|
231 |
-
self.register_buffer('betas', to_torch(betas))
|
232 |
-
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
233 |
-
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
234 |
-
|
235 |
-
# calculations for diffusion q(x_t | x_{t-1}) and others
|
236 |
-
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
237 |
-
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
238 |
-
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
239 |
-
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
240 |
-
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
241 |
-
|
242 |
-
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
243 |
-
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
|
244 |
-
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
245 |
-
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
246 |
-
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
247 |
-
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
248 |
-
self.register_buffer('posterior_mean_coef1', to_torch(
|
249 |
-
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
250 |
-
self.register_buffer('posterior_mean_coef2', to_torch(
|
251 |
-
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
252 |
-
|
253 |
-
self.register_buffer('spec_min', torch.FloatTensor([spec_min])[None, None, :out_dims])
|
254 |
-
self.register_buffer('spec_max', torch.FloatTensor([spec_max])[None, None, :out_dims])
|
255 |
-
self.ad = AfterDiffusion(self.spec_max, self.spec_min)
|
256 |
-
self.xp = Pred(self.alphas_cumprod)
|
257 |
-
|
258 |
-
def q_mean_variance(self, x_start, t):
|
259 |
-
mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
260 |
-
variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
|
261 |
-
log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
262 |
-
return mean, variance, log_variance
|
263 |
-
|
264 |
-
def predict_start_from_noise(self, x_t, t, noise):
|
265 |
-
return (
|
266 |
-
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
267 |
-
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
268 |
-
)
|
269 |
-
|
270 |
-
def q_posterior(self, x_start, x_t, t):
|
271 |
-
posterior_mean = (
|
272 |
-
extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
273 |
-
extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
274 |
-
)
|
275 |
-
posterior_variance = extract(self.posterior_variance, t, x_t.shape)
|
276 |
-
posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
|
277 |
-
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
278 |
-
|
279 |
-
def p_mean_variance(self, x, t, cond):
|
280 |
-
noise_pred = self.denoise_fn(x, t, cond=cond)
|
281 |
-
x_recon = self.predict_start_from_noise(x, t=t, noise=noise_pred)
|
282 |
-
|
283 |
-
x_recon.clamp_(-1., 1.)
|
284 |
-
|
285 |
-
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
286 |
-
return model_mean, posterior_variance, posterior_log_variance
|
287 |
-
|
288 |
-
@torch.no_grad()
|
289 |
-
def p_sample(self, x, t, cond, clip_denoised=True, repeat_noise=False):
|
290 |
-
b, *_, device = *x.shape, x.device
|
291 |
-
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, cond=cond)
|
292 |
-
noise = noise_like(x.shape, device, repeat_noise)
|
293 |
-
# no noise when t == 0
|
294 |
-
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
295 |
-
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
296 |
-
|
297 |
-
@torch.no_grad()
|
298 |
-
def p_sample_plms(self, x, t, interval, cond, clip_denoised=True, repeat_noise=False):
|
299 |
-
"""
|
300 |
-
Use the PLMS method from
|
301 |
-
[Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778).
|
302 |
-
"""
|
303 |
-
|
304 |
-
def get_x_pred(x, noise_t, t):
|
305 |
-
a_t = extract(self.alphas_cumprod, t)
|
306 |
-
a_prev = extract(self.alphas_cumprod, torch.max(t - interval, torch.zeros_like(t)))
|
307 |
-
a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
|
308 |
-
|
309 |
-
x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x - 1 / (
|
310 |
-
a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
|
311 |
-
x_pred = x + x_delta
|
312 |
-
|
313 |
-
return x_pred
|
314 |
-
|
315 |
-
noise_list = self.noise_list
|
316 |
-
noise_pred = self.denoise_fn(x, t, cond=cond)
|
317 |
-
|
318 |
-
if len(noise_list) == 0:
|
319 |
-
x_pred = get_x_pred(x, noise_pred, t)
|
320 |
-
noise_pred_prev = self.denoise_fn(x_pred, max(t - interval, 0), cond=cond)
|
321 |
-
noise_pred_prime = (noise_pred + noise_pred_prev) / 2
|
322 |
-
elif len(noise_list) == 1:
|
323 |
-
noise_pred_prime = (3 * noise_pred - noise_list[-1]) / 2
|
324 |
-
elif len(noise_list) == 2:
|
325 |
-
noise_pred_prime = (23 * noise_pred - 16 * noise_list[-1] + 5 * noise_list[-2]) / 12
|
326 |
-
else:
|
327 |
-
noise_pred_prime = (55 * noise_pred - 59 * noise_list[-1] + 37 * noise_list[-2] - 9 * noise_list[-3]) / 24
|
328 |
-
|
329 |
-
x_prev = get_x_pred(x, noise_pred_prime, t)
|
330 |
-
noise_list.append(noise_pred)
|
331 |
-
|
332 |
-
return x_prev
|
333 |
-
|
334 |
-
def q_sample(self, x_start, t, noise=None):
|
335 |
-
noise = default(noise, lambda: torch.randn_like(x_start))
|
336 |
-
return (
|
337 |
-
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
338 |
-
extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
|
339 |
-
)
|
340 |
-
|
341 |
-
def p_losses(self, x_start, t, cond, noise=None, loss_type='l2'):
|
342 |
-
noise = default(noise, lambda: torch.randn_like(x_start))
|
343 |
-
|
344 |
-
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
345 |
-
x_recon = self.denoise_fn(x_noisy, t, cond)
|
346 |
-
|
347 |
-
if loss_type == 'l1':
|
348 |
-
loss = (noise - x_recon).abs().mean()
|
349 |
-
elif loss_type == 'l2':
|
350 |
-
loss = F.mse_loss(noise, x_recon)
|
351 |
-
else:
|
352 |
-
raise NotImplementedError()
|
353 |
-
|
354 |
-
return loss
|
355 |
-
|
356 |
-
def org_forward(self,
|
357 |
-
condition,
|
358 |
-
init_noise=None,
|
359 |
-
gt_spec=None,
|
360 |
-
infer=True,
|
361 |
-
infer_speedup=100,
|
362 |
-
method='pndm',
|
363 |
-
k_step=1000,
|
364 |
-
use_tqdm=True):
|
365 |
-
"""
|
366 |
-
conditioning diffusion, use fastspeech2 encoder output as the condition
|
367 |
-
"""
|
368 |
-
cond = condition
|
369 |
-
b, device = condition.shape[0], condition.device
|
370 |
-
if not infer:
|
371 |
-
spec = self.norm_spec(gt_spec)
|
372 |
-
t = torch.randint(0, self.k_step, (b,), device=device).long()
|
373 |
-
norm_spec = spec.transpose(1, 2)[:, None, :, :] # [B, 1, M, T]
|
374 |
-
return self.p_losses(norm_spec, t, cond=cond)
|
375 |
-
else:
|
376 |
-
shape = (cond.shape[0], 1, self.out_dims, cond.shape[2])
|
377 |
-
|
378 |
-
if gt_spec is None:
|
379 |
-
t = self.k_step
|
380 |
-
if init_noise is None:
|
381 |
-
x = torch.randn(shape, device=device)
|
382 |
-
else:
|
383 |
-
x = init_noise
|
384 |
-
else:
|
385 |
-
t = k_step
|
386 |
-
norm_spec = self.norm_spec(gt_spec)
|
387 |
-
norm_spec = norm_spec.transpose(1, 2)[:, None, :, :]
|
388 |
-
x = self.q_sample(x_start=norm_spec, t=torch.tensor([t - 1], device=device).long())
|
389 |
-
|
390 |
-
if method is not None and infer_speedup > 1:
|
391 |
-
if method == 'dpm-solver':
|
392 |
-
from .dpm_solver_pytorch import NoiseScheduleVP, model_wrapper, DPM_Solver
|
393 |
-
# 1. Define the noise schedule.
|
394 |
-
noise_schedule = NoiseScheduleVP(schedule='discrete', betas=self.betas[:t])
|
395 |
-
|
396 |
-
# 2. Convert your discrete-time `model` to the continuous-time
|
397 |
-
# noise prediction model. Here is an example for a diffusion model
|
398 |
-
# `model` with the noise prediction type ("noise") .
|
399 |
-
def my_wrapper(fn):
|
400 |
-
def wrapped(x, t, **kwargs):
|
401 |
-
ret = fn(x, t, **kwargs)
|
402 |
-
if use_tqdm:
|
403 |
-
self.bar.update(1)
|
404 |
-
return ret
|
405 |
-
|
406 |
-
return wrapped
|
407 |
-
|
408 |
-
model_fn = model_wrapper(
|
409 |
-
my_wrapper(self.denoise_fn),
|
410 |
-
noise_schedule,
|
411 |
-
model_type="noise", # or "x_start" or "v" or "score"
|
412 |
-
model_kwargs={"cond": cond}
|
413 |
-
)
|
414 |
-
|
415 |
-
# 3. Define dpm-solver and sample by singlestep DPM-Solver.
|
416 |
-
# (We recommend singlestep DPM-Solver for unconditional sampling)
|
417 |
-
# You can adjust the `steps` to balance the computation
|
418 |
-
# costs and the sample quality.
|
419 |
-
dpm_solver = DPM_Solver(model_fn, noise_schedule)
|
420 |
-
|
421 |
-
steps = t // infer_speedup
|
422 |
-
if use_tqdm:
|
423 |
-
self.bar = tqdm(desc="sample time step", total=steps)
|
424 |
-
x = dpm_solver.sample(
|
425 |
-
x,
|
426 |
-
steps=steps,
|
427 |
-
order=3,
|
428 |
-
skip_type="time_uniform",
|
429 |
-
method="singlestep",
|
430 |
-
)
|
431 |
-
if use_tqdm:
|
432 |
-
self.bar.close()
|
433 |
-
elif method == 'pndm':
|
434 |
-
self.noise_list = deque(maxlen=4)
|
435 |
-
if use_tqdm:
|
436 |
-
for i in tqdm(
|
437 |
-
reversed(range(0, t, infer_speedup)), desc='sample time step',
|
438 |
-
total=t // infer_speedup,
|
439 |
-
):
|
440 |
-
x = self.p_sample_plms(
|
441 |
-
x, torch.full((b,), i, device=device, dtype=torch.long),
|
442 |
-
infer_speedup, cond=cond
|
443 |
-
)
|
444 |
-
else:
|
445 |
-
for i in reversed(range(0, t, infer_speedup)):
|
446 |
-
x = self.p_sample_plms(
|
447 |
-
x, torch.full((b,), i, device=device, dtype=torch.long),
|
448 |
-
infer_speedup, cond=cond
|
449 |
-
)
|
450 |
-
else:
|
451 |
-
raise NotImplementedError(method)
|
452 |
-
else:
|
453 |
-
if use_tqdm:
|
454 |
-
for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
|
455 |
-
x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
|
456 |
-
else:
|
457 |
-
for i in reversed(range(0, t)):
|
458 |
-
x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
|
459 |
-
x = x.squeeze(1).transpose(1, 2) # [B, T, M]
|
460 |
-
return self.denorm_spec(x).transpose(2, 1)
|
461 |
-
|
462 |
-
def norm_spec(self, x):
|
463 |
-
return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
|
464 |
-
|
465 |
-
def denorm_spec(self, x):
|
466 |
-
return (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
|
467 |
-
|
468 |
-
def get_x_pred(self, x_1, noise_t, t_1, t_prev):
|
469 |
-
a_t = extract(self.alphas_cumprod, t_1)
|
470 |
-
a_prev = extract(self.alphas_cumprod, t_prev)
|
471 |
-
a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
|
472 |
-
x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x_1 - 1 / (
|
473 |
-
a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
|
474 |
-
x_pred = x_1 + x_delta
|
475 |
-
return x_pred
|
476 |
-
|
477 |
-
def OnnxExport(self, project_name=None, init_noise=None, hidden_channels=256, export_denoise=True, export_pred=True, export_after=True):
|
478 |
-
cond = torch.randn([1, self.n_hidden, 10]).cpu()
|
479 |
-
if init_noise is None:
|
480 |
-
x = torch.randn((1, 1, self.mel_bins, cond.shape[2]), dtype=torch.float32).cpu()
|
481 |
-
else:
|
482 |
-
x = init_noise
|
483 |
-
pndms = 100
|
484 |
-
|
485 |
-
org_y_x = self.org_forward(cond, init_noise=x)
|
486 |
-
|
487 |
-
device = cond.device
|
488 |
-
n_frames = cond.shape[2]
|
489 |
-
step_range = torch.arange(0, self.k_step, pndms, dtype=torch.long, device=device).flip(0)
|
490 |
-
plms_noise_stage = torch.tensor(0, dtype=torch.long, device=device)
|
491 |
-
noise_list = torch.zeros((0, 1, 1, self.mel_bins, n_frames), device=device)
|
492 |
-
|
493 |
-
ot = step_range[0]
|
494 |
-
ot_1 = torch.full((1,), ot, device=device, dtype=torch.long)
|
495 |
-
if export_denoise:
|
496 |
-
torch.onnx.export(
|
497 |
-
self.denoise_fn,
|
498 |
-
(x.cpu(), ot_1.cpu(), cond.cpu()),
|
499 |
-
f"{project_name}_denoise.onnx",
|
500 |
-
input_names=["noise", "time", "condition"],
|
501 |
-
output_names=["noise_pred"],
|
502 |
-
dynamic_axes={
|
503 |
-
"noise": [3],
|
504 |
-
"condition": [2]
|
505 |
-
},
|
506 |
-
opset_version=16
|
507 |
-
)
|
508 |
-
|
509 |
-
for t in step_range:
|
510 |
-
t_1 = torch.full((1,), t, device=device, dtype=torch.long)
|
511 |
-
noise_pred = self.denoise_fn(x, t_1, cond)
|
512 |
-
t_prev = t_1 - pndms
|
513 |
-
t_prev = t_prev * (t_prev > 0)
|
514 |
-
if plms_noise_stage == 0:
|
515 |
-
if export_pred:
|
516 |
-
torch.onnx.export(
|
517 |
-
self.xp,
|
518 |
-
(x.cpu(), noise_pred.cpu(), t_1.cpu(), t_prev.cpu()),
|
519 |
-
f"{project_name}_pred.onnx",
|
520 |
-
input_names=["noise", "noise_pred", "time", "time_prev"],
|
521 |
-
output_names=["noise_pred_o"],
|
522 |
-
dynamic_axes={
|
523 |
-
"noise": [3],
|
524 |
-
"noise_pred": [3]
|
525 |
-
},
|
526 |
-
opset_version=16
|
527 |
-
)
|
528 |
-
|
529 |
-
x_pred = self.get_x_pred(x, noise_pred, t_1, t_prev)
|
530 |
-
noise_pred_prev = self.denoise_fn(x_pred, t_prev, cond=cond)
|
531 |
-
noise_pred_prime = predict_stage0(noise_pred, noise_pred_prev)
|
532 |
-
|
533 |
-
elif plms_noise_stage == 1:
|
534 |
-
noise_pred_prime = predict_stage1(noise_pred, noise_list)
|
535 |
-
|
536 |
-
elif plms_noise_stage == 2:
|
537 |
-
noise_pred_prime = predict_stage2(noise_pred, noise_list)
|
538 |
-
|
539 |
-
else:
|
540 |
-
noise_pred_prime = predict_stage3(noise_pred, noise_list)
|
541 |
-
|
542 |
-
noise_pred = noise_pred.unsqueeze(0)
|
543 |
-
|
544 |
-
if plms_noise_stage < 3:
|
545 |
-
noise_list = torch.cat((noise_list, noise_pred), dim=0)
|
546 |
-
plms_noise_stage = plms_noise_stage + 1
|
547 |
-
|
548 |
-
else:
|
549 |
-
noise_list = torch.cat((noise_list[-2:], noise_pred), dim=0)
|
550 |
-
|
551 |
-
x = self.get_x_pred(x, noise_pred_prime, t_1, t_prev)
|
552 |
-
if export_after:
|
553 |
-
torch.onnx.export(
|
554 |
-
self.ad,
|
555 |
-
x.cpu(),
|
556 |
-
f"{project_name}_after.onnx",
|
557 |
-
input_names=["x"],
|
558 |
-
output_names=["mel_out"],
|
559 |
-
dynamic_axes={
|
560 |
-
"x": [3]
|
561 |
-
},
|
562 |
-
opset_version=16
|
563 |
-
)
|
564 |
-
x = self.ad(x)
|
565 |
-
|
566 |
-
print((x == org_y_x).all())
|
567 |
-
return x
|
568 |
-
|
569 |
-
def forward(self, condition=None, init_noise=None, pndms=None, k_step=None):
|
570 |
-
cond = condition
|
571 |
-
x = init_noise
|
572 |
-
|
573 |
-
device = cond.device
|
574 |
-
n_frames = cond.shape[2]
|
575 |
-
step_range = torch.arange(0, k_step.item(), pndms.item(), dtype=torch.long, device=device).flip(0)
|
576 |
-
plms_noise_stage = torch.tensor(0, dtype=torch.long, device=device)
|
577 |
-
noise_list = torch.zeros((0, 1, 1, self.mel_bins, n_frames), device=device)
|
578 |
-
|
579 |
-
ot = step_range[0]
|
580 |
-
ot_1 = torch.full((1,), ot, device=device, dtype=torch.long)
|
581 |
-
|
582 |
-
for t in step_range:
|
583 |
-
t_1 = torch.full((1,), t, device=device, dtype=torch.long)
|
584 |
-
noise_pred = self.denoise_fn(x, t_1, cond)
|
585 |
-
t_prev = t_1 - pndms
|
586 |
-
t_prev = t_prev * (t_prev > 0)
|
587 |
-
if plms_noise_stage == 0:
|
588 |
-
x_pred = self.get_x_pred(x, noise_pred, t_1, t_prev)
|
589 |
-
noise_pred_prev = self.denoise_fn(x_pred, t_prev, cond=cond)
|
590 |
-
noise_pred_prime = predict_stage0(noise_pred, noise_pred_prev)
|
591 |
-
|
592 |
-
elif plms_noise_stage == 1:
|
593 |
-
noise_pred_prime = predict_stage1(noise_pred, noise_list)
|
594 |
-
|
595 |
-
elif plms_noise_stage == 2:
|
596 |
-
noise_pred_prime = predict_stage2(noise_pred, noise_list)
|
597 |
-
|
598 |
-
else:
|
599 |
-
noise_pred_prime = predict_stage3(noise_pred, noise_list)
|
600 |
-
|
601 |
-
noise_pred = noise_pred.unsqueeze(0)
|
602 |
-
|
603 |
-
if plms_noise_stage < 3:
|
604 |
-
noise_list = torch.cat((noise_list, noise_pred), dim=0)
|
605 |
-
plms_noise_stage = plms_noise_stage + 1
|
606 |
-
|
607 |
-
else:
|
608 |
-
noise_list = torch.cat((noise_list[-2:], noise_pred), dim=0)
|
609 |
-
|
610 |
-
x = self.get_x_pred(x, noise_pred_prime, t_1, t_prev)
|
611 |
-
x = self.ad(x)
|
612 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/dpm_solver_pytorch.py
DELETED
@@ -1,1201 +0,0 @@
|
|
1 |
-
import math
|
2 |
-
|
3 |
-
import torch
|
4 |
-
|
5 |
-
|
6 |
-
class NoiseScheduleVP:
|
7 |
-
def __init__(
|
8 |
-
self,
|
9 |
-
schedule='discrete',
|
10 |
-
betas=None,
|
11 |
-
alphas_cumprod=None,
|
12 |
-
continuous_beta_0=0.1,
|
13 |
-
continuous_beta_1=20.,
|
14 |
-
):
|
15 |
-
"""Create a wrapper class for the forward SDE (VP type).
|
16 |
-
|
17 |
-
***
|
18 |
-
Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
|
19 |
-
We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
|
20 |
-
***
|
21 |
-
|
22 |
-
The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
|
23 |
-
We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
|
24 |
-
Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
|
25 |
-
|
26 |
-
log_alpha_t = self.marginal_log_mean_coeff(t)
|
27 |
-
sigma_t = self.marginal_std(t)
|
28 |
-
lambda_t = self.marginal_lambda(t)
|
29 |
-
|
30 |
-
Moreover, as lambda(t) is an invertible function, we also support its inverse function:
|
31 |
-
|
32 |
-
t = self.inverse_lambda(lambda_t)
|
33 |
-
|
34 |
-
===============================================================
|
35 |
-
|
36 |
-
We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
|
37 |
-
|
38 |
-
1. For discrete-time DPMs:
|
39 |
-
|
40 |
-
For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
|
41 |
-
t_i = (i + 1) / N
|
42 |
-
e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
|
43 |
-
We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
|
44 |
-
|
45 |
-
Args:
|
46 |
-
betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
|
47 |
-
alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
|
48 |
-
|
49 |
-
Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
|
50 |
-
|
51 |
-
**Important**: Please pay special attention for the args for `alphas_cumprod`:
|
52 |
-
The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
|
53 |
-
q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
|
54 |
-
Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
|
55 |
-
alpha_{t_n} = \sqrt{\hat{alpha_n}},
|
56 |
-
and
|
57 |
-
log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
|
58 |
-
|
59 |
-
|
60 |
-
2. For continuous-time DPMs:
|
61 |
-
|
62 |
-
We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
|
63 |
-
schedule are the default settings in DDPM and improved-DDPM:
|
64 |
-
|
65 |
-
Args:
|
66 |
-
beta_min: A `float` number. The smallest beta for the linear schedule.
|
67 |
-
beta_max: A `float` number. The largest beta for the linear schedule.
|
68 |
-
cosine_s: A `float` number. The hyperparameter in the cosine schedule.
|
69 |
-
cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
|
70 |
-
T: A `float` number. The ending time of the forward process.
|
71 |
-
|
72 |
-
===============================================================
|
73 |
-
|
74 |
-
Args:
|
75 |
-
schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
|
76 |
-
'linear' or 'cosine' for continuous-time DPMs.
|
77 |
-
Returns:
|
78 |
-
A wrapper object of the forward SDE (VP type).
|
79 |
-
|
80 |
-
===============================================================
|
81 |
-
|
82 |
-
Example:
|
83 |
-
|
84 |
-
# For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
|
85 |
-
>>> ns = NoiseScheduleVP('discrete', betas=betas)
|
86 |
-
|
87 |
-
# For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
|
88 |
-
>>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
|
89 |
-
|
90 |
-
# For continuous-time DPMs (VPSDE), linear schedule:
|
91 |
-
>>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
|
92 |
-
|
93 |
-
"""
|
94 |
-
|
95 |
-
if schedule not in ['discrete', 'linear', 'cosine']:
|
96 |
-
raise ValueError(
|
97 |
-
"Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(
|
98 |
-
schedule))
|
99 |
-
|
100 |
-
self.schedule = schedule
|
101 |
-
if schedule == 'discrete':
|
102 |
-
if betas is not None:
|
103 |
-
log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
|
104 |
-
else:
|
105 |
-
assert alphas_cumprod is not None
|
106 |
-
log_alphas = 0.5 * torch.log(alphas_cumprod)
|
107 |
-
self.total_N = len(log_alphas)
|
108 |
-
self.T = 1.
|
109 |
-
self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
|
110 |
-
self.log_alpha_array = log_alphas.reshape((1, -1,))
|
111 |
-
else:
|
112 |
-
self.total_N = 1000
|
113 |
-
self.beta_0 = continuous_beta_0
|
114 |
-
self.beta_1 = continuous_beta_1
|
115 |
-
self.cosine_s = 0.008
|
116 |
-
self.cosine_beta_max = 999.
|
117 |
-
self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (
|
118 |
-
1. + self.cosine_s) / math.pi - self.cosine_s
|
119 |
-
self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
|
120 |
-
self.schedule = schedule
|
121 |
-
if schedule == 'cosine':
|
122 |
-
# For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
|
123 |
-
# Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
|
124 |
-
self.T = 0.9946
|
125 |
-
else:
|
126 |
-
self.T = 1.
|
127 |
-
|
128 |
-
def marginal_log_mean_coeff(self, t):
|
129 |
-
"""
|
130 |
-
Compute log(alpha_t) of a given continuous-time label t in [0, T].
|
131 |
-
"""
|
132 |
-
if self.schedule == 'discrete':
|
133 |
-
return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device),
|
134 |
-
self.log_alpha_array.to(t.device)).reshape((-1))
|
135 |
-
elif self.schedule == 'linear':
|
136 |
-
return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
|
137 |
-
elif self.schedule == 'cosine':
|
138 |
-
log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
|
139 |
-
log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
|
140 |
-
return log_alpha_t
|
141 |
-
|
142 |
-
def marginal_alpha(self, t):
|
143 |
-
"""
|
144 |
-
Compute alpha_t of a given continuous-time label t in [0, T].
|
145 |
-
"""
|
146 |
-
return torch.exp(self.marginal_log_mean_coeff(t))
|
147 |
-
|
148 |
-
def marginal_std(self, t):
|
149 |
-
"""
|
150 |
-
Compute sigma_t of a given continuous-time label t in [0, T].
|
151 |
-
"""
|
152 |
-
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
153 |
-
|
154 |
-
def marginal_lambda(self, t):
|
155 |
-
"""
|
156 |
-
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
157 |
-
"""
|
158 |
-
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
159 |
-
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
160 |
-
return log_mean_coeff - log_std
|
161 |
-
|
162 |
-
def inverse_lambda(self, lamb):
|
163 |
-
"""
|
164 |
-
Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
|
165 |
-
"""
|
166 |
-
if self.schedule == 'linear':
|
167 |
-
tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
168 |
-
Delta = self.beta_0 ** 2 + tmp
|
169 |
-
return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
|
170 |
-
elif self.schedule == 'discrete':
|
171 |
-
log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
|
172 |
-
t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]),
|
173 |
-
torch.flip(self.t_array.to(lamb.device), [1]))
|
174 |
-
return t.reshape((-1,))
|
175 |
-
else:
|
176 |
-
log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
177 |
-
t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (
|
178 |
-
1. + self.cosine_s) / math.pi - self.cosine_s
|
179 |
-
t = t_fn(log_alpha)
|
180 |
-
return t
|
181 |
-
|
182 |
-
|
183 |
-
def model_wrapper(
|
184 |
-
model,
|
185 |
-
noise_schedule,
|
186 |
-
model_type="noise",
|
187 |
-
model_kwargs={},
|
188 |
-
guidance_type="uncond",
|
189 |
-
condition=None,
|
190 |
-
unconditional_condition=None,
|
191 |
-
guidance_scale=1.,
|
192 |
-
classifier_fn=None,
|
193 |
-
classifier_kwargs={},
|
194 |
-
):
|
195 |
-
"""Create a wrapper function for the noise prediction model.
|
196 |
-
|
197 |
-
DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
|
198 |
-
firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
|
199 |
-
|
200 |
-
We support four types of the diffusion model by setting `model_type`:
|
201 |
-
|
202 |
-
1. "noise": noise prediction model. (Trained by predicting noise).
|
203 |
-
|
204 |
-
2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
|
205 |
-
|
206 |
-
3. "v": velocity prediction model. (Trained by predicting the velocity).
|
207 |
-
The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
|
208 |
-
|
209 |
-
[1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
|
210 |
-
arXiv preprint arXiv:2202.00512 (2022).
|
211 |
-
[2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
|
212 |
-
arXiv preprint arXiv:2210.02303 (2022).
|
213 |
-
|
214 |
-
4. "score": marginal score function. (Trained by denoising score matching).
|
215 |
-
Note that the score function and the noise prediction model follows a simple relationship:
|
216 |
-
```
|
217 |
-
noise(x_t, t) = -sigma_t * score(x_t, t)
|
218 |
-
```
|
219 |
-
|
220 |
-
We support three types of guided sampling by DPMs by setting `guidance_type`:
|
221 |
-
1. "uncond": unconditional sampling by DPMs.
|
222 |
-
The input `model` has the following format:
|
223 |
-
``
|
224 |
-
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
225 |
-
``
|
226 |
-
|
227 |
-
2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
|
228 |
-
The input `model` has the following format:
|
229 |
-
``
|
230 |
-
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
231 |
-
``
|
232 |
-
|
233 |
-
The input `classifier_fn` has the following format:
|
234 |
-
``
|
235 |
-
classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
|
236 |
-
``
|
237 |
-
|
238 |
-
[3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
|
239 |
-
in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
|
240 |
-
|
241 |
-
3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
|
242 |
-
The input `model` has the following format:
|
243 |
-
``
|
244 |
-
model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
|
245 |
-
``
|
246 |
-
And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
|
247 |
-
|
248 |
-
[4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
|
249 |
-
arXiv preprint arXiv:2207.12598 (2022).
|
250 |
-
|
251 |
-
|
252 |
-
The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
|
253 |
-
or continuous-time labels (i.e. epsilon to T).
|
254 |
-
|
255 |
-
We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
|
256 |
-
``
|
257 |
-
def model_fn(x, t_continuous) -> noise:
|
258 |
-
t_input = get_model_input_time(t_continuous)
|
259 |
-
return noise_pred(model, x, t_input, **model_kwargs)
|
260 |
-
``
|
261 |
-
where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
|
262 |
-
|
263 |
-
===============================================================
|
264 |
-
|
265 |
-
Args:
|
266 |
-
model: A diffusion model with the corresponding format described above.
|
267 |
-
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
268 |
-
model_type: A `str`. The parameterization type of the diffusion model.
|
269 |
-
"noise" or "x_start" or "v" or "score".
|
270 |
-
model_kwargs: A `dict`. A dict for the other inputs of the model function.
|
271 |
-
guidance_type: A `str`. The type of the guidance for sampling.
|
272 |
-
"uncond" or "classifier" or "classifier-free".
|
273 |
-
condition: A pytorch tensor. The condition for the guided sampling.
|
274 |
-
Only used for "classifier" or "classifier-free" guidance type.
|
275 |
-
unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
|
276 |
-
Only used for "classifier-free" guidance type.
|
277 |
-
guidance_scale: A `float`. The scale for the guided sampling.
|
278 |
-
classifier_fn: A classifier function. Only used for the classifier guidance.
|
279 |
-
classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
|
280 |
-
Returns:
|
281 |
-
A noise prediction model that accepts the noised data and the continuous time as the inputs.
|
282 |
-
"""
|
283 |
-
|
284 |
-
def get_model_input_time(t_continuous):
|
285 |
-
"""
|
286 |
-
Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
|
287 |
-
For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
|
288 |
-
For continuous-time DPMs, we just use `t_continuous`.
|
289 |
-
"""
|
290 |
-
if noise_schedule.schedule == 'discrete':
|
291 |
-
return (t_continuous - 1. / noise_schedule.total_N) * noise_schedule.total_N
|
292 |
-
else:
|
293 |
-
return t_continuous
|
294 |
-
|
295 |
-
def noise_pred_fn(x, t_continuous, cond=None):
|
296 |
-
if t_continuous.reshape((-1,)).shape[0] == 1:
|
297 |
-
t_continuous = t_continuous.expand((x.shape[0]))
|
298 |
-
t_input = get_model_input_time(t_continuous)
|
299 |
-
if cond is None:
|
300 |
-
output = model(x, t_input, **model_kwargs)
|
301 |
-
else:
|
302 |
-
output = model(x, t_input, cond, **model_kwargs)
|
303 |
-
if model_type == "noise":
|
304 |
-
return output
|
305 |
-
elif model_type == "x_start":
|
306 |
-
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
307 |
-
dims = x.dim()
|
308 |
-
return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
|
309 |
-
elif model_type == "v":
|
310 |
-
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
311 |
-
dims = x.dim()
|
312 |
-
return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
|
313 |
-
elif model_type == "score":
|
314 |
-
sigma_t = noise_schedule.marginal_std(t_continuous)
|
315 |
-
dims = x.dim()
|
316 |
-
return -expand_dims(sigma_t, dims) * output
|
317 |
-
|
318 |
-
def cond_grad_fn(x, t_input):
|
319 |
-
"""
|
320 |
-
Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
|
321 |
-
"""
|
322 |
-
with torch.enable_grad():
|
323 |
-
x_in = x.detach().requires_grad_(True)
|
324 |
-
log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
|
325 |
-
return torch.autograd.grad(log_prob.sum(), x_in)[0]
|
326 |
-
|
327 |
-
def model_fn(x, t_continuous):
|
328 |
-
"""
|
329 |
-
The noise predicition model function that is used for DPM-Solver.
|
330 |
-
"""
|
331 |
-
if t_continuous.reshape((-1,)).shape[0] == 1:
|
332 |
-
t_continuous = t_continuous.expand((x.shape[0]))
|
333 |
-
if guidance_type == "uncond":
|
334 |
-
return noise_pred_fn(x, t_continuous)
|
335 |
-
elif guidance_type == "classifier":
|
336 |
-
assert classifier_fn is not None
|
337 |
-
t_input = get_model_input_time(t_continuous)
|
338 |
-
cond_grad = cond_grad_fn(x, t_input)
|
339 |
-
sigma_t = noise_schedule.marginal_std(t_continuous)
|
340 |
-
noise = noise_pred_fn(x, t_continuous)
|
341 |
-
return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
|
342 |
-
elif guidance_type == "classifier-free":
|
343 |
-
if guidance_scale == 1. or unconditional_condition is None:
|
344 |
-
return noise_pred_fn(x, t_continuous, cond=condition)
|
345 |
-
else:
|
346 |
-
x_in = torch.cat([x] * 2)
|
347 |
-
t_in = torch.cat([t_continuous] * 2)
|
348 |
-
c_in = torch.cat([unconditional_condition, condition])
|
349 |
-
noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
|
350 |
-
return noise_uncond + guidance_scale * (noise - noise_uncond)
|
351 |
-
|
352 |
-
assert model_type in ["noise", "x_start", "v"]
|
353 |
-
assert guidance_type in ["uncond", "classifier", "classifier-free"]
|
354 |
-
return model_fn
|
355 |
-
|
356 |
-
|
357 |
-
class DPM_Solver:
|
358 |
-
def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
|
359 |
-
"""Construct a DPM-Solver.
|
360 |
-
|
361 |
-
We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
|
362 |
-
If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
|
363 |
-
If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
|
364 |
-
In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
|
365 |
-
The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
|
366 |
-
|
367 |
-
Args:
|
368 |
-
model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
|
369 |
-
``
|
370 |
-
def model_fn(x, t_continuous):
|
371 |
-
return noise
|
372 |
-
``
|
373 |
-
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
374 |
-
predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
|
375 |
-
thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
|
376 |
-
max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
|
377 |
-
|
378 |
-
[1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
|
379 |
-
"""
|
380 |
-
self.model = model_fn
|
381 |
-
self.noise_schedule = noise_schedule
|
382 |
-
self.predict_x0 = predict_x0
|
383 |
-
self.thresholding = thresholding
|
384 |
-
self.max_val = max_val
|
385 |
-
|
386 |
-
def noise_prediction_fn(self, x, t):
|
387 |
-
"""
|
388 |
-
Return the noise prediction model.
|
389 |
-
"""
|
390 |
-
return self.model(x, t)
|
391 |
-
|
392 |
-
def data_prediction_fn(self, x, t):
|
393 |
-
"""
|
394 |
-
Return the data prediction model (with thresholding).
|
395 |
-
"""
|
396 |
-
noise = self.noise_prediction_fn(x, t)
|
397 |
-
dims = x.dim()
|
398 |
-
alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
|
399 |
-
x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
|
400 |
-
if self.thresholding:
|
401 |
-
p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
|
402 |
-
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
403 |
-
s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
|
404 |
-
x0 = torch.clamp(x0, -s, s) / s
|
405 |
-
return x0
|
406 |
-
|
407 |
-
def model_fn(self, x, t):
|
408 |
-
"""
|
409 |
-
Convert the model to the noise prediction model or the data prediction model.
|
410 |
-
"""
|
411 |
-
if self.predict_x0:
|
412 |
-
return self.data_prediction_fn(x, t)
|
413 |
-
else:
|
414 |
-
return self.noise_prediction_fn(x, t)
|
415 |
-
|
416 |
-
def get_time_steps(self, skip_type, t_T, t_0, N, device):
|
417 |
-
"""Compute the intermediate time steps for sampling.
|
418 |
-
|
419 |
-
Args:
|
420 |
-
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
|
421 |
-
- 'logSNR': uniform logSNR for the time steps.
|
422 |
-
- 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
|
423 |
-
- 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
|
424 |
-
t_T: A `float`. The starting time of the sampling (default is T).
|
425 |
-
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
426 |
-
N: A `int`. The total number of the spacing of the time steps.
|
427 |
-
device: A torch device.
|
428 |
-
Returns:
|
429 |
-
A pytorch tensor of the time steps, with the shape (N + 1,).
|
430 |
-
"""
|
431 |
-
if skip_type == 'logSNR':
|
432 |
-
lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
|
433 |
-
lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
|
434 |
-
logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
|
435 |
-
return self.noise_schedule.inverse_lambda(logSNR_steps)
|
436 |
-
elif skip_type == 'time_uniform':
|
437 |
-
return torch.linspace(t_T, t_0, N + 1).to(device)
|
438 |
-
elif skip_type == 'time_quadratic':
|
439 |
-
t_order = 2
|
440 |
-
t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device)
|
441 |
-
return t
|
442 |
-
else:
|
443 |
-
raise ValueError(
|
444 |
-
"Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
|
445 |
-
|
446 |
-
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
|
447 |
-
"""
|
448 |
-
Get the order of each step for sampling by the singlestep DPM-Solver.
|
449 |
-
|
450 |
-
We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
|
451 |
-
Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
|
452 |
-
- If order == 1:
|
453 |
-
We take `steps` of DPM-Solver-1 (i.e. DDIM).
|
454 |
-
- If order == 2:
|
455 |
-
- Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
|
456 |
-
- If steps % 2 == 0, we use K steps of DPM-Solver-2.
|
457 |
-
- If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
|
458 |
-
- If order == 3:
|
459 |
-
- Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
|
460 |
-
- If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
|
461 |
-
- If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
|
462 |
-
- If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
|
463 |
-
|
464 |
-
============================================
|
465 |
-
Args:
|
466 |
-
order: A `int`. The max order for the solver (2 or 3).
|
467 |
-
steps: A `int`. The total number of function evaluations (NFE).
|
468 |
-
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
|
469 |
-
- 'logSNR': uniform logSNR for the time steps.
|
470 |
-
- 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
|
471 |
-
- 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
|
472 |
-
t_T: A `float`. The starting time of the sampling (default is T).
|
473 |
-
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
474 |
-
device: A torch device.
|
475 |
-
Returns:
|
476 |
-
orders: A list of the solver order of each step.
|
477 |
-
"""
|
478 |
-
if order == 3:
|
479 |
-
K = steps // 3 + 1
|
480 |
-
if steps % 3 == 0:
|
481 |
-
orders = [3, ] * (K - 2) + [2, 1]
|
482 |
-
elif steps % 3 == 1:
|
483 |
-
orders = [3, ] * (K - 1) + [1]
|
484 |
-
else:
|
485 |
-
orders = [3, ] * (K - 1) + [2]
|
486 |
-
elif order == 2:
|
487 |
-
if steps % 2 == 0:
|
488 |
-
K = steps // 2
|
489 |
-
orders = [2, ] * K
|
490 |
-
else:
|
491 |
-
K = steps // 2 + 1
|
492 |
-
orders = [2, ] * (K - 1) + [1]
|
493 |
-
elif order == 1:
|
494 |
-
K = 1
|
495 |
-
orders = [1, ] * steps
|
496 |
-
else:
|
497 |
-
raise ValueError("'order' must be '1' or '2' or '3'.")
|
498 |
-
if skip_type == 'logSNR':
|
499 |
-
# To reproduce the results in DPM-Solver paper
|
500 |
-
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
|
501 |
-
else:
|
502 |
-
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[
|
503 |
-
torch.cumsum(torch.tensor([0, ] + orders), dim=0).to(device)]
|
504 |
-
return timesteps_outer, orders
|
505 |
-
|
506 |
-
def denoise_fn(self, x, s):
|
507 |
-
"""
|
508 |
-
Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
|
509 |
-
"""
|
510 |
-
return self.data_prediction_fn(x, s)
|
511 |
-
|
512 |
-
def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
|
513 |
-
"""
|
514 |
-
DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
|
515 |
-
|
516 |
-
Args:
|
517 |
-
x: A pytorch tensor. The initial value at time `s`.
|
518 |
-
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
519 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
520 |
-
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
521 |
-
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
522 |
-
return_intermediate: A `bool`. If true, also return the model value at time `s`.
|
523 |
-
Returns:
|
524 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
525 |
-
"""
|
526 |
-
ns = self.noise_schedule
|
527 |
-
dims = x.dim()
|
528 |
-
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
529 |
-
h = lambda_t - lambda_s
|
530 |
-
log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
|
531 |
-
sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
|
532 |
-
alpha_t = torch.exp(log_alpha_t)
|
533 |
-
|
534 |
-
if self.predict_x0:
|
535 |
-
phi_1 = torch.expm1(-h)
|
536 |
-
if model_s is None:
|
537 |
-
model_s = self.model_fn(x, s)
|
538 |
-
x_t = (
|
539 |
-
expand_dims(sigma_t / sigma_s, dims) * x
|
540 |
-
- expand_dims(alpha_t * phi_1, dims) * model_s
|
541 |
-
)
|
542 |
-
if return_intermediate:
|
543 |
-
return x_t, {'model_s': model_s}
|
544 |
-
else:
|
545 |
-
return x_t
|
546 |
-
else:
|
547 |
-
phi_1 = torch.expm1(h)
|
548 |
-
if model_s is None:
|
549 |
-
model_s = self.model_fn(x, s)
|
550 |
-
x_t = (
|
551 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
552 |
-
- expand_dims(sigma_t * phi_1, dims) * model_s
|
553 |
-
)
|
554 |
-
if return_intermediate:
|
555 |
-
return x_t, {'model_s': model_s}
|
556 |
-
else:
|
557 |
-
return x_t
|
558 |
-
|
559 |
-
def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
|
560 |
-
solver_type='dpm_solver'):
|
561 |
-
"""
|
562 |
-
Singlestep solver DPM-Solver-2 from time `s` to time `t`.
|
563 |
-
|
564 |
-
Args:
|
565 |
-
x: A pytorch tensor. The initial value at time `s`.
|
566 |
-
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
567 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
568 |
-
r1: A `float`. The hyperparameter of the second-order solver.
|
569 |
-
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
570 |
-
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
571 |
-
return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
|
572 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
573 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
574 |
-
Returns:
|
575 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
576 |
-
"""
|
577 |
-
if solver_type not in ['dpm_solver', 'taylor']:
|
578 |
-
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
579 |
-
if r1 is None:
|
580 |
-
r1 = 0.5
|
581 |
-
ns = self.noise_schedule
|
582 |
-
dims = x.dim()
|
583 |
-
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
584 |
-
h = lambda_t - lambda_s
|
585 |
-
lambda_s1 = lambda_s + r1 * h
|
586 |
-
s1 = ns.inverse_lambda(lambda_s1)
|
587 |
-
log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
|
588 |
-
s1), ns.marginal_log_mean_coeff(t)
|
589 |
-
sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
|
590 |
-
alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
|
591 |
-
|
592 |
-
if self.predict_x0:
|
593 |
-
phi_11 = torch.expm1(-r1 * h)
|
594 |
-
phi_1 = torch.expm1(-h)
|
595 |
-
|
596 |
-
if model_s is None:
|
597 |
-
model_s = self.model_fn(x, s)
|
598 |
-
x_s1 = (
|
599 |
-
expand_dims(sigma_s1 / sigma_s, dims) * x
|
600 |
-
- expand_dims(alpha_s1 * phi_11, dims) * model_s
|
601 |
-
)
|
602 |
-
model_s1 = self.model_fn(x_s1, s1)
|
603 |
-
if solver_type == 'dpm_solver':
|
604 |
-
x_t = (
|
605 |
-
expand_dims(sigma_t / sigma_s, dims) * x
|
606 |
-
- expand_dims(alpha_t * phi_1, dims) * model_s
|
607 |
-
- (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
|
608 |
-
)
|
609 |
-
elif solver_type == 'taylor':
|
610 |
-
x_t = (
|
611 |
-
expand_dims(sigma_t / sigma_s, dims) * x
|
612 |
-
- expand_dims(alpha_t * phi_1, dims) * model_s
|
613 |
-
+ (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
|
614 |
-
model_s1 - model_s)
|
615 |
-
)
|
616 |
-
else:
|
617 |
-
phi_11 = torch.expm1(r1 * h)
|
618 |
-
phi_1 = torch.expm1(h)
|
619 |
-
|
620 |
-
if model_s is None:
|
621 |
-
model_s = self.model_fn(x, s)
|
622 |
-
x_s1 = (
|
623 |
-
expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
|
624 |
-
- expand_dims(sigma_s1 * phi_11, dims) * model_s
|
625 |
-
)
|
626 |
-
model_s1 = self.model_fn(x_s1, s1)
|
627 |
-
if solver_type == 'dpm_solver':
|
628 |
-
x_t = (
|
629 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
630 |
-
- expand_dims(sigma_t * phi_1, dims) * model_s
|
631 |
-
- (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
|
632 |
-
)
|
633 |
-
elif solver_type == 'taylor':
|
634 |
-
x_t = (
|
635 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
636 |
-
- expand_dims(sigma_t * phi_1, dims) * model_s
|
637 |
-
- (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
|
638 |
-
)
|
639 |
-
if return_intermediate:
|
640 |
-
return x_t, {'model_s': model_s, 'model_s1': model_s1}
|
641 |
-
else:
|
642 |
-
return x_t
|
643 |
-
|
644 |
-
def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
|
645 |
-
return_intermediate=False, solver_type='dpm_solver'):
|
646 |
-
"""
|
647 |
-
Singlestep solver DPM-Solver-3 from time `s` to time `t`.
|
648 |
-
|
649 |
-
Args:
|
650 |
-
x: A pytorch tensor. The initial value at time `s`.
|
651 |
-
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
652 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
653 |
-
r1: A `float`. The hyperparameter of the third-order solver.
|
654 |
-
r2: A `float`. The hyperparameter of the third-order solver.
|
655 |
-
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
656 |
-
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
657 |
-
model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
|
658 |
-
If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
|
659 |
-
return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
|
660 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
661 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
662 |
-
Returns:
|
663 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
664 |
-
"""
|
665 |
-
if solver_type not in ['dpm_solver', 'taylor']:
|
666 |
-
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
667 |
-
if r1 is None:
|
668 |
-
r1 = 1. / 3.
|
669 |
-
if r2 is None:
|
670 |
-
r2 = 2. / 3.
|
671 |
-
ns = self.noise_schedule
|
672 |
-
dims = x.dim()
|
673 |
-
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
674 |
-
h = lambda_t - lambda_s
|
675 |
-
lambda_s1 = lambda_s + r1 * h
|
676 |
-
lambda_s2 = lambda_s + r2 * h
|
677 |
-
s1 = ns.inverse_lambda(lambda_s1)
|
678 |
-
s2 = ns.inverse_lambda(lambda_s2)
|
679 |
-
log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
|
680 |
-
s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
|
681 |
-
sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
|
682 |
-
s2), ns.marginal_std(t)
|
683 |
-
alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
|
684 |
-
|
685 |
-
if self.predict_x0:
|
686 |
-
phi_11 = torch.expm1(-r1 * h)
|
687 |
-
phi_12 = torch.expm1(-r2 * h)
|
688 |
-
phi_1 = torch.expm1(-h)
|
689 |
-
phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
|
690 |
-
phi_2 = phi_1 / h + 1.
|
691 |
-
phi_3 = phi_2 / h - 0.5
|
692 |
-
|
693 |
-
if model_s is None:
|
694 |
-
model_s = self.model_fn(x, s)
|
695 |
-
if model_s1 is None:
|
696 |
-
x_s1 = (
|
697 |
-
expand_dims(sigma_s1 / sigma_s, dims) * x
|
698 |
-
- expand_dims(alpha_s1 * phi_11, dims) * model_s
|
699 |
-
)
|
700 |
-
model_s1 = self.model_fn(x_s1, s1)
|
701 |
-
x_s2 = (
|
702 |
-
expand_dims(sigma_s2 / sigma_s, dims) * x
|
703 |
-
- expand_dims(alpha_s2 * phi_12, dims) * model_s
|
704 |
-
+ r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
|
705 |
-
)
|
706 |
-
model_s2 = self.model_fn(x_s2, s2)
|
707 |
-
if solver_type == 'dpm_solver':
|
708 |
-
x_t = (
|
709 |
-
expand_dims(sigma_t / sigma_s, dims) * x
|
710 |
-
- expand_dims(alpha_t * phi_1, dims) * model_s
|
711 |
-
+ (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
|
712 |
-
)
|
713 |
-
elif solver_type == 'taylor':
|
714 |
-
D1_0 = (1. / r1) * (model_s1 - model_s)
|
715 |
-
D1_1 = (1. / r2) * (model_s2 - model_s)
|
716 |
-
D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
|
717 |
-
D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
|
718 |
-
x_t = (
|
719 |
-
expand_dims(sigma_t / sigma_s, dims) * x
|
720 |
-
- expand_dims(alpha_t * phi_1, dims) * model_s
|
721 |
-
+ expand_dims(alpha_t * phi_2, dims) * D1
|
722 |
-
- expand_dims(alpha_t * phi_3, dims) * D2
|
723 |
-
)
|
724 |
-
else:
|
725 |
-
phi_11 = torch.expm1(r1 * h)
|
726 |
-
phi_12 = torch.expm1(r2 * h)
|
727 |
-
phi_1 = torch.expm1(h)
|
728 |
-
phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
|
729 |
-
phi_2 = phi_1 / h - 1.
|
730 |
-
phi_3 = phi_2 / h - 0.5
|
731 |
-
|
732 |
-
if model_s is None:
|
733 |
-
model_s = self.model_fn(x, s)
|
734 |
-
if model_s1 is None:
|
735 |
-
x_s1 = (
|
736 |
-
expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
|
737 |
-
- expand_dims(sigma_s1 * phi_11, dims) * model_s
|
738 |
-
)
|
739 |
-
model_s1 = self.model_fn(x_s1, s1)
|
740 |
-
x_s2 = (
|
741 |
-
expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
|
742 |
-
- expand_dims(sigma_s2 * phi_12, dims) * model_s
|
743 |
-
- r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
|
744 |
-
)
|
745 |
-
model_s2 = self.model_fn(x_s2, s2)
|
746 |
-
if solver_type == 'dpm_solver':
|
747 |
-
x_t = (
|
748 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
749 |
-
- expand_dims(sigma_t * phi_1, dims) * model_s
|
750 |
-
- (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
|
751 |
-
)
|
752 |
-
elif solver_type == 'taylor':
|
753 |
-
D1_0 = (1. / r1) * (model_s1 - model_s)
|
754 |
-
D1_1 = (1. / r2) * (model_s2 - model_s)
|
755 |
-
D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
|
756 |
-
D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
|
757 |
-
x_t = (
|
758 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
759 |
-
- expand_dims(sigma_t * phi_1, dims) * model_s
|
760 |
-
- expand_dims(sigma_t * phi_2, dims) * D1
|
761 |
-
- expand_dims(sigma_t * phi_3, dims) * D2
|
762 |
-
)
|
763 |
-
|
764 |
-
if return_intermediate:
|
765 |
-
return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
|
766 |
-
else:
|
767 |
-
return x_t
|
768 |
-
|
769 |
-
def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
|
770 |
-
"""
|
771 |
-
Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
|
772 |
-
|
773 |
-
Args:
|
774 |
-
x: A pytorch tensor. The initial value at time `s`.
|
775 |
-
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
776 |
-
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
777 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
778 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
779 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
780 |
-
Returns:
|
781 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
782 |
-
"""
|
783 |
-
if solver_type not in ['dpm_solver', 'taylor']:
|
784 |
-
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
785 |
-
ns = self.noise_schedule
|
786 |
-
dims = x.dim()
|
787 |
-
model_prev_1, model_prev_0 = model_prev_list
|
788 |
-
t_prev_1, t_prev_0 = t_prev_list
|
789 |
-
lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(
|
790 |
-
t_prev_0), ns.marginal_lambda(t)
|
791 |
-
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
792 |
-
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
793 |
-
alpha_t = torch.exp(log_alpha_t)
|
794 |
-
|
795 |
-
h_0 = lambda_prev_0 - lambda_prev_1
|
796 |
-
h = lambda_t - lambda_prev_0
|
797 |
-
r0 = h_0 / h
|
798 |
-
D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
|
799 |
-
if self.predict_x0:
|
800 |
-
if solver_type == 'dpm_solver':
|
801 |
-
x_t = (
|
802 |
-
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
803 |
-
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
804 |
-
- 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
|
805 |
-
)
|
806 |
-
elif solver_type == 'taylor':
|
807 |
-
x_t = (
|
808 |
-
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
809 |
-
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
810 |
-
+ expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
|
811 |
-
)
|
812 |
-
else:
|
813 |
-
if solver_type == 'dpm_solver':
|
814 |
-
x_t = (
|
815 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
816 |
-
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
817 |
-
- 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
|
818 |
-
)
|
819 |
-
elif solver_type == 'taylor':
|
820 |
-
x_t = (
|
821 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
822 |
-
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
823 |
-
- expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
|
824 |
-
)
|
825 |
-
return x_t
|
826 |
-
|
827 |
-
def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
|
828 |
-
"""
|
829 |
-
Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
|
830 |
-
|
831 |
-
Args:
|
832 |
-
x: A pytorch tensor. The initial value at time `s`.
|
833 |
-
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
834 |
-
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
835 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
836 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
837 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
838 |
-
Returns:
|
839 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
840 |
-
"""
|
841 |
-
ns = self.noise_schedule
|
842 |
-
dims = x.dim()
|
843 |
-
model_prev_2, model_prev_1, model_prev_0 = model_prev_list
|
844 |
-
t_prev_2, t_prev_1, t_prev_0 = t_prev_list
|
845 |
-
lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(
|
846 |
-
t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
|
847 |
-
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
848 |
-
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
849 |
-
alpha_t = torch.exp(log_alpha_t)
|
850 |
-
|
851 |
-
h_1 = lambda_prev_1 - lambda_prev_2
|
852 |
-
h_0 = lambda_prev_0 - lambda_prev_1
|
853 |
-
h = lambda_t - lambda_prev_0
|
854 |
-
r0, r1 = h_0 / h, h_1 / h
|
855 |
-
D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
|
856 |
-
D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
|
857 |
-
D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
|
858 |
-
D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
|
859 |
-
if self.predict_x0:
|
860 |
-
x_t = (
|
861 |
-
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
862 |
-
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
863 |
-
+ expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
|
864 |
-
- expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2
|
865 |
-
)
|
866 |
-
else:
|
867 |
-
x_t = (
|
868 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
869 |
-
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
870 |
-
- expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
|
871 |
-
- expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2
|
872 |
-
)
|
873 |
-
return x_t
|
874 |
-
|
875 |
-
def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None,
|
876 |
-
r2=None):
|
877 |
-
"""
|
878 |
-
Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
|
879 |
-
|
880 |
-
Args:
|
881 |
-
x: A pytorch tensor. The initial value at time `s`.
|
882 |
-
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
883 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
884 |
-
order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
|
885 |
-
return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
|
886 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
887 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
888 |
-
r1: A `float`. The hyperparameter of the second-order or third-order solver.
|
889 |
-
r2: A `float`. The hyperparameter of the third-order solver.
|
890 |
-
Returns:
|
891 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
892 |
-
"""
|
893 |
-
if order == 1:
|
894 |
-
return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
|
895 |
-
elif order == 2:
|
896 |
-
return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate,
|
897 |
-
solver_type=solver_type, r1=r1)
|
898 |
-
elif order == 3:
|
899 |
-
return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate,
|
900 |
-
solver_type=solver_type, r1=r1, r2=r2)
|
901 |
-
else:
|
902 |
-
raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
|
903 |
-
|
904 |
-
def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
|
905 |
-
"""
|
906 |
-
Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
|
907 |
-
|
908 |
-
Args:
|
909 |
-
x: A pytorch tensor. The initial value at time `s`.
|
910 |
-
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
911 |
-
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
912 |
-
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
913 |
-
order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
|
914 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
915 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
916 |
-
Returns:
|
917 |
-
x_t: A pytorch tensor. The approximated solution at time `t`.
|
918 |
-
"""
|
919 |
-
if order == 1:
|
920 |
-
return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
|
921 |
-
elif order == 2:
|
922 |
-
return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
|
923 |
-
elif order == 3:
|
924 |
-
return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
|
925 |
-
else:
|
926 |
-
raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
|
927 |
-
|
928 |
-
def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5,
|
929 |
-
solver_type='dpm_solver'):
|
930 |
-
"""
|
931 |
-
The adaptive step size solver based on singlestep DPM-Solver.
|
932 |
-
|
933 |
-
Args:
|
934 |
-
x: A pytorch tensor. The initial value at time `t_T`.
|
935 |
-
order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
|
936 |
-
t_T: A `float`. The starting time of the sampling (default is T).
|
937 |
-
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
938 |
-
h_init: A `float`. The initial step size (for logSNR).
|
939 |
-
atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
|
940 |
-
rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
|
941 |
-
theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
|
942 |
-
t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
|
943 |
-
current time and `t_0` is less than `t_err`. The default setting is 1e-5.
|
944 |
-
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
945 |
-
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
946 |
-
Returns:
|
947 |
-
x_0: A pytorch tensor. The approximated solution at time `t_0`.
|
948 |
-
|
949 |
-
[1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
|
950 |
-
"""
|
951 |
-
ns = self.noise_schedule
|
952 |
-
s = t_T * torch.ones((x.shape[0],)).to(x)
|
953 |
-
lambda_s = ns.marginal_lambda(s)
|
954 |
-
lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
|
955 |
-
h = h_init * torch.ones_like(s).to(x)
|
956 |
-
x_prev = x
|
957 |
-
nfe = 0
|
958 |
-
if order == 2:
|
959 |
-
r1 = 0.5
|
960 |
-
lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
|
961 |
-
higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
|
962 |
-
solver_type=solver_type,
|
963 |
-
**kwargs)
|
964 |
-
elif order == 3:
|
965 |
-
r1, r2 = 1. / 3., 2. / 3.
|
966 |
-
lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
|
967 |
-
return_intermediate=True,
|
968 |
-
solver_type=solver_type)
|
969 |
-
higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2,
|
970 |
-
solver_type=solver_type,
|
971 |
-
**kwargs)
|
972 |
-
else:
|
973 |
-
raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
|
974 |
-
while torch.abs((s - t_0)).mean() > t_err:
|
975 |
-
t = ns.inverse_lambda(lambda_s + h)
|
976 |
-
x_lower, lower_noise_kwargs = lower_update(x, s, t)
|
977 |
-
x_higher = higher_update(x, s, t, **lower_noise_kwargs)
|
978 |
-
delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
|
979 |
-
norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
|
980 |
-
E = norm_fn((x_higher - x_lower) / delta).max()
|
981 |
-
if torch.all(E <= 1.):
|
982 |
-
x = x_higher
|
983 |
-
s = t
|
984 |
-
x_prev = x_lower
|
985 |
-
lambda_s = ns.marginal_lambda(s)
|
986 |
-
h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
|
987 |
-
nfe += order
|
988 |
-
print('adaptive solver nfe', nfe)
|
989 |
-
return x
|
990 |
-
|
991 |
-
def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
|
992 |
-
method='singlestep', denoise=False, solver_type='dpm_solver', atol=0.0078,
|
993 |
-
rtol=0.05,
|
994 |
-
):
|
995 |
-
"""
|
996 |
-
Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
|
997 |
-
|
998 |
-
=====================================================
|
999 |
-
|
1000 |
-
We support the following algorithms for both noise prediction model and data prediction model:
|
1001 |
-
- 'singlestep':
|
1002 |
-
Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
|
1003 |
-
We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
|
1004 |
-
The total number of function evaluations (NFE) == `steps`.
|
1005 |
-
Given a fixed NFE == `steps`, the sampling procedure is:
|
1006 |
-
- If `order` == 1:
|
1007 |
-
- Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
|
1008 |
-
- If `order` == 2:
|
1009 |
-
- Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
|
1010 |
-
- If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
|
1011 |
-
- If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
|
1012 |
-
- If `order` == 3:
|
1013 |
-
- Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
|
1014 |
-
- If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
|
1015 |
-
- If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
|
1016 |
-
- If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
|
1017 |
-
- 'multistep':
|
1018 |
-
Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
|
1019 |
-
We initialize the first `order` values by lower order multistep solvers.
|
1020 |
-
Given a fixed NFE == `steps`, the sampling procedure is:
|
1021 |
-
Denote K = steps.
|
1022 |
-
- If `order` == 1:
|
1023 |
-
- We use K steps of DPM-Solver-1 (i.e. DDIM).
|
1024 |
-
- If `order` == 2:
|
1025 |
-
- We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
|
1026 |
-
- If `order` == 3:
|
1027 |
-
- We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
|
1028 |
-
- 'singlestep_fixed':
|
1029 |
-
Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
|
1030 |
-
We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
|
1031 |
-
- 'adaptive':
|
1032 |
-
Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
|
1033 |
-
We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
|
1034 |
-
You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
|
1035 |
-
(NFE) and the sample quality.
|
1036 |
-
- If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
|
1037 |
-
- If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
|
1038 |
-
|
1039 |
-
=====================================================
|
1040 |
-
|
1041 |
-
Some advices for choosing the algorithm:
|
1042 |
-
- For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
|
1043 |
-
Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
|
1044 |
-
e.g.
|
1045 |
-
>>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
|
1046 |
-
>>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
|
1047 |
-
skip_type='time_uniform', method='singlestep')
|
1048 |
-
- For **guided sampling with large guidance scale** by DPMs:
|
1049 |
-
Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
|
1050 |
-
e.g.
|
1051 |
-
>>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
|
1052 |
-
>>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
|
1053 |
-
skip_type='time_uniform', method='multistep')
|
1054 |
-
|
1055 |
-
We support three types of `skip_type`:
|
1056 |
-
- 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
|
1057 |
-
- 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
|
1058 |
-
- 'time_quadratic': quadratic time for the time steps.
|
1059 |
-
|
1060 |
-
=====================================================
|
1061 |
-
Args:
|
1062 |
-
x: A pytorch tensor. The initial value at time `t_start`
|
1063 |
-
e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
|
1064 |
-
steps: A `int`. The total number of function evaluations (NFE).
|
1065 |
-
t_start: A `float`. The starting time of the sampling.
|
1066 |
-
If `T` is None, we use self.noise_schedule.T (default is 1.0).
|
1067 |
-
t_end: A `float`. The ending time of the sampling.
|
1068 |
-
If `t_end` is None, we use 1. / self.noise_schedule.total_N.
|
1069 |
-
e.g. if total_N == 1000, we have `t_end` == 1e-3.
|
1070 |
-
For discrete-time DPMs:
|
1071 |
-
- We recommend `t_end` == 1. / self.noise_schedule.total_N.
|
1072 |
-
For continuous-time DPMs:
|
1073 |
-
- We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
|
1074 |
-
order: A `int`. The order of DPM-Solver.
|
1075 |
-
skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
|
1076 |
-
method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
|
1077 |
-
denoise: A `bool`. Whether to denoise at the final step. Default is False.
|
1078 |
-
If `denoise` is True, the total NFE is (`steps` + 1).
|
1079 |
-
solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
|
1080 |
-
atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
|
1081 |
-
rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
|
1082 |
-
Returns:
|
1083 |
-
x_end: A pytorch tensor. The approximated solution at time `t_end`.
|
1084 |
-
|
1085 |
-
"""
|
1086 |
-
t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
|
1087 |
-
t_T = self.noise_schedule.T if t_start is None else t_start
|
1088 |
-
device = x.device
|
1089 |
-
if method == 'adaptive':
|
1090 |
-
with torch.no_grad():
|
1091 |
-
x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol,
|
1092 |
-
solver_type=solver_type)
|
1093 |
-
elif method == 'multistep':
|
1094 |
-
assert steps >= order
|
1095 |
-
timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
|
1096 |
-
assert timesteps.shape[0] - 1 == steps
|
1097 |
-
with torch.no_grad():
|
1098 |
-
vec_t = timesteps[0].expand((x.shape[0]))
|
1099 |
-
model_prev_list = [self.model_fn(x, vec_t)]
|
1100 |
-
t_prev_list = [vec_t]
|
1101 |
-
# Init the first `order` values by lower order multistep DPM-Solver.
|
1102 |
-
for init_order in range(1, order):
|
1103 |
-
vec_t = timesteps[init_order].expand(x.shape[0])
|
1104 |
-
x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order,
|
1105 |
-
solver_type=solver_type)
|
1106 |
-
model_prev_list.append(self.model_fn(x, vec_t))
|
1107 |
-
t_prev_list.append(vec_t)
|
1108 |
-
# Compute the remaining values by `order`-th order multistep DPM-Solver.
|
1109 |
-
for step in range(order, steps + 1):
|
1110 |
-
vec_t = timesteps[step].expand(x.shape[0])
|
1111 |
-
x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, order,
|
1112 |
-
solver_type=solver_type)
|
1113 |
-
for i in range(order - 1):
|
1114 |
-
t_prev_list[i] = t_prev_list[i + 1]
|
1115 |
-
model_prev_list[i] = model_prev_list[i + 1]
|
1116 |
-
t_prev_list[-1] = vec_t
|
1117 |
-
# We do not need to evaluate the final model value.
|
1118 |
-
if step < steps:
|
1119 |
-
model_prev_list[-1] = self.model_fn(x, vec_t)
|
1120 |
-
elif method in ['singlestep', 'singlestep_fixed']:
|
1121 |
-
if method == 'singlestep':
|
1122 |
-
timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order,
|
1123 |
-
skip_type=skip_type,
|
1124 |
-
t_T=t_T, t_0=t_0,
|
1125 |
-
device=device)
|
1126 |
-
elif method == 'singlestep_fixed':
|
1127 |
-
K = steps // order
|
1128 |
-
orders = [order, ] * K
|
1129 |
-
timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
|
1130 |
-
for i, order in enumerate(orders):
|
1131 |
-
t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
|
1132 |
-
timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(),
|
1133 |
-
N=order, device=device)
|
1134 |
-
lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
|
1135 |
-
vec_s, vec_t = t_T_inner.repeat(x.shape[0]), t_0_inner.repeat(x.shape[0])
|
1136 |
-
h = lambda_inner[-1] - lambda_inner[0]
|
1137 |
-
r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
|
1138 |
-
r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
|
1139 |
-
x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
|
1140 |
-
if denoise:
|
1141 |
-
x = self.denoise_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
|
1142 |
-
return x
|
1143 |
-
|
1144 |
-
|
1145 |
-
#############################################################
|
1146 |
-
# other utility functions
|
1147 |
-
#############################################################
|
1148 |
-
|
1149 |
-
def interpolate_fn(x, xp, yp):
|
1150 |
-
"""
|
1151 |
-
A piecewise linear function y = f(x), using xp and yp as keypoints.
|
1152 |
-
We implement f(x) in a differentiable way (i.e. applicable for autograd).
|
1153 |
-
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
|
1154 |
-
|
1155 |
-
Args:
|
1156 |
-
x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
|
1157 |
-
xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
|
1158 |
-
yp: PyTorch tensor with shape [C, K].
|
1159 |
-
Returns:
|
1160 |
-
The function values f(x), with shape [N, C].
|
1161 |
-
"""
|
1162 |
-
N, K = x.shape[0], xp.shape[1]
|
1163 |
-
all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
|
1164 |
-
sorted_all_x, x_indices = torch.sort(all_x, dim=2)
|
1165 |
-
x_idx = torch.argmin(x_indices, dim=2)
|
1166 |
-
cand_start_idx = x_idx - 1
|
1167 |
-
start_idx = torch.where(
|
1168 |
-
torch.eq(x_idx, 0),
|
1169 |
-
torch.tensor(1, device=x.device),
|
1170 |
-
torch.where(
|
1171 |
-
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
1172 |
-
),
|
1173 |
-
)
|
1174 |
-
end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
|
1175 |
-
start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
|
1176 |
-
end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
|
1177 |
-
start_idx2 = torch.where(
|
1178 |
-
torch.eq(x_idx, 0),
|
1179 |
-
torch.tensor(0, device=x.device),
|
1180 |
-
torch.where(
|
1181 |
-
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
1182 |
-
),
|
1183 |
-
)
|
1184 |
-
y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
|
1185 |
-
start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
|
1186 |
-
end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
|
1187 |
-
cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
|
1188 |
-
return cand
|
1189 |
-
|
1190 |
-
|
1191 |
-
def expand_dims(v, dims):
|
1192 |
-
"""
|
1193 |
-
Expand the tensor `v` to the dim `dims`.
|
1194 |
-
|
1195 |
-
Args:
|
1196 |
-
`v`: a PyTorch tensor with shape [N].
|
1197 |
-
`dim`: a `int`.
|
1198 |
-
Returns:
|
1199 |
-
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
|
1200 |
-
"""
|
1201 |
-
return v[(...,) + (None,) * (dims - 1)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/how to export onnx.md
DELETED
@@ -1,4 +0,0 @@
|
|
1 |
-
- Open [onnx_export](onnx_export.py)
|
2 |
-
- project_name = "dddsp" change "project_name" to your project name
|
3 |
-
- model_path = f'{project_name}/model_500000.pt' change "model_path" to your model path
|
4 |
-
- Run
|
|
|
|
|
|
|
|
|
|
diffusion/infer_gt_mel.py
DELETED
@@ -1,74 +0,0 @@
|
|
1 |
-
import numpy as np
|
2 |
-
import torch
|
3 |
-
import torch.nn.functional as F
|
4 |
-
from diffusion.unit2mel import load_model_vocoder
|
5 |
-
|
6 |
-
|
7 |
-
class DiffGtMel:
|
8 |
-
def __init__(self, project_path=None, device=None):
|
9 |
-
self.project_path = project_path
|
10 |
-
if device is not None:
|
11 |
-
self.device = device
|
12 |
-
else:
|
13 |
-
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
14 |
-
self.model = None
|
15 |
-
self.vocoder = None
|
16 |
-
self.args = None
|
17 |
-
|
18 |
-
def flush_model(self, project_path, ddsp_config=None):
|
19 |
-
if (self.model is None) or (project_path != self.project_path):
|
20 |
-
model, vocoder, args = load_model_vocoder(project_path, device=self.device)
|
21 |
-
if self.check_args(ddsp_config, args):
|
22 |
-
self.model = model
|
23 |
-
self.vocoder = vocoder
|
24 |
-
self.args = args
|
25 |
-
|
26 |
-
def check_args(self, args1, args2):
|
27 |
-
if args1.data.block_size != args2.data.block_size:
|
28 |
-
raise ValueError("DDSP与DIFF模型的block_size不一致")
|
29 |
-
if args1.data.sampling_rate != args2.data.sampling_rate:
|
30 |
-
raise ValueError("DDSP与DIFF模型的sampling_rate不一致")
|
31 |
-
if args1.data.encoder != args2.data.encoder:
|
32 |
-
raise ValueError("DDSP与DIFF模型的encoder不一致")
|
33 |
-
return True
|
34 |
-
|
35 |
-
def __call__(self, audio, f0, hubert, volume, acc=1, spk_id=1, k_step=0, method='pndm',
|
36 |
-
spk_mix_dict=None, start_frame=0):
|
37 |
-
input_mel = self.vocoder.extract(audio, self.args.data.sampling_rate)
|
38 |
-
out_mel = self.model(
|
39 |
-
hubert,
|
40 |
-
f0,
|
41 |
-
volume,
|
42 |
-
spk_id=spk_id,
|
43 |
-
spk_mix_dict=spk_mix_dict,
|
44 |
-
gt_spec=input_mel,
|
45 |
-
infer=True,
|
46 |
-
infer_speedup=acc,
|
47 |
-
method=method,
|
48 |
-
k_step=k_step,
|
49 |
-
use_tqdm=False)
|
50 |
-
if start_frame > 0:
|
51 |
-
out_mel = out_mel[:, start_frame:, :]
|
52 |
-
f0 = f0[:, start_frame:, :]
|
53 |
-
output = self.vocoder.infer(out_mel, f0)
|
54 |
-
if start_frame > 0:
|
55 |
-
output = F.pad(output, (start_frame * self.vocoder.vocoder_hop_size, 0))
|
56 |
-
return output
|
57 |
-
|
58 |
-
def infer(self, audio, f0, hubert, volume, acc=1, spk_id=1, k_step=0, method='pndm', silence_front=0,
|
59 |
-
use_silence=False, spk_mix_dict=None):
|
60 |
-
start_frame = int(silence_front * self.vocoder.vocoder_sample_rate / self.vocoder.vocoder_hop_size)
|
61 |
-
if use_silence:
|
62 |
-
audio = audio[:, start_frame * self.vocoder.vocoder_hop_size:]
|
63 |
-
f0 = f0[:, start_frame:, :]
|
64 |
-
hubert = hubert[:, start_frame:, :]
|
65 |
-
volume = volume[:, start_frame:, :]
|
66 |
-
_start_frame = 0
|
67 |
-
else:
|
68 |
-
_start_frame = start_frame
|
69 |
-
audio = self.__call__(audio, f0, hubert, volume, acc=acc, spk_id=spk_id, k_step=k_step,
|
70 |
-
method=method, spk_mix_dict=spk_mix_dict, start_frame=_start_frame)
|
71 |
-
if use_silence:
|
72 |
-
if start_frame > 0:
|
73 |
-
audio = F.pad(audio, (start_frame * self.vocoder.vocoder_hop_size, 0))
|
74 |
-
return audio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/logger/__init__.py
DELETED
File without changes
|
diffusion/logger/saver.py
DELETED
@@ -1,150 +0,0 @@
|
|
1 |
-
'''
|
2 |
-
author: wayn391@mastertones
|
3 |
-
'''
|
4 |
-
|
5 |
-
import os
|
6 |
-
import json
|
7 |
-
import time
|
8 |
-
import yaml
|
9 |
-
import datetime
|
10 |
-
import torch
|
11 |
-
import matplotlib.pyplot as plt
|
12 |
-
from . import utils
|
13 |
-
from torch.utils.tensorboard import SummaryWriter
|
14 |
-
|
15 |
-
class Saver(object):
|
16 |
-
def __init__(
|
17 |
-
self,
|
18 |
-
args,
|
19 |
-
initial_global_step=-1):
|
20 |
-
|
21 |
-
self.expdir = args.env.expdir
|
22 |
-
self.sample_rate = args.data.sampling_rate
|
23 |
-
|
24 |
-
# cold start
|
25 |
-
self.global_step = initial_global_step
|
26 |
-
self.init_time = time.time()
|
27 |
-
self.last_time = time.time()
|
28 |
-
|
29 |
-
# makedirs
|
30 |
-
os.makedirs(self.expdir, exist_ok=True)
|
31 |
-
|
32 |
-
# path
|
33 |
-
self.path_log_info = os.path.join(self.expdir, 'log_info.txt')
|
34 |
-
|
35 |
-
# ckpt
|
36 |
-
os.makedirs(self.expdir, exist_ok=True)
|
37 |
-
|
38 |
-
# writer
|
39 |
-
self.writer = SummaryWriter(os.path.join(self.expdir, 'logs'))
|
40 |
-
|
41 |
-
# save config
|
42 |
-
path_config = os.path.join(self.expdir, 'config.yaml')
|
43 |
-
with open(path_config, "w") as out_config:
|
44 |
-
yaml.dump(dict(args), out_config)
|
45 |
-
|
46 |
-
|
47 |
-
def log_info(self, msg):
|
48 |
-
'''log method'''
|
49 |
-
if isinstance(msg, dict):
|
50 |
-
msg_list = []
|
51 |
-
for k, v in msg.items():
|
52 |
-
tmp_str = ''
|
53 |
-
if isinstance(v, int):
|
54 |
-
tmp_str = '{}: {:,}'.format(k, v)
|
55 |
-
else:
|
56 |
-
tmp_str = '{}: {}'.format(k, v)
|
57 |
-
|
58 |
-
msg_list.append(tmp_str)
|
59 |
-
msg_str = '\n'.join(msg_list)
|
60 |
-
else:
|
61 |
-
msg_str = msg
|
62 |
-
|
63 |
-
# dsplay
|
64 |
-
print(msg_str)
|
65 |
-
|
66 |
-
# save
|
67 |
-
with open(self.path_log_info, 'a') as fp:
|
68 |
-
fp.write(msg_str+'\n')
|
69 |
-
|
70 |
-
def log_value(self, dict):
|
71 |
-
for k, v in dict.items():
|
72 |
-
self.writer.add_scalar(k, v, self.global_step)
|
73 |
-
|
74 |
-
def log_spec(self, name, spec, spec_out, vmin=-14, vmax=3.5):
|
75 |
-
spec_cat = torch.cat([(spec_out - spec).abs() + vmin, spec, spec_out], -1)
|
76 |
-
spec = spec_cat[0]
|
77 |
-
if isinstance(spec, torch.Tensor):
|
78 |
-
spec = spec.cpu().numpy()
|
79 |
-
fig = plt.figure(figsize=(12, 9))
|
80 |
-
plt.pcolor(spec.T, vmin=vmin, vmax=vmax)
|
81 |
-
plt.tight_layout()
|
82 |
-
self.writer.add_figure(name, fig, self.global_step)
|
83 |
-
|
84 |
-
def log_audio(self, dict):
|
85 |
-
for k, v in dict.items():
|
86 |
-
self.writer.add_audio(k, v, global_step=self.global_step, sample_rate=self.sample_rate)
|
87 |
-
|
88 |
-
def get_interval_time(self, update=True):
|
89 |
-
cur_time = time.time()
|
90 |
-
time_interval = cur_time - self.last_time
|
91 |
-
if update:
|
92 |
-
self.last_time = cur_time
|
93 |
-
return time_interval
|
94 |
-
|
95 |
-
def get_total_time(self, to_str=True):
|
96 |
-
total_time = time.time() - self.init_time
|
97 |
-
if to_str:
|
98 |
-
total_time = str(datetime.timedelta(
|
99 |
-
seconds=total_time))[:-5]
|
100 |
-
return total_time
|
101 |
-
|
102 |
-
def save_model(
|
103 |
-
self,
|
104 |
-
model,
|
105 |
-
optimizer,
|
106 |
-
name='model',
|
107 |
-
postfix='',
|
108 |
-
to_json=False):
|
109 |
-
# path
|
110 |
-
if postfix:
|
111 |
-
postfix = '_' + postfix
|
112 |
-
path_pt = os.path.join(
|
113 |
-
self.expdir , name+postfix+'.pt')
|
114 |
-
|
115 |
-
# check
|
116 |
-
print(' [*] model checkpoint saved: {}'.format(path_pt))
|
117 |
-
|
118 |
-
# save
|
119 |
-
if optimizer is not None:
|
120 |
-
torch.save({
|
121 |
-
'global_step': self.global_step,
|
122 |
-
'model': model.state_dict(),
|
123 |
-
'optimizer': optimizer.state_dict()}, path_pt)
|
124 |
-
else:
|
125 |
-
torch.save({
|
126 |
-
'global_step': self.global_step,
|
127 |
-
'model': model.state_dict()}, path_pt)
|
128 |
-
|
129 |
-
# to json
|
130 |
-
if to_json:
|
131 |
-
path_json = os.path.join(
|
132 |
-
self.expdir , name+'.json')
|
133 |
-
utils.to_json(path_params, path_json)
|
134 |
-
|
135 |
-
def delete_model(self, name='model', postfix=''):
|
136 |
-
# path
|
137 |
-
if postfix:
|
138 |
-
postfix = '_' + postfix
|
139 |
-
path_pt = os.path.join(
|
140 |
-
self.expdir , name+postfix+'.pt')
|
141 |
-
|
142 |
-
# delete
|
143 |
-
if os.path.exists(path_pt):
|
144 |
-
os.remove(path_pt)
|
145 |
-
print(' [*] model checkpoint deleted: {}'.format(path_pt))
|
146 |
-
|
147 |
-
def global_step_increment(self):
|
148 |
-
self.global_step += 1
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/logger/utils.py
DELETED
@@ -1,126 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import yaml
|
3 |
-
import json
|
4 |
-
import pickle
|
5 |
-
import torch
|
6 |
-
|
7 |
-
def traverse_dir(
|
8 |
-
root_dir,
|
9 |
-
extensions,
|
10 |
-
amount=None,
|
11 |
-
str_include=None,
|
12 |
-
str_exclude=None,
|
13 |
-
is_pure=False,
|
14 |
-
is_sort=False,
|
15 |
-
is_ext=True):
|
16 |
-
|
17 |
-
file_list = []
|
18 |
-
cnt = 0
|
19 |
-
for root, _, files in os.walk(root_dir):
|
20 |
-
for file in files:
|
21 |
-
if any([file.endswith(f".{ext}") for ext in extensions]):
|
22 |
-
# path
|
23 |
-
mix_path = os.path.join(root, file)
|
24 |
-
pure_path = mix_path[len(root_dir)+1:] if is_pure else mix_path
|
25 |
-
|
26 |
-
# amount
|
27 |
-
if (amount is not None) and (cnt == amount):
|
28 |
-
if is_sort:
|
29 |
-
file_list.sort()
|
30 |
-
return file_list
|
31 |
-
|
32 |
-
# check string
|
33 |
-
if (str_include is not None) and (str_include not in pure_path):
|
34 |
-
continue
|
35 |
-
if (str_exclude is not None) and (str_exclude in pure_path):
|
36 |
-
continue
|
37 |
-
|
38 |
-
if not is_ext:
|
39 |
-
ext = pure_path.split('.')[-1]
|
40 |
-
pure_path = pure_path[:-(len(ext)+1)]
|
41 |
-
file_list.append(pure_path)
|
42 |
-
cnt += 1
|
43 |
-
if is_sort:
|
44 |
-
file_list.sort()
|
45 |
-
return file_list
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
class DotDict(dict):
|
50 |
-
def __getattr__(*args):
|
51 |
-
val = dict.get(*args)
|
52 |
-
return DotDict(val) if type(val) is dict else val
|
53 |
-
|
54 |
-
__setattr__ = dict.__setitem__
|
55 |
-
__delattr__ = dict.__delitem__
|
56 |
-
|
57 |
-
|
58 |
-
def get_network_paras_amount(model_dict):
|
59 |
-
info = dict()
|
60 |
-
for model_name, model in model_dict.items():
|
61 |
-
# all_params = sum(p.numel() for p in model.parameters())
|
62 |
-
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
63 |
-
|
64 |
-
info[model_name] = trainable_params
|
65 |
-
return info
|
66 |
-
|
67 |
-
|
68 |
-
def load_config(path_config):
|
69 |
-
with open(path_config, "r") as config:
|
70 |
-
args = yaml.safe_load(config)
|
71 |
-
args = DotDict(args)
|
72 |
-
# print(args)
|
73 |
-
return args
|
74 |
-
|
75 |
-
def save_config(path_config,config):
|
76 |
-
config = dict(config)
|
77 |
-
with open(path_config, "w") as f:
|
78 |
-
yaml.dump(config, f)
|
79 |
-
|
80 |
-
def to_json(path_params, path_json):
|
81 |
-
params = torch.load(path_params, map_location=torch.device('cpu'))
|
82 |
-
raw_state_dict = {}
|
83 |
-
for k, v in params.items():
|
84 |
-
val = v.flatten().numpy().tolist()
|
85 |
-
raw_state_dict[k] = val
|
86 |
-
|
87 |
-
with open(path_json, 'w') as outfile:
|
88 |
-
json.dump(raw_state_dict, outfile,indent= "\t")
|
89 |
-
|
90 |
-
|
91 |
-
def convert_tensor_to_numpy(tensor, is_squeeze=True):
|
92 |
-
if is_squeeze:
|
93 |
-
tensor = tensor.squeeze()
|
94 |
-
if tensor.requires_grad:
|
95 |
-
tensor = tensor.detach()
|
96 |
-
if tensor.is_cuda:
|
97 |
-
tensor = tensor.cpu()
|
98 |
-
return tensor.numpy()
|
99 |
-
|
100 |
-
|
101 |
-
def load_model(
|
102 |
-
expdir,
|
103 |
-
model,
|
104 |
-
optimizer,
|
105 |
-
name='model',
|
106 |
-
postfix='',
|
107 |
-
device='cpu'):
|
108 |
-
if postfix == '':
|
109 |
-
postfix = '_' + postfix
|
110 |
-
path = os.path.join(expdir, name+postfix)
|
111 |
-
path_pt = traverse_dir(expdir, ['pt'], is_ext=False)
|
112 |
-
global_step = 0
|
113 |
-
if len(path_pt) > 0:
|
114 |
-
steps = [s[len(path):] for s in path_pt]
|
115 |
-
maxstep = max([int(s) if s.isdigit() else 0 for s in steps])
|
116 |
-
if maxstep >= 0:
|
117 |
-
path_pt = path+str(maxstep)+'.pt'
|
118 |
-
else:
|
119 |
-
path_pt = path+'best.pt'
|
120 |
-
print(' [*] restoring model from', path_pt)
|
121 |
-
ckpt = torch.load(path_pt, map_location=torch.device(device))
|
122 |
-
global_step = ckpt['global_step']
|
123 |
-
model.load_state_dict(ckpt['model'], strict=False)
|
124 |
-
if ckpt.get('optimizer') != None:
|
125 |
-
optimizer.load_state_dict(ckpt['optimizer'])
|
126 |
-
return global_step, model, optimizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/onnx_export.py
DELETED
@@ -1,226 +0,0 @@
|
|
1 |
-
from diffusion_onnx import GaussianDiffusion
|
2 |
-
import os
|
3 |
-
import yaml
|
4 |
-
import torch
|
5 |
-
import torch.nn as nn
|
6 |
-
import numpy as np
|
7 |
-
from wavenet import WaveNet
|
8 |
-
import torch.nn.functional as F
|
9 |
-
import diffusion
|
10 |
-
|
11 |
-
class DotDict(dict):
|
12 |
-
def __getattr__(*args):
|
13 |
-
val = dict.get(*args)
|
14 |
-
return DotDict(val) if type(val) is dict else val
|
15 |
-
|
16 |
-
__setattr__ = dict.__setitem__
|
17 |
-
__delattr__ = dict.__delitem__
|
18 |
-
|
19 |
-
|
20 |
-
def load_model_vocoder(
|
21 |
-
model_path,
|
22 |
-
device='cpu'):
|
23 |
-
config_file = os.path.join(os.path.split(model_path)[0], 'config.yaml')
|
24 |
-
with open(config_file, "r") as config:
|
25 |
-
args = yaml.safe_load(config)
|
26 |
-
args = DotDict(args)
|
27 |
-
|
28 |
-
# load model
|
29 |
-
model = Unit2Mel(
|
30 |
-
args.data.encoder_out_channels,
|
31 |
-
args.model.n_spk,
|
32 |
-
args.model.use_pitch_aug,
|
33 |
-
128,
|
34 |
-
args.model.n_layers,
|
35 |
-
args.model.n_chans,
|
36 |
-
args.model.n_hidden)
|
37 |
-
|
38 |
-
print(' [Loading] ' + model_path)
|
39 |
-
ckpt = torch.load(model_path, map_location=torch.device(device))
|
40 |
-
model.to(device)
|
41 |
-
model.load_state_dict(ckpt['model'])
|
42 |
-
model.eval()
|
43 |
-
return model, args
|
44 |
-
|
45 |
-
|
46 |
-
class Unit2Mel(nn.Module):
|
47 |
-
def __init__(
|
48 |
-
self,
|
49 |
-
input_channel,
|
50 |
-
n_spk,
|
51 |
-
use_pitch_aug=False,
|
52 |
-
out_dims=128,
|
53 |
-
n_layers=20,
|
54 |
-
n_chans=384,
|
55 |
-
n_hidden=256):
|
56 |
-
super().__init__()
|
57 |
-
self.unit_embed = nn.Linear(input_channel, n_hidden)
|
58 |
-
self.f0_embed = nn.Linear(1, n_hidden)
|
59 |
-
self.volume_embed = nn.Linear(1, n_hidden)
|
60 |
-
if use_pitch_aug:
|
61 |
-
self.aug_shift_embed = nn.Linear(1, n_hidden, bias=False)
|
62 |
-
else:
|
63 |
-
self.aug_shift_embed = None
|
64 |
-
self.n_spk = n_spk
|
65 |
-
if n_spk is not None and n_spk > 1:
|
66 |
-
self.spk_embed = nn.Embedding(n_spk, n_hidden)
|
67 |
-
|
68 |
-
# diffusion
|
69 |
-
self.decoder = GaussianDiffusion(out_dims, n_layers, n_chans, n_hidden)
|
70 |
-
self.hidden_size = n_hidden
|
71 |
-
self.speaker_map = torch.zeros((self.n_spk,1,1,n_hidden))
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
def forward(self, units, mel2ph, f0, volume, g = None):
|
76 |
-
|
77 |
-
'''
|
78 |
-
input:
|
79 |
-
B x n_frames x n_unit
|
80 |
-
return:
|
81 |
-
dict of B x n_frames x feat
|
82 |
-
'''
|
83 |
-
|
84 |
-
decoder_inp = F.pad(units, [0, 0, 1, 0])
|
85 |
-
mel2ph_ = mel2ph.unsqueeze(2).repeat([1, 1, units.shape[-1]])
|
86 |
-
units = torch.gather(decoder_inp, 1, mel2ph_) # [B, T, H]
|
87 |
-
|
88 |
-
x = self.unit_embed(units) + self.f0_embed((1 + f0.unsqueeze(-1) / 700).log()) + self.volume_embed(volume.unsqueeze(-1))
|
89 |
-
|
90 |
-
if self.n_spk is not None and self.n_spk > 1: # [N, S] * [S, B, 1, H]
|
91 |
-
g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
|
92 |
-
g = g * self.speaker_map # [N, S, B, 1, H]
|
93 |
-
g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
|
94 |
-
g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
|
95 |
-
x = x.transpose(1, 2) + g
|
96 |
-
return x
|
97 |
-
else:
|
98 |
-
return x.transpose(1, 2)
|
99 |
-
|
100 |
-
|
101 |
-
def init_spkembed(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
|
102 |
-
gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
|
103 |
-
|
104 |
-
'''
|
105 |
-
input:
|
106 |
-
B x n_frames x n_unit
|
107 |
-
return:
|
108 |
-
dict of B x n_frames x feat
|
109 |
-
'''
|
110 |
-
x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
|
111 |
-
if self.n_spk is not None and self.n_spk > 1:
|
112 |
-
if spk_mix_dict is not None:
|
113 |
-
spk_embed_mix = torch.zeros((1,1,self.hidden_size))
|
114 |
-
for k, v in spk_mix_dict.items():
|
115 |
-
spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
|
116 |
-
spk_embeddd = self.spk_embed(spk_id_torch)
|
117 |
-
self.speaker_map[k] = spk_embeddd
|
118 |
-
spk_embed_mix = spk_embed_mix + v * spk_embeddd
|
119 |
-
x = x + spk_embed_mix
|
120 |
-
else:
|
121 |
-
x = x + self.spk_embed(spk_id - 1)
|
122 |
-
self.speaker_map = self.speaker_map.unsqueeze(0)
|
123 |
-
self.speaker_map = self.speaker_map.detach()
|
124 |
-
return x.transpose(1, 2)
|
125 |
-
|
126 |
-
def OnnxExport(self, project_name=None, init_noise=None, export_encoder=True, export_denoise=True, export_pred=True, export_after=True):
|
127 |
-
hubert_hidden_size = 768
|
128 |
-
n_frames = 100
|
129 |
-
hubert = torch.randn((1, n_frames, hubert_hidden_size))
|
130 |
-
mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
|
131 |
-
f0 = torch.randn((1, n_frames))
|
132 |
-
volume = torch.randn((1, n_frames))
|
133 |
-
spk_mix = []
|
134 |
-
spks = {}
|
135 |
-
if self.n_spk is not None and self.n_spk > 1:
|
136 |
-
for i in range(self.n_spk):
|
137 |
-
spk_mix.append(1.0/float(self.n_spk))
|
138 |
-
spks.update({i:1.0/float(self.n_spk)})
|
139 |
-
spk_mix = torch.tensor(spk_mix)
|
140 |
-
spk_mix = spk_mix.repeat(n_frames, 1)
|
141 |
-
orgouttt = self.init_spkembed(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
|
142 |
-
outtt = self.forward(hubert, mel2ph, f0, volume, spk_mix)
|
143 |
-
if export_encoder:
|
144 |
-
torch.onnx.export(
|
145 |
-
self,
|
146 |
-
(hubert, mel2ph, f0, volume, spk_mix),
|
147 |
-
f"{project_name}_encoder.onnx",
|
148 |
-
input_names=["hubert", "mel2ph", "f0", "volume", "spk_mix"],
|
149 |
-
output_names=["mel_pred"],
|
150 |
-
dynamic_axes={
|
151 |
-
"hubert": [1],
|
152 |
-
"f0": [1],
|
153 |
-
"volume": [1],
|
154 |
-
"mel2ph": [1],
|
155 |
-
"spk_mix": [0],
|
156 |
-
},
|
157 |
-
opset_version=16
|
158 |
-
)
|
159 |
-
|
160 |
-
self.decoder.OnnxExport(project_name, init_noise=init_noise, export_denoise=export_denoise, export_pred=export_pred, export_after=export_after)
|
161 |
-
|
162 |
-
def ExportOnnx(self, project_name=None):
|
163 |
-
hubert_hidden_size = 768
|
164 |
-
n_frames = 100
|
165 |
-
hubert = torch.randn((1, n_frames, hubert_hidden_size))
|
166 |
-
mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
|
167 |
-
f0 = torch.randn((1, n_frames))
|
168 |
-
volume = torch.randn((1, n_frames))
|
169 |
-
spk_mix = []
|
170 |
-
spks = {}
|
171 |
-
if self.n_spk is not None and self.n_spk > 1:
|
172 |
-
for i in range(self.n_spk):
|
173 |
-
spk_mix.append(1.0/float(self.n_spk))
|
174 |
-
spks.update({i:1.0/float(self.n_spk)})
|
175 |
-
spk_mix = torch.tensor(spk_mix)
|
176 |
-
orgouttt = self.orgforward(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
|
177 |
-
outtt = self.forward(hubert, mel2ph, f0, volume, spk_mix)
|
178 |
-
|
179 |
-
torch.onnx.export(
|
180 |
-
self,
|
181 |
-
(hubert, mel2ph, f0, volume, spk_mix),
|
182 |
-
f"{project_name}_encoder.onnx",
|
183 |
-
input_names=["hubert", "mel2ph", "f0", "volume", "spk_mix"],
|
184 |
-
output_names=["mel_pred"],
|
185 |
-
dynamic_axes={
|
186 |
-
"hubert": [1],
|
187 |
-
"f0": [1],
|
188 |
-
"volume": [1],
|
189 |
-
"mel2ph": [1]
|
190 |
-
},
|
191 |
-
opset_version=16
|
192 |
-
)
|
193 |
-
|
194 |
-
condition = torch.randn(1,self.decoder.n_hidden,n_frames)
|
195 |
-
noise = torch.randn((1, 1, self.decoder.mel_bins, condition.shape[2]), dtype=torch.float32)
|
196 |
-
pndm_speedup = torch.LongTensor([100])
|
197 |
-
K_steps = torch.LongTensor([1000])
|
198 |
-
self.decoder = torch.jit.script(self.decoder)
|
199 |
-
self.decoder(condition, noise, pndm_speedup, K_steps)
|
200 |
-
|
201 |
-
torch.onnx.export(
|
202 |
-
self.decoder,
|
203 |
-
(condition, noise, pndm_speedup, K_steps),
|
204 |
-
f"{project_name}_diffusion.onnx",
|
205 |
-
input_names=["condition", "noise", "pndm_speedup", "K_steps"],
|
206 |
-
output_names=["mel"],
|
207 |
-
dynamic_axes={
|
208 |
-
"condition": [2],
|
209 |
-
"noise": [3],
|
210 |
-
},
|
211 |
-
opset_version=16
|
212 |
-
)
|
213 |
-
|
214 |
-
|
215 |
-
if __name__ == "__main__":
|
216 |
-
project_name = "dddsp"
|
217 |
-
model_path = f'{project_name}/model_500000.pt'
|
218 |
-
|
219 |
-
model, _ = load_model_vocoder(model_path)
|
220 |
-
|
221 |
-
# 分开Diffusion导出(需要使用MoeSS/MoeVoiceStudio或者自己编写Pndm/Dpm采样)
|
222 |
-
model.OnnxExport(project_name, export_encoder=True, export_denoise=True, export_pred=True, export_after=True)
|
223 |
-
|
224 |
-
# 合并Diffusion导出(Encoder和Diffusion分开,直接将Encoder的结果和初始噪声输入Diffusion即可)
|
225 |
-
# model.ExportOnnx(project_name)
|
226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/solver.py
DELETED
@@ -1,195 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import time
|
3 |
-
import numpy as np
|
4 |
-
import torch
|
5 |
-
import librosa
|
6 |
-
from diffusion.logger.saver import Saver
|
7 |
-
from diffusion.logger import utils
|
8 |
-
from torch import autocast
|
9 |
-
from torch.cuda.amp import GradScaler
|
10 |
-
|
11 |
-
def test(args, model, vocoder, loader_test, saver):
|
12 |
-
print(' [*] testing...')
|
13 |
-
model.eval()
|
14 |
-
|
15 |
-
# losses
|
16 |
-
test_loss = 0.
|
17 |
-
|
18 |
-
# intialization
|
19 |
-
num_batches = len(loader_test)
|
20 |
-
rtf_all = []
|
21 |
-
|
22 |
-
# run
|
23 |
-
with torch.no_grad():
|
24 |
-
for bidx, data in enumerate(loader_test):
|
25 |
-
fn = data['name'][0].split("/")[-1]
|
26 |
-
speaker = data['name'][0].split("/")[-2]
|
27 |
-
print('--------')
|
28 |
-
print('{}/{} - {}'.format(bidx, num_batches, fn))
|
29 |
-
|
30 |
-
# unpack data
|
31 |
-
for k in data.keys():
|
32 |
-
if not k.startswith('name'):
|
33 |
-
data[k] = data[k].to(args.device)
|
34 |
-
print('>>', data['name'][0])
|
35 |
-
|
36 |
-
# forward
|
37 |
-
st_time = time.time()
|
38 |
-
mel = model(
|
39 |
-
data['units'],
|
40 |
-
data['f0'],
|
41 |
-
data['volume'],
|
42 |
-
data['spk_id'],
|
43 |
-
gt_spec=None,
|
44 |
-
infer=True,
|
45 |
-
infer_speedup=args.infer.speedup,
|
46 |
-
method=args.infer.method)
|
47 |
-
signal = vocoder.infer(mel, data['f0'])
|
48 |
-
ed_time = time.time()
|
49 |
-
|
50 |
-
# RTF
|
51 |
-
run_time = ed_time - st_time
|
52 |
-
song_time = signal.shape[-1] / args.data.sampling_rate
|
53 |
-
rtf = run_time / song_time
|
54 |
-
print('RTF: {} | {} / {}'.format(rtf, run_time, song_time))
|
55 |
-
rtf_all.append(rtf)
|
56 |
-
|
57 |
-
# loss
|
58 |
-
for i in range(args.train.batch_size):
|
59 |
-
loss = model(
|
60 |
-
data['units'],
|
61 |
-
data['f0'],
|
62 |
-
data['volume'],
|
63 |
-
data['spk_id'],
|
64 |
-
gt_spec=data['mel'],
|
65 |
-
infer=False)
|
66 |
-
test_loss += loss.item()
|
67 |
-
|
68 |
-
# log mel
|
69 |
-
saver.log_spec(f"{speaker}_{fn}.wav", data['mel'], mel)
|
70 |
-
|
71 |
-
# log audi
|
72 |
-
path_audio = data['name_ext'][0]
|
73 |
-
audio, sr = librosa.load(path_audio, sr=args.data.sampling_rate)
|
74 |
-
if len(audio.shape) > 1:
|
75 |
-
audio = librosa.to_mono(audio)
|
76 |
-
audio = torch.from_numpy(audio).unsqueeze(0).to(signal)
|
77 |
-
saver.log_audio({f"{speaker}_{fn}_gt.wav": audio,f"{speaker}_{fn}_pred.wav": signal})
|
78 |
-
# report
|
79 |
-
test_loss /= args.train.batch_size
|
80 |
-
test_loss /= num_batches
|
81 |
-
|
82 |
-
# check
|
83 |
-
print(' [test_loss] test_loss:', test_loss)
|
84 |
-
print(' Real Time Factor', np.mean(rtf_all))
|
85 |
-
return test_loss
|
86 |
-
|
87 |
-
|
88 |
-
def train(args, initial_global_step, model, optimizer, scheduler, vocoder, loader_train, loader_test):
|
89 |
-
# saver
|
90 |
-
saver = Saver(args, initial_global_step=initial_global_step)
|
91 |
-
|
92 |
-
# model size
|
93 |
-
params_count = utils.get_network_paras_amount({'model': model})
|
94 |
-
saver.log_info('--- model size ---')
|
95 |
-
saver.log_info(params_count)
|
96 |
-
|
97 |
-
# run
|
98 |
-
num_batches = len(loader_train)
|
99 |
-
model.train()
|
100 |
-
saver.log_info('======= start training =======')
|
101 |
-
scaler = GradScaler()
|
102 |
-
if args.train.amp_dtype == 'fp32':
|
103 |
-
dtype = torch.float32
|
104 |
-
elif args.train.amp_dtype == 'fp16':
|
105 |
-
dtype = torch.float16
|
106 |
-
elif args.train.amp_dtype == 'bf16':
|
107 |
-
dtype = torch.bfloat16
|
108 |
-
else:
|
109 |
-
raise ValueError(' [x] Unknown amp_dtype: ' + args.train.amp_dtype)
|
110 |
-
saver.log_info("epoch|batch_idx/num_batches|output_dir|batch/s|lr|time|step")
|
111 |
-
for epoch in range(args.train.epochs):
|
112 |
-
for batch_idx, data in enumerate(loader_train):
|
113 |
-
saver.global_step_increment()
|
114 |
-
optimizer.zero_grad()
|
115 |
-
|
116 |
-
# unpack data
|
117 |
-
for k in data.keys():
|
118 |
-
if not k.startswith('name'):
|
119 |
-
data[k] = data[k].to(args.device)
|
120 |
-
|
121 |
-
# forward
|
122 |
-
if dtype == torch.float32:
|
123 |
-
loss = model(data['units'].float(), data['f0'], data['volume'], data['spk_id'],
|
124 |
-
aug_shift = data['aug_shift'], gt_spec=data['mel'].float(), infer=False)
|
125 |
-
else:
|
126 |
-
with autocast(device_type=args.device, dtype=dtype):
|
127 |
-
loss = model(data['units'], data['f0'], data['volume'], data['spk_id'],
|
128 |
-
aug_shift = data['aug_shift'], gt_spec=data['mel'], infer=False)
|
129 |
-
|
130 |
-
# handle nan loss
|
131 |
-
if torch.isnan(loss):
|
132 |
-
raise ValueError(' [x] nan loss ')
|
133 |
-
else:
|
134 |
-
# backpropagate
|
135 |
-
if dtype == torch.float32:
|
136 |
-
loss.backward()
|
137 |
-
optimizer.step()
|
138 |
-
else:
|
139 |
-
scaler.scale(loss).backward()
|
140 |
-
scaler.step(optimizer)
|
141 |
-
scaler.update()
|
142 |
-
scheduler.step()
|
143 |
-
|
144 |
-
# log loss
|
145 |
-
if saver.global_step % args.train.interval_log == 0:
|
146 |
-
current_lr = optimizer.param_groups[0]['lr']
|
147 |
-
saver.log_info(
|
148 |
-
'epoch: {} | {:3d}/{:3d} | {} | batch/s: {:.2f} | lr: {:.6} | loss: {:.3f} | time: {} | step: {}'.format(
|
149 |
-
epoch,
|
150 |
-
batch_idx,
|
151 |
-
num_batches,
|
152 |
-
args.env.expdir,
|
153 |
-
args.train.interval_log/saver.get_interval_time(),
|
154 |
-
current_lr,
|
155 |
-
loss.item(),
|
156 |
-
saver.get_total_time(),
|
157 |
-
saver.global_step
|
158 |
-
)
|
159 |
-
)
|
160 |
-
|
161 |
-
saver.log_value({
|
162 |
-
'train/loss': loss.item()
|
163 |
-
})
|
164 |
-
|
165 |
-
saver.log_value({
|
166 |
-
'train/lr': current_lr
|
167 |
-
})
|
168 |
-
|
169 |
-
# validation
|
170 |
-
if saver.global_step % args.train.interval_val == 0:
|
171 |
-
optimizer_save = optimizer if args.train.save_opt else None
|
172 |
-
|
173 |
-
# save latest
|
174 |
-
saver.save_model(model, optimizer_save, postfix=f'{saver.global_step}')
|
175 |
-
last_val_step = saver.global_step - args.train.interval_val
|
176 |
-
if last_val_step % args.train.interval_force_save != 0:
|
177 |
-
saver.delete_model(postfix=f'{last_val_step}')
|
178 |
-
|
179 |
-
# run testing set
|
180 |
-
test_loss = test(args, model, vocoder, loader_test, saver)
|
181 |
-
|
182 |
-
# log loss
|
183 |
-
saver.log_info(
|
184 |
-
' --- <validation> --- \nloss: {:.3f}. '.format(
|
185 |
-
test_loss,
|
186 |
-
)
|
187 |
-
)
|
188 |
-
|
189 |
-
saver.log_value({
|
190 |
-
'validation/loss': test_loss
|
191 |
-
})
|
192 |
-
|
193 |
-
model.train()
|
194 |
-
|
195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/unit2mel.py
DELETED
@@ -1,147 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import yaml
|
3 |
-
import torch
|
4 |
-
import torch.nn as nn
|
5 |
-
import numpy as np
|
6 |
-
from .diffusion import GaussianDiffusion
|
7 |
-
from .wavenet import WaveNet
|
8 |
-
from .vocoder import Vocoder
|
9 |
-
|
10 |
-
class DotDict(dict):
|
11 |
-
def __getattr__(*args):
|
12 |
-
val = dict.get(*args)
|
13 |
-
return DotDict(val) if type(val) is dict else val
|
14 |
-
|
15 |
-
__setattr__ = dict.__setitem__
|
16 |
-
__delattr__ = dict.__delitem__
|
17 |
-
|
18 |
-
|
19 |
-
def load_model_vocoder(
|
20 |
-
model_path,
|
21 |
-
device='cpu',
|
22 |
-
config_path = None
|
23 |
-
):
|
24 |
-
if config_path is None: config_file = os.path.join(os.path.split(model_path)[0], 'config.yaml')
|
25 |
-
else: config_file = config_path
|
26 |
-
|
27 |
-
with open(config_file, "r") as config:
|
28 |
-
args = yaml.safe_load(config)
|
29 |
-
args = DotDict(args)
|
30 |
-
|
31 |
-
# load vocoder
|
32 |
-
vocoder = Vocoder(args.vocoder.type, args.vocoder.ckpt, device=device)
|
33 |
-
|
34 |
-
# load model
|
35 |
-
model = Unit2Mel(
|
36 |
-
args.data.encoder_out_channels,
|
37 |
-
args.model.n_spk,
|
38 |
-
args.model.use_pitch_aug,
|
39 |
-
vocoder.dimension,
|
40 |
-
args.model.n_layers,
|
41 |
-
args.model.n_chans,
|
42 |
-
args.model.n_hidden)
|
43 |
-
|
44 |
-
print(' [Loading] ' + model_path)
|
45 |
-
ckpt = torch.load(model_path, map_location=torch.device(device))
|
46 |
-
model.to(device)
|
47 |
-
model.load_state_dict(ckpt['model'])
|
48 |
-
model.eval()
|
49 |
-
return model, vocoder, args
|
50 |
-
|
51 |
-
|
52 |
-
class Unit2Mel(nn.Module):
|
53 |
-
def __init__(
|
54 |
-
self,
|
55 |
-
input_channel,
|
56 |
-
n_spk,
|
57 |
-
use_pitch_aug=False,
|
58 |
-
out_dims=128,
|
59 |
-
n_layers=20,
|
60 |
-
n_chans=384,
|
61 |
-
n_hidden=256):
|
62 |
-
super().__init__()
|
63 |
-
self.unit_embed = nn.Linear(input_channel, n_hidden)
|
64 |
-
self.f0_embed = nn.Linear(1, n_hidden)
|
65 |
-
self.volume_embed = nn.Linear(1, n_hidden)
|
66 |
-
if use_pitch_aug:
|
67 |
-
self.aug_shift_embed = nn.Linear(1, n_hidden, bias=False)
|
68 |
-
else:
|
69 |
-
self.aug_shift_embed = None
|
70 |
-
self.n_spk = n_spk
|
71 |
-
if n_spk is not None and n_spk > 1:
|
72 |
-
self.spk_embed = nn.Embedding(n_spk, n_hidden)
|
73 |
-
|
74 |
-
self.n_hidden = n_hidden
|
75 |
-
# diffusion
|
76 |
-
self.decoder = GaussianDiffusion(WaveNet(out_dims, n_layers, n_chans, n_hidden), out_dims=out_dims)
|
77 |
-
self.input_channel = input_channel
|
78 |
-
|
79 |
-
def init_spkembed(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
|
80 |
-
gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
|
81 |
-
|
82 |
-
'''
|
83 |
-
input:
|
84 |
-
B x n_frames x n_unit
|
85 |
-
return:
|
86 |
-
dict of B x n_frames x feat
|
87 |
-
'''
|
88 |
-
x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
|
89 |
-
if self.n_spk is not None and self.n_spk > 1:
|
90 |
-
if spk_mix_dict is not None:
|
91 |
-
spk_embed_mix = torch.zeros((1,1,self.hidden_size))
|
92 |
-
for k, v in spk_mix_dict.items():
|
93 |
-
spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
|
94 |
-
spk_embeddd = self.spk_embed(spk_id_torch)
|
95 |
-
self.speaker_map[k] = spk_embeddd
|
96 |
-
spk_embed_mix = spk_embed_mix + v * spk_embeddd
|
97 |
-
x = x + spk_embed_mix
|
98 |
-
else:
|
99 |
-
x = x + self.spk_embed(spk_id - 1)
|
100 |
-
self.speaker_map = self.speaker_map.unsqueeze(0)
|
101 |
-
self.speaker_map = self.speaker_map.detach()
|
102 |
-
return x.transpose(1, 2)
|
103 |
-
|
104 |
-
def init_spkmix(self, n_spk):
|
105 |
-
self.speaker_map = torch.zeros((n_spk,1,1,self.n_hidden))
|
106 |
-
hubert_hidden_size = self.input_channel
|
107 |
-
n_frames = 10
|
108 |
-
hubert = torch.randn((1, n_frames, hubert_hidden_size))
|
109 |
-
mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
|
110 |
-
f0 = torch.randn((1, n_frames))
|
111 |
-
volume = torch.randn((1, n_frames))
|
112 |
-
spks = {}
|
113 |
-
for i in range(n_spk):
|
114 |
-
spks.update({i:1.0/float(self.n_spk)})
|
115 |
-
orgouttt = self.init_spkembed(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
|
116 |
-
|
117 |
-
def forward(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
|
118 |
-
gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
|
119 |
-
|
120 |
-
'''
|
121 |
-
input:
|
122 |
-
B x n_frames x n_unit
|
123 |
-
return:
|
124 |
-
dict of B x n_frames x feat
|
125 |
-
'''
|
126 |
-
|
127 |
-
x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
|
128 |
-
if self.n_spk is not None and self.n_spk > 1:
|
129 |
-
if spk_mix_dict is not None:
|
130 |
-
for k, v in spk_mix_dict.items():
|
131 |
-
spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
|
132 |
-
x = x + v * self.spk_embed(spk_id_torch)
|
133 |
-
else:
|
134 |
-
if spk_id.shape[1] > 1:
|
135 |
-
g = spk_id.reshape((spk_id.shape[0], spk_id.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
|
136 |
-
g = g * self.speaker_map # [N, S, B, 1, H]
|
137 |
-
g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
|
138 |
-
g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
|
139 |
-
x = x + g
|
140 |
-
else:
|
141 |
-
x = x + self.spk_embed(spk_id)
|
142 |
-
if self.aug_shift_embed is not None and aug_shift is not None:
|
143 |
-
x = x + self.aug_shift_embed(aug_shift / 5)
|
144 |
-
x = self.decoder(x, gt_spec=gt_spec, infer=infer, infer_speedup=infer_speedup, method=method, k_step=k_step, use_tqdm=use_tqdm)
|
145 |
-
|
146 |
-
return x
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/vocoder.py
DELETED
@@ -1,94 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
from vdecoder.nsf_hifigan.nvSTFT import STFT
|
3 |
-
from vdecoder.nsf_hifigan.models import load_model,load_config
|
4 |
-
from torchaudio.transforms import Resample
|
5 |
-
|
6 |
-
|
7 |
-
class Vocoder:
|
8 |
-
def __init__(self, vocoder_type, vocoder_ckpt, device = None):
|
9 |
-
if device is None:
|
10 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
11 |
-
self.device = device
|
12 |
-
|
13 |
-
if vocoder_type == 'nsf-hifigan':
|
14 |
-
self.vocoder = NsfHifiGAN(vocoder_ckpt, device = device)
|
15 |
-
elif vocoder_type == 'nsf-hifigan-log10':
|
16 |
-
self.vocoder = NsfHifiGANLog10(vocoder_ckpt, device = device)
|
17 |
-
else:
|
18 |
-
raise ValueError(f" [x] Unknown vocoder: {vocoder_type}")
|
19 |
-
|
20 |
-
self.resample_kernel = {}
|
21 |
-
self.vocoder_sample_rate = self.vocoder.sample_rate()
|
22 |
-
self.vocoder_hop_size = self.vocoder.hop_size()
|
23 |
-
self.dimension = self.vocoder.dimension()
|
24 |
-
|
25 |
-
def extract(self, audio, sample_rate, keyshift=0):
|
26 |
-
|
27 |
-
# resample
|
28 |
-
if sample_rate == self.vocoder_sample_rate:
|
29 |
-
audio_res = audio
|
30 |
-
else:
|
31 |
-
key_str = str(sample_rate)
|
32 |
-
if key_str not in self.resample_kernel:
|
33 |
-
self.resample_kernel[key_str] = Resample(sample_rate, self.vocoder_sample_rate, lowpass_filter_width = 128).to(self.device)
|
34 |
-
audio_res = self.resample_kernel[key_str](audio)
|
35 |
-
|
36 |
-
# extract
|
37 |
-
mel = self.vocoder.extract(audio_res, keyshift=keyshift) # B, n_frames, bins
|
38 |
-
return mel
|
39 |
-
|
40 |
-
def infer(self, mel, f0):
|
41 |
-
f0 = f0[:,:mel.size(1),0] # B, n_frames
|
42 |
-
audio = self.vocoder(mel, f0)
|
43 |
-
return audio
|
44 |
-
|
45 |
-
|
46 |
-
class NsfHifiGAN(torch.nn.Module):
|
47 |
-
def __init__(self, model_path, device=None):
|
48 |
-
super().__init__()
|
49 |
-
if device is None:
|
50 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
51 |
-
self.device = device
|
52 |
-
self.model_path = model_path
|
53 |
-
self.model = None
|
54 |
-
self.h = load_config(model_path)
|
55 |
-
self.stft = STFT(
|
56 |
-
self.h.sampling_rate,
|
57 |
-
self.h.num_mels,
|
58 |
-
self.h.n_fft,
|
59 |
-
self.h.win_size,
|
60 |
-
self.h.hop_size,
|
61 |
-
self.h.fmin,
|
62 |
-
self.h.fmax)
|
63 |
-
|
64 |
-
def sample_rate(self):
|
65 |
-
return self.h.sampling_rate
|
66 |
-
|
67 |
-
def hop_size(self):
|
68 |
-
return self.h.hop_size
|
69 |
-
|
70 |
-
def dimension(self):
|
71 |
-
return self.h.num_mels
|
72 |
-
|
73 |
-
def extract(self, audio, keyshift=0):
|
74 |
-
mel = self.stft.get_mel(audio, keyshift=keyshift).transpose(1, 2) # B, n_frames, bins
|
75 |
-
return mel
|
76 |
-
|
77 |
-
def forward(self, mel, f0):
|
78 |
-
if self.model is None:
|
79 |
-
print('| Load HifiGAN: ', self.model_path)
|
80 |
-
self.model, self.h = load_model(self.model_path, device=self.device)
|
81 |
-
with torch.no_grad():
|
82 |
-
c = mel.transpose(1, 2)
|
83 |
-
audio = self.model(c, f0)
|
84 |
-
return audio
|
85 |
-
|
86 |
-
class NsfHifiGANLog10(NsfHifiGAN):
|
87 |
-
def forward(self, mel, f0):
|
88 |
-
if self.model is None:
|
89 |
-
print('| Load HifiGAN: ', self.model_path)
|
90 |
-
self.model, self.h = load_model(self.model_path, device=self.device)
|
91 |
-
with torch.no_grad():
|
92 |
-
c = 0.434294 * mel.transpose(1, 2)
|
93 |
-
audio = self.model(c, f0)
|
94 |
-
return audio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
diffusion/wavenet.py
DELETED
@@ -1,108 +0,0 @@
|
|
1 |
-
import math
|
2 |
-
from math import sqrt
|
3 |
-
|
4 |
-
import torch
|
5 |
-
import torch.nn as nn
|
6 |
-
import torch.nn.functional as F
|
7 |
-
from torch.nn import Mish
|
8 |
-
|
9 |
-
|
10 |
-
class Conv1d(torch.nn.Conv1d):
|
11 |
-
def __init__(self, *args, **kwargs):
|
12 |
-
super().__init__(*args, **kwargs)
|
13 |
-
nn.init.kaiming_normal_(self.weight)
|
14 |
-
|
15 |
-
|
16 |
-
class SinusoidalPosEmb(nn.Module):
|
17 |
-
def __init__(self, dim):
|
18 |
-
super().__init__()
|
19 |
-
self.dim = dim
|
20 |
-
|
21 |
-
def forward(self, x):
|
22 |
-
device = x.device
|
23 |
-
half_dim = self.dim // 2
|
24 |
-
emb = math.log(10000) / (half_dim - 1)
|
25 |
-
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
|
26 |
-
emb = x[:, None] * emb[None, :]
|
27 |
-
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
|
28 |
-
return emb
|
29 |
-
|
30 |
-
|
31 |
-
class ResidualBlock(nn.Module):
|
32 |
-
def __init__(self, encoder_hidden, residual_channels, dilation):
|
33 |
-
super().__init__()
|
34 |
-
self.residual_channels = residual_channels
|
35 |
-
self.dilated_conv = nn.Conv1d(
|
36 |
-
residual_channels,
|
37 |
-
2 * residual_channels,
|
38 |
-
kernel_size=3,
|
39 |
-
padding=dilation,
|
40 |
-
dilation=dilation
|
41 |
-
)
|
42 |
-
self.diffusion_projection = nn.Linear(residual_channels, residual_channels)
|
43 |
-
self.conditioner_projection = nn.Conv1d(encoder_hidden, 2 * residual_channels, 1)
|
44 |
-
self.output_projection = nn.Conv1d(residual_channels, 2 * residual_channels, 1)
|
45 |
-
|
46 |
-
def forward(self, x, conditioner, diffusion_step):
|
47 |
-
diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
|
48 |
-
conditioner = self.conditioner_projection(conditioner)
|
49 |
-
y = x + diffusion_step
|
50 |
-
|
51 |
-
y = self.dilated_conv(y) + conditioner
|
52 |
-
|
53 |
-
# Using torch.split instead of torch.chunk to avoid using onnx::Slice
|
54 |
-
gate, filter = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
|
55 |
-
y = torch.sigmoid(gate) * torch.tanh(filter)
|
56 |
-
|
57 |
-
y = self.output_projection(y)
|
58 |
-
|
59 |
-
# Using torch.split instead of torch.chunk to avoid using onnx::Slice
|
60 |
-
residual, skip = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
|
61 |
-
return (x + residual) / math.sqrt(2.0), skip
|
62 |
-
|
63 |
-
|
64 |
-
class WaveNet(nn.Module):
|
65 |
-
def __init__(self, in_dims=128, n_layers=20, n_chans=384, n_hidden=256):
|
66 |
-
super().__init__()
|
67 |
-
self.input_projection = Conv1d(in_dims, n_chans, 1)
|
68 |
-
self.diffusion_embedding = SinusoidalPosEmb(n_chans)
|
69 |
-
self.mlp = nn.Sequential(
|
70 |
-
nn.Linear(n_chans, n_chans * 4),
|
71 |
-
Mish(),
|
72 |
-
nn.Linear(n_chans * 4, n_chans)
|
73 |
-
)
|
74 |
-
self.residual_layers = nn.ModuleList([
|
75 |
-
ResidualBlock(
|
76 |
-
encoder_hidden=n_hidden,
|
77 |
-
residual_channels=n_chans,
|
78 |
-
dilation=1
|
79 |
-
)
|
80 |
-
for i in range(n_layers)
|
81 |
-
])
|
82 |
-
self.skip_projection = Conv1d(n_chans, n_chans, 1)
|
83 |
-
self.output_projection = Conv1d(n_chans, in_dims, 1)
|
84 |
-
nn.init.zeros_(self.output_projection.weight)
|
85 |
-
|
86 |
-
def forward(self, spec, diffusion_step, cond):
|
87 |
-
"""
|
88 |
-
:param spec: [B, 1, M, T]
|
89 |
-
:param diffusion_step: [B, 1]
|
90 |
-
:param cond: [B, M, T]
|
91 |
-
:return:
|
92 |
-
"""
|
93 |
-
x = spec.squeeze(1)
|
94 |
-
x = self.input_projection(x) # [B, residual_channel, T]
|
95 |
-
|
96 |
-
x = F.relu(x)
|
97 |
-
diffusion_step = self.diffusion_embedding(diffusion_step)
|
98 |
-
diffusion_step = self.mlp(diffusion_step)
|
99 |
-
skip = []
|
100 |
-
for layer in self.residual_layers:
|
101 |
-
x, skip_connection = layer(x, cond, diffusion_step)
|
102 |
-
skip.append(skip_connection)
|
103 |
-
|
104 |
-
x = torch.sum(torch.stack(skip), dim=0) / sqrt(len(self.residual_layers))
|
105 |
-
x = self.skip_projection(x)
|
106 |
-
x = F.relu(x)
|
107 |
-
x = self.output_projection(x) # [B, mel_bins, T]
|
108 |
-
return x[:, None, :, :]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
inference/infer_tool.py
CHANGED
@@ -1,27 +1,24 @@
|
|
|
|
1 |
import hashlib
|
2 |
import io
|
3 |
import json
|
4 |
import logging
|
5 |
import os
|
|
|
6 |
import time
|
7 |
from pathlib import Path
|
8 |
-
from inference import slicer
|
9 |
-
import gc
|
10 |
|
11 |
import librosa
|
12 |
import numpy as np
|
|
|
13 |
# import onnxruntime
|
14 |
import soundfile
|
15 |
import torch
|
16 |
import torchaudio
|
17 |
|
18 |
-
import cluster
|
19 |
import utils
|
|
|
20 |
from models import SynthesizerTrn
|
21 |
-
import pickle
|
22 |
-
|
23 |
-
from diffusion.unit2mel import load_model_vocoder
|
24 |
-
import yaml
|
25 |
|
26 |
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
27 |
|
@@ -142,53 +139,26 @@ class Svc(object):
|
|
142 |
self.dev = torch.device(device)
|
143 |
self.net_g_ms = None
|
144 |
if not self.only_diffusion:
|
145 |
-
self.hps_ms = utils.get_hparams_from_file(config_path)
|
146 |
self.target_sample = self.hps_ms.data.sampling_rate
|
147 |
self.hop_size = self.hps_ms.data.hop_length
|
148 |
self.spk2id = self.hps_ms.spk
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
self.vol_embedding = False
|
153 |
-
try:
|
154 |
-
self.speech_encoder = self.hps_ms.model.speech_encoder
|
155 |
-
except Exception as e:
|
156 |
-
self.speech_encoder = 'vec768l12'
|
157 |
|
158 |
self.nsf_hifigan_enhance = nsf_hifigan_enhance
|
159 |
-
if self.shallow_diffusion or self.only_diffusion:
|
160 |
-
if os.path.exists(diffusion_model_path) and os.path.exists(diffusion_model_path):
|
161 |
-
self.diffusion_model, self.vocoder, self.diffusion_args = load_model_vocoder(diffusion_model_path,
|
162 |
-
self.dev,
|
163 |
-
config_path=diffusion_config_path)
|
164 |
-
if self.only_diffusion:
|
165 |
-
self.target_sample = self.diffusion_args.data.sampling_rate
|
166 |
-
self.hop_size = self.diffusion_args.data.block_size
|
167 |
-
self.spk2id = self.diffusion_args.spk
|
168 |
-
self.speech_encoder = self.diffusion_args.data.encoder
|
169 |
-
if spk_mix_enable:
|
170 |
-
self.diffusion_model.init_spkmix(len(self.spk2id))
|
171 |
-
else:
|
172 |
-
print("No diffusion model or config found. Shallow diffusion mode will False")
|
173 |
-
self.shallow_diffusion = self.only_diffusion = False
|
174 |
|
175 |
# load hubert and model
|
176 |
self.load_model(spk_mix_enable)
|
177 |
-
# self.hubert_model = utils.get_speech_encoder(self.speech_encoder, device=self.dev)
|
178 |
self.volume_extractor = utils.Volume_Extractor(self.hop_size)
|
179 |
|
180 |
-
if os.path.exists(cluster_model_path):
|
181 |
-
if self.feature_retrieval:
|
182 |
-
with open(cluster_model_path, "rb") as f:
|
183 |
-
self.cluster_model = pickle.load(f)
|
184 |
-
self.big_npy = None
|
185 |
-
self.now_spk_id = -1
|
186 |
-
else:
|
187 |
-
self.cluster_model = cluster.get_cluster_model(cluster_model_path)
|
188 |
-
else:
|
189 |
-
self.feature_retrieval = False
|
190 |
|
191 |
-
|
|
|
|
|
|
|
192 |
if self.nsf_hifigan_enhance:
|
193 |
from modules.enhancer import Enhancer
|
194 |
self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model', device=self.dev)
|
@@ -200,6 +170,7 @@ class Svc(object):
|
|
200 |
self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
|
201 |
**self.hps_ms.model)
|
202 |
_ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
|
|
|
203 |
if "half" in self.net_g_path and torch.cuda.is_available():
|
204 |
_ = self.net_g_ms.half().eval().to(self.dev)
|
205 |
else:
|
@@ -209,11 +180,13 @@ class Svc(object):
|
|
209 |
|
210 |
def get_unit_f0(self, wav, tran, cluster_infer_ratio, speaker, f0_filter, f0_predictor, cr_threshold=0.05):
|
211 |
|
212 |
-
|
213 |
-
|
214 |
-
|
|
|
|
|
|
|
215 |
|
216 |
-
f0, uv = f0_predictor_object.compute_f0_uv(wav)
|
217 |
if f0_filter and sum(f0) == 0:
|
218 |
raise F0FilterException("No voice detected")
|
219 |
f0 = torch.FloatTensor(f0).to(self.dev)
|
@@ -223,36 +196,13 @@ class Svc(object):
|
|
223 |
f0 = f0.unsqueeze(0)
|
224 |
uv = uv.unsqueeze(0)
|
225 |
|
226 |
-
|
227 |
-
|
|
|
|
|
|
|
228 |
c = self.hubert_model.encoder(wav16k)
|
229 |
-
c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
|
230 |
-
|
231 |
-
if cluster_infer_ratio != 0:
|
232 |
-
if self.feature_retrieval:
|
233 |
-
speaker_id = self.spk2id.get(speaker)
|
234 |
-
if speaker_id is None:
|
235 |
-
raise RuntimeError("The name you entered is not in the speaker list!")
|
236 |
-
if not speaker_id and type(speaker) is int:
|
237 |
-
if len(self.spk2id.__dict__) >= speaker:
|
238 |
-
speaker_id = speaker
|
239 |
-
feature_index = self.cluster_model[speaker_id]
|
240 |
-
feat_np = c.transpose(0, 1).cpu().numpy()
|
241 |
-
if self.big_npy is None or self.now_spk_id != speaker_id:
|
242 |
-
self.big_npy = feature_index.reconstruct_n(0, feature_index.ntotal)
|
243 |
-
self.now_spk_id = speaker_id
|
244 |
-
print("starting feature retrieval...")
|
245 |
-
score, ix = feature_index.search(feat_np, k=8)
|
246 |
-
weight = np.square(1 / score)
|
247 |
-
weight /= weight.sum(axis=1, keepdims=True)
|
248 |
-
npy = np.sum(self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
249 |
-
c = cluster_infer_ratio * npy + (1 - cluster_infer_ratio) * feat_np
|
250 |
-
c = torch.FloatTensor(c).to(self.dev).transpose(0, 1)
|
251 |
-
print("end feature retrieval...")
|
252 |
-
else:
|
253 |
-
cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T
|
254 |
-
cluster_c = torch.FloatTensor(cluster_c).to(self.dev)
|
255 |
-
c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c
|
256 |
|
257 |
c = c.unsqueeze(0)
|
258 |
return c, f0, uv
|
@@ -271,7 +221,11 @@ class Svc(object):
|
|
271 |
second_encoding=False,
|
272 |
loudness_envelope_adjustment=1
|
273 |
):
|
274 |
-
|
|
|
|
|
|
|
|
|
275 |
if spk_mix:
|
276 |
c, f0, uv = self.get_unit_f0(wav, tran, 0, None, f0_filter, f0_predictor, cr_threshold=cr_threshold)
|
277 |
n_frames = f0.size(1)
|
@@ -287,8 +241,9 @@ class Svc(object):
|
|
287 |
c, f0, uv = self.get_unit_f0(wav, tran, cluster_infer_ratio, speaker, f0_filter, f0_predictor,
|
288 |
cr_threshold=cr_threshold)
|
289 |
n_frames = f0.size(1)
|
290 |
-
|
291 |
-
|
|
|
292 |
with torch.no_grad():
|
293 |
start = time.time()
|
294 |
vol = None
|
@@ -302,17 +257,22 @@ class Svc(object):
|
|
302 |
else:
|
303 |
audio = torch.FloatTensor(wav).to(self.dev)
|
304 |
audio_mel = None
|
|
|
|
|
|
|
|
|
305 |
if self.only_diffusion or self.shallow_diffusion:
|
306 |
-
vol = self.volume_extractor.extract(audio[None, :])[None, :, None].to(self.dev) if vol
|
307 |
:,
|
308 |
:,
|
309 |
None]
|
310 |
if self.shallow_diffusion and second_encoding:
|
311 |
-
|
312 |
-
|
313 |
-
|
|
|
314 |
c = self.hubert_model.encoder(audio16k)
|
315 |
-
c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
|
316 |
f0 = f0[:, :, None]
|
317 |
c = c.transpose(-1, -2)
|
318 |
audio_mel = self.diffusion_model(
|
@@ -461,7 +421,8 @@ class Svc(object):
|
|
461 |
datas = [data]
|
462 |
for k, dat in enumerate(datas):
|
463 |
per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds != 0 else length
|
464 |
-
if clip_seconds != 0:
|
|
|
465 |
# padd
|
466 |
pad_len = int(audio_sr * pad_seconds)
|
467 |
dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
|
@@ -497,51 +458,3 @@ class Svc(object):
|
|
497 |
return np.array(audio)
|
498 |
|
499 |
|
500 |
-
class RealTimeVC:
|
501 |
-
def __init__(self):
|
502 |
-
self.last_chunk = None
|
503 |
-
self.last_o = None
|
504 |
-
self.chunk_len = 16000 # chunk length
|
505 |
-
self.pre_len = 3840 # cross fade length, multiples of 640
|
506 |
-
|
507 |
-
# Input and output are 1-dimensional numpy waveform arrays
|
508 |
-
|
509 |
-
def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path,
|
510 |
-
cluster_infer_ratio=0,
|
511 |
-
auto_predict_f0=False,
|
512 |
-
noice_scale=0.4,
|
513 |
-
f0_filter=False):
|
514 |
-
|
515 |
-
import maad
|
516 |
-
audio, sr = torchaudio.load(input_wav_path)
|
517 |
-
audio = audio.cpu().numpy()[0]
|
518 |
-
temp_wav = io.BytesIO()
|
519 |
-
if self.last_chunk is None:
|
520 |
-
input_wav_path.seek(0)
|
521 |
-
|
522 |
-
audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path,
|
523 |
-
cluster_infer_ratio=cluster_infer_ratio,
|
524 |
-
auto_predict_f0=auto_predict_f0,
|
525 |
-
noice_scale=noice_scale,
|
526 |
-
f0_filter=f0_filter)
|
527 |
-
|
528 |
-
audio = audio.cpu().numpy()
|
529 |
-
self.last_chunk = audio[-self.pre_len:]
|
530 |
-
self.last_o = audio
|
531 |
-
return audio[-self.chunk_len:]
|
532 |
-
else:
|
533 |
-
audio = np.concatenate([self.last_chunk, audio])
|
534 |
-
soundfile.write(temp_wav, audio, sr, format="wav")
|
535 |
-
temp_wav.seek(0)
|
536 |
-
|
537 |
-
audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav,
|
538 |
-
cluster_infer_ratio=cluster_infer_ratio,
|
539 |
-
auto_predict_f0=auto_predict_f0,
|
540 |
-
noice_scale=noice_scale,
|
541 |
-
f0_filter=f0_filter)
|
542 |
-
|
543 |
-
audio = audio.cpu().numpy()
|
544 |
-
ret = maad.util.crossfade(self.last_o, audio, self.pre_len)
|
545 |
-
self.last_chunk = audio[-self.pre_len:]
|
546 |
-
self.last_o = audio
|
547 |
-
return ret[self.chunk_len:2 * self.chunk_len]
|
|
|
1 |
+
import gc
|
2 |
import hashlib
|
3 |
import io
|
4 |
import json
|
5 |
import logging
|
6 |
import os
|
7 |
+
import pickle
|
8 |
import time
|
9 |
from pathlib import Path
|
|
|
|
|
10 |
|
11 |
import librosa
|
12 |
import numpy as np
|
13 |
+
|
14 |
# import onnxruntime
|
15 |
import soundfile
|
16 |
import torch
|
17 |
import torchaudio
|
18 |
|
|
|
19 |
import utils
|
20 |
+
from inference import slicer
|
21 |
from models import SynthesizerTrn
|
|
|
|
|
|
|
|
|
22 |
|
23 |
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
24 |
|
|
|
139 |
self.dev = torch.device(device)
|
140 |
self.net_g_ms = None
|
141 |
if not self.only_diffusion:
|
142 |
+
self.hps_ms = utils.get_hparams_from_file(config_path, True)
|
143 |
self.target_sample = self.hps_ms.data.sampling_rate
|
144 |
self.hop_size = self.hps_ms.data.hop_length
|
145 |
self.spk2id = self.hps_ms.spk
|
146 |
+
self.unit_interpolate_mode = self.hps_ms.data.unit_interpolate_mode if self.hps_ms.data.unit_interpolate_mode is not None else 'left'
|
147 |
+
self.vol_embedding = self.hps_ms.model.vol_embedding if self.hps_ms.model.vol_embedding is not None else False
|
148 |
+
self.speech_encoder = self.hps_ms.model.speech_encoder if self.hps_ms.model.speech_encoder is not None else 'vec768l12'
|
|
|
|
|
|
|
|
|
|
|
149 |
|
150 |
self.nsf_hifigan_enhance = nsf_hifigan_enhance
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
# load hubert and model
|
153 |
self.load_model(spk_mix_enable)
|
154 |
+
# self.hubert_model = utils.get_speech_encoder(self.speech_encoder, device=self.dev)
|
155 |
self.volume_extractor = utils.Volume_Extractor(self.hop_size)
|
156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
+
self.feature_retrieval = False
|
159 |
+
|
160 |
+
if self.shallow_diffusion:
|
161 |
+
self.nsf_hifigan_enhance = False
|
162 |
if self.nsf_hifigan_enhance:
|
163 |
from modules.enhancer import Enhancer
|
164 |
self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model', device=self.dev)
|
|
|
170 |
self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
|
171 |
**self.hps_ms.model)
|
172 |
_ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
|
173 |
+
self.dtype = list(self.net_g_ms.parameters())[0].dtype
|
174 |
if "half" in self.net_g_path and torch.cuda.is_available():
|
175 |
_ = self.net_g_ms.half().eval().to(self.dev)
|
176 |
else:
|
|
|
180 |
|
181 |
def get_unit_f0(self, wav, tran, cluster_infer_ratio, speaker, f0_filter, f0_predictor, cr_threshold=0.05):
|
182 |
|
183 |
+
if not hasattr(self,
|
184 |
+
"f0_predictor_object") or self.f0_predictor_object is None or f0_predictor != self.f0_predictor_object.name:
|
185 |
+
self.f0_predictor_object = utils.get_f0_predictor(f0_predictor, hop_length=self.hop_size,
|
186 |
+
sampling_rate=self.target_sample, device=self.dev,
|
187 |
+
threshold=cr_threshold)
|
188 |
+
f0, uv = self.f0_predictor_object.compute_f0_uv(wav)
|
189 |
|
|
|
190 |
if f0_filter and sum(f0) == 0:
|
191 |
raise F0FilterException("No voice detected")
|
192 |
f0 = torch.FloatTensor(f0).to(self.dev)
|
|
|
196 |
f0 = f0.unsqueeze(0)
|
197 |
uv = uv.unsqueeze(0)
|
198 |
|
199 |
+
wav = torch.from_numpy(wav).to(self.dev)
|
200 |
+
if not hasattr(self, "audio16k_resample_transform"):
|
201 |
+
self.audio16k_resample_transform = torchaudio.transforms.Resample(self.target_sample, 16000).to(self.dev)
|
202 |
+
wav16k = self.audio16k_resample_transform(wav[None, :])[0]
|
203 |
+
|
204 |
c = self.hubert_model.encoder(wav16k)
|
205 |
+
c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1], self.unit_interpolate_mode)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
c = c.unsqueeze(0)
|
208 |
return c, f0, uv
|
|
|
221 |
second_encoding=False,
|
222 |
loudness_envelope_adjustment=1
|
223 |
):
|
224 |
+
torchaudio.set_audio_backend("soundfile")
|
225 |
+
wav, sr = torchaudio.load(raw_path)
|
226 |
+
if not hasattr(self, "audio_resample_transform") or self.audio16k_resample_transform.orig_freq != sr:
|
227 |
+
self.audio_resample_transform = torchaudio.transforms.Resample(sr, self.target_sample)
|
228 |
+
wav = self.audio_resample_transform(wav).numpy()[0]
|
229 |
if spk_mix:
|
230 |
c, f0, uv = self.get_unit_f0(wav, tran, 0, None, f0_filter, f0_predictor, cr_threshold=cr_threshold)
|
231 |
n_frames = f0.size(1)
|
|
|
241 |
c, f0, uv = self.get_unit_f0(wav, tran, cluster_infer_ratio, speaker, f0_filter, f0_predictor,
|
242 |
cr_threshold=cr_threshold)
|
243 |
n_frames = f0.size(1)
|
244 |
+
c = c.to(self.dtype)
|
245 |
+
f0 = f0.to(self.dtype)
|
246 |
+
uv = uv.to(self.dtype)
|
247 |
with torch.no_grad():
|
248 |
start = time.time()
|
249 |
vol = None
|
|
|
257 |
else:
|
258 |
audio = torch.FloatTensor(wav).to(self.dev)
|
259 |
audio_mel = None
|
260 |
+
if self.dtype != torch.float32:
|
261 |
+
c = c.to(torch.float32)
|
262 |
+
f0 = f0.to(torch.float32)
|
263 |
+
uv = uv.to(torch.float32)
|
264 |
if self.only_diffusion or self.shallow_diffusion:
|
265 |
+
vol = self.volume_extractor.extract(audio[None, :])[None, :, None].to(self.dev) if vol is None else vol[
|
266 |
:,
|
267 |
:,
|
268 |
None]
|
269 |
if self.shallow_diffusion and second_encoding:
|
270 |
+
if not hasattr(self, "audio16k_resample_transform"):
|
271 |
+
self.audio16k_resample_transform = torchaudio.transforms.Resample(self.target_sample, 16000).to(
|
272 |
+
self.dev)
|
273 |
+
audio16k = self.audio16k_resample_transform(audio[None, :])[0]
|
274 |
c = self.hubert_model.encoder(audio16k)
|
275 |
+
c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1], self.unit_interpolate_mode)
|
276 |
f0 = f0[:, :, None]
|
277 |
c = c.transpose(-1, -2)
|
278 |
audio_mel = self.diffusion_model(
|
|
|
421 |
datas = [data]
|
422 |
for k, dat in enumerate(datas):
|
423 |
per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds != 0 else length
|
424 |
+
if clip_seconds != 0:
|
425 |
+
print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
|
426 |
# padd
|
427 |
pad_len = int(audio_sr * pad_seconds)
|
428 |
dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
|
|
|
458 |
return np.array(audio)
|
459 |
|
460 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
inference/infer_tool_grad.py
CHANGED
@@ -1,22 +1,18 @@
|
|
1 |
-
import
|
2 |
-
import json
|
3 |
import logging
|
4 |
import os
|
5 |
-
|
6 |
-
from pathlib import Path
|
7 |
-
import io
|
8 |
import librosa
|
9 |
-
import maad
|
10 |
import numpy as np
|
11 |
-
from inference import slicer
|
12 |
import parselmouth
|
13 |
import soundfile
|
14 |
import torch
|
15 |
import torchaudio
|
16 |
|
17 |
-
from hubert import hubert_model
|
18 |
import utils
|
|
|
19 |
from models import SynthesizerTrn
|
|
|
20 |
logging.getLogger('numba').setLevel(logging.WARNING)
|
21 |
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
22 |
|
@@ -93,7 +89,7 @@ class VitsSvc(object):
|
|
93 |
def set_device(self, device):
|
94 |
self.device = torch.device(device)
|
95 |
self.hubert_soft.to(self.device)
|
96 |
-
if self.SVCVITS
|
97 |
self.SVCVITS.to(self.device)
|
98 |
|
99 |
def loadCheckpoint(self, path):
|
|
|
1 |
+
import io
|
|
|
2 |
import logging
|
3 |
import os
|
4 |
+
|
|
|
|
|
5 |
import librosa
|
|
|
6 |
import numpy as np
|
|
|
7 |
import parselmouth
|
8 |
import soundfile
|
9 |
import torch
|
10 |
import torchaudio
|
11 |
|
|
|
12 |
import utils
|
13 |
+
from inference import slicer
|
14 |
from models import SynthesizerTrn
|
15 |
+
|
16 |
logging.getLogger('numba').setLevel(logging.WARNING)
|
17 |
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
18 |
|
|
|
89 |
def set_device(self, device):
|
90 |
self.device = torch.device(device)
|
91 |
self.hubert_soft.to(self.device)
|
92 |
+
if self.SVCVITS is not None:
|
93 |
self.SVCVITS.to(self.device)
|
94 |
|
95 |
def loadCheckpoint(self, path):
|
inference/slicer.py
CHANGED
@@ -117,8 +117,8 @@ class Slicer:
|
|
117 |
return chunk_dict
|
118 |
|
119 |
|
120 |
-
def cut(
|
121 |
-
audio, sr = librosa.load(
|
122 |
slicer = Slicer(
|
123 |
sr=sr,
|
124 |
threshold=db_thresh,
|
|
|
117 |
return chunk_dict
|
118 |
|
119 |
|
120 |
+
def cut(audio_path, db_thresh=-30, min_len=5000):
|
121 |
+
audio, sr = librosa.load(audio_path, sr=None)
|
122 |
slicer = Slicer(
|
123 |
sr=sr,
|
124 |
threshold=db_thresh,
|
inference_main.py
DELETED
@@ -1,181 +0,0 @@
|
|
1 |
-
import io
|
2 |
-
import logging
|
3 |
-
import time
|
4 |
-
from pathlib import Path
|
5 |
-
from spkmix import spk_mix_map
|
6 |
-
import librosa
|
7 |
-
import matplotlib.pyplot as plt
|
8 |
-
import numpy as np
|
9 |
-
import soundfile
|
10 |
-
from inference import infer_tool
|
11 |
-
from inference import slicer
|
12 |
-
from inference.infer_tool import Svc
|
13 |
-
|
14 |
-
logging.getLogger('numba').setLevel(logging.WARNING)
|
15 |
-
chunks_dict = infer_tool.read_temp("inference/chunks_temp.json")
|
16 |
-
|
17 |
-
|
18 |
-
def main():
|
19 |
-
import argparse
|
20 |
-
|
21 |
-
parser = argparse.ArgumentParser(description='sovits4 inference')
|
22 |
-
|
23 |
-
# 一定要设置的部分
|
24 |
-
parser.add_argument('-m', '--model_path', type=str, default="logs/44k/", help='模型路径')
|
25 |
-
parser.add_argument('-c', '--config_path', type=str, default="configs/", help='配置文件路径')
|
26 |
-
parser.add_argument('-cl', '--clip', type=float, default=0, help='音频强制切片,默认0为自动切片,单位为秒/s')
|
27 |
-
parser.add_argument('-n', '--clean_names', type=str, nargs='+', default=["test.wav"],
|
28 |
-
help='wav文件名列表,放在raw文件夹下')
|
29 |
-
parser.add_argument('-t', '--trans', type=int, nargs='+', default=[0], help='音高调整,支持正负(半音)')
|
30 |
-
parser.add_argument('-s', '--spk_list', type=str, nargs='+', default=['buyizi'], help='合成目标说话人名称')
|
31 |
-
|
32 |
-
# 可选项部分
|
33 |
-
parser.add_argument('-a', '--auto_predict_f0', action='store_true', default=False,
|
34 |
-
help='语音转换自动预测音高,转换歌声时不要打开这个会严重跑调')
|
35 |
-
parser.add_argument('-cm', '--cluster_model_path', type=str, default="logs/44k/kmeans_10000.pt",
|
36 |
-
help='聚类模型或特征检索索引路径,如果没有训练聚类或特征检索则随便填')
|
37 |
-
parser.add_argument('-cr', '--cluster_infer_ratio', type=float, default=0,
|
38 |
-
help='聚类方案或特征检索占比,范围0-1,若没有训练聚类模型或特征检索则默认0即可')
|
39 |
-
parser.add_argument('-lg', '--linear_gradient', type=float, default=0,
|
40 |
-
help='两段音频切片的交叉淡入长度,如果强制切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,单位为秒')
|
41 |
-
parser.add_argument('-f0p', '--f0_predictor', type=str, default="harvest",
|
42 |
-
help='选择F0预测器,可选择crepe,pm,dio,harvest,默认为pm(注意:crepe为原F0使用均值滤波器)')
|
43 |
-
parser.add_argument('-eh', '--enhance', action='store_true', default=False,
|
44 |
-
help='是否使用NSF_HIFIGAN增强器,该选项对部分训练集少的模型有一定的音质增强效果,但是对训练好的模型有反面效果,默认关闭')
|
45 |
-
parser.add_argument('-shd', '--shallow_diffusion', action='store_true', default=False,
|
46 |
-
help='是否使用浅层扩散,使用后可解决一部分电音问题,默认关闭,该选项打开时,NSF_HIFIGAN增强器将会被禁止')
|
47 |
-
parser.add_argument('-usm', '--use_spk_mix', action='store_true', default=False, help='是否使用角色融合')
|
48 |
-
parser.add_argument('-lea', '--loudness_envelope_adjustment', type=float, default=1,
|
49 |
-
help='输入源响度包络替换输出响度包络融合比例,越靠近1越使用输出响度包络')
|
50 |
-
parser.add_argument('-fr', '--feature_retrieval', action='store_true', default=False,
|
51 |
-
help='是否使用特征检索,如果使用聚类模型将被禁用,且cm与cr参数将会变成特征检索的索引路径与混合比例')
|
52 |
-
|
53 |
-
# 浅扩散设置
|
54 |
-
parser.add_argument('-dm', '--diffusion_model_path', type=str, default="logs/44k/diffusion/model_0.pt",
|
55 |
-
help='扩散模型路径')
|
56 |
-
parser.add_argument('-dc', '--diffusion_config_path', type=str, default="logs/44k/diffusion/config.yaml",
|
57 |
-
help='扩散模型配置文件路径')
|
58 |
-
parser.add_argument('-ks', '--k_step', type=int, default=100, help='扩散步数,越大越接近扩散模型的结果,默认100')
|
59 |
-
parser.add_argument('-se', '--second_encoding', action='store_true', default=False,
|
60 |
-
help='二次编码,浅扩散前会对原始音频进行二次编码,玄学选项,有时候效果好,有时候效果差')
|
61 |
-
parser.add_argument('-od', '--only_diffusion', action='store_true', default=False,
|
62 |
-
help='纯扩散模式,该模式不会加载sovits模型,以扩散模型推理')
|
63 |
-
|
64 |
-
# 不用动的部分
|
65 |
-
parser.add_argument('-sd', '--slice_db', type=int, default=-40,
|
66 |
-
help='默认-40,嘈杂的音频可以-30,干声保留呼吸可以-50')
|
67 |
-
parser.add_argument('-d', '--device', type=str, default=None, help='推理设备,None则为自动选择cpu和gpu')
|
68 |
-
parser.add_argument('-ns', '--noice_scale', type=float, default=0.4, help='噪音级别,会影响咬字和音质,较为玄学')
|
69 |
-
parser.add_argument('-p', '--pad_seconds', type=float, default=0.5,
|
70 |
-
help='推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现')
|
71 |
-
parser.add_argument('-wf', '--wav_format', type=str, default='flac', help='音频输出格式')
|
72 |
-
parser.add_argument('-lgr', '--linear_gradient_retain', type=float, default=0.75,
|
73 |
-
help='自动音频切片后,需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例,范围0-1,左开右闭')
|
74 |
-
parser.add_argument('-eak', '--enhancer_adaptive_key', type=int, default=0,
|
75 |
-
help='使增强器适应更高的音域(单位为半音数)|默认为0')
|
76 |
-
parser.add_argument('-ft', '--f0_filter_threshold', type=float, default=0.05,
|
77 |
-
help='F0过滤阈值,只有使用crepe时有效. 数值范围从0-1. 降低该值可减少跑调概率,但会增加哑音')
|
78 |
-
|
79 |
-
def preprocess_args(args1):
|
80 |
-
spk1 = args1.spk_list[0]
|
81 |
-
args1.model_path += f"{spk1}.pth"
|
82 |
-
args1.config_path += f"config_{spk1}.json"
|
83 |
-
args1.clip = 30
|
84 |
-
|
85 |
-
if spk1 == 'tomori':
|
86 |
-
args1.feature_retrieval = True
|
87 |
-
args1.cluster_model_path = "logs/44k/tomori_index.pkl"
|
88 |
-
args1.cluster_infer_ratio = 0.5
|
89 |
-
args1.f0_predictor = 'crepe'
|
90 |
-
|
91 |
-
return args1
|
92 |
-
|
93 |
-
args = parser.parse_args()
|
94 |
-
args = preprocess_args(args)
|
95 |
-
|
96 |
-
clean_names = args.clean_names
|
97 |
-
trans = args.trans
|
98 |
-
spk_list = args.spk_list
|
99 |
-
slice_db = args.slice_db
|
100 |
-
wav_format = args.wav_format
|
101 |
-
auto_predict_f0 = args.auto_predict_f0
|
102 |
-
cluster_infer_ratio = args.cluster_infer_ratio
|
103 |
-
noice_scale = args.noice_scale
|
104 |
-
pad_seconds = args.pad_seconds
|
105 |
-
clip = args.clip
|
106 |
-
lg = args.linear_gradient
|
107 |
-
lgr = args.linear_gradient_retain
|
108 |
-
f0p = args.f0_predictor
|
109 |
-
enhance = args.enhance
|
110 |
-
enhancer_adaptive_key = args.enhancer_adaptive_key
|
111 |
-
cr_threshold = args.f0_filter_threshold
|
112 |
-
diffusion_model_path = args.diffusion_model_path
|
113 |
-
diffusion_config_path = args.diffusion_config_path
|
114 |
-
k_step = args.k_step
|
115 |
-
only_diffusion = args.only_diffusion
|
116 |
-
shallow_diffusion = args.shallow_diffusion
|
117 |
-
use_spk_mix = args.use_spk_mix
|
118 |
-
second_encoding = args.second_encoding
|
119 |
-
loudness_envelope_adjustment = args.loudness_envelope_adjustment
|
120 |
-
|
121 |
-
svc_model = Svc(args.model_path,
|
122 |
-
args.config_path,
|
123 |
-
args.device,
|
124 |
-
args.cluster_model_path,
|
125 |
-
enhance,
|
126 |
-
diffusion_model_path,
|
127 |
-
diffusion_config_path,
|
128 |
-
shallow_diffusion,
|
129 |
-
only_diffusion,
|
130 |
-
use_spk_mix,
|
131 |
-
args.feature_retrieval)
|
132 |
-
|
133 |
-
infer_tool.mkdir(["raw", "results"])
|
134 |
-
|
135 |
-
if len(spk_mix_map) <= 1:
|
136 |
-
use_spk_mix = False
|
137 |
-
if use_spk_mix:
|
138 |
-
spk_list = [spk_mix_map]
|
139 |
-
|
140 |
-
infer_tool.fill_a_to_b(trans, clean_names)
|
141 |
-
for clean_name, tran in zip(clean_names, trans):
|
142 |
-
raw_audio_path = f"raw/{clean_name}"
|
143 |
-
if "." not in raw_audio_path:
|
144 |
-
raw_audio_path += ".wav"
|
145 |
-
infer_tool.format_wav(raw_audio_path)
|
146 |
-
for spk in spk_list:
|
147 |
-
kwarg = {
|
148 |
-
"raw_audio_path": raw_audio_path,
|
149 |
-
"spk": spk,
|
150 |
-
"tran": tran,
|
151 |
-
"slice_db": slice_db,
|
152 |
-
"cluster_infer_ratio": cluster_infer_ratio,
|
153 |
-
"auto_predict_f0": auto_predict_f0,
|
154 |
-
"noice_scale": noice_scale,
|
155 |
-
"pad_seconds": pad_seconds,
|
156 |
-
"clip_seconds": clip,
|
157 |
-
"lg_num": lg,
|
158 |
-
"lgr_num": lgr,
|
159 |
-
"f0_predictor": f0p,
|
160 |
-
"enhancer_adaptive_key": enhancer_adaptive_key,
|
161 |
-
"cr_threshold": cr_threshold,
|
162 |
-
"k_step": k_step,
|
163 |
-
"use_spk_mix": use_spk_mix,
|
164 |
-
"second_encoding": second_encoding,
|
165 |
-
"loudness_envelope_adjustment": loudness_envelope_adjustment
|
166 |
-
}
|
167 |
-
audio = svc_model.slice_inference(**kwarg)
|
168 |
-
key = "auto" if auto_predict_f0 else f"{tran}key"
|
169 |
-
cluster_name = "" if cluster_infer_ratio == 0 else f"_{cluster_infer_ratio}"
|
170 |
-
isdiffusion = "sovits"
|
171 |
-
if shallow_diffusion: isdiffusion = "sovdiff"
|
172 |
-
if only_diffusion: isdiffusion = "diff"
|
173 |
-
if use_spk_mix:
|
174 |
-
spk = "spk_mix"
|
175 |
-
res_path = f'results/{clean_name}_{key}_{spk}{cluster_name}_{isdiffusion}.{wav_format}'
|
176 |
-
soundfile.write(res_path, audio, svc_model.target_sample, format=wav_format)
|
177 |
-
svc_model.clear_empty()
|
178 |
-
|
179 |
-
|
180 |
-
if __name__ == '__main__':
|
181 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models.py
CHANGED
@@ -1,20 +1,17 @@
|
|
1 |
-
import copy
|
2 |
-
import math
|
3 |
import torch
|
4 |
from torch import nn
|
|
|
5 |
from torch.nn import functional as F
|
|
|
6 |
|
7 |
import modules.attentions as attentions
|
8 |
import modules.commons as commons
|
9 |
import modules.modules as modules
|
10 |
-
|
11 |
-
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
12 |
-
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
13 |
-
|
14 |
import utils
|
15 |
-
from modules.commons import
|
16 |
from utils import f0_to_coarse
|
17 |
|
|
|
18 |
class ResidualCouplingBlock(nn.Module):
|
19 |
def __init__(self,
|
20 |
channels,
|
@@ -23,7 +20,9 @@ class ResidualCouplingBlock(nn.Module):
|
|
23 |
dilation_rate,
|
24 |
n_layers,
|
25 |
n_flows=4,
|
26 |
-
gin_channels=0
|
|
|
|
|
27 |
super().__init__()
|
28 |
self.channels = channels
|
29 |
self.hidden_channels = hidden_channels
|
@@ -34,10 +33,53 @@ class ResidualCouplingBlock(nn.Module):
|
|
34 |
self.gin_channels = gin_channels
|
35 |
|
36 |
self.flows = nn.ModuleList()
|
|
|
|
|
|
|
37 |
for i in range(n_flows):
|
38 |
self.flows.append(
|
39 |
modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
|
40 |
-
gin_channels=gin_channels, mean_only=True))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
self.flows.append(modules.Flip())
|
42 |
|
43 |
def forward(self, x, x_mask, g=None, reverse=False):
|
@@ -125,7 +167,7 @@ class DiscriminatorP(torch.nn.Module):
|
|
125 |
super(DiscriminatorP, self).__init__()
|
126 |
self.period = period
|
127 |
self.use_spectral_norm = use_spectral_norm
|
128 |
-
norm_f = weight_norm if use_spectral_norm
|
129 |
self.convs = nn.ModuleList([
|
130 |
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
131 |
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
@@ -160,7 +202,7 @@ class DiscriminatorP(torch.nn.Module):
|
|
160 |
class DiscriminatorS(torch.nn.Module):
|
161 |
def __init__(self, use_spectral_norm=False):
|
162 |
super(DiscriminatorS, self).__init__()
|
163 |
-
norm_f = weight_norm if use_spectral_norm
|
164 |
self.convs = nn.ModuleList([
|
165 |
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
166 |
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
@@ -321,6 +363,12 @@ class SynthesizerTrn(nn.Module):
|
|
321 |
sampling_rate=44100,
|
322 |
vol_embedding=False,
|
323 |
vocoder_name = "nsf-hifigan",
|
|
|
|
|
|
|
|
|
|
|
|
|
324 |
**kwargs):
|
325 |
|
326 |
super().__init__()
|
@@ -343,6 +391,9 @@ class SynthesizerTrn(nn.Module):
|
|
343 |
self.ssl_dim = ssl_dim
|
344 |
self.vol_embedding = vol_embedding
|
345 |
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
|
|
|
|
|
|
346 |
if vol_embedding:
|
347 |
self.emb_vol = nn.Linear(1, hidden_channels)
|
348 |
|
@@ -367,9 +418,11 @@ class SynthesizerTrn(nn.Module):
|
|
367 |
"upsample_initial_channel": upsample_initial_channel,
|
368 |
"upsample_kernel_sizes": upsample_kernel_sizes,
|
369 |
"gin_channels": gin_channels,
|
|
|
370 |
}
|
371 |
|
372 |
-
|
|
|
373 |
if vocoder_name == "nsf-hifigan":
|
374 |
from vdecoder.hifigan.models import Generator
|
375 |
self.dec = Generator(h=hps)
|
@@ -382,17 +435,21 @@ class SynthesizerTrn(nn.Module):
|
|
382 |
self.dec = Generator(h=hps)
|
383 |
|
384 |
self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
hidden_channels,
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
|
|
|
|
|
|
|
|
396 |
self.emb_uv = nn.Embedding(2, hidden_channels)
|
397 |
self.character_mix = False
|
398 |
|
@@ -407,17 +464,21 @@ class SynthesizerTrn(nn.Module):
|
|
407 |
g = self.emb_g(g).transpose(1,2)
|
408 |
|
409 |
# vol proj
|
410 |
-
vol = self.emb_vol(vol[:,:,None]).transpose(1,2) if vol
|
411 |
|
412 |
# ssl prenet
|
413 |
x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
|
414 |
x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1,2) + vol
|
415 |
-
|
416 |
# f0 predict
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
|
|
|
|
|
|
|
|
421 |
# encoder
|
422 |
z_ptemp, m_p, logs_p, _ = self.enc_p(x, x_mask, f0=f0_to_coarse(f0))
|
423 |
z, m_q, logs_q, spec_mask = self.enc_q(spec, spec_lengths, g=g)
|
@@ -431,6 +492,7 @@ class SynthesizerTrn(nn.Module):
|
|
431 |
|
432 |
return o, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q), pred_lf0, norm_lf0, lf0
|
433 |
|
|
|
434 |
def infer(self, c, f0, uv, g=None, noice_scale=0.35, seed=52468, predict_f0=False, vol = None):
|
435 |
|
436 |
if c.device == torch.device("cuda"):
|
@@ -452,11 +514,13 @@ class SynthesizerTrn(nn.Module):
|
|
452 |
|
453 |
x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
|
454 |
# vol proj
|
455 |
-
vol = self.emb_vol(vol[:,:,None]).transpose(1,2) if vol!=None and self.vol_embedding else 0
|
456 |
-
|
457 |
-
x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1,2) + vol
|
458 |
|
459 |
-
if
|
|
|
|
|
|
|
|
|
|
|
460 |
lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
|
461 |
norm_lf0 = utils.normalize_f0(lf0, x_mask, uv, random_scale=False)
|
462 |
pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
|
|
|
|
|
|
|
1 |
import torch
|
2 |
from torch import nn
|
3 |
+
from torch.nn import Conv1d, Conv2d
|
4 |
from torch.nn import functional as F
|
5 |
+
from torch.nn.utils import spectral_norm, weight_norm
|
6 |
|
7 |
import modules.attentions as attentions
|
8 |
import modules.commons as commons
|
9 |
import modules.modules as modules
|
|
|
|
|
|
|
|
|
10 |
import utils
|
11 |
+
from modules.commons import get_padding
|
12 |
from utils import f0_to_coarse
|
13 |
|
14 |
+
|
15 |
class ResidualCouplingBlock(nn.Module):
|
16 |
def __init__(self,
|
17 |
channels,
|
|
|
20 |
dilation_rate,
|
21 |
n_layers,
|
22 |
n_flows=4,
|
23 |
+
gin_channels=0,
|
24 |
+
share_parameter=False
|
25 |
+
):
|
26 |
super().__init__()
|
27 |
self.channels = channels
|
28 |
self.hidden_channels = hidden_channels
|
|
|
33 |
self.gin_channels = gin_channels
|
34 |
|
35 |
self.flows = nn.ModuleList()
|
36 |
+
|
37 |
+
self.wn = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=0, gin_channels=gin_channels) if share_parameter else None
|
38 |
+
|
39 |
for i in range(n_flows):
|
40 |
self.flows.append(
|
41 |
modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
|
42 |
+
gin_channels=gin_channels, mean_only=True, wn_sharing_parameter=self.wn))
|
43 |
+
self.flows.append(modules.Flip())
|
44 |
+
|
45 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
46 |
+
if not reverse:
|
47 |
+
for flow in self.flows:
|
48 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
49 |
+
else:
|
50 |
+
for flow in reversed(self.flows):
|
51 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
52 |
+
return x
|
53 |
+
|
54 |
+
class TransformerCouplingBlock(nn.Module):
|
55 |
+
def __init__(self,
|
56 |
+
channels,
|
57 |
+
hidden_channels,
|
58 |
+
filter_channels,
|
59 |
+
n_heads,
|
60 |
+
n_layers,
|
61 |
+
kernel_size,
|
62 |
+
p_dropout,
|
63 |
+
n_flows=4,
|
64 |
+
gin_channels=0,
|
65 |
+
share_parameter=False
|
66 |
+
):
|
67 |
+
|
68 |
+
super().__init__()
|
69 |
+
self.channels = channels
|
70 |
+
self.hidden_channels = hidden_channels
|
71 |
+
self.kernel_size = kernel_size
|
72 |
+
self.n_layers = n_layers
|
73 |
+
self.n_flows = n_flows
|
74 |
+
self.gin_channels = gin_channels
|
75 |
+
|
76 |
+
self.flows = nn.ModuleList()
|
77 |
+
|
78 |
+
self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None
|
79 |
+
|
80 |
+
for i in range(n_flows):
|
81 |
+
self.flows.append(
|
82 |
+
modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels))
|
83 |
self.flows.append(modules.Flip())
|
84 |
|
85 |
def forward(self, x, x_mask, g=None, reverse=False):
|
|
|
167 |
super(DiscriminatorP, self).__init__()
|
168 |
self.period = period
|
169 |
self.use_spectral_norm = use_spectral_norm
|
170 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
171 |
self.convs = nn.ModuleList([
|
172 |
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
173 |
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
|
|
202 |
class DiscriminatorS(torch.nn.Module):
|
203 |
def __init__(self, use_spectral_norm=False):
|
204 |
super(DiscriminatorS, self).__init__()
|
205 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
206 |
self.convs = nn.ModuleList([
|
207 |
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
208 |
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
|
|
363 |
sampling_rate=44100,
|
364 |
vol_embedding=False,
|
365 |
vocoder_name = "nsf-hifigan",
|
366 |
+
use_depthwise_conv = False,
|
367 |
+
use_automatic_f0_prediction = True,
|
368 |
+
flow_share_parameter = False,
|
369 |
+
n_flow_layer = 4,
|
370 |
+
n_layers_trans_flow = 3,
|
371 |
+
use_transformer_flow = False,
|
372 |
**kwargs):
|
373 |
|
374 |
super().__init__()
|
|
|
391 |
self.ssl_dim = ssl_dim
|
392 |
self.vol_embedding = vol_embedding
|
393 |
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
394 |
+
self.use_depthwise_conv = use_depthwise_conv
|
395 |
+
self.use_automatic_f0_prediction = use_automatic_f0_prediction
|
396 |
+
self.n_layers_trans_flow = n_layers_trans_flow
|
397 |
if vol_embedding:
|
398 |
self.emb_vol = nn.Linear(1, hidden_channels)
|
399 |
|
|
|
418 |
"upsample_initial_channel": upsample_initial_channel,
|
419 |
"upsample_kernel_sizes": upsample_kernel_sizes,
|
420 |
"gin_channels": gin_channels,
|
421 |
+
"use_depthwise_conv":use_depthwise_conv
|
422 |
}
|
423 |
|
424 |
+
modules.set_Conv1dModel(self.use_depthwise_conv)
|
425 |
+
|
426 |
if vocoder_name == "nsf-hifigan":
|
427 |
from vdecoder.hifigan.models import Generator
|
428 |
self.dec = Generator(h=hps)
|
|
|
435 |
self.dec = Generator(h=hps)
|
436 |
|
437 |
self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
|
438 |
+
if use_transformer_flow:
|
439 |
+
self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels, share_parameter= flow_share_parameter)
|
440 |
+
else:
|
441 |
+
self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels, share_parameter= flow_share_parameter)
|
442 |
+
if self.use_automatic_f0_prediction:
|
443 |
+
self.f0_decoder = F0Decoder(
|
444 |
+
1,
|
445 |
+
hidden_channels,
|
446 |
+
filter_channels,
|
447 |
+
n_heads,
|
448 |
+
n_layers,
|
449 |
+
kernel_size,
|
450 |
+
p_dropout,
|
451 |
+
spk_channels=gin_channels
|
452 |
+
)
|
453 |
self.emb_uv = nn.Embedding(2, hidden_channels)
|
454 |
self.character_mix = False
|
455 |
|
|
|
464 |
g = self.emb_g(g).transpose(1,2)
|
465 |
|
466 |
# vol proj
|
467 |
+
vol = self.emb_vol(vol[:,:,None]).transpose(1,2) if vol is not None and self.vol_embedding else 0
|
468 |
|
469 |
# ssl prenet
|
470 |
x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
|
471 |
x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1,2) + vol
|
472 |
+
|
473 |
# f0 predict
|
474 |
+
if self.use_automatic_f0_prediction:
|
475 |
+
lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
|
476 |
+
norm_lf0 = utils.normalize_f0(lf0, x_mask, uv)
|
477 |
+
pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
|
478 |
+
else:
|
479 |
+
lf0 = 0
|
480 |
+
norm_lf0 = 0
|
481 |
+
pred_lf0 = 0
|
482 |
# encoder
|
483 |
z_ptemp, m_p, logs_p, _ = self.enc_p(x, x_mask, f0=f0_to_coarse(f0))
|
484 |
z, m_q, logs_q, spec_mask = self.enc_q(spec, spec_lengths, g=g)
|
|
|
492 |
|
493 |
return o, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q), pred_lf0, norm_lf0, lf0
|
494 |
|
495 |
+
@torch.no_grad()
|
496 |
def infer(self, c, f0, uv, g=None, noice_scale=0.35, seed=52468, predict_f0=False, vol = None):
|
497 |
|
498 |
if c.device == torch.device("cuda"):
|
|
|
514 |
|
515 |
x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
|
516 |
# vol proj
|
|
|
|
|
|
|
517 |
|
518 |
+
vol = self.emb_vol(vol[:,:,None]).transpose(1,2) if vol is not None and self.vol_embedding else 0
|
519 |
+
|
520 |
+
x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1, 2) + vol
|
521 |
+
|
522 |
+
|
523 |
+
if self.use_automatic_f0_prediction and predict_f0:
|
524 |
lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
|
525 |
norm_lf0 = utils.normalize_f0(lf0, x_mask, uv, random_scale=False)
|
526 |
pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
|
modules/DSConv.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from torch.nn.utils import remove_weight_norm, weight_norm
|
3 |
+
|
4 |
+
|
5 |
+
class Depthwise_Separable_Conv1D(nn.Module):
|
6 |
+
def __init__(
|
7 |
+
self,
|
8 |
+
in_channels,
|
9 |
+
out_channels,
|
10 |
+
kernel_size,
|
11 |
+
stride = 1,
|
12 |
+
padding = 0,
|
13 |
+
dilation = 1,
|
14 |
+
bias = True,
|
15 |
+
padding_mode = 'zeros', # TODO: refine this type
|
16 |
+
device=None,
|
17 |
+
dtype=None
|
18 |
+
):
|
19 |
+
super().__init__()
|
20 |
+
self.depth_conv = nn.Conv1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size, groups=in_channels,stride = stride,padding=padding,dilation=dilation,bias=bias,padding_mode=padding_mode,device=device,dtype=dtype)
|
21 |
+
self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias, device=device,dtype=dtype)
|
22 |
+
|
23 |
+
def forward(self, input):
|
24 |
+
return self.point_conv(self.depth_conv(input))
|
25 |
+
|
26 |
+
def weight_norm(self):
|
27 |
+
self.depth_conv = weight_norm(self.depth_conv, name = 'weight')
|
28 |
+
self.point_conv = weight_norm(self.point_conv, name = 'weight')
|
29 |
+
|
30 |
+
def remove_weight_norm(self):
|
31 |
+
self.depth_conv = remove_weight_norm(self.depth_conv, name = 'weight')
|
32 |
+
self.point_conv = remove_weight_norm(self.point_conv, name = 'weight')
|
33 |
+
|
34 |
+
class Depthwise_Separable_TransposeConv1D(nn.Module):
|
35 |
+
def __init__(
|
36 |
+
self,
|
37 |
+
in_channels,
|
38 |
+
out_channels,
|
39 |
+
kernel_size,
|
40 |
+
stride = 1,
|
41 |
+
padding = 0,
|
42 |
+
output_padding = 0,
|
43 |
+
bias = True,
|
44 |
+
dilation = 1,
|
45 |
+
padding_mode = 'zeros', # TODO: refine this type
|
46 |
+
device=None,
|
47 |
+
dtype=None
|
48 |
+
):
|
49 |
+
super().__init__()
|
50 |
+
self.depth_conv = nn.ConvTranspose1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size, groups=in_channels,stride = stride,output_padding=output_padding,padding=padding,dilation=dilation,bias=bias,padding_mode=padding_mode,device=device,dtype=dtype)
|
51 |
+
self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias, device=device,dtype=dtype)
|
52 |
+
|
53 |
+
def forward(self, input):
|
54 |
+
return self.point_conv(self.depth_conv(input))
|
55 |
+
|
56 |
+
def weight_norm(self):
|
57 |
+
self.depth_conv = weight_norm(self.depth_conv, name = 'weight')
|
58 |
+
self.point_conv = weight_norm(self.point_conv, name = 'weight')
|
59 |
+
|
60 |
+
def remove_weight_norm(self):
|
61 |
+
remove_weight_norm(self.depth_conv, name = 'weight')
|
62 |
+
remove_weight_norm(self.point_conv, name = 'weight')
|
63 |
+
|
64 |
+
|
65 |
+
def weight_norm_modules(module, name = 'weight', dim = 0):
|
66 |
+
if isinstance(module,Depthwise_Separable_Conv1D) or isinstance(module,Depthwise_Separable_TransposeConv1D):
|
67 |
+
module.weight_norm()
|
68 |
+
return module
|
69 |
+
else:
|
70 |
+
return weight_norm(module,name,dim)
|
71 |
+
|
72 |
+
def remove_weight_norm_modules(module, name = 'weight'):
|
73 |
+
if isinstance(module,Depthwise_Separable_Conv1D) or isinstance(module,Depthwise_Separable_TransposeConv1D):
|
74 |
+
module.remove_weight_norm()
|
75 |
+
else:
|
76 |
+
remove_weight_norm(module,name)
|
modules/F0Predictor/CrepeF0Predictor.py
CHANGED
@@ -1,7 +1,9 @@
|
|
1 |
-
from modules.F0Predictor.F0Predictor import F0Predictor
|
2 |
-
from modules.F0Predictor.crepe import CrepePitchExtractor
|
3 |
import torch
|
4 |
|
|
|
|
|
|
|
|
|
5 |
class CrepeF0Predictor(F0Predictor):
|
6 |
def __init__(self,hop_length=512,f0_min=50,f0_max=1100,device=None,sampling_rate=44100,threshold=0.05,model="full"):
|
7 |
self.F0Creper = CrepePitchExtractor(hop_length=hop_length,f0_min=f0_min,f0_max=f0_max,device=device,threshold=threshold,model=model)
|
@@ -11,6 +13,7 @@ class CrepeF0Predictor(F0Predictor):
|
|
11 |
self.device = device
|
12 |
self.threshold = threshold
|
13 |
self.sampling_rate = sampling_rate
|
|
|
14 |
|
15 |
def compute_f0(self,wav,p_len=None):
|
16 |
x = torch.FloatTensor(wav).to(self.device)
|
|
|
|
|
|
|
1 |
import torch
|
2 |
|
3 |
+
from modules.F0Predictor.crepe import CrepePitchExtractor
|
4 |
+
from modules.F0Predictor.F0Predictor import F0Predictor
|
5 |
+
|
6 |
+
|
7 |
class CrepeF0Predictor(F0Predictor):
|
8 |
def __init__(self,hop_length=512,f0_min=50,f0_max=1100,device=None,sampling_rate=44100,threshold=0.05,model="full"):
|
9 |
self.F0Creper = CrepePitchExtractor(hop_length=hop_length,f0_min=f0_min,f0_max=f0_max,device=device,threshold=threshold,model=model)
|
|
|
13 |
self.device = device
|
14 |
self.threshold = threshold
|
15 |
self.sampling_rate = sampling_rate
|
16 |
+
self.name = "crepe"
|
17 |
|
18 |
def compute_f0(self,wav,p_len=None):
|
19 |
x = torch.FloatTensor(wav).to(self.device)
|
modules/F0Predictor/DioF0Predictor.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
-
from modules.F0Predictor.F0Predictor import F0Predictor
|
2 |
-
import pyworld
|
3 |
import numpy as np
|
|
|
|
|
|
|
|
|
4 |
|
5 |
class DioF0Predictor(F0Predictor):
|
6 |
def __init__(self,hop_length=512,f0_min=50,f0_max=1100,sampling_rate=44100):
|
@@ -8,44 +10,31 @@ class DioF0Predictor(F0Predictor):
|
|
8 |
self.f0_min = f0_min
|
9 |
self.f0_max = f0_max
|
10 |
self.sampling_rate = sampling_rate
|
|
|
11 |
|
12 |
def interpolate_f0(self,f0):
|
13 |
'''
|
14 |
对F0进行插值处理
|
15 |
'''
|
|
|
|
|
|
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
break
|
33 |
-
if j < frame_number - 1:
|
34 |
-
if last_value > 0.0:
|
35 |
-
step = (data[j] - data[i - 1]) / float(j - i)
|
36 |
-
for k in range(i, j):
|
37 |
-
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
38 |
-
else:
|
39 |
-
for k in range(i, j):
|
40 |
-
ip_data[k] = data[j]
|
41 |
-
else:
|
42 |
-
for k in range(i, frame_number):
|
43 |
-
ip_data[k] = last_value
|
44 |
-
else:
|
45 |
-
ip_data[i] = data[i] #这里可能存在一个没有必要的拷贝
|
46 |
-
last_value = data[i]
|
47 |
-
|
48 |
-
return ip_data[:,0], vuv_vector[:,0]
|
49 |
|
50 |
def resize_f0(self,x, target_len):
|
51 |
source = np.array(x)
|
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
+
import pyworld
|
3 |
+
|
4 |
+
from 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):
|
|
|
10 |
self.f0_min = f0_min
|
11 |
self.f0_max = f0_max
|
12 |
self.sampling_rate = sampling_rate
|
13 |
+
self.name = "dio"
|
14 |
|
15 |
def interpolate_f0(self,f0):
|
16 |
'''
|
17 |
对F0进行插值处理
|
18 |
'''
|
19 |
+
vuv_vector = np.zeros_like(f0, dtype=np.float32)
|
20 |
+
vuv_vector[f0 > 0.0] = 1.0
|
21 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
22 |
|
23 |
+
nzindex = np.nonzero(f0)[0]
|
24 |
+
data = f0[nzindex]
|
25 |
+
nzindex = nzindex.astype(np.float32)
|
26 |
+
time_org = self.hop_length / self.sampling_rate * nzindex
|
27 |
+
time_frame = np.arange(f0.shape[0]) * self.hop_length / self.sampling_rate
|
28 |
+
|
29 |
+
if data.shape[0] <= 0:
|
30 |
+
return np.zeros(f0.shape[0], dtype=np.float32),vuv_vector
|
31 |
+
|
32 |
+
if data.shape[0] == 1:
|
33 |
+
return np.ones(f0.shape[0], dtype=np.float32) * f0[0],vuv_vector
|
34 |
+
|
35 |
+
f0 = np.interp(time_frame, time_org, data, left=data[0], right=data[-1])
|
36 |
+
|
37 |
+
return f0,vuv_vector
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
def resize_f0(self,x, target_len):
|
40 |
source = np.array(x)
|
modules/F0Predictor/FCPEF0Predictor.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
|
7 |
+
from modules.F0Predictor.F0Predictor import F0Predictor
|
8 |
+
|
9 |
+
from .fcpe.model import FCPEInfer
|
10 |
+
|
11 |
+
|
12 |
+
class FCPEF0Predictor(F0Predictor):
|
13 |
+
def __init__(self, hop_length=512, f0_min=50, f0_max=1100, dtype=torch.float32, device=None, sampling_rate=44100,
|
14 |
+
threshold=0.05):
|
15 |
+
self.fcpe = FCPEInfer(model_path="pretrain/fcpe.pt", device=device, dtype=dtype)
|
16 |
+
self.hop_length = hop_length
|
17 |
+
self.f0_min = f0_min
|
18 |
+
self.f0_max = f0_max
|
19 |
+
if device is None:
|
20 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
21 |
+
else:
|
22 |
+
self.device = device
|
23 |
+
self.threshold = threshold
|
24 |
+
self.sampling_rate = sampling_rate
|
25 |
+
self.dtype = dtype
|
26 |
+
self.name = "fcpe"
|
27 |
+
|
28 |
+
def repeat_expand(
|
29 |
+
self, content: Union[torch.Tensor, np.ndarray], target_len: int, mode: str = "nearest"
|
30 |
+
):
|
31 |
+
ndim = content.ndim
|
32 |
+
|
33 |
+
if content.ndim == 1:
|
34 |
+
content = content[None, None]
|
35 |
+
elif content.ndim == 2:
|
36 |
+
content = content[None]
|
37 |
+
|
38 |
+
assert content.ndim == 3
|
39 |
+
|
40 |
+
is_np = isinstance(content, np.ndarray)
|
41 |
+
if is_np:
|
42 |
+
content = torch.from_numpy(content)
|
43 |
+
|
44 |
+
results = torch.nn.functional.interpolate(content, size=target_len, mode=mode)
|
45 |
+
|
46 |
+
if is_np:
|
47 |
+
results = results.numpy()
|
48 |
+
|
49 |
+
if ndim == 1:
|
50 |
+
return results[0, 0]
|
51 |
+
elif ndim == 2:
|
52 |
+
return results[0]
|
53 |
+
|
54 |
+
def post_process(self, x, sampling_rate, f0, pad_to):
|
55 |
+
if isinstance(f0, np.ndarray):
|
56 |
+
f0 = torch.from_numpy(f0).float().to(x.device)
|
57 |
+
|
58 |
+
if pad_to is None:
|
59 |
+
return f0
|
60 |
+
|
61 |
+
f0 = self.repeat_expand(f0, pad_to)
|
62 |
+
|
63 |
+
vuv_vector = torch.zeros_like(f0)
|
64 |
+
vuv_vector[f0 > 0.0] = 1.0
|
65 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
66 |
+
|
67 |
+
# 去掉0频率, 并线性插值
|
68 |
+
nzindex = torch.nonzero(f0).squeeze()
|
69 |
+
f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
|
70 |
+
time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
|
71 |
+
time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
|
72 |
+
|
73 |
+
vuv_vector = F.interpolate(vuv_vector[None, None, :], size=pad_to)[0][0]
|
74 |
+
|
75 |
+
if f0.shape[0] <= 0:
|
76 |
+
return torch.zeros(pad_to, dtype=torch.float, device=x.device).cpu().numpy(), vuv_vector.cpu().numpy()
|
77 |
+
if f0.shape[0] == 1:
|
78 |
+
return (torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[
|
79 |
+
0]).cpu().numpy(), vuv_vector.cpu().numpy()
|
80 |
+
|
81 |
+
# 大概可以用 torch 重写?
|
82 |
+
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
83 |
+
# vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
|
84 |
+
|
85 |
+
return f0, vuv_vector.cpu().numpy()
|
86 |
+
|
87 |
+
def compute_f0(self, wav, p_len=None):
|
88 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
89 |
+
if p_len is None:
|
90 |
+
p_len = x.shape[0] // self.hop_length
|
91 |
+
else:
|
92 |
+
assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
93 |
+
f0 = self.fcpe(x, sr=self.sampling_rate, threshold=self.threshold)[0,:,0]
|
94 |
+
if torch.all(f0 == 0):
|
95 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
96 |
+
return rtn, rtn
|
97 |
+
return self.post_process(x, self.sampling_rate, f0, p_len)[0]
|
98 |
+
|
99 |
+
def compute_f0_uv(self, wav, p_len=None):
|
100 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
101 |
+
if p_len is None:
|
102 |
+
p_len = x.shape[0] // self.hop_length
|
103 |
+
else:
|
104 |
+
assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
105 |
+
f0 = self.fcpe(x, sr=self.sampling_rate, threshold=self.threshold)[0,:,0]
|
106 |
+
if torch.all(f0 == 0):
|
107 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
108 |
+
return rtn, rtn
|
109 |
+
return self.post_process(x, self.sampling_rate, f0, p_len)
|
modules/F0Predictor/HarvestF0Predictor.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
-
from modules.F0Predictor.F0Predictor import F0Predictor
|
2 |
-
import pyworld
|
3 |
import numpy as np
|
|
|
|
|
|
|
|
|
4 |
|
5 |
class HarvestF0Predictor(F0Predictor):
|
6 |
def __init__(self,hop_length=512,f0_min=50,f0_max=1100,sampling_rate=44100):
|
@@ -8,45 +10,31 @@ class HarvestF0Predictor(F0Predictor):
|
|
8 |
self.f0_min = f0_min
|
9 |
self.f0_max = f0_max
|
10 |
self.sampling_rate = sampling_rate
|
|
|
11 |
|
12 |
def interpolate_f0(self,f0):
|
13 |
'''
|
14 |
对F0进行插值处理
|
15 |
'''
|
|
|
|
|
|
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
ip_data = data
|
24 |
-
|
25 |
-
frame_number = data.size
|
26 |
-
last_value = 0.0
|
27 |
-
for i in range(frame_number):
|
28 |
-
if data[i] <= 0.0:
|
29 |
-
j = i + 1
|
30 |
-
for j in range(i + 1, frame_number):
|
31 |
-
if data[j] > 0.0:
|
32 |
-
break
|
33 |
-
if j < frame_number - 1:
|
34 |
-
if last_value > 0.0:
|
35 |
-
step = (data[j] - data[i - 1]) / float(j - i)
|
36 |
-
for k in range(i, j):
|
37 |
-
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
38 |
-
else:
|
39 |
-
for k in range(i, j):
|
40 |
-
ip_data[k] = data[j]
|
41 |
-
else:
|
42 |
-
for k in range(i, frame_number):
|
43 |
-
ip_data[k] = last_value
|
44 |
-
else:
|
45 |
-
ip_data[i] = data[i] #这里可能存在一个没有必要的拷贝
|
46 |
-
last_value = data[i]
|
47 |
-
|
48 |
-
return ip_data[:,0], vuv_vector[:,0]
|
49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
def resize_f0(self,x, target_len):
|
51 |
source = np.array(x)
|
52 |
source[source<0.001] = np.nan
|
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
+
import pyworld
|
3 |
+
|
4 |
+
from 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):
|
|
|
10 |
self.f0_min = f0_min
|
11 |
self.f0_max = f0_max
|
12 |
self.sampling_rate = sampling_rate
|
13 |
+
self.name = "harvest"
|
14 |
|
15 |
def interpolate_f0(self,f0):
|
16 |
'''
|
17 |
对F0进行插值处理
|
18 |
'''
|
19 |
+
vuv_vector = np.zeros_like(f0, dtype=np.float32)
|
20 |
+
vuv_vector[f0 > 0.0] = 1.0
|
21 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
22 |
|
23 |
+
nzindex = np.nonzero(f0)[0]
|
24 |
+
data = f0[nzindex]
|
25 |
+
nzindex = nzindex.astype(np.float32)
|
26 |
+
time_org = self.hop_length / self.sampling_rate * nzindex
|
27 |
+
time_frame = np.arange(f0.shape[0]) * self.hop_length / self.sampling_rate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
if data.shape[0] <= 0:
|
30 |
+
return np.zeros(f0.shape[0], dtype=np.float32),vuv_vector
|
31 |
+
|
32 |
+
if data.shape[0] == 1:
|
33 |
+
return np.ones(f0.shape[0], dtype=np.float32) * f0[0],vuv_vector
|
34 |
+
|
35 |
+
f0 = np.interp(time_frame, time_org, data, left=data[0], right=data[-1])
|
36 |
+
|
37 |
+
return f0,vuv_vector
|
38 |
def resize_f0(self,x, target_len):
|
39 |
source = np.array(x)
|
40 |
source[source<0.001] = np.nan
|
modules/F0Predictor/PMF0Predictor.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
-
from modules.F0Predictor.F0Predictor import F0Predictor
|
2 |
-
import parselmouth
|
3 |
import numpy as np
|
|
|
|
|
|
|
|
|
4 |
|
5 |
class PMF0Predictor(F0Predictor):
|
6 |
def __init__(self,hop_length=512,f0_min=50,f0_max=1100,sampling_rate=44100):
|
@@ -8,45 +10,32 @@ class PMF0Predictor(F0Predictor):
|
|
8 |
self.f0_min = f0_min
|
9 |
self.f0_max = f0_max
|
10 |
self.sampling_rate = sampling_rate
|
11 |
-
|
12 |
|
13 |
def interpolate_f0(self,f0):
|
14 |
'''
|
15 |
对F0进行插值处理
|
16 |
'''
|
|
|
|
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
break
|
34 |
-
if j < frame_number - 1:
|
35 |
-
if last_value > 0.0:
|
36 |
-
step = (data[j] - data[i - 1]) / float(j - i)
|
37 |
-
for k in range(i, j):
|
38 |
-
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
39 |
-
else:
|
40 |
-
for k in range(i, j):
|
41 |
-
ip_data[k] = data[j]
|
42 |
-
else:
|
43 |
-
for k in range(i, frame_number):
|
44 |
-
ip_data[k] = last_value
|
45 |
-
else:
|
46 |
-
ip_data[i] = data[i] #这里可能存在一个没有必要的拷贝
|
47 |
-
last_value = data[i]
|
48 |
|
49 |
-
return ip_data[:,0], vuv_vector[:,0]
|
50 |
|
51 |
def compute_f0(self,wav,p_len=None):
|
52 |
x = wav
|
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
+
import parselmouth
|
3 |
+
|
4 |
+
from 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):
|
|
|
10 |
self.f0_min = f0_min
|
11 |
self.f0_max = f0_max
|
12 |
self.sampling_rate = sampling_rate
|
13 |
+
self.name = "pm"
|
14 |
|
15 |
def interpolate_f0(self,f0):
|
16 |
'''
|
17 |
对F0进行插值处理
|
18 |
'''
|
19 |
+
vuv_vector = np.zeros_like(f0, dtype=np.float32)
|
20 |
+
vuv_vector[f0 > 0.0] = 1.0
|
21 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
22 |
|
23 |
+
nzindex = np.nonzero(f0)[0]
|
24 |
+
data = f0[nzindex]
|
25 |
+
nzindex = nzindex.astype(np.float32)
|
26 |
+
time_org = self.hop_length / self.sampling_rate * nzindex
|
27 |
+
time_frame = np.arange(f0.shape[0]) * self.hop_length / self.sampling_rate
|
28 |
+
|
29 |
+
if data.shape[0] <= 0:
|
30 |
+
return np.zeros(f0.shape[0], dtype=np.float32),vuv_vector
|
31 |
+
|
32 |
+
if data.shape[0] == 1:
|
33 |
+
return np.ones(f0.shape[0], dtype=np.float32) * f0[0],vuv_vector
|
34 |
+
|
35 |
+
f0 = np.interp(time_frame, time_org, data, left=data[0], right=data[-1])
|
36 |
+
|
37 |
+
return f0,vuv_vector
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
|
|
39 |
|
40 |
def compute_f0(self,wav,p_len=None):
|
41 |
x = wav
|
modules/F0Predictor/RMVPEF0Predictor.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
|
7 |
+
from modules.F0Predictor.F0Predictor import F0Predictor
|
8 |
+
|
9 |
+
from .rmvpe import RMVPE
|
10 |
+
|
11 |
+
|
12 |
+
class RMVPEF0Predictor(F0Predictor):
|
13 |
+
def __init__(self,hop_length=512,f0_min=50,f0_max=1100, dtype=torch.float32, device=None,sampling_rate=44100,threshold=0.05):
|
14 |
+
self.rmvpe = RMVPE(model_path="pretrain/rmvpe.pt",dtype=dtype,device=device)
|
15 |
+
self.hop_length = hop_length
|
16 |
+
self.f0_min = f0_min
|
17 |
+
self.f0_max = f0_max
|
18 |
+
if device is None:
|
19 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
20 |
+
else:
|
21 |
+
self.device = device
|
22 |
+
self.threshold = threshold
|
23 |
+
self.sampling_rate = sampling_rate
|
24 |
+
self.dtype = dtype
|
25 |
+
self.name = "rmvpe"
|
26 |
+
|
27 |
+
def repeat_expand(
|
28 |
+
self, content: Union[torch.Tensor, np.ndarray], target_len: int, mode: str = "nearest"
|
29 |
+
):
|
30 |
+
ndim = content.ndim
|
31 |
+
|
32 |
+
if content.ndim == 1:
|
33 |
+
content = content[None, None]
|
34 |
+
elif content.ndim == 2:
|
35 |
+
content = content[None]
|
36 |
+
|
37 |
+
assert content.ndim == 3
|
38 |
+
|
39 |
+
is_np = isinstance(content, np.ndarray)
|
40 |
+
if is_np:
|
41 |
+
content = torch.from_numpy(content)
|
42 |
+
|
43 |
+
results = torch.nn.functional.interpolate(content, size=target_len, mode=mode)
|
44 |
+
|
45 |
+
if is_np:
|
46 |
+
results = results.numpy()
|
47 |
+
|
48 |
+
if ndim == 1:
|
49 |
+
return results[0, 0]
|
50 |
+
elif ndim == 2:
|
51 |
+
return results[0]
|
52 |
+
|
53 |
+
def post_process(self, x, sampling_rate, f0, pad_to):
|
54 |
+
if isinstance(f0, np.ndarray):
|
55 |
+
f0 = torch.from_numpy(f0).float().to(x.device)
|
56 |
+
|
57 |
+
if pad_to is None:
|
58 |
+
return f0
|
59 |
+
|
60 |
+
f0 = self.repeat_expand(f0, pad_to)
|
61 |
+
|
62 |
+
vuv_vector = torch.zeros_like(f0)
|
63 |
+
vuv_vector[f0 > 0.0] = 1.0
|
64 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
65 |
+
|
66 |
+
# 去掉0频率, 并线性插值
|
67 |
+
nzindex = torch.nonzero(f0).squeeze()
|
68 |
+
f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
|
69 |
+
time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
|
70 |
+
time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
|
71 |
+
|
72 |
+
vuv_vector = F.interpolate(vuv_vector[None,None,:],size=pad_to)[0][0]
|
73 |
+
|
74 |
+
if f0.shape[0] <= 0:
|
75 |
+
return torch.zeros(pad_to, dtype=torch.float, device=x.device).cpu().numpy(),vuv_vector.cpu().numpy()
|
76 |
+
if f0.shape[0] == 1:
|
77 |
+
return (torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[0]).cpu().numpy() ,vuv_vector.cpu().numpy()
|
78 |
+
|
79 |
+
# 大概可以用 torch 重写?
|
80 |
+
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
81 |
+
#vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
|
82 |
+
|
83 |
+
return f0,vuv_vector.cpu().numpy()
|
84 |
+
|
85 |
+
def compute_f0(self,wav,p_len=None):
|
86 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
87 |
+
if p_len is None:
|
88 |
+
p_len = x.shape[0]//self.hop_length
|
89 |
+
else:
|
90 |
+
assert abs(p_len-x.shape[0]//self.hop_length) < 4, "pad length error"
|
91 |
+
f0 = self.rmvpe.infer_from_audio(x,self.sampling_rate,self.threshold)
|
92 |
+
if torch.all(f0 == 0):
|
93 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
94 |
+
return rtn,rtn
|
95 |
+
return self.post_process(x,self.sampling_rate,f0,p_len)[0]
|
96 |
+
|
97 |
+
def compute_f0_uv(self,wav,p_len=None):
|
98 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
99 |
+
if p_len is None:
|
100 |
+
p_len = x.shape[0]//self.hop_length
|
101 |
+
else:
|
102 |
+
assert abs(p_len-x.shape[0]//self.hop_length) < 4, "pad length error"
|
103 |
+
f0 = self.rmvpe.infer_from_audio(x,self.sampling_rate,self.threshold)
|
104 |
+
if torch.all(f0 == 0):
|
105 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
106 |
+
return rtn,rtn
|
107 |
+
return self.post_process(x,self.sampling_rate,f0,p_len)
|
modules/F0Predictor/crepe.py
CHANGED
@@ -1,14 +1,14 @@
|
|
1 |
-
from typing import Optional,Union
|
|
|
2 |
try:
|
3 |
from typing import Literal
|
4 |
-
except Exception
|
5 |
from typing_extensions import Literal
|
6 |
import numpy as np
|
7 |
import torch
|
8 |
import torchcrepe
|
9 |
from torch import nn
|
10 |
from torch.nn import functional as F
|
11 |
-
import scipy
|
12 |
|
13 |
#from:https://github.com/fishaudio/fish-diffusion
|
14 |
|
@@ -97,19 +97,19 @@ class BasePitchExtractor:
|
|
97 |
f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
|
98 |
time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
|
99 |
time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
|
|
|
|
|
100 |
|
101 |
if f0.shape[0] <= 0:
|
102 |
-
return torch.zeros(pad_to, dtype=torch.float, device=x.device),
|
103 |
-
|
104 |
if f0.shape[0] == 1:
|
105 |
-
return torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[0],
|
106 |
|
107 |
# 大概可以用 torch 重写?
|
108 |
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
109 |
-
vuv_vector =
|
110 |
-
vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
|
111 |
|
112 |
-
return f0,vuv_vector
|
113 |
|
114 |
|
115 |
class MaskedAvgPool1d(nn.Module):
|
@@ -323,7 +323,7 @@ class CrepePitchExtractor(BasePitchExtractor):
|
|
323 |
else:
|
324 |
pd = torchcrepe.filter.median(pd, 3)
|
325 |
|
326 |
-
pd = torchcrepe.threshold.Silence(-60.0)(pd, x, sampling_rate,
|
327 |
f0 = torchcrepe.threshold.At(self.threshold)(f0, pd)
|
328 |
|
329 |
if self.use_fast_filters:
|
@@ -334,7 +334,7 @@ class CrepePitchExtractor(BasePitchExtractor):
|
|
334 |
f0 = torch.where(torch.isnan(f0), torch.full_like(f0, 0), f0)[0]
|
335 |
|
336 |
if torch.all(f0 == 0):
|
337 |
-
rtn = f0.cpu().numpy() if pad_to
|
338 |
return rtn,rtn
|
339 |
|
340 |
return self.post_process(x, sampling_rate, f0, pad_to)
|
|
|
1 |
+
from typing import Optional, Union
|
2 |
+
|
3 |
try:
|
4 |
from typing import Literal
|
5 |
+
except Exception:
|
6 |
from typing_extensions import Literal
|
7 |
import numpy as np
|
8 |
import torch
|
9 |
import torchcrepe
|
10 |
from torch import nn
|
11 |
from torch.nn import functional as F
|
|
|
12 |
|
13 |
#from:https://github.com/fishaudio/fish-diffusion
|
14 |
|
|
|
97 |
f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
|
98 |
time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
|
99 |
time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
|
100 |
+
|
101 |
+
vuv_vector = F.interpolate(vuv_vector[None,None,:],size=pad_to)[0][0]
|
102 |
|
103 |
if f0.shape[0] <= 0:
|
104 |
+
return torch.zeros(pad_to, dtype=torch.float, device=x.device),vuv_vector.cpu().numpy()
|
|
|
105 |
if f0.shape[0] == 1:
|
106 |
+
return torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[0],vuv_vector.cpu().numpy()
|
107 |
|
108 |
# 大概可以用 torch 重写?
|
109 |
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
110 |
+
#vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
|
|
|
111 |
|
112 |
+
return f0,vuv_vector.cpu().numpy()
|
113 |
|
114 |
|
115 |
class MaskedAvgPool1d(nn.Module):
|
|
|
323 |
else:
|
324 |
pd = torchcrepe.filter.median(pd, 3)
|
325 |
|
326 |
+
pd = torchcrepe.threshold.Silence(-60.0)(pd, x, sampling_rate, self.hop_length)
|
327 |
f0 = torchcrepe.threshold.At(self.threshold)(f0, pd)
|
328 |
|
329 |
if self.use_fast_filters:
|
|
|
334 |
f0 = torch.where(torch.isnan(f0), torch.full_like(f0, 0), f0)[0]
|
335 |
|
336 |
if torch.all(f0 == 0):
|
337 |
+
rtn = f0.cpu().numpy() if pad_to is None else np.zeros(pad_to)
|
338 |
return rtn,rtn
|
339 |
|
340 |
return self.post_process(x, sampling_rate, f0, pad_to)
|
modules/F0Predictor/fcpe/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from .model import FCPEInfer # noqa: F401
|
2 |
+
from .nvSTFT import STFT # noqa: F401
|
3 |
+
from .pcmer import PCmer # noqa: F401
|
modules/F0Predictor/fcpe/model.py
ADDED
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torch.nn.utils import weight_norm
|
6 |
+
from torchaudio.transforms import Resample
|
7 |
+
|
8 |
+
from .nvSTFT import STFT
|
9 |
+
from .pcmer import PCmer
|
10 |
+
|
11 |
+
|
12 |
+
def l2_regularization(model, l2_alpha):
|
13 |
+
l2_loss = []
|
14 |
+
for module in model.modules():
|
15 |
+
if type(module) is nn.Conv2d:
|
16 |
+
l2_loss.append((module.weight ** 2).sum() / 2.0)
|
17 |
+
return l2_alpha * sum(l2_loss)
|
18 |
+
|
19 |
+
|
20 |
+
class FCPE(nn.Module):
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
input_channel=128,
|
24 |
+
out_dims=360,
|
25 |
+
n_layers=12,
|
26 |
+
n_chans=512,
|
27 |
+
use_siren=False,
|
28 |
+
use_full=False,
|
29 |
+
loss_mse_scale=10,
|
30 |
+
loss_l2_regularization=False,
|
31 |
+
loss_l2_regularization_scale=1,
|
32 |
+
loss_grad1_mse=False,
|
33 |
+
loss_grad1_mse_scale=1,
|
34 |
+
f0_max=1975.5,
|
35 |
+
f0_min=32.70,
|
36 |
+
confidence=False,
|
37 |
+
threshold=0.05,
|
38 |
+
use_input_conv=True
|
39 |
+
):
|
40 |
+
super().__init__()
|
41 |
+
if use_siren is True:
|
42 |
+
raise ValueError("Siren is not supported yet.")
|
43 |
+
if use_full is True:
|
44 |
+
raise ValueError("Full model is not supported yet.")
|
45 |
+
|
46 |
+
self.loss_mse_scale = loss_mse_scale if (loss_mse_scale is not None) else 10
|
47 |
+
self.loss_l2_regularization = loss_l2_regularization if (loss_l2_regularization is not None) else False
|
48 |
+
self.loss_l2_regularization_scale = loss_l2_regularization_scale if (loss_l2_regularization_scale
|
49 |
+
is not None) else 1
|
50 |
+
self.loss_grad1_mse = loss_grad1_mse if (loss_grad1_mse is not None) else False
|
51 |
+
self.loss_grad1_mse_scale = loss_grad1_mse_scale if (loss_grad1_mse_scale is not None) else 1
|
52 |
+
self.f0_max = f0_max if (f0_max is not None) else 1975.5
|
53 |
+
self.f0_min = f0_min if (f0_min is not None) else 32.70
|
54 |
+
self.confidence = confidence if (confidence is not None) else False
|
55 |
+
self.threshold = threshold if (threshold is not None) else 0.05
|
56 |
+
self.use_input_conv = use_input_conv if (use_input_conv is not None) else True
|
57 |
+
|
58 |
+
self.cent_table_b = torch.Tensor(
|
59 |
+
np.linspace(self.f0_to_cent(torch.Tensor([f0_min]))[0], self.f0_to_cent(torch.Tensor([f0_max]))[0],
|
60 |
+
out_dims))
|
61 |
+
self.register_buffer("cent_table", self.cent_table_b)
|
62 |
+
|
63 |
+
# conv in stack
|
64 |
+
_leaky = nn.LeakyReLU()
|
65 |
+
self.stack = nn.Sequential(
|
66 |
+
nn.Conv1d(input_channel, n_chans, 3, 1, 1),
|
67 |
+
nn.GroupNorm(4, n_chans),
|
68 |
+
_leaky,
|
69 |
+
nn.Conv1d(n_chans, n_chans, 3, 1, 1))
|
70 |
+
|
71 |
+
# transformer
|
72 |
+
self.decoder = PCmer(
|
73 |
+
num_layers=n_layers,
|
74 |
+
num_heads=8,
|
75 |
+
dim_model=n_chans,
|
76 |
+
dim_keys=n_chans,
|
77 |
+
dim_values=n_chans,
|
78 |
+
residual_dropout=0.1,
|
79 |
+
attention_dropout=0.1)
|
80 |
+
self.norm = nn.LayerNorm(n_chans)
|
81 |
+
|
82 |
+
# out
|
83 |
+
self.n_out = out_dims
|
84 |
+
self.dense_out = weight_norm(
|
85 |
+
nn.Linear(n_chans, self.n_out))
|
86 |
+
|
87 |
+
def forward(self, mel, infer=True, gt_f0=None, return_hz_f0=False, cdecoder = "local_argmax"):
|
88 |
+
"""
|
89 |
+
input:
|
90 |
+
B x n_frames x n_unit
|
91 |
+
return:
|
92 |
+
dict of B x n_frames x feat
|
93 |
+
"""
|
94 |
+
if cdecoder == "argmax":
|
95 |
+
self.cdecoder = self.cents_decoder
|
96 |
+
elif cdecoder == "local_argmax":
|
97 |
+
self.cdecoder = self.cents_local_decoder
|
98 |
+
if self.use_input_conv:
|
99 |
+
x = self.stack(mel.transpose(1, 2)).transpose(1, 2)
|
100 |
+
else:
|
101 |
+
x = mel
|
102 |
+
x = self.decoder(x)
|
103 |
+
x = self.norm(x)
|
104 |
+
x = self.dense_out(x) # [B,N,D]
|
105 |
+
x = torch.sigmoid(x)
|
106 |
+
if not infer:
|
107 |
+
gt_cent_f0 = self.f0_to_cent(gt_f0) # mel f0 #[B,N,1]
|
108 |
+
gt_cent_f0 = self.gaussian_blurred_cent(gt_cent_f0) # #[B,N,out_dim]
|
109 |
+
loss_all = self.loss_mse_scale * F.binary_cross_entropy(x, gt_cent_f0) # bce loss
|
110 |
+
# l2 regularization
|
111 |
+
if self.loss_l2_regularization:
|
112 |
+
loss_all = loss_all + l2_regularization(model=self, l2_alpha=self.loss_l2_regularization_scale)
|
113 |
+
x = loss_all
|
114 |
+
if infer:
|
115 |
+
x = self.cdecoder(x)
|
116 |
+
x = self.cent_to_f0(x)
|
117 |
+
if not return_hz_f0:
|
118 |
+
x = (1 + x / 700).log()
|
119 |
+
return x
|
120 |
+
|
121 |
+
def cents_decoder(self, y, mask=True):
|
122 |
+
B, N, _ = y.size()
|
123 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
124 |
+
rtn = torch.sum(ci * y, dim=-1, keepdim=True) / torch.sum(y, dim=-1, keepdim=True) # cents: [B,N,1]
|
125 |
+
if mask:
|
126 |
+
confident = torch.max(y, dim=-1, keepdim=True)[0]
|
127 |
+
confident_mask = torch.ones_like(confident)
|
128 |
+
confident_mask[confident <= self.threshold] = float("-INF")
|
129 |
+
rtn = rtn * confident_mask
|
130 |
+
if self.confidence:
|
131 |
+
return rtn, confident
|
132 |
+
else:
|
133 |
+
return rtn
|
134 |
+
|
135 |
+
def cents_local_decoder(self, y, mask=True):
|
136 |
+
B, N, _ = y.size()
|
137 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
138 |
+
confident, max_index = torch.max(y, dim=-1, keepdim=True)
|
139 |
+
local_argmax_index = torch.arange(0,9).to(max_index.device) + (max_index - 4)
|
140 |
+
local_argmax_index[local_argmax_index<0] = 0
|
141 |
+
local_argmax_index[local_argmax_index>=self.n_out] = self.n_out - 1
|
142 |
+
ci_l = torch.gather(ci,-1,local_argmax_index)
|
143 |
+
y_l = torch.gather(y,-1,local_argmax_index)
|
144 |
+
rtn = torch.sum(ci_l * y_l, dim=-1, keepdim=True) / torch.sum(y_l, dim=-1, keepdim=True) # cents: [B,N,1]
|
145 |
+
if mask:
|
146 |
+
confident_mask = torch.ones_like(confident)
|
147 |
+
confident_mask[confident <= self.threshold] = float("-INF")
|
148 |
+
rtn = rtn * confident_mask
|
149 |
+
if self.confidence:
|
150 |
+
return rtn, confident
|
151 |
+
else:
|
152 |
+
return rtn
|
153 |
+
|
154 |
+
def cent_to_f0(self, cent):
|
155 |
+
return 10. * 2 ** (cent / 1200.)
|
156 |
+
|
157 |
+
def f0_to_cent(self, f0):
|
158 |
+
return 1200. * torch.log2(f0 / 10.)
|
159 |
+
|
160 |
+
def gaussian_blurred_cent(self, cents): # cents: [B,N,1]
|
161 |
+
mask = (cents > 0.1) & (cents < (1200. * np.log2(self.f0_max / 10.)))
|
162 |
+
B, N, _ = cents.size()
|
163 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
164 |
+
return torch.exp(-torch.square(ci - cents) / 1250) * mask.float()
|
165 |
+
|
166 |
+
|
167 |
+
class FCPEInfer:
|
168 |
+
def __init__(self, model_path, device=None, dtype=torch.float32):
|
169 |
+
if device is None:
|
170 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
171 |
+
self.device = device
|
172 |
+
ckpt = torch.load(model_path, map_location=torch.device(self.device))
|
173 |
+
self.args = DotDict(ckpt["config"])
|
174 |
+
self.dtype = dtype
|
175 |
+
model = FCPE(
|
176 |
+
input_channel=self.args.model.input_channel,
|
177 |
+
out_dims=self.args.model.out_dims,
|
178 |
+
n_layers=self.args.model.n_layers,
|
179 |
+
n_chans=self.args.model.n_chans,
|
180 |
+
use_siren=self.args.model.use_siren,
|
181 |
+
use_full=self.args.model.use_full,
|
182 |
+
loss_mse_scale=self.args.loss.loss_mse_scale,
|
183 |
+
loss_l2_regularization=self.args.loss.loss_l2_regularization,
|
184 |
+
loss_l2_regularization_scale=self.args.loss.loss_l2_regularization_scale,
|
185 |
+
loss_grad1_mse=self.args.loss.loss_grad1_mse,
|
186 |
+
loss_grad1_mse_scale=self.args.loss.loss_grad1_mse_scale,
|
187 |
+
f0_max=self.args.model.f0_max,
|
188 |
+
f0_min=self.args.model.f0_min,
|
189 |
+
confidence=self.args.model.confidence,
|
190 |
+
)
|
191 |
+
model.to(self.device).to(self.dtype)
|
192 |
+
model.load_state_dict(ckpt['model'])
|
193 |
+
model.eval()
|
194 |
+
self.model = model
|
195 |
+
self.wav2mel = Wav2Mel(self.args, dtype=self.dtype, device=self.device)
|
196 |
+
|
197 |
+
@torch.no_grad()
|
198 |
+
def __call__(self, audio, sr, threshold=0.05):
|
199 |
+
self.model.threshold = threshold
|
200 |
+
audio = audio[None,:]
|
201 |
+
mel = self.wav2mel(audio=audio, sample_rate=sr).to(self.dtype)
|
202 |
+
f0 = self.model(mel=mel, infer=True, return_hz_f0=True)
|
203 |
+
return f0
|
204 |
+
|
205 |
+
|
206 |
+
class Wav2Mel:
|
207 |
+
|
208 |
+
def __init__(self, args, device=None, dtype=torch.float32):
|
209 |
+
# self.args = args
|
210 |
+
self.sampling_rate = args.mel.sampling_rate
|
211 |
+
self.hop_size = args.mel.hop_size
|
212 |
+
if device is None:
|
213 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
214 |
+
self.device = device
|
215 |
+
self.dtype = dtype
|
216 |
+
self.stft = STFT(
|
217 |
+
args.mel.sampling_rate,
|
218 |
+
args.mel.num_mels,
|
219 |
+
args.mel.n_fft,
|
220 |
+
args.mel.win_size,
|
221 |
+
args.mel.hop_size,
|
222 |
+
args.mel.fmin,
|
223 |
+
args.mel.fmax
|
224 |
+
)
|
225 |
+
self.resample_kernel = {}
|
226 |
+
|
227 |
+
def extract_nvstft(self, audio, keyshift=0, train=False):
|
228 |
+
mel = self.stft.get_mel(audio, keyshift=keyshift, train=train).transpose(1, 2) # B, n_frames, bins
|
229 |
+
return mel
|
230 |
+
|
231 |
+
def extract_mel(self, audio, sample_rate, keyshift=0, train=False):
|
232 |
+
audio = audio.to(self.dtype).to(self.device)
|
233 |
+
# resample
|
234 |
+
if sample_rate == self.sampling_rate:
|
235 |
+
audio_res = audio
|
236 |
+
else:
|
237 |
+
key_str = str(sample_rate)
|
238 |
+
if key_str not in self.resample_kernel:
|
239 |
+
self.resample_kernel[key_str] = Resample(sample_rate, self.sampling_rate, lowpass_filter_width=128)
|
240 |
+
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.dtype).to(self.device)
|
241 |
+
audio_res = self.resample_kernel[key_str](audio)
|
242 |
+
|
243 |
+
# extract
|
244 |
+
mel = self.extract_nvstft(audio_res, keyshift=keyshift, train=train) # B, n_frames, bins
|
245 |
+
n_frames = int(audio.shape[1] // self.hop_size) + 1
|
246 |
+
if n_frames > int(mel.shape[1]):
|
247 |
+
mel = torch.cat((mel, mel[:, -1:, :]), 1)
|
248 |
+
if n_frames < int(mel.shape[1]):
|
249 |
+
mel = mel[:, :n_frames, :]
|
250 |
+
return mel
|
251 |
+
|
252 |
+
def __call__(self, audio, sample_rate, keyshift=0, train=False):
|
253 |
+
return self.extract_mel(audio, sample_rate, keyshift=keyshift, train=train)
|
254 |
+
|
255 |
+
|
256 |
+
class DotDict(dict):
|
257 |
+
def __getattr__(*args):
|
258 |
+
val = dict.get(*args)
|
259 |
+
return DotDict(val) if type(val) is dict else val
|
260 |
+
|
261 |
+
__setattr__ = dict.__setitem__
|
262 |
+
__delattr__ = dict.__delitem__
|
modules/F0Predictor/fcpe/nvSTFT.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import librosa
|
4 |
+
import numpy as np
|
5 |
+
import soundfile as sf
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
import torch.utils.data
|
9 |
+
from librosa.filters import mel as librosa_mel_fn
|
10 |
+
|
11 |
+
os.environ["LRU_CACHE_CAPACITY"] = "3"
|
12 |
+
|
13 |
+
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
|
14 |
+
sampling_rate = None
|
15 |
+
try:
|
16 |
+
data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile.
|
17 |
+
except Exception as ex:
|
18 |
+
print(f"'{full_path}' failed to load.\nException:")
|
19 |
+
print(ex)
|
20 |
+
if return_empty_on_exception:
|
21 |
+
return [], sampling_rate or target_sr or 48000
|
22 |
+
else:
|
23 |
+
raise Exception(ex)
|
24 |
+
|
25 |
+
if len(data.shape) > 1:
|
26 |
+
data = data[:, 0]
|
27 |
+
assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension)
|
28 |
+
|
29 |
+
if np.issubdtype(data.dtype, np.integer): # if audio data is type int
|
30 |
+
max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX
|
31 |
+
else: # if audio data is type fp32
|
32 |
+
max_mag = max(np.amax(data), -np.amin(data))
|
33 |
+
max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32
|
34 |
+
|
35 |
+
data = torch.FloatTensor(data.astype(np.float32))/max_mag
|
36 |
+
|
37 |
+
if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except
|
38 |
+
return [], sampling_rate or target_sr or 48000
|
39 |
+
if target_sr is not None and sampling_rate != target_sr:
|
40 |
+
data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr))
|
41 |
+
sampling_rate = target_sr
|
42 |
+
|
43 |
+
return data, sampling_rate
|
44 |
+
|
45 |
+
def dynamic_range_compression(x, C=1, clip_val=1e-5):
|
46 |
+
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
|
47 |
+
|
48 |
+
def dynamic_range_decompression(x, C=1):
|
49 |
+
return np.exp(x) / C
|
50 |
+
|
51 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
52 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
53 |
+
|
54 |
+
def dynamic_range_decompression_torch(x, C=1):
|
55 |
+
return torch.exp(x) / C
|
56 |
+
|
57 |
+
class STFT():
|
58 |
+
def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5):
|
59 |
+
self.target_sr = sr
|
60 |
+
|
61 |
+
self.n_mels = n_mels
|
62 |
+
self.n_fft = n_fft
|
63 |
+
self.win_size = win_size
|
64 |
+
self.hop_length = hop_length
|
65 |
+
self.fmin = fmin
|
66 |
+
self.fmax = fmax
|
67 |
+
self.clip_val = clip_val
|
68 |
+
self.mel_basis = {}
|
69 |
+
self.hann_window = {}
|
70 |
+
|
71 |
+
def get_mel(self, y, keyshift=0, speed=1, center=False, train=False):
|
72 |
+
sampling_rate = self.target_sr
|
73 |
+
n_mels = self.n_mels
|
74 |
+
n_fft = self.n_fft
|
75 |
+
win_size = self.win_size
|
76 |
+
hop_length = self.hop_length
|
77 |
+
fmin = self.fmin
|
78 |
+
fmax = self.fmax
|
79 |
+
clip_val = self.clip_val
|
80 |
+
|
81 |
+
factor = 2 ** (keyshift / 12)
|
82 |
+
n_fft_new = int(np.round(n_fft * factor))
|
83 |
+
win_size_new = int(np.round(win_size * factor))
|
84 |
+
hop_length_new = int(np.round(hop_length * speed))
|
85 |
+
if not train:
|
86 |
+
mel_basis = self.mel_basis
|
87 |
+
hann_window = self.hann_window
|
88 |
+
else:
|
89 |
+
mel_basis = {}
|
90 |
+
hann_window = {}
|
91 |
+
|
92 |
+
if torch.min(y) < -1.:
|
93 |
+
print('min value is ', torch.min(y))
|
94 |
+
if torch.max(y) > 1.:
|
95 |
+
print('max value is ', torch.max(y))
|
96 |
+
|
97 |
+
mel_basis_key = str(fmax)+'_'+str(y.device)
|
98 |
+
if mel_basis_key not in mel_basis:
|
99 |
+
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax)
|
100 |
+
mel_basis[mel_basis_key] = torch.from_numpy(mel).float().to(y.device)
|
101 |
+
|
102 |
+
keyshift_key = str(keyshift)+'_'+str(y.device)
|
103 |
+
if keyshift_key not in hann_window:
|
104 |
+
hann_window[keyshift_key] = torch.hann_window(win_size_new).to(y.device)
|
105 |
+
|
106 |
+
pad_left = (win_size_new - hop_length_new) //2
|
107 |
+
pad_right = max((win_size_new- hop_length_new + 1) //2, win_size_new - y.size(-1) - pad_left)
|
108 |
+
if pad_right < y.size(-1):
|
109 |
+
mode = 'reflect'
|
110 |
+
else:
|
111 |
+
mode = 'constant'
|
112 |
+
y = torch.nn.functional.pad(y.unsqueeze(1), (pad_left, pad_right), mode = mode)
|
113 |
+
y = y.squeeze(1)
|
114 |
+
|
115 |
+
spec = torch.stft(y, n_fft_new, hop_length=hop_length_new, win_length=win_size_new, window=hann_window[keyshift_key],
|
116 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
|
117 |
+
spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + (1e-9))
|
118 |
+
if keyshift != 0:
|
119 |
+
size = n_fft // 2 + 1
|
120 |
+
resize = spec.size(1)
|
121 |
+
if resize < size:
|
122 |
+
spec = F.pad(spec, (0, 0, 0, size-resize))
|
123 |
+
spec = spec[:, :size, :] * win_size / win_size_new
|
124 |
+
spec = torch.matmul(mel_basis[mel_basis_key], spec)
|
125 |
+
spec = dynamic_range_compression_torch(spec, clip_val=clip_val)
|
126 |
+
return spec
|
127 |
+
|
128 |
+
def __call__(self, audiopath):
|
129 |
+
audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr)
|
130 |
+
spect = self.get_mel(audio.unsqueeze(0)).squeeze(0)
|
131 |
+
return spect
|
132 |
+
|
133 |
+
stft = STFT()
|
modules/F0Predictor/fcpe/pcmer.py
ADDED
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from functools import partial
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
from local_attention import LocalAttention
|
8 |
+
from torch import nn
|
9 |
+
|
10 |
+
#import fast_transformers.causal_product.causal_product_cuda
|
11 |
+
|
12 |
+
def softmax_kernel(data, *, projection_matrix, is_query, normalize_data=True, eps=1e-4, device = None):
|
13 |
+
b, h, *_ = data.shape
|
14 |
+
# (batch size, head, length, model_dim)
|
15 |
+
|
16 |
+
# normalize model dim
|
17 |
+
data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1.
|
18 |
+
|
19 |
+
# what is ration?, projection_matrix.shape[0] --> 266
|
20 |
+
|
21 |
+
ratio = (projection_matrix.shape[0] ** -0.5)
|
22 |
+
|
23 |
+
projection = repeat(projection_matrix, 'j d -> b h j d', b = b, h = h)
|
24 |
+
projection = projection.type_as(data)
|
25 |
+
|
26 |
+
#data_dash = w^T x
|
27 |
+
data_dash = torch.einsum('...id,...jd->...ij', (data_normalizer * data), projection)
|
28 |
+
|
29 |
+
|
30 |
+
# diag_data = D**2
|
31 |
+
diag_data = data ** 2
|
32 |
+
diag_data = torch.sum(diag_data, dim=-1)
|
33 |
+
diag_data = (diag_data / 2.0) * (data_normalizer ** 2)
|
34 |
+
diag_data = diag_data.unsqueeze(dim=-1)
|
35 |
+
|
36 |
+
#print ()
|
37 |
+
if is_query:
|
38 |
+
data_dash = ratio * (
|
39 |
+
torch.exp(data_dash - diag_data -
|
40 |
+
torch.max(data_dash, dim=-1, keepdim=True).values) + eps)
|
41 |
+
else:
|
42 |
+
data_dash = ratio * (
|
43 |
+
torch.exp(data_dash - diag_data + eps))#- torch.max(data_dash)) + eps)
|
44 |
+
|
45 |
+
return data_dash.type_as(data)
|
46 |
+
|
47 |
+
def orthogonal_matrix_chunk(cols, qr_uniform_q = False, device = None):
|
48 |
+
unstructured_block = torch.randn((cols, cols), device = device)
|
49 |
+
q, r = torch.linalg.qr(unstructured_block.cpu(), mode='reduced')
|
50 |
+
q, r = map(lambda t: t.to(device), (q, r))
|
51 |
+
|
52 |
+
# proposed by @Parskatt
|
53 |
+
# to make sure Q is uniform https://arxiv.org/pdf/math-ph/0609050.pdf
|
54 |
+
if qr_uniform_q:
|
55 |
+
d = torch.diag(r, 0)
|
56 |
+
q *= d.sign()
|
57 |
+
return q.t()
|
58 |
+
def exists(val):
|
59 |
+
return val is not None
|
60 |
+
|
61 |
+
def empty(tensor):
|
62 |
+
return tensor.numel() == 0
|
63 |
+
|
64 |
+
def default(val, d):
|
65 |
+
return val if exists(val) else d
|
66 |
+
|
67 |
+
def cast_tuple(val):
|
68 |
+
return (val,) if not isinstance(val, tuple) else val
|
69 |
+
|
70 |
+
class PCmer(nn.Module):
|
71 |
+
"""The encoder that is used in the Transformer model."""
|
72 |
+
|
73 |
+
def __init__(self,
|
74 |
+
num_layers,
|
75 |
+
num_heads,
|
76 |
+
dim_model,
|
77 |
+
dim_keys,
|
78 |
+
dim_values,
|
79 |
+
residual_dropout,
|
80 |
+
attention_dropout):
|
81 |
+
super().__init__()
|
82 |
+
self.num_layers = num_layers
|
83 |
+
self.num_heads = num_heads
|
84 |
+
self.dim_model = dim_model
|
85 |
+
self.dim_values = dim_values
|
86 |
+
self.dim_keys = dim_keys
|
87 |
+
self.residual_dropout = residual_dropout
|
88 |
+
self.attention_dropout = attention_dropout
|
89 |
+
|
90 |
+
self._layers = nn.ModuleList([_EncoderLayer(self) for _ in range(num_layers)])
|
91 |
+
|
92 |
+
# METHODS ########################################################################################################
|
93 |
+
|
94 |
+
def forward(self, phone, mask=None):
|
95 |
+
|
96 |
+
# apply all layers to the input
|
97 |
+
for (i, layer) in enumerate(self._layers):
|
98 |
+
phone = layer(phone, mask)
|
99 |
+
# provide the final sequence
|
100 |
+
return phone
|
101 |
+
|
102 |
+
|
103 |
+
# ==================================================================================================================== #
|
104 |
+
# CLASS _ E N C O D E R L A Y E R #
|
105 |
+
# ==================================================================================================================== #
|
106 |
+
|
107 |
+
|
108 |
+
class _EncoderLayer(nn.Module):
|
109 |
+
"""One layer of the encoder.
|
110 |
+
|
111 |
+
Attributes:
|
112 |
+
attn: (:class:`mha.MultiHeadAttention`): The attention mechanism that is used to read the input sequence.
|
113 |
+
feed_forward (:class:`ffl.FeedForwardLayer`): The feed-forward layer on top of the attention mechanism.
|
114 |
+
"""
|
115 |
+
|
116 |
+
def __init__(self, parent: PCmer):
|
117 |
+
"""Creates a new instance of ``_EncoderLayer``.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
parent (Encoder): The encoder that the layers is created for.
|
121 |
+
"""
|
122 |
+
super().__init__()
|
123 |
+
|
124 |
+
|
125 |
+
self.conformer = ConformerConvModule(parent.dim_model)
|
126 |
+
self.norm = nn.LayerNorm(parent.dim_model)
|
127 |
+
self.dropout = nn.Dropout(parent.residual_dropout)
|
128 |
+
|
129 |
+
# selfatt -> fastatt: performer!
|
130 |
+
self.attn = SelfAttention(dim = parent.dim_model,
|
131 |
+
heads = parent.num_heads,
|
132 |
+
causal = False)
|
133 |
+
|
134 |
+
# METHODS ########################################################################################################
|
135 |
+
|
136 |
+
def forward(self, phone, mask=None):
|
137 |
+
|
138 |
+
# compute attention sub-layer
|
139 |
+
phone = phone + (self.attn(self.norm(phone), mask=mask))
|
140 |
+
|
141 |
+
phone = phone + (self.conformer(phone))
|
142 |
+
|
143 |
+
return phone
|
144 |
+
|
145 |
+
def calc_same_padding(kernel_size):
|
146 |
+
pad = kernel_size // 2
|
147 |
+
return (pad, pad - (kernel_size + 1) % 2)
|
148 |
+
|
149 |
+
# helper classes
|
150 |
+
|
151 |
+
class Swish(nn.Module):
|
152 |
+
def forward(self, x):
|
153 |
+
return x * x.sigmoid()
|
154 |
+
|
155 |
+
class Transpose(nn.Module):
|
156 |
+
def __init__(self, dims):
|
157 |
+
super().__init__()
|
158 |
+
assert len(dims) == 2, 'dims must be a tuple of two dimensions'
|
159 |
+
self.dims = dims
|
160 |
+
|
161 |
+
def forward(self, x):
|
162 |
+
return x.transpose(*self.dims)
|
163 |
+
|
164 |
+
class GLU(nn.Module):
|
165 |
+
def __init__(self, dim):
|
166 |
+
super().__init__()
|
167 |
+
self.dim = dim
|
168 |
+
|
169 |
+
def forward(self, x):
|
170 |
+
out, gate = x.chunk(2, dim=self.dim)
|
171 |
+
return out * gate.sigmoid()
|
172 |
+
|
173 |
+
class DepthWiseConv1d(nn.Module):
|
174 |
+
def __init__(self, chan_in, chan_out, kernel_size, padding):
|
175 |
+
super().__init__()
|
176 |
+
self.padding = padding
|
177 |
+
self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, groups = chan_in)
|
178 |
+
|
179 |
+
def forward(self, x):
|
180 |
+
x = F.pad(x, self.padding)
|
181 |
+
return self.conv(x)
|
182 |
+
|
183 |
+
class ConformerConvModule(nn.Module):
|
184 |
+
def __init__(
|
185 |
+
self,
|
186 |
+
dim,
|
187 |
+
causal = False,
|
188 |
+
expansion_factor = 2,
|
189 |
+
kernel_size = 31,
|
190 |
+
dropout = 0.):
|
191 |
+
super().__init__()
|
192 |
+
|
193 |
+
inner_dim = dim * expansion_factor
|
194 |
+
padding = calc_same_padding(kernel_size) if not causal else (kernel_size - 1, 0)
|
195 |
+
|
196 |
+
self.net = nn.Sequential(
|
197 |
+
nn.LayerNorm(dim),
|
198 |
+
Transpose((1, 2)),
|
199 |
+
nn.Conv1d(dim, inner_dim * 2, 1),
|
200 |
+
GLU(dim=1),
|
201 |
+
DepthWiseConv1d(inner_dim, inner_dim, kernel_size = kernel_size, padding = padding),
|
202 |
+
#nn.BatchNorm1d(inner_dim) if not causal else nn.Identity(),
|
203 |
+
Swish(),
|
204 |
+
nn.Conv1d(inner_dim, dim, 1),
|
205 |
+
Transpose((1, 2)),
|
206 |
+
nn.Dropout(dropout)
|
207 |
+
)
|
208 |
+
|
209 |
+
def forward(self, x):
|
210 |
+
return self.net(x)
|
211 |
+
|
212 |
+
def linear_attention(q, k, v):
|
213 |
+
if v is None:
|
214 |
+
#print (k.size(), q.size())
|
215 |
+
out = torch.einsum('...ed,...nd->...ne', k, q)
|
216 |
+
return out
|
217 |
+
|
218 |
+
else:
|
219 |
+
k_cumsum = k.sum(dim = -2)
|
220 |
+
#k_cumsum = k.sum(dim = -2)
|
221 |
+
D_inv = 1. / (torch.einsum('...nd,...d->...n', q, k_cumsum.type_as(q)) + 1e-8)
|
222 |
+
|
223 |
+
context = torch.einsum('...nd,...ne->...de', k, v)
|
224 |
+
#print ("TRUEEE: ", context.size(), q.size(), D_inv.size())
|
225 |
+
out = torch.einsum('...de,...nd,...n->...ne', context, q, D_inv)
|
226 |
+
return out
|
227 |
+
|
228 |
+
def gaussian_orthogonal_random_matrix(nb_rows, nb_columns, scaling = 0, qr_uniform_q = False, device = None):
|
229 |
+
nb_full_blocks = int(nb_rows / nb_columns)
|
230 |
+
#print (nb_full_blocks)
|
231 |
+
block_list = []
|
232 |
+
|
233 |
+
for _ in range(nb_full_blocks):
|
234 |
+
q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)
|
235 |
+
block_list.append(q)
|
236 |
+
# block_list[n] is a orthogonal matrix ... (model_dim * model_dim)
|
237 |
+
#print (block_list[0].size(), torch.einsum('...nd,...nd->...n', block_list[0], torch.roll(block_list[0],1,1)))
|
238 |
+
#print (nb_rows, nb_full_blocks, nb_columns)
|
239 |
+
remaining_rows = nb_rows - nb_full_blocks * nb_columns
|
240 |
+
#print (remaining_rows)
|
241 |
+
if remaining_rows > 0:
|
242 |
+
q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)
|
243 |
+
#print (q[:remaining_rows].size())
|
244 |
+
block_list.append(q[:remaining_rows])
|
245 |
+
|
246 |
+
final_matrix = torch.cat(block_list)
|
247 |
+
|
248 |
+
if scaling == 0:
|
249 |
+
multiplier = torch.randn((nb_rows, nb_columns), device = device).norm(dim = 1)
|
250 |
+
elif scaling == 1:
|
251 |
+
multiplier = math.sqrt((float(nb_columns))) * torch.ones((nb_rows,), device = device)
|
252 |
+
else:
|
253 |
+
raise ValueError(f'Invalid scaling {scaling}')
|
254 |
+
|
255 |
+
return torch.diag(multiplier) @ final_matrix
|
256 |
+
|
257 |
+
class FastAttention(nn.Module):
|
258 |
+
def __init__(self, dim_heads, nb_features = None, ortho_scaling = 0, causal = False, generalized_attention = False, kernel_fn = nn.ReLU(), qr_uniform_q = False, no_projection = False):
|
259 |
+
super().__init__()
|
260 |
+
nb_features = default(nb_features, int(dim_heads * math.log(dim_heads)))
|
261 |
+
|
262 |
+
self.dim_heads = dim_heads
|
263 |
+
self.nb_features = nb_features
|
264 |
+
self.ortho_scaling = ortho_scaling
|
265 |
+
|
266 |
+
self.create_projection = partial(gaussian_orthogonal_random_matrix, nb_rows = self.nb_features, nb_columns = dim_heads, scaling = ortho_scaling, qr_uniform_q = qr_uniform_q)
|
267 |
+
projection_matrix = self.create_projection()
|
268 |
+
self.register_buffer('projection_matrix', projection_matrix)
|
269 |
+
|
270 |
+
self.generalized_attention = generalized_attention
|
271 |
+
self.kernel_fn = kernel_fn
|
272 |
+
|
273 |
+
# if this is turned on, no projection will be used
|
274 |
+
# queries and keys will be softmax-ed as in the original efficient attention paper
|
275 |
+
self.no_projection = no_projection
|
276 |
+
|
277 |
+
self.causal = causal
|
278 |
+
|
279 |
+
@torch.no_grad()
|
280 |
+
def redraw_projection_matrix(self):
|
281 |
+
projections = self.create_projection()
|
282 |
+
self.projection_matrix.copy_(projections)
|
283 |
+
del projections
|
284 |
+
|
285 |
+
def forward(self, q, k, v):
|
286 |
+
device = q.device
|
287 |
+
|
288 |
+
if self.no_projection:
|
289 |
+
q = q.softmax(dim = -1)
|
290 |
+
k = torch.exp(k) if self.causal else k.softmax(dim = -2)
|
291 |
+
else:
|
292 |
+
create_kernel = partial(softmax_kernel, projection_matrix = self.projection_matrix, device = device)
|
293 |
+
|
294 |
+
q = create_kernel(q, is_query = True)
|
295 |
+
k = create_kernel(k, is_query = False)
|
296 |
+
|
297 |
+
attn_fn = linear_attention if not self.causal else self.causal_linear_fn
|
298 |
+
if v is None:
|
299 |
+
out = attn_fn(q, k, None)
|
300 |
+
return out
|
301 |
+
else:
|
302 |
+
out = attn_fn(q, k, v)
|
303 |
+
return out
|
304 |
+
class SelfAttention(nn.Module):
|
305 |
+
def __init__(self, dim, causal = False, heads = 8, dim_head = 64, local_heads = 0, local_window_size = 256, nb_features = None, feature_redraw_interval = 1000, generalized_attention = False, kernel_fn = nn.ReLU(), qr_uniform_q = False, dropout = 0., no_projection = False):
|
306 |
+
super().__init__()
|
307 |
+
assert dim % heads == 0, 'dimension must be divisible by number of heads'
|
308 |
+
dim_head = default(dim_head, dim // heads)
|
309 |
+
inner_dim = dim_head * heads
|
310 |
+
self.fast_attention = FastAttention(dim_head, nb_features, causal = causal, generalized_attention = generalized_attention, kernel_fn = kernel_fn, qr_uniform_q = qr_uniform_q, no_projection = no_projection)
|
311 |
+
|
312 |
+
self.heads = heads
|
313 |
+
self.global_heads = heads - local_heads
|
314 |
+
self.local_attn = LocalAttention(window_size = local_window_size, causal = causal, autopad = True, dropout = dropout, look_forward = int(not causal), rel_pos_emb_config = (dim_head, local_heads)) if local_heads > 0 else None
|
315 |
+
|
316 |
+
#print (heads, nb_features, dim_head)
|
317 |
+
#name_embedding = torch.zeros(110, heads, dim_head, dim_head)
|
318 |
+
#self.name_embedding = nn.Parameter(name_embedding, requires_grad=True)
|
319 |
+
|
320 |
+
|
321 |
+
self.to_q = nn.Linear(dim, inner_dim)
|
322 |
+
self.to_k = nn.Linear(dim, inner_dim)
|
323 |
+
self.to_v = nn.Linear(dim, inner_dim)
|
324 |
+
self.to_out = nn.Linear(inner_dim, dim)
|
325 |
+
self.dropout = nn.Dropout(dropout)
|
326 |
+
|
327 |
+
@torch.no_grad()
|
328 |
+
def redraw_projection_matrix(self):
|
329 |
+
self.fast_attention.redraw_projection_matrix()
|
330 |
+
#torch.nn.init.zeros_(self.name_embedding)
|
331 |
+
#print (torch.sum(self.name_embedding))
|
332 |
+
def forward(self, x, context = None, mask = None, context_mask = None, name=None, inference=False, **kwargs):
|
333 |
+
_, _, _, h, gh = *x.shape, self.heads, self.global_heads
|
334 |
+
|
335 |
+
cross_attend = exists(context)
|
336 |
+
|
337 |
+
context = default(context, x)
|
338 |
+
context_mask = default(context_mask, mask) if not cross_attend else context_mask
|
339 |
+
#print (torch.sum(self.name_embedding))
|
340 |
+
q, k, v = self.to_q(x), self.to_k(context), self.to_v(context)
|
341 |
+
|
342 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, k, v))
|
343 |
+
(q, lq), (k, lk), (v, lv) = map(lambda t: (t[:, :gh], t[:, gh:]), (q, k, v))
|
344 |
+
|
345 |
+
attn_outs = []
|
346 |
+
#print (name)
|
347 |
+
#print (self.name_embedding[name].size())
|
348 |
+
if not empty(q):
|
349 |
+
if exists(context_mask):
|
350 |
+
global_mask = context_mask[:, None, :, None]
|
351 |
+
v.masked_fill_(~global_mask, 0.)
|
352 |
+
if cross_attend:
|
353 |
+
pass
|
354 |
+
#print (torch.sum(self.name_embedding))
|
355 |
+
#out = self.fast_attention(q,self.name_embedding[name],None)
|
356 |
+
#print (torch.sum(self.name_embedding[...,-1:]))
|
357 |
+
else:
|
358 |
+
out = self.fast_attention(q, k, v)
|
359 |
+
attn_outs.append(out)
|
360 |
+
|
361 |
+
if not empty(lq):
|
362 |
+
assert not cross_attend, 'local attention is not compatible with cross attention'
|
363 |
+
out = self.local_attn(lq, lk, lv, input_mask = mask)
|
364 |
+
attn_outs.append(out)
|
365 |
+
|
366 |
+
out = torch.cat(attn_outs, dim = 1)
|
367 |
+
out = rearrange(out, 'b h n d -> b n (h d)')
|
368 |
+
out = self.to_out(out)
|
369 |
+
return self.dropout(out)
|
modules/F0Predictor/rmvpe/__init__.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .constants import * # noqa: F403
|
2 |
+
from .inference import RMVPE # noqa: F401
|
3 |
+
from .model import E2E, E2E0 # noqa: F401
|
4 |
+
from .spec import MelSpectrogram # noqa: F401
|
5 |
+
from .utils import ( # noqa: F401
|
6 |
+
cycle,
|
7 |
+
summary,
|
8 |
+
to_local_average_cents,
|
9 |
+
to_viterbi_cents,
|
10 |
+
)
|
modules/F0Predictor/rmvpe/constants.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
SAMPLE_RATE = 16000
|
2 |
+
|
3 |
+
N_CLASS = 360
|
4 |
+
|
5 |
+
N_MELS = 128
|
6 |
+
MEL_FMIN = 30
|
7 |
+
MEL_FMAX = SAMPLE_RATE // 2
|
8 |
+
WINDOW_LENGTH = 1024
|
9 |
+
CONST = 1997.3794084376191
|
modules/F0Predictor/rmvpe/deepunet.py
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .constants import N_MELS
|
5 |
+
|
6 |
+
|
7 |
+
class ConvBlockRes(nn.Module):
|
8 |
+
def __init__(self, in_channels, out_channels, momentum=0.01):
|
9 |
+
super(ConvBlockRes, self).__init__()
|
10 |
+
self.conv = nn.Sequential(
|
11 |
+
nn.Conv2d(in_channels=in_channels,
|
12 |
+
out_channels=out_channels,
|
13 |
+
kernel_size=(3, 3),
|
14 |
+
stride=(1, 1),
|
15 |
+
padding=(1, 1),
|
16 |
+
bias=False),
|
17 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
18 |
+
nn.ReLU(),
|
19 |
+
|
20 |
+
nn.Conv2d(in_channels=out_channels,
|
21 |
+
out_channels=out_channels,
|
22 |
+
kernel_size=(3, 3),
|
23 |
+
stride=(1, 1),
|
24 |
+
padding=(1, 1),
|
25 |
+
bias=False),
|
26 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
27 |
+
nn.ReLU(),
|
28 |
+
)
|
29 |
+
if in_channels != out_channels:
|
30 |
+
self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
|
31 |
+
self.is_shortcut = True
|
32 |
+
else:
|
33 |
+
self.is_shortcut = False
|
34 |
+
|
35 |
+
def forward(self, x):
|
36 |
+
if self.is_shortcut:
|
37 |
+
return self.conv(x) + self.shortcut(x)
|
38 |
+
else:
|
39 |
+
return self.conv(x) + x
|
40 |
+
|
41 |
+
|
42 |
+
class ResEncoderBlock(nn.Module):
|
43 |
+
def __init__(self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01):
|
44 |
+
super(ResEncoderBlock, self).__init__()
|
45 |
+
self.n_blocks = n_blocks
|
46 |
+
self.conv = nn.ModuleList()
|
47 |
+
self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
|
48 |
+
for i in range(n_blocks - 1):
|
49 |
+
self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
|
50 |
+
self.kernel_size = kernel_size
|
51 |
+
if self.kernel_size is not None:
|
52 |
+
self.pool = nn.AvgPool2d(kernel_size=kernel_size)
|
53 |
+
|
54 |
+
def forward(self, x):
|
55 |
+
for i in range(self.n_blocks):
|
56 |
+
x = self.conv[i](x)
|
57 |
+
if self.kernel_size is not None:
|
58 |
+
return x, self.pool(x)
|
59 |
+
else:
|
60 |
+
return x
|
61 |
+
|
62 |
+
|
63 |
+
class ResDecoderBlock(nn.Module):
|
64 |
+
def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
|
65 |
+
super(ResDecoderBlock, self).__init__()
|
66 |
+
out_padding = (0, 1) if stride == (1, 2) else (1, 1)
|
67 |
+
self.n_blocks = n_blocks
|
68 |
+
self.conv1 = nn.Sequential(
|
69 |
+
nn.ConvTranspose2d(in_channels=in_channels,
|
70 |
+
out_channels=out_channels,
|
71 |
+
kernel_size=(3, 3),
|
72 |
+
stride=stride,
|
73 |
+
padding=(1, 1),
|
74 |
+
output_padding=out_padding,
|
75 |
+
bias=False),
|
76 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
77 |
+
nn.ReLU(),
|
78 |
+
)
|
79 |
+
self.conv2 = nn.ModuleList()
|
80 |
+
self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
|
81 |
+
for i in range(n_blocks-1):
|
82 |
+
self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
|
83 |
+
|
84 |
+
def forward(self, x, concat_tensor):
|
85 |
+
x = self.conv1(x)
|
86 |
+
x = torch.cat((x, concat_tensor), dim=1)
|
87 |
+
for i in range(self.n_blocks):
|
88 |
+
x = self.conv2[i](x)
|
89 |
+
return x
|
90 |
+
|
91 |
+
|
92 |
+
class Encoder(nn.Module):
|
93 |
+
def __init__(self, in_channels, in_size, n_encoders, kernel_size, n_blocks, out_channels=16, momentum=0.01):
|
94 |
+
super(Encoder, self).__init__()
|
95 |
+
self.n_encoders = n_encoders
|
96 |
+
self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
|
97 |
+
self.layers = nn.ModuleList()
|
98 |
+
self.latent_channels = []
|
99 |
+
for i in range(self.n_encoders):
|
100 |
+
self.layers.append(ResEncoderBlock(in_channels, out_channels, kernel_size, n_blocks, momentum=momentum))
|
101 |
+
self.latent_channels.append([out_channels, in_size])
|
102 |
+
in_channels = out_channels
|
103 |
+
out_channels *= 2
|
104 |
+
in_size //= 2
|
105 |
+
self.out_size = in_size
|
106 |
+
self.out_channel = out_channels
|
107 |
+
|
108 |
+
def forward(self, x):
|
109 |
+
concat_tensors = []
|
110 |
+
x = self.bn(x)
|
111 |
+
for i in range(self.n_encoders):
|
112 |
+
_, x = self.layers[i](x)
|
113 |
+
concat_tensors.append(_)
|
114 |
+
return x, concat_tensors
|
115 |
+
|
116 |
+
|
117 |
+
class Intermediate(nn.Module):
|
118 |
+
def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
|
119 |
+
super(Intermediate, self).__init__()
|
120 |
+
self.n_inters = n_inters
|
121 |
+
self.layers = nn.ModuleList()
|
122 |
+
self.layers.append(ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum))
|
123 |
+
for i in range(self.n_inters-1):
|
124 |
+
self.layers.append(ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum))
|
125 |
+
|
126 |
+
def forward(self, x):
|
127 |
+
for i in range(self.n_inters):
|
128 |
+
x = self.layers[i](x)
|
129 |
+
return x
|
130 |
+
|
131 |
+
|
132 |
+
class Decoder(nn.Module):
|
133 |
+
def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
|
134 |
+
super(Decoder, self).__init__()
|
135 |
+
self.layers = nn.ModuleList()
|
136 |
+
self.n_decoders = n_decoders
|
137 |
+
for i in range(self.n_decoders):
|
138 |
+
out_channels = in_channels // 2
|
139 |
+
self.layers.append(ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum))
|
140 |
+
in_channels = out_channels
|
141 |
+
|
142 |
+
def forward(self, x, concat_tensors):
|
143 |
+
for i in range(self.n_decoders):
|
144 |
+
x = self.layers[i](x, concat_tensors[-1-i])
|
145 |
+
return x
|
146 |
+
|
147 |
+
|
148 |
+
class TimbreFilter(nn.Module):
|
149 |
+
def __init__(self, latent_rep_channels):
|
150 |
+
super(TimbreFilter, self).__init__()
|
151 |
+
self.layers = nn.ModuleList()
|
152 |
+
for latent_rep in latent_rep_channels:
|
153 |
+
self.layers.append(ConvBlockRes(latent_rep[0], latent_rep[0]))
|
154 |
+
|
155 |
+
def forward(self, x_tensors):
|
156 |
+
out_tensors = []
|
157 |
+
for i, layer in enumerate(self.layers):
|
158 |
+
out_tensors.append(layer(x_tensors[i]))
|
159 |
+
return out_tensors
|
160 |
+
|
161 |
+
|
162 |
+
class DeepUnet(nn.Module):
|
163 |
+
def __init__(self, kernel_size, n_blocks, en_de_layers=5, inter_layers=4, in_channels=1, en_out_channels=16):
|
164 |
+
super(DeepUnet, self).__init__()
|
165 |
+
self.encoder = Encoder(in_channels, N_MELS, en_de_layers, kernel_size, n_blocks, en_out_channels)
|
166 |
+
self.intermediate = Intermediate(self.encoder.out_channel // 2, self.encoder.out_channel, inter_layers, n_blocks)
|
167 |
+
self.tf = TimbreFilter(self.encoder.latent_channels)
|
168 |
+
self.decoder = Decoder(self.encoder.out_channel, en_de_layers, kernel_size, n_blocks)
|
169 |
+
|
170 |
+
def forward(self, x):
|
171 |
+
x, concat_tensors = self.encoder(x)
|
172 |
+
x = self.intermediate(x)
|
173 |
+
concat_tensors = self.tf(concat_tensors)
|
174 |
+
x = self.decoder(x, concat_tensors)
|
175 |
+
return x
|
176 |
+
|
177 |
+
|
178 |
+
class DeepUnet0(nn.Module):
|
179 |
+
def __init__(self, kernel_size, n_blocks, en_de_layers=5, inter_layers=4, in_channels=1, en_out_channels=16):
|
180 |
+
super(DeepUnet0, self).__init__()
|
181 |
+
self.encoder = Encoder(in_channels, N_MELS, en_de_layers, kernel_size, n_blocks, en_out_channels)
|
182 |
+
self.intermediate = Intermediate(self.encoder.out_channel // 2, self.encoder.out_channel, inter_layers, n_blocks)
|
183 |
+
self.tf = TimbreFilter(self.encoder.latent_channels)
|
184 |
+
self.decoder = Decoder(self.encoder.out_channel, en_de_layers, kernel_size, n_blocks)
|
185 |
+
|
186 |
+
def forward(self, x):
|
187 |
+
x, concat_tensors = self.encoder(x)
|
188 |
+
x = self.intermediate(x)
|
189 |
+
x = self.decoder(x, concat_tensors)
|
190 |
+
return x
|
modules/F0Predictor/rmvpe/inference.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from torchaudio.transforms import Resample
|
4 |
+
|
5 |
+
from .constants import * # noqa: F403
|
6 |
+
from .model import E2E0
|
7 |
+
from .spec import MelSpectrogram
|
8 |
+
from .utils import to_local_average_cents, to_viterbi_cents
|
9 |
+
|
10 |
+
|
11 |
+
class RMVPE:
|
12 |
+
def __init__(self, model_path, device=None, dtype = torch.float32, hop_length=160):
|
13 |
+
self.resample_kernel = {}
|
14 |
+
if device is None:
|
15 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
16 |
+
else:
|
17 |
+
self.device = device
|
18 |
+
model = E2E0(4, 1, (2, 2))
|
19 |
+
ckpt = torch.load(model_path, map_location=torch.device(self.device))
|
20 |
+
model.load_state_dict(ckpt['model'])
|
21 |
+
model = model.to(dtype).to(self.device)
|
22 |
+
model.eval()
|
23 |
+
self.model = model
|
24 |
+
self.dtype = dtype
|
25 |
+
self.mel_extractor = MelSpectrogram(N_MELS, SAMPLE_RATE, WINDOW_LENGTH, hop_length, None, MEL_FMIN, MEL_FMAX) # noqa: F405
|
26 |
+
self.resample_kernel = {}
|
27 |
+
|
28 |
+
def mel2hidden(self, mel):
|
29 |
+
with torch.no_grad():
|
30 |
+
n_frames = mel.shape[-1]
|
31 |
+
mel = F.pad(mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode='constant')
|
32 |
+
hidden = self.model(mel)
|
33 |
+
return hidden[:, :n_frames]
|
34 |
+
|
35 |
+
def decode(self, hidden, thred=0.03, use_viterbi=False):
|
36 |
+
if use_viterbi:
|
37 |
+
cents_pred = to_viterbi_cents(hidden, thred=thred)
|
38 |
+
else:
|
39 |
+
cents_pred = to_local_average_cents(hidden, thred=thred)
|
40 |
+
f0 = torch.Tensor([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred]).to(self.device)
|
41 |
+
return f0
|
42 |
+
|
43 |
+
def infer_from_audio(self, audio, sample_rate=16000, thred=0.05, use_viterbi=False):
|
44 |
+
audio = audio.unsqueeze(0).to(self.dtype).to(self.device)
|
45 |
+
if sample_rate == 16000:
|
46 |
+
audio_res = audio
|
47 |
+
else:
|
48 |
+
key_str = str(sample_rate)
|
49 |
+
if key_str not in self.resample_kernel:
|
50 |
+
self.resample_kernel[key_str] = Resample(sample_rate, 16000, lowpass_filter_width=128)
|
51 |
+
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.dtype).to(self.device)
|
52 |
+
audio_res = self.resample_kernel[key_str](audio)
|
53 |
+
mel_extractor = self.mel_extractor.to(self.device)
|
54 |
+
mel = mel_extractor(audio_res, center=True).to(self.dtype)
|
55 |
+
hidden = self.mel2hidden(mel)
|
56 |
+
f0 = self.decode(hidden.squeeze(0), thred=thred, use_viterbi=use_viterbi)
|
57 |
+
return f0
|
modules/F0Predictor/rmvpe/model.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
|
3 |
+
from .constants import * # noqa: F403
|
4 |
+
from .deepunet import DeepUnet, DeepUnet0
|
5 |
+
from .seq import BiGRU
|
6 |
+
from .spec import MelSpectrogram
|
7 |
+
|
8 |
+
|
9 |
+
class E2E(nn.Module):
|
10 |
+
def __init__(self, hop_length, n_blocks, n_gru, kernel_size, en_de_layers=5, inter_layers=4, in_channels=1,
|
11 |
+
en_out_channels=16):
|
12 |
+
super(E2E, self).__init__()
|
13 |
+
self.mel = MelSpectrogram(N_MELS, SAMPLE_RATE, WINDOW_LENGTH, hop_length, None, MEL_FMIN, MEL_FMAX) # noqa: F405
|
14 |
+
self.unet = DeepUnet(kernel_size, n_blocks, en_de_layers, inter_layers, in_channels, en_out_channels)
|
15 |
+
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
|
16 |
+
if n_gru:
|
17 |
+
self.fc = nn.Sequential(
|
18 |
+
BiGRU(3 * N_MELS, 256, n_gru), # noqa: F405
|
19 |
+
nn.Linear(512, N_CLASS), # noqa: F405
|
20 |
+
nn.Dropout(0.25),
|
21 |
+
nn.Sigmoid()
|
22 |
+
)
|
23 |
+
else:
|
24 |
+
self.fc = nn.Sequential(
|
25 |
+
nn.Linear(3 * N_MELS, N_CLASS), # noqa: F405
|
26 |
+
nn.Dropout(0.25),
|
27 |
+
nn.Sigmoid()
|
28 |
+
)
|
29 |
+
|
30 |
+
def forward(self, x):
|
31 |
+
mel = self.mel(x.reshape(-1, x.shape[-1])).transpose(-1, -2).unsqueeze(1)
|
32 |
+
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
|
33 |
+
# x = self.fc(x)
|
34 |
+
hidden_vec = 0
|
35 |
+
if len(self.fc) == 4:
|
36 |
+
for i in range(len(self.fc)):
|
37 |
+
x = self.fc[i](x)
|
38 |
+
if i == 0:
|
39 |
+
hidden_vec = x
|
40 |
+
return hidden_vec, x
|
41 |
+
|
42 |
+
|
43 |
+
class E2E0(nn.Module):
|
44 |
+
def __init__(self, n_blocks, n_gru, kernel_size, en_de_layers=5, inter_layers=4, in_channels=1,
|
45 |
+
en_out_channels=16):
|
46 |
+
super(E2E0, self).__init__()
|
47 |
+
self.unet = DeepUnet0(kernel_size, n_blocks, en_de_layers, inter_layers, in_channels, en_out_channels)
|
48 |
+
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
|
49 |
+
if n_gru:
|
50 |
+
self.fc = nn.Sequential(
|
51 |
+
BiGRU(3 * N_MELS, 256, n_gru), # noqa: F405
|
52 |
+
nn.Linear(512, N_CLASS), # noqa: F405
|
53 |
+
nn.Dropout(0.25),
|
54 |
+
nn.Sigmoid()
|
55 |
+
)
|
56 |
+
else:
|
57 |
+
self.fc = nn.Sequential(
|
58 |
+
nn.Linear(3 * N_MELS, N_CLASS), # noqa: F405
|
59 |
+
nn.Dropout(0.25),
|
60 |
+
nn.Sigmoid()
|
61 |
+
)
|
62 |
+
|
63 |
+
def forward(self, mel):
|
64 |
+
mel = mel.transpose(-1, -2).unsqueeze(1)
|
65 |
+
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
|
66 |
+
x = self.fc(x)
|
67 |
+
return x
|
modules/F0Predictor/rmvpe/seq.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
|
3 |
+
|
4 |
+
class BiGRU(nn.Module):
|
5 |
+
def __init__(self, input_features, hidden_features, num_layers):
|
6 |
+
super(BiGRU, self).__init__()
|
7 |
+
self.gru = nn.GRU(input_features, hidden_features, num_layers=num_layers, batch_first=True, bidirectional=True)
|
8 |
+
|
9 |
+
def forward(self, x):
|
10 |
+
return self.gru(x)[0]
|
11 |
+
|
12 |
+
|
13 |
+
class BiLSTM(nn.Module):
|
14 |
+
def __init__(self, input_features, hidden_features, num_layers):
|
15 |
+
super(BiLSTM, self).__init__()
|
16 |
+
self.lstm = nn.LSTM(input_features, hidden_features, num_layers=num_layers, batch_first=True, bidirectional=True)
|
17 |
+
|
18 |
+
def forward(self, x):
|
19 |
+
return self.lstm(x)[0]
|
20 |
+
|
modules/F0Predictor/rmvpe/spec.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from librosa.filters import mel
|
5 |
+
|
6 |
+
|
7 |
+
class MelSpectrogram(torch.nn.Module):
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
n_mel_channels,
|
11 |
+
sampling_rate,
|
12 |
+
win_length,
|
13 |
+
hop_length,
|
14 |
+
n_fft=None,
|
15 |
+
mel_fmin=0,
|
16 |
+
mel_fmax=None,
|
17 |
+
clamp = 1e-5
|
18 |
+
):
|
19 |
+
super().__init__()
|
20 |
+
n_fft = win_length if n_fft is None else n_fft
|
21 |
+
self.hann_window = {}
|
22 |
+
mel_basis = mel(
|
23 |
+
sr=sampling_rate,
|
24 |
+
n_fft=n_fft,
|
25 |
+
n_mels=n_mel_channels,
|
26 |
+
fmin=mel_fmin,
|
27 |
+
fmax=mel_fmax,
|
28 |
+
htk=True)
|
29 |
+
mel_basis = torch.from_numpy(mel_basis).float()
|
30 |
+
self.register_buffer("mel_basis", mel_basis)
|
31 |
+
self.n_fft = win_length if n_fft is None else n_fft
|
32 |
+
self.hop_length = hop_length
|
33 |
+
self.win_length = win_length
|
34 |
+
self.sampling_rate = sampling_rate
|
35 |
+
self.n_mel_channels = n_mel_channels
|
36 |
+
self.clamp = clamp
|
37 |
+
|
38 |
+
def forward(self, audio, keyshift=0, speed=1, center=True):
|
39 |
+
factor = 2 ** (keyshift / 12)
|
40 |
+
n_fft_new = int(np.round(self.n_fft * factor))
|
41 |
+
win_length_new = int(np.round(self.win_length * factor))
|
42 |
+
hop_length_new = int(np.round(self.hop_length * speed))
|
43 |
+
|
44 |
+
keyshift_key = str(keyshift)+'_'+str(audio.device)
|
45 |
+
if keyshift_key not in self.hann_window:
|
46 |
+
self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(audio.device)
|
47 |
+
|
48 |
+
fft = torch.stft(
|
49 |
+
audio,
|
50 |
+
n_fft=n_fft_new,
|
51 |
+
hop_length=hop_length_new,
|
52 |
+
win_length=win_length_new,
|
53 |
+
window=self.hann_window[keyshift_key],
|
54 |
+
center=center,
|
55 |
+
return_complex=True)
|
56 |
+
magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
|
57 |
+
|
58 |
+
if keyshift != 0:
|
59 |
+
size = self.n_fft // 2 + 1
|
60 |
+
resize = magnitude.size(1)
|
61 |
+
if resize < size:
|
62 |
+
magnitude = F.pad(magnitude, (0, 0, 0, size-resize))
|
63 |
+
magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
|
64 |
+
|
65 |
+
mel_output = torch.matmul(self.mel_basis, magnitude)
|
66 |
+
log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
|
67 |
+
return log_mel_spec
|
modules/F0Predictor/rmvpe/utils.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from functools import reduce
|
3 |
+
|
4 |
+
import librosa
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
from torch.nn.modules.module import _addindent
|
8 |
+
|
9 |
+
from .constants import * # noqa: F403
|
10 |
+
|
11 |
+
|
12 |
+
def cycle(iterable):
|
13 |
+
while True:
|
14 |
+
for item in iterable:
|
15 |
+
yield item
|
16 |
+
|
17 |
+
|
18 |
+
def summary(model, file=sys.stdout):
|
19 |
+
def repr(model):
|
20 |
+
# We treat the extra repr like the sub-module, one item per line
|
21 |
+
extra_lines = []
|
22 |
+
extra_repr = model.extra_repr()
|
23 |
+
# empty string will be split into list ['']
|
24 |
+
if extra_repr:
|
25 |
+
extra_lines = extra_repr.split('\n')
|
26 |
+
child_lines = []
|
27 |
+
total_params = 0
|
28 |
+
for key, module in model._modules.items():
|
29 |
+
mod_str, num_params = repr(module)
|
30 |
+
mod_str = _addindent(mod_str, 2)
|
31 |
+
child_lines.append('(' + key + '): ' + mod_str)
|
32 |
+
total_params += num_params
|
33 |
+
lines = extra_lines + child_lines
|
34 |
+
|
35 |
+
for name, p in model._parameters.items():
|
36 |
+
if hasattr(p, 'shape'):
|
37 |
+
total_params += reduce(lambda x, y: x * y, p.shape)
|
38 |
+
|
39 |
+
main_str = model._get_name() + '('
|
40 |
+
if lines:
|
41 |
+
# simple one-liner info, which most builtin Modules will use
|
42 |
+
if len(extra_lines) == 1 and not child_lines:
|
43 |
+
main_str += extra_lines[0]
|
44 |
+
else:
|
45 |
+
main_str += '\n ' + '\n '.join(lines) + '\n'
|
46 |
+
|
47 |
+
main_str += ')'
|
48 |
+
if file is sys.stdout:
|
49 |
+
main_str += ', \033[92m{:,}\033[0m params'.format(total_params)
|
50 |
+
else:
|
51 |
+
main_str += ', {:,} params'.format(total_params)
|
52 |
+
return main_str, total_params
|
53 |
+
|
54 |
+
string, count = repr(model)
|
55 |
+
if file is not None:
|
56 |
+
if isinstance(file, str):
|
57 |
+
file = open(file, 'w')
|
58 |
+
print(string, file=file)
|
59 |
+
file.flush()
|
60 |
+
|
61 |
+
return count
|
62 |
+
|
63 |
+
|
64 |
+
def to_local_average_cents(salience, center=None, thred=0.05):
|
65 |
+
"""
|
66 |
+
find the weighted average cents near the argmax bin
|
67 |
+
"""
|
68 |
+
|
69 |
+
if not hasattr(to_local_average_cents, 'cents_mapping'):
|
70 |
+
# the bin number-to-cents mapping
|
71 |
+
to_local_average_cents.cents_mapping = (
|
72 |
+
20 * torch.arange(N_CLASS) + CONST).to(salience.device) # noqa: F405
|
73 |
+
|
74 |
+
if salience.ndim == 1:
|
75 |
+
if center is None:
|
76 |
+
center = int(torch.argmax(salience))
|
77 |
+
start = max(0, center - 4)
|
78 |
+
end = min(len(salience), center + 5)
|
79 |
+
salience = salience[start:end]
|
80 |
+
product_sum = torch.sum(
|
81 |
+
salience * to_local_average_cents.cents_mapping[start:end])
|
82 |
+
weight_sum = torch.sum(salience)
|
83 |
+
return product_sum / weight_sum if torch.max(salience) > thred else 0
|
84 |
+
if salience.ndim == 2:
|
85 |
+
return torch.Tensor([to_local_average_cents(salience[i, :], None, thred) for i in
|
86 |
+
range(salience.shape[0])]).to(salience.device)
|
87 |
+
|
88 |
+
raise Exception("label should be either 1d or 2d ndarray")
|
89 |
+
|
90 |
+
def to_viterbi_cents(salience, thred=0.05):
|
91 |
+
# Create viterbi transition matrix
|
92 |
+
if not hasattr(to_viterbi_cents, 'transition'):
|
93 |
+
xx, yy = torch.meshgrid(range(N_CLASS), range(N_CLASS)) # noqa: F405
|
94 |
+
transition = torch.maximum(30 - abs(xx - yy), 0)
|
95 |
+
transition = transition / transition.sum(axis=1, keepdims=True)
|
96 |
+
to_viterbi_cents.transition = transition
|
97 |
+
|
98 |
+
# Convert to probability
|
99 |
+
prob = salience.T
|
100 |
+
prob = prob / prob.sum(axis=0)
|
101 |
+
|
102 |
+
# Perform viterbi decoding
|
103 |
+
path = librosa.sequence.viterbi(prob.detach().cpu().numpy(), to_viterbi_cents.transition).astype(np.int64)
|
104 |
+
|
105 |
+
return torch.Tensor([to_local_average_cents(salience[i, :], path[i], thred) for i in
|
106 |
+
range(len(path))]).to(salience.device)
|
107 |
+
|
modules/attentions.py
CHANGED
@@ -1,18 +1,17 @@
|
|
1 |
-
import copy
|
2 |
import math
|
3 |
-
|
4 |
import torch
|
5 |
from torch import nn
|
6 |
from torch.nn import functional as F
|
7 |
|
8 |
import modules.commons as commons
|
9 |
-
|
10 |
from modules.modules import LayerNorm
|
11 |
|
12 |
|
13 |
class FFT(nn.Module):
|
14 |
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0.,
|
15 |
-
proximal_bias=False, proximal_init=True, **kwargs):
|
16 |
super().__init__()
|
17 |
self.hidden_channels = hidden_channels
|
18 |
self.filter_channels = filter_channels
|
@@ -22,7 +21,11 @@ class FFT(nn.Module):
|
|
22 |
self.p_dropout = p_dropout
|
23 |
self.proximal_bias = proximal_bias
|
24 |
self.proximal_init = proximal_init
|
25 |
-
|
|
|
|
|
|
|
|
|
26 |
self.drop = nn.Dropout(p_dropout)
|
27 |
self.self_attn_layers = nn.ModuleList()
|
28 |
self.norm_layers_0 = nn.ModuleList()
|
@@ -37,14 +40,25 @@ class FFT(nn.Module):
|
|
37 |
FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
|
38 |
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
39 |
|
40 |
-
def forward(self, x, x_mask):
|
41 |
"""
|
42 |
x: decoder input
|
43 |
h: encoder output
|
44 |
"""
|
|
|
|
|
|
|
45 |
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
46 |
x = x * x_mask
|
47 |
for i in range(self.n_layers):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
49 |
y = self.drop(y)
|
50 |
x = self.norm_layers_0[i](x + y)
|
@@ -243,7 +257,7 @@ class MultiHeadAttention(nn.Module):
|
|
243 |
return ret
|
244 |
|
245 |
def _get_relative_embeddings(self, relative_embeddings, length):
|
246 |
-
|
247 |
# Pad first before slice to avoid using cond ops.
|
248 |
pad_length = max(length - (self.window_size + 1), 0)
|
249 |
slice_start_position = max((self.window_size + 1) - length, 0)
|
|
|
|
|
1 |
import math
|
2 |
+
|
3 |
import torch
|
4 |
from torch import nn
|
5 |
from torch.nn import functional as F
|
6 |
|
7 |
import modules.commons as commons
|
8 |
+
from modules.DSConv import weight_norm_modules
|
9 |
from modules.modules import LayerNorm
|
10 |
|
11 |
|
12 |
class FFT(nn.Module):
|
13 |
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0.,
|
14 |
+
proximal_bias=False, proximal_init=True, isflow = False, **kwargs):
|
15 |
super().__init__()
|
16 |
self.hidden_channels = hidden_channels
|
17 |
self.filter_channels = filter_channels
|
|
|
21 |
self.p_dropout = p_dropout
|
22 |
self.proximal_bias = proximal_bias
|
23 |
self.proximal_init = proximal_init
|
24 |
+
if isflow:
|
25 |
+
cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2*hidden_channels*n_layers, 1)
|
26 |
+
self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
27 |
+
self.cond_layer = weight_norm_modules(cond_layer, name='weight')
|
28 |
+
self.gin_channels = kwargs["gin_channels"]
|
29 |
self.drop = nn.Dropout(p_dropout)
|
30 |
self.self_attn_layers = nn.ModuleList()
|
31 |
self.norm_layers_0 = nn.ModuleList()
|
|
|
40 |
FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
|
41 |
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
42 |
|
43 |
+
def forward(self, x, x_mask, g = None):
|
44 |
"""
|
45 |
x: decoder input
|
46 |
h: encoder output
|
47 |
"""
|
48 |
+
if g is not None:
|
49 |
+
g = self.cond_layer(g)
|
50 |
+
|
51 |
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
52 |
x = x * x_mask
|
53 |
for i in range(self.n_layers):
|
54 |
+
if g is not None:
|
55 |
+
x = self.cond_pre(x)
|
56 |
+
cond_offset = i * 2 * self.hidden_channels
|
57 |
+
g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
|
58 |
+
x = commons.fused_add_tanh_sigmoid_multiply(
|
59 |
+
x,
|
60 |
+
g_l,
|
61 |
+
torch.IntTensor([self.hidden_channels]))
|
62 |
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
63 |
y = self.drop(y)
|
64 |
x = self.norm_layers_0[i](x + y)
|
|
|
257 |
return ret
|
258 |
|
259 |
def _get_relative_embeddings(self, relative_embeddings, length):
|
260 |
+
2 * self.window_size + 1
|
261 |
# Pad first before slice to avoid using cond ops.
|
262 |
pad_length = max(length - (self.window_size + 1), 0)
|
263 |
slice_start_position = max((self.window_size + 1) - length, 0)
|
modules/commons.py
CHANGED
@@ -1,9 +1,9 @@
|
|
1 |
import math
|
2 |
-
|
3 |
import torch
|
4 |
-
from torch import nn
|
5 |
from torch.nn import functional as F
|
6 |
|
|
|
7 |
def slice_pitch_segments(x, ids_str, segment_size=4):
|
8 |
ret = torch.zeros_like(x[:, :segment_size])
|
9 |
for i in range(x.size(0)):
|
@@ -24,10 +24,12 @@ def rand_slice_segments_with_pitch(x, pitch, x_lengths=None, segment_size=4):
|
|
24 |
|
25 |
def init_weights(m, mean=0.0, std=0.01):
|
26 |
classname = m.__class__.__name__
|
27 |
-
if
|
|
|
|
|
|
|
28 |
m.weight.data.normal_(mean, std)
|
29 |
|
30 |
-
|
31 |
def get_padding(kernel_size, dilation=1):
|
32 |
return int((kernel_size*dilation - dilation)/2)
|
33 |
|
@@ -134,12 +136,6 @@ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
|
134 |
return acts
|
135 |
|
136 |
|
137 |
-
def convert_pad_shape(pad_shape):
|
138 |
-
l = pad_shape[::-1]
|
139 |
-
pad_shape = [item for sublist in l for item in sublist]
|
140 |
-
return pad_shape
|
141 |
-
|
142 |
-
|
143 |
def shift_1d(x):
|
144 |
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
145 |
return x
|
@@ -157,7 +153,6 @@ def generate_path(duration, mask):
|
|
157 |
duration: [b, 1, t_x]
|
158 |
mask: [b, 1, t_y, t_x]
|
159 |
"""
|
160 |
-
device = duration.device
|
161 |
|
162 |
b, _, t_y, t_x = mask.shape
|
163 |
cum_duration = torch.cumsum(duration, -1)
|
|
|
1 |
import math
|
2 |
+
|
3 |
import torch
|
|
|
4 |
from torch.nn import functional as F
|
5 |
|
6 |
+
|
7 |
def slice_pitch_segments(x, ids_str, segment_size=4):
|
8 |
ret = torch.zeros_like(x[:, :segment_size])
|
9 |
for i in range(x.size(0)):
|
|
|
24 |
|
25 |
def init_weights(m, mean=0.0, std=0.01):
|
26 |
classname = m.__class__.__name__
|
27 |
+
if "Depthwise_Separable" in classname:
|
28 |
+
m.depth_conv.weight.data.normal_(mean, std)
|
29 |
+
m.point_conv.weight.data.normal_(mean, std)
|
30 |
+
elif classname.find("Conv") != -1:
|
31 |
m.weight.data.normal_(mean, std)
|
32 |
|
|
|
33 |
def get_padding(kernel_size, dilation=1):
|
34 |
return int((kernel_size*dilation - dilation)/2)
|
35 |
|
|
|
136 |
return acts
|
137 |
|
138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
def shift_1d(x):
|
140 |
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
141 |
return x
|
|
|
153 |
duration: [b, 1, t_x]
|
154 |
mask: [b, 1, t_y, t_x]
|
155 |
"""
|
|
|
156 |
|
157 |
b, _, t_y, t_x = mask.shape
|
158 |
cum_duration = torch.cumsum(duration, -1)
|
modules/enhancer.py
CHANGED
@@ -1,10 +1,12 @@
|
|
1 |
import numpy as np
|
2 |
import torch
|
3 |
import torch.nn.functional as F
|
4 |
-
from vdecoder.nsf_hifigan.nvSTFT import STFT
|
5 |
-
from vdecoder.nsf_hifigan.models import load_model
|
6 |
from torchaudio.transforms import Resample
|
7 |
|
|
|
|
|
|
|
|
|
8 |
class Enhancer:
|
9 |
def __init__(self, enhancer_type, enhancer_ckpt, device=None):
|
10 |
if device is None:
|
|
|
1 |
import numpy as np
|
2 |
import torch
|
3 |
import torch.nn.functional as F
|
|
|
|
|
4 |
from torchaudio.transforms import Resample
|
5 |
|
6 |
+
from vdecoder.nsf_hifigan.models import load_model
|
7 |
+
from vdecoder.nsf_hifigan.nvSTFT import STFT
|
8 |
+
|
9 |
+
|
10 |
class Enhancer:
|
11 |
def __init__(self, enhancer_type, enhancer_ckpt, device=None):
|
12 |
if device is None:
|
modules/losses.py
CHANGED
@@ -1,7 +1,4 @@
|
|
1 |
-
import torch
|
2 |
-
from torch.nn import functional as F
|
3 |
-
|
4 |
-
import modules.commons as commons
|
5 |
|
6 |
|
7 |
def feature_loss(fmap_r, fmap_g):
|
|
|
1 |
+
import torch
|
|
|
|
|
|
|
2 |
|
3 |
|
4 |
def feature_loss(fmap_r, fmap_g):
|
modules/mel_processing.py
CHANGED
@@ -1,16 +1,5 @@
|
|
1 |
-
import math
|
2 |
-
import os
|
3 |
-
import random
|
4 |
import torch
|
5 |
-
from torch import nn
|
6 |
-
import torch.nn.functional as F
|
7 |
import torch.utils.data
|
8 |
-
import numpy as np
|
9 |
-
import librosa
|
10 |
-
import librosa.util as librosa_util
|
11 |
-
from librosa.util import normalize, pad_center, tiny
|
12 |
-
from scipy.signal import get_window
|
13 |
-
from scipy.io.wavfile import read
|
14 |
from librosa.filters import mel as librosa_mel_fn
|
15 |
|
16 |
MAX_WAV_VALUE = 32768.0
|
@@ -62,9 +51,14 @@ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False)
|
|
62 |
|
63 |
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
64 |
y = y.squeeze(1)
|
|
|
|
|
|
|
|
|
65 |
|
66 |
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
67 |
-
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=
|
|
|
68 |
|
69 |
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
70 |
return spec
|
@@ -83,30 +77,7 @@ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
|
|
83 |
|
84 |
|
85 |
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
print('max value is ', torch.max(y))
|
90 |
-
|
91 |
-
global mel_basis, hann_window
|
92 |
-
dtype_device = str(y.dtype) + '_' + str(y.device)
|
93 |
-
fmax_dtype_device = str(fmax) + '_' + dtype_device
|
94 |
-
wnsize_dtype_device = str(win_size) + '_' + dtype_device
|
95 |
-
if fmax_dtype_device not in mel_basis:
|
96 |
-
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
|
97 |
-
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
|
98 |
-
if wnsize_dtype_device not in hann_window:
|
99 |
-
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
|
100 |
-
|
101 |
-
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
102 |
-
y = y.squeeze(1)
|
103 |
-
|
104 |
-
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
105 |
-
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
|
106 |
-
|
107 |
-
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
108 |
-
|
109 |
-
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
110 |
-
spec = spectral_normalize_torch(spec)
|
111 |
-
|
112 |
return spec
|
|
|
|
|
|
|
|
|
1 |
import torch
|
|
|
|
|
2 |
import torch.utils.data
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from librosa.filters import mel as librosa_mel_fn
|
4 |
|
5 |
MAX_WAV_VALUE = 32768.0
|
|
|
51 |
|
52 |
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
53 |
y = y.squeeze(1)
|
54 |
+
|
55 |
+
y_dtype = y.dtype
|
56 |
+
if y.dtype == torch.bfloat16:
|
57 |
+
y = y.to(torch.float32)
|
58 |
|
59 |
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
60 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
|
61 |
+
spec = torch.view_as_real(spec).to(y_dtype)
|
62 |
|
63 |
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
64 |
return spec
|
|
|
77 |
|
78 |
|
79 |
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
|
80 |
+
spec = spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center)
|
81 |
+
spec = spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax)
|
82 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
return spec
|
modules/modules.py
CHANGED
@@ -1,20 +1,24 @@
|
|
1 |
-
import copy
|
2 |
-
import math
|
3 |
-
import numpy as np
|
4 |
-
import scipy
|
5 |
import torch
|
6 |
from torch import nn
|
7 |
from torch.nn import functional as F
|
8 |
|
9 |
-
|
10 |
-
from torch.nn.utils import weight_norm, remove_weight_norm
|
11 |
-
|
12 |
import modules.commons as commons
|
13 |
-
from modules.commons import
|
14 |
-
|
|
|
|
|
|
|
|
|
15 |
|
16 |
LRELU_SLOPE = 0.1
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
class LayerNorm(nn.Module):
|
20 |
def __init__(self, channels, eps=1e-5):
|
@@ -44,13 +48,13 @@ class ConvReluNorm(nn.Module):
|
|
44 |
|
45 |
self.conv_layers = nn.ModuleList()
|
46 |
self.norm_layers = nn.ModuleList()
|
47 |
-
self.conv_layers.append(
|
48 |
self.norm_layers.append(LayerNorm(hidden_channels))
|
49 |
self.relu_drop = nn.Sequential(
|
50 |
nn.ReLU(),
|
51 |
nn.Dropout(p_dropout))
|
52 |
for _ in range(n_layers-1):
|
53 |
-
self.conv_layers.append(
|
54 |
self.norm_layers.append(LayerNorm(hidden_channels))
|
55 |
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
56 |
self.proj.weight.data.zero_()
|
@@ -66,47 +70,6 @@ class ConvReluNorm(nn.Module):
|
|
66 |
return x * x_mask
|
67 |
|
68 |
|
69 |
-
class DDSConv(nn.Module):
|
70 |
-
"""
|
71 |
-
Dialted and Depth-Separable Convolution
|
72 |
-
"""
|
73 |
-
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
|
74 |
-
super().__init__()
|
75 |
-
self.channels = channels
|
76 |
-
self.kernel_size = kernel_size
|
77 |
-
self.n_layers = n_layers
|
78 |
-
self.p_dropout = p_dropout
|
79 |
-
|
80 |
-
self.drop = nn.Dropout(p_dropout)
|
81 |
-
self.convs_sep = nn.ModuleList()
|
82 |
-
self.convs_1x1 = nn.ModuleList()
|
83 |
-
self.norms_1 = nn.ModuleList()
|
84 |
-
self.norms_2 = nn.ModuleList()
|
85 |
-
for i in range(n_layers):
|
86 |
-
dilation = kernel_size ** i
|
87 |
-
padding = (kernel_size * dilation - dilation) // 2
|
88 |
-
self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
|
89 |
-
groups=channels, dilation=dilation, padding=padding
|
90 |
-
))
|
91 |
-
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
92 |
-
self.norms_1.append(LayerNorm(channels))
|
93 |
-
self.norms_2.append(LayerNorm(channels))
|
94 |
-
|
95 |
-
def forward(self, x, x_mask, g=None):
|
96 |
-
if g is not None:
|
97 |
-
x = x + g
|
98 |
-
for i in range(self.n_layers):
|
99 |
-
y = self.convs_sep[i](x * x_mask)
|
100 |
-
y = self.norms_1[i](y)
|
101 |
-
y = F.gelu(y)
|
102 |
-
y = self.convs_1x1[i](y)
|
103 |
-
y = self.norms_2[i](y)
|
104 |
-
y = F.gelu(y)
|
105 |
-
y = self.drop(y)
|
106 |
-
x = x + y
|
107 |
-
return x * x_mask
|
108 |
-
|
109 |
-
|
110 |
class WN(torch.nn.Module):
|
111 |
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
|
112 |
super(WN, self).__init__()
|
@@ -124,14 +87,14 @@ class WN(torch.nn.Module):
|
|
124 |
|
125 |
if gin_channels != 0:
|
126 |
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
|
127 |
-
self.cond_layer =
|
128 |
|
129 |
for i in range(n_layers):
|
130 |
dilation = dilation_rate ** i
|
131 |
padding = int((kernel_size * dilation - dilation) / 2)
|
132 |
-
in_layer =
|
133 |
dilation=dilation, padding=padding)
|
134 |
-
in_layer =
|
135 |
self.in_layers.append(in_layer)
|
136 |
|
137 |
# last one is not necessary
|
@@ -141,7 +104,7 @@ class WN(torch.nn.Module):
|
|
141 |
res_skip_channels = hidden_channels
|
142 |
|
143 |
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
144 |
-
res_skip_layer =
|
145 |
self.res_skip_layers.append(res_skip_layer)
|
146 |
|
147 |
def forward(self, x, x_mask, g=None, **kwargs):
|
@@ -176,32 +139,32 @@ class WN(torch.nn.Module):
|
|
176 |
|
177 |
def remove_weight_norm(self):
|
178 |
if self.gin_channels != 0:
|
179 |
-
|
180 |
for l in self.in_layers:
|
181 |
-
|
182 |
for l in self.res_skip_layers:
|
183 |
-
|
184 |
|
185 |
|
186 |
class ResBlock1(torch.nn.Module):
|
187 |
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
188 |
super(ResBlock1, self).__init__()
|
189 |
self.convs1 = nn.ModuleList([
|
190 |
-
|
191 |
padding=get_padding(kernel_size, dilation[0]))),
|
192 |
-
|
193 |
padding=get_padding(kernel_size, dilation[1]))),
|
194 |
-
|
195 |
padding=get_padding(kernel_size, dilation[2])))
|
196 |
])
|
197 |
self.convs1.apply(init_weights)
|
198 |
|
199 |
self.convs2 = nn.ModuleList([
|
200 |
-
|
201 |
padding=get_padding(kernel_size, 1))),
|
202 |
-
|
203 |
padding=get_padding(kernel_size, 1))),
|
204 |
-
|
205 |
padding=get_padding(kernel_size, 1)))
|
206 |
])
|
207 |
self.convs2.apply(init_weights)
|
@@ -223,18 +186,18 @@ class ResBlock1(torch.nn.Module):
|
|
223 |
|
224 |
def remove_weight_norm(self):
|
225 |
for l in self.convs1:
|
226 |
-
|
227 |
for l in self.convs2:
|
228 |
-
|
229 |
|
230 |
|
231 |
class ResBlock2(torch.nn.Module):
|
232 |
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
233 |
super(ResBlock2, self).__init__()
|
234 |
self.convs = nn.ModuleList([
|
235 |
-
|
236 |
padding=get_padding(kernel_size, dilation[0]))),
|
237 |
-
|
238 |
padding=get_padding(kernel_size, dilation[1])))
|
239 |
])
|
240 |
self.convs.apply(init_weights)
|
@@ -252,7 +215,7 @@ class ResBlock2(torch.nn.Module):
|
|
252 |
|
253 |
def remove_weight_norm(self):
|
254 |
for l in self.convs:
|
255 |
-
|
256 |
|
257 |
|
258 |
class Log(nn.Module):
|
@@ -303,7 +266,9 @@ class ResidualCouplingLayer(nn.Module):
|
|
303 |
n_layers,
|
304 |
p_dropout=0,
|
305 |
gin_channels=0,
|
306 |
-
mean_only=False
|
|
|
|
|
307 |
assert channels % 2 == 0, "channels should be divisible by 2"
|
308 |
super().__init__()
|
309 |
self.channels = channels
|
@@ -315,7 +280,56 @@ class ResidualCouplingLayer(nn.Module):
|
|
315 |
self.mean_only = mean_only
|
316 |
|
317 |
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
318 |
-
self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
320 |
self.post.weight.data.zero_()
|
321 |
self.post.bias.data.zero_()
|
|
|
|
|
|
|
|
|
|
|
1 |
import torch
|
2 |
from torch import nn
|
3 |
from torch.nn import functional as F
|
4 |
|
5 |
+
import modules.attentions as attentions
|
|
|
|
|
6 |
import modules.commons as commons
|
7 |
+
from modules.commons import get_padding, init_weights
|
8 |
+
from modules.DSConv import (
|
9 |
+
Depthwise_Separable_Conv1D,
|
10 |
+
remove_weight_norm_modules,
|
11 |
+
weight_norm_modules,
|
12 |
+
)
|
13 |
|
14 |
LRELU_SLOPE = 0.1
|
15 |
|
16 |
+
Conv1dModel = nn.Conv1d
|
17 |
+
|
18 |
+
def set_Conv1dModel(use_depthwise_conv):
|
19 |
+
global Conv1dModel
|
20 |
+
Conv1dModel = Depthwise_Separable_Conv1D if use_depthwise_conv else nn.Conv1d
|
21 |
+
|
22 |
|
23 |
class LayerNorm(nn.Module):
|
24 |
def __init__(self, channels, eps=1e-5):
|
|
|
48 |
|
49 |
self.conv_layers = nn.ModuleList()
|
50 |
self.norm_layers = nn.ModuleList()
|
51 |
+
self.conv_layers.append(Conv1dModel(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
52 |
self.norm_layers.append(LayerNorm(hidden_channels))
|
53 |
self.relu_drop = nn.Sequential(
|
54 |
nn.ReLU(),
|
55 |
nn.Dropout(p_dropout))
|
56 |
for _ in range(n_layers-1):
|
57 |
+
self.conv_layers.append(Conv1dModel(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
58 |
self.norm_layers.append(LayerNorm(hidden_channels))
|
59 |
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
60 |
self.proj.weight.data.zero_()
|
|
|
70 |
return x * x_mask
|
71 |
|
72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
class WN(torch.nn.Module):
|
74 |
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
|
75 |
super(WN, self).__init__()
|
|
|
87 |
|
88 |
if gin_channels != 0:
|
89 |
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
|
90 |
+
self.cond_layer = weight_norm_modules(cond_layer, name='weight')
|
91 |
|
92 |
for i in range(n_layers):
|
93 |
dilation = dilation_rate ** i
|
94 |
padding = int((kernel_size * dilation - dilation) / 2)
|
95 |
+
in_layer = Conv1dModel(hidden_channels, 2*hidden_channels, kernel_size,
|
96 |
dilation=dilation, padding=padding)
|
97 |
+
in_layer = weight_norm_modules(in_layer, name='weight')
|
98 |
self.in_layers.append(in_layer)
|
99 |
|
100 |
# last one is not necessary
|
|
|
104 |
res_skip_channels = hidden_channels
|
105 |
|
106 |
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
107 |
+
res_skip_layer = weight_norm_modules(res_skip_layer, name='weight')
|
108 |
self.res_skip_layers.append(res_skip_layer)
|
109 |
|
110 |
def forward(self, x, x_mask, g=None, **kwargs):
|
|
|
139 |
|
140 |
def remove_weight_norm(self):
|
141 |
if self.gin_channels != 0:
|
142 |
+
remove_weight_norm_modules(self.cond_layer)
|
143 |
for l in self.in_layers:
|
144 |
+
remove_weight_norm_modules(l)
|
145 |
for l in self.res_skip_layers:
|
146 |
+
remove_weight_norm_modules(l)
|
147 |
|
148 |
|
149 |
class ResBlock1(torch.nn.Module):
|
150 |
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
151 |
super(ResBlock1, self).__init__()
|
152 |
self.convs1 = nn.ModuleList([
|
153 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=dilation[0],
|
154 |
padding=get_padding(kernel_size, dilation[0]))),
|
155 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=dilation[1],
|
156 |
padding=get_padding(kernel_size, dilation[1]))),
|
157 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=dilation[2],
|
158 |
padding=get_padding(kernel_size, dilation[2])))
|
159 |
])
|
160 |
self.convs1.apply(init_weights)
|
161 |
|
162 |
self.convs2 = nn.ModuleList([
|
163 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=1,
|
164 |
padding=get_padding(kernel_size, 1))),
|
165 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=1,
|
166 |
padding=get_padding(kernel_size, 1))),
|
167 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=1,
|
168 |
padding=get_padding(kernel_size, 1)))
|
169 |
])
|
170 |
self.convs2.apply(init_weights)
|
|
|
186 |
|
187 |
def remove_weight_norm(self):
|
188 |
for l in self.convs1:
|
189 |
+
remove_weight_norm_modules(l)
|
190 |
for l in self.convs2:
|
191 |
+
remove_weight_norm_modules(l)
|
192 |
|
193 |
|
194 |
class ResBlock2(torch.nn.Module):
|
195 |
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
196 |
super(ResBlock2, self).__init__()
|
197 |
self.convs = nn.ModuleList([
|
198 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=dilation[0],
|
199 |
padding=get_padding(kernel_size, dilation[0]))),
|
200 |
+
weight_norm_modules(Conv1dModel(channels, channels, kernel_size, 1, dilation=dilation[1],
|
201 |
padding=get_padding(kernel_size, dilation[1])))
|
202 |
])
|
203 |
self.convs.apply(init_weights)
|
|
|
215 |
|
216 |
def remove_weight_norm(self):
|
217 |
for l in self.convs:
|
218 |
+
remove_weight_norm_modules(l)
|
219 |
|
220 |
|
221 |
class Log(nn.Module):
|
|
|
266 |
n_layers,
|
267 |
p_dropout=0,
|
268 |
gin_channels=0,
|
269 |
+
mean_only=False,
|
270 |
+
wn_sharing_parameter=None
|
271 |
+
):
|
272 |
assert channels % 2 == 0, "channels should be divisible by 2"
|
273 |
super().__init__()
|
274 |
self.channels = channels
|
|
|
280 |
self.mean_only = mean_only
|
281 |
|
282 |
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
283 |
+
self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter
|
284 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
285 |
+
self.post.weight.data.zero_()
|
286 |
+
self.post.bias.data.zero_()
|
287 |
+
|
288 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
289 |
+
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
290 |
+
h = self.pre(x0) * x_mask
|
291 |
+
h = self.enc(h, x_mask, g=g)
|
292 |
+
stats = self.post(h) * x_mask
|
293 |
+
if not self.mean_only:
|
294 |
+
m, logs = torch.split(stats, [self.half_channels]*2, 1)
|
295 |
+
else:
|
296 |
+
m = stats
|
297 |
+
logs = torch.zeros_like(m)
|
298 |
+
|
299 |
+
if not reverse:
|
300 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
301 |
+
x = torch.cat([x0, x1], 1)
|
302 |
+
logdet = torch.sum(logs, [1,2])
|
303 |
+
return x, logdet
|
304 |
+
else:
|
305 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
306 |
+
x = torch.cat([x0, x1], 1)
|
307 |
+
return x
|
308 |
+
|
309 |
+
class TransformerCouplingLayer(nn.Module):
|
310 |
+
def __init__(self,
|
311 |
+
channels,
|
312 |
+
hidden_channels,
|
313 |
+
kernel_size,
|
314 |
+
n_layers,
|
315 |
+
n_heads,
|
316 |
+
p_dropout=0,
|
317 |
+
filter_channels=0,
|
318 |
+
mean_only=False,
|
319 |
+
wn_sharing_parameter=None,
|
320 |
+
gin_channels = 0
|
321 |
+
):
|
322 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
323 |
+
super().__init__()
|
324 |
+
self.channels = channels
|
325 |
+
self.hidden_channels = hidden_channels
|
326 |
+
self.kernel_size = kernel_size
|
327 |
+
self.n_layers = n_layers
|
328 |
+
self.half_channels = channels // 2
|
329 |
+
self.mean_only = mean_only
|
330 |
+
|
331 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
332 |
+
self.enc = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter
|
333 |
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
334 |
self.post.weight.data.zero_()
|
335 |
self.post.bias.data.zero_()
|