models.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # MIT License
  15. #
  16. # Copyright (c) 2020 Jungil Kong
  17. #
  18. # Permission is hereby granted, free of charge, to any person obtaining a copy
  19. # of this software and associated documentation files (the "Software"), to deal
  20. # in the Software without restriction, including without limitation the rights
  21. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  22. # copies of the Software, and to permit persons to whom the Software is
  23. # furnished to do so, subject to the following conditions:
  24. #
  25. # The above copyright notice and this permission notice shall be included in all
  26. # copies or substantial portions of the Software.
  27. #
  28. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  30. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  32. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  33. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  34. # SOFTWARE.
  35. # The following functions/classes were based on code from https://github.com/jik876/hifi-gan:
  36. # ResBlock1, ResBlock2, Generator, DiscriminatorP, DiscriminatorS, MultiScaleDiscriminator,
  37. # MultiPeriodDiscriminator, feature_loss, discriminator_loss, generator_loss,
  38. # init_weights, get_padding
  39. import torch
  40. import torch.nn as nn
  41. import torch.nn.functional as F
  42. from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
  43. from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
  44. from common.stft import STFT
  45. from common.utils import AttrDict, init_weights, get_padding
  46. LRELU_SLOPE = 0.1
  47. class NoAMPConv1d(Conv1d):
  48. def __init__(self, *args, no_amp=False, **kwargs):
  49. super().__init__(*args, **kwargs)
  50. self.no_amp = no_amp
  51. def _cast(self, x, dtype):
  52. if isinstance(x, (list, tuple)):
  53. return [self._cast(t, dtype) for t in x]
  54. else:
  55. return x.to(dtype)
  56. def forward(self, *args):
  57. if not self.no_amp:
  58. return super().forward(*args)
  59. with torch.cuda.amp.autocast(enabled=False):
  60. return self._cast(
  61. super().forward(*self._cast(args, torch.float)), args[0].dtype)
  62. class ResBlock1(nn.Module):
  63. __constants__ = ['lrelu_slope']
  64. def __init__(self, conf, channels, kernel_size=3, dilation=(1, 3, 5)):
  65. super().__init__()
  66. self.conf = conf
  67. self.lrelu_slope = LRELU_SLOPE
  68. ch, ks = channels, kernel_size
  69. self.convs1 = nn.Sequential(*[
  70. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[0]), dilation[0])),
  71. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[1]), dilation[1])),
  72. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[2]), dilation[2])),
  73. ])
  74. self.convs2 = nn.Sequential(*[
  75. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
  76. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
  77. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
  78. ])
  79. self.convs1.apply(init_weights)
  80. self.convs2.apply(init_weights)
  81. def forward(self, x):
  82. for c1, c2 in zip(self.convs1, self.convs2):
  83. xt = F.leaky_relu(x, self.lrelu_slope)
  84. xt = c1(xt)
  85. xt = F.leaky_relu(xt, self.lrelu_slope)
  86. xt = c2(xt)
  87. x = xt + x
  88. return x
  89. def remove_weight_norm(self):
  90. for l in self.convs1:
  91. remove_weight_norm(l)
  92. for l in self.convs2:
  93. remove_weight_norm(l)
  94. class ResBlock2(nn.Module):
  95. __constants__ = ['lrelu_slope']
  96. def __init__(self, conf, channels, kernel_size=3, dilation=(1, 3)):
  97. super().__init__()
  98. self.conf = conf
  99. ch, ks = channels, kernel_size
  100. self.convs = nn.ModuleList([
  101. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(kernel_size, dilation[0]), dilation[0])),
  102. weight_norm(Conv1d(ch, ch, ks, 1, get_padding(kernel_size, dilation[1]), dilation[1])),
  103. ])
  104. self.convs.apply(init_weights)
  105. def forward(self, x):
  106. for c in self.convs:
  107. xt = F.leaky_relu(x, self.lrelu_slope)
  108. xt = c(xt)
  109. x = xt + x
  110. return x
  111. def remove_weight_norm(self):
  112. for l in self.convs:
  113. remove_weight_norm(l)
  114. class Generator(nn.Module):
  115. __constants__ = ['lrelu_slope', 'num_kernels', 'num_upsamples']
  116. def __init__(self, conf):
  117. super().__init__()
  118. conf = AttrDict(conf)
  119. self.conf = conf
  120. self.num_kernels = len(conf.resblock_kernel_sizes)
  121. self.num_upsamples = len(conf.upsample_rates)
  122. self.conv_pre = weight_norm(
  123. Conv1d(80, conf.upsample_initial_channel, 7, 1, padding=3))
  124. self.lrelu_slope = LRELU_SLOPE
  125. resblock = ResBlock1 if conf.resblock == '1' else ResBlock2
  126. self.ups = []
  127. for i, (u, k) in enumerate(zip(conf.upsample_rates,
  128. conf.upsample_kernel_sizes)):
  129. self.ups.append(weight_norm(
  130. ConvTranspose1d(conf.upsample_initial_channel // (2 ** i),
  131. conf.upsample_initial_channel // (2 ** (i + 1)),
  132. k, u, padding=(k-u)//2)))
  133. self.ups = nn.Sequential(*self.ups)
  134. self.resblocks = []
  135. for i in range(len(self.ups)):
  136. resblock_list = []
  137. ch = conf.upsample_initial_channel // (2 ** (i + 1))
  138. for j, (k, d) in enumerate(zip(conf.resblock_kernel_sizes,
  139. conf.resblock_dilation_sizes)):
  140. resblock_list.append(resblock(conf, ch, k, d))
  141. resblock_list = nn.Sequential(*resblock_list)
  142. self.resblocks.append(resblock_list)
  143. self.resblocks = nn.Sequential(*self.resblocks)
  144. self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
  145. self.ups.apply(init_weights)
  146. self.conv_post.apply(init_weights)
  147. def load_state_dict(self, state_dict, strict=True):
  148. # Fallback for old checkpoints (pre-ONNX fix)
  149. new_sd = {}
  150. for k, v in state_dict.items():
  151. new_k = k
  152. if 'resblocks' in k:
  153. parts = k.split(".")
  154. # only do this is the checkpoint type is older
  155. if len(parts) == 5:
  156. layer = int(parts[1])
  157. new_layer = f"{layer//3}.{layer%3}"
  158. new_k = f"resblocks.{new_layer}.{'.'.join(parts[2:])}"
  159. new_sd[new_k] = v
  160. # Fix for conv1d/conv2d/NHWC
  161. curr_sd = self.state_dict()
  162. for key in new_sd:
  163. len_diff = len(new_sd[key].size()) - len(curr_sd[key].size())
  164. if len_diff == -1:
  165. new_sd[key] = new_sd[key].unsqueeze(-1)
  166. elif len_diff == 1:
  167. new_sd[key] = new_sd[key].squeeze(-1)
  168. super().load_state_dict(new_sd, strict=strict)
  169. def forward(self, x):
  170. x = self.conv_pre(x)
  171. for upsample_layer, resblock_group in zip(self.ups, self.resblocks):
  172. x = F.leaky_relu(x, self.lrelu_slope)
  173. x = upsample_layer(x)
  174. xs = 0
  175. for resblock in resblock_group:
  176. xs += resblock(x)
  177. x = xs / self.num_kernels
  178. x = F.leaky_relu(x)
  179. x = self.conv_post(x)
  180. x = torch.tanh(x)
  181. return x
  182. def remove_weight_norm(self):
  183. print('HiFi-GAN: Removing weight norm.')
  184. for l in self.ups:
  185. remove_weight_norm(l)
  186. for group in self.resblocks:
  187. for block in group:
  188. block.remove_weight_norm()
  189. remove_weight_norm(self.conv_pre)
  190. remove_weight_norm(self.conv_post)
  191. class Denoiser(nn.Module):
  192. """ Removes model bias from audio produced with hifigan """
  193. def __init__(self, hifigan, filter_length=1024, n_overlap=4,
  194. win_length=1024, mode='zeros', **infer_kw):
  195. super().__init__()
  196. self.stft = STFT(filter_length=filter_length,
  197. hop_length=int(filter_length/n_overlap),
  198. win_length=win_length).cuda()
  199. for name, p in hifigan.named_parameters():
  200. if name.endswith('.weight'):
  201. dtype = p.dtype
  202. device = p.device
  203. break
  204. mel_init = {'zeros': torch.zeros, 'normal': torch.randn}[mode]
  205. mel_input = mel_init((1, 80, 88), dtype=dtype, device=device)
  206. with torch.no_grad():
  207. bias_audio = hifigan(mel_input, **infer_kw).float()
  208. if len(bias_audio.size()) > 2:
  209. bias_audio = bias_audio.squeeze(0)
  210. elif len(bias_audio.size()) < 2:
  211. bias_audio = bias_audio.unsqueeze(0)
  212. assert len(bias_audio.size()) == 2
  213. bias_spec, _ = self.stft.transform(bias_audio)
  214. self.register_buffer('bias_spec', bias_spec[:, :, 0][:, :, None])
  215. def forward(self, audio, strength=0.1):
  216. audio_spec, audio_angles = self.stft.transform(audio.cuda().float())
  217. audio_spec_denoised = audio_spec - self.bias_spec * strength
  218. audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0)
  219. audio_denoised = self.stft.inverse(audio_spec_denoised, audio_angles)
  220. return audio_denoised
  221. class DiscriminatorP(nn.Module):
  222. def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
  223. super().__init__()
  224. self.period = period
  225. norm_f = spectral_norm if use_spectral_norm else weight_norm
  226. ks = kernel_size
  227. self.convs = nn.ModuleList([
  228. norm_f(Conv2d(1, 32, (ks, 1), (stride, 1), (get_padding(5, 1), 0))),
  229. norm_f(Conv2d(32, 128, (ks, 1), (stride, 1), (get_padding(5, 1), 0))),
  230. norm_f(Conv2d(128, 512, (ks, 1), (stride, 1), (get_padding(5, 1), 0))),
  231. norm_f(Conv2d(512, 1024, (ks, 1), (stride, 1), (get_padding(5, 1), 0))),
  232. norm_f(Conv2d(1024, 1024, (ks, 1), 1, padding=(2, 0))),
  233. ])
  234. self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
  235. def forward(self, x):
  236. fmap = []
  237. # 1d to 2d
  238. b, c, t = x.shape
  239. if t % self.period != 0: # pad first
  240. n_pad = self.period - (t % self.period)
  241. x = F.pad(x, (0, n_pad), "reflect")
  242. t = t + n_pad
  243. x = x.view(b, c, t // self.period, self.period)
  244. for l in self.convs:
  245. x = l(x)
  246. x = F.leaky_relu(x, LRELU_SLOPE)
  247. fmap.append(x)
  248. x = self.conv_post(x)
  249. fmap.append(x)
  250. x = torch.flatten(x, 1, -1)
  251. return x, fmap
  252. def share_params_of(self, dp):
  253. assert len(self.convs) == len(dp.convs)
  254. for c1, c2 in zip(self.convs, dp.convs):
  255. c1.weight = c2.weight
  256. c1.bias = c2.bias
  257. class MultiPeriodDiscriminator(nn.Module):
  258. def __init__(self, periods, concat_fwd=False):
  259. super().__init__()
  260. layers = [DiscriminatorP(p) for p in periods]
  261. self.discriminators = nn.ModuleList(layers)
  262. self.concat_fwd = concat_fwd
  263. def forward(self, y, y_hat):
  264. y_d_rs = []
  265. y_d_gs = []
  266. fmap_rs = []
  267. fmap_gs = []
  268. for i, d in enumerate(self.discriminators):
  269. if self.concat_fwd:
  270. y_ds, fmaps = d(concat_discr_input(y, y_hat))
  271. y_d_r, y_d_g, fmap_r, fmap_g = split_discr_output(y_ds, fmaps)
  272. else:
  273. y_d_r, fmap_r = d(y)
  274. y_d_g, fmap_g = d(y_hat)
  275. y_d_rs.append(y_d_r)
  276. fmap_rs.append(fmap_r)
  277. y_d_gs.append(y_d_g)
  278. fmap_gs.append(fmap_g)
  279. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  280. class DiscriminatorS(nn.Module):
  281. def __init__(self, use_spectral_norm=False, no_amp_grouped_conv=False):
  282. super().__init__()
  283. norm_f = spectral_norm if use_spectral_norm else weight_norm
  284. self.convs = nn.ModuleList([
  285. norm_f(Conv1d(1, 128, 15, 1, padding=7)),
  286. norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
  287. norm_f(NoAMPConv1d(128, 256, 41, 2, groups=16, padding=20, no_amp=no_amp_grouped_conv)),
  288. norm_f(NoAMPConv1d(256, 512, 41, 4, groups=16, padding=20, no_amp=no_amp_grouped_conv)),
  289. norm_f(NoAMPConv1d(512, 1024, 41, 4, groups=16, padding=20, no_amp=no_amp_grouped_conv)),
  290. norm_f(NoAMPConv1d(1024, 1024, 41, 1, groups=16, padding=20, no_amp=no_amp_grouped_conv)),
  291. norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
  292. ])
  293. self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
  294. def forward(self, x):
  295. fmap = []
  296. for l in self.convs:
  297. # x = l(x.unsqueeze(-1)).squeeze(-1)
  298. x = l(x)
  299. x = F.leaky_relu(x, LRELU_SLOPE)
  300. fmap.append(x)
  301. x = self.conv_post(x)
  302. fmap.append(x)
  303. x = torch.flatten(x, 1, -1)
  304. return x, fmap
  305. class MultiScaleDiscriminator(nn.Module):
  306. def __init__(self, no_amp_grouped_conv=False, concat_fwd=False):
  307. super().__init__()
  308. self.discriminators = nn.ModuleList([
  309. DiscriminatorS(use_spectral_norm=True, no_amp_grouped_conv=no_amp_grouped_conv),
  310. DiscriminatorS(no_amp_grouped_conv=no_amp_grouped_conv),
  311. DiscriminatorS(no_amp_grouped_conv=no_amp_grouped_conv),
  312. ])
  313. self.meanpools = nn.ModuleList([
  314. AvgPool1d(4, 2, padding=1),
  315. AvgPool1d(4, 2, padding=1)
  316. ])
  317. self.concat_fwd = concat_fwd
  318. def forward(self, y, y_hat):
  319. y_d_rs = []
  320. y_d_gs = []
  321. fmap_rs = []
  322. fmap_gs = []
  323. for i, d in enumerate(self.discriminators):
  324. if self.concat_fwd:
  325. ys = concat_discr_input(y, y_hat)
  326. if i != 0:
  327. ys = self.meanpools[i-1](ys)
  328. y_ds, fmaps = d(ys)
  329. y_d_r, y_d_g, fmap_r, fmap_g = split_discr_output(y_ds, fmaps)
  330. else:
  331. if i != 0:
  332. y = self.meanpools[i-1](y)
  333. y_hat = self.meanpools[i-1](y_hat)
  334. y_d_r, fmap_r = d(y)
  335. y_d_g, fmap_g = d(y_hat)
  336. y_d_rs.append(y_d_r)
  337. fmap_rs.append(fmap_r)
  338. y_d_gs.append(y_d_g)
  339. fmap_gs.append(fmap_g)
  340. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  341. def concat_discr_input(y, y_hat):
  342. return torch.cat((y, y_hat), dim=0)
  343. def split_discr_output(y_ds, fmaps):
  344. y_d_r, y_d_g = torch.chunk(y_ds, 2, dim=0)
  345. fmap_r, fmap_g = zip(*(torch.chunk(f, 2, dim=0) for f in fmaps))
  346. return y_d_r, y_d_g, fmap_r, fmap_g
  347. def feature_loss(fmap_r, fmap_g):
  348. loss = 0
  349. for dr, dg in zip(fmap_r, fmap_g):
  350. for rl, gl in zip(dr, dg):
  351. loss += torch.mean(torch.abs(rl - gl))
  352. return loss*2
  353. def discriminator_loss(disc_real_outputs, disc_generated_outputs):
  354. loss = 0
  355. r_losses = []
  356. g_losses = []
  357. for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
  358. r_loss = torch.mean((1-dr)**2)
  359. g_loss = torch.mean(dg**2)
  360. loss += (r_loss + g_loss)
  361. r_losses.append(r_loss.item())
  362. g_losses.append(g_loss.item())
  363. return loss, r_losses, g_losses
  364. def generator_loss(disc_outputs):
  365. loss = 0
  366. gen_losses = []
  367. for dg in disc_outputs:
  368. l = torch.mean((1-dg)**2)
  369. gen_losses.append(l)
  370. loss += l
  371. return loss, gen_losses