U
    4Af                     @   s  d Z ddl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 dd	lmZmZmZmZmZmZmZmZ dd
lmZ ddlm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ e(,e-Z.dZ/dZ0dd Z1G dd dej2Z3G dd dej2Z4G dd dej2Z5G dd dej2Z6G dd dej2Z7G dd dej2Z8G dd  d ej2Z9G d!d" d"ej2Z:G d#d$ d$ej2Z;G d%d& d&ej2Z<G d'd( d(ej2Z=G d)d* d*ej2Z>G d+d, d,ej2Z?G d-d. d.ej2Z@G d/d0 d0ej2ZAG d1d2 d2eZBeG d3d4 d4e$ZCd5ZDd6ZEe&d7eDG d8d9 d9eBZFe&d:eDG d;d< d<eBZGe&d=eDG d>d? d?eBZHe&d@eDG dAdB dBeBZIe&dCeDG dDdE dEeBZJe&dFeDG dGdH dHeBZKe&dIeDG dJdK dKeBZLe&dLeDG dMdN dNeBZMdS )OzPyTorch Nezha model.    N)	dataclass)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)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   )NezhaConfigzsijunhe/nezha-cn-baser    c                 C   s  zddl }ddl}ddl}W n  tk
r<   td  Y nX tj|}t	d|  |j
|}g }g }	|D ]@\}
}t	d|
 d|  |j
||
}||
 |	| qrt||	D ]\}
}|
d}
tdd	 |
D rt	d
d|
  q| }|
D ]}|d|r&|d|}n|g}|d dksH|d dkrTt|d}n|d dksp|d dkr|t|d}nz|d dkrt|d}n`|d dkrt|d}nFzt||d }W n2 tk
r   t	d
d|
  Y qY nX t|dkrt|d }|| }q|dd dkr:t|d}n|dkrN||}z,|j|jkrxtd|j d|j dW n< tk
r } z| j|j|jf7  _ W 5 d}~X Y nX t	d|
  t||_q| 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 /c                 s   s   | ]}|d kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr"   r"   W/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/deprecated/nezha/modeling_nezha.py	<genexpr>W   s   z+load_tf_weights_in_nezha.<locals>.<genexpr>z	Skipping z[A-Za-z]+_\d+z_(\d+)kernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquad
classifier   r   iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )reZnumpyZ
tensorflowImportErrorloggererrorospathabspathinfoZtrainZlist_variablesZload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshape
ValueErrorAssertionErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr.   nptfZtf_pathZ	init_varsnamesZarraysnamerA   arraypointerZm_nameZscope_namesnumer"   r"   r%   load_tf_weights_in_nezha:   sx    




rQ   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )NezhaRelativePositionsEncodingz3Implement the Functional Relative Position Encoding   c                    sH  t    |d d }t|}||||}|t| }t|| |}|| }	t||}
tjd|tj	d
 d}ttd|d
 td |  }t|| |
d d dd df< t|| |
d d dd df< |	d}tjjj||d
 }t||
}t|	 }|| ||}| jd|d	d
 d S )Nr-   r   r   dtypeg     @)Znum_classespositions_encodingF
persistent)super__init__rE   ZarangerepeatviewtclampzerosZint64floatZ	unsqueezeexpmathlogsincosr   
functionalZone_hotmatmullistsizer6   register_buffer)selflengthdepthmax_relative_position
vocab_sizeZ	range_vecZ	range_matZdistance_matZdistance_mat_clippedZ	final_matZembeddings_tablepositionZdiv_termZflat_relative_positions_matrixZ!one_hot_relative_positions_matrixrW   Zmy_shape	__class__r"   r%   r[      s,    

(  
 


z'NezhaRelativePositionsEncoding.__init__c                 C   s   | j d |d |d d f S N)rW   )rl   rm   r"   r"   r%   forward   s    z&NezhaRelativePositionsEncoding.forward)rS   )__name__
__module____qualname____doc__r[   ru   __classcell__r"   r"   rr   r%   rR      s   rR   c                       sJ   e Zd ZdZ fddZdeej eej eej ej	dddZ
  ZS )	NezhaEmbeddingsz=Construct the embeddings from word and token_type embeddings.c                    s|   t    tj|j|j|jd| _t|j|j| _	tj
|j|jd| _
t|j| _| jdtjd|jftjddd d S )N)padding_idxZepstoken_type_idsr   rT   FrX   )rZ   r[   r   	Embeddingrp   hidden_sizepad_token_idword_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutrk   rE   r`   max_position_embeddingslongrl   rH   rr   r"   r%   r[      s    
  zNezhaEmbeddings.__init__N)	input_idsr~   inputs_embedsreturnc           
      C   s   |d k	r|  }n|  d d }|d }|d kr<| |}|d krt| drz| jd d d |f }||d |}|}ntj|tj|jd}| 	|}|| }	| 
|	}	| |	}	|	S )NrV   r   r~   r   rU   device)rj   r   hasattrr~   expandrE   r`   r   r   r   r   r   )
rl   r   r~   r   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr   
embeddingsr"   r"   r%   ru      s"    





zNezhaEmbeddings.forward)NNN)rv   rw   rx   ry   r[   r   rE   Z
LongTensorFloatTensorTensorru   rz   r"   r"   rr   r%   r{      s      r{   c                
       s   e Zd Z fddZejejdddZdejeej eej eej eej ee	e	ej   ee
 e	ej dd	d
Z  ZS )NezhaSelfAttentionc                    s   t    |j|j dkr4td|j d|j d|j| _t|j|j | _| j| j | _t	|j| j| _
t	|j| j| _t	|j| j| _t|j| _t|j| j|jd| _|j| _d S )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ())rm   rn   ro   )rZ   r[   r   num_attention_headsrB   r?   attention_head_sizeall_head_sizer   Linearquerykeyvaluer   Zattention_probs_dropout_probr   rR   r   ro   relative_positions_encoding
is_decoderr   rr   r"   r%   r[      s$    
zNezhaSelfAttention.__init__)xr   c                 C   s6   |  d d | j| jf }||}|ddddS )NrV   r   r-   r      )rj   r   r   r]   permute)rl   r   Znew_x_shaper"   r"   r%   transpose_for_scores   s    
z'NezhaSelfAttention.transpose_for_scoresNFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsr   c           "      C   s  |  |}|d k	}	|	r4|d k	r4|d }
|d }|}n|	r^| | |}
| | |}|}nv|d k	r| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n | | |}
| | |}| |}| jr|
|f}t||
dd}|	 \}}}}| 
|}|dddd}| ||| | j}t||ddd}|||||}|dddd}|| }|t| j }|d k	r|| }tjj|dd}| |}|d k	r|| }t||}| 
|}|dddd}| ||| |}t||}||||| j}|dddd}|| }|dddd }|	 d d | jf } || }|r||fn|f}!| jr|!|f }!|!S )Nr   r   r-   ZdimrV   r   )r   r   r   r   rE   catr   rh   r@   rj   r   r   
contiguousr]   r   rc   sqrtr   rg   Zsoftmaxr   r   )"rl   r   r   r   r   r   r   r   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerZattention_scores
batch_sizer   Zfrom_seq_lengthZto_seq_lengthZrelations_keysZquery_layer_tZquery_layer_rZkey_position_scoresZkey_position_scores_rZkey_position_scores_r_tZattention_probsZcontext_layerZrelations_valuesZattention_probs_tZattentions_probs_rZvalue_position_scoresZvalue_position_scores_rZvalue_position_scores_r_tZnew_context_layer_shapeoutputsr"   r"   r%   ru      s    



     



     

zNezhaSelfAttention.forward)NNNNNF)rv   rw   rx   r[   rE   r   r   r   r   r   boolru   rz   r"   r"   rr   r%   r      s$         r   c                       s4   e Zd Z fddZejejejdddZ  ZS )NezhaSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr}   )rZ   r[   r   r   r   denser   r   r   r   r   r   rr   r"   r%   r[   ^  s    
zNezhaSelfOutput.__init__r   input_tensorr   c                 C   s&   |  |}| |}| || }|S rt   r   r   r   rl   r   r   r"   r"   r%   ru   d  s    

zNezhaSelfOutput.forwardrv   rw   rx   r[   rE   r   ru   rz   r"   r"   rr   r%   r   ]  s   r   c                
       st   e Zd Z fddZdd Zd
ejeej eej eej eej ee	e	ej   ee
 e	ej ddd	Z  ZS )NezhaAttentionc                    s*   t    t|| _t|| _t | _d S rt   )rZ   r[   r   rl   r   outputsetpruned_headsr   rr   r"   r%   r[   l  s    


zNezhaAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r   )r>   r   rl   r   r   r   r   r   r   r   r   r   r   union)rl   headsindexr"   r"   r%   prune_headsr  s       zNezhaAttention.prune_headsNFr   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )rl   r   )rl   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r"   r"   r%   ru     s    
	zNezhaAttention.forward)NNNNNF)rv   rw   rx   r[   r   rE   r   r   r   r   r   ru   rz   r"   r"   rr   r%   r   k  s$         r   c                       s0   e Zd Z fddZejejdddZ  ZS )NezhaIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S rt   )rZ   r[   r   r   r   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr   rr   r"   r%   r[     s
    
zNezhaIntermediate.__init__r   r   c                 C   s   |  |}| |}|S rt   )r   r   rl   r   r"   r"   r%   ru     s    

zNezhaIntermediate.forwardr   r"   r"   rr   r%   r     s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )NezhaOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rZ   r[   r   r   r   r   r   r   r   r   r   r   r   rr   r"   r%   r[     s    
zNezhaOutput.__init__r   c                 C   s&   |  |}| |}| || }|S rt   r   r   r"   r"   r%   ru     s    

zNezhaOutput.forwardr   r"   r"   rr   r%   r     s   r   c                
       st   e Zd Z fddZd
ejeej eej eej eej eeeej   ee	 eej dddZ
dd	 Z  ZS )
NezhaLayerc                    sn   t    |j| _d| _t|| _|j| _|j| _| jrV| jsLt|  dt|| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is added)rZ   r[   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionrB   crossattentionr   intermediater   r   r   rr   r"   r%   r[     s    



zNezhaLayer.__init__NFr   c              	   C   s  |d k	r|d d nd }| j |||||d}	|	d }
| jrP|	dd }|	d }n|	dd  }d }| jr|d k	rt| dstd|  d|d k	r|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nr-   )r   r   r   r   rV   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   rB   r   r   feed_forward_chunkr   r   )rl   r   r   r   r   r   r   r   Zself_attn_past_key_valueZself_attention_outputsr   r   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputslayer_outputr"   r"   r%   ru     sV    


	   

zNezhaLayer.forwardc                 C   s   |  |}| ||}|S rt   )r   r   )rl   r   Zintermediate_outputr   r"   r"   r%   r   	  s    
zNezhaLayer.feed_forward_chunk)NNNNNF)rv   rw   rx   r[   rE   r   r   r   r   r   ru   r   rz   r"   r"   rr   r%   r     s$         Ar   c                       s   e Zd Z fddZd	ejeej eej eej eej eeeej   ee	 ee	 ee	 ee	 e
eej ef dddZ  ZS )
NezhaEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r"   )r   )r#   _rH   r"   r%   
<listcomp>  s     z)NezhaEncoder.__init__.<locals>.<listcomp>F)	rZ   r[   rH   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   rr   r   r%   r[     s    
 zNezhaEncoder.__init__NFT)r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictr   c                 C   sb  |	rdnd }|rdnd }|r(| j jr(dnd }| jrJ| jrJ|rJtd d}|rRdnd }t| jD ]\}}|	rv||f }|d k	r|| nd }|d k	r|| nd }| jr| jr| |j	|||||||}n||||||||}|d }|r||d f7 }|r`||d f }| j jr`||d f }q`|	r.||f }|
sPt
dd	 |||||fD S t|||||d
S )Nr"   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   rV   r   r-   c                 s   s   | ]}|d k	r|V  qd S rt   r"   )r#   vr"   r"   r%   r&   X  s   z'NezhaEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)rH   r   r   Ztrainingr0   Zwarning_once	enumerater   Z_gradient_checkpointing_func__call__tupler   )rl   r   r   r   r   r   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr"   r"   r%   ru     sx    


zNezhaEncoder.forward)	NNNNNNFFT)rv   rw   rx   r[   rE   r   r   r   r   r   r   r   ru   rz   r"   r"   rr   r%   r     s.   	         r   c                       s0   e Zd Z fddZejejdddZ  ZS )NezhaPoolerc                    s*   t    t|j|j| _t | _d S rt   )rZ   r[   r   r   r   r   ZTanh
activationr   rr   r"   r%   r[   m  s    
zNezhaPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rl   r   Zfirst_token_tensorpooled_outputr"   r"   r%   ru   r  s    

zNezhaPooler.forwardr   r"   r"   rr   r%   r   l  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )NezhaPredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S r   )rZ   r[   r   r   r   r   r   r   r   r   transform_act_fnr   r   r   rr   r"   r%   r[   |  s    
z%NezhaPredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S rt   )r   r   r   r   r"   r"   r%   ru     s    


z$NezhaPredictionHeadTransform.forwardr   r"   r"   rr   r%   r   {  s   	r   c                       s,   e Zd Z fddZdd Zdd Z  ZS )NezhaLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r+   )rZ   r[   r   	transformr   r   r   rp   decoder	ParameterrE   r`   r+   r   rr   r"   r%   r[     s
    

zNezhaLMPredictionHead.__init__c                 C   s   | j | j_ d S rt   )r+   r   rl   r"   r"   r%   _tie_weights  s    z"NezhaLMPredictionHead._tie_weightsc                 C   s   |  |}| |}|S rt   )r   r   r   r"   r"   r%   ru     s    

zNezhaLMPredictionHead.forward)rv   rw   rx   r[   r   ru   rz   r"   r"   rr   r%   r     s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )NezhaOnlyMLMHeadc                    s   t    t|| _d S rt   )rZ   r[   r   predictionsr   rr   r"   r%   r[     s    
zNezhaOnlyMLMHead.__init__)sequence_outputr   c                 C   s   |  |}|S rt   )r   )rl   r   prediction_scoresr"   r"   r%   ru     s    
zNezhaOnlyMLMHead.forwardr   r"   r"   rr   r%   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )NezhaOnlyNSPHeadc                    s   t    t|jd| _d S Nr-   )rZ   r[   r   r   r   seq_relationshipr   rr   r"   r%   r[     s    
zNezhaOnlyNSPHead.__init__c                 C   s   |  |}|S rt   )r  )rl   r   seq_relationship_scorer"   r"   r%   ru     s    
zNezhaOnlyNSPHead.forwardrv   rw   rx   r[   ru   rz   r"   r"   rr   r%   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )NezhaPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S r   )rZ   r[   r   r   r   r   r   r  r   rr   r"   r%   r[     s    

zNezhaPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS rt   )r   r  )rl   r   r   r   r  r"   r"   r%   ru     s    

zNezhaPreTrainingHeads.forwardr  r"   r"   rr   r%   r    s   r  c                   @   s(   e Zd ZdZeZeZdZdZ	dd Z
dS )NezhaPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    nezhaTc                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n&t |tjr|jj	  |jjd dS )zInitialize the weightsg        )ZmeanZstdNg      ?)r   r   r   r)   rF   Znormal_rH   Zinitializer_ranger+   Zzero_r   r|   r   Zfill_)rl   moduler"   r"   r%   _init_weights  s    

z"NezhaPreTrainedModel._init_weightsN)rv   rw   rx   ry   r    config_classrQ   Zload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingr  r"   r"   r"   r%   r    s   r  c                   @   sl   e Zd ZU dZdZeej ed< dZ	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 )NezhaForPreTrainingOutputa]  
    Output type of [`NezhaForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the masked language modeling loss and the next sequence prediction
            (classification) loss.
        prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            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lossprediction_logitsseq_relationship_logitsr   r   )rv   rw   rx   ry   r  r   rE   r   __annotations__r  r  r   r   r   r"   r"   r"   r%   r
    s   
r
  a?  

    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 ([`NezhaConfig`]): 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)
        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.
        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.
z_The bare Nezha Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zee	
deeeeddeej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dddZ  ZS )
NezhaModela  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in [Attention is
    all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
    Tc                    sD   t  | || _t|| _t|| _|r2t|nd | _| 	  d S rt   )
rZ   r[   rH   r{   r   r   encoderr   pooler	post_init)rl   rH   add_pooling_layerrr   r"   r%   r[   O  s    

zNezhaModel.__init__c                 C   s   | j jS rt   r   r   r   r"   r"   r%   get_input_embeddings[  s    zNezhaModel.get_input_embeddingsc                 C   s   || j _d S rt   r  )rl   r   r"   r"   r%   set_input_embeddings^  s    zNezhaModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )rl   Zheads_to_pruner   r   r"   r"   r%   _prune_headsa  s    zNezhaModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer	  N)r   r   r~   r   r   r   r   r   r   r   r   r   r   c                 C   sZ  |
dk	r|
n| j j}
|dk	r |n| j j}|dk	r4|n| j j}| j jrZ|	dk	rP|	n| j j}	nd}	|dk	rx|dk	rxtdn@|dk	r| || | }n"|dk	r| dd }ntd|\}}|dk	r|j	n|j	}|dk	r|d d j
d nd}|dkrtj||| f|d}|dkrft| jd	rT| jjddd|f }|||}|}ntj|tj|d
}| ||}| j jr|dk	r| \}}}||f}|dkrtj||d}| |}nd}| || j j}| j|||d}| j|||||||	|
||d
}|d }| jdk	r | |nd}|s>||f|dd  S t|||j|j|j|jdS )a  
        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**.
        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`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timerV   z5You have to specify either input_ids or inputs_embedsr   r-   )r   r~   r   )r   r~   r   )	r   r   r   r   r   r   r   r   r   r   )r   Zpooler_outputr   r   r   r   )rH   r   r   use_return_dictr   r   rB   Z%warn_if_padding_and_no_attention_maskrj   r   rA   rE   Zonesr   r   r~   r   r`   r   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r  r  r   r   r   r   r   )rl   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   Zpast_key_values_lengthr   r   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsr   r   r"   r"   r%   ru   i  s    )




zNezhaModel.forward)T)NNNNNNNNNNNN)rv   rw   rx   ry   r[   r  r  r  r   NEZHA_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rE   r   r   r   r   r   r   ru   rz   r"   r"   rr   r%   r  >  sL               r  z
    Nezha Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
    sentence prediction (classification)` head.
    c                       s   e Zd ZdgZ fddZdd Zdd Zee	de
eed	deej eej eej eej eej eej eej ee ee ee eeej ef dddZ  ZS )NezhaForPreTrainingcls.predictions.decoderc                    s,   t  | t|| _t|| _|   d S rt   )rZ   r[   r  r  r  clsr  r   rr   r"   r%   r[     s    

zNezhaForPreTraining.__init__c                 C   s
   | j jjS rt   r$  r   r   r   r"   r"   r%   get_output_embeddings  s    z)NezhaForPreTraining.get_output_embeddingsc                 C   s   || j j_|j| j j_d S rt   r$  r   r   r+   rl   Znew_embeddingsr"   r"   r%   set_output_embeddings  s    
z)NezhaForPreTraining.set_output_embeddingsr  r  r	  N)r   r   r~   r   r   labelsnext_sentence_labelr   r   r   r   c              
   C   s   |
dk	r|
n| j j}
| j|||||||	|
d}|dd \}}| ||\}}d}|dk	r|dk	rt }||d| j j|d}||dd|d}|| }|
s||f|dd  }|dk	r|f| S |S t||||j|j	dS )a!  
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
                config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
                the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
            next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
                pair (see `input_ids` docstring) Indices should be in `[0, 1]`:

                - 0 indicates sequence B is a continuation of sequence A,
                - 1 indicates sequence B is a random sequence.
            kwargs (`Dict[str, any]`, optional, defaults to *{}*):
                Used to hide legacy arguments that have been deprecated.

        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
        >>> model = NezhaForPreTraining.from_pretrained("sijunhe/nezha-cn-base")

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

        >>> prediction_logits = outputs.prediction_logits
        >>> seq_relationship_logits = outputs.seq_relationship_logits
        ```
        Nr   r~   r   r   r   r   r   r-   rV   )r  r  r  r   r   )
rH   r  r  r$  r	   r]   rp   r
  r   r   )rl   r   r   r~   r   r   r+  r,  r   r   r   r   r   r   r   r  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   r"   r"   r%   ru   	  s:    /zNezhaForPreTraining.forward)
NNNNNNNNNN)rv   rw   rx   _tied_weights_keysr[   r&  r)  r   r  r  r   r
  r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   r"    s:   	
          r"  z3Nezha Model with a `language modeling` head on top.c                       s   e Zd ZdgZ fddZdd Zdd Zee	de
eeed	deej eej eej eej eej eej eej eej ee ee ee eeej ef dddZdddZ  ZS )NezhaForMaskedLMr#  c                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NzlIf you want to use `NezhaForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr  )
rZ   r[   r   r0   warningr  r  r   r$  r  r   rr   r"   r%   r[   `  s    
zNezhaForMaskedLM.__init__c                 C   s
   | j jjS rt   r%  r   r"   r"   r%   r&  o  s    z&NezhaForMaskedLM.get_output_embeddingsc                 C   s   || j j_|j| j j_d S rt   r'  r(  r"   r"   r%   r)  r  s    
z&NezhaForMaskedLM.set_output_embeddingsr  r  N)r   r   r~   r   r   r   r   r+  r   r   r   r   c                 C   s   |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}d}|dk	rrt }||d| j j|d}|s|f|dd  }|dk	r|f| S |S t|||j|j	dS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        N)	r   r~   r   r   r   r   r   r   r   r   rV   r-   r  logitsr   r   )
rH   r  r  r$  r	   r]   rp   r   r   r   )rl   r   r   r~   r   r   r   r   r+  r   r   r   r   r   r   r0  r/  r   r"   r"   r%   ru   v  s8    
zNezhaForMaskedLM.forwardc                 K   s~   |j }|d }| jjd kr"tdtj|||j d dfgdd}tj|df| jjtj|j	d}tj||gdd}||dS )Nr   z.The PAD token should be defined for generationr   rV   r   r   )r   r   )
rA   rH   r   rB   rE   r   Z	new_zerosfullr   r   )rl   r   r   Zmodel_kwargsr   Zeffective_batch_sizeZdummy_tokenr"   r"   r%   prepare_inputs_for_generation  s    "   z.NezhaForMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNN)N)rv   rw   rx   r2  r[   r&  r)  r   r  r  r   r   r   r!  r   rE   r   r   r   r   ru   r9  rz   r"   r"   rr   r%   r3  \  sH              7r3  zKNezha Model with a `next sentence prediction (classification)` head on top.c                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef d
ddZ  ZS )
NezhaForNextSentencePredictionc                    s,   t  | t|| _t|| _|   d S rt   )rZ   r[   r  r  r   r$  r  r   rr   r"   r%   r[     s    

z'NezhaForNextSentencePrediction.__init__r  r*  N
r   r   r~   r   r   r+  r   r   r   r   c
              
   K   s   d|
krt dt |
d}|	dk	r*|	n| jj}	| j||||||||	d}|d }| |}d}|dk	rt }||	dd|	d}|	s|f|dd  }|dk	r|f| S |S t
|||j|jdS )	a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
            (see `input_ids` docstring). Indices should be in `[0, 1]`:

            - 0 indicates sequence B is a continuation of sequence A,
            - 1 indicates sequence B is a random sequence.

        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
        >>> model = NezhaForNextSentencePrediction.from_pretrained("sijunhe/nezha-cn-base")

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
        >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")

        >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
        >>> logits = outputs.logits
        >>> assert logits[0, 0] < logits[0, 1]  # next sentence was random
        ```
        r,  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.Nr-  r   rV   r-   r6  )warningswarnFutureWarningpoprH   r  r  r$  r	   r]   r   r   r   )rl   r   r   r~   r   r   r+  r   r   r   kwargsr   r   Zseq_relationship_scoresr1  r/  r   r"   r"   r%   ru     s@    ,

z&NezhaForNextSentencePrediction.forward)	NNNNNNNNN)rv   rw   rx   r[   r   r  r  r   r   r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   r:    s0   	
         r:  z
    Nezha Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
    output) e.g. for GLUE tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej ee ee ee eeej e	f d
ddZ  ZS )
NezhaForSequenceClassificationc                    sd   t  | |j| _|| _t|| _|jd k	r4|jn|j}t	|| _
t|j|j| _|   d S rt   )rZ   r[   
num_labelsrH   r  r  classifier_dropoutr   r   r   r   r   r   r,   r  rl   rH   rC  rr   r"   r%   r[   0  s    
z'NezhaForSequenceClassification.__init__r  r  Nr;  c
              
   C   sz  |	dk	r|	n| j j}	| j||||||||	d}
|
d }| |}| |}d}|dk	r6| j jdkr| jdkrxd| j _n4| jdkr|jtj	ks|jtj
krd| j _nd| j _| j jdkrt }| jdkr|| | }n
|||}nN| j jdkrt }||d| j|d}n| j jdkr6t }|||}|	sf|f|
dd  }|dk	rb|f| S |S t|||
j|
jd	S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr-  r   Z
regressionZsingle_label_classificationZmulti_label_classificationrV   r-   r6  )rH   r  r  r   r,   Zproblem_typerB  rU   rE   r   r?   r
   squeezer	   r]   r   r   r   r   )rl   r   r   r~   r   r   r+  r   r   r   r   r   r7  r  r/  r   r"   r"   r%   ru   ?  sT    




"


z&NezhaForSequenceClassification.forward)	NNNNNNNNN)rv   rw   rx   r[   r   r  r  r   r   r   r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   rA  (  s8            rA  z
    Nezha Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej ee ee ee eeej e	f d
ddZ  ZS )
NezhaForMultipleChoicec                    sT   t  | t|| _|jd k	r&|jn|j}t|| _t	|j
d| _|   d S )Nr   )rZ   r[   r  r  rC  r   r   r   r   r   r   r,   r  rD  rr   r"   r%   r[     s    
zNezhaForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr  Nr;  c
              
   C   sp  |	dk	r|	n| j j}	|dk	r&|jd n|jd }
|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	d}|d }t|j | |}| |}t|j t|
 |d|
}d}|dk	r,t	 }|||}|	s\|f|dd  }|dk	rX|f| S |S t
|||j|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr   rV   r   r-  r-   r6  )rH   r  rA   r]   rj   r  printr   r,   r	   r   r   r   )rl   r   r   r~   r   r   r+  r   r   r   Znum_choicesr   r   r7  Zreshaped_logitsr  r/  r   r"   r"   r%   ru     sN    





zNezhaForMultipleChoice.forward)	NNNNNNNNN)rv   rw   rx   r[   r   r  r  r   r   r   r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   rF    s8            rF  z
    Nezha Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej ee ee ee eeej e	f d
ddZ  ZS )
NezhaForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j|j| _|   d S NFr4  )rZ   r[   rB  r  r  rC  r   r   r   r   r   r   r,   r  rD  rr   r"   r%   r[     s    z$NezhaForTokenClassification.__init__r  r  Nr;  c
              
   C   s   |	dk	r|	n| j j}	| j||||||||	d}
|
d }| |}| |}d}|dk	rvt }||d| j|d}|	s|f|
dd  }|dk	r|f| S |S t|||
j	|
j
dS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr-  r   rV   r-   r6  )rH   r  r  r   r,   r	   r]   rB  r   r   r   )rl   r   r   r~   r   r   r+  r   r   r   r   r   r7  r  r/  r   r"   r"   r%   ru     s6    

z#NezhaForTokenClassification.forward)	NNNNNNNNN)rv   rw   rx   r[   r   r  r  r   r   r   r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   rH    s8            rH  z
    Nezha 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 fddZeedeee	e
dd	eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
NezhaForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S rI  )
rZ   r[   rB  r  r  r   r   r   
qa_outputsr  r   rr   r"   r%   r[   >  s
    z"NezhaForQuestionAnswering.__init__r  r  N)r   r   r~   r   r   start_positionsend_positionsr   r   r   r   c              
   C   sN  |
dk	r|
n| j j}
| j|||||||	|
d}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|
s8||f|dd  }|dk	r4|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        Nr-  r   r   rV   r   )Zignore_indexr-   )r  start_logits
end_logitsr   r   )rH   r  r  rK  r8   rE  r   r>   rj   r_   r	   r   r   r   )rl   r   r   r~   r   r   rL  rM  r   r   r   r   r   r7  rN  rO  r.  Zignored_indexr/  Z
start_lossZend_lossr   r"   r"   r%   ru   H  sN    






z!NezhaForQuestionAnswering.forward)
NNNNNNNNNN)rv   rw   rx   r[   r   r  r  r   r   r   r!  r   rE   r   r   r   r   ru   rz   r"   r"   rr   r%   rJ  6  s<   
          rJ  )Nry   rc   r2   r<  Zdataclassesr   typingr   r   r   r   rE   Ztorch.utils.checkpointr   Ztorch.nnr   r	   r
   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   Zconfiguration_nezhar    Z
get_loggerrv   r0   r   r!  rQ   ModulerR   r{   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r
  ZNEZHA_START_DOCSTRINGr  r  r"  r3  r:  rA  rF  rH  rJ  r"   r"   r"   r%   <module>   s   (
 
I 3 1V]

!- .fg`\UH