discriminator.py 5.2 KB

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