o
    Zh*                     @   s  d Z ddlZddlZddlmZmZmZ ddlZddl	Z	ddl
Z	ddl	mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z# e rsddlm$Z$ e%e&Z'dZ(		dCdee)e)f de*de)dee	j+ de)dej,fddZ-G dd dej.Z/G dd dej.Z0G dd dej.Z1G d d! d!ej.Z2G d"d# d#ej.Z3G d$d% d%ej.Z4G d&d' d'ej.Z5G d(d) d)e5Z6G d*d+ d+ej.Z7G d,d- d-e7Z8G d.d/ d/e7Z9e7e9e8d0Z:G d1d2 d2ej.Z;G d3d4 d4ej.Z<G d5d6 d6ej.Z=eG d7d8 d8eZ>eG d9d: d:e>Z?ed;d<G d=d> d>e>Z@ed?d<G d@dA dAe>ZAg dBZBdS )DzPyTorch SEW model.    N)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)is_fsdp_managed_module)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutputCausalLMOutputSequenceClassifierOutput)PreTrainedModel)auto_docstringlogging)deprecate_kwarg   )	SEWConfig)_flash_attention_forwardshape	mask_probmask_lengthattention_mask	min_masksreturnc                    s  | \}dk rt dkrt d d dtjd   fdd}|dur:| d	 n
fd
dt|D }tj	|ft
d}g }	|}
|
dkrZ|S |D ];}||}tjjt|d  |dd}t|dkr}d }n|d }t|tj|
| tjd| g}|	| q\t|	}	t|	dddddf ||
f}	|	||
 }	tddddf }t|||
f||
 }|	| }	|	 d krd |	|	d k< t||	dd	 |S )af  
    Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
    ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
    CPU as part of the preprocessing during training.

    Args:
        shape: The shape for which to compute masks. This should be of a tuple of size 2 where
               the first element is the batch size and the second element is the length of the axis to span.
        mask_prob:  The percentage of the whole axis (between 0 and 1) which will be masked. The number of
                    independently generated mask spans of length `mask_length` is computed by
                    `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
                    actual percentage will be smaller.
        mask_length: size of the mask
        min_masks: minimum number of masked spans
        attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
                        each batch dimension.
    r   z&`mask_length` has to be bigger than 0.zO`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: z and `sequence_length`: `c                    sX   t |     }t|}| kr }| d  |k r*t| d  d}|S )z;Given input length, compute how many spans should be maskedr   r   )intmax)input_lengthnum_masked_spanepsilonr   r   r   sequence_length S/var/www/auris/lib/python3.10/site-packages/transformers/models/sew/modeling_sew.pycompute_num_masked_spanW   s   
z6_compute_mask_indices.<locals>.compute_num_masked_spanNc                    s   g | ]} qS r%   r%   .0_)r$   r%   r&   
<listcomp>j   s    z)_compute_mask_indices.<locals>.<listcomp>dtyper   F)replace)
ValueErrornprandomranditemdetachsumtolistrangezerosboolchoicearangelenZconcatenateonesZint32appendarrayZbroadcast_toreshaper   Zput_along_axis)r   r   r   r   r   
batch_sizer'   input_lengthsZspec_aug_maskZspec_aug_mask_idxsZmax_num_masked_spanr    r!   Zspec_aug_mask_idxZdummy_mask_idxoffsetsr%   r"   r&   _compute_mask_indices1   s\   

rE   c                       &   e Zd Zd fdd	Zdd Z  ZS )SEWNoLayerNormConvLayerr   c                    sj   t    |dkr|j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
t|j | _d S )Nr   r   kernel_sizestridebias)super__init__conv_dimin_conv_dimout_conv_dimr   Conv1dconv_kernelconv_stride	conv_biasconvr   feat_extract_activation
activationselfconfiglayer_id	__class__r%   r&   rM      s   
z SEWNoLayerNormConvLayer.__init__c                 C   s   |  |}| |}|S N)rU   rW   rY   hidden_statesr%   r%   r&   forward   s   

zSEWNoLayerNormConvLayer.forwardr   __name__
__module____qualname__rM   ra   __classcell__r%   r%   r\   r&   rG      s    rG   c                       rF   )SEWLayerNormConvLayerr   c                    s|   t    |dkr|j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
tj| jdd| _t|j | _d S )Nr   r   rH   T)Zelementwise_affine)rL   rM   rN   rO   rP   r   rQ   rR   rS   rT   rU   	LayerNorm
layer_normr   rV   rW   rX   r\   r%   r&   rM      s   
zSEWLayerNormConvLayer.__init__c                 C   s:   |  |}|dd}| |}|dd}| |}|S )Nr(   )rU   	transposerj   rW   r_   r%   r%   r&   ra      s   


zSEWLayerNormConvLayer.forwardrb   rc   r%   r%   r\   r&   rh      s    rh   c                       rF   )SEWGroupNormConvLayerr   c                    s   t    |dkr|j|d  nd| _|j| | _tj| j| j|j| |j| |j	d| _
t|j | _tj| j| jdd| _d S )Nr   r   rH   T)Z
num_groupsZnum_channelsZaffine)rL   rM   rN   rO   rP   r   rQ   rR   rS   rT   rU   r   rV   rW   	GroupNormrj   rX   r\   r%   r&   rM      s   
zSEWGroupNormConvLayer.__init__c                 C   "   |  |}| |}| |}|S r^   )rU   rj   rW   r_   r%   r%   r&   ra      s   


zSEWGroupNormConvLayer.forwardrb   rc   r%   r%   r\   r&   rm      s    rm   c                       $   e Zd Z fddZdd Z  ZS )SEWPositionalConvEmbeddingc                    s(  t    tj|j|j|j|jd |j|jd| _tj	j
}ttj	jdr)tj	jj
}t r}dd l}|jj| jjdd || jddd| _W d    n1 sNw   Y  t| jdrf| jjjj}| jjjj}n| jj}| jj}|j| | |j| | n	|| jddd| _t|j| _t|j | _d S )	N   )rI   paddinggroupsrJ   weight_normr   Zmodifier_rankweight)namedimparametrizations)rL   rM   r   rQ   hidden_sizenum_conv_pos_embeddingsZnum_conv_pos_embedding_groupssqueeze_factorrU   utilsru   hasattrrz   r	   	deepspeedzeroGatheredParametersrw   Z	original0Z	original1weight_gweight_vZregister_external_parameterSEWSamePadLayerrs   r   rV   rW   )rY   rZ   ru   r   r   r   r\   r%   r&   rM      s6   
	
z#SEWPositionalConvEmbedding.__init__c                 C   ro   r^   )rU   rs   rW   r_   r%   r%   r&   ra     s   


z"SEWPositionalConvEmbedding.forwardrc   r%   r%   r\   r&   rq      s    "rq   c                       rp   )r   c                    s*   t    |d dkrd| _d S d| _d S )Nrr   r   r   )rL   rM   num_pad_remove)rY   r|   r\   r%   r&   rM      s   
 zSEWSamePadLayer.__init__c                 C   s,   | j dkr|d d d d d | j  f }|S Nr   )r   r_   r%   r%   r&   ra   $  s   
zSEWSamePadLayer.forwardrc   r%   r%   r\   r&   r     s    r   c                       rp   )SEWUpsamplingc                    s:   t    t|j|j|j | _t|j | _	|j| _d S r^   )
rL   rM   r   Linearr{   r}   
projectionr   rV   rW   rY   rZ   r\   r%   r&   rM   +  s   
zSEWUpsampling.__init__c                 C   sd   |  |}| |}| jdkr0| \}}}|| j }|| j }|||| j|}||||}|S )Nr   )r   rW   r}   sizerA   )rY   r`   bszsrc_lenZsrc_embed_dimtgt_lenZtgt_embed_dimr%   r%   r&   ra   1  s   




zSEWUpsampling.forwardrc   r%   r%   r\   r&   r   *  s    r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )SEWFeatureEncoderz.Construct the features from raw audio waveformc                    s   t     jdkr t ddg fddt jd D  }n jdkr2 fddt jD }n	td	 j d
t|| _	d| _
d| _d S )Ngroupr   r[   c                    s   g | ]
}t  |d  dqS )r   r   )rG   r*   irZ   r%   r&   r,   H  s    z.SEWFeatureEncoder.__init__.<locals>.<listcomp>r   layerc                    s   g | ]}t  |d qS )r   )rh   r   r   r%   r&   r,   L  s    z`config.feat_extract_norm` is z), but has to be one of ['group', 'layer']FT)rL   rM   Zfeat_extract_normrm   r8   Znum_feat_extract_layersr0   r   
ModuleListconv_layersgradient_checkpointing_requires_grad)rY   rZ   r   r\   r   r&   rM   D  s   




zSEWFeatureEncoder.__init__c                 C   s   |   D ]}d|_qd| _d S NF)
parametersrequires_gradr   rY   paramr%   r%   r&   _freeze_parametersU  s   
z$SEWFeatureEncoder._freeze_parametersc                 C   s\   |d d d f }| j r| jrd|_| jD ]}| j r'| jr'| jr'| |j|}q||}q|S )NT)r   trainingr   r   r   _gradient_checkpointing_func__call__)rY   input_valuesr`   Z
conv_layerr%   r%   r&   ra   Z  s   

zSEWFeatureEncoder.forward)rd   re   rf   __doc__rM   r   ra   rg   r%   r%   r\   r&   r   A  s
    r   c                       s   e Zd Z fddZ  ZS )SEWFeatureExtractorc                    s8   t  | td| jj d| jjd j dt d S )NzThe class `zD` has been depreciated and will be removed in Transformers v5. Use `r   z
` instead.)rL   rM   warningswarnr]   rd   	__bases__FutureWarningr   r\   r%   r&   rM   n  s   zSEWFeatureExtractor.__init__)rd   re   rf   rM   rg   r%   r%   r\   r&   r   m  s    r   c                       s   e Zd ZdZ						ddededed	ed
ededee dee f fddZ	e
ddde
ddde
ddd						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 deejeej eeej  f fddZ  ZS )SEWAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderrK   	is_causalrZ   	layer_idxc	           	         s   t    || _|| _|| _|| | _|| _| j| | jkr*td| j d| d| jd | _|| _	|| _
|| _|d u rK| j	rKtd| jj d tj|||d| _tj|||d| _tj|||d| _tj|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.)rK   )rL   rM   r   r   r   head_dimrZ   r0   scalingr   r   r   loggerwarning_oncer]   rd   r   r   k_projv_projq_projout_proj)	rY   r   r   r   r   rK   r   rZ   r   r\   r%   r&   rM   |  s0   


zSEWAttention.__init__key_value_states4.55versionpast_key_valuecache_positionr`   r   layer_head_maskoutput_attentionsr   c                 C   s  |  \}}	}
| ||d| j| jdd}|| j }| ||d| j| jdd}| ||d| j| jdd}|| j d| jf}|j	| }|j	| }|j	| }| d}t
||dd}|  || j |	|fkrtd|| j |	|f d|   |dur|ddddddd|jd f }||| j|	|| }||| j |	|}tjj|dd}|dur|  | jfkrtd	| jf d|   |dddd||| j|	| }||| j |	|}|r||| j|	|}||| j |	|}nd}tjj|| j| jd
}t
||}|  || j |	| jfkr8td|| j |	| jf d|   ||| j|	| j}|dd}|	||	| j}| |}||dfS )#Input shape: Batch x Time x Channelr(   r   rr   z$Attention weights should be of size z	, but is Nrk   ry   z/Head mask for a single layer should be of size )pr   z `attn_output` should be of size )r   r   viewr   r   rl   r   r   r   rA   torchZbmmr0   r   r   
functionalsoftmaxr   r   r   r   )rY   r`   r   r   r   r   r   r   r   r   r+   query_states
key_statesvalue_statesZ
proj_shaper   attn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr%   r%   r&   ra     s`   "
""



&"

zSEWAttention.forward)r   FTFNNNNNNFN)rd   re   rf   r   r   floatr:   r   r   rM   r   r   Tensorr   ra   rg   r%   r%   r\   r&   r   y  sf    	
(

	r   c                       s   e Zd ZdZ fddZedddedddeddd									
		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 de	ejeej ee	ej  f fddZ  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                    s   t  j|i | t | _d S r^   )rL   rM   r   _flash_attn_uses_top_left_mask)rY   argskwargsr\   r%   r&   rM     s   zSEWFlashAttention2.__init__r   r   r   r   r   NFr`   r   r   r   r   c              
   C   s,  |rt d| \}}	}
| ||d| j| j}| |}| |}||d| j| j}||d| j| j}|j}|t	j
krqt	 rIt	 }nt| jdrT| jj}n| jjj}td| d ||}||}||}t|||||	| jr}| jnd| j| jd}|||	d}| |}|d d fS )NzSEWSdpaAttention2 attention does not support `output_attentions`. Use the argument `attn_implementation='eager'` when loading the model.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   Zuse_top_left_mask)r0   r   r   r   r   r   r   r   r.   r   float32Zis_autocast_enabledZget_autocast_gpu_dtyper   rZ   r   rw   r   r   tor   r   r   r   r   rA   r   )rY   r`   r   r   r   r   r   r   r   Zq_lenr+   r   r   r   Zinput_dtypeZtarget_dtyper   r%   r%   r&   ra     sL   










zSEWFlashAttention2.forwardr   )rd   re   rf   r   rM   r   r   r   r   r   r:   ra   rg   r%   r%   r\   r&   r     s:    
	

	r   c                       s   e Zd Zedddedddeddd						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 deejeej eeej  f f fddZ	  Z
S )SEWSdpaAttentionr   r   r   r   r   NFr`   r   r   r   r   c                    st  |rt d t j||||dS | \}}	}
| ||d| j| j	dd}| 
|}| |}||d| j| j	dd}||d| j| j	dd}d}|durh|ddddddd|jd f }|jjdkr~|dur~| }| }| }| jr|du r|	dkrd	nd
}tjjj||||| jr| jnd|d}|	dd }|||	| j}| |}|ddfS )r   a  SEWModel is using SEWSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` . Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r   r(   r   rr   Nrk   cudaTFr   )Z	attn_maskZ	dropout_pr   )r   r   rL   ra   r   r   r   r   r   rl   r   r   r   devicetype
contiguousr   r   r   r   Zscaled_dot_product_attentionr   r   r   r   )rY   r`   r   r   r   r   r   r   r   r   r+   r   r   r   Zcausal_maskr   r   r\   r%   r&   ra   T  sH   "

&	

zSEWSdpaAttention.forwardr   )rd   re   rf   r   r   r   r   r   r:   ra   rg   r%   r%   r\   r&   r   S  s6    


	r   )eagerZsdpaflash_attention_2c                       rp   )SEWFeedForwardc                    sp   t    t|j| _t|j|j| _	t
|jtr"t|j | _n|j| _t|j|j| _t|j| _d S r^   )rL   rM   r   DropoutZactivation_dropoutintermediate_dropoutr   r{   Zintermediate_sizeintermediate_dense
isinstanceZ
hidden_actstrr   intermediate_act_fnoutput_densehidden_dropoutoutput_dropoutr   r\   r%   r&   rM     s   
zSEWFeedForward.__init__c                 C   s6   |  |}| |}| |}| |}| |}|S r^   )r   r   r   r   r   r_   r%   r%   r&   ra     s   




zSEWFeedForward.forwardrc   r%   r%   r\   r&   r     s    r   c                       s&   e Zd Z fddZdddZ  ZS )SEWEncoderLayerc                    sl   t    t|j |j|j|jdd| _t	|j
| _tj|j|jd| _t|| _tj|j|jd| _d S )NF)r   r   r   r   Zeps)rL   rM   SEW_ATTENTION_CLASSES_attn_implementationr{   Znum_attention_headsZattention_dropout	attentionr   r   r   r   ri   layer_norm_epsrj   r   feed_forwardfinal_layer_normr   r\   r%   r&   rM     s   

zSEWEncoderLayer.__init__NFc                 C   sf   |}| j |||d\}}}| |}|| }| |}|| | }| |}|f}|r1||f7 }|S )Nr   r   )r   r   rj   r   r   )rY   r`   r   r   Zattn_residualr   r+   outputsr%   r%   r&   ra     s   



zSEWEncoderLayer.forwardr   rc   r%   r%   r\   r&   r     s    r   c                       s.   e Zd Z fddZ				dddZ  ZS )	
SEWEncoderc                    s   t     | _t | _t j j| _tj	 j
 jd| _t j| _t fddt jD | _t | _d| _ jdk| _d S )Nr   c                    s   g | ]}t  qS r%   )r   r)   r   r%   r&   r,     s    z'SEWEncoder.__init__.<locals>.<listcomp>Fr   )rL   rM   rZ   rq   pos_conv_embedr   Z	AvgPool1dr}   poolri   r{   r   rj   r   r   r   r   r8   num_hidden_layerslayersr   upsampler   r   _use_flash_attention_2r   r\   r   r&   rM     s   

 
zSEWEncoder.__init__NFTc              	   C   s  |rdnd }|r
dnd }|d ur| ddd|jd }| jr2d|| < |d ur/d|v r/|nd }nfd|| < | d}	|	| jj }
|jd | jj }tj	d||
j
ddd|
jd d}||
ddk  }d|d d d d d d f j|jd	 }|t|jj }||jd d|jd |jd }|jd }|dd}| |}| |}t|d|d}|d
d |f |d
d |f  }|dd}| |}| |}t pt| }| jD ]M}|r||f }tg }| jr|| jjk rdnd}|r|r | jr| jr| |j|||}n||||d}|d }|r%d}|r/||d f }q|r8||f }|  |}|jd |k rUt!j"#|ddd||jd  f}|sdt$dd |||fD S t%|||dS )Nr%   r(   r   rr   r   r   r         ?r-   .TFr   NNc                 s   s    | ]	}|d ur|V  qd S r^   r%   )r*   vr%   r%   r&   	<genexpr>I  s    z%SEWEncoder.forward.<locals>.<genexpr>Zlast_hidden_stater`   
attentions)&	unsqueezerepeatr   r   longr6   rZ   r}   r   r<   r   r   expandr   r.   Zfinfominrl   r   r   r   rj   r   r	   r
   r   r3   r   Z	layerdropr   r   r   r   r   r   padtupler   )rY   r`   r   r   output_hidden_statesreturn_dictZall_hidden_statesZall_self_attentionsZexpand_attention_maskrC   output_lengthsZmax_encoder_lengthZattention_idsZn_input_timestepsZposition_embeddingsZpooled_hidden_statesZ
min_lengthZsynced_gpusr   Zdropout_probabilityZskip_the_layerZlayer_outputsr%   r%   r&   ra     s   

&


 






 zSEWEncoder.forward)NFFTrc   r%   r%   r\   r&   r     s    r   c                   @   sX   e Zd ZeZdZdZdZdZdZ	dd Z
deejef fddZd	ed
ejfddZdS )SEWPreTrainedModelsewr   Tc              	   C   s  t |tr)tjj|jjddtd|jj	d |jj
   d tj|jjd nt |tjr;|jjjd| jjd n}t |tjtjfrR|jj  |jjd nft |tjrt rddl}t|drt|d	r|jj|j|jgdd
 tj|jj W d   n1 sw   Y  n*|jj|jdd
 tj|jj W d   n1 sw   Y  ntj|jj t |tjtjfr|jdur|jj  dS dS dS )zInitialize the weightsr   rr   r   )meanZstdr   r   Nr   r   rv   )r   rq   r   initZnormal_rU   rw   mathsqrtrI   Zin_channelsZ	constant_rK   r   datarZ   Zinitializer_rangeri   rn   Zzero_Zfill_rQ   r	   r   r   r   r   r   r   Zkaiming_normal_)rY   moduler   r%   r%   r&   _init_weightsZ  s8   
 z SEWPreTrainedModel._init_weightsrC   c                 C   s4   dd }t | jj| jjD ]
\}}||||}q|S )zH
        Computes the output length of the convolutional layers
        c                 S   s   t j| | |ddd S )Nfloor)Zrounding_moder   )r   div)r    rI   rJ   r%   r%   r&   _conv_out_length  s   zMSEWPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_length)ziprZ   rR   rS   )rY   rC   r  rI   rJ   r%   r%   r&    _get_feat_extract_output_lengthsz  s   z3SEWPreTrainedModel._get_feat_extract_output_lengthsfeature_vector_lengthr   c                 C   s~   |  |dtj}|jd }tj||f|j|jd}d|tj	|jd |jd|d f< |
dgd
dg }|S )Nr(   r   )r.   r   r   r   )r  r6   r   r   r  r   r9   r.   r   r<   flipZcumsumr:   )rY   r  r   r  rB   r%   r%   r&   "_get_feature_vector_attention_mask  s   
"z5SEWPreTrainedModel._get_feature_vector_attention_maskN)rd   re   rf   r   Zconfig_classZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingZ_supports_flash_attn_2Z_supports_sdpar  r   r   
LongTensorr   r  r  r%   r%   r%   r&   r  Q  s     r  c                       s   e Zd Zdef fddZ		ddejdeej deej fdd	Z	e
					dd
eej deej deej dee dee dee deeef fddZ  ZS )SEWModelrZ   c                    s   t  | || _t|| _tj|jd |jd| _	|jd |j
k| _| jr1t|jd |j
| _t|j| _|jdksB|jdkrNtt|j
 | _t|| _|   d S )Nr(   r   r   )rL   rM   rZ   r   feature_extractorr   ri   rN   r   rj   r{   project_featuresr   feature_projectionr   Zfeat_proj_dropoutfeature_dropoutmask_time_probmask_feature_prob	Parameterr   r   Zuniform_masked_spec_embedr   encoder	post_initr   r\   r%   r&   rM     s   

zSEWModel.__init__Nr`   mask_time_indicesr   c                 C   s  t | jdds	|S | \}}}|dur| j|j||< n-| jjdkrK| jrKt||f| jj| jj	|| jj
d}tj||jtjd}| j|j||< | jjdkr| jrt||f| jj| jj| jjd}tj||jtjd}|dddf d|d}d||< |S )	z
        Masks extracted features along time axis and/or along feature axis according to
        [SpecAugment](https://arxiv.org/abs/1904.08779).
        Zapply_spec_augmentTNr   )r   r   r   r   )r   r.   )r   r   r   r(   )getattrrZ   r   r'  r   r.   r$  r   rE   Zmask_time_lengthZmask_time_min_masksr   Ztensorr   r:   r%  Zmask_feature_lengthZmask_feature_min_masksr  )rY   r`   r*  r   rB   r$   r{   Zmask_feature_indicesr%   r%   r&   _mask_hidden_states  s4   zSEWModel._mask_hidden_statesr   r   r
  r  r   c           
      C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| |}|dd}| |}| jr6| |}| 	|}|durH| 
|jd |}| j||d}| j|||||d}	|	d }|sh|f|	dd  S t||	j|	jdS )a/  
        mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
            masked extracted features in *config.proj_codevector_dim* space.
        Nr   rr   )r*  r   r   r
  r  r   r  )rZ   r   r
  use_return_dictr   rl   rj   r!  r"  r#  r  r   r,  r(  r   r`   r  )
rY   r   r   r*  r   r
  r  Zextract_featuresr`   Zencoder_outputsr%   r%   r&   ra     s8   



zSEWModel.forwardr   NNNNN)rd   re   rf   r   rM   r   ZFloatTensorr   r  r,  r   r   r:   r   r   r   ra   rg   r%   r%   r\   r&   r    s@    
.
r  zk
    SEW Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
    )Zcustom_introc                       s   e Zd Zddee f fddZdd Zdd Zd	d
 Zdd Z	e
					ddeej deej dee dee dee deej deeef fddZ  ZS )	SEWForCTCNtarget_langc                    s~   t  | t|| _t|j| _|| _|j	du r#t
d| j dt|dr.|jr.|jn|j}t||j	| _|   dS )a-  
        target_lang (`str`, *optional*):
            Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
            adapter.<lang>.bin. Only relevant when using an instance of [`SEWForCTC`] with adapters. Uses 'eng' by
            default.
        NzYou are trying to instantiate z with a configuration that does not define the vocabulary size of the language model head. Please instantiate the model as follows: `SEWForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.add_adapter)rL   rM   r  r  r   r   Zfinal_dropoutr   r1  
vocab_sizer0   r]   r   r2  output_hidden_sizer{   r   lm_headr)  )rY   rZ   r1  r4  r\   r%   r&   rM     s   

zSEWForCTC.__init__c                 C   sv   | j }|durt| jdddu rtd| d|du r,t| jdddur,td dS |dur9| j|d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.
        NZ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)Z
force_load)r1  r+  rZ   r0   r   infoZload_adapter)rY   r1  r%   r%   r&   tie_weights5  s   zSEWForCTC.tie_weightsc                 C      t 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rY   r%   r%   r&   freeze_feature_extractorJ  
   z"SEWForCTC.freeze_feature_extractorc                 C      | j j  dS r9  Nr  r   r   r=  r%   r%   r&   r<  V     z SEWForCTC.freeze_feature_encoderc                 C      | j  D ]}d|_qdS z
        Calling this function will disable the gradient computation for the base model so that its parameters will not
        be updated during training. Only the classification head will be updated.
        FNr  r   r   r   r%   r%   r&   freeze_base_model]     zSEWForCTC.freeze_base_modelr   r   r   r
  r  labelsr   c              
   C   s|  |dur|n| j j}|dur| | j jkrtd| j j | j|||||d}|d }| |}| |}	d}
|dur|durC|ntj	|tj
d}| |dtj
}|dk}|d}||}tjj|	dtjddd}tjjjd	d
 tjj||||| j j| j j| j jd}
W d   n1 sw   Y  |s|	f|td  }|
dur|
f| S |S t|
|	|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
            Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
            the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
            All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
            config.vocab_size - 1]`.
        Nz$Label values must be <= vocab_size: r-  r   r-   r(   )ry   r.   r   F)enabled)blankZ	reductionZzero_infinitylosslogitsr`   r  )rZ   r.  r   r3  r0   r  r   r5  r   Z	ones_liker  r  r6   r   Zmasked_selectr   r   Zlog_softmaxr   rl   backendsZcudnnflagsZctc_lossZpad_token_idZctc_loss_reductionZctc_zero_infinity_HIDDEN_STATES_START_POSITIONr   r`   r  )rY   r   r   r   r
  r  rI  r   r`   rN  rM  rC   Zlabels_maskZtarget_lengthsZflattened_targetsZ	log_probsoutputr%   r%   r&   ra   e  sN   



zSEWForCTC.forwardr^   r/  )rd   re   rf   r   r   rM   r7  r>  r<  rG  r   r   r   r:   r   r   r   ra   rg   r%   r%   r\   r&   r0    s6    
r0  z
    SEW Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB
    Keyword Spotting.
    c                       s   e Zd Z fddZdd Zdd Zdd Ze										dd
ee	j
 dee	j
 dee dee dee dee	j
 deeef fddZ  ZS )SEWForSequenceClassificationc                    s   t  | t|dr|jrtdt|| _|jd }|jr*t	
t|| | _t	|j|j| _t	|j|j| _|   d S )Nr2  zZSequence classification does not support the use of SEW adapters (config.add_adapter=True)r   )rL   rM   r   r2  r0   r  r  r   use_weighted_layer_sumr   r&  r   r>   layer_weightsr   r{   Zclassifier_proj_size	projector
num_labels
classifierr)  )rY   rZ   Z
num_layersr\   r%   r&   rM     s   

z%SEWForSequenceClassification.__init__c                 C   r8  )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=  r%   r%   r&   r>    r?  z5SEWForSequenceClassification.freeze_feature_extractorc                 C   r@  rA  rB  r=  r%   r%   r&   r<    rC  z3SEWForSequenceClassification.freeze_feature_encoderc                 C   rD  rE  rF  r   r%   r%   r&   rG    rH  z.SEWForSequenceClassification.freeze_base_modelNr   r   r   r
  r  rI  r   c                 C   sz  |dur|n| j j}| j jrdn|}| j|||||d}| j jrB|t }tj|dd}tjj	| j
dd}	||	ddd jdd}n|d }| |}|du rV|jdd}
n+| |jd |}|ddd|jd }d	|| < |jdd|jdddd }
| |
}d}|durt }||d| j j|d}|s|f|td  }|dur|f| S |S t|||j|jd
S )a  
        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 [`SEWProcessor.__call__`] for details.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NTr-  r   r   r(   r   rr   r   rL  )rZ   r.  rT  r  rQ  r   stackr   r   r   rU  r   r6   rV  r  r  r   r  r  rX  r   rW  r   r`   r  )rY   r   r   r   r
  r  rI  r   r`   Znorm_weightsZpooled_outputZpadding_maskZexpand_padding_maskrN  rM  Zloss_fctrR  r%   r%   r&   ra     sH   

 
z$SEWForSequenceClassification.forwardr/  )rd   re   rf   rM   r>  r<  rG  r   r   r   r   r:   r   r   r   ra   rg   r%   r%   r\   r&   rS    s4    
rS  )r0  rS  r  r  r   )Cr   r  r   typingr   r   r   numpyr1   r   Ztorch.utils.checkpointr   Ztorch.nnr   Zactivationsr   Zintegrations.deepspeedr	   Zintegrations.fsdpr
   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   Zmodeling_utilsr   r~   r   r   Zutils.deprecationr   Zconfiguration_sewr   r   Z
get_loggerrd   r   rQ  r   r   r  ZndarrayrE   ModulerG   rh   rm   rq   r   r   r   r   r   r   r   r   r   r   r   r  r  r0  rS  __all__r%   r%   r%   r&   <module>   s   


x,, XL#oDz r