U
    4A·fm( ã                   @   sÚ  d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlZ
ddl
mZ ddlmZmZmZ ddlmZmZ dd	lmZmZmZmZmZmZmZmZ dd
l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l+m,Z, e) -e.¡Z/dZ0dZ1dIdd„Z2G dd„ dej3ƒZ4G dd„ dej3ƒZ5G dd„ dej3ƒZ6de5iZ7G dd„ dej3ƒZ8G dd„ dej3ƒZ9G dd „ d ej3ƒZ:G d!d"„ d"ej3ƒZ;G d#d$„ d$ej3ƒZ<G d%d&„ d&ej3ƒZ=G d'd(„ d(ej3ƒZ>G d)d*„ d*eƒZ?eG d+d,„ d,e%ƒƒZ@d-ZAd.ZBe'd/eAƒG d0d1„ d1e?ƒƒZCG d2d3„ d3ej3ƒZDe'd4eAƒG d5d6„ d6e?ƒƒZEe'd7eAƒG d8d9„ d9e?ƒƒZFe'd:eAƒG d;d<„ d<e?ƒƒZGe'd=eAƒG d>d?„ d?e?ƒƒZHe'd@eAƒG dAdB„ dBe?ƒƒZIe'dCeAƒG dDdE„ dEe?ƒƒZJe'dFeAƒG dGdH„ dHe?ƒƒZKdS )JzPyTorch ELECTRA model.é    N)Ú	dataclass)ÚListÚOptionalÚTupleÚUnion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )ÚACT2FNÚget_activation)Ú"BaseModelOutputWithCrossAttentionsÚ)BaseModelOutputWithPastAndCrossAttentionsÚ!CausalLMOutputWithCrossAttentionsÚMaskedLMOutputÚMultipleChoiceModelOutputÚQuestionAnsweringModelOutputÚSequenceClassifierOutputÚTokenClassifierOutput)ÚPreTrainedModelÚSequenceSummary)Úapply_chunking_to_forwardÚ find_pruneable_heads_and_indicesÚprune_linear_layer)ÚModelOutputÚadd_code_sample_docstringsÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsé   )ÚElectraConfigz"google/electra-small-discriminatorr"   Údiscriminatorc                 C   s2  zddl }ddl}ddl}W n  tk
r<   t d¡ ‚ Y nX tj |¡}t 	d|› ¡ |j
 |¡}g }	g }
|D ]@\}}t 	d|› d|› ¡ |j
 ||¡}|	 |¡ |
 |¡ qrt|	|
ƒD ]l\}}|}zt| tƒræ| dd¡}|d	kr| d
d¡}| dd
¡}| dd¡}| dd¡}| d¡}tdd„ |D ƒƒrRt 	d|› ¡ W q¾| }|D ]Ü}| d|¡rz| d|¡}n|g}|d dksœ|d dkr¨t|dƒ}nj|d dksÄ|d dkrÐt|dƒ}nB|d dkrêt|dƒ}n(|d dkrt|dƒ}nt||d ƒ}t|ƒd krZt|d! ƒ}|| }qZ| d"¡rPt|dƒ}n|dkrd| |¡}z,|j|jkrŽtd#|j› d$|j› d%ƒ‚W n< tk
rÌ } z| j|j|jf7  _‚ W 5 d}~X Y nX td&|› |ƒ t |¡|_ W q¾ t!k
r* } ztd|› ||ƒ W Y ¢q¾W 5 d}~X Y q¾X q¾| S )'z'Load tf checkpoints in a pytorch model.r   Nz™Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape zelectra/embeddings/zgenerator/embeddings/Ú	generatorzelectra/zdiscriminator/z
generator/Zdense_1Údense_predictionz!generator_predictions/output_biaszgenerator_lm_head/biasú/c                 s   s   | ]}|d kV  qdS ))Zglobal_stepZtemperatureN© )Ú.0Únr'   r'   úP/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/electra/modeling_electra.pyÚ	<genexpr>c   s     z-load_tf_weights_in_electra.<locals>.<genexpr>z	Skipping z[A-Za-z]+_\d+z_(\d+)ÚkernelÚgammaÚweightZoutput_biasÚbetaÚbiasZoutput_weightsZsquadÚ
classifieré   r!   Z_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )"ÚreZnumpyZ
tensorflowÚImportErrorÚloggerÚerrorÚosÚpathÚabspathÚinfoZtrainZlist_variablesZload_variableÚappendÚzipÚ
isinstanceÚElectraForMaskedLMÚreplaceÚsplitÚanyÚ	fullmatchÚgetattrÚlenÚintÚendswithÚ	transposeÚshapeÚ
ValueErrorÚargsÚprintÚtorchZ
from_numpyÚdataÚAttributeError)ÚmodelÚconfigZtf_checkpoint_pathZdiscriminator_or_generatorr3   ÚnpÚtfZtf_pathZ	init_varsÚnamesZarraysÚnamerH   ÚarrayÚoriginal_nameÚpointerZm_nameZscope_namesÚnumÚer'   r'   r*   Úload_tf_weights_in_electra9   s„    ÿ





rZ   c                       sT   e Zd ZdZ‡ fdd„Zd	eej eej eej eej e	ej
dœdd„Z‡  ZS )
ÚElectraEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    sº   t ƒ  ¡  tj|j|j|jd| _t |j|j¡| _	t |j
|j¡| _tj|j|jd| _t |j¡| _| jdt |j¡ d¡dd t|ddƒ| _| jd	tj| j ¡ tjd
dd d S )N)Úpadding_idx©ZepsÚposition_ids)r!   éÿÿÿÿF)Ú
persistentÚposition_embedding_typeÚabsoluteÚtoken_type_ids©Údtype)ÚsuperÚ__init__r   Ú	EmbeddingÚ
vocab_sizeÚembedding_sizeZpad_token_idÚword_embeddingsÚmax_position_embeddingsÚposition_embeddingsZtype_vocab_sizeÚtoken_type_embeddingsÚ	LayerNormÚlayer_norm_epsÚDropoutÚhidden_dropout_probÚdropoutZregister_bufferrL   ÚarangeÚexpandrC   ra   Úzerosr^   ÚsizeÚlong©ÚselfrP   ©Ú	__class__r'   r*   rg   Ž   s"    
  ÿ  ÿzElectraEmbeddings.__init__Nr   )Ú	input_idsrc   r^   Úinputs_embedsÚpast_key_values_lengthÚreturnc                 C   sø   |d k	r|  ¡ }n|  ¡ d d… }|d }|d krL| jd d …||| …f }|d kr t| dƒrŠ| jd d …d |…f }| |d |¡}	|	}ntj|tj| jjd}|d kr²|  	|¡}|  
|¡}
||
 }| jdkrà|  |¡}||7 }|  |¡}|  |¡}|S )Nr_   r!   rc   r   ©re   Údevicerb   )rw   r^   Úhasattrrc   ru   rL   rv   rx   r‚   rk   rn   ra   rm   ro   rs   )rz   r}   rc   r^   r~   r   Úinput_shapeÚ
seq_lengthÚbuffered_token_type_idsÚ buffered_token_type_ids_expandedrn   Ú
embeddingsrm   r'   r'   r*   Úforward£   s,    







zElectraEmbeddings.forward)NNNNr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rg   r   rL   Z
LongTensorÚFloatTensorrE   ÚTensorr‰   Ú__classcell__r'   r'   r{   r*   r[   ‹   s        úùr[   c                
       s‚   e Zd Zd‡ fdd„	Zejejdœdd„Zdejeej eej eej eej ee	e	ej   ee
 e	ej dœd	d
„Z‡  ZS )ÚElectraSelfAttentionNc                    sþ   t ƒ  ¡  |j|j dkr>t|dƒs>td|j› d|j› dƒ‚|j| _t|j|j ƒ| _| j| j | _t	 
|j| j¡| _t	 
|j| j¡| _t	 
|j| j¡| _t	 |j¡| _|p¸t|ddƒ| _| jdksÐ| jd	krò|j| _t	 d
|j d | j¡| _|j| _d S )Nr   rj   zThe hidden size (z6) is not a multiple of the number of attention heads (ú)ra   rb   Úrelative_keyÚrelative_key_queryr2   r!   )rf   rg   Úhidden_sizeÚnum_attention_headsrƒ   rI   rE   Úattention_head_sizeÚall_head_sizer   ÚLinearÚqueryÚkeyÚvaluerq   Zattention_probs_dropout_probrs   rC   ra   rl   rh   Údistance_embeddingÚ
is_decoder©rz   rP   ra   r{   r'   r*   rg   Ï   s*    
ÿ  ÿzElectraSelfAttention.__init__)Úxr€   c                 C   s6   |  ¡ d d… | j| jf }| |¡}| dddd¡S )Nr_   r   r2   r!   r   )rw   r–   r—   ÚviewÚpermute)rz   r    Znew_x_shaper'   r'   r*   Útranspose_for_scoresé   s    
z)ElectraSelfAttention.transpose_for_scoresF©Úhidden_statesÚattention_maskÚ	head_maskÚencoder_hidden_statesÚencoder_attention_maskÚpast_key_valueÚoutput_attentionsr€   c                 C   sÒ  |   |¡}|d k	}	|	r4|d k	r4|d }
|d }|}n |	r^|  |  |¡¡}
|  |  |¡¡}|}nv|d k	r´|  |  |¡¡}
|  |  |¡¡}tj|d |
gdd}
tj|d |gdd}n |  |  |¡¡}
|  |  |¡¡}|  |¡}|d k	}| jrô|
|f}t ||
 dd¡¡}| j	dks | j	dkr|j
d |
j
d  }}|r^tj|d tj|jd	 dd¡}ntj|tj|jd	 dd¡}tj|tj|jd	 dd¡}|| }|  || j d ¡}|j|jd
}| j	dkrät d||¡}|| }n4| j	dkrt d||¡}t d|
|¡}|| | }|t | j¡ }|d k	r:|| }tjj|dd}|  |¡}|d k	rf|| }t ||¡}| dddd¡ ¡ }| ¡ d d… | jf }| |¡}|r¶||fn|f}| jrÎ||f }|S )Nr   r!   r2   ©Zdimr_   éþÿÿÿr“   r”   r   rd   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) rš   r£   r›   rœ   rL   Úcatrž   ÚmatmulrG   ra   rH   Ztensorrx   r‚   r¡   rt   r   rl   Útore   ZeinsumÚmathÚsqrtr—   r   Z
functionalZsoftmaxrs   r¢   Ú
contiguousrw   r˜   )rz   r¥   r¦   r§   r¨   r©   rª   r«   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerÚ	use_cacheZattention_scoresZquery_lengthZ
key_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeÚoutputsr'   r'   r*   r‰   î   sp    


 ÿ





zElectraSelfAttention.forward)N)NNNNNF)rŠ   r‹   rŒ   rg   rL   r   r£   r   rŽ   r   Úboolr‰   r   r'   r'   r{   r*   r‘   Î   s$         ø÷r‘   c                       s4   e Zd Z‡ fdd„Zejejejdœdd„Z‡  ZS )ÚElectraSelfOutputc                    sB   t ƒ  ¡  t |j|j¡| _tj|j|jd| _t |j	¡| _
d S ©Nr]   )rf   rg   r   r™   r•   Údensero   rp   rq   rr   rs   ry   r{   r'   r*   rg   V  s    
zElectraSelfOutput.__init__©r¥   Úinput_tensorr€   c                 C   s&   |   |¡}|  |¡}|  || ¡}|S ©N©r¹   rs   ro   ©rz   r¥   r»   r'   r'   r*   r‰   \  s    

zElectraSelfOutput.forward©rŠ   r‹   rŒ   rg   rL   r   r‰   r   r'   r'   r{   r*   r·   U  s   r·   Úeagerc                
       sv   e Zd Zd
‡ fdd„	Zdd„ Zdejeej eej eej eej ee	e	ej   ee
 e	ej dœdd	„Z‡  ZS )ÚElectraAttentionNc                    s4   t ƒ  ¡  t|j ||d| _t|ƒ| _tƒ | _d S )N©ra   )	rf   rg   ÚELECTRA_SELF_ATTENTION_CLASSESZ_attn_implementationrz   r·   ÚoutputÚsetÚpruned_headsrŸ   r{   r'   r*   rg   j  s    
 ÿ
zElectraAttention.__init__c                 C   s²   t |ƒdkrd S t|| jj| jj| jƒ\}}t| jj|ƒ| j_t| jj|ƒ| j_t| jj	|ƒ| j_	t| j
j|dd| j
_| jjt |ƒ | j_| jj| jj | j_| j |¡| _d S )Nr   r!   r¬   )rD   r   rz   r–   r—   rÆ   r   rš   r›   rœ   rÄ   r¹   r˜   Úunion)rz   ÚheadsÚindexr'   r'   r*   Úprune_headsr  s       ÿzElectraAttention.prune_headsFr¤   c              	   C   s<   |   |||||||¡}|  |d |¡}	|	f|dd …  }
|
S )Nr   r!   )rz   rÄ   )rz   r¥   r¦   r§   r¨   r©   rª   r«   Zself_outputsÚattention_outputrµ   r'   r'   r*   r‰   „  s    
ù	zElectraAttention.forward)N)NNNNNF)rŠ   r‹   rŒ   rg   rÊ   rL   r   r   rŽ   r   r¶   r‰   r   r'   r'   r{   r*   rÁ   i  s$         ø÷rÁ   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )ÚElectraIntermediatec                    sB   t ƒ  ¡  t |j|j¡| _t|jt	ƒr6t
|j | _n|j| _d S r¼   )rf   rg   r   r™   r•   Úintermediate_sizer¹   r=   Ú
hidden_actÚstrr   Úintermediate_act_fnry   r{   r'   r*   rg   ž  s
    
zElectraIntermediate.__init__)r¥   r€   c                 C   s   |   |¡}|  |¡}|S r¼   )r¹   rÐ   )rz   r¥   r'   r'   r*   r‰   ¦  s    

zElectraIntermediate.forwardr¿   r'   r'   r{   r*   rÌ     s   rÌ   c                       s4   e Zd Z‡ fdd„Zejejejdœdd„Z‡  ZS )ÚElectraOutputc                    sB   t ƒ  ¡  t |j|j¡| _tj|j|jd| _t 	|j
¡| _d S r¸   )rf   rg   r   r™   rÍ   r•   r¹   ro   rp   rq   rr   rs   ry   r{   r'   r*   rg   ®  s    
zElectraOutput.__init__rº   c                 C   s&   |   |¡}|  |¡}|  || ¡}|S r¼   r½   r¾   r'   r'   r*   r‰   ´  s    

zElectraOutput.forwardr¿   r'   r'   r{   r*   rÑ   ­  s   rÑ   c                
       st   e Zd Z‡ fdd„Zd
ejeej eej eej eej eeeej   ee	 eej dœdd„Z
dd	„ Z‡  ZS )ÚElectraLayerc                    sr   t ƒ  ¡  |j| _d| _t|ƒ| _|j| _|j| _| jrZ| jsLt| › dƒ‚t|dd| _	t
|ƒ| _t|ƒ| _d S )Nr!   z> should be used as a decoder model if cross attention is addedrb   rÂ   )rf   rg   Úchunk_size_feed_forwardÚseq_len_dimrÁ   Ú	attentionrž   Úadd_cross_attentionrI   ÚcrossattentionrÌ   ÚintermediaterÑ   rÄ   ry   r{   r'   r*   rg   ½  s    


zElectraLayer.__init__NFr¤   c              	   C   s  |d k	r|d d… nd }| j |||||d}	|	d }
| jrP|	dd… }|	d }n|	dd … }d }| jrÞ|d k	rÞt| dƒsˆtd| › dƒ‚|d k	rœ|d	d … nd }|  |
||||||¡}|d }
||dd…  }|d }|| }t| j| j| j|
ƒ}|f| }| jr||f }|S )
Nr2   )r«   rª   r   r!   r_   r×   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r­   )	rÕ   rž   rƒ   rI   r×   r   Úfeed_forward_chunkrÓ   rÔ   )rz   r¥   r¦   r§   r¨   r©   rª   r«   Zself_attn_past_key_valueZself_attention_outputsrË   rµ   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputsÚlayer_outputr'   r'   r*   r‰   Ë  sV    û


ÿù	   ÿ

zElectraLayer.forwardc                 C   s   |   |¡}|  ||¡}|S r¼   )rØ   rÄ   )rz   rË   Zintermediate_outputrÚ   r'   r'   r*   rÙ     s    
zElectraLayer.feed_forward_chunk)NNNNNF)rŠ   r‹   rŒ   rg   rL   r   r   rŽ   r   r¶   r‰   rÙ   r   r'   r'   r{   r*   rÒ   ¼  s$         ø÷ArÒ   c                       s†   e Zd Z‡ fdd„Zd	ejeej eej eej eej eeeej   ee	 ee	 ee	 ee	 e
eej ef dœdd„Z‡  ZS )
ÚElectraEncoderc                    s:   t ƒ  ¡  ˆ | _t ‡ fdd„tˆ jƒD ƒ¡| _d| _d S )Nc                    s   g | ]}t ˆ ƒ‘qS r'   )rÒ   )r(   Ú_©rP   r'   r*   Ú
<listcomp>  s     z+ElectraEncoder.__init__.<locals>.<listcomp>F)	rf   rg   rP   r   Z
ModuleListÚrangeÚnum_hidden_layersÚlayerÚgradient_checkpointingry   r{   rÝ   r*   rg     s    
 zElectraEncoder.__init__NFT)r¥   r¦   r§   r¨   r©   Úpast_key_valuesr´   r«   Úoutput_hidden_statesÚreturn_dictr€   c                 C   sb  |	rdnd }|rdnd }|r(| j jr(dnd }| jrJ| jrJ|rJt d¡ d}|rRdnd }t| jƒD ]¼\}}|	rv||f }|d k	r†|| nd }|d k	rš|| nd }| jrÆ| jrÆ|  |j	|||||||¡}n||||||||ƒ}|d }|rô||d f7 }|r`||d f }| j jr`||d f }q`|	r.||f }|
sPt
dd	„ |||||fD ƒƒS t|||||d
S )Nr'   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r_   r!   r2   c                 s   s   | ]}|d k	r|V  qd S r¼   r'   )r(   Úvr'   r'   r*   r+   \  s   øz)ElectraEncoder.forward.<locals>.<genexpr>)Zlast_hidden_staterã   r¥   Ú
attentionsÚcross_attentions)rP   rÖ   râ   Ztrainingr5   Zwarning_onceÚ	enumeraterá   Z_gradient_checkpointing_funcÚ__call__Útupler   )rz   r¥   r¦   r§   r¨   r©   rã   r´   r«   rä   rå   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheÚiZlayer_moduleZlayer_head_maskrª   Zlayer_outputsr'   r'   r*   r‰     sx    ÿ
øù

ûþûzElectraEncoder.forward)	NNNNNNFFT)rŠ   r‹   rŒ   rg   rL   r   r   rŽ   r   r¶   r   r   r‰   r   r'   r'   r{   r*   rÛ     s.   	         õôrÛ   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚElectraDiscriminatorPredictionszEPrediction module for the discriminator, made up of two dense layers.c                    sB   t ƒ  ¡  t |j|j¡| _t|jƒ| _t |jd¡| _	|| _
d S ©Nr!   )rf   rg   r   r™   r•   r¹   r   rÎ   Ú
activationr%   rP   ry   r{   r'   r*   rg   s  s
    
z(ElectraDiscriminatorPredictions.__init__c                 C   s(   |   |¡}|  |¡}|  |¡ d¡}|S )Nr_   )r¹   rï   r%   Úsqueeze)rz   Údiscriminator_hidden_statesr¥   Úlogitsr'   r'   r*   r‰   {  s    

z'ElectraDiscriminatorPredictions.forward©rŠ   r‹   rŒ   r   rg   r‰   r   r'   r'   r{   r*   rí   p  s   rí   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚElectraGeneratorPredictionszAPrediction module for the generator, made up of two dense layers.c                    s>   t ƒ  ¡  tdƒ| _tj|j|jd| _t |j	|j¡| _
d S )NÚgelur]   )rf   rg   r   rï   r   ro   rj   rp   r™   r•   r¹   ry   r{   r'   r*   rg   †  s    

z$ElectraGeneratorPredictions.__init__c                 C   s"   |   |¡}|  |¡}|  |¡}|S r¼   )r¹   rï   ro   )rz   Úgenerator_hidden_statesr¥   r'   r'   r*   r‰     s    


z#ElectraGeneratorPredictions.forwardró   r'   r'   r{   r*   rô   ƒ  s   rô   c                   @   s(   e Zd ZdZeZeZdZdZ	dd„ Z
dS )ÚElectraPreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ÚelectraTc                 C   s¤   t |tjƒr:|jjjd| jjd |jdk	r |jj 	¡  nft |tj
ƒrz|jjjd| jjd |jdk	r |jj|j  	¡  n&t |tjƒr |jj 	¡  |jj d¡ dS )zInitialize the weightsg        )ZmeanZstdNg      ð?)r=   r   r™   r.   rM   Znormal_rP   Zinitializer_ranger0   Zzero_rh   r\   ro   Zfill_)rz   Úmoduler'   r'   r*   Ú_init_weights¡  s    

z$ElectraPreTrainedModel._init_weightsN)rŠ   r‹   rŒ   r   r"   Úconfig_classrZ   Zload_tf_weightsÚbase_model_prefixZsupports_gradient_checkpointingrú   r'   r'   r'   r*   r÷   •  s   r÷   c                   @   s^   e Zd ZU dZdZeej ed< dZ	ejed< dZ
eeej  ed< dZeeej  ed< dS )ÚElectraForPreTrainingOutputaä  
    Output type of [`ElectraForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Total loss of the ELECTRA objective.
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
            Prediction scores of the head (scores for each token before SoftMax).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    NÚlossrò   r¥   rç   )rŠ   r‹   rŒ   r   rþ   r   rL   rŽ   Ú__annotations__rò   r¥   r   rç   r'   r'   r'   r*   rý   ²  s
   
rý   aA  

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`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 (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

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

        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        encoder_hidden_states  (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `({0})`, *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 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
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                       sÒ   e Zd Z‡ fdd„Zdd„ Zdd„ Zdd„ Zee 	d	¡ƒe
eeed
deej eej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dœdd„ƒƒZ‡  ZS )ÚElectraModelc                    sP   t ƒ  |¡ t|ƒ| _|j|jkr4t |j|j¡| _t	|ƒ| _
|| _|  ¡  d S r¼   )rf   rg   r[   rˆ   rj   r•   r   r™   Úembeddings_projectrÛ   ÚencoderrP   Ú	post_initry   r{   r'   r*   rg   $  s    

zElectraModel.__init__c                 C   s   | j jS r¼   ©rˆ   rk   ©rz   r'   r'   r*   Úget_input_embeddings0  s    z!ElectraModel.get_input_embeddingsc                 C   s   || j _d S r¼   r  )rz   rœ   r'   r'   r*   Úset_input_embeddings3  s    z!ElectraModel.set_input_embeddingsc                 C   s*   |  ¡ D ]\}}| jj| j |¡ qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)Úitemsr  rá   rÕ   rÊ   )rz   Zheads_to_prunerá   rÈ   r'   r'   r*   Ú_prune_heads6  s    zElectraModel._prune_headsúbatch_size, sequence_length©Ú
checkpointÚoutput_typerû   N)r}   r¦   rc   r^   r§   r~   r¨   r©   rã   r´   r«   rä   rå   r€   c                 C   sô  |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}|d k	rV|d k	rVtdƒ‚n@|d k	rt|  ||¡ | ¡ }n"|d k	rŽ| ¡ d d… }ntdƒ‚|\}}|d k	r¬|jn|j}|	d k	rÌ|	d d jd nd}|d kræt	j
||d}|d kr:t| jdƒr(| jjd d …d |…f }| ||¡}|}nt	j|t	j|d}|  ||¡}| j jr”|d k	r”| ¡ \}}}||f}|d krˆt	j
||d}|  |¡}nd }|  || j j¡}| j|||||d	}t| d
ƒrÒ|  |¡}| 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   r2   )r‚   rc   r   )r}   r^   rc   r~   r   r  )	r¦   r§   r¨   r©   rã   r´   r«   rä   rå   )rP   r«   rä   Úuse_return_dictrI   Z%warn_if_padding_and_no_attention_maskrw   r‚   rH   rL   Zonesrƒ   rˆ   rc   ru   rv   rx   Zget_extended_attention_maskrž   Zinvert_attention_maskZget_head_maskrà   r  r  )rz   r}   r¦   rc   r^   r§   r~   r¨   r©   rã   r´   r«   rä   rå   r„   Z
batch_sizer…   r‚   r   r†   r‡   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthrÜ   Zencoder_hidden_shapeZencoder_extended_attention_maskr¥   r'   r'   r*   r‰   >  sl    ÿ



û
özElectraModel.forward)NNNNNNNNNNNNN)rŠ   r‹   rŒ   rg   r  r  r	  r   ÚELECTRA_INPUTS_DOCSTRINGÚformatr   Ú_CHECKPOINT_FOR_DOCr   Ú_CONFIG_FOR_DOCr   rL   r   r   rŽ   r¶   r   r   r‰   r   r'   r'   r{   r*   r     sN   	ý             òñr   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚElectraClassificationHeadz-Head for sentence-level classification tasks.c                    s^   t ƒ  ¡  t |j|j¡| _|jd k	r,|jn|j}tdƒ| _	t 
|¡| _t |j|j¡| _d S )Nrõ   )rf   rg   r   r™   r•   r¹   Úclassifier_dropoutrr   r   rï   rq   rs   Ú
num_labelsÚout_proj©rz   rP   r  r{   r'   r*   rg   ¡  s    
ÿ
z"ElectraClassificationHead.__init__c                 K   sL   |d d …dd d …f }|   |¡}|  |¡}|  |¡}|   |¡}|  |¡}|S )Nr   )rs   r¹   rï   r  )rz   ÚfeaturesÚkwargsr    r'   r'   r*   r‰   «  s    




z!ElectraClassificationHead.forwardró   r'   r'   r{   r*   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                       s¤   e Zd Z‡ fdd„Zee d¡ƒedee	dddde
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef d	œd
d„ƒƒZ‡  ZS )Ú ElectraForSequenceClassificationc                    s:   t ƒ  |¡ |j| _|| _t|ƒ| _t|ƒ| _|  ¡  d S r¼   )	rf   rg   r  rP   r   rø   r  r1   r  ry   r{   r'   r*   rg   ½  s    

z)ElectraForSequenceClassification.__init__r
  z$bhadresh-savani/electra-base-emotionz'joy'g¸…ëQ¸®?©r  r  rû   Úexpected_outputÚexpected_lossN©r}   r¦   rc   r^   r§   r~   Úlabelsr«   rä   rå   r€   c                 C   sr  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}d}|dk	r.| j jdkr¤| jdkrpd| j _n4| jdkrœ|jtjks’|jtj	krœd| j _nd| j _| j jdkràt
ƒ }| jdkrÔ|| ¡ | ¡ ƒ}n
|||ƒ}nN| j jdkrtƒ }|| d| j¡| d¡ƒ}n| j jdkr.tƒ }|||ƒ}|
s^|f|dd…  }|dk	rZ|f| S |S t|||j|jd	S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N©r¦   rc   r^   r§   r~   r«   rä   rå   r   r!   Z
regressionZsingle_label_classificationZmulti_label_classificationr_   ©rþ   rò   r¥   rç   )rP   r  rø   r1   Zproblem_typer  re   rL   rx   rE   r
   rð   r	   r¡   r   r   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r  r«   rä   rå   rñ   Úsequence_outputrò   rþ   Úloss_fctrÄ   r'   r'   r*   r‰   Ç  sT    ÷



"


üz(ElectraForSequenceClassification.forward)
NNNNNNNNNN)rŠ   r‹   rŒ   rg   r   r  r  r   r   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r  µ  s@   
û	          õôr  zÊ
    Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.

    It is recommended to load the discriminator checkpoint into that model.
    c                       sž   e Zd Z‡ fdd„Zee d¡ƒeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dœdd„ƒƒZ‡  ZS )
ÚElectraForPreTrainingc                    s,   t ƒ  |¡ t|ƒ| _t|ƒ| _|  ¡  d S r¼   )rf   rg   r   rø   rí   Údiscriminator_predictionsr  ry   r{   r'   r*   rg     s    

zElectraForPreTraining.__init__r
  ©r  rû   Nr  c                 C   sþ   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}d}|dk	r¾t ¡ }|dk	r¢| d|jd ¡dk}| d|jd ¡| }|| }||| ¡ ƒ}n|| d|jd ¡| ¡ ƒ}|
sê|f|dd…  }|dk	ræ|f| S |S t	|||j
|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the ELECTRA loss. Input should be a sequence of tokens (see `input_ids` docstring)
            Indices should be in `[0, 1]`:

            - 0 indicates the token is an original token,
            - 1 indicates the token was replaced.

        Returns:

        Examples:

        ```python
        >>> from transformers import ElectraForPreTraining, AutoTokenizer
        >>> import torch

        >>> discriminator = ElectraForPreTraining.from_pretrained("google/electra-base-discriminator")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-discriminator")

        >>> sentence = "The quick brown fox jumps over the lazy dog"
        >>> fake_sentence = "The quick brown fox fake over the lazy dog"

        >>> fake_tokens = tokenizer.tokenize(fake_sentence, add_special_tokens=True)
        >>> fake_inputs = tokenizer.encode(fake_sentence, return_tensors="pt")
        >>> discriminator_outputs = discriminator(fake_inputs)
        >>> predictions = torch.round((torch.sign(discriminator_outputs[0]) + 1) / 2)

        >>> fake_tokens
        ['[CLS]', 'the', 'quick', 'brown', 'fox', 'fake', 'over', 'the', 'lazy', 'dog', '[SEP]']

        >>> predictions.squeeze().tolist()
        [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        ```Nr   r   r_   r!   r!  )rP   r  rø   r%  r   r   r¡   rH   Úfloatrý   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r  r«   rä   rå   rñ   Údiscriminator_sequence_outputrò   rþ   r#  Zactive_lossZactive_logitsZactive_labelsrÄ   r'   r'   r*   r‰   '  s@    0÷
üzElectraForPreTraining.forward)
NNNNNNNNNN)rŠ   r‹   rŒ   rg   r   r  r  r    rý   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r$    s4   	
          õô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dgZ‡ fdd„Zdd„ Zdd„ Zee 	d¡ƒe
d	eed
ddddeej eej eej eej eej eej eej ee ee ee eeej ef dœdd„ƒƒZ‡  ZS )r>   úgenerator_lm_head.weightc                    s>   t ƒ  |¡ t|ƒ| _t|ƒ| _t |j|j	¡| _
|  ¡  d S r¼   )rf   rg   r   rø   rô   Úgenerator_predictionsr   r™   rj   ri   Úgenerator_lm_headr  ry   r{   r'   r*   rg   ‹  s
    

zElectraForMaskedLM.__init__c                 C   s   | j S r¼   ©r+  r  r'   r'   r*   Úget_output_embeddings•  s    z(ElectraForMaskedLM.get_output_embeddingsc                 C   s
   || _ d S r¼   r,  )rz   rk   r'   r'   r*   Úset_output_embeddings˜  s    z(ElectraForMaskedLM.set_output_embeddingsr
  zgoogle/electra-small-generatorz[MASK]z'paris'g…ëQ¸…ó?)r  r  rû   Úmaskr  r  Nr  c                 C   s¼   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}|  |¡}d}|dk	r|t ¡ }|| d| j j¡| d¡ƒ}|
s¨|f|dd…  }|dk	r¤|f| S |S t	|||j
|jdS )a¢  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        Nr   r   r_   r!   r!  )rP   r  rø   r*  r+  r   r	   r¡   ri   r   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r  r«   rä   rå   rö   Zgenerator_sequence_outputÚprediction_scoresrþ   r#  rÄ   r'   r'   r*   r‰   ›  s8    ÷

üzElectraForMaskedLM.forward)
NNNNNNNNNN)rŠ   r‹   rŒ   Ú_tied_weights_keysrg   r-  r.  r   r  r  r   r   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r>     sH   

ú
          õôr>   z‰
    Electra model with a token classification head on top.

    Both the discriminator and generator may be loaded into this model.
    c                       s¤   e Zd Z‡ fdd„Zee d¡ƒedee	dddde
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef d	œd
d„ƒƒZ‡  ZS )ÚElectraForTokenClassificationc                    s^   t ƒ  |¡ |j| _t|ƒ| _|jd k	r.|jn|j}t |¡| _	t 
|j|j¡| _|  ¡  d S r¼   )rf   rg   r  r   rø   r  rr   r   rq   rs   r™   r•   r1   r  r  r{   r'   r*   rg   ä  s    
ÿz&ElectraForTokenClassification.__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  Nr  c                 C   s¸   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }|  |¡}|  |¡}d}|dk	rxtƒ }|| d| j¡| d¡ƒ}|
s¤|f|dd…  }|dk	r |f| S |S t|||j	|j
dS )zÛ
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr   r   r_   r!   r!  )rP   r  rø   rs   r1   r	   r¡   r  r   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r  r«   rä   rå   rñ   r(  rò   rþ   r#  rÄ   r'   r'   r*   r‰   ñ  s8    ÷

üz%ElectraForTokenClassification.forward)
NNNNNNNNNN)rŠ   r‹   rŒ   rg   r   r  r  r   r   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r2  Û  s@   	û	          õôr2  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                       s¸   e Zd ZeZdZ‡ fdd„Zee 	d¡ƒe
deedddd	d
deej eej eej eej eej eej eej eej ee ee ee eeej ef dœdd„ƒƒZ‡  ZS )ÚElectraForQuestionAnsweringrø   c                    s<   t ƒ  |¡ |j| _t|ƒ| _t |j|j¡| _|  	¡  d S r¼   )
rf   rg   r  r   rø   r   r™   r•   Ú
qa_outputsr  ry   r{   r'   r*   rg   8  s
    
z$ElectraForQuestionAnswering.__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  N)r}   r¦   rc   r^   r§   r~   Ústart_positionsÚend_positionsr«   rä   rå   r€   c              
   C   sN  |dk	r|n| j j}| j|||||||	|
d}|d }|  |¡}|jddd\}}| d¡ ¡ }| d¡ ¡ }d}|dk	r|dk	rt| ¡ ƒdkr | d¡}t| ¡ ƒdkrº| d¡}| d¡}| 	d|¡}| 	d|¡}t
|d}|||ƒ}|||ƒ}|| d }|s8||f|dd…  }|dk	r4|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        N)r¦   rc   r^   r§   r~   r«   rä   r   r!   r_   r¬   )Zignore_indexr2   )rþ   Ústart_logitsÚ
end_logitsr¥   rç   )rP   r  rø   r4  r@   rð   r³   rD   rw   Úclampr	   r   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r7  r8  r«   rä   rå   rñ   r"  rò   r9  r:  Z
total_lossZignored_indexr#  Z
start_lossZend_lossrÄ   r'   r'   r*   r‰   B  sV    "ø






þ
ýûz#ElectraForQuestionAnswering.forward)NNNNNNNNNNN)rŠ   r‹   rŒ   r"   rû   rü   rg   r   r  r  r   r   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r3  -  sL   
ù           ôór3  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                       s    e Zd Z‡ fdd„Zee d¡ƒeee	e
dd	eej eej eej eej eej eej eej ee ee ee eeej e	f dœdd„ƒƒZ‡  ZS )
ÚElectraForMultipleChoicec                    s<   t ƒ  |¡ t|ƒ| _t|ƒ| _t |jd¡| _	|  
¡  d S rî   )rf   rg   r   rø   r   Úsequence_summaryr   r™   r•   r1   r  ry   r{   r'   r*   rg   ¡  s
    

z!ElectraForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr  Nr  c                 C   st  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ| d| d¡¡nd}|dk	rh| d| d¡¡nd}|dk	r†| d| d¡¡nd}|dk	r¤| d| d¡¡nd}|dk	rÊ| d| d¡| d¡¡nd}| j||||||||	|
d	}|d }|  |¡}|  |¡}| d|¡}d}|dk	r0tƒ }|||ƒ}|
s`|f|dd…  }|dk	r\|f| S |S t	|||j
|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr!   r_   r­   r   r   r!  )rP   r  rH   r¡   rw   rø   r=  r1   r	   r   r¥   rç   )rz   r}   r¦   rc   r^   r§   r~   r  r«   rä   rå   Znum_choicesrñ   r"  Zpooled_outputrò   Zreshaped_logitsrþ   r#  rÄ   r'   r'   r*   r‰   «  sL    ÿý÷



üz ElectraForMultipleChoice.forward)
NNNNNNNNNN)rŠ   r‹   rŒ   rg   r   r  r  r   r  r   r  r   rL   r   r¶   r   r   r‰   r   r'   r'   r{   r*   r<  ™  s<   
ý          õôr<  zIELECTRA Model with a `language modeling` head on top for CLM fine-tuning.c                       sè   e Zd ZdgZ‡ fdd„Zdd„ Zdd„ Zee 	d¡ƒe
eed	deej eej eej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dœdd„ƒƒZddd„Zdd„ Z‡  ZS )ÚElectraForCausalLMr)  c                    sN   t ƒ  |¡ |jst d¡ t|ƒ| _t|ƒ| _t	 
|j|j¡| _|  ¡  d S )NzOIf you want to use `ElectraForCausalLM` as a standalone, add `is_decoder=True.`)rf   rg   rž   r5   Úwarningr   rø   rô   r*  r   r™   rj   ri   r+  Zinit_weightsry   r{   r'   r*   rg   ú  s    


zElectraForCausalLM.__init__c                 C   s   | j S r¼   r,  r  r'   r'   r*   r-    s    z(ElectraForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r¼   r,  )rz   Znew_embeddingsr'   r'   r*   r.  	  s    z(ElectraForCausalLM.set_output_embeddingsr
  r&  N)r}   r¦   rc   r^   r§   r~   r¨   r©   r  rã   r´   r«   rä   rå   r€   c                 C   s  |dk	r|n| j j}|	dk	r d}| j|||||||||
||||d}|d }|  |  |¡¡}d}|	dk	rÀ|dd…dd…dd…f  ¡ }|	dd…dd…f  ¡ }	tƒ }|| d| j j¡|	 d¡ƒ}|sì|f|dd…  }|dk	rè|f| S |S t	|||j
|j|j|jdS )aJ
  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, ElectraForCausalLM, ElectraConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-generator")
        >>> config = ElectraConfig.from_pretrained("google/electra-base-generator")
        >>> config.is_decoder = True
        >>> model = ElectraForCausalLM.from_pretrained("google/electra-base-generator", config=config)

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> prediction_logits = outputs.logits
        ```NF)r¦   rc   r^   r§   r~   r¨   r©   rã   r´   r«   rä   rå   r   r_   r!   )rþ   rò   rã   r¥   rç   rè   )rP   r  rø   r+  r*  r³   r	   r¡   ri   r   rã   r¥   rç   rè   )rz   r}   r¦   rc   r^   r§   r~   r¨   r©   r  rã   r´   r«   rä   rå   rµ   r"  r0  Zlm_lossZshifted_prediction_scoresr#  rÄ   r'   r'   r*   r‰     sJ    >óúzElectraForCausalLM.forwardc                 K   st   |j }|d kr| |¡}|d k	rh|d d j d }|j d |krF|}n|j d d }|d d …|d …f }|||dœS )Nr   r2   r!   )r}   r¦   rã   )rH   Znew_ones)rz   r}   rã   r¦   Zmodel_kwargsr„   Zpast_lengthZremove_prefix_lengthr'   r'   r*   Úprepare_inputs_for_generationw  s    
z0ElectraForCausalLM.prepare_inputs_for_generationc                    s.   d}|D ] }|t ‡ fdd„|D ƒƒf7 }q|S )Nr'   c                 3   s"   | ]}|  d ˆ  |j¡¡V  qdS )r   N)Zindex_selectr°   r‚   )r(   Z
past_state©Úbeam_idxr'   r*   r+   ‘  s     z4ElectraForCausalLM._reorder_cache.<locals>.<genexpr>)rë   )rz   rã   rB  Zreordered_pastZ
layer_pastr'   rA  r*   Ú_reorder_cache  s    ÿz!ElectraForCausalLM._reorder_cache)NNNNNNNNNNNNNN)NN)rŠ   r‹   rŒ   r1  rg   r-  r.  r   r  r  r    r   r  r   rL   r   r   r¶   r   r   r‰   r@  rC  r   r'   r'   r{   r*   r>  ô  sN   
              ñði
r>  )r#   )Lr   r±   r7   Zdataclassesr   Útypingr   r   r   r   rL   Ztorch.utils.checkpointr   Ztorch.nnr   r	   r
   Zactivationsr   r   Zmodeling_outputsr   r   r   r   r   r   r   r   Zmodeling_utilsr   r   Zpytorch_utilsr   r   r   Úutilsr   r   r   r   r   r    Zconfiguration_electrar"   Z
get_loggerrŠ   r5   r  r  rZ   ÚModuler[   r‘   r·   rÃ   rÁ   rÌ   rÑ   rÒ   rÛ   rí   rô   r÷   rý   ZELECTRA_START_DOCSTRINGr  r   r  r  r$  r>   r2  r3  r<  r>  r'   r'   r'   r*   Ú<module>   sœ   (
 

RC  ÿ4W]<ú{ûZúaù	SúJûeûT ÿ