o
    Zh                    @   s  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 ddlmZ dd	lmZmZ dd
l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! ddl"m#Z# e roddlm$Z$ e!%e&Z'G dd de	j(Z)G dd de	j(Z*G dd de	j(Z+G dd de	j(Z,G dd de	j(Z-G dd de	j(Z.G dd de	j(Z/G dd de/Z0G d d! d!e/Z1G d"d# d#e	j(Z2e/e1e0d$Z3G d%d& d&e	j(Z4G d'd( d(e	j(Z5G d)d* d*e	j(Z6G d+d, d,e	j(Z7eG d-d. d.eZ8		 dKd/ee9e9f d0e:d1e9d2eej; d3e9d4ej<fd5d6Z=eZ>eG d7d8 d8e8Z?d9Z@ed:d;G d<d= d=e8ZAed>d;G d?d@ d@e8ZBeG dAdB dBe8ZCG dCdD dDe	j(ZDG dEdF dFe	j(ZEedGd;G dHdI dIe8ZFg dJZGdS )L    N)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)is_fsdp_managed_module)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutputCausalLMOutputSequenceClassifierOutputTokenClassifierOutputWav2Vec2BaseModelOutputXVectorOutput)PreTrainedModel)auto_docstringis_peft_availablelogging   )Data2VecAudioConfig)_flash_attention_forwardc                       s&   e Zd Zd fdd	Zdd Z  ZS )Data2VecAudioConvLayerr   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   )kernel_sizestridebiasTZelementwise_affine)super__init__conv_dimin_conv_dimout_conv_dimr   Conv1dconv_kernelconv_strideZ	conv_biasconv	LayerNorm
layer_normr   feat_extract_activation
activationselfconfiglayer_id	__class__ c/var/www/auris/lib/python3.10/site-packages/transformers/models/data2vec/modeling_data2vec_audio.pyr    )   s   
zData2VecAudioConvLayer.__init__c                 C   s:   |  |}|dd}| |}|dd}| |}|S )N)r'   	transposer)   r+   r-   hidden_statesr2   r2   r3   forward8   s   


zData2VecAudioConvLayer.forwardr   __name__
__module____qualname__r    r9   __classcell__r2   r2   r0   r3   r   (   s    r   c                       $   e Zd Z fddZdd Z  ZS )Data2VecAudioPadLayerc                    s*   t    |d dkrd| _d S d| _d S )N   r   r   )r   r    num_pad_remove)r-   num_conv_pos_embeddingsr0   r2   r3   r    D   s   
 zData2VecAudioPadLayer.__init__c                 C   s,   | j dkr|d d d d d | j  f }|S Nr   )rC   r7   r2   r2   r3   r9   H   s   
zData2VecAudioPadLayer.forwardr;   r2   r2   r0   r3   rA   C   s    rA   c                       r@   ) Data2VecAudioPositionalConvLayerc                    s\   t    tj|j|j|j|jd |jd| _t|j| _	t
|j | _tj|jdd| _d S )NrB   )r   paddinggroupsFr   )r   r    r   r$   hidden_sizeZconv_pos_kernel_sizeZnum_conv_pos_embedding_groupsr'   rA   rG   r   r*   r+   r(   r)   r-   r.   r0   r2   r3   r    O   s   
z)Data2VecAudioPositionalConvLayer.__init__c                 C   sD   |  |}| |}|dd}| |}|dd}| |}|S Nr   rB   )r'   rG   r6   r)   r+   r7   r2   r2   r3   r9   ^   s   



z(Data2VecAudioPositionalConvLayer.forwardr;   r2   r2   r0   r3   rF   N   s    rF   c                       r@   )$Data2VecAudioPositionalConvEmbeddingc                    s.   t    t fddt jD | _d S )Nc                       g | ]}t  qS r2   )rF   .0_r.   r2   r3   
<listcomp>m       zAData2VecAudioPositionalConvEmbedding.__init__.<locals>.<listcomp>)r   r    r   
ModuleListrangerD   layersrJ   r0   rQ   r3   r    j   s   

z-Data2VecAudioPositionalConvEmbedding.__init__c                 C   s0   | dd}| jD ]}||}q	| dd}|S rK   )r6   rV   )r-   r8   layerr2   r2   r3   r9   p   s
   

z,Data2VecAudioPositionalConvEmbedding.forwardr;   r2   r2   r0   r3   rL   i       rL   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )Data2VecAudioFeatureEncoderz.Construct the features from raw audio waveformc                    s:   t    t fddt jD | _d| _d| _d S )Nc                    s   g | ]}t  |d qS ))r/   )r   rO   irQ   r2   r3   rR   ~   s    z8Data2VecAudioFeatureEncoder.__init__.<locals>.<listcomp>FT)	r   r    r   rT   rU   Znum_feat_extract_layersconv_layersgradient_checkpointing_requires_gradrJ   r0   rQ   r3   r    {   s   

z$Data2VecAudioFeatureEncoder.__init__c                 C   s   |   D ]}d|_qd| _d S NF)
parametersrequires_gradr^   r-   paramr2   r2   r3   _freeze_parameters   s   
z.Data2VecAudioFeatureEncoder._freeze_parametersc                 C   s\   |d d d f }| j r| jrd|_| jD ]}| j r'| jr'| jr'| |j|}q||}q|S )NT)r^   trainingra   r\   r]   _gradient_checkpointing_func__call__)r-   input_valuesr8   Z
conv_layerr2   r2   r3   r9      s   

z#Data2VecAudioFeatureEncoder.forward)r<   r=   r>   __doc__r    rd   r9   r?   r2   r2   r0   r3   rY   x   s
    rY   c                       r@   )Data2VecAudioFeatureProjectionc                    sJ   t    tj|jd |jd| _t|jd |j| _	t
|j| _d S )Nr5   Zeps)r   r    r   r(   r!   layer_norm_epsr)   LinearrI   
projectionDropoutZfeat_proj_dropoutdropoutrJ   r0   r2   r3   r       s   
z'Data2VecAudioFeatureProjection.__init__c                 C   s&   |  |}| |}| |}||fS N)r)   rn   rp   )r-   r8   Znorm_hidden_statesr2   r2   r3   r9      s   


z&Data2VecAudioFeatureProjection.forwardr;   r2   r2   r0   r3   rj      rX   rj   c                       s   e Zd ZdZ					ddededed	ed
ededee f fddZ	de
jdedefddZ					dde
jdee
j deee
j  dee
j dee
j dedee
jee
j eee
j  f fddZ  ZS )Data2VecAudioAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsrp   
is_decoderr   	is_causalr.   c                    s   t    || _|| _|| _|| | _|| _| j| | jkr*t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      )r   )r   r    rt   ru   rp   head_dimr.   
ValueErrorscalingrv   rw   r   rm   k_projv_projq_projout_proj)r-   rt   ru   rp   rv   r   rw   r.   r0   r2   r3   r       s&   



zData2VecAudioAttention.__init__tensorseq_lenbszc                 C   s    | ||| j| jdd S rK   )viewru   rx   r6   
contiguousr-   r   r   r   r2   r2   r3   _shape   s    zData2VecAudioAttention._shaper8   key_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsreturnc                 C   sr  |du}|  \}}	}
| || j }|r.|dur.|d jd |jd kr.|d }|d }nZ|rE| | |d|}| | |d|}nC|durt| | |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ur|  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|durL|  | j
fkr1td
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|rc||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkrtd|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )#Input shape: Batch x Time x ChannelNr   rB   r   r5   dimz$Attention weights should be of size 	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size )pre    `attn_output` should be of size )sizer}   rz   shaper   r{   r|   torchcatrv   ru   rx   r   reshapeZbmmr6   ry   r   
functionalsoftmaxrp   re   rt   r~   )r-   r8   r   r   r   r   r   is_cross_attentionr   tgt_lenrP   query_states
key_statesvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr2   r2   r3   r9      s   





"

zData2VecAudioAttention.forward)rs   FTFNNNNNF)r<   r=   r>   ri   intfloatboolr   r   r    r   Tensorr   r   r9   r?   r2   r2   r0   r3   rr      sV    rr   c                       s   e Zd ZdZ fddZdejdedefddZ									
ddejde	ej de	e
ej  de	ej de	ej dede
eje	ej e	e
ej  f fddZ  ZS )Data2VecAudioFlashAttention2aV  
    Data2VecAudio flash attention module. This module inherits from `Data2VecAudioAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S rq   )r   r    r   _flash_attn_uses_top_left_mask)r-   argskwargsr0   r2   r3   r    O  s   z%Data2VecAudioFlashAttention2.__init__r   r   r   c                 C   s   | ||| j| jS rq   )r   ru   rx   r   r2   r2   r3   _reshapeW  s   z%Data2VecAudioFlashAttention2._reshapeNFr8   r   r   r   r   r   r   c              
   C   s>  |d u}|  \}}	}
| | |d|}|r8|d ur8|d jd |jd kr8|d dd}|d dd}nb|rO| | |d|}| | |d|}nK|d ur| | |d|}| | |d|}tj|d dd|gdd}tj|d dd|gdd}n| | |d|}| | |d|}| j	r|dd|ddf}|jd }|d ur||d jd 7 }|j
}|tjkrt rt }nt| jdr| jj}n| jjj
}td| d	 ||}||}||}t|||||	| jr| jnd
| j| jd}|||	d}| |}|sd }|||fS )Nr5   r   rB   r   r   r4   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .rs   )rp   rw   Zuse_top_left_mask)r   r   r}   r   r6   r{   r|   r   r   rv   dtypefloat32Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr.   r   weightloggerwarning_oncetor   re   rp   rw   r   r   r~   )r-   r8   r   r   r   r   r   r   r   Zq_lenrP   r   r   r   Z
kv_seq_lenZinput_dtypeZtarget_dtyper   r   r2   r2   r3   r9   Z  sl    









z$Data2VecAudioFlashAttention2.forwardr   )r<   r=   r>   ri   r    r   r   r   r   r   r   r   r9   r?   r2   r2   r0   r3   r   H  s0    r   c                       s   e Zd Z					ddejdeej deeej  deej deej ded	eejeej eeej  f f fd
dZ  Z	S )Data2VecAudioSdpaAttentionNFr8   r   r   r   r   r   r   c                    s  |rt d t j|||||dS |du}| \}}	}
| |}|r=|dur=|d jd |jd kr=|d }|d }nZ|rT| | |d|}| | 	|d|}nC|dur| | |d|}| | 	|d|}t
j|d |gdd}t
j|d |gdd}n| | |d|}| | 	|d|}| jr||f}| ||	|}| jr|du r|	dkrd	nd
}t
jjj||||| jr| jnd|d}| || j|	| jfkrtd|| j|	| jf d|  |dd}|||	| j}| |}|d|fS )r   a  Data2VecAudioModel is using Data2VecAudioSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` . Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r   r   Nr   rB   r   r5   r   TFrs   )Z	attn_maskZ	dropout_prw   r   r   )r   r   r   r9   r   r}   r   r   r{   r|   r   r   rv   rw   r   r   Zscaled_dot_product_attentionre   rp   ru   rx   ry   r6   r   rt   r~   )r-   r8   r   r   r   r   r   r   r   r   rP   r   r   r   rw   r   r0   r2   r3   r9     sh   



	

z"Data2VecAudioSdpaAttention.forwardr   )
r<   r=   r>   r   r   r   r   r   r9   r?   r2   r2   r0   r3   r     s*    r   c                       r@   )Data2VecAudioFeedForwardc                    sp   t    t|j| _t|j|j| _	t
|jtr"t|j | _n|j| _t|j|j| _t|j| _d S rq   )r   r    r   ro   Zactivation_dropoutintermediate_dropoutrm   rI   Zintermediate_sizeintermediate_dense
isinstanceZ
hidden_actstrr   intermediate_act_fnoutput_densehidden_dropoutoutput_dropoutrJ   r0   r2   r3   r    ,  s   
z!Data2VecAudioFeedForward.__init__c                 C   s6   |  |}| |}| |}| |}| |}|S rq   )r   r   r   r   r   r7   r2   r2   r3   r9   9  s   




z Data2VecAudioFeedForward.forwardr;   r2   r2   r0   r3   r   +      r   )eagerZsdpaflash_attention_2c                       s&   e Zd Z fddZdddZ  ZS )Data2VecAudioEncoderLayerc                    sl   t    t|j |j|j|jdd| _t	|j
| _tj|j|jd| _t|| _tj|j|jd| _d S )NF)rt   ru   rp   rv   rk   )r   r     DATA2VEC_AUDIO_ATTENTION_CLASSES_attn_implementationrI   Znum_attention_headsZattention_dropout	attentionr   ro   r   rp   r(   rl   r)   r   feed_forwardfinal_layer_normrJ   r0   r2   r3   r    K  s   

z"Data2VecAudioEncoderLayer.__init__NFc                 C   sf   |}| j |||d\}}}| |}|| }| |}|| | }| |}|f}|r1||f7 }|S )Nr   r   )r   rp   r)   r   r   )r-   r8   r   r   Zattn_residualr   rP   outputsr2   r2   r3   r9   Y  s   



z!Data2VecAudioEncoderLayer.forwardr_   r;   r2   r2   r0   r3   r   J  s    r   c                       sL   e Zd Z fddZ				ddejdeej ded	ed
ef
ddZ	  Z
S )Data2VecAudioEncoderc                    sr   t     | _t | _tj j jd| _	t
 j| _t fddt jD | _d| _ jdk| _d S )Nrk   c                    rM   r2   )r   rN   rQ   r2   r3   rR   t  rS   z1Data2VecAudioEncoder.__init__.<locals>.<listcomp>Fr   )r   r    r.   rL   pos_conv_embedr   r(   rI   rl   r)   ro   r   rp   rT   rU   num_hidden_layersrV   r]   r   _use_flash_attention_2rJ   r0   rQ   r3   r    n  s   

 zData2VecAudioEncoder.__init__NFTr8   r   r   output_hidden_statesreturn_dictc                 C   s  |rdnd }|r
dnd }|d ur_| ddd|jd }d|| < | jr2|d ur/d|v r/|nd }n-d|d d d d d d f j|jd }|t|jj }|	|jd d|jd |jd }| 
|}	||	 }| |}| |}t pxt| }
| jD ]G}|r||f }tg }| jr|| jjk rdnd	}|r|
r| jr| jr| |j|||}n||||d
}|d }|rd}|r||d f }q||r||f }|stdd |||fD S t|||dS )Nr2   r5   r   rB   r         ?r   TFr   NNc                 s   s    | ]	}|d ur|V  qd S rq   r2   )rO   vr2   r2   r3   	<genexpr>  s    z/Data2VecAudioEncoder.forward.<locals>.<genexpr>)last_hidden_stater8   
attentions)	unsqueezerepeatr   r   r   r   r   Zfinfominexpandr   r)   rp   r	   r
   rV   randre   r.   	layerdropr]   rf   rg   tupler   )r-   r8   r   r   r   r   Zall_hidden_statesZall_self_attentionsZexpand_attention_maskZposition_embeddingsZsynced_gpusrW   Zdropout_probabilityZskip_the_layerZlayer_outputsr2   r2   r3   r9   x  s`   
&






zData2VecAudioEncoder.forward)NFFT)r<   r=   r>   r    r   r   r   r   r   r9   r?   r2   r2   r0   r3   r   m  s"    r   c                       r@   )Data2VecAudioAdapterLayerc                    s0   t    tj|jd|j |j|jdd| _d S )NrB   r   )r   rG   )r   r    r   r$   output_hidden_sizeZadapter_kernel_sizeadapter_strider'   rJ   r0   r2   r3   r      s   
z"Data2VecAudioAdapterLayer.__init__c                 C   s   |  |}tjj|dd}|S )Nr   r   )r'   r   r   Zglur7   r2   r2   r3   r9     s   
z!Data2VecAudioAdapterLayer.forwardr;   r2   r2   r0   r3   r     s    
r   c                       r@   )Data2VecAudioAdapterc                    sp   t     j jkrt j j| _t j| _nd  | _| _t	 fddt
 jD | _ j| _d S )Nc                 3   s    | ]}t  V  qd S rq   )r   rN   rQ   r2   r3   r     s    z0Data2VecAudioAdapter.__init__.<locals>.<genexpr>)r   r    r   rI   r   rm   projr(   proj_layer_normrT   rU   num_adapter_layersrV   r   rJ   r0   rQ   r3   r      s   
 zData2VecAudioAdapter.__init__c                 C   sr   | j d ur| jd ur|  |}| |}|dd}| jD ]}tj }| jr,|| jkr0||}q|dd}|S rK   )r   r   r6   rV   nprandomre   r   )r-   r8   rW   Zlayerdrop_probr2   r2   r3   r9     s   



zData2VecAudioAdapter.forwardr;   r2   r2   r0   r3   r     r   r   c                   @   sh   e Zd ZeZdZdZdZdZdZ	dd Z
	ddeejef dee fd	d
Z	ddedejfddZdS )Data2VecAudioPreTrainedModeldata2vec_audiorh   Tc                 C   sZ  t |tr(td|jj }tjj|jj	| |d tjj|jj
| |d dS t |tr8tj|jj
d dS t |tjrX|j	jjd| jjd |j
durV|j
j  dS dS t |tjtjfr||j
durl|j
j  |j	durz|j	jd dS dS t |tjrtj|j	 |j
durt|j|j|jd   }tjj|j
| |d dS dS dS )zInitialize the weightsr   )abr   rs   )meanstdNr   )r   rj   mathsqrtrn   Zin_featuresr   inituniform_r   r   rF   Z	constant_r'   rm   dataZnormal_r.   Zinitializer_rangeZzero_r(   Z	GroupNormZfill_r$   Zkaiming_normal_rH   Zin_channelsr   )r-   modulekr2   r2   r3   _init_weights  s0   





z*Data2VecAudioPreTrainedModel._init_weightsNinput_lengthsadd_adapterc                 C   sn   |du r| j jn|}dd }t| j j| j jD ]
\}}||||}q|r5t| j jD ]
}||d| j j}q*|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input_lengthr   r   r2   r2   r3   _conv_out_length  s   zWData2VecAudioPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_lengthr   )r.   r   zipr%   r&   rU   r   r   )r-   r   r   r   r   r   rP   r2   r2   r3    _get_feat_extract_output_lengths  s   z=Data2VecAudioPreTrainedModel._get_feat_extract_output_lengthsfeature_vector_lengthr   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 )Nr5   r   r   r   )r   devicer   )r   )Zcumsumr   r   r   longr   zerosr   r   arangeflipr   )r-   r   r   r   Znon_padded_lengthsZoutput_lengths
batch_sizer2   r2   r3   "_get_feature_vector_attention_mask,  s   
"z?Data2VecAudioPreTrainedModel._get_feature_vector_attention_maskrq   )r<   r=   r>   r   Zconfig_classZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingZ_supports_flash_attn_2Z_supports_sdpar   r   r   
LongTensorr   r   r   r   r  r2   r2   r2   r3   r     s(    
r   r   	mask_probmask_lengthr   	min_masksr   c                    s  | \}dk rt dkrt d d dtjd   fdd}|dur:| d	 n
fd
dt|D }tj	|ft
d}g }	|}
|
dkrZ|S |D ];}||}tjjt|d  |dd}t|dkr}d }n|d }t|tj|
| tjd| g}|	| q\t|	}	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r }| d  |k r*t| d  d}|S )z;Given input length, compute how many spans should be maskedr   r   )r   max)r   num_masked_spanepsilonr  r  r  sequence_lengthr2   r3   compute_num_masked_spang  s   
z6_compute_mask_indices.<locals>.compute_num_masked_spanNr5   c                    s   g | ]} qS r2   r2   rN   )r  r2   r3   rR   z  s    z)_compute_mask_indices.<locals>.<listcomp>r   r   F)replace)ry   r   r   r   itemdetachsumtolistrU   r   r   choicer  lenZconcatenateonesZint32appendarrayZbroadcast_tor   r
  Zput_along_axis)r   r  r  r   r  r  r  r   Zspec_aug_maskZspec_aug_mask_idxsZmax_num_masked_spanr   r  Zspec_aug_mask_idxZdummy_mask_idxoffsetsr2   r  r3   _compute_mask_indicesA  s\   

r  c                       s   e Zd Zdef fddZdd Z		ddejdeej d	eej	 fd
dZ
e					ddeej d	eej deej dee dee dee deeef fddZ  ZS )Data2VecAudioModelr.   c                    s|   t  | || _t|| _t|| _|jdks|jdkr)t	
t|j | _t|| _|jr5t|nd | _|   d S )Nrs   )r   r    r.   rY   feature_extractorrj   feature_projectionmask_time_probmask_feature_probr   	Parameterr   r   rI   r   masked_spec_embedr   encoderr   r   adapter	post_initrJ   r0   r2   r3   r      s   


zData2VecAudioModel.__init__c                 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  rd   r-   r2   r2   r3   freeze_feature_encoder  s   z)Data2VecAudioModel.freeze_feature_encoderNr8   mask_time_indicesr   c                 C   s  t | jdds	|S | \}}}|dur| j|j||< n-| jjdkrK| jrKt||f| jj| jj	|| jj
d}tj||jtjd}| j|j||< | jjdkr| jrt||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   )r  r  r   r  )r   r   )r  r  r  r5   )getattrr.   r   r"  r   r   r  re   r  Zmask_time_lengthZmask_time_min_masksr   r   r   r   r   Zmask_feature_lengthZmask_feature_min_masksr   )r-   r8   r*  r   r  r  rI   Zmask_feature_indicesr2   r2   r3   _mask_hidden_states  s4   z&Data2VecAudioModel._mask_hidden_statesrh   r   r   r   r   c           
      C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| |}|dd}|dur8| j|jd |dd}| |\}}| j	|||d}| j
|||||d}	|	d }| jdur_| |}|sk||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.
        Nr   rB   Fr   )r*  r   r   r   r   r   r   )r   extract_featuresr8   r   )r.   r   r   use_return_dictr  r6   r  r   r  r,  r#  r$  Data2VecAudioBaseModelOutputr8   r   )
r-   rh   r   r*  r   r   r   r.  r8   Zencoder_outputsr2   r2   r3   r9     s@   


zData2VecAudioModel.forwardr   NNNNN)r<   r=   r>   r   r    r)  r   ZFloatTensorr   r  r,  r   r   r   r   r   r0  r9   r?   r2   r2   r0   r3   r    sB    

.
r  rB   zu
    Data2VecAudio Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
    )Zcustom_introc                       s   e Zd Z fddZdd Zdd Ze					ddeej	 d	eej	 d
ee
 dee
 dee
 deej	 deeef fddZ  ZS )Data2VecAudioForCTCc                    sx   t  | t|| _t|j| _|jdu r t	d| j
 dt|dr+|jr+|jn|j}t||j| _|   dS )a7  
        target_lang (`str`, *optional*):
            Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
            adapter.<lang>.bin. Only relevant when using an instance of [`Data2VecAudioForCTC`] with adapters. Uses 'eng' by
            default.
        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: `Data2VecAudioForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.r   )r   r    r  r   r   ro   Zfinal_dropoutrp   
vocab_sizery   r1   r   r   r   rI   rm   lm_headr%  )r-   r.   r   r0   r2   r3   r    G  s   

zData2VecAudioForCTC.__init__c                 C      t dt |   dS r'  The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. Please use the equivalent `freeze_feature_encoder` method instead.NwarningswarnFutureWarningr)  r(  r2   r2   r3   freeze_feature_extractorb  
   z,Data2VecAudioForCTC.freeze_feature_extractorc                 C      | j j  dS r&  r   r  rd   r(  r2   r2   r3   r)  n     z*Data2VecAudioForCTC.freeze_feature_encoderNrh   r   r   r   r   labelsr   c              
   C   s|  |dur|n| j j}|dur| | j jkrtd| j j | j|||||d}|d }| |}| |}	d}
|dur|durC|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 d   n1 sw   Y  |s|	f|td  }|
dur|
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]`.
        Nz$Label values must be <= vocab_size: r-  r   r   r5   )r   r   r   F)enabled)blankZ	reductionZzero_infinitylosslogitsr8   r   )r.   r/  r
  r3  ry   r   rp   r4  r   Z	ones_liker   r   r  r   Zmasked_selectr   r   Zlog_softmaxr   r6   backendsZcudnnflagsZctc_lossZpad_token_idZctc_loss_reductionZctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   r8   r   )r-   rh   r   r   r   r   rA  r   r8   rF  rE  r   Zlabels_maskZtarget_lengthsZflattened_targetsZ	log_probsoutputr2   r2   r3   r9   u  sN   



zData2VecAudioForCTC.forwardr1  )r<   r=   r>   r    r<  r)  r   r   r   r   r   r   r   r   r9   r?   r2   r2   r0   r3   r2  A  s2    
r2  z
    Data2VecAudio 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										dd
ee	j
 dee	j
 dee dee dee dee	j
 deeef fddZ  ZS )&Data2VecAudioForSequenceClassificationc                    s   t  | t|dr|jrtdt|| _|jd }|jr*t	
t|| | _t	|j|j| _t	|j|j| _|   d S )Nr   zdSequence classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)r   )r   r    r   r   ry   r  r   r   use_weighted_layer_sumr   r!  r   r  layer_weightsrm   rI   Zclassifier_proj_size	projector
num_labels
classifierr%  r-   r.   
num_layersr0   r2   r3   r      s   

z/Data2VecAudioForSequenceClassification.__init__c                 C   r5  )z
        Calling this function will disable the gradient computation for the feature encoder so that its parameters will
        not be updated during training.
        r7  Nr8  r(  r2   r2   r3   r<    r=  z?Data2VecAudioForSequenceClassification.freeze_feature_extractorc                 C   r>  r&  r?  r(  r2   r2   r3   r)    r@  z=Data2VecAudioForSequenceClassification.freeze_feature_encoderc                 C      | 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r   r`   ra   rb   r2   r2   r3   freeze_base_model     z8Data2VecAudioForSequenceClassification.freeze_base_modelNrh   r   r   r   r   rA  r   c                 C   sz  |dur|n| j j}| j jrdn|}| j|||||d}| j jrB|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}|du rV|jdd}
n+| |jd |}|ddd|jd }d	|| < |jdd|jdddd }
| |
}d}|durt }||d| j j|d}|s|f|td  }|dur|f| S |S t|||j|jd
S )  
        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 [`Data2VecAudioProcessor.__call__`] for details.
        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   r5   r   rB   rs   rD  )r.   r/  rL  r   rI  r   stackr   r   r   rM  r   r  rN  r   r  r   r   r   rP  r   rO  r   r8   r   )r-   rh   r   r   r   r   rA  r   r8   norm_weightsZpooled_outputZpadding_maskZexpand_padding_maskrF  rE  loss_fctrJ  r2   r2   r3   r9     sH   

 
z.Data2VecAudioForSequenceClassification.forwardr1  )r<   r=   r>   r    r<  r)  rV  r   r   r   r   r   r   r   r   r9   r?   r2   r2   r0   r3   rK    s4    
rK  c                       s   e Zd Z fddZdd Zdd Zdd Ze										dd
ee	j
 dee	j
 dee	j
 dee dee dee deeef fddZ  ZS )(Data2VecAudioForAudioFrameClassificationc                    sz   t  | t|dr|jrtdt|| _|jd }|jr*t	
t|| | _t	|j|j| _|j| _|   d S )Nr   zgAudio frame classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)r   )r   r    r   r   ry   r  r   r   rL  r   r!  r   r  rM  rm   rI   rO  rP  init_weightsrQ  r0   r2   r3   r    7  s   

z1Data2VecAudioForAudioFrameClassification.__init__c                 C   r5  r6  r8  r(  r2   r2   r3   r<  G  r=  zAData2VecAudioForAudioFrameClassification.freeze_feature_extractorc                 C   r>  r&  r?  r(  r2   r2   r3   r)  S  r@  z?Data2VecAudioForAudioFrameClassification.freeze_feature_encoderc                 C   rS  rT  rU  rb   r2   r2   r3   rV  Z  rW  z:Data2VecAudioForAudioFrameClassification.freeze_base_modelNrh   r   rA  r   r   r   r   c                 C   s   |dur|n| j j}| j jrdn|}| j|||||d}| j jrB|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}
d}|durht }||
d| jtj|d| jdd}|su|
f|td  }|S t||
|j|jd	S )
rX  NTr-  r   r   r5   r   )ZaxisrD  )r.   r/  rL  r   rI  r   rY  r   r   r   rM  r   r  rP  r   rO  Zargmaxr   r8   r   )r-   rh   r   rA  r   r   r   r   r8   rZ  rF  rE  r[  rJ  r2   r2   r3   r9   b  s:   
(z0Data2VecAudioForAudioFrameClassification.forwardr1  )r<   r=   r>   r    r<  r)  rV  r   r   r   r   r   r   r   r   r9   r?   r2   r2   r0   r3   r\  5  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)ra   )r   r^  r    scalemarginrO  r   r!  r   Zrandnr   r   rE  )r-   Z	input_dimrO  ra  rb  r0   r2   r3   r      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   )flattenr   r   	normalizer   r   mmrb  Zone_hotrO  ra  wherer   rE  )	r-   r8   rA  r   Z	cos_thetapsiZonehotrF  rE  r2   r2   r3   r9     s   
zAMSoftmaxLoss.forward)r_  r`  r;   r2   r2   r0   r3   r^    s    r^  c                       s4   e Zd Zd fdd	Zdejdejf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   )r   r    tdnn_dimr"   r#   tdnn_kernelr   Ztdnn_dilationdilationr   rm   kernelZReLUr+   r,   r0   r2   r3   r      s   
"zTDNNLayer.__init__r8   r   c                 C   s   t  r	ddlm} t  rt| j|rtd |dd}| jj	| j
| j| jdd}tjj||| jj| jd}|dd}| |}|S )Nr   )	LoraLayerzDetected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. You should exclude TDNNLayer from LoRA's target modules.r   rB   )rk  )r   Zpeft.tuners.lorarm  r   rl  r9  r:  r6   r   r   r#   r   r"   r   r   Zconv1dr   rk  r+   )r-   r8   rm  r   r2   r2   r3   r9     s    
zTDNNLayer.forwardr:   )r<   r=   r>   r    r   r   r9   r?   r2   r2   r0   r3   rh    s    
rh  zq
    Data2VecAudio 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d	eej	e
f fd
dZe					ddeej deej dee dee dee deej deeef fddZ  ZS )Data2VecAudioForXVectorc                    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 r2   )rh  rZ   rQ   r2   r3   rR     s    z4Data2VecAudioForXVector.__init__.<locals>.<listcomp>r5   rB   )r   r    r  r   r   rL  r   r!  r   r  rM  rm   rI   ri  rN  rU   r  rT   tdnnZxvector_output_dimr  rP  r^  rO  	objectiver]  )r-   r.   rR  Ztdnn_layersr0   rQ   r3   r      s   

z Data2VecAudioForXVector.__init__c                 C   r5  r6  r8  r(  r2   r2   r3   r<    r=  z0Data2VecAudioForXVector.freeze_feature_extractorc                 C   r>  r&  r?  r(  r2   r2   r3   r)    r@  z.Data2VecAudioForXVector.freeze_feature_encoderc                 C   rS  rT  rU  rb   r2   r2   r3   rV    rW  z)Data2VecAudioForXVector.freeze_base_modelr   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   r2   r   r2   r2   r3   r     s   zJData2VecAudioForXVector._get_tdnn_output_lengths.<locals>._conv_out_lengthr   )r.   rj  )r-   r   r   r   r2   r2   r3   _get_tdnn_output_lengths	  s   z0Data2VecAudioForXVector._get_tdnn_output_lengthsNrh   r   r   r   r   rA  r   c                 C   s  |dur|n| j j}| j jrdn|}| j|||||d}| j jrB|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}| jD ]}
|
|}qN|du rf|jdd}|jdd}nC| |jdd}| |}g }g }t|D ]"\}}|||d|f jdd |||d|f jdd q|t|}t|}tj||gdd}| |}| |}d}|dur| ||}|s||f|td  }|dur|f| S |S t||||j|jdS )	rX  NTr-  r   r   r5   r   )rE  rF  Z
embeddingsr8   r   )r.   r/  rL  r   rI  r   rY  r   r   r   rM  r   r  rN  ro  r   r   r   rq  	enumerater  r   r  rP  rp  r   r8   r   )r-   rh   r   r   r   r   rA  r   r8   rZ  Z
tdnn_layerZmean_featuresZstd_featuresZfeat_extract_output_lengthsZtdnn_output_lengthsr[   lengthZstatistic_poolingZoutput_embeddingsrF  rE  rJ  r2   r2   r3   r9     s\   



 



zData2VecAudioForXVector.forwardr1  )r<   r=   r>   r    r<  r)  rV  r   r   r  r   rq  r   r   r   r   r   r   r9   r?   r2   r2   r0   r3   rn    s6    
rn  )r\  r2  rK  rn  r  r   rE   )Hr   r9  typingr   r   r   numpyr   r   r   Ztorch.nnr   Zactivationsr   Zintegrations.deepspeedr	   Zintegrations.fsdpr
   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   Zconfiguration_data2vec_audior   r   Z
get_loggerr<   r   Moduler   rA   rF   rL   rY   rj   rr   r   r   r   r   r   r   r   r   r   r   r   r  Zndarrayr  r0  r  rI  r2  rK  r\  r^  rh  rn  __all__r2   r2   r2   r3   <module>   s    
# zi#UQ

w wrh  