
    gE$                    .   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 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+j/        e0          Z1dZ2dZ3dIdZ4 G d dej5                  Z6 G d dej5                  Z7 G d dej5                  Z8de7iZ9 G d dej5                  Z: G d dej5                  Z; G d d ej5                  Z< G d! d"ej5                  Z= G d# d$ej5                  Z> G d% d&ej5                  Z? G d' d(ej5                  Z@ G d) d*e           ZAe G d+ d,e'                      ZBd-ZCd.ZD e)d/eC           G d0 d1eA                      ZE G d2 d3ej5                  ZF e)d4eC           G d5 d6eA                      ZG e)d7eC           G d8 d9eA                      ZH e)d:eC           G d; d<eA                      ZI e)d=eC           G d> d?eA                      ZJ e)d@eC           G dA dBeA                      ZK e)dCeC           G dD dEeA                      ZL e)dFeC           G dG dHeAe                      ZMdS )JzPyTorch ELECTRA model.    N)	dataclass)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FNget_activation)GenerationMixin)"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                    	 ddl }ddl}ddl}n)# t          $ r t                              d            w xY wt          j                            |          }t          	                    d|            |j
                            |          }g }	g }
|D ]j\  }}t          	                    d| d|            |j
                            ||          }|	                    |           |
                    |           kt          |	|
          D ]\  }}|}	 t          | t                     r|                    dd          }|d	k    r,|                    d
d          }|                    dd
          }|                    dd          }|                    dd          }|                    d          }t'          d |D                       rt          	                    d|            | }|D ]}|                    d|          r|                    d|          }n|g}|d         dk    s|d         dk    rt+          |d          }ny|d         dk    s|d         dk    rt+          |d          }nP|d         dk    rt+          |d          }n3|d         dk    rt+          |d          }nt+          ||d                   }t-          |          dk    rt/          |d                    }||         }|                    d!          rt+          |d          }n|dk    r|                    |          }	 |j        |j        k    r t7          d"|j         d#|j         d$          n/# t6          $ r"}|xj        |j        |j        fz  c_         d}~ww xY wt;          d%| |           t=          j        |          |_         # tB          $ r}t;          d| ||           Y d}~d}~ww xY w| S )&z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape zelectra/embeddings/zgenerator/embeddings/	generatorzelectra/zdiscriminator/z
generator/dense_1dense_predictionz!generator_predictions/output_biaszgenerator_lm_head/bias/c              3      K   | ]}|d v V  	dS ))global_steptemperatureN ).0ns     h/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/electra/modeling_electra.py	<genexpr>z-load_tf_weights_in_electra.<locals>.<genexpr>d   s(      EE1166EEEEEE    z	Skipping z[A-Za-z]+_\d+z_(\d+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifier   r#   _embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )"renumpy
tensorflowImportErrorloggererrorospathabspathinfotrainlist_variablesload_variableappendzip
isinstanceElectraForMaskedLMreplacesplitany	fullmatchgetattrlenintendswith	transposeshape
ValueErrorargsprinttorch
from_numpydataAttributeError)modelconfigtf_checkpoint_pathdiscriminator_or_generatorr?   nptftf_path	init_varsnamesarraysnamerY   arrayoriginal_namepointerm_namescope_namesnumes                       r1   load_tf_weights_in_electrars   :   s   
			   Q	
 	
 	
 	 goo011G
KKBBBCCC''00IEF   eBBB5BBCCC&&w55Te5&)) 6 6e!3	%!344 T||$9;RSS)[88||J0@AA||L*==<<	+=>>D<< CE]^^D::c??D EEEEEEE 777888G + +<< 0&99 +"$((9f"="=KK#)(Kq>X--Q71J1J%gx88GG ^}44A&8P8P%gv66GG ^'777%gx88GG ^w..%g|<<GG%g{1~>>G{##q((k!n--C%clG}-- ,!'8448##U++=EK//$%ngm%n%nV[Va%n%n%nooo 0   7=%+66 5t55}EEE +E22GLL 	 	 	-m--tQ777HHHH	 LsL    &5CO-EO:0M+*O+
N5NN/O
O1O,,O1c                        e Zd ZdZ fdZ	 	 	 	 	 ddeej                 deej                 deej                 deej                 d	e	d
ej
        fdZ xZS )ElectraEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    t                                                       t          j        |j        |j        |j                  | _        t          j        |j        |j                  | _	        t          j        |j
        |j                  | _        t          j        |j        |j                  | _        t          j        |j                  | _        |                     dt%          j        |j                                      d          d           t+          |dd          | _        |                     d	t%          j        | j                                        t$          j        
          d           d S )N)padding_idxepsposition_ids)r#   F)
persistentposition_embedding_typeabsolutetoken_type_idsdtype)super__init__r   	Embedding
vocab_sizeembedding_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferr]   arangeexpandrT   r}   zerosrz   sizelongselfrb   	__class__s     r1   r   zElectraEmbeddings.__init__   sM   !|F,=v?Tbhbuvvv#%<0NPVPe#f#f %'\&2H&J_%`%`" f&;AVWWWz&"<== 	EL)GHHOOPWXXej 	 	
 	
 	
 (/v7PR\']']$ek$*;*@*@*B*B%*UUUbg 	 	
 	
 	
 	
 	
r3   Nr   	input_idsr   rz   inputs_embedspast_key_values_lengthreturnc                    ||                                 }n|                                 d d         }|d         }|| j        d d |||z   f         }|mt          | d          r2| j        d d d |f         }|                    |d         |          }	|	}n+t          j        |t
          j        | j        j                  }|| 	                    |          }| 
                    |          }
||
z   }| j        dk    r|                     |          }||z  }|                     |          }|                     |          }|S )Nr{   r#   r   r   r   devicer~   )r   rz   hasattrr   r   r]   r   r   r   r   r   r}   r   r   r   )r   r   r   rz   r   r   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr   
embeddingsr   s                r1   forwardzElectraEmbeddings.forward   sm     #..**KK',,..ss3K ^
,QQQ0FVlIl0l-lmL
 !t-.. m*.*=aaa*n*M'3J3Q3QR]^_R`bl3m3m0!A!&[
SWSdSk!l!l!l  00;;M $ : :> J J"%::
':55"&":":<"H"H--J^^J//
\\*--
r3   )NNNNr   )__name__
__module____qualname____doc__r   r   r]   
LongTensorFloatTensorrV   Tensorr   __classcell__r   s   @r1   ru   ru      s        QQ
 
 
 
 
. 15593759&'' 'E,-' !!12' u/0	'
   12' !$' 
' ' ' ' ' ' ' 'r3   ru   c                   ,    e Zd Zd fd	Zdej        dej        fdZ	 	 	 	 	 	 ddej        deej                 d	eej                 d
eej                 deej                 dee	e	ej                                   dee
         de	ej                 fdZ xZS )ElectraSelfAttentionNc                 D   t                                                       |j        |j        z  dk    r0t	          |d          s t          d|j         d|j         d          |j        | _        t          |j        |j        z            | _        | j        | j        z  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j        |j                  | _        |pt#          |dd          | _        | j        dk    s| j        d	k    r6|j        | _        t          j        d
|j        z  dz
  | j                  | _        |j        | _        d S )Nr   r   zThe hidden size (z6) is not a multiple of the number of attention heads ()r}   r~   relative_keyrelative_key_queryr=   r#   )r   r   hidden_sizenum_attention_headsr   rZ   rV   attention_head_sizeall_head_sizer   Linearquerykeyvaluer   attention_probs_dropout_probr   rT   r}   r   r   distance_embedding
is_decoderr   rb   r}   r   s      r1   r   zElectraSelfAttention.__init__   s    ::a??PVXhHiHi?8F$6 8 8 48 8 8  
 $*#= #&v'9F<V'V#W#W !58PPYv143EFF
9V/1CDDYv143EFF
z&"EFF'> (
'-zC
 C
$ '>99T=Y]q=q=q+1+ID(&(l1v7U3UXY3Y[_[s&t&tD# +r3   xr   c                     |                                 d d         | j        | j        fz   }|                    |          }|                    dddd          S )Nr{   r   r=   r#   r   )r   r   r   viewpermute)r   r   new_x_shapes      r1   transpose_for_scoresz)ElectraSelfAttention.transpose_for_scores   sP    ffhhssmt'?AY&ZZFF;yyAq!$$$r3   Fhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 ^   |                      |          }|d u}	|	r||d         }
|d         }|}n4|	rS|                     |                     |                    }
|                     |                     |                    }|}n||                     |                     |                    }
|                     |                     |                    }t	          j        |d         |
gd          }
t	          j        |d         |gd          }nP|                     |                     |                    }
|                     |                     |                    }|                     |          }|d u}| j        r|
|f}t	          j        ||
                    dd                    }| j	        dk    s| j	        dk    rt|j
        d         |
j
        d         }}|r>t	          j        |dz
  t          j        |j        	                              dd          }n:t	          j        |t          j        |j        	                              dd          }t	          j        |t          j        |j        	                              dd          }||z
  }|                     || j        z   dz
            }|                    |j        
          }| j	        dk    rt	          j        d||          }||z   }n?| j	        dk    r4t	          j        d||          }t	          j        d|
|          }||z   |z   }|t+          j        | j                  z  }|||z   }t0          j                            |d          }|                     |          }|||z  }t	          j        ||          }|                    dddd                                          }|                                d d         | j        fz   }|                    |          }|r||fn|f}| j        r||fz   }|S )Nr   r#   r=   dimr{   r   r   r   r   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r   r   r   r   r]   catr   matmulrX   r}   rY   tensorr   r   r   r   r   r   tor   einsummathsqrtr   r   
functionalsoftmaxr   r   
contiguousr   r   )r   r   r   r   r   r   r   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layer	use_cacheattention_scoresquery_length
key_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapeoutputss                               r1   r   zElectraSelfAttention.forward   sZ    !JJ}55
 3$> 	O."<&q)I(+K3NN 	O11$((;P2Q2QRRI33DJJ?T4U4UVVK3NN'11$((=2I2IJJI33DJJ}4M4MNNK	>!#4i"@aHHHI)^A%6$D!LLLKK11$((=2I2IJJI33DJJ}4M4MNNK//0ABB"$.	? 	6 (5N !<Y5H5HR5P5PQQ'>99T=Y]q=q=q'2'8';Y_Q=O*L w!&j1nEJWdWk!l!l!l!q!q" " "'l%*UbUi!j!j!j!o!oprtu!v!v"\*EJ}OcdddiijkmoppN%6H#'#:#:8dFb;bef;f#g#g #7#:#:AR#:#S#S +~==+0<8H+Wk+l+l(#36N#N  -1EEE16>NP[]q1r1r./4|<LiYm/n/n,#36T#TWs#s +di8P.Q.QQ%/.@ -//0@b/II ,,77  -	9O_kBB%--aAq99DDFF"/"4"4"6"6ss";t?Q>S"S%**+BCC6G]=/22mM]? 	2 11Gr3   NNNNNNF)r   r   r   r   r]   r   r   r   r   r   boolr   r   r   s   @r1   r   r      s.       , , , , , ,4%el %u| % % % % 7;15=A>BDH,1c c|c !!23c E-.	c
  ((9:c !)): ;c !uU->'?!@Ac $D>c 
u|	c c c c c c c cr3   r   c                   P     e Zd Z fdZdej        dej        dej        fdZ xZS )ElectraSelfOutputc                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j        |j	                  | _
        d S Nrx   )r   r   r   r   r   denser   r   r   r   r   r   s     r1   r   zElectraSelfOutput.__init__W  sf    Yv163EFF
f&8f>STTTz&"<==r3   r   input_tensorr   c                     |                      |          }|                     |          }|                     ||z             }|S r   r   r   r   r   r   r   s      r1   r   zElectraSelfOutput.forward]  @    

=11]33}|'CDDr3   r   r   r   r   r]   r   r   r   r   s   @r1   r   r   V  i        > > > > >U\  RWR^        r3   r   eagerc                       e Zd Zd fd	Zd Z	 	 	 	 	 	 ddej        deej                 deej                 deej                 d	eej                 d
ee	e	ej                                   dee
         de	ej                 fdZ xZS )ElectraAttentionNc                     t                                                       t          |j                 ||          | _        t          |          | _        t                      | _        d S )Nr}   )	r   r   ELECTRA_SELF_ATTENTION_CLASSES_attn_implementationr   r   outputsetpruned_headsr   s      r1   r   zElectraAttention.__init__k  s`    263NO,C
 
 
	 (//EEr3   c                    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          | j
        _        | j        j        t          |          z
  | j        _        | j        j        | j        j        z  | j        _        | j                            |          | _        d S )Nr   r#   r   )rU   r   r   r   r   r  r   r   r   r   r	  r   r   union)r   headsindexs      r1   prune_headszElectraAttention.prune_headss  s    u::??F7490$)2OQUQb
 
u
 -TY_eDD	*49=%@@	,TY_eDD	.t{/@%QOOO )-	(EE

(R	%"&)"?$)B_"_	 -33E::r3   Fr   r   r   r   r   r   r   r   c           	          |                      |||||||          }|                     |d         |          }	|	f|dd          z   }
|
S )Nr   r#   )r   r	  )r   r   r   r   r   r   r   r   self_outputsattention_outputr   s              r1   r   zElectraAttention.forward  sa     yy!"
 
  ;;|AFF#%QRR(88r3   r   r   )r   r   r   r   r  r]   r   r   r   r   r   r   r   r   s   @r1   r  r  j  s       " " " " " "; ; ;* 7;15=A>BDH,1 | !!23 E-.	
  ((9: !)): ; !uU->'?!@A $D> 
u|	       r3   r  c                   B     e Zd Z fdZdej        dej        fdZ xZS )ElectraIntermediatec                    t                                                       t          j        |j        |j                  | _        t          |j        t                    rt          |j                 | _        d S |j        | _        d S r   )r   r   r   r   r   intermediate_sizer   rN   
hidden_actstrr   intermediate_act_fnr   s     r1   r   zElectraIntermediate.__init__  sn    Yv163KLL
f'-- 	9'-f.?'@D$$$'-'8D$$$r3   r   r   c                 Z    |                      |          }|                     |          }|S r   )r   r  )r   r   s     r1   r   zElectraIntermediate.forward  s,    

=1100??r3   r   r   s   @r1   r  r    s^        9 9 9 9 9U\ el        r3   r  c                   P     e Zd Z fdZdej        dej        dej        fdZ xZS )ElectraOutputc                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j	        |j
                  | _        d S r   )r   r   r   r   r  r   r   r   r   r   r   r   r   s     r1   r   zElectraOutput.__init__  sf    Yv79KLL
f&8f>STTTz&"<==r3   r   r   r   c                     |                      |          }|                     |          }|                     ||z             }|S r   r   r   s      r1   r   zElectraOutput.forward  r   r3   r   r   s   @r1   r  r    r  r3   r  c                       e Zd Z fdZ	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 d	eeeej                                   d
ee	         deej                 fdZ
d Z xZS )ElectraLayerc                    t                                                       |j        | _        d| _        t	          |          | _        |j        | _        |j        | _        | j        r/| j        st          |  d          t	          |d          | _	        t          |          | _        t          |          | _        d S )Nr#   z> should be used as a decoder model if cross attention is addedr~   r  )r   r   chunk_size_feed_forwardseq_len_dimr  	attentionr   add_cross_attentionrZ   crossattentionr  intermediater  r	  r   s     r1   r   zElectraLayer.__init__  s    '-'E$)&11 +#)#= # 	_? j D!h!h!hiii"26S]"^"^"^D/77#F++r3   NFr   r   r   r   r   r   r   r   c           	         |
|d d         nd }|                      |||||          }	|	d         }
| j        r|	dd         }|	d         }n
|	dd          }d }| j        rp|nt          | d          st          d|  d          |
|d	d          nd }|                     |
||||||          }|d         }
||dd         z   }|d         }||z   }t          | j        | j        | j        |
          }|f|z   }| j        r||fz   }|S )
Nr=   )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   rZ   r'  r   feed_forward_chunkr#  r$  )r   r   r   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr  r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputs                    r1   r   zElectraLayer.forward  s    :H9S>"1"#5#5Y] !%/3 "0 "
 "
 2!4 ? 	1,QrT2G 6r :,QRR0G'+$? 	Q4@4!122  Dd D D D   @N?Yrss(;(;_c%&*&9&9 %&)!' '#  7q9 7" ==G ,C2+F( 14P P0#T%A4CSUe
 
  /G+ ? 	5!2 44Gr3   c                 \    |                      |          }|                     ||          }|S r   )r(  r	  )r   r  intermediate_outputr1  s       r1   r*  zElectraLayer.feed_forward_chunk  s2    "//0@AA{{#68HIIr3   r   )r   r   r   r   r]   r   r   r   r   r   r   r*  r   r   s   @r1   r!  r!    s       , , , , ," 7;15=A>BDH,1? ?|? !!23? E-.	?
  ((9:? !)): ;? !uU->'?!@A? $D>? 
u|	? ? ? ?B      r3   r!  c                   L    e Zd Z fdZ	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 d	eej                 d
eeeej                                   dee	         dee	         dee	         dee	         de
eej                 ef         fdZ xZS )ElectraEncoderc                     t                                                       | _        t          j        fdt          j                  D                       | _        d| _        d S )Nc                 .    g | ]}t                    S r.   )r!  )r/   _rb   s     r1   
<listcomp>z+ElectraEncoder.__init__.<locals>.<listcomp>  s!    #b#b#bQL$8$8#b#b#br3   F)	r   r   rb   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   s    `r1   r   zElectraEncoder.__init__  s`    ]#b#b#b#b%H`BaBa#b#b#bcc
&+###r3   NFTr   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictr   c                    |	rdnd }|rdnd }|r| j         j        rdnd }| j        r%| j        r|rt                              d           d}|rdnd }t          | j                  D ]\  }}|	r||fz   }|||         nd }|||         nd }| j        r)| j        r"|                     |j	        |||||||          }n ||||||||          }|d         }|r||d         fz  }|r$||d         fz   }| j         j        r||d         fz   }|	r||fz   }|
st          d |||||fD                       S t          |||||	          S )
Nr.   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r{   r#   r=   c              3      K   | ]}||V  	d S r   r.   )r/   vs     r1   r2   z)ElectraEncoder.forward.<locals>.<genexpr>]  s4       
 
 =  !===
 
r3   )last_hidden_stater?  r   
attentionscross_attentions)rb   r&  r>  trainingrC   warning_once	enumerater=  _gradient_checkpointing_func__call__tupler   )r   r   r   r   r   r   r?  r   r   r@  rA  all_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputss                       r1   r   zElectraEncoder.forward  sB    #7@BBD$5?bb4%6d4;;Zdrr`d& 	"4= 	" "##p   "	#,6RR$(44 #	V #	VOA|# I$58H$H!.7.CillO3B3N_Q//TXN* t}  $ A A )!"#)*"%	! 	! !-!"#)*"%! ! *!,M ;"}R'8&::"  V&9]1=M<O&O#;2 V+?=QRCSBU+U( 	E 1]4D D 	 
 
 "&%'(
 
 
 
 
 
 9+.+*1
 
 
 	
r3   )	NNNNNNFFT)r   r   r   r   r]   r   r   r   r   r   r   r   r   r   r   s   @r1   r5  r5    sD       , , , , , 7;15=A>BEI$(,1/4&*S
 S
|S
 !!23S
 E-.	S

  ((9:S
 !)): ;S
 "%e.?(@"ABS
 D>S
 $D>S
 'tnS
 d^S
 
uU\"$MM	NS
 S
 S
 S
 S
 S
 S
 S
r3   r5  c                   (     e Zd ZdZ fdZd Z xZS )ElectraDiscriminatorPredictionszEPrediction module for the discriminator, made up of two dense layers.c                    t                                                       t          j        |j        |j                  | _        t          |j                  | _        t          j        |j        d          | _	        || _
        d S Nr#   )r   r   r   r   r   r   r   r  
activationr)   rb   r   s     r1   r   z(ElectraDiscriminatorPredictions.__init__t  sf    Yv163EFF
():;; "	&*<a @ @r3   c                     |                      |          }|                     |          }|                     |                              d          }|S )Nr{   )r   rZ  r)   squeeze)r   discriminator_hidden_statesr   logitss       r1   r   z'ElectraDiscriminatorPredictions.forward|  sK    

#>??66&&}55==bAAr3   r   r   r   r   r   r   r   r   s   @r1   rW  rW  q  sM        OO          r3   rW  c                   (     e Zd ZdZ fdZd Z xZS )ElectraGeneratorPredictionszAPrediction module for the generator, made up of two dense layers.c                    t                                                       t          d          | _        t	          j        |j        |j                  | _        t	          j        |j	        |j                  | _
        d S )Ngelurx   )r   r   r   rZ  r   r   r   r   r   r   r   r   s     r1   r   z$ElectraGeneratorPredictions.__init__  sa    (00f&;AVWWWYv163HII


r3   c                     |                      |          }|                     |          }|                     |          }|S r   )r   rZ  r   )r   generator_hidden_statesr   s      r1   r   z#ElectraGeneratorPredictions.forward  s<    

#:;;66}55r3   r_  r   s   @r1   ra  ra    sR        KKJ J J J J      r3   ra  c                   (    e Zd ZdZeZeZdZdZ	d Z
dS )ElectraPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    electraTc                    t          |t          j                  rT|j        j                            d| j        j                   |j         |j        j        	                                 dS dS t          |t          j
                  r_|j        j                            d| j        j                   |j        +|j        j        |j                 	                                 dS dS t          |t          j                  r?|j        j        	                                 |j        j                            d           dS dS )zInitialize the weightsg        )meanstdNg      ?)rN   r   r   r6   r_   normal_rb   initializer_ranger9   zero_r   rw   r   fill_)r   modules     r1   _init_weightsz$ElectraPreTrainedModel._init_weights  s)   fbi(( 	* M&&CT[5R&SSS{& &&((((( '&-- 	*M&&CT[5R&SSS!-"6#56<<>>>>> .--- 	*K""$$$M$$S)))))	* 	*r3   N)r   r   r   r   r$   config_classrs   load_tf_weightsbase_model_prefixsupports_gradient_checkpointingrq  r.   r3   r1   rg  rg    sE         
 !L0O!&*#* * * * *r3   rg  c                       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   rF  )r   r   r   r   rx  r   r]   r   __annotations__r^  r   r   rF  r.   r3   r1   rw  rw    s          * )-D(5$
%,,, $FE$$$8<M8E%"345<<<59Ju01299999r3   rw  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            !       $    e Zd Z fdZd Zd Zd Z ee	                    d                     e
eee          	 	 	 	 	 	 	 	 	 	 	 	 	 ddeej                 d	eej                 d
eej                 deej                 deej                 deej                 deej                 deej                 deeej                          dee         dee         dee         dee         deeej                 ef         fd                        Z xZS )ElectraModelc                 8   t                                          |           t          |          | _        |j        |j        k    r$t          j        |j        |j                  | _        t          |          | _
        || _        |                                  d S r   )r   r   ru   r   r   r   r   r   embeddings_projectr5  encoderrb   	post_initr   s     r1   r   zElectraModel.__init__%  s       +F33 F$666&(i0EvGY&Z&ZD#%f--r3   c                     | j         j        S r   r   r   r   s    r1   get_input_embeddingsz!ElectraModel.get_input_embeddings1  s    ..r3   c                     || j         _        d S r   r  )r   r   s     r1   set_input_embeddingsz!ElectraModel.set_input_embeddings4  s    */'''r3   c                     |                                 D ]/\  }}| j        j        |         j                            |           0d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  )r   heads_to_pruner=  r  s       r1   _prune_headszElectraModel._prune_heads7  sU    
 +0022 	C 	CLE5Lu%/;;EBBBB	C 	Cr3   batch_size, sequence_length
checkpointoutput_typerr  Nr   r   r   rz   r   r   r   r   r?  r   r   r@  rA  r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }||t	          d          |+|                     ||           |                                }n.||                                d d         }nt	          d          |\  }}||j        n|j        }|	|	d         d         j        d         nd}|t          j
        ||          }|gt          | j        d          r1| j        j        d d d |f         }|                    ||          }|}n!t          j        |t          j        |          }|                     ||          }| j         j        rL|J|                                \  }}}||f}|t          j
        ||          }|                     |          }nd }|                     || j         j                  }|                     |||||	          }t          | d
          r|                     |          }|                     ||||||	|
|||
  
        }|S )NzDYou cannot specify both input_ids and inputs_embeds at the same timer{   z5You have to specify either input_ids or inputs_embedsr   r=   )r   r   r   )r   rz   r   r   r   r}  )	r   r   r   r   r?  r   r   r@  rA  )rb   r   r@  use_return_dictrZ   %warn_if_padding_and_no_attention_maskr   r   rY   r]   onesr   r   r   r   r   r   get_extended_attention_maskr   invert_attention_maskget_head_maskr<  r}  r~  )r   r   r   r   rz   r   r   r   r   r?  r   r   r@  rA  r   
batch_sizer   r   r   r   r   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr8  encoder_hidden_shapeencoder_extended_attention_maskr   s                               r1   r   zElectraModel.forward?  s   , 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] ]%>cddd"66y.QQQ#..**KK&',,..ss3KKTUUU!,
J%.%:!!@T DSC^!3A!6!<Q!?!?de!"ZFCCCN!t(899 [*./*HKZK*X'3J3Q3QR\^h3i3i0!A!&[
SY!Z!Z!Z"&"B"B>S^"_"_ ;! 	3&;&G=R=W=W=Y=Y: 7$68O#P %-).4HQW)X)X)X&.2.H.HI_.`.`++.2+&&y$+2OPP	%)'#9 ( 
 
 4-.. 	C 33MBBM2"7#B+/!5# % 
 
 r3   )NNNNNNNNNNNNN)r   r   r   r   r  r  r  r    ELECTRA_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r]   r   r   r   r   r   r   r   r   r   s   @r1   r{  r{    s       
 
 
 
 
/ / /0 0 0C C C +*+C+J+JKh+i+ijj&6$   -11515/3,0048<9==A$(,0/3&*W WEL)W !.W !.	W
 u|,W EL)W  -W  (5W !) 6W "$u'8"9:W D>W $D>W 'tnW d^W 
uU\"$FF	GW W W  kjW W W W Wr3   r{  c                   (     e Zd ZdZ fdZd Z xZS )ElectraClassificationHeadz-Head for sentence-level classification tasks.c                 \   t                                                       t          j        |j        |j                  | _        |j        |j        n|j        }t          d          | _	        t          j
        |          | _        t          j        |j        |j                  | _        d S )Nrc  )r   r   r   r   r   r   classifier_dropoutr   r   rZ  r   r   
num_labelsout_projr   rb   r  r   s      r1   r   z"ElectraClassificationHead.__init__  s    Yv163EFF
)/)B)NF%%TZTn 	 )00z"455	&"4f6GHHr3   c                     |d d dd d f         }|                      |          }|                     |          }|                     |          }|                      |          }|                     |          }|S )Nr   )r   r   rZ  r  )r   featureskwargsr   s       r1   r   z!ElectraClassificationHead.forward  sn    QQQ111WLLOOJJqMMOOALLOOMM!r3   r_  r   s   @r1   r  r    sR        77I I I I I      r3   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                       e Zd Z fdZ ee                    d                     edee	dd          	 	 	 	 	 	 	 	 	 	 dde
ej                 d	e
ej                 d
e
ej                 de
ej                 de
ej                 de
ej                 de
ej                 de
e         de
e         de
e         deeej                 ef         fd                        Z xZS ) ElectraForSequenceClassificationc                     t                                          |           |j        | _        || _        t	          |          | _        t          |          | _        |                                  d S r   )	r   r   r  rb   r{  rh  r  r<   r  r   s     r1   r   z)ElectraForSequenceClassification.__init__  sb        +#F++3F;; 	r3   r  z$bhadresh-savani/electra-base-emotionz'joy'gQ?r  r  rr  expected_outputexpected_lossNr   r   r   rz   r   r   labelsr   r@  rA  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }d}|Z| j         j        f| j        dk    rd| j         _        nN| j        dk    r7|j        t          j        k    s|j        t          j	        k    rd| j         _        nd| j         _        | j         j        dk    rWt                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        dk    rGt                      } ||                    d| j                  |                    d                    }n*| j         j        dk    rt                      } |||          }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        	          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   r   rz   r   r   r   r@  rA  r   r#   
regressionsingle_label_classificationmulti_label_classificationr{   rx  r^  r   rF  )rb   r  rh  r<   problem_typer  r   r]   r   rV   r   r\  r
   r   r	   r   r   rF  )r   r   r   r   rz   r   r   r  r   r@  rA  r]  sequence_outputr^  rx  loss_fctr	  s                    r1   r   z(ElectraForSequenceClassification.forward  s   6 &1%<kk$+B]&*ll))%'/!5# '3 
'
 
'
# 6a811{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB @ @&++b//RR)-III,..x// 	FY!<QRR!@@F)-)9TGf$$vE'5C2=	
 
 
 	
r3   
NNNNNNNNNN)r   r   r   r   r    r  r  r   r   r  r   r]   r   r   r   r   r   r   r   s   @r1   r  r    s            +*+C+J+JKh+i+ijj9,$   -11515/3,004)-,0/3&*D
 D
EL)D
 !.D
 !.	D

 u|,D
 EL)D
  -D
 &D
 $D>D
 'tnD
 d^D
 
uU\"$<<	=D
 D
 D
  kjD
 D
 D
 D
 D
r3   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                       e Zd Z fdZ ee                    d                     eee	          	 	 	 	 	 	 	 	 	 	 dde
ej                 de
ej                 de
ej                 de
ej                 d	e
ej                 d
e
ej                 de
ej                 de
e         de
e         de
e         deeej                 ef         fd                        Z xZS )ElectraForPreTrainingc                     t                                          |           t          |          | _        t	          |          | _        |                                  d S r   )r   r   r{  rh  rW  discriminator_predictionsr  r   s     r1   r   zElectraForPreTraining.__init__   sP       #F++)H)P)P&r3   r  r  rr  Nr   r   r   rz   r   r   r  r   r@  rA  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }d}|t	          j                    }|s|                    d|j        d                   dk    }|                    d|j        d                   |         }||         } |||                                          }n= ||                    d|j        d                   |                                          }|
s|f|dd         z   }||f|z   n|S t          |||j
        |j                  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  )rb   r  rh  r  r   r	   r   rY   floatrw  r   rF  )r   r   r   r   rz   r   r   r  r   r@  rA  r]  discriminator_sequence_outputr^  rx  r  active_lossactive_logitsactive_labelsr	  s                       r1   r   zElectraForPreTraining.forward(  s   ` &1%<kk$+B]&*ll))%'/!5# '3 
'
 
'
# )DA(F%//0MNN+--H),11"6S6YZ[6\]]abb &B0M0STU0V W WXc d &{ 3x}/B/B/D/DEExB0M0STU0V W WY_YeYeYgYghh 	FY!<QRR!@@F)-)9TGf$$vE*5C2=	
 
 
 	
r3   r  )r   r   r   r   r    r  r  r"   rw  r  r   r]   r   r   r   r   r   r   r   s   @r1   r  r    s            +*+C+J+JKh+i+ijj+FUdeee -11515/3,004)-,0/3&*S
 S
EL)S
 !.S
 !.	S

 u|,S
 EL)S
  -S
 &S
 $D>S
 'tnS
 d^S
 
uU\"$??	@S
 S
 S
 fe kjS
 S
 S
 S
 S
r3   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                       e Zd ZdgZ fdZd Zd Z ee	                    d                     e
deeddd	
          	 	 	 	 	 	 	 	 	 	 ddeej                 deej                 deej                 deej                 deej                 deej                 deej                 dee         dee         dee         deeej                 ef         fd                        Z xZS )rO   generator_lm_head.weightc                 
   t                                          |           t          |          | _        t	          |          | _        t          j        |j        |j	                  | _
        |                                  d S r   )r   r   r{  rh  ra  generator_predictionsr   r   r   r   generator_lm_headr  r   s     r1   r   zElectraForMaskedLM.__init__  sj       #F++%@%H%H"!#6+@&BS!T!Tr3   c                     | j         S r   r  r  s    r1   get_output_embeddingsz(ElectraForMaskedLM.get_output_embeddings      %%r3   c                     || _         d S r   r  )r   r   s     r1   set_output_embeddingsz(ElectraForMaskedLM.set_output_embeddings  s    !0r3   r  zgoogle/electra-small-generatorz[MASK]z'paris'gQ?)r  r  rr  maskr  r  Nr   r   r   rz   r   r   r  r   r@  rA  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}|Pt          j                    } ||                    d| j         j                  |                    d                    }|
s|f|dd         z   }||f|z   n|S t          |||j
        |j                  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  )rb   r  rh  r  r  r   r
   r   r   r   r   rF  )r   r   r   r   rz   r   r   r  r   r@  rA  re  generator_sequence_outputprediction_scoresrx  r  r	  s                    r1   r   zElectraForMaskedLM.forward  s2   8 &1%<kk$+B]"&,,))%'/!5# #/ 
#
 
#
 %<A$>! 667PQQ 223DEE*,,H8-222t{7MNNPVP[P[\^P_P_``D 	F'),CABB,GGF)-)9TGf$$vE$1?.9	
 
 
 	
r3   r  )r   r   r   _tied_weights_keysr   r  r  r    r  r  r   r   r  r   r]   r   r   r   r   r   r   r   s   @r1   rO   rO     s        55    & & &1 1 1 +*+C+J+JKh+i+ijj3"$!   -11515/3,004)-,0/3&*4
 4
EL)4
 !.4
 !.	4

 u|,4
 EL)4
  -4
 &4
 $D>4
 'tn4
 d^4
 
uU\"N2	34
 4
 4
  kj4
 4
 4
 4
 4
r3   rO   z
    Electra model with a token classification head on top.

    Both the discriminator and generator may be loaded into this model.
    c                       e Zd Z fdZ ee                    d                     edee	dd          	 	 	 	 	 	 	 	 	 	 dde
ej                 d	e
ej                 d
e
ej                 de
ej                 de
ej                 de
ej                 de
ej                 de
e         de
e         de
e         deeej                 ef         fd                        Z xZS )ElectraForTokenClassificationc                 V   t                                          |           |j        | _        t          |          | _        |j        |j        n|j        }t          j        |          | _	        t          j
        |j        |j                  | _        |                                  d S r   )r   r   r  r{  rh  r  r   r   r   r   r   r   r<   r  r  s      r1   r   z&ElectraForTokenClassification.__init__  s        +#F++)/)B)NF%%TZTn 	 z"455)F$68IJJr3   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   r   r   rz   r   r   r  r   r@  rA  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}|Ft                      } ||                    d| j                  |                    d                    }|
s|f|dd         z   }||f|z   n|S t          |||j	        |j
                  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  )rb   r  rh  r   r<   r
   r   r  r   r   rF  )r   r   r   r   rz   r   r   r  r   r@  rA  r]  r  r^  rx  r  r	  s                    r1   r   z%ElectraForTokenClassification.forward  s   2 &1%<kk$+B]&*ll))%'/!5# '3 
'
 
'
# )DA(F%(,5R(S(S%!>??'))H8FKKDO<<fkk"ooNND 	FY!<QRR!@@F)-)9TGf$$vE$5C2=	
 
 
 	
r3   r  )r   r   r   r   r    r  r  r   r   r  r   r]   r   r   r   r   r   r   r   s   @r1   r  r    s            +*+C+J+JKh+i+ijjY)$e   -11515/3,004)-,0/3&*1
 1
EL)1
 !.1
 !.	1

 u|,1
 EL)1
  -1
 &1
 $D>1
 'tn1
 d^1
 
uU\"$99	:1
 1
 1
  kj1
 1
 1
 1
 1
r3   r  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                       e Zd ZeZdZ fdZ ee	                    d                     e
deedddd	          	 	 	 	 	 	 	 	 	 	 	 ddeej                 deej                 deej                 deej                 deej                 deej                 deej                 deej                 dee         dee         dee         deeej                 ef         fd                        Z xZS )ElectraForQuestionAnsweringrh  c                     t                                          |           |j        | _        t          |          | _        t          j        |j        |j                  | _        | 	                                 d S r   )
r   r   r  r{  rh  r   r   r   
qa_outputsr  r   s     r1   r   z$ElectraForQuestionAnswering.__init__9  se        +#F++)F$68IJJ 	r3   r  z#bhadresh-savani/electra-base-squad2      z'a nice puppet'gQ@)r  r  rr  qa_target_start_indexqa_target_end_indexr  r  Nr   r   r   rz   r   r   start_positionsend_positionsr   r@  rA  r   c           
         ||n| j         j        }|                     |||||||	|
          }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}||t          |                                          dk    r|                    d          }t          |                                          dk    r|                    d          }|                    d          }|	                    d|          }|	                    d|          }t          |          } |||          } |||          }||z   dz  }|s||f|dd         z   }||f|z   n|S t          ||||j        |j        	          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   r   rz   r   r   r   r@  r   r#   r{   r   )ignore_indexr=   )rx  start_logits
end_logitsr   rF  )rb   r  rh  r  rQ   r\  r   rU   r   clampr
   r   r   rF  )r   r   r   r   rz   r   r   r  r  r   r@  rA  r]  r  r^  r  r  
total_lossignored_indexr  
start_lossend_lossr	  s                          r1   r   z#ElectraForQuestionAnswering.forwardC  s   D &1%<kk$+B]&*ll))%'/!5 '3 	'
 	'
# 6a811#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEO)//=AAM']CCCH!,@@Jx
M::H$x/14J 	R ,ABB/0F 0:/EZMF**6Q+%!5C2=
 
 
 	
r3   )NNNNNNNNNNN)r   r   r   r$   rr  rt  r   r    r  r  r   r   r  r   r]   r   r   r   r   r   r   r   s   @r1   r  r  .  s        !L!     +*+C+J+JKh+i+ijj80$ )   -11515/3,0042604,0/3&*J
 J
EL)J
 !.J
 !.	J

 u|,J
 EL)J
  -J
 "%,/J
  -J
 $D>J
 'tnJ
 d^J
 
uU\"$@@	AJ
 J
 J
  kjJ
 J
 J
 J
 J
r3   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                       e Zd Z fdZ ee                    d                     eee	e
          	 	 	 	 	 	 	 	 	 	 ddeej                 deej                 deej                 deej                 d	eej                 d
eej                 deej                 dee         dee         dee         deeej                 e	f         fd                        Z xZS )ElectraForMultipleChoicec                     t                                          |           t          |          | _        t	          |          | _        t          j        |j        d          | _	        | 
                                 d S rY  )r   r   r{  rh  r   sequence_summaryr   r   r   r<   r  r   s     r1   r   z!ElectraForMultipleChoice.__init__  sh       #F++ / 7 7)F$6:: 	r3   z(batch_size, num_choices, sequence_lengthr  Nr   r   r   rz   r   r   r  r   r@  rA  r   c                    |
|
n| j         j        }
||j        d         n|j        d         }|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|=|                    d|                    d          |                    d                    nd}|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }|                    d|          }d}|t                      } |||          }|
s|f|dd         z   }||f|z   n|S t          |||j
        |j                  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  )rb   r  rY   r   r   rh  r  r<   r
   r   r   rF  )r   r   r   r   rz   r   r   r  r   r@  rA  num_choicesr]  r  pooled_outputr^  reshaped_logitsrx  r  r	  s                       r1   r   z ElectraForMultipleChoice.forward  s0   2 &1%<kk$+B],5,Aioa((}GZ[\G]>G>SINN2y~~b'9'9:::Y]	M[Mg,,R1D1DR1H1HIIImqM[Mg,,R1D1DR1H1HIIImqGSG_|((\->->r-B-BCCCei ( r=#5#5b#9#9=;M;Mb;Q;QRRR 	 '+ll))%'/!5# '3 
'
 
'
# 6a8--o>>// ++b+66'))H8OV44D 	F%'*Eabb*IIF)-)9TGf$$vE("5C2=	
 
 
 	
r3   r  )r   r   r   r   r    r  r  r   r  r   r  r   r]   r   r   r   r   r   r   r   s   @r1   r  r    s            +*+C+J+JKu+v+vww&-$   -11515/3,004)-,0/3&*@
 @
EL)@
 !.@
 !.	@

 u|,@
 EL)@
  -@
 &@
 $D>@
 'tn@
 d^@
 
uU\"$==	>@
 @
 @
  xw@
 @
 @
 @
 @
r3   r  zIELECTRA Model with a `language modeling` head on top for CLM fine-tuning.c            #       D    e Zd ZdgZ fdZd Zd Z ee	                    d                     e
ee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddeej                 d	eej                 d
eej                 deej                 deej                 deej                 deej                 deej                 deej                 deeej                          dee         dee         dee         dee         deeej                 ef         fd                        Zd Z xZS )ElectraForCausalLMr  c                 L   t                                          |           |j        st                              d           t          |          | _        t          |          | _        t          j
        |j        |j                  | _        |                                  d S )NzOIf you want to use `ElectraForCausalLM` as a standalone, add `is_decoder=True.`)r   r   r   rC   warningr{  rh  ra  r  r   r   r   r   r  init_weightsr   s     r1   r   zElectraForCausalLM.__init__  s         	nNNlmmm#F++%@%H%H"!#6+@&BS!T!Tr3   c                     | j         S r   r  r  s    r1   r  z(ElectraForCausalLM.get_output_embeddings  r  r3   c                     || _         d S r   r  )r   new_embeddingss     r1   r  z(ElectraForCausalLM.set_output_embeddings
  s    !/r3   r  r  Nr   r   r   rz   r   r   r   r   r  r?  r   r   r@  rA  r   c                 x   ||n| j         j        }|	d}|                     |||||||||
||||          }|d         }|                     |                     |                    }d}|	|ddddddf                                         }|	ddddf                                         }	t                      } ||                    d| j         j                  |	                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j
        |j        |j        |j                  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   r   rz   r   r   r   r   r?  r   r   r@  rA  r   r{   r#   )rx  r^  r?  r   rF  rG  )rb   r  rh  r  r  r   r
   r   r   r   r?  r   rF  rG  )r   r   r   r   rz   r   r   r   r   r  r?  r   r   r@  rA  r   r  r  lm_lossshifted_prediction_scoresr  r	  s                         r1   r   zElectraForCausalLM.forward  s   | &1%<kk$+B]I,,))%'"7#9+/!5#  
 
  "!* 2243M3Mo3^3^__(9!!!SbS!!!)(D(O(O(Q(Q%AAAqrrE]--//F'))Hh8==b$+BXYY[a[f[fgi[j[jkkG 	L')GABBK7F,3,?WJ''VK0$#3!/)$5
 
 
 	
r3   c                 T    d}|D ]!}|t          fd|D                       fz  }"|S )Nr.   c              3   t   K   | ]2}|                     d                     |j                            V  3dS )r   N)index_selectr   r   )r/   
past_statebeam_idxs     r1   r2   z4ElectraForCausalLM._reorder_cache.<locals>.<genexpr>|  sC      nnU_j--aZ=N1O1OPPnnnnnnr3   )rM  )r   r?  r  reordered_past
layer_pasts     `  r1   _reorder_cachez!ElectraForCausalLM._reorder_cachex  sQ    ) 	 	Jnnnncmnnnnn NN r3   )NNNNNNNNNNNNNN)r   r   r   r  r   r  r  r    r  r  r"   r   r  r   r]   r   r   r   r   r   r   r  r   r   s   @r1   r  r    s        55
 
 
 
 
& & &0 0 0 +*+C+J+JKh+i+ijj+L[jkkk -11515/3,0048<9=)-8<$(,0/3&*f
 f
EL)f
 !.f
 !.	f

 u|,f
 EL)f
  -f
  (5f
 !) 6f
 &f
 "$u|"45f
 D>f
 $D>f
 'tnf
 d^f
  
uU\"$EE	F!f
 f
 f
 lk kjf
R      r3   r  )r%   )Nr   r   rE   dataclassesr   typingr   r   r   r   r]   torch.utils.checkpointr   torch.nnr	   r
   r   activationsr   r   
generationr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   r   pytorch_utilsr   r   r   utilsr   r   r   r    r!   r"   configuration_electrar$   
get_loggerr   rC   r  r  rs   Moduleru   r   r   r  r  r  r  r!  r5  rW  ra  rg  rw  ELECTRA_START_DOCSTRINGr  r{  r  r  r  rO   r  r  r  r  r.   r3   r1   <module>r     sX      				 ! ! ! ! ! ! / / / / / / / / / / / /            A A A A A A A A A A 1 1 1 1 1 1 1 1 ) ) ) ) ) )	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ? > > > > > > > l l l l l l l l l l                1 0 0 0 0 0 
	H	%	%: !O O O Od? ? ? ? ?	 ? ? ?FC C C C C29 C C CN    	    !" 0 0 0 0 0ry 0 0 0h    ")        BI   S S S S S29 S S SnZ
 Z
 Z
 Z
 Z
RY Z
 Z
 Z
z    bi   &    ")   $* * * * *_ * * *: : : : : :+ : : :8  9 x V
  x x x x x) x x xv    	   .   W
 W
 W
 W
 W
'= W
 W
 W
t 
  ^
 ^
 ^
 ^
 ^
2 ^
 ^
 ^
B   P
 P
 P
 P
 P
/ P
 P
 P
f 
  G
 G
 G
 G
 G
$: G
 G
 G
T   b
 b
 b
 b
 b
"8 b
 b
 b
J   Q
 Q
 Q
 Q
 Q
5 Q
 Q
 Q
h SUl F F F F F/ F F F F Fr3   