U
    ,-eO                    @   s  d Z ddlZddlZddlmZ ddlmZmZmZ ddl	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 dd
lmZmZmZmZmZmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( dZ)dZ*e$ rddl+m,Z- e%.e/Z0dZ1dZ2dZ3dddgZ4dZ5dZ6dZ7dZ8dZ9dZ:ddgZ;dZ<dZ=ddd d!gZ>eG d"d# d#eZ?dkee@e@f eAe@eejB e@e
jCd$d%d&ZDdlee@ee
jC d'd(d)ZEG d*d+ d+ejFZGG d,d- d-ejFZHG d.d/ d/ejFZIG d0d1 d1ejFZJG d2d3 d3ejFZKG d4d5 d5ejFZLG d6d7 d7eLZMG d8d9 d9ejFZNG d:d; d;ejFZOG d<d= d=ejFZPG d>d? d?ejFZQG d@dA dAejFZRG dBdC dCejFZSG dDdE dEejFZTG dFdG dGejFZUG dHdI dIejFZVG dJdK dKejFZWG dLdM dMejFZXG dNdO dOeZYdPZZdQZ[e!dReZG dSdT dTeYZ\e!dUeZG dVdW dWeYZ]e!dXeZG dYdZ dZeYZ^e!d[eZG d\d] d]eYZ_e!d^eZG d_d` d`eYZ`e!daeZG dbdc dceYZaG ddde deejFZbG dfdg dgejFZce!dheZG didj djeYZddS )mz PyTorch Wav2Vec2 model.    N)	dataclass)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)BaseModelOutputCausalLMOutputMaskedLMOutputSequenceClassifierOutputTokenClassifierOutputWav2Vec2BaseModelOutputXVectorOutput)PreTrainedModel)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardcached_fileis_safetensors_availableloggingreplace_return_docstrings   )Wav2Vec2Configzadapter.{}.binzadapter.{}.safetensors)	load_file   r   zfacebook/wav2vec2-base-960hi$  i   z['MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'g=
ףpJ@zsuperb/wav2vec2-base-superb-ksz'_unknown_'g)\(@zanton-l/wav2vec2-base-superb-sdzanton-l/wav2vec2-base-superb-svg\(\?zfacebook/wav2vec2-large-960hz!facebook/wav2vec2-large-960h-lv60z&facebook/wav2vec2-large-960h-lv60-selfc                   @   s   e Zd ZU dZdZeej ed< dZ	ejed< dZ
ejed< dZejed< dZeeej  ed< dZeeej  ed< dZeej ed	< dZeej ed
< dS )Wav2Vec2ForPreTrainingOutputa1	  
    Output type of [`Wav2Vec2ForPreTraining`], with potential hidden states and attentions.

    Args:
        loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
            paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
        projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
            Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
            projected quantized states.
        projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
            Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
            target vectors for contrastive loss.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
            The contrastive loss (L_m) as stated in the [official paper](https://arxiv.org/pdf/2006.11477.pdf) .
        diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
            The diversity loss (L_d) as stated in the [official paper](https://arxiv.org/pdf/2006.11477.pdf) .
    Nlossprojected_statesprojected_quantized_statescodevector_perplexityhidden_states
attentionscontrastive_lossdiversity_loss)__name__
__module____qualname____doc__r    r   torchFloatTensor__annotations__r!   r"   r#   r$   r   r%   r&   r'    r/   r/   o/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/wav2vec2/modeling_wav2vec2.pyr   c   s   
r   )shape	mask_probmask_lengthattention_mask	min_masksreturnc                    s  | \}dk rt dkr6t d d dtjd   fdd}|dk	rt|d	  nfd
dt|D }tj	|ft
d}g }	|}
|
dkr|S |D ]v}||}tjjt|d  |dd}t|dkrd }n|d }t|tj|
| tjd| g}|	| qt|	}	t|	dddddf ||
f}	|	||
 }	tddddf }t|||
f||
 }|	| }	|	 d kr҈d |	|	d k< t||	dd	 |S )af  
    Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
    ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
    CPU as part of the preprocessing during training.

    Args:
        shape: The shape for which to compute masks. This should be of a tuple of size 2 where
               the first element is the batch size and the second element is the length of the axis to span.
        mask_prob:  The percentage of the whole axis (between 0 and 1) which will be masked. The number of
                    independently generated mask spans of length `mask_length` is computed by
                    `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
                    actual percentage will be smaller.
        mask_length: size of the mask
        min_masks: minimum number of masked spans
        attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
                        each batch dimension.
    r   z&`mask_length` has to be bigger than 0.zO`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: z and `sequence_length`: `c                    sX   t |     }t|}| kr2 }| d  |k rTt| d  d}|S )z;Given input length, compute how many spans should be maskedr   r   )intmax)input_lengthnum_masked_spanepsilonr3   r2   r5   sequence_lengthr/   r0   compute_num_masked_span   s    
z6_compute_mask_indices.<locals>.compute_num_masked_spanNc                    s   g | ]} qS r/   r/   .0_)r>   r/   r0   
<listcomp>   s     z)_compute_mask_indices.<locals>.<listcomp>dtyper   F)replace)
ValueErrornprandomranditemsumdetachtolistrangezerosboolchoicearangelenZconcatenateonesint32appendarraybroadcast_toreshaper9   Zput_along_axis)r1   r2   r3   r4   r5   
batch_sizer?   input_lengthsZspec_aug_maskZspec_aug_mask_idxsZmax_num_masked_spanr:   r;   Zspec_aug_mask_idxZdummy_mask_idxoffsetsr/   r<   r0   _compute_mask_indices   s`      

  r_   )features_shapenum_negativesmask_time_indicesc                 C   s   | \}}t |}t j|||ft jd}|dk	r:|tnt j| td}t|D ]}||  d }|||  }	t 	t |d dddf |d |f}
t j
jd||d |fd}|||
k  d7  < |	| || || < ||  || 7  < qP|S )z>
    Sample `num_negatives` vectors from feature vectors.
    )r1   rF   NrE   r   r   )size)rI   rT   rQ   rW   ZastyperR   rV   rP   rM   rZ   rJ   randint)r`   ra   rb   r\   r>   Zsequence_length_rangesampled_negative_indicesZ	batch_idxhighZmapped_masked_indicesZfeature_indicesZsampled_indicesr/   r/   r0   _sample_negative_indices  s    
*rg   c                       s&   e Zd Zd fdd	Zdd Z  ZS )Wav2Vec2NoLayerNormConvLayerr   c                    sj   t    |dkr |j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
t|j | _d S )Nr   r   kernel_sizestridebias)super__init__conv_dimin_conv_dimout_conv_dimr   Conv1dconv_kernelconv_stride	conv_biasconvr	   feat_extract_activation
activationselfconfiglayer_id	__class__r/   r0   rn   )  s    
z%Wav2Vec2NoLayerNormConvLayer.__init__c                 C   s   |  |}| |}|S N)rv   rx   rz   r$   r/   r/   r0   forward7  s    

z$Wav2Vec2NoLayerNormConvLayer.forward)r   r(   r)   r*   rn   r   __classcell__r/   r/   r}   r0   rh   (  s   rh   c                       s&   e Zd Zd fdd	Zdd Z  ZS )Wav2Vec2LayerNormConvLayerr   c                    s|   t    |dkr |j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
tj| jdd| _t|j | _d S )Nr   r   ri   T)Zelementwise_affine)rm   rn   ro   rp   rq   r   rr   rs   rt   ru   rv   	LayerNorm
layer_normr	   rw   rx   ry   r}   r/   r0   rn   >  s    
z#Wav2Vec2LayerNormConvLayer.__init__c                 C   s:   |  |}|dd}| |}|dd}| |}|S )Nr@   )rv   	transposer   rx   r   r/   r/   r0   r   M  s    


z"Wav2Vec2LayerNormConvLayer.forward)r   r   r/   r/   r}   r0   r   =  s   r   c                       s&   e Zd Zd fdd	Zdd Z  ZS )Wav2Vec2GroupNormConvLayerr   c                    s   t    |dkr |j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
t|j | _tj| j| jdd| _d S )Nr   r   ri   T)
num_groupsZnum_channelsZaffine)rm   rn   ro   rp   rq   r   rr   rs   rt   ru   rv   r	   rw   rx   	GroupNormr   ry   r}   r/   r0   rn   Y  s    
z#Wav2Vec2GroupNormConvLayer.__init__c                 C   s"   |  |}| |}| |}|S r   )rv   r   rx   r   r/   r/   r0   r   i  s    


z"Wav2Vec2GroupNormConvLayer.forward)r   r   r/   r/   r}   r0   r   X  s   r   c                       s$   e Zd Z fddZdd Z  ZS )Wav2Vec2PositionalConvEmbeddingc              	      s   t    tj|j|j|j|jd |jd| _tjj	}t
tjjdrNtjjj	}t rdd l}|jj| jjdd || jddd| _W 5 Q R X |j| | jj |j| | jj n|| jddd| _t|j| _t|j | _d S )Nr   )rj   paddinggroupsweight_normr   )Zmodifier_rankweight)namedim)rm   rn   r   rr   hidden_sizenum_conv_pos_embeddingsZnum_conv_pos_embedding_groupsrv   utilsr   hasattrZparametrizationsr
   	deepspeedzeroZGatheredParametersr   Zregister_external_parameterZweight_vZweight_gWav2Vec2SamePadLayerr   r	   rw   rx   )rz   r{   r   r   r}   r/   r0   rn   q  s(    

z(Wav2Vec2PositionalConvEmbedding.__init__c                 C   s:   | dd}| |}| |}| |}| dd}|S Nr   r   )r   rv   r   rx   r   r/   r/   r0   r     s    


z'Wav2Vec2PositionalConvEmbedding.forwardr   r/   r/   r}   r0   r   p  s   r   c                       s$   e Zd Z fddZdd Z  ZS )r   c                    s$   t    |d dkrdnd| _d S )Nr   r   r   )rm   rn   num_pad_remove)rz   r   r}   r/   r0   rn     s    
zWav2Vec2SamePadLayer.__init__c                 C   s,   | j dkr(|d d d d d | j  f }|S )Nr   )r   r   r/   r/   r0   r     s    
zWav2Vec2SamePadLayer.forwardr   r/   r/   r}   r0   r     s   r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )Wav2Vec2FeatureEncoderz.Construct the features from raw audio waveformc                    s   t     jdkr@t ddg fddt jd D  }n6 jdkrd fddt jD }ntd	 j d
t|| _	d| _
d| _d S )Ngroupr   r|   c                    s   g | ]}t  |d  dqS )r   r   )rh   rB   ir{   r/   r0   rD     s    z3Wav2Vec2FeatureEncoder.__init__.<locals>.<listcomp>r   layerc                    s   g | ]}t  |d qS )r   )r   r   r   r/   r0   rD     s    z`config.feat_extract_norm` is z), but has to be one of ['group', 'layer']FT)rm   rn   Zfeat_extract_normr   rP   Znum_feat_extract_layersrH   r   
ModuleListconv_layersgradient_checkpointing_requires_grad)rz   r{   r   r}   r   r0   rn     s    




zWav2Vec2FeatureEncoder.__init__c                 C   s   |   D ]
}d|_qd| _d S )NF)
parametersrequires_gradr   rz   paramr/   r/   r0   _freeze_parameters  s    z)Wav2Vec2FeatureEncoder._freeze_parametersc                 C   sj   |d d d f }| j r"| jr"d|_| jD ]<}| j r\| jr\| jr\dd }tjj|||}q(||}q(|S )NTc                    s    fdd}|S )Nc                     s    |  S r   r/   inputsmoduler/   r0   custom_forward  s    zUWav2Vec2FeatureEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr/   r   r   r/   r   r0   create_custom_forward  s    z=Wav2Vec2FeatureEncoder.forward.<locals>.create_custom_forward)r   trainingr   r   r   r,   r   
checkpoint)rz   input_valuesr$   Z
conv_layerr   r/   r/   r0   r     s    

zWav2Vec2FeatureEncoder.forward)r(   r)   r*   r+   rn   r   r   r   r/   r/   r}   r0   r     s   r   c                       s   e Zd Z fddZ  ZS )Wav2Vec2FeatureExtractorc                    s8   t  | td| jj d| jjd j dt d S )NzThe class `zD` has been depreciated and will be removed in Transformers v5. Use `r   z
` instead.)rm   rn   warningswarnr~   r(   	__bases__FutureWarningrz   r{   r}   r/   r0   rn     s
    z!Wav2Vec2FeatureExtractor.__init__)r(   r)   r*   rn   r   r/   r/   r}   r0   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )Wav2Vec2FeatureProjectionc                    sJ   t    tj|jd |jd| _t|jd |j| _	t
|j| _d S )Nr@   Zeps)rm   rn   r   r   ro   layer_norm_epsr   Linearr   
projectionDropoutZfeat_proj_dropoutdropoutr   r}   r/   r0   rn     s    
z"Wav2Vec2FeatureProjection.__init__c                 C   s&   |  |}| |}| |}||fS r   )r   r   r   )rz   r$   Znorm_hidden_statesr/   r/   r0   r     s    


z!Wav2Vec2FeatureProjection.forwardr   r/   r/   r}   r0   r     s   r   c                       s   e Zd ZdZdeeeeed fddZej	eedd	d
Z
dej	eej	 eeej	  eej	 eej	 eeej	eej	 eeej	  f dddZ  ZS )Wav2Vec2Attentionz=Multi-headed attention from 'Attention Is All You Need' paper        FT)	embed_dim	num_headsr   
is_decoderrl   c                    s   t    || _|| _|| _|| | _| j| | jkrNtd| j d| d| jd | _|| _t	j
|||d| _t	j
|||d| _t	j
|||d| _t	j
|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      )rl   )rm   rn   r   r   r   head_dimrH   scalingr   r   r   k_projv_projq_projout_proj)rz   r   r   r   r   rl   r}   r/   r0   rn     s    

zWav2Vec2Attention.__init__)tensorseq_lenbszc                 C   s    | ||| j| jdd S r   )viewr   r   r   
contiguous)rz   r   r   r   r/   r/   r0   _shape  s    zWav2Vec2Attention._shapeN)r$   key_value_statespast_key_valuer4   layer_head_maskoutput_attentionsr6   c                 C   sx  |dk	}|  \}}	}
| || j }|r\|dk	r\|d jd |jd kr\|d }|d }n|r| | |d|}| | |d|}n|dk	r| | |d|}| | |d|}tj|d |gdd}tj|d |gdd}n(| | |d|}| | |d|}| j	r ||f}|| j
 d| jf}| ||	|j| }|j| }|j| }| d}t||dd}|  || j
 |	|fkrtd|| j
 |	|f d|   |dk	r |  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|dk	r|  | j
fkrhtd
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|r||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkr4td|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )z#Input shape: Batch x Time x ChannelNr   r   r   r@   r   z$Attention weights should be of size z	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size )pr   z `attn_output` should be of size )rc   r   r   r1   r   r   r   r,   catr   r   r   r   r[   Zbmmr   rH   r   
functionalsoftmaxr   r   r   r   )rz   r$   r   r   r4   r   r   Zis_cross_attentionr   Ztgt_lenrC   Zquery_statesZ
key_statesZvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr/   r/   r0   r     s~    





" 
zWav2Vec2Attention.forward)r   FT)NNNNF)r(   r)   r*   r+   r8   floatrR   rn   r,   Tensorr   r   r   r   r   r/   r/   r}   r0   r     s4           r   c                       s$   e Zd Z fddZdd Z  ZS )Wav2Vec2FeedForwardc                    sp   t    t|j| _t|j|j| _	t
|jtrDt|j | _n|j| _t|j|j| _t|j| _d S r   )rm   rn   r   r   Zactivation_dropoutintermediate_dropoutr   r   Zintermediate_sizeintermediate_dense
isinstanceZ
hidden_actstrr	   intermediate_act_fnoutput_densehidden_dropoutoutput_dropoutr   r}   r/   r0   rn     s    
zWav2Vec2FeedForward.__init__c                 C   s6   |  |}| |}| |}| |}| |}|S r   )r   r   r   r   r   r   r/   r/   r0   r     s    




zWav2Vec2FeedForward.forwardr   r/   r/   r}   r0   r     s   r   c                       s&   e Zd Z fddZdddZ  ZS )Wav2Vec2EncoderLayerc                    sf   t    t|j|j|jdd| _t|j	| _
tj|j|jd| _t|| _tj|j|jd| _d S )NFr   r   r   r   r   )rm   rn   r   r   num_attention_headsattention_dropout	attentionr   r   r   r   r   r   r   r   feed_forwardfinal_layer_normr   r}   r/   r0   rn     s    

zWav2Vec2EncoderLayer.__init__NFc                 C   sf   |}| j |||d\}}}| |}|| }| |}|| | }| |}|f}|rb||f7 }|S Nr4   r   )r   r   r   r   r   rz   r$   r4   r   Zattn_residualr   rC   outputsr/   r/   r0   r     s      



zWav2Vec2EncoderLayer.forward)NFr   r/   r/   r}   r0   r     s   r   c                       s8   e Zd Z fddZdejeej edddZ  Z	S )	#Wav2Vec2EncoderLayerStableLayerNormc                    s   t    t|j|j|jdd| _t|j	| _
tj|j|jd| _t|| _tj|j|jd| _t|dd d k	r~t|| _nd | _d S )NFr   r   adapter_attn_dim)rm   rn   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   getattrWav2Vec2AttnAdapterLayeradapter_layerr   r}   r/   r0   rn     s    

z,Wav2Vec2EncoderLayerStableLayerNorm.__init__NF)r$   r4   r   c                 C   sz   |}|  |}| j|||d\}}}| |}|| }|| | | }| jd k	rb|| | }|f}|rv||f7 }|S r   )r   r   r   r   r   r   r   r/   r/   r0   r     s     
  


z+Wav2Vec2EncoderLayerStableLayerNorm.forward)NF)
r(   r)   r*   rn   r,   r   r   rR   r   r   r/   r/   r}   r0   r     s     r   c                       s<   e Zd Z fddZd	ejeej eeedddZ	  Z
S )
Wav2Vec2Encoderc                    sf   t     | _t | _tj j jd| _	t
 j| _t fddt jD | _d| _d S )Nr   c                    s   g | ]}t  qS r/   )r   rA   r   r/   r0   rD     s     z,Wav2Vec2Encoder.__init__.<locals>.<listcomp>Frm   rn   r{   r   pos_conv_embedr   r   r   r   r   r   r   r   r   rP   num_hidden_layerslayersr   r   r}   r   r0   rn     s    

 zWav2Vec2Encoder.__init__NFT)r$   r4   r   output_hidden_statesreturn_dictc                    s  |rdnd } rdnd }|d k	r| ddd|jd }d|| < d|d d d d d d f j|jd }|t|jj }||jd d|jd |jd }| 	|}	||	 }| 
|}| |}t }
| jD ]}|r||f }tg }| jr|| jjk rdnd	}|r|
r`| jrJ| jrJ fd
d}tjj||||}n||| d}|d }|rjd} r||d f }q|r||f }|stdd |||fD S t|||dS )Nr/   r@   r   r   r         ?rE   TFc                    s    fdd}|S )Nc                     s    | f S r   r/   r   r   r   r/   r0   r   (  s    zNWav2Vec2Encoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr/   r   r   r   r0   r   '  s    z6Wav2Vec2Encoder.forward.<locals>.create_custom_forwardr   NNc                 s   s   | ]}|d k	r|V  qd S r   r/   rB   vr/   r/   r0   	<genexpr>B  s      z*Wav2Vec2Encoder.forward.<locals>.<genexpr>last_hidden_stater$   r%   )	unsqueezerepeatr1   torF   r,   finfominexpandr   r   r   r
   r   rK   r   r{   	layerdropr   r   r   tupler   rz   r$   r4   r   r   r   Zall_hidden_statesZall_self_attentionsZexpand_attention_maskZposition_embeddingsZdeepspeed_zero3_is_enabledr   Zdropout_probabilityZskip_the_layerr   Zlayer_outputsr/   r  r0   r     sd    
&   





  
zWav2Vec2Encoder.forward)NFFT)r(   r)   r*   rn   r,   r   r   r   rR   r   r   r/   r/   r}   r0   r     s       r   c                       s&   e Zd Z fddZdddZ  ZS )	Wav2Vec2EncoderStableLayerNormc                    sf   t     | _t | _tj j jd| _	t
 j| _t fddt jD | _d| _d S )Nr   c                    s   g | ]}t  qS r/   )r   rA   r   r/   r0   rD   R  s     z;Wav2Vec2EncoderStableLayerNorm.__init__.<locals>.<listcomp>Fr   r   r}   r   r0   rn   K  s    

z'Wav2Vec2EncoderStableLayerNorm.__init__NFTc                    s  |rdnd } rdnd }|d k	r| ddd|jd }d|| < d|d d d d d d f j|jd }|t|jj }||jd d|jd |jd }| 	|}	||	 }| 
|}t }
| jD ]}|r||f }tg }| jr|| jjk rdnd	}|r|
rR| jr<| jr< fd
d}tjj||||}n||| d}|d }|r\d} r||d f }q| |}|r||f }|stdd |||fD S t|||dS )Nr/   r@   r   r   r   r   rE   TFc                    s    fdd}|S )Nc                     s    | f S r   r/   r   r  r/   r0   r     s    z]Wav2Vec2EncoderStableLayerNorm.forward.<locals>.create_custom_forward.<locals>.custom_forwardr/   r   r  r   r0   r     s    zEWav2Vec2EncoderStableLayerNorm.forward.<locals>.create_custom_forwardr   r  c                 s   s   | ]}|d k	r|V  qd S r   r/   r  r/   r/   r0   r    s      z9Wav2Vec2EncoderStableLayerNorm.forward.<locals>.<genexpr>r  )r	  r
  r1   r  rF   r,   r  r  r  r   r   r
   r   rK   r   r{   r  r   r   r   r   r  r   r  r/   r  r0   r   V  sd    
&   




  

z&Wav2Vec2EncoderStableLayerNorm.forward)NFFTr   r/   r/   r}   r0   r  J  s       r  c                       s8   e Zd ZdZ fddZed	ddZd
ddZ  ZS )Wav2Vec2GumbelVectorQuantizerz
    Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
    GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.
    c                    s   t    |j| _|j| _|j| j dkrDtd|j d| j dt	t
d| j| j |j| j | _t|jd | j| j | _d| _d S )Nr   z`config.codevector_dim z5 must be divisible by `config.num_codevector_groups` z for concatenationr   r@   r   )rm   rn   num_codevector_groupsr   num_codevectors_per_groupnum_varscodevector_dimrH   r   	Parameterr,   r-   codevectorsr   ro   weight_projtemperaturer   r}   r/   r0   rn     s    
z&Wav2Vec2GumbelVectorQuantizer.__init__Nc                 C   s   |d k	rP|  d d d d f | j}t|| t| } | jdd|  }n| jdd}ttj|t	|d  dd  }|S )Nr   r   gHz>r@   )
flattenr  r1   r,   whereZ
zeros_likerM   meanexplog)ZprobsmaskZmask_extendedZmarginal_probs
perplexityr/   r/   r0   _compute_perplexity  s    (z1Wav2Vec2GumbelVectorQuantizer._compute_perplexityc                 C   s  |j \}}}| |}||| | j d}| jrtjj| | j	dd
|}tj||| | jd dd}| ||}nJ|jdd}	||j d|	ddd}||| | jd}| ||}||| d}|d| j }
|
|| | j| jd}|d||d}||fS )Nr@   T)tauhardr   r   r   r   )r1   r  r   r   r   r   r   Zgumbel_softmaxr   r  type_asr,   r   r#  argmaxZ	new_zerosZscatter_r	  r  r  rM   )rz   r$   rb   r\   r>   r   Zcodevector_probsZcodevector_soft_distr"  Zcodevector_idxZcodevectors_per_groupr  r/   r/   r0   r     s:    
    
 z%Wav2Vec2GumbelVectorQuantizer.forward)N)N)	r(   r)   r*   r+   rn   staticmethodr#  r   r   r/   r/   r}   r0   r    s
   r  c                       s$   e Zd Z fddZdd Z  ZS )Wav2Vec2Adapterc                    sp   t     j jkr8t j j| _t j| _nd  | _| _t	 fddt
 jD | _ j| _d S )Nc                 3   s   | ]}t  V  qd S r   )Wav2Vec2AdapterLayerrA   r   r/   r0   r    s     z+Wav2Vec2Adapter.__init__.<locals>.<genexpr>)rm   rn   output_hidden_sizer   r   r   projr   proj_layer_normr   rP   num_adapter_layersr   r  r   r}   r   r0   rn     s    
 zWav2Vec2Adapter.__init__c                 C   sr   | j d k	r(| jd k	r(|  |}| |}|dd}| jD ]&}tj }| jrX|| jkr:||}q:|dd}|S r   )r,  r-  r   r   rI   rJ   r   r  )rz   r$   r   Zlayerdrop_probr/   r/   r0   r     s    




zWav2Vec2Adapter.forwardr   r/   r/   r}   r0   r)    s   r)  c                       s$   e Zd Z fddZdd Z  ZS )r*  c                    s0   t    tj|jd|j |j|jdd| _d S )Nr   r   )rk   r   )rm   rn   r   rr   r+  Zadapter_kernel_sizeadapter_striderv   r   r}   r/   r0   rn     s    
zWav2Vec2AdapterLayer.__init__c                 C   s   |  |}tjj|dd}|S )Nr   r   )rv   r   r   Zglur   r/   r/   r0   r     s    
zWav2Vec2AdapterLayer.forwardr   r/   r/   r}   r0   r*    s   
r*  c                       s,   e Zd Z fddZejdddZ  ZS )r   c                    sZ   t    |j| _|j| _t| j| _t	| j| j| _
t | _t	| j| j| _dS )z
        Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
        up training throughput.
        N)rm   rn   r   	input_dimr   Z
hidden_dimr   r   normr   linear_1ReLUact_fnlinear_2r   r}   r/   r0   rn   #  s    

z!Wav2Vec2AttnAdapterLayer.__init__)r$   c                 C   s,   |  |}| |}| |}| |}|S r   )r1  r2  r4  r5  r   r/   r/   r0   r   1  s
    



z Wav2Vec2AttnAdapterLayer.forward)r(   r)   r*   rn   r,   r-   r   r   r/   r/   r}   r0   r   "  s   r   c                   @   s   e Zd ZdZeZdZdZdZdd Z	de
ejef ee dd	d
ZdeejdddZdddZdd Zdd ZdedddZdS )Wav2Vec2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    wav2vec2r   Tc              	   C   s  t |tr2|j  |j  d|j_d|j_nt |trp|jjj	j
ddd |jjj	  tj|j nlt |trtjj
|jjddtd|jjd |jj   d tj|jjd nt |trtd|jj }tjj|jj| |d tjj|jj| |d nt |tjrR|jj	j
d| jjd |jdk	r|jj	  nt |tjtjfr|jj	  |jj	 d	 nZt |tj!rtj"|j |jdk	rt|j#|j|jd   }tjj|j| |d dS )
zInitialize the weightsTr   r   )r  stdr   r   )abNr   )$r   Wav2Vec2ForPreTrainingproject_hidZreset_parameters	project_qZ_is_hf_initializedr  r  r   dataZnormal_rl   Zzero_r   inituniform_r  r   rv   mathsqrtrj   Zin_channelsZ	constant_r   r   Zin_featuresr   r{   Zinitializer_ranger   r   Zfill_rr   Zkaiming_normal_r   )rz   r   kr/   r/   r0   _init_weightsF  s@    




 z%Wav2Vec2PreTrainedModel._init_weightsN)r]   add_adapterc                 C   sn   |dkr| j jn|}dd }t| j j| j jD ]\}}||||}q.|rjt| j jD ]}||d| j j}qT|S )zH
        Computes the output length of the convolutional layers
        Nc                 S   s   t j| | |ddd S )Nfloor)Zrounding_moder   )r,   divr:   rj   rk   r/   r/   r0   _conv_out_lengthv  s    zRWav2Vec2PreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_lengthr   )r{   rE  ziprs   rt   rP   r.  r/  )rz   r]   rE  rI  rj   rk   rC   r/   r/   r0    _get_feat_extract_output_lengthsm  s    z8Wav2Vec2PreTrainedModel._get_feat_extract_output_lengths)feature_vector_lengthr4   c                 C   s   |j ddd d df }| j||d}|tj}|jd }tj||f|j|jd}d|tj	|jd |jd|d f< |
dg d
dg }|S )Nr@   r   rE  r   )rF   devicer   )rN  )ZcumsumrK  r  r,   longr1   rQ   rF   rN  rT   fliprR   )rz   rL  r4   rE  Znon_padded_lengthsZoutput_lengthsr\   r/   r/   r0   "_get_feature_vector_attention_mask  s    
  "z:Wav2Vec2PreTrainedModel._get_feature_vector_attention_maskFc                 C   s   t |tttfr||_d S r   )r   r   r  r   r   )rz   r   valuer/   r/   r0   _set_gradient_checkpointing  s    z3Wav2Vec2PreTrainedModel._set_gradient_checkpointingc                 C   s   | j jd krt| j di }|  D ]6\}}t|tr(| D ]\}}||d||g< qBq(t| t	r| j
 D ]\}}||dd|g< qt|S )NzF has no adapter layers. Make sure to define `config.adapter_attn_dim`..lm_head)r{   r   rH   r~   Znamed_modulesr   r   Znamed_parametersjoinWav2Vec2ForCTCrU  )rz   adapter_weightsr   r   
param_namer   r/   r/   r0   _get_adapters  s    

z%Wav2Vec2PreTrainedModel._get_adaptersc                 C   s<   |   D ]}t|tr| | qt| tr8| | j dS )zc
        (Re-)initialize attention adapter layers and lm head for adapter-only fine-tuning
        N)modulesr   r   rD  rW  rU  )rz   r   r/   r/   r0   init_adapter_layers  s
    

z+Wav2Vec2PreTrainedModel.init_adapter_layerstarget_langc                    s   | j jdkrtd| d|| jkr@|s@td| d dS |dd}|dd}|d	d}|d
d}|dd}|dd}	|dd}
|dd}|dt rdnd}|
dk	rt	dt
 |	dk	rtd|
}	| j j}d}|dk	rzt|}z&t|||||||	||d	}t|}W nT tk
rB   |r> Y n8 tk
rx   |rttd| d| d| dY nX |dkrt|}z,t|||||||	||d	}tj|dd}W nH tk
r    Y n2 tk
r   td| d| d| dY nX |   t| t   }t  t|  }t|dkrhtd| dd| dn*t|dkrtd| dd| d|d jd }|| j jkrtj| j j|| j| j d| _!|| j _ fdd |" D }| j#|dd! || _dS )"a  
        Load a language adapter model from a pre-trained adapter model.

        Parameters:
            target_lang (`str`):
                Has to be a language id of an existing adapter weight. Adapter weights are stored in the format
                adapter.<lang>.safetensors or adapter.<lang>.bin
            force_load (`bool`, defaults to `True`):
                Whether the weights shall be loaded even if `target_lang` matches `self.target_lang`.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            resume_download (`bool`, *optional*, defaults to `False`):
                Whether or not to delete incompletely received files. Will attempt to resume the download if such a
                file exists.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only(`bool`, *optional*, defaults to `False`):
                Whether or not to only look at local files (i.e., do not try to download the model).
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
                the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.

                <Tip>

                To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>".

                </Tip>

            mirror (`str`, *optional*):
                Mirror source to accelerate downloads in China. If you are from China and have an accessibility
                problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
                Please refer to the mirror site for more information.

        <Tip>

        Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to
        use this method in a firewalled environment.

        </Tip>

        Examples:

        ```python
        >>> from transformers import Wav2Vec2ForCTC, AutoProcessor

        >>> ckpt = "facebook/mms-1b-all"
        >>> processor = AutoProcessor.from_pretrained(ckpt)
        >>> model = Wav2Vec2ForCTC.from_pretrained(ckpt, target_lang="eng")
        >>> # set specific language
        >>> processor.tokenizer.set_target_lang("spa")
        >>> model.load_adapter("spa")
        ```
        NzCannot load_adapter for - if `config.adapter_attn_dim` is not defined.z#Adapter weights are already set to rT  	cache_dirforce_downloadFresume_downloadproxieslocal_files_onlytokenuse_auth_tokenrevisionuse_safetensorszVThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.zV`token` and `use_auth_token` are both specified. Please set only the argument `token`.)filenamera  rb  rc  rd  re  rg  r`  zCan't load the model for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z=' is the correct path to a directory containing a file named cpu)Zmap_locationr   zThe adapter weights z has unexpected keys: z, z has missing keys: zlm_head.weightrN  rF   c                    s    i | ]\}}||  | qS r/   )r  )rB   rC  r  rX  r/   r0   
<dictcomp>l  s      z8Wav2Vec2PreTrainedModel.load_adapter.<locals>.<dictcomp>)strict)$r{   r   rH   r^  loggerwarningpopr   r   r   r   Z_name_or_pathWAV2VEC2_ADAPTER_SAFE_FILEformatr   safe_load_fileEnvironmentError	ExceptionWAV2VEC2_ADAPTER_PT_FILEr,   loadrZ  setkeysrU   rV  r1   
vocab_sizer   r   r+  rN  rF   rU  itemsZload_state_dict)rz   r^  
force_loadkwargsr`  ra  rb  rc  rd  re  rf  rg  rh  Zmodel_path_or_idZ
state_dictfilepathZweight_pathZunexpected_keysZmissing_keysZtarget_vocab_sizer/   rl  r0   load_adapter  s    ? 





   z$Wav2Vec2PreTrainedModel.load_adapter)N)N)F)T)r(   r)   r*   r+   r   config_classZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingrD  r   r,   
LongTensorr8   r   rR   rK  rQ  rS  rZ  r\  r   r  r/   r/   r/   r0   r6  ;  s(   (    
r6  a  
    Wav2Vec2 was proposed in [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech
    Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael
    Auli.

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving etc.).

    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 ([`Wav2Vec2Config`]): 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_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
            Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
            into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install
            soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and
            conversion into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
        attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing convolution and 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)

            <Tip warning={true}>

            `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask ==
            True`. For all models whose processor has `config.return_attention_mask == False`, such as
            [wav2vec2-base](https://huggingface.co/facebook/wav2vec2-base-960h), `attention_mask` should **not** be
            passed to avoid degraded performance when doing batched inference. For such models `input_values` should
            simply be padded with 0 and passed without `attention_mask`. Be aware that these models also yield slightly
            different results depending on whether `input_values` is padded or not.

            </Tip>

        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 [`~utils.ModelOutput`] instead of a plain tuple.
zbThe bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zed fddZdd Zdd Zdeje	ej e	ej
 d	d
dZeeeeeededde	ej e	ej e	ej e	e e	e e	e eeef dddZ  ZS )Wav2Vec2Modelr   c                    s   t  | || _t|| _t|| _|jdks:|jdkrRt	
t|j | _|jrdt|| _n
t|| _|jr|t|nd | _|   d S )Nr   )rm   rn   r{   r   feature_extractorr   feature_projectionmask_time_probmask_feature_probr   r  r,   r-   r   r@  masked_spec_embedZdo_stable_layer_normr  encoderr   rE  r)  adapter	post_initr   r}   r/   r0   rn     s    


zWav2Vec2Model.__init__c                 C   s   t dt |   dS z
        Calling this function will disable the gradient computation for the feature encoder so that its parameters will
        not be updated during training.
        The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.Please use the equivalent `freeze_feature_encoder` method instead.Nr   r   r   freeze_feature_encoderrz   r/   r/   r0   freeze_feature_extractor  s
    z&Wav2Vec2Model.freeze_feature_extractorc                 C   s   | j   dS 
        Calling this function will disable the gradient computation for the feature encoder so that its parameter will
        not be updated during training.
        N)r  r   r  r/   r/   r0   r    s    z$Wav2Vec2Model.freeze_feature_encoderN)r$   rb   r4   c                 C   s  t | jdds|S | \}}}|dk	r<| j|j||< nZ| jjdkr| jrt||f| jj| jj	|| jj
d}tj||jtjd}| j|j||< | jjdkr| jrt||f| jj| jj| jjd}tj||jtjd}|dddf d|d}d||< |S )	z
        Masks extracted features along time axis and/or along feature axis according to
        [SpecAugment](https://arxiv.org/abs/1904.08779).
        Zapply_spec_augmentTNr   )r2   r3   r4   r5   rk  )r2   r3   r5   r@   )r   r{   rc   r  r  rF   r  r   r_   Zmask_time_lengthZmask_time_min_masksr,   r   rN  rR   r  Zmask_feature_lengthZmask_feature_min_masksr  )rz   r$   rb   r4   r\   r>   r   Zmask_feature_indicesr/   r/   r0   _mask_hidden_states  s4    z!Wav2Vec2Model._mask_hidden_statesaudior   output_typer  modalityexpected_output)r   r4   rb   r   r   r   r6   c           
      C   s   |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}| |}|dd}|d k	rp| j|jd |dd}| |\}}| j	|||d}| j
|||||d}	|	d }| jd k	r| |}|s||f|	dd   S t|||	j|	jdS )	Nr   r   FrM  )rb   r4   r4   r   r   r   r   )r  extract_featuresr$   r%   )r{   r   r   use_return_dictr  r   rQ  r1   r  r  r  r  r   r$   r%   )
rz   r   r4   rb   r   r   r   r  r$   Zencoder_outputsr/   r/   r0   r     sH    
    

zWav2Vec2Model.forward)NN)NNNNN)r(   r)   r*   r   rn   r  r  r,   r-   r   r  r  r   WAV_2_VEC_2_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   rR   r   r   r   r   r/   r/   r}   r0   r    s@   
  .
     
r  z5Wav2Vec2 Model with a quantizer and `VQ` head on top.c                       s   e Zd Zed fddZedddZdd Zd	d
 Ze	de
je
je
jedddZeeeeeddee
j ee
j ee
j ee
j ee ee ee eeef dddZ  ZS )r;  r   c                    s^   t  | t|| _t|j| _t|| _	t
|j|j| _t
|j|j| _|   d S r   )rm   rn   r  r7  r   r   Zfeat_quantizer_dropoutdropout_featuresr  	quantizerr   r   Zproj_codevector_dimr<  r  r=  r  r   r}   r/   r0   rn   E  s    

zWav2Vec2ForPreTraining.__init__)r  c                 C   s   || j _dS )zb
        Set the Gumbel softmax temperature to a given value. Only necessary for training
        N)r  r  )rz   r  r/   r/   r0   set_gumbel_temperatureR  s    z-Wav2Vec2ForPreTraining.set_gumbel_temperaturec                 C   s   t dt |   dS r  r  r  r/   r/   r0   r  X  s
    z/Wav2Vec2ForPreTraining.freeze_feature_extractorc                 C   s   | j j  dS r  r7  r  r   r  r/   r/   r0   r  d  s    z-Wav2Vec2ForPreTraining.freeze_feature_encoder皙?)target_featuresnegative_featurespredicted_featuresr  c                 C   s<   t j| |gdd} t j| |  dd| }|| }|S )z
        Compute logits for contrastive loss based using cosine similarity as the distance measure between
        `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
        r   r   r@   )r,   r   Zcosine_similarityr   r&  )r  r  r  r  logitsr/   r/   r0   compute_contrastive_logitsk  s    z1Wav2Vec2ForPreTraining.compute_contrastive_logits)r  r  N)r   r4   rb   re   r   r   r   r6   c              
   C   s  |dk	r|n| j j}|dk	r(|tj}| j||||||d}| |d }	| |d }
|dk	rx| j|
j	d |dd}| j
|
|d\}}| |}d } }}|dk	r|j	\}}}|d|| d }|||d|d	ddd
}| |dddf ||	| j j}||kd}| r8td|dd |< |dd	d|d}d|  d dd }tjj| |dd}| j j| j j }|| | |  }|| j j|  }|s|dk	r||	||f|d	d  S |	||f|d	d  S t||	|||j |j!||dS )a  
        mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
            masked extracted features in *config.proj_codevector_dim* space.
        sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
            Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
            Required input for pre-training.

        Returns:

        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoFeatureExtractor, Wav2Vec2ForPreTraining
        >>> from transformers.models.wav2vec2.modeling_wav2vec2 import _compute_mask_indices, _sample_negative_indices
        >>> from datasets import load_dataset

        >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
        >>> model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base")

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> input_values = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt").input_values  # Batch size 1

        >>> # compute masked indices
        >>> batch_size, raw_sequence_length = input_values.shape
        >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length).item()
        >>> mask_time_indices = _compute_mask_indices(
        ...     shape=(batch_size, sequence_length), mask_prob=0.2, mask_length=2
        ... )
        >>> sampled_negative_indices = _sample_negative_indices(
        ...     features_shape=(batch_size, sequence_length),
        ...     num_negatives=model.config.num_negatives,
        ...     mask_time_indices=mask_time_indices,
        ... )
        >>> mask_time_indices = torch.tensor(data=mask_time_indices, device=input_values.device, dtype=torch.long)
        >>> sampled_negative_indices = torch.tensor(
        ...     data=sampled_negative_indices, device=input_values.device, dtype=torch.long
        ... )

        >>> with torch.no_grad():
        ...     outputs = model(input_values, mask_time_indices=mask_time_indices)

        >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)
        >>> cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)

        >>> # show that cosine similarity is much higher than random
        >>> cosine_sim[mask_time_indices.to(torch.bool)].mean() > 0.5
        tensor(True)

        >>> # for contrastive loss training model should be put into train mode
        >>> model = model.train()
        >>> loss = model(
        ...     input_values, mask_time_indices=mask_time_indices, sampled_negative_indices=sampled_negative_indices
        ... ).loss
        ```N)r4   r   r   rb   r   r   r   FrM  )rb   r@   r   r   z-infirM   )	reduction)r    r!   r"   r#   r$   r%   r&   r'   )"r{   r  r  r,   rR   r7  r<  r  rQ  r1   r  r=  r   rO  Zpermuter  Zcontrastive_logits_temperatureallanyr   r   r[   rc   r  r   r   Zcross_entropyr  r  rM   Zdiversity_loss_weightr   r$   r%   )rz   r   r4   rb   re   r   r   r   r   Ztransformer_featuresr  Zquantized_featuresr#   r    r&   r'   r\   r>   r   Znegative_quantized_featuresr  Z
neg_is_postargetZnum_codevectorsr/   r/   r0   r     s    E
   



      	

zWav2Vec2ForPreTraining.forward)r  )NNNNNN)r(   r)   r*   r   rn   r8   r  r  r  r(  r,   r-   r  r   r  r   r   r  r   r   Z
BoolTensorrR   r   r   r   r   r/   r/   r}   r0   r;  C  s<    
      
r;  z6Wav2Vec2 Model with a `language modeling` head on top.c                       sb   e Zd Z fddZeedejeej	 ee
 ee
 ee
 eej eeef dddZ  ZS )Wav2Vec2ForMaskedLMc                    sN   t  | tdt t|| _t|j	| _
t|j|j| _|   d S )NzSThe class `Wav2Vec2ForMaskedLM` is deprecated. Please use `Wav2Vec2ForCTC` instead.)rm   rn   r   r   r   r  r7  r   r   final_dropoutr   r   r   r{  rU  r  r   r}   r/   r0   rn   #  s     
zWav2Vec2ForMaskedLM.__init__Nr   r4   r   r   r   labelsr6   c                 C   sn   |d k	r|n| j j}| j||||d}|d }| |}| |}	|s\|	f|dd   }
|
S t|	|j|jdS )N)r   r   r   r   r   )r  r$   r%   )r{   r  r7  r   rU  r   r$   r%   )rz   r   r4   r   r   r   r  r   r$   r  outputr/   r/   r0   r   1  s    


zWav2Vec2ForMaskedLM.forward)NNNNN)r(   r)   r*   rn   r   r  r,   r-   r   r  rR   r   r   r   r   r   r   r/   r/   r}   r0   r  !  s         
r  zfWav2Vec2 Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).c                       s   e Zd Zdee d fddZdd Zdd Zd	d
 Zdd Z	e
eeeeeeedd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 )rW  Nr]  c                    s~   t  | t|| _t|j| _|| _|j	d krFt
d| j dt|dr\|jr\|jn|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: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.rE  )rm   rn   r  r7  r   r   r  r   r^  r{  rH   r~   r   rE  r+  r   r   rU  r  )rz   r{   r^  r+  r}   r/   r0   rn   T  s    

zWav2Vec2ForCTC.__init__c                 C   sr   | j }|dk	r2t| jdddkr2td| dn<|dkrXt| jdddk	rXtd n|dk	rn| j|dd dS )a'  
        This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
        passing `target_lang=...` to `from_pretrained(...)`.

        This method is **not** supposed to be called by the user and is prone to be changed in the future.
        Nr   zCannot pass `target_lang`: r_  z)By default `target_lang` is set to 'eng'.T)r}  )r^  r   r{   rH   ro  infor  )rz   r^  r/   r/   r0   tie_weightsk  s    zWav2Vec2ForCTC.tie_weightsc                 C   s   t dt |   dS r  r  Nr  r  r/   r/   r0   r    s
    z'Wav2Vec2ForCTC.freeze_feature_extractorc                 C   s   | j j  dS r  r  r  r/   r/   r0   r    s    z%Wav2Vec2ForCTC.freeze_feature_encoderc                 C   s   | j  D ]
}d|_q
dS z
        Calling this function will disable the gradient computation for the base model so that its parameters will not
        be updated during training. Only the classification head will be updated.
        FNr7  r   r   r   r/   r/   r0   freeze_base_model  s    z Wav2Vec2ForCTC.freeze_base_model)r   r  r  r  expected_lossr  c              
   C   sf  |dk	r|n| j j}| j|||||d}|d }| |}| |}	d}
|dk	r"| | j jkrttd| j j |dk	r|ntj	|tj
d}| |dtj
}|dk}|d}||}tjj|	dtjddd}tjjjd	d
, tjj||||| j j| j j| j jd}
W 5 Q R X |sR|	f|td  }|
dk	rN|
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: rE   r@   )r   rF   r   F)enabled)blankr  Zzero_infinityr    r  r$   r%   )r{   r  r7  r   rU  r9   r{  rH   r,   Z	ones_likerO  rK  rM   r  Zmasked_selectr   r   Zlog_softmaxZfloat32r   backendsZcudnnflagsZctc_lossZpad_token_idZctc_loss_reductionZctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   r$   r%   )rz   r   r4   r   r   r   r  r   r$   r  r    r]   Zlabels_maskZtarget_lengthsZflattened_targetsZ	log_probsr  r/   r/   r0   r     sR    





   zWav2Vec2ForCTC.forward)N)NNNNN)r(   r)   r*   r   r   rn   r  r  r  r  r   r  r   r  r   r  _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr,   r   rR   r   r   r   r   r/   r/   r}   r0   rW  O  s6   
     
rW  z
    Wav2Vec2 Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
    SUPERB Keyword Spotting.
    c                       s   e Zd Z fddZdd Zdd Zdd Zeee	e
eed	eed
d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 )!Wav2Vec2ForSequenceClassificationc                    s   t  | t|dr$|jr$tdt|| _|jd }|jrTt	
t|| | _t	|j|j| _t	|j|j| _|   d S )NrE  z_Sequence classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)r   )rm   rn   r   rE  rH   r  r7  r   use_weighted_layer_sumr   r  r,   rV   layer_weightsr   r   Zclassifier_proj_size	projector
num_labels
classifierr  rz   r{   
num_layersr}   r/   r0   rn     s    

z*Wav2Vec2ForSequenceClassification.__init__c                 C   s   t dt |   dS r  r  r  r/   r/   r0   r    s
    z:Wav2Vec2ForSequenceClassification.freeze_feature_extractorc                 C   s   | j j  dS r  r  r  r/   r/   r0   r    s    z8Wav2Vec2ForSequenceClassification.freeze_feature_encoderc                 C   s   | j  D ]
}d|_q
dS r  r  r   r/   r/   r0   r    s    z3Wav2Vec2ForSequenceClassification.freeze_base_modelr  )r   r  r  r  r  r  Nr  c                 C   sf  |dk	r|n| j j}| j jr dn|}| j|||||d}| j jr|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}|dkr|jdd}
n<| |jd |}d|| < |jdd|jdddd }
| |
}d}|dk	r"t }||d| j j|d}|sR|f|td  }|dk	rN|f| S |S t|||j|jd	S )
  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NTr  r   r   r@   r   r   r  )r{   r  r  r7  r  r,   stackr   r   r   r  r   rM   r  r  rQ  r1   r  r   r  r   r$   r%   )rz   r   r4   r   r   r   r  r   r$   norm_weightsZpooled_outputZpadding_maskr  r    loss_fctr  r/   r/   r0   r     sF    

 

z)Wav2Vec2ForSequenceClassification.forward)NNNNN)r(   r)   r*   rn   r  r  r  r   r  r   _SEQ_CLASS_CHECKPOINTr   r  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r,   r   rR   r   r   r   r   r/   r/   r}   r0   r    s6        
r  zd
    Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.
    c                       s   e Zd Z fddZdd Zdd Zdd Zeee	e
eed	ed
deej eej eej ee ee ee eeef dddZ  ZS )#Wav2Vec2ForAudioFrameClassificationc                    sz   t  | t|dr$|jr$tdt|| _|jd }|jrTt	
t|| | _t	|j|j| _|j| _|   d S )NrE  zbAudio frame classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)r   )rm   rn   r   rE  rH   r  r7  r   r  r   r  r,   rV   r  r   r   r  r  init_weightsr  r}   r/   r0   rn   m  s    

z,Wav2Vec2ForAudioFrameClassification.__init__c                 C   s   t dt |   dS r  r  r  r/   r/   r0   r  }  s
    z<Wav2Vec2ForAudioFrameClassification.freeze_feature_extractorc                 C   s   | j j  dS r  r  r  r/   r/   r0   r    s    z:Wav2Vec2ForAudioFrameClassification.freeze_feature_encoderc                 C   s   | j  D ]
}d|_q
dS r  r  r   r/   r/   r0   r    s    z5Wav2Vec2ForAudioFrameClassification.freeze_base_modelr  r  N)r   r4   r  r   r   r   r6   c                 C   s   |dk	r|n| j j}| j jr dn|}| j|||||d}| j jr|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}
d}|dk	rt }||
d| jtj|d| jdd}|s|
f|td  }|S t||
|j|jd	S )
r  NTr  r   r   r@   r   )Zaxisr  )r{   r  r  r7  r  r,   r  r   r   r   r  r   rM   r  r   r  r'  r   r$   r%   )rz   r   r4   r  r   r   r   r   r$   r  r  r    r  r  r/   r/   r0   r     s:    
(z+Wav2Vec2ForAudioFrameClassification.forward)NNNNN)r(   r)   r*   rn   r  r  r  r   r  r   _FRAME_CLASS_CHECKPOINTr   r  _FRAME_EXPECTED_OUTPUTr   r,   r   rR   r   r   r   r   r/   r/   r}   r0   r  f  s4   
     
r  c                       s&   e Zd Zd fdd	Zdd Z  ZS )AMSoftmaxLoss      >@皙?c                    sF   t t|   || _|| _|| _tjt	||dd| _
t | _d S )NT)r   )rm   r  rn   scalemarginr  r   r  r,   Zrandnr   r   r    )rz   r0  r  r  r  r}   r/   r0   rn     s    zAMSoftmaxLoss.__init__c           	      C   sx   |  }tjj| jdd}tjj|dd}t||}|| j }tj|| j	}| j
t| || }| ||}|S )Nr   r   r   )r  r   r   	normalizer   r,   mmr  Zone_hotr  r  r  rR   r    )	rz   r$   r  r   Z	cos_thetapsiZonehotr  r    r/   r/   r0   r     s    
zAMSoftmaxLoss.forward)r  r  r   r/   r/   r}   r0   r    s   r  c                       s&   e Zd Zd fdd	Zdd Z  ZS )	TDNNLayerr   c                    sv   t    |dkr |j|d  n|j| | _|j| | _|j| | _|j| | _t	
| j| j | j| _t	 | _d S )Nr   r   )rm   rn   tdnn_dimrp   rq   tdnn_kernelrj   Ztdnn_dilationdilationr   r   kernelr3  rx   ry   r}   r/   r0   rn     s    
"zTDNNLayer.__init__c                 C   sV   | d}tjj|| j| jfd| jf| jdfd}|dd}| |}| 	|}|S )Nr   )rk   r  r   )
r	  r   r   Zunfoldrj   rp   r  r   r  rx   r   r/   r/   r0   r     s    



zTDNNLayer.forward)r   r   r/   r/   r}   r0   r    s   
r  zl
    Wav2Vec2 Model with an XVector feature extraction head on top for tasks like Speaker Verification.
    c                       s   e Zd Z fddZdd Zdd Zdd Zeej	e
f d	d
dZeeeeeededd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 )Wav2Vec2ForXVectorc                    s   t    t | _ jd } jr<tt	|| | _
t j jd | _ fddtt jD }t|| _t jd d  j| _t j j| _t j j| _|   d S )Nr   r   c                    s   g | ]}t  |qS r/   )r  r   r   r/   r0   rD   	  s     z/Wav2Vec2ForXVector.__init__.<locals>.<listcomp>r@   r   )rm   rn   r  r7  r   r  r   r  r,   rV   r  r   r   r  r  rP   rU   r   tdnnZxvector_output_dimr  r  r  r  	objectiver  )rz   r{   r  Ztdnn_layersr}   r   r0   rn   	  s    

zWav2Vec2ForXVector.__init__c                 C   s   t dt |   dS r  r  r  r/   r/   r0   r  !	  s
    z+Wav2Vec2ForXVector.freeze_feature_extractorc                 C   s   | j j  dS r  r  r  r/   r/   r0   r  -	  s    z)Wav2Vec2ForXVector.freeze_feature_encoderc                 C   s   | j  D ]
}d|_q
dS r  r  r   r/   r/   r0   r  4	  s    z$Wav2Vec2ForXVector.freeze_base_model)r]   c                 C   s&   dd }| j jD ]}|||d}q|S )z?
        Computes the output length of the TDNN layers
        c                 S   s   | | | d S )Nr   r/   rH  r/   r/   r0   rI  A	  s    zEWav2Vec2ForXVector._get_tdnn_output_lengths.<locals>._conv_out_lengthr   )r{   r  )rz   r]   rI  rj   r/   r/   r0   _get_tdnn_output_lengths<	  s    z+Wav2Vec2ForXVector._get_tdnn_output_lengthsr  r  Nr  c                 C   s  |dk	r|n| j j}| j jr dn|}| j|||||d}| j jr|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}| jD ]}
|
|}q|dkr|jdd}|jdd}n| |jdd}| |}g }g }t|D ]D\}}|||d|f jdd |||d|f jdd qt|}t|}tj||gdd}| |}| |}d}|dk	r| ||}|s||f|td  }|dk	r|f| S |S t||||j|jdS )	r  NTr  r   r   r@   r   )r    r  Z
embeddingsr$   r%   )r{   r  r  r7  r  r,   r  r   r   r   r  r   rM   r  r  r  r8  rK  r  	enumeraterX   r   r  r  r  r   r$   r%   )rz   r   r4   r   r   r   r  r   r$   r  Z
tdnn_layerZmean_featuresZstd_featuresZfeat_extract_output_lengthsZtdnn_output_lengthsr   lengthZstatistic_poolingZoutput_embeddingsr  r    r  r/   r/   r0   r   K	  s\    



 




zWav2Vec2ForXVector.forward)NNNNN)r(   r)   r*   rn   r  r  r  r   r,   r  r8   r  r   r  r   _XVECTOR_CHECKPOINTr   r  _XVECTOR_EXPECTED_OUTPUTr   r   rR   r   r   r   r/   r/   r}   r0   r  	  s6   
     
r  )Nr   )N)er+   rA  r   dataclassesr   typingr   r   r   numpyrI   r,   Ztorch.utils.checkpointr   Ztorch.nnr   Zactivationsr	   Zintegrations.deepspeedr
   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   r   r   r   r   r   r   r   r   r   Zconfiguration_wav2vec2r   rw  rr  Zsafetensors.torchr   rt  Z
get_loggerr(   ro  r  r  r  r  r  r  r  r  r  r  r  r  r  Z)WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LISTr   r8   r   r  Zndarrayr_   rg   Modulerh   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r)  r*  r   r6  ZWAV_2_VEC_2_START_DOCSTRINGr  r  r;  r  rW  r  r  r  r  r  r/   r/   r/   r0   <module>   s   $	(


	-  
x   $'5 "-W[L  :&  ^- tj