U
    4A·fßb ã                   @   sŠ  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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-m.Z.m/Z/m0Z0 ddl1m2Z2 e/ 3e4¡Z5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBdd„ ZCG dd „ d ejDƒZEG d!d"„ d"ejDƒZFG d#d$„ d$eFƒZGG d%d&„ d&ejDƒZHeFeGd'œZIG d(d)„ d)ejDƒZJG d*d+„ d+ejDƒZKG d,d-„ d-ejDƒZLG d.d/„ d/ejDƒZMG d0d1„ d1ejDƒZNG d2d3„ d3ejDƒZOG d4d5„ d5ejDƒZPG d6d7„ d7ejDƒZQG d8d9„ d9ejDƒZRG d:d;„ d;ejDƒZSG d<d=„ d=ejDƒZTG d>d?„ d?e$ƒZUeG d@dA„ dAe*ƒƒZVdBZWdCZXe,dDeWƒG dEdF„ dFeUƒƒZYe,dGeWƒG dHdI„ dIeUƒƒZZe,dJeWƒG dKdL„ dLeUƒƒZ[e,dMeWƒG dNdO„ dOeUƒƒZ\e,dPeWƒG dQdR„ dReUƒƒZ]e,dSeWƒG dTdU„ dUeUƒƒZ^e,dVeWƒG dWdX„ dXeUƒƒZ_e,dYeWƒG dZd[„ d[eUƒƒZ`e,d\eWƒG d]d^„ d^eUƒƒZadS )_zPyTorch BERT model.é    N)Ú	dataclass)ÚListÚOptionalÚTupleÚUnion)Úversion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )ÚACT2FN)Ú#_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Úadd_code_sample_docstringsÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚget_torch_versionÚloggingÚreplace_return_docstringsé   )Ú
BertConfigzgoogle-bert/bert-base-uncasedr%   z0dbmdz/bert-large-cased-finetuned-conll03-englishzZ['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] g{®Gáz„?zdeepset/bert-base-cased-squad2z'a nice puppet'g¤p=
×£@é   é   z*textattack/bert-base-uncased-yelp-polarityz	'LABEL_1'c                 C   sÚ  zddl }ddl}ddl}W n  tk
r<   t d¡ ‚ Y nX tj |¡}t 	d|› ¡ |j
 |¡}g }g }	|D ]@\}
}t 	d|
› d|› ¡ |j
 ||
¡}| |
¡ |	 |¡ qrt||	ƒD ]\}
}|
 d¡}
tdd	„ |
D ƒƒrüt 	d
d |
¡› ¡ q¾| }|
D ]}| d|¡r&| d|¡}n|g}|d dksH|d dkrTt|dƒ}n¢|d dksp|d dkr|t|dƒ}nz|d dkr–t|dƒ}n`|d dkr°t|dƒ}nFzt||d ƒ}W n2 tk
rô   t 	d
d |
¡› ¡ Y qY nX t|ƒdkrt|d ƒ}|| }q|dd… dkr:t|dƒ}n|dkrN| |¡}z,|j|jkrxtd|j› d|j› dƒ‚W n< tk
r¶ } z| j|j|jf7  _‚ W 5 d}~X Y nX t 	d|
› ¡ t |¡|_q¾| S )z'Load tf checkpoints in a pytorch model.r   Nz™Loading 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 kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN© )Ú.0Únr)   r)   úJ/tmp/pip-unpacked-wheel-zw5xktn0/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+)ÚkernelÚgammaÚweightZoutput_biasÚbetaÚbiasZoutput_weightsZsquadÚ
classifieré   r$   iõÿÿÿZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )ÚreZnumpyZ
tensorflowÚImportErrorÚloggerÚerrorÚosÚpathÚabspathÚinfoZ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_pathr5   ÚnpÚtfZtf_pathZ	init_varsÚnamesZarraysÚnamerH   ÚarrayÚpointerZm_nameZscope_namesÚnumÚer)   r)   r,   Úload_tf_weights_in_bertU   sx    ÿ

þ


rW   c                       sT   e Zd ZdZ‡ fdd„Zd	eej eej eej eej e	ej
dœ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ÚdropoutrC   r[   Zregister_bufferrK   ÚarangeÚexpandÚzerosr]   ÚsizeÚlong©ÚselfrN   ©Ú	__class__r)   r,   rd   ¡   s"    
  ÿ  ÿzBertEmbeddings.__init__Nr   )Ú	input_idsr`   r]   Úinputs_embedsÚpast_key_values_lengthÚreturnc                 C   sø   |d k	r|  ¡ }n|  ¡ d d… }|d }|d krL| jd d …||| …f }|d kr t| dƒrŠ| jd d …d |…f }| |d |¡}	|	}ntj|tj| jjd}|d kr²|  	|¡}|  
|¡}
||
 }| jdkrà|  |¡}||7 }|  |¡}|  |¡}|S )Nr^   r$   r`   r   ©rb   Údevicer\   )ru   r]   Úhasattrr`   rs   rK   rt   rv   r€   ri   rl   r[   rk   rm   rq   )rx   r{   r`   r]   r|   r}   Úinput_shapeÚ
seq_lengthÚbuffered_token_type_idsÚ buffered_token_type_ids_expandedrl   Ú
embeddingsrk   r)   r)   r,   Úforward´   s,    







zBertEmbeddings.forward)NNNNr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rd   r   rK   Z
LongTensorÚFloatTensorrF   ÚTensorr‡   Ú__classcell__r)   r)   ry   r,   rX   ž   s        úùrX   c                
       s‚   e Zd Zd‡ fdd„	Zejejdœdd„Zdejeej eej eej eej ee	e	ej   ee
 e	ej dœ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sÐ| jd	krò|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 (ú)r[   r\   Úrelative_keyÚrelative_key_queryr4   r$   )rc   rd   rg   Únum_attention_headsr   rI   rF   Úattention_head_sizeÚall_head_sizer   ÚLinearÚqueryÚkeyÚvaluero   Úattention_probs_dropout_probrq   rC   r[   rj   re   Údistance_embeddingÚ
is_decoder©rx   rN   r[   ry   r)   r,   rd   ß   s*    
ÿ  ÿzBertSelfAttention.__init__)Úxr~   c                 C   s6   |  ¡ d d… | j| jf }| |¡}| dddd¡S )Nr^   r   r4   r$   r   )ru   r“   r”   ÚviewÚpermute)rx   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_attentionsr~   c                 C   sÒ  |   |¡}|d k	}	|	r4|d k	r4|d }
|d }|}n |	r^|  |  |¡¡}
|  |  |¡¡}|}nv|d k	r´|  |  |¡¡}
|  |  |¡¡}tj|d |
gdd}
tj|d |gdd}n |  |  |¡¡}
|  |  |¡¡}|  |¡}|d k	}| jrô|
|f}t ||
 dd¡¡}| j	dks | j	dkr|j
d |
j
d  }}|r^t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||¡}|| }n4| j	dkrt d||¡}t d|
|¡}|| | }|t | j¡ }|d k	r:|| }tjj|dd}|  |¡}|d k	rf|| }t ||¡}| dddd¡ ¡ }| ¡ d d… | jf }| |¡}|r¶||fn|f}| jrÎ||f }|S )Nr   r$   r4   ©Zdimr^   éþÿÿÿr‘   r’   r   ra   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r—   r¡   r˜   r™   rK   Úcatrœ   ÚmatmulrG   r[   rH   Ztensorrv   r€   rŸ   rr   r›   rj   Útorb   ZeinsumÚmathÚsqrtr”   r   Ú
functionalZsoftmaxrq   r    Ú
contiguousru   r•   )rx   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‡   þ   sp    


 ÿ





zBertSelfAttention.forward)N)NNNNNF)rˆ   r‰   rŠ   rd   rK   r   r¡   r   rŒ   r   Úboolr‡   rŽ   r)   r)   ry   r,   r   Þ   s$         ø÷r   c                
       sr   e Zd Zd‡ fdd„	Zd	ejeej eej eej eej eeeej   ee	 eej dœ‡ fdd„Z
‡  ZS )
ÚBertSdpaSelfAttentionNc                    s4   t ƒ j||d |j| _t tƒ ¡t d¡k | _d S )N©r[   z2.2.0)rc   rd   rš   Údropout_probr   Úparser!   Úrequire_contiguous_qkvr   ry   r)   r,   rd   e  s    zBertSdpaSelfAttention.__init__Fr¢   c              	      sÊ  | j dks|s|d k	r8t d¡ tƒ  |||||||¡S | ¡ \}}	}
|  |  |¡¡}|d k	}|rf|n|}|rr|n|}|r |r |d jd |jd kr |\}}nX|  |  	|¡¡}|  |  
|¡¡}|d k	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 k	r@| ¡ }| ¡ }| ¡ }| jrf|sf|d krf|	dkrfdnd	}tjjj||||| jrˆ| jnd
|d}| dd¡}| ||	| j¡}|f}| jrÆ||f }|S )Nr\   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   r4   r$   rª   ZcudaTFç        )Z	attn_maskZ	dropout_pÚ	is_causal)r[   r7   Úwarning_oncerc   r‡   ru   r¡   r—   rH   r˜   r™   rK   r¬   rœ   r¾   r€   Útyper²   r   r±   Zscaled_dot_product_attentionÚtrainingr¼   rG   Zreshaper•   )rx   r£   r¤   r¥   r¦   r§   r¨   r©   ZbszÚtgt_lenÚ_r¶   r³   Zcurrent_statesr´   rµ   rÀ   Zattn_outputr¸   ry   r)   r,   r‡   k  s^    
ÿù
 
 (ÿú	
zBertSdpaSelfAttention.forward)N)NNNNNF)rˆ   r‰   rŠ   rd   rK   r   r   rŒ   r   r¹   r‡   rŽ   r)   r)   ry   r,   rº   d  s"   	      ø÷rº   c                       s4   e Zd Z‡ fdd„Zejejejdœdd„Z‡  ZS )ÚBertSelfOutputc                    sB   t ƒ  ¡  t |j|j¡| _tj|j|jd| _t |j	¡| _
d S ©NrZ   )rc   rd   r   r–   rg   Údenserm   rn   ro   rp   rq   rw   ry   r)   r,   rd   Ê  s    
zBertSelfOutput.__init__©r£   Úinput_tensorr~   c                 C   s&   |   |¡}|  |¡}|  || ¡}|S ©N©rÈ   rq   rm   ©rx   r£   rÊ   r)   r)   r,   r‡   Ð  s    

zBertSelfOutput.forward©rˆ   r‰   rŠ   rd   rK   r   r‡   rŽ   r)   r)   ry   r,   rÆ   É  s   rÆ   )ÚeagerÚsdpac                
       sv   e Zd Zd
‡ fdd„	Zdd„ Zdejeej eej eej eej ee	e	ej   ee
 e	ej dœdd	„Z‡  ZS )ÚBertAttentionNc                    s4   t ƒ  ¡  t|j ||d| _t|ƒ| _tƒ | _d S )Nr»   )	rc   rd   ÚBERT_SELF_ATTENTION_CLASSESÚ_attn_implementationrx   rÆ   ÚoutputÚsetÚpruned_headsr   ry   r)   r,   rd   Þ  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ª   )rE   r   rx   r“   r”   rÖ   r   r—   r˜   r™   rÔ   rÈ   r•   Úunion)rx   ÚheadsÚindexr)   r)   r,   Úprune_headsæ  s       ÿzBertAttention.prune_headsFr¢   c              	   C   s<   |   |||||||¡}|  |d |¡}	|	f|dd …  }
|
S )Nr   r$   )rx   rÔ   )rx   r£   r¤   r¥   r¦   r§   r¨   r©   Zself_outputsÚattention_outputr¸   r)   r)   r,   r‡   ø  s    
ù	zBertAttention.forward)N)NNNNNF)rˆ   r‰   rŠ   rd   rÚ   rK   r   r   rŒ   r   r¹   r‡   rŽ   r)   r)   ry   r,   rÑ   Ý  s$         ø÷rÑ   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )ÚBertIntermediatec                    sB   t ƒ  ¡  t |j|j¡| _t|jt	ƒr6t
|j | _n|j| _d S rË   )rc   rd   r   r–   rg   Úintermediate_sizerÈ   Ú
isinstanceÚ
hidden_actÚstrr   Úintermediate_act_fnrw   ry   r)   r,   rd     s
    
zBertIntermediate.__init__©r£   r~   c                 C   s   |   |¡}|  |¡}|S rË   )rÈ   rá   ©rx   r£   r)   r)   r,   r‡     s    

zBertIntermediate.forwardrÎ   r)   r)   ry   r,   rÜ     s   rÜ   c                       s4   e Zd Z‡ fdd„Zejejejdœdd„Z‡  ZS )Ú
BertOutputc                    sB   t ƒ  ¡  t |j|j¡| _tj|j|jd| _t 	|j
¡| _d S rÇ   )rc   rd   r   r–   rÝ   rg   rÈ   rm   rn   ro   rp   rq   rw   ry   r)   r,   rd      s    
zBertOutput.__init__rÉ   c                 C   s&   |   |¡}|  |¡}|  || ¡}|S rË   rÌ   rÍ   r)   r)   r,   r‡   &  s    

zBertOutput.forwardrÎ   r)   r)   ry   r,   rä     s   rä   c                
       st   e Zd Z‡ fdd„Zd
ejeej eej eej eej eeeej   ee	 eej dœdd„Z
dd	„ Z‡  ZS )Ú	BertLayerc                    sr   t ƒ  ¡  |j| _d| _t|ƒ| _|j| _|j| _| jrZ| jsLt| › dƒ‚t|dd| _	t
|ƒ| _t|ƒ| _d S )Nr$   z> should be used as a decoder model if cross attention is addedr\   r»   )rc   rd   Úchunk_size_feed_forwardÚseq_len_dimrÑ   Ú	attentionrœ   Úadd_cross_attentionrI   ÚcrossattentionrÜ   Úintermediaterä   rÔ   rw   ry   r)   r,   rd   .  s    


zBertLayer.__init__NFr¢   c              	   C   s  |d k	r|d d… nd }| j |||||d}	|	d }
| jrP|	dd… }|	d }n|	dd … }d }| jrÞ|d k	rÞt| dƒsˆtd| › dƒ‚|d k	rœ|d	d … nd }|  |
||||||¡}|d }
||dd…  }|d }|| }t| j| j| j|
ƒ}|f| }| jr||f }|S )
Nr4   )r©   r¨   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è   rœ   r   rI   rê   r   Úfeed_forward_chunkræ   rç   )rx   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‡   <  sV    û


ÿù	   ÿ

zBertLayer.forwardc                 C   s   |   |¡}|  ||¡}|S rË   )rë   rÔ   )rx   rÛ   Zintermediate_outputrí   r)   r)   r,   rì   }  s    
zBertLayer.feed_forward_chunk)NNNNNF)rˆ   r‰   rŠ   rd   rK   r   r   rŒ   r   r¹   r‡   rì   rŽ   r)   r)   ry   r,   rå   -  s$         ø÷Arå   c                       s†   e Zd Z‡ fdd„Zd	ejeej eej eej eej eeeej   ee	 ee	 ee	 ee	 e
eej ef dœ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Å   ©rN   r)   r,   Ú
<listcomp>‡  s     z(BertEncoder.__init__.<locals>.<listcomp>F)	rc   rd   rN   r   Z
ModuleListÚrangeÚnum_hidden_layersÚlayerÚgradient_checkpointingrw   ry   rï   r,   rd   „  s    
 zBertEncoder.__init__NFT)r£   r¤   r¥   r¦   r§   Úpast_key_valuesr·   r©   Úoutput_hidden_statesÚreturn_dictr~   c                 C   sb  |	rdnd }|rdnd }|r(| j jr(dnd }| jrJ| jrJ|rJt d¡ d}|rRdnd }t| jƒD ]¼\}}|	rv||f }|d k	r†|| nd }|d k	rš|| nd }| jrÆ| jrÆ|  |j	|||||||¡}n||||||||ƒ}|d }|rô||d f7 }|r`||d f }| j jr`||d f }q`|	r.||f }|
sPt
dd	„ |||||fD ƒƒS t|||||d
S )Nr)   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r^   r$   r4   c                 s   s   | ]}|d k	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)rN   ré   rô   rÃ   r7   rÁ   Ú	enumerateró   Z_gradient_checkpointing_funcÚ__call__Útupler   )rx   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‡   Š  sx    ÿ
øù

ûþûzBertEncoder.forward)	NNNNNNFFT)rˆ   r‰   rŠ   rd   rK   r   r   rŒ   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   rî   ƒ  s.   	         õôrî   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )Ú
BertPoolerc                    s*   t ƒ  ¡  t |j|j¡| _t ¡ | _d S rË   )rc   rd   r   r–   rg   rÈ   ZTanhÚ
activationrw   ry   r)   r,   rd   á  s    
zBertPooler.__init__râ   c                 C   s(   |d d …df }|   |¡}|  |¡}|S )Nr   )rÈ   r  )rx   r£   Zfirst_token_tensorÚpooled_outputr)   r)   r,   r‡   æ  s    

zBertPooler.forwardrÎ   r)   r)   ry   r,   r   à  s   r   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )ÚBertPredictionHeadTransformc                    sV   t ƒ  ¡  t |j|j¡| _t|jtƒr6t	|j | _
n|j| _
tj|j|jd| _d S rÇ   )rc   rd   r   r–   rg   rÈ   rÞ   rß   rà   r   Útransform_act_fnrm   rn   rw   ry   r)   r,   rd   ð  s    
z$BertPredictionHeadTransform.__init__râ   c                 C   s"   |   |¡}|  |¡}|  |¡}|S rË   )rÈ   r  rm   rã   r)   r)   r,   r‡   ù  s    


z#BertPredictionHeadTransform.forwardrÎ   r)   r)   ry   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)r2   )rc   rd   r  Ú	transformr   r–   rg   rf   ÚdecoderÚ	ParameterrK   rt   r2   rw   ry   r)   r,   rd     s
    

zBertLMPredictionHead.__init__c                 C   s   | j | j_ d S rË   )r2   r  ©rx   r)   r)   r,   Ú_tie_weights  s    z!BertLMPredictionHead._tie_weightsc                 C   s   |   |¡}|  |¡}|S rË   )r  r  rã   r)   r)   r,   r‡     s    

zBertLMPredictionHead.forward)rˆ   r‰   rŠ   rd   r
  r‡   rŽ   r)   r)   ry   r,   r     s   r  c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )ÚBertOnlyMLMHeadc                    s   t ƒ  ¡  t|ƒ| _d S rË   )rc   rd   r  Úpredictionsrw   ry   r)   r,   rd     s    
zBertOnlyMLMHead.__init__)Úsequence_outputr~   c                 C   s   |   |¡}|S rË   )r  )rx   r  Úprediction_scoresr)   r)   r,   r‡     s    
zBertOnlyMLMHead.forwardrÎ   r)   r)   ry   r,   r    s   r  c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚBertOnlyNSPHeadc                    s   t ƒ  ¡  t |jd¡| _d S ©Nr4   )rc   rd   r   r–   rg   Úseq_relationshiprw   ry   r)   r,   rd   "  s    
zBertOnlyNSPHead.__init__c                 C   s   |   |¡}|S rË   )r  )rx   r  Úseq_relationship_scorer)   r)   r,   r‡   &  s    
zBertOnlyNSPHead.forward©rˆ   r‰   rŠ   rd   r‡   rŽ   r)   r)   ry   r,   r  !  s   r  c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚBertPreTrainingHeadsc                    s(   t ƒ  ¡  t|ƒ| _t |jd¡| _d S r  )rc   rd   r  r  r   r–   rg   r  rw   ry   r)   r,   rd   ,  s    

zBertPreTrainingHeads.__init__c                 C   s   |   |¡}|  |¡}||fS rË   )r  r  )rx   r  r  r  r  r)   r)   r,   r‡   1  s    

zBertPreTrainingHeads.forwardr  r)   r)   ry   r,   r  +  s   r  c                   @   s,   e Zd ZdZeZeZdZdZ	dZ
dd„ ZdS )ÚBertPreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ÚbertTc                 C   s¤   t |tjƒr:|jjjd| jjd |jdk	r |jj 	¡  nft |tj
ƒrz|jjjd| jjd |jdk	r |jj|j  	¡  n&t |tjƒr |jj 	¡  |jj d¡ dS )zInitialize the weightsr¿   )ZmeanZstdNg      ð?)rÞ   r   r–   r0   rL   Znormal_rN   Zinitializer_ranger2   Zzero_re   rY   rm   Zfill_)rx   Úmoduler)   r)   r,   Ú_init_weightsC  s    

z!BertPreTrainedModel._init_weightsN)rˆ   r‰   rŠ   r‹   r%   Úconfig_classrW   Zload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingZ_supports_sdpar  r)   r)   r)   r,   r  7  s   r  c                   @   sl   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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   rK   rŒ   Ú__annotations__r  r  r£   r   rú   r)   r)   r)   r,   r  T  s   
r  a>  

    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, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`BertConfig`]): 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.
a5
  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            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)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing 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)
        token_type_ids (`torch.LongTensor` of shape `({0})`, *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 `({0})`, *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)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `({0}, 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.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z^The bare Bert Model transformer outputting raw hidden-states without any specific head on top.c                       sà   e Zd ZdZddgZd‡ fdd„	Zdd„ Zd	d
„ Zdd„ Ze	e
 d¡ƒeeeeddeej eej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dœdd„ƒƒZ‡  ZS )Ú	BertModela  

    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.
    rX   rå   Tc                    sT   t ƒ  |¡ || _t|ƒ| _t|ƒ| _|r2t|ƒnd | _|j	| _
|j| _|  ¡  d S rË   )rc   rd   rN   rX   r†   rî   Úencoderr   ÚpoolerrÓ   Úattn_implementationr[   Ú	post_init)rx   rN   Úadd_pooling_layerry   r)   r,   rd   Ë  s    

zBertModel.__init__c                 C   s   | j jS rË   ©r†   ri   r	  r)   r)   r,   Úget_input_embeddingsÚ  s    zBertModel.get_input_embeddingsc                 C   s   || j _d S rË   r%  )rx   r™   r)   r)   r,   Úset_input_embeddingsÝ  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Ú   )rx   Zheads_to_pruneró   rØ   r)   r)   r,   Ú_prune_headsà  s    zBertModel._prune_headsúbatch_size, sequence_length©Ú
checkpointÚoutput_typer  N)r{   r¤   r`   r]   r¥   r|   r¦   r§   rõ   r·   r©   rö   r÷   r~   c                  C   sÐ  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}| j jrZ|
dk	rP|
n| j j}
nd}
|dk	rx|dk	rxtdƒ‚n@|dk	r–|  ||¡ | ¡ }n"|dk	r°| ¡ dd… }ntdƒ‚|\}}|dk	rÎ|j	n|j	}|	dk	rî|	d d j
d nd}|dkrFt| jdƒr4| jjdd…d|…f }| ||¡}|}ntj|tj|d	}| j|||||d
}|dkrztj||| f|d}| jdko | jdko |dko | }|rÔ| j jrÂt||||ƒ}nt||j|d}n|  ||¡}| j jrF|dk	rF| ¡ \}}}||f}|dkr"tj||d}|r:t||j|d}n
|  |¡}nd}|  || j j¡}| j||||||	|
|||d
}|d }| jdk	r–|  |¡nd}|s´||f|dd…  S t|||j|j |j!|j"dS )a  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer^   z5You have to specify either input_ids or inputs_embedsr   r4   r`   r   )r{   r]   r`   r|   r}   )r€   rÐ   r\   )rÄ   )	r¤   r¥   r¦   r§   rõ   r·   r©   rö   r÷   r$   )rù   Zpooler_outputrõ   r£   rú   rû   )#rN   r©   rö   Úuse_return_dictrœ   r·   rI   Z%warn_if_padding_and_no_attention_maskru   r€   rH   r   r†   r`   rs   rK   rt   rv   Zonesr"  r[   r   r   rb   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskrò   r   r!  r   rõ   r£   rú   rû   ) rx   r{   r¤   r`   r]   r¥   r|   r¦   r§   rõ   r·   r©   rö   r÷   r‚   Z
batch_sizerƒ   r€   r}   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Š   r‹   Z_no_split_modulesrd   r&  r'  r)  r    ÚBERT_INPUTS_DOCSTRINGÚformatr   Ú_CHECKPOINT_FOR_DOCr   Ú_CONFIG_FOR_DOCr   rK   r   r   rŒ   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   r  ¸  sR   ý             òñ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e 	d	¡ƒe
eed
deej eej eej eej eej eej eej eej ee ee ee eeej ef dœdd„ƒƒZ‡  ZS )ÚBertForPreTrainingúpredictions.decoder.biasúcls.predictions.decoder.weightc                    s,   t ƒ  |¡ t|ƒ| _t|ƒ| _|  ¡  d S rË   )rc   rd   r  r  r  Úclsr#  rw   ry   r)   r,   rd   ›  s    

zBertForPreTraining.__init__c                 C   s
   | j jjS rË   ©r6  r  r  r	  r)   r)   r,   Úget_output_embeddings¤  s    z(BertForPreTraining.get_output_embeddingsc                 C   s   || j j_|j| j j_d S rË   ©r6  r  r  r2   ©rx   Znew_embeddingsr)   r)   r,   Úset_output_embeddings§  s    
z(BertForPreTraining.set_output_embeddingsr*  ©r-  r  N)r{   r¤   r`   r]   r¥   r|   ÚlabelsÚnext_sentence_labelr©   rö   r÷   r~   c                 C   sê   |dk	r|n| j j}| j|||||||	|
|d	}|dd… \}}|  ||¡\}}d}|dk	r¦|dk	r¦tƒ }|| d| j j¡| d¡ƒ}|| dd¡| d¡ƒ}|| }|sÔ||f|dd…  }|dk	rÐ|f| S |S t||||j|j	dS )a1  
            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.
            kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
                Used to hide legacy arguments that have been deprecated.

        Returns:

        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`   r]   r¥   r|   r©   rö   r÷   r4   r^   )r  r  r  r£   rú   )
rN   r.  r  r6  r
   rŸ   rf   r  r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r=  r>  r©   rö   r÷   r¸   r  r  r  r  Ú
total_lossÚloss_fctÚmasked_lm_lossÚnext_sentence_lossrÔ   r)   r)   r,   r‡   «  s<    0÷ûzBertForPreTraining.forward)NNNNNNNNNNN)rˆ   r‰   rŠ   Ú_tied_weights_keysrd   r8  r;  r    r/  r0  r#   r  r2  r   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   r3  ‘  s>   	
           ôór3  zFBert 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e 	d	¡ƒe
eeed
deej eej eej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dœdd„ƒƒZddd„Zdd„ Z‡  ZS )ÚBertLMHeadModelzcls.predictions.decoder.biasr5  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$  ©
rc   rd   rœ   r7   Úwarningr  r  r  r6  r#  rw   ry   r)   r,   rd     s    

zBertLMHeadModel.__init__c                 C   s
   | j jjS rË   r7  r	  r)   r)   r,   r8    s    z%BertLMHeadModel.get_output_embeddingsc                 C   s   || j j_|j| j j_d S rË   r9  r:  r)   r)   r,   r;    s    
z%BertLMHeadModel.set_output_embeddingsr*  r+  N)r{   r¤   r`   r]   r¥   r|   r¦   r§   r=  rõ   r·   r©   rö   r÷   r~   c                 C   s  |dk	r|n| j j}|	dk	r d}| j|||||||||
||||d}|d }|  |¡}d}|	dk	rº|dd…dd…dd…f  ¡ }|	dd…dd…f  ¡ }	tƒ }|| d| j j¡|	 d¡ƒ}|sæ|f|dd…  }|dk	râ|f| S |S t|||j	|j
|j|jdS )	aÃ  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        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]`
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        NF)r¤   r`   r]   r¥   r|   r¦   r§   rõ   r·   r©   rö   r÷   r   r^   r$   r4   )r  Úlogitsrõ   r£   rú   rû   )rN   r.  r  r6  r²   r
   rŸ   rf   r   rõ   r£   rú   rû   )rx   r{   r¤   r`   r]   r¥   r|   r¦   r§   r=  rõ   r·   r©   rö   r÷   r¸   r  r  Zlm_lossZshifted_prediction_scoresrA  rÔ   r)   r)   r,   r‡     sJ    /ó
úzBertLMHeadModel.forwardTc           	      K   sv   |j }|d kr| |¡}|d k	rh|d d j d }|j d |krF|}n|j d d }|d d …|d …f }||||dœS )Nr   r4   r$   )r{   r¤   rõ   r·   )rH   Znew_ones)	rx   r{   rõ   r¤   r·   Úmodel_kwargsr‚   Zpast_lengthZremove_prefix_lengthr)   r)   r,   Úprepare_inputs_for_generationt  s    
üz-BertLMHeadModel.prepare_inputs_for_generationc                    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þ   )rx   rõ   rM  Zreordered_pastZ
layer_pastr)   rL  r,   Ú_reorder_cache  s    ÿzBertLMHeadModel._reorder_cache)NNNNNNNNNNNNNN)NNT)rˆ   r‰   rŠ   rD  rd   r8  r;  r    r/  r0  r   r1  r   r2  r   rK   r   r   r¹   r   r   r‡   rK  rN  rŽ   r)   r)   ry   r,   rE     s\   ý              ñðV     ÿ
rE  z2Bert Model with a `language modeling` head on top.c                       sÖ   e Zd ZddgZ‡ fdd„Zdd„ Zdd„ Zee 	d	¡ƒe
eeed
dddeej eej eej eej eej eej eej eej eej ee ee ee eeej ef dœdd„ƒƒZddd„Z‡  ZS )ÚBertForMaskedLMr4  r5  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.FrF  rG  rw   ry   r)   r,   rd     s    ÿ
zBertForMaskedLM.__init__c                 C   s
   | j jjS rË   r7  r	  r)   r)   r,   r8  ¬  s    z%BertForMaskedLM.get_output_embeddingsc                 C   s   || j j_|j| j j_d S rË   r9  r:  r)   r)   r,   r;  ¯  s    
z%BertForMaskedLM.set_output_embeddingsr*  z'paris'g)\Âõ(ì?©r,  r-  r  Úexpected_outputÚexpected_lossN)r{   r¤   r`   r]   r¥   r|   r¦   r§   r=  r©   rö   r÷   r~   c                 C   s´   |dk	r|n| j j}| j|||||||||
||d}|d }|  |¡}d}|	dk	rttƒ }|| d| j j¡|	 d¡ƒ}|s |f|dd…  }|dk	rœ|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¥   r|   r¦   r§   r©   rö   r÷   r   r^   r4   ©r  rI  r£   rú   )
rN   r.  r  r6  r
   rŸ   rf   r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r¦   r§   r=  r©   rö   r÷   r¸   r  r  rB  rA  rÔ   r)   r)   r,   r‡   ³  s:    õ
üzBertForMaskedLM.forwardc                 K   s~   |j }|d }| jjd k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$   r^   rª   r   )r{   r¤   )
rH   rN   rh   rI   rK   r¬   Z	new_zerosÚfullrv   r€   )rx   r{   r¤   rJ  r‚   Zeffective_batch_sizeZdummy_tokenr)   r)   r,   rK  ô  s    "   ÿz-BertForMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNNN)N)rˆ   r‰   rŠ   rD  rd   r8  r;  r    r/  r0  r   r1  r   r2  r   rK   r   r¹   r   r   r‡   rK  rŽ   r)   r)   ry   r,   rO  ™  sP   û	            óò9rO  zJBert Model with a `next sentence prediction (classification)` head on top.c                       sž   e Zd Z‡ fdd„Zee d¡ƒeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dœdd„ƒƒZ‡  ZS )
ÚBertForNextSentencePredictionc                    s,   t ƒ  |¡ t|ƒ| _t|ƒ| _|  ¡  d S rË   )rc   rd   r  r  r  r6  r#  rw   ry   r)   r,   rd   
  s    

z&BertForNextSentencePrediction.__init__r*  r<  N©r{   r¤   r`   r]   r¥   r|   r=  r©   rö   r÷   r~   c                 K   sÊ   d|krt  dt¡ | d¡}|
dk	r*|
n| jj}
| j||||||||	|
d	}|d }|  |¡}d}|dk	rŠtƒ }|| 	dd¡| 	d¡ƒ}|
s¶|f|dd…  }|dk	r²|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.

        Returns:

        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
        ```
        r>  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.Nr?  r$   r^   r4   rS  )ÚwarningsÚwarnÚFutureWarningÚpoprN   r.  r  r6  r
   rŸ   r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r=  r©   rö   r÷   Úkwargsr¸   r  Zseq_relationship_scoresrC  rA  rÔ   r)   r)   r,   r‡     sB    -ý
÷
üz%BertForNextSentencePrediction.forward)
NNNNNNNNNN)rˆ   r‰   rŠ   rd   r    r/  r0  r#   r   r2  r   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   rU    s4   	
          õórU  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                       s¤   e Zd Z‡ fdd„Zee d¡ƒeee	e
eedd	eej eej eej eej eej eej eej ee ee ee eeej e	f dœdd„ƒƒZ‡  ZS )
ÚBertForSequenceClassificationc                    sd   t ƒ  |¡ |j| _|| _t|ƒ| _|jd k	r4|jn|j}t 	|¡| _
t |j|j¡| _|  ¡  d S rË   )rc   rd   Ú
num_labelsrN   r  r  Úclassifier_dropoutrp   r   ro   rq   r–   rg   r3   r#  ©rx   rN   r^  ry   r)   r,   rd   s  s    
ÿz&BertForSequenceClassification.__init__r*  rP  NrV  c                 C   s|  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}|  |¡}d}|dk	r8| j jdkr®| jdkrzd| j _n4| jdkr¦|jtj	ksœ|jtj
kr¦d| j _nd| j _| j jdkrêtƒ }| jdkrÞ|| ¡ | ¡ ƒ}n
|||ƒ}nN| j jdkrtƒ }|| d| j¡| d¡ƒ}n| j jdkr8tƒ }|||ƒ}|
sh|f|dd…  }|dk	rd|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).
        Nr?  r$   Z
regressionZsingle_label_classificationZmulti_label_classificationr^   r4   rS  )rN   r.  r  rq   r3   Zproblem_typer]  rb   rK   rv   rF   r   Úsqueezer
   rŸ   r	   r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r=  r©   rö   r÷   r¸   r  rI  r  rA  rÔ   r)   r)   r,   r‡   ‚  sV    ÷




"


üz%BertForSequenceClassification.forward)
NNNNNNNNNN)rˆ   r‰   rŠ   rd   r    r/  r0  r   Ú'_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r2  Ú_SEQ_CLASS_EXPECTED_OUTPUTÚ_SEQ_CLASS_EXPECTED_LOSSr   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   r\  k  s@   û	          õôr\  z¥
    Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       s    e Zd Z‡ fdd„Zee d¡ƒeee	e
dd	eej eej eej eej eej eej eej ee ee ee eeej e	f dœdd„ƒƒZ‡  ZS )
ÚBertForMultipleChoicec                    sT   t ƒ  |¡ t|ƒ| _|jd k	r&|jn|j}t |¡| _t 	|j
d¡| _|  ¡  d S )Nr$   )rc   rd   r  r  r^  rp   r   ro   rq   r–   rg   r3   r#  r_  ry   r)   r,   rd   Ú  s    
ÿzBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr+  NrV  c                 C   st  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ| d| d¡¡nd}|dk	rh| d| d¡¡nd}|dk	r†| d| d¡¡nd}|dk	r¤| d| d¡¡nd}|dk	rÊ| d| d¡| d¡¡nd}| j||||||||	|
d	}|d }|  |¡}|  |¡}| d|¡}d}|dk	r0tƒ }|||ƒ}|
s`|f|dd…  }|dk	r\|f| S |S t	|||j
|jdS )aJ  
        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$   r^   r«   r?  r4   rS  )rN   r.  rH   rŸ   ru   r  rq   r3   r
   r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r=  r©   rö   r÷   Znum_choicesr¸   r  rI  Zreshaped_logitsr  rA  rÔ   r)   r)   r,   r‡   ç  sL    ÿý÷



üzBertForMultipleChoice.forward)
NNNNNNNNNN)rˆ   r‰   rŠ   rd   r    r/  r0  r   r1  r   r2  r   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   rd  Ò  s<   ý          õôrd  z£
    Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       s¤   e Zd Z‡ fdd„Zee d¡ƒeee	e
eedd	eej eej eej eej eej eej eej ee ee ee eeej e	f dœdd„ƒƒZ‡  ZS )
ÚBertForTokenClassificationc                    sb   t ƒ  |¡ |j| _t|dd| _|jd k	r2|jn|j}t |¡| _	t 
|j|j¡| _|  ¡  d S ©NFrF  )rc   rd   r]  r  r  r^  rp   r   ro   rq   r–   rg   r3   r#  r_  ry   r)   r,   rd   8  s    ÿz#BertForTokenClassification.__init__r*  rP  NrV  c                 C   s¸   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}|  |¡}d}|dk	rxtƒ }|| d| j¡| d¡ƒ}|
s¤|f|dd…  }|dk	r |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]`.
        Nr?  r   r^   r4   rS  )rN   r.  r  rq   r3   r
   rŸ   r]  r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   r=  r©   rö   r÷   r¸   r  rI  r  rA  rÔ   r)   r)   r,   r‡   F  s8    ÷

üz"BertForTokenClassification.forward)
NNNNNNNNNN)rˆ   r‰   rŠ   rd   r    r/  r0  r   Ú$_CHECKPOINT_FOR_TOKEN_CLASSIFICATIONr   r2  Ú_TOKEN_CLASS_EXPECTED_OUTPUTÚ_TOKEN_CLASS_EXPECTED_LOSSr   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   re  0  s@   û	          õôre  zÝ
    Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s°   e Zd Z‡ fdd„Zee d¡ƒeee	e
eeeedd	eej eej eej eej eej eej eej eej ee ee ee eeej e	f dœdd„ƒƒZ‡  ZS )
ÚBertForQuestionAnsweringc                    s@   t ƒ  |¡ |j| _t|dd| _t |j|j¡| _|  	¡  d S rf  )
rc   rd   r]  r  r  r   r–   rg   Ú
qa_outputsr#  rw   ry   r)   r,   rd   ‹  s
    z!BertForQuestionAnswering.__init__r*  )r,  r-  r  Zqa_target_start_indexZqa_target_end_indexrQ  rR  N)r{   r¤   r`   r]   r¥   r|   Ústart_positionsÚend_positionsr©   rö   r÷   r~   c                 C   sP  |dk	r|n| j j}| j|||||||	|
|d	}|d }|  |¡}|jddd\}}| d¡ ¡ }| d¡ ¡ }d}|dk	r|dk	rt| ¡ ƒdkr¢| d¡}t| ¡ ƒdkr¼| d¡}| d¡}| 	d|¡}| 	d|¡}t
|d}|||ƒ}|||ƒ}|| d }|s:||f|dd…  }|dk	r6|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        Nr?  r   r$   r^   rª   )Zignore_indexr4   )r  Ústart_logitsÚ
end_logitsr£   rú   )rN   r.  r  rk  r?   r`  r²   rE   ru   Úclampr
   r   r£   rú   )rx   r{   r¤   r`   r]   r¥   r|   rl  rm  r©   rö   r÷   r¸   r  rI  rn  ro  r@  Zignored_indexrA  Z
start_lossZend_lossrÔ   r)   r)   r,   r‡   •  sP    "÷






ûz BertForQuestionAnswering.forward)NNNNNNNNNNN)rˆ   r‰   rŠ   rd   r    r/  r0  r   Ú_CHECKPOINT_FOR_QAr   r2  Ú_QA_TARGET_START_INDEXÚ_QA_TARGET_END_INDEXÚ_QA_EXPECTED_OUTPUTÚ_QA_EXPECTED_LOSSr   rK   r   r¹   r   r   r‡   rŽ   r)   r)   ry   r,   rj  ƒ  sH   
ù           ôórj  )br‹   r¯   r9   rW  Zdataclassesr   Útypingr   r   r   r   rK   Ztorch.utils.checkpointÚ	packagingr   r   Ztorch.nnr	   r
   r   Zactivationsr   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    r!   r"   r#   Zconfiguration_bertr%   Z
get_loggerrˆ   r7   r1  r2  rg  rh  ri  rq  rt  ru  rr  rs  ra  rb  rc  rW   ÚModulerX   r   rº   rÆ   rÒ   rÑ   rÜ   rä   rå   rî   r   r  r  r  r  r  r  r  ZBERT_START_DOCSTRINGr/  r  r3  rE  rO  rU  r\  rd  re  rj  r)   r)   r)   r,   Ú<module>   sÊ   ,$	
ÿI@ eþ3V]

!2þ Vûh ÿ kþbû`ûWûLû