o
    
jE                     @   s   d dl Z d dlmZ d dlZd dlmZ d dlm  mZ d dl	m
Z
mZmZ d dlmZ dedeeef fddZG d	d
 d
ejZG dd dejjZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZdS )    N)Tuple)	Conv1dGLUDepthWiseConv1dPointwiseConv1d)GLUActivationkernel_sizereturnc                 C   s   | d }||| d d  fS )N       )r   padr   r   Z/home/kuhnn/.local/lib/python3.10/site-packages/TTS/tts/layers/delightful_tts/conformer.pycalc_same_padding   s   r   c                       sb   e Zd Zdededededededef fdd	Zd
ejdejdejdejdejf
ddZ  Z	S )	Conformerdimn_layersn_headsspeaker_embedding_dim	p_dropoutkernel_size_conv_modlrelu_slopec              
      sF   t       t fddt|D | _dS )aI  
        A Transformer variant that integrates both CNNs and Transformers components.
        Conformer proposes a novel combination of self-attention and convolution, in which self-attention
        learns the global interaction while the convolutions efficiently capture the local correlations.

        Args:
            dim (int): Number of the dimensions for the model.
            n_layers (int): Number of model layers.
            n_heads (int): The number of attention heads.
            speaker_embedding_dim (int): Number of speaker embedding dimensions.
            p_dropout (float): Probabilty of dropout.
            kernel_size_conv_mod (int): Size of kernels for convolution modules.

        Inputs: inputs, mask
            - **inputs** (batch, time, dim): Tensor containing input vector
            - **encoding** (batch, time, dim): Positional embedding tensor
            - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
        Returns:
            - **outputs** (batch, time, dim): Tensor produced by Conformer Encoder.
        c                    s$   g | ]}t  d qS ))r   dropoutr   r   )ConformerBlock).0_d_kd_vr   r   r   r   r   r   r   r   
<listcomp>4   s    z&Conformer.__init__.<locals>.<listcomp>N)super__init__nn
ModuleListrangelayer_stack)selfr   r   r   r   r   r   r   	__class__r   r   r       s   

zConformer.__init__xmaskspeaker_embeddingencodingr   c                 C   s@   | |jd dd|jd f}| jD ]}||||||d}q|S )z
        Shapes:
            - x: :math:`[B, T_src, C]`
            - mask: :math: `[B]`
            - speaker_embedding: :math: `[B, C]`
            - encoding: :math: `[B, T_max2, C]`
        r   r
   )r)   slf_attn_maskr*   r+   )viewshaper$   )r%   r(   r)   r*   r+   	attn_mask	enc_layerr   r   r   forwardC   s   
zConformer.forward
__name__
__module____qualname__intfloatr    torchTensorr1   __classcell__r   r   r&   r   r      s6    0r   c                       sp   e Zd Z	ddededededededed	ef fd
dZdejdejdejdejdejdejfddZ  Z	S )r   333333?d_modeln_headr   r   r   r   r   r   c	           	         s   t    t|trt|||d |d| _t||d|d| _t||||d| _	t
|| _t|||d| _t||||d| _dS )a  
        A Conformer block is composed of four modules stacked together,
        A feed-forward module, a self-attention module, a convolution module,
        and a second feed-forward module in the end. The block starts with two Feed forward
        modules sandwiching the Multi-Headed Self-Attention module and the Conv module.

        Args:
            d_model (int): The dimension of model
            n_head (int): The number of attention heads.
            kernel_size_conv_mod (int): Size of kernels for convolution modules.
            speaker_embedding_dim (int): Number of speaker embedding dimensions.
            emotion_embedding_dim (int): Number of emotion embedding dimensions.
            dropout (float): Probabilty of dropout.

        Inputs: inputs, mask
            - **inputs** (batch, time, dim): Tensor containing input vector
            - **encoding** (batch, time, dim): Positional embedding tensor
            - **slf_attn_mask** (batch, 1, 1, time1): Tensor containing indices to be masked in self attention module
            - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
        Returns:
            - **outputs** (batch, time, dim): Tensor produced by the Conformer Block.
        r	   )r<   r   paddingembedding_dim   )r<   r   r   r   )r   r   r   )r<   	num_heads	dropout_pN)r   r    
isinstancer6   r   conditioningFeedForwardffConformerConvModuleconformer_conv_1r!   	LayerNormln!ConformerMultiHeadedSelfAttentionslf_attnconformer_conv_2)	r%   r<   r=   r   r   r   r   r   r   r&   r   r   r    _   s"   
!
zConformerBlock.__init__r(   r*   r)   r,   r+   r   c                 C   s   |dur| j ||d}| || }| || }|}| |}| j|||||d\}}|| }||dd}| || }|S )a*  
        Shapes:
            - x: :math:`[B, T_src, C]`
            - mask: :math: `[B]`
            - slf_attn_mask: :math: `[B, 1, 1, T_src]`
            - speaker_embedding: :math: `[B, C]`
            - emotion_embedding: :math: `[B, C]`
            - encoding: :math: `[B, T_max2, C]`
        N)
embeddings)querykeyvaluer)   r+   r   )rD   rF   rH   rJ   rL   masked_fill	unsqueezerM   )r%   r(   r*   r)   r,   r+   resr   r   r   r   r1      s   
zConformerBlock.forward)r;   r2   r   r   r&   r   r   ^   s@    
	4r   c                       sL   e Zd Z	ddededededef
 fddZd	ejd
ejfddZ  Z	S )rE      r<   r   r   r   expansion_factorc                    sd   t    t|| _t|| _tj||| ||d d| _t	|| _
tj|| |dd| _dS )aw  
        Feed Forward module for conformer block.

        Args:
            d_model (int): The dimension of model.
            kernel_size (int): Size of the kernels for conv layers.
            dropout (float): probability of dropout.
            expansion_factor (int): The factor by which to project the number of channels.
            lrelu_slope (int): the negative slope factor for the leaky relu activation.

        Inputs: inputs
            - **inputs** (batch, time, dim): Tensor containing input vector
        Returns:
            - **outputs** (batch, time, dim): Tensor produced by the feed forward module.
        r	   r   r>   r
   )r   N)r   r    r!   Dropoutr   rI   rJ   Conv1dconv_1	LeakyReLUactconv_2)r%   r<   r   r   r   rW   r&   r   r   r       s   
zFeedForward.__init__r(   r   c                 C   sp   |  |}|d}| |}|d}| |}| |}|d}| |}|d}| |}d| }|S );
        Shapes:
            x: :math: `[B, T, C]`
        )r   r	   r
         ?)rJ   permuter[   r]   r   r^   r%   r(   r   r   r   r1      s   









zFeedForward.forward)rV   r2   r   r   r&   r   rE      s    #rE   c                       sR   e Zd Z				ddedededed	ef
 fd
dZdejdejfddZ  Z	S )rG   r	      皙?r;   r<   rW   r   r   r   c                    s   t    || }t|| _t||d | _t|d| _t	|||t
|d d| _td|| _t|| _t||| _t|| _dS )a  
        Convolution module for conformer. Starts with a gating machanism.
        a pointwise convolution and a gated linear unit (GLU). This is followed
        by a single 1-D depthwise convolution layer. Batchnorm is deployed just after the convolution
        to help with training. it also contains an expansion factor to project the number of channels.

        Args:
            d_model (int): The dimension of model.
            expansion_factor (int): The factor by which to project the number of channels.
            kernel_size (int): Size of kernels for convolution modules.
            dropout (float): Probabilty of dropout.
            lrelu_slope (float): The slope coefficient for leaky relu activation.

        Inputs: inputs
            - **inputs** (batch, time, dim): Tensor containing input vector
        Returns:
            - **outputs** (batch, time, dim): Tensor produced by the conv module.

        r	   )sloper   rX   r
   N)r   r    r!   rI   ln_1r   r[   r   conv_actr   r   	depthwise	GroupNormln_2r\   
activationr^   rY   r   )r%   r<   rW   r   r   r   	inner_dimr&   r   r   r       s   

zConformerConvModule.__init__r(   r   c                 C   sp   |  |}|ddd}| |}| |}| |}| |}| |}| |}|ddd}| |}|S )r_   r   r	   r
   )	rf   ra   r[   rg   rh   rj   rk   r^   r   rb   r   r   r   r1     s   







zConformerConvModule.forward)r	   rc   rd   r;   r2   r   r   r&   r   rG      s"    +rG   c                       sf   e Zd ZdZdededef fddZdejdejd	ejd
ejdejde	ejejf fddZ
  ZS )rK   a  
    Conformer employ multi-headed self-attention (MHSA) while integrating an important technique from Transformer-XL,
    the relative sinusoidal positional encoding scheme. The relative positional encoding allows the self-attention
    module to generalize better on different input length and the resulting encoder is more robust to the variance of
    the utterance length. Conformer use prenorm residual units with dropout which helps training
    and regularizing deeper models.
    Args:
        d_model (int): The dimension of model
        num_heads (int): The number of attention heads.
        dropout_p (float): probability of dropout
    Inputs: inputs, mask
        - **inputs** (batch, time, dim): Tensor containing input vector
        - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
    Returns:
        - **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module.
    r<   rA   rB   c                    s*   t    t||d| _tj|d| _d S )N)r<   rA   )p)r   r    RelativeMultiHeadAttention	attentionr!   rY   r   )r%   r<   rA   rB   r&   r   r   r    9  s   
z*ConformerMultiHeadedSelfAttention.__init__rO   rP   rQ   r)   r+   r   c                 C   s`   |  \}}}|d d d |jd f }||dd}| j|||||d\}	}
| |	}	|	|
fS )Nr
   )pos_embeddingr)   )sizer.   repeatro   r   )r%   rO   rP   rQ   r)   r+   
batch_size
seq_lengthr   outputsattnr   r   r   r1   >  s   
z)ConformerMultiHeadedSelfAttention.forward)r3   r4   r5   __doc__r6   r7   r    r8   r9   r   r1   r:   r   r   r&   r   rK   '  s     rK   c                       s~   e Zd ZdZ		ddedef fddZdejd	ejd
ejdejdejdeejejf fddZ	dejdejfddZ
  ZS )rn   a3  
    Multi-head attention with relative positional encoding.
    This concept was proposed in the "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
    Args:
        d_model (int): The dimension of model
        num_heads (int): The number of attention heads.
    Inputs: query, key, value, pos_embedding, mask
        - **query** (batch, time, dim): Tensor containing query vector
        - **key** (batch, time, dim): Tensor containing key vector
        - **value** (batch, time, dim): Tensor containing value vector
        - **pos_embedding** (batch, time, dim): Positional embedding tensor
        - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
    Returns:
        - **outputs**: Tensor produces by relative multi head attention module.
          r<   rA   c                    s   t    || dksJ d|| _t|| | _|| _t|| _t	
||| _t	j
||dd| _t	j
||dd| _t	j
||dd| _t	t| j| j| _t	t| j| j| _tj	j| j tj	j| j t	
||| _d S )Nr   z#d_model % num_heads should be zero.F)bias)r   r    r<   r6   d_headrA   mathsqrtsqrt_dimr!   Linear
query_projkey_proj
value_projpos_proj	Parameterr8   r9   u_biasv_biasinitxavier_uniform_out_proj)r%   r<   rA   r&   r   r   r    _  s   
z#RelativeMultiHeadAttention.__init__rO   rP   rQ   rp   r)   r   c                 C   sP  |j d }| ||d| j| j}| ||d| j| jdddd}| ||d| j| jdddd}| ||d| j| j}| j	
|}| j
|}|| dd}	|	|dd }
|| dd}||dddd }| |}|
| }|d| j  }||d t|d}|| dd}| |d| j}| ||fS )Nr   rR   r	   r
   r@   g      ?g    e)r.   r   r-   rA   r{   r   ra   r   r   r   	expand_asr   	transpose_relative_shiftr~   masked_fill_Fsoftmax
contiguousr<   r   )r%   rO   rP   rQ   rp   r)   rs   r   r   acontent_scoreb	pos_scorescorerv   contextr   r   r   r1   v  s&   
&&
z"RelativeMultiHeadAttention.forwardr   c                 C   sr   |  \}}}}tj|||df|jd}tj||gdd}||||d |}|d d d d dd f |}|S )Nr
   )devicerR   r   )rq   r8   zerosr   catr-   view_as)r%   r   rs   rA   seq_length1seq_length2r   padded_pos_scorer   r   r   r     s    z*RelativeMultiHeadAttention._relative_shift)rx   ry   )r3   r4   r5   rw   r6   r    r8   r9   r   r1   r   r:   r   r   r&   r   rn   N  s.    
!rn   c                       sN   e Zd ZdZdedededef fddZdejd	ejd
ejfddZ  Z	S )MultiHeadAttentionz
    input:
        query --- [N, T_q, query_dim]
        key --- [N, T_k, key_dim]
    output:
        out --- [N, T_q, num_units]
    	query_dimkey_dim	num_unitsrA   c                    sV   t    || _|| _|| _tj||dd| _tj||dd| _tj||dd| _	d S )NF)in_featuresout_featuresrz   )
r   r    r   rA   r   r!   r   W_queryW_keyW_value)r%   r   r   r   rA   r&   r   r   r      s   
zMultiHeadAttention.__init__rO   rP   r   c           	      C   s   |  |}| |}| |}| j| j }tjtj||dddd}tjtj||dddd}tjtj||dddd}t||	dd}|| j
d  }tj|dd}t||}tjtj|dddddd}|S )Nr	   r   r   r@   r`   r
   )r   r   r   r   rA   r8   stacksplitmatmulr   r   r   r   r   squeeze)	r%   rO   rP   queryskeysvalues
split_sizescoresoutr   r   r   r1     s   


 zMultiHeadAttention.forward)
r3   r4   r5   rw   r6   r    r8   r9   r1   r:   r   r   r&   r   r     s    $
r   )r|   typingr   r8   torch.nnr!   torch.nn.functional
functionalr   )TTS.tts.layers.delightful_tts.conv_layersr   r   r   &TTS.tts.layers.delightful_tts.networksr   r6   r   Moduler   r   rE   rG   rK   rn   r   r   r   r   r   <module>   s   LT7>'R