Spaces:
Running
Running
Upload 14 files
Browse files- .gitattributes +1 -0
- attentions.py +303 -0
- data_utils.py +392 -0
- mel_processing.py +112 -0
- melspec_gen.py +61 -0
- monotonic_align/__init__.py +19 -0
- monotonic_align/__pycache__/__init__.cpython-36.pyc +0 -0
- monotonic_align/build/temp.linux-x86_64-3.6/core.o +3 -0
- monotonic_align/core.c +0 -0
- monotonic_align/core.pyx +42 -0
- monotonic_align/monotonic_align/core.cpython-36m-x86_64-linux-gnu.so +0 -0
- monotonic_align/setup.py +9 -0
- preprocess.py +25 -0
- train.py +290 -0
- train_ms.py +294 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
monotonic_align/build/temp.linux-x86_64-3.6/core.o filter=lfs diff=lfs merge=lfs -text
|
attentions.py
ADDED
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import math
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
from torch.nn import functional as F
|
7 |
+
|
8 |
+
import commons
|
9 |
+
import modules
|
10 |
+
from modules import LayerNorm
|
11 |
+
|
12 |
+
|
13 |
+
class Encoder(nn.Module):
|
14 |
+
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
|
15 |
+
super().__init__()
|
16 |
+
self.hidden_channels = hidden_channels
|
17 |
+
self.filter_channels = filter_channels
|
18 |
+
self.n_heads = n_heads
|
19 |
+
self.n_layers = n_layers
|
20 |
+
self.kernel_size = kernel_size
|
21 |
+
self.p_dropout = p_dropout
|
22 |
+
self.window_size = window_size
|
23 |
+
|
24 |
+
self.drop = nn.Dropout(p_dropout)
|
25 |
+
self.attn_layers = nn.ModuleList()
|
26 |
+
self.norm_layers_1 = nn.ModuleList()
|
27 |
+
self.ffn_layers = nn.ModuleList()
|
28 |
+
self.norm_layers_2 = nn.ModuleList()
|
29 |
+
for i in range(self.n_layers):
|
30 |
+
self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
|
31 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
32 |
+
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
|
33 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
34 |
+
|
35 |
+
def forward(self, x, x_mask):
|
36 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
37 |
+
x = x * x_mask
|
38 |
+
for i in range(self.n_layers):
|
39 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
40 |
+
y = self.drop(y)
|
41 |
+
x = self.norm_layers_1[i](x + y)
|
42 |
+
|
43 |
+
y = self.ffn_layers[i](x, x_mask)
|
44 |
+
y = self.drop(y)
|
45 |
+
x = self.norm_layers_2[i](x + y)
|
46 |
+
x = x * x_mask
|
47 |
+
return x
|
48 |
+
|
49 |
+
|
50 |
+
class Decoder(nn.Module):
|
51 |
+
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
|
52 |
+
super().__init__()
|
53 |
+
self.hidden_channels = hidden_channels
|
54 |
+
self.filter_channels = filter_channels
|
55 |
+
self.n_heads = n_heads
|
56 |
+
self.n_layers = n_layers
|
57 |
+
self.kernel_size = kernel_size
|
58 |
+
self.p_dropout = p_dropout
|
59 |
+
self.proximal_bias = proximal_bias
|
60 |
+
self.proximal_init = proximal_init
|
61 |
+
|
62 |
+
self.drop = nn.Dropout(p_dropout)
|
63 |
+
self.self_attn_layers = nn.ModuleList()
|
64 |
+
self.norm_layers_0 = nn.ModuleList()
|
65 |
+
self.encdec_attn_layers = nn.ModuleList()
|
66 |
+
self.norm_layers_1 = nn.ModuleList()
|
67 |
+
self.ffn_layers = nn.ModuleList()
|
68 |
+
self.norm_layers_2 = nn.ModuleList()
|
69 |
+
for i in range(self.n_layers):
|
70 |
+
self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
|
71 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
72 |
+
self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
|
73 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
74 |
+
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
|
75 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
76 |
+
|
77 |
+
def forward(self, x, x_mask, h, h_mask):
|
78 |
+
"""
|
79 |
+
x: decoder input
|
80 |
+
h: encoder output
|
81 |
+
"""
|
82 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
83 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
84 |
+
x = x * x_mask
|
85 |
+
for i in range(self.n_layers):
|
86 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
87 |
+
y = self.drop(y)
|
88 |
+
x = self.norm_layers_0[i](x + y)
|
89 |
+
|
90 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
91 |
+
y = self.drop(y)
|
92 |
+
x = self.norm_layers_1[i](x + y)
|
93 |
+
|
94 |
+
y = self.ffn_layers[i](x, x_mask)
|
95 |
+
y = self.drop(y)
|
96 |
+
x = self.norm_layers_2[i](x + y)
|
97 |
+
x = x * x_mask
|
98 |
+
return x
|
99 |
+
|
100 |
+
|
101 |
+
class MultiHeadAttention(nn.Module):
|
102 |
+
def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
|
103 |
+
super().__init__()
|
104 |
+
assert channels % n_heads == 0
|
105 |
+
|
106 |
+
self.channels = channels
|
107 |
+
self.out_channels = out_channels
|
108 |
+
self.n_heads = n_heads
|
109 |
+
self.p_dropout = p_dropout
|
110 |
+
self.window_size = window_size
|
111 |
+
self.heads_share = heads_share
|
112 |
+
self.block_length = block_length
|
113 |
+
self.proximal_bias = proximal_bias
|
114 |
+
self.proximal_init = proximal_init
|
115 |
+
self.attn = None
|
116 |
+
|
117 |
+
self.k_channels = channels // n_heads
|
118 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
119 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
120 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
121 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
122 |
+
self.drop = nn.Dropout(p_dropout)
|
123 |
+
|
124 |
+
if window_size is not None:
|
125 |
+
n_heads_rel = 1 if heads_share else n_heads
|
126 |
+
rel_stddev = self.k_channels**-0.5
|
127 |
+
self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
128 |
+
self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
129 |
+
|
130 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
131 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
132 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
133 |
+
if proximal_init:
|
134 |
+
with torch.no_grad():
|
135 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
136 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
137 |
+
|
138 |
+
def forward(self, x, c, attn_mask=None):
|
139 |
+
q = self.conv_q(x)
|
140 |
+
k = self.conv_k(c)
|
141 |
+
v = self.conv_v(c)
|
142 |
+
|
143 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
144 |
+
|
145 |
+
x = self.conv_o(x)
|
146 |
+
return x
|
147 |
+
|
148 |
+
def attention(self, query, key, value, mask=None):
|
149 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
150 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
151 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
152 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
153 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
154 |
+
|
155 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
156 |
+
if self.window_size is not None:
|
157 |
+
assert t_s == t_t, "Relative attention is only available for self-attention."
|
158 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
159 |
+
rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
|
160 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
161 |
+
scores = scores + scores_local
|
162 |
+
if self.proximal_bias:
|
163 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
164 |
+
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
165 |
+
if mask is not None:
|
166 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
167 |
+
if self.block_length is not None:
|
168 |
+
assert t_s == t_t, "Local attention is only available for self-attention."
|
169 |
+
block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
170 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
171 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
172 |
+
p_attn = self.drop(p_attn)
|
173 |
+
output = torch.matmul(p_attn, value)
|
174 |
+
if self.window_size is not None:
|
175 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
176 |
+
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
|
177 |
+
output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
|
178 |
+
output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
179 |
+
return output, p_attn
|
180 |
+
|
181 |
+
def _matmul_with_relative_values(self, x, y):
|
182 |
+
"""
|
183 |
+
x: [b, h, l, m]
|
184 |
+
y: [h or 1, m, d]
|
185 |
+
ret: [b, h, l, d]
|
186 |
+
"""
|
187 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
188 |
+
return ret
|
189 |
+
|
190 |
+
def _matmul_with_relative_keys(self, x, y):
|
191 |
+
"""
|
192 |
+
x: [b, h, l, d]
|
193 |
+
y: [h or 1, m, d]
|
194 |
+
ret: [b, h, l, m]
|
195 |
+
"""
|
196 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
197 |
+
return ret
|
198 |
+
|
199 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
200 |
+
max_relative_position = 2 * self.window_size + 1
|
201 |
+
# Pad first before slice to avoid using cond ops.
|
202 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
203 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
204 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
205 |
+
if pad_length > 0:
|
206 |
+
padded_relative_embeddings = F.pad(
|
207 |
+
relative_embeddings,
|
208 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
|
209 |
+
else:
|
210 |
+
padded_relative_embeddings = relative_embeddings
|
211 |
+
used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
|
212 |
+
return used_relative_embeddings
|
213 |
+
|
214 |
+
def _relative_position_to_absolute_position(self, x):
|
215 |
+
"""
|
216 |
+
x: [b, h, l, 2*l-1]
|
217 |
+
ret: [b, h, l, l]
|
218 |
+
"""
|
219 |
+
batch, heads, length, _ = x.size()
|
220 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
221 |
+
x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
|
222 |
+
|
223 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
224 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
225 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
|
226 |
+
|
227 |
+
# Reshape and slice out the padded elements.
|
228 |
+
x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
|
229 |
+
return x_final
|
230 |
+
|
231 |
+
def _absolute_position_to_relative_position(self, x):
|
232 |
+
"""
|
233 |
+
x: [b, h, l, l]
|
234 |
+
ret: [b, h, l, 2*l-1]
|
235 |
+
"""
|
236 |
+
batch, heads, length, _ = x.size()
|
237 |
+
# padd along column
|
238 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
|
239 |
+
x_flat = x.view([batch, heads, length**2 + length*(length -1)])
|
240 |
+
# add 0's in the beginning that will skew the elements after reshape
|
241 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
242 |
+
x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
|
243 |
+
return x_final
|
244 |
+
|
245 |
+
def _attention_bias_proximal(self, length):
|
246 |
+
"""Bias for self-attention to encourage attention to close positions.
|
247 |
+
Args:
|
248 |
+
length: an integer scalar.
|
249 |
+
Returns:
|
250 |
+
a Tensor with shape [1, 1, length, length]
|
251 |
+
"""
|
252 |
+
r = torch.arange(length, dtype=torch.float32)
|
253 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
254 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
255 |
+
|
256 |
+
|
257 |
+
class FFN(nn.Module):
|
258 |
+
def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
|
259 |
+
super().__init__()
|
260 |
+
self.in_channels = in_channels
|
261 |
+
self.out_channels = out_channels
|
262 |
+
self.filter_channels = filter_channels
|
263 |
+
self.kernel_size = kernel_size
|
264 |
+
self.p_dropout = p_dropout
|
265 |
+
self.activation = activation
|
266 |
+
self.causal = causal
|
267 |
+
|
268 |
+
if causal:
|
269 |
+
self.padding = self._causal_padding
|
270 |
+
else:
|
271 |
+
self.padding = self._same_padding
|
272 |
+
|
273 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
274 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
275 |
+
self.drop = nn.Dropout(p_dropout)
|
276 |
+
|
277 |
+
def forward(self, x, x_mask):
|
278 |
+
x = self.conv_1(self.padding(x * x_mask))
|
279 |
+
if self.activation == "gelu":
|
280 |
+
x = x * torch.sigmoid(1.702 * x)
|
281 |
+
else:
|
282 |
+
x = torch.relu(x)
|
283 |
+
x = self.drop(x)
|
284 |
+
x = self.conv_2(self.padding(x * x_mask))
|
285 |
+
return x * x_mask
|
286 |
+
|
287 |
+
def _causal_padding(self, x):
|
288 |
+
if self.kernel_size == 1:
|
289 |
+
return x
|
290 |
+
pad_l = self.kernel_size - 1
|
291 |
+
pad_r = 0
|
292 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
293 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
294 |
+
return x
|
295 |
+
|
296 |
+
def _same_padding(self, x):
|
297 |
+
if self.kernel_size == 1:
|
298 |
+
return x
|
299 |
+
pad_l = (self.kernel_size - 1) // 2
|
300 |
+
pad_r = self.kernel_size // 2
|
301 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
302 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
303 |
+
return x
|
data_utils.py
ADDED
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.utils.data
|
7 |
+
|
8 |
+
import commons
|
9 |
+
from mel_processing import spectrogram_torch
|
10 |
+
from utils import load_wav_to_torch, load_filepaths_and_text
|
11 |
+
from text import text_to_sequence, cleaned_text_to_sequence
|
12 |
+
|
13 |
+
|
14 |
+
class TextAudioLoader(torch.utils.data.Dataset):
|
15 |
+
"""
|
16 |
+
1) loads audio, text pairs
|
17 |
+
2) normalizes text and converts them to sequences of integers
|
18 |
+
3) computes spectrograms from audio files.
|
19 |
+
"""
|
20 |
+
def __init__(self, audiopaths_and_text, hparams):
|
21 |
+
self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
|
22 |
+
self.text_cleaners = hparams.text_cleaners
|
23 |
+
self.max_wav_value = hparams.max_wav_value
|
24 |
+
self.sampling_rate = hparams.sampling_rate
|
25 |
+
self.filter_length = hparams.filter_length
|
26 |
+
self.hop_length = hparams.hop_length
|
27 |
+
self.win_length = hparams.win_length
|
28 |
+
self.sampling_rate = hparams.sampling_rate
|
29 |
+
|
30 |
+
self.cleaned_text = getattr(hparams, "cleaned_text", False)
|
31 |
+
|
32 |
+
self.add_blank = hparams.add_blank
|
33 |
+
self.min_text_len = getattr(hparams, "min_text_len", 1)
|
34 |
+
self.max_text_len = getattr(hparams, "max_text_len", 190)
|
35 |
+
|
36 |
+
random.seed(1234)
|
37 |
+
random.shuffle(self.audiopaths_and_text)
|
38 |
+
self._filter()
|
39 |
+
|
40 |
+
|
41 |
+
def _filter(self):
|
42 |
+
"""
|
43 |
+
Filter text & store spec lengths
|
44 |
+
"""
|
45 |
+
# Store spectrogram lengths for Bucketing
|
46 |
+
# wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
|
47 |
+
# spec_length = wav_length // hop_length
|
48 |
+
|
49 |
+
audiopaths_and_text_new = []
|
50 |
+
lengths = []
|
51 |
+
for audiopath, text in self.audiopaths_and_text:
|
52 |
+
if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
|
53 |
+
audiopaths_and_text_new.append([audiopath, text])
|
54 |
+
lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
|
55 |
+
self.audiopaths_and_text = audiopaths_and_text_new
|
56 |
+
self.lengths = lengths
|
57 |
+
|
58 |
+
def get_audio_text_pair(self, audiopath_and_text):
|
59 |
+
# separate filename and text
|
60 |
+
audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
|
61 |
+
text = self.get_text(text)
|
62 |
+
spec, wav = self.get_audio(audiopath)
|
63 |
+
return (text, spec, wav)
|
64 |
+
|
65 |
+
def get_audio(self, filename):
|
66 |
+
audio, sampling_rate = load_wav_to_torch(filename)
|
67 |
+
if sampling_rate != self.sampling_rate:
|
68 |
+
raise ValueError("{} {} SR doesn't match target {} SR".format(
|
69 |
+
sampling_rate, self.sampling_rate))
|
70 |
+
audio_norm = audio / self.max_wav_value
|
71 |
+
audio_norm = audio_norm.unsqueeze(0)
|
72 |
+
spec_filename = filename.replace(".wav", ".spec.pt")
|
73 |
+
if os.path.exists(spec_filename):
|
74 |
+
spec = torch.load(spec_filename)
|
75 |
+
else:
|
76 |
+
spec = spectrogram_torch(audio_norm, self.filter_length,
|
77 |
+
self.sampling_rate, self.hop_length, self.win_length,
|
78 |
+
center=False)
|
79 |
+
spec = torch.squeeze(spec, 0)
|
80 |
+
torch.save(spec, spec_filename)
|
81 |
+
return spec, audio_norm
|
82 |
+
|
83 |
+
def get_text(self, text):
|
84 |
+
if self.cleaned_text:
|
85 |
+
text_norm = cleaned_text_to_sequence(text)
|
86 |
+
else:
|
87 |
+
text_norm = text_to_sequence(text, self.text_cleaners)
|
88 |
+
if self.add_blank:
|
89 |
+
text_norm = commons.intersperse(text_norm, 0)
|
90 |
+
text_norm = torch.LongTensor(text_norm)
|
91 |
+
return text_norm
|
92 |
+
|
93 |
+
def __getitem__(self, index):
|
94 |
+
return self.get_audio_text_pair(self.audiopaths_and_text[index])
|
95 |
+
|
96 |
+
def __len__(self):
|
97 |
+
return len(self.audiopaths_and_text)
|
98 |
+
|
99 |
+
|
100 |
+
class TextAudioCollate():
|
101 |
+
""" Zero-pads model inputs and targets
|
102 |
+
"""
|
103 |
+
def __init__(self, return_ids=False):
|
104 |
+
self.return_ids = return_ids
|
105 |
+
|
106 |
+
def __call__(self, batch):
|
107 |
+
"""Collate's training batch from normalized text and aduio
|
108 |
+
PARAMS
|
109 |
+
------
|
110 |
+
batch: [text_normalized, spec_normalized, wav_normalized]
|
111 |
+
"""
|
112 |
+
# Right zero-pad all one-hot text sequences to max input length
|
113 |
+
_, ids_sorted_decreasing = torch.sort(
|
114 |
+
torch.LongTensor([x[1].size(1) for x in batch]),
|
115 |
+
dim=0, descending=True)
|
116 |
+
|
117 |
+
max_text_len = max([len(x[0]) for x in batch])
|
118 |
+
max_spec_len = max([x[1].size(1) for x in batch])
|
119 |
+
max_wav_len = max([x[2].size(1) for x in batch])
|
120 |
+
|
121 |
+
text_lengths = torch.LongTensor(len(batch))
|
122 |
+
spec_lengths = torch.LongTensor(len(batch))
|
123 |
+
wav_lengths = torch.LongTensor(len(batch))
|
124 |
+
|
125 |
+
text_padded = torch.LongTensor(len(batch), max_text_len)
|
126 |
+
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
|
127 |
+
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
|
128 |
+
text_padded.zero_()
|
129 |
+
spec_padded.zero_()
|
130 |
+
wav_padded.zero_()
|
131 |
+
for i in range(len(ids_sorted_decreasing)):
|
132 |
+
row = batch[ids_sorted_decreasing[i]]
|
133 |
+
|
134 |
+
text = row[0]
|
135 |
+
text_padded[i, :text.size(0)] = text
|
136 |
+
text_lengths[i] = text.size(0)
|
137 |
+
|
138 |
+
spec = row[1]
|
139 |
+
spec_padded[i, :, :spec.size(1)] = spec
|
140 |
+
spec_lengths[i] = spec.size(1)
|
141 |
+
|
142 |
+
wav = row[2]
|
143 |
+
wav_padded[i, :, :wav.size(1)] = wav
|
144 |
+
wav_lengths[i] = wav.size(1)
|
145 |
+
|
146 |
+
if self.return_ids:
|
147 |
+
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
|
148 |
+
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
|
149 |
+
|
150 |
+
|
151 |
+
"""Multi speaker version"""
|
152 |
+
class TextAudioSpeakerLoader(torch.utils.data.Dataset):
|
153 |
+
"""
|
154 |
+
1) loads audio, speaker_id, text pairs
|
155 |
+
2) normalizes text and converts them to sequences of integers
|
156 |
+
3) computes spectrograms from audio files.
|
157 |
+
"""
|
158 |
+
def __init__(self, audiopaths_sid_text, hparams):
|
159 |
+
self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
|
160 |
+
self.text_cleaners = hparams.text_cleaners
|
161 |
+
self.max_wav_value = hparams.max_wav_value
|
162 |
+
self.sampling_rate = hparams.sampling_rate
|
163 |
+
self.filter_length = hparams.filter_length
|
164 |
+
self.hop_length = hparams.hop_length
|
165 |
+
self.win_length = hparams.win_length
|
166 |
+
self.sampling_rate = hparams.sampling_rate
|
167 |
+
|
168 |
+
self.cleaned_text = getattr(hparams, "cleaned_text", False)
|
169 |
+
|
170 |
+
self.add_blank = hparams.add_blank
|
171 |
+
self.min_text_len = getattr(hparams, "min_text_len", 1)
|
172 |
+
self.max_text_len = getattr(hparams, "max_text_len", 190)
|
173 |
+
|
174 |
+
random.seed(1234)
|
175 |
+
random.shuffle(self.audiopaths_sid_text)
|
176 |
+
self._filter()
|
177 |
+
|
178 |
+
def _filter(self):
|
179 |
+
"""
|
180 |
+
Filter text & store spec lengths
|
181 |
+
"""
|
182 |
+
# Store spectrogram lengths for Bucketing
|
183 |
+
# wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
|
184 |
+
# spec_length = wav_length // hop_length
|
185 |
+
|
186 |
+
audiopaths_sid_text_new = []
|
187 |
+
lengths = []
|
188 |
+
for audiopath, sid, text in self.audiopaths_sid_text:
|
189 |
+
if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
|
190 |
+
audiopaths_sid_text_new.append([audiopath, sid, text])
|
191 |
+
lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
|
192 |
+
self.audiopaths_sid_text = audiopaths_sid_text_new
|
193 |
+
self.lengths = lengths
|
194 |
+
|
195 |
+
def get_audio_text_speaker_pair(self, audiopath_sid_text):
|
196 |
+
# separate filename, speaker_id and text
|
197 |
+
audiopath, sid, text = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2]
|
198 |
+
text = self.get_text(text)
|
199 |
+
spec, wav = self.get_audio(audiopath)
|
200 |
+
sid = self.get_sid(sid)
|
201 |
+
return (text, spec, wav, sid)
|
202 |
+
|
203 |
+
def get_audio(self, filename):
|
204 |
+
audio, sampling_rate = load_wav_to_torch(filename)
|
205 |
+
if sampling_rate != self.sampling_rate:
|
206 |
+
raise ValueError("{} {} SR doesn't match target {} SR".format(
|
207 |
+
sampling_rate, self.sampling_rate))
|
208 |
+
audio_norm = audio / self.max_wav_value
|
209 |
+
audio_norm = audio_norm.unsqueeze(0)
|
210 |
+
spec_filename = filename.replace(".wav", ".spec.pt")
|
211 |
+
if os.path.exists(spec_filename):
|
212 |
+
spec = torch.load(spec_filename)
|
213 |
+
else:
|
214 |
+
spec = spectrogram_torch(audio_norm, self.filter_length,
|
215 |
+
self.sampling_rate, self.hop_length, self.win_length,
|
216 |
+
center=False)
|
217 |
+
spec = torch.squeeze(spec, 0)
|
218 |
+
torch.save(spec, spec_filename)
|
219 |
+
return spec, audio_norm
|
220 |
+
|
221 |
+
def get_text(self, text):
|
222 |
+
if self.cleaned_text:
|
223 |
+
text_norm = cleaned_text_to_sequence(text)
|
224 |
+
else:
|
225 |
+
text_norm = text_to_sequence(text, self.text_cleaners)
|
226 |
+
if self.add_blank:
|
227 |
+
text_norm = commons.intersperse(text_norm, 0)
|
228 |
+
text_norm = torch.LongTensor(text_norm)
|
229 |
+
return text_norm
|
230 |
+
|
231 |
+
def get_sid(self, sid):
|
232 |
+
sid = torch.LongTensor([int(sid)])
|
233 |
+
return sid
|
234 |
+
|
235 |
+
def __getitem__(self, index):
|
236 |
+
return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
|
237 |
+
|
238 |
+
def __len__(self):
|
239 |
+
return len(self.audiopaths_sid_text)
|
240 |
+
|
241 |
+
|
242 |
+
class TextAudioSpeakerCollate():
|
243 |
+
""" Zero-pads model inputs and targets
|
244 |
+
"""
|
245 |
+
def __init__(self, return_ids=False):
|
246 |
+
self.return_ids = return_ids
|
247 |
+
|
248 |
+
def __call__(self, batch):
|
249 |
+
"""Collate's training batch from normalized text, audio and speaker identities
|
250 |
+
PARAMS
|
251 |
+
------
|
252 |
+
batch: [text_normalized, spec_normalized, wav_normalized, sid]
|
253 |
+
"""
|
254 |
+
# Right zero-pad all one-hot text sequences to max input length
|
255 |
+
_, ids_sorted_decreasing = torch.sort(
|
256 |
+
torch.LongTensor([x[1].size(1) for x in batch]),
|
257 |
+
dim=0, descending=True)
|
258 |
+
|
259 |
+
max_text_len = max([len(x[0]) for x in batch])
|
260 |
+
max_spec_len = max([x[1].size(1) for x in batch])
|
261 |
+
max_wav_len = max([x[2].size(1) for x in batch])
|
262 |
+
|
263 |
+
text_lengths = torch.LongTensor(len(batch))
|
264 |
+
spec_lengths = torch.LongTensor(len(batch))
|
265 |
+
wav_lengths = torch.LongTensor(len(batch))
|
266 |
+
sid = torch.LongTensor(len(batch))
|
267 |
+
|
268 |
+
text_padded = torch.LongTensor(len(batch), max_text_len)
|
269 |
+
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
|
270 |
+
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
|
271 |
+
text_padded.zero_()
|
272 |
+
spec_padded.zero_()
|
273 |
+
wav_padded.zero_()
|
274 |
+
for i in range(len(ids_sorted_decreasing)):
|
275 |
+
row = batch[ids_sorted_decreasing[i]]
|
276 |
+
|
277 |
+
text = row[0]
|
278 |
+
text_padded[i, :text.size(0)] = text
|
279 |
+
text_lengths[i] = text.size(0)
|
280 |
+
|
281 |
+
spec = row[1]
|
282 |
+
spec_padded[i, :, :spec.size(1)] = spec
|
283 |
+
spec_lengths[i] = spec.size(1)
|
284 |
+
|
285 |
+
wav = row[2]
|
286 |
+
wav_padded[i, :, :wav.size(1)] = wav
|
287 |
+
wav_lengths[i] = wav.size(1)
|
288 |
+
|
289 |
+
sid[i] = row[3]
|
290 |
+
|
291 |
+
if self.return_ids:
|
292 |
+
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing
|
293 |
+
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid
|
294 |
+
|
295 |
+
|
296 |
+
class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
|
297 |
+
"""
|
298 |
+
Maintain similar input lengths in a batch.
|
299 |
+
Length groups are specified by boundaries.
|
300 |
+
Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
|
301 |
+
|
302 |
+
It removes samples which are not included in the boundaries.
|
303 |
+
Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
|
304 |
+
"""
|
305 |
+
def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
|
306 |
+
super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
|
307 |
+
self.lengths = dataset.lengths
|
308 |
+
self.batch_size = batch_size
|
309 |
+
self.boundaries = boundaries
|
310 |
+
|
311 |
+
self.buckets, self.num_samples_per_bucket = self._create_buckets()
|
312 |
+
self.total_size = sum(self.num_samples_per_bucket)
|
313 |
+
self.num_samples = self.total_size // self.num_replicas
|
314 |
+
|
315 |
+
def _create_buckets(self):
|
316 |
+
buckets = [[] for _ in range(len(self.boundaries) - 1)]
|
317 |
+
for i in range(len(self.lengths)):
|
318 |
+
length = self.lengths[i]
|
319 |
+
idx_bucket = self._bisect(length)
|
320 |
+
if idx_bucket != -1:
|
321 |
+
buckets[idx_bucket].append(i)
|
322 |
+
|
323 |
+
for i in range(len(buckets) - 1, 0, -1):
|
324 |
+
if len(buckets[i]) == 0:
|
325 |
+
buckets.pop(i)
|
326 |
+
self.boundaries.pop(i+1)
|
327 |
+
|
328 |
+
num_samples_per_bucket = []
|
329 |
+
for i in range(len(buckets)):
|
330 |
+
len_bucket = len(buckets[i])
|
331 |
+
total_batch_size = self.num_replicas * self.batch_size
|
332 |
+
rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
|
333 |
+
num_samples_per_bucket.append(len_bucket + rem)
|
334 |
+
return buckets, num_samples_per_bucket
|
335 |
+
|
336 |
+
def __iter__(self):
|
337 |
+
# deterministically shuffle based on epoch
|
338 |
+
g = torch.Generator()
|
339 |
+
g.manual_seed(self.epoch)
|
340 |
+
|
341 |
+
indices = []
|
342 |
+
if self.shuffle:
|
343 |
+
for bucket in self.buckets:
|
344 |
+
indices.append(torch.randperm(len(bucket), generator=g).tolist())
|
345 |
+
else:
|
346 |
+
for bucket in self.buckets:
|
347 |
+
indices.append(list(range(len(bucket))))
|
348 |
+
|
349 |
+
batches = []
|
350 |
+
for i in range(len(self.buckets)):
|
351 |
+
bucket = self.buckets[i]
|
352 |
+
len_bucket = len(bucket)
|
353 |
+
ids_bucket = indices[i]
|
354 |
+
num_samples_bucket = self.num_samples_per_bucket[i]
|
355 |
+
|
356 |
+
# add extra samples to make it evenly divisible
|
357 |
+
rem = num_samples_bucket - len_bucket
|
358 |
+
ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
|
359 |
+
|
360 |
+
# subsample
|
361 |
+
ids_bucket = ids_bucket[self.rank::self.num_replicas]
|
362 |
+
|
363 |
+
# batching
|
364 |
+
for j in range(len(ids_bucket) // self.batch_size):
|
365 |
+
batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]
|
366 |
+
batches.append(batch)
|
367 |
+
|
368 |
+
if self.shuffle:
|
369 |
+
batch_ids = torch.randperm(len(batches), generator=g).tolist()
|
370 |
+
batches = [batches[i] for i in batch_ids]
|
371 |
+
self.batches = batches
|
372 |
+
|
373 |
+
assert len(self.batches) * self.batch_size == self.num_samples
|
374 |
+
return iter(self.batches)
|
375 |
+
|
376 |
+
def _bisect(self, x, lo=0, hi=None):
|
377 |
+
if hi is None:
|
378 |
+
hi = len(self.boundaries) - 1
|
379 |
+
|
380 |
+
if hi > lo:
|
381 |
+
mid = (hi + lo) // 2
|
382 |
+
if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:
|
383 |
+
return mid
|
384 |
+
elif x <= self.boundaries[mid]:
|
385 |
+
return self._bisect(x, lo, mid)
|
386 |
+
else:
|
387 |
+
return self._bisect(x, mid + 1, hi)
|
388 |
+
else:
|
389 |
+
return -1
|
390 |
+
|
391 |
+
def __len__(self):
|
392 |
+
return self.num_samples // self.batch_size
|
mel_processing.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
17 |
+
|
18 |
+
|
19 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
20 |
+
"""
|
21 |
+
PARAMS
|
22 |
+
------
|
23 |
+
C: compression factor
|
24 |
+
"""
|
25 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
26 |
+
|
27 |
+
|
28 |
+
def dynamic_range_decompression_torch(x, C=1):
|
29 |
+
"""
|
30 |
+
PARAMS
|
31 |
+
------
|
32 |
+
C: compression factor used to compress
|
33 |
+
"""
|
34 |
+
return torch.exp(x) / C
|
35 |
+
|
36 |
+
|
37 |
+
def spectral_normalize_torch(magnitudes):
|
38 |
+
output = dynamic_range_compression_torch(magnitudes)
|
39 |
+
return output
|
40 |
+
|
41 |
+
|
42 |
+
def spectral_de_normalize_torch(magnitudes):
|
43 |
+
output = dynamic_range_decompression_torch(magnitudes)
|
44 |
+
return output
|
45 |
+
|
46 |
+
|
47 |
+
mel_basis = {}
|
48 |
+
hann_window = {}
|
49 |
+
|
50 |
+
|
51 |
+
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
|
52 |
+
if torch.min(y) < -1.:
|
53 |
+
print('min value is ', torch.min(y))
|
54 |
+
if torch.max(y) > 1.:
|
55 |
+
print('max value is ', torch.max(y))
|
56 |
+
|
57 |
+
global hann_window
|
58 |
+
dtype_device = str(y.dtype) + '_' + str(y.device)
|
59 |
+
wnsize_dtype_device = str(win_size) + '_' + dtype_device
|
60 |
+
if wnsize_dtype_device not in hann_window:
|
61 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
|
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)
|
68 |
+
|
69 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
70 |
+
return spec
|
71 |
+
|
72 |
+
|
73 |
+
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
|
74 |
+
global mel_basis
|
75 |
+
dtype_device = str(spec.dtype) + '_' + str(spec.device)
|
76 |
+
fmax_dtype_device = str(fmax) + '_' + dtype_device
|
77 |
+
if fmax_dtype_device not in mel_basis:
|
78 |
+
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
|
79 |
+
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
|
80 |
+
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
81 |
+
spec = spectral_normalize_torch(spec)
|
82 |
+
return spec
|
83 |
+
|
84 |
+
|
85 |
+
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
|
86 |
+
if torch.min(y) < -1.:
|
87 |
+
print('min value is ', torch.min(y))
|
88 |
+
if torch.max(y) > 1.:
|
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(sampling_rate, n_fft, num_mels, fmin, 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)
|
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
|
melspec_gen.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy.io.wavfile import read
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import os
|
5 |
+
from multiprocessing import Pool
|
6 |
+
#from tqdm import tqdm
|
7 |
+
|
8 |
+
# Change here
|
9 |
+
base="/mnt/beegfs/home/espinosa/wallon/wallon_ms_02/p02/"
|
10 |
+
|
11 |
+
hann_window = {}
|
12 |
+
def load_wav_to_torch(full_path):
|
13 |
+
sampling_rate, data = read(full_path)
|
14 |
+
# data, sampling_rate = librosa.load(full_path)
|
15 |
+
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
|
16 |
+
|
17 |
+
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
|
18 |
+
if torch.min(y) < -1.:
|
19 |
+
print('min value is ', torch.min(y))
|
20 |
+
if torch.max(y) > 1.:
|
21 |
+
print('max value is ', torch.max(y))
|
22 |
+
|
23 |
+
global hann_window
|
24 |
+
dtype_device = str(y.dtype) + '_' + str(y.device)
|
25 |
+
wnsize_dtype_device = str(win_size) + '_' + dtype_device
|
26 |
+
if wnsize_dtype_device not in hann_window:
|
27 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
|
28 |
+
|
29 |
+
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
30 |
+
y = y.squeeze(1)
|
31 |
+
|
32 |
+
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
33 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True)
|
34 |
+
|
35 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
36 |
+
return spec
|
37 |
+
|
38 |
+
def get_audio(filename):
|
39 |
+
max_wave_length = 32768.0
|
40 |
+
filter_length = 1024
|
41 |
+
hop_length = 256
|
42 |
+
win_length = 1024
|
43 |
+
audio, sampling_rate = load_wav_to_torch(filename)
|
44 |
+
audio_norm = audio / max_wave_length
|
45 |
+
audio_norm = audio_norm.unsqueeze(0)
|
46 |
+
spec_filename = filename.replace(".wav", ".spec.pt")
|
47 |
+
spec = spectrogram_torch(audio_norm, filter_length,
|
48 |
+
sampling_rate, hop_length, win_length,
|
49 |
+
center=False)
|
50 |
+
spec = torch.squeeze(spec, 0)
|
51 |
+
torch.save(spec, spec_filename)
|
52 |
+
|
53 |
+
if __name__=="__main__":
|
54 |
+
waves = []
|
55 |
+
for wav_name in os.listdir(base):
|
56 |
+
wav_path = os.path.join(base, wav_name)
|
57 |
+
if wav_path.endswith(".wav"):
|
58 |
+
waves.append(wav_path)
|
59 |
+
|
60 |
+
for wav_path in waves:
|
61 |
+
get_audio(wav_path)
|
monotonic_align/__init__.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
from .monotonic_align.core import maximum_path_c
|
4 |
+
|
5 |
+
|
6 |
+
def maximum_path(neg_cent, mask):
|
7 |
+
""" Cython optimized version.
|
8 |
+
neg_cent: [b, t_t, t_s]
|
9 |
+
mask: [b, t_t, t_s]
|
10 |
+
"""
|
11 |
+
device = neg_cent.device
|
12 |
+
dtype = neg_cent.dtype
|
13 |
+
neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
|
14 |
+
path = np.zeros(neg_cent.shape, dtype=np.int32)
|
15 |
+
|
16 |
+
t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
|
17 |
+
t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
|
18 |
+
maximum_path_c(path, neg_cent, t_t_max, t_s_max)
|
19 |
+
return torch.from_numpy(path).to(device=device, dtype=dtype)
|
monotonic_align/__pycache__/__init__.cpython-36.pyc
ADDED
Binary file (786 Bytes). View file
|
|
monotonic_align/build/temp.linux-x86_64-3.6/core.o
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1cf087f75fefa878bf0c2823e9481756bf83d24988a4ba54f9e2bbb9ddfdf9f8
|
3 |
+
size 2165448
|
monotonic_align/core.c
ADDED
The diff for this file is too large to render.
See raw diff
|
|
monotonic_align/core.pyx
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cimport cython
|
2 |
+
from cython.parallel import prange
|
3 |
+
|
4 |
+
|
5 |
+
@cython.boundscheck(False)
|
6 |
+
@cython.wraparound(False)
|
7 |
+
cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil:
|
8 |
+
cdef int x
|
9 |
+
cdef int y
|
10 |
+
cdef float v_prev
|
11 |
+
cdef float v_cur
|
12 |
+
cdef float tmp
|
13 |
+
cdef int index = t_x - 1
|
14 |
+
|
15 |
+
for y in range(t_y):
|
16 |
+
for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
|
17 |
+
if x == y:
|
18 |
+
v_cur = max_neg_val
|
19 |
+
else:
|
20 |
+
v_cur = value[y-1, x]
|
21 |
+
if x == 0:
|
22 |
+
if y == 0:
|
23 |
+
v_prev = 0.
|
24 |
+
else:
|
25 |
+
v_prev = max_neg_val
|
26 |
+
else:
|
27 |
+
v_prev = value[y-1, x-1]
|
28 |
+
value[y, x] += max(v_prev, v_cur)
|
29 |
+
|
30 |
+
for y in range(t_y - 1, -1, -1):
|
31 |
+
path[y, index] = 1
|
32 |
+
if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]):
|
33 |
+
index = index - 1
|
34 |
+
|
35 |
+
|
36 |
+
@cython.boundscheck(False)
|
37 |
+
@cython.wraparound(False)
|
38 |
+
cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil:
|
39 |
+
cdef int b = paths.shape[0]
|
40 |
+
cdef int i
|
41 |
+
for i in prange(b, nogil=True):
|
42 |
+
maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i])
|
monotonic_align/monotonic_align/core.cpython-36m-x86_64-linux-gnu.so
ADDED
Binary file (868 kB). View file
|
|
monotonic_align/setup.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from distutils.core import setup
|
2 |
+
from Cython.Build import cythonize
|
3 |
+
import numpy
|
4 |
+
|
5 |
+
setup(
|
6 |
+
name = 'monotonic_align',
|
7 |
+
ext_modules = cythonize("core.pyx"),
|
8 |
+
include_dirs=[numpy.get_include()]
|
9 |
+
)
|
preprocess.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import text
|
3 |
+
from utils import load_filepaths_and_text
|
4 |
+
|
5 |
+
if __name__ == '__main__':
|
6 |
+
parser = argparse.ArgumentParser()
|
7 |
+
parser.add_argument("--out_extension", default="cleaned")
|
8 |
+
parser.add_argument("--text_index", default=1, type=int)
|
9 |
+
parser.add_argument("--filelists", nargs="+", default=["filelists/ljs_audio_text_val_filelist.txt", "filelists/ljs_audio_text_test_filelist.txt"])
|
10 |
+
parser.add_argument("--text_cleaners", nargs="+", default=["basic_cleaners"])
|
11 |
+
|
12 |
+
args = parser.parse_args()
|
13 |
+
|
14 |
+
|
15 |
+
for filelist in args.filelists:
|
16 |
+
print("START:", filelist)
|
17 |
+
filepaths_and_text = load_filepaths_and_text(filelist)
|
18 |
+
for i in range(len(filepaths_and_text)):
|
19 |
+
original_text = filepaths_and_text[i][args.text_index]
|
20 |
+
cleaned_text = text._clean_text(original_text, args.text_cleaners)
|
21 |
+
filepaths_and_text[i][args.text_index] = cleaned_text
|
22 |
+
|
23 |
+
new_filelist = filelist + "." + args.out_extension
|
24 |
+
with open(new_filelist, "w", encoding="utf-8") as f:
|
25 |
+
f.writelines(["|".join(x) + "\n" for x in filepaths_and_text])
|
train.py
ADDED
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import argparse
|
4 |
+
import itertools
|
5 |
+
import math
|
6 |
+
import torch
|
7 |
+
from torch import nn, optim
|
8 |
+
from torch.nn import functional as F
|
9 |
+
from torch.utils.data import DataLoader
|
10 |
+
from torch.utils.tensorboard import SummaryWriter
|
11 |
+
import torch.multiprocessing as mp
|
12 |
+
import torch.distributed as dist
|
13 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
14 |
+
from torch.cuda.amp import autocast, GradScaler
|
15 |
+
|
16 |
+
import commons
|
17 |
+
import utils
|
18 |
+
from data_utils import (
|
19 |
+
TextAudioLoader,
|
20 |
+
TextAudioCollate,
|
21 |
+
DistributedBucketSampler
|
22 |
+
)
|
23 |
+
from models import (
|
24 |
+
SynthesizerTrn,
|
25 |
+
MultiPeriodDiscriminator,
|
26 |
+
)
|
27 |
+
from losses import (
|
28 |
+
generator_loss,
|
29 |
+
discriminator_loss,
|
30 |
+
feature_loss,
|
31 |
+
kl_loss
|
32 |
+
)
|
33 |
+
from mel_processing import mel_spectrogram_torch, spec_to_mel_torch
|
34 |
+
from text.symbols import symbols
|
35 |
+
|
36 |
+
|
37 |
+
torch.backends.cudnn.benchmark = True
|
38 |
+
global_step = 0
|
39 |
+
|
40 |
+
|
41 |
+
def main():
|
42 |
+
"""Assume Single Node Multi GPUs Training Only"""
|
43 |
+
assert torch.cuda.is_available(), "CPU training is not allowed."
|
44 |
+
|
45 |
+
n_gpus = torch.cuda.device_count()
|
46 |
+
os.environ['MASTER_ADDR'] = 'localhost'
|
47 |
+
os.environ['MASTER_PORT'] = '80000'
|
48 |
+
|
49 |
+
hps = utils.get_hparams()
|
50 |
+
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
|
51 |
+
|
52 |
+
|
53 |
+
def run(rank, n_gpus, hps):
|
54 |
+
global global_step
|
55 |
+
if rank == 0:
|
56 |
+
logger = utils.get_logger(hps.model_dir)
|
57 |
+
logger.info(hps)
|
58 |
+
utils.check_git_hash(hps.model_dir)
|
59 |
+
writer = SummaryWriter(log_dir=hps.model_dir)
|
60 |
+
writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
|
61 |
+
|
62 |
+
dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank)
|
63 |
+
torch.manual_seed(hps.train.seed)
|
64 |
+
torch.cuda.set_device(rank)
|
65 |
+
|
66 |
+
train_dataset = TextAudioLoader(hps.data.training_files, hps.data)
|
67 |
+
train_sampler = DistributedBucketSampler(
|
68 |
+
train_dataset,
|
69 |
+
hps.train.batch_size,
|
70 |
+
[32,300,400,500,600,700,800,900,1000],
|
71 |
+
num_replicas=n_gpus,
|
72 |
+
rank=rank,
|
73 |
+
shuffle=True)
|
74 |
+
collate_fn = TextAudioCollate()
|
75 |
+
train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False, pin_memory=True,
|
76 |
+
collate_fn=collate_fn, batch_sampler=train_sampler)
|
77 |
+
if rank == 0:
|
78 |
+
eval_dataset = TextAudioLoader(hps.data.validation_files, hps.data)
|
79 |
+
eval_loader = DataLoader(eval_dataset, num_workers=8, shuffle=False,
|
80 |
+
batch_size=hps.train.batch_size, pin_memory=True,
|
81 |
+
drop_last=False, collate_fn=collate_fn)
|
82 |
+
|
83 |
+
net_g = SynthesizerTrn(
|
84 |
+
len(symbols),
|
85 |
+
hps.data.filter_length // 2 + 1,
|
86 |
+
hps.train.segment_size // hps.data.hop_length,
|
87 |
+
**hps.model).cuda(rank)
|
88 |
+
net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)
|
89 |
+
optim_g = torch.optim.AdamW(
|
90 |
+
net_g.parameters(),
|
91 |
+
hps.train.learning_rate,
|
92 |
+
betas=hps.train.betas,
|
93 |
+
eps=hps.train.eps)
|
94 |
+
optim_d = torch.optim.AdamW(
|
95 |
+
net_d.parameters(),
|
96 |
+
hps.train.learning_rate,
|
97 |
+
betas=hps.train.betas,
|
98 |
+
eps=hps.train.eps)
|
99 |
+
net_g = DDP(net_g, device_ids=[rank])
|
100 |
+
net_d = DDP(net_d, device_ids=[rank])
|
101 |
+
|
102 |
+
try:
|
103 |
+
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g)
|
104 |
+
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d)
|
105 |
+
global_step = (epoch_str - 1) * len(train_loader)
|
106 |
+
except:
|
107 |
+
epoch_str = 1
|
108 |
+
global_step = 0
|
109 |
+
|
110 |
+
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)
|
111 |
+
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)
|
112 |
+
|
113 |
+
scaler = GradScaler(enabled=hps.train.fp16_run)
|
114 |
+
|
115 |
+
for epoch in range(epoch_str, hps.train.epochs + 1):
|
116 |
+
if rank==0:
|
117 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, eval_loader], logger, [writer, writer_eval])
|
118 |
+
else:
|
119 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, None], None, None)
|
120 |
+
scheduler_g.step()
|
121 |
+
scheduler_d.step()
|
122 |
+
|
123 |
+
|
124 |
+
def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
|
125 |
+
net_g, net_d = nets
|
126 |
+
optim_g, optim_d = optims
|
127 |
+
scheduler_g, scheduler_d = schedulers
|
128 |
+
train_loader, eval_loader = loaders
|
129 |
+
if writers is not None:
|
130 |
+
writer, writer_eval = writers
|
131 |
+
|
132 |
+
train_loader.batch_sampler.set_epoch(epoch)
|
133 |
+
global global_step
|
134 |
+
|
135 |
+
net_g.train()
|
136 |
+
net_d.train()
|
137 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths) in enumerate(train_loader):
|
138 |
+
x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
|
139 |
+
spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True)
|
140 |
+
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
|
141 |
+
|
142 |
+
with autocast(enabled=hps.train.fp16_run):
|
143 |
+
y_hat, l_length, attn, ids_slice, x_mask, z_mask,\
|
144 |
+
(z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths)
|
145 |
+
|
146 |
+
mel = spec_to_mel_torch(
|
147 |
+
spec,
|
148 |
+
hps.data.filter_length,
|
149 |
+
hps.data.n_mel_channels,
|
150 |
+
hps.data.sampling_rate,
|
151 |
+
hps.data.mel_fmin,
|
152 |
+
hps.data.mel_fmax)
|
153 |
+
y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
|
154 |
+
y_hat_mel = mel_spectrogram_torch(
|
155 |
+
y_hat.squeeze(1),
|
156 |
+
hps.data.filter_length,
|
157 |
+
hps.data.n_mel_channels,
|
158 |
+
hps.data.sampling_rate,
|
159 |
+
hps.data.hop_length,
|
160 |
+
hps.data.win_length,
|
161 |
+
hps.data.mel_fmin,
|
162 |
+
hps.data.mel_fmax
|
163 |
+
)
|
164 |
+
|
165 |
+
y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
|
166 |
+
|
167 |
+
# Discriminator
|
168 |
+
y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
|
169 |
+
with autocast(enabled=False):
|
170 |
+
loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
|
171 |
+
loss_disc_all = loss_disc
|
172 |
+
optim_d.zero_grad()
|
173 |
+
scaler.scale(loss_disc_all).backward()
|
174 |
+
scaler.unscale_(optim_d)
|
175 |
+
grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
|
176 |
+
scaler.step(optim_d)
|
177 |
+
|
178 |
+
with autocast(enabled=hps.train.fp16_run):
|
179 |
+
# Generator
|
180 |
+
y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
|
181 |
+
with autocast(enabled=False):
|
182 |
+
loss_dur = torch.sum(l_length.float())
|
183 |
+
loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
|
184 |
+
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
|
185 |
+
|
186 |
+
loss_fm = feature_loss(fmap_r, fmap_g)
|
187 |
+
loss_gen, losses_gen = generator_loss(y_d_hat_g)
|
188 |
+
loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl
|
189 |
+
optim_g.zero_grad()
|
190 |
+
scaler.scale(loss_gen_all).backward()
|
191 |
+
scaler.unscale_(optim_g)
|
192 |
+
grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
|
193 |
+
scaler.step(optim_g)
|
194 |
+
scaler.update()
|
195 |
+
|
196 |
+
if rank==0:
|
197 |
+
if global_step % hps.train.log_interval == 0:
|
198 |
+
lr = optim_g.param_groups[0]['lr']
|
199 |
+
losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]
|
200 |
+
logger.info('Train Epoch: {} [{:.0f}%]'.format(
|
201 |
+
epoch,
|
202 |
+
100. * batch_idx / len(train_loader)))
|
203 |
+
logger.info([x.item() for x in losses] + [global_step, lr])
|
204 |
+
|
205 |
+
scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
|
206 |
+
scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl})
|
207 |
+
|
208 |
+
scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
|
209 |
+
scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
|
210 |
+
scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
|
211 |
+
image_dict = {
|
212 |
+
"slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
|
213 |
+
"slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
|
214 |
+
"all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
|
215 |
+
"all/attn": utils.plot_alignment_to_numpy(attn[0,0].data.cpu().numpy())
|
216 |
+
}
|
217 |
+
utils.summarize(
|
218 |
+
writer=writer,
|
219 |
+
global_step=global_step,
|
220 |
+
images=image_dict,
|
221 |
+
scalars=scalar_dict)
|
222 |
+
|
223 |
+
if global_step % hps.train.eval_interval == 0:
|
224 |
+
evaluate(hps, net_g, eval_loader, writer_eval)
|
225 |
+
utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
|
226 |
+
utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
|
227 |
+
global_step += 1
|
228 |
+
|
229 |
+
if rank == 0:
|
230 |
+
logger.info('====> Epoch: {}'.format(epoch))
|
231 |
+
|
232 |
+
|
233 |
+
def evaluate(hps, generator, eval_loader, writer_eval):
|
234 |
+
generator.eval()
|
235 |
+
with torch.no_grad():
|
236 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths) in enumerate(eval_loader):
|
237 |
+
x, x_lengths = x.cuda(0), x_lengths.cuda(0)
|
238 |
+
spec, spec_lengths = spec.cuda(0), spec_lengths.cuda(0)
|
239 |
+
y, y_lengths = y.cuda(0), y_lengths.cuda(0)
|
240 |
+
|
241 |
+
# remove else
|
242 |
+
x = x[:1]
|
243 |
+
x_lengths = x_lengths[:1]
|
244 |
+
spec = spec[:1]
|
245 |
+
spec_lengths = spec_lengths[:1]
|
246 |
+
y = y[:1]
|
247 |
+
y_lengths = y_lengths[:1]
|
248 |
+
break
|
249 |
+
y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, max_len=1000)
|
250 |
+
y_hat_lengths = mask.sum([1,2]).long() * hps.data.hop_length
|
251 |
+
|
252 |
+
mel = spec_to_mel_torch(
|
253 |
+
spec,
|
254 |
+
hps.data.filter_length,
|
255 |
+
hps.data.n_mel_channels,
|
256 |
+
hps.data.sampling_rate,
|
257 |
+
hps.data.mel_fmin,
|
258 |
+
hps.data.mel_fmax)
|
259 |
+
y_hat_mel = mel_spectrogram_torch(
|
260 |
+
y_hat.squeeze(1).float(),
|
261 |
+
hps.data.filter_length,
|
262 |
+
hps.data.n_mel_channels,
|
263 |
+
hps.data.sampling_rate,
|
264 |
+
hps.data.hop_length,
|
265 |
+
hps.data.win_length,
|
266 |
+
hps.data.mel_fmin,
|
267 |
+
hps.data.mel_fmax
|
268 |
+
)
|
269 |
+
image_dict = {
|
270 |
+
"gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy())
|
271 |
+
}
|
272 |
+
audio_dict = {
|
273 |
+
"gen/audio": y_hat[0,:,:y_hat_lengths[0]]
|
274 |
+
}
|
275 |
+
if global_step == 0:
|
276 |
+
image_dict.update({"gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())})
|
277 |
+
audio_dict.update({"gt/audio": y[0,:,:y_lengths[0]]})
|
278 |
+
|
279 |
+
utils.summarize(
|
280 |
+
writer=writer_eval,
|
281 |
+
global_step=global_step,
|
282 |
+
images=image_dict,
|
283 |
+
audios=audio_dict,
|
284 |
+
audio_sampling_rate=hps.data.sampling_rate
|
285 |
+
)
|
286 |
+
generator.train()
|
287 |
+
|
288 |
+
|
289 |
+
if __name__ == "__main__":
|
290 |
+
main()
|
train_ms.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import argparse
|
4 |
+
import itertools
|
5 |
+
import math
|
6 |
+
import torch
|
7 |
+
from torch import nn, optim
|
8 |
+
from torch.nn import functional as F
|
9 |
+
from torch.utils.data import DataLoader
|
10 |
+
from torch.utils.tensorboard import SummaryWriter
|
11 |
+
import torch.multiprocessing as mp
|
12 |
+
import torch.distributed as dist
|
13 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
14 |
+
from torch.cuda.amp import autocast, GradScaler
|
15 |
+
|
16 |
+
import commons
|
17 |
+
import utils
|
18 |
+
from data_utils import (
|
19 |
+
TextAudioSpeakerLoader,
|
20 |
+
TextAudioSpeakerCollate,
|
21 |
+
DistributedBucketSampler
|
22 |
+
)
|
23 |
+
from models import (
|
24 |
+
SynthesizerTrn,
|
25 |
+
MultiPeriodDiscriminator,
|
26 |
+
)
|
27 |
+
from losses import (
|
28 |
+
generator_loss,
|
29 |
+
discriminator_loss,
|
30 |
+
feature_loss,
|
31 |
+
kl_loss
|
32 |
+
)
|
33 |
+
from mel_processing import mel_spectrogram_torch, spec_to_mel_torch
|
34 |
+
from text.symbols import symbols
|
35 |
+
|
36 |
+
|
37 |
+
torch.backends.cudnn.benchmark = True
|
38 |
+
global_step = 0
|
39 |
+
|
40 |
+
|
41 |
+
def main():
|
42 |
+
"""Assume Single Node Multi GPUs Training Only"""
|
43 |
+
assert torch.cuda.is_available(), "CPU training is not allowed."
|
44 |
+
|
45 |
+
n_gpus = torch.cuda.device_count()
|
46 |
+
os.environ['MASTER_ADDR'] = 'localhost'
|
47 |
+
os.environ['MASTER_PORT'] = '80000'
|
48 |
+
|
49 |
+
hps = utils.get_hparams()
|
50 |
+
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
|
51 |
+
|
52 |
+
|
53 |
+
def run(rank, n_gpus, hps):
|
54 |
+
global global_step
|
55 |
+
if rank == 0:
|
56 |
+
logger = utils.get_logger(hps.model_dir)
|
57 |
+
logger.info(hps)
|
58 |
+
utils.check_git_hash(hps.model_dir)
|
59 |
+
writer = SummaryWriter(log_dir=hps.model_dir)
|
60 |
+
writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
|
61 |
+
|
62 |
+
dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank)
|
63 |
+
torch.manual_seed(hps.train.seed)
|
64 |
+
torch.cuda.set_device(rank)
|
65 |
+
|
66 |
+
train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data)
|
67 |
+
train_sampler = DistributedBucketSampler(
|
68 |
+
train_dataset,
|
69 |
+
hps.train.batch_size,
|
70 |
+
[32,300,400,500,600,700,800,900,1000],
|
71 |
+
num_replicas=n_gpus,
|
72 |
+
rank=rank,
|
73 |
+
shuffle=True)
|
74 |
+
collate_fn = TextAudioSpeakerCollate()
|
75 |
+
train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False, pin_memory=True,
|
76 |
+
collate_fn=collate_fn, batch_sampler=train_sampler)
|
77 |
+
if rank == 0:
|
78 |
+
eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data)
|
79 |
+
eval_loader = DataLoader(eval_dataset, num_workers=8, shuffle=False,
|
80 |
+
batch_size=hps.train.batch_size, pin_memory=True,
|
81 |
+
drop_last=False, collate_fn=collate_fn)
|
82 |
+
|
83 |
+
net_g = SynthesizerTrn(
|
84 |
+
len(symbols),
|
85 |
+
hps.data.filter_length // 2 + 1,
|
86 |
+
hps.train.segment_size // hps.data.hop_length,
|
87 |
+
n_speakers=hps.data.n_speakers,
|
88 |
+
**hps.model).cuda(rank)
|
89 |
+
net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)
|
90 |
+
optim_g = torch.optim.AdamW(
|
91 |
+
net_g.parameters(),
|
92 |
+
hps.train.learning_rate,
|
93 |
+
betas=hps.train.betas,
|
94 |
+
eps=hps.train.eps)
|
95 |
+
optim_d = torch.optim.AdamW(
|
96 |
+
net_d.parameters(),
|
97 |
+
hps.train.learning_rate,
|
98 |
+
betas=hps.train.betas,
|
99 |
+
eps=hps.train.eps)
|
100 |
+
net_g = DDP(net_g, device_ids=[rank])
|
101 |
+
net_d = DDP(net_d, device_ids=[rank])
|
102 |
+
|
103 |
+
try:
|
104 |
+
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g)
|
105 |
+
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d)
|
106 |
+
global_step = (epoch_str - 1) * len(train_loader)
|
107 |
+
except:
|
108 |
+
epoch_str = 1
|
109 |
+
global_step = 0
|
110 |
+
|
111 |
+
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)
|
112 |
+
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)
|
113 |
+
|
114 |
+
scaler = GradScaler(enabled=hps.train.fp16_run)
|
115 |
+
|
116 |
+
for epoch in range(epoch_str, hps.train.epochs + 1):
|
117 |
+
if rank==0:
|
118 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, eval_loader], logger, [writer, writer_eval])
|
119 |
+
else:
|
120 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, None], None, None)
|
121 |
+
scheduler_g.step()
|
122 |
+
scheduler_d.step()
|
123 |
+
|
124 |
+
|
125 |
+
def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
|
126 |
+
net_g, net_d = nets
|
127 |
+
optim_g, optim_d = optims
|
128 |
+
scheduler_g, scheduler_d = schedulers
|
129 |
+
train_loader, eval_loader = loaders
|
130 |
+
if writers is not None:
|
131 |
+
writer, writer_eval = writers
|
132 |
+
|
133 |
+
train_loader.batch_sampler.set_epoch(epoch)
|
134 |
+
global global_step
|
135 |
+
|
136 |
+
net_g.train()
|
137 |
+
net_d.train()
|
138 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(train_loader):
|
139 |
+
x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
|
140 |
+
spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True)
|
141 |
+
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
|
142 |
+
speakers = speakers.cuda(rank, non_blocking=True)
|
143 |
+
|
144 |
+
with autocast(enabled=hps.train.fp16_run):
|
145 |
+
y_hat, l_length, attn, ids_slice, x_mask, z_mask,\
|
146 |
+
(z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths, speakers)
|
147 |
+
|
148 |
+
mel = spec_to_mel_torch(
|
149 |
+
spec,
|
150 |
+
hps.data.filter_length,
|
151 |
+
hps.data.n_mel_channels,
|
152 |
+
hps.data.sampling_rate,
|
153 |
+
hps.data.mel_fmin,
|
154 |
+
hps.data.mel_fmax)
|
155 |
+
y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
|
156 |
+
y_hat_mel = mel_spectrogram_torch(
|
157 |
+
y_hat.squeeze(1),
|
158 |
+
hps.data.filter_length,
|
159 |
+
hps.data.n_mel_channels,
|
160 |
+
hps.data.sampling_rate,
|
161 |
+
hps.data.hop_length,
|
162 |
+
hps.data.win_length,
|
163 |
+
hps.data.mel_fmin,
|
164 |
+
hps.data.mel_fmax
|
165 |
+
)
|
166 |
+
|
167 |
+
y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
|
168 |
+
|
169 |
+
# Discriminator
|
170 |
+
y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
|
171 |
+
with autocast(enabled=False):
|
172 |
+
loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
|
173 |
+
loss_disc_all = loss_disc
|
174 |
+
optim_d.zero_grad()
|
175 |
+
scaler.scale(loss_disc_all).backward()
|
176 |
+
scaler.unscale_(optim_d)
|
177 |
+
grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
|
178 |
+
scaler.step(optim_d)
|
179 |
+
|
180 |
+
with autocast(enabled=hps.train.fp16_run):
|
181 |
+
# Generator
|
182 |
+
y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
|
183 |
+
with autocast(enabled=False):
|
184 |
+
loss_dur = torch.sum(l_length.float())
|
185 |
+
loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
|
186 |
+
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
|
187 |
+
|
188 |
+
loss_fm = feature_loss(fmap_r, fmap_g)
|
189 |
+
loss_gen, losses_gen = generator_loss(y_d_hat_g)
|
190 |
+
loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl
|
191 |
+
optim_g.zero_grad()
|
192 |
+
scaler.scale(loss_gen_all).backward()
|
193 |
+
scaler.unscale_(optim_g)
|
194 |
+
grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
|
195 |
+
scaler.step(optim_g)
|
196 |
+
scaler.update()
|
197 |
+
|
198 |
+
if rank==0:
|
199 |
+
if global_step % hps.train.log_interval == 0:
|
200 |
+
lr = optim_g.param_groups[0]['lr']
|
201 |
+
losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]
|
202 |
+
logger.info('Train Epoch: {} [{:.0f}%]'.format(
|
203 |
+
epoch,
|
204 |
+
100. * batch_idx / len(train_loader)))
|
205 |
+
logger.info([x.item() for x in losses] + [global_step, lr])
|
206 |
+
|
207 |
+
scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
|
208 |
+
scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl})
|
209 |
+
|
210 |
+
scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
|
211 |
+
scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
|
212 |
+
scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
|
213 |
+
image_dict = {
|
214 |
+
"slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
|
215 |
+
"slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
|
216 |
+
"all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
|
217 |
+
"all/attn": utils.plot_alignment_to_numpy(attn[0,0].data.cpu().numpy())
|
218 |
+
}
|
219 |
+
utils.summarize(
|
220 |
+
writer=writer,
|
221 |
+
global_step=global_step,
|
222 |
+
images=image_dict,
|
223 |
+
scalars=scalar_dict)
|
224 |
+
|
225 |
+
if global_step % hps.train.eval_interval == 0:
|
226 |
+
evaluate(hps, net_g, eval_loader, writer_eval)
|
227 |
+
utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
|
228 |
+
utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
|
229 |
+
global_step += 1
|
230 |
+
|
231 |
+
if rank == 0:
|
232 |
+
logger.info('====> Epoch: {}'.format(epoch))
|
233 |
+
|
234 |
+
|
235 |
+
def evaluate(hps, generator, eval_loader, writer_eval):
|
236 |
+
generator.eval()
|
237 |
+
with torch.no_grad():
|
238 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(eval_loader):
|
239 |
+
x, x_lengths = x.cuda(0), x_lengths.cuda(0)
|
240 |
+
spec, spec_lengths = spec.cuda(0), spec_lengths.cuda(0)
|
241 |
+
y, y_lengths = y.cuda(0), y_lengths.cuda(0)
|
242 |
+
speakers = speakers.cuda(0)
|
243 |
+
|
244 |
+
# remove else
|
245 |
+
x = x[:1]
|
246 |
+
x_lengths = x_lengths[:1]
|
247 |
+
spec = spec[:1]
|
248 |
+
spec_lengths = spec_lengths[:1]
|
249 |
+
y = y[:1]
|
250 |
+
y_lengths = y_lengths[:1]
|
251 |
+
speakers = speakers[:1]
|
252 |
+
break
|
253 |
+
y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, max_len=1000)
|
254 |
+
y_hat_lengths = mask.sum([1,2]).long() * hps.data.hop_length
|
255 |
+
|
256 |
+
mel = spec_to_mel_torch(
|
257 |
+
spec,
|
258 |
+
hps.data.filter_length,
|
259 |
+
hps.data.n_mel_channels,
|
260 |
+
hps.data.sampling_rate,
|
261 |
+
hps.data.mel_fmin,
|
262 |
+
hps.data.mel_fmax)
|
263 |
+
y_hat_mel = mel_spectrogram_torch(
|
264 |
+
y_hat.squeeze(1).float(),
|
265 |
+
hps.data.filter_length,
|
266 |
+
hps.data.n_mel_channels,
|
267 |
+
hps.data.sampling_rate,
|
268 |
+
hps.data.hop_length,
|
269 |
+
hps.data.win_length,
|
270 |
+
hps.data.mel_fmin,
|
271 |
+
hps.data.mel_fmax
|
272 |
+
)
|
273 |
+
image_dict = {
|
274 |
+
"gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy())
|
275 |
+
}
|
276 |
+
audio_dict = {
|
277 |
+
"gen/audio": y_hat[0,:,:y_hat_lengths[0]]
|
278 |
+
}
|
279 |
+
if global_step == 0:
|
280 |
+
image_dict.update({"gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())})
|
281 |
+
audio_dict.update({"gt/audio": y[0,:,:y_lengths[0]]})
|
282 |
+
|
283 |
+
utils.summarize(
|
284 |
+
writer=writer_eval,
|
285 |
+
global_step=global_step,
|
286 |
+
images=image_dict,
|
287 |
+
audios=audio_dict,
|
288 |
+
audio_sampling_rate=hps.data.sampling_rate
|
289 |
+
)
|
290 |
+
generator.train()
|
291 |
+
|
292 |
+
|
293 |
+
if __name__ == "__main__":
|
294 |
+
main()
|