o
    i6A                     @   s|   d Z ddlZddlmZmZmZ ddlZddlZddl	m
Z
 G dd dejjZG dd dejjZG d	d
 d
ejjZdS )z]MelGAN Modules.

This code is modified from https://github.com/kan-bayashi/ParallelWaveGAN.

    N)AnyDictList)ResidualStackc                       s   e Zd ZdZdddddg dddd	d
didi ddfdedededededee dedededeee	f dedeee	f dedef fddZ
dejdejfdd Zd!d" Zd#d$ Zd%d& Zdejdejfd'd(Z  ZS ))MelGANGeneratorzMelGAN generator module.P         i   T)   r
      r      	LeakyReLUnegative_slope皙?ReflectionPad1din_channelsout_channelskernel_sizechannelsbiasupsample_scalesstack_kernel_sizestacksnonlinear_activationnonlinear_activation_paramspad
pad_paramsuse_final_nonlinear_activationuse_weight_normc                    s  t    |t|ksJ |dt|  dksJ |d d dks&J dg }|ttj||d d fi |tjj||||dg7 }t	t|| | _
t|D ]T\}}|ttj|	d	i |
g7 }|tjj|d|  |d|d   |d ||d |d  |d |dg7 }t|D ]}|t||d|d   || ||	|
||dg7 }qqR|ttj|	d	i |
g7 }|ttj||d d fi |tjj|d|d   |||dg7 }|r|tj g7 }tjj| | _|r|   |   dS )
a  Initialize MelGANGenerator module.

        Args:
            in_channels (int): Number of input channels.
            out_channels (int): Number of output channels.
            kernel_size (int): Kernel size of initial and final conv layer.
            channels (int): Initial number of channels for conv layer.
            bias (bool): Whether to add bias parameter in convolution layers.
            upsample_scales (List[int]): List of upsampling scales.
            stack_kernel_size (int): Kernel size of dilated conv layers in residual
                stack.
            stacks (int): Number of stacks in a single residual stack.
            nonlinear_activation (str): Activation function module name.
            nonlinear_activation_params (Dict[str, Any]): Hyperparameters for activation
                function.
            pad (str): Padding function module name before dilated convolution layer.
            pad_params (Dict[str, Any]): Hyperparameters for padding function.
            use_final_nonlinear_activation (torch.nn.Module): Activation function for
                the final layer.
            use_weight_norm (bool): Whether to use weight norm.
                If set to true, it will be applied to all of the conv layers.

        r   r   r   z$Not support even number kernel size.r   )stridepaddingoutput_paddingr   )r   r   dilationr   r   r   r   r   N )super__init__npprodlengetattrtorchnnConv1dintupsample_factor	enumerateConvTranspose1dranger   Tanh
Sequentialmelganapply_weight_normreset_parameters)selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   layersiupsample_scalej	__class__r$   Q/home/ubuntu/.local/lib/python3.10/site-packages/espnet2/gan_tts/melgan/melgan.pyr&      sl   
(
zMelGANGenerator.__init__creturnc                 C   s
   |  |S )zCalculate forward propagation.

        Args:
            c (Tensor): Input tensor (B, channels, T).

        Returns:
            Tensor: Output tensor (B, 1, T ** prod(upsample_scales)).

        )r5   r8   r@   r$   r$   r?   forward   s   

zMelGANGenerator.forwardc                 C       dt jjfdd}| | dS ):Remove weight normalization module from all of the layers.mc                 S   <   zt d|  d tjj|  W d S  ty   Y d S w NzWeight norm is removed from .loggingdebugr+   r,   utilsremove_weight_norm
ValueErrorrF   r$   r$   r?   _remove_weight_norm      z?MelGANGenerator.remove_weight_norm.<locals>._remove_weight_normNr+   r,   Moduleapplyr8   rQ   r$   r$   r?   rN         z"MelGANGenerator.remove_weight_normc                 C   rD   )9Apply weight normalization module from all of the layers.rF   c                 S   D   t | tjjst | tjjr tjj|  td|  d d S d S NzWeight norm is applied to rI   	
isinstancer+   r,   r-   r1   rM   weight_normrK   rL   rP   r$   r$   r?   _apply_weight_norm      z=MelGANGenerator.apply_weight_norm.<locals>._apply_weight_normNrS   r8   r^   r$   r$   r?   r6      rW   z!MelGANGenerator.apply_weight_normc                 C   s   dd }|  | dS )Reset parameters.

        This initialization follows official implementation manner.
        https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py

        c                 S   F   t | tjjst | tjjr!| jjdd t	d|  d d S d S Ng        g{Gz?zReset parameters in rI   
r\   r+   r,   r-   r1   weightdatanormal_rK   rL   rP   r$   r$   r?   _reset_parameters      z;MelGANGenerator.reset_parameters.<locals>._reset_parametersN)rU   r8   rh   r$   r$   r?   r7      s   z MelGANGenerator.reset_parametersc                 C   s*   |  |ddd}|dddS )zPerform inference.

        Args:
            c (Tensor): Input tensor (T, in_channels).

        Returns:
            Tensor: Output tensor (T ** prod(upsample_scales), out_channels).

        r   r   )r5   	transpose	unsqueezesqueezerB   r$   r$   r?   	inference   s   
zMelGANGenerator.inference)__name__
__module____qualname____doc__r.   boolr   strr   r   r&   r+   TensorrC   rN   r6   r7   rn   __classcell__r$   r$   r=   r?   r      sd    	


nr   c                       s   e Zd ZdZddddgdddg dd	d
didi fdededee dedededee dedeee	f dedeee	f f fddZ
dejdeej fddZ  ZS )MelGANDiscriminatorzMelGAN discriminator module.r      r         T   r|   r|   r|   r   r   r   r   r   r   kernel_sizesr   max_downsample_channelsr   downsample_scalesr   r   r   r   c                    s  t    tj | _t|dksJ |d d dksJ |d d dks'J |  jtjttj|
t	
|d d fi |tjj||t	
||dttj|di |	g7  _|}|D ]4}t|| |}|  jtjtjj|||d d ||d |d |dttj|di |	g7  _|}q^t|d |}|  jtjtjj|||d |d d d |d	ttj|di |	g7  _|  jtjj|||d |d d d |d	g7  _d
S )a  Initilize MelGANDiscriminator module.

        Args:
            in_channels (int): Number of input channels.
            out_channels (int): Number of output channels.
            kernel_sizes (List[int]): List of two kernel sizes. The prod will be used
                for the first conv layer, and the first and the second kernel sizes
                will be used for the last two layers. For example if kernel_sizes =
                [5, 3], the first layer kernel size will be 5 * 3 = 15, the last two
                layers' kernel size will be 5 and 3, respectively.
            channels (int): Initial number of channels for conv layer.
            max_downsample_channels (int): Maximum number of channels for downsampling
                layers.
            bias (bool): Whether to add bias parameter in convolution layers.
            downsample_scales (List[int]): List of downsampling scales.
            nonlinear_activation (str): Activation function module name.
            nonlinear_activation_params (Dict[str, Any]): Hyperparameters for activation
                function.
            pad (str): Padding function module name before dilated convolution layer.
            pad_params (Dict[str, Any]): Hyperparameters for padding function.

        r   r   r   r   
   rx   r|   )r   r    r!   groupsr   )r!   r   Nr$   )r%   r&   r+   r,   
ModuleListr9   r)   r4   r*   r'   r(   r-   min)r8   r   r   r}   r   r~   r   r   r   r   r   r   in_chsdownsample_scaleout_chsr=   r$   r?   r&      sp   
$$
	zMelGANDiscriminator.__init__xrA   c                 C   s&   g }| j D ]}||}||g7 }q|S )zCalculate forward propagation.

        Args:
            x (Tensor): Input noise signal (B, 1, T).

        Returns:
            List[Tensor]: List of output tensors of each layer.

        )r9   r8   r   outsfr$   r$   r?   rC   /  s
   

zMelGANDiscriminator.forward)ro   rp   rq   rr   r.   r   rs   rt   r   r   r&   r+   ru   rC   rv   r$   r$   r=   r?   rw      sJ    	


"erw   c                       s   e Zd ZdZdddddddddd	dgd
ddg ddddidi dfdededededeeef dee dedede	dee dedeeef dedeeef d e	f fd!d"Z
d#ejd$eeej  fd%d&Zd'd( Zd)d* Zd+d, Z  ZS )-MelGANMultiScaleDiscriminatorz(MelGAN multi-scale discriminator module.r   r   	AvgPool1dr|   r   F)r   r    r!   count_include_padrx   ry   rz   Tr{   r   r   r   r   r   r   scalesdownsample_poolingdownsample_pooling_paramsr}   r   r~   r   r   r   r   r   r   r   c                    s~   t    tj | _t|D ]}|  jt||||||	|
||||dg7  _qttj|di || _	|r9| 
  |   dS )a  Initilize MelGANMultiScaleDiscriminator module.

        Args:
            in_channels (int): Number of input channels.
            out_channels (int): Number of output channels.
            scales (int): Number of multi-scales.
            downsample_pooling (str): Pooling module name for downsampling of the
                inputs.
            downsample_pooling_params (Dict[str, Any]): Parameters for the above
                pooling module.
            kernel_sizes (List[int]): List of two kernel sizes. The sum will be used
                for the first conv layer, and the first and the second kernel sizes
                will be used for the last two layers.
            channels (int): Initial number of channels for conv layer.
            max_downsample_channels (int): Maximum number of channels for downsampling
                layers.
            bias (bool): Whether to add bias parameter in convolution layers.
            downsample_scales (List[int]): List of downsampling scales.
            nonlinear_activation (str): Activation function module name.
            nonlinear_activation_params (Dict[str, Any]): Hyperparameters for activation
                function.
            pad (str): Padding function module name before dilated convolution layer.
            pad_params (Dict[str, Any]): Hyperparameters for padding function.
            use_weight_norm (bool): Whether to use weight norm.

        )r   r   r}   r   r~   r   r   r   r   r   r   Nr$   )r%   r&   r+   r,   r   discriminatorsr2   rw   r*   poolingr6   r7   )r8   r   r   r   r   r   r}   r   r~   r   r   r   r   r   r   r   _r=   r$   r?   r&   D  s0   
2
z&MelGANMultiScaleDiscriminator.__init__r   rA   c                 C   s,   g }| j D ]}|||g7 }| |}q|S )a  Calculate forward propagation.

        Args:
            x (Tensor): Input noise signal (B, 1, T).

        Returns:
            List[List[Tensor]]: List of list of each discriminator outputs, which
                consists of each layer output tensors.

        )r   r   r   r$   r$   r?   rC     s
   
z%MelGANMultiScaleDiscriminator.forwardc                 C   rD   )rE   rF   c                 S   rG   rH   rJ   rP   r$   r$   r?   rQ     rR   zMMelGANMultiScaleDiscriminator.remove_weight_norm.<locals>._remove_weight_normNrS   rV   r$   r$   r?   rN     rW   z0MelGANMultiScaleDiscriminator.remove_weight_normc                 C   rD   )rX   rF   c                 S   rY   rZ   r[   rP   r$   r$   r?   r^     r_   zKMelGANMultiScaleDiscriminator.apply_weight_norm.<locals>._apply_weight_normNrS   r`   r$   r$   r?   r6     rW   z/MelGANMultiScaleDiscriminator.apply_weight_normc                 C   rD   )ra   rF   c                 S   rb   rc   rd   rP   r$   r$   r?   rh     ri   zIMelGANMultiScaleDiscriminator.reset_parameters.<locals>._reset_parametersNrS   rj   r$   r$   r?   r7     s   z.MelGANMultiScaleDiscriminator.reset_parameters)ro   rp   rq   rr   r.   rt   r   r   r   rs   r&   r+   ru   rC   rN   r6   r7   rv   r$   r$   r=   r?   r   A  sp    


Qr   )rr   rK   typingr   r   r   numpyr'   r+   %espnet2.gan_tts.melgan.residual_stackr   r,   rT   r   rw   r   r$   r$   r$   r?   <module>   s    5z