a
    âñhÏ-  ã                   @   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 )
z‘Implements Conv-TasNet with building blocks of it.

Based on https://github.com/naplab/Conv-TasNet/tree/e66d82a8f956a69749ec8a4ae382217faa097c5c
é    )ÚTupleÚOptionalNc                       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): Dilation value of the convolution in the middle layer.
        no_redisual (bool): Disable residual block/output.

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.

    Reference:
        - Conv-TasNet: Surpassing Ideal Time--Frequency Magnitude Masking for Speech Separation

          Luo, Yi and Mesgarani, Nima

          https://arxiv.org/abs/1809.07454
    é   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   ç:Œ0âŽyE>©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__© ú]/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/models/conv_tasnet.pyr   !   s6    	
ÿúñÿÿýÿzConvBlock.__init__©ÚinputÚreturnc                 C   s6   |   |¡}| jd u rd }n
|  |¡}|  |¡}||fS )N)r   r   r   )r   r#   ÚfeatureÚresidualr   r    r    r!   ÚforwardI   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                       sF   e Zd ZdZeeeeeeedœ‡ fdd„Zejejdœdd„Z‡  Z	S )ÚMaskGeneratorap  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>.

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.

    References:
        - Conv-TasNet: Surpassing Ideal Time--Frequency Magnitude Masking for Speech Separation
          Luo, Yi and Mesgarani, Nima
          https://arxiv.org/abs/1809.07454
    ©Ú	input_dimÚnum_sourcesr   Ú	num_featsÚ
num_hiddenÚ
num_layersÚ
num_stacksc                    sø   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 S )Nr   r   r   r   r   é   )r   r   r   r
   r	   r   )r   r   r2   r3   r   r   r   Ú
input_normr   Ú
input_convZreceptive_fieldZ
ModuleListr   ÚrangeÚappendr   r   Úoutput_preluÚoutput_conv)r   r2   r3   r   r4   r5   r6   r7   ÚsÚlZmultir   r    r!   r   l   s>    

ÿÿùÿÿ

ÿzMaskGenerator.__init__r"   c                 C   s„   |j d }|  |¡}|  |¡}d}| jD ](}||ƒ\}}|durH|| }|| }q(|  |¡}|  |¡}t |¡}| || j	| j
d¡S )zÛGenerate separation mask.

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

        Returns:
            torch.Tensor: shape [batch, num_sources, features, frames]
        r   g        Néÿÿÿÿ)Úshaper9   r:   r   r=   r>   r   ZsigmoidÚviewr3   r2   )r   r#   Ú
batch_sizeÚfeatsÚoutputZlayerr&   Úskipr    r    r!   r'   š   s    	







zMaskGenerator.forward)
r(   r)   r*   r+   r,   r   r   r.   r'   r/   r    r    r   r!   r0   U   s   ø.r0   c                
       sf   e Zd ZdZd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 )Ú
ConvTasNetaC  Conv-TasNet: a fully-convolutional time-domain audio separation network

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

    Note:
        This implementation corresponds to the "non-causal" setting in the paper.

    Reference:
        - Conv-TasNet: Surpassing Ideal Time--Frequency Magnitude Masking for Speech Separation

          Luo, Yi and Mesgarani, Nima

          https://arxiv.org/abs/1809.07454
    r8   é   é   é   é€   é   )r3   Úenc_kernel_sizeÚenc_num_featsÚmsk_kernel_sizeÚmsk_num_featsÚmsk_num_hidden_featsÚmsk_num_layersÚmsk_num_stacksc	           	   	      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biasr1   )r   r   r3   rO   rN   Ú
enc_strider   r   r   Úencoderr0   Úmask_generatorZConvTranspose1dÚdecoder)	r   r3   rN   rO   rP   rQ   rR   rS   rT   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:
            torch.Tensor: Padded Tensor
            int: Number of paddings performed
        r8   r   )ÚdtypeÚdevice)rB   rN   rU   r   ÚzerosrY   rZ   Úcat)
r   r#   rD   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:
            torch.Tensor: 3D Tensor with shape [batch, channel==num_sources, frames]
        rK   r   z7Expected 3D tensor (batch, channel==1, frames). Found: r   r8   rA   .N)ÚndimrB   Ú
ValueErrorr^   rV   rW   Z	unsqueezerC   r3   rO   rX   )
r   r#   ÚpaddedZnum_padsrD   Znum_padded_framesrE   ZmaskedÚdecodedrF   r    r    r!   r'   %  s$    	
ÿ
ÿ
ÿzConvTasNet.forward)r8   rI   rJ   rK   rL   rJ   rM   rK   )r(   r)   r*   r+   r,   r   r   r.   r   r^   r'   r/   r    r    r   r!   rH   ²   s.           õõ/þ-rH   )
r+   Útypingr   r   r   r   ÚModuler   r0   rH   r    r    r    r!   Ú<module>   s
   J]