Spaces:
Running
on
Zero
Running
on
Zero
Delete istftnet.py
Browse files- istftnet.py +0 -523
istftnet.py
DELETED
@@ -1,523 +0,0 @@
|
|
1 |
-
# https://github.com/yl4579/StyleTTS2/blob/main/Modules/istftnet.py
|
2 |
-
from scipy.signal import get_window
|
3 |
-
from torch.nn import Conv1d, ConvTranspose1d
|
4 |
-
from torch.nn.utils import weight_norm, remove_weight_norm
|
5 |
-
import numpy as np
|
6 |
-
import torch
|
7 |
-
import torch.nn as nn
|
8 |
-
import torch.nn.functional as F
|
9 |
-
|
10 |
-
# https://github.com/yl4579/StyleTTS2/blob/main/Modules/utils.py
|
11 |
-
def init_weights(m, mean=0.0, std=0.01):
|
12 |
-
classname = m.__class__.__name__
|
13 |
-
if classname.find("Conv") != -1:
|
14 |
-
m.weight.data.normal_(mean, std)
|
15 |
-
|
16 |
-
def get_padding(kernel_size, dilation=1):
|
17 |
-
return int((kernel_size*dilation - dilation)/2)
|
18 |
-
|
19 |
-
LRELU_SLOPE = 0.1
|
20 |
-
|
21 |
-
class AdaIN1d(nn.Module):
|
22 |
-
def __init__(self, style_dim, num_features):
|
23 |
-
super().__init__()
|
24 |
-
self.norm = nn.InstanceNorm1d(num_features, affine=False)
|
25 |
-
self.fc = nn.Linear(style_dim, num_features*2)
|
26 |
-
|
27 |
-
def forward(self, x, s):
|
28 |
-
h = self.fc(s)
|
29 |
-
h = h.view(h.size(0), h.size(1), 1)
|
30 |
-
gamma, beta = torch.chunk(h, chunks=2, dim=1)
|
31 |
-
return (1 + gamma) * self.norm(x) + beta
|
32 |
-
|
33 |
-
class AdaINResBlock1(torch.nn.Module):
|
34 |
-
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), style_dim=64):
|
35 |
-
super(AdaINResBlock1, self).__init__()
|
36 |
-
self.convs1 = nn.ModuleList([
|
37 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
38 |
-
padding=get_padding(kernel_size, dilation[0]))),
|
39 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
40 |
-
padding=get_padding(kernel_size, dilation[1]))),
|
41 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
42 |
-
padding=get_padding(kernel_size, dilation[2])))
|
43 |
-
])
|
44 |
-
self.convs1.apply(init_weights)
|
45 |
-
|
46 |
-
self.convs2 = nn.ModuleList([
|
47 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
48 |
-
padding=get_padding(kernel_size, 1))),
|
49 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
50 |
-
padding=get_padding(kernel_size, 1))),
|
51 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
52 |
-
padding=get_padding(kernel_size, 1)))
|
53 |
-
])
|
54 |
-
self.convs2.apply(init_weights)
|
55 |
-
|
56 |
-
self.adain1 = nn.ModuleList([
|
57 |
-
AdaIN1d(style_dim, channels),
|
58 |
-
AdaIN1d(style_dim, channels),
|
59 |
-
AdaIN1d(style_dim, channels),
|
60 |
-
])
|
61 |
-
|
62 |
-
self.adain2 = nn.ModuleList([
|
63 |
-
AdaIN1d(style_dim, channels),
|
64 |
-
AdaIN1d(style_dim, channels),
|
65 |
-
AdaIN1d(style_dim, channels),
|
66 |
-
])
|
67 |
-
|
68 |
-
self.alpha1 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs1))])
|
69 |
-
self.alpha2 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs2))])
|
70 |
-
|
71 |
-
|
72 |
-
def forward(self, x, s):
|
73 |
-
for c1, c2, n1, n2, a1, a2 in zip(self.convs1, self.convs2, self.adain1, self.adain2, self.alpha1, self.alpha2):
|
74 |
-
xt = n1(x, s)
|
75 |
-
xt = xt + (1 / a1) * (torch.sin(a1 * xt) ** 2) # Snake1D
|
76 |
-
xt = c1(xt)
|
77 |
-
xt = n2(xt, s)
|
78 |
-
xt = xt + (1 / a2) * (torch.sin(a2 * xt) ** 2) # Snake1D
|
79 |
-
xt = c2(xt)
|
80 |
-
x = xt + x
|
81 |
-
return x
|
82 |
-
|
83 |
-
def remove_weight_norm(self):
|
84 |
-
for l in self.convs1:
|
85 |
-
remove_weight_norm(l)
|
86 |
-
for l in self.convs2:
|
87 |
-
remove_weight_norm(l)
|
88 |
-
|
89 |
-
class TorchSTFT(torch.nn.Module):
|
90 |
-
def __init__(self, filter_length=800, hop_length=200, win_length=800, window='hann'):
|
91 |
-
super().__init__()
|
92 |
-
self.filter_length = filter_length
|
93 |
-
self.hop_length = hop_length
|
94 |
-
self.win_length = win_length
|
95 |
-
self.window = torch.from_numpy(get_window(window, win_length, fftbins=True).astype(np.float32))
|
96 |
-
|
97 |
-
def transform(self, input_data):
|
98 |
-
forward_transform = torch.stft(
|
99 |
-
input_data,
|
100 |
-
self.filter_length, self.hop_length, self.win_length, window=self.window.to(input_data.device),
|
101 |
-
return_complex=True)
|
102 |
-
|
103 |
-
return torch.abs(forward_transform), torch.angle(forward_transform)
|
104 |
-
|
105 |
-
def inverse(self, magnitude, phase):
|
106 |
-
inverse_transform = torch.istft(
|
107 |
-
magnitude * torch.exp(phase * 1j),
|
108 |
-
self.filter_length, self.hop_length, self.win_length, window=self.window.to(magnitude.device))
|
109 |
-
|
110 |
-
return inverse_transform.unsqueeze(-2) # unsqueeze to stay consistent with conv_transpose1d implementation
|
111 |
-
|
112 |
-
def forward(self, input_data):
|
113 |
-
self.magnitude, self.phase = self.transform(input_data)
|
114 |
-
reconstruction = self.inverse(self.magnitude, self.phase)
|
115 |
-
return reconstruction
|
116 |
-
|
117 |
-
class SineGen(torch.nn.Module):
|
118 |
-
""" Definition of sine generator
|
119 |
-
SineGen(samp_rate, harmonic_num = 0,
|
120 |
-
sine_amp = 0.1, noise_std = 0.003,
|
121 |
-
voiced_threshold = 0,
|
122 |
-
flag_for_pulse=False)
|
123 |
-
samp_rate: sampling rate in Hz
|
124 |
-
harmonic_num: number of harmonic overtones (default 0)
|
125 |
-
sine_amp: amplitude of sine-wavefrom (default 0.1)
|
126 |
-
noise_std: std of Gaussian noise (default 0.003)
|
127 |
-
voiced_thoreshold: F0 threshold for U/V classification (default 0)
|
128 |
-
flag_for_pulse: this SinGen is used inside PulseGen (default False)
|
129 |
-
Note: when flag_for_pulse is True, the first time step of a voiced
|
130 |
-
segment is always sin(np.pi) or cos(0)
|
131 |
-
"""
|
132 |
-
|
133 |
-
def __init__(self, samp_rate, upsample_scale, harmonic_num=0,
|
134 |
-
sine_amp=0.1, noise_std=0.003,
|
135 |
-
voiced_threshold=0,
|
136 |
-
flag_for_pulse=False):
|
137 |
-
super(SineGen, self).__init__()
|
138 |
-
self.sine_amp = sine_amp
|
139 |
-
self.noise_std = noise_std
|
140 |
-
self.harmonic_num = harmonic_num
|
141 |
-
self.dim = self.harmonic_num + 1
|
142 |
-
self.sampling_rate = samp_rate
|
143 |
-
self.voiced_threshold = voiced_threshold
|
144 |
-
self.flag_for_pulse = flag_for_pulse
|
145 |
-
self.upsample_scale = upsample_scale
|
146 |
-
|
147 |
-
def _f02uv(self, f0):
|
148 |
-
# generate uv signal
|
149 |
-
uv = (f0 > self.voiced_threshold).type(torch.float32)
|
150 |
-
return uv
|
151 |
-
|
152 |
-
def _f02sine(self, f0_values):
|
153 |
-
""" f0_values: (batchsize, length, dim)
|
154 |
-
where dim indicates fundamental tone and overtones
|
155 |
-
"""
|
156 |
-
# convert to F0 in rad. The interger part n can be ignored
|
157 |
-
# because 2 * np.pi * n doesn't affect phase
|
158 |
-
rad_values = (f0_values / self.sampling_rate) % 1
|
159 |
-
|
160 |
-
# initial phase noise (no noise for fundamental component)
|
161 |
-
rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \
|
162 |
-
device=f0_values.device)
|
163 |
-
rand_ini[:, 0] = 0
|
164 |
-
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
165 |
-
|
166 |
-
# instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
|
167 |
-
if not self.flag_for_pulse:
|
168 |
-
# # for normal case
|
169 |
-
|
170 |
-
# # To prevent torch.cumsum numerical overflow,
|
171 |
-
# # it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1.
|
172 |
-
# # Buffer tmp_over_one_idx indicates the time step to add -1.
|
173 |
-
# # This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi
|
174 |
-
# tmp_over_one = torch.cumsum(rad_values, 1) % 1
|
175 |
-
# tmp_over_one_idx = (padDiff(tmp_over_one)) < 0
|
176 |
-
# cumsum_shift = torch.zeros_like(rad_values)
|
177 |
-
# cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
178 |
-
|
179 |
-
# phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
|
180 |
-
rad_values = torch.nn.functional.interpolate(rad_values.transpose(1, 2),
|
181 |
-
scale_factor=1/self.upsample_scale,
|
182 |
-
mode="linear").transpose(1, 2)
|
183 |
-
|
184 |
-
# tmp_over_one = torch.cumsum(rad_values, 1) % 1
|
185 |
-
# tmp_over_one_idx = (padDiff(tmp_over_one)) < 0
|
186 |
-
# cumsum_shift = torch.zeros_like(rad_values)
|
187 |
-
# cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
188 |
-
|
189 |
-
phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
|
190 |
-
phase = torch.nn.functional.interpolate(phase.transpose(1, 2) * self.upsample_scale,
|
191 |
-
scale_factor=self.upsample_scale, mode="linear").transpose(1, 2)
|
192 |
-
sines = torch.sin(phase)
|
193 |
-
|
194 |
-
else:
|
195 |
-
# If necessary, make sure that the first time step of every
|
196 |
-
# voiced segments is sin(pi) or cos(0)
|
197 |
-
# This is used for pulse-train generation
|
198 |
-
|
199 |
-
# identify the last time step in unvoiced segments
|
200 |
-
uv = self._f02uv(f0_values)
|
201 |
-
uv_1 = torch.roll(uv, shifts=-1, dims=1)
|
202 |
-
uv_1[:, -1, :] = 1
|
203 |
-
u_loc = (uv < 1) * (uv_1 > 0)
|
204 |
-
|
205 |
-
# get the instantanouse phase
|
206 |
-
tmp_cumsum = torch.cumsum(rad_values, dim=1)
|
207 |
-
# different batch needs to be processed differently
|
208 |
-
for idx in range(f0_values.shape[0]):
|
209 |
-
temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
|
210 |
-
temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
|
211 |
-
# stores the accumulation of i.phase within
|
212 |
-
# each voiced segments
|
213 |
-
tmp_cumsum[idx, :, :] = 0
|
214 |
-
tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
|
215 |
-
|
216 |
-
# rad_values - tmp_cumsum: remove the accumulation of i.phase
|
217 |
-
# within the previous voiced segment.
|
218 |
-
i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
|
219 |
-
|
220 |
-
# get the sines
|
221 |
-
sines = torch.cos(i_phase * 2 * np.pi)
|
222 |
-
return sines
|
223 |
-
|
224 |
-
def forward(self, f0):
|
225 |
-
""" sine_tensor, uv = forward(f0)
|
226 |
-
input F0: tensor(batchsize=1, length, dim=1)
|
227 |
-
f0 for unvoiced steps should be 0
|
228 |
-
output sine_tensor: tensor(batchsize=1, length, dim)
|
229 |
-
output uv: tensor(batchsize=1, length, 1)
|
230 |
-
"""
|
231 |
-
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim,
|
232 |
-
device=f0.device)
|
233 |
-
# fundamental component
|
234 |
-
fn = torch.multiply(f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device))
|
235 |
-
|
236 |
-
# generate sine waveforms
|
237 |
-
sine_waves = self._f02sine(fn) * self.sine_amp
|
238 |
-
|
239 |
-
# generate uv signal
|
240 |
-
# uv = torch.ones(f0.shape)
|
241 |
-
# uv = uv * (f0 > self.voiced_threshold)
|
242 |
-
uv = self._f02uv(f0)
|
243 |
-
|
244 |
-
# noise: for unvoiced should be similar to sine_amp
|
245 |
-
# std = self.sine_amp/3 -> max value ~ self.sine_amp
|
246 |
-
# . for voiced regions is self.noise_std
|
247 |
-
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
248 |
-
noise = noise_amp * torch.randn_like(sine_waves)
|
249 |
-
|
250 |
-
# first: set the unvoiced part to 0 by uv
|
251 |
-
# then: additive noise
|
252 |
-
sine_waves = sine_waves * uv + noise
|
253 |
-
return sine_waves, uv, noise
|
254 |
-
|
255 |
-
|
256 |
-
class SourceModuleHnNSF(torch.nn.Module):
|
257 |
-
""" SourceModule for hn-nsf
|
258 |
-
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
259 |
-
add_noise_std=0.003, voiced_threshod=0)
|
260 |
-
sampling_rate: sampling_rate in Hz
|
261 |
-
harmonic_num: number of harmonic above F0 (default: 0)
|
262 |
-
sine_amp: amplitude of sine source signal (default: 0.1)
|
263 |
-
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
264 |
-
note that amplitude of noise in unvoiced is decided
|
265 |
-
by sine_amp
|
266 |
-
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
267 |
-
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
268 |
-
F0_sampled (batchsize, length, 1)
|
269 |
-
Sine_source (batchsize, length, 1)
|
270 |
-
noise_source (batchsize, length 1)
|
271 |
-
uv (batchsize, length, 1)
|
272 |
-
"""
|
273 |
-
|
274 |
-
def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
|
275 |
-
add_noise_std=0.003, voiced_threshod=0):
|
276 |
-
super(SourceModuleHnNSF, self).__init__()
|
277 |
-
|
278 |
-
self.sine_amp = sine_amp
|
279 |
-
self.noise_std = add_noise_std
|
280 |
-
|
281 |
-
# to produce sine waveforms
|
282 |
-
self.l_sin_gen = SineGen(sampling_rate, upsample_scale, harmonic_num,
|
283 |
-
sine_amp, add_noise_std, voiced_threshod)
|
284 |
-
|
285 |
-
# to merge source harmonics into a single excitation
|
286 |
-
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
287 |
-
self.l_tanh = torch.nn.Tanh()
|
288 |
-
|
289 |
-
def forward(self, x):
|
290 |
-
"""
|
291 |
-
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
292 |
-
F0_sampled (batchsize, length, 1)
|
293 |
-
Sine_source (batchsize, length, 1)
|
294 |
-
noise_source (batchsize, length 1)
|
295 |
-
"""
|
296 |
-
# source for harmonic branch
|
297 |
-
with torch.no_grad():
|
298 |
-
sine_wavs, uv, _ = self.l_sin_gen(x)
|
299 |
-
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
300 |
-
|
301 |
-
# source for noise branch, in the same shape as uv
|
302 |
-
noise = torch.randn_like(uv) * self.sine_amp / 3
|
303 |
-
return sine_merge, noise, uv
|
304 |
-
def padDiff(x):
|
305 |
-
return F.pad(F.pad(x, (0,0,-1,1), 'constant', 0) - x, (0,0,0,-1), 'constant', 0)
|
306 |
-
|
307 |
-
|
308 |
-
class Generator(torch.nn.Module):
|
309 |
-
def __init__(self, style_dim, resblock_kernel_sizes, upsample_rates, upsample_initial_channel, resblock_dilation_sizes, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size):
|
310 |
-
super(Generator, self).__init__()
|
311 |
-
|
312 |
-
self.num_kernels = len(resblock_kernel_sizes)
|
313 |
-
self.num_upsamples = len(upsample_rates)
|
314 |
-
resblock = AdaINResBlock1
|
315 |
-
|
316 |
-
self.m_source = SourceModuleHnNSF(
|
317 |
-
sampling_rate=24000,
|
318 |
-
upsample_scale=np.prod(upsample_rates) * gen_istft_hop_size,
|
319 |
-
harmonic_num=8, voiced_threshod=10)
|
320 |
-
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * gen_istft_hop_size)
|
321 |
-
self.noise_convs = nn.ModuleList()
|
322 |
-
self.noise_res = nn.ModuleList()
|
323 |
-
|
324 |
-
self.ups = nn.ModuleList()
|
325 |
-
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
326 |
-
self.ups.append(weight_norm(
|
327 |
-
ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
|
328 |
-
k, u, padding=(k-u)//2)))
|
329 |
-
|
330 |
-
self.resblocks = nn.ModuleList()
|
331 |
-
for i in range(len(self.ups)):
|
332 |
-
ch = upsample_initial_channel//(2**(i+1))
|
333 |
-
for j, (k, d) in enumerate(zip(resblock_kernel_sizes,resblock_dilation_sizes)):
|
334 |
-
self.resblocks.append(resblock(ch, k, d, style_dim))
|
335 |
-
|
336 |
-
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
337 |
-
|
338 |
-
if i + 1 < len(upsample_rates): #
|
339 |
-
stride_f0 = np.prod(upsample_rates[i + 1:])
|
340 |
-
self.noise_convs.append(Conv1d(
|
341 |
-
gen_istft_n_fft + 2, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=(stride_f0+1) // 2))
|
342 |
-
self.noise_res.append(resblock(c_cur, 7, [1,3,5], style_dim))
|
343 |
-
else:
|
344 |
-
self.noise_convs.append(Conv1d(gen_istft_n_fft + 2, c_cur, kernel_size=1))
|
345 |
-
self.noise_res.append(resblock(c_cur, 11, [1,3,5], style_dim))
|
346 |
-
|
347 |
-
|
348 |
-
self.post_n_fft = gen_istft_n_fft
|
349 |
-
self.conv_post = weight_norm(Conv1d(ch, self.post_n_fft + 2, 7, 1, padding=3))
|
350 |
-
self.ups.apply(init_weights)
|
351 |
-
self.conv_post.apply(init_weights)
|
352 |
-
self.reflection_pad = torch.nn.ReflectionPad1d((1, 0))
|
353 |
-
self.stft = TorchSTFT(filter_length=gen_istft_n_fft, hop_length=gen_istft_hop_size, win_length=gen_istft_n_fft)
|
354 |
-
|
355 |
-
|
356 |
-
def forward(self, x, s, f0):
|
357 |
-
with torch.no_grad():
|
358 |
-
f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
359 |
-
|
360 |
-
har_source, noi_source, uv = self.m_source(f0)
|
361 |
-
har_source = har_source.transpose(1, 2).squeeze(1)
|
362 |
-
har_spec, har_phase = self.stft.transform(har_source)
|
363 |
-
har = torch.cat([har_spec, har_phase], dim=1)
|
364 |
-
|
365 |
-
for i in range(self.num_upsamples):
|
366 |
-
x = F.leaky_relu(x, LRELU_SLOPE)
|
367 |
-
x_source = self.noise_convs[i](har)
|
368 |
-
x_source = self.noise_res[i](x_source, s)
|
369 |
-
|
370 |
-
x = self.ups[i](x)
|
371 |
-
if i == self.num_upsamples - 1:
|
372 |
-
x = self.reflection_pad(x)
|
373 |
-
|
374 |
-
x = x + x_source
|
375 |
-
xs = None
|
376 |
-
for j in range(self.num_kernels):
|
377 |
-
if xs is None:
|
378 |
-
xs = self.resblocks[i*self.num_kernels+j](x, s)
|
379 |
-
else:
|
380 |
-
xs += self.resblocks[i*self.num_kernels+j](x, s)
|
381 |
-
x = xs / self.num_kernels
|
382 |
-
x = F.leaky_relu(x)
|
383 |
-
x = self.conv_post(x)
|
384 |
-
spec = torch.exp(x[:,:self.post_n_fft // 2 + 1, :])
|
385 |
-
phase = torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
|
386 |
-
return self.stft.inverse(spec, phase)
|
387 |
-
|
388 |
-
def fw_phase(self, x, s):
|
389 |
-
for i in range(self.num_upsamples):
|
390 |
-
x = F.leaky_relu(x, LRELU_SLOPE)
|
391 |
-
x = self.ups[i](x)
|
392 |
-
xs = None
|
393 |
-
for j in range(self.num_kernels):
|
394 |
-
if xs is None:
|
395 |
-
xs = self.resblocks[i*self.num_kernels+j](x, s)
|
396 |
-
else:
|
397 |
-
xs += self.resblocks[i*self.num_kernels+j](x, s)
|
398 |
-
x = xs / self.num_kernels
|
399 |
-
x = F.leaky_relu(x)
|
400 |
-
x = self.reflection_pad(x)
|
401 |
-
x = self.conv_post(x)
|
402 |
-
spec = torch.exp(x[:,:self.post_n_fft // 2 + 1, :])
|
403 |
-
phase = torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
|
404 |
-
return spec, phase
|
405 |
-
|
406 |
-
def remove_weight_norm(self):
|
407 |
-
print('Removing weight norm...')
|
408 |
-
for l in self.ups:
|
409 |
-
remove_weight_norm(l)
|
410 |
-
for l in self.resblocks:
|
411 |
-
l.remove_weight_norm()
|
412 |
-
remove_weight_norm(self.conv_pre)
|
413 |
-
remove_weight_norm(self.conv_post)
|
414 |
-
|
415 |
-
|
416 |
-
class AdainResBlk1d(nn.Module):
|
417 |
-
def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2),
|
418 |
-
upsample='none', dropout_p=0.0):
|
419 |
-
super().__init__()
|
420 |
-
self.actv = actv
|
421 |
-
self.upsample_type = upsample
|
422 |
-
self.upsample = UpSample1d(upsample)
|
423 |
-
self.learned_sc = dim_in != dim_out
|
424 |
-
self._build_weights(dim_in, dim_out, style_dim)
|
425 |
-
self.dropout = nn.Dropout(dropout_p)
|
426 |
-
|
427 |
-
if upsample == 'none':
|
428 |
-
self.pool = nn.Identity()
|
429 |
-
else:
|
430 |
-
self.pool = weight_norm(nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1))
|
431 |
-
|
432 |
-
|
433 |
-
def _build_weights(self, dim_in, dim_out, style_dim):
|
434 |
-
self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
|
435 |
-
self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1))
|
436 |
-
self.norm1 = AdaIN1d(style_dim, dim_in)
|
437 |
-
self.norm2 = AdaIN1d(style_dim, dim_out)
|
438 |
-
if self.learned_sc:
|
439 |
-
self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
|
440 |
-
|
441 |
-
def _shortcut(self, x):
|
442 |
-
x = self.upsample(x)
|
443 |
-
if self.learned_sc:
|
444 |
-
x = self.conv1x1(x)
|
445 |
-
return x
|
446 |
-
|
447 |
-
def _residual(self, x, s):
|
448 |
-
x = self.norm1(x, s)
|
449 |
-
x = self.actv(x)
|
450 |
-
x = self.pool(x)
|
451 |
-
x = self.conv1(self.dropout(x))
|
452 |
-
x = self.norm2(x, s)
|
453 |
-
x = self.actv(x)
|
454 |
-
x = self.conv2(self.dropout(x))
|
455 |
-
return x
|
456 |
-
|
457 |
-
def forward(self, x, s):
|
458 |
-
out = self._residual(x, s)
|
459 |
-
out = (out + self._shortcut(x)) / np.sqrt(2)
|
460 |
-
return out
|
461 |
-
|
462 |
-
class UpSample1d(nn.Module):
|
463 |
-
def __init__(self, layer_type):
|
464 |
-
super().__init__()
|
465 |
-
self.layer_type = layer_type
|
466 |
-
|
467 |
-
def forward(self, x):
|
468 |
-
if self.layer_type == 'none':
|
469 |
-
return x
|
470 |
-
else:
|
471 |
-
return F.interpolate(x, scale_factor=2, mode='nearest')
|
472 |
-
|
473 |
-
class Decoder(nn.Module):
|
474 |
-
def __init__(self, dim_in=512, F0_channel=512, style_dim=64, dim_out=80,
|
475 |
-
resblock_kernel_sizes = [3,7,11],
|
476 |
-
upsample_rates = [10, 6],
|
477 |
-
upsample_initial_channel=512,
|
478 |
-
resblock_dilation_sizes=[[1,3,5], [1,3,5], [1,3,5]],
|
479 |
-
upsample_kernel_sizes=[20, 12],
|
480 |
-
gen_istft_n_fft=20, gen_istft_hop_size=5):
|
481 |
-
super().__init__()
|
482 |
-
|
483 |
-
self.decode = nn.ModuleList()
|
484 |
-
|
485 |
-
self.encode = AdainResBlk1d(dim_in + 2, 1024, style_dim)
|
486 |
-
|
487 |
-
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
488 |
-
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
489 |
-
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
490 |
-
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 512, style_dim, upsample=True))
|
491 |
-
|
492 |
-
self.F0_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
|
493 |
-
|
494 |
-
self.N_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
|
495 |
-
|
496 |
-
self.asr_res = nn.Sequential(
|
497 |
-
weight_norm(nn.Conv1d(512, 64, kernel_size=1)),
|
498 |
-
)
|
499 |
-
|
500 |
-
|
501 |
-
self.generator = Generator(style_dim, resblock_kernel_sizes, upsample_rates,
|
502 |
-
upsample_initial_channel, resblock_dilation_sizes,
|
503 |
-
upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size)
|
504 |
-
|
505 |
-
def forward(self, asr, F0_curve, N, s):
|
506 |
-
F0 = self.F0_conv(F0_curve.unsqueeze(1))
|
507 |
-
N = self.N_conv(N.unsqueeze(1))
|
508 |
-
|
509 |
-
x = torch.cat([asr, F0, N], axis=1)
|
510 |
-
x = self.encode(x, s)
|
511 |
-
|
512 |
-
asr_res = self.asr_res(asr)
|
513 |
-
|
514 |
-
res = True
|
515 |
-
for block in self.decode:
|
516 |
-
if res:
|
517 |
-
x = torch.cat([x, asr_res, F0, N], axis=1)
|
518 |
-
x = block(x, s)
|
519 |
-
if block.upsample_type != "none":
|
520 |
-
res = False
|
521 |
-
|
522 |
-
x = self.generator(x, s, F0_curve)
|
523 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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