U
    4Af<                     @   sL  d dl mZmZmZ d dlZd dlmZ d dlZd dl	m
Z d dl
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 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&m'Z'm(Z(m)Z) d	dl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 e.1e2Z3dZ4dZ5ej6Z6ej7j8G dd de+Z9dZ:dZ;G dd dej<Z=G dd dej<Z>G dd dej<Z?G dd dej<Z@G dd dej<ZAG dd  d ej<ZBG d!d" d"ej<ZCG d#d$ d$ej<ZDG d%d& d&ej<ZEG d'd( d(ej<ZFG d)d* d*ej<ZGG d+d, d,e&ZHG d-d. d.ej<ZIe,d/e:G d0d1 d1eHZJe'eJe4ee5 G d2d3 d3ej<ZKG d4d5 d5ej<ZLe,d6e:G d7d8 d8eHZMe'eMe4ee5 G d9d: d:ej<ZNe,d;e:G d<d= d=eHZOd>ZPe)eOe;Qd?eP  e(eOe9e5d@ G dAdB dBej<ZRe,dCe:G dDdE dEeHZSe'eSe4e#e5 dFdG ZTG dHdI dIej<ZUG dJdK dKej<ZVe,dLe:G dMdN dNeHZWe)eWe;QdO e'eWe4e e5 G dPdQ dQej<ZXe,dRe:G dSdT dTeHZYe'eYe4e!e5 G dUdV dVej<ZZG dWdX dXej<Z[e,dYe:G dZd[ d[eHZ\e'e\e4e"e5 G d\d] d]ej<Z]e,d^e:G d_d` d`eHZ^e'e^e4ee5 dS )a    )CallableOptionalTupleN)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)partitioning)dot_product_attention_weights)flatten_dictunflatten_dict)lax   )FlaxBaseModelOutput-FlaxBaseModelOutputWithPastAndCrossAttentions%FlaxCausalLMOutputWithCrossAttentionsFlaxMaskedLMOutputFlaxMultipleChoiceModelOutput FlaxQuestionAnsweringModelOutputFlaxSequenceClassifierOutputFlaxTokenClassifierOutput)ACT2FNFlaxPreTrainedModelappend_call_sample_docstring append_replace_return_docstringsoverwrite_call_docstring)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )ElectraConfigz"google/electra-small-discriminatorr"   c                   @   sL   e Zd ZU dZdZejed< dZe	e
ej  ed< dZe	e
ej  ed< dS )FlaxElectraForPreTrainingOutputaa  
    Output type of [`ElectraForPreTraining`].

    Args:
        logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `jnp.ndarray` (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logitshidden_states
attentions)__name__
__module____qualname____doc__r$   jnpndarray__annotations__r%   r   r   r&    r.   r.   U/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/electra/modeling_flax_electra.pyr#   ;   s   
r#   a  

    This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading, saving and converting weights from PyTorch models)

    This model is also a Flax Linen
    [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
    regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.

    Finally, this model supports inherent JAX features such as:

    - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
    - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
    - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
    - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)

    Parameters:
        config ([`ElectraConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`numpy.ndarray` 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 (`numpy.ndarray` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`numpy.ndarray` 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]`.
        head_mask (`numpy.ndarray` of shape `({0})`, `optional):
            Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

c                   @   sB   e Zd ZU dZeed< ejZejed< dd Z	de
ddd	Zd
S )FlaxElectraEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.configdtypec                 C   s   t j| jj| jjtj jj| jjdd| _	t j| jj
| jjtj jj| jjdd| _t j| jj| jjtj jj| jjdd| _t j| jj| jd| _t j| jjd| _d S )N)stddev)Zembedding_initepsilonr2   Zrate)nnZEmbedr1   
vocab_sizeembedding_sizejaxinitializersnormalinitializer_rangeword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsr2   Dropouthidden_dropout_probdropoutselfr.   r.   r/   setup   s"    zFlaxElectraEmbeddings.setupTdeterministicc           
      C   sX   |  |d}| |d}| |d}|| | }	| |	}	| j|	|d}	|	S )Ni4rJ   )r>   astyper@   rA   rB   rF   )
rH   	input_idstoken_type_idsposition_idsattention_maskrK   Zinputs_embedsZposition_embedsrA   r%   r.   r.   r/   __call__   s    
zFlaxElectraEmbeddings.__call__N)Tr'   r(   r)   r*   r"   r-   r+   float32r2   rI   boolrR   r.   r.   r.   r/   r0      s
   
r0   c                   @   sr   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
dd Zd	d
 Zejdd Zdeej eedddZdS )FlaxElectraSelfAttentionr1   Fcausalr2   c                 C   s   | j j| j j | _| j j| j j dkr.tdtj| j j| jtjj	
| j jd| _tj| j j| jtjj	
| j jd| _tj| j j| jtjj	
| j jd| _| jrttjd| j jfdddd| _d S )Nr   z`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads`                    : {self.config.num_attention_heads})r2   kernel_initr!   rU   r2   )r1   hidden_sizenum_attention_headshead_dim
ValueErrorr7   Denser2   r:   r;   r<   r=   querykeyvaluerW   r	   r+   onesr?   causal_maskrG   r.   r.   r/   rI      s2     zFlaxElectraSelfAttention.setupc                 C   s"   | |jd d | jj| jf S N   )reshapeshaper1   r[   r\   rH   r%   r.   r.   r/   _split_heads   s    z%FlaxElectraSelfAttention._split_headsc                 C   s   | |jd d | jjf S rd   )rf   rg   r1   rZ   rh   r.   r.   r/   _merge_heads   s    z%FlaxElectraSelfAttention._merge_headsc                 C   s   |  dd}| ddtj|j|j}| ddtj|j|j}| dddd }|r|jj^ }	}
}}|j}dt|	 |ddf }t	|j||}t	|j||}||_||_|jd	 }|j| |_t
t|
|| k t|	d	||
f }t||}|||fS )
a[  
        This function takes projected key, value states from a single input token and concatenates the states to cached
        states from previous steps. This function is slighly adapted from the official Flax repository:
        https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
        cache
cached_keycached_valuecache_indexc                   S   s   t jdt jdS )Nr   rY   )r+   arrayZint32r.   r.   r.   r/   <lambda>       z@FlaxElectraSelfAttention._concatenate_to_cache.<locals>.<lambda>r   r   r!   )has_variablevariabler+   zerosrg   r2   ra   lenr   dynamic_update_slicebroadcast_toarangetupler   )rH   r`   ra   r_   rQ   Zis_initializedrl   rm   rn   Z
batch_dims
max_lengthZ	num_headsZdepth_per_headZ	cur_indexindicesZnum_updated_cache_vectorsZpad_maskr.   r.   r/   _concatenate_to_cache   s(    	

z.FlaxElectraSelfAttention._concatenate_to_cacheNT)key_value_states
init_cacheoutput_attentionsc                 C   s  |d k	}|j d }	| |}
|r6| |}| |}n| |}| |}| |
}
| |}| |}| jr|
j d |j d  }}| ddr| jd d }| jd d j d }t	| j
dd|dfdd||f}n"| j
d d d d d |d |f }t||	f|j dd   }|d k	rJ| jrJttj|dd|j }t||}n&| jrX|}n|d k	rptj|dd}| jr| dds|r| |||
|\}}}|d k	rt|dkt|j d| jt|j t| jj| j}nd }d }|s| jjdkr| d	}t|
|||| jjd
|| jd d	}|d k	rLtd||}td||}||j d d d }|r||fn|f}|S )Nr   r!   rk   rl   rn   )Zaxisg        rF   T)biasdropout_rngZdropout_rateZbroadcast_dropoutrK   r2   	precisionz...hqk,h->...hqkz...hqk,...khd->...qhdre   ))rg   r_   r`   ra   ri   rW   rs   	variablesr   Zdynamic_slicerc   r+   rx   Zexpand_dimsr   r}   selectfullrM   r2   Zfinfominr1   Zattention_probs_dropout_probZmake_rngr   Zeinsumrf   )rH   r%   rQ   layer_head_maskr~   r   rK   r   Zis_cross_attention
batch_sizeZquery_statesZ
key_statesZvalue_statesZquery_lengthZ
key_lengthZ
mask_shiftZmax_decoder_lengthrc   Zattention_biasr   Zattn_weightsattn_outputoutputsr.   r.   r/   rR     s    







 
 
"
   



z!FlaxElectraSelfAttention.__call__)NFTF)r'   r(   r)   r"   r-   rW   rU   r+   rT   r2   rI   ri   rj   r7   compactr}   r   r,   rR   r.   r.   r.   r/   rV      s"   

$    rV   c                   @   s>   e Zd ZU eed< ejZejed< dd Zd
e	dddZ
d	S )FlaxElectraSelfOutputr1   r2   c                 C   sR   t j| jjtj j| jj| jd| _	t j
| jj| jd| _
t j| jjd| _d S )NrX   r2   r4   r6   )r7   r^   r1   rZ   r:   r;   r<   r=   r2   denserB   rC   rD   rE   rF   rG   r.   r.   r/   rI   l  s    zFlaxElectraSelfOutput.setupTrJ   c                 C   s*   |  |}| j||d}| || }|S NrJ   r   rF   rB   )rH   r%   Zinput_tensorrK   r.   r.   r/   rR   u  s    
zFlaxElectraSelfOutput.__call__N)Tr'   r(   r)   r"   r-   r+   rT   r2   rI   rU   rR   r.   r.   r.   r/   r   h  s   
	r   c                   @   sJ   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
ded	d
dZdS )FlaxElectraAttentionr1   FrW   r2   c                 C   s,   t | j| j| jd| _t| j| jd| _d S )NrW   r2   rY   )rV   r1   rW   r2   rH   r   outputrG   r.   r.   r/   rI     s    zFlaxElectraAttention.setupNT)r   c              	   C   sL   | j |||||||d}|d }	| j|	||d}|f}
|rH|
|d f7 }
|
S )N)r   r~   r   rK   r   r   rJ   r!   )rH   r   )rH   r%   rQ   r   r~   r   rK   r   Zattn_outputsr   r   r.   r.   r/   rR     s    	zFlaxElectraAttention.__call__)NFTF)r'   r(   r)   r"   r-   rW   rU   r+   rT   r2   rI   rR   r.   r.   r.   r/   r   }  s   
	    r   c                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxElectraIntermediater1   r2   c                 C   s8   t j| jjtj j| jj| jd| _	t
| jj | _d S )Nr   )r7   r^   r1   Zintermediate_sizer:   r;   r<   r=   r2   r   r   
hidden_act
activationrG   r.   r.   r/   rI     s    zFlaxElectraIntermediate.setupc                 C   s   |  |}| |}|S N)r   r   rh   r.   r.   r/   rR     s    

z FlaxElectraIntermediate.__call__N
r'   r(   r)   r"   r-   r+   rT   r2   rI   rR   r.   r.   r.   r/   r     s   
r   c                   @   s>   e Zd ZU eed< ejZejed< dd Zd
e	dddZ
d	S )FlaxElectraOutputr1   r2   c                 C   sR   t j| jjtj j| jj| jd| _	t j
| jjd| _t j| jj| jd| _d S )Nr   r6   r4   )r7   r^   r1   rZ   r:   r;   r<   r=   r2   r   rD   rE   rF   rB   rC   rG   r.   r.   r/   rI     s    zFlaxElectraOutput.setupTrJ   c                 C   s*   |  |}| j||d}| || }|S r   r   )rH   r%   attention_outputrK   r.   r.   r/   rR     s    
zFlaxElectraOutput.__call__N)Tr   r.   r.   r.   r/   r     s   
	r   c                   @   sR   e Zd ZU eed< ejZejed< dd Zde	ej
 e	ej
 eeedd	d
ZdS )FlaxElectraLayerr1   r2   c                 C   s\   t | j| jj| jd| _t| j| jd| _t| j| jd| _| jj	rXt | jd| jd| _
d S )Nr   rY   F)r   r1   Z
is_decoderr2   	attentionr   intermediater   r   add_cross_attentioncrossattentionrG   r.   r.   r/   rI     s
    zFlaxElectraLayer.setupNFT)encoder_hidden_statesencoder_attention_maskr   rK   r   c	                 C   s   | j ||||||d}	|	d }
|d k	rD| j|
|||||d}|d }
| |
}| j||
|d}|f}|r||	d f7 }|d k	r||d f7 }|S )N)r   r   rK   r   r   )rQ   r   r~   rK   r   rJ   r!   )r   r   r   r   )rH   r%   rQ   r   r   r   r   rK   r   Zattention_outputsr   Zcross_attention_outputsr   r.   r.   r/   rR     s6    
zFlaxElectraLayer.__call__)NNFTF)r'   r(   r)   r"   r-   r+   rT   r2   rI   r   r,   rU   rR   r.   r.   r.   r/   r     s   
     r   c                	   @   sb   e Zd ZU eed< ejZejed< dZe	ed< dd Z
deej eej e	e	e	e	e	d	d
dZdS )FlaxElectraLayerCollectionr1   r2   Fgradient_checkpointingc                    sR   j r2ttdd  fddtjjD _nfddtjjD _d S )N)         )Zstatic_argnumsc                    s"   g | ]} j t|jd qS )namer2   )r1   strr2   .0iZFlaxElectraCheckpointLayerrH   r.   r/   
<listcomp>  s   z4FlaxElectraLayerCollection.setup.<locals>.<listcomp>c                    s"   g | ]}t  jt| jd qS r   )r   r1   r   r2   r   rG   r.   r/   r     s   )r   rematr   ranger1   num_hidden_layerslayersrG   r.   r   r/   rI     s    



z FlaxElectraLayerCollection.setupNTr   r   r   rK   r   output_hidden_statesreturn_dictc              
   C   s$  |rdnd }|	rdnd }|r(|d k	r(dnd }|d k	rj|j d t| jkrjtdt| j d|j d  dt| jD ]l\}}|	r||f7 }||||d k	r|| nd |||||}|d }|rt||d f7 }|d k	rt||d f7 }qt|	r||f7 }||||f}|
stdd	 |D S t||||d
S )Nr.   r   z&The head_mask should be specified for z/ layers, but it is for                         .r!   re   c                 s   s   | ]}|d k	r|V  qd S r   r.   )r   vr.   r.   r/   	<genexpr>R  s      z6FlaxElectraLayerCollection.__call__.<locals>.<genexpr>)Zlast_hidden_stater%   r&   cross_attentions)rg   rv   r   r]   	enumeraterz   r   )rH   r%   rQ   	head_maskr   r   r   rK   r   r   r   Zall_attentionsZall_hidden_statesZall_cross_attentionsr   layerZlayer_outputsr   r.   r.   r/   rR     sJ    

z#FlaxElectraLayerCollection.__call__)NNFTFFTr'   r(   r)   r"   r-   r+   rT   r2   r   rU   rI   r   r,   rR   r.   r.   r.   r/   r   
  s(   
       r   c                	   @   sb   e Zd ZU eed< ejZejed< dZe	ed< dd Z
deej eej e	e	e	e	e	d	d
dZdS )FlaxElectraEncoderr1   r2   Fr   c                 C   s   t | j| j| jd| _d S )Nr2   r   )r   r1   r2   r   r   rG   r.   r.   r/   rI   b  s
    zFlaxElectraEncoder.setupNTr   c                 C   s   | j |||||||||	|
d
S )Nr   r   r   r   rK   r   r   r   )r   )rH   r%   rQ   r   r   r   r   rK   r   r   r   r.   r.   r/   rR   i  s    zFlaxElectraEncoder.__call__)NNFTFFTr   r.   r.   r.   r/   r   ]  s(   
       r   c                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxElectraGeneratorPredictionsr1   r2   c                 C   s0   t j| jj| jd| _t j| jj| jd| _d S )Nr4   rY   )r7   rB   r1   rC   r2   r^   r9   r   rG   r.   r.   r/   rI     s    z%FlaxElectraGeneratorPredictions.setupc                 C   s(   |  |}t| jj |}| |}|S r   )r   r   r1   r   rB   rh   r.   r.   r/   rR     s    

z(FlaxElectraGeneratorPredictions.__call__Nr   r.   r.   r.   r/   r     s   
r   c                   @   s:   e Zd ZU dZeed< ejZejed< dd Z	dd Z
dS )	#FlaxElectraDiscriminatorPredictionszEPrediction module for the discriminator, made up of two dense layers.r1   r2   c                 C   s,   t j| jj| jd| _t jd| jd| _d S )NrY   r!   )r7   r^   r1   rZ   r2   r   dense_predictionrG   r.   r.   r/   rI     s    z)FlaxElectraDiscriminatorPredictions.setupc                 C   s.   |  |}t| jj |}| |d}|S )Nr   )r   r   r1   r   r   squeezerh   r.   r.   r/   rR     s    
z,FlaxElectraDiscriminatorPredictions.__call__N)r'   r(   r)   r*   r"   r-   r+   rT   r2   rI   rR   r.   r.   r.   r/   r     s
   
r   c                       s   e Zd ZU dZeZdZdZej	e
d< ddejddfeeeejeed	 fd
dZdd ZdejjeeedddZdd Zeeddeejjeee ee ee edddZ  ZS )FlaxElectraPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    electraNmodule_class)r!   r!   r   TF)r1   input_shapeseedr2   _do_initr   c           	         s4   | j f |||d|}t j||||||d d S )Nr1   r2   r   )r   r   r2   r   )r   super__init__)	rH   r1   r   r   r2   r   r   kwargsmodule	__class__r.   r/   r     s    
z#FlaxElectraPreTrainedModel.__init__c                 C   s   | j | j| jdd| _d S )NTr   )r   r1   r2   _modulerG   r.   r.   r/   enable_gradient_checkpointing  s
    z8FlaxElectraPreTrainedModel.enable_gradient_checkpointing)rngr   paramsreturnc                 C   s(  t j|dd}t |}t t t |jd |}t |}t | j	j
| j	jf}tj|\}	}
|	|
d}| j	jrt || j	jf }|}| jj||||||||dd	}n| jj||||||dd}|d }|d k	r tt|}tt|}| jD ]}|| ||< qt | _tt|S |S d S )NrL   rY   r   )r   rF   F)r   r   )r+   ru   Z
zeros_likerx   ry   
atleast_2drg   	ones_likerb   r1   r   r[   r:   randomsplitr   rZ   r   initr   r   Z_missing_keyssetr   r   )rH   r   r   r   rN   rO   rP   rQ   r   Z
params_rngr   rngsr   r   Zmodule_init_outputsZrandom_paramsZmissing_keyr.   r.   r/   init_weights  sN    


      

z'FlaxElectraPreTrainedModel.init_weightsc                 C   sl   t j||fdd}t j|dd}t t t |jd |j}| jjt	j
d|||ddd}t|d S )	aW  
        Args:
            batch_size (`int`):
                batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
            max_length (`int`):
                maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
                cache.
        rL   rY   r   r   FT)r   r   rk   )r+   rb   r   rx   ry   r   rg   r   r   r:   r   PRNGKeyr   )rH   r   r{   rN   rQ   rP   Zinit_variablesr.   r.   r/   r     s    
 
     z%FlaxElectraPreTrainedModel.init_cachebatch_size, sequence_length)r   r   trainr   r   r   past_key_valuesc                 C   s  |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}|d krNt|}|d krvttt|j	d |j	}|d krt|}|d krt
| j j| j jf}i }|	d k	r|	|d< d|p| ji}| j jr|r||d< dg}nd}| jj|tj|ddtj|ddtj|ddtj|ddtj|dd|||
 |||||d}|d k	rr|rr|\}}t|d |d	< |S |d k	r|s|\}}|d d
 t|d f |d
d   }nV| jj|tj|ddtj|ddtj|ddtj|ddtj|dd|
 ||||d}|S )Nr   rF   r   rk   FrL   rY   )rO   rP   r   r   r   rK   r   r   r   r   mutabler   r!   )rO   rP   r   rK   r   r   r   r   )r1   r   r   r   r+   r   rx   ry   r   rg   rb   r   r[   r   r   r   applyro   r   )rH   rN   rQ   rO   rP   r   r   r   r   r   r   r   r   r   r   r   inputsr   r   r.   r.   r/   rR     st    
 

(z#FlaxElectraPreTrainedModel.__call__)N)NNNNNNNNFNNNN) r'   r(   r)   r*   r"   config_classZbase_model_prefixr   r7   Moduler-   r+   rT   r   intr2   rU   r   r   r:   r   r   r   r   r   r   ELECTRA_INPUTS_DOCSTRINGformatdictr   rR   __classcell__r.   r.   r   r/   r     sV   
+             	r   c                
   @   sj   e Zd ZU eed< ejZejed< dZe	ed< dd Z
deej eej eej e	e	e	e	e	d	d
dZdS )FlaxElectraModuler1   r2   Fr   c                 C   sR   t | j| jd| _| jj| jjkr8tj| jj| jd| _t	| j| j| j
d| _d S )NrY   r   )r0   r1   r2   
embeddingsr9   rZ   r7   r^   embeddings_projectr   r   encoderrG   r.   r.   r/   rI   i  s      zFlaxElectraModule.setupNTr   c                 C   sF   | j |||||	d}t| dr(| |}| j||||	||||
||d
S )NrJ   r   )r   rK   r   r   r   r   r   r   )r   hasattrr   r   )rH   rN   rQ   rO   rP   r   r   r   r   rK   r   r   r   r   r.   r.   r/   rR   q  s*        

zFlaxElectraModule.__call__)NNNFTFFT)r'   r(   r)   r"   r-   r+   rT   r2   r   rU   rI   r   npr,   rR   r.   r.   r.   r/   r   d  s,   
        r   zaThe bare Electra Model transformer outputting raw hidden-states without any specific head on top.c                   @   s   e Zd ZeZdS )FlaxElectraModelN)r'   r(   r)   r   r   r.   r.   r.   r/   r     s   r   c                   @   sV   e Zd ZU eed< ejZejed< dZe	j
jjZedejf ed< dd Zdd	 ZdS )
FlaxElectraTiedDenser9   r2   N.	bias_initc                 C   s   |  d| j| jf| _d S )Nr   )paramr   r9   r   rG   r.   r.   r/   rI     s    zFlaxElectraTiedDense.setupc                 C   sX   t || j}t || j}tj|||jd fdfdf| jd}t | j| j}|| S )Nr!   rr   )r.   r.   )r   )r+   Zasarrayr2   r   Zdot_generalndimr   r   )rH   xkernelyr   r.   r.   r/   rR     s    zFlaxElectraTiedDense.__call__)r'   r(   r)   r   r-   r+   rT   r2   r   r:   r7   r;   ru   r   r   r   r,   rI   rR   r.   r.   r.   r/   r     s   
r   c                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )FlaxElectraForMaskedLMModuler1   r2   Fr   c                 C   s`   t | j| j| jd| _t| j| jd| _| jjrFt| jj	| jd| _
ntj| jj	| jd| _
d S Nr   r1   r2   rY   r   r1   r2   r   r   r   generator_predictionstie_word_embeddingsr   r8   generator_lm_headr7   r^   rG   r.   r.   r/   rI     s      z"FlaxElectraForMaskedLMModule.setupNTrK   r   r   r   c
                 C   s   | j |||||||||	d	}
|
d }| |}| jjr^| j jd d d d }| ||j}n
| |}|	s~|f|
dd   S t||
j|
j	dS )	Nr  r   r   r   r>   	embeddingr!   r$   r%   r&   )
r   r  r1   r  r   r  Tr   r%   r&   )rH   rN   rQ   rO   rP   r   rK   r   r   r   r   r%   prediction_scoresshared_embeddingr.   r.   r/   rR     s0    

z%FlaxElectraForMaskedLMModule.__call__)NNNNTFFTr'   r(   r)   r"   r-   r+   rT   r2   r   rU   rI   rR   r.   r.   r.   r/   r    s$   
        r  z5Electra Model with a `language modeling` head on top.c                   @   s   e Zd ZeZdS )FlaxElectraForMaskedLMN)r'   r(   r)   r  r   r.   r.   r.   r/   r    s   r  c                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )FlaxElectraForPreTrainingModuler1   r2   Fr   c                 C   s,   t | j| j| jd| _t| j| jd| _d S Nr   r  )r   r1   r2   r   r   r   discriminator_predictionsrG   r.   r.   r/   rI     s      z%FlaxElectraForPreTrainingModule.setupNTr  c
                 C   sV   | j |||||||||	d	}
|
d }| |}|	sD|f|
dd   S t||
j|
jdS )Nr  r   r!   r
  )r   r  r#   r%   r&   rH   rN   rQ   rO   rP   r   rK   r   r   r   r   r%   r$   r.   r.   r/   rR     s(    
z(FlaxElectraForPreTrainingModule.__call__)NNNNTFFTr  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eZdS )FlaxElectraForPreTrainingN)r'   r(   r)   r  r   r.   r.   r.   r/   r  '  s   	r  a  
    Returns:

    Example:

    ```python
    >>> from transformers import AutoTokenizer, FlaxElectraForPreTraining

    >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-small-discriminator")
    >>> model = FlaxElectraForPreTraining.from_pretrained("google/electra-small-discriminator")

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

    >>> prediction_logits = outputs.logits
    ```
r   )output_typer   c                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )'FlaxElectraForTokenClassificationModuler1   r2   Fr   c                 C   sX   t | j| j| jd| _| jjd k	r*| jjn| jj}t|| _	tj
| jj| jd| _d S Nr   rY   )r   r1   r2   r   r   classifier_dropoutrE   r7   rD   rF   r^   
num_labels
classifierrH   r  r.   r.   r/   rI   S  s      

z-FlaxElectraForTokenClassificationModule.setupNTr  c
                 C   sd   | j |||||||||	d	}
|
d }| j||d}| |}|	sR|f|
dd   S t||
j|
jdS Nr  r   rJ   r!   r
  )r   rF   r  r   r%   r&   r  r.   r.   r/   rR   _  s*    
z0FlaxElectraForTokenClassificationModule.__call__)NNNNTFFTr  r.   r.   r.   r/   r  N  s$   
        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eZdS )!FlaxElectraForTokenClassificationN)r'   r(   r)   r  r   r.   r.   r.   r/   r    s   	r  c                 K   s   | S r   r.   )r   r   r.   r.   r/   identity  s    r  c                   @   sB   e Zd ZU dZeed< ejZejed< dd Z	de
dd	d
ZdS )FlaxElectraSequenceSummarya  
    Compute a single vector summary of a sequence hidden states.

    Args:
        config ([`PretrainedConfig`]):
            The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
            config class of your model for the default values it uses):

            - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
            - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
              (otherwise to `config.hidden_size`).
            - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
              another string or `None` will add no activation.
            - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
            - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
    r1   r2   c                 C   s   t | _t| jdr^| jjr^t| jdrD| jjrD| jjdkrD| jj}n| jj}tj	|| j
d| _t| jdd }|rxt| ndd | _t | _t| jdr| jjdkrt| jj| _t | _t| jd	r| jjdkrt| jj| _d S )
Nsummary_use_projsummary_proj_to_labelsr   rY   Zsummary_activationc                 S   s   | S r   r.   )r   r.   r.   r/   rp     rq   z2FlaxElectraSequenceSummary.setup.<locals>.<lambda>summary_first_dropoutsummary_last_dropout)r  summaryr   r1   r   r!  r  rZ   r7   r^   r2   getattrr   r   first_dropoutr"  rD   last_dropoutr#  )rH   Znum_classesZactivation_stringr.   r.   r/   rI     s&    


z FlaxElectraSequenceSummary.setupNTrJ   c                 C   sD   |dddf }| j ||d}| |}| |}| j||d}|S )aZ  
        Compute a single vector summary of a sequence hidden states.

        Args:
            hidden_states (`jnp.ndarray` of shape `[batch_size, seq_len, hidden_size]`):
                The hidden states of the last layer.
            cls_index (`jnp.ndarray` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
                Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.

        Returns:
            `jnp.ndarray`: The summary of the sequence hidden states.
        Nr   rJ   )r&  r$  r   r'  )rH   r%   Z	cls_indexrK   r   r.   r.   r/   rR     s    

z#FlaxElectraSequenceSummary.__call__)NTrS   r.   r.   r.   r/   r    s
   
r  c                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )"FlaxElectraForMultipleChoiceModuler1   r2   Fr   c                 C   s>   t | j| j| jd| _t| j| jd| _tjd| jd| _	d S )Nr   r  r!   rY   )
r   r1   r2   r   r   r  sequence_summaryr7   r^   r  rG   r.   r.   r/   rI     s      z(FlaxElectraForMultipleChoiceModule.setupNTr  c
                 C   s   |j d }
|d k	r$|d|j d nd }|d k	rB|d|j d nd }|d k	r`|d|j d nd }|d k	r~|d|j d nd }| j|||||||||	d	}|d }| j||d}| |}|d|
}|	s|f|dd   S t||j|jdS )Nr!   r   r  r   rJ   r
  )rg   rf   r   r)  r  r   r%   r&   )rH   rN   rQ   rO   rP   r   rK   r   r   r   Znum_choicesr   r%   Zpooled_outputr$   Zreshaped_logitsr.   r.   r/   rR     s6    

z+FlaxElectraForMultipleChoiceModule.__call__)NNNNTFFTr  r.   r.   r.   r/   r(    s$   

        r(  z
    ELECTRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                   @   s   e Zd ZeZdS )FlaxElectraForMultipleChoiceN)r'   r(   r)   r(  r   r.   r.   r.   r/   r*    s   r*  z(batch_size, num_choices, sequence_lengthc                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )%FlaxElectraForQuestionAnsweringModuler1   r2   Fr   c                 C   s0   t | j| j| jd| _tj| jj| jd| _d S r  )	r   r1   r2   r   r   r7   r^   r  
qa_outputsrG   r.   r.   r/   rI   7  s      z+FlaxElectraForQuestionAnsweringModule.setupNTr  c
                 C   s   | j |||||||||	d	}
|
d }| |}|j| jjdd\}}|d}|d}|	sp||f|
dd   S t|||
j|
jdS )Nr  r   r   r   r!   )start_logits
end_logitsr%   r&   )	r   r,  r   r1   r  r   r   r%   r&   )rH   rN   rQ   rO   rP   r   rK   r   r   r   r   r%   r$   r-  r.  r.   r.   r/   rR   =  s0    


z.FlaxElectraForQuestionAnsweringModule.__call__)NNNNTFFTr  r.   r.   r.   r/   r+  2  s$   
	        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                   @   s   e Zd ZeZdS )FlaxElectraForQuestionAnsweringN)r'   r(   r)   r+  r   r.   r.   r.   r/   r/  f  s   r/  c                   @   sB   e Zd ZU dZeed< ejZejed< dd Z	de
ddd	Zd
S )FlaxElectraClassificationHeadz-Head for sentence-level classification tasks.r1   r2   c                 C   sX   t j| jj| jd| _| jjd k	r*| jjn| jj}t || _	t j| jj
| jd| _d S )NrY   )r7   r^   r1   rZ   r2   r   r  rE   rD   rF   r  out_projr  r.   r.   r/   rI     s    

z#FlaxElectraClassificationHead.setupTrJ   c                 C   sV   |d d dd d f }| j ||d}| |}td |}| j ||d}| |}|S )Nr   rJ   Zgelu)rF   r   r   r1  )rH   r%   rK   r   r.   r.   r/   rR     s    

z&FlaxElectraClassificationHead.__call__N)TrS   r.   r.   r.   r/   r0  y  s
   

r0  c                   @   sP   e Zd ZU eed< ejZejed< dZe	ed< dd Z
de	e	e	e	d	d
dZdS )*FlaxElectraForSequenceClassificationModuler1   r2   Fr   c                 C   s,   t | j| j| jd| _t| j| jd| _d S r  )r   r1   r2   r   r   r0  r  rG   r.   r.   r/   rI     s      z0FlaxElectraForSequenceClassificationModule.setupNTr  c
                 C   sZ   | j |||||||||	d	}
|
d }| j||d}|	sH|f|
dd   S t||
j|
jdS r  )r   r  r   r%   r&   r  r.   r.   r/   rR     s(    z3FlaxElectraForSequenceClassificationModule.__call__)NNNNTFFTr  r.   r.   r.   r/   r2    s$   
	        r2  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eZdS )$FlaxElectraForSequenceClassificationN)r'   r(   r)   r2  r   r.   r.   r.   r/   r3    s   r3  c                   @   s   e Zd ZU eed< ejZejed< dZe	ed< dd Z
deej eej eej eej eej eej e	e	e	e	e	d	d
dZdS )FlaxElectraForCausalLMModuler1   r2   Fr   c                 C   s`   t | j| j| jd| _t| j| jd| _| jjrFt| jj	| jd| _
ntj| jj	| jd| _
d S r  r  rG   r.   r.   r/   rI     s      z"FlaxElectraForCausalLMModule.setupNT)rQ   rO   rP   r   r   r   r   rK   r   r   r   c                 C   s   | j |||||||||	|
||d}|d }| |}| jjrd| j jd d d d }| ||j}n
| |}|s|f|dd   S t||j|j	|j
dS )	Nr   r   r   r   r>   r	  r!   )r$   r%   r&   r   )r   r  r1   r  r   r  r  r   r%   r&   r   )rH   rN   rQ   rO   rP   r   r   r   r   rK   r   r   r   r   r%   r  r  r.   r.   r/   rR     s8    

z%FlaxElectraForCausalLMModule.__call__)NNNNNNFTFFTr   r.   r.   r.   r/   r4    s8   
           r4  z
    Electra Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
    autoregressive tasks.
    c                   @   s.   e Zd ZeZdeej dddZdd Z	dS )FlaxElectraForCausalLMN)rQ   c           	      C   s   |j \}}| ||}tj||fdd}|d k	rP|jddd }t||d}n&ttj|ddd d d f ||f}|||dS )NrL   rY   r   r   r!   )r   r   )r   rQ   rP   )	rg   r   r+   rb   Zcumsumr   rw   rx   ry   )	rH   rN   r{   rQ   r   Z
seq_lengthr   Zextended_attention_maskrP   r.   r.   r/   prepare_inputs_for_generation!  s    
&z4FlaxElectraForCausalLM.prepare_inputs_for_generationc                 C   s.   |j |d< |d d d dd f d |d< |S )Nr   rP   r   r!   )r   )rH   Zmodel_outputsZmodel_kwargsr.   r.   r/   update_inputs_for_generation6  s    
 z3FlaxElectraForCausalLM.update_inputs_for_generation)N)
r'   r(   r)   r4  r   r   r:   Arrayr6  r7  r.   r.   r.   r/   r5    s   	r5  )_typingr   r   r   ZflaxZ
flax.linenZlinenr7   r:   Z	jax.numpyZnumpyr+   r   Zflax.core.frozen_dictr   r   r   r   r	   r
   Znn_partitioningZflax.linen.attentionr   Zflax.traverse_utilr   r   r   Zmodeling_flax_outputsr   r   r   r   r   r   r   r   Zmodeling_flax_utilsr   r   r   r   r   utilsr   r   r   r    Zconfiguration_electrar"   Z
get_loggerr'   loggerZ_CHECKPOINT_FOR_DOCZ_CONFIG_FOR_DOCr   structZ	dataclassr#   ZELECTRA_START_DOCSTRINGr   r   r0   rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  Z&FLAX_ELECTRA_FOR_PRETRAINING_DOCSTRINGr   r  r  r  r  r(  r*  r+  r/  r0  r2  r3  r4  r5  r.   r.   r.   r/   <module>   s  (

'* -+:S' A091  8C: 40@