U
    4AfH                    @   s  d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlZ
ddl
mZ ddlmZmZmZ ddlmZ dd	lmZ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Z0G dd dej1Z2G dd dej1Z3G dd dej1Z4de3iZ5G dd dej1Z6G dd dej1Z7G dd dej1Z8G dd dej1Z9G d d! d!ej1Z:G d"d# d#ej1Z;G d$d% d%ej1Z<G d&d' d'ej1Z=G d(d) d)ej1Z>G d*d+ d+ej1Z?G d,d- d-ej1Z@G d.d/ d/eZAeG d0d1 d1e$ZBd2ZCd3ZDe&d4eCG d5d6 d6eAZEe&d7eCG d8d9 d9eAZFe&d:eCG d;d< d<eAZGe&d=eCG d>d? d?eAZHe&d@eCG dAdB dBeAZIe&dCeCG dDdE dEeAZJe&dFeCG dGdH dHeAZKe&dIeCG dJdK dKeAZLe&dLeCG dMdN dNeAZMdS )OzPyTorch ERNIE model.    N)	dataclass)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentions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   )ErnieConfigznghuyong/ernie-1.0-base-zhr!   c                	       s\   e Zd ZdZ fddZd	eej eej eej eej eej e	ej
dddZ  ZS )
ErnieEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _|j| _|jrft|j|j| _tj|j|jd| _t|j| _t|dd| _| jdt|jddd | jd	tj| j tjd
dd d S )N)padding_idxZepsposition_embedding_typeabsoluteposition_ids)r    F)
persistenttoken_type_idsdtype)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddingsuse_task_idZtask_type_vocab_sizetask_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutgetattrr%   Zregister_buffertorcharangeexpandzerosr'   sizelongselfconfig	__class__ L/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/ernie/modeling_ernie.pyr.   =   s(    
    zErnieEmbeddings.__init__Nr   )	input_idsr*   task_type_idsr'   inputs_embedspast_key_values_lengthreturnc                 C   s2  |d k	r|  }n|  d d }|d }|d krL| jd d ||| f }|d krt| dr| jd d d |f }	|	|d |}
|
}ntj|tj| jjd}|d kr| 	|}| 
|}|| }| jdkr| |}||7 }| jr|d krtj|tj| jjd}| |}||7 }| |}| |}|S )Nr(   r    r*   r   r,   devicer&   )rC   r'   hasattrr*   rA   r?   rB   rD   rR   r3   r6   r%   r5   r7   r8   r9   r=   )rF   rL   r*   rM   r'   rN   rO   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr6   
embeddingsr5   r8   rJ   rJ   rK   forwardS   s6    	









zErnieEmbeddings.forward)NNNNNr   )__name__
__module____qualname____doc__r.   r   r?   Z
LongTensorFloatTensorintTensorrY   __classcell__rJ   rJ   rH   rK   r"   :   s"         r"   c                
       s   e Zd Zd fdd	ZejejdddZdejeej eej eej eej ee	e	ej   ee
 e	ej dd	d
Z  ZS )ErnieSelfAttentionNc                    s   t    |j|j dkr>t|ds>td|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|pt|dd| _| jdks| jd	kr|j| _t	d
|j d | j| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r%   r&   relative_keyrelative_key_query   r    )r-   r.   r1   num_attention_headsrS   
ValueErrorr_   attention_head_sizeall_head_sizer   Linearquerykeyvaluer;   Zattention_probs_dropout_probr=   r>   r%   r4   r/   distance_embedding
is_decoderrF   rG   r%   rH   rJ   rK   r.      s*    
  zErnieSelfAttention.__init__)xrP   c                 C   s6   |  d d | j| jf }||}|ddddS )Nr(   r   rf   r    r   )rC   rg   ri   viewpermute)rF   rr   Znew_x_shaperJ   rJ   rK   transpose_for_scores   s    
z'ErnieSelfAttention.transpose_for_scoresFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrP   c                 C   s  |  |}|d k	}	|	r4|d k	r4|d }
|d }|}n|	r^| | |}
| | |}|}nv|d k	r| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n | | |}
| | |}| |}|d k	}| jr|
|f}t||
dd}| j	dks | j	dkr|j
d |
j
d  }}|r^tj|d tj|jd	dd}ntj|tj|jd	dd}tj|tj|jd	dd}|| }| || j d }|j|jd
}| j	dkrtd||}|| }n4| j	dkrtd||}td|
|}|| | }|t| j }|d k	r:|| }tjj|dd}| |}|d k	rf|| }t||}|dddd }| d d | jf }||}|r||fn|f}| jr||f }|S )Nr   r    rf   Zdimr(   rd   re   rQ   r+   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) rl   ru   rm   rn   r?   catrp   matmulZ	transposer%   shapeZtensorrD   rR   rs   r@   ro   r4   tor,   Zeinsummathsqrtri   r   Z
functionalZsoftmaxr=   rt   
contiguousrC   rj   )rF   rw   rx   ry   rz   r{   r|   r}   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layer	use_cacheZattention_scoresZquery_lengthZ
key_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeoutputsrJ   rJ   rK   rY      sp    


 





zErnieSelfAttention.forward)N)NNNNNF)rZ   r[   r\   r.   r?   r`   ru   r   r^   r   boolrY   ra   rJ   rJ   rH   rK   rb      s$         rb   c                       s4   e Zd Z fddZejejejdddZ  ZS )ErnieSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr$   )r-   r.   r   rk   r1   denser9   r:   r;   r<   r=   rE   rH   rJ   rK   r.     s    
zErnieSelfOutput.__init__rw   input_tensorrP   c                 C   s&   |  |}| |}| || }|S Nr   r=   r9   rF   rw   r   rJ   rJ   rK   rY     s    

zErnieSelfOutput.forwardrZ   r[   r\   r.   r?   r`   rY   ra   rJ   rJ   rH   rK   r     s   r   eagerc                
       sv   e Zd Zd
 fdd	Zdd Zdejeej eej eej eej ee	e	ej   ee
 e	ej ddd	Z  ZS )ErnieAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )Nr%   )	r-   r.   ERNIE_SELF_ATTENTION_CLASSESZ_attn_implementationrF   r   outputsetpruned_headsrq   rH   rJ   rK   r.   #  s    
 
zErnieAttention.__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~   )lenr   rF   rg   ri   r   r   rl   rm   rn   r   r   rj   union)rF   headsindexrJ   rJ   rK   prune_heads+  s       zErnieAttention.prune_headsFrv   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r    )rF   r   )rF   rw   rx   ry   rz   r{   r|   r}   Zself_outputsattention_outputr   rJ   rJ   rK   rY   =  s    
	zErnieAttention.forward)N)NNNNNF)rZ   r[   r\   r.   r   r?   r`   r   r^   r   r   rY   ra   rJ   rJ   rH   rK   r   "  s$         r   c                       s0   e Zd Z fddZejejdddZ  ZS )ErnieIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r-   r.   r   rk   r1   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrE   rH   rJ   rK   r.   W  s
    
zErnieIntermediate.__init__rw   rP   c                 C   s   |  |}| |}|S r   )r   r   rF   rw   rJ   rJ   rK   rY   _  s    

zErnieIntermediate.forwardr   rJ   rJ   rH   rK   r   V  s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )ErnieOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r-   r.   r   rk   r   r1   r   r9   r:   r;   r<   r=   rE   rH   rJ   rK   r.   g  s    
zErnieOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   rJ   rJ   rK   rY   m  s    

zErnieOutput.forwardr   rJ   rJ   rH   rK   r   f  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 )
ErnieLayerc                    sr   t    |j| _d| _t|| _|j| _|j| _| jrZ| jsLt|  dt|dd| _	t
|| _t|| _d S )Nr    z> should be used as a decoder model if cross attention is addedr&   r   )r-   r.   chunk_size_feed_forwardseq_len_dimr   	attentionrp   add_cross_attentionrh   crossattentionr   intermediater   r   rE   rH   rJ   rK   r.   v  s    


zErnieLayer.__init__NFrv   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 )
Nrf   )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   rp   rS   rh   r   r   feed_forward_chunkr   r   )rF   rw   rx   ry   rz   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_outputrJ   rJ   rK   rY     sV    


	   

zErnieLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rF   r   Zintermediate_outputr   rJ   rJ   rK   r     s    
zErnieLayer.feed_forward_chunk)NNNNNF)rZ   r[   r\   r.   r?   r`   r   r^   r   r   rY   r   ra   rJ   rJ   rH   rK   r   u  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 )
ErnieEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS rJ   )r   ).0_rG   rJ   rK   
<listcomp>  s     z)ErnieEncoder.__init__.<locals>.<listcomp>F)	r-   r.   rG   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingrE   rH   r   rK   r.     s    
 zErnieEncoder.__init__NFT)rw   rx   ry   rz   r{   past_key_valuesr   r}   output_hidden_statesreturn_dictrP   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 )NrJ   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r(   r    rf   c                 s   s   | ]}|d k	r|V  qd S r   rJ   )r   vrJ   rJ   rK   	<genexpr>  s   z'ErnieEncoder.forward.<locals>.<genexpr>)last_hidden_stater   rw   
attentionscross_attentions)rG   r   r   ZtrainingloggerZwarning_once	enumerater   Z_gradient_checkpointing_func__call__tupler   )rF   rw   rx   ry   rz   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_outputsrJ   rJ   rK   rY     sx    


zErnieEncoder.forward)	NNNNNNFFT)rZ   r[   r\   r.   r?   r`   r   r^   r   r   r   r   rY   ra   rJ   rJ   rH   rK   r     s.   	         r   c                       s0   e Zd Z fddZejejdddZ  ZS )ErniePoolerc                    s*   t    t|j|j| _t | _d S r   )r-   r.   r   rk   r1   r   ZTanh
activationrE   rH   rJ   rK   r.   +  s    
zErniePooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rF   rw   Zfirst_token_tensorpooled_outputrJ   rJ   rK   rY   0  s    

zErniePooler.forwardr   rJ   rJ   rH   rK   r   *  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )ErniePredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S r   )r-   r.   r   rk   r1   r   r   r   r   r   transform_act_fnr9   r:   rE   rH   rJ   rK   r.   ;  s    
z%ErniePredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S r   )r   r   r9   r   rJ   rJ   rK   rY   D  s    


z$ErniePredictionHeadTransform.forwardr   rJ   rJ   rH   rK   r   :  s   	r   c                       s,   e Zd Z fddZdd Zdd Z  ZS )ErnieLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)bias)r-   r.   r   	transformr   rk   r1   r0   decoder	Parameterr?   rB   r   rE   rH   rJ   rK   r.   M  s
    

zErnieLMPredictionHead.__init__c                 C   s   | j | j_ d S r   )r   r   rF   rJ   rJ   rK   _tie_weightsZ  s    z"ErnieLMPredictionHead._tie_weightsc                 C   s   |  |}| |}|S r   )r   r   r   rJ   rJ   rK   rY   ]  s    

zErnieLMPredictionHead.forward)rZ   r[   r\   r.   r   rY   ra   rJ   rJ   rH   rK   r   L  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )ErnieOnlyMLMHeadc                    s   t    t|| _d S r   )r-   r.   r   predictionsrE   rH   rJ   rK   r.   e  s    
zErnieOnlyMLMHead.__init__)sequence_outputrP   c                 C   s   |  |}|S r   )r   )rF   r   prediction_scoresrJ   rJ   rK   rY   i  s    
zErnieOnlyMLMHead.forwardr   rJ   rJ   rH   rK   r   d  s   r   c                       s$   e Zd Z fddZdd Z  ZS )ErnieOnlyNSPHeadc                    s   t    t|jd| _d S Nrf   )r-   r.   r   rk   r1   seq_relationshiprE   rH   rJ   rK   r.   p  s    
zErnieOnlyNSPHead.__init__c                 C   s   |  |}|S r   )r   )rF   r   seq_relationship_scorerJ   rJ   rK   rY   t  s    
zErnieOnlyNSPHead.forwardrZ   r[   r\   r.   rY   ra   rJ   rJ   rH   rK   r   o  s   r   c                       s$   e Zd Z fddZdd Z  ZS )ErniePreTrainingHeadsc                    s(   t    t|| _t|jd| _d S r   )r-   r.   r   r   r   rk   r1   r   rE   rH   rJ   rK   r.   {  s    

zErniePreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r   )r   r   )rF   r   r   r   r   rJ   rJ   rK   rY     s    

zErniePreTrainingHeads.forwardr   rJ   rJ   rH   rK   r   z  s   r   c                   @   s$   e Zd ZdZeZdZdZdd ZdS )ErniePreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ernieTc                 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   rk   ZweightdataZnormal_rG   Zinitializer_ranger   Zzero_r/   r#   r9   Zfill_)rF   modulerJ   rJ   rK   _init_weights  s    

z"ErniePreTrainedModel._init_weightsN)	rZ   r[   r\   r]   r!   config_classZbase_model_prefixZsupports_gradient_checkpointingr   rJ   rJ   rJ   rK   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 )ErnieForPreTrainingOutputa]  
    Output type of [`ErnieForPreTraining`].

    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_logitsrw   r   )rZ   r[   r\   r]   r   r   r?   r^   __annotations__r   r   rw   r   r   rJ   rJ   rJ   rK   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 ([`ErnieConfig`]): 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)
        task_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Task type embedding is a special embedding to represent the characteristic of different tasks, such as
            word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
            assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
            config.task_type_vocab_size-1]
        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.
        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 Ernie 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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 )
ErnieModela  

    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 r   )
r-   r.   rG   r"   rX   r   encoderr   pooler	post_init)rF   rG   add_pooling_layerrH   rJ   rK   r.     s    

zErnieModel.__init__c                 C   s   | j jS r   rX   r3   r   rJ   rJ   rK   get_input_embeddings*  s    zErnieModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rF   rn   rJ   rJ   rK   set_input_embeddings.  s    zErnieModel.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   )rF   Zheads_to_pruner   r   rJ   rJ   rK   _prune_heads2  s    zErnieModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer   N)rL   rx   r*   rM   r'   ry   rN   rz   r{   r   r   r}   r   r   rP   c                  C   s`  |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}|sD||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 timer(   z5You have to specify either input_ids or inputs_embedsr   rf   )rR   r*   rQ   )rL   r'   r*   rM   rN   rO   )	rx   ry   rz   r{   r   r   r}   r   r   r    )r   Zpooler_outputr   rw   r   r   )rG   r}   r   use_return_dictrp   r   rh   Z%warn_if_padding_and_no_attention_maskrC   rR   r   r?   ZonesrS   rX   r*   rA   rB   rD   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r   r   r   r   rw   r   r   ) rF   rL   rx   r*   rM   r'   ry   rN   rz   r{   r   r   r}   r   r   rT   Z
batch_sizerU   rR   rO   rV   rW   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsr   r   rJ   rJ   rK   rY   :  s    +




zErnieModel.forward)T)NNNNNNNNNNNNNN)rZ   r[   r\   r]   r.   r   r   r   r   ERNIE_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r?   r`   r   r^   r   r   r   rY   ra   rJ   rJ   rH   rK   r     sT                 r   z
    Ernie 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dgZ fddZdd Zdd Zee	d	e
eed
deej eej eej eej eej eej eej eej eej ee ee ee eeej ef dddZ  ZS )ErnieForPreTrainingcls.predictions.decoder.biascls.predictions.decoder.weightc                    s,   t  | t|| _t|| _|   d S r   )r-   r.   r   r   r   clsr   rE   rH   rJ   rK   r.     s    

zErnieForPreTraining.__init__c                 C   s
   | j jjS r   r   r   r   r   rJ   rJ   rK   get_output_embeddings  s    z)ErnieForPreTraining.get_output_embeddingsc                 C   s   || j j_|j| j j_d S r   r   r   r   r   rF   Znew_embeddingsrJ   rJ   rK   set_output_embeddings  s    
z)ErnieForPreTraining.set_output_embeddingsr   r   r   N)rL   rx   r*   rM   r'   ry   rN   labelsnext_sentence_labelr}   r   r   rP   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, ErnieForPreTraining
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
        >>> model = ErnieForPreTraining.from_pretrained("nghuyong/ernie-1.0-base-zh")

        >>> 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	rx   r*   rM   r'   ry   rN   r}   r   r   rf   r(   )r   r   r   rw   r   )
rG   r   r   r   r	   rs   r0   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r  r  r}   r   r   r   r   r   r   r   
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   rJ   rJ   rK   rY     s>    1zErnieForPreTraining.forward)NNNNNNNNNNNN)rZ   r[   r\   _tied_weights_keysr.   r  r  r   r   r   r   r   r   r   r?   r`   r   r   r   rY   ra   rJ   rJ   rH   rK   r     sB   

            r   zGErnie Model with a `language modeling` head on top for CLM fine-tuning.c                       s   e Zd Zd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j eej eeej  ee ee ee ee eeej ef dddZdddZdd Z  ZS )ErnieForCausalLMr   r   c                    s@   t  | |jstd t|dd| _t|| _| 	  d S )NzMIf you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`Fr   
r-   r.   rp   r   warningr   r   r   r   r   rE   rH   rJ   rK   r.   @  s    

zErnieForCausalLM.__init__c                 C   s
   | j jjS r   r   r   rJ   rJ   rK   r  M  s    z&ErnieForCausalLM.get_output_embeddingsc                 C   s   || j j_|j| j j_d S r   r  r  rJ   rJ   rK   r  Q  s    
z&ErnieForCausalLM.set_output_embeddingsr   r   N)rL   rx   r*   rM   r'   ry   rN   rz   r{   r  r   r   r}   r   r   rP   c                 C   s  |dk	r|n| j j}|
dk	r d}| j|||||||||	|||||d}|d }| |}d}|
dk	r|ddddddf  }|
ddddf  }
t }||d| j j|
d}|s|f|dd  }|dk	r|f| S |S t|||j	|j
|j|jdS )	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**.
        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 n `[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`).
        NF)rx   r*   rM   r'   ry   rN   rz   r{   r   r   r}   r   r   r   r(   r    rf   )r   logitsr   rw   r   r   )rG   r   r   r   r   r	   rs   r0   r   r   rw   r   r   )rF   rL   rx   r*   rM   r'   ry   rN   rz   r{   r  r   r   r}   r   r   r   r   r   Zlm_lossZshifted_prediction_scoresr
  r   rJ   rJ   rK   rY   U  sL    0
zErnieForCausalLM.forwardTc           	      K   sv   |j }|d kr||}|d k	rh|d d j d }|j d |krF|}n|j d d }|d d |d f }||||dS )Nr   rf   r    )rL   rx   r   r   )r   Znew_ones)	rF   rL   r   rx   r   model_kwargsrT   Zpast_lengthZremove_prefix_lengthrJ   rJ   rK   prepare_inputs_for_generation  s    
z.ErnieForCausalLM.prepare_inputs_for_generationc                    s.   d}|D ] }|t  fdd|D f7 }q|S )NrJ   c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selectr   rR   )r   Z
past_statebeam_idxrJ   rK   r     s     z2ErnieForCausalLM._reorder_cache.<locals>.<genexpr>)r   )rF   r   r  Zreordered_pastZ
layer_pastrJ   r  rK   _reorder_cache  s    zErnieForCausalLM._reorder_cache)NNNNNNNNNNNNNNN)NNT)rZ   r[   r\   r  r.   r  r  r   r   r   r   r   r   r   r   r?   r`   r   r   r   r   rY   r  r  ra   rJ   rJ   rH   rK   r  9  s`                  Y     
r  z3Ernie Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZdd Zdd Zee	d	e
eeed
dddeej eej eej eej eej eej eej ee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 )ErnieForMaskedLMr   r   c                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NzlIf you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr  r  rE   rH   rJ   rK   r.     s    
zErnieForMaskedLM.__init__c                 C   s
   | j jjS r   r   r   rJ   rJ   rK   r    s    z&ErnieForMaskedLM.get_output_embeddingsc                 C   s   || j j_|j| j j_d S r   r  r  rJ   rJ   rK   r    s    
z&ErnieForMaskedLM.set_output_embeddingsr   z'paris'g)\(?)r   r   r   Zexpected_outputZexpected_lossN)rL   rx   r*   rM   r'   ry   rN   rz   r{   r  r}   r   r   rP   c                 C   s   |dk	r|n| j j}| j|||||||||	|||d}|d }| |}d}|
dk	rvt }||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)rx   r*   rM   r'   ry   rN   rz   r{   r}   r   r   r   r(   rf   r   r  rw   r   )
rG   r   r   r   r	   rs   r0   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   rz   r{   r  r}   r   r   r   r   r   r  r
  r   rJ   rJ   rK   rY     s<    
zErnieForMaskedLM.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    r(   r~   rQ   )rL   rx   )
r   rG   r2   rh   r?   r   Z	new_zerosfullrD   rR   )rF   rL   rx   r  rT   Zeffective_batch_sizeZdummy_tokenrJ   rJ   rK   r  :  s    "   z.ErnieForMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNNNN)N)rZ   r[   r\   r  r.   r  r  r   r   r   r   r   r   r   r   r?   r`   r   r   r   rY   r  ra   rJ   rJ   rH   rK   r    sT   	             <r  zKErnie 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j e
ej e
e e
e e
e eeej ef dddZ  ZS )
ErnieForNextSentencePredictionc                    s,   t  | t|| _t|| _|   d S r   )r-   r.   r   r   r   r   r   rE   rH   rJ   rK   r.   Q  s    

z'ErnieForNextSentencePrediction.__init__r   r  NrL   rx   r*   rM   r'   ry   rN   r  r}   r   r   rP   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, ErnieForNextSentencePrediction
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
        >>> model = ErnieForNextSentencePrediction.from_pretrained("nghuyong/ernie-1.0-base-zh")

        >>> 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    r(   rf   r  )warningswarnFutureWarningpoprG   r   r   r   r	   rs   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r  r}   r   r   kwargsr   r   Zseq_relationship_scoresr  r
  r   rJ   rJ   rK   rY   Z  sD    .

z&ErnieForNextSentencePrediction.forward)NNNNNNNNNNN)rZ   r[   r\   r.   r   r   r   r   r   r   r   r?   r`   r   r   r   rY   ra   rJ   rJ   rH   rK   r  K  s8   	
           r  z
    Ernie 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deej	 eej	 eej	 eej	 eej	 eej	 eej	 eej	 ee
 ee
 ee
 eeej	 ef dddZ  ZS )	ErnieForSequenceClassificationc                    sd   t  | |j| _|| _t|| _|jd k	r4|jn|j}t	|| _
t|j|j| _|   d S r   )r-   r.   
num_labelsrG   r   r   classifier_dropoutr<   r   r;   r=   rk   r1   
classifierr   rF   rG   r$  rH   rJ   rK   r.     s    
z'ErnieForSequenceClassification.__init__r   Nr  c                 C   s~  |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}| |}d}|dk	r:| j jdkr| jdkr|d| 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r:t }|||}|sj|f|dd  }|dk	rf|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_classificationr(   rf   r  )rG   r   r   r=   r%  Zproblem_typer#  r,   r?   rD   r_   r
   squeezer	   rs   r   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r  r}   r   r   r   r   r  r   r
  r   rJ   rJ   rK   rY     sX    




"


z&ErnieForSequenceClassification.forward)NNNNNNNNNNN)rZ   r[   r\   r.   r   r   r   r   r?   r`   r   r   r   r   rY   ra   rJ   rJ   rH   rK   r"    s6   	           r"  z
    Ernie Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
ErnieForMultipleChoicec                    sT   t  | t|| _|jd k	r&|jn|j}t|| _t	|j
d| _|   d S )Nr    )r-   r.   r   r   r$  r<   r   r;   r=   rk   r1   r%  r   r&  rH   rJ   rK   r.      s    
zErnieForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   Nr  c                 C   sv  |dk	r|n| j j}|dk	r&|jd n|jd }|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	|
|d
}|d }| |}| |}|d|}d}|dk	r2t }|||}|sb|f|dd  }|dk	r^|f| S |S t	|||j
|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr    r(   r   r  rf   r  )rG   r   r   rs   rC   r   r=   r%  r	   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r  r}   r   r   Znum_choicesr   r   r  Zreshaped_logitsr   r
  r   rJ   rJ   rK   rY   -  sN    



zErnieForMultipleChoice.forward)NNNNNNNNNNN)rZ   r[   r\   r.   r   r   r   r   r   r   r   r   r?   r`   r   r   r   rY   ra   rJ   rJ   rH   rK   r(    s@   	           r(  z
    Ernie 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deej	 eej	 eej	 eej	 eej	 eej	 eej	 eej	 ee
 ee
 ee
 eeej	 ef dddZ  ZS )	ErnieForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j|j| _|   d S NFr  )r-   r.   r#  r   r   r$  r<   r   r;   r=   rk   r1   r%  r   r&  rH   rJ   rK   r.     s    z$ErnieForTokenClassification.__init__r   Nr  c                 C   s   |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}| |}d}|dk	rzt }||d| j|d}|s|f|dd  }|dk	r|f| S |S t|||j	|j
dS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr  r   r(   rf   r  )rG   r   r   r=   r%  r	   rs   r#  r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r  r}   r   r   r   r   r  r   r
  r   rJ   rJ   rK   rY     s:    

z#ErnieForTokenClassification.forward)NNNNNNNNNNN)rZ   r[   r\   r.   r   r   r   r   r?   r`   r   r   r   r   rY   ra   rJ   rJ   rH   rK   r)  x  s6   	           r)  z
    Ernie 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deej	 eej	 eej	 eej	 eej	 eej	 eej	 eej	 eej	 ee
 ee
 ee
 eeej	 ef dddZ  ZS )	ErnieForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r*  )
r-   r.   r#  r   r   r   rk   r1   
qa_outputsr   rE   rH   rJ   rK   r.     s
    z"ErnieForQuestionAnswering.__init__r   N)rL   rx   r*   rM   r'   ry   rN   start_positionsend_positionsr}   r   r   rP   c                 C   sR  |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 }|s<||f|dd  }|dk	r8|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    r(   r~   )Zignore_indexrf   )r   start_logits
end_logitsrw   r   )rG   r   r   r,  splitr'  r   r   rC   clampr	   r   rw   r   )rF   rL   rx   r*   rM   r'   ry   rN   r-  r.  r}   r   r   r   r   r  r/  r0  r	  Zignored_indexr
  Z
start_lossZend_lossr   rJ   rJ   rK   rY     sR    






z!ErnieForQuestionAnswering.forward)NNNNNNNNNNNN)rZ   r[   r\   r.   r   r   r   r   r?   r`   r   r   r   r   rY   ra   rJ   rJ   rH   rK   r+    s:   	
            r+  )Nr]   r   r  Zdataclassesr   typingr   r   r   r   r?   Ztorch.utils.checkpointr   Ztorch.nnr   r	   r
   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   Zconfiguration_ernier!   Z
get_loggerrZ   r   r   r   Moduler"   rb   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ZERNIE_START_DOCSTRINGr   r   r   r  r  r  r"  r(  r)  r+  rJ   rJ   rJ   rK   <module>   s   , 
M  4W^!7 7m  qe\ZH