
    gv                    r   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 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"  e            rddl#m$Z$  e j%        e&          Z'dZ(dZ)dZ*g dZ+dZ,dZ-dZ.dZ/dZ0	 	 dIdee1e1f         de2de1dee	j3                 de1dej4        fdZ5 G d d ej6                  Z7 G d! d"ej6                  Z8 G d# d$ej6                  Z9 G d% d&ej6                  Z: G d' d(ej6                  Z; G d) d*ej6                  Z< G d+ d,ej6                  Z= G d- d.e=          Z> G d/ d0ej6                  Z? G d1 d2e?          Z@ G d3 d4e?          ZAe?eAe@d5ZB G d6 d7ej6                  ZC G d8 d9ej6                  ZD G d: d;ej6                  ZE G d< d=e          ZFd>ZGd?ZH ed@eG           G dA dBeF                      ZI edCeG           G dD dEeF                      ZJ edFeG           G dG dHeF                      ZKdS )JzPyTorch SEW model.    N)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)is_fsdp_managed_module)BaseModelOutputCausalLMOutputSequenceClassifierOutput)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logging   )	SEWConfig)_flash_attention_forwardr   zasapp/sew-tiny-100k-ft-ls100h)r   i$  i   z_'MISTER QUILTER IS THE APPOSTILE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPOLLE'gzG?z(anton-l/sew-mid-100k-ft-keyword-spottingz'_unknown_'g
ףp=
#@shape	mask_probmask_lengthattention_mask	min_masksreturnc                 @   | \  }dk     rt          d          k    rt          d d d          t          j                            d                                          fd}|9|                    d                                                                          nfd	t          |          D             }t          j	        |ft          
          }g }	 |          }
|
dk    r|S |D ]} ||          }t          j                            t          j        |dz
  z
            |d          }t          |          dk    rdz
  }n|d         }t          j        |t          j        |
|z
  t          j        
          |z  g          }|	                    |           t          j        |	          }	t          j        |	dddddf         ||
f          }	|	                    ||
z            }	t          j                  ddddf         }t          j        |||
f                              ||
z            }|	|z   }	|	                                dz
  k    rdz
  |	|	dz
  k    <   t          j        ||	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                     t          | z  z  z             }t          |          }|z  k    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     `/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/sew/modeling_sew.pycompute_num_masked_spanz6_compute_mask_indices.<locals>.compute_num_masked_spann   s~    i,6DwNOOoy99 [(?::-<O ;?+o==!,+/"BAFFO    Nc                     g | ]}S  r-   ).0_r'   s     r(   
<listcomp>z)_compute_mask_indices.<locals>.<listcomp>   s    999!o999r*   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_indicesrR   H   sP   0 #(JQABBB_$$:^i : :'6: : :
 
 	
 innQ$$&&G        $ % 	2%%''..0009999uZ'8'8999  Hj/:$GGGM11/BBa% 5 511,?? I,,IlkAo677RW - 
 
  !!Q&& -q0NN.q1NN(;o(MUWU] ^ ^ ^ao op
 
 	!!"34444"455 111aaa:&5H+(V  ,33J@SVa@abb i$$T4]3Gog
4G'UVV^^'+5 G ,g5 /A"555GVYZGZ-!0CCD m%7B???r*   c                   &     e Zd Zd fd	Zd Z xZS )SEWNoLayerNormConvLayerr   c                 Z   t                                                       |dk    r|j        |dz
           nd| _        |j        |         | _        t          j        | j        | j        |j        |         |j        |         |j	                  | _
        t          |j                 | _        d S )Nr   r   kernel_sizestridebias)super__init__conv_dimin_conv_dimout_conv_dimr   Conv1dconv_kernelconv_stride	conv_biasconvr	   feat_extract_activation
activationselfconfiglayer_id	__class__s      r(   r[   z SEWNoLayerNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@r*   c                 Z    |                      |          }|                     |          }|S N)rc   re   rg   hidden_statess     r(   forwardzSEWNoLayerNormConvLayer.forward   s*    		-0066r*   r   __name__
__module____qualname__r[   ro   __classcell__rj   s   @r(   rT   rT      sR        A A A A A A      r*   rT   c                   &     e Zd Zd fd	Zd Z xZS )SEWLayerNormConvLayerr   c                    t                                                       |dk    r|j        |dz
           nd| _        |j        |         | _        t          j        | j        | j        |j        |         |j        |         |j	                  | _
        t          j        | j        d          | _        t          |j                 | _        d S )Nr   r   rV   T)elementwise_affine)rZ   r[   r\   r]   r^   r   r_   r`   ra   rb   rc   	LayerNorm
layer_normr	   rd   re   rf   s      r(   r[   zSEWLayerNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 ,t'8TRRR !?@r*   c                     |                      |          }|                    dd          }|                     |          }|                    dd          }|                     |          }|S )Nr+   )rc   	transposer|   re   rm   s     r(   ro   zSEWLayerNormConvLayer.forward   se    		-00%//B7766%//B7766r*   rp   rq   rv   s   @r(   rx   rx      sR        A A A A A A      r*   rx   c                   &     e Zd Zd fd	Zd Z xZS )SEWGroupNormConvLayerr   c                    t                                                       |dk    r|j        |dz
           nd| _        |j        |         | _        t          j        | j        | j        |j        |         |j        |         |j	                  | _
        t          |j                 | _        t          j        | j        | j        d          | _        d S )Nr   r   rV   T)
num_groupsnum_channelsaffine)rZ   r[   r\   r]   r^   r   r_   r`   ra   rb   rc   r	   rd   re   	GroupNormr|   rf   s      r(   r[   zSEWGroupNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@,$2CRVRclpqqqr*   c                     |                      |          }|                     |          }|                     |          }|S rl   )rc   r|   re   rm   s     r(   ro   zSEWGroupNormConvLayer.forward  s;    		-006666r*   rp   rq   rv   s   @r(   r   r      sR        r r r r r r       r*   r   c                   $     e Zd Z fdZd Z xZS )SEWPositionalConvEmbeddingc                    t                                                       t          j        |j        |j        |j        |j        dz  |j        |j                  | _        t          j	        j
        }t          t          j	        j        d          rt          j	        j        j
        }t                      rdd l}|j                            | j        j        d          5   || j        dd          | _        d d d            n# 1 swxY w Y   t          | j        d          r-| j        j        j        j        }| j        j        j        j        }n| j        j        }| j        j        }|j                            | |           |j                            | |           n || j        dd          | _        t/          |j                  | _        t2          |j                 | _        d S )	N   )rW   paddinggroupsrX   weight_normr   modifier_rankweight)namedimparametrizations)rZ   r[   r   r_   hidden_sizenum_conv_pos_embeddingsnum_conv_pos_embedding_groupssqueeze_factorrc   utilsr   hasattrr   r
   	deepspeedzeroGatheredParametersr   	original0	original1weight_gweight_vregister_external_parameterSEWSamePadLayerr   r	   rd   re   )rg   rh   r   r   r   r   rj   s         r(   r[   z#SEWPositionalConvEmbedding.__init__  s   I62a77(
 
 
	 h*28,m<< 	@(3?K%'' 	E22493CST2UU I I'K	aHHH	I I I I I I I I I I I I I I Ity"455 .95<F95<F9-9-N66tXFFFN66tXFFFF#DIH!DDDDI&v'EFF !?@s    DD	D	c                     |                      |          }|                     |          }|                     |          }|S rl   )rc   r   re   rm   s     r(   ro   z"SEWPositionalConvEmbedding.forward-  s;    		-00]3366r*   rq   rv   s   @r(   r   r   
  sM         A  A  A  A  AD      r*   r   c                   $     e Zd Z fdZd Z xZS )r   c                 l    t                                                       |dz  dk    rdnd| _        d S )Nr   r   r   )rZ   r[   num_pad_remove)rg   r   rj   s     r(   r[   zSEWSamePadLayer.__init__7  s:    #:Q#>!#C#Caar*   c                 J    | j         dk    r|d d d d d | j          f         }|S Nr   )r   rm   s     r(   ro   zSEWSamePadLayer.forward;  s;    "")!!!QQQ0F43F2F0F*FGMr*   rq   rv   s   @r(   r   r   6  sL        K K K K K      r*   r   c                   $     e Zd Z fdZd Z xZS )SEWUpsamplingc                     t                                                       t          j        |j        |j        |j        z            | _        t          |j                 | _	        |j        | _        d S rl   )
rZ   r[   r   Linearr   r   
projectionr	   rd   re   rg   rh   rj   s     r(   r[   zSEWUpsampling.__init__B  sZ    )F$68JVMb8bcc !?@$3r*   c                 0   |                      |          }|                     |          }| j        dk    r`|                                \  }}}|| j        z  }|| j        z  }|                    ||| j        |          }|                    |||          }|S )Nr   )r   re   r   sizerH   )rg   rn   bszsrc_lensrc_embed_dimtgt_lentgt_embed_dims          r(   ro   zSEWUpsampling.forwardH  s    6666""*7*<*<*>*>'C- 33G)T-@@M)11#w@SUbccM)11#wNNMr*   rq   rv   s   @r(   r   r   A  sG        4 4 4 4 4      r*   r   c                   .     e Zd ZdZ fdZd Zd Z xZS )SEWFeatureEncoderz.Construct the features from raw audio waveformc                    t                                                       j        dk    r7t          d          gfdt	          j        dz
            D             z   }nDj        dk    r!fdt	          j                  D             }nt          dj         d	          t          j        |          | _	        d
| _
        d| _        d S )Ngroupr   ri   c                 8    g | ]}t          |d z             S )r   r   )rT   r.   irh   s     r(   r0   z.SEWFeatureEncoder.__init__.<locals>.<listcomp>_  s>     I I IDE'Q???I I Ir*   r   layerc                 2    g | ]}t          |           S )r   )rx   r   s     r(   r0   z.SEWFeatureEncoder.__init__.<locals>.<listcomp>c  s'    ttt0!DDDtttr*   z`config.feat_extract_norm` is z), but has to be one of ['group', 'layer']FT)rZ   r[   feat_extract_normr   r<   num_feat_extract_layersr4   r   
ModuleListconv_layersgradient_checkpointing_requires_grad)rg   rh   r   rj   s    ` r(   r[   zSEWFeatureEncoder.__init__[  s   #w..0!DDDE I I I IINvOmpqOqIrIrI I I KK %00tttteTZTrNsNstttKKt1Ittt   =55&+#"r*   c                 P    |                                  D ]	}d|_        
d| _        d S NF)
parametersrequires_gradr   rg   params     r(   _freeze_parametersz$SEWFeatureEncoder._freeze_parametersl  s4    __&& 	( 	(E"'E#r*   c                     |d d d f         }| j         r| j        rd|_        | j        D ]>}| j         r*| j        r#| j        r|                     |j        |          }3 ||          }?|S )NT)r   trainingr   r   r   _gradient_checkpointing_func__call__)rg   input_valuesrn   
conv_layers       r(   ro   zSEWFeatureEncoder.forwardq  s    $QQQW-  	/4= 	/*.M'* 	: 	:J" :t'B :t} : $ A A'!! !
 !+
= 9 9r*   )rr   rs   rt   __doc__r[   r   ro   ru   rv   s   @r(   r   r   X  s\        88# # # # #"$ $ $
      r*   r   c                        e Zd Z fdZ xZS )SEWFeatureExtractorc                     t                                          |           t          j        d| j        j         d| j        j        d         j         dt                     d S )NzThe class `zD` has been depreciated and will be removed in Transformers v5. Use `r   z
` instead.)rZ   r[   warningswarnrj   rr   	__bases__FutureWarningr   s     r(   r[   zSEWFeatureExtractor.__init__  sy       E$.1 E EN,Q/8E E E 		
 	
 	
 	
 	
r*   )rr   rs   rt   r[   ru   rv   s   @r(   r   r     s8        
 
 
 
 
 
 
 
 
r*   r   c                   h    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 )SEWAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderrY   	is_causalrh   c                 
   t                                                       || _        || _        || _        ||z  | _        || _        | j        |z  | j        k    rt          d| j         d| d          | j        dz  | _        || _	        || _
        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      )rY   )rZ   r[   r   r   r   head_dimrh   r4   scalingr   r   r   r   k_projv_projq_projout_proj)	rg   r   r   r   r   rY   r   rh   rj   s	           r(   r[   zSEWAttention.__init__  s    	""!Y.MI%$.883dn 3 3%.3 3 3   }d*$"i	94@@@i	94@@@i	94@@@	)YTBBBr*   tensorseq_lenr   c                     |                     ||| j        | j                                      dd                                          S )Nr   r   )viewr   r   r   
contiguousrg   r   r   r   s       r(   _shapezSEWAttention._shape  s<    {{3GGQQRSUVWWbbdddr*   rn   key_value_statespast_key_valuer   layer_head_maskoutput_attentionsr   c                 Z
   |du}|                                 \  }}	}
|                     |          | j        z  }|r6|4|d         j        d         |j        d         k    r|d         }|d         }n>|rU|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j	        r||f}|| j
        z  d| j        f} |                     ||	|          j        | } |j        | } |j        | }|                     d          }t          j        ||                    dd                    }|                                 || j
        z  |	|fk    r2t!          d|| j
        z  |	|f d|                                            ||                                 |d|	|fk    r+t!          d	|d|	|f d|                                            |                    || j
        |	|          |z   }|                    || j
        z  |	|          }t"          j                            |d          }||                                 | j
        fk    r-t!          d
| j
        f d|                                            |                    dddd          |                    || j
        |	|          z  }|                    || j
        z  |	|          }|r=|                    || j
        |	|          }|                    || j
        z  |	|          }nd}t"          j                            || j        | j                  }t          j        ||          }|                                 || j
        z  |	| j        fk    r7t!          d|| j
        z  |	| j        f d|                                            |                    || j
        |	| j                  }|                    dd          }|                    ||	| j                  }|                     |          }|||fS )#Input shape: Batch x Time x ChannelNr   r   r   r+   r   z$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 )r   r   r   r   r   r   r   torchcatr   r   r   r   rH   bmmr   r4   r   
functionalsoftmaxr   r   r   r   )rg   rn   r   r   r   r   r   is_cross_attentionr   r   r/   query_states
key_statesvalue_states
proj_shaper   attn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r(   ro   zSEWAttention.forward  s    .T9',,..Wa {{=11DL@ 	L*q!'*.>.DQ.GGG (*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7NDN*B>
Ct{{<#>>CZP'Z'4
+|+Z8//!$$yz/C/CAq/I/IJJ3#7'"JJJ*dn8LgW^7_ * * %%''* *  
 %""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (,,S$.'7SSVddL',,S4>-A7GTTL},,\r,BB&##%%$.)::: 1t~FW 1 1',,..1 1   +//2q!<<|?P?PQTVZVdfmov?w?wwL',,S4>-A7GTTL 	)
 %1$5$5c4>7T[$\$\!055cDN6JGU\]]LL$(!]**<4<RVR_*``
i
L99#"6!OOO)C$.4H'SWS`3a ) )$$&&) )  
 "&&sDNGT]SS!++Aq11 "))#wGGmmK001>AAr*   )r   FTFNNNNNF)rr   rs   rt   r   r"   floatr>   r   r   r[   r   Tensorr   r   ro   ru   rv   s   @r(   r   r     s       GG  &*C CC C 	C
 C C C #C C C C C C>eU\ eC ec e e e e 488<1526"'vB vB|vB #5<0vB !u|!45	vB
 !.vB "%,/vB  vB 
u|Xel3XeEL>Q5RR	SvB vB vB vB vB vB vB vBr*   r   c                   2    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 )SEWFlashAttention2aB  
    SEW flash attention module. This module inherits from `SEWAttention` 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                 b     t                      j        |i | t                       | _        d S rl   )rZ   r[   r   _flash_attn_uses_top_left_mask)rg   argskwargsrj   s      r(   r[   zSEWFlashAttention2.__init__7  s9    $)&)))
 3V2W2W.W+++r*   r   r   r   c                 F    |                     ||| j        | j                  S rl   )r   r   r   r   s       r(   _reshapezSEWFlashAttention2._reshape?  s    {{3GGGr*   NFrn   r   r   r   r   r   r   c           
      R   |rt          d          |d u}|                                \  }}	}
|                     |                     |          d|          }|r^|\|d         j        d         |j        d         k    r:|d                             dd          }|d                             dd          }ng|rV|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j	        |d                             dd          |gd          }t          j	        |d                             dd          |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j
        r,|                    dd          |                    dd          f}|j        d         }|||d         j        d         z  }|j        }|t          j        k    rt          j                    rt          j                    }n3t          | j        d          r| j        j        }n| j        j        j        }t&                              d	| d
           |                    |          }|                    |          }|                    |          }t-          |||||	| j        r| j        nd| j        | j                  }|                    ||	d          }|                     |          }|sd }|||fS )Nz?SEWFlashAttention2 attention does not support output_attentionsr+   r   r   r   r   r~   _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   r   r   r   r   r   r   r2   float32is_autocast_enabledget_autocast_gpu_dtyper   rh   r  r   loggerwarning_oncetor   r   r   r   r  rH   r   )rg   rn   r   r   r   r   r   r  r   q_lenr/   r  r  r  
kv_seq_leninput_dtypetarget_dtyper	  r  s                      r(   ro   zSEWFlashAttention2.forwardB  s     	`^___ .T9%**,,UA }}T[[%?%?SII 	N*q!'*.>.DQ.GGG (*44Q::J)!,66q!<<LL 	Nt{{3C'D'Db#NNJ==5E)F)FCPPLL't{{='A'A2sKKJ==])C)CRMMLN1$5$?$?1$E$Ez#RXYZZZJ 9nQ&7&A&A!Q&G&G%V\]^^^LL t{{='A'A2sKKJ==])C)CRMML? 	X )221a88,:P:PQRTU:V:VWN%b)
%.+1"55J #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.$(M:DLLsn"A	
 	
 	
 "))#ub99mmK00  	 LL.88r*   r
  )rr   rs   rt   r   r[   r   r  r"   r  r   r   r>   ro   ru   rv   s   @r(   r  r  /  s;        X X X X XHu| Hc H H H H H 488<1526"'i9 i9|i9 #5<0i9 !u|!45	i9
 !.i9 "%,/i9  i9 
u|Xel3XeEL>Q5RR	Si9 i9 i9 i9 i9 i9 i9 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 )SEWSdpaAttentionNFrn   r   r   r   r   r   r   c                    |s|At                               d           t                                          ||||||          S |du}|                                \  }}	}
|                     |          }|r6|4|d         j        d         |j        d         k    r|d         }|d         }n>|rU|                     |                     |          d|          }|                     | 	                    |          d|          }n||                     |                     |          d|          }|                     | 	                    |          d|          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|          }|                     | 	                    |          d|          }| j        r||f}|                     ||	|          }| j        r
||	dk    rd	nd
}t          j        j                            ||||| j        r| j        nd|          }|                                || j        |	| j        fk    r5t+          d|| j        |	| j        f d|                                           |                    dd          }|                    ||	| j                  }|                     |          }|d|fS )r   Na  SEWModel is using SEWSdpaAttention, 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   r+   r   TFr   )	attn_mask	dropout_pr   r   r   )r  r  rZ   ro   r   r   r   r   r   r   r   r   r   r   r   r   scaled_dot_product_attentionr   r   r   r   r4   r   rH   r   r   )rg   rn   r   r   r   r   r   r  r   r   r/   r  r  r  r   r	  rj   s                   r(   ro   zSEWSdpaAttention.forward  sK     	 ;l   77??!1-- /"3 #    .T9',,..Wa {{=11 	L*q!'*.>.DQ.GGG (*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7N{{<#>>
 !N`~/E'TU++DD[`	 h)FF$&*m<dll G 
 
 #t~w!NNN)CRVR_3` ) )$$&&) )  
 "++Aq11 "))#wGGmmK00D.00r*   r
  )
rr   rs   rt   r   r  r   r   r>   ro   ru   rv   s   @r(   r$  r$    s        
 488<1526"'f1 f1|f1 #5<0f1 !u|!45	f1
 !.f1 "%,/f1  f1 
u|Xel3XeEL>Q5RR	Sf1 f1 f1 f1 f1 f1 f1 f1 f1 f1r*   r$  )eagersdpaflash_attention_2c                   $     e Zd Z fdZd Z xZS )SEWFeedForwardc                    t                                                       t          j        |j                  | _        t          j        |j        |j                  | _	        t          |j        t                    rt          |j                 | _        n|j        | _        t          j        |j        |j                  | _        t          j        |j                  | _        d S rl   )rZ   r[   r   Dropout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SEWFeedForward.__init__"  s    $&Jv/H$I$I!"$)F,>@X"Y"Yf'-- 	9'-f.?'@D$$'-'8D$If&>@RSS j)>??r*   c                     |                      |          }|                     |          }|                     |          }|                     |          }|                     |          }|S rl   )r3  r7  r1  r8  r:  rm   s     r(   ro   zSEWFeedForward.forward/  sg    //>>00??11-@@))-88++M::r*   rq   rv   s   @r(   r-  r-  !  sL        @ @ @ @ @      r*   r-  c                   &     e Zd Z fdZddZ xZS )SEWEncoderLayerc                    t                                                       t          |j                 |j        |j        |j        d          | _        t          j	        |j
                  | _        t          j        |j        |j                  | _        t          |          | _        t          j        |j        |j                  | _        d S )NF)r   r   r   r   eps)rZ   r[   SEW_ATTENTION_CLASSES_attn_implementationr   num_attention_headsattention_dropout	attentionr   r/  r9  r   r{   layer_norm_epsr|   r-  feed_forwardfinal_layer_normr   s     r(   r[   zSEWEncoderLayer.__init__;  s    .v/JK(0,	
 
 
 z&"788,v'9v?TUUU*622 "V-?VEZ [ [ [r*   NFc                    |}|                      |||          \  }}}|                     |          }||z   }|                     |          }||                     |          z   }|                     |          }|f}|r||fz  }|S )Nr   r   )rE  r   r|   rG  rH  )rg   rn   r   r   attn_residualr  r/   outputss           r(   ro   zSEWEncoderLayer.forwardI  s    %)-.L] *8 *
 *
&|Q ]33%566%(9(9-(H(HH--m<< " 	'&Gr*   r   rq   rv   s   @r(   r=  r=  :  sQ        \ \ \ \ \       r*   r=  c                   .     e Zd Z fdZ	 	 	 	 ddZ xZS )
SEWEncoderc                    t                                                       | _        t                    | _        t          j        j        j                  | _        t          j	        j
        j                  | _        t          j        j                  | _        t          j        fdt#          j                  D                       | _        t)                    | _        d| _        j        dk    | _        d S )Nr?  c                 .    g | ]}t                    S r-   )r=  )r.   r/   rh   s     r(   r0   z'SEWEncoder.__init__.<locals>.<listcomp>e  s!    $f$f$f_V%<%<$f$f$fr*   Fr+  )rZ   r[   rh   r   pos_conv_embedr   	AvgPool1dr   poolr{   r   rF  r|   r/  r9  r   r   r<   num_hidden_layerslayersr   upsampler   rB  _use_flash_attention_2r   s    `r(   r[   zSEWEncoder.__init__^  s    8@@L!68MNN	,v'9v?TUUUz&"788m$f$f$f$feFLdFeFe$f$f$fgg%f--&+#&,&AEX&X###r*   NFTc           	      D   |rdnd }|rdnd }|p| j         rd|| <   |d|v r|nd }nWd|| <   |                                                    d          }|| j        j        z  }	|j        d         | j        j        z  }
t          j        d|
|	j                  	                    dd          
                    |	j        d         d          }||		                    dd          k                                     }d|d d d d d d f                             |j                  z
  }|t          j        |j                  j        z  }|
                    |j        d         d|j        d         |j        d                   }|j        d         }|                    dd	          }|                     |          }|                     |          }t          |                    d          |                    d                    }|d
d |f         |d
d |f         z   }|                    dd	          }|                     |          }|                     |          }t+                      pt-          |           }| j        D ]}|r||fz   }t          j        g           }| j        r|| j        j        k     rdnd}|r|rB| j        r%| j        r|                     |j        |||          }n ||||          }|d         }|rd}|r||d         fz   }|r||fz   }|                     |          }|j        d         |k     r2t>          j         !                    |ddd||j        d         z
  f          }|stE          d |||fD                       S tG          |||          S )Nr-   r   r   r+   r   device      ?r1   r   .TFrJ  NNc              3      K   | ]}||V  	d S rl   r-   )r.   vs     r(   	<genexpr>z%SEWEncoder.forward.<locals>.<genexpr>  s(      mmq_`_l_l_l_l_lmmr*   last_hidden_statern   
attentions)$rW  longr9   rh   r   r   r   r@   rZ  r   expandr  r2   finfominr   rQ  rS  r   r|   r   r
   r   rU  r7   r   	layerdropr   r   r   rV  r   r   padtupler   )rg   rn   r   r   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsrK   output_lengthsmax_encoder_lengthattention_idsn_input_timestepsposition_embeddingspooled_hidden_states
min_lengthsynced_gpusr   dropout_probabilityskip_the_layerlayer_outputss                        r(   ro   zSEWEncoder.forwardj  sI    #7@BBD$5?bb4%* 14~o.4B4NSTXfSfSfmq 25~o.!/!4!4!6!6 ; ;B ? ?!.$+2L!L%2%8%;t{?Y%Y"L$6~?TUUUT!R[[VN03R88 
 #0.2E2Eb!2L2L"L!R!R!T!T "%~aaatQQQ6F'G'J'JQ^Qd'J'e'e!e!/%+m>Q2R2R2V!V!/!6!6"(+Q0DR0H.J^_aJb" " */2%//155"11-@@#yy77,11"557K7P7PQS7T7TUU
,S+:+-=>ATUXZe[eZeUeAff%//15566]33022R6LT6R6R[ 	P 	PE# I$58H$H! #(*R..%)]o8KdkNc8c8cTTjoN! 1[ 1. 
4= 
$($E$E%&)	% %MM %*E%nXi% % %M !.a 0 - ,  P&9]1=M<O&O# 	E 1]4D Dm44q!$555M--maAGX[h[nop[qGq=rssM 	nmm]4EGZ$[mmmmmm++*
 
 
 	
r*   )NFFTrq   rv   s   @r(   rN  rN  ]  sg        
Y 
Y 
Y 
Y 
Y "_
 _
 _
 _
 _
 _
 _
 _
r*   rN  c                   p    e Zd ZdZeZdZdZdZdZ	dZ
d Zdeej        ef         fdZded	ej        fd
ZdS )SEWPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    sewr   Tc           
         t          |t                    rt          j                            |j        j        ddt          j        d|j        j	        d         |j        j
        z  z            z             t          j                            |j        j        d           nt          |t          j                  r-|j        j                            d| j        j                   nt          |t          j        t          j        f          r?|j        j                                         |j        j                            d           nCt          |t          j                  r(t-                      rddl}t1          |d          rzt1          |d	          rj|j                            |j        |j        gd
          5  t          j                            |j        j                   ddd           n# 1 swxY w Y   n|j                            |j        d
          5  t          j                            |j        j                   ddd           n# 1 swxY w Y   n)t          j                            |j        j                   t          |t          j        t          j        f          r'|j        "|j        j                                         dS dS dS )zInitialize the weightsr   r   r   )meanstdr   r[  Nr   r   r   )r4  r   r   initnormal_rc   r   mathsqrtrW   in_channels	constant_rY   r   datarh   initializer_ranger{   r   zero_fill_r_   r
   r   r   r   r   r   r   kaiming_normal_)rg   moduler   s      r(   _init_weightsz SEWPreTrainedModel._init_weights  s   f899 	<GOO"	!v{'>q'AFKD['["\]]]    
 Gfk.2222	** 	< M&&CT[5R&SSSSr| <== 	<K""$$$M$$S))))	** 	<)++ 
<    6:.. D76:3N3N D"::FOV_;]mn:oo D D//0BCCCD D D D D D D D D D D D D D D #::6=XY:ZZ D D//0BCCCD D D D D D D D D D D D D D D ''(:;;;fry")455 	%&+:QK""$$$$$	% 	%:Q:Qs$   *G::G>G>'*II!$I!rK   c                 z    d }t          | j        j        | j        j                  D ]\  }} ||||          }|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_lengthzMSEWPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_length  s&     9\K7wWWWZ[[[r*   )ziprh   r`   ra   )rg   rK   r  rW   rX   s        r(    _get_feat_extract_output_lengthsz3SEWPreTrainedModel._get_feat_extract_output_lengths  s\    
	\ 	\ 	\
 $'t{'>@W#X#X 	Q 	QK,,]KPPMMr*   feature_vector_lengthr   c                    |                      |                    d                                        t          j                  }|j        d         }t          j        ||f|j        |j                  }d|t          j	        |j        d         |j                  |dz
  f<   |
                    dg                              d          
                    dg                                          }|S )Nr+   r   )r2   rZ  r   rY  )r  r9   r  r   rc  r   r=   r2   rZ  r@   flipcumsumr>   )rg   r  r   rn  rJ   s        r(   "_get_feature_vector_attention_maskz5SEWPreTrainedModel._get_feature_vector_attention_mask  s    >>~?Q?QRT?U?UVVYYZ_Zdee#)!,
./~7KTbTi
 
 
 uv^%9!%<^EZ[[[]kno]opq',,bT2299"==BBB4HHMMOOr*   N)rr   rs   rt   r   r   config_classbase_model_prefixmain_input_namesupports_gradient_checkpointing_supports_flash_attn_2_supports_sdpar  r   r   
LongTensorr"   r  r  r-   r*   r(   rz  rz    s         
 L$O&*#!N% % %@eEDTVYDY>Z    
 
]b]m 
 
 
 
 
 
r*   rz  a  
    SEW was proposed in [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech
    Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger,
    Yoav Artzi.

    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 ([`SEWConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
            Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
            into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install
            soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and
            conversion into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
        attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
            1]`:

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

            [What are attention masks?](../glossary#attention-mask)

        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.
z]The bare SEW Model transformer outputting raw hidden-states without any specific head on top.c                   h    e Zd Zdef f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 )SEWModelrh   c                    t                                          |           || _        t          |          | _        t          j        |j        d         |j                  | _	        |j        d         |j
        k    | _        | j        r*t          j        |j        d         |j
                  | _        t          j        |j                  | _        |j        dk    s|j        dk    rBt          j        t)          j        |j
                                                            | _        t1          |          | _        |                                  d S )Nr+   r?  r   )rZ   r[   rh   r   feature_extractorr   r{   r\   rF  r|   r   project_featuresr   feature_projectionr/  feat_proj_dropoutfeature_dropoutmask_time_probmask_feature_prob	Parameterr   r  uniform_masked_spec_embedrN  encoder	post_initr   s     r(   r[   zSEWModel.__init__H  s      !26!:!:,vr':@UVVV & 3v7I I  	Y&(i0CVEW&X&XD#!z&*BCC 3&&&*BS*H*H%'\%,v?Q2R2R2[2[2]2]%^%^D"!&)) 	r*   Nrn   mask_time_indicesr   c                    t          | j        dd          s|S |                                \  }}}|#| j                            |j                  ||<   n| j        j        dk    r| j        r|t          ||f| j        j        | j        j	        || j        j
                  }t          j        ||j        t          j                  }| j                            |j                  ||<   | j        j        dk    r| j        rt          ||f| j        j        | j        j        | j        j                  }t          j        ||j        t          j                  }|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).
        apply_spec_augmentTNr   )r   r   r   r   )rZ  r2   )r   r   r   r+   )getattrrh   r   r  r  r2   r  r   rR   mask_time_lengthmask_time_min_masksr   r   rZ  r>   r  mask_feature_lengthmask_feature_min_masksrd  )rg   rn   r  r   rJ   r'   r   mask_feature_indicess           r(   _mask_hidden_stateszSEWModel._mask_hidden_states\  s    t{$8$?? 	!   4A3E3E3G3G0
O[(/3/E/H/HI\/]/]M+,,['!+++ 5_-+4 K8-+9! ! ! !&->}G[chcm n n n/3/E/H/HI\/]/]M+,;(1,,,#8[)+7 K;+<	$ $ $  $)<0D]Mainis#t#t#t #74#@#G#GO]_#`#` 23M./r*   audio)
checkpointoutput_typer  modalityexpected_outputr   r   rj  rk  r   c                 T   ||n| j         j        }||n| j         j        }||n| j         j        }|                     |          }|                    dd          }|                     |          }| j        r|                     |          }| 	                    |          }|!| 
                    |j        d         |          }|                     ||          }|                     |||||          }	|	d         }|s|f|	dd          z   S t          ||	j        |	j                  S )Nr   r   )r  r   r   rj  rk  r   r`  )rh   r   rj  use_return_dictr  r   r|   r  r  r  r  r   r  r  r   rn   rb  )
rg   r   r   r  r   rj  rk  extract_featuresrn   encoder_outputss
             r(   ro   zSEWModel.forward  sr   " 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]11,??+55a;;??+;<<  	I#667GHH,,-=>>%!DD]EXYZE[]kllN00Rc0dd,,)/!5# ' 
 
 (* 	:!#oabb&999+)7&1
 
 
 	
r*   r\  NNNNN)rr   rs   rt   r   r[   r   FloatTensorr   r  r  r   SEW_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr  r>   r   r   ro   ru   rv   s   @r(   r  r  C  sw       
y      . :>59	, ,(, $E$56, !!12	, , , ,\ +*+?@@&#$.   269=,0/3&*.
 .
u|,.
 !..
 $E$56	.

 $D>.
 'tn.
 d^.
 
uo%	&.
 .
 .
  A@.
 .
 .
 .
 .
r*   r  zaSEW Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).c                   >    e Zd Zddee         f fdZd Z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 )	SEWForCTCNtarget_langc                    t                                          |           t          |          | _        t	          j        |j                  | _        || _        |j	        t          d| j         d          t          |d          r|j        r|j        n|j        }t	          j        ||j	                  | _        |                                  d S )NzYou are trying to instantiate z with a configuration that does not define the vocabulary size of the language model head. Please instantiate the model as follows: `SEWForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.add_adapter)rZ   r[   r  r{  r   r/  final_dropoutr   r  
vocab_sizer4   rj   r   r  output_hidden_sizer   r   lm_headr  )rg   rh   r  r  rj   s       r(   r[   zSEWForCTC.__init__  s       F##z&"677&$H H H H   *1)G)GvFL^vF%%djdv 	 y!3V5FGG 	r*   c                    | j         }|)t          | j        dd          t          d| d          |2t          | j        dd          t                              d           dS ||                     |d           dS dS )a'  
        This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
        passing `target_lang=...` to `from_pretrained(...)`.

        This method is **not** supposed to be called by the user and is prone to be changed in the future.
        Nadapter_attn_dimzCannot pass `target_lang`: z- if `config.adapter_attn_dim` is not defined.z)By default `target_lang` is set to 'eng'.T)
force_load)r  r  rh   r4   r  infoload_adapter)rg   r  s     r(   tie_weightszSEWForCTC.tie_weights  s     &"wt{<NPT'U'U']u;uuuvvv WT[:Ld%S%S%_KKCDDDDD$kd;;;;; %$r*   c                 b    t          j        dt                     |                                  dS )
        Calling this function will disable the gradient computation for the feature encoder so that its parameter will
        not be updated during training.
        The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. Please use the equivalent `freeze_feature_encoder` method instead.Nr   r   r   freeze_feature_encoderrg   s    r(   freeze_feature_extractorz"SEWForCTC.freeze_feature_extractor  ;    
 	Q	
 	
 	

 	##%%%%%r*   c                 B    | j         j                                         dS r  Nr{  r  r   r  s    r(   r  z SEWForCTC.freeze_feature_encoder  !    
 	"5577777r*   c                 L    | j                                         D ]	}d|_        
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   r   r   s     r(   freeze_base_modelzSEWForCTC.freeze_base_model  6    
 X((** 	( 	(E"'E	( 	(r*   )r  r  r  r  expected_lossr   r   r   rj  rk  labelsr   c           
      p   ||n| j         j        }|>|                                | j         j        k    rt	          d| j         j                   |                     |||||          }|d         }|                     |          }|                     |          }	d}
|Z||nt          j	        |t          j
                  }|                     |                    d                                        t          j
                  }|dk    }|                    d          }|                    |          }t          j                            |	dt          j                                      dd          }t          j        j                            d	
          5  t          j                            ||||| j         j        | j         j        | j         j                  }
ddd           n# 1 swxY w Y   |s|	f|t6          d         z   }|
|
f|z   n|S t9          |
|	|j        |j                  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   r1   r+   )r   r2   r   F)enabled)blank	reductionzero_infinitylosslogitsrn   rb  )rh   r  r#   r  r4   r{  r   r  r   	ones_likerc  r  r9   r  masked_selectr   r   log_softmaxr  r   backendscudnnflagsctc_losspad_token_idctc_loss_reductionctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   rn   rb  )rg   r   r   r   rj  rk  r  rL  rn   r  r  rK   labels_masktarget_lengthsflattened_targets	log_probsoutputs                    r(   ro   zSEWForCTC.forward  s   0 &1%<kk$+B]&**,,$+2H"H"H\DKDZ\\]]](()/!5#  
 
  
]33m,, #1"<%/R^fkfpBqBqBq  !AA.BTBTUWBXBXYY\\]b]ghhM !A+K(__R00N & 4 4[ A A 11&b1VV``abdeffI%++E+:: 	 	}--%!"+2"k<"&+"? .  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	FY)F)G)G!HHF)-)9TGf$$vEfG4IV]Vh
 
 
 	
s    AG11G58G5rl   r  )rr   rs   rt   r   r6  r[   r  r  r  r  r   r  r   r  r   r  _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr   r  r>   r   r   ro   ru   rv   s   @r(   r  r    sz        HSM      .< < <*
& 
& 
&8 8 8( ( ( +*+?@@&"$,(   26,0/3&*)-D
 D
u|,D
 !.D
 $D>	D

 'tnD
 d^D
 &D
 
un$	%D
 D
 D
  A@D
 D
 D
 D
 D
r*   r  z
    SEW 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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 )SEWForSequenceClassificationc                    t                                          |           t          |d          r|j        rt	          d          t          |          | _        |j        dz   }|j        r.t          j
        t          j        |          |z            | _        t          j        |j        |j                  | _        t          j        |j        |j                  | _        |                                  d S )Nr  zZSequence classification does not support the use of SEW adapters (config.add_adapter=True)r   )rZ   r[   r   r  r4   r  r{  rT  use_weighted_layer_sumr   r  r   rC   layer_weightsr   r   classifier_proj_size	projector
num_labels
classifierr  )rg   rh   
num_layersrj   s      r(   r[   z%SEWForSequenceClassification.__init__h  s       6=)) 	f.@ 	l   F##-1
( 	S!#ej.D.Dz.Q!R!RD6#5v7RSS)F$?ARSS 	r*   c                 b    t          j        dt                     |                                  dS )z
        Calling this function will disable the gradient computation for the feature encoder so that its parameters will
        not be updated during training.
        r  Nr  r  s    r(   r  z5SEWForSequenceClassification.freeze_feature_extractory  r  r*   c                 B    | j         j                                         dS r  r  r  s    r(   r  z3SEWForSequenceClassification.freeze_feature_encoder  r  r*   c                 L    | j                                         D ]	}d|_        
dS r  r  r   s     r(   r  z.SEWForSequenceClassification.freeze_base_model  r  r*   r  )r  r  r  r  r  r  Nr   r   r   rj  rk  r  r   c                    ||n| j         j        }| j         j        rdn|}|                     |||||          }| j         j        rx|t                   }t          j        |d          }t          j        	                    | j
        d          }	||	                    ddd          z                      d          }n|d         }|                     |          }||                    d          }
nh|                     |j        d         |          }d|| <   |                    d          |                    d                              dd          z  }
|                     |
          }d}|Kt%                      } ||                    d| j         j                  |                    d                    }|s|f|t          d         z   }||f|z   n|S t)          |||j        |j        	          S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NTr  r   r   r+   r   r   r  )rh   r  r  r{  r  r   stackr   r   r   r	  r   r9   r  r}  r  r   r  r   r  r   rn   rb  )rg   r   r   r   rj  rk  r  rL  rn   norm_weightspooled_outputpadding_maskr  r  loss_fctr  s                   r(   ro   z$SEWForSequenceClassification.forward  s&   2 &1%<kk$+B]'+{'IcttOc(()/!5#  
 
 ;- 	'#$ABM!K1===M=001C0LLL*\->->r1a-H-HHMMRSMTTMM#AJM}55!)..1.55MMBB=CVWXCY[ijjL+.M<-()--!-44|7G7GA7G7N7N7S7STVXY7Z7ZZM//'))H8FKKDK,BCCV[[QS__UUD 	FY)F)G)G!HHF)-)9TGf$$vE'!/)	
 
 
 	
r*   r  )rr   rs   rt   r[   r  r  r  r   r  r   _SEQ_CLASS_CHECKPOINTr   r  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r   r  r>   r   r   ro   ru   rv   s   @r(   r  r  _  sJ           "
& 
& 
&8 8 8( ( ( +*+?@@(,$2.   26,0/3&*)-;
 ;
u|,;
 !.;
 $D>	;

 'tn;
 d^;
 &;
 
u..	/;
 ;
 ;
  A@;
 ;
 ;
 ;
 ;
r*   r  r   )Lr   r  r   typingr   r   r   numpyr5   r   torch.utils.checkpointr   torch.nnr   activationsr	   integrations.deepspeedr
   integrations.fsdpr   modeling_outputsr   r   r   modeling_utilsr   r   r   r   r   r   r   r   configuration_sewr   modeling_flash_attention_utilsr   
get_loggerrr   r  r  r  r  r  r  r  r  r  r  r"   r  r  ndarrayrR   ModulerT   rx   r   r   r   r   r   r   r   r  r$  rA  r-  r=  rN  rz  SEW_START_DOCSTRINGr  r  r  r  r-   r*   r(   <module>r*     sD       ) ) ) ) ) ) ) ) ) )                % % % % % % ! ! ! ! ! ! @ @ @ @ @ @ 7 7 7 7 7 7 Y Y Y Y Y Y Y Y Y Y - - - - - -                ) ( ( ( ( (  KJJJJJJ 
	H	%	% !"   6 &  f    C *   26t tc?tt t U-.	t
 t Zt t t tp    bi   ,    BI   8    BI   0( ( ( ( ( ( ( (X    bi       BI   .) ) ) ) )	 ) ) )X
 
 
 
 
+ 
 
 
[B [B [B [B [B29 [B [B [B~|9 |9 |9 |9 |9 |9 |9 |9~h1 h1 h1 h1 h1| h1 h1 h1X +      RY   2         bi      Fl
 l
 l
 l
 l
 l
 l
 l
^F F F F F F F FR & 6 c y
 y
 y
 y
 y
! y
 y
	 y
x k 
T
 T
 T
 T
 T
" T
 T
 
T
n   q
 q
 q
 q
 q
#5 q
 q
 q
 q
 q
r*   