discriminator.py 5.2 KB

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