U
    %d?                     @   s  d dl Z d dlmZmZmZ d dlZd dlmZmZ d dlm	Z	m
Z
 e eZG dd dejZG dd de	ZG d	d
 d
e	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	Zeeeeeef  eedddZeeeeeeeeeeeeeedddZd1eeef ee eeeeeeeed"
d#d$Zeeed%d&d'ZG d(d) d)e	Z eee
ed*d+d,Z!G d-d. d.e	Z"G d/d0 d0ej#j$Z%dS )2    N)ListOptionalTuple)nnTensor)Module	Parameterc                   @   s    e Zd ZdZeedddZdS )	LayerNormzLayer norm with transpose)inputreturnc                 C   s8   | dd}tj|| j| j| j| j}| dd}|S )N)	transposer   
functional
layer_normnormalized_shapeweightbiasZeps)selfr
   x r   I/tmp/pip-unpacked-wheel-lbdmvq91/torchaudio/models/wav2vec2/components.pyforward   s    zLayerNorm.forwardN)__name__
__module____qualname____doc__r   r   r   r   r   r   r	      s   r	   c                       sV   e Zd ZdZeeeeeee d fddZe	ee	 e
e	ee	 f dddZ  ZS )ConvLayerBlockz$Convolution unit of FeatureExtractorin_channelsout_channelskernel_sizestrider   r   c                    s6   t    || _|| _|| _tj|||||d| _d S )N)r   r    r!   r"   r   )super__init__r!   r"   r   r   Conv1dconv)r   r   r    r!   r"   r   r   	__class__r   r   r$      s    	
zConvLayerBlock.__init__r   lengthr   c                 C   sh   |  |}| jdk	r| |}tj|}|dk	r`tj|| j | jddd }t	t
||}||fS )a#  
        Args:
            x (Tensor): Shape: ``[batch, in_channels, in_frame]``.
            length (Tensor or None, optional): Shape ``[batch, ]``.
        Returns:
            Tensor: Shape ``[batch, out_channels, out_frames]``.
            Optional[Tensor]: Shape ``[batch, ]``.
        Nfloor)Zrounding_mode   )r&   r   r   r   gelutorchdivr!   r"   maxZ
zeros_like)r   r   r*   r   r   r   r   -   s    


zConvLayerBlock.forward)r   r   r   r   intboolr   r   r$   r   r   r   __classcell__r   r   r'   r   r      s   r   c                       sJ   e Zd ZdZejd fddZeee e	eee f dddZ
  ZS )FeatureExtractorzoExtract features from audio

    Args:
        conv_layers (nn.ModuleList):
            convolution layers
    )conv_layersc                    s   t    || _d S N)r#   r$   r5   )r   r5   r'   r   r   r$   N   s    
zFeatureExtractor.__init__r)   c                 C   sJ   |j dkrtd|d}| jD ]}|||\}}q"|dd}||fS )a  
        Args:
            x (Tensor):
                Input Tensor representing a batch of audio,
                shape: ``[batch, time]``.
            length (Tensor or None, optional):
                Valid length of each input sample. shape: ``[batch, ]``.

        Returns:
            Tensor:
                The resulting feature, shape: ``[batch, frame, feature]``
            Optional[Tensor]:
                Valid length of each output sample. shape: ``[batch, ]``.
           zNExpected the input Tensor to be 2D (batch, time), but received {list(x.shape)}r,   )ndim
ValueError	unsqueezer5   r   )r   r   r*   layerr   r   r   r   U   s    


zFeatureExtractor.forward)r   r   r   r   r   
ModuleListr$   r   r   r   r   r3   r   r   r'   r   r4   F   s   		r4   c                       s2   e Zd ZdZeeed fddZdd Z  ZS )FeatureProjectionzLayer that connects FeatureExtractor and Encoder

    Projects features to encoder dimension.

    Args:
        in_features (int): Input feature dim.
        out_features (int): Output feature dim.
        dropout (float): Dropout probability.
    )in_featuresout_featuresdropoutc                    s4   t    t|| _t||| _t|| _d S r6   )	r#   r$   r   r	   r   Linear
projectionDropoutr@   )r   r>   r?   r@   r'   r   r   r$   }   s    
zFeatureProjection.__init__c                 C   s"   |  |}| |}| |}|S )z
        Args:
            x (Tensor):
                Feature Tensor. shape: ``[batch, frame, in_feature]``
        Returns:
            Tensor: Projected features. ``[batch, frame, out_feature]``.
        )r   rB   r@   r   r   r   r   r   r      s    


zFeatureProjection.forward	r   r   r   r   r1   floatr$   r   r3   r   r   r'   r   r=   r   s   r=   c                       s:   e Zd ZdZeeed fddZdd Zdd Z  ZS )	 ConvolutionalPositionalEmbeddinga  Positional embedding which is placed at the beginning of Transformer.

    Args:
        embed_dim (int): Feature dimension of the input Tensor.
        kernel_size (int): The number of frames to be use.
        groups (int): The number of groups in feature dimensions.
    )	embed_dimr!   groupsc                    sZ   t    || _tj||||d |d| _tjj| jddd| _|d dkrPdnd| _d S )Nr7   )r   r    r!   paddingrI   r   )namedimr   r,   )	r#   r$   rH   r   r%   r&   utilsZweight_norm
num_remove)r   rH   r!   rI   r'   r   r   r$      s    
z)ConvolutionalPositionalEmbedding.__init__c                 C   sL   | j j D ]:}|jdkr|jjdkrtd| jj tj	j
| j  q| S )Nztorch.nn.utils.weight_normZ
WeightNormzRemoving weight_norm from %s)r&   Z_forward_pre_hooksvaluesr   r(   r   _LGwarningr.   r   rM   Zremove_weight_norm)r   hookr   r   r   __prepare_scriptable__   s
    z7ConvolutionalPositionalEmbedding.__prepare_scriptable__c                 C   sR   | dd}| |}| jdkr4|dd| j f }tjj|}| dd}|S )z
        Args:
            x (Tensor): shape ``[batch, frame, feature]``.

        Returns:
            Tensor: The resulting feature. Shape ``[batch, frame, feature]``.
        r   r   r   .N)r   r&   rN   r.   r   r   r-   rD   r   r   r   r      s    

z(ConvolutionalPositionalEmbedding.forward)	r   r   r   r   r1   r$   rS   r   r3   r   r   r'   r   rG      s   
rG   c                       sD   e Zd ZdZd
eeed fddZdeee eddd	Z	  Z
S )SelfAttentiona   Multihead Self Attention module

    Args:
        embed_dim (int): Total dimension of the model.
        num_heads (int): The number of heads.
        dropout (float, optional):
            Dropout probabiliry on attn_output_weights. Default: ``0.0``
            rH   	num_headsr@   c                    s   t    || }|| |kr4td| d| d|| _|| _tj|| _|| _	| j	d | _
tj||dd| _tj||dd| _tj||dd| _tj||dd| _d S )Nz`embed_dim (z#)` is not divisible by `num_heads (z)`g      T)r   )r#   r$   r9   rH   rW   r.   r   rC   r@   head_dimscalingrA   k_projv_projq_projout_proj)r   rH   rW   r@   rX   r'   r   r   r$      s    
zSelfAttention.__init__N)r   attention_maskr   c                 C   s>  |j dks|jd | jkr4td| j d|j d| \}}}|dk	r||d||f}| |kr|td| d	|  d||| j| jf}| |j| 	dd}| 
|j| d
ddd}	| |j| 	dd}
| j||	  }|dk	r||7 }tjjj|dd}| |}||
 }|	dd|||}| |}|S )aS  
        Args:
            x (Tensor): shape: ``[batch_size, sequence_length, embed_dim]``.
            attention_mask (Tensor or None, optional):
                shape: ``[batch_size, 1, sequence_length, sequence_length]``

        Returns:
            Tensor: The resulting tensor. shape: ``[batch, sequence_length, embed_dim]``
           r7   z9The expected input shape is (batch, sequence, embed_dim==z	). Found .Nr,   z%The expected attention mask shape is z. Found r   r   rL   )r8   shaperH   r9   sizerW   rX   r\   viewr   rZ   Zpermuter[   rY   r.   r   r   Zsoftmaxr@   Zreshaper]   )r   r   r^   
batch_sizer*   rH   Zshape_rb   qkvweightsoutputr   r   r   r      s,    

zSelfAttention.forward)rU   )N)r   r   r   r   r1   rF   r$   r   r   r   r3   r   r   r'   r   rT      s     rT   c                       s4   e Zd ZdZeeeed fddZdd Z  ZS )FeedForwardz4Layer that follows attention layer in encoder layer.io_featuresintermediate_featuresintermediate_dropoutoutput_dropoutc                    sB   t    t||| _t|| _t||| _t|| _d S r6   )	r#   r$   r   rA   intermediate_denserC   ro   output_denserp   )r   rm   rn   ro   rp   r'   r   r   r$     s
    
zFeedForward.__init__c                 C   s:   |  |}tjj|}| |}| |}| |}|S )z
        Args:
            x (Tensor): shape: `(batch, sequence_length, io_features)`
        Returns:
            x (Tensor): shape: `(batch, sequence_length, io_features)`
        )rq   r.   r   r   r-   ro   rr   rp   rD   r   r   r   r   ,  s    



zFeedForward.forwardrE   r   r   r'   r   rk     s   rk   c                       sB   e Zd ZdZeeeed fddZd	ee	e dddZ
  ZS )
EncoderLayerzLA layer unit in encoder. Combines multihead self attention and feed forward.	attentionr@   layer_norm_firstfeed_forwardc                    sH   t    || _t|| _t|j| _|| _	|| _
t|j| _d S r6   )r#   r$   ru   r   rC   r@   r	   rH   r   rv   rw   final_layer_norm)r   ru   r@   rv   rw   r'   r   r   r$   ?  s    
zEncoderLayer.__init__Nr   r^   c                 C   sp   |}| j r| |}| ||}| |}|| }| j rN|| | | }n| |}| || | }|S )z
        Args:
            x (Tensor): shape: `(batch, sequence_length, embed_dim)`
            attention_mask (Tensor or None, optional):
                shape: `(batch, 1, sequence_length, sequence_length)`
        )rv   r   ru   r@   rw   rx   )r   r   r^   Zresidualr   r   r   r   N  s    


zEncoderLayer.forward)N)r   r   r   r   r   rF   r2   r$   r   r   r   r3   r   r   r'   r   rs   <  s    rs   c                       sp   e Zd Zeeeeed fddZedddZdee	e dd	d
Z
dee	e e	e ee dddZ  ZS )Transformerpos_conv_embedr@   layersrv   
layer_dropc                    s@   t    || _t|j| _|| _|| _t	|| _
|| _d S r6   )r#   r$   r|   r   r	   rH   r   rv   r~   rC   r@   r}   )r   r|   r@   r}   rv   r~   r'   r   r   r$   k  s    
zTransformer.__init__)r   c                 C   s,   ||  | }| jr| |}| |}|S r6   )r|   rv   r   r@   rD   r   r   r   _preprocess{  s
    

zTransformer._preprocessNry   c                 C   sN   |  |}| jD ](}| jr.td | jks|||}q| jsJ| |}|S )Nr,   )	r   r}   Ztrainingr.   randitemr~   rv   r   )r   r   r^   r;   r   r   r   r     s    


zTransformer.forward)r   r^   
num_layersr   c                 C   s   |d k	r:d|  k r"t | jks:n tdt | j dg }| |}| jD ]4}|||}|| |d k	rNt ||krN|  S qN|S )Nr   z!`num_layers` must be between [1, ])lenr}   r9   r   append)r   r   r^   r   retr;   r   r   r   get_intermediate_outputs  s    




z$Transformer.get_intermediate_outputs)N)NN)r   r   r   r   rF   r2   r$   r   r   r   r   r1   r   r   r3   r   r   r'   r   rz   j  s(      rz   c                       s   e Zd Zeed fddZdeee eeee f dddZdeee eddd	Z	deee ee
 ee d
ddZ  ZS )Encoder)feature_projectiontransformerc                    s   t    || _|| _d S r6   )r#   r$   r   r   )r   r   r   r'   r   r   r$     s    
zEncoder.__init__N)featureslengthsr   c                 C   s   |  |}d }|d k	r|j\}}}tj||jd|||d d d f k}d||< d|d d d d d d f j|jd }||d||}||fS )NdevicerU   g     dtyper,   )r   rb   r.   aranger   expandtor   )r   r   r   r   maskre   max_len_r   r   r   r     s    
(&zEncoder._preprocessc                 C   s"   |  ||\}}| j||d}|S )N)r^   )r   r   )r   r   r   r   r   r   r   r   r     s    zEncoder.forward)r   r   r   r   c                 C   s"   |  ||\}}| jj|||dS )N)r^   r   )r   r   r   )r   r   r   r   r   masksr   r   r   extract_features  s    zEncoder.extract_features)N)N)NN)r   r   r   r   r$   r   r   r   r   r   r1   r   r   r3   r   r   r'   r   r     s.       r   )	norm_modeshapesr   r   c           
      C   s   | dkst g }d}t|D ]f\}\}}}d}	| dkrP|dkrPtj||dd}	n| dkrdt|dd	}	|t||||||	d
 |}qtt|S )a  
    Args:
        norm_mode (str):
            Either "group_norm" or "layer_norm".
            If "group_norm", then a single normalization is applied
            in the first convolution block. Otherwise, all the convolution
            blocks will have layer normalization.
            This option corresponds to "extractor_mode" from fairseq.
            Expected values are "group_norm" for Base arch, and
            "layer_norm" for Large arch.
        shapes (list of tuple of int):
            Configuration of convolution layers. List of convolution configuration,
            i.e. ``[(output_channel, kernel_size, stride), ...]``
            This option corresponds to "conv_feature_layers" from fairseq.
            Expected values are
            ``[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512, 2, 2)] * 2``
            for all the architectures.
        bias (bool):
            Whether to include bias term to each convolution operation.
            This option corresponds to "conv_bias" from fairseq.
            Expected values are False for Base arch, and True for Large arch.

    See Also:
        * Original implementation
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L666-L733
        * "extractor_mode"
          - Def and base:
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L38-L45
          - Large:
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L52
        * "conv_feature_layers"
          - Def, base and large:
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L94-L100
        * "conv_bias"
          - Def and base:
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L101-L103
          - Large:
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L61
    )
group_normr   r,   Nr   r   T)Z
num_groupsZnum_channelsZaffiner   )r   Zelementwise_affiner   )	AssertionError	enumerater   Z	GroupNormr	   r   r   r4   r<   )
r   r   r   blocksr   ir    r!   r"   Znormalizationr   r   r   _get_feature_extractor  s8    ,
r   )r>   rH   dropout_inputpos_conv_kernelpos_conv_groupsr   rW   attention_dropoutff_interm_featuresff_interm_dropoutr@   rv   r~   r   c              	   C   s   t | ||}t|||}t }t|D ]8}t|||d}t|||	|
d}|t||
||d q(t	||
|| |d}t
||S )a  
    Args:
        in_features (int): The number of input features.
        embed_dim (int):
            The dimension of embedding.
            This option corresponds to "encoder_embed_dim" from fairseq.
            Expected values are 768 for Base arch, and 1024 for Large arch.
        dropout_input (float):
            The dropout probability applied after the input feature is projected
            to ``embed_dim``.
            This option corresponds to "dropout_input" from fairseq.
            Expected values are 0.1 for both Base and Large arch.
        pos_conv_kernel (int):
            The kernel size of convolutional positional embeddings.
            This option corresponds to "conv_pos" from fairseq.
            Expected values are 128 for both Base and Large arch.
        pos_conv_groups (int):
            The number of groups of convolutional positional embeddings.
            This option corresponds to "conv_pos_groups" from fairseq.
            Expected values are 16 for both Base and Large arch.
        num_layers (int):
            The number of self attention layers in transformer block.
            This option corresponds to "encoder_layers" from fairseq.
            Expected values are 12 for Base and 24 for Large arch.
        num_heads (int):
            The number of heads in self attention layers.
            This option corresponds to "encoder_attention_heads" from fairseq.
            Expected values are 12 for Base and 16 for Large arch.
        attention_dropout (float):
            The dropout probability applied after softmax in self-attention layer.
            This option corresponds to "attention_dropout" from fairseq.
            Expected values are 0.1 for Base and 0.0 for Large arch.
        ff_interm_features (int):
            The dimension of hidden features in feed forward layer.
            This option corresponds to "encoder_ffn_embed_dim" from fairseq.
            Expected values are 3072 for Base and 4096 for Large arch.
        ff_interm_dropout (float):
            The dropout probability applied in feedforward layer.
            This option correspinds to "activation_dropout" from fairseq.
            Expected values are 0.1 for both Base and Large arch.
        dropout (float):
            The dropout probability applied at the end of feed forward layer.
            This option corresponds to "dropout" from fairseq.
            Expected values are 0.1 for Base and 0.0 for Large arch.
        layer_norm_first (bool):
            Control the order of layer norm in transformer layer and each encoder layer.
            If True, in transformer layer, layer norm is applied before features are fed
            to encoder layers. In encoder layer, two layer norms are applied before and after
            self attention.
            If False, in transformer layer, layer norm is applied after features are fed
            to encoder layers. In encoder layer, two layer norms are applied after self
            attention, before and after feed forward.
            This option corresponds to "layer_norm_first" from fairseq.
            Expected values are False for Base and True for Large arch.
        layer_drop (float):
            Probability to drop each encoder layer during training.
            This option corresponds to "layerdrop" from fairseq.
            Expected values are 0.1 for both Base and Large arch.

    See Also:
        * "encoder_embed_dim"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L49-L51
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L64
        * "dropout_input"
          - Def, base and large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L75-L78
        * "conv_pos"
          - Def, base and large
            NOTE: The description is wrong.
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L204-L207
          - Usage
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L756
        * "conv_pos_groups"
          - Def, base and large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L208-L211
        * "encoder_layers"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L46-L48
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L63
        * "encoder_attention_heads"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L55-L57
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L66
        * "attention_dropout"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L66-L68
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L60
        * "encoder_ffn_embed_dim"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L52-L54
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L65
        * "activation_dropout"
          - Def
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L69-L71
          - Base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/base_960h.yaml#L55
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/vox_960h.yaml#L55
        * "dropout"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L63-L65
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L59
        * "layer_norm_first"
          - Def and base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L91-L93
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L53
        * "layerdrop"
          - Def
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L72-L74
          - Base
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/base_960h.yaml#L54
          - Large
            https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/vox_960h.yaml#L54
    rV   rl   rt   r{   )r=   rG   r   r<   rangerT   rk   r   rs   rz   r   )r>   rH   r   r   r   r   rW   r   r   r   r@   rv   r~   r   Zpos_convZencoder_layersr   ru   rw   r   r   r   r   _get_encoder!  s@     
r   staticrU   F)
rb   padding_mask	mask_probmask_length	mask_type
mask_other	min_masks
no_overlap	min_spacer   c	              
      s   | \}	}
t |	|
fd}t||
 t| t d }t||}g }t|	D ]d}|dk	r|
||   	  }t|| t| t d }t||}n|
}|}|dkrt |f| n|dkrt j
||d d |fd nr|dkrt j|||fd t t dt    n8|d	krDt j||fd t    ntd
| t dkrrt||d  d< |r:g fdd}d|fg}t }t ddD ]}t jdd |D t jd}d||| k < | }|dkr q.|| }t jj| }||\}}|||||| qt n`t }|| |kr\|| d }t jt || f|ddt  fddttD |t |k   qLtdd |D }t|D ]L\}t|krt dt jt j d f|ddd||f< q|S )a  Computes random mask spans for a given shape.
    Args:
        shape (int, int): The shape for which to compute masks.
            The first element is batch size and second is the number of frames.
        padding_mask (Tensor or None): The padding mask of the same dimension as shape,
            which will prevent masking padded elements.
        mask_prob (float): Probability for each token to be chosen as start of the span to be masked.
            This will be multiplied by number of timesteps divided by length of mask span to mask
            approximately this percentage of all elements. However due to overlaps, the actual number
            will be smaller (unless no_overlap is True).
        mask_type (str): How to compute mask lengths. Options: [``static``, ``uniform``, ``normal``, ``poisson``].
            ``static``: Fixed size
            ``uniform``: Sample from uniform distribution [mask_other, mask_length*2]
            ``normal``: Sample from normal distribution with mean ``mask_length`` and stdev ``mask_other``.
            ``poisson``: Sample from possion distribution with lambda = ``mask_length``.
        min_masks (int): Minimum number of masked spans.
        no_overlap (bool): If false, will switch to an alternative recursive algorithm
            that prevents spans from overlapping.
        min_space (int): How many frames to keep unmasked between spans (Only used if no_overlap is True).

    Returns:
        (Tensor): The mask indices of dimension `[batch, frame]`.
    Fr,   Nr   uniformr7   rc   normalpoissonzunknown mask selection: r   c                    s   t j| || dd  fddt|D  g } |   |krZ||   d f |  |  |kr| |  |f |S )N)r,   r   c                 3   s   | ]} | V  qd S r6   r   ).0r   Z
span_startr   r   	<genexpr>  s     z9_compute_mask_indices.<locals>.arrange.<locals>.<genexpr>r,   )r.   randintextendr   r   )ser*   Zkeep_lengthZ	new_parts)mask_idcr   r   r   arrange  s    z&_compute_mask_indices.<locals>.arrangeT)reversec                 S   s   g | ]\}}|| qS r   r   )r   r   r   r   r   r   
<listcomp>$  s     z)_compute_mask_indices.<locals>.<listcomp>r   )Znum_samplesreplacementc                    s*   g | ]"}t  | D ]}| | qqS r   )r   )r   joffset)r   r   r   r   r   6  s       c                 S   s   g | ]}t |qS r   )r   )r   mr   r   r   r   ;  s     )!r.   fullr1   rF   r   r0   r   longsumr   r   r   maximumZonesroundr   	ExceptionminsortedZtensordistributionsZcategoricalZCategoricalsamplepopr   Zmultinomialr   r   uniquer   index_selectrb   )rb   r   r   r   r   r   r   r   r   re   framer   Zall_num_maskZ	mask_idcsr   szZnum_maskr   partsZ
min_lengthr*   ZlensZl_sumZprobscr   r   Zmin_lenr   )r   r   r   r   _compute_mask_indices  s~    #




	r   )r
   r   r   c                 C   s8   | j \}}}tj||jd|||dddf k}|S )a&  Generate the padding mask given the padded input and the lengths Tensors.
    Args:
        input (Tensor): The padded Tensor of dimension `[batch, max_len, frequency]`.
        lengths (Tensor): The lengths Tensor of dimension `[batch,]`.

    Returns:
        (Tensor): The padding mask.
    r   N)rb   r.   r   r   r   )r
   r   re   r   r   r   r   r   r   _get_padding_maskL  s    	(r   c                       sT   e Zd ZdZeeeeeeeeeeeeed fddZe	e
e	 e	dddZ  ZS )MaskGeneratoraA  Generate the masks for masked prediction.
    Args:
        encoder_embed_dim (int): The dimension of the transformer embedding output.
        mask_prob (float): Probability for each token to be chosen as start of the span to be masked.
            This will be multiplied by number of timesteps divided by length of mask span to mask
            approximately this percentage of all elements. However due to overlaps, the actual number
            will be smaller (unless no_overlap is True).
        mask_selection (str): How to choose the mask length.
            Options: [``static``, ``uniform``, ``normal``, ``poisson``].
        mask_other (float): Secondary mask argument (used for more complex distributions).
        mask_length (int): The lengths of the mask.
        no_mask_overlap (bool):  Whether to allow masks to overlap.
        mask_min_space (int):  Minimum space between spans (if no overlap is enabled).
        mask_channel_prob (float): The probability of replacing a feature with 0.
        mask_channel_selection (str): How to choose the mask length for channel masking.
            Options: [``static``, ``uniform``, ``normal``, ``poisson``].
        mask_channel_other (float): Secondary mask argument for channel masking(used for more complex distributions).
        mask_channel_length (int): Minimum space between spans (if no overlap is enabled) for channel masking.
        no_mask_channel_overlap (bool):  Whether to allow channel masks to overlap.
        mask_channel_min_space (int): Minimum space between spans for channel masking(if no overlap is enabled).
    )encoder_embed_dimr   mask_selectionr   r   no_mask_overlapmask_min_spacemask_channel_probmask_channel_selectionmask_channel_othermask_channel_lengthno_mask_channel_overlapmask_channel_min_spacec                    sv   t    || _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _tt|| _tjj| j d S r6   )r#   r$   r   r   r   r   r   r   r   r   r   r   r   r   r   r.   FloatTensormask_embeddingr   inituniform_)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r'   r   r   r$   q  s    
zMaskGenerator.__init__)r   r   r   c                 C   s   |j \}}}| jdkrXt||f|| j| j| j| jd| j| jd	}||j	}| j
||< nd}| jdkrt||fd| j| j| j| j| j| jd}||j	dd|d}d||< ||fS )a  
        Args:
            x (Tensor): The encoded representations after feature extraction module.
            padding_mask (Tensor or None): The padding mask of the same dimension as shape,
                which will prevent masking padded elements.

        Returns:
            Tensor: The feature representations after masking.
            Tensor: The generated mask indices.
        r   r7   )r   r   r   N)r   r   r,   r   )rb   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r:   r   )r   r   r   BTCZmask_indicesZmask_channel_indicesr   r   r   r     s<    


zMaskGenerator.forward)r   r   r   r   r1   rF   strr2   r$   r   r   r   r3   r   r   r'   r   r   Z  s     r   )proj_xtargetlabel_embeddingsr   c           	      C   s   d}t |d| }|dd| dd}||kd}|d}t j||gdd}t j| 	 |	 dd
| }|| }| rt	d|dd |< |dd}|S )a  Compute the logits of the embeddings.
    Args:
        proj_x (Tensor): The projected masked representations of dimension `[batch, frame, final_dim]`.
        target (Tensor): The target Tensor of dimension `[batch, frame, final_dim]`.
        label_embeddings (Parameter): The trainable embeddings of target of dimension `[num_class, final_dim]`.

    Returns:
        (Tensor): The logits of the inputs.
    g?r   r,   r   ra   z-infN)r.   r   r   r:   r   rc   allcatZcosine_similarityrF   Ztype_asanyr   )	r   r   r   Z
logit_tempposZnegsZ
neg_is_postargetsZlogitsr   r   r   _compute_logits  s    
r   c                       sL   e Zd ZdZeeeeed fddZeeeeeeef dddZ	  Z
S )LogitGeneratora  Generate the logits of masked and unmasked inputs.
    Args:
        encoder_embed_dim (int): The dimension of the transformer embedding output.
        num_classes (int): The number of classes in the labels.
        final_dim (int): Project final representations and targets to `final_dim`.
        skip_masked (bool): If True, skip computing losses over masked frames.
        skip_nomask (bool): If True, skip computing losses over unmasked frames.
    )r   num_classes	final_dimskip_maskedskip_nomaskc                    sL   t    tt||| _tjj| j tj	||| _
|| _|| _d S r6   )r#   r$   r   r.   r   r   r   r   r   rA   
final_projr   r   )r   r   r   r   r   r   r'   r   r   r$     s    
zLogitGenerator.__init__)r   labelmask_mmask_ur   c                 C   sf   |  |}| jrd}n|| }|| }t||| j}| jr@d}	n|| }
|| }t|
|| j}	||	fS )a/  
        Args:
            x (Tensor): The feature representation of the last transformer layer.
            label (Tensor): The label Tensor of dimension `[batch, frame]`.
            mask_m (Tensor): The masked indices of dimension `[batch, frame]`.
            mask_u (Tensor): The unmasked indices of dimension `[batch, frame]`.

        Returns:
            Tensor: The logits of masked frames. Tensor of dimension `[masked_frame, final_dim]`.
            Tensor: The logits of unmasked frames. Tensor of dimension `[unmasked_frame, final_dim]`.
        N)r   r   r   r   r   )r   r   r   r   r   r   Zlogit_mZproj_x_mZlabel_mZlogit_uZproj_x_uZlabel_ur   r   r   r     s    
zLogitGenerator.forward)r   r   r   r   r1   r2   r$   r   r   r   r3   r   r   r'   r   r     s   r   c                   @   s$   e Zd Zedd Zedd ZdS )GradMultiplyc                 C   s   || _ ||}|S r6   )scalenew)ctxr   r   resr   r   r   r     s    
zGradMultiply.forwardc                 C   s   || j  d fS r6   )r   )r   Zgradr   r   r   backward  s    zGradMultiply.backwardN)r   r   r   staticmethodr   r  r   r   r   r   r     s   
r   )r   rU   r   Fr   )&loggingtypingr   r   r   r.   r   r   Ztorch.nnr   r   	getLoggerr   rP   r	   r   r4   r=   rG   rT   rk   rs   rz   r   r   r1   r2   r   rF   r   r   r   r   r   r   ZautogradZFunctionr   r   r   r   r   <module>   s|   

1,'7L .=1K 3     
~f6