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|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""MS-STFT discriminator, provided here for reference."""
|
| 8 |
+
|
| 9 |
+
import typing as tp
|
| 10 |
+
|
| 11 |
+
import torchaudio
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from einops import rearrange
|
| 15 |
+
|
| 16 |
+
from .modules import NormConv2d
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
FeatureMapType = tp.List[torch.Tensor]
|
| 20 |
+
LogitsType = torch.Tensor
|
| 21 |
+
DiscriminatorOutput = tp.Tuple[tp.List[LogitsType], tp.List[FeatureMapType]]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_2d_padding(kernel_size: tp.Tuple[int, int], dilation: tp.Tuple[int, int] = (1, 1)):
|
| 25 |
+
return (((kernel_size[0] - 1) * dilation[0]) // 2, ((kernel_size[1] - 1) * dilation[1]) // 2)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DiscriminatorSTFT(nn.Module):
|
| 29 |
+
"""STFT sub-discriminator.
|
| 30 |
+
Args:
|
| 31 |
+
filters (int): Number of filters in convolutions
|
| 32 |
+
in_channels (int): Number of input channels. Default: 1
|
| 33 |
+
out_channels (int): Number of output channels. Default: 1
|
| 34 |
+
n_fft (int): Size of FFT for each scale. Default: 1024
|
| 35 |
+
hop_length (int): Length of hop between STFT windows for each scale. Default: 256
|
| 36 |
+
kernel_size (tuple of int): Inner Conv2d kernel sizes. Default: ``(3, 9)``
|
| 37 |
+
stride (tuple of int): Inner Conv2d strides. Default: ``(1, 2)``
|
| 38 |
+
dilations (list of int): Inner Conv2d dilation on the time dimension. Default: ``[1, 2, 4]``
|
| 39 |
+
win_length (int): Window size for each scale. Default: 1024
|
| 40 |
+
normalized (bool): Whether to normalize by magnitude after stft. Default: True
|
| 41 |
+
norm (str): Normalization method. Default: `'weight_norm'`
|
| 42 |
+
activation (str): Activation function. Default: `'LeakyReLU'`
|
| 43 |
+
activation_params (dict): Parameters to provide to the activation function.
|
| 44 |
+
growth (int): Growth factor for the filters. Default: 1
|
| 45 |
+
"""
|
| 46 |
+
def __init__(self, filters: int, in_channels: int = 1, out_channels: int = 1,
|
| 47 |
+
n_fft: int = 1024, hop_length: int = 256, win_length: int = 1024, max_filters: int = 1024,
|
| 48 |
+
filters_scale: int = 1, kernel_size: tp.Tuple[int, int] = (3, 9), dilations: tp.List = [1, 2, 4],
|
| 49 |
+
stride: tp.Tuple[int, int] = (1, 2), normalized: bool = True, norm: str = 'weight_norm',
|
| 50 |
+
activation: str = 'LeakyReLU', activation_params: dict = {'negative_slope': 0.2}):
|
| 51 |
+
super().__init__()
|
| 52 |
+
assert len(kernel_size) == 2
|
| 53 |
+
assert len(stride) == 2
|
| 54 |
+
self.filters = filters
|
| 55 |
+
self.in_channels = in_channels
|
| 56 |
+
self.out_channels = out_channels
|
| 57 |
+
self.n_fft = n_fft
|
| 58 |
+
self.hop_length = hop_length
|
| 59 |
+
self.win_length = win_length
|
| 60 |
+
self.normalized = normalized
|
| 61 |
+
self.activation = getattr(torch.nn, activation)(**activation_params)
|
| 62 |
+
self.spec_transform = torchaudio.transforms.Spectrogram(
|
| 63 |
+
n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length, window_fn=torch.hann_window,
|
| 64 |
+
normalized=self.normalized, center=False, pad_mode=None, power=None)
|
| 65 |
+
spec_channels = 2 * self.in_channels
|
| 66 |
+
self.convs = nn.ModuleList()
|
| 67 |
+
self.convs.append(
|
| 68 |
+
NormConv2d(spec_channels, self.filters, kernel_size=kernel_size, padding=get_2d_padding(kernel_size))
|
| 69 |
+
)
|
| 70 |
+
in_chs = min(filters_scale * self.filters, max_filters)
|
| 71 |
+
for i, dilation in enumerate(dilations):
|
| 72 |
+
out_chs = min((filters_scale ** (i + 1)) * self.filters, max_filters)
|
| 73 |
+
self.convs.append(NormConv2d(in_chs, out_chs, kernel_size=kernel_size, stride=stride,
|
| 74 |
+
dilation=(dilation, 1), padding=get_2d_padding(kernel_size, (dilation, 1)),
|
| 75 |
+
norm=norm))
|
| 76 |
+
in_chs = out_chs
|
| 77 |
+
out_chs = min((filters_scale ** (len(dilations) + 1)) * self.filters, max_filters)
|
| 78 |
+
self.convs.append(NormConv2d(in_chs, out_chs, kernel_size=(kernel_size[0], kernel_size[0]),
|
| 79 |
+
padding=get_2d_padding((kernel_size[0], kernel_size[0])),
|
| 80 |
+
norm=norm))
|
| 81 |
+
self.conv_post = NormConv2d(out_chs, self.out_channels,
|
| 82 |
+
kernel_size=(kernel_size[0], kernel_size[0]),
|
| 83 |
+
padding=get_2d_padding((kernel_size[0], kernel_size[0])),
|
| 84 |
+
norm=norm)
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor):
|
| 87 |
+
fmap = []
|
| 88 |
+
z = self.spec_transform(x) # [B, 2, Freq, Frames, 2]
|
| 89 |
+
z = torch.cat([z.real, z.imag], dim=1)
|
| 90 |
+
z = rearrange(z, 'b c w t -> b c t w')
|
| 91 |
+
for i, layer in enumerate(self.convs):
|
| 92 |
+
z = layer(z)
|
| 93 |
+
z = self.activation(z)
|
| 94 |
+
fmap.append(z)
|
| 95 |
+
z = self.conv_post(z)
|
| 96 |
+
return z, fmap
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class MultiScaleSTFTDiscriminator(nn.Module):
|
| 100 |
+
"""Multi-Scale STFT (MS-STFT) discriminator.
|
| 101 |
+
Args:
|
| 102 |
+
filters (int): Number of filters in convolutions
|
| 103 |
+
in_channels (int): Number of input channels. Default: 1
|
| 104 |
+
out_channels (int): Number of output channels. Default: 1
|
| 105 |
+
n_ffts (Sequence[int]): Size of FFT for each scale
|
| 106 |
+
hop_lengths (Sequence[int]): Length of hop between STFT windows for each scale
|
| 107 |
+
win_lengths (Sequence[int]): Window size for each scale
|
| 108 |
+
**kwargs: additional args for STFTDiscriminator
|
| 109 |
+
"""
|
| 110 |
+
def __init__(self, filters: int, in_channels: int = 1, out_channels: int = 1,
|
| 111 |
+
n_ffts: tp.List[int] = [1024, 2048, 512], hop_lengths: tp.List[int] = [256, 512, 128],
|
| 112 |
+
win_lengths: tp.List[int] = [1024, 2048, 512], **kwargs):
|
| 113 |
+
super().__init__()
|
| 114 |
+
assert len(n_ffts) == len(hop_lengths) == len(win_lengths)
|
| 115 |
+
self.discriminators = nn.ModuleList([
|
| 116 |
+
DiscriminatorSTFT(filters, in_channels=in_channels, out_channels=out_channels,
|
| 117 |
+
n_fft=n_ffts[i], win_length=win_lengths[i], hop_length=hop_lengths[i], **kwargs)
|
| 118 |
+
for i in range(len(n_ffts))
|
| 119 |
+
])
|
| 120 |
+
self.num_discriminators = len(self.discriminators)
|
| 121 |
+
|
| 122 |
+
def forward(self, x: torch.Tensor) -> DiscriminatorOutput:
|
| 123 |
+
logits = []
|
| 124 |
+
fmaps = []
|
| 125 |
+
for disc in self.discriminators:
|
| 126 |
+
logit, fmap = disc(x)
|
| 127 |
+
logits.append(logit)
|
| 128 |
+
fmaps.append(fmap)
|
| 129 |
+
return logits, fmaps
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test():
|
| 133 |
+
disc = MultiScaleSTFTDiscriminator(filters=32)
|
| 134 |
+
y = torch.randn(1, 1, 24000)
|
| 135 |
+
y_hat = torch.randn(1, 1, 24000)
|
| 136 |
+
|
| 137 |
+
y_disc_r, fmap_r = disc(y)
|
| 138 |
+
y_disc_gen, fmap_gen = disc(y_hat)
|
| 139 |
+
assert len(y_disc_r) == len(y_disc_gen) == len(fmap_r) == len(fmap_gen) == disc.num_discriminators
|
| 140 |
+
|
| 141 |
+
assert all([len(fm) == 5 for fm in fmap_r + fmap_gen])
|
| 142 |
+
assert all([list(f.shape)[:2] == [1, 32] for fm in fmap_r + fmap_gen for f in fm])
|
| 143 |
+
assert all([len(logits.shape) == 4 for logits in y_disc_r + y_disc_gen])
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == '__main__':
|
| 147 |
+
test(work to DRC and Spotify)
|