o
    ߥi6                    @   s  d dl 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 d dl	Z	d dl
m  mZ d dlZ	d dlZd dl	mZmZmZmZ d dlmZmZ d dlmZ d dlmZmZmZ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)m*Z*m+Z+m,Z, d d
l-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= ej0>  e0? Z@dZAdZBdd ZCG dd dejDZEG dd dejDZFG dd dejDZGG dd dejDZHG dd dejD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 d(d) d)ejDZNG d*d+ d+ejDZOG d,d- d-ejDZPG d.d/ d/ejDZQG d0d1 d1ejDZRG d2d3 d3ejDZSG d4d5 d5e)ZTeG d6d7 d7eZUG d8d9 d9eTZVG d:d; d;eTZWG d<d= d=eTZXG d>d? d?ejDZYG d@dA dAeTZZG dBdC dCeTZ[G dDdE dEeTZ\G dFdG dGeTZ]G dHdI dIeTZ^G dJdK dKeTZ_G dLdM dMeTZ`G dNdO dOe5e)Zae7jbe;jce2jddPG dQdR dReaZedS )S    N)	dataclass)OptionalTuple)Tensordevicedtypenn)CrossEntropyLossMSELoss)ACT2FN)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardreplace_return_docstrings)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModelapply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)
BertConfig)logging)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)parse_labels_in_orderr   BertTokenizerc                 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
|
| |j||
}||
 |	| q6t||	D ]\}
}|
d}
tdd |
D rxt	d	
d|
 qZ| }|
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s'J d|j d|j dW n tyA } z| j|j|jf7  _ d}~ww t	d
|
 t||_qZ| 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 {} with shape {}/c                 s   s    | ]}|d v V  qdS ))adam_vadam_mAdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepN ).0nr.   r.   _/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/multi_modal/mgeo/backbone.py	<genexpr>M   s    z*load_tf_weights_in_bert.<locals>.<genexpr>zSkipping {}z[A-Za-z]+_\d+z_(\d+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifier      i_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight {})renumpy
tensorflowImportErrorloggererrorospathabspathinfoformattrainlist_variablesload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorch
from_numpydata)modelconfigtf_checkpoint_pathr?   nptftf_path	init_varsnamesarraysnamerX   arraypointerm_namescope_namesnumer.   r.   r1   load_tf_weights_in_bert0   s   



rn   c                       s@   e Zd ZdZ fddZ											dddZ  ZS )	GisEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    sV  t    tj|j|jdd| _t|j|j| _tj|j	|jdd| _
tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _t|drtj|j|jdd| _tj|j|jdd| _tj|j|jdd| _tj|j|jd| _t|j| _ | !dt"#|j$d t%|dd| _&|| _'d S )	Nr   padding_idxprov_vocab_sizeepsposition_idsr=   position_embedding_typeabsolute)(super__init__r   	Embedding
vocab_sizehidden_sizeword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddingsrel_type_vocab_sizerel_type_embeddingsabsolute_x_vocab_sizeabsolute_x_embeddingsabsolute_y_vocab_sizeabsolute_y_embeddingsrelative_x_vocab_sizerelative_x_embeddingsrelative_y_vocab_sizerelative_y_embeddingshasattrrr   prov_embeddingscity_vocab_sizecity_embeddingsdist_vocab_sizedist_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferr[   arangeexpandrS   rx   r_   selfr_   	__class__r.   r1   r{   }   s`   












zGisEmbeddings.__init__Nr   c                 C   s  |d ur	|  }n|  d d }|d }|d u r&| jd d ||| f }|d u r5tj|tj| jjd}|d u r>| |}| |}|| }| jdkrU| 	|}||7 }|| 
|7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|| |d d d d df 7 }|	d ur|| |	7 }|| |
7 }|| |7 }| |}| |}|S )Nrw   r=   r   r   ry   r   r<      )sizeru   r[   zeroslongr   r   r   rx   r   r   r   r   r   r   r   r   r   r   r   )r   	input_idstoken_type_idsru   inputs_embedspast_key_values_lengthrel_type_idsabsolute_position_idsrelative_position_idsprov_idscity_idsdist_idsinput_shape
seq_lengthr   
embeddingsr   r.   r.   r1   forward   sj   















zGisEmbeddings.forward)NNNNr   NNNNNN__name__
__module____qualname____doc__r{   r   __classcell__r.   r.   r   r1   ro   z   s    +ro   c                       s:   e Zd ZdZ fddZ								dddZ  ZS )	BertEmbeddingszKConstruct 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| _| dt|jd t|dd| _|| _d S )Nrp   rs   ru   rv   rx   ry   )rz   r{   r   r|   r}   r~   pad_token_idr   r   r   r   r   r   r   r   r   r   r   r[   r   r   rS   rx   r_   r   r   r.   r1   r{      s2   

zBertEmbeddings.__init__Nr   c	                 C   s   |d ur	|  }	n|  d d }	|	d }
|d u r&| jd d ||
| f }|d u r5tj|	tj| jjd}|d u r>| |}| |}|| }| jdkrU| 	|}||7 }| 
|}| |}|S )Nrw   r=   r   ry   )r   ru   r[   r   r   r   r   r   rx   r   r   r   )r   r   r   ru   r   r   r   r   r   r   r   r   r   r   r.   r.   r1   r     s0   	







zBertEmbeddings.forward)NNNNr   NNNr   r.   r.   r   r1   r      s    r   c                       sZ   e Zd Z fddZdd Zdd Zdd Zd	d
 Zdd Z						dddZ	  Z
S )BertSelfAttentionc                    s"  t    || _|j|j dkrt|dstd|j|jf |j| _t|j|j | _| j| j | _	t
|j| j	| _|rQt
|j| j	| _t
|j| j	| _nt
|j| j	| _t
|j| j	| _t
|j| _t|dd| _| jdks{| jdkr|j| _t
d|j d	 | j| _d
| _d S )Nr   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)rx   ry   relative_keyrelative_key_queryr<   r=   F)rz   r{   r_   r~   num_attention_headsr   
ValueErrorrV   attention_head_sizeall_head_sizer   Linearqueryencoder_widthkeyvaluer   attention_probs_dropout_probr   rS   rx   r   r|   distance_embeddingsave_attentionr   r_   is_cross_attentionr   r.   r1   r{   /  sB   


zBertSelfAttention.__init__c                 C   
   || _ d S Nattn_gradients)r   r   r.   r.   r1   save_attn_gradientsQ     
z%BertSelfAttention.save_attn_gradientsc                 C      | j S r   r   r   r.   r.   r1   get_attn_gradientsT     z$BertSelfAttention.get_attn_gradientsc                 C   r   r   attention_map)r   r   r.   r.   r1   save_attention_mapW  r   z$BertSelfAttention.save_attention_mapc                 C   r   r   r   r   r.   r.   r1   get_attention_mapZ  r   z#BertSelfAttention.get_attention_mapc                 C   s6   |  d d | j| jf }|j| }|ddddS )Nrw   r   r<   r=   r   )r   r   r   viewpermute)r   xnew_x_shaper.   r.   r1   transpose_for_scores]  s
   
z&BertSelfAttention.transpose_for_scoresNFc                 C   s~  |  |}|d u}	|	r| | |}
| | |}|}n;|d urI| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}|
|f}t||
dd}| jdksv| jdkr|	 d }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rtd||}td|
|}|| | }|t| j }|d ur|| }tjdd|}|	r| jr| | || j | |}|d ur|| }t||}|dddd }|	 d d | jf }|j| }|r5||fn|f}||f }|S )Nr   r<   dimr=   rw   r   r   r   r   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r   r   r   r   r[   catmatmulrW   rx   r   r   r   r   r   r   r   tor   einsummathsqrtr   r   Softmaxr   r   register_hookr   r   r   
contiguousr   )r   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsmixed_query_layerr   	key_layervalue_layerquery_layerattention_scoresr   position_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probsattention_probs_droppedcontext_layernew_context_layer_shapeoutputsr.   r.   r1   r   c  s   












zBertSelfAttention.forwardNNNNNF)r   r   r   r{   r   r   r   r   r   r   r   r.   r.   r   r1   r   -  s    "	r   c                       $   e Zd Z fddZdd Z  ZS )BertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nrs   )rz   r{   r   r   r~   denser   r   r   r   r   r   r   r.   r1   r{        
zBertSelfOutput.__init__c                 C   &   |  |}| |}| || }|S r   r	  r   r   r   r   input_tensorr.   r.   r1   r        

zBertSelfOutput.forwardr   r   r   r{   r   r   r.   r.   r   r1   r        r  c                       s<   e Zd Zd	 fdd	Zdd Z						d
ddZ  ZS )BertAttentionFc                    s,   t    t||| _t|| _t | _d S r   )rz   r{   r   r   r  outputsetpruned_headsr   r   r.   r1   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   )rU   r   r   r   r   r  r   r   r   r   r  r	  r   union)r   headsindexr.   r.   r1   prune_heads  s   

zBertAttention.prune_headsNc              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r=   )r   r  )r   r   r   r   r   r   r   r   self_outputsattention_outputr  r.   r.   r1   r     s   
	
zBertAttention.forwardFr  )r   r   r   r{   r  r   r   r.   r.   r   r1   r    s    r  c                       r  )BertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )rz   r{   r   r   r~   intermediate_sizer	  
isinstance
hidden_actstrr   intermediate_act_fnr   r   r.   r1   r{     s
   
zBertIntermediate.__init__c                 C      |  |}| |}|S r   )r	  r"  r   r   r.   r.   r1   r        

zBertIntermediate.forwardr  r.   r.   r   r1   r    s    r  c                       r  )
BertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r  )rz   r{   r   r   r  r~   r	  r   r   r   r   r   r   r   r.   r1   r{     r
  zBertOutput.__init__c                 C   r  r   r  r  r.   r.   r1   r   $  r  zBertOutput.forwardr  r.   r.   r   r1   r&    r  r&  c                       s:   e Zd Z fddZ						d	ddZdd Z  ZS )
	BertLayerc                    sf   t    || _|j| _d| _t|| _||jk| _| jr'|| _	t|dd| _
t|| _t|| _d S )Nr=   T)r   )rz   r{   r_   chunk_size_feed_forwardseq_len_dimr  	attentionfusion_layerhas_cross_attention	layer_numcrossattentionr  intermediater&  r  )r   r_   r-  r   r.   r1   r{   -  s   


zBertLayer.__init__NFc              	   C   s   |d ur
|d d nd }| j |||||d}	|	d }
|	dd }|	d }| jrz|d us/J dt|tkrc| j|
|||| j| jj t|  || j| jj t|  |d}|d }
||dd  }n| j|
|||||d}|d }
||dd  }t	| j
| j| j|
}|f| }||f }|S )Nr<   r   r   r   r=   rw   z>encoder_hidden_states must be given for cross-attention layers)r   )r*  r,  typelistr.  r-  r_   r+  rU   r   feed_forward_chunkr(  r)  )r   r   r   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr  r  present_key_valuecross_attention_outputslayer_outputr.   r.   r1   r   <  sv   

zBertLayer.forwardc                 C   s   |  |}| ||}|S r   )r/  r  )r   r  intermediate_outputr8  r.   r.   r1   r3    s   
zBertLayer.feed_forward_chunkr  )r   r   r   r{   r   r3  r   r.   r.   r   r1   r'  +  s    
Dr'  c                       s:   e Zd Z fddZ										d	ddZ  ZS )
BertEncoderc                    s4   t     | _t fddt jD | _d S )Nc                    s   g | ]}t  |qS r.   )r'  )r/   ir_   r.   r1   
<listcomp>      z(BertEncoder.__init__.<locals>.<listcomp>)rz   r{   r_   r   
ModuleListrangenum_hidden_layerslayerr   r   r<  r1   r{     s
   

zBertEncoder.__init__NFTmulti_modalc              	      s  |	rdnd } r
dnd } r| j jrdnd }|rdnd }|dkr'd}| j j}n"|dkr2d}| j j}n|dkr?| j j}| j j}n
|dkrId}| j j}t||D ]k}| j| }|	r\||f }|d urd|| nd }|d urn|| nd t| j ddr| jr|rt	d	 d} fd
d}t
jj|||||||}n
|||||| }|d }|r||d f7 } r||d f }qN|	r||f }|
stdd |||||fD S t|||||dS )Nr.   textr   r   fusionrC  gradient_checkpointingFzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...c                    s    fdd}|S )Nc                     s    g | R  S r   r.   )inputs)moduler   r   r.   r1   custom_forward  s   zJBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr.   )rH  rI  r0  )rH  r1   create_custom_forward  s   z2BertEncoder.forward.<locals>.create_custom_forwardrw   r=   c                 s   s    | ]	}|d ur|V  qd S r   r.   )r/   vr.   r.   r1   r2     s    z&BertEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesr   
attentionscross_attentions)r_   add_cross_attentionr+  rA  r@  rB  rS   trainingrC   warnr[   utils
checkpointtupler   )r   r   r   r   r   r   rM  	use_cacher   output_hidden_statesreturn_dictmodeall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cachestart_layeroutput_layerr;  layer_modulelayer_head_maskrJ  layer_outputsr.   r0  r1   r     s   




	


zBertEncoder.forward)
NNNNNNFFTrC  r  r.   r.   r   r1   r:    s    	r:  c                       r  )
BertPoolerc                    s*   t    t|j|j| _t | _d S r   )rz   r{   r   r   r~   r	  Tanh
activationr   r   r.   r1   r{     s   
zBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S Nr   )r	  re  )r   r   first_token_tensorpooled_outputr.   r.   r1   r     s   

zBertPooler.forwardr  r.   r.   r   r1   rc        rc  c                       r  )BertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r  )rz   r{   r   r   r~   r	  r  r   r!  r   transform_act_fnr   r   r   r   r.   r1   r{     s   
z$BertPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S r   )r	  rk  r   r$  r.   r.   r1   r     s   


z#BertPredictionHeadTransform.forwardr  r.   r.   r   r1   rj    s    
rj  c                       r  )BertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S NF)r8   )rz   r{   rj  	transformr   r   r~   r}   decoder	Parameterr[   r   r8   r   r   r.   r1   r{      s   


zBertLMPredictionHead.__init__c                 C   r#  r   rn  ro  r$  r.   r.   r1   r   .  r%  zBertLMPredictionHead.forwardr  r.   r.   r   r1   rl    s    rl  c                       r  )BertOnlyMLMHeadc                    s   t    t|| _d S r   )rz   r{   rl  predictionsr   r   r.   r1   r{   6  s   
zBertOnlyMLMHead.__init__c                 C      |  |}|S r   )rs  )r   sequence_outputprediction_scoresr.   r.   r1   r   :     
zBertOnlyMLMHead.forwardr  r.   r.   r   r1   rr  4      rr  c                       r  )BertOnlyNSPHeadc                    s   t    t|jd| _d S Nr<   )rz   r{   r   r   r~   seq_relationshipr   r   r.   r1   r{   A  s   
zBertOnlyNSPHead.__init__c                 C   rt  r   )r{  )r   rh  seq_relationship_scorer.   r.   r1   r   E  rw  zBertOnlyNSPHead.forwardr  r.   r.   r   r1   ry  ?  rx  ry  c                       r  )BertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S rz  )rz   r{   rl  rs  r   r   r~   r{  r   r   r.   r1   r{   L  s   

zBertPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r   )rs  r{  )r   ru  rh  rv  r|  r.   r.   r1   r   Q  s   

zBertPreTrainingHeads.forwardr  r.   r.   r   r1   r}  J  ri  r}  c                   @   s*   e Zd ZdZeZeZdZdgZ	dd Z
dS )BertPreTrainedModel
    An abstract class to handle weights initialization and a simple interface
    for downloading and loading pretrained models.
    bertru   c                 C   s~   t |tjtjfr|jjjd| jjd nt |tj	r(|j
j  |jjd t |tjr;|j
dur=|j
j  dS dS dS )z Initialize the weights         meanstd      ?N)r  r   r   r|   r5   r]   normal_r_   initializer_ranger   r8   zero_fill_r   rH  r.   r.   r1   _init_weightsb  s   z!BertPreTrainedModel._init_weightsN)r   r   r   r   r   config_classrn   load_tf_weightsbase_model_prefix_keys_to_ignore_on_load_missingr  r.   r.   r.   r1   r~  W  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 :class:`~transformers.BertForPreTraining`. Args:
        loss (`optional`, returned when ``labels`` is provided,
        ``torch.FloatTensor`` of shape :obj:`(1,)`):
            Total loss as the sum of the masked language modeling loss and the
            next sequence prediction (classification) loss.
        prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size,
        sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each
            vocabulary token before SoftMax).
        seq_relationship_logits (:obj:`torch.FloatTensor` of shape
        :obj:`(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification)
            head (scores of True/False continuation before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned
        when ``output_hidden_states=True`` is passed or when
        ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the
            embeddings + one for the output of each layer) of shape
            :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of
            the model at the output of each layer plus the initial embedding
            outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when
        ``output_attentions=True`` is passed or when
        ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(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   rN  )r   r   r   r   r  r   r[   FloatTensor__annotations__r  r  r   r   rN  r.   r.   r.   r1   r  p  s   
 r  c                
       s   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zdede	e
 dededef
ddZ																						dddZ  ZS )	BertModelaS  
    Noted that the bert model here is slightly updated from original bert, so we
    maintian the code here independently. The Bert Model transformer outputting
    raw hidden-states without any specific head on top.

    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.

    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.


    Tc                    sZ   t  | || _|jdkrt|| _nt|| _t|| _|r$t	|nd | _
|   d S rf  )rz   r{   r_   gis_embeddingr   r   ro   r:  encoderrc  poolerinit_weights)r   r_   add_pooling_layerr   r.   r1   r{     s   


zBertModel.__init__c                 C   s   | j jS r   r   r   r   r.   r.   r1   get_input_embeddings     zBertModel.get_input_embeddingsc                 C   s   || j _d S r   r  )r   r   r.   r.   r1   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  rB  r*  r  )r   heads_to_prunerB  r  r.   r.   r1   _prune_heads  s   zBertModel._prune_headsr   r   r   
is_decoderreturnc                 C   sX  |  dkr|dddddddf }n|  dkr|r|\}}tj||d}|ddddf ||d|ddddf k}	|	|j}	|	jd |jd k rl|jd |	jd  }
tjtj|||
f||	jd|	gdd}	|	dddddddf |ddddddf  }n|ddddddf }n	t	d	
||j|j| jd
}d| d }|S )a{  
        Makes broadcastable attention and causal masks so that future and masked
        tokens are ignored.

        Arguments:
            attention_mask (:obj:`torch.Tensor`):
                Mask with ones indicating tokens to attend to, zeros for tokens
                to ignore.
            input_shape (:obj:`Tuple[int]`):
                The shape of the input to the model.
            device: (:obj:`torch.device`):
                The device of the input to the model.

        Returns:
            :obj:`torch.Tensor` The extended attention mask, with a the same
            dtype as :obj:`attention_mask.dtype`.
        r   Nr<   r   r=   )r   r   rw   )axiszAWrong shape for input_ids (shape {}) or attention_mask (shape {})r   r  g     )r   r[   r   repeatr   r   rX   r   onesr   rI   )r   r   r   r   r  extended_attention_mask
batch_sizer   seq_idscausal_maskprefix_seq_lenr.   r.   r1   get_extended_attention_mask  s\   
	z%BertModel.get_extended_attention_maskNFrC  c           &         s  |dur|n j j}|dur|n j j}|dur|n j j}|r+|dur&|n j j}nd}|dur9|dur9td|durI| }|\}}|j}n,|dur]| dd }|\}}|j}n|durq| dd }|\}}|j}ntd|
dur|
d d jd nd}|du rt	j
||| f|d}|du rt	j|t	j|d	} ||||}|durt|tkr|d  \}}}n| \}}}||f} t|	tkrׇ fd
d|	D }!n|	du rt	j
| |d}	 |	}!n |	}!nd}! | j j}|du r j|||||||||||d}"n|}" j|"||||!|
|||||d}#|#d }$ jdur/ |$nd}%|s>|$|%f|#dd  S t|$|%|#j|#j|#j|#jdS )a  
        Args:
        input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `((batch_size, sequence_length)`, *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 `((batch_size, 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, 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)
        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 `((batch_size, 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.
        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 [`~file_utils.ModelOutput`] instead of a
            plain tuple.
        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`).
        Others (**kwargs)
            some additional parameters might passed in from upstream pipeline,
            which not influence the results.
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timerw   zGYou have to specify either input_ids or inputs_embeds or encoder_embedsr   r<   r  r   c                       g | ]}  |qS r.   )invert_attention_mask)r/   maskr   r.   r1   r=    s    z%BertModel.forward.<locals>.<listcomp>)r   ru   r   r   r   r   r   r   r   r   r   )
r   r   r   r   rM  rV  r   rW  rX  rY  r=   rL  pooler_outputrM  r   rN  rO  )r_   r   rW  use_return_dictrV  r   r   r   rX   r[   r  r   r   r  r1  r2  r  get_head_maskrA  r   r  r  r   rM  r   rN  rO  )&r   r   r   r   ru   r   r   encoder_embedsr   r   rM  rV  r   rW  rX  r  rY  r   r   r   r   r   r   r   r  r   r   r   r  encoder_batch_sizeencoder_sequence_length_encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputsru  rh  r.   r   r1   r   )  s   o



zBertModel.forward)T)NNNNNNNNNNNNNNFrC  NNNNNN)r   r   r   r   r{   r  r  r  r   r   rV   r   boolr  r   r   r.   r.   r   r1   r    sL    '
Nr  c                       sL   e Zd Z fddZdd Zdd Z											d
dd	Z  ZS )BertForPreTrainingc                    ,   t  | t|| _t|| _|   d S r   )rz   r{   r  r  r}  clsr  r   r   r.   r1   r{         

zBertForPreTraining.__init__c                 C   
   | j jjS r   r  rs  ro  r   r.   r.   r1   get_output_embeddings(  r   z(BertForPreTraining.get_output_embeddingsc                 C      || j j_d S r   r  r   new_embeddingsr.   r.   r1   set_output_embeddings+     z(BertForPreTraining.set_output_embeddingsNc                 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 )a  
        labels (:obj:`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 :obj:`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 (:obj:`Dict[str, any]`, optional, defaults to `{}`):
            Used to hide legacy arguments that have been deprecated.
        Returns:
        Example:
            >>> from transformers import BertTokenizer, BertForPreTraining
            >>> import torch
            >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
            >>> model = BertForPreTraining.from_pretrained('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   ru   r   r   r   rW  rX  r<   rw   )r  r  r  r   rN  )
r_   r  r  r  r	   r   r}   r  r   rN  )r   r   r   r   ru   r   r   labelsnext_sentence_labelr   rW  rX  r  ru  rh  rv  r|  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr  r.   r.   r1   r   .  sV   %
zBertForPreTraining.forwardNNNNNNNNNNN)r   r   r   r{   r  r  r   r   r.   r.   r   r1   r    s     r  c                       s   e Zd ZdgZddgZ fddZdd Zdd	 Z	
	
	
	
	
	
	
	
	
	
	
	
	
	
				
		dddZ	
	
dddZ	dd Z
  ZS )BertLMHeadModelr  ru   predictions.decoder.biasc                    0   t  | t|dd| _t|| _|   d S NFr  rz   r{   r  r  rr  r  r  r   r   r.   r1   r{        
zBertLMHeadModel.__init__c                 C   r  r   r  r   r.   r.   r1   r    r   z%BertLMHeadModel.get_output_embeddingsc                 C   r  r   r  r  r.   r.   r1   r    r  z%BertLMHeadModel.set_output_embeddingsNTr  rC  r   Fc                 C   s  |dur|n| j j}|	durd}| j|||||||||
||||||d}|d }| |}|r>|ddddddf  S d}|	dur~|ddddddf  }|	ddddf  }	t|d}||d| j j|	d}||dd	d}|durt
j	tj|dd| dd }||	d	k 	d}d| | ||  }|s|f|d
d  }|dur|f| S |S t|||j|j|j|jdS )a
  
        encoder_hidden_states  (:obj:`torch.FloatTensor` of shape
        :obj:`(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 (:obj:`torch.FloatTensor` of shape
        :obj:`(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 (:obj:`torch.LongTensor` of shape :obj:`(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 (:obj:`tuple(tuple(torch.FloatTensor))` of length
        :obj:`config.n_layers` with each tuple having 4 tensors of shape
        :obj:`(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 :obj:`past_key_values`
            are used, the user can optionally input only the last
            :obj:`decoder_input_ids` (those that don't have their past key value
            states given to this model) of shape :obj:`(batch_size, 1)` instead
            of all :obj:`decoder_input_ids` of shape :obj:`(batch_size,
            sequence_length)`.
        use_cache (:obj:`bool`, `optional`):
            If set to :obj:`True`, :obj:`past_key_values` key value states are
            returned and can be used to speed up decoding (see
            :obj:`past_key_values`).

        Returns:

        Example:
            >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
            >>> import torch
            >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
            >>> config = BertConfig.from_pretrained("bert-base-cased")
            >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
            >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
            >>> outputs = model(**inputs)
            >>> prediction_logits = outputs.logits
        NF)r   r   ru   r   r   r   r   rM  rV  r   rW  rX  r  rY  r   rw   r=   )	reductionr   r<   )r  logitsrM  r   rN  rO  )r_   r  r  r  r   r	   r   r}   r   sumr[   Flog_softmaxr   rM  r   rN  rO  )r   r   r   r   ru   r   r   r   r   r  rM  rV  r   rW  rX  r  r  rY  soft_labelsalphareturn_logitsr  ru  rv  lm_lossshifted_prediction_scoresr  loss_distillr  r.   r.   r1   r     st   H


zBertLMHeadModel.forwardc                 K   sV   |j }|d u r||}|d ur|d d dd f }||||dd |dd ddS )Nrw   r   r   T)r   r   rM  r   r   r  )rX   new_onesget)r   r   pastr   model_kwargsr   r.   r.   r1   prepare_inputs_for_generation  s   


z-BertLMHeadModel.prepare_inputs_for_generationc                    s.   d}|D ]}|t  fdd|D f7 }q|S )Nr.   c                 3   s    | ]	}| d  V  qdS )r   N)index_select)r/   
past_statebeam_idxr.   r1   r2   7  s
    

z1BertLMHeadModel._reorder_cache.<locals>.<genexpr>)rU  )r   r  r  reordered_past
layer_pastr.   r  r1   _reorder_cache4  s   zBertLMHeadModel._reorder_cache)NNNNNNNNNNNNNNTr  rC  Nr   F)NN)r   r   r   "_keys_to_ignore_on_load_unexpectedr  r{   r  r  r   r  r  r   r.   r.   r   r1   r  ~  sB    
 
r  c                       r  )GisBertLMPredictionHeadc                    sH   t    t|| _tj|j|dd| _tt	
|| _| j| j_d S rm  )rz   r{   rj  rn  r   r   r~   ro  rp  r[   r   r8   )r   r_   r}   r   r.   r1   r{   ?  s
   

z GisBertLMPredictionHead.__init__c                 C   r#  r   rq  r$  r.   r.   r1   r   L  r%  zGisBertLMPredictionHead.forwardr  r.   r.   r   r1   r  =  s    r  c                       sr   e Zd ZdgZddgZ fddZ																										dd
dZ	dddZ  ZS )BertForGisMaskedLMr  ru   r  c                    s   t  | t|dd| _t||j| _t||j| _t||j	| _
t||j| _t||j| _t||j| _t||j| _t||j| _t||j| _t||j| _t||j| _|| _|   d S r  )rz   r{   r  r  r  r}   cls_geom_idr   cls_geom_typer   cls_rel_typer   cls_absolute_position_x1cls_absolute_position_x2r   cls_absolute_position_y1cls_absolute_position_y2r   cls_relative_position_x1cls_relative_position_x2r   cls_relative_position_y1cls_relative_position_y2r_   r  r   r   r.   r1   r{   Y  sF   zBertForGisMaskedLM.__init__NFrC  r   c           '      C   sT  |dur|n| j j}| j|fi d|d|d|d|d|d|d|d	|	d
|d|d|d|d|d|d|d|}|d }| |}t }||d| j j|
d}| j| j| j	| j
| j| j| j| j| j| jg
}|||dddddf |dddddf |dddddf |dddddf |dddddf |dddddf |dddddf |dddddf g
} | j j| j j| j j| j j| j j| j j| j j| j j| j j| j jg
}!t|| |!D ]\}"}#}$|#dur|"|}%|||%d|$|#d7 }q|s |f|dd  }&|dur|f|& S |&S t|||j|jdS )a  
        labels (:obj:`torch.LongTensor` of shape :obj:`(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]``
        Nr   r   ru   r   r   r  r   r   r   rW  rX  r  rY  r   r   r   r   rw   r<   r=   r   r  r  r   rN  )r_   r  r  r  r	   r   r}   r  r  r  r  r  r  r  r  r  r  r   r   r   r   r   r   rN   r   r   rN  )'r   r   r   r   ru   r   r   r  r   r   r  r   rW  rX  r  rY  r  r  r  r   r   r   token_type_ids_labelrel_type_ids_labelabsolute_position_ids_labelrelative_position_ids_labelr  ru  rv  r  r  positions_clspositions_labelpositions_sizemyclsmylabelsmysizemyprediction_scoresr  r.   r.   r1   r   u  s   &	



zBertForGisMaskedLM.forwardc                 K      |j }|d }| jjd usJ d||j d df}tj||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=   rw   r   r   )r   r   	rX   r_   r   	new_zerosr[   r   fullr   r   r   r   r   r  r   effective_batch_sizepadding_maskdummy_tokenr.   r.   r1   r    s   

z0BertForGisMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNNNNFrC  Nr   FNNNNNNNr   )	r   r   r   r  r  r{   r   r  r   r.   r.   r   r1   r  R  sB    
zr  c                       sz   e Zd ZdgZddgZ fddZdd Zdd	 Z	
	
	
	
	
	
	
	
	
	
	
	
	
			
			
	
	
dddZ	
dddZ	  Z
S )BertForMaskedLMr  ru   r  c                    r  r  r  r   r   r.   r1   r{     r  zBertForMaskedLM.__init__c                 C   r  r   r  r   r.   r.   r1   r    r   z%BertForMaskedLM.get_output_embeddingsc                 C   r  r   r  r  r.   r.   r1   r    r  z%BertForMaskedLM.set_output_embeddingsNFrC  r   c                 C   sT  |dur|n| j j}| j|fi d|d|d|d|d|d|d|d	|	d
|d|d|d|d|d|d|d|}|d }| |}|rN|S d}|
duret }||d| j j|
d}|durtjt	j
|dd| dd }||
dk  }d| | ||  }|s|f|dd  }|dur|f| S |S t|||j|jdS )a  
        labels (:obj:`torch.LongTensor` of shape :obj:`(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]``
        Nr   r   ru   r   r   r  r   r   r   rW  rX  r  rY  r   r   r   r   rw   r   r  r=   r<   r   )r_   r  r  r  r	   r   r}   r[   r  r  r  r  r   r   rN  )r   r   r   r   ru   r   r   r  r   r   r  r   rW  rX  r  rY  r  r  r  r   r   r   r  ru  rv  r  r  r  r  r.   r.   r1   r     s   	

zBertForMaskedLM.forwardc                 K   r  r  r  r  r.   r.   r1   r  k  s   

z-BertForMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNNNNFrC  Nr   FNNNr   )r   r   r   r  r  r{   r  r  r   r  r   r.   r.   r   r1   r    s>    
Wr  c                       :   e Zd Z fddZ										dddZ  ZS )BertForNextSentencePredictionc                    r  r   )rz   r{   r  r  ry  r  r  r   r   r.   r1   r{     r  z&BertForNextSentencePrediction.__init__Nc                 K   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dur6t }||dd|d}|
sL|f|dd  }|durJ|f| S |S t|||j|jdS )u  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
            Labels for computing the next sequenåce 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:
            >>> from transformers import BertTokenizer, BertForNextSentencePrediction
            >>> import torch
            >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
            >>> model = BertForNextSentencePrediction.from_pretrained('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
        Nr  r=   rw   r<   r   )	r_   r  r  r  r	   r   r   r   rN  )r   r   r   r   ru   r   r   r  r   rW  rX  kwargsr  rh  seq_relationship_scoresr  r  r  r.   r.   r1   r     sD   !
z%BertForNextSentencePrediction.forward
NNNNNNNNNNr  r.   r.   r   r1   r    s    	r  c                       r  )BertForSequenceClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   rz   r{   
num_labelsr  r  r   r   r   r   r   r~   r;   r  r   r   r.   r1   r{     s   
z&BertForSequenceClassification.__init__Nc                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|durP| jdkr@t }||d|d}nt }||d| j|d}|
sf|f|dd  }|durd|f| S |S t	|||j
|jdS )a  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
            Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
            config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
            If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr  r=   rw   r<   r   )r_   r  r  r   r;   r  r
   r   r	   r   r   rN  )r   r   r   r   ru   r   r   r  r   rW  rX  r  rh  r  r  r  r  r.   r.   r1   r     sB   


z%BertForSequenceClassification.forwardr  r  r.   r.   r   r1   r    s    r  c                       r  )BertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr=   )rz   r{   r  r  r   r   r   r   r   r~   r;   r  r   r   r.   r1   r{     s
   
zBertForMultipleChoice.__init__Nc                 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 )at  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
        `optional`):
            Labels for computing the multiple choice classification loss.
            Indices should be in ``[0, ..., num_choices-1]`` where
            :obj:`num_choices` is the size of the second dimension of the input
            tensors. (See :obj:`input_ids` above)
        Nr=   rw   r   r  r<   r   )r_   r  rX   r   r   r  r   r;   r	   r   r   rN  )r   r   r   r   ru   r   r   r  r   rW  rX  num_choicesr  rh  r  reshaped_logitsr  r  r  r.   r.   r1   r   $  s   




zBertForMultipleChoice.forwardr  r  r.   r.   r   r1   r    s    r  c                       s@   e Zd ZdgZ fddZ										dddZ  ZS )BertForTokenClassificationr  c                    sN   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   d S r  r  r   r   r.   r1   r{   s  s   z#BertForTokenClassification.__init__Nc                 C   s
  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|duret }|durX|ddk}|d| j}t	||dt
|j|}|||}n||d| j|d}|
s{|f|dd  }|dury|f| S |S t|||j|jdS )z
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
        sequence_length)`, `optional`):
            Labels for computing the token classification loss. Indices should
            be in ``[0, ..., config.num_labels - 1]``.
        Nr  r   rw   r=   r<   r   )r_   r  r  r   r;   r	   r   r  r[   wheretensorignore_indextype_asr   r   rN  )r   r   r   r   ru   r   r   r  r   rW  rX  r  ru  r  r  r  active_lossactive_logitsactive_labelsr  r.   r.   r1   r   }  sL   


z"BertForTokenClassification.forwardr  r   r   r   r  r{   r   r   r.   r.   r   r1   r!  o  s    r!  c                       sB   e Zd ZdgZ fddZ											dddZ  ZS )BertForQuestionAnsweringr  c                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r  )
rz   r{   r  r  r  r   r   r~   
qa_outputsr  r   r   r.   r1   r{     s
   z!BertForQuestionAnswering.__init__Nc                 C   s@  |dur|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d}|d}d}|dur~|dur~t| dkrK|d}t| dkrX|d}|d}|d| |d| t	|d}|||}|||}|| d }|s||f|dd  }|dur|f| S |S t
||||j|jd	S )
aa  
        start_positions (:obj:`torch.LongTensor` of shape :obj:`(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 (:obj:`sequence_length`). Position
            outside of the sequence are not taken into account for computing the
            loss.
        end_positions (:obj:`torch.LongTensor` of shape :obj:`(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 (:obj:`sequence_length`). Position
            outside of the sequence are not taken into account for computing the
            loss.
        Nr  r   r=   rw   r   )r$  r<   )r  start_logits
end_logitsr   rN  )r_   r  r  r+  rO   squeezerU   r   clamp_r	   r   r   rN  )r   r   r   r   ru   r   r   start_positionsend_positionsr   rW  rX  r  ru  r  r,  r-  r  ignored_indexr  
start_lossend_lossr  r.   r.   r1   r     sZ   








z BertForQuestionAnswering.forwardr  r)  r.   r.   r   r1   r*    s    r*  c                       sT   e Zd ZdZeZdZdZdgZ fddZ	dd Z
dd
dZe fddZ  ZS )MGeoPreTrainedModelr  r  Tru   c                    s*   t  j|jfi | t t| | d S r   )rz   r{   name_or_pathr!   )r   r_   r  r   r.   r1   r{   (	  s   zMGeoPreTrainedModel.__init__c                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS dS )zInitialize the weightsr  r  Nr  )r  r   r   r5   r]   r  r_   r  r8   r  r|   rq   r   r  r  r.   r.   r1   r  ,	  s$   

z!MGeoPreTrainedModel._init_weightsFc                 C   s   t |tr
||_d S d S r   )r  r:  rF  )r   rH  r   r.   r.   r1   _set_gradient_checkpointing>	  s   

z/MGeoPreTrainedModel._set_gradient_checkpointingc                    sn   | dd}| dd}t||fi |}|du r%tdi |}| |}ntt| jdd|i|}||_|S )a  Instantiate the model.

        Args:
            kwargs: Input args.
                    model_dir: The model dir used to load the checkpoint and the
                    label information. num_labels: An optional arg to tell the
                    model how many classes to initialize.
                                    Method will call utils.parse_label_mapping
                                    if num_labels not supplied. If num_labels is
                                    not found, the model will use the default
                                    setting (2 classes).

        Returns:
            The loaded model, which is initialized by
            transformers.PreTrainedModel.from_pretrained
        	model_dirNcfgpretrained_model_name_or_pathr.   )popr&   r   rz   r!   from_pretrainedr8  )r  r  r8  r9  
model_argsr_   r^   r   r.   r1   _instantiateB	  s   
z MGeoPreTrainedModel._instantiater  )r   r   r   r   r   r  r  supports_gradient_checkpointingr  r{   r  r7  classmethodr>  r   r.   r.   r   r1   r5  	  s    
r5  )module_namec                       sr   e Zd Z			ddededef fddZ																																			dd
dZdd Zdd Z	  Z
S )MGeosingle-modalr=   Fr_   finetune_modegis_numc                    s   t  | || _|| _t||d| _| jdkrBt|j}t|dd| _| j	 D ]}d|_
q*t|j| jj| _t||j| _|   d S )Nr  multi-modalF)rz   r{   rD  r_   r  text_encoderr   	from_dictgis_encoder
parametersrequires_gradr   r   r~   gis2textr|   gis_typer  )r   r_   rD  rE  r  r  
gis_configparamr   r.   r1   r{   e	  s    
zMGeo.__init__Nc           !         sX   j dkr.|d ur.t|dkr.g }g }|D ]}| jdddd|j ||d  q|r: jj|||d}n jj|d} j dkr|d urt|dkr|g}|g} fd	d
|D }t|||D ]\}}}| ||  || qet	j
|dd}t	j
|dd}n|}|} j|||||dd} |s| S t| j| j| j| j| j| jdS )NrF  r   TrD  )rX  rY  r   )r   ru   r   )r   c                    r  r.   )rM  )r/   gtpr   r.   r1   r=  	  r>  z MGeo.forward.<locals>.<listcomp>r=   r   rw   )r   r  r   rW  rX  rY  r  r.   )rD  rU   rM   rI  rL  rG  r   rN   rL  r[   r   r$   r  rM  r   rN  rO  r  )!r   r   r   r   ru   r   r   r  r   r   rM  rV  r   rW  rX  r  rY  gis_listgis_tpuse_token_typegis_embsgis_attsgisr  embsattstp_embgegagt	merge_embmerge_attentionr  r.   r   r1   r   ~	  sr   zMGeo.forwardc                 C      |d S )NrL  r.   r   r  r.   r.   r1   extract_sequence_outputs	  r  zMGeo.extract_sequence_outputsc                 C   r_  )Nr  r.   r`  r.   r.   r1   extract_pooled_outputs	  r  zMGeo.extract_pooled_outputs)rC  r=   F)NNNNNNNNNNNNNNFrC  NNF)r   r   r   r   r!  rV   r{   r   ra  rb  r   r.   r.   r   r1   rB  b	  sB    
IrB  )fr   rE   randomwarningsdataclassesr   typingr   r   r[   torch.nn.functionalr   
functionalr  torch.utils.checkpointtransformersr   r   r   torch.nnr	   r
   transformers.activationsr   transformers.file_utilsr   r   r   r   r   transformers.modeling_outputsr   r   r   r   r   r   r   r   r   transformers.modeling_utilsr   r   r   r   +transformers.models.bert.configuration_bertr   transformers.utilsr   modelscope.metainfor    modelscope.modelsr!   r"   modelscope.models.builderr#   modelscope.outputsr$   modelscope.utils.constantr%   modelscope.utils.nlp.utilsr&   set_verbosity_error
get_loggerrC   _CONFIG_FOR_DOC_TOKENIZER_FOR_DOCrn   Modulero   r   r   r  r  r  r&  r'  r:  rc  rj  rl  rr  ry  r}  r~  r  r  r  r  r  r  r  r  r  r  r!  r*  r5  register_modulebackbonemgeorB  r.   r.   r.   r1   <module>   s    ,
JmF 4[u'   	` @ 0PIVO_E