
    sg3                       d Z ddlZddlZddlmZmZmZ ddlZddl	Z	ddl
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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$ ddl%m&Z&  e!       rddl'm(Z(  e$jR                  e*      Z+dZ,dZ-dZ.g dZ/dZ0dZ1	 	 dQdee2e2f   de3de2dee	jh                     de2dejj                  fdZ6 G d dejn                        Z8 G d d ejn                        Z9 G d! d"ejn                        Z: G d# d$ejn                        Z; G d% d&ejn                        Z< G d' d(ejn                        Z= G d) d*ejn                        Z> G d+ d,e>      Z? G d- d.e>      Z@e>e@e?d/ZA G d0 d1ejn                        ZB G d2 d3ejn                        ZC G d4 d5ejn                        ZD G d6 d7ejn                        ZE G d8 d9ejn                        ZF G d: d;e      ZGd<ZHd=ZI ed>eH       G d? d@eG             ZJ edAeH       G dB dCeG             ZK edDeH       G dE dFeG             ZL edGeH       G dH dIeG             ZM G dJ dKejn                        ZN G dL dMejn                        ZO edNeH       G dO dPeG             ZPy)RzPyTorch Data2VecAudio model.    N)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)is_fsdp_managed_module)BaseModelOutputCausalLMOutputSequenceClassifierOutputTokenClassifierOutputWav2Vec2BaseModelOutputXVectorOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10is_peft_availablelogging   )Data2VecAudioConfig)_flash_attention_forward   r   z!facebook/data2vec-audio-base-960h)r   i$  i   z['MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'g̼P@shape	mask_probmask_lengthattention_mask	min_masksreturnc                    | \  }dk  rt        d      kD  rt        d d d      t        j                  j                  d      j	                         fd}|-|j                  d      j                         j                         nt        |      D cg c]  } c}}t        j                  |ft        	      }	g }
 |      }|d
k(  r|	S |D ]  } ||      }t        j                  j                  t        j                  |dz
  z
        |d      }t        |      d
k(  rdz
  }n|d
   }t        j                  |t        j                  ||z
  t        j                   	      |z  g      }|
j#                  |        t        j$                  |
      }
t        j&                  |
dddddf   ||f      }
|
j)                  ||z        }
t        j                        ddddf   }t        j&                  |||f      j)                  ||z        }|
|z   }
|
j+                         dz
  kD  rdz
  |
|
dz
  kD  <   t        j,                  |	|
dd       |	S c c}w )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                     t        | z  z  z         }t        |      }|z  kD  rz  }| dz
  z
  |k  rt        | dz
  z
  d      }|S )z;Given input length, compute how many spans should be maskedr   r   )intmax)input_lengthnum_masked_spanepsilonr    r   r"   sequence_lengths     g/var/www/html/venv/lib/python3.12/site-packages/transformers/models/data2vec/modeling_data2vec_audio.pycompute_num_masked_spanz6_compute_mask_indices.<locals>.compute_num_masked_spann   so    i,6DwNOoy9 [(?:-<O ;?+o=!,+/"BAFO    Ndtyper   F)replace)
ValueErrornprandomranditemsumdetachtolistrangezerosboolchoicearangelenconcatenateonesint32appendarraybroadcast_toreshaper(   put_along_axis)r   r   r    r!   r"   
batch_sizer.   _input_lengthsspec_aug_maskspec_aug_mask_idxsmax_num_masked_spanr)   r*   spec_aug_mask_idxdummy_mask_idxoffsetsr+   r,   s    `` `            @@r-   _compute_mask_indicesrS   H   s   0 #(JQABB_$]^i]j&&7q:
 	
 iinnQ$$&G $ % 	2%%'..0',Z'89!o9  HHj/:$GM1/Ba% 51,? II,,IIlkAo67RW - 
  !Q& -q0N.q1NNN(;o(MUWU]U] ^ao op
 	!!"34/52 "45 1a:&5H+(V ,33J@SVa@ab ii$T4]3Goog
4G'UV^^'+5G ,g5 /A"55GVYZGZ-!0CCD m%7B?w :s   $	I+c                   &     e Zd Zd fd	Zd Z xZS )Data2VecAudioConvLayerc                    t         |           |dkD  r|j                  |dz
     nd| _        |j                  |   | _        t        j                  | j                  | j                  |j                  |   |j                  |   |j                        | _
        t        j                  | j                  d      | _        t        |j                     | _        y )Nr   r   )kernel_sizestridebiasTelementwise_affine)super__init__conv_dimin_conv_dimout_conv_dimr   Conv1dconv_kernelconv_stride	conv_biasconv	LayerNorm
layer_normr	   feat_extract_activation
activationselfconfiglayer_id	__class__s      r-   r]   zData2VecAudioConvLayer.__init__   s    <DqL6??8a<8a"OOH5II**84%%h/!!
	 ,,t'8'8TR !?!?@r/   c                     | j                  |      }|j                  dd      }| j                  |      }|j                  dd      }| j                  |      }|S )Nr0   )re   	transposerg   ri   rk   hidden_statess     r-   forwardzData2VecAudioConvLayer.forward   sV    		-0%//B76%//B76r/   r   __name__
__module____qualname__r]   rt   __classcell__rn   s   @r-   rU   rU      s    Ar/   rU   c                   $     e Zd Z fdZd Z xZS )Data2VecAudioPadLayerc                 P    t         |           |dz  dk(  rd| _        y d| _        y )Nr   r   r   )r\   r]   num_pad_remove)rk   num_conv_pos_embeddingsrn   s     r-   r]   zData2VecAudioPadLayer.__init__   s)    #:Q#>!#Car/   c                 V    | j                   dkD  r|d d d d d | j                    f   }|S Nr   )r   rr   s     r-   rt   zData2VecAudioPadLayer.forward   s6    ")!Q0F43F3F2F0F*FGMr/   rv   r{   s   @r-   r}   r}      s    Kr/   r}   c                   $     e Zd Z fdZd Z xZS ) Data2VecAudioPositionalConvLayerc                 z   t         |           t        j                  |j                  |j                  |j
                  |j
                  dz  |j                        | _        t        |j
                        | _	        t        |j                     | _        t        j                  |j                  d      | _        y )Nr   )rW   paddinggroupsFrZ   )r\   r]   r   ra   hidden_sizeconv_pos_kernel_sizenum_conv_pos_embedding_groupsre   r}   r   r	   rh   ri   rf   rg   rk   rl   rn   s     r-   r]   z)Data2VecAudioPositionalConvLayer.__init__   s    II33//1477
	 -V-H-HI !?!?@,,v'9'9eTr/   c                     | j                  |      }| j                  |      }|j                  dd      }| j                  |      }|j                  dd      }| j	                  |      }|S Nr   r   )re   r   rq   rg   ri   rr   s     r-   rt   z(Data2VecAudioPositionalConvLayer.forward   sd    		-0]3%//156%//156r/   rv   r{   s   @r-   r   r      s    Ur/   r   c                   $     e Zd Z fdZd Z xZS )$Data2VecAudioPositionalConvEmbeddingc                     t         |           t        j                  t	        |j
                        D cg c]  }t        |       c}      | _        y c c}w N)r\   r]   r   
ModuleListr<   r   r   layersrk   rl   rK   rn   s      r-   r]   z-Data2VecAudioPositionalConvEmbedding.__init__  s@    mm?DVEcEc?de!-f5e
es   Ac                     |j                  dd      }| j                  D ]
  } ||      } |j                  dd      }|S r   )rq   r   )rk   rs   layers      r-   rt   z,Data2VecAudioPositionalConvEmbedding.forward  sI    %//15[[ 	1E!-0M	1%//15r/   rv   r{   s   @r-   r   r     s    
r/   r   c                   .     e Zd ZdZ fdZd Zd Z xZS )Data2VecAudioFeatureEncoderz.Construct the features from raw audio waveformc           	          t         |           t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        d| _        d| _	        y c c}w )N)rm   FT)
r\   r]   r   r   r<   num_feat_extract_layersrU   conv_layersgradient_checkpointing_requires_grad)rk   rl   irn   s      r-   r]   z$Data2VecAudioFeatureEncoder.__init__  sX    ==AFvGeGeAfgA#FQ7g
 ',#" hs   A%c                 J    | j                         D ]	  }d|_         d| _        y NF)
parametersrequires_gradr   rk   params     r-   _freeze_parametersz.Data2VecAudioFeatureEncoder._freeze_parameters  s(    __& 	(E"'E	(#r/   c                 
   |d d d f   }| j                   r| j                  rd|_        | j                  D ]K  }| j                   r5| j                  r)| j                  r| j                  |j                  |      }D ||      }M |S )NT)r   trainingr   r   r   _gradient_checkpointing_func__call__)rk   input_valuesrs   
conv_layers       r-   rt   z#Data2VecAudioFeatureEncoder.forward"  s    $QW- 4==*.M'** 	:J""t'B'Bt}} $ A A''!!
 !+= 9	: r/   )rw   rx   ry   __doc__r]   r   rt   rz   r{   s   @r-   r   r     s    8#$r/   r   c                   $     e Zd Z fdZd Z xZS )Data2VecAudioFeatureProjectionc                 4   t         |           t        j                  |j                  d   |j
                        | _        t        j                  |j                  d   |j                        | _	        t        j                  |j                        | _        y )Nr0   eps)r\   r]   r   rf   r^   layer_norm_epsrg   Linearr   
projectionDropoutfeat_proj_dropoutdropoutr   s     r-   r]   z'Data2VecAudioFeatureProjection.__init__7  sf    ,,vr':@U@UV))FOOB$79K9KLzz&":":;r/   c                 p    | j                  |      }| j                  |      }| j                  |      }||fS r   )rg   r   r   )rk   rs   norm_hidden_statess      r-   rt   z&Data2VecAudioFeatureProjection.forward=  s:    !__];(:;]3000r/   rv   r{   s   @r-   r   r   6  s    <1r/   r   c                       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	Z	d
e
j                  dedef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Z xZS )Data2VecAudioAttentionz=Multi-headed attention from 'Attention Is All You Need' paper	embed_dim	num_headsr   
is_decoderrY   	is_causalrl   c                 
   t         |           || _        || _        || _        ||z  | _        || _        | j
                  |z  | j                  k7  rt        d| j                   d| d      | j
                  dz  | _        || _	        || _
        t        j                  |||      | _        t        j                  |||      | _        t        j                  |||      | _        t        j                  |||      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      )rY   )r\   r]   r   r   r   head_dimrl   r4   scalingr   r   r   r   k_projv_projq_projout_proj)	rk   r   r   r   r   rY   r   rl   rn   s	           r-   r]   zData2VecAudioAttention.__init__I  s     	""!Y.MMI%$..8MdnnM]$YKr3  }}d*$"ii	94@ii	94@ii	94@		)YTBr/   tensorseq_lenbszc                     |j                  ||| j                  | j                        j                  dd      j	                         S r   )viewr   r   rq   
contiguousrk   r   r   r   s       r-   _shapezData2VecAudioAttention._shapeh  s7    {{3GQQRSUVWbbddr/   rs   key_value_statespast_key_valuer!   layer_head_maskoutput_attentionsr#   c                 
   |du}|j                         \  }}	}
| j                  |      | j                  z  }|r0|.|d   j                  d   |j                  d   k(  r|d   }|d   }n
|rE| j	                  | j                  |      d|      }| j	                  | j                  |      d|      }n|}| j	                  | j                  |      d|      }| j	                  | j                  |      d|      }t        j                  |d   |gd      }t        j                  |d   |gd      }nD| j	                  | j                  |      d|      }| j	                  | j                  |      d|      }| j                  r||f}|| j                  z  d| j                  f} | j	                  ||	|      j                  | } |j                  | } |j                  | }|j                  d      }t        j                  ||j                  dd            }|j                         || j                  z  |	|fk7  r/t!        d|| j                  z  |	|f d|j                                |{|j                         |d|	|fk7  r#t!        d	|d|	|f d|j                                |j                  || j                  |	|      |z   }|j                  || j                  z  |	|      }t"        j$                  j'                  |d      }||j                         | j                  fk7  r*t!        d
| j                  f d|j                                |j                  dddd      |j                  || j                  |	|      z  }|j                  || j                  z  |	|      }|r?|j                  || j                  |	|      }|j                  || j                  z  |	|      }nd}t"        j$                  j)                  || j(                  | j*                        }t        j                  ||      }|j                         || j                  z  |	| j                  fk7  r9t!        d|| j                  z  |	| j                  f d|j                                |j                  || j                  |	| j                        }|j                  dd      }|j                  ||	| j,                        }| j/                  |      }|||fS )#Input shape: Batch x Time x ChannelNr   r   r   r0   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 )pr    `attn_output` should be of size )sizer   r   r   r   r   r   torchcatr   r   r   r   rH   bmmrq   r4   r   
functionalsoftmaxr   r   r   r   )rk   rs   r   r   r!   r   r   is_cross_attentionr   tgt_lenrK   query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r-   rt   zData2VecAudioAttention.forwardk  s    .T9',,.Wa {{=1DLL@ *q!''*.>.D.DQ.GG (*J)!,LT[[1A%BBLJ;;t{{3C'Db#NL'T[[%?SIJ;;t{{='A2sKLN1$5z#BJJ 99nQ&7%FANL T[[%?SIJ;;t{{='A2sKL?? ),7NDNN*B>
Ct{{<#>CCZP'Z''4
+|++Z8//!$yyz/C/CAq/IJ3#7'"JJ6dnn8LgW^7_6` a %%'(* 
 %""$a'(BB 7a'8R7SS\]k]p]p]r\st  (,,S$..'7SVddL',,S4>>-A7GTL}},,\r,B&##%$..):: Et~~FWEX Y',,./1  +//2q!<|?P?PQTVZVdVdfmov?wwL',,S4>>-A7GTL
 %1$5$5c4>>7T[$\!055cDNN6JGU\]L$(!]]**<4<<RVR_R_*`
ii
L9#"6!OO2C$..4H'SWS`S`3a2b c$$&') 
 "&&sDNNGT]]S!++Aq1 "))#wGmmK01>AAr/   )        FTFNNNNNF)rw   rx   ry   r   r'   floatr>   r   r   r]   r   Tensorr   r   rt   rz   r{   s   @r-   r   r   F  sN   G  04CC C 	C
 C C C ,-C>eU\\ eC ec e 488<1526"'vB||vB #5<<0vB !u||!45	vB
 !.vB "%,,/vB  vB 
u||Xell3XeELL>Q5RR	SvBr/   r   c                   V    e Zd ZdZ fdZdej                  dedef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Z x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                 D    t        |   |i | t                | _        y r   )r\   r]   r   _flash_attn_uses_top_left_mask)rk   argskwargsrn   s      r-   r]   z%Data2VecAudioFlashAttention2.__init__  s&    $)&)
 3V2W.W+r/   r   r   r   c                 R    |j                  ||| j                  | j                        S r   )r   r   r   r   s       r-   _reshapez%Data2VecAudioFlashAttention2._reshape  s    {{3GGr/   rs   r   r   r!   r   r   r#   c           
         |rt        d      |d u}|j                         \  }}	}
| j                  | j                  |      d|      }|rP|N|d   j                  d   |j                  d   k(  r,|d   j                  dd      }|d   j                  dd      }n*|rE| j                  | j                  |      d|      }| j                  | j                  |      d|      }n|| j                  | j                  |      d|      }| j                  | j                  |      d|      }t        j                  |d   j                  dd      |gd      }t        j                  |d   j                  dd      |gd      }nD| j                  | j                  |      d|      }| j                  | j                  |      d|      }| j                  r$|j                  dd      |j                  dd      f}|j                  d   }|||d   j                  d   z  }|j                  }|t        j                  k(  rt        j                         rt        j                         }nMt        | j                   d      r| j                   j"                  }n | j                  j$                  j                  }t&        j)                  d	| d
       |j+                  |      }|j+                  |      }|j+                  |      }t-        |||||	| j.                  r| j0                  nd| j2                  | j4                        }|j7                  ||	d      }| j9                  |      }|sd }||fS )NzIData2VecAudioFlashAttention2 attention does not support output_attentionsr0   r   r   r   r   rp   _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 .r   )r   r   use_top_left_mask)r4   r   r   r   r   rq   r   r   r   r   r   r2   float32is_autocast_enabledget_autocast_gpu_dtypehasattrrl   r   weightloggerwarning_oncetor   r   r   r   r   rH   r   )rk   rs   r   r   r!   r   r   r   r   q_lenrK   r   r   r   
kv_seq_leninput_dtypetarget_dtyper   r   s                      r-   rt   z$Data2VecAudioFlashAttention2.forward  s0    hii .T9%**,UA }}T[[%?SI *q!''*.>.D.DQ.GG (*44Q:J)!,66q!<Lt{{3C'Db#NJ==5E)FCPL't{{='A2sKJ==])CRMLN1$5$?$?1$Ez#RXYZJ 99nQ&7&A&A!Q&G%V\]^L t{{='A2sKJ==])CRML?? )221a8,:P:PQRTU:VWN%%b)
%.+11"55J #((%--'((*$;;=&?@#{{BB#{{1177 >$ (??<8L#|4J'??<8L.$(MMDLLsnn"AA	
 "))#ub9mmK0 LL.88r/   r   )rw   rx   ry   r   r]   r   r   r'   r   r   r   r>   rt   rz   r{   s   @r-   r   r     s    XHu|| Hc H H 488<1526"'i9||i9 #5<<0i9 !u||!45	i9
 !.i9 "%,,/i9  i9 
u||Xell3XeELL>Q5RR	Si9r/   r   c                   $    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Z xZ	S )
Data2VecAudioSdpaAttentionrs   r   r   r!   r   r   r#   c                 z   |s|*t         j                  d       t        |   ||||||      S |du}|j	                         \  }}	}
| j                  |      }|r0|.|d   j                  d   |j                  d   k(  r|d   }|d   }n
|rE| j                  | j                  |      d|      }| j                  | j                  |      d|      }n|}| j                  | j                  |      d|      }| j                  | j                  |      d|      }t        j                  |d   |gd      }t        j                  |d   |gd      }nD| j                  | j                  |      d|      }| j                  | j                  |      d|      }| j                  r||f}| j                  ||	|      }| j                  r	||	dkD  rd	nd
}t        j                  j                  j!                  ||||| j"                  r| j$                  nd|      }|j	                         || j&                  |	| j(                  fk7  r7t+        d|| j&                  |	| j(                  f d|j	                                |j-                  dd      }|j/                  ||	| j0                        }| j3                  |      }|d|fS )r   Na  Data2VecAudioModel is using Data2VecAudioSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. 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   r   r   r   r   r0   r   TFr   )	attn_mask	dropout_pr   r   r   )r   r  r\   rt   r   r   r   r   r   r   r   r   r   r   r   r   scaled_dot_product_attentionr   r   r   r   r4   rq   rH   r   r   )rk   rs   r   r   r!   r   r   r   r   r   rK   r   r   r   r   r   rn   s                   r-   rt   z"Data2VecAudioSdpaAttention.forwardf  s     ;l 7?!1-- /"3 #   .T9',,.Wa {{=1 *q!''*.>.D.DQ.GG (*J)!,LT[[1A%BBLJ;;t{{3C'Db#NL'T[[%?SIJ;;t{{='A2sKLN1$5z#BJJ 99nQ&7%FANL T[[%?SIJ;;t{{='A2sKL?? ),7N{{<#>
 !NN~/E'TU+D[`	 hh))FF$&*mmdll G 
 #t~~w!NN2CRVR_R_3`2a b$$&') 
 "++Aq1 "))#wGmmK0D.00r/   r   )
rw   rx   ry   r   r   r   r   r>   rt   rz   r{   s   @r-   r  r  d  s    
 488<1526"'f1||f1 #5<<0f1 !u||!45	f1
 !.f1 "%,,/f1  f1 
u||Xell3XeELL>Q5RR	Sf1 f1r/   r  )eagersdpaflash_attention_2c                   $     e Zd Z fdZd Z xZS )Data2VecAudioFeedForwardc                    t         |           t        j                  |j                        | _        t        j                  |j                  |j                        | _	        t        |j                  t              rt        |j                     | _        n|j                  | _        t        j                  |j                  |j                        | _        t        j                  |j                         | _        y r   )r\   r]   r   r   activation_dropoutintermediate_dropoutr   r   intermediate_sizeintermediate_dense
isinstance
hidden_actstrr	   intermediate_act_fnoutput_densehidden_dropoutoutput_dropoutr   s     r-   r]   z!Data2VecAudioFeedForward.__init__  s    $&JJv/H/H$I!"$))F,>,>@X@X"Yf''-'-f.?.?'@D$'-'8'8D$IIf&>&>@R@RS jj)>)>?r/   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }| j	                  |      }|S r   )r  r  r  r  r  rr   s     r-   rt   z Data2VecAudioFeedForward.forward  sX    //>00?11-@))-8++M:r/   rv   r{   s   @r-   r  r    s    @r/   r  c                   &     e Zd Z fdZddZ xZS )Data2VecAudioEncoderLayerc                    t         |           t        |j                     |j                  |j
                  |j                  d      | _        t        j                  |j                        | _        t        j                  |j                  |j                        | _        t        |      | _        t        j                  |j                  |j                        | _        y )NF)r   r   r   r   r   )r\   r]    DATA2VEC2AUDIO_ATTENTION_CLASSES_attn_implementationr   num_attention_headsattention_dropout	attentionr   r   r  r   rf   r   rg   r  feed_forwardfinal_layer_normr   s     r-   r]   z"Data2VecAudioEncoderLayer.__init__  s    9&:U:UV((00,,	
 zz&"7"78,,v'9'9v?T?TU4V< "V-?-?VEZEZ [r/   c                     |}| j                  |||      \  }}}| j                  |      }||z   }| j                  |      }|| j                  |      z   }| j	                  |      }|f}|r||fz  }|S )Nr!   r   )r&  r   rg   r'  r(  )rk   rs   r!   r   attn_residualr   rK   outputss           r-   rt   z!Data2VecAudioEncoderLayer.forward  s    %)-.L] *8 *
&|Q ]3%56%(9(9-(HH--m< "&Gr/   r   rv   r{   s   @r-   r   r     s    \r/   r   c                   r     e Zd Z fdZ	 	 	 	 ddej
                  deej                     dededef
dZ	 xZ
S )	Data2VecAudioEncoderc                    t         |           || _        t        |      | _        t        j                  |j                  |j                        | _	        t        j                  |j                        | _        t        j                  t        |j                        D cg c]  }t!        |       c}      | _        d| _        |j&                  dk(  | _        y c c}w )Nr   Fr  )r\   r]   rl   r   pos_conv_embedr   rf   r   r   rg   r   r  r   r   r<   num_hidden_layersr   r   r   r#  _use_flash_attention_2r   s      r-   r]   zData2VecAudioEncoder.__init__  s    B6J,,v'9'9v?T?TUzz&"7"78mmPUV\VnVnPo$p1%>v%F$pq&+#&,&A&AEX&X# %qs   !Crs   r!   r   output_hidden_statesreturn_dictc                 4   |rdnd }|rdnd }||j                  d      j                  dd|j                  d         }d|| <   | j                  r|d|v r|nd }nd|d d d d d d f   j	                  |j
                        z
  }|t        j                  |j
                        j                  z  }|j                  |j                  d   d|j                  d   |j                  d         }| j                  |      }	||	z   }| j                  |      }| j                  |      }t               xs t        |       }
| j                  D ]  }|r||fz   }t        j                   g       }| j"                  r|| j$                  j&                  k  rdnd	}|r|
rG| j(                  r+| j"                  r| j+                  |j,                  |||      }n ||||
      }|d   }|rd}|s|d   fz   } |r||fz   }|st/        d |||fD              S t1        |||      S )N r0   r   r   r         ?r1   TFr*  NNc              3   &   K   | ]	  }||  y wr   r6  ).0vs     r-   	<genexpr>z/Data2VecAudioEncoder.forward.<locals>.<genexpr>a  s     mq_`_lms   )last_hidden_staters   
attentions)	unsqueezerepeatr   r2  r  r2   r   finfominexpandr0  rg   r   r
   r   r   r7   r   rl   	layerdropr   r   r   tupler   )rk   rs   r!   r   r3  r4  all_hidden_statesall_self_attentionsexpand_attention_maskposition_embeddingssynced_gpusr   dropout_probabilityskip_the_layerlayer_outputss                  r-   rt   zData2VecAudioEncoder.forward  s[    #7BD$5b4%$2$<$<R$@$G$G1mNaNabcNd$e!45M001**4B4NSTXfSfmq "%~atQ6F'G'J'JQ^QdQd'J'e!e!/%++m>Q>Q2R2V2V!V!/!6!6"((+Q0D0DR0H.J^J^_aJb" #11-@%(;;6]302R6LT6R[[ 	PE#$58H$H! #(**R.%)]]8KdkkNcNc8cTjoN![..4==$($E$E%&)	%M %*%nXi%M !.a 0 , &9]1=M<O&O#7	P:   1]4D Dm]4EGZ$[mmm++*
 	
r/   )NFFT)rw   rx   ry   r]   r   r   r   r   r>   rt   rz   r{   s   @r-   r.  r.    s_    Y 26"'%* G
||G
 !.G
  	G

 #G
 G
r/   r.  c                   $     e Zd Z fdZd Z xZS )Data2VecAudioAdapterc                    t         |           j                  j                  k7  rTt	        j
                  j                  j                        | _        t	        j                  j                        | _        nd x| _        | _        t	        j                  fdt        j                        D              | _        j                  | _        y )Nc              3   4   K   | ]  }t                y wr   )Data2VecAudioAdapterLayer)r:  rK   rl   s     r-   r<  z0Data2VecAudioAdapter.__init__.<locals>.<genexpr>u  s     #p!$=f$E#ps   )r\   r]   output_hidden_sizer   r   r   projrf   proj_layer_normr   r<   num_adapter_layersr   rD  r   s    `r-   r]   zData2VecAudioAdapter.__init__k  s     $$(:(::		&"4"4f6O6OPDI#%<<0I0I#JD /33DI,mm#puU[UnUnOo#pp))r/   c                 h   | j                   .| j                  "| j                  |      }| j                  |      }|j                  dd      }| j                  D ]D  }t        j
                  j                         }| j                  r|| j                  kD  s= ||      }F |j                  dd      }|S r   )rT  rU  rq   r   r5   r6   r   rD  )rk   rs   r   layerdrop_probs       r-   rt   zData2VecAudioAdapter.forwardx  s    99 T%9%9%E IIm4M 00?M%//15[[ 	5EYY--/N==^dnn%D %m 4	5
 &//15r/   rv   r{   s   @r-   rO  rO  j  s    *r/   rO  c                   $     e Zd Z fdZd Z xZS )rR  c                     t         |           t        j                  |j                  d|j                  z  |j
                  |j                  d      | _        y )Nr   r   )rX   r   )r\   r]   r   ra   rS  adapter_kernel_sizeadapter_stridere   r   s     r-   r]   z"Data2VecAudioAdapterLayer.__init__  sJ    II%%)))&&((
	r/   c                 j    | j                  |      }t        j                  j                  |d      }|S )Nr   r   )re   r   r   glurr   s     r-   rt   z!Data2VecAudioAdapterLayer.forward  s/    		-0))-Q)?r/   rv   r{   s   @r-   rR  rR    s    
r/   rR  c                       e Zd ZdZeZdZdZdZdZ	dZ
d Z	 ddeej                  ef   dee   fd	Z	 dd
edej                  fdZy)Data2VecAudioPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    data2vec_audior   Tc                    t        |t              rt        j                  d|j                  j
                  z        }t        j                  j                  |j                  j                  | |       t        j                  j                  |j                  j                  | |       yt        |t              r5t        j                  j                  |j                  j                  d       yt        |t        j                        rm|j                  j                  j!                  d| j"                  j$                         |j                  %|j                  j                  j'                          yyt        |t        j(                  t        j*                  f      rc|j                  $|j                  j                  j'                          |j                  &|j                  j                  j-                  d       yyt        |t        j.                        rt        j                  j1                  |j                         |j                  jt        j                  |j2                  |j4                  |j6                  d   z  z        }t        j                  j                  |j                  | |       yyy)zInitialize the weightsr   )abr   r   )meanstdNr7  )r  r   mathsqrtr   in_featuresr   inituniform_r   rY   r   	constant_re   r   datanormal_rl   initializer_rangezero_rf   	GroupNormfill_ra   kaiming_normal_r   in_channelsrW   )rk   moduleks      r-   _init_weightsz*Data2VecAudioPreTrainedModel._init_weights  s   f<=		!f//;;;<AGGV..55!qAGGV..33rQ? @AGGfkk..2		*MM&&CT[[5R5R&S{{&  &&( 'r|| <={{&  &&(}}(""((- )		*GG##FMM2{{&IIfmmv/A/AFDVDVWXDY/YZ[  a 8 ' +r/   NrL   add_adapterc                 T   || j                   j                  n|}d }t        | j                   j                  | j                   j                        D ]  \  }} ||||      } |rBt        | j                   j                        D ]   } ||d| j                   j                        }" |S )zH
        Computes the output length of the convolutional layers
        c                 >    t        j                  | |z
  |d      dz   S )Nfloor)rounding_moder   )r   divr)   rW   rX   s      r-   _conv_out_lengthzWData2VecAudioPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_length  s"     99\K7wWZ[[[r/   r   )rl   rx  ziprb   rc   r<   rV  r\  )rk   rL   rx  r  rW   rX   rK   s          r-    _get_feat_extract_output_lengthsz=Data2VecAudioPreTrainedModel._get_feat_extract_output_lengths  s     2=1Ddkk--+	\
 $'t{{'>'>@W@W#X 	QK,]KPM	Q 4;;99: _ 04;;C]C] ^_ r/   feature_vector_lengthr!   c                     |j                  d      d d df   }| j                  ||      }|j                  t        j                        }|j
                  d   }t        j                  ||f|j                  |j                        }d|t        j                  |j
                  d   |j                        |dz
  f<   |j                  dg      j                  d      j                  dg      j                         }|S )Nr0   r   rx  r   )r2   devicer   )r  )cumsumr  r  r   longr   r=   r2   r  r@   flipr>   )rk   r  r!   rx  non_padded_lengthsoutput_lengthsrJ   s          r-   "_get_feature_vector_attention_maskz?Data2VecAudioPreTrainedModel._get_feature_vector_attention_mask  s    
 ,22r2:1b5A>>?Q_j>k'**5::6#))!,
./~7K7KTbTiTi
 uv^%9%9!%<^EZEZ[]kno]opq',,bT299"=BBB4HMMOr/   r   )rw   rx   ry   r   r   config_classbase_model_prefixmain_input_namesupports_gradient_checkpointing_supports_flash_attn_2_supports_sdparw  r   r   
LongTensorr'   r   r>   r  r  r6  r/   r-   r`  r`    s    
 'L($O&*#!N96 Z^"5#3#3S#89HPQU2 Y]%(:?:J:Jr/   r`  a  
    Data2VecAudio was proposed in [data2vec: A General Framework for Self-supervised Learning in Speech, Vision and
    Language](https://arxiv.org/pdf/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu and
    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 ([`Data2VecAudioConfig`]): 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.
aJ  
    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 be passed if the corresponding processor has `config.return_attention_mask ==
            True`, which is the case for all pre-trained Data2Vec Audio models. Be aware that that even with
            `attention_mask`, zero-padded inputs will have slightly different outputs compared to non-padded inputs
            because there are more than one convolutional layer in the positional encodings. For a more detailed
            explanation, see [here](https://github.com/huggingface/transformers/issues/25621#issuecomment-1713759349).

            </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.
zgThe bare Data2VecAudio Model transformer outputting raw hidden-states without any specific head on top.c                   \    e Zd Zdef fdZd Z	 	 ddej                  deej                     deej                     fdZ
 ee       eeeed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              Z xZS )Data2VecAudioModelrl   c                    t         |   |       || _        t        |      | _        t        |      | _        |j                  dkD  s|j                  dkD  rEt        j                  t        j                  |j                        j                               | _        t!        |      | _        |j$                  rt'        |      nd | _        | j+                          y )Nr   )r\   r]   rl   r   feature_extractorr   feature_projectionmask_time_probmask_feature_probr   	Parameterr   r   r   rk  masked_spec_embedr.  encoderrx  rO  adapter	post_initr   s     r-   r]   zData2VecAudioModel.__init__-  s     !<V!D"@"H   3&&*B*BS*H%'\\%,,v?Q?Q2R2[2[2]%^D"+F37=7I7I+F3t 	r/   c                 8    | j                   j                          y
        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   rk   s    r-   freeze_feature_encoderz)Data2VecAudioModel.freeze_feature_encoder>  s    
 	113r/   rs   mask_time_indicesr!   c                    t        | j                  dd      s|S |j                         \  }}}|)| j                  j	                  |j
                        ||<   n| j                  j                  dkD  r| j                  rt        ||f| j                  j                  | j                  j                  || j                  j                        }t        j                  ||j                  t        j                        }| j                  j	                  |j
                        ||<   | j                  j                  dkD  r| j                  rt        ||f| j                  j                  | j                  j                   | j                  j"                        }t        j                  ||j                  t        j                        }|dddf   j%                  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).
        apply_spec_augmentTNr   )r   r    r!   r"   )r  r2   )r   r    r"   r0   )getattrrl   r   r  r  r2   r  r   rS   mask_time_lengthmask_time_min_masksr   r   r  r>   r  mask_feature_lengthmask_feature_min_masksrC  )rk   rs   r  r!   rJ   r,   r   mask_feature_indicess           r-   _mask_hidden_statesz&Data2VecAudioModel._mask_hidden_statesE  s    t{{$8$?   4A3E3E3G0
O[(/3/E/E/H/HI\I\/]M+,[[''!+ 5_-++44 KK88-++99! !&->}G[G[chcmcm n/3/E/E/H/HI\I\/]M+,;;((1,#8[)++77 KK;;++<<	$  $)<<0D]MaMainisis#t #74#@#G#GO]_#` 23M./r/   audio)
checkpointoutput_typer  modalityexpected_outputr   r   r3  r4  r#   c                 H   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j	                  |      }|j                  dd      }|!| j                  |j                  d   |d      }| j                  |      \  }}| j                  |||      }| j                  |||||      }	|	d   }| j                  | j                  |      }|s
||f|	dd  z   S t        |||	j                  |	j                        S )	Nr   r   Fr  )r  r!   r!   r   r3  r4  r   )r=  extract_featuresrs   r>  )rl   r   r3  use_return_dictr  rq   r  r   r  r  r  r  r   rs   r>  )
rk   r   r!   r  r   r3  r4  r  rs   encoder_outputss
             r-   rt   zData2VecAudioModel.forwards  sb   " 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]11,?+55a;%!DD &&q)>u E N +/*A*ABR*S''00->~ 1 
 ,,)/!5# ' 
 (*<<# LL7M!#34qr7JJJ&+-)77&11	
 	
r/   r8  NNNNN)rw   rx   ry   r   r]   r  r   FloatTensorr   r  r  r   DATA2VEC_AUDIO_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   r>   r   r   rt   rz   r{   s   @r-   r  r  (  s   
2 "4 :>59	,((, $E$5$56, !!1!12	,\ ++JK&+$. 269=,0/3&*2
u||,2
 !.2
 $E$5$56	2

 $D>2
 'tn2
 d^2
 
u--	.2
 L2
r/   r  zkData2VecAudio Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).c                        e Zd Z fdZd Zd Z ee       ee	e
ee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              Z xZS )Data2VecAudioForCTCc                    t         |   |       t        |      | _        t	        j
                  |j                        | _        |j                  t        d| j                   d      t        |d      r|j                  r|j                  n|j                  }t	        j                  ||j                        | _        | j#                          y )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.rx  )r\   r]   r  ra  r   r   final_dropoutr   
vocab_sizer4   rn   r   rx  rS  r   r   lm_headr  )rk   rl   rS  rn   s      r-   r]   zData2VecAudioForCTC.__init__  s     08zz&"6"67$00@ AH H  *1)GFL^L^F%%djdvdv 	 yy!3V5F5FG 	r/   c                 X    t        j                  dt               | j                          y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  s    r-   freeze_feature_extractorz,Data2VecAudioForCTC.freeze_feature_extractor  '    
 	Q	

 	##%r/   c                 L    | j                   j                  j                          yr  ra  r  r   r  s    r-   r  z*Data2VecAudioForCTC.freeze_feature_encoder      
 	--@@Br/   )r  r  r  r  expected_lossr   r!   r   r3  r4  labelsr#   c           
         ||n| j                   j                  }|I|j                         | j                   j                  k\  r"t	        d| j                   j                         | j                  |||||      }|d   }| j                  |      }| j                  |      }	d}
|b||n$t        j                  |t        j                        }| j                  |j                  d            j                  t        j                        }|dk\  }|j                  d      }|j                  |      }t        j                   j#                  |	dt        j$                        j'                  dd      }t        j(                  j*                  j-                  d	
      5  t        j                   j/                  ||||| j                   j0                  | j                   j2                  | j                   j4                        }
ddd       |s|	f|t6        d z   }|
|
f|z   S |S t9        |
|	|j:                  |j<                        S # 1 sw Y   ExY w)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   r1   r0   )r   r2   r   F)enabled)blank	reductionzero_infinitylosslogitsrs   r>  )rl   r  r(   r  r4   ra  r   r  r   	ones_liker  r  r9   r  masked_selectr   r   log_softmaxr   rq   backendscudnnflagsctc_losspad_token_idctc_loss_reductionctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   rs   r>  )rk   r   r!   r   r3  r4  r  r,  rs   r  r  rL   labels_masktarget_lengthsflattened_targets	log_probsoutputs                    r-   rt   zData2VecAudioForCTC.forward  s)   2 &1%<k$++B]B]&**,$++2H2H"HCDKKDZDZC[\]]%%)/!5# & 
  
]3m, #1"<%//R^fkfpfpBq  !AA.BTBTUWBXY\\]b]g]ghM !A+K(__R0N & 4 4[ A 11&b1V``abdefI%%++E+: 	}}--%!"++22"kk<<"&++"?"? . 	 Y)F)G!HHF)-)9TGf$EvEfG4I4IV]VhVh
 	
	 	s   A#IIr  )rw   rx   ry   r]   r  r  r   r  r   r  r   r  _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr   r   r   r>   r   r   rt   rz   r{   s   @r-   r  r    s    
*
&C ++JK&"$,( 26,0/3&*)-D
u||,D
 !.D
 $D>	D

 'tnD
 d^D
 &D
 
un$	%D
 LD
r/   r  z
    Data2VecAudio Model with a sequence classification head on top (a linear layer over the pooled output) for tasks
    like SUPERB Keyword Spotting.
    c                        e Zd Z fdZd Zd Zd Z ee       e	e
eed      	 	 	 	 	 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              Z xZS )&Data2VecAudioForSequenceClassificationc                    t         |   |       t        |d      r|j                  rt	        d      t        |      | _        |j                  dz   }|j                  r0t        j                  t        j                  |      |z        | _        t        j                  |j                  |j                         | _        t        j                  |j                   |j$                        | _        | j)                          y )Nrx  zdSequence classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)r   )r\   r]   r   rx  r4   r  ra  r1  use_weighted_layer_sumr   r  r   rC   layer_weightsr   r   classifier_proj_size	projector
num_labels
classifierr  rk   rl   
num_layersrn   s      r-   r]   z/Data2VecAudioForSequenceClassification.__init__5  s     6=)f.@.@v  18--1
((!#ejj.Dz.Q!RD6#5#5v7R7RS))F$?$?ARARS 	r/   c                 X    t        j                  dt               | j                          y)z
        Calling this function will disable the gradient computation for the feature encoder so that its parameters will
        not be updated during training.
        r  Nr  r  s    r-   r  z?Data2VecAudioForSequenceClassification.freeze_feature_extractorF  r  r/   c                 L    | j                   j                  j                          yr  r  r  s    r-   r  z=Data2VecAudioForSequenceClassification.freeze_feature_encoderR  r  r/   c                 P    | j                   j                         D ]	  }d|_         y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ra  r   r   r   s     r-   freeze_base_modelz8Data2VecAudioForSequenceClassification.freeze_base_modelY  *    
 ((335 	(E"'E	(r/   r  r  r  r  r  r   r!   r   r3  r4  r  r#   c                    ||n| j                   j                  }| j                   j                  rdn|}| j                  |||||      }| j                   j                  rr|t           }t        j                  |d      }t        j                  j                  | j                  d      }	||	j                  ddd      z  j                  d      }n|d   }| j                  |      }||j                  d      }
nZ| j                  |j                   d   |      }d|| <   |j                  d      |j                  d      j                  dd      z  }
| j#                  |
      }d}|Ft%               } ||j                  d| j                   j&                        |j                  d            }|s|f|t        d z   }||f|z   S |S t)        |||j*                  |j,                  	      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   r0   r   r   r  )rl   r  r  ra  r  r   stackr   r   r   r  r   r9   r  re  r  r   r  r   r  r   rs   r>  )rk   r   r!   r   r3  r4  r  r,  rs   norm_weightspooled_outputpadding_maskr  r  loss_fctr  s                   r-   rt   z.Data2VecAudioForSequenceClassification.forwarda  s   0 &1%<k$++B]B]'+{{'I'ItOc%%)/!5# & 
 ;;--#$ABM!KK1=M==001C1C0LL*\->->r1a-HHMMRSMTM#AJM}5!)..1.5MBB=CVCVWXCY[ijL+.M<-()--!-4|7G7GA7G7N7S7STVXY7ZZM/')HFKKDKK,B,BCV[[QS_UDY)F)G!HHF)-)9TGf$EvE'!//))	
 	
r/   r  )rw   rx   ry   r]   r  r  r  r   r  r   r  r   r  r   r   r   r>   r   r   rt   rz   r{   s   @r-   r  r  -  s    "
&C( ++JK&,$	 26,0/3&*)-;
u||,;
 !.;
 $D>	;

 'tn;
 d^;
 &;
 
u..	/;
 L;
r/   r  zi
    Data2VecAudio Model with a frame classification head on top for tasks like Speaker Diarization.
    c                        e Zd Z fdZd Zd Zd Z ee       e	e
eed      	 	 	 	 	 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              Z xZS )(Data2VecAudioForAudioFrameClassificationc                    t         |   |       t        |d      r|j                  rt	        d      t        |      | _        |j                  dz   }|j                  r0t        j                  t        j                  |      |z        | _        t        j                  |j                  |j                         | _        |j                   | _        | j%                          y )Nrx  zgAudio frame classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)r   )r\   r]   r   rx  r4   r  ra  r1  r  r   r  r   rC   r  r   r   r  r  init_weightsr  s      r-   r]   z1Data2VecAudioForAudioFrameClassification.__init__  s     6=)f.@.@-  18--1
((!#ejj.Dz.Q!RD))F$6$68I8IJ ++r/   c                 X    t        j                  dt               | j                          yr  r  r  s    r-   r  zAData2VecAudioForAudioFrameClassification.freeze_feature_extractor  r  r/   c                 L    | j                   j                  j                          yr  r  r  s    r-   r  z?Data2VecAudioForAudioFrameClassification.freeze_feature_encoder  r  r/   c                 P    | j                   j                         D ]	  }d|_         yr  r  r   s     r-   r  z:Data2VecAudioForAudioFrameClassification.freeze_base_model  r  r/   r  r  r   r!   r  r   r3  r4  r#   c           	         ||n| j                   j                  }| j                   j                  rdn|}| j                  |||||      }| j                   j                  rr|t           }t        j                  |d      }t        j                  j                  | j                  d      }	||	j                  ddd      z  j                  d      }n|d   }| j                  |      }
d}|\t               } ||
j                  d| j                        t        j                   |j                  d| j                        d            }|s|
f|t        d z   }|S t#        ||
|j$                  |j&                  	      S )
r   NTr  r   r   r0   r   )axisr  )rl   r  r  ra  r  r   r  r   r   r   r  r   r9   r  r   r  argmaxr   rs   r>  )rk   r   r!   r  r   r3  r4  r,  rs   r  r  r  r  r  s                 r-   rt   z0Data2VecAudioForAudioFrameClassification.forward  sj   0 &1%<k$++B]B]'+{{'I'ItOc%%)/!5# & 
 ;;--#$ABM!KK1=M==001C1C0LL*\->->r1a-HHMMRSMTM#AJM/')HFKKDOO<ell6;;WY[_[j[jKkrs>tuDY)F)G!HHFM$!//))	
 	
r/   r  )rw   rx   ry   r]   r  r  r  r   r  r   r  r   r  r   r   r   r>   r   r   rt   rz   r{   s   @r-   r  r    s    "
&C( ++JK&)$	 26)-,0/3&*3
u||,3
 !.3
 &	3

 $D>3
 'tn3
 d^3
 
u++	,3
 L3
r/   r  c                   &     e Zd Zd fd	Zd Z xZS )AMSoftmaxLossc                     t         t        |           || _        || _        || _        t        j                  t        j                  ||      d      | _
        t        j                         | _        y )NT)r   )r\   r  r]   scalemarginr  r   r  r   randnr   r   r  )rk   	input_dimr  r  r  rn   s        r-   r]   zAMSoftmaxLoss.__init__  sS    mT+-
$ll5;;y*#EUYZ'')	r/   c                    |j                         }t        j                  j                  | j                  d      }t        j                  j                  |d      }t        j                  ||      }|| j                  z
  }t        j                  j                  || j                        }| j                  t        j                  |j                         ||      z  }| j                  ||      }|S )Nr   r   r   )flattenr   r   	normalizer   r   mmr  one_hotr  r  wherer>   r  )	rk   rs   r  r   	cos_thetapsionehotr  r  s	            r-   rt   zAMSoftmaxLoss.forward"  s    !((!(<//1/EHH]F3	$++%&&vt?ekk&++-iHHyy(r/   )g      >@g?rv   r{   s   @r-   r  r    s    *r/   r  c                   X     e Zd Zd fd	Zdej
                  dej
                  fdZ xZS )	TDNNLayerc                    t         |           |dkD  r|j                  |dz
     n|j                  |   | _        |j                  |   | _        |j
                  |   | _        |j                  |   | _        t        j                  | j                  | j                  z  | j                        | _        t        j                         | _        y )Nr   r   )r\   r]   tdnn_dimr_   r`   tdnn_kernelrW   tdnn_dilationdilationr   r   kernelReLUri   rj   s      r-   r]   zTDNNLayer.__init__2  s    <DqL6??8a<8foo^fNg"OOH5!--h7,,X6ii 0 043C3C CTEVEVW'')r/   rs   r#   c                    t               r1ddlm} t        | j                  |      rt        j                  d       |j                  dd      }| j                  j                  j                  | j                  | j                  | j                        j                  dd      }t        j                  j                  ||| j                  j                   | j"                        }|j                  dd      }| j%                  |      }|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   r   )r&  )r   peft.tuners.lorar*  r  r'  r  r  rq   r   r   r`   rW   r_   r   r   conv1drY   r&  ri   )rk   rs   r*  r   s       r-   rt   zTDNNLayer.forward<  s    2$++y1O &//15##(():):D<L<LdN^N^_iijkmno,,]FDKKDTDT_c_l_l,m%//156r/   ru   )rw   rx   ry   r]   r   r   rt   rz   r{   s   @r-   r!  r!  1  s#    $U\\ ell r/   r!  zq
    Data2VecAudio Model with an XVector feature extraction head on top for tasks like Speaker Verification.
    c                   (    e Zd Z fdZd Zd Zd Zdeej                  e
f   fdZ ee       eeeed      	 	 	 	 	 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              Z xZS )Data2VecAudioForXVectorc                    t         |   |       t        |      | _        |j                  dz   }|j
                  r0t        j                  t        j                  |      |z        | _
        t        j                  |j                  |j                  d         | _        t        t!        |j                              D cg c]  }t#        ||       }}t        j$                  |      | _        t        j                  |j                  d   dz  |j(                        | _        t        j                  |j(                  |j(                        | _        t/        |j(                  |j0                        | _        | j5                          y c c}w )Nr   r   r0   r   )r\   r]   r  ra  r1  r  r   r  r   rC   r  r   r   r#  r  r<   rA   r!  r   tdnnxvector_output_dimr  r  r  r  	objectiver	  )rk   rl   r  r   tdnn_layersrn   s        r-   r]   z Data2VecAudioForXVector.__init__W  s    08--1
((!#ejj.Dz.Q!RD6#5#5vq7IJ5:3v;O5PQy+QQMM+.	!#6??2+>+BFD]D]!^))F$=$=v?X?XY&v'@'@&BSBST Rs   >Fc                 X    t        j                  dt               | j                          yr  r  r  s    r-   r  z0Data2VecAudioForXVector.freeze_feature_extractorj  r  r/   c                 L    | j                   j                  j                          yr  r  r  s    r-   r  z.Data2VecAudioForXVector.freeze_feature_encoderv  r  r/   c                 P    | j                   j                         D ]	  }d|_         yr  r  r   s     r-   r  z)Data2VecAudioForXVector.freeze_base_model}  r  r/   rL   c                 V    d }| j                   j                  D ]  } |||d      } |S )z?
        Computes the output length of the TDNN layers
        c                     | |z
  |z  dz   S )Nr   r6  r~  s      r-   r  zJData2VecAudioForXVector._get_tdnn_output_lengths.<locals>._conv_out_length  s     !;.69A==r/   r   )rl   r$  )rk   rL   r  rW   s       r-   _get_tdnn_output_lengthsz0Data2VecAudioForXVector._get_tdnn_output_lengths  s:    
	>
  ;;22 	LK,]KKM	L r/   r  r  r   r!   r   r3  r4  r  r#   c                    ||n| j                   j                  }| j                   j                  rdn|}| j                  |||||      }| j                   j                  rr|t           }t        j                  |d      }t        j                  j                  | j                  d      }	||	j                  ddd      z  j                  d      }n|d   }| j                  |      }| j                  D ]
  }
 |
|      } |%|j                  d      }|j!                  d      }n| j#                  |j                  d            }| j%                  |      }g }g }t'        |      D ]U  \  }}|j)                  ||d|f   j                  d             |j)                  ||d|f   j!                  d             W t        j                  |      }t        j                  |      }t        j*                  ||gd      }| j-                  |      }| j/                  |      }d}|| j1                  ||      }|s||f|t        d z   }||f|z   S |S t3        ||||j4                  |j6                        S )	r   NTr  r   r   r0   r   )r  r  
embeddingsrs   r>  )rl   r  r  ra  r  r   r  r   r   r   r  r   r9   r  r0  re  rf  r  r9  	enumeraterE   r   r  r  r2  r   rs   r>  )rk   r   r!   r   r3  r4  r  r,  rs   r  
tdnn_layermean_featuresstd_featuresfeat_extract_output_lengthstdnn_output_lengthsr   lengthstatistic_poolingoutput_embeddingsr  r  r  s                         r-   rt   zData2VecAudioForXVector.forward  s   0 &1%<k$++B]B]'+{{'I'ItOc%%)/!5# & 
 ;;--#$ABM!KK1=M==001C1C0LL*\->->r1a-HHMMRSMTM#AJM}5)) 	6J&}5M	6 !)..1.5M(,,,3L*.*O*OP^PbPbghPbPi*j'"&"?"?@["\ML&':; J	6$$]1gvg:%>%C%C%C%JK##M!WfW*$=$A$Aa$A$HIJ "KK6M ;;|4L!II}l&CL 223DE!23>>&&1D/07;X;Y3ZZF)-)9TGf$EvE(!//))
 	
r/   r  )rw   rx   ry   r]   r  r  r  r   r   r  r'   r9  r   r  r   r  r   r  r   r   r>   r   rt   rz   r{   s   @r-   r.  r.  P  s    &
&C(eE<L<Lc<Q6R  ++JK&!$	 26,0/3&*)-I
u||,I
 !.I
 $D>	I

 'tnI
 d^I
 &I
 
um#	$I
 LI
r/   r.  r   )Qr   rg  r  typingr   r   r   numpyr5   r   torch.utils.checkpointr   torch.nnr   activationsr	   integrations.deepspeedr
   integrations.fsdpr   modeling_outputsr   r   r   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   configuration_data2vec_audior   modeling_flash_attention_utilsr   
get_loggerrw   r   r  r  r  r  r  r  r'   r   r  ndarrayrS   ModulerU   r}   r   r   r   r   r   r   r  r"  r  r   r.  rO  rR  r`  DATA2VEC_AUDIO_START_DOCSTRINGr  r  r  r  r  r  r!  r.  r6  r/   r-   <module>rU     s   #   ) )     % ! @ 7  .   > J			H	% !"  ( : &  u   26tc?tt t U--.	t
 t ZZtnRYY 8BII ryy 6299 "")) "L1RYY 1 [BRYY [B~|9#9 |9~h1!7 h1X $&5$  ryy 2 		  HR
299 R
l299 @		 $Q? Qh" &"# J m"A
5 A
	A
H u"v
6 v
	v
r  #p
-I p
p
f  #	h
/K h
h
XBII 0		 >  #	O
: O
O
r/   