discriminator.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. try:
  5. from torch.nn.utils.parametrizations import weight_norm, spectral_norm
  6. except ImportError:
  7. from torch.nn.utils import weight_norm, spectral_norm
  8. from typing import List, Optional, Tuple
  9. from einops import rearrange
  10. from torchaudio.transforms import Spectrogram
  11. LRELU_SLOPE = 0.1
  12. class MultipleDiscriminator(nn.Module):
  13. def __init__(
  14. self, mpd: nn.Module, mrd: nn.Module
  15. ):
  16. super().__init__()
  17. self.mpd = mpd
  18. self.mrd = mrd
  19. def forward(self, y: torch.Tensor, y_hat: torch.Tensor):
  20. y_d_rs, y_d_gs, fmap_rs, fmap_gs = [], [], [], []
  21. this_y_d_rs, this_y_d_gs, this_fmap_rs, this_fmap_gs = self.mpd(y.unsqueeze(dim=1), y_hat.unsqueeze(dim=1))
  22. y_d_rs += this_y_d_rs
  23. y_d_gs += this_y_d_gs
  24. fmap_rs += this_fmap_rs
  25. fmap_gs += this_fmap_gs
  26. this_y_d_rs, this_y_d_gs, this_fmap_rs, this_fmap_gs = self.mrd(y, y_hat)
  27. y_d_rs += this_y_d_rs
  28. y_d_gs += this_y_d_gs
  29. fmap_rs += this_fmap_rs
  30. fmap_gs += this_fmap_gs
  31. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  32. class MultiResolutionDiscriminator(nn.Module):
  33. def __init__(
  34. self,
  35. fft_sizes: Tuple[int, ...] = (2048, 1024, 512),
  36. num_embeddings: Optional[int] = None,
  37. ):
  38. """
  39. Multi-Resolution Discriminator module adapted from https://github.com/descriptinc/descript-audio-codec.
  40. Additionally, it allows incorporating conditional information with a learned embeddings table.
  41. Args:
  42. fft_sizes (tuple[int]): Tuple of window lengths for FFT. Defaults to (2048, 1024, 512).
  43. num_embeddings (int, optional): Number of embeddings. None means non-conditional discriminator.
  44. Defaults to None.
  45. """
  46. super().__init__()
  47. self.discriminators = nn.ModuleList(
  48. [DiscriminatorR(window_length=w, num_embeddings=num_embeddings) for w in fft_sizes]
  49. )
  50. def forward(
  51. self, y: torch.Tensor, y_hat: torch.Tensor, bandwidth_id: torch.Tensor = None
  52. ) -> Tuple[List[torch.Tensor], List[torch.Tensor], List[List[torch.Tensor]], List[List[torch.Tensor]]]:
  53. y_d_rs = []
  54. y_d_gs = []
  55. fmap_rs = []
  56. fmap_gs = []
  57. for d in self.discriminators:
  58. y_d_r, fmap_r = d(x=y, cond_embedding_id=bandwidth_id)
  59. y_d_g, fmap_g = d(x=y_hat, cond_embedding_id=bandwidth_id)
  60. y_d_rs.append(y_d_r)
  61. fmap_rs.append(fmap_r)
  62. y_d_gs.append(y_d_g)
  63. fmap_gs.append(fmap_g)
  64. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  65. class DiscriminatorR(nn.Module):
  66. def __init__(
  67. self,
  68. window_length: int,
  69. num_embeddings: Optional[int] = None,
  70. channels: int = 32,
  71. hop_factor: float = 0.25,
  72. bands: Tuple[Tuple[float, float], ...] = ((0.0, 0.1), (0.1, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)),
  73. ):
  74. super().__init__()
  75. self.window_length = window_length
  76. self.hop_factor = hop_factor
  77. self.spec_fn = Spectrogram(
  78. n_fft=window_length, hop_length=int(window_length * hop_factor), win_length=window_length, power=None
  79. )
  80. n_fft = window_length // 2 + 1
  81. bands = [(int(b[0] * n_fft), int(b[1] * n_fft)) for b in bands]
  82. self.bands = bands
  83. convs = lambda: nn.ModuleList(
  84. [
  85. weight_norm(nn.Conv2d(2, channels, (3, 9), (1, 1), padding=(1, 4))),
  86. weight_norm(nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4))),
  87. weight_norm(nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4))),
  88. weight_norm(nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4))),
  89. weight_norm(nn.Conv2d(channels, channels, (3, 3), (1, 1), padding=(1, 1))),
  90. ]
  91. )
  92. self.band_convs = nn.ModuleList([convs() for _ in range(len(self.bands))])
  93. if num_embeddings is not None:
  94. self.emb = torch.nn.Embedding(num_embeddings=num_embeddings, embedding_dim=channels)
  95. torch.nn.init.zeros_(self.emb.weight)
  96. self.conv_post = weight_norm(nn.Conv2d(channels, 1, (3, 3), (1, 1), padding=(1, 1)))
  97. def spectrogram(self, x):
  98. # Remove DC offset
  99. x = x - x.mean(dim=-1, keepdims=True)
  100. # Peak normalize the volume of input audio
  101. x = 0.8 * x / (x.abs().max(dim=-1, keepdim=True)[0] + 1e-9)
  102. x = self.spec_fn(x)
  103. x = torch.view_as_real(x)
  104. x = rearrange(x, "b f t c -> b c t f")
  105. # Split into bands
  106. x_bands = [x[..., b[0]: b[1]] for b in self.bands]
  107. return x_bands
  108. def forward(self, x: torch.Tensor, cond_embedding_id: torch.Tensor = None):
  109. x_bands = self.spectrogram(x)
  110. fmap = []
  111. x = []
  112. for band, stack in zip(x_bands, self.band_convs):
  113. for i, layer in enumerate(stack):
  114. band = layer(band)
  115. band = torch.nn.functional.leaky_relu(band, 0.1)
  116. if i > 0:
  117. fmap.append(band)
  118. x.append(band)
  119. x = torch.cat(x, dim=-1)
  120. if cond_embedding_id is not None:
  121. emb = self.emb(cond_embedding_id)
  122. h = (emb.view(1, -1, 1, 1) * x).sum(dim=1, keepdims=True)
  123. else:
  124. h = 0
  125. x = self.conv_post(x)
  126. fmap.append(x)
  127. x += h
  128. return x, fmap
  129. class MultiResSpecDiscriminator(torch.nn.Module):
  130. def __init__(self,
  131. fft_sizes=[1024, 2048, 512],
  132. hop_sizes=[120, 240, 50],
  133. win_lengths=[600, 1200, 240],
  134. window="hann_window"):
  135. super(MultiResSpecDiscriminator, self).__init__()
  136. self.discriminators = nn.ModuleList([
  137. SpecDiscriminator(fft_sizes[0], hop_sizes[0], win_lengths[0], window),
  138. SpecDiscriminator(fft_sizes[1], hop_sizes[1], win_lengths[1], window),
  139. SpecDiscriminator(fft_sizes[2], hop_sizes[2], win_lengths[2], window)])
  140. def forward(self, y, y_hat):
  141. y_d_rs = []
  142. y_d_gs = []
  143. fmap_rs = []
  144. fmap_gs = []
  145. for _, d in enumerate(self.discriminators):
  146. y_d_r, fmap_r = d(y)
  147. y_d_g, fmap_g = d(y_hat)
  148. y_d_rs.append(y_d_r)
  149. fmap_rs.append(fmap_r)
  150. y_d_gs.append(y_d_g)
  151. fmap_gs.append(fmap_g)
  152. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  153. def stft(x, fft_size, hop_size, win_length, window):
  154. """Perform STFT and convert to magnitude spectrogram.
  155. Args:
  156. x (Tensor): Input signal tensor (B, T).
  157. fft_size (int): FFT size.
  158. hop_size (int): Hop size.
  159. win_length (int): Window length.
  160. window (str): Window function type.
  161. Returns:
  162. Tensor: Magnitude spectrogram (B, #frames, fft_size // 2 + 1).
  163. """
  164. x_stft = torch.stft(x, fft_size, hop_size, win_length, window, return_complex=True)
  165. # NOTE(kan-bayashi): clamp is needed to avoid nan or inf
  166. return torch.abs(x_stft).transpose(2, 1)
  167. class SpecDiscriminator(nn.Module):
  168. """docstring for Discriminator."""
  169. def __init__(self, fft_size=1024, shift_size=120, win_length=600, window="hann_window", use_spectral_norm=False):
  170. super(SpecDiscriminator, self).__init__()
  171. norm_f = weight_norm if use_spectral_norm is False else spectral_norm
  172. self.fft_size = fft_size
  173. self.shift_size = shift_size
  174. self.win_length = win_length
  175. self.window = getattr(torch, window)(win_length)
  176. self.discriminators = nn.ModuleList([
  177. norm_f(nn.Conv2d(1, 32, kernel_size=(3, 9), padding=(1, 4))),
  178. norm_f(nn.Conv2d(32, 32, kernel_size=(3, 9), stride=(1, 2), padding=(1, 4))),
  179. norm_f(nn.Conv2d(32, 32, kernel_size=(3, 9), stride=(1, 2), padding=(1, 4))),
  180. norm_f(nn.Conv2d(32, 32, kernel_size=(3, 9), stride=(1, 2), padding=(1, 4))),
  181. norm_f(nn.Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))),
  182. ])
  183. self.out = norm_f(nn.Conv2d(32, 1, 3, 1, 1))
  184. def forward(self, y):
  185. fmap = []
  186. y = y.squeeze(1)
  187. y = stft(y, self.fft_size, self.shift_size, self.win_length, self.window.to(y.device))
  188. y = y.unsqueeze(1)
  189. for _, d in enumerate(self.discriminators):
  190. y = d(y)
  191. y = F.leaky_relu(y, LRELU_SLOPE)
  192. fmap.append(y)
  193. y = self.out(y)
  194. fmap.append(y)
  195. return torch.flatten(y, 1, -1), fmap