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.

317 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.nn.functional.tanh(in_act[:, :n_channels_int, :])
  36. s_act = torch.nn.functional.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) - \
  53. log_s_total - log_det_W_total
  54. return loss/(z.size(0)*z.size(1)*z.size(2))
  55. class Invertible1x1Conv(torch.nn.Module):
  56. """
  57. The layer outputs both the convolution, and the log determinant
  58. of its weight matrix. If reverse=True it does convolution with
  59. inverse
  60. """
  61. def __init__(self, c):
  62. super(Invertible1x1Conv, self).__init__()
  63. self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding=0,
  64. bias=False)
  65. # Sample a random orthonormal matrix to initialize weights
  66. W = torch.qr(torch.FloatTensor(c, c).normal_())[0]
  67. # Ensure determinant is 1.0 not -1.0
  68. if torch.det(W) < 0:
  69. W[:, 0] = -1*W[:, 0]
  70. W = W.view(c, c, 1)
  71. self.conv.weight.data = W
  72. def forward(self, z, reverse=False):
  73. # shape
  74. batch_size, group_size, n_of_groups = z.size()
  75. W = self.conv.weight.squeeze()
  76. if reverse:
  77. if not hasattr(self, 'W_inverse'):
  78. # Reverse computation
  79. W_inverse = W.inverse()
  80. W_inverse = Variable(W_inverse[..., None])
  81. if z.type() == 'torch.cuda.HalfTensor':
  82. W_inverse = W_inverse.half()
  83. self.W_inverse = W_inverse
  84. z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)
  85. return z
  86. else:
  87. # Forward computation
  88. log_det_W = batch_size * n_of_groups * torch.logdet(W)
  89. z = self.conv(z)
  90. return z, log_det_W
  91. class WN(torch.nn.Module):
  92. """
  93. This is the WaveNet like layer for the affine coupling. The primary difference
  94. from WaveNet is the convolutions need not be causal. There is also no dilation
  95. size reset. The dilation only doubles on each layer
  96. """
  97. def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels,
  98. kernel_size):
  99. super(WN, self).__init__()
  100. assert(kernel_size % 2 == 1)
  101. assert(n_channels % 2 == 0)
  102. self.n_layers = n_layers
  103. self.n_channels = n_channels
  104. self.in_layers = torch.nn.ModuleList()
  105. self.res_skip_layers = torch.nn.ModuleList()
  106. self.cond_layers = torch.nn.ModuleList()
  107. start = torch.nn.Conv1d(n_in_channels, n_channels, 1)
  108. start = torch.nn.utils.weight_norm(start, name='weight')
  109. self.start = start
  110. # Initializing last layer to 0 makes the affine coupling layers
  111. # do nothing at first. This helps with training stability
  112. end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1)
  113. end.weight.data.zero_()
  114. end.bias.data.zero_()
  115. self.end = end
  116. for i in range(n_layers):
  117. dilation = 2 ** i
  118. padding = int((kernel_size*dilation - dilation)/2)
  119. in_layer = torch.nn.Conv1d(n_channels, 2*n_channels, kernel_size,
  120. dilation=dilation, padding=padding)
  121. in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
  122. self.in_layers.append(in_layer)
  123. cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels, 1)
  124. cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
  125. self.cond_layers.append(cond_layer)
  126. # last one is not necessary
  127. if i < n_layers - 1:
  128. res_skip_channels = 2*n_channels
  129. else:
  130. res_skip_channels = n_channels
  131. res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1)
  132. res_skip_layer = torch.nn.utils.weight_norm(
  133. res_skip_layer, name='weight')
  134. self.res_skip_layers.append(res_skip_layer)
  135. def forward(self, forward_input):
  136. audio, spect = forward_input
  137. audio = self.start(audio)
  138. for i in range(self.n_layers):
  139. acts = fused_add_tanh_sigmoid_multiply(
  140. self.in_layers[i](audio),
  141. self.cond_layers[i](spect),
  142. torch.IntTensor([self.n_channels]))
  143. res_skip_acts = self.res_skip_layers[i](acts)
  144. if i < self.n_layers - 1:
  145. audio = res_skip_acts[:, :self.n_channels, :] + audio
  146. skip_acts = res_skip_acts[:, self.n_channels:, :]
  147. else:
  148. skip_acts = res_skip_acts
  149. if i == 0:
  150. output = skip_acts
  151. else:
  152. output = skip_acts + output
  153. return self.end(output)
  154. class WaveGlow(torch.nn.Module):
  155. def __init__(self, n_mel_channels, n_flows, n_group, n_early_every,
  156. n_early_size, WN_config):
  157. super(WaveGlow, self).__init__()
  158. self.upsample = torch.nn.ConvTranspose1d(n_mel_channels,
  159. n_mel_channels,
  160. 1024, stride=256)
  161. assert(n_group % 2 == 0)
  162. self.n_flows = n_flows
  163. self.n_group = n_group
  164. self.n_early_every = n_early_every
  165. self.n_early_size = n_early_size
  166. self.WN = torch.nn.ModuleList()
  167. self.convinv = torch.nn.ModuleList()
  168. n_half = int(n_group/2)
  169. # Set up layers with the right sizes based on how many dimensions
  170. # have been output already
  171. n_remaining_channels = n_group
  172. for k in range(n_flows):
  173. if k % self.n_early_every == 0 and k > 0:
  174. n_half = n_half - int(self.n_early_size/2)
  175. n_remaining_channels = n_remaining_channels - self.n_early_size
  176. self.convinv.append(Invertible1x1Conv(n_remaining_channels))
  177. self.WN.append(WN(n_half, n_mel_channels*n_group, **WN_config))
  178. self.n_remaining_channels = n_remaining_channels # Useful during inference
  179. def forward(self, forward_input):
  180. """
  181. forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
  182. forward_input[1] = audio: batch x time
  183. """
  184. spect, audio = forward_input
  185. # Upsample spectrogram to size of audio
  186. spect = self.upsample(spect)
  187. assert(spect.size(2) >= audio.size(1))
  188. if spect.size(2) > audio.size(1):
  189. spect = spect[:, :, :audio.size(1)]
  190. spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
  191. spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)
  192. audio = audio.unfold(1, self.n_group, self.n_group).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 = self.upsample(spect)
  215. # trim conv artifacts. maybe pad spec to kernel multiple
  216. time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0]
  217. spect = spect[:, :, :-time_cutoff]
  218. spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
  219. spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)
  220. if spect.type() == 'torch.cuda.HalfTensor':
  221. audio = torch.cuda.HalfTensor(spect.size(0),
  222. self.n_remaining_channels,
  223. spect.size(2)).normal_()
  224. else:
  225. audio = torch.cuda.FloatTensor(spect.size(0),
  226. self.n_remaining_channels,
  227. spect.size(2)).normal_()
  228. audio = torch.autograd.Variable(sigma*audio)
  229. for k in reversed(range(self.n_flows)):
  230. n_half = int(audio.size(1)/2)
  231. audio_0 = audio[:, :n_half, :]
  232. audio_1 = audio[:, n_half:, :]
  233. output = self.WN[k]((audio_0, spect))
  234. s = output[:, n_half:, :]
  235. b = output[:, :n_half, :]
  236. audio_1 = (audio_1 - b)/torch.exp(s)
  237. audio = torch.cat([audio_0, audio_1], 1)
  238. audio = self.convinv[k](audio, reverse=True)
  239. if k % self.n_early_every == 0 and k > 0:
  240. if spect.type() == 'torch.cuda.HalfTensor':
  241. z = torch.cuda.HalfTensor(spect.size(
  242. 0), self.n_early_size, spect.size(2)).normal_()
  243. else:
  244. z = torch.cuda.FloatTensor(spect.size(
  245. 0), self.n_early_size, spect.size(2)).normal_()
  246. audio = torch.cat((sigma*z, audio), 1)
  247. audio = audio.permute(0, 2, 1).contiguous().view(
  248. audio.size(0), -1).data
  249. return audio
  250. @staticmethod
  251. def remove_weightnorm(model):
  252. waveglow = model
  253. for WN in waveglow.WN:
  254. WN.start = torch.nn.utils.remove_weight_norm(WN.start)
  255. WN.in_layers = remove(WN.in_layers)
  256. WN.cond_layers = remove(WN.cond_layers)
  257. WN.res_skip_layers = remove(WN.res_skip_layers)
  258. return waveglow
  259. def remove(conv_list):
  260. new_conv_list = torch.nn.ModuleList()
  261. for old_conv in conv_list:
  262. old_conv = torch.nn.utils.remove_weight_norm(old_conv)
  263. new_conv_list.append(old_conv)
  264. return new_conv_list