o
    Zh7                    @   sD  d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ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-m.Z.m/Z/ ddl0m1Z1 e/2e3Z4dd Z5G dd dej6Z7G dd dej6Z8G dd de8Z9G dd dej6Z:e8e9dZ;G dd dej6Z<G dd  d ej6Z=G d!d" d"ej6Z>G d#d$ d$ej6Z?G d%d& d&ej6Z@G d'd( d(ej6ZAG d)d* d*ej6ZBG d+d, d,ej6ZCG d-d. d.ej6ZDG d/d0 d0ej6ZEG d1d2 d2ej6ZFe-G d3d4 d4e&ZGeG d5d6 d6e,ZHe-d7d8G d9d: d:eGZIe-d;d8G d<d= d=eGZJe-d>d8G d?d@ d@eGeZKe-G dAdB dBeGZLe-dCd8G dDdE dEeGZMe-dFd8G dGdH dHeGZNe-G dIdJ dJeGZOe-G dKdL dLeGZPe-G dMdN dNeGZQg dOZRdS )PzPyTorch BERT model.    N)	dataclass)ListOptionalTupleUnion)version)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GenerationMixin)#_prepare_4d_attention_mask_for_sdpa*_prepare_4d_causal_attention_mask_for_sdpa)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputauto_docstringget_torch_versionlogging   )
BertConfigc                 C   s  zddl }ddl}ddl}W n ty   td  w tj|}t	d|  |j
|}g }g }	|D ] \}
}t	d|
 d|  |j
||
}||
 |	| q6t||	D ]\}
}|
d}
tdd	 |
D rzt	d
d|
  q\| }|
D ]|}|d|r|d|}n|g}|d dks|d dkrt|d}nH|d dks|d dkrt|d}n6|d dkrt|d}n*|d dkrt|d}nz	t||d }W n ty   t	d
d|
  Y q~w t|dkrt|d }|| }q~|dd dkr
t|d}n
|dkr||}z|j|jkr)td|j d|j dW n tyC } z| j|j|jf7  _ d}~ww t	d|
  t||_q\| S )z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape /c                 s   s    | ]}|d v V  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr%   r%   U/var/www/auris/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py	<genexpr>R   s
    
z*load_tf_weights_in_bert.<locals>.<genexpr>z	Skipping z[A-Za-z]+_\d+z_(\d+)ZkernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquad
classifier   r"   iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )renumpyZ
tensorflowImportErrorloggererrorospathabspathinfotrainZlist_variablesZload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshape
ValueErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr0   nptfZtf_pathZ	init_varsnamesZarraysnamerE   arrayZpointerZm_nameZscope_namesnumer%   r%   r(   load_tf_weights_in_bert5   s   



rS   c                       sh   e Zd ZdZ fddZ					ddeej deej deej d	eej d
e	dej
fddZ  ZS )BertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.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 d S )N)padding_idxZ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_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutr@   rW   Zregister_bufferrH   arangeexpandzerosrY   sizelongselfrK   	__class__r%   r(   r`      s   

zBertEmbeddings.__init__Nr   	input_idsr\   rY   inputs_embedspast_key_values_lengthreturnc                 C   s   |d ur	|  }n|  d d }|d }|d u r&| jd d ||| f }|d u rPt| drE| jd d d |f }||d |}	|	}ntj|tj| jjd}|d u rY| 	|}| 
|}
||
 }| jdkrp| |}||7 }| |}| |}|S )NrZ   r"   r\   r   r^   devicerX   )rq   rY   hasattrr\   ro   rH   rp   rr   r|   re   rh   rW   rg   ri   rm   )rt   rw   r\   rY   rx   ry   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedrh   
embeddingsrg   r%   r%   r(   forward   s,   







zBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r`   r   rH   Z
LongTensorFloatTensorrC   Tensorr   __classcell__r%   r%   ru   r(   rT   ~   s*    rT   c                       s   e Zd Zd fdd	Zdejdej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	e	ej   dee
 de	ej fddZ  ZS )BertSelfAttentionNc                    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   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()rW   rX   relative_keyrelative_key_queryr/   r"   )r_   r`   rc   num_attention_headsr}   rF   rC   attention_head_sizeall_head_sizer   Linearquerykeyvaluerk   attention_probs_dropout_probrm   r@   rW   rf   ra   distance_embedding
is_decoderrt   rK   rW   ru   r%   r(   r`      s*   

zBertSelfAttention.__init__xrz   c                 C   s6   |  d d | j| jf }||}|ddddS )NrZ   r   r/   r"   r   )rq   r   r   viewpermute)rt   r   Znew_x_shaper%   r%   r(   transpose_for_scores   s   
z&BertSelfAttention.transpose_for_scoresFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 C   s  |  |}|d u}	|	r|d ur|d }
|d }|}nP|	r/| | |}
| | |}|}n;|d urZ| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}|d u}| jrz|
|f}t||
dd}| j	dks| j	dkr	|j
d |
j
d }}|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rtd||}|| }n| j	dkr	td||}td|
|}|| | }|t| j }|d ur|| }tjj|dd}| |}|d ur0|| }t||}|dddd }| d d | jf }||}|rX||fn|f}| jrd||f }|S )Nr   r"   r/   dimrZ   r   r   r{   r]   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r   r   r   r   rH   catr   matmulrD   rW   rE   Ztensorrr   r|   r   rn   r   rf   tor^   Zeinsummathsqrtr   r   
functionalZsoftmaxrm   r   
contiguousrq   r   )rt   r   r   r   r   r   r   r   Zmixed_query_layeris_cross_attention	key_layervalue_layerquery_layer	use_cacheZattention_scoresZquery_lengthZ
key_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr%   r%   r(   r      sn   









zBertSelfAttention.forwardNNNNNNF)r   r   r   r`   rH   r   r   r   r   r   boolr   r   r%   r%   ru   r(   r      s4    	r   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eej   dee	 deej f fddZ
  ZS )BertSdpaSelfAttentionNc                    s4   t  j||d |j| _tt tdk | _d S )NrW   z2.2.0)r_   r`   r   dropout_probr   parser    require_contiguous_qkvr   ru   r%   r(   r`   E  s   zBertSdpaSelfAttention.__init__Fr   r   r   r   r   r   r   rz   c              	      s  | j dks|s|d urtd t |||||||S | \}}	}
| | |}|d u}|r3|n|}|r9|n|}|rP|rP|d jd |jd krP|\}}n,| | 	|}| | 
|}|d ur||s|tj|d |gdd}tj|d |gdd}| jr||f}| jr|jjdkr|d ur| }| }| }| jr|s|d u r|	dkrdnd	}tjjj||||| jr| jnd
|d}|dd}|||	| j}|f}| jr||f }|S )NrX   a  BertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   r/   r"   r   cudaTF        )Z	attn_maskZ	dropout_p	is_causal)rW   r3   warning_oncer_   r   rq   r   r   rE   r   r   rH   r   r   r   r|   typer   r   r   Zscaled_dot_product_attentiontrainingr   rD   Zreshaper   )rt   r   r   r   r   r   r   r   Zbsztgt_len_r   r   Zcurrent_statesr   r   r   Zattn_outputr   ru   r%   r(   r   K  s^   

 
 	
zBertSdpaSelfAttention.forwardr   r   )r   r   r   r`   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   r   D  s2    		r   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 )BertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrV   )r_   r`   r   r   rc   denseri   rj   rk   rl   rm   rs   ru   r%   r(   r`        
zBertSelfOutput.__init__r   input_tensorrz   c                 C   &   |  |}| |}| || }|S r   r   rm   ri   rt   r   r   r%   r%   r(   r        

zBertSelfOutput.forwardr   r   r   r`   rH   r   r   r   r%   r%   ru   r(   r         $r   )eagersdpac                       s   e Zd Zd fdd	Z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	e	ej   dee
 de	ej fddZ  ZS )BertAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )Nr   )	r_   r`   BERT_SELF_ATTENTION_CLASSES_attn_implementationrt   r   outputsetpruned_headsr   ru   r%   r(   r`     s   

zBertAttention.__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   )rB   r   rt   r   r   r   r   r   r   r   r   r   r   union)rt   headsindexr%   r%   r(   prune_heads  s   zBertAttention.prune_headsFr   r   r   r   r   r   r   rz   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r"   )rt   r   )rt   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r%   r%   r(   r     s   
	zBertAttention.forwardr   r   )r   r   r   r`   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   r     s4    	r   c                       2   e Zd Z fddZdejdejfddZ  ZS )BertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r_   r`   r   r   rc   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrs   ru   r%   r(   r`     s
   
zBertIntermediate.__init__r   rz   c                 C      |  |}| |}|S r   )r   r   rt   r   r%   r%   r(   r        

zBertIntermediate.forwardr   r%   r%   ru   r(   r     s    r   c                       r   )
BertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r_   r`   r   r   r   rc   r   ri   rj   rk   rl   rm   rs   ru   r%   r(   r`      r   zBertOutput.__init__r   r   rz   c                 C   r   r   r   r   r%   r%   r(   r     r   zBertOutput.forwardr   r%   r%   ru   r(   r     r   r   c                       s   e Zd Z 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eej   dee	 deej fddZ
dd Z  ZS )	BertLayerc                    sr   t    |j| _d| _t|| _|j| _|j| _| jr-| js&t|  dt|dd| _	t
|| _t|| _d S )Nr"   z> should be used as a decoder model if cross attention is addedrX   r   )r_   r`   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionrF   crossattentionr   intermediater   r   rs   ru   r%   r(   r`     s   


zBertLayer.__init__NFr   r   r   r   r   r   r   rz   c              	   C   s  |d ur
|d d nd }| j |||||d}	|	d }
| jr(|	dd }|	d }n|	dd  }d }| jro|d urot| dsDtd|  d|d urN|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nr/   )r   r   r   r"   rZ   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   r   r}   rF   r   r   feed_forward_chunkr   r   )rt   r   r   r   r   r   r   r   Zself_attn_past_key_valueZself_attention_outputsr   r   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputslayer_outputr%   r%   r(   r     sP   


	

zBertLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rt   r   Zintermediate_outputr   r%   r%   r(   r   ]  s   
zBertLayer.feed_forward_chunkr   )r   r   r   r`   rH   r   r   r   r   r   r   r   r   r%   r%   ru   r(   r     s4    	
Ar   c                       s   e Zd Z 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eej   dee	 dee	 dee	 dee	 de
eej ef fddZ  ZS )BertEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r%   )r   )r&   r   rK   r%   r(   
<listcomp>g  s    z(BertEncoder.__init__.<locals>.<listcomp>F)	r_   r`   rK   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingrs   ru   r   r(   r`   d  s   
 
zBertEncoder.__init__NFTr   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictrz   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)dnd }t| jD ]^\}}|	r;||f }|d urC|| nd }|d urM|| nd }| jrc| jrc| |j	|||||||}n
||||||||}|d }|rz||d f7 }|r||d f }| j jr||d f }q0|	r||f }|
st
dd	 |||||fD S t|||||d
S )Nr%   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   rZ   r"   r/   c                 s   s    | ]	}|d ur|V  qd S r   r%   )r&   vr%   r%   r(   r)     s    z&BertEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)rK   r   r   r   r3   r   	enumerater   Z_gradient_checkpointing_func__call__tupler   )rt   r   r   r   r   r   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr%   r%   r(   r   j  sz   


zBertEncoder.forward)	NNNNNNFFT)r   r   r   r`   rH   r   r   r   r   r   r   r   r   r   r%   r%   ru   r(   r   c  sD    		
r   c                       r   )
BertPoolerc                    s*   t    t|j|j| _t | _d S r   )r_   r`   r   r   rc   r   ZTanh
activationrs   ru   r%   r(   r`     s   
zBertPooler.__init__r   rz   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r  )rt   r   Zfirst_token_tensorpooled_outputr%   r%   r(   r     s   

zBertPooler.forwardr   r%   r%   ru   r(   r    s    r  c                       r   )BertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r   )r_   r`   r   r   rc   r   r   r   r   r   transform_act_fnri   rj   rs   ru   r%   r(   r`     s   
z$BertPredictionHeadTransform.__init__r   rz   c                 C   s"   |  |}| |}| |}|S r   )r   r  ri   r   r%   r%   r(   r     s   


z#BertPredictionHeadTransform.forwardr   r%   r%   ru   r(   r    s    	r  c                       s,   e Zd Z fddZdd Zdd Z  ZS )BertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r-   )r_   r`   r  	transformr   r   rc   rb   decoder	ParameterrH   rp   r-   rs   ru   r%   r(   r`     s
   

zBertLMPredictionHead.__init__c                 C   s   | j | j_ d S r   )r-   r  rt   r%   r%   r(   _tie_weights  s   z!BertLMPredictionHead._tie_weightsc                 C   r   r   )r
  r  r   r%   r%   r(   r     r   zBertLMPredictionHead.forward)r   r   r   r`   r  r   r   r%   r%   ru   r(   r	    s    r	  c                       r   )BertOnlyMLMHeadc                    s   t    t|| _d S r   )r_   r`   r	  predictionsrs   ru   r%   r(   r`     s   
zBertOnlyMLMHead.__init__sequence_outputrz   c                 C      |  |}|S r   )r  )rt   r  prediction_scoresr%   r%   r(   r        
zBertOnlyMLMHead.forwardr   r%   r%   ru   r(   r    s    r  c                       $   e Zd Z fddZdd Z  ZS )BertOnlyNSPHeadc                    s   t    t|jd| _d S Nr/   )r_   r`   r   r   rc   seq_relationshiprs   ru   r%   r(   r`     s   
zBertOnlyNSPHead.__init__c                 C   r  r   )r  )rt   r  seq_relationship_scorer%   r%   r(   r     r  zBertOnlyNSPHead.forwardr   r   r   r`   r   r   r%   r%   ru   r(   r    s    r  c                       r  )BertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S r  )r_   r`   r	  r  r   r   rc   r  rs   ru   r%   r(   r`     s   

zBertPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r   )r  r  )rt   r  r  r  r  r%   r%   r(   r     s   

zBertPreTrainingHeads.forwardr  r%   r%   ru   r(   r    s    r  c                   @   s(   e Zd ZeZeZdZdZdZ	dd Z
dS )BertPreTrainedModelbertTc                 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rX|jj	  |jjd dS t |tre|jj	  dS dS )zInitialize the weightsr   )meanZstdNg      ?)r   r   r   r+   rI   Znormal_rK   Zinitializer_ranger-   Zzero_ra   rU   ri   Zfill_r	  )rt   moduler%   r%   r(   _init_weights  s    


z!BertPreTrainedModel._init_weightsN)r   r   r   r#   Zconfig_classrS   Zload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingZ_supports_sdpar   r%   r%   r%   r(   r    s    r  c                   @   st   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eej ed< dZeeej  ed< dZeeej  ed< dS )BertForPreTrainingOutputa\  
    Output type of [`BertForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the masked language modeling loss and the next sequence prediction
            (classification) loss.
        prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            before SoftMax).
        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prediction_logitsseq_relationship_logitsr   r   )r   r   r   r   r"  r   rH   r   __annotations__r#  r$  r   r   r   r%   r%   r%   r(   r!  2  s   
 r!  a  
    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](https://arxiv.org/abs/1706.03762) 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.
    )Zcustom_introc                        s   e Zd Zddg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e
j  de	e de	e de	e de	e deee
j ef fddZ  ZS )	BertModelrT   r   Tc                    sT   t  | || _t|| _t|| _|rt|nd| _|j	| _
|j| _|   dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)r_   r`   rK   rT   r   r   encoderr  poolerr   attn_implementationrW   	post_init)rt   rK   add_pooling_layerru   r%   r(   r`   c  s   

zBertModel.__init__c                 C   s   | j jS r   r   re   r  r%   r%   r(   get_input_embeddingsv  s   zBertModel.get_input_embeddingsc                 C   s   || j _d S r   r,  )rt   r   r%   r%   r(   set_input_embeddingsy  s   zBertModel.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   )rt   Zheads_to_pruner   r   r%   r%   r(   _prune_heads|  s   zBertModel._prune_headsNrw   r   r\   rY   r   rx   r   r   r   r   r   r   r   rz   c                  C   s  |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 urv|	d d j
d nd}|d u rt| jdr| jjd d d |f }|||}|}n	tj|tj|d}| j|||||d	}|d u rtj||| f|d
}| jdko| jdko|d u o| }|r| dkr| j jrt||||}nt||j|d}n| ||}| j jr'|d ur'| \}}}||f}|d u rtj||d
}|r!| dkr!t||j|d}n| |}nd }| || j j}| j||||||	|
|||d
}|d }| jd urO| |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 timerZ   z5You have to specify either input_ids or inputs_embedsr   r/   r\   r{   )rw   rY   r\   rx   ry   )r|   r   rX   )r   )	r   r   r   r   r   r   r   r   r   r"   )r   Zpooler_outputr   r   r   r   )$rK   r   r   use_return_dictr   r   rF   Z%warn_if_padding_and_no_attention_maskrq   r|   rE   r}   r   r\   ro   rH   rp   rr   Zonesr)  rW   r   r   r   r^   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r'  r(  r   r   r   r   r   ) rt   rw   r   r\   rY   r   rx   r   r   r   r   r   r   r   r~   Z
batch_sizer   r|   ry   r   r   Zembedding_outputZuse_sdpa_attention_masksZextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZencoder_outputsr  r  r%   r%   r(   r     s   


zBertModel.forward)T)NNNNNNNNNNNNN)r   r   r   Z_no_split_modulesr`   r-  r.  r0  r   r   rH   r   r   r   r   r   r   r   r   r   r%   r%   ru   r(   r&  T  sb    	
r&  z
    Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
    sentence prediction (classification)` head.
    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 dee dee deee	j
 ef fddZ  ZS )BertForPreTrainingpredictions.decoder.biascls.predictions.decoder.weightc                    ,   t  | t|| _t|| _|   d S r   )r_   r`   r&  r  r  clsr*  rs   ru   r%   r(   r`        

zBertForPreTraining.__init__c                 C   
   | j jjS r   r6  r  r  r  r%   r%   r(   get_output_embeddings&     
z(BertForPreTraining.get_output_embeddingsc                 C      || j j_|j| j j_d S r   r6  r  r  r-   rt   Znew_embeddingsr%   r%   r(   set_output_embeddings)     
z(BertForPreTraining.set_output_embeddingsNrw   r   r\   rY   r   rx   labelsnext_sentence_labelr   r   r   rz   c                 C   s   |dur|n| j j}| j|||||||	|
|d	}|dd \}}| ||\}}d}|durS|durSt }||d| j j|d}||dd|d}|| }|sj||f|dd  }|durh|f| S |S t||||j|j	dS )am  
        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]`
        next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
            pair (see `input_ids` docstring) Indices should be in `[0, 1]`:

            - 0 indicates sequence B is a continuation of sequence A,
            - 1 indicates sequence B is a random sequence.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, BertForPreTraining
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
        >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")

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

        >>> prediction_logits = outputs.prediction_logits
        >>> seq_relationship_logits = outputs.seq_relationship_logits
        ```
        Nr   r\   rY   r   rx   r   r   r   r/   rZ   )r"  r#  r$  r   r   )
rK   r1  r  r6  r
   r   rb   r!  r   r   )rt   rw   r   r\   rY   r   rx   rA  rB  r   r   r   r   r  r  r  r  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   r%   r%   r(   r   -  s<   +zBertForPreTraining.forwardNNNNNNNNNNN)r   r   r   _tied_weights_keysr`   r:  r?  r   r   rH   r   r   r   r   r!  r   r   r%   r%   ru   r(   r2    sT    		
r2  zP
    Bert Model with a `language modeling` head on top for CLM fine-tuning.
    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e	j
  dee dee dee dee deee	j
 ef fddZdd Z  ZS )BertLMHeadModelzcls.predictions.decoder.biasr4  c                    s@   t  | |jstd t|dd| _t|| _| 	  d S )NzLIf you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`Fr+  
r_   r`   r   r3   warningr&  r  r  r6  r*  rs   ru   r%   r(   r`     s   

zBertLMHeadModel.__init__c                 C   r8  r   r9  r  r%   r%   r(   r:    r;  z%BertLMHeadModel.get_output_embeddingsc                 C   r<  r   r=  r>  r%   r%   r(   r?    r@  z%BertLMHeadModel.set_output_embeddingsNrw   r   r\   rY   r   rx   r   r   rA  r   r   r   r   r   rz   c                 K   s   |dur|n| j j}|	durd}| j|||||||||
||||d}|d }| |}d}|	dur>| j||	| j jfi |}|sT|f|dd  }|durR|f| S |S t|||j|j|j	|j
dS )a  
        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 n `[0, ..., config.vocab_size]`
        NF)r   r\   rY   r   rx   r   r   r   r   r   r   r   r   r/   )r"  logitsr   r   r   r   )rK   r1  r  r6  Zloss_functionrb   r   r   r   r   r   )rt   rw   r   r\   rY   r   rx   r   r   rA  r   r   r   r   r   Zloss_kwargsr   r  r  Zlm_lossr   r%   r%   r(   r     sD   
zBertLMHeadModel.forwardc                    s.   d}|D ]}|t  fdd|D f7 }q|S )Nr%   c                 3   s$    | ]}| d  |jV  qdS )r   N)Zindex_selectr   r|   )r&   Z
past_statebeam_idxr%   r(   r)     s   " z1BertLMHeadModel._reorder_cache.<locals>.<genexpr>)r  )rt   r   rP  Zreordered_pastZ
layer_pastr%   rO  r(   _reorder_cache  s   zBertLMHeadModel._reorder_cache)NNNNNNNNNNNNNN)r   r   r   rI  r`   r:  r?  r   r   rH   r   r   r   r   r   r   r   rQ  r   r%   r%   ru   r(   rJ  }  sh    	
@rJ  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	j
 ef fddZdddZedefddZ  ZS )BertForMaskedLMr3  r4  c                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NzkIf you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.FrK  rL  rs   ru   r%   r(   r`     s   
zBertForMaskedLM.__init__c                 C   r8  r   r9  r  r%   r%   r(   r:    r;  z%BertForMaskedLM.get_output_embeddingsc                 C   r<  r   r=  r>  r%   r%   r(   r?    r@  z%BertForMaskedLM.set_output_embeddingsNrw   r   r\   rY   r   rx   r   r   rA  r   r   r   rz   c                 C   s   |dur|n| j j}| j|||||||||
||d}|d }| |}d}|	dur:t }||d| j j|	d}|sP|f|dd  }|durN|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\   rY   r   rx   r   r   r   r   r   r   rZ   r/   r"  rN  r   r   )
rK   r1  r  r6  r
   r   rb   r   r   r   )rt   rw   r   r\   rY   r   rx   r   r   rA  r   r   r   r   r  r  rF  rE  r   r%   r%   r(   r     s:   
zBertForMaskedLM.forwardc                 K   s~   |j }|d }| jjd u rtdtj|||j d dfgdd}tj|df| jjtj|j	d}tj||gdd}||dS )Nr   z.The PAD token should be defined for generationr"   rZ   r   r{   )rw   r   )
rE   rK   rd   rF   rH   r   Z	new_zerosfullrr   r|   )rt   rw   r   Zmodel_kwargsr~   Zeffective_batch_sizeZdummy_tokenr%   r%   r(   prepare_inputs_for_generation6  s   "
z-BertForMaskedLM.prepare_inputs_for_generationc                 C   s   dS )z
        Legacy correction: BertForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
        `prepare_inputs_for_generation` method.
        Fr%   )r6  r%   r%   r(   can_generateF  s   zBertForMaskedLM.can_generate)NNNNNNNNNNNNr   )r   r   r   rI  r`   r:  r?  r   r   rH   r   r   r   r   r   r   rU  classmethodrV  r   r%   r%   ru   r(   rR    s`    	

9rR  zT
    Bert Model with a `next sentence prediction (classification)` head on top.
    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j ef fddZ  ZS )BertForNextSentencePredictionc                    r5  r   )r_   r`   r&  r  r  r6  r*  rs   ru   r%   r(   r`   U  r7  z&BertForNextSentencePrediction.__init__Nrw   r   r\   rY   r   rx   rA  r   r   r   rz   c                 K   s   d|v rt dt |d}|
dur|
n| jj}
| j||||||||	|
d	}|d }| |}d}|durEt }||	dd|	d}|
s[|f|dd  }|durY|f| S |S t
|||j|jdS )	a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
            (see `input_ids` docstring). Indices should be in `[0, 1]`:

            - 0 indicates sequence B is a continuation of sequence A,
            - 1 indicates sequence B is a random sequence.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
        >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
        >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")

        >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
        >>> logits = outputs.logits
        >>> assert logits[0, 0] < logits[0, 1]  # next sentence was random
        ```
        rB  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.NrC  r"   rZ   r/   rS  )warningswarnFutureWarningpoprK   r1  r  r6  r
   r   r   r   r   )rt   rw   r   r\   rY   r   rx   rA  r   r   r   kwargsr   r  Zseq_relationship_scoresrG  rE  r   r%   r%   r(   r   ^  sB   *

z%BertForNextSentencePrediction.forward
NNNNNNNNNN)r   r   r   r`   r   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   rY  O  sH    		
rY  z
    Bert 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                       rX  )BertForSequenceClassificationc                    sd   t  | |j| _|| _t|| _|jd ur|jn|j}t	|| _
t|j|j| _|   d S r   )r_   r`   
num_labelsrK   r&  r  classifier_dropoutrl   r   rk   rm   r   rc   r.   r*  rt   rK   rb  ru   r%   r(   r`     s   
z&BertForSequenceClassification.__init__Nrw   r   r\   rY   r   rx   rA  r   r   r   rz   c                 C   sr  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dur| j jdu rV| jdkr<d| j _n| jdkrR|jtj	ksM|jtj
krRd| j _nd| j _| j jdkrtt }| jdkrn|| | }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).
        NrC  r"   Z
regressionZsingle_label_classificationZmulti_label_classificationrZ   r/   rS  )rK   r1  r  rm   r.   Zproblem_typera  r^   rH   rr   rC   r   squeezer
   r   r	   r   r   r   )rt   rw   r   r\   rY   r   rx   rA  r   r   r   r   r  rN  r"  rE  r   r%   r%   r(   r     sV   



"


z%BertForSequenceClassification.forwardr_  )r   r   r   r`   r   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   r`    sH    	
r`  c                       rX  )BertForMultipleChoicec                    sT   t  | t|| _|jd ur|jn|j}t|| _t	|j
d| _|   d S )Nr"   )r_   r`   r&  r  rb  rl   r   rk   rm   r   rc   r.   r*  rc  ru   r%   r(   r`     s   
zBertForMultipleChoice.__init__Nrw   r   r\   rY   r   rx   rA  r   r   r   rz   c                 C   sn  |
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 }|||}|
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)
        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.
        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)
        Nr"   rZ   r   rC  r/   rS  )rK   r1  rE   r   rq   r  rm   r.   r
   r   r   r   )rt   rw   r   r\   rY   r   rx   rA  r   r   r   Znum_choicesr   r  rN  Zreshaped_logitsr"  rE  r   r%   r%   r(   r   !  sL   ,


zBertForMultipleChoice.forwardr_  )r   r   r   r`   r   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   re    sH    	
re  c                       rX  )BertForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd ur|jn|j}t|| _	t
|j|j| _|   d S NFrK  )r_   r`   ra  r&  r  rb  rl   r   rk   rm   r   rc   r.   r*  rc  ru   r%   r(   r`     s   z#BertForTokenClassification.__init__Nrw   r   r\   rY   r   rx   rA  r   r   r   rz   c                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dur<t }||d| j|d}|
sR|f|dd  }|durP|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]`.
        NrC  r   rZ   r/   rS  )rK   r1  r  rm   r.   r
   r   ra  r   r   r   )rt   rw   r   r\   rY   r   rx   rA  r   r   r   r   r  rN  r"  rE  r   r%   r%   r(   r     s8   

z"BertForTokenClassification.forwardr_  )r   r   r   r`   r   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   rf  }  sH    	
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j ef fddZ  ZS )BertForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S rg  )
r_   r`   ra  r&  r  r   r   rc   
qa_outputsr*  rs   ru   r%   r(   r`     s
   z!BertForQuestionAnswering.__init__Nrw   r   r\   rY   r   rx   start_positionsend_positionsr   r   r   rz   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 )	NrC  r   r"   rZ   r   )Zignore_indexr/   )r"  start_logits
end_logitsr   r   )rK   r1  r  ri  r<   rd  r   rB   rq   clampr
   r   r   r   )rt   rw   r   r\   rY   r   rx   rj  rk  r   r   r   r   r  rN  rl  rm  rD  Zignored_indexrE  Z
start_lossZend_lossr   r%   r%   r(   r     sP   






z BertForQuestionAnswering.forwardrH  )r   r   r   r`   r   r   rH   r   r   r   r   r   r   r   r%   r%   ru   r(   rh    sN    
	
rh  )rR  re  rY  r2  rh  r`  rf  r   rJ  r&  r  rS   )Sr   r   r5   rZ  dataclassesr   typingr   r   r   r   rH   Ztorch.utils.checkpoint	packagingr   r   Ztorch.nnr	   r
   r   Zactivationsr   Z
generationr   Zmodeling_attn_mask_utilsr   r   Zmodeling_outputsr   r   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r    r!   Zconfiguration_bertr#   Z
get_loggerr   r3   rS   ModulerT   r   r   r   r   r   r   r   r   r   r  r  r	  r  r  r  r  r!  r&  r2  rJ  rR  rY  r`  re  rf  rh  __all__r%   r%   r%   r(   <module>   s   ,
I@ e3V]

! 5c`l_YjEM