U
    4AfUp                    @  s  d Z ddlm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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 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- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 e37e8Z9dZ:dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBdZCdZDdZEdZFG dd dZGG dd de'jHjIZJG dd de'jHjIZKG d d! d!e'jHjIZLG d"d# d#e'jHjIZMG d$d% d%e'jHjIZNG d&d' d'e'jHjIZOG d(d) d)e'jHjIZPG d*d+ d+e'jHjIZQG d,d- d-e'jHjIZRG d.d/ d/e'jHjIZSG d0d1 d1e'jHjIZTG d2d3 d3e'jHjIZUG d4d5 d5e'jHjIZVe(G d6d7 d7e'jHjIZWG d8d9 d9e"ZXeG d:d; d;e/ZYd<ZZd=Z[e1d>eZG d?d@ d@eXZ\e1dAeZG dBdC dCeXeGZ]e1dDeZG dEdF dFeXeZ^G dGdH dHeXeZ_e1dIeZG dJdK dKeXe!Z`e1dLeZG dMdN dNeXe$Zae1dOeZG dPdQ dQeXe Zbe1dReZG dSdT dTeXe%Zce1dUeZG dVdW dWeXe#ZddS )XzTF 2.0 BERT model.    )annotationsN)	dataclass)DictOptionalTupleUnion   )get_tf_activation)	+TFBaseModelOutputWithPastAndCrossAttentions.TFBaseModelOutputWithPoolingAndCrossAttentions#TFCausalLMOutputWithCrossAttentionsTFMaskedLMOutputTFMultipleChoiceModelOutputTFNextSentencePredictorOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)TFCausalLanguageModelingLossTFMaskedLanguageModelingLossTFModelInputTypeTFMultipleChoiceLossTFNextSentencePredictionLossTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFTokenClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forward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{Gz?zydshieh/bert-base-cased-squad2z'a nice puppet'gp=
ף@      z'ydshieh/bert-base-uncased-yelp-polarityz	'LABEL_1'c                   @  s"   e Zd ZdZddddddZdS )TFBertPreTrainingLossz
    Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
    NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
    computation.
    	tf.Tensor)labelslogitsreturnc                 C  s   t jjdt jjjd}|tj|d |d d}tj|d dk|j	d}|| }t
|t
| }|tj|d |d	 d}tj|d dk|j	d}	||	 }
t
|
t
|	 }t|| d
S )NT)Zfrom_logitsZ	reductionr/   r   )Zy_trueZy_predidtypenext_sentence_labelr)   )r)   )r   ZlossesZSparseCategoricalCrossentropyZ	ReductionNONEtfnnZrelucastr3   Z
reduce_sumreshape)selfr/   r0   Zloss_fnZunmasked_lm_lossesZlm_loss_maskZmasked_lm_lossesZreduced_masked_lm_lossZunmasked_ns_lossZns_loss_maskZmasked_ns_lossZreduced_masked_ns_loss r;   M/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/bert/modeling_tf_bert.pyhf_compute_lossc   s    z%TFBertPreTrainingLoss.hf_compute_lossN)__name__
__module____qualname____doc__r=   r;   r;   r;   r<   r-   \   s   r-   c                      sJ   e Zd ZdZdd fddZdddZddddddddddZ  ZS )TFBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.r*   configc                   sV   t  jf | || _|j| _|j| _|j| _tjj|j	dd| _
tjj|jd| _d S )N	LayerNormepsilonnameZrate)super__init__rD   hidden_sizemax_position_embeddingsinitializer_ranger   layersLayerNormalizationlayer_norm_epsrE   Dropouthidden_dropout_probdropoutr:   rD   kwargs	__class__r;   r<   rK   {   s    zTFBertEmbeddings.__init__Nc              	   C  s   t d( | jd| jj| jgt| jd| _W 5 Q R X t d( | jd| jj	| jgt| jd| _
W 5 Q R X t d& | jd| j| jgt| jd| _W 5 Q R X | jrd S d| _t| dd d k	rt | jj | jd d | jjg W 5 Q R X d S )	NZword_embeddingsweight)rH   shapeinitializertoken_type_embeddings
embeddingsposition_embeddingsTrE   )r6   
name_scope
add_weightrD   
vocab_sizerL   r   rN   rY   Ztype_vocab_sizer\   rM   r^   builtgetattrrE   rH   buildr:   input_shaper;   r;   r<   rd      s0    
zTFBertEmbeddings.buildr   Fr.   bool)	input_idsposition_idstoken_type_idsinputs_embedstrainingr1   c                 C  s   |dkr|dkrt d|dk	r>t|| jj tj| j|d}t|dd }|dkrdtj|dd}|dkrtj	tj
||d | ddd	}tj| j|d}tj| j|d}	|| |	 }
| j|
d
}
| j|
|d}
|
S )z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        Nz5Need to provide either `input_ids` or `input_embeds`.)paramsindicesr   Zdimsvaluer)   )startlimitaxisinputsrw   rl   )
ValueErrorr    rD   ra   r6   ZgatherrY   r!   fillZexpand_dimsranger^   r\   rE   rT   )r:   rh   ri   rj   rk   past_key_values_lengthrl   rf   Zposition_embedsZtoken_type_embedsZfinal_embeddingsr;   r;   r<   call   s&     zTFBertEmbeddings.call)N)NNNNr   F)r>   r?   r@   rA   rK   rd   r}   __classcell__r;   r;   rW   r<   rB   x   s   

      rB   c                      s^   e Zd Zdd fddZdddddd	Zddddddddddd	ddZdddZ  ZS )TFBertSelfAttentionr*   rC   c                   s   t  jf | |j|j dkr8td|j d|j d|j| _t|j|j | _| j| j | _t	| j| _
tjj| jt|jdd| _tjj| jt|jdd| _tjj| jt|jdd| _tjj|jd	| _|j| _|| _d S )
Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()queryunitskernel_initializerrH   keyrq   rI   )rJ   rK   rL   num_attention_headsry   intattention_head_sizeall_head_sizemathsqrtsqrt_att_head_sizer   rO   Denser   rN   r   r   rq   rR   Zattention_probs_dropout_probrT   
is_decoderrD   rU   rW   r;   r<   rK      s6          zTFBertSelfAttention.__init__r.   r   )tensor
batch_sizer1   c                 C  s0   t j||d| j| jfd}t j|ddddgdS )Nro   r   rZ   r      r)   r   perm)r6   r9   r   r   	transpose)r:   r   r   r;   r;   r<   transpose_for_scores   s    z(TFBertSelfAttention.transpose_for_scoresFTuple[tf.Tensor]rg   	hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrl   r1   c	                 C  s  t |d }	| j|d}
|d k	}|rB|d k	rB|d }|d }|}n|rt| | j|d|	}| | j|d|	}|}n|d k	r| | j|d|	}| | j|d|	}tj|d |gdd}tj|d |gdd}n(| | j|d|	}| | j|d|	}| |
|	}| jr||f}tj||dd}tj	| j
|jd}t||}|d k	rZt||}t|d	d
}| j||d}|d k	rt||}t||}tj|ddddgd}tj||	d	| jfd}|r||fn|f}| jr||f }|S )Nr   rv   r)   r   rt   T)transpose_br2   ro   )r0   ru   rx   r   r   r   )r!   r   r   r   rq   r6   concatr   matmulr8   r   r3   divideaddr"   rT   multiplyr   r9   r   )r:   r   r   r   r   r   r   r   rl   r   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerZattention_scoresZdkZattention_probsattention_outputoutputsr;   r;   r<   r}      sJ    


zTFBertSelfAttention.callNc              	   C  s   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X t| dd d k	rt| j	j | j	d d | jjg W 5 Q R X t| dd d k	rt| j
j | j
d d | jjg W 5 Q R X d S )NTr   r   rq   )rb   rc   r6   r_   r   rH   rd   rD   rL   r   rq   re   r;   r;   r<   rd   @  s      zTFBertSelfAttention.build)F)N)r>   r?   r@   rK   r   r}   rd   r~   r;   r;   rW   r<   r      s
     Qr   c                      sB   e Zd Zdd fddZddddddd	d
ZdddZ  ZS )TFBertSelfOutputr*   rC   c                   sZ   t  jf | tjj|jt|jdd| _tjj	|j
dd| _tjj|jd| _|| _d S Ndenser   rE   rF   rI   rJ   rK   r   rO   r   rL   r   rN   r   rP   rQ   rE   rR   rS   rT   rD   rU   rW   r;   r<   rK   P  s      zTFBertSelfOutput.__init__Fr.   rg   r   input_tensorrl   r1   c                 C  s.   | j |d}| j||d}| j|| d}|S Nrv   rx   r   rT   rE   r:   r   r   rl   r;   r;   r<   r}   Z  s    zTFBertSelfOutput.callNc              	   C  s   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X t| dd d k	rt| j	j | j	d d | jjg W 5 Q R X d S NTr   rE   
rb   rc   r6   r_   r   rH   rd   rD   rL   rE   re   r;   r;   r<   rd   a  s     zTFBertSelfOutput.build)F)Nr>   r?   r@   rK   r}   rd   r~   r;   r;   rW   r<   r   O  s   
r   c                      sT   e Zd Zdd fddZdd Zddddddd	d
d
d	d	ddZdddZ  ZS )TFBertAttentionr*   rC   c                   s.   t  jf | t|dd| _t|dd| _d S )Nr:   rH   output)rJ   rK   r   self_attentionr   dense_outputrU   rW   r;   r<   rK   n  s    zTFBertAttention.__init__c                 C  s   t d S NNotImplementedError)r:   Zheadsr;   r;   r<   prune_headst  s    zTFBertAttention.prune_headsFr.   r   rg   )	r   r   r   r   r   r   r   rl   r1   c	              
   C  sD   | j ||||||||d}	| j|	d ||d}
|
f|	dd   }|S )Nr   r   r   r   r   r   r   rl   r   r   r   rl   r)   )r   r   )r:   r   r   r   r   r   r   r   rl   Zself_outputsr   r   r;   r;   r<   r}   w  s"    
  zTFBertAttention.callNc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X d S )NTr   r   )rb   rc   r6   r_   r   rH   rd   r   re   r;   r;   r<   rd     s    zTFBertAttention.build)F)N)r>   r?   r@   rK   r   r}   rd   r~   r;   r;   rW   r<   r   m  s
     r   c                      s<   e Zd Zdd fddZdddddZdd
dZ  ZS )TFBertIntermediater*   rC   c                   sV   t  jf | tjj|jt|jdd| _t	|j
trDt|j
| _n|j
| _|| _d S )Nr   r   )rJ   rK   r   rO   r   intermediate_sizer   rN   r   
isinstance
hidden_actstrr	   intermediate_act_fnrD   rU   rW   r;   r<   rK     s      zTFBertIntermediate.__init__r.   r   r1   c                 C  s   | j |d}| |}|S Nrv   )r   r   r:   r   r;   r;   r<   r}     s    
zTFBertIntermediate.callNc              	   C  sT   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X d S NTr   	rb   rc   r6   r_   r   rH   rd   rD   rL   re   r;   r;   r<   rd     s    zTFBertIntermediate.build)Nr   r;   r;   rW   r<   r     s   r   c                      sB   e Zd Zdd fddZddddddd	d
ZdddZ  ZS )TFBertOutputr*   rC   c                   sZ   t  jf | tjj|jt|jdd| _tjj	|j
dd| _tjj|jd| _|| _d S r   r   rU   rW   r;   r<   rK     s      zTFBertOutput.__init__Fr.   rg   r   c                 C  s.   | j |d}| j||d}| j|| d}|S r   r   r   r;   r;   r<   r}     s    zTFBertOutput.callNc              	   C  s   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X t| dd d k	rt| j	j | j	d d | jj
g W 5 Q R X d S r   )rb   rc   r6   r_   r   rH   rd   rD   r   rE   rL   re   r;   r;   r<   rd     s     zTFBertOutput.build)F)Nr   r;   r;   rW   r<   r     s   
r   c                      sL   e Zd Zdd fddZdddddddd	d	d
d	ddZdddZ  ZS )TFBertLayerr*   rC   c                   st   t  jf | t|dd| _|j| _|j| _| jrT| jsFt|  dt|dd| _t|dd| _	t
|dd| _d S )N	attentionr   z> should be used as a decoder model if cross attention is addedcrossattentionintermediater   )rJ   rK   r   r   r   add_cross_attentionry   r   r   r   r   bert_outputrU   rW   r;   r<   rK     s    zTFBertLayer.__init__Fr.   tf.Tensor | NonezTuple[tf.Tensor] | Nonerg   r   r   c	              
   C  s$  |d k	r|d d nd }	| j |||d d |	||d}
|
d }| jrV|
dd }|
d }n|
dd  }d }| jr|d k	rt| dstd|  d|d k	r|d	d  nd }| j||||||||d}|d }||dd  }|d }|| }| j|d
}| j|||d}|f| }| jr ||f }|S )Nr   )r   r   r   r   r   r   r   rl   r   r)   ro   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   hasattrry   r   r   r   )r:   r   r   r   r   r   r   r   rl   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_outputsZintermediate_outputZlayer_outputr;   r;   r<   r}     s^    




  

zTFBertLayer.callNc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X t| dd d k	rt| j	j | j	d  W 5 Q R X d S )NTr   r   r   r   )
rb   rc   r6   r_   r   rH   rd   r   r   r   re   r;   r;   r<   rd   0  s    zTFBertLayer.build)F)Nr   r;   r;   rW   r<   r     s     Gr   c                      sR   e Zd Zdd fddZdddddddd	d
d
d
d
ddddZdddZ  ZS )TFBertEncoderr*   rC   c                   s2   t  jf |  | _ fddt jD | _d S )Nc                   s   g | ]}t  d | dqS )zlayer_._r   )r   ).0irC   r;   r<   
<listcomp>F  s     z*TFBertEncoder.__init__.<locals>.<listcomp>)rJ   rK   rD   r{   num_hidden_layerslayerrU   rW   rC   r<   rK   C  s    zTFBertEncoder.__init__Fr.   r   zTuple[Tuple[tf.Tensor]] | NoneOptional[bool]rg   zDUnion[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]])r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictrl   r1   c                 C  s  |	rdnd }|rdnd }|r(| j jr(dnd }|r4dnd }t| jD ]\}}|	rX||f }|d k	rh|| nd }||||| |||||d}|d }|r||d f7 }|rB||d f }| j jrB|d k	rB||d f }qB|	r||f }|
stdd ||||fD S t|||||d	S )
Nr;   r   r   ro   r)   r   c                 s  s   | ]}|d k	r|V  qd S r   r;   )r   vr;   r;   r<   	<genexpr>z  s     z%TFBertEncoder.call.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)rD   r   	enumerater   tupler
   )r:   r   r   r   r   r   r   r   r   r   r   rl   Zall_hidden_statesZall_attentionsZall_cross_attentionsZnext_decoder_cacher   Zlayer_moduler   Zlayer_outputsr;   r;   r<   r}   H  sL    



zTFBertEncoder.callNc              
   C  sR   | j r
d S d| _ t| dd d k	rN| jD ]&}t|j |d  W 5 Q R X q&d S )NTr   )rb   rc   r   r6   r_   rH   rd   )r:   rf   r   r;   r;   r<   rd     s    
zTFBertEncoder.build)F)Nr   r;   r;   rW   r<   r   B  s    &>r   c                      s<   e Zd Zdd fddZdddddZdd
dZ  ZS )TFBertPoolerr*   rC   c                   s6   t  jf | tjj|jt|jddd| _|| _	d S )Ntanhr   )r   r   Z
activationrH   )
rJ   rK   r   rO   r   rL   r   rN   r   rD   rU   rW   r;   r<   rK     s    zTFBertPooler.__init__r.   r   c                 C  s    |d d df }| j |d}|S )Nr   rv   )r   )r:   r   Zfirst_token_tensorpooled_outputr;   r;   r<   r}     s    zTFBertPooler.callNc              	   C  sT   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X d S r   r   re   r;   r;   r<   rd     s    zTFBertPooler.build)Nr   r;   r;   rW   r<   r     s   r   c                      s<   e Zd Zdd fddZdddddZdd
dZ  ZS )TFBertPredictionHeadTransformr*   rC   c                   sj   t  jf | tjj|jt|jdd| _t	|j
trDt|j
| _n|j
| _tjj|jdd| _|| _d S )Nr   r   rE   rF   )rJ   rK   r   rO   r   rL   r   rN   r   r   r   r   r	   transform_act_fnrP   rQ   rE   rD   rU   rW   r;   r<   rK     s    z&TFBertPredictionHeadTransform.__init__r.   r   c                 C  s&   | j |d}| |}| j|d}|S r   )r   r   rE   r   r;   r;   r<   r}     s    
z"TFBertPredictionHeadTransform.callNc              	   C  s   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X t| dd d k	rt| j	j | j	d d | jjg W 5 Q R X d S r   r   re   r;   r;   r<   rd     s     z#TFBertPredictionHeadTransform.build)Nr   r;   r;   rW   r<   r     s   r   c                      sv   e Zd Zddd fddZdddZdd	d
dZddddZdd	ddZddddZdddddZ	  Z
S )TFBertLMPredictionHeadr*   keras.layers.LayerrD   input_embeddingsc                   s4   t  jf | || _|j| _t|dd| _|| _d S )N	transformr   )rJ   rK   rD   rL   r   r   r   r:   rD   r   rV   rW   r;   r<   rK     s
    zTFBertLMPredictionHead.__init__Nc              	   C  sd   | j | jjfdddd| _| jr$d S d| _t| dd d k	r`t| jj	 | j
d  W 5 Q R X d S )NzerosTbias)rZ   r[   Z	trainablerH   r   )r`   rD   ra   r   rb   rc   r6   r_   r   rH   rd   re   r;   r;   r<   rd     s    zTFBertLMPredictionHead.buildr1   c                 C  s   | j S r   )r   r:   r;   r;   r<   get_output_embeddings  s    z,TFBertLMPredictionHead.get_output_embeddingstf.Variablerq   c                 C  s   || j _t|d | j _d S Nr   )r   rY   r!   ra   r:   rq   r;   r;   r<   set_output_embeddings  s    z,TFBertLMPredictionHead.set_output_embeddingszDict[str, tf.Variable]c                 C  s
   d| j iS )Nr   )r   r   r;   r;   r<   get_bias  s    zTFBertLMPredictionHead.get_biasc                 C  s"   |d | _ t|d d | j_d S )Nr   r   )r   r!   rD   ra   r   r;   r;   r<   set_bias  s    
zTFBertLMPredictionHead.set_biasr.   r   c                 C  sn   | j |d}t|d }tj|d| jgd}tj|| jjdd}tj|d|| jj	gd}tj
j|| jd}|S )Nr   r)   ro   r   T)abr   )rq   r   )r   r!   r6   r9   rL   r   r   rY   rD   ra   r7   Zbias_addr   )r:   r   
seq_lengthr;   r;   r<   r}     s    zTFBertLMPredictionHead.call)N)r>   r?   r@   rK   rd   r   r   r   r   r}   r~   r;   r;   rW   r<   r     s   

r   c                      s>   e Zd Zddd fddZddddd	ZdddZ  ZS )TFBertMLMHeadr*   r   r   c                   s"   t  jf | t||dd| _d S )Npredictionsr   )rJ   rK   r   r  r   rW   r;   r<   rK     s    zTFBertMLMHead.__init__r.   )sequence_outputr1   c                 C  s   | j |d}|S )Nr   )r  )r:   r  prediction_scoresr;   r;   r<   r}     s    zTFBertMLMHead.callNc              	   C  sJ   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X d S )NTr  )rb   rc   r6   r_   r  rH   rd   re   r;   r;   r<   rd     s    zTFBertMLMHead.build)Nr   r;   r;   rW   r<   r    s   r  c                      s<   e Zd Zdd fddZdddddZdd
dZ  ZS )TFBertNSPHeadr*   rC   c                   s2   t  jf | tjjdt|jdd| _|| _d S )Nr   seq_relationshipr   )	rJ   rK   r   rO   r   r   rN   r  rD   rU   rW   r;   r<   rK     s    zTFBertNSPHead.__init__r.   )r   r1   c                 C  s   | j |d}|S r   )r  )r:   r   seq_relationship_scorer;   r;   r<   r}   !  s    zTFBertNSPHead.callNc              	   C  sT   | j r
d S d| _ t| dd d k	rPt| jj | jd d | jjg W 5 Q R X d S )NTr  )	rb   rc   r6   r_   r  rH   rd   rD   rL   re   r;   r;   r<   rd   &  s    zTFBertNSPHead.build)Nr   r;   r;   rW   r<   r    s   
r  c                      s   e Zd ZeZdddd fddZddd	d
ZddddZdd Ze	dddddddddddddddddddZ
dddZ  ZS ) TFBertMainLayerTr*   rg   rD   add_pooling_layerc                   sR   t  jf | || _|j| _t|dd| _t|dd| _|rHt|ddnd | _	d S )Nr]   r   encoderpooler)
rJ   rK   rD   r   rB   r]   r   r  r   r  )r:   rD   r
  rV   rW   r;   r<   rK   3  s    zTFBertMainLayer.__init__r   r   c                 C  s   | j S r   )r]   r   r;   r;   r<   get_input_embeddings=  s    z$TFBertMainLayer.get_input_embeddingsr   r   c                 C  s   || j _t|d | j _d S r   )r]   rY   r!   ra   r   r;   r;   r<   set_input_embeddings@  s    z$TFBertMainLayer.set_input_embeddingsc                 C  s   t 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
        Nr   )r:   Zheads_to_pruner;   r;   r<   _prune_headsD  s    zTFBertMainLayer._prune_headsNFTFModelInputType | Nonenp.ndarray | tf.Tensor | None4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]r   GUnion[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   rl   r1   c                  C  s<  | j jsd}
|d k	r&|d k	r&tdn4|d k	r8t|}n"|d k	rRt|d d }ntd|\}}|	d krd}d gt| jj }	nt|	d d d }|d krtj||| fdd}|d krtj|dd}| j	||||||d	}t|}|| }| jrt
|}tt|d d d d f ||df|d d d d f }tj||jd
}||d d d d d f  }t|}t||d d|d |d f}|	d d k	r|d d d d | d d d f }nt||d dd|d f}tj||jd
}tjd|jd
}tjd|jd
}tt|||}| jr|d k	rtj||jd
}tt|}|dkrp|d d d d d d d f }|dkr|d d d d d d f }d| d }nd }|d k	rtnd g| j j }| j||||||	|
||||d}|d }| jd k	r| j|dnd }|s ||f|dd   S t|||j|j|j|jdS )NFzDYou cannot specify both input_ids and inputs_embeds at the same timero   z5You have to specify either input_ids or inputs_embedsr   r   r)   rp   )rh   ri   rj   rk   r|   rl   r2   r   g      ?g     r   )r   r   r   r   r   r   r   r   r   r   rl   r   )r   Zpooler_outputr   r   r   r   )rD   r   ry   r!   lenr  r   r6   rz   r]   r{   Z
less_equalZtiler8   r3   r9   Zconstantr   subtractr   r   r  r   r   r   r   r   ) r:   rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   rl   rf   r   r   r|   Zembedding_outputZattention_mask_shapeZmask_seq_lengthZseq_idsZcausal_maskZextended_attention_maskZone_cstZten_thousand_cstZnum_dims_encoder_attention_maskZencoder_extended_attention_maskZencoder_outputsr  r   r;   r;   r<   r}   K  s    


 $ 	



zTFBertMainLayer.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X d S )NTr]   r  r  )	rb   rc   r6   r_   r]   rH   rd   r  r  re   r;   r;   r<   rd     s    zTFBertMainLayer.build)T)NNNNNNNNNNNNNF)N)r>   r?   r@   r*   config_classrK   r  r  r  r   r}   rd   r~   r;   r;   rW   r<   r  /  s.   
              . r  c                   @  s   e Zd ZdZeZdZdS )TFBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    bertN)r>   r?   r@   rA   r*   r  Zbase_model_prefixr;   r;   r;   r<   r    s   r  c                   @  sN   e Zd ZU dZdZded< dZded< dZded< dZded	< dZ	ded
< dS )TFBertForPreTrainingOutputa?  
    Output type of [`TFBertForPreTraining`].

    Args:
        prediction_logits (`tf.Tensor` 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 (`tf.Tensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            before SoftMax).
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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.
    Nr   lossr.   prediction_logitsseq_relationship_logitsz,Optional[Union[Tuple[tf.Tensor], tf.Tensor]]r   r   )
r>   r?   r@   rA   r  __annotations__r  r  r   r   r;   r;   r;   r<   r    s   
r  av	  

    This model inherits from [`TFPreTrainedModel`]. 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 [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TensorFlow models and layers in `transformers` accept two formats as input:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional argument.

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
    `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
    `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    Args:
        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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`np.ndarray` or `tf.Tensor` 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 (`np.ndarray` or `tf.Tensor` 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 (`np.ndarray` or `tf.Tensor` 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 (`np.ndarray` or `tf.Tensor` 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 (`np.ndarray` or `tf.Tensor` 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. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        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. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False``):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
z^The bare Bert Model transformer outputting raw hidden-states without any specific head on top.c                      s|   e Zd Zdddd fddZeeedee	e
eddddddddddddddddddddZdddZ  ZS )TFBertModelTr*   rg   r	  c                   s(   t  j|f|| t||dd| _d S )Nr  r   )rJ   rK   r  r  )r:   rD   r
  rw   rV   rW   r;   r<   rK     s    zTFBertModel.__init__batch_size, sequence_length
checkpointoutput_typer  NFr  r  r  r   r  r  c                 C  s*   | j |||||||||	|
||||d}|S )a  
        encoder_hidden_states  (`tf.Tensor` 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 (`tf.Tensor` 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[tf.Tensor]]` of length `config.n_layers`)
            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*, defaults to `True`):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`). Set to `False` during training, `True` during generation
        rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   rl   )r  )r:   rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   rl   r   r;   r;   r<   r}     s"    ,zTFBertModel.callc              	   C  sJ   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X d S )NTr  )rb   rc   r6   r_   r  rH   rd   re   r;   r;   r<   rd     s    zTFBertModel.build)T)NNNNNNNNNNNNNF)N)r>   r?   r@   rK   r   r&   BERT_INPUTS_DOCSTRINGformatr$   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr}   rd   r~   r;   r;   rW   r<   r    s0                 27r  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dgZdd fddZdd	d
dZdd	ddZeee	
deeeddddddddddddddddddZdddZ  ZS )TFBertForPreTrainingri   cls.predictions.decoder.weightzcls.predictions.decoder.biasr*   rC   c                   sH   t  j|f|| t|dd| _t|dd| _t|| jjdd| _d S )Nr  r   	nsp___cls	mlm___clsr   rH   )	rJ   rK   r  r  r  nspr  r]   mlmr:   rD   rw   rV   rW   r;   r<   rK     s    zTFBertForPreTraining.__init__r   r   c                 C  s   | j jS r   r/  r  r   r;   r;   r<   get_lm_head  s    z TFBertForPreTraining.get_lm_headr   c                 C  s,   t dt | jd | jj d | jjj S NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./warningswarnFutureWarningrH   r/  r  r   r;   r;   r<   get_prefix_bias_name  s    z)TFBertForPreTraining.get_prefix_bias_namer   r#  r  NFr  r  r   z3Union[TFBertForPreTrainingOutput, Tuple[tf.Tensor]])rh   r   rj   ri   r   rk   r   r   r   r/   r4   rl   r1   c                 C  s   | j |||||||||	|d
}|dd \}}| j||d}| j|d}d}|
dk	r~|dk	r~d|
i}||d< | j|||fd}|	s||f|dd  }|dk	r|f| S |S t||||j|jd	S )
a  
        labels (`tf.Tensor` 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 (`tf.Tensor` 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.

        Return:

        Examples:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFBertForPreTraining

        >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
        >>> model = TFBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
        >>> input_ids = tokenizer("Hello, my dog is cute", add_special_tokens=True, return_tensors="tf")
        >>> # Batch size 1

        >>> outputs = model(input_ids)
        >>> prediction_logits, seq_relationship_logits = outputs[:2]
        ```
rh   r   rj   ri   r   rk   r   r   r   rl   Nr   r  rl   r   r/   r4   r/   r0   )r  r  r  r   r   )r  r/  r.  r=   r  r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r/   r4   rl   r   r  r   r  r  Z
total_lossZd_labelsr   r;   r;   r<   r}     s<    0zTFBertForPreTraining.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X d S )NTr  r.  r/  )	rb   rc   r6   r_   r  rH   rd   r.  r/  re   r;   r;   r<   rd   C  s    zTFBertForPreTraining.build)NNNNNNNNNNNF)N)r>   r?   r@   "_keys_to_ignore_on_load_unexpectedrK   r2  r9  r   r&   r%  r&  r(   r  r(  r}   rd   r~   r;   r;   rW   r<   r)    s0   

            .Or)  z2Bert Model with a `language modeling` head on top.c                      s   e Zd ZddddgZdd fddZd	d
ddZdd
ddZeee	
deeeedddddddddddddddddddZd ddZ  ZS )!TFBertForMaskedLMr  cls.seq_relationshipr*  r+  r*   rC   c                   sL   t  j|f|| |jr$td t|ddd| _t|| jjdd| _	d S )NzmIf you want to use `TFBertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr  r
  rH   r,  r-  
rJ   rK   r   loggerwarningr  r  r  r]   r/  r0  rW   r;   r<   rK   \  s    zTFBertForMaskedLM.__init__r   r   c                 C  s   | j jS r   r1  r   r;   r;   r<   r2  h  s    zTFBertForMaskedLM.get_lm_headr   c                 C  s,   t dt | jd | jj d | jjj S r3  r5  r   r;   r;   r<   r9  k  s    z&TFBertForMaskedLM.get_prefix_bias_namer   z'paris'g)\(?r"  r#  r  expected_outputexpected_lossNFr  r  r   z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]rh   r   rj   ri   r   rk   r   r   r   r/   rl   r1   c                 C  s   | j |||||||||	|d
}|d }| j||d}|
dkr@dn| j|
|d}|	sz|f|dd  }|dk	rv|f| S |S t|||j|jdS )a  
        labels (`tf.Tensor` or `np.ndarray` 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]`
        r;  r   r<  Nr>  r   r  r0   r   r   )r  r/  r=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r/   rl   r   r  r  r  r   r;   r;   r<   r}   o  s0    zTFBertForMaskedLM.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X d S NTr  r/  rb   rc   r6   r_   r  rH   rd   r/  re   r;   r;   r<   rd     s    zTFBertForMaskedLM.build)NNNNNNNNNNF)N)r>   r?   r@   r?  rK   r2  r9  r   r&   r%  r&  r$   r'  r   r(  r}   rd   r~   r;   r;   rW   r<   r@  R  s<   	           ,/r@  c                      s   e Zd ZddddgZdd fddZd	d
ddZdd
ddZdddZee	e
eedd dddddddddddddddddddZd!ddZ  ZS )"TFBertLMHeadModelr  rA  r*  r+  r*   rC   c                   sL   t  j|f|| |js$td t|ddd| _t|| jjdd| _	d S )NzNIf you want to use `TFBertLMHeadModel` as a standalone, add `is_decoder=True.`Fr  rB  r,  r-  rC  r0  rW   r;   r<   rK     s
    
zTFBertLMHeadModel.__init__r   r   c                 C  s   | j jS r   r1  r   r;   r;   r<   r2    s    zTFBertLMHeadModel.get_lm_headr   c                 C  s,   t dt | jd | jj d | jjj S r3  r5  r   r;   r;   r<   r9    s    z&TFBertLMHeadModel.get_prefix_bias_nameNc                 K  s@   |j }|d krt|}|d k	r4|d d dd f }|||dS )Nro   )rh   r   r   )rZ   r6   Zones)r:   rh   r   r   Zmodel_kwargsrf   r;   r;   r<   prepare_inputs_for_generation  s    
z/TFBertLMHeadModel.prepare_inputs_for_generationr!  Fr  r  r  r   z<Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]])rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   r/   rl   r1   c                 K  s   | j |||||||||	|
||||d}|d }| j||d}d}|dk	r~|ddddf }|ddddf }| j||d}|s|f|dd  }|dk	r|f| S |S t|||j|j|j|jd	S )
a  
        encoder_hidden_states  (`tf.Tensor` 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 (`tf.Tensor` 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[tf.Tensor]]` of length `config.n_layers`)
            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*, defaults to `True`):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`). Set to `False` during training, `True` during generation
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
            config.vocab_size - 1]`.
        r$  r   r<  Nro   r)   r>  r   )r  r0   r   r   r   r   )r  r/  r=   r   r   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r   r   r   r   r/   rl   rV   r   r  r0   r  Zshifted_logitsr   r;   r;   r<   r}     sD    0zTFBertLMHeadModel.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X d S rK  rL  re   r;   r;   r<   rd   /  s    zTFBertLMHeadModel.build)NN)NNNNNNNNNNNNNNF)N)r>   r?   r@   r?  rK   r2  r9  rN  r   r$   r'  r   r(  r}   rd   r~   r;   r;   rW   r<   rM    s@   	
               2QrM  zJBert Model with a `next sentence prediction (classification)` head on top.c                      sx   e Zd ZddgZdd fddZeeede	e
edddddddddddddddddZdddZ  ZS )TFBertForNextSentencePredictionr,  cls.predictionsr*   rC   c                   s4   t  j|f|| t|dd| _t|dd| _d S )Nr  r   r+  )rJ   rK   r  r  r  r.  r0  rW   r;   r<   rK   C  s    z(TFBertForNextSentencePrediction.__init__r   r:  NFr  r  r   z6Union[TFNextSentencePredictorOutput, Tuple[tf.Tensor]])rh   r   rj   ri   r   rk   r   r   r   r4   rl   r1   c                 C  s   | j |||||||||	|d
}|d }| j|d}|
dkr>dn| j|
|d}|	sx|f|dd  }|dk	rt|f| S |S t|||j|jdS )aB  
        Return:

        Examples:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFBertForNextSentencePrediction

        >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
        >>> model = TFBertForNextSentencePrediction.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="tf")

        >>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
        >>> assert logits[0][0] < logits[0][1]  # the next sentence was random
        ```r;  r)   r=  Nr>  r   rJ  )r  r.  r=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r4   rl   r   r   Zseq_relationship_scoresZnext_sentence_lossr   r;   r;   r<   r}   I  s6    $z$TFBertForNextSentencePrediction.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X d S )NTr  r.  )rb   rc   r6   r_   r  rH   rd   r.  re   r;   r;   r<   rd     s    z%TFBertForNextSentencePrediction.build)NNNNNNNNNNF)N)r>   r?   r@   r?  rK   r   r&   r%  r&  r(   r   r(  r}   rd   r~   r;   r;   rW   r<   rO  ;  s$   
           ,@rO  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ddddgZdgZdd fdd	Zeee	d
e
eeeeedddddddddddddddddZdddZ  ZS )TFBertForSequenceClassificationr,  r+  rP  rA  rT   r*   rC   c                   sv   t  j|f|| |j| _t|dd| _|jd k	r:|jn|j}tjj	|d| _
tjj|jt|jdd| _|| _d S )Nr  r   rI   
classifierr   rJ   rK   
num_labelsr  r  classifier_dropoutrS   r   rO   rR   rT   r   r   rN   rR  rD   r:   rD   rw   rV   rU  rW   r;   r<   rK     s    z(TFBertForSequenceClassification.__init__r   rF  NFr  r  r   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]rI  c                 C  s   | j |||||||||	|d
}|d }| j||d}| j|d}|
dkrLdn| j|
|d}|	s|f|dd  }|dk	r|f| S |S t|||j|jdS )	a  
        labels (`tf.Tensor` or `np.ndarray` 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).
        r;  r)   rx   rv   Nr>  r   rJ  )r  rT   rR  r=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r/   rl   r   r   r0   r  r   r;   r;   r<   r}     s2    z$TFBertForSequenceClassification.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd d | jj	g W 5 Q R X d S NTr  rR  
rb   rc   r6   r_   r  rH   rd   rR  rD   rL   re   r;   r;   r<   rd     s    z%TFBertForSequenceClassification.build)NNNNNNNNNNF)N)r>   r?   r@   r?  _keys_to_ignore_on_load_missingrK   r   r&   r%  r&  r$   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r(  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr}   rd   r~   r;   r;   rW   r<   rQ    s2   		           ,0rQ  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ddddgZdgZdd fdd	Zeee	d
e
eeedddddddddddddddddZdddZ  ZS )TFBertForMultipleChoicer,  r+  rP  rA  rT   r*   rC   c                   sX   t  j|f|| t|dd| _tjj|jd| _tjj	dt
|jdd| _|| _d S )Nr  r   rI   r)   rR  r   )rJ   rK   r  r  r   rO   rR   rS   rT   r   r   rN   rR  rD   r0  rW   r;   r<   rK     s      z TFBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr!  NFr  r  r   z4Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]rI  c                 C  s  |dk	r"t |d }t |d }nt |d }t |d }|dk	rTtj|d|fdnd}|dk	rrtj|d|fdnd}|dk	rtj|d|fdnd}|dk	rtj|d|fdnd}|dk	rtj|d|t |d fdnd}| j|||||||||	|d
}|d }| j||d}| j|d	}tj|d|fd}|
dkr:dn| j|
|d
}|	sx|f|dd  }|dk	rt|f| S |S t|||j|j	dS )aE  
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
            where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
        Nr)   r   ro   r   r   r;  rx   rv   r>  rJ  )
r!   r6   r9   r  rT   rR  r=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r/   rl   Znum_choicesr   Zflat_input_idsZflat_attention_maskZflat_token_type_idsZflat_position_idsZflat_inputs_embedsr   r   r0   Zreshaped_logitsr  r   r;   r;   r<   r}     sT    zTFBertForMultipleChoice.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd d | jj	g W 5 Q R X d S rW  rX  re   r;   r;   r<   rd   ]  s    zTFBertForMultipleChoice.build)NNNNNNNNNNF)N)r>   r?   r@   r?  rY  rK   r   r&   r%  r&  r$   r'  r   r(  r}   rd   r~   r;   r;   rW   r<   r]    s.   	
           ,Fr]  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dddddgZdgZdd fd	d
Zeee	de
eeeeedddddddddddddddddZdddZ  ZS )TFBertForTokenClassificationr  r,  r+  rP  rA  rT   r*   rC   c                   sx   t  j|f|| |j| _t|ddd| _|jd k	r<|jn|j}tjj	|d| _
tjj|jt|jdd| _|| _d S )NFr  rB  rI   rR  r   rS  rV  rW   r;   r<   rK   {  s    z%TFBertForTokenClassification.__init__r   rF  NFr  r  r   z0Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]rI  c                 C  s   | j |||||||||	|d
}|d }| j||d}| j|d}|
dkrLdn| j|
|d}|	s|f|dd  }|dk	r|f| S |S t|||j|jdS )	z
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        r;  r   rx   rv   Nr>  r   rJ  )r  rT   rR  r=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   r/   rl   r   r  r0   r  r   r;   r;   r<   r}     s2    z!TFBertForTokenClassification.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd d | jj	g W 5 Q R X d S rW  rX  re   r;   r;   r<   rd     s    z"TFBertForTokenClassification.build)NNNNNNNNNNF)N)r>   r?   r@   r?  rY  rK   r   r&   r%  r&  r$   $_CHECKPOINT_FOR_TOKEN_CLASSIFICATIONr   r(  _TOKEN_CLASS_EXPECTED_OUTPUT_TOKEN_CLASS_EXPECTED_LOSSr}   rd   r~   r;   r;   rW   r<   r^  i  s<   
	           ,.r^  z
    Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                      s   e Zd ZdddddgZdd fdd	Zeeed
e	e
eeeeeeddddddddddddddddddZdddZ  ZS )TFBertForQuestionAnsweringr  r,  r+  rP  rA  r*   rC   c                   sR   t  j|f|| |j| _t|ddd| _tjj|jt|j	dd| _
|| _d S )NFr  rB  
qa_outputsr   )rJ   rK   rT  r  r  r   rO   r   r   rN   rc  rD   r0  rW   r;   r<   rK     s    z#TFBertForQuestionAnswering.__init__r   )r"  r#  r  Zqa_target_start_indexZqa_target_end_indexrG  rH  NFr  r  r   z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]])rh   r   rj   ri   r   rk   r   r   r   start_positionsend_positionsrl   r1   c                 C  s   | j |||||||||	|d
}|d }| j|d}tj|ddd\}}tj|dd}tj|dd}d}|
dk	r|dk	rd	|
i}||d
< | j|||fd}|	s||f|dd  }|dk	r|f| S |S t||||j|jdS )a  
        start_positions (`tf.Tensor` or `np.ndarray` 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 (`tf.Tensor` or `np.ndarray` 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.
        r;  r   rv   r   ro   )rq   Znum_or_size_splitsru   )inputru   NZstart_positionZend_positionr>  )r  start_logits
end_logitsr   r   )	r  rc  r6   splitZsqueezer=   r   r   r   )r:   rh   r   rj   ri   r   rk   r   r   r   rd  re  rl   r   r  r0   rg  rh  r  r/   r   r;   r;   r<   r}     s@    $zTFBertForQuestionAnswering.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd d | jj	g W 5 Q R X d S )NTr  rc  )
rb   rc   r6   r_   r  rH   rd   rc  rD   rL   re   r;   r;   r<   rd   5  s    z TFBertForQuestionAnswering.build)NNNNNNNNNNNF)N)r>   r?   r@   r?  rK   r   r&   r%  r&  r$   _CHECKPOINT_FOR_QAr   r(  _QA_TARGET_START_INDEX_QA_TARGET_END_INDEX_QA_EXPECTED_OUTPUT_QA_EXPECTED_LOSSr}   rd   r~   r;   r;   rW   r<   rb    s@   
            .=rb  )erA   
__future__r   r   r6  Zdataclassesr   typingr   r   r   r   ZnumpynpZ
tensorflowr6   Zactivations_tfr	   Zmodeling_tf_outputsr
   r   r   r   r   r   r   r   r   Zmodeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   Ztf_utilsr    r!   r"   utilsr#   r$   r%   r&   r'   r(   Zconfiguration_bertr*   Z
get_loggerr>   rD  r'  r(  r_  r`  ra  rj  rm  rn  rk  rl  rZ  r[  r\  r-   rO   ZLayerrB   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  ZBERT_START_DOCSTRINGr%  r  r)  r@  rM  rO  rQ  r]  r^  rb  r;   r;   r;   r<   <module>   s   ,< 
S 3gN%0 I
*8Mw` 	Y[h_