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.

329 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. self.W_inverse = W_inverse.half()
  92. self.W_inverse = self.W_inverse.to(torch.float32)
  93. z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)
  94. return z
  95. else:
  96. # Forward computation
  97. log_det_W = batch_size * n_of_groups * torch.logdet(W)
  98. z = self.conv(z)
  99. return z, log_det_W
  100. class WN(torch.nn.Module):
  101. """
  102. This is the WaveNet like layer for the affine coupling. The primary difference
  103. from WaveNet is the convolutions need not be causal. There is also no dilation
  104. size reset. The dilation only doubles on each layer
  105. """
  106. def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels,
  107. kernel_size):
  108. super(WN, self).__init__()
  109. assert(kernel_size % 2 == 1)
  110. assert(n_channels % 2 == 0)
  111. self.n_layers = n_layers
  112. self.n_channels = n_channels
  113. self.in_layers = torch.nn.ModuleList()
  114. self.res_skip_layers = torch.nn.ModuleList()
  115. self.upsample = Upsample1d(2)
  116. start = torch.nn.Conv1d(n_in_channels, n_channels, 1)
  117. start = torch.nn.utils.weight_norm(start, name='weight')
  118. self.start = start
  119. end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1)
  120. end.weight.data.zero_()
  121. end.bias.data.zero_()
  122. self.end = end
  123. # cond_layer
  124. cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels*n_layers, 1)
  125. self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
  126. for i in range(n_layers):
  127. dilation = 1
  128. padding = int((kernel_size*dilation - dilation)/2)
  129. # depthwise separable convolution
  130. depthwise = torch.nn.Conv1d(n_channels, n_channels, 3,
  131. dilation=dilation, padding=padding,
  132. groups=n_channels)
  133. pointwise = torch.nn.Conv1d(n_channels, 2*n_channels, 1)
  134. bn = torch.nn.BatchNorm1d(n_channels)
  135. self.in_layers.append(torch.nn.Sequential(bn, depthwise, pointwise))
  136. # res_skip_layer
  137. res_skip_layer = torch.nn.Conv1d(n_channels, n_channels, 1)
  138. res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
  139. self.res_skip_layers.append(res_skip_layer)
  140. def forward(self, forward_input):
  141. audio, spect = forward_input
  142. audio = self.start(audio)
  143. n_channels_tensor = torch.IntTensor([self.n_channels])
  144. # pass all the mel_spectrograms to cond_layer
  145. spect = self.cond_layer(spect)
  146. for i in range(self.n_layers):
  147. # split the corresponding mel_spectrogram
  148. spect_offset = i*2*self.n_channels
  149. spec = spect[:,spect_offset:spect_offset+2*self.n_channels,:]
  150. if audio.size(2) > spec.size(2):
  151. cond = self.upsample(spec)
  152. else:
  153. cond = spec
  154. acts = fused_add_tanh_sigmoid_multiply(
  155. self.in_layers[i](audio),
  156. cond,
  157. n_channels_tensor)
  158. # res_skip
  159. res_skip_acts = self.res_skip_layers[i](acts)
  160. audio = audio + res_skip_acts
  161. return self.end(audio)
  162. class SqueezeWave(torch.nn.Module):
  163. def __init__(self, n_mel_channels, n_flows, n_audio_channel, n_early_every,
  164. n_early_size, WN_config):
  165. super(SqueezeWave, self).__init__()
  166. assert(n_audio_channel % 2 == 0)
  167. self.n_flows = n_flows
  168. self.n_audio_channel = n_audio_channel
  169. self.n_early_every = n_early_every
  170. self.n_early_size = n_early_size
  171. self.WN = torch.nn.ModuleList()
  172. self.convinv = torch.nn.ModuleList()
  173. n_half = int(n_audio_channel / 2)
  174. # Set up layers with the right sizes based on how many dimensions
  175. # have been output already
  176. n_remaining_channels = n_audio_channel
  177. for k in range(n_flows):
  178. if k % self.n_early_every == 0 and k > 0:
  179. n_half = n_half - int(self.n_early_size/2)
  180. n_remaining_channels = n_remaining_channels - self.n_early_size
  181. self.convinv.append(Invertible1x1Conv(n_remaining_channels))
  182. self.WN.append(WN(n_half, n_mel_channels, **WN_config))
  183. self.n_remaining_channels = n_remaining_channels # Useful during inference
  184. def forward(self, forward_input):
  185. """
  186. forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
  187. forward_input[1] = audio: batch x time
  188. """
  189. spect, audio = forward_input
  190. audio = audio.unfold(
  191. 1, self.n_audio_channel, self.n_audio_channel).permute(0, 2, 1)
  192. output_audio = []
  193. log_s_list = []
  194. log_det_W_list = []
  195. for k in range(self.n_flows):
  196. if k % self.n_early_every == 0 and k > 0:
  197. output_audio.append(audio[:,:self.n_early_size,:])
  198. audio = audio[:,self.n_early_size:,:]
  199. audio, log_det_W = self.convinv[k](audio)
  200. log_det_W_list.append(log_det_W)
  201. n_half = int(audio.size(1)/2)
  202. audio_0 = audio[:,:n_half,:]
  203. audio_1 = audio[:,n_half:,:]
  204. output = self.WN[k]((audio_0, spect))
  205. log_s = output[:, n_half:, :]
  206. b = output[:, :n_half, :]
  207. audio_1 = (torch.exp(log_s))*audio_1 + b
  208. log_s_list.append(log_s)
  209. audio = torch.cat([audio_0, audio_1], 1)
  210. output_audio.append(audio)
  211. return torch.cat(output_audio, 1), log_s_list, log_det_W_list
  212. def infer(self, spect, sigma=1.0):
  213. spect_size = spect.size()
  214. l = spect.size(2)*(256 // self.n_audio_channel)
  215. spect = spect.to(torch.float32)
  216. if spect.type() == 'torch.HalfTensor':
  217. audio = torch.HalfTensor(spect.size(0),
  218. self.n_remaining_channels,
  219. l).normal_()
  220. else:
  221. audio = torch.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.HalfTensor':
  236. z = torch.HalfTensor(spect.size(0), self.n_early_size, l).normal_()
  237. else:
  238. z = torch.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