Path: blob/main/modules/parallel_wavegan/models/melgan.py
694 views
# -*- coding: utf-8 -*-12# Copyright 2020 Tomoki Hayashi3# MIT License (https://opensource.org/licenses/MIT)45"""MelGAN Modules."""67import logging89import numpy as np10import torch1112from modules.parallel_wavegan.layers import CausalConv1d13from modules.parallel_wavegan.layers import CausalConvTranspose1d14from modules.parallel_wavegan.layers import ResidualStack151617class MelGANGenerator(torch.nn.Module):18"""MelGAN generator module."""1920def __init__(self,21in_channels=80,22out_channels=1,23kernel_size=7,24channels=512,25bias=True,26upsample_scales=[8, 8, 2, 2],27stack_kernel_size=3,28stacks=3,29nonlinear_activation="LeakyReLU",30nonlinear_activation_params={"negative_slope": 0.2},31pad="ReflectionPad1d",32pad_params={},33use_final_nonlinear_activation=True,34use_weight_norm=True,35use_causal_conv=False,36):37"""Initialize MelGANGenerator module.3839Args:40in_channels (int): Number of input channels.41out_channels (int): Number of output channels.42kernel_size (int): Kernel size of initial and final conv layer.43channels (int): Initial number of channels for conv layer.44bias (bool): Whether to add bias parameter in convolution layers.45upsample_scales (list): List of upsampling scales.46stack_kernel_size (int): Kernel size of dilated conv layers in residual stack.47stacks (int): Number of stacks in a single residual stack.48nonlinear_activation (str): Activation function module name.49nonlinear_activation_params (dict): Hyperparameters for activation function.50pad (str): Padding function module name before dilated convolution layer.51pad_params (dict): Hyperparameters for padding function.52use_final_nonlinear_activation (torch.nn.Module): Activation function for the final layer.53use_weight_norm (bool): Whether to use weight norm.54If set to true, it will be applied to all of the conv layers.55use_causal_conv (bool): Whether to use causal convolution.5657"""58super(MelGANGenerator, self).__init__()5960# check hyper parameters is valid61assert channels >= np.prod(upsample_scales)62assert channels % (2 ** len(upsample_scales)) == 063if not use_causal_conv:64assert (kernel_size - 1) % 2 == 0, "Not support even number kernel size."6566# add initial layer67layers = []68if not use_causal_conv:69layers += [70getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),71torch.nn.Conv1d(in_channels, channels, kernel_size, bias=bias),72]73else:74layers += [75CausalConv1d(in_channels, channels, kernel_size,76bias=bias, pad=pad, pad_params=pad_params),77]7879for i, upsample_scale in enumerate(upsample_scales):80# add upsampling layer81layers += [getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params)]82if not use_causal_conv:83layers += [84torch.nn.ConvTranspose1d(85channels // (2 ** i),86channels // (2 ** (i + 1)),87upsample_scale * 2,88stride=upsample_scale,89padding=upsample_scale // 2 + upsample_scale % 2,90output_padding=upsample_scale % 2,91bias=bias,92)93]94else:95layers += [96CausalConvTranspose1d(97channels // (2 ** i),98channels // (2 ** (i + 1)),99upsample_scale * 2,100stride=upsample_scale,101bias=bias,102)103]104105# add residual stack106for j in range(stacks):107layers += [108ResidualStack(109kernel_size=stack_kernel_size,110channels=channels // (2 ** (i + 1)),111dilation=stack_kernel_size ** j,112bias=bias,113nonlinear_activation=nonlinear_activation,114nonlinear_activation_params=nonlinear_activation_params,115pad=pad,116pad_params=pad_params,117use_causal_conv=use_causal_conv,118)119]120121# add final layer122layers += [getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params)]123if not use_causal_conv:124layers += [125getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),126torch.nn.Conv1d(channels // (2 ** (i + 1)), out_channels, kernel_size, bias=bias),127]128else:129layers += [130CausalConv1d(channels // (2 ** (i + 1)), out_channels, kernel_size,131bias=bias, pad=pad, pad_params=pad_params),132]133if use_final_nonlinear_activation:134layers += [torch.nn.Tanh()]135136# define the model as a single function137self.melgan = torch.nn.Sequential(*layers)138139# apply weight norm140if use_weight_norm:141self.apply_weight_norm()142143# reset parameters144self.reset_parameters()145146def forward(self, c):147"""Calculate forward propagation.148149Args:150c (Tensor): Input tensor (B, channels, T).151152Returns:153Tensor: Output tensor (B, 1, T ** prod(upsample_scales)).154155"""156return self.melgan(c)157158def remove_weight_norm(self):159"""Remove weight normalization module from all of the layers."""160def _remove_weight_norm(m):161try:162logging.debug(f"Weight norm is removed from {m}.")163torch.nn.utils.remove_weight_norm(m)164except ValueError: # this module didn't have weight norm165return166167self.apply(_remove_weight_norm)168169def apply_weight_norm(self):170"""Apply weight normalization module from all of the layers."""171def _apply_weight_norm(m):172if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):173torch.nn.utils.weight_norm(m)174logging.debug(f"Weight norm is applied to {m}.")175176self.apply(_apply_weight_norm)177178def reset_parameters(self):179"""Reset parameters.180181This initialization follows official implementation manner.182https://github.com/descriptinc/melgan-neurips/blob/master/spec2wav/modules.py183184"""185def _reset_parameters(m):186if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):187m.weight.data.normal_(0.0, 0.02)188logging.debug(f"Reset parameters in {m}.")189190self.apply(_reset_parameters)191192193class MelGANDiscriminator(torch.nn.Module):194"""MelGAN discriminator module."""195196def __init__(self,197in_channels=1,198out_channels=1,199kernel_sizes=[5, 3],200channels=16,201max_downsample_channels=1024,202bias=True,203downsample_scales=[4, 4, 4, 4],204nonlinear_activation="LeakyReLU",205nonlinear_activation_params={"negative_slope": 0.2},206pad="ReflectionPad1d",207pad_params={},208):209"""Initilize MelGAN discriminator module.210211Args:212in_channels (int): Number of input channels.213out_channels (int): Number of output channels.214kernel_sizes (list): List of two kernel sizes. The prod will be used for the first conv layer,215and the first and the second kernel sizes will be used for the last two layers.216For example if kernel_sizes = [5, 3], the first layer kernel size will be 5 * 3 = 15,217the last two layers' kernel size will be 5 and 3, respectively.218channels (int): Initial number of channels for conv layer.219max_downsample_channels (int): Maximum number of channels for downsampling layers.220bias (bool): Whether to add bias parameter in convolution layers.221downsample_scales (list): List of downsampling scales.222nonlinear_activation (str): Activation function module name.223nonlinear_activation_params (dict): Hyperparameters for activation function.224pad (str): Padding function module name before dilated convolution layer.225pad_params (dict): Hyperparameters for padding function.226227"""228super(MelGANDiscriminator, self).__init__()229self.layers = torch.nn.ModuleList()230231# check kernel size is valid232assert len(kernel_sizes) == 2233assert kernel_sizes[0] % 2 == 1234assert kernel_sizes[1] % 2 == 1235236# add first layer237self.layers += [238torch.nn.Sequential(239getattr(torch.nn, pad)((np.prod(kernel_sizes) - 1) // 2, **pad_params),240torch.nn.Conv1d(in_channels, channels, np.prod(kernel_sizes), bias=bias),241getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),242)243]244245# add downsample layers246in_chs = channels247for downsample_scale in downsample_scales:248out_chs = min(in_chs * downsample_scale, max_downsample_channels)249self.layers += [250torch.nn.Sequential(251torch.nn.Conv1d(252in_chs, out_chs,253kernel_size=downsample_scale * 10 + 1,254stride=downsample_scale,255padding=downsample_scale * 5,256groups=in_chs // 4,257bias=bias,258),259getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),260)261]262in_chs = out_chs263264# add final layers265out_chs = min(in_chs * 2, max_downsample_channels)266self.layers += [267torch.nn.Sequential(268torch.nn.Conv1d(269in_chs, out_chs, kernel_sizes[0],270padding=(kernel_sizes[0] - 1) // 2,271bias=bias,272),273getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),274)275]276self.layers += [277torch.nn.Conv1d(278out_chs, out_channels, kernel_sizes[1],279padding=(kernel_sizes[1] - 1) // 2,280bias=bias,281),282]283284def forward(self, x):285"""Calculate forward propagation.286287Args:288x (Tensor): Input noise signal (B, 1, T).289290Returns:291List: List of output tensors of each layer.292293"""294outs = []295for f in self.layers:296x = f(x)297outs += [x]298299return outs300301302class MelGANMultiScaleDiscriminator(torch.nn.Module):303"""MelGAN multi-scale discriminator module."""304305def __init__(self,306in_channels=1,307out_channels=1,308scales=3,309downsample_pooling="AvgPool1d",310# follow the official implementation setting311downsample_pooling_params={312"kernel_size": 4,313"stride": 2,314"padding": 1,315"count_include_pad": False,316},317kernel_sizes=[5, 3],318channels=16,319max_downsample_channels=1024,320bias=True,321downsample_scales=[4, 4, 4, 4],322nonlinear_activation="LeakyReLU",323nonlinear_activation_params={"negative_slope": 0.2},324pad="ReflectionPad1d",325pad_params={},326use_weight_norm=True,327):328"""Initilize MelGAN multi-scale discriminator module.329330Args:331in_channels (int): Number of input channels.332out_channels (int): Number of output channels.333downsample_pooling (str): Pooling module name for downsampling of the inputs.334downsample_pooling_params (dict): Parameters for the above pooling module.335kernel_sizes (list): List of two kernel sizes. The sum will be used for the first conv layer,336and the first and the second kernel sizes will be used for the last two layers.337channels (int): Initial number of channels for conv layer.338max_downsample_channels (int): Maximum number of channels for downsampling layers.339bias (bool): Whether to add bias parameter in convolution layers.340downsample_scales (list): List of downsampling scales.341nonlinear_activation (str): Activation function module name.342nonlinear_activation_params (dict): Hyperparameters for activation function.343pad (str): Padding function module name before dilated convolution layer.344pad_params (dict): Hyperparameters for padding function.345use_causal_conv (bool): Whether to use causal convolution.346347"""348super(MelGANMultiScaleDiscriminator, self).__init__()349self.discriminators = torch.nn.ModuleList()350351# add discriminators352for _ in range(scales):353self.discriminators += [354MelGANDiscriminator(355in_channels=in_channels,356out_channels=out_channels,357kernel_sizes=kernel_sizes,358channels=channels,359max_downsample_channels=max_downsample_channels,360bias=bias,361downsample_scales=downsample_scales,362nonlinear_activation=nonlinear_activation,363nonlinear_activation_params=nonlinear_activation_params,364pad=pad,365pad_params=pad_params,366)367]368self.pooling = getattr(torch.nn, downsample_pooling)(**downsample_pooling_params)369370# apply weight norm371if use_weight_norm:372self.apply_weight_norm()373374# reset parameters375self.reset_parameters()376377def forward(self, x):378"""Calculate forward propagation.379380Args:381x (Tensor): Input noise signal (B, 1, T).382383Returns:384List: List of list of each discriminator outputs, which consists of each layer output tensors.385386"""387outs = []388for f in self.discriminators:389outs += [f(x)]390x = self.pooling(x)391392return outs393394def remove_weight_norm(self):395"""Remove weight normalization module from all of the layers."""396def _remove_weight_norm(m):397try:398logging.debug(f"Weight norm is removed from {m}.")399torch.nn.utils.remove_weight_norm(m)400except ValueError: # this module didn't have weight norm401return402403self.apply(_remove_weight_norm)404405def apply_weight_norm(self):406"""Apply weight normalization module from all of the layers."""407def _apply_weight_norm(m):408if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):409torch.nn.utils.weight_norm(m)410logging.debug(f"Weight norm is applied to {m}.")411412self.apply(_apply_weight_norm)413414def reset_parameters(self):415"""Reset parameters.416417This initialization follows official implementation manner.418https://github.com/descriptinc/melgan-neurips/blob/master/spec2wav/modules.py419420"""421def _reset_parameters(m):422if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):423m.weight.data.normal_(0.0, 0.02)424logging.debug(f"Reset parameters in {m}.")425426self.apply(_reset_parameters)427428429