U
    %d-                     @   s\   d Z ddlmZmZ ddl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 )
zImplements Conv-TasNet with building blocks of it.

Based on https://github.com/naplab/Conv-TasNet/tree/e66d82a8f956a69749ec8a4ae382217faa097c5c
    )OptionalTupleNc                       sT   e Zd ZdZd
eeeeeed fddZeje	e
ej ejf ddd	Z  ZS )	ConvBlocka[  1D Convolutional block.

    Args:
        io_channels (int): The number of input/output channels, <B, Sc>
        hidden_channels (int): The number of channels in the internal layers, <H>.
        kernel_size (int): The convolution kernel size of the middle layer, <P>.
        padding (int): Padding value of the convolution in the middle layer.
        dilation (int, optional): Dilation value of the convolution in the middle layer.
        no_redisual (bool, optional): Disable residual block/output.

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.
       F)io_channelshidden_channelskernel_sizepaddingdilationno_residualc                    s   t    tjtjj||ddtj tjjd|ddtjj||||||dtj tjjd|dd| _|rtd ntjj||dd| _	tjj||dd| _
d S )Nr   in_channelsout_channelsr   :0yE>Z
num_groupsnum_channelsZeps)r   r   r   r	   r
   groups)super__init__torchnnZ
SequentialConv1dPReLU	GroupNormconv_layersres_outskip_out)selfr   r   r   r	   r
   r   	__class__ A/tmp/pip-unpacked-wheel-lbdmvq91/torchaudio/models/conv_tasnet.pyr      s*    	
zConvBlock.__init__inputreturnc                 C   s6   |  |}| jd krd }n
| |}| |}||fS )N)r   r   r   )r   r#   Zfeatureresidualr   r    r    r!   forward<   s    



zConvBlock.forward)r   F)__name__
__module____qualname____doc__intboolr   r   Tensorr   r   r&   __classcell__r    r    r   r!   r      s     "r   c                	       sH   e Zd ZdZeeeeeeeed fddZejejdddZ	  Z
S )MaskGeneratora  TCN (Temporal Convolution Network) Separation Module

    Generates masks for separation.

    Args:
        input_dim (int): Input feature dimension, <N>.
        num_sources (int): The number of sources to separate.
        kernel_size (int): The convolution kernel size of conv blocks, <P>.
        num_featrs (int): Input/output feature dimenstion of conv blocks, <B, Sc>.
        num_hidden (int): Intermediate feature dimention of conv blocks, <H>
        num_layers (int): The number of conv blocks in one stack, <X>.
        num_stacks (int): The number of conv block stacks, <R>.
        msk_activate (str): The activation function of the mask output.

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.
    	input_dimnum_sourcesr   	num_feats
num_hidden
num_layers
num_stacksmsk_activatec	                    s6  t    || _|| _tjjd|dd| _tjj||dd| _	d| _
tjg | _t|D ]t}	t|D ]f}
d|
 }| jt||||||
|d ko|	|d kd |  j
|	dkr|
dkr|n
|d | 7  _
qfqZtj | _tjj||| dd| _|dkrtj | _n&|d	kr$tj | _ntd
| d S )Nr   r   r   r   r      )r   r   r   r
   r	   r   sigmoidZreluzUnsupported activation )r   r   r1   r2   r   r   r   
input_normr   
input_convZreceptive_fieldZ
ModuleListr   rangeappendr   r   output_preluoutput_convZSigmoidmask_activateZReLU
ValueError)r   r1   r2   r   r3   r4   r5   r6   r7   slZmultir   r    r!   r   Y   s@    
.

zMaskGenerator.__init__r"   c                 C   s   |j d }| |}| |}d}| jD ](}||\}}|dk	rH|| }|| }q(| |}| |}| |}||| j| j	dS )zGenerate separation mask.

        Args:
            input (torch.Tensor): 3D Tensor with shape [batch, features, frames]

        Returns:
            Tensor: shape [batch, num_sources, features, frames]
        r   g        N)
shaper:   r;   r   r>   r?   r@   viewr2   r1   )r   r#   
batch_sizefeatsoutputZlayerr%   skipr    r    r!   r&      s    	







zMaskGenerator.forward)r'   r(   r)   r*   r+   strr   r   r-   r&   r.   r    r    r   r!   r/   F   s   1r/   c                       sh   e Zd ZdZdeeeeeeeeed		 fd
dZeje	ejef dddZ
ejejdddZ  ZS )
ConvTasNetu  Conv-TasNet: a fully-convolutional time-domain audio separation network
    *Conv-TasNet: Surpassing Ideal Time–Frequency Magnitude Masking for Speech Separation*
    [:footcite:`Luo_2019`].

    Args:
        num_sources (int, optional): The number of sources to split.
        enc_kernel_size (int, optional): The convolution kernel size of the encoder/decoder, <L>.
        enc_num_feats (int, optional): The feature dimensions passed to mask generator, <N>.
        msk_kernel_size (int, optional): The convolution kernel size of the mask generator, <P>.
        msk_num_feats (int, optional): The input/output feature dimension of conv block in the mask generator, <B, Sc>.
        msk_num_hidden_feats (int, optional): The internal feature dimension of conv block of the mask generator, <H>.
        msk_num_layers (int, optional): The number of layers in one conv block of the mask generator, <X>.
        msk_num_stacks (int, optional): The numbr of conv blocks of the mask generator, <R>.
        msk_activate (str, optional): The activation function of the mask output (Default: ``sigmoid``).

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.
    r8                  r9   )	r2   enc_kernel_sizeenc_num_featsmsk_kernel_sizemsk_num_featsmsk_num_hidden_featsmsk_num_layersmsk_num_stacksr7   c
           
   
      s   t    || _|| _|| _|d | _tjjd||| j| jdd| _	t
||||||||	d| _tjj|d|| j| jdd| _d S )Nr8   r   F)r   r   r   Zstrider	   Zbiasr0   )r   r   r2   rS   rR   
enc_strider   r   r   encoderr/   mask_generatorZConvTranspose1ddecoder)
r   r2   rR   rS   rT   rU   rV   rW   rX   r7   r   r    r!   r      s>    


zConvTasNet.__init__r"   c           
      C   s|   |j \}}}| jd }|| | j }|||| j   }|dkrF|dfS | j| }tj||||j|jd}	t||	gd|fS )a  Pad input Tensor so that the end of the input tensor corresponds with

        1. (if kernel size is odd) the center of the last convolution kernel
        or 2. (if kernel size is even) the end of the first half of the last convolution kernel

        Assumption:
            The resulting Tensor will be padded with the size of stride (== kernel_width // 2)
            on the both ends in Conv1D

        |<--- k_1 --->|
        |      |            |<-- k_n-1 -->|
        |      |                  |  |<--- k_n --->|
        |      |                  |         |      |
        |      |                  |         |      |
        |      v                  v         v      |
        |<---->|<--- input signal --->|<--->|<---->|
         stride                         PAD  stride

        Args:
            input (torch.Tensor): 3D Tensor with shape (batch_size, channels==1, frames)

        Returns:
            Tensor: Padded Tensor
            int: Number of paddings performed
        r8   r   )dtypedevice)rE   rR   rY   r   zerosr]   r^   cat)
r   r#   rG   r   Z
num_framesZis_oddZnum_stridesZnum_remainingsZnum_paddingspadr    r    r!   _align_num_frames_with_strides   s    

z)ConvTasNet._align_num_frames_with_stridesc           
      C   s   |j dks|jd dkr(td|j | |\}}|jd |jd  }}| |}| ||d }||| j | j	d}| 
|}||| j|}	|dkr|	dd| f }	|	S )	a  Perform source separation. Generate audio source waveforms.

        Args:
            input (torch.Tensor): 3D Tensor with shape [batch, channel==1, frames]

        Returns:
            Tensor: 3D Tensor with shape [batch, channel==num_sources, frames]
        rO   r   z7Expected 3D tensor (batch, channel==1, frames). Found: r   r8   rD   .N)ndimrE   rA   rb   rZ   r[   Z	unsqueezerF   r2   rS   r\   )
r   r#   ZpaddedZnum_padsrG   Znum_padded_framesrH   ZmaskeddecodedrI   r    r    r!   r&     s    		

zConvTasNet.forward)	r8   rM   rN   rO   rP   rN   rQ   rO   r9   )r'   r(   r)   r*   r+   rK   r   r   r-   r   rb   r&   r.   r    r    r   r!   rL      s.            0+rL   )
r*   typingr   r   r   r   Moduler   r/   rL   r    r    r    r!   <module>   s
   ;\