discriminator.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from torch.nn.utils.parametrizations import weight_norm
  5. except ImportError:
  6. from torch.nn.utils import weight_norm
  7. from typing import List, Optional, Tuple
  8. from einops import rearrange
  9. from torchaudio.transforms import Spectrogram
  10. class MultipleDiscriminator(nn.Module):
  11. def __init__(
  12. self, mpd: nn.Module, mrd: nn.Module
  13. ):
  14. super().__init__()
  15. self.mpd = mpd
  16. self.mrd = mrd
  17. def forward(self, y: torch.Tensor, y_hat: torch.Tensor):
  18. y_d_rs, y_d_gs, fmap_rs, fmap_gs = [], [], [], []
  19. 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))
  20. y_d_rs += this_y_d_rs
  21. y_d_gs += this_y_d_gs
  22. fmap_rs += this_fmap_rs
  23. fmap_gs += this_fmap_gs
  24. this_y_d_rs, this_y_d_gs, this_fmap_rs, this_fmap_gs = self.mrd(y, y_hat)
  25. y_d_rs += this_y_d_rs
  26. y_d_gs += this_y_d_gs
  27. fmap_rs += this_fmap_rs
  28. fmap_gs += this_fmap_gs
  29. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  30. class MultiResolutionDiscriminator(nn.Module):
  31. def __init__(
  32. self,
  33. fft_sizes: Tuple[int, ...] = (2048, 1024, 512),
  34. num_embeddings: Optional[int] = None,
  35. ):
  36. """
  37. Multi-Resolution Discriminator module adapted from https://github.com/descriptinc/descript-audio-codec.
  38. Additionally, it allows incorporating conditional information with a learned embeddings table.
  39. Args:
  40. fft_sizes (tuple[int]): Tuple of window lengths for FFT. Defaults to (2048, 1024, 512).
  41. num_embeddings (int, optional): Number of embeddings. None means non-conditional discriminator.
  42. Defaults to None.
  43. """
  44. super().__init__()
  45. self.discriminators = nn.ModuleList(
  46. [DiscriminatorR(window_length=w, num_embeddings=num_embeddings) for w in fft_sizes]
  47. )
  48. def forward(
  49. self, y: torch.Tensor, y_hat: torch.Tensor, bandwidth_id: torch.Tensor = None
  50. ) -> Tuple[List[torch.Tensor], List[torch.Tensor], List[List[torch.Tensor]], List[List[torch.Tensor]]]:
  51. y_d_rs = []
  52. y_d_gs = []
  53. fmap_rs = []
  54. fmap_gs = []
  55. for d in self.discriminators:
  56. y_d_r, fmap_r = d(x=y, cond_embedding_id=bandwidth_id)
  57. y_d_g, fmap_g = d(x=y_hat, cond_embedding_id=bandwidth_id)
  58. y_d_rs.append(y_d_r)
  59. fmap_rs.append(fmap_r)
  60. y_d_gs.append(y_d_g)
  61. fmap_gs.append(fmap_g)
  62. return y_d_rs, y_d_gs, fmap_rs, fmap_gs
  63. class DiscriminatorR(nn.Module):
  64. def __init__(
  65. self,
  66. window_length: int,
  67. num_embeddings: Optional[int] = None,
  68. channels: int = 32,
  69. hop_factor: float = 0.25,
  70. 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)),
  71. ):
  72. super().__init__()
  73. self.window_length = window_length
  74. self.hop_factor = hop_factor
  75. self.spec_fn = Spectrogram(
  76. n_fft=window_length, hop_length=int(window_length * hop_factor), win_length=window_length, power=None
  77. )
  78. n_fft = window_length // 2 + 1
  79. bands = [(int(b[0] * n_fft), int(b[1] * n_fft)) for b in bands]
  80. self.bands = bands
  81. convs = lambda: nn.ModuleList(
  82. [
  83. weight_norm(nn.Conv2d(2, channels, (3, 9), (1, 1), padding=(1, 4))),
  84. weight_norm(nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4))),
  85. weight_norm(nn.Conv2d(channels, channels, (3, 9), (1, 2), 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, 3), (1, 1), padding=(1, 1))),
  88. ]
  89. )
  90. self.band_convs = nn.ModuleList([convs() for _ in range(len(self.bands))])
  91. if num_embeddings is not None:
  92. self.emb = torch.nn.Embedding(num_embeddings=num_embeddings, embedding_dim=channels)
  93. torch.nn.init.zeros_(self.emb.weight)
  94. self.conv_post = weight_norm(nn.Conv2d(channels, 1, (3, 3), (1, 1), padding=(1, 1)))
  95. def spectrogram(self, x):
  96. # Remove DC offset
  97. x = x - x.mean(dim=-1, keepdims=True)
  98. # Peak normalize the volume of input audio
  99. x = 0.8 * x / (x.abs().max(dim=-1, keepdim=True)[0] + 1e-9)
  100. x = self.spec_fn(x)
  101. x = torch.view_as_real(x)
  102. x = rearrange(x, "b f t c -> b c t f")
  103. # Split into bands
  104. x_bands = [x[..., b[0]: b[1]] for b in self.bands]
  105. return x_bands
  106. def forward(self, x: torch.Tensor, cond_embedding_id: torch.Tensor = None):
  107. x_bands = self.spectrogram(x)
  108. fmap = []
  109. x = []
  110. for band, stack in zip(x_bands, self.band_convs):
  111. for i, layer in enumerate(stack):
  112. band = layer(band)
  113. band = torch.nn.functional.leaky_relu(band, 0.1)
  114. if i > 0:
  115. fmap.append(band)
  116. x.append(band)
  117. x = torch.cat(x, dim=-1)
  118. if cond_embedding_id is not None:
  119. emb = self.emb(cond_embedding_id)
  120. h = (emb.view(1, -1, 1, 1) * x).sum(dim=1, keepdims=True)
  121. else:
  122. h = 0
  123. x = self.conv_post(x)
  124. fmap.append(x)
  125. x += h
  126. return x, fmap