
    g|R                       d Z ddlZddlZddlmZ ddlmZmZmZ ddl	Z
ddlZddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZ ddlmZ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Z0dZ1dZ2e G d de                      Z3	 	 dVdee4e4f         de5de4deej6                 de4de
j7        fdZ8 G d  d!ej9                  Z: G d" d#ej9                  Z; G d$ d%ej9                  Z< G d& d'ej9                  Z= G d( d)ej9                  Z> G d* d+ej9                  Z? G d, d-e?          Z@ G d. d/ej9                  ZA G d0 d1ej9                  ZB G d2 d3eB          ZC G d4 d5eB          ZDeBeDeCd6ZE G d7 d8ej9                  ZF G d9 d:ej9                  ZG G d; d<ej9                  ZH G d= d>ej9                  ZI G d? d@ej9                  ZJ G dA dBej9                  ZK G dC dDej9                  ZL G dE dFe          ZMdGZNdHZO e dIeN           G dJ dKeM                      ZP e dLeN           G dM dNeM                      ZQ e dOeNdP           G dQ dReM                      ZR e dSeN           G dT dUeM                      ZSdS )WzPyTorch UniSpeech model.    N)	dataclass)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)is_deepspeed_zero3_enabled)is_fsdp_managed_module)BaseModelOutputCausalLMOutputSequenceClassifierOutputWav2Vec2BaseModelOutput)PreTrainedModel)ModelOutput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   )UniSpeechConfig)_flash_attention_forward   r   z/patrickvonplaten/unispeech-large-1500h-cv-timit)r   i$  i   zW'mister quilter is the apposl of the midle classes and weare glad to welcom his gosepl'gQ+1@c                       e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
ej        ed<   dZej        ed<   dZeeej                          ed<   dZeeej                          ed<   dS )	UniSpeechForPreTrainingOutputaL  
    Output type of [`UniSpeechForPreTrainingOutput`], with potential hidden states and attentions.

    Args:
        loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
            paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
        projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
            Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
            projected quantized states.
        projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
            Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
            target vectors for contrastive loss.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nlossprojected_statesprojected_quantized_statescodevector_perplexityhidden_states
attentions)__name__
__module____qualname____doc__r    r   torchFloatTensor__annotations__r!   r"   r#   r$   r   r%        l/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/unispeech/modeling_unispeech.pyr   r   C   s          4 )-D(5$
%,,,*.e'...48 1888/35,3338<M8E%"345<<<59Ju01299999r.   r   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epsilonr2   r1   r4   sequence_lengths     r/   compute_num_masked_spanz6_compute_mask_indices.<locals>.compute_num_masked_span   s~    i,6DwNOOoy99 [(?::-<O ;?+o==!,+/"BAFFOr.   Nc                     g | ]}S r-   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)r0   r1   r2   r3   r4   
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_indicesrf   h   sP   0 #(JQABBB_$$:^i : :'6: : :
 
 	
 innQ$$&&G        $ % 	2%%''..0009999uZ'8'8999  Hj/:$GGGM11/BBa% 5 511,?? I,,IlkAo677RW - 
 
  !!Q&& -q0NN.q1NN(;o(MUWU] ^ ^ ^ao op
 
 	!!"34444"455 111aaa:&5H+(V  ,33J@SVa@abb i$$T4]3Gog
4G'UVV^^'+5 G ,g5 /A"555GVYZGZ-!0CCD m%7B???r.   c                   &     e Zd Zd fd	Zd Z xZS )UniSpeechNoLayerNormConvLayerr   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/   ro   z&UniSpeechNoLayerNormConvLayer.__init__   s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@r.   c                 Z    |                      |          }|                     |          }|S N)rw   ry   r{   r$   s     r/   forwardz%UniSpeechNoLayerNormConvLayer.forward   s*    		-0066r.   r   r&   r'   r(   ro   r   __classcell__r~   s   @r/   rh   rh      sR        A A A A A A      r.   rh   c                   &     e Zd Zd fd	Zd Z xZS )UniSpeechLayerNormConvLayerr   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   rj   T)elementwise_affine)rn   ro   rp   rq   rr   r   rs   rt   ru   rv   rw   	LayerNorm
layer_normr
   rx   ry   rz   s      r/   ro   z$UniSpeechLayerNormConvLayer.__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@   )rw   	transposer   ry   r   s     r/   r   z#UniSpeechLayerNormConvLayer.forward  se    		-00%//B7766%//B7766r.   r   r   r   s   @r/   r   r      sR        A A A A A A      r.   r   c                   &     e Zd Zd fd	Zd Z xZS )UniSpeechGroupNormConvLayerr   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   rj   T)
num_groupsnum_channelsaffine)rn   ro   rp   rq   rr   r   rs   rt   ru   rv   rw   r
   rx   ry   	GroupNormr   rz   s      r/   ro   z$UniSpeechGroupNormConvLayer.__init__  s    <DqLL6?8a<88a"OH5I*84%h/!
 
 
	 !!?@,$2CRVRclpqqqr.   c                     |                      |          }|                     |          }|                     |          }|S r   )rw   r   ry   r   s     r/   r   z#UniSpeechGroupNormConvLayer.forward#  s;    		-006666r.   r   r   r   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 ) UniSpeechPositionalConvEmbeddingc                    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 )	Nr   )rk   paddinggroupsweight_normr   )modifier_rankweight)namedimparametrizations)rn   ro   r   rs   hidden_sizenum_conv_pos_embeddingsnum_conv_pos_embedding_groupsrw   utilsr   hasattrr   r   	deepspeedzeroGatheredParametersr   	original0	original1weight_gweight_vregister_external_parameterUniSpeechSamePadLayerr   r
   rx   ry   )r{   r|   r   r   r   r   r~   s         r/   ro   z)UniSpeechPositionalConvEmbedding.__init__,  s   I62a77
 
 
	 h*28,m<< 	@(3?K%'' 	E22493CST2UU I I'K	aHHH	I I I I I I I I I I I I I I Ity"455 .95<F95<F9-9-N66tXFFFN66tXFFFF#DIH!DDDDI,V-KLL !?@s   C??DDc                     |                     dd          }|                     |          }|                     |          }|                     |          }|                     dd          }|S Nr   r   )r   rw   r   ry   r   s     r/   r   z(UniSpeechPositionalConvEmbedding.forwardM  se    %//155		-00]3366%//155r.   r   r   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   )rn   ro   num_pad_remove)r{   r   r~   s     r/   ro   zUniSpeechSamePadLayer.__init__Z  s:    #:Q#>!#C#Caar.   c                 J    | j         dk    r|d d d d d | j          f         }|S Nr   )r   r   s     r/   r   zUniSpeechSamePadLayer.forward^  s;    "")!!!QQQ0F43F2F0F*FGMr.   r   r   s   @r/   r   r   Y  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 )UniSpeechFeatureEncoderz.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   r}   c                 8    g | ]}t          |d z             S )r   r   )rh   rB   ir|   s     r/   rD   z4UniSpeechFeatureEncoder.__init__.<locals>.<listcomp>l  s@     O O O .fq1uEEEO O Or.   r   layerc                 2    g | ]}t          |           S )r   )r   r   s     r/   rD   z4UniSpeechFeatureEncoder.__init__.<locals>.<listcomp>q  s4       DE+FQ???  r.   z`config.feat_extract_norm` is z), but has to be one of ['group', 'layer']FT)rn   ro   feat_extract_normr   rP   num_feat_extract_layersrH   r   
ModuleListconv_layersgradient_checkpointing_requires_grad)r{   r|   r   r~   s    ` r/   ro   z UniSpeechFeatureEncoder.__init__h  s   #w..6vJJJK O O O Ov=ABBO O O KK %00   INvOmInIn  KK t1Ittt   =55&+#"r.   c                 P    |                                  D ]	}d|_        
d| _        d S NF)
parametersrequires_gradr   r{   params     r/   _freeze_parametersz*UniSpeechFeatureEncoder._freeze_parameters|  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__)r{   input_valuesr$   
conv_layers       r/   r   zUniSpeechFeatureEncoder.forward  s    $QQQW-  	/4= 	/*.M'* 	: 	:J" :t'B :t} : $ A A'!! !
 !+
= 9 9r.   )r&   r'   r(   r)   ro   r   r   r   r   s   @r/   r   r   e  s\        88# # # # #($ $ $
      r.   r   c                        e Zd Z fdZ xZS )UniSpeechFeatureExtractorc                     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.)rn   ro   warningswarnr~   r&   	__bases__FutureWarningr{   r|   r~   s     r/   ro   z"UniSpeechFeatureExtractor.__init__  sy       E$.1 E EN,Q/8E E E 		
 	
 	
 	
 	
r.   )r&   r'   r(   ro   r   r   s   @r/   r   r     s8        
 
 
 
 
 
 
 
 
r.   r   c                   $     e Zd Z fdZd Z xZS )UniSpeechFeatureProjectionc                 .   t                                                       t          j        |j        d         |j                  | _        t          j        |j        d         |j                  | _	        t          j
        |j                  | _        d S )Nr@   eps)rn   ro   r   r   rp   layer_norm_epsr   Linearr   
projectionDropoutfeat_proj_dropoutdropoutr   s     r/   ro   z#UniSpeechFeatureProjection.__init__  sn    ,vr':@UVVV)FOB$79KLLz&":;;r.   c                     |                      |          }|                     |          }|                     |          }||fS r   )r   r   r   )r{   r$   norm_hidden_statess      r/   r   z"UniSpeechFeatureProjection.forward  sC    !__];;(:;;]33000r.   r   r   s   @r/   r   r     sG        < < < < <1 1 1 1 1 1 1r.   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 )UniSpeechAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsr   
is_decoderrm   	is_causalr|   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      )rm   )rn   ro   r   r   r   head_dimr|   rH   scalingr   r   r   r   k_projv_projq_projout_proj)	r{   r   r   r   r   rm   r   r|   r~   s	           r/   ro   zUniSpeechAttention.__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r{   r   r   r   s       r/   _shapezUniSpeechAttention._shape  s<    {{3GGQQRSUVWWbbdddr.   r$   key_value_statespast_key_valuer3   layer_head_maskoutput_attentionsr5   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   r0   r   r   r   r*   catr   r   r   r   r\   bmmr   rH   r   
functionalsoftmaxr   r   r   r   )r{   r$   r   r  r3   r  r  is_cross_attentionr   tgt_lenrC   query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r/   r   zUniSpeechAttention.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)r&   r'   r(   r)   r9   floatrR   r   r   ro   r*   Tensorr   r   r   r   r   s   @r/   r   r     s       GG  ,0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 )UniSpeechFlashAttention2aN  
    UniSpeech flash attention module. This module inherits from `UniSpeechAttention` 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 r   )rn   ro   r   _flash_attn_uses_top_left_mask)r{   argskwargsr~   s      r/   ro   z!UniSpeechFlashAttention2.__init__W  s9    $)&)))
 3V2W2W.W+++r.   r   r   r   c                 F    |                     ||| j        | j                  S r   )r   r   r   r   s       r/   _reshapez!UniSpeechFlashAttention2._reshape_  s    {{3GGGr.   NFr$   r   r  r3   r  r  r5   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 )NzEUniSpeechFlashAttention2 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)rH   r
  r$  r   r0   r   r   r   r*   r  r   rF   float32is_autocast_enabledget_autocast_gpu_dtyper   r|   r&  r   loggerwarning_oncetor   r   r   r   r   r\   r   )r{   r$   r   r  r3   r  r  r  r   q_lenrC   r  r  r  
kv_seq_leninput_dtypetarget_dtyper  r  s                      r/   r   z UniSpeechFlashAttention2.forwardb  s     	fdeee .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  )r&   r'   r(   r)   ro   r*   r  r9   r$  r   r   rR   r   r   r   s   @r/   r  r  O  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 )UniSpeechSdpaAttentionNFr$   r   r  r3   r  r  r5   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  UniSpeechModel is using UniSpeechSdpaAttention, 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  r3   r  r  r   r   r   r@   r  TFr   )	attn_mask	dropout_pr   r	  r  )r,  r-  rn   r   r
  r   r0   r   r   r   r*   r  r   r   r   r  scaled_dot_product_attentionr   r   r   r   rH   r   r\   r   r   )r{   r$   r   r  r3   r  r  r  r   r  rC   r  r  r  r   r  r~   s                   r/   r   zUniSpeechSdpaAttention.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  )
r&   r'   r(   r*   r  r   r   rR   r   r   r   s   @r/   r4  r4    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.   r4  )eagersdpaflash_attention_2c                   $     e Zd Z fdZd Z xZS )UniSpeechFeedForwardc                    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 r   )rn   ro   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/   ro   zUniSpeechFeedForward.__init__B  s    $&Jv/H$I$I!"$)F,>@X"Y"Yf'-- 	9'-f.?'@D$$'-'8D$If&>@RSS j)>??r.   c                     |                      |          }|                     |          }|                     |          }|                     |          }|                     |          }|S r   )rB  rF  r@  rG  rI  r   s     r/   r   zUniSpeechFeedForward.forwardO  sg    //>>00??11-@@))-88++M::r.   r   r   s   @r/   r=  r=  A  sL        @ @ @ @ @      r.   r=  c                   &     e Zd Z fdZddZ xZS )UniSpeechEncoderLayerc                    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   )rn   ro   UNISPEECH_ATTENTION_CLASSES_attn_implementationr   num_attention_headsattention_dropout	attentionr   r   rH  r   r   r   r   r=  feed_forwardfinal_layer_normr   s     r/   ro   zUniSpeechEncoderLayer.__init__[  s    4V5PQ(0,	
 
 
 z&"788,v'9v?TUUU088 "V-?VEZ [ [ [r.   NFc                    |}|                      |||          \  }}}|                     |          }||z   }|                     |          }||                     |          z   }|                     |          }|f}|r||fz  }|S Nr3   r  )rS  r   r   rT  rU  r{   r$   r3   r  attn_residualr  rC   outputss           r/   r   zUniSpeechEncoderLayer.forwardi  s    %)-.L] *8 *
 *
&|Q ]33%566%(9(9-(H(HH--m<< " 	'&Gr.   r   r   r   s   @r/   rL  rL  Z  sQ        \ \ \ \ \       r.   rL  c                   4     e Zd Z fdZdej        fdZ xZS )UniSpeechAttnAdapterLayerc                 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)rn   ro   adapter_attn_dim	input_dimr   
hidden_dimr   r   normr   linear_1ReLUact_fnlinear_2r   s     r/   ro   z"UniSpeechAttnAdapterLayer.__init__  s    
 	0 ,L11		$/4>BBgii	$.$/BBr.   r$   c                     |                      |          }|                     |          }|                     |          }|                     |          }|S r   )rb  rc  re  rf  r   s     r/   r   z!UniSpeechAttnAdapterLayer.forward  sL    		-00m44M22m44r.   )r&   r'   r(   ro   r*   r+   r   r   r   s   @r/   r]  r]  ~  s[        C C C C CU%6        r.   r]  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 )	$UniSpeechEncoderLayerStableLayerNormc                     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 )NFrN  r   r_  )rn   ro   rO  rP  r   rQ  rR  rS  r   r   rH  r   r   r   r   r=  rT  rU  getattrr]  adapter_layerr   s     r/   ro   z-UniSpeechEncoderLayerStableLayerNorm.__init__  s    4V5PQ(0,	
 
 
 z&"788,v'9v?TUUU088 "V-?VEZ [ [ [6-t44@!:6!B!BD!%Dr.   NFr$   r3   r  c                 J   |}|                      |          }|                     |||          \  }}}|                     |          }||z   }||                     |                     |                    z   }| j        ||                     |          z   }|f}|r||fz  }|S rW  )r   rS  r   rT  rU  rl  rY  s           r/   r   z,UniSpeechEncoderLayerStableLayerNorm.forward  s     &66)-.L] *8 *
 *
&|Q ]33%5%(9(9$:O:OP]:^:^(_(__))D,>,>},M,MMM " 	'&Gr.   r   )
r&   r'   r(   ro   r*   r  r   rR   r   r   r   s   @r/   ri  ri    s~        & & & & &* 26"'	 | !.  	       r.   ri  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 )UniSpeechEncoderc                    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-   )rL  rB   rC   r|   s     r/   rD   z-UniSpeechEncoder.__init__.<locals>.<listcomp>  s"    $l$l$lq%:6%B%B$l$l$lr.   Fr;  rn   ro   r|   r   pos_conv_embedr   r   r   r   r   r   rH  r   r   rP   num_hidden_layerslayersr   rP  _use_flash_attention_2r   s    `r/   ro   zUniSpeechEncoder.__init__  s    >vFF,v'9v?TUUUz&"788m$l$l$l$lERXRjLkLk$l$l$lmm&+#&,&AEX&X###r.   NFTr$   r3   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         ?rE   TFrX  NNc              3      K   | ]}||V  	d S r   r-   rB   vs     r/   	<genexpr>z+UniSpeechEncoder.forward.<locals>.<genexpr>  (      mmq_`_l_l_l_l_lmmr.   last_hidden_stater$   r%   )	unsqueezerepeatr0   rw  r.  rF   r*   finfominexpandrt  r   r   r   r   rv  rK   r   r|   	layerdropr   r   r   tupler   r{   r$   r3   r  rx  ry  all_hidden_statesall_self_attentionsexpand_attention_maskposition_embeddingssynced_gpusr   dropout_probabilityskip_the_layerlayer_outputss                  r/   r   zUniSpeechEncoder.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)r&   r'   r(   ro   r*   r   r   r  rR   r   r   r   s   @r/   ro  ro    s        Y Y Y Y Y 26"'%* G
 G
|G
 !.G
  	G

 #G
 G
 G
 G
 G
 G
 G
 G
 G
r.   ro  c                   .     e Zd Z fdZ	 	 	 	 ddZ xZS )UniSpeechEncoderStableLayerNormc                    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-   )ri  rr  s     r/   rD   z<UniSpeechEncoderStableLayerNorm.__init__.<locals>.<listcomp>$  s"    ccca1&99cccr.   Fr;  rs  r   s    `r/   ro   z(UniSpeechEncoderStableLayerNorm.__init__  s    >vFF,v'9v?TUUUz&"788mcccc5IaCbCbccc
 
 ',#&,&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   rE   r   r{  TFrX  r|  c              3      K   | ]}||V  	d S r   r-   r~  s     r/   r  z:UniSpeechEncoderStableLayerNorm.forward.<locals>.<genexpr>m  r  r.   r  )r  r  r0   r.  rF   rw  r*   r  r  r  rt  r   r   r   rv  rK   r   r|   r  r   r   r   r   r  r   r  s                  r/   r   z'UniSpeechEncoderStableLayerNorm.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  r   r   s   @r/   r  r    sg        
Y 
Y 
Y 
Y 
Y "I
 I
 I
 I
 I
 I
 I
 I
r.   r  c                   >     e Zd ZdZ fdZed             Zd Z xZS )UniSpeechGumbelVectorQuantizerz
    Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
    GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.
    c                    t                                                       |j        | _        |j        | _        |j        | j        z  dk    r t          d|j         d| j         d          t          j	        t          j        d| j        | j        z  |j        | j        z                      | _        t          j        |j        d         | j        | j        z            | _        d| _        d S )Nr   z`config.codevector_dim z5 must be divisible by `config.num_codevector_groups` z for concatenationr   r@   r   )rn   ro   num_codevector_groupsr   num_codevectors_per_groupnum_varscodevector_dimrH   r   	Parameterr*   r+   codevectorsr   rp   weight_projtemperaturer   s     r/   ro   z'UniSpeechGumbelVectorQuantizer.__init__{  s     68 4?2a778&*? 8 8O8 8 8   <a4=!@&BW[_[jBjkk
 
 9V_R%8$/DM:YZZ r.   c           	          |                      d          }t          j        t          j        |t          j        |dz             z  d                                                     }|S )Nr   r  gHz>r@   )meanr*   exprM   log)probsmarginal_probs
perplexitys      r/   _compute_perplexityz2UniSpeechGumbelVectorQuantizer._compute_perplexity  s^    **Y	.59^VZEZ;[;[*[ac d d ddeeiikk
r.   c                    |j         \  }}}|                     |          }|                    ||z  | j        z  d          }| j        rt
          j                            |                                | j	        d          
                    |          }t          j        |                    ||z  | j        d                                          d          }|                     |          }n|                    d          } |j        |j                              d|                    dd          d          }|                    ||z  | j        d          }|                     |          }|                    ||z  d          }|                    d          | j        z  }	|	                    ||z  | j        | j        d          }
|
                    d                              ||d          }
|
|fS )Nr@   T)tauhardr  r   r{  r   )r0   r  r   r   r   r   r  gumbel_softmaxr  r  type_asr*   r  r  argmax	new_zerosscatter_r  r  r  rM   )r{   r$   r^   r>   r   codevector_probscodevector_soft_distr  codevector_idxcodevectors_per_groupr  s              r/   r   z&UniSpeechGumbelVectorQuantizer.forward  s   3@3F0
O[ ((77%**:+G$/+Y[]^^= 	D!};;##%%4+;$  <    gm$$ 
 $)="":#?RTUU[[]]ce$ $ $  112FGGJJ +11b199N6}68KLUUN''A..     044Z/5QSWSbdfgg112BCCJ+00o1MrRR 0 : :2 > >AQ Q+00o1Mt`d`moqrr!oob))..z?BOOJ&&r.   )	r&   r'   r(   r)   ro   staticmethodr  r   r   r   s   @r/   r  r  u  sl         
    (   \
#' #' #' #' #' #' #'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 )UniSpeechPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    	unispeechr   Tc           
      \   t          |t                    ro|j        j        j                            dd           |j        j        j                                         t          j	        
                    |j                   dS t          |t                    rt          j	                            |j        j        ddt          j        d|j        j        d         |j        j        z  z            z             t          j	                            |j        j        d           dS t          |t&                    r}t          j        d|j        j        z            }t          j	        
                    |j        j        | |           t          j	        
                    |j        j        | |           dS t          |t          j                  rT|j        j                            d| j        j                   |j         |j        j                                         dS dS t          |t          j        t          j        f          r?|j        j                                         |j        j                            d           dS t          |t          j                  rt          j	                            |j                   |j        [t          j        |j        |j        |j        d         z  z            }t          j	        
                    |j        | |           dS dS dS )	zInitialize the weightsr   r   )r  stdr   r   )abNr{  )rC  r  r  r   datanormal_rm   zero_r   inituniform_r  r   rw   mathsqrtrk   in_channels	constant_r   r   in_featuresr   r|   initializer_ranger   r   fill_rs   kaiming_normal_r   )r{   moduleks      r/   _init_weightsz&UniSpeechPreTrainedModel._init_weights  s    f<== 	9%*222CCC#(..000GV/00000 @AA 	9GOO"	!v{'>q'AFKD['["\]]]    
 Gfk.22222 :;; 	9	!f/;;<<AGV.5!qAAAGV.3rQ?????	** 	9M&&CT[5R&SSS{& &&((((( '&r| <== 	9K""$$$M$$S)))))	** 	9G##FM222{&Ifmv/AFDVWXDY/YZ[[  a 88888	9 	9 '&r.   r_   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;   rk   rl   s      r/   _conv_out_lengthzSUniSpeechPreTrainedModel._get_feat_extract_output_lengths.<locals>._conv_out_length  s&     9\K7wWWWZ[[[r.   )zipr|   rt   ru   )r{   r_   r  rk   rl   s        r/    _get_feat_extract_output_lengthsz9UniSpeechPreTrainedModel._get_feat_extract_output_lengths  s\    
	\ 	\ 	\
 $'t{'>@W#X#X 	Q 	QK,,]KPPMMr.   feature_vector_lengthr3   c                    |                     d          d d df         }|                     |                              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  r   )rF   devicer   )r  )cumsumr  r.  r*   longr0   rQ   rF   r  rT   fliprR   )r{   r  r3   non_padded_lengthsoutput_lengthsr^   s         r/   "_get_feature_vector_attention_maskz;UniSpeechPreTrainedModel._get_feature_vector_attention_mask  s     ,22r2::111b5A>>?QRRUUV[V`aa#)!,
./~7KTbTi
 
 
 uv^%9!%<^EZ[[[]kno]opq',,bT2299"==BBB4HHMMOOr.   N)r&   r'   r(   r)   r   config_classbase_model_prefixmain_input_namesupports_gradient_checkpointing_supports_flash_attn_2_supports_sdpar  r   r*   
LongTensorr9   r  r  r-   r.   r/   r  r    s         
 #L#$O&*#!N9 9 9BeEDTVYDY>Z     ]b]m      r.   r  a  
    UniSpeech was proposed in [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled
    Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei,
    Michael Zeng, Xuedong Huang.

    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 ([`UniSpeechConfig`]): 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.
aI  
    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`, `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.
zcThe bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.c                   h    e Zd Zdef fdZ	 	 ddej        deej                 deej                 fdZ	 e
e           eeeede	          	 	 	 	 	 dd
eej                 deej                 deej                 dee         dee         dee         deeef         fd                        Z xZS )UniSpeechModelr|   c                    t                                          |           || _        t          |          | _        t          |          | _        |j        dk    s|j        dk    rBt          j
        t          j        |j                                                            | _        |j        rt#          |          | _        nt'          |          | _        |                                  d S )Nr   )rn   ro   r|   r   feature_extractorr   feature_projectionmask_time_probmask_feature_probr   r  r*   r  r   r  masked_spec_embeddo_stable_layer_normr  encoderro  	post_initr   s     r/   ro   zUniSpeechModel.__init__E  s       !8!@!@"<V"D"D 3&&&*BS*H*H%'\%,v?Q2R2R2[2[2]2]%^%^D"& 	4:6BBDLL+F33DL 	r.   Nr$   mask_time_indicesr3   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   )r1   r2   r3   r4   )r  rF   )r1   r2   r4   r@   )rk  r|   r
  r  r.  rF   r  r   rf   mask_time_lengthmask_time_min_masksr*   r   r  rR   r  mask_feature_lengthmask_feature_min_masksr  )r{   r$   r  r3   r^   r>   r   mask_feature_indicess           r/   _mask_hidden_statesz"UniSpeechModel._mask_hidden_statesW  s    t{$8$?? 	!   4A3E3E3G3G0
O[(/3/E/H/HI\/]/]M+,,['!+++ 5_-+4 K8-+9! ! ! !&->}G[chcm n n n/3/E/H/HI\/]/]M+,;(1,,,#8[)+7 K;+<	$ $ $  $)<0D]Mainis#t#t#t #74#@#G#GO]_#`#` 23M./r.   audio)
checkpointoutput_typer  modalityexpected_outputr   r  rx  ry  r5   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 )Nr   r   )r  r3   r3   r  rx  ry  r   )r  extract_featuresr$   r%   )r|   r  rx  use_return_dictr  r   r  r0   r  r  r  r   r$   r%   )
r{   r   r3   r  r  rx  ry  r  r$   encoder_outputss
             r/   r   zUniSpeechModel.forward  sW   " 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]11,??+55a;;%!DDEUE[\]E^`nooN*.*A*ABR*S*S''00->~ 1 
 
 ,,)/!5# ' 
 
 (* 	K!#34qrr7JJJ&+-)7&1	
 
 
 	
r.   r|  NNNNN)r&   r'   r(   r   ro   r*   r+   r   r  r  r   UNISPEECH_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr  rR   r   r   r   r   r   s   @r/   r  r  @  sx       
      * :>59	, ,(, $E$56, !!12	, , , ,\ +*+EFF&+$.   269=,0/3&*-
 -
u|,-
 !.-
 $E$56	-

 $D>-
 'tn-
 d^-
 
u--	.-
 -
 -
  GF-
 -
 -
 -
 -
r.   r  zPUniSpeech Model with a vector-quantization module and ctc loss for pre-training.c                   X    e Zd Zdef fdZdefdZd Zd Ze		 dde
j        d	e
j        d
e
j        defd            Z 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ef         fd                        Z xZS )UniSpeechForPreTrainingr|   c                    t                                          |           t          |          | _        t	          j        |j                  | _        t          |          | _	        t	          j
        |j        |j                  | _        t	          j
        |j        |j                  | _        t	          j
        |j        |j                  | _        t	          j        |j                  | _        |                                  d S r   )rn   ro   r  r  r   r   feat_quantizer_dropoutdropout_featuresr  	quantizerr   r  proj_codevector_dim	project_qr   project_hidnum_ctc_classesctc_projfinal_dropoutr   r  r   s     r/   ro   z UniSpeechForPreTraining.__init__  s       '// "
6+H I I7??6#8&:TUU9V%?ASTT	&"4f6LMMz&"677 	r.   r  c                     || j         _        dS )zb
        Set the Gumbel softmax temperature to a given value. Only necessary for training
        N)r  r  )r{   r  s     r/   set_gumbel_temperaturez.UniSpeechForPreTraining.set_gumbel_temperature  s     &1"""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.
        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r{   s    r/   freeze_feature_extractorz0UniSpeechForPreTraining.freeze_feature_extractor  ;    
 	Q	
 	
 	

 	##%%%%%r.   c                 B    | j         j                                         dS 
        Calling this function will disable the gradient computation for the feature encoder so that its parameter will
        not be updated during training.
        Nr  r  r   r   s    r/   r  z.UniSpeechForPreTraining.freeze_feature_encoder  !    
 	(;;=====r.   r   target_featuresnegative_featurespredicted_featuresc                     t          j        | |gd          } t          j        |                                |                                 d          }|                    |           }||z  }|S )z
        Compute logits for contrastive loss based using cosine similarity as the distance measure between
        `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
        r   r  r@   )r*   r  cosine_similarityr  r  )r(  r)  r*  r  logitss        r/   compute_contrastive_logitsz2UniSpeechForPreTraining.compute_contrastive_logits  sq      )_6G$HaPPP();)A)A)C)C_EZEZE\E\bdeee00 +%r.   )r   r  Nr   r3   r  rx  ry  r5   c                 
   ||n| j         j        }|                     |||||          }|d         }|                     |d                   }|                     |          \  }	}
|                     |	          }	|                     |	          }	t          j        |	                    d          |	                    d                    
                    | j         j                  }|                    dd          }t          j        |                                                              |j                  }|                    dd          }|                    d          }|                    |d          |	                    | d          z   }|                     |          }|                     |          }d}|s#||||	|
f|dd         z   S ||	|
f|dd         z   S t+          |||	|
|j        |j                  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.
        sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
            Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
            Required input for pre-training.

        Returns:

        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining

        >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
        >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
        >>> # TODO: Add full pretraining example
        ```Nr  r   r   r@   r   r   )r    r!   r"   r#   r$   r%   )r|   r  r  r  r  r  r  r*   emptyr
  r  replace_probr   	bernoullirR   r.  r  r  masked_fillr   r  r   r$   r%   )r{   r   r3   r  rx  ry  r[  transformer_featuresr  quantized_featuresr#   prob_replace_matrixsampled_replace_matrixr-  r    s                  r/   r   zUniSpeechForPreTraining.forward  sA   > &1%<kk$+B]..)/!5# ! 
 
  'qz  00<<48NNCS4T4T11 "^^,>??!--.@AA#k*>*C*CA*F*FH\HaHabcHdHdeekkK$
 
 2;;AqAA!&1D!E!E!J!J!L!L!O!OPdPk!l!l!7!A!A!Q!G!G!7!A!A"!E!E%112H#NN**,B+BCHH

 f%%v&&  	c24FH]^ahijikikalll(*<>STW^_`_a_aWbbb,1'9"7!/)
 
 
 	
r.   )r   )NNNN)r&   r'   r(   r   ro   r9   r  r!  r  r  r*   r+   r.  r   r	  r   r   r  r   r  rR   r   r   r   r   r   s   @r/   r  r    s             1# 1 1 1 1
& 
& 
&> > > 
 	 * , "- 	   \& +*+EFF+HWfggg 26,0/3&*M
 M
u|,M
 !.M
 $D>	M

 'tnM
 d^M
 
u33	4M
 M
 M
 hg GFM
 M
 M
 M
 M
r.   r  zgUniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).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 [`UniSpeechForCTC`] with adapters. Uses 'eng'
            by default.
    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 )UniSpeechForCTCN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: `UniSpeechForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of your model's configuration.add_adapter)rn   ro   r  r  r   r   r  r   r:  
vocab_sizerH   r~   r   r<  output_hidden_sizer   r   lm_headr  )r{   r|   r:  r>  r~   s       r/   ro   zUniSpeechForCTC.__init__[  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.
        Nr_  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:  rk  r|   rH   r,  infoload_adapter)r{   r:  s     r/   tie_weightszUniSpeechForCTC.tie_weightsr  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 )r%  r  Nr  r   s    r/   r!  z(UniSpeechForCTC.freeze_feature_extractor  r"  r.   c                 B    | j         j                                         dS r$  r&  r   s    r/   r  z&UniSpeechForCTC.freeze_feature_encoder  r'  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!UniSpeechForCTC.freeze_base_model  6    
 ^..00 	( 	(E"'E	( 	(r.   )r  r   r  r  expected_lossr   r3   r  rx  ry  labelsr5   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   rE   r@   )r   rF   r   F)enabled)blank	reductionzero_infinityr    r-  r$   r%   )r|   r  r:   r=  rH   r  r   r?  r*   	ones_liker  r  rM   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   r$   r%   )r{   r   r3   r  rx  ry  rM  r[  r$   r-  r    r_   labels_masktarget_lengthsflattened_targets	log_probsoutputs                    r/   r   zUniSpeechForCTC.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r   r  )r&   r'   r(   r   rE  ro   rD  r!  r  rJ  r   r	  r   r
  r   r  _CTC_EXPECTED_OUTPUT_CTC_EXPECTED_LOSSr*   r  rR   r   r   r   r   r   s   @r/   r9  r9  O  sz        HSM      .< < <*
& 
& 
&> > >( ( ( +*+EFF&"$,(   26,0/3&*)-D
 D
u|,D
 !.D
 $D>	D

 'tnD
 d^D
 &D
 
un$	%D
 D
 D
  GFD
 D
 D
 D
 D
r.   r9  z
    UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
    SUPERB Keyword Spotting.
    c                   "    e Zd Z fdZd Zd Zd Z ee           e	e
eed          	 	 	 	 	 ddeej                 d	eej                 d
ee         dee         dee         deej                 deeef         fd                        Z xZS )"UniSpeechForSequenceClassificationc                    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 UniSpeech adapters (config.add_adapter=True)r   )rn   ro   r   r<  rH   r  r  ru  use_weighted_layer_sumr   r  r*   rW   layer_weightsr   r   classifier_proj_size	projector
num_labels
classifierr  )r{   r|   
num_layersr~   s      r/   ro   z+UniSpeechForSequenceClassification.__init__  s       6=)) 	f.@ 	r   (//-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 r  r  r   s    r/   r!  z;UniSpeechForSequenceClassification.freeze_feature_extractor  r"  r.   c                 B    | j         j                                         dS r$  r&  r   s    r/   r  z9UniSpeechForSequenceClassification.freeze_feature_encoder  r'  r.   c                 L    | j                                         D ]	}d|_        
dS rH  rI  r   s     r/   rJ  z4UniSpeechForSequenceClassification.freeze_base_model   rK  r.   r  )r  r   r  r  Nr   r3   r  rx  ry  rM  r5   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   rS  )r|   r  ri  r  r^  r*   stackr   r  r  rj  r   rM   rl  r  r  r0   rn  r   rm  r   r$   r%   )r{   r   r3   r  rx  ry  rM  r[  r$   norm_weightspooled_outputpadding_maskr-  r    loss_fctrc  s                   r/   r   z*UniSpeechForSequenceClassification.forward(  s&   0 &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  )r&   r'   r(   ro   r!  r  rJ  r   r	  r   r
  r   r  r   r*   r  rR   r   r   r   r   r   s   @r/   rg  rg    sD           $
& 
& 
&> > >( ( ( +*+EFF&,$	   26,0/3&*)-;
 ;
u|,;
 !.;
 $D>	;

 'tn;
 d^;
 &;
 
u..	/;
 ;
 ;
  GF;
 ;
 ;
 ;
 ;
r.   rg  r   )Tr)   r  r   dataclassesr   typingr   r   r   numpyrI   r*   torch.utils.checkpointr   torch.nnr   activationsr
   integrations.deepspeedr   integrations.fsdpr   modeling_outputsr   r   r   r   modeling_utilsr   r   r   r   r   r   r   r   r   r   configuration_unispeechr   modeling_flash_attention_utilsr   
get_loggerr&   r,  r^  r  r
  r  rd  re  r   r9   r  r  ndarrayrf   Modulerh   r   r   r   r   r   r   r   r   r  r4  rO  r=  rL  r]  ri  ro  r  r  r  UNISPEECH_START_DOCSTRINGr	  r  r  r9  rg  r-   r.   r/   <module>r     s       ! ! ! ! ! ! ) ) ) ) ) ) ) ) ) )                % % % % % % ! ! ! ! ! ! @ @ @ @ @ @ 7 7 7 7 7 7 r r r r r r r r r r r r - - - - - -	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 5 4 4 4 4 4  KJJJJJJ 
	H	%	% !"  $ H '  q    :  :  :  :  :K  :  :  :P 26t tc?tt t U-.	t
 t Zt t t tp    BI   ,    ")   8    ")   2* * * * *ry * * *\    BI   , , , , ,bi , , ,^
 
 
 
 
 7 
 
 
1 1 1 1 1 1 1 1 [B [B [B [B [B [B [B [B~|9 |9 |9 |9 |91 |9 |9 |9~h1 h1 h1 h1 h1/ h1 h1 h1X  "1      29   2         BI      H    	   4* * * * *29 * * *\R
 R
 R
 R
 R
ry R
 R
 R
lV
 V
 V
 V
 V
bi V
 V
 V
rC' C' C' C' C'RY C' C' C'LJ J J J J J J JZ &" J i v
 v
 v
 v
 v
- v
 v
	 v
r Z\u L
 L
 L
 L
 L
6 L
 L
 L
^ q	 	T
 T
 T
 T
 T
. T
 T
	 	T
n   s
 s
 s
 s
 s
)A s
 s
 s
 s
 s
r.   