o
    ZhH                    @  s  d Z ddlmZ ddlZddlmZ ddl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 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% dd
l&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 e/3e4Z5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBG dd dZCG dd de#jDjEZFG dd  d e#jDjGZHG d!d" d"e#jDjEZIeHeId#ZJG d$d% d%e#jDjEZKG d&d' d'e#jDjEZLG d(d) d)e#jDjEZMG d*d+ d+e#jDjEZNG d,d- d-e#jDjEZOG d.d/ d/e#jDjEZPG d0d1 d1e#jDjEZQG d2d3 d3e#jDjEZRG d4d5 d5e#jDjEZSG d6d7 d7e#jDjEZTG d8d9 d9e#jDjEZUG d:d; d;e#jDjEZVG d<d= d=e#jDjEZWG d>d? d?e#jDjEZXG d@dA dAe#jDjEZYG dBdC dCe#jDjEZZe$G dDdE dEe#jDjEZ[G dFdG dGeZ\eG dHdI dIe+Z]dJZ^dKZ_e-dLe^G dMdN dNe\Z`e-dOe^G dPdQ dQe\eCZae-dRe^G dSdT dTe\eZbG dUdV dVe#jDjEZce-dWe^G dXdY dYe\eZde-dZe^G d[d\ d\e\e Zee-d]e^G d^d_ d_e\eZfe-d`e^G dadb dbe\eZge-dce^G ddde dee\e!Zhg dfZidS )gzTF 2.0 MobileBERT model.    )annotationsN)	dataclass)OptionalTupleUnion   )get_tf_activation)TFBaseModelOutputTFBaseModelOutputWithPoolingTFMaskedLMOutputTFMultipleChoiceModelOutputTFNextSentencePredictorOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)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   )MobileBertConfigzgoogle/mobilebert-uncasedr'   z"vumichien/mobilebert-finetuned-nerzK['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']gQ?z%vumichien/mobilebert-uncased-squad-v2z'a nice puppet'gףp=
@      zvumichien/emo-mobilebertz'others'z4.72c                   @  s   e Zd ZdZd	ddZdS )
TFMobileBertPreTrainingLossz
    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.
    labels	tf.Tensor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castr0   Z
reduce_sumreshape)selfr+   r-   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 r8   d/var/www/auris/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_tf_mobilebert.pyhf_compute_loss_   s   z+TFMobileBertPreTrainingLoss.hf_compute_lossN)r+   r,   r-   r,   r.   r,   )__name__
__module____qualname____doc__r:   r8   r8   r8   r9   r*   X   s    r*   c                      .   e Zd Z fddZdd ZdddZ  ZS )	TFMobileBertIntermediatec                   sR   t  jdi | tjj|jdd| _t|jt	r t
|j| _n|j| _|| _d S )Ndensenamer8   )super__init__r   layersDenseintermediate_sizerA   
isinstance
hidden_actstrr   intermediate_act_fnconfigr7   rM   kwargs	__class__r8   r9   rE   u   s   
z!TFMobileBertIntermediate.__init__c                 C  s   |  |}| |}|S N)rA   rL   r7   hidden_statesr8   r8   r9   call   s   

zTFMobileBertIntermediate.callNc                 C  n   | j rd S d| _ t| dd d ur5t| jj | jd d | jjg W d    d S 1 s.w   Y  d S d S NTrA   )	builtgetattrr3   
name_scoperA   rC   buildrM   true_hidden_sizer7   input_shaper8   r8   r9   r[         "zTFMobileBertIntermediate.buildrR   r;   r<   r=   rE   rU   r[   __classcell__r8   r8   rP   r9   r@   t   s    r@   c                      s*   e Zd Z fddZd fdd	Z  ZS )TFLayerNormc                   s   || _ t j|i | d S rR   )	feat_sizerD   rE   )r7   rc   argsrO   rP   r8   r9   rE      s   zTFLayerNorm.__init__Nc                   s   t  d d | jg d S rR   )rD   r[   rc   r]   rP   r8   r9   r[      s   zTFLayerNorm.buildrR   )r;   r<   r=   rE   r[   ra   r8   r8   rP   r9   rb      s    rb   c                      s4   e Zd Zd
 fdd	Z fddZddd	Z  ZS )TFNoNormNc                   s   t  jdi | || _d S )Nr8   )rD   rE   rc   )r7   rc   epsilonrO   rP   r8   r9   rE      s   
zTFNoNorm.__init__c                   s<   | j d| jgdd| _| j d| jgdd| _t | d S )Nbiaszeros)shapeinitializerweightZones)
add_weightrc   rg   rk   rD   r[   r]   rP   r8   r9   r[      s   zTFNoNorm.buildinputsr,   c                 C  s   || j  | j S rR   )rk   rg   )r7   rm   r8   r8   r9   rU      s   zTFNoNorm.callrR   )rm   r,   )r;   r<   r=   rE   r[   rU   ra   r8   r8   rP   r9   re      s    re   )
layer_normZno_normc                      s4   e Zd ZdZ fddZd
ddZddd	Z  ZS )TFMobileBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                   s   t  jdi | |j| _|j| _|| _|j| _|j| _|j| _tj	j
|jdd| _t|j |j|jdd| _tj	j|jd| _| j| jrGdnd | _d S )	Nembedding_transformationrB   	LayerNormrf   rC   )Zrater   r&   r8   )rD   rE   trigram_inputembedding_sizerM   hidden_sizemax_position_embeddingsinitializer_ranger   rF   rG   rp   NORM2FNnormalization_typelayer_norm_epsrq   Dropouthidden_dropout_probdropoutembedded_input_sizerN   rP   r8   r9   rE      s   
zTFMobileBertEmbeddings.__init__Nc                 C  s  t d | jd| jj| jgt| jdd| _W d    n1 s"w   Y  t d | jd| jj	| j
gt| jdd| _W d    n1 sIw   Y  t d | jd| j| j
gt| jdd| _W d    n1 sow   Y  | jryd S d| _t| d	d d urt | jj | jd d | jg W d    n1 sw   Y  t| d
d d urt | jj | jd  W d    d S 1 sw   Y  d S d S )NZword_embeddingsrk   )rw   )rC   ri   rj   token_type_embeddings
embeddingsposition_embeddingsTrp   rq   )r3   rZ   rl   rM   
vocab_sizert   r   rw   rk   Ztype_vocab_sizeru   r   rv   r   rX   rY   rp   rC   r[   r~   rq   r]   r8   r8   r9   r[      sB   






"zTFMobileBertEmbeddings.buildFc           
   	   C  s4  |du r
|du r
J |durt || jj tj| j|d}t|dd }|du r0tj|dd}| jrUtj	t
|ddddf d|t
|ddddf dgd	d
}| js^| j| jkrc| |}|du rutjtjd|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.
        N)paramsindicesr   )dimsvaluer&   )r   r   )r   r&   r   )r   )r&   r   r      Zaxis)startlimit)rm   )rm   training)r   rM   r   r3   gatherrk   r   fillrs   concatpadrt   ru   rp   Zexpand_dimsranger   r   rq   r}   )
r7   	input_idsposition_idstoken_type_idsinputs_embedsr   r^   Zposition_embedsZtoken_type_embedsZfinal_embeddingsr8   r8   r9   rU      s2   	
zTFMobileBertEmbeddings.callrR   )NNNNF)r;   r<   r=   r>   rE   r[   rU   ra   r8   r8   rP   r9   ro      s
    
 ro   c                      :   e Zd Z fddZdd Z	dddZdd	d
Z  ZS )TFMobileBertSelfAttentionc                   s   t  jdi | |j|j dkrtd|j d|j |j| _|j| _|j|j dks/J t|j|j | _| j| 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| _|| _d S )	Nr   zThe hidden size (z6) is not a multiple of the number of attention heads (querykernel_initializerrC   keyr   r8   )rD   rE   ru   num_attention_heads
ValueErroroutput_attentionsintr\   attention_head_sizeall_head_sizer   rF   rG   r   rw   r   r   r   r{   Zattention_probs_dropout_probr}   rM   rN   rP   r8   r9   rE     s.   

z"TFMobileBertSelfAttention.__init__c                 C  s*   t ||d| j| jf}t j|g ddS )Nr   r   r   r&   r   perm)r3   r6   r   r   	transpose)r7   x
batch_sizer8   r8   r9   transpose_for_scores-  s   z.TFMobileBertSelfAttention.transpose_for_scoresFc                 C  s  t |d }| |}	| |}
| |}| |	|}| |
|}| ||}tj||dd}tjt |d |jd}|tj	
| }|d urStj||jd}|| }t|dd}| j||d}|d urh|| }t||}tj|g dd	}t||d| jf}|r||f}|S |f}|S )
Nr   T)Ztranspose_br   r/   r   r   r   r   )r   r   r   r   r   r3   matmulr5   r0   mathsqrtr   r}   r   r6   r   )r7   query_tensor
key_tensorvalue_tensorattention_mask	head_maskr   r   r   Zmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresZdkZattention_probsZcontext_layeroutputsr8   r8   r9   rU   2  s8   


zTFMobileBertSelfAttention.callNc                 C  s&  | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d ur\t| j	j | j	d d | jjg W d    n1 sWw   Y  t| dd d urt| j
j | j
d d | jjry| jjn| jjg W d    d S 1 sw   Y  d S d S )NTr   r   r   )rX   rY   r3   rZ   r   rC   r[   rM   r\   r   r   use_bottleneck_attentionru   r]   r8   r8   r9   r[   _  s.   
"zTFMobileBertSelfAttention.buildFrR   )r;   r<   r=   rE   r   rU   r[   ra   r8   r8   rP   r9   r     s    
-r   c                      0   e Zd Z fddZd	ddZd
ddZ  ZS )TFMobileBertSelfOutputc                   sp   t  jdi | |j| _tjj|jt|jdd| _	t
|j |j|jdd| _| js3tj|j| _|| _d S )NrA   r   rq   rr   r8   )rD   rE   use_bottleneckr   rF   rG   r\   r   rw   rA   rx   ry   rz   rq   r{   r|   r}   rM   rN   rP   r8   r9   rE   w  s   

zTFMobileBertSelfOutput.__init__Fc                 C  s0   |  |}| js| j||d}| || }|S Nr   )rA   r   r}   rq   )r7   rT   residual_tensorr   r8   r8   r9   rU     s
   
zTFMobileBertSelfOutput.callNc                 C     | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d urZt| j	j | j	d  W d    d S 1 sSw   Y  d S d S NTrA   rq   
rX   rY   r3   rZ   rA   rC   r[   rM   r\   rq   r]   r8   r8   r9   r[        "zTFMobileBertSelfOutput.buildr   rR   r`   r8   r8   rP   r9   r   v  s    
r   c                      r   )TFMobileBertAttentionc                   2   t  jdi | t|dd| _t|dd| _d S )Nr7   rB   outputr8   )rD   rE   r   r7   r   mobilebert_outputrN   rP   r8   r9   rE        zTFMobileBertAttention.__init__c                 C     t rR   NotImplementedError)r7   Zheadsr8   r8   r9   prune_heads     z!TFMobileBertAttention.prune_headsFc	              	   C  sB   | j |||||||d}	| j|	d ||d}
|
f|	dd   }|S )Nr   r   r&   )r7   r   )r7   r   r   r   layer_inputr   r   r   r   Zself_outputsattention_outputr   r8   r8   r9   rU     s   zTFMobileBertAttention.callNc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urUt| jj | jd  W d    d S 1 sNw   Y  d S d S )NTr7   r   )rX   rY   r3   rZ   r7   rC   r[   r   r]   r8   r8   r9   r[        "zTFMobileBertAttention.buildr   rR   )r;   r<   r=   rE   r   rU   r[   ra   r8   r8   rP   r9   r     s    
r   c                      r   )TFOutputBottleneckc                   sZ   t  jdi | tjj|jdd| _t|j |j|j	dd| _
tj|j| _|| _d S NrA   rB   rq   rr   r8   )rD   rE   r   rF   rG   ru   rA   rx   ry   rz   rq   r{   r|   r}   rM   rN   rP   r8   r9   rE     s   

zTFOutputBottleneck.__init__Fc                 C  s*   |  |}| j||d}| || }|S r   )rA   r}   rq   )r7   rT   r   r   layer_outputsr8   r8   r9   rU     s   
zTFOutputBottleneck.callNc                 C  r   r   r   r]   r8   r8   r9   r[     r   zTFOutputBottleneck.buildr   rR   r`   r8   r8   rP   r9   r     s    
	r   c                      r   )TFMobileBertOutputc                   s   t  jdi | |j| _tjj|jt|jdd| _	t
|j |j|jdd| _| js4tj|j| _nt|dd| _|| _d S )NrA   r   rq   rr   
bottleneckrB   r8   )rD   rE   r   r   rF   rG   r\   r   rw   rA   rx   ry   rz   rq   r{   r|   r}   r   r   rM   rN   rP   r8   r9   rE     s   

zTFMobileBertOutput.__init__Fc                 C  sN   |  |}| js| j||d}| || }|S | || }| ||}|S r   )rA   r   r}   rq   r   )r7   rT   Zresidual_tensor_1Zresidual_tensor_2r   r8   r8   r9   rU     s   
zTFMobileBertOutput.callNc                 C  s  | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d urWt| j	j | j	d  W d    n1 sRw   Y  t| dd d urt| j
j | j
d  W d    d S 1 sxw   Y  d S d S )NTrA   rq   r   )rX   rY   r3   rZ   rA   rC   r[   rM   rH   rq   r   r]   r8   r8   r9   r[     s    "zTFMobileBertOutput.buildr   rR   r`   r8   r8   rP   r9   r     s    

r   c                      r?   )	TFBottleneckLayerc                   J   t  jdi | tjj|jdd| _t|j |j|j	dd| _
|| _d S r   )rD   rE   r   rF   rG   Zintra_bottleneck_sizerA   rx   ry   rz   rq   rM   rN   rP   r8   r9   rE        

zTFBottleneckLayer.__init__c                 C  s   |  |}| |}|S rR   rA   rq   )r7   rm   rT   r8   r8   r9   rU     s   

zTFBottleneckLayer.callNc                 C  r   r   
rX   rY   r3   rZ   rA   rC   r[   rM   ru   rq   r]   r8   r8   r9   r[     r   zTFBottleneckLayer.buildrR   r`   r8   r8   rP   r9   r         r   c                      r?   )	TFBottleneckc                   sL   t  jdi | |j| _|j| _t|dd| _| jr$t|dd| _d S d S )NinputrB   	attentionr8   )rD   rE   key_query_shared_bottleneckr   r   bottleneck_inputr   rN   rP   r8   r9   rE     s   zTFBottleneck.__init__c                 C  sB   |  |}| jr|fd S | jr| |}||||fS ||||fS )N   )r   r   r   r   )r7   rT   Zbottlenecked_hidden_statesZshared_attention_inputr8   r8   r9   rU   '  s   


zTFBottleneck.callNc                 C  r   )NTr   r   )rX   rY   r3   rZ   r   rC   r[   r   r]   r8   r8   r9   r[   A  r   zTFBottleneck.buildrR   r`   r8   r8   rP   r9   r     s    r   c                      r?   )	TFFFNOutputc                   r   r   )rD   rE   r   rF   rG   r\   rA   rx   ry   rz   rq   rM   rN   rP   r8   r9   rE   N  r   zTFFFNOutput.__init__c                 C  s   |  |}| || }|S rR   r   )r7   rT   r   r8   r8   r9   rU   V  s   
zTFFFNOutput.callNc                 C  r   r   )
rX   rY   r3   rZ   rA   rC   r[   rM   rH   rq   r]   r8   r8   r9   r[   [  r   zTFFFNOutput.buildrR   r`   r8   r8   rP   r9   r   M  r   r   c                      r?   )	
TFFFNLayerc                   r   )NintermediaterB   r   r8   )rD   rE   r@   r   r   r   rN   rP   r8   r9   rE   h  r   zTFFFNLayer.__init__c                 C  s   |  |}| ||}|S rR   )r   r   )r7   rT   intermediate_outputr   r8   r8   r9   rU   m  s   
zTFFFNLayer.callNc                 C  r   )NTr   r   )rX   rY   r3   rZ   r   rC   r[   r   r]   r8   r8   r9   r[   r  r   zTFFFNLayer.buildrR   r`   r8   r8   rP   r9   r   g  s    r   c                      r   )TFMobileBertLayerc                   s   t  jd	i |  j| _ j| _t dd| _t dd| _t dd| _	| jr0t
 dd| _ jdkrF fddt jd D | _d S d S )
Nr   rB   r   r   r   r&   c                      g | ]}t  d | dqS )zffn.rB   )r   .0irM   r8   r9   
<listcomp>      z.TFMobileBertLayer.__init__.<locals>.<listcomp>r8   )rD   rE   r   num_feedforward_networksr   r   r@   r   r   r   r   r   r   ffnrN   rP   r   r9   rE     s   
"zTFMobileBertLayer.__init__Fc              
   C  s   | j r| |\}}}}	n	|gd \}}}}	| j||||	||||d}
|
d }|f}| jdkrBt| jD ]\}}||}||f7 }q4| |}| j||||d}|f|
dd   t	d||||	||f | }|S )Nr   r   r   r&   )
r   r   r   r   	enumerater   r   r   r3   constant)r7   rT   r   r   r   r   r   r   r   r   Zattention_outputsr   sr   Z
ffn_moduler   Zlayer_outputr   r8   r8   r9   rU     sJ   


zTFMobileBertLayer.callNc              	   C  s  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urwt| jj | jd  W d    n1 srw   Y  t| dd d urt| j	j | j	d  W d    n1 sw   Y  t| dd d ur| j
D ]}t|j |d  W d    n1 sw   Y  qd S d S )NTr   r   r   r   r   )rX   rY   r3   rZ   r   rC   r[   r   r   r   r   r7   r^   layerr8   r8   r9   r[     s6   
zTFMobileBertLayer.buildr   rR   r`   r8   r8   rP   r9   r   ~  s    
-r   c                      s2   e Zd Z fddZ	d	ddZd
ddZ  ZS )TFMobileBertEncoderc                   s@   t  jdi |  j| _ j| _ fddt jD | _d S )Nc                   r   )zlayer_._rB   )r   r   r   r8   r9   r     r   z0TFMobileBertEncoder.__init__.<locals>.<listcomp>r8   )rD   rE   r   output_hidden_statesr   num_hidden_layersr   rN   rP   r   r9   rE     s   zTFMobileBertEncoder.__init__Fc                 C  s   |rdnd }|r
dnd }	t | jD ]#\}
}|r||f }|||||
 ||d}|d }|r4|	|d f }	q|r<||f }|sJtdd |||	fD S t|||	dS )Nr8   r   r   r&   c                 s  s    | ]	}|d ur|V  qd S rR   r8   )r   vr8   r8   r9   	<genexpr>  s    z+TFMobileBertEncoder.call.<locals>.<genexpr>)last_hidden_staterT   
attentions)r   r   tupler	   )r7   rT   r   r   r   r   return_dictr   Zall_hidden_statesZall_attentionsr   Zlayer_moduler   r8   r8   r9   rU     s&   


zTFMobileBertEncoder.callNc              	   C  sj   | j rd S d| _ t| dd d ur1| jD ]}t|j |d  W d    n1 s+w   Y  qd S d S )NTr   )rX   rY   r   r3   rZ   rC   r[   r   r8   r8   r9   r[     s   
zTFMobileBertEncoder.buildr   rR   r`   r8   r8   rP   r9   r     s
    
#r   c                      r?   )	TFMobileBertPoolerc                   sH   t  jdi | |j| _| jrtjj|jt|j	ddd| _
|| _d S )NtanhrA   )r   Z
activationrC   r8   )rD   rE   Zclassifier_activationdo_activater   rF   rG   ru   r   rw   rA   rM   rN   rP   r8   r9   rE     s   
zTFMobileBertPooler.__init__c                 C  s(   |d d df }| j s|S | |}|S Nr   )r   rA   )r7   rT   Zfirst_token_tensorpooled_outputr8   r8   r9   rU     s
   
zTFMobileBertPooler.callNc                 C  rV   rW   )	rX   rY   r3   rZ   rA   rC   r[   rM   ru   r]   r8   r8   r9   r[     r_   zTFMobileBertPooler.buildrR   r`   r8   r8   rP   r9   r     s    
r   c                      r?   )	#TFMobileBertPredictionHeadTransformc                   sr   t  jdi | tjj|jt|jdd| _t	|j
tr$t|j
| _n|j
| _td |j|jdd| _|| _d S )NrA   r   rn   rq   rr   r8   )rD   rE   r   rF   rG   ru   r   rw   rA   rI   rJ   rK   r   transform_act_fnrx   rz   rq   rM   rN   rP   r8   r9   rE   $  s   
z,TFMobileBertPredictionHeadTransform.__init__c                 C  s"   |  |}| |}| |}|S rR   )rA   r   rq   rS   r8   r8   r9   rU   0  s   


z(TFMobileBertPredictionHeadTransform.callNc                 C  r   r   r   r]   r8   r8   r9   r[   6  r   z)TFMobileBertPredictionHeadTransform.buildrR   r`   r8   r8   rP   r9   r   #  s    r   c                      sN   e Zd Z fddZdddZdd Zdd	 Zd
d Zdd Zdd Z	  Z
S )TFMobileBertLMPredictionHeadc                   s*   t  jdi | t|dd| _|| _d S )N	transformrB   r8   )rD   rE   r   r  rM   rN   rP   r8   r9   rE   C  s   
z%TFMobileBertLMPredictionHead.__init__Nc                 C  s   | j | jjfdddd| _| j | jj| jj | jjfdddd| _| j | jj| jjfdddd| _| jr6d S d| _t	| dd d urat
| jj | jd  W d    d S 1 sZw   Y  d S d S )Nrh   Trg   )ri   rj   Z	trainablerC   zdense/weightzdecoder/weightr  )rl   rM   r   rg   ru   rt   rA   decoderrX   rY   r3   rZ   r  rC   r[   r]   r8   r8   r9   r[   H  s*   "z"TFMobileBertLMPredictionHead.buildc                 C  s   | S rR   r8   r7   r8   r8   r9   get_output_embeddings^  r   z2TFMobileBertLMPredictionHead.get_output_embeddingsc                 C  s   || _ t|d | j_d S r   )r  r   rM   r   r7   r   r8   r8   r9   set_output_embeddingsa  s   z2TFMobileBertLMPredictionHead.set_output_embeddingsc                 C  s
   d| j iS )Nrg   )rg   r  r8   r8   r9   get_biase  s   
z%TFMobileBertLMPredictionHead.get_biasc                 C  s"   |d | _ t|d d | j_d S )Nrg   r   )rg   r   rM   r   r  r8   r8   r9   set_biash  s   
z%TFMobileBertLMPredictionHead.set_biasc                 C  s<   |  |}t|tjt| j| jgdd}|| j }|S )Nr   r   )r  r3   r   r   r   r  rA   rg   rS   r8   r8   r9   rU   l  s   
$
z!TFMobileBertLMPredictionHead.callrR   )r;   r<   r=   rE   r[   r  r  r  r	  rU   ra   r8   r8   rP   r9   r  B  s    
r  c                      r?   )	TFMobileBertMLMHeadc                   s$   t  jdi | t|dd| _d S )NpredictionsrB   r8   )rD   rE   r  r  rN   rP   r8   r9   rE   t  s   zTFMobileBertMLMHead.__init__c                 C     |  |}|S rR   r  )r7   sequence_outputprediction_scoresr8   r8   r9   rU   x     
zTFMobileBertMLMHead.callNc                 C  d   | j rd S d| _ t| dd d ur0t| jj | jd  W d    d S 1 s)w   Y  d S d S )NTr  )rX   rY   r3   rZ   r  rC   r[   r]   r8   r8   r9   r[   |     "zTFMobileBertMLMHead.buildrR   r`   r8   r8   rP   r9   r
  s  s    r
  c                      sf   e Zd ZeZd fdd	Zdd Zdd Zdd	 Ze		
	
	
	
	
	
	
	
	
	dddZ
dddZ  ZS )TFMobileBertMainLayerTc                   st   t  jdi | || _|j| _|j| _|j| _|j| _t|dd| _	t
|dd| _|r5t|dd| _d S d | _d S )Nr   rB   encoderpoolerr8   )rD   rE   rM   r   r   r   Zuse_return_dictr   ro   r   r   r  r   r  )r7   rM   add_pooling_layerrO   rP   r8   r9   rE     s    zTFMobileBertMainLayer.__init__c                 C  s   | j S rR   )r   r  r8   r8   r9   get_input_embeddings  s   z*TFMobileBertMainLayer.get_input_embeddingsc                 C  s   || j _t|d | j _d S r   )r   rk   r   r   r  r8   r8   r9   set_input_embeddings  s   z*TFMobileBertMainLayer.set_input_embeddingsc                 C  r   )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
        r   )r7   Zheads_to_pruner8   r8   r9   _prune_heads  s   z"TFMobileBertMainLayer._prune_headsNFc              	   C  sd  |d ur|d urt d|d urt|}n|d ur"t|d d }nt d|d u r0t|d}|d u r:t|d}| j|||||
d}t||d dd|d f}tj||jd}tjd|jd}tjd	|jd}t	t
|||}|d urztd g| j }| j||||||	|
d}|d }| jd ur| |nd }|	s||f|dd   S t|||j|jd
S )NzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr&   r   r   r/   g      ?g     )r   Zpooler_outputrT   r   )r   r   r3   r   r   r6   r5   r0   r   multiplysubtractr   r   r  r  r
   rT   r   )r7   r   r   r   r   r   r   r   r   r   r   r^   Zembedding_outputZextended_attention_maskZone_cstZten_thousand_cstZencoder_outputsr  r   r8   r8   r9   rU     sV   


zTFMobileBertMainLayer.callc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urzt| jj | jd  W d    d S 1 ssw   Y  d S d S )NTr   r  r  )	rX   rY   r3   rZ   r   rC   r[   r  r  r]   r8   r8   r9   r[         "zTFMobileBertMainLayer.build)T
NNNNNNNNNFrR   )r;   r<   r=   r'   config_classrE   r  r  r  r   rU   r[   ra   r8   r8   rP   r9   r    s&    Sr  c                   @  s   e Zd ZdZeZdZdS )TFMobileBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    
mobilebertN)r;   r<   r=   r>   r'   r  Zbase_model_prefixr8   r8   r8   r9   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 ) TFMobileBertForPreTrainingOutputaE  
    Output type of [`TFMobileBertForPreTraining`].

    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.
    Nztf.Tensor | NonelosszOptional[tf.Tensor]prediction_logitsseq_relationship_logitszTuple[tf.Tensor] | NonerT   r   )
r;   r<   r=   r>   r#  __annotations__r$  r%  rT   r   r8   r8   r8   r9   r"    s   
 r"  a	  

    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>

    Parameters:
        config ([`MobileBertConfig`]): 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.
a  
    Args:
        input_ids (`Numpy array` or `tf.Tensor` of 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 (`Numpy array` 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 (`Numpy array` 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 (`Numpy array` 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 (`Numpy array` 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 (`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).
zdThe bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.c                      sf   e Zd Z fddZeeedee	e
ed										ddddZdddZ  ZS )TFMobileBertModelc                   s,   t  j|g|R i | t|dd| _d S )Nr!  rB   )rD   rE   r  r!  r7   rM   rm   rO   rP   r8   r9   rE     s   zTFMobileBertModel.__init__batch_size, sequence_length
checkpointoutput_typer  NFr   TFModelInputType | Noner   np.ndarray | tf.Tensor | Noner   r   r   r   r   Optional[bool]r   r   r   r.   *Union[Tuple, TFBaseModelOutputWithPooling]c                 C  s"   | j |||||||||	|
d
}|S )N)
r   r   r   r   r   r   r   r   r   r   )r!  )r7   r   r   r   r   r   r   r   r   r   r   r   r8   r8   r9   rU     s   zTFMobileBertModel.callc                 C  r  )NTr!  )rX   rY   r3   rZ   r!  rC   r[   r]   r8   r8   r9   r[     r  zTFMobileBertModel.buildr  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r   r/  r.   r0  rR   )r;   r<   r=   rE   r   r#   MOBILEBERT_INPUTS_DOCSTRINGformatr!   _CHECKPOINT_FOR_DOCr
   _CONFIG_FOR_DOCrU   r[   ra   r8   r8   rP   r9   r'    s*    r'  z
    MobileBert 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 fddZdd Zdd Zeee	de
eed																							
d"d#ddZd$ddZd d! Z  ZS )%TFMobileBertForPreTrainingc                   sH   t  j|g|R i | t|dd| _t|dd| _t|dd| _d S )Nr!  rB   predictions___clsseq_relationship___cls)rD   rE   r  r!  r
  r  TFMobileBertOnlyNSPHeadseq_relationshipr(  rP   r8   r9   rE     s   z#TFMobileBertForPreTraining.__init__c                 C     | j j S rR   r  r  r8   r8   r9   get_lm_head     z&TFMobileBertForPreTraining.get_lm_headc                 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FutureWarningrC   r  r  r8   r8   r9   get_prefix_bias_name      z/TFMobileBertForPreTraining.get_prefix_bias_namer)  r,  r  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   r+   r1   r   r.   .Union[Tuple, TFMobileBertForPreTrainingOutput]c                 C  s   | j |||||||||	|d
}|dd \}}| |}| |}d}|
dur<|dur<d|
i}||d< | j|||fd}|	sS||f|dd  }|durQ|f| S |S t||||j|jdS )a9  
        Return:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
        >>> model = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
        >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :]  # Batch size 1
        >>> outputs = model(input_ids)
        >>> prediction_scores, seq_relationship_scores = outputs[:2]
        ```	r   r   r   r   r   r   r   r   r   Nr   r+   r1   r+   r-   )r#  r$  r%  rT   r   )r!  r  r9  r:   r"  rT   r   )r7   r   r   r   r   r   r   r   r   r   r+   r1   r   r   r  r   r  seq_relationship_scoreZ
total_lossZd_labelsr   r8   r8   r9   rU     s<   !

zTFMobileBertForPreTraining.callc                 C  r  )NTr!  r  r9  )	rX   rY   r3   rZ   r!  rC   r[   r  r9  r]   r8   r8   r9   r[      r  z TFMobileBertForPreTraining.buildc                 C     |dkr|dfS |fS Nzcls.predictions.decoder.weightz,mobilebert.embeddings.word_embeddings.weightr8   r7   Z	tf_weightr8   r8   r9   tf_to_pt_weight_rename.     z1TFMobileBertForPreTraining.tf_to_pt_weight_renameNNNNNNNNNNNF)r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r+   r.  r1   r.  r   r/  r.   rE  rR   )r;   r<   r=   rE   r;  rB  r   r#   r1  r2  r%   r"  r4  rU   r[   rL  ra   r8   r8   rP   r9   r5    s,    

Ar5  z8MobileBert Model with a `language modeling` head on top.c                	      s   e Zd Zg dZ fddZdd Zdd Zeee	
deeeed	d
d											d$d%ddZd&d d!Zd"d# Z  ZS )'TFMobileBertForMaskedLM)r  r7  cls.seq_relationshipc                   s<   t  j|g|R i | t|ddd| _t|dd| _d S )NFr!  r  rC   r6  rB   )rD   rE   r  r!  r
  r  r(  rP   r8   r9   rE   >  s   z TFMobileBertForMaskedLM.__init__c                 C  r:  rR   r  r  r8   r8   r9   r;  D  r<  z#TFMobileBertForMaskedLM.get_lm_headc                 C  s,   t dt | jd | jj d | jjj S r=  )r?  r@  rA  rC   Zmlmr  r  r8   r8   r9   rB  G  rC  z,TFMobileBertForMaskedLM.get_prefix_bias_namer)  z'paris'g=
ףp=?r+  r,  r  expected_outputexpected_lossNFr   r-  r   r.  r   r   r   r   r   r/  r   r   r+   r   r.   Union[Tuple, TFMaskedLMOutput]c                 C  s   | j |||||||||	|d
}|d }| j||d}|
du r dn| |
|}|	s<|f|dd  }|dur:|f| S |S t|||j|jdS )az  
        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
        rF  r   r   Nr   r#  r-   rT   r   )r!  r  r:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   r+   r   r   r  r  r#  r   r8   r8   r9   rU   K  s0   zTFMobileBertForMaskedLM.callc                 C  r   )NTr!  r  )rX   rY   r3   rZ   r!  rC   r[   r  r]   r8   r8   r9   r[     r   zTFMobileBertForMaskedLM.buildc                 C  rI  rJ  r8   rK  r8   r8   r9   rL    rM  z.TFMobileBertForMaskedLM.tf_to_pt_weight_renameNNNNNNNNNNF)r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r+   r.  r   r/  r.   rU  rR   )r;   r<   r=   "_keys_to_ignore_on_load_unexpectedrE   r;  rB  r   r#   r1  r2  r!   r3  r   r4  rU   r[   rL  ra   r8   r8   rP   r9   rO  5  s8    	
0rO  c                      r?   )	r8  c                   s.   t  jdi | tjjddd| _|| _d S )Nr   r9  rB   r8   )rD   rE   r   rF   rG   r9  rM   rN   rP   r8   r9   rE     s   
z TFMobileBertOnlyNSPHead.__init__c                 C  r  rR   )r9  )r7   r   rH  r8   r8   r9   rU     r  zTFMobileBertOnlyNSPHead.callNc                 C  rV   )NTr9  )	rX   rY   r3   rZ   r9  rC   r[   rM   ru   r]   r8   r8   r9   r[     r_   zTFMobileBertOnlyNSPHead.buildrR   r`   r8   r8   rP   r9   r8    s    r8  zPMobileBert Model with a `next sentence prediction (classification)` head on top.c                      sn   e Zd ZddgZ fddZeeede	e
ed											ddddZdddZ  ZS ) %TFMobileBertForNextSentencePredictionr6  cls.predictionsc                   s:   t  j|g|R i | t|dd| _t|dd| _d S )Nr!  rB   r7  )rD   rE   r  r!  r8  clsr(  rP   r8   r9   rE     s   z.TFMobileBertForNextSentencePrediction.__init__r)  rD  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   r1   r   r.   +Union[Tuple, TFNextSentencePredictorOutput]c                 C  s   | j |||||||||	|d
}|d }| |}|
du rdn| j|
|d}|	s;|f|dd  }|dur9|f| S |S t|||j|jdS )a  
        Return:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
        >>> model = TFMobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-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]
        ```rF  r&   NrG  r   rV  )r!  r[  r:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   r1   r   r   r   Zseq_relationship_scoresZnext_sentence_lossr   r8   r8   r9   rU     s6   #
z*TFMobileBertForNextSentencePrediction.callc                 C  r   )NTr!  r[  )rX   rY   r3   rZ   r!  rC   r[   r[  r]   r8   r8   r9   r[     r   z+TFMobileBertForNextSentencePrediction.buildrW  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r1   r.  r   r/  r.   r\  rR   )r;   r<   r=   rX  rE   r   r#   r1  r2  r%   r   r4  rU   r[   ra   r8   r8   rP   r9   rY    s&    
@rY  z
    MobileBert 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                	      z   e Zd Zg dZdgZ fddZeee	de
eeeeed											ddddZdddZ  ZS ) %TFMobileBertForSequenceClassificationr6  r7  rZ  rP  r}   c                   sz   t  j|g|R i | |j| _t|dd| _|jd ur |jn|j}tj	|| _
tjj|jt|jdd| _|| _d S )Nr!  rB   
classifierr   rD   rE   
num_labelsr  r!  classifier_dropoutr|   r   rF   r{   r}   rG   r   rw   r`  rM   r7   rM   rm   rO   rc  rP   r8   r9   rE     s   
z.TFMobileBertForSequenceClassification.__init__r)  rR  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   r+   r   r.   (Union[Tuple, TFSequenceClassifierOutput]c                 C     | j |||||||||	|d
}|d }| j||d}| |}|
du r%dn| |
|}|	sA|f|dd  }|dur?|f| S |S t|||j|jdS )a  
        labels (`tf.Tensor` 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).
        rF  r&   r   Nr   rV  )r!  r}   r`  r:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   r+   r   r   r   r-   r#  r   r8   r8   r9   rU   %  s2   
z*TFMobileBertForSequenceClassification.callc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urZt| jj | jd d | jj	g W d    d S 1 sSw   Y  d S d S NTr!  r`  
rX   rY   r3   rZ   r!  rC   r[   r`  rM   ru   r]   r8   r8   r9   r[   `     "z+TFMobileBertForSequenceClassification.buildrW  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r+   r.  r   r/  r.   re  rR   )r;   r<   r=   rX  _keys_to_ignore_on_load_missingrE   r   r#   r1  r2  r!   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r4  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSrU   r[   ra   r8   r8   rP   r9   r^    s4    		2r^  z
    MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
    linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                      sz   e Zd Zg dZ fddZeeede	e
eeeeeed												ddddZdddZ  ZS )  TFMobileBertForQuestionAnsweringr  r6  r7  rZ  rP  c                   sX   t  j|g|R i | |j| _t|ddd| _tjj|jt|j	dd| _
|| _d S )NFr!  rQ  
qa_outputsr   )rD   rE   rb  r  r!  r   rF   rG   r   rw   rq  rM   r(  rP   r8   r9   rE   }  s   
z)TFMobileBertForQuestionAnswering.__init__r)  )r+  r,  r  Zqa_target_start_indexZqa_target_end_indexrS  rT  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   start_positionsend_positionsr   r.   ,Union[Tuple, TFQuestionAnsweringModelOutput]c                 C  s   | j |||||||||	|d
}|d }| |}tj|ddd\}}tj|dd}tj|dd}d}|
durG|durG|
|d}| |||f}|	s^||f|dd  }|dur\|f| S |S t||||j|jdS )	a  
        start_positions (`tf.Tensor` 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` 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.
        rF  r   r   r   r   N)Zstart_positionZend_position)r#  start_logits
end_logitsrT   r   )	r!  rq  r3   splitZsqueezer:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   rr  rs  r   r   r  r-   ru  rv  r#  r+   r   r8   r8   r9   rU     s>   $

z%TFMobileBertForQuestionAnswering.callc                 C  rg  )NTr!  rq  )
rX   rY   r3   rZ   r!  rC   r[   rq  rM   ru   r]   r8   r8   r9   r[     rj  z&TFMobileBertForQuestionAnswering.buildrN  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  rr  r.  rs  r.  r   r/  r.   rt  rR   )r;   r<   r=   rX  rE   r   r#   r1  r2  r!   _CHECKPOINT_FOR_QAr   r4  _QA_TARGET_START_INDEX_QA_TARGET_END_INDEX_QA_EXPECTED_OUTPUT_QA_EXPECTED_LOSSrU   r[   ra   r8   r8   rP   r9   ro  l  s8    	
=ro  z
    MobileBert 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                      sv   e Zd Zg dZdgZ fddZeee	de
eeed											ddddZdddZ  ZS ) TFMobileBertForMultipleChoicer_  r}   c                   s\   t  j|g|R i | t|dd| _tj|j| _tjj	dt
|jdd| _|| _d S )Nr!  rB   r&   r`  r   )rD   rE   r  r!  r   rF   r{   r|   r}   rG   r   rw   r`  rM   r(  rP   r8   r9   rE     s   
z&TFMobileBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr*  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   r+   r   r.   )Union[Tuple, TFMultipleChoiceModelOutput]c                 C  sv  |durt |d }t |d }nt |d }t |d }|dur)t|d|fnd}|dur7t|d|fnd}|durEt|d|fnd}|durSt|d|fnd}|durft|d|t |d fnd}| j|||||||||	|d
}|d }| j||d}| |}t|d|f}|
du rdn| |
|}|	s|f|dd  }|dur|f| S |S t|||j|j	dS )	a5  
        labels (`tf.Tensor` 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   r   r   )r   r   r   rV  )
r   r3   r6   r!  r}   r`  r:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   r+   r   Znum_choicesZ
seq_lengthZflat_input_idsZflat_attention_maskZflat_token_type_idsZflat_position_idsZflat_inputs_embedsr   r   r-   Zreshaped_logitsr#  r   r8   r8   r9   rU     sN   
z"TFMobileBertForMultipleChoice.callc                 C  rg  rh  ri  r]   r8   r8   r9   r[   @  rj  z#TFMobileBertForMultipleChoice.buildrW  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r+   r.  r   r/  r.   r~  rR   )r;   r<   r=   rX  rk  rE   r   r#   r1  r2  r!   r3  r   r4  rU   r[   ra   r8   r8   rP   r9   r}    s4    	
Ar}  z
    MobileBert 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                	      r]  ) "TFMobileBertForTokenClassificationrp  r}   c                   s|   t  j|g|R i | |j| _t|ddd| _|jd ur!|jn|j}tj	|| _
tjj|jt|jdd| _|| _d S )NFr!  rQ  r`  r   ra  rd  rP   r8   r9   rE   ^  s   
z+TFMobileBertForTokenClassification.__init__r)  rR  NFr   r-  r   r.  r   r   r   r   r   r/  r   r   r+   r   r.   %Union[Tuple, TFTokenClassifierOutput]c                 C  rf  )z
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        rF  r   r   Nr   rV  )r!  r}   r`  r:   r   rT   r   )r7   r   r   r   r   r   r   r   r   r   r+   r   r   r  r-   r#  r   r8   r8   r9   rU   l  s2   
z'TFMobileBertForTokenClassification.callc                 C  rg  rh  ri  r]   r8   r8   r9   r[     rj  z(TFMobileBertForTokenClassification.buildrW  )r   r-  r   r.  r   r.  r   r.  r   r.  r   r.  r   r/  r   r/  r   r/  r+   r.  r   r/  r.   r  rR   )r;   r<   r=   rX  rk  rE   r   r#   r1  r2  r!   $_CHECKPOINT_FOR_TOKEN_CLASSIFICATIONr   r4  _TOKEN_CLASS_EXPECTED_OUTPUT_TOKEN_CLASS_EXPECTED_LOSSrU   r[   ra   r8   r8   rP   r9   r  L  s4    		0r  )
rO  r}  rY  r5  ro  r^  r  r  r'  r   )jr>   
__future__r   r?  dataclassesr   typingr   r   r   numpynpZ
tensorflowr3   Zactivations_tfr   Zmodeling_tf_outputsr	   r
   r   r   r   r   r   r   Zmodeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   r   Ztf_utilsr   r   r   utilsr    r!   r"   r#   r$   r%   Zconfiguration_mobilebertr'   Z
get_loggerr;   loggerr3  r4  r  r  r  rx  r{  r|  ry  rz  rl  rm  rn  r*   rF   ZLayerr@   ZLayerNormalizationrb   re   rx   ro   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r  r   r"  ZMOBILEBERT_START_DOCSTRINGr1  r'  r5  rO  r8  rY  r^  ro  r}  r  __all__r8   r8   r8   r9   <module>   s   (8
 
	
he!()/Q4 1 
*81g`Y_hj^