Fork of https://github.com/alokprasad/fastspeech_squeezewave to also fix denoising in squeezewave
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
13 KiB

  1. # We retain the copyright notice by NVIDIA from the original code. However, we
  2. # we reserve our rights on the modifications based on the original code.
  3. #
  4. # *****************************************************************************
  5. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are met:
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. # * Neither the name of the NVIDIA CORPORATION nor the
  15. # names of its contributors may be used to endorse or promote products
  16. # derived from this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
  22. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. #
  29. # *****************************************************************************
  30. import torch
  31. from torch.autograd import Variable
  32. import torch.nn.functional as F
  33. import numpy as np
  34. @torch.jit.script
  35. def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
  36. n_channels_int = n_channels[0]
  37. in_act = input_a+input_b
  38. t_act = torch.tanh(in_act[:, :n_channels_int, :])
  39. s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
  40. acts = t_act * s_act
  41. return acts
  42. class Upsample1d(torch.nn.Module):
  43. def __init__(self, scale=2):
  44. super(Upsample1d, self).__init__()
  45. self.scale = scale
  46. def forward(self, x):
  47. y = F.interpolate(
  48. x, scale_factor=self.scale, mode='nearest')
  49. return y
  50. class SqueezeWaveLoss(torch.nn.Module):
  51. def __init__(self, sigma=1.0):
  52. super(SqueezeWaveLoss, self).__init__()
  53. self.sigma = sigma
  54. def forward(self, model_output):
  55. z, log_s_list, log_det_W_list = model_output
  56. for i, log_s in enumerate(log_s_list):
  57. if i == 0:
  58. log_s_total = torch.sum(log_s)
  59. log_det_W_total = log_det_W_list[i]
  60. else:
  61. log_s_total = log_s_total + torch.sum(log_s)
  62. log_det_W_total += log_det_W_list[i]
  63. loss = torch.sum(z*z)/(2*self.sigma*self.sigma) - log_s_total - log_det_W_total
  64. return loss/(z.size(0)*z.size(1)*z.size(2))
  65. class Invertible1x1Conv(torch.nn.Module):
  66. """
  67. The layer outputs both the convolution, and the log determinant
  68. of its weight matrix. If reverse=True it does convolution with
  69. inverse
  70. """
  71. def __init__(self, c):
  72. super(Invertible1x1Conv, self).__init__()
  73. self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding=0,
  74. bias=False)
  75. # Sample a random orthonormal matrix to initialize weights
  76. W = torch.qr(torch.FloatTensor(c, c).normal_())[0]
  77. # Ensure determinant is 1.0 not -1.0
  78. if torch.det(W) < 0:
  79. W[:,0] = -1*W[:,0]
  80. W = W.view(c, c, 1)
  81. self.conv.weight.data = W
  82. def forward(self, z, reverse=False):
  83. # shape
  84. batch_size, group_size, n_of_groups = z.size()
  85. W = self.conv.weight.squeeze()
  86. if reverse:
  87. if not hasattr(self, 'W_inverse'):
  88. # Reverse computation
  89. W_inverse = W.float().inverse()
  90. W_inverse = Variable(W_inverse[..., None])
  91. if z.type() == 'torch.cuda.HalfTensor':
  92. W_inverse = W_inverse.half()
  93. self.W_inverse = W_inverse
  94. z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)
  95. return z
  96. else:
  97. # Forward computation
  98. log_det_W = batch_size * n_of_groups * torch.logdet(W)
  99. z = self.conv(z)
  100. return z, log_det_W
  101. class WN(torch.nn.Module):
  102. """
  103. This is the WaveNet like layer for the affine coupling. The primary difference
  104. from WaveNet is the convolutions need not be causal. There is also no dilation
  105. size reset. The dilation only doubles on each layer
  106. """
  107. def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels,
  108. kernel_size):
  109. super(WN, self).__init__()
  110. assert(kernel_size % 2 == 1)
  111. assert(n_channels % 2 == 0)
  112. self.n_layers = n_layers
  113. self.n_channels = n_channels
  114. self.in_layers = torch.nn.ModuleList()
  115. self.res_skip_layers = torch.nn.ModuleList()
  116. self.upsample = Upsample1d(2)
  117. start = torch.nn.Conv1d(n_in_channels, n_channels, 1)
  118. start = torch.nn.utils.weight_norm(start, name='weight')
  119. self.start = start
  120. end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1)
  121. end.weight.data.zero_()
  122. end.bias.data.zero_()
  123. self.end = end
  124. # cond_layer
  125. cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels*n_layers, 1)
  126. self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
  127. for i in range(n_layers):
  128. dilation = 1
  129. padding = int((kernel_size*dilation - dilation)/2)
  130. # depthwise separable convolution
  131. depthwise = torch.nn.Conv1d(n_channels, n_channels, 3,
  132. dilation=dilation, padding=padding,
  133. groups=n_channels).cuda()
  134. pointwise = torch.nn.Conv1d(n_channels, 2*n_channels, 1).cuda()
  135. bn = torch.nn.BatchNorm1d(n_channels)
  136. self.in_layers.append(torch.nn.Sequential(bn, depthwise, pointwise))
  137. # res_skip_layer
  138. res_skip_layer = torch.nn.Conv1d(n_channels, n_channels, 1)
  139. res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
  140. self.res_skip_layers.append(res_skip_layer)
  141. def forward(self, forward_input):
  142. audio, spect = forward_input
  143. audio = self.start(audio)
  144. n_channels_tensor = torch.IntTensor([self.n_channels])
  145. # pass all the mel_spectrograms to cond_layer
  146. spect = self.cond_layer(spect)
  147. for i in range(self.n_layers):
  148. # split the corresponding mel_spectrogram
  149. spect_offset = i*2*self.n_channels
  150. spec = spect[:,spect_offset:spect_offset+2*self.n_channels,:]
  151. if audio.size(2) > spec.size(2):
  152. cond = self.upsample(spec)
  153. else:
  154. cond = spec
  155. acts = fused_add_tanh_sigmoid_multiply(
  156. self.in_layers[i](audio),
  157. cond,
  158. n_channels_tensor)
  159. # res_skip
  160. res_skip_acts = self.res_skip_layers[i](acts)
  161. audio = audio + res_skip_acts
  162. return self.end(audio)
  163. class SqueezeWave(torch.nn.Module):
  164. def __init__(self, n_mel_channels, n_flows, n_audio_channel, n_early_every,
  165. n_early_size, WN_config):
  166. super(SqueezeWave, self).__init__()
  167. assert(n_audio_channel % 2 == 0)
  168. self.n_flows = n_flows
  169. self.n_audio_channel = n_audio_channel
  170. self.n_early_every = n_early_every
  171. self.n_early_size = n_early_size
  172. self.WN = torch.nn.ModuleList()
  173. self.convinv = torch.nn.ModuleList()
  174. n_half = int(n_audio_channel / 2)
  175. # Set up layers with the right sizes based on how many dimensions
  176. # have been output already
  177. n_remaining_channels = n_audio_channel
  178. for k in range(n_flows):
  179. if k % self.n_early_every == 0 and k > 0:
  180. n_half = n_half - int(self.n_early_size/2)
  181. n_remaining_channels = n_remaining_channels - self.n_early_size
  182. self.convinv.append(Invertible1x1Conv(n_remaining_channels))
  183. self.WN.append(WN(n_half, n_mel_channels, **WN_config))
  184. self.n_remaining_channels = n_remaining_channels # Useful during inference
  185. def forward(self, forward_input):
  186. """
  187. forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
  188. forward_input[1] = audio: batch x time
  189. """
  190. spect, audio = forward_input
  191. audio = audio.unfold(
  192. 1, self.n_audio_channel, self.n_audio_channel).permute(0, 2, 1)
  193. output_audio = []
  194. log_s_list = []
  195. log_det_W_list = []
  196. for k in range(self.n_flows):
  197. if k % self.n_early_every == 0 and k > 0:
  198. output_audio.append(audio[:,:self.n_early_size,:])
  199. audio = audio[:,self.n_early_size:,:]
  200. audio, log_det_W = self.convinv[k](audio)
  201. log_det_W_list.append(log_det_W)
  202. n_half = int(audio.size(1)/2)
  203. audio_0 = audio[:,:n_half,:]
  204. audio_1 = audio[:,n_half:,:]
  205. output = self.WN[k]((audio_0, spect))
  206. log_s = output[:, n_half:, :]
  207. b = output[:, :n_half, :]
  208. audio_1 = (torch.exp(log_s))*audio_1 + b
  209. log_s_list.append(log_s)
  210. audio = torch.cat([audio_0, audio_1], 1)
  211. output_audio.append(audio)
  212. return torch.cat(output_audio, 1), log_s_list, log_det_W_list
  213. def infer(self, spect, sigma=1.0):
  214. spect_size = spect.size()
  215. l = spect.size(2)*(256 // self.n_audio_channel)
  216. if spect.type() == 'torch.cuda.HalfTensor':
  217. audio = torch.cuda.HalfTensor(spect.size(0),
  218. self.n_remaining_channels,
  219. l).normal_()
  220. else:
  221. audio = torch.cuda.FloatTensor(spect.size(0),
  222. self.n_remaining_channels,
  223. l).normal_()
  224. for k in reversed(range(self.n_flows)):
  225. n_half = int(audio.size(1)/2)
  226. audio_0 = audio[:,:n_half,:]
  227. audio_1 = audio[:,n_half:,:]
  228. output = self.WN[k]((audio_0, spect))
  229. s = output[:, n_half:, :]
  230. b = output[:, :n_half, :]
  231. audio_1 = (audio_1 - b)/torch.exp(s)
  232. audio = torch.cat([audio_0, audio_1],1)
  233. audio = self.convinv[k](audio, reverse=True)
  234. if k % self.n_early_every == 0 and k > 0:
  235. if spect.type() == 'torch.cuda.HalfTensor':
  236. z = torch.cuda.HalfTensor(spect.size(0), self.n_early_size, l).normal_()
  237. else:
  238. z = torch.cuda.FloatTensor(spect.size(0), self.n_early_size, l).normal_()
  239. audio = torch.cat((sigma*z, audio),1)
  240. audio = audio.permute(0,2,1).contiguous().view(audio.size(0), -1).data
  241. return audio
  242. @staticmethod
  243. def remove_weightnorm(model):
  244. squeezewave = model
  245. for WN in squeezewave.WN:
  246. WN.start = torch.nn.utils.remove_weight_norm(WN.start)
  247. WN.in_layers = remove_batch_norm(WN.in_layers)
  248. WN.cond_layer = torch.nn.utils.remove_weight_norm(WN.cond_layer)
  249. WN.res_skip_layers = remove(WN.res_skip_layers)
  250. return squeezewave
  251. def fuse_conv_and_bn(conv, bn):
  252. fusedconv = torch.nn.Conv1d(
  253. conv.in_channels,
  254. conv.out_channels,
  255. kernel_size = conv.kernel_size,
  256. padding=conv.padding,
  257. bias=True,
  258. groups=conv.groups)
  259. w_conv = conv.weight.clone().view(conv.out_channels, -1)
  260. w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps+bn.running_var)))
  261. w_bn = w_bn.clone()
  262. fusedconv.weight.data = torch.mm(w_bn, w_conv).view(fusedconv.weight.size())
  263. if conv.bias is not None:
  264. b_conv = conv.bias
  265. else:
  266. b_conv = torch.zeros( conv.weight.size(0) )
  267. b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
  268. b_bn = torch.unsqueeze(b_bn, 1)
  269. bn_3 = b_bn.expand(-1, 3)
  270. b = torch.matmul(w_conv, torch.transpose(bn_3, 0, 1))[range(b_bn.size()[0]), range(b_bn.size()[0])]
  271. fusedconv.bias.data = ( b_conv + b )
  272. return fusedconv
  273. def remove_batch_norm(conv_list):
  274. new_conv_list = torch.nn.ModuleList()
  275. for old_conv in conv_list:
  276. depthwise = fuse_conv_and_bn(old_conv[1], old_conv[0])
  277. pointwise = old_conv[2]
  278. new_conv_list.append(torch.nn.Sequential(depthwise, pointwise))
  279. return new_conv_list
  280. def remove(conv_list):
  281. new_conv_list = torch.nn.ModuleList()
  282. for old_conv in conv_list:
  283. old_conv = torch.nn.utils.remove_weight_norm(old_conv)
  284. new_conv_list.append(old_conv)
  285. return new_conv_list