
    g!                       d 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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	 	 dOd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<          Z= G d- d.e
j6                  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
j6                  ZF G d> d?e
j6                  ZG G d@ dAe
j6                  ZH G dB dCe          ZIdDZJdEZK edFeJ           G dG dHeI                      ZL edIeJ           G dJ dKeI                      ZM edLeJ           G dM dNeI                      ZNdS )PzPyTorch Hubert 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replace_return_docstrings   )HubertConfig)_flash_attention_forwardr   zfacebook/hubert-large-ls960-ft)r   i$  i   z['MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'gGz6@zsuperb/hubert-base-superb-ksz'_unknown_'g(\!@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     f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/hubert/modeling_hubert.pycompute_num_masked_spanz6_compute_mask_indices.<locals>.compute_num_masked_spank   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_indicesrS   E   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 )HubertNoLayerNormConvLayerr   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#HubertNoLayerNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@r+   c                 Z    |                      |          }|                     |          }|S N)rd   rf   rh   hidden_statess     r)   forwardz"HubertNoLayerNormConvLayer.forward   s*    		-0066r+   r   __name__
__module____qualname__r\   rp   __classcell__rk   s   @r)   rU   rU      sR        A A A A A A      r+   rU   c                   &     e Zd Zd fd	Zd Z xZS )HubertLayerNormConvLayerr   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   rW   T)elementwise_affine)r[   r\   r]   r^   r_   r   r`   ra   rb   rc   rd   	LayerNorm
layer_normr	   re   rf   rg   s      r)   r\   z!HubertLayerNormConvLayer.__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,   )rd   	transposer}   rf   rn   s     r)   rp   z HubertLayerNormConvLayer.forward   se    		-00%//B7766%//B7766r+   rq   rr   rw   s   @r)   ry   ry      sR        A A A A A A      r+   ry   c                   &     e Zd Zd fd	Zd Z xZS )HubertGroupNormConvLayerr   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   rW   T)
num_groupsnum_channelsaffine)r[   r\   r]   r^   r_   r   r`   ra   rb   rc   rd   r	   re   rf   	GroupNormr}   rg   s      r)   r\   z!HubertGroupNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@,$2CRVRclpqqqr+   c                     |                      |          }|                     |          }|                     |          }|S rm   )rd   r}   rf   rn   s     r)   rp   z HubertGroupNormConvLayer.forward   s;    		-006666r+   rq   rr   rw   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 )HubertPositionalConvEmbeddingc                    t                                                       t          j        |j        |j        |j        |j        dz  |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                  | _        t0          |j                 | _        d S )	N   )rX   paddinggroupsweight_normr   modifier_rankweight)namedimparametrizations)r[   r\   r   r`   hidden_sizenum_conv_pos_embeddingsnum_conv_pos_embedding_groupsrd   utilsr   hasattrr   r
   	deepspeedzeroGatheredParametersr   	original0	original1weight_gweight_vregister_external_parameterHubertSamePadLayerr   r	   re   rf   )rh   ri   r   r   r   r   rk   s         r)   r\   z&HubertPositionalConvEmbedding.__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)&*HII !?@s   C??DDc                     |                     dd          }|                     |          }|                     |          }|                     |          }|                     dd          }|S Nr   r   )r   rd   r   rf   rn   s     r)   rp   z%HubertPositionalConvEmbedding.forward*  se    %//155		-00]3366%//155r+   rr   rw   s   @r)   r   r     sM        A A A A AB      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   )r[   r\   num_pad_remove)rh   r   rk   s     r)   r\   zHubertSamePadLayer.__init__7  s:    #:Q#>!#C#Caar+   c                 J    | j         dk    r|d d d d d | j          f         }|S Nr   )r   rn   s     r)   rp   zHubertSamePadLayer.forward;  s;    "")!!!QQQ0F43F2F0F*FGMr+   rr   rw   s   @r)   r   r   6  sL        K K K K K      r+   r   c                   .     e Zd ZdZ fdZd Zd Z xZS )HubertFeatureEncoderz.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   rj   c                 8    g | ]}t          |d z             S )r   r   )rU   r/   iri   s     r)   r1   z1HubertFeatureEncoder.__init__.<locals>.<listcomp>I  s>     L L LGH*6AEBBBL L Lr+   r   layerc                 2    g | ]}t          |           S )r   )ry   r   s     r)   r1   z1HubertFeatureEncoder.__init__.<locals>.<listcomp>M  s'    wwwA3FQGGGwwwr+   z`config.feat_extract_norm` is z), but has to be one of ['group', 'layer']FT)r[   r\   feat_extract_normr   r=   num_feat_extract_layersr5   r   
ModuleListconv_layersgradient_checkpointing_requires_grad)rh   ri   r   rk   s    ` r)   r\   zHubertFeatureEncoder.__init__E  s   #w..3FQGGGH L L L LLQRXRpstRtLuLuL L L KK %00wwwwQVW]WuQvQvwwwKKt1Ittt   =55&+#"r+   c                 P    |                                  D ]	}d|_        
d| _        d S NF)
parametersrequires_gradr   rh   params     r)   _freeze_parametersz'HubertFeatureEncoder._freeze_parametersV  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__)rh   input_valuesro   
conv_layers       r)   rp   zHubertFeatureEncoder.forward[  s    $QQQW-  	/4= 	/*.M'* 	: 	:J" :t'B :t} : $ A A'!! !
 !+
= 9 9r+   )rs   rt   ru   __doc__r\   r   rp   rv   rw   s   @r)   r   r   B  s\        88# # # # #"$ $ $
      r+   r   c                        e Zd Z fdZ xZS )HubertFeatureExtractorc                     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.)r[   r\   warningswarnrk   rs   	__bases__FutureWarningrh   ri   rk   s     r)   r\   zHubertFeatureExtractor.__init__o  sy       E$.1 E EN,Q/8E E E 		
 	
 	
 	
 	
r+   )rs   rt   ru   r\   rv   rw   s   @r)   r   r   n  s8        
 
 
 
 
 
 
 
 
r+   r   c                   $     e Zd Z fdZd Z xZS )HubertFeatureProjectionc                 T   t                                                       |j        | _        | j        r+t          j        |j        d         |j                  | _        t          j        |j        d         |j	                  | _
        t          j        |j                  | _        d S )Nr,   eps)r[   r\   feat_proj_layer_normr   r|   r]   layer_norm_epsr}   Linearr   
projectionDropoutfeat_proj_dropoutdropoutr   s     r)   r\   z HubertFeatureProjection.__init__z  s    $*$?!$ 	[ l6?2+>FDYZZZDO)FOB$79KLLz&":;;r+   c                     | j         r|                     |          }|                     |          }|                     |          }|S rm   )r   r}   r   r   rn   s     r)   rp   zHubertFeatureProjection.forward  sF    $ 	; OOM::M66]33r+   rr   rw   s   @r)   r   r   y  sG        < < < < <      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 )HubertAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsr   
is_decoderrZ   	is_causalri   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      )rZ   )r[   r\   r   r   r   head_dimri   r5   scalingr   r   r   r   k_projv_projq_projout_proj)	rh   r   r   r   r   rZ   r   ri   rk   s	           r)   r\   zHubertAttention.__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_lenbszc                     |                     ||| j        | j                                      dd                                          S r   )viewr   r   r   
contiguousrh   r   r   r   s       r)   _shapezHubertAttention._shape  s<    {{3GGQQRSUVWWbbdddr+   ro   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 )sizer   r   r   r   r   r   torchcatr   r   r   r   rI   bmmr   r5   r   
functionalsoftmaxr   r   r   r   )rh   ro   r   r   r   r   r   is_cross_attentionr   tgt_lenr0   query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r)   rp   zHubertAttention.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)rs   rt   ru   r   r#   floatr?   r   r   r\   r   Tensorr   r   rp   rv   rw   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 )HubertFlashAttention2aH  
    Hubert flash attention module. This module inherits from `HubertAttention` 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 rm   )r[   r\   r   _flash_attn_uses_top_left_mask)rh   argskwargsrk   s      r)   r\   zHubertFlashAttention2.__init__3  s9    $)&)))
 3V2W2W.W+++r+   r   r   r   c                 F    |                     ||| j        | j                  S rm   )r   r   r   r   s       r)   _reshapezHubertFlashAttention2._reshape;  s    {{3GGGr+   NFro   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 )NzBHubertFlashAttention2 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)r5   r   r  r   r   r   r   r   r   r   r   r3   float32is_autocast_enabledget_autocast_gpu_dtyper   ri   r  r   loggerwarning_oncetor   r   r   r   r  rI   r   )rh   ro   r   r   r   r   r   r  r   q_lenr0   r  r  r  
kv_seq_leninput_dtypetarget_dtyper  r  s                      r)   rp   zHubertFlashAttention2.forward>  s     	cabbb .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  )rs   rt   ru   r   r\   r   r  r#   r  r   r   r?   rp   rv   rw   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 )HubertSdpaAttentionNFro   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  HubertModel is using HubertSdpaAttention, 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"  r[   rp   r   r   r   r   r   r   r   r   r   r   r   r  scaled_dot_product_attentionr   r   r   r   r5   r   rI   r   r   )rh   ro   r   r   r   r   r   r  r   r  r0   r  r  r  r   r  rk   s                   r)   rp   zHubertSdpaAttention.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  )
rs   rt   ru   r   r  r   r   r?   rp   rv   rw   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 )HubertFeedForwardc                    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 rm   )r[   r\   r   r   activation_dropoutintermediate_dropoutr   r   intermediate_sizeintermediate_dense
isinstance
hidden_actstrr	   intermediate_act_fnoutput_densehidden_dropoutoutput_dropoutr   s     r)   r\   zHubertFeedForward.__init__  s    $&Jv/H$I$I!"$)F,>@X"Y"Yf'-- 	9'-f.?'@D$$'-'8D$If&>@RSS j)>??r+   c                     |                      |          }|                     |          }|                     |          }|                     |          }|                     |          }|S rm   )r7  r;  r5  r<  r>  rn   s     r)   rp   zHubertFeedForward.forward+  sg    //>>00??11-@@))-88++M::r+   rr   rw   s   @r)   r2  r2    sL        @ @ @ @ @      r+   r2  c                   &     e Zd Z fdZddZ xZS )HubertEncoderLayerc                    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   r   )r[   r\   HUBERT_ATTENTION_CLASSES_attn_implementationr   num_attention_headsattention_dropout	attentionr   r   r=  r   r|   r   r}   r2  feed_forwardfinal_layer_normr   s     r)   r\   zHubertEncoderLayer.__init__7  s    1&2MN(0,	
 
 
 z&"788,v'9v?TUUU-f55 "V-?VEZ [ [ [r+   NFc                    |}|                      |||          \  }}}|                     |          }||z   }|                     |          }||                     |          z   }|                     |          }|f}|r||fz  }|S Nr   r   )rH  r   r}   rI  rJ  rh   ro   r   r   attn_residualr  r0   outputss           r)   rp   zHubertEncoderLayer.forwardE  s    %)-.L] *8 *
 *
&|Q ]33%566%(9(9-(H(HH--m<< " 	'&Gr+   r   rr   rw   s   @r)   rA  rA  6  sQ        \ \ \ \ \       r+   rA  c                   4     e Zd Z fdZdej        fdZ xZS )HubertAttnAdapterLayerc                 t   t                                                       |j        | _        |j        | _        t          j        | j                  | _        t          j	        | j        | j                  | _
        t          j                    | _        t          j	        | j        | j                  | _        dS )z
        Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
        up training throughput.
        N)r[   r\   adapter_attn_dim	input_dimr   
hidden_dimr   r|   normr   linear_1ReLUact_fnlinear_2r   s     r)   r\   zHubertAttnAdapterLayer.__init__[  s    
 	0 ,L11		$/4>BBgii	$.$/BBr+   ro   c                     |                      |          }|                     |          }|                     |          }|                     |          }|S rm   )rW  rX  rZ  r[  rn   s     r)   rp   zHubertAttnAdapterLayer.forwardi  sL    		-00m44M22m44r+   )rs   rt   ru   r\   r   FloatTensorrp   rv   rw   s   @r)   rR  rR  Z  s[        C C C C CU%6        r+   rR  c                   X     e Zd Z fdZ	 	 ddej        deej                 defdZ xZ	S )	!HubertEncoderLayerStableLayerNormc                     t                                                       t          |j                 |j        |j        |j        d          | _        t          j	        |j
                  | _        t          j        |j        |j                  | _        t          |          | _        t          j        |j        |j                  | _        t%          |dd           t'          |          | _        d S d | _        d S )NFrC  r   rT  )r[   r\   rD  rE  r   rF  rG  rH  r   r   r=  r   r|   r   r}   r2  rI  rJ  getattrrR  adapter_layerr   s     r)   r\   z*HubertEncoderLayerStableLayerNorm.__init__u  s    1&2MN(0,	
 
 
 z&"788,v'9v?TUUU-f55 "V-?VEZ [ [ [6-t44@!7!?!?D!%Dr+   NFro   r   r   c                 J   |}|                      |          }|                     |||          \  }}}|                     |          }||z   }||                     |                     |                    z   }| j        ||                     |          z   }|f}|r||fz  }|S rL  )r}   rH  r   rI  rJ  rb  rN  s           r)   rp   z)HubertEncoderLayerStableLayerNorm.forward  s     &66)-.L] *8 *
 *
&|Q ]33%5%(9(9$:O:OP]:^:^(_(__))D,>,>},M,MMM " 	'&Gr+   r   )
rs   rt   ru   r\   r   r  r   r?   rp   rv   rw   s   @r)   r_  r_  t  s~        & & & & &* 26"'	 | !.  	       r+   r_  c                   d     e Zd Z fdZ	 	 	 	 ddej        deej                 deded	ef
d
Z	 xZ
S )HubertEncoderc                    t                                                       | _        t                    | _        t          j        j        j                  | _	        t          j
        j                  | _        t          j        fdt          j                  D                       | _        d| _        j        dk    | _        d S )Nr   c                 .    g | ]}t                    S r.   )rA  r/   r0   ri   s     r)   r1   z*HubertEncoder.__init__.<locals>.<listcomp>  s"    $i$i$iA%7%?%?$i$i$ir+   Fr0  r[   r\   ri   r   pos_conv_embedr   r|   r   r   r}   r   r=  r   r   r=   num_hidden_layerslayersr   rE  _use_flash_attention_2r   s    `r)   r\   zHubertEncoder.__init__  s    ;FCC,v'9v?TUUUz&"788m$i$i$i$ivOgIhIh$i$i$ijj&+#&,&AEX&X###r+   NFTro   r   r   output_hidden_statesreturn_dictc                 (   |rdnd }|rdnd }||                     d                              dd|j        d                   }d|| <   | j        r|d|v r|nd }nd|d d d d d d f                             |j                  z
  }|t          j        |j                  j        z  }|	                    |j        d         d|j        d         |j        d                   }| 
                    |          }	||	z   }|                     |          }|                     |          }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   }|st/          d |||fD                       S t1          |||          S )Nr.   r,   r   r   r         ?r2   TFrM  NNc              3      K   | ]}||V  	d S rm   r.   r/   vs     r)   	<genexpr>z(HubertEncoder.forward.<locals>.<genexpr>  (      mmq_`_l_l_l_l_lmmr+   last_hidden_statero   
attentions)	unsqueezerepeatr   rm  r#  r3   r   finfominexpandrj  r}   r   r
   r   rl  r8   r   ri   	layerdropr   r   r   tupler   rh   ro   r   r   rn  ro  all_hidden_statesall_self_attentionsexpand_attention_maskposition_embeddingssynced_gpusr   dropout_probabilityskip_the_layerlayer_outputss                  r)   rp   zHubertEncoder.forward  s    #7@BBD$5?bb4%$2$<$<R$@$@$G$G1mNabcNd$e$e!45M001* 	4B4NSTXfSfSfmq "%~aaatQQQ6F'G'J'JQ^Qd'J'e'e!e!/%+m>Q2R2R2V!V!/!6!6"(+Q0DR0H.J^_aJb" " #11-@@%(;;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 	nmm]4EGZ$[mmmmmm++*
 
 
 	
r+   NFFT)rs   rt   ru   r\   r   r   r   r  r?   rp   rv   rw   s   @r)   re  re    s        Y Y Y Y Y 26"'%* G
 G
|G
 !.G
  	G

 #G
 G
 G
 G
 G
 G
 G
 G
 G
r+   re  c                   .     e Zd Z fdZ	 	 	 	 ddZ xZS )HubertEncoderStableLayerNormc                    t                                                       | _        t                    | _        t          j        j        j                  | _	        t          j
        j                  | _        t          j        fdt          j                  D                       | _        d| _        j        dk    | _        d S )Nr   c                 .    g | ]}t                    S r.   )r_  rh  s     r)   r1   z9HubertEncoderStableLayerNorm.__init__.<locals>.<listcomp>   s"    ```1.v66```r+   Fr0  ri  r   s    `r)   r\   z%HubertEncoderStableLayerNorm.__init__  s    ;FCC,v'9v?TUUUz&"788m````fF^@_@_```
 
 ',#&,&AEX&X###r+   NFTc                 X   |rdnd }|rdnd }||                     d                              dd|j        d                   }||                    |j                  z  }| j        r|d|v r|nd }nd|d d d d d d f                             |j                  z
  }|t          j        |j                  j        z  }|	                    |j        d         d|j        d         |j        d                   }| 
                    |          }	||	z   }|                     |          }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   }|st/          d |||fD                       S t1          |||          S )Nr.   r,   r   r   r2   r   rq  TFrM  rr  c              3      K   | ]}||V  	d S rm   r.   rt  s     r)   rv  z7HubertEncoderStableLayerNorm.forward.<locals>.<genexpr>I  rw  r+   rx  )r{  r|  r   r#  r3   rm  r   r}  r~  r  rj  r   r
   r   rl  r8   r   ri   r  r   r   r   r}   r  r   r  s                  r)   rp   z$HubertEncoderStableLayerNorm.forward  s    #7@BBD$5?bb4%$2$<$<R$@$@$G$G1mNabcNd$e$e!),A,D,D=K^,D,_,__M* 	4B4NSTXfSfSfmq "%~aaatQQQ6F'G'J'JQ^Qd'J'e'e!e!/%+m>Q2R2R2V!V!/!6!6"(+Q0DR0H.J^_aJb" " #11-@@%(;;]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#66 	E 1]4D D 	nmm]4EGZ$[mmmmmm++*
 
 
 	
r+   r  rr   rw   s   @r)   r  r    sg        
Y 
Y 
Y 
Y 
Y "I
 I
 I
 I
 I
 I
 I
 I
r+   r  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 )HubertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    hubertr   Tc                    t          |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}t!          |d          rzt!          |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   )meanstdrq  r   Nr   r   r   )r8  r   r   r   datanormal_ri   initializer_ranger|   r   rZ   zero_fill_r`   r
   r   r   r   r   r   r   initkaiming_normal_)rh   moduler   s      r)   _init_weightsz#HubertPreTrainedModel._init_weights^  s   fbi(( 	< 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$   "*EEE*F;;F?F?rL   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%   rX   rY   s      r)   _conv_out_lengthzPHubertPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_length|  s&     9\K7wWWWZ[[[r+   )zipri   ra   rb   )rh   rL   r  rX   rY   s        r)    _get_feat_extract_output_lengthsz6HubertPreTrainedModel._get_feat_extract_output_lengthsw  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   )r3   devicer   )r  )r  r:   r#  r   longr   r>   r3   r  rA   flipcumsumr?   )rh   r  r   output_lengthsrK   s        r)   "_get_feature_vector_attention_maskz8HubertPreTrainedModel._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)rs   rt   ru   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)   r  r  Q  s         
  L $O&*#!N% % %2eEDTVYDY>Z    
 
]b]m 
 
 
 
 
 
r+   r  a!  
    Hubert was proposed in [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden
    Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia,
    Ruslan Salakhutdinov, Abdelrahman Mohamed.

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

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

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

            <Tip warning={true}>

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

            </Tip>

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z`The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.c                   b    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          	 	 	 	 	 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 )HubertModelri   c                    t                                          |           || _        t          |          | _        t          |          | _        |j        dk    s|j        dk    rBt          j
        t          j        |j                                                            | _        |j        rt#          |          | _        nt'          |          | _        |                                  d S )Nr   )r[   r\   ri   r   feature_extractorr   feature_projectionmask_time_probmask_feature_probr   	Parameterr   r  r   uniform_masked_spec_embeddo_stable_layer_normr  encoderre  	post_initr   s     r)   r\   zHubertModel.__init__  s       !5f!=!="9&"A"A 3&&&*BS*H*H%'\%,v?Q2R2R2[2[2]2]%^%^D"& 	17??DLL(00DL 	r+   Nro   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   )r  r3   )r   r   r   r,   )ra  ri   r   r  r#  r3   r  r   rS   mask_time_lengthmask_time_min_masksr   r   r  r?   r  mask_feature_lengthmask_feature_min_masksr  )rh   ro   r  r   rK   r(   r   mask_feature_indicess           r)   _mask_hidden_stateszHubertModel._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+   )output_typer  r   r   rn  ro  r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|                     |          }|                    dd          }|!|                     |j        d         |          }|                     |          }| 	                    ||          }| 
                    |||||          }	|	d         }|s|f|	dd         z   S t          ||	j        |	j                  S )aZ  

        Returns:

        Example:

        ```python
        >>> from transformers import AutoProcessor, HubertModel
        >>> from datasets import load_dataset
        >>> import soundfile as sf

        >>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
        >>> model = HubertModel.from_pretrained("facebook/hubert-large-ls960-ft")


        >>> def map_to_array(batch):
        ...     speech, _ = sf.read(batch["file"])
        ...     batch["speech"] = speech
        ...     return batch


        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.map(map_to_array)

        >>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values  # Batch size 1
        >>> hidden_states = model(input_values).last_hidden_state
        ```Nr   r   )r  r   r   rn  ro  r   rx  )ri   r   rn  use_return_dictr  r   r  r   r  r  r  r   ro   rz  )
rh   r   r   r  r   rn  ro  extract_featuresro   encoder_outputss
             r)   rp   zHubertModel.forward  s@   L 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]11,??+55a;;%!DDEUE[\]E^`nooN//0@AA00Rc0dd,,)/!5# ' 
 
 (* 	:!#oabb&999+)7&1
 
 
 	
r+   rr  NNNNN)rs   rt   ru   r   r\   r   r]  r   r  r  r   HUBERT_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr  r?   r   r   rp   rv   rw   s   @r)   r  r    su       
|      * :>59	, ,(, $E$56, !!12	, , , ,\ +*+BCC?YYY 269=,0/3&*E
 E
u|,E
 !.E
 $E$56	E

 $D>E
 'tnE
 d^E
 
uo%	&E
 E
 E
 ZY DCE
 E
 E
 E
 E
r+   r  zdHubert 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 )HubertForCTCN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: `HubertForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.add_adapter)r[   r\   r  r  r   r   final_dropoutr   r  
vocab_sizer5   rk   r   r  output_hidden_sizer   r   lm_headr  )rh   ri   r  r  rk   s       r)   r\   zHubertForCTC.__init__a  s       !&))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.
        NrT  z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  ra  ri   r5   r!  infoload_adapter)rh   r  s     r)   tie_weightszHubertForCTC.tie_weightsx  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rh   s    r)   freeze_feature_extractorz%HubertForCTC.freeze_feature_extractor  ;    
 	Q	
 	
 	

 	##%%%%%r+   c                 B    | j         j                                         dS r  Nr  r  r   r  s    r)   r  z#HubertForCTC.freeze_feature_encoder  !    
 	%88:::::r+   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HubertForCTC.freeze_base_model  6    
 [++-- 	( 	(E"'E	( 	(r+   )
checkpointr  r  expected_outputexpected_lossr   r   r   rn  ro  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   r2   r,   )r   r3   r   F)enabled)blank	reductionzero_infinitylosslogitsro   rz  )ri   r  r$   r  r5   r  r   r  r   	ones_liker  r  r:   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   ro   rz  )rh   r   r   r   rn  ro  r  rP  ro   r  r   rL   labels_masktarget_lengthsflattened_targets	log_probsoutputs                    r)   rp   zHubertForCTC.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rm   r  )rs   rt   ru   r   r:  r\   r  r  r  r  r   r  r   _CHECKPOINT_FOR_DOCr   r  _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr   r  r?   r   r   rp   rv   rw   s   @r)   r  r  [  sz        HSM      .< < <*
& 
& 
&; ; ;( ( ( +*+BCC&"$,(   26,0/3&*)-D
 D
u|,D
 !.D
 $D>	D

 'tnD
 d^D
 &D
 
un$	%D
 D
 D
  DCD
 D
 D
 D
 D
r+   r  z
    Hubert 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 )HubertForSequenceClassificationc                    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  z]Sequence classification does not support the use of Hubert adapters (config.add_adapter=True)r   )r[   r\   r   r  r5   r  r  rk  use_weighted_layer_sumr   r  r   rD   layer_weightsr   r   classifier_proj_size	projector
num_labels
classifierr  )rh   ri   
num_layersrk   s      r)   r\   z(HubertForSequenceClassification.__init__   s       6=)) 	f.@ 	o   "&))-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  z8HubertForSequenceClassification.freeze_feature_extractor  r  r+   c                 B    | j         j                                         dS r  r  r  s    r)   r  z6HubertForSequenceClassification.freeze_feature_encoder  r  r+   c                 L    | j                                         D ]	}d|_        
dS r  r  r   s     r)   r  z1HubertForSequenceClassification.freeze_base_model$  r  r+   audio)r  r  r  modalityr  r  Nr   r   r   rn  ro  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  )ri   r  r  r  r  r   stackr   r  r  r  r   r:   r  r  r  r   r  r   r  r   ro   rz  )rh   r   r   r   rn  ro  r  rP  ro   norm_weightspooled_outputpadding_maskr  r   loss_fctr  s                   r)   rp   z'HubertForSequenceClassification.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  )rs   rt   ru   r\   r  r  r  r   r  r   _SEQ_CLASS_CHECKPOINTr   r  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r   r  r?   r   r   rp   rv   rw   s   @r)   r  r    sJ           "
& 
& 
&; ; ;( ( ( +*+BCC(,$2.   26,0/3&*)-;
 ;
u|,;
 !.;
 $D>	;

 'tn;
 d^;
 &;
 
u..	/;
 ;
 ;
  DC;
 ;
 ;
 ;
 ;
r+   r  r   )Or   r   typingr   r   r   numpyr6   r   torch.utils.checkpointr   torch.nnr   activationsr	   integrations.deepspeedr
   integrations.fsdpr   modeling_outputsr   r   r   modeling_utilsr   r   r   r   r   r   r   r   r   configuration_hubertr   modeling_flash_attention_utilsr   
get_loggerrs   r!  r  r  r  _EXPECTED_OUTPUT_SHAPEr  r  r*  r+  r,  r#   r  r  ndarrayrS   ModulerU   ry   r   r   r   r   r   r   r   r  r)  rD  r2  rA  rR  r_  re  r  r  HUBERT_START_DOCSTRINGr  r  r  r  r.   r+   r)   <module>r=     s      ) ) ) ) ) ) ) ) ) )                % % % % % % ! ! ! ! ! ! @ @ @ @ @ @ 7 7 7 7 7 7 Y Y Y Y Y Y Y Y Y Y - - - - - -                  / . . . . .  KJJJJJJ 
	H	%	% !  ! 7 &  u   7 *   26t tc?tt t U-.	t
 t Zt t t tp       ,    ry   8    ry   2* * * * *BI * * *\       ) ) ) ) )29 ) ) )X
 
 
 
 
1 
 
 
    bi   &[B [B [B [B [Bbi [B [B [B~|9 |9 |9 |9 |9O |9 |9 |9~h1 h1 h1 h1 h1/ h1 h1 h1X .      	   2               H    RY   4* * * * *	 * * *\R
 R
 R
 R
 R
BI R
 R
 R
lV
 V
 V
 V
 V
29 V
 V
 V
r? ? ? ? ?O ? ? ?D &# L f H
 H
 H
 H
 H
' H
 H
	 H
V n 
T
 T
 T
 T
 T
( T
 T
 
T
n   q
 q
 q
 q
 q
&; q
 q
 q
 q
 q
r+   