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.

310 lines
12 KiB

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