o
    i                     @   s  d Z ddlZddlmZmZ ddlZddlmZ ddlmZm	Z	m
Z
 ddlmZmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ e',e-Z.dZ/G dd dej0Z1G dd dej0Z2G dd dej0Z3de2iZ4G dd dej0Z5G dd dej0Z6G dd dej0Z7G d d! d!eZ8G d"d# d#ej0Z9G d$d% d%ej0Z:e&G d&d' d'e Z;e&G d(d) d)e;Z<e&d*d+G d,d- d-e;eZ=e&G d.d/ d/e;Z>G d0d1 d1ej0Z?e&d2d+G d3d4 d4e;Z@e&G d5d6 d6e;ZAe&G d7d8 d8e;ZBG d9d: d:ej0ZCe&G d;d< d<e;ZDd@d=d>ZEg d?ZFdS )AzPyTorch Data2VecText model.    N)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FNgelu)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging)deprecate_kwarg   )Data2VecTextConfig   c                       s4   e Zd ZdZ fddZ	d
ddZdd	 Z  ZS )Data2VecTextForTextEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _t|dd| _| jdt|jddd | jd	tj| j tjd
dd |j| _tj|j|j| jd| _	d S )N)padding_idxepsposition_embedding_typeabsoluteposition_ids)r   F)
persistenttoken_type_idsdtype)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutgetattrr&   register_buffertorcharangeexpandzerosr(   sizelongr#   selfconfig	__class__ g/home/ubuntu/.local/lib/python3.10/site-packages/transformers/models/data2vec/modeling_data2vec_text.pyr/   :   s"   
z&Data2VecTextForTextEmbeddings.__init__Nr   c                 C   s   |d u r|d urt || j|}n| |}|d ur| }n| d d }|d }|d u rTt| drI| jd d d |f }||d |}	|	}ntj|tj	| j
jd}|d u r]| |}| |}
||
 }| jdkrt| |}||7 }| |}| |}|S )Nr)   r   r+   r   r-   devicer'   )"create_position_ids_from_input_idsr#   &create_position_ids_from_inputs_embedsrD   hasattrr+   rB   r@   rC   rE   r(   rN   r4   r8   r&   r6   r9   r=   )rG   	input_idsr+   r(   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr8   
embeddingsr6   rK   rK   rL   forwardS   s0   








z%Data2VecTextForTextEmbeddings.forwardc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr)   r   rM   r   )rD   r@   rA   r#   rE   rN   	unsqueezerB   )rG   rS   rU   sequence_lengthr(   rK   rK   rL   rP   {   s   	zDData2VecTextForTextEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )__name__
__module____qualname____doc__r/   rZ   rP   __classcell__rK   rK   rI   rL   r"   4   s    
(r"   c                       s   e Zd Zd fdd	Zedddd						dd	ejd
eej deej deej dee	 dee
 deej deej fddZ  ZS )Data2VecTextSelfAttentionNc                    s  t    |j|j dkrt|dstd|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|p\t|dd| _| jdksh| jd	kry|j| _t	d
|j d | j| _|j| _|| _d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r&   r'   relative_keyrelative_key_queryr!   r   )r.   r/   r2   num_attention_headsrQ   
ValueErrorintattention_head_sizeall_head_sizer   Linearquerykeyvaluer;   attention_probs_dropout_probr=   r>   r&   r5   r0   distance_embedding
is_decoder	layer_idxrG   rH   r&   rs   rI   rK   rL   r/      s,   


z"Data2VecTextSelfAttention.__init__past_key_valuepast_key_values4.58new_nameversionFhidden_statesattention_mask	head_maskencoder_hidden_statesoutput_attentionscache_positionreturnc                 C   s   |j \}}	}
| |}||d| j| jdd}d}|d u}|d ur;t|tr9|j	| j
}|r5|j}n|j}n|}|r?|n|}|rX|d urX|rX|j| j
 j}|j| j
 j}nJ| |}||d| j| jdd}| |}||d| j| jdd}|d ur|s|nd }|||| j
d|i\}}|rt|trd|j| j
< t||dd}| jdks| jd	kr4|j d |j d }}|d urtj|d tj|jd
dd}ntj|tj|jd
dd}tj|tj|jd
dd}|| }| || j d }|j|jd}| jdkrtd||}|| }n| jd	kr4td||}td||}|| | }|t | j }|d urE|| }t!j"j#|dd}| $|}|d ur[|| }t||}|%dddd& }|' d d | j(f }||}||fS )Nr)   r   r!   Fr   Tre   rf   rM   r,   zbhld,lrd->bhlrzbhrd,lrd->bhlrdimr   r   ))shaperm   viewrg   rj   	transpose
isinstancer   
is_updatedgetrs   cross_attention_cacheself_attention_cachelayerskeysvaluesrn   ro   updater@   matmulr&   tensorrE   rN   rA   rq   r5   tor-   einsummathsqrtr   
functionalsoftmaxr=   permute
contiguousrD   rk   )rG   r{   r|   r}   r~   rv   r   r   
batch_sizerV   _query_layerr   is_cross_attentioncurr_past_key_valuecurrent_states	key_layervalue_layerattention_scoresquery_length
key_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shaperK   rK   rL   rZ      s   








z!Data2VecTextSelfAttention.forwardNNNNNNFN)r]   r^   r_   r/   r   r@   Tensorr   FloatTensorr   booltuplerZ   ra   rK   rK   rI   rL   rb      s4    	rb   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )Data2VecTextSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr$   )r.   r/   r   rl   r2   denser9   r:   r;   r<   r=   rF   rI   rK   rL   r/        
zData2VecTextSelfOutput.__init__r{   input_tensorr   c                 C   &   |  |}| |}| || }|S Nr   r=   r9   rG   r{   r   rK   rK   rL   rZ        

zData2VecTextSelfOutput.forwardr]   r^   r_   r/   r@   r   rZ   ra   rK   rK   rI   rL   r         $r   eagerc                       s   e Zd Zd fdd	Zdd Zedddd						
	ddejdeej	 deej	 deej	 dee
 dee deej deej fddZ  ZS )Data2VecTextAttentionNc                    s6   t    t|j |||d| _t|| _t | _d S )Nr&   rs   )	r.   r/   $DATA2VEC_TEXT_SELF_ATTENTION_CLASSES_attn_implementationrG   r   outputsetpruned_headsrt   rI   rK   rL   r/   )  s   

zData2VecTextAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r   )lenr   rG   rg   rj   r   r   rm   rn   ro   r   r   rk   union)rG   headsindexrK   rK   rL   prune_heads3  s   z!Data2VecTextAttention.prune_headsru   rv   rw   rx   Fr{   r|   r}   r~   r   r   r   c              	   C   s>   | j |||||||d}| |d |}	|	f|dd   }
|
S )Nr|   r}   r~   rv   r   r   r   r   )rG   r   )rG   r{   r|   r}   r~   rv   r   r   self_outputsattention_outputoutputsrK   rK   rL   rZ   E  s   	zData2VecTextAttention.forwardr   r   )r]   r^   r_   r/   r   r   r@   r   r   r   r   r   r   rZ   ra   rK   rK   rI   rL   r   (  s6    
	r   c                       2   e Zd Z fddZdejdejfddZ  ZS )Data2VecTextIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r.   r/   r   rl   r2   intermediate_sizer   r   
hidden_actstrr	   intermediate_act_fnrF   rI   rK   rL   r/   `  s
   
z!Data2VecTextIntermediate.__init__r{   r   c                 C   s   |  |}| |}|S r   )r   r   )rG   r{   rK   rK   rL   rZ   h  s   

z Data2VecTextIntermediate.forwardr   rK   rK   rI   rL   r   _  s    r   c                       r   )Data2VecTextOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r.   r/   r   rl   r   r2   r   r9   r:   r;   r<   r=   rF   rI   rK   rL   r/   p  r   zData2VecTextOutput.__init__r{   r   r   c                 C   r   r   r   r   rK   rK   rL   rZ   v  r   zData2VecTextOutput.forwardr   rK   rK   rI   rL   r   o  r   r   c                       s   e Zd Zd fdd	Zedddd							dd	ejd
eej deej deej deej dee	 dee
 deej deej fddZdd Z  ZS )Data2VecTextLayerNc                    sx   t    |j| _d| _t||d| _|j| _|j| _| jr0| js(t|  dt|d|d| _	t
|| _t|| _d S )Nr   rs   z> should be used as a decoder model if cross attention is addedr'   r   )r.   r/   chunk_size_feed_forwardseq_len_dimr   	attentionrr   add_cross_attentionrh   crossattentionr   intermediater   r   rG   rH   rs   rI   rK   rL   r/     s   

zData2VecTextLayer.__init__ru   rv   rw   rx   Fr{   r|   r}   r~   encoder_attention_maskr   r   r   c	              	   C   s   | j ||||||d}	|	d }
|	dd  }| jrA|d urAt| ds)td|  d| j|
||||||d}|d }
||dd   }t| j| j| j|
}|f| }|S )N)r|   r}   r   rv   r   r   r   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   )	r   rr   rQ   rh   r   r   feed_forward_chunkr   r   )rG   r{   r|   r}   r~   r   rv   r   r   self_attention_outputsr   r   cross_attention_outputslayer_outputrK   rK   rL   rZ     s>   

	
zData2VecTextLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rG   r   intermediate_outputr   rK   rK   rL   r     s   
z$Data2VecTextLayer.feed_forward_chunkr   )NNNNNFN)r]   r^   r_   r/   r   r@   r   r   r   r   r   r   rZ   r   ra   rK   rK   rI   rL   r   ~  s<    	
0r   c                       s   e Zd Zd fdd	Z										ddejdeej deej d	eej d
eej dee dee	 dee	 dee	 dee	 deej de
eej ef fddZ  ZS )Data2VecTextEncoderNc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  |d qS )r   )r   ).0irH   rK   rL   
<listcomp>  s    z0Data2VecTextEncoder.__init__.<locals>.<listcomp>F)	r.   r/   rH   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   rI   r   rL   r/     s   
 
zData2VecTextEncoder.__init__FTr{   r|   r}   r~   r   rv   	use_cacher   output_hidden_statesreturn_dictr   r   c                 C   s`  |	rdnd }|r
dnd }|r| j jrdnd }| jr%| jr%|r%td d}|r<| j jr<|d u r<tt| j dt| j d}|rQ| j jrQt	|t
rQtd t|}t| jD ]9\}}|	ra||f }|d uri|| nd }|||||||||d}|d }|r||d f }| j jr||d	 f }qV|	r||f }|
st
d
d |||||fD S t|||||dS )NrK   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   zPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.)r   rv   r   r   r   r   r!   c                 s   s    | ]	}|d ur|V  qd S r   rK   )r   vrK   rK   rL   	<genexpr>  s    z.Data2VecTextEncoder.forward.<locals>.<genexpr>)last_hidden_staterv   r{   
attentionscross_attentions)rH   r   r   trainingloggerwarning_oncerr   r   r   r   r   from_legacy_cache	enumerater   r   )rG   r{   r|   r}   r~   r   rv   r   r   r   r   r   all_hidden_statesall_self_attentionsall_cross_attentionsr   layer_modulelayer_head_masklayer_outputsrK   rK   rL   rZ     sl   


zData2VecTextEncoder.forwardr   )
NNNNNNFFTN)r]   r^   r_   r/   r@   r   r   r   r   r   r   r   r   rZ   ra   rK   rK   rI   rL   r     sJ    		
r   c                       r   )Data2VecTextPoolerc                    s*   t    t|j|j| _t | _d S r   )r.   r/   r   rl   r2   r   Tanh
activationrF   rI   rK   rL   r/   #  s   
zData2VecTextPooler.__init__r{   r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r	  )rG   r{   first_token_tensorpooled_outputrK   rK   rL   rZ   (  s   

zData2VecTextPooler.forwardr   rK   rK   rI   rL   r  "  s    r  c                   @   s.   e Zd ZU eed< dZdZddgZdd ZdS )	Data2VecTextPreTrainedModelrH   data2vec_textTr"   r   c                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrlt|drY|jdurY|jj	  t|drn|jdurp|jjd dS dS dS dS )zInitialize the weightsg        )meanstdNbiasweightg      ?)r   r   rl   r  datanormal_rH   initializer_ranger  zero_r0   r#   r9   rQ   fill_)rG   modulerK   rK   rL   _init_weights8  s"   

z)Data2VecTextPreTrainedModel._init_weightsN)	r]   r^   r_   r    __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modulesr  rK   rK   rK   rL   r  1  s   
 r  c                "       s   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Ze														dde	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e de	e de	e de	e de	e de	e
j deee
j ef fddZ  ZS )Data2VecTextModela2  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in *Attention is
    all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
    Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.

    .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762

    Tc                    sD   t  | || _t|| _t|| _|rt|nd| _| 	  dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)
r.   r/   rH   r"   rY   r   encoderr  pooler	post_init)rG   rH   add_pooling_layerrI   rK   rL   r/   \  s   

zData2VecTextModel.__init__c                 C      | j jS r   rY   r4   rG   rK   rK   rL   get_input_embeddingsl     z&Data2VecTextModel.get_input_embeddingsc                 C      || j _d S r   r$  )rG   ro   rK   rK   rL   set_input_embeddingso     z&Data2VecTextModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )rG   heads_to_pruner   r   rK   rK   rL   _prune_headsr  s   zData2VecTextModel._prune_headsNrR   r|   r+   r(   r}   rS   r~   r   rv   r   r   r   r   r   r   c                  C   sd  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}| j jr-|
d ur(|
n| j j}
nd}
|d ur;|d ur;td|d urJ| || | }n|d urW| d d }ntd|\}}|d urf|j	n|j	}d}|	d urt
|	ts}|	d d jd n|	 }|d u rtj||| f|d}|d u rt| jdr| jjd d d |f }|||}|}n	tj|tj|d	}| ||}| j jr|d ur| \}}}||f}|d u rtj||d}| |}nd }| || j j}| j|||||d
}| j||||||	|
||||d}|d }| jd ur| |nd }|s$||f|dd   S t|||j|j|j|j dS )NFzDYou cannot specify both input_ids and inputs_embeds at the same timer)   z5You have to specify either input_ids or inputs_embedsr   r   )rN   r+   rM   )rR   r(   r+   rS   rT   )
r|   r}   r~   r   rv   r   r   r   r   r   r   )r   pooler_outputrv   r{   r   r   )!rH   r   r   use_return_dictrr   r   rh   %warn_if_padding_and_no_attention_maskrD   rN   r   r   r   get_seq_lengthr@   onesrQ   rY   r+   rB   rC   rE   get_extended_attention_maskinvert_attention_maskget_head_maskr   r  r   r   rv   r{   r   r   ) rG   rR   r|   r+   r(   r}   rS   r~   r   rv   r   r   r   r   r   rU   r   rV   rN   rT   rW   rX   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputr  rK   rK   rL   rZ   z  s   
zData2VecTextModel.forward)T)NNNNNNNNNNNNNN)r]   r^   r_   r`   r/   r&  r)  r-  r   r   r@   r   r   r   r   r   r   rZ   ra   rK   rK   rI   rL   r  K  sh    	
r  zX
    Data2VecText Model with a `language modeling` head on top for CLM fine-tuning.
    )custom_introc                $       s   e Zd ZddgZ fddZdd Zdd Ze																														dd
ee	j
 dee	j dee	j
 dee	j
 dee	j dee	j dee	j dee	j dee	j
 dee dee dee dee dee dee	j deeef f ddZ  ZS )Data2VecTextForCausalLMlm_head.decoder.weightlm_head.decoder.biasc                    s@   t  | |jstd t|dd| _t|| _| 	  d S )NzTIf you want to use `Data2VecTextLMHeadModel` as a standalone, add `is_decoder=True.`Fr"  
r.   r/   rr   r   warningr  r  Data2VecTextLMHeadlm_headr!  rF   rI   rK   rL   r/     s   

z Data2VecTextForCausalLM.__init__c                 C   r#  r   rF  decoderr%  rK   rK   rL   get_output_embeddings  r'  z-Data2VecTextForCausalLM.get_output_embeddingsc                 C   r(  r   rG  rG   new_embeddingsrK   rK   rL   set_output_embeddings  r*  z-Data2VecTextForCausalLM.set_output_embeddingsNrR   r|   r+   r(   r}   rS   r~   r   labelsrv   r   r   r   r   r   r   c                 K   s   |dur|n| j j}|	durd}| j|||||||||
|||||d}|d }| |}d}|	dur@| j||	fd| j ji|}|sV|f|dd  }|durT|f| S |S t|||j|j|j	|j
dS )aA  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Example:

        ```python
        >>> from transformers import AutoTokenizer, Data2VecTextForCausalLM, Data2VecTextConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/data2vec-text-base")
        >>> config = Data2VecTextConfig.from_pretrained("facebook/data2vec-text-base")
        >>> config.is_decoder = True
        >>> model = Data2VecTextForCausalLM.from_pretrained("facebook/data2vec-text-base", config=config)

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> prediction_logits = outputs.logits
        ```NF)r|   r+   r(   r}   rS   r~   r   rv   r   r   r   r   r   r   r1   r!   )losslogitsrv   r{   r   r   )rH   r/  r  rF  loss_functionr1   r   rv   r{   r   r   )rG   rR   r|   r+   r(   r}   rS   r~   r   rM  rv   r   r   r   r   r   kwargsr   r=  prediction_scoreslm_lossr   rK   rK   rL   rZ     sT   *
zData2VecTextForCausalLM.forward)NNNNNNNNNNNNNNN)r]   r^   r_   _tied_weights_keysr/   rI  rL  r   r   r@   
LongTensorr   r   r   r   r   r   r   rZ   ra   rK   rK   rI   rL   r?    sl    	

r?  c                       s   e Zd ZddgZ fddZdd Zdd Ze																								dd
ee	j
 dee	j dee	j
 dee	j
 dee	j dee	j dee	j dee	j dee	j
 dee dee dee deeef fddZ  ZS )Data2VecTextForMaskedLMr@  rA  c                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NzsIf you want to use `Data2VecTextForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.FrB  rC  rF   rI   rK   rL   r/   h  s   
z Data2VecTextForMaskedLM.__init__c                 C   r#  r   rG  r%  rK   rK   rL   rI  w  r'  z-Data2VecTextForMaskedLM.get_output_embeddingsc                 C   r(  r   rG  rJ  rK   rK   rL   rL  z  r*  z-Data2VecTextForMaskedLM.set_output_embeddingsNrR   r|   r+   r(   r}   rS   r~   r   rM  r   r   r   r   c                 C   s   |dur|n| j j}| j|||||||||
||d}|d }| |}d}|	dur@t }|	|j}	||d| j j|	d}|sV|f|dd  }|durT|f| S |S t	|||j
|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        N)
r|   r+   r(   r}   rS   r~   r   r   r   r   r   r)   r!   rN  rO  r{   r   )rH   r/  r  rF  r   r   rN   r   r1   r   r{   r   )rG   rR   r|   r+   r(   r}   rS   r~   r   rM  r   r   r   r   r=  rR  masked_lm_lossloss_fctr   rK   rK   rL   rZ   }  s<   
zData2VecTextForMaskedLM.forward)NNNNNNNNNNNN)r]   r^   r_   rT  r/   rI  rL  r   r   r@   rU  r   r   r   r   r   rZ   ra   rK   rK   rI   rL   rV  d  sZ    	

rV  c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )rE  z/Data2VecText Head for masked language modeling.c                    sd   t    t|j|j| _tj|j|jd| _t|j|j	| _
tt|j	| _| j| j
_d S r   )r.   r/   r   rl   r2   r   r9   r:   
layer_normr1   rH  	Parameterr@   rC   r  rF   rI   rK   rL   r/     s   
zData2VecTextLMHead.__init__c                 K   s*   |  |}t|}| |}| |}|S r   )r   r
   rZ  rH  rG   featuresrQ  xrK   rK   rL   rZ     s
   


zData2VecTextLMHead.forwardc                 C   s,   | j jjjdkr| j| j _d S | j j| _d S )Nmeta)rH  r  rN   typer%  rK   rK   rL   _tie_weights  s   zData2VecTextLMHead._tie_weights)r]   r^   r_   r`   r/   rZ   ra  ra   rK   rK   rI   rL   rE    s
    	
rE  z
    Data2VecText Model transformer with a sequence classification/regression head on top (a linear layer on top of the
    pooled output) e.g. for GLUE tasks.
    c                          e Zd Z fddZe										ddeej deej deej deej deej d	eej d
eej dee	 dee	 dee	 de
eef fddZ  ZS )%Data2VecTextForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NFrB  )	r.   r/   
num_labelsrH   r  r  Data2VecTextClassificationHead
classifierr!  rF   rI   rK   rL   r/     s   
z.Data2VecTextForSequenceClassification.__init__NrR   r|   r+   r(   r}   rS   rM  r   r   r   r   c                 C   st  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dur||j}| j jdu rW| jdkr=d| j _n| jdkrS|jt	j
ksN|jt	jkrSd| j _nd| j _| j jdkrut }| jdkro|| | }n+|||}n%| j jdkrt }||d| j|d}n| j jdkrt }|||}|
s|f|d	d  }|dur|f| S |S t|||j|jd
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).
        Nr|   r+   r(   r}   rS   r   r   r   r   r   
regressionsingle_label_classificationmulti_label_classificationr)   r!   rW  )rH   r/  r  rg  r   rN   problem_typere  r-   r@   rE   ri   r   squeezer   r   r   r   r{   r   rG   rR   r|   r+   r(   r}   rS   rM  r   r   r   r   r=  rO  rN  rY  r   rK   rK   rL   rZ     sV   


"


z-Data2VecTextForSequenceClassification.forward
NNNNNNNNNN)r]   r^   r_   r/   r   r   r@   rU  r   r   r   r   r   rZ   ra   rK   rK   rI   rL   rc    sH    	

rc  c                       s   e Zd Z fddZe										ddeej deej deej deej deej d	eej d
eej dee	 dee	 dee	 de
eef fddZ  ZS )Data2VecTextForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )r.   r/   r  r  r   r;   r<   r=   rl   r2   rg  r!  rF   rI   rK   rL   r/   5  s
   
z&Data2VecTextForMultipleChoice.__init__NrR   r+   r|   rM  r(   r}   rS   r   r   r   r   c                 C   sz  |
dur|
n| j j}
|dur|jd n|jd }|dur%|d|dnd}|dur4|d|dnd}|durC|d|dnd}|durR|d|dnd}|dure|d|d|dnd}| j||||||||	|
d	}|d }| |}| |}|d|}d}|durt }|	|j
}|||}|
s|f|dd  }|dur|f| S |S t|||j|jdS )a[  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        Nr   r)   r   )r(   r+   r|   r}   rS   r   r   r   r!   rW  )rH   r/  r   r   rD   r  r=   rg  r   r   rN   r   r{   r   )rG   rR   r+   r|   rM  r(   r}   rS   r   r   r   num_choicesflat_input_idsflat_position_idsflat_token_type_idsflat_attention_maskflat_inputs_embedsr   r  rO  reshaped_logitsrN  rY  r   rK   rK   rL   rZ   ?  sN   ,


z%Data2VecTextForMultipleChoice.forwardro  )r]   r^   r_   r/   r   r   r@   rU  r   r   r   r   r   rZ   ra   rK   rK   rI   rL   rp  3  sH    
	

rp  c                       rb  )"Data2VecTextForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd ur|jn|j}t|| _	t
|j|j| _|   d S rd  )r.   r/   re  r  r  classifier_dropoutr<   r   r;   r=   rl   r2   rg  r!  rG   rH   ry  rI   rK   rL   r/     s   z+Data2VecTextForTokenClassification.__init__NrR   r|   r+   r(   r}   rS   rM  r   r   r   r   c                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|durBt }||j}||d| j	|d}|
sX|f|dd  }|durV|f| S |S t
|||j|jdS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nrh  r   r)   r!   rW  )rH   r/  r  r=   rg  r   r   rN   r   re  r   r{   r   rn  rK   rK   rL   rZ     s:   

z*Data2VecTextForTokenClassification.forwardro  )r]   r^   r_   r/   r   r   r@   rU  r   r   r   r   r   rZ   ra   rK   rK   rI   rL   rx    sH    	

rx  c                       s(   e Zd ZdZ fddZdd Z  ZS )rf  z-Head for sentence-level classification tasks.c                    sT   t    t|j|j| _|jd ur|jn|j}t|| _	t|j|j
| _d S r   )r.   r/   r   rl   r2   r   ry  r<   r;   r=   re  out_projrz  rI   rK   rL   r/     s   
z'Data2VecTextClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r
  )r=   r   r@   tanhr{  r\  rK   rK   rL   rZ     s   




z&Data2VecTextClassificationHead.forward)r]   r^   r_   r`   r/   rZ   ra   rK   rK   rI   rL   rf    s    	rf  c                       s   e Zd Z fddZe											ddeej deej deej deej deej d	eej d
eej deej dee	 dee	 dee	 de
eef fddZ  ZS ) Data2VecTextForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S rd  )
r.   r/   re  r  r  r   rl   r2   
qa_outputsr!  rF   rI   rK   rL   r/     s
   z)Data2VecTextForQuestionAnswering.__init__NrR   r|   r+   r(   r}   rS   start_positionsend_positionsr   r   r   r   c                 C   sH  |d ur|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d }|d ur|d urt| dkrO|d}t| dkr\|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s||f|dd   }|d ur|f| S |S t||||j|jdS )	Nrh  r   r   r)   r   )ignore_indexr!   )rN  start_logits
end_logitsr{   r   )rH   r/  r  r~  splitrm  r   r   rD   clampr   r   r{   r   )rG   rR   r|   r+   r(   r}   rS   r  r  r   r   r   r   r=  rO  r  r  
total_lossignored_indexrY  
start_lossend_lossr   rK   rK   rL   rZ     sP   






z(Data2VecTextForQuestionAnswering.forward)NNNNNNNNNNN)r]   r^   r_   r/   r   r   r@   rU  r   r   r   r   r   rZ   ra   rK   rK   rI   rL   r}    sN    
	

r}  c                 C   s6   |  | }tj|dd|| | }| | S )a  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.

    Args:
        x: torch.Tensor x:

    Returns: torch.Tensor
    r   r   )neri   r@   cumsumtype_asrE   )rR   r#   rT   maskincremental_indicesrK   rK   rL   rO   I  s   rO   )r?  rV  rp  r}  rc  rx  r  r  )r   )Gr`   r   typingr   r   r@   r   torch.nnr   r   r   activationsr	   r
   cache_utilsr   r   r   
generationr   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   utils.deprecationr   configuration_data2vec_textr    
get_loggerr]   r   _HIDDEN_STATES_START_POSITIONModuler"   rb   r   r   r   r   r   r   r   r  r  r  r?  rV  rE  rc  rp  rx  rf  r}  rO   __all__rK   rK   rK   rL   <module>   sn   (

Z 7I[ &nTUhH
M