U
    4Af1                    @  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
 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 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.m/Z/ ddl0m1Z1 e.2e3Z4dZ5dZ6G dd de"j7j8Z9G dd de"j7j8Z:G dd de"j7j8Z;G dd de"j7j8Z<G dd de"j7j8Z=G dd de"j7j8Z>G dd de"j7j8Z?G dd de"j7j8Z@G d d! d!e"j7j8ZAG d"d# d#e"j7j8ZBG d$d% d%e"j7j8ZCG d&d' d'eZDe#G d(d) d)e"j7j8ZEeG d*d+ d+e*ZFd,ZGd-ZHe,d.eGG d/d0 d0eDZIe,d1eGG d2d3 d3eDZJG d4d5 d5e"j7j8ZKe,d6eGG d7d8 d8eDeZLG d9d: d:e"j7j8ZMe,d;eGG d<d= d=eDeZNe,d>eGG d?d@ d@eDeZOe,dAeGG dBdC dCeDe ZPe,dDeGG dEdF dFeDeZQdS )GzTF Electra model.    )annotationsN)	dataclass)OptionalTupleUnion   )get_tf_activation)+TFBaseModelOutputWithPastAndCrossAttentionsTFMaskedLMOutputTFMultipleChoiceModelOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)TFMaskedLanguageModelingLossTFModelInputTypeTFMultipleChoiceLossTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFSequenceSummary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   )ElectraConfigz"google/electra-small-discriminatorr%   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 )TFElectraSelfAttentionr%   configc                   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_initializernamekeyvalueZrate)super__init__hidden_sizenum_attention_heads
ValueErrorintattention_head_sizeall_head_sizemathsqrtsqrt_att_head_sizer   layersDenser   initializer_ranger*   r/   r0   DropoutZattention_probs_dropout_probdropout
is_decoderr(   selfr(   kwargs	__class__ S/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/electra/modeling_tf_electra.pyr3   F   s6          zTFElectraSelfAttention.__init__	tf.Tensorr7   )tensor
batch_sizereturnc                 C  s0   t j||d| j| jfd}t j|ddddgdS )NrK   shaper      r$   r   perm)tfreshaper5   r8   	transpose)rD   rK   rL   rH   rH   rI   transpose_for_scoresb   s    z+TFElectraSelfAttention.transpose_for_scoresFTuple[tf.Tensor]bool	hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionstrainingrM   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   inputsr$   rQ   axisT)transpose_bdtyperN   )logitsrf   rd   rb   r   rR   rO   )r   r*   rW   r/   r0   rT   concatrB   matmulcastr<   ri   divideaddr   rA   multiplyrV   rU   r9   )rD   r[   r\   r]   r^   r_   r`   ra   rb   rL   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerZattention_scoresZdkZattention_probsattention_outputoutputsrH   rH   rI   calli   sJ    


zTFElectraSelfAttention.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/   r0   )builtgetattrrT   
name_scoper*   r.   buildr(   r4   r/   r0   rD   input_shaperH   rH   rI   rx      s      zTFElectraSelfAttention.build)F)N)__name__
__module____qualname__r3   rW   rt   rx   __classcell__rH   rH   rF   rI   r&   E   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 )TFElectraSelfOutputr%   r'   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+   	LayerNormepsilonr.   r1   r2   r3   r   r=   r>   r4   r   r?   r   LayerNormalizationlayer_norm_epsr   r@   hidden_dropout_probrA   r(   rC   rF   rH   rI   r3      s      zTFElectraSelfOutput.__init__FrJ   rY   r[   input_tensorrb   rM   c                 C  s.   | j |d}| j||d}| j|| d}|S Nrc   rk   r   rA   r   rD   r[   r   rb   rH   rH   rI   rt      s    zTFElectraSelfOutput.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   r   )
ru   rv   rT   rw   r   r.   rx   r(   r4   r   ry   rH   rH   rI   rx      s     zTFElectraSelfOutput.build)F)Nr{   r|   r}   r3   rt   rx   r~   rH   rH   rF   rI   r      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 )TFElectraAttentionr%   r'   c                   s.   t  jf | t|dd| _t|dd| _d S )NrD   r.   output)r2   r3   r&   self_attentionr   dense_outputrC   rF   rH   rI   r3      s    zTFElectraAttention.__init__c                 C  s   t d S NNotImplementedError)rD   ZheadsrH   rH   rI   prune_heads   s    zTFElectraAttention.prune_headsFrJ   rX   rY   )	r   r\   r]   r^   r_   r`   ra   rb   rM   c	              
   C  sD   | j ||||||||d}	| j|	d ||d}
|
f|	dd   }|S )Nr[   r\   r]   r^   r_   r`   ra   rb   r   r[   r   rb   r$   )r   r   )rD   r   r\   r]   r^   r_   r`   ra   rb   Zself_outputsrr   rs   rH   rH   rI   rt      s"    
  zTFElectraAttention.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   )ru   rv   rT   rw   r   r.   rx   r   ry   rH   rH   rI   rx     s    zTFElectraAttention.build)F)N)r{   r|   r}   r3   r   rt   rx   r~   rH   rH   rF   rI   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 )TFElectraIntermediater%   r'   c                   sV   t  jf | tjj|jt|jdd| _t	|j
trDt|j
| _n|j
| _|| _d S )Nr   r+   )r2   r3   r   r=   r>   intermediate_sizer   r?   r   
isinstance
hidden_actstrr   intermediate_act_fnr(   rC   rF   rH   rI   r3     s      zTFElectraIntermediate.__init__rJ   r[   rM   c                 C  s   | j |d}| |}|S )Nrc   )r   r   )rD   r[   rH   rH   rI   rt   +  s    
zTFElectraIntermediate.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   	ru   rv   rT   rw   r   r.   rx   r(   r4   ry   rH   rH   rI   rx   1  s    zTFElectraIntermediate.build)Nr   rH   rH   rF   rI   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 )TFElectraOutputr%   r'   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   rC   rF   rH   rI   r3   <  s      zTFElectraOutput.__init__FrJ   rY   r   c                 C  s.   | j |d}| j||d}| j|| d}|S r   r   r   rH   rH   rI   rt   F  s    zTFElectraOutput.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   )ru   rv   rT   rw   r   r.   rx   r(   r   r   r4   ry   rH   rH   rI   rx   M  s     zTFElectraOutput.build)F)Nr   rH   rH   rF   rI   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 )TFElectraLayerr%   r'   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   )r2   r3   r   r   rB   add_cross_attentionr6   r   r   r   r   bert_outputrC   rF   rH   rI   r3   [  s    zTFElectraLayer.__init__FrJ   tf.Tensor | NoneTuple[tf.Tensor] | NonerY   rX   rZ   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 )NrQ   )r   r\   r]   r^   r_   r`   ra   rb   r   r$   rN   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   rB   hasattrr6   r   r   r   )rD   r[   r\   r]   r^   r_   r`   ra   rb   Zself_attn_past_key_valueZself_attention_outputsrr   rs   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputsZintermediate_outputZlayer_outputrH   rH   rI   rt   h  s^    




  

zTFElectraLayer.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   )
ru   rv   rT   rw   r   r.   rx   r   r   r   ry   rH   rH   rI   rx     s    zTFElectraLayer.build)F)Nr   rH   rH   rF   rI   r   Z  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 )TFElectraEncoderr%   r'   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ir'   rH   rI   
<listcomp>  s     z-TFElectraEncoder.__init__.<locals>.<listcomp>)r2   r3   r(   rangenum_hidden_layerslayerrC   rF   r'   rI   r3     s    zTFElectraEncoder.__init__FrJ   r   zTuple[Tuple[tf.Tensor]] | NoneOptional[bool]rY   DUnion[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]])r[   r\   r]   r^   r_   past_key_values	use_cachera   output_hidden_statesreturn_dictrb   rM   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 )
NrH   r   r   rN   r$   rQ   c                 s  s   | ]}|d k	r|V  qd S r   rH   )r   vrH   rH   rI   	<genexpr>  s     z(TFElectraEncoder.call.<locals>.<genexpr>)Zlast_hidden_stater   r[   
attentionsZcross_attentions)r(   r   	enumerater   tupler	   )rD   r[   r\   r]   r^   r_   r   r   ra   r   r   rb   Zall_hidden_statesZall_attentionsZall_cross_attentionsZnext_decoder_cacher   Zlayer_moduler`   Zlayer_outputsrH   rH   rI   rt     sL    



zTFElectraEncoder.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   )ru   rv   r   rT   rw   r.   rx   )rD   rz   r   rH   rH   rI   rx     s    
zTFElectraEncoder.build)F)Nr   rH   rH   rF   rI   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 )TFElectraPoolerr%   r'   c                   s6   t  jf | tjj|jt|jddd| _|| _	d S )Ntanhr   )r,   r-   
activationr.   )
r2   r3   r   r=   r>   r4   r   r?   r   r(   rC   rF   rH   rI   r3     s    zTFElectraPooler.__init__rJ   r   c                 C  s    |d d df }| j |d}|S )Nr   rc   )r   )rD   r[   Zfirst_token_tensorZpooled_outputrH   rH   rI   rt     s    zTFElectraPooler.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   ry   rH   rH   rI   rx   %  s    zTFElectraPooler.build)Nr   rH   rH   rF   rI   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 )TFElectraEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.r%   r'   c                   sV   t  jf | || _|j| _|j| _|j| _tjj|j	dd| _
tjj|jd| _d S )Nr   r   r1   )r2   r3   r(   embedding_sizemax_position_embeddingsr?   r   r=   r   r   r   r@   r   rA   rC   rF   rH   rI   r3   2  s    zTFElectraEmbeddings.__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)r.   rP   initializertoken_type_embeddings
embeddingsposition_embeddingsTr   )rT   rw   
add_weightr(   
vocab_sizer   r   r?   r   Ztype_vocab_sizer   r   r   ru   rv   r   r.   rx   ry   rH   rH   rI   rx   <  s0    
zTFElectraEmbeddings.buildr   FrJ   rY   )	input_idsposition_idstoken_type_idsinputs_embedsrb   rM   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indicesrN   r   Zdimsr0   r$   )startlimitre   rc   rk   )r6   r   r(   r   rT   Zgatherr   r   fillZexpand_dimsr   r   r   r   rA   )rD   r   r   r   r   past_key_values_lengthrb   rz   Zposition_embedsZtoken_type_embedsZfinal_embeddingsrH   rH   rI   rt   Z  s&     zTFElectraEmbeddings.call)N)NNNNr   F)r{   r|   r}   __doc__r3   rx   rt   r~   rH   rH   rF   rI   r   /  s   

       r   c                      s0   e Zd Z fddZd	ddZd
ddZ  ZS )!TFElectraDiscriminatorPredictionsc                   s>   t  jf | tjj|jdd| _tjjddd| _|| _d S )Nr   r   r$   dense_prediction)	r2   r3   r   r=   r>   r4   r   r   r(   rC   rF   rH   rI   r3     s    z*TFElectraDiscriminatorPredictions.__init__Fc                 C  s0   |  |}t| jj|}t| |d}|S )NrN   )r   r   r(   r   rT   squeezer   )rD   discriminator_hidden_statesrb   r[   rj   rH   rH   rI   rt     s    
z&TFElectraDiscriminatorPredictions.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   r   )
ru   rv   rT   rw   r   r.   rx   r(   r4   r   ry   rH   rH   rI   rx     s     z'TFElectraDiscriminatorPredictions.build)F)Nr   rH   rH   rF   rI   r     s   
r   c                      s0   e Zd Z fddZd	ddZd
ddZ  ZS )TFElectraGeneratorPredictionsc                   s@   t  jf | tjj|jdd| _tjj|jdd| _	|| _
d S )Nr   r   r   r   )r2   r3   r   r=   r   r   r   r>   r   r   r(   rC   rF   rH   rI   r3     s    z&TFElectraGeneratorPredictions.__init__Fc                 C  s$   |  |}td|}| |}|S )Ngelu)r   r   r   )rD   generator_hidden_statesrb   r[   rH   rH   rI   rt     s    

z"TFElectraGeneratorPredictions.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   r   )ru   rv   rT   rw   r   r.   rx   r(   r   r   r4   ry   rH   rH   rI   rx     s     z#TFElectraGeneratorPredictions.build)F)Nr   rH   rH   rF   rI   r     s   
r   c                   @  s$   e Zd ZdZeZdZdgZdgZdS )TFElectraPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    electrazgenerator_lm_head.weightrA   N)	r{   r|   r}   r   r%   config_classZbase_model_prefixZ"_keys_to_ignore_on_load_unexpectedZ_keys_to_ignore_on_load_missingrH   rH   rH   rI   r     s
   r   c                      s   e Zd ZeZ fddZdd Zdd Zdd Z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 )TFElectraMainLayerc                   s\   t  jf | || _|j| _t|dd| _|j|jkrJtj	j
|jdd| _t|dd| _d S )Nr   r   embeddings_projectencoder)r2   r3   r(   rB   r   r   r   r4   r   r=   r>   r   r   r   rC   rF   rH   rI   r3     s    zTFElectraMainLayer.__init__c                 C  s   | j S r   )r   rD   rH   rH   rI   get_input_embeddings  s    z'TFElectraMainLayer.get_input_embeddingsc                 C  s   || j _t|d | j _d S Nr   )r   r   r   r   rD   r0   rH   rH   rI   set_input_embeddings  s    z'TFElectraMainLayer.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   )rD   Zheads_to_prunerH   rH   rI   _prune_heads  s    zTFElectraMainLayer._prune_headsr   c              	   C  sX  |\}}|d kr&t j||| fd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kr|d d d d | d d d f }nt 	||d dd|d f}t j||d}t j
d|d}t j
d|d}t t |||}|S )Nr$   r   rh   r   rQ         ?     )rT   r   r   rB   r   Z
less_equalZtilern   ri   rU   Zconstantrq   subtract)rD   r\   rz   ri   r   rL   
seq_lengthZattention_mask_shapeZmask_seq_lengthZseq_idsZcausal_maskextended_attention_maskZone_cstZten_thousand_cstrH   rH   rI   get_extended_attention_mask  s:    
 $ 	z.TFElectraMainLayer.get_extended_attention_maskc                 C  s    |d k	rt nd g| jj }|S r   )r   r(   r   )rD   r]   rH   rH   rI   get_head_mask  s    z TFElectraMainLayer.get_head_maskNFTFModelInputType | Nonenp.ndarray | tf.Tensor | None4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]r   r   r   r\   r   r   r]   r   r^   r_   r   r   ra   r   r   rb   rM   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	}| 
|||j|}| jrv|d k	rvtj||jd
}tt|}|dkrF|d d d d d d d f }|dkrh|d d d d d d f }d| d }nd }| |}t| dr| j||d}| j||||||	|
||||d}|S )NFzDYou cannot specify both input_ids and inputs_embeds at the same timerN   z5You have to specify either input_ids or inputs_embedsr   r   r$   r   )r   r   r   r   r   rb   rh   r   rQ   r   r   r   rb   )r[   r\   r]   r^   r_   r   r   ra   r   r   rb   )r(   rB   r6   r   lenr   r   rT   r   r   r   ri   rn   r   r   r   )rD   r   r\   r   r   r]   r   r^   r_   r   r   ra   r   r   rb   rz   rL   r   r   r[   r   Znum_dims_encoder_attention_maskZencoder_extended_attention_maskrH   rH   rI   rt     st    

   


zTFElectraMainLayer.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 d | j	j
g W 5 Q R X d S )NTr   r   r   )ru   rv   rT   rw   r   r.   rx   r   r   r(   r   ry   rH   rH   rI   rx     s    zTFElectraMainLayer.build)r   )NNNNNNNNNNNNNF)N)r{   r|   r}   r%   r   r3   r   r   r   r   r   r   rt   rx   r~   rH   rH   rF   rI   r     s0   
1              .ar   c                   @  s6   e Zd ZU dZdZded< dZded< dZded< dS )TFElectraForPreTrainingOutputa  
    Output type of [`TFElectraForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
            Total loss of the ELECTRA objective.
        logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Prediction scores of the head (scores for each token 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.
    NrJ   rj   r   r[   r   )r{   r|   r}   r   rj   __annotations__r[   r   rH   rH   rH   rI   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 ([`ElectraConfig`]): 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)
        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).
a]  The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the hidden size and embedding size are different. Both the generator and discriminator checkpoints may be loaded into this model.c                      sr   e Zd Z 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 )TFElectraModelc                   s&   t  j|f|| t|dd| _d S )Nr   r   )r2   r3   r   r   rD   r(   rd   rE   rF   rH   rI   r3     s    zTFElectraModel.__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
        )r   r\   r   r   r]   r^   r_   r   r   r   ra   r   r   rb   )r   )rD   r   r\   r   r   r]   r   r^   r_   r   r   ra   r   r   rb   rs   rH   rH   rI   rt     s"    ,zTFElectraModel.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   )ru   rv   rT   rw   r   r.   rx   ry   rH   rH   rI   rx   R  s    zTFElectraModel.build)NNNNNNNNNNNNNF)N)r{   r|   r}   r3   r   r!   ELECTRA_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr	   _CONFIG_FOR_DOCrt   rx   r~   rH   rH   rF   rI   r     s0   	              28r   aH  
    Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.

    Even though both the discriminator and generator may be loaded into this model, the discriminator is the only model
    of the two to have the correct classification head to be used for this model.
    c                      sh   e Zd Z 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ZdddZ  ZS )TFElectraForPreTrainingc                   s0   t  j|f| t|dd| _t|dd| _d S )Nr   r   discriminator_predictions)r2   r3   r   r   r   r  rC   rF   rH   rI   r3   e  s    z TFElectraForPreTraining.__init__r   )r  r   NFr   r   r   z6Union[TFElectraForPreTrainingOutput, Tuple[tf.Tensor]])r   r\   r   r   r]   r   ra   r   r   rb   rM   c                 C  sX   | j |||||||||	|
d
}|d }| |}|	sF|f|dd  S t||j|jdS )a!  
        Returns:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-small-discriminator")
        >>> model = TFElectraForPreTraining.from_pretrained("google/electra-small-discriminator")
        >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :]  # Batch size 1
        >>> outputs = model(input_ids)
        >>> scores = outputs[0]
        ```
r   r\   r   r   r]   r   ra   r   r   rb   r   r$   N)rj   r[   r   )r   r  r   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   rb   r   discriminator_sequence_outputrj   rH   rH   rI   rt   k  s*    
zTFElectraForPreTraining.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  )ru   rv   rT   rw   r   r.   rx   r  ry   rH   rH   rI   rx     s    zTFElectraForPreTraining.build)
NNNNNNNNNF)N)r{   r|   r}   r3   r   r!   r  r  r#   r   r  rt   rx   r~   rH   rH   rF   rI   r  [  s    

          *4r  c                      sP   e Zd Z fddZ fddZdd Zdd Zd	d
 Zdd Zdd Z	  Z
S )TFElectraMaskedLMHeadc                   s&   t  jf | || _|j| _|| _d S r   )r2   r3   r(   r   input_embeddings)rD   r(   r  rE   rF   rH   rI   r3     s    zTFElectraMaskedLMHead.__init__c                   s*   | j | jjfdddd| _t | d S )NzerosTbias)rP   r   Z	trainabler.   )r   r(   r   r  r2   rx   ry   rF   rH   rI   rx     s    zTFElectraMaskedLMHead.buildc                 C  s   | j S r   )r  r   rH   rH   rI   get_output_embeddings  s    z+TFElectraMaskedLMHead.get_output_embeddingsc                 C  s   || j _t|d | j _d S r   )r  r   r   r   r   rH   rH   rI   set_output_embeddings  s    z+TFElectraMaskedLMHead.set_output_embeddingsc                 C  s
   d| j iS )Nr  )r  r   rH   rH   rI   get_bias  s    zTFElectraMaskedLMHead.get_biasc                 C  s"   |d | _ t|d d | j_d S )Nr  r   )r  r   r(   r   r   rH   rH   rI   set_bias  s    
zTFElectraMaskedLMHead.set_biasc                 C  sd   t |d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 )N)rK   r$   rN   rO   T)abrg   )r0   r  )r   rT   rU   r   rm   r  r   r(   r   nnZbias_addr  )rD   r[   r   rH   rH   rI   rt     s    zTFElectraMaskedLMHead.call)r{   r|   r}   r3   rx   r  r  r  r  rt   r~   rH   rH   rF   rI   r
    s   r
  z
    Electra model with a language modeling head on top.

    Even though both the discriminator and generator may be loaded into this model, the generator is the only model of
    the two to have been trained for the masked language modeling task.
    c                      s   e Zd Z fddZdd Zdd Zeee	de
d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 )TFElectraForMaskedLMc                   sl   t  j|f| || _t|dd| _t|dd| _t|jt	rLt
|j| _n|j| _t|| jjdd| _d S )Nr   r   generator_predictionsgenerator_lm_head)r2   r3   r(   r   r   r   r  r   r   r   r   r   r
  r   r  rC   rF   rH   rI   r3     s    zTFElectraForMaskedLM.__init__c                 C  s   | j S r   )r  r   rH   rH   rI   get_lm_head  s    z TFElectraForMaskedLM.get_lm_headc                 C  s   t dt | jd | jj S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr.   r  r   rH   rH   rI   get_prefix_bias_name  s    z)TFElectraForMaskedLM.get_prefix_bias_namer   zgoogle/electra-small-generatorz[MASK]z'paris'gQ?)r   r  r   maskexpected_outputexpected_lossNFr   r   r   z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]r   r\   r   r   r]   r   ra   r   r   labelsrb   rM   c                 C  s   | j |||||||||	|d
}|d }| j||d}| j||d}|
dkrNdn
| |
|}|	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]`
        r  r   r   Nr$   lossrj   r[   r   )r   r  r  hf_compute_lossr
   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   r"  rb   r   Zgenerator_sequence_outputZprediction_scoresr$  r   rH   rH   rI   rt     s2    zTFElectraForMaskedLM.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  )	ru   rv   rT   rw   r   r.   rx   r  r  ry   rH   rH   rI   rx   -  s    zTFElectraForMaskedLM.build)NNNNNNNNNNF)N)r{   r|   r}   r3   r  r  r   r!   r  r  r   r
   r  rt   rx   r~   rH   rH   rF   rI   r    s4   

           ,1r  c                      s2   e Zd ZdZ fddZdd Zd	ddZ  ZS )
TFElectraClassificationHeadz-Head for sentence-level classification tasks.c                   st   t  jf | tjj|jt|jdd| _|j	d k	r:|j
n|j}tj|| _tjj|jt|jdd| _|| _d S )Nr   r-   r.   out_proj)r2   r3   r   r=   r>   r4   r   r?   r   classifier_dropoutZ%classifhidden_dropout_probier_dropoutr   r@   rA   
num_labelsr(  r(   rD   r(   rE   r)  rF   rH   rI   r3   ?  s"        z$TFElectraClassificationHead.__init__c                 K  sN   |d d dd d f }|  |}| |}td|}|  |}| |}|S )Nr   r   )rA   r   r   r(  )rD   rd   rE   xrH   rH   rI   rt   P  s    



z TFElectraClassificationHead.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   r(  )
ru   rv   rT   rw   r   r.   rx   r(   r4   r(  ry   rH   rH   rI   rx   Z  s     z!TFElectraClassificationHead.build)N)r{   r|   r}   r   r3   rt   rx   r~   rH   rH   rF   rI   r&  <  s   
r&  z
    ELECTRA 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                      sp   e Zd Z fddZeeeded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 )"TFElectraForSequenceClassificationc                   s<   t  j|f|| |j| _t|dd| _t|dd| _d S )Nr   r   
classifier)r2   r3   r*  r   r   r&  r.  r   rF   rH   rI   r3   n  s    z+TFElectraForSequenceClassification.__init__r   z$bhadresh-savani/electra-base-emotionz'joy'gQ?r   r  r   r  r   NFr   r   r   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]r!  c                 C  s   | j |||||||||	|d
}| |d }|
dkr8dn
| |
|}|	sp|f|dd  }|dk	rl|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).
        r  r   Nr$   r#  )r   r.  r%  r   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   r"  rb   rs   rj   r$  r   rH   rH   rI   rt   t  s.    z'TFElectraForSequenceClassification.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.  )ru   rv   rT   rw   r   r.   rx   r.  ry   rH   rH   rI   rx     s    z(TFElectraForSequenceClassification.build)NNNNNNNNNNF)N)r{   r|   r}   r3   r   r!   r  r  r   r   r  rt   rx   r~   rH   rH   rF   rI   r-  f  s.   	           ,/r-  z
    ELECTRA 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                      sl   e Zd Z 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 )TFElectraForMultipleChoicec                   sX   t  j|f|| t|dd| _t||jdd| _tjj	dt
|jdd| _|| _d S )Nr   r   sequence_summary)r?   r.   r$   r.  r'  )r2   r3   r   r   r   r?   r2  r   r=   r>   r   r.  r(   r   rF   rH   rI   r3     s        z#TFElectraForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   NFr   r   r   z4Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]r!  c                 C  st  |dk	r"t |d }t |d }nt |d }t |d }|dk	rRt|d|fnd}|dk	rnt|d|fnd}|dk	rt|d|fnd}|dk	rt|d|fnd}|dk	rt|d|t |d fnd}| j|||||||||	|d
}| |d }| |}t|d|f}|
dkr$dn
| |
|}|	s`|f|dd  }|dk	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$   rQ   rN   r   r  r   r#  )
r   rT   rU   r   r2  r.  r%  r   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   r"  rb   Znum_choicesr   Zflat_input_idsZflat_attention_maskZflat_token_type_idsZflat_position_idsZflat_inputs_embedsrs   rj   Zreshaped_logitsr$  r   rH   rH   rI   rt     sL    
zTFElectraForMultipleChoice.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 d | j	j
g W 5 Q R X d S )NTr   r2  r.  )ru   rv   rT   rw   r   r.   rx   r2  r.  r(   r4   ry   rH   rH   rI   rx     s    z TFElectraForMultipleChoice.build)NNNNNNNNNNF)N)r{   r|   r}   r3   r   r!   r  r  r   r  r   r  rt   rx   r~   rH   rH   rF   rI   r1    s*              ,Ar1  z
    Electra model with a token classification head on top.

    Both the discriminator and generator may be loaded into this model.
    c                      sp   e Zd Z fddZeeeded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 )TFElectraForTokenClassificationc                   sh   t  j|f| t|dd| _|jd k	r.|jn|j}tj|| _	tjj
|jt|jdd| _|| _d S )Nr   r   r.  r'  )r2   r3   r   r   r)  r   r   r=   r@   rA   r>   r*  r   r?   r.  r(   r+  rF   rH   rI   r3   ,  s      z(TFElectraForTokenClassification.__init__r   zDbhadresh-savani/electra-base-discriminator-finetuned-conll03-englishzK['B-LOC', 'B-ORG', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'O', 'B-LOC', 'I-LOC']g)\(?r/  NFr   r   r   z0Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]r!  c                 C  s   | j |||||||||	|d
}|d }| |}| |}|
dkrFdn
| |
|}|	s~|f|dd  }|dk	rz|f| S |S t|||j|jdS )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]`.
        r  r   Nr$   r#  )r   rA   r.  r%  r   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   r"  rb   r   r	  rj   r$  r   rH   rH   rI   rt   9  s2    

z$TFElectraForTokenClassification.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 r0  )
ru   rv   rT   rw   r   r.   rx   r.  r(   r4   ry   rH   rH   rI   rx   q  s    z%TFElectraForTokenClassification.build)NNNNNNNNNNF)N)r{   r|   r}   r3   r   r!   r  r  r   r   r  rt   rx   r~   rH   rH   rF   rI   r3  #  s.   		           ,/r3  z
    Electra 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                      sv   e Zd Z fddZeeedede	e
d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 )TFElectraForQuestionAnsweringc                   sP   t  j|f|| |j| _t|dd| _tjj|jt|j	dd| _
|| _d S )Nr   r   
qa_outputsr'  )r2   r3   r*  r   r   r   r=   r>   r   r?   r5  r(   r   rF   rH   rI   r3     s      z&TFElectraForQuestionAnswering.__init__r   z#bhadresh-savani/electra-base-squad2      z'a nice puppet'gQ@)r   r  r   Zqa_target_start_indexZqa_target_end_indexr  r   NFr   r   r   z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]])r   r\   r   r   r]   r   ra   r   r   start_positionsend_positionsrb   rM   c                 C  s   | j |||||||||	|d
}|d }| |}tj|ddd\}}tj|dd}tj|dd}d}|
dk	r|dk	rd|
i}||d< | |||f}|	s||f|d	d  }|dk	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.
        r  r   rQ   rN   re   NZstart_positionZend_positionr$   )r$  start_logits
end_logitsr[   r   )	r   r5  rT   splitr   r%  r   r[   r   )rD   r   r\   r   r   r]   r   ra   r   r   r8  r9  rb   r   r	  rj   r:  r;  r$  r"  r   rH   rH   rI   rt     sH    $

z"TFElectraForQuestionAnswering.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   r5  )
ru   rv   rT   rw   r   r.   rx   r5  r(   r4   ry   rH   rH   rI   rx     s    z#TFElectraForQuestionAnswering.build)NNNNNNNNNNNF)N)r{   r|   r}   r3   r   r!   r  r  r   r   r  rt   rx   r~   rH   rH   rF   rI   r4  }  s4   
            .Ar4  )Rr   
__future__r   r:   r  Zdataclassesr   typingr   r   r   ZnumpynpZ
tensorflowrT   Zactivations_tfr   Zmodeling_tf_outputsr	   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_electrar%   Z
get_loggerr{   loggerr  r  r=   ZLayerr&   r   r   r   r   r   r   r   r   r   r   r   r   r   ZELECTRA_START_DOCSTRINGr  r   r  r
  r  r&  r-  r1  r3  r4  rH   rH   rH   rI   <module>   s    8 
 4hOT I*0N	J%	`*KdR