a
    d                     @   s  d Z ddl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	 ddl
mZ ddlmZ ddlmZmZmZ dd	lmZmZ dd
lmZmZmZmZ ddlmZ ddlmZ eeZ dZ!dZ"dZ#g dZ$dZ%dZ&dgZ'd4ej(ej)ee* ddd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,Z0G dd de	j,Z1G d d! d!e	j,Z2G d"d# d#e	j,Z3G d$d% d%e	j,Z4G d&d' d'e	j,Z5G d(d) d)eZ6d*Z7d+Z8G d,d- d-e6Z9ed.e7G d/d0 d0e6Z:ed1e7G d2d3 d3e6Z;dS )5z PyTorch M-CTC-T model.    N)OptionalTupleUnion)nn   )ACT2FN)is_deepspeed_zero3_enabled)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forward)BaseModelOutputCausalLMOutput)PreTrainedModelapply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)logging   )MCTCTConfigr   zspeechbrain/m-ctc-t-large)r      i   zY"Mr. Quilter is the apostle of the middle classes, and we're glad to welcome his gospel."gv@)maskdtypetgt_lenc                 C   sj   |   \}}|dur|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)sizeexpandtoZmasked_filltorchboolZfinfomin)r   r   r   bszZsrc_lenZexpanded_maskZinverted_mask r!   q/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/models/mctct/modeling_mctct.py_expand_mask>   s
    *r#   c                       s(   e Zd ZdZ fddZdd Z  ZS )MCTCTConv1dSubsamplerz
    Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation
    via gated linear units (https://arxiv.org/abs/1911.08460)
    c                    s   t    | _|j _t|j _|j	 _
|j|j  _ j
dkrb|jd u rXtd|j _nd  _|jd  _|j _|j _t fddt jD  _d S )Nr   zbNeed to specify `conv_channels` configuration in `MCTCTConfig` to use multiple convolution layers.   c                 3   sZ   | ]R\}}t j|d kr jn j| | jd k r< j| n j| j| ddV  qdS )r   r   Zvalid)kernel_sizestridepaddingN)r   Conv1din_channelsmid_channels
num_layersout_channelsr'   ).0ikselfr!   r"   	<genexpr>n   s   z1MCTCTConv1dSubsampler.__init__.<locals>.<genexpr>)super__init__configZconv_glu_dimglu_dimr   DropoutZconv_dropoutdropoutnum_conv_layersr,   Zinput_feat_per_channelZinput_channelsr*   Zconv_channels
ValueErrorr+   hidden_sizer-   conv_kernelr&   conv_strider'   
ModuleList	enumerateconv_layersr2   r6   	__class__r1   r"   r5   R   s&    



zMCTCTConv1dSubsampler.__init__c                 C   s   t dd | jD }tjj|dd||fdd}|dd }| jD ](}||}tjj	|| j
d}| |}qF|dd }|S )Nc                 S   s   g | ]}|d  qS )r%   r!   )r.   r   r!   r!   r"   
<listcomp>|       z1MCTCTConv1dSubsampler.forward.<locals>.<listcomp>r   Zconstantr   r%   dim)sumr&   r   r   
functionalpad	transpose
contiguousrA   Zglur7   r9   )r2   input_featuresr(   hidden_statesconvr!   r!   r"   forwardy   s    
zMCTCTConv1dSubsampler.forward__name__
__module____qualname____doc__r5   rQ   __classcell__r!   r!   rC   r"   r$   L   s   'r$   c                       s*   e Zd ZdZ fddZdddZ  ZS )	MCTCTEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _t | _t|j| _| dt|jd | jdtj| j tj| jjddd d S )N)padding_idxposition_ids)r   token_type_idsr   deviceF)
persistent)r4   r5   r   	Embedding
vocab_sizer<   pad_token_idword_embeddingsmax_position_embeddingsZposition_embeddingsZtype_vocab_sizetoken_type_embeddingsMCTCTLayerNorm	LayerNormr8   hidden_dropout_probr9   Zregister_bufferr   aranger   zerosrZ   r   longr^   rB   rC   r!   r"   r5      s    
zMCTCTEmbeddings.__init__Nr   c                 C   s   |d ur|  n|  d d }|d }|d u rJ| jd d ||| f }|d u rt| dr| jd d d |f }||d |}	|	}ntj|tj| jjd}|d u r| 	|}| 
|}
||
 }| |}| |}|S )Nr[   r   r\   r   r]   )r   rZ   hasattrr\   r   r   rj   rk   r^   rc   re   rg   r9   )r2   rN   r\   rZ   inputs_embedsZpast_key_values_lengthZinput_shapeZ
seq_lengthZbuffered_token_type_idsZ buffered_token_type_ids_expandedre   Z
embeddingsr!   r!   r"   rQ      s"     




zMCTCTEmbeddings.forward)NNNNr   rR   r!   r!   rC   r"   rX      s    rX   c                       s>   e Zd Z fddZdd Zdd Zdd ZdddZ  ZS )MCTCTSelfAttentionc                    s   t    |j|j dkr>t|ds>td|j d|j d|j| _|j| _| j| j | _t	j
|j| jdd| _t	j
|j| jdd| _t	j
|j| jdd| _t	|j| _|j| _t	d|j d	 | j| _|j| _d S )
Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()Fbiasr%   r   )r4   r5   r<   num_attention_headsrl   r;   Zattention_head_dimattention_head_sizeall_head_sizer   Linearquerykeyvaluer8   Zattention_probs_dropout_probr9   rd   r`   distance_embedding
is_decoderrB   rC   r!   r"   r5      s"    

zMCTCTSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr[   r   r%   r   r   )r   rr   rs   viewpermute)r2   xZnew_x_shaper!   r!   r"   transpose_for_scores   s    
z'MCTCTSelfAttention.transpose_for_scoresc                 C   sF   t |jdkr&|jttt |j }|jt| jttt | S )Nr   )lenshaper|   reversedrangeZreshape)r2   r}   r   r!   r!   r"   reshape_fortran   s    z"MCTCTSelfAttention.reshape_fortranc                 C   s   | dddd}|j\}}}}tj|tj||||f|jdfdd}| |||| | d|g}|d d d || d | f }| |||| d ||g}|d }|d d ||| f dd}| ddddS )Nr   r%   r   r   r^   rG   )r|   r   r   catrj   r^   r   rL   )r2   ZscoresbatchZhidden_stateZseq_lenheadsZ	halfpointr!   r!   r"   "relative_position_embedding_rotate   s    &  z5MCTCTSelfAttention.relative_position_embedding_rotateNFc                 C   s   |  |}|t| j }| | |}| | |}| |}t||	dd}	| j
j}
td|
|	dd}| |}|	| }	|d ur|	| }	tjj|	dd}| |}|d ur|| }t||}|ddddjdd	}|r||fn|f}|S )
Nr[   zlh, bche -> bcler%   r   rG   r   r   )Z	start_dim)rv   mathsqrtrs   r~   rw   rx   r   matmulrL   ry   weightZeinsumr   r   rJ   Zsoftmaxr9   r|   flatten)r2   rO   attention_mask	head_maskoutput_attentionsZmixed_query_layerZ	key_layerZvalue_layerZquery_layerZattention_scoresZpositional_embeddingZrelative_position_scoresZattention_probsZcontext_layeroutputsr!   r!   r"   rQ      s(    



zMCTCTSelfAttention.forward)NNF)	rS   rT   rU   r5   r~   r   r   rQ   rW   r!   r!   rC   r"   rn      s      rn   c                       s$   e Zd Z fddZdd Z  ZS )rf   c                    s2   t    ttd| _ttd| _d S Nr   )	r4   r5   r   	Parameterr   onessingleton_weightrj   singleton_biasr1   rC   r!   r"   r5   .  s    
zMCTCTLayerNorm.__init__c                 C   s   || j  | j S N)r   r   r2   rO   r!   r!   r"   rQ   3  s    zMCTCTLayerNorm.forwardrS   rT   rU   r5   rQ   rW   r!   r!   rC   r"   rf   -  s   rf   c                       s$   e Zd Z fddZdd Z  ZS )MCTCTSelfOutputc                    sL   t    || _tj|j|jdd| _tj|j|jd| _t	|j
| _d S NFrp   )Zeps)r4   r5   r6   r   ru   r<   denserg   layer_norm_epsr8   rh   r9   rB   rC   r!   r"   r5   8  s
    
zMCTCTSelfOutput.__init__c                 C   s&   |  |}| |}| || }|S r   r   r9   rg   r2   rO   Zinput_tensorr!   r!   r"   rQ   ?  s    

zMCTCTSelfOutput.forwardr   r!   r!   rC   r"   r   7  s   r   c                       s.   e Zd Z fddZdd Zd	ddZ  ZS )
MCTCTAttentionc                    s*   t    t|| _t|| _t | _d S r   )r4   r5   rn   r2   r   outputsetpruned_headsrB   rC   r!   r"   r5   G  s    


zMCTCTAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   rG   )r   r   r2   rr   rs   r   r   rv   rw   rx   r   r   rt   union)r2   r   indexr!   r!   r"   prune_headsM  s    zMCTCTAttention.prune_headsNFc                 C   s6   |  ||||}| |d |}|f|dd   }|S )Nr   r   )r2   r   )r2   rO   r   r   r   Zself_outputsattention_outputr   r!   r!   r"   rQ   _  s    zMCTCTAttention.forward)NNF)rS   rT   rU   r5   r   rQ   rW   r!   r!   rC   r"   r   F  s      r   c                       s$   e Zd Z fddZdd Z  ZS )MCTCTIntermediatec                    sF   t    tj|j|jdd| _t|jt	r:t
|j | _n|j| _d S )NFrp   )r4   r5   r   ru   r<   intermediate_sizer   
isinstanceZ
hidden_actstrr   intermediate_act_fnrB   rC   r!   r"   r5   s  s
    
zMCTCTIntermediate.__init__c                 C   s   |  |}| |}|S r   )r   r   r   r!   r!   r"   rQ   {  s    

zMCTCTIntermediate.forwardr   r!   r!   rC   r"   r   r  s   r   c                       s$   e Zd Z fddZdd Z  ZS )MCTCTOutputc                    sF   t    tj|j|jdd| _tj|j|jd| _t	|j
| _d S r   )r4   r5   r   ru   r   r<   r   rg   r   r8   rh   r9   rB   rC   r!   r"   r5     s    
zMCTCTOutput.__init__c                 C   s&   |  |}| |}| || }|S r   r   r   r!   r!   r"   rQ     s    

zMCTCTOutput.forwardr   r!   r!   rC   r"   r     s   r   c                       s4   e Zd Zed fddZd
ddZdd	 Z  ZS )
MCTCTLayerr6   c                    sB   t    d| _|j| _t|| _t|| _|j| _t	|| _
d S r   )r4   r5   seq_len_dimchunk_size_feed_forwardr   intermediater   	attentionrz   r   r   rB   rC   r!   r"   r5     s    


zMCTCTLayer.__init__NFc           	      C   sH   | j ||||d}|d }|dd  }t| j| j| j|}|f| }|S )Nr   r   r   )r   r   feed_forward_chunkr   r   )	r2   rO   r   r   r   Zself_attention_outputsr   r   layer_outputr!   r!   r"   rQ     s    
zMCTCTLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r2   r   Zintermediate_outputr   r!   r!   r"   r     s    
zMCTCTLayer.feed_forward_chunk)NNF)rS   rT   rU   r   r5   rQ   r   rW   r!   r!   rC   r"   r     s      
r   c                   @   sP   e Zd ZdZeZdZdZdgZdZ	dd Z
ejdd	d
Zdd ZdddZdS )MCTCTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    mctctrN   rZ   Tc                 C   s  | j j}t|tjr>|jjjd|d |jdur|jj	  nt|tj
rz|jjjd|d |jdur|jj|j 	  nLt|tjr|jj	  |jjd n$t|tr|jjd |jj	  t|tjtjfr|jjjd|d |jdur|jj	  dS )zInitialize the weightsg        )meanstdNr   )r6   Zinitializer_ranger   r   ru   r   dataZnormal_rq   Zzero_r`   rY   rg   Zfill_rf   r   r   r)   )r2   moduler   r!   r!   r"   _init_weights  s&    


z"MCTCTPreTrainedModel._init_weights)input_lengthsc                 C   sh   d}t t| jj| jj| jjD ]B\}}}|d }|d|  ||d   d }tj||ddd }q |S )zH
        Computes the output length of the convolutional layers
        r   r%   trunc)Zrounding_mode)zipr   r6   r:   r=   r>   r   div)r2   r   Zdilation_Z	kernel_szr'   r(   r!   r!   r"    _get_feat_extract_output_lengths  s    z5MCTCTPreTrainedModel._get_feat_extract_output_lengthsc                 C   s   t |jdkr$|d d d d df }| |d}| d }tj||f|j|jd}d|tj	||jd|d f< |
dgd
dg }|S )Nr%   r[   r   r]   r   r   )r   r   r   rI   r   r   rj   r   r^   ri   ZflipZcumsumrk   )r2   Zfeature_vector_lengthr   Zsubsampled_lengthsr    r!   r!   r"   "_get_feature_vector_attention_mask  s    z7MCTCTPreTrainedModel._get_feature_vector_attention_maskFc                 C   s   t |tr||_d S r   )r   MCTCTEncodergradient_checkpointing)r2   r   rx   r!   r!   r"   _set_gradient_checkpointing  s    
z0MCTCTPreTrainedModel._set_gradient_checkpointingN)F)rS   rT   rU   rV   r   config_classZbase_model_prefixZmain_input_nameZ_keys_to_ignore_on_load_missingZsupports_gradient_checkpointingr   r   
LongTensorr   r   r   r!   r!   r!   r"   r     s   r   aH  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MCTCTConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_features (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`Wav2Vec2CTCTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
c                
       sL   e Zd Zed fddZd	ejejejeeeee	e
f dddZ  ZS )
r   r   c                    sP   t     j| _t | _t | _t fddt	 j
D | _d| _d S )Nc                    s   g | ]}t  qS r!   )r   )r.   r   r   r!   r"   rE   2  rF   z)MCTCTEncoder.__init__.<locals>.<listcomp>F)r4   r5   rh   rf   
layer_normr$   rP   r   r?   r   Znum_hidden_layerslayersr   rB   rC   r   r"   r5   ,  s    
 zMCTCTEncoder.__init__FTrN   r   r   r   output_hidden_statesreturn_dictreturnc                    s   d ur n| j j |d ur |n| j j}|d ur4|n| j j}| |}| |}|d urj| |jd |}tj	j
|| j| jd}|d urt||j}|rdnd }	 rdnd }
|d ur| d t| jkrtdt| j d| d  dt }t| jD ]\}}|r|	|f }	tdd}| jr<|| j jk r<dnd	}|rL|r| jr| jr fd
d}tjj|||||d ur|| nd }n||| d}|d }|rd} r|
|d f }
q|r|	|f }	|stdd ||	|
fD S t||	|
dS )Nr   )ptrainingr!   r   z&The head_mask should be specified for z layers, but it is for .TFc                    s    fdd}|S )Nc                     s    g | R  S r   r!   )inputs)r   r   r!   r"   custom_forwardm  s    zKMCTCTEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr!   )r   r   r   )r   r"   create_custom_forwardl  s    z3MCTCTEncoder.forward.<locals>.create_custom_forward)rO   r   r   )NNc                 s   s   | ]}|d ur|V  qd S r   r!   )r.   vr!   r!   r"   r3     rF   z'MCTCTEncoder.forward.<locals>.<genexpr>Zlast_hidden_staterO   
attentions)r6   r   r   use_return_dictr   rP   r   r   r   rJ   r9   rh   r   r#   r   r   r   r   r;   r   r@   randomuniformZ	layerdropr   r   utils
checkpointtupler   )r2   rN   r   r   r   r   r   rm   rO   Zencoder_statesZall_attentionsZdeepspeed_zero3_is_enabledidxZencoder_layerZdropout_probabilityZskip_the_layerr   Zlayer_outputsr!   r   r"   rQ   6  sh    	




zMCTCTEncoder.forward)FFT)rS   rT   rU   r   r5   r   Tensorr   r   r   r   rQ   rW   r!   r!   rC   r"   r   +  s      
r   zaThe bare M-CTC-T Model transformer outputting raw hidden-states without any specific head on top.c                       sz   e Zd Z fddZeedeee	e
dedd
ejeej eej ee ee ee eee	f ddd	Z  ZS )
MCTCTModelc                    s(   t  | || _t|| _|   d S r   )r4   r5   r6   r   encoder	post_initrB   rC   r!   r"   r5     s    
zMCTCTModel.__init__zbatch_size, sequence_lengthaudio)r   output_typer   Zmodalityexpected_outputNr   c           	      C   s   |d ur|n| j j}|d ur |n| j j}|d ur4|n| j j}|d u rLtd| j||||||d}|d }|s|f|dd   S t||j|jdS )Nz#You have to specify input_features.r   r   r   r   r   r   r   r   )	r6   r   r   r   r;   r   r   rO   r   )	r2   rN   r   r   r   r   r   Zencoder_outputsZsequence_outputr!   r!   r"   rQ     s,    zMCTCTModel.forward)NNNNN)rS   rT   rU   r5   r   MCTCT_INPUTS_DOCSTRINGformatr	   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   r   r   r   r   r   rQ   rW   r!   r!   rC   r"   r     s.   	
     
r   zcMCTCT Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).c                       s|   e Zd Z fddZeeeeee	e
eddejeej eej ee ee ee eej eeef dddZ  ZS )	MCTCTForCTCc                    sT   t  | t|| _|jd u r2td| j d|j}t	||j| _
|   d S )NzYou are trying to instantiate z with a configuration that does not define the vocabulary size of the language model head. Please instantiate the model as follows: `MCTCTForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.)r4   r5   r   r   ra   r;   rD   r<   r   ru   ctc_headr   )r2   r6   Zoutput_hidden_sizerC   r!   r"   r5     s    

zMCTCTForCTC.__init__)r   r   r   r   Zexpected_lossN)rN   r   r   r   r   r   labelsr   c              
   C   s~  |dur|n| j j}| j||||||d}|d }	| |	}
d}|dur:| | j jkrltd| j j |durx|ntj|j	dd tj
d}| |dtj
}|dk}|d}||}tjj|
dtjddd}tjjjd	d
6 tjj||||| j j| j j| j jd}W d   n1 s00    Y  |sj|
f|td  }|durf|f| S |S t||
|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
            Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
            the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
            All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
            config.vocab_size - 1]`.
        Nr   r   z$Label values must be <= vocab_size: r[   )r   )rH   r   r   F)Zenabled)ZblankZ	reductionZzero_infinity)losslogitsrO   r   )r6   r   r   r   maxra   r;   r   r   r   rk   r   rI   r   Zmasked_selectr   rJ   Zlog_softmaxfloat32rL   backendsZcudnnflagsZctc_lossrb   Zctc_loss_reductionZctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   rO   r   )r2   rN   r   r   r   r   r   r   r   rO   r   r   r   Zlabels_maskZtarget_lengthsZflattened_targetsZ	log_probsr   r!   r!   r"   rQ     sP    	



&
zMCTCTForCTC.forward)NNNNNN)rS   rT   rU   r5   r   r   r	   r   r   r   _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr   r   r   r   r   r   r   rQ   rW   r!   r!   rC   r"   r     s2   
      
r   )N)<rV   r   r   typingr   r   r   r   Ztorch.utils.checkpointr   Zactivationsr   Z	deepspeedr   Z
file_utilsr	   r
   r   Zmodeling_outputsr   r   Zmodeling_utilsr   r   r   r   r   r   Zconfiguration_mctctr   Z
get_loggerrS   loggerr   r   r   r   r   r   Z#MCTCT_PRETRAINED_MODEL_ARCHIVE_LISTr   r   intr#   Moduler$   rX   rn   rf   r   r   r   r   r   r   ZMCTCT_START_DOCSTRINGr   r   r   r   r!   r!   r!   r"   <module>   s\   
=8l
,'J f8