
    i                        d 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 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 dd
lmZmZmZ ddlm Z m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7  ejp                  e9      Z: G d de&      Z; G d de5      Z< G d de%      Z= G d de0      Z> G d de4      Z? G d de2      Z@ G d de'      ZAe G d d e             ZB G d! d"e3      ZC G d# d$e,      ZD G d% d&e+      ZE G d' d(e1      ZF G d) d*e(      ZG G d+ d,e*      ZH G d- d.e.      ZI G d/ d0e)      ZJ G d1 d2e/      ZK G d3 d4e-      ZLg d5ZMy)6zPyTorch ERNIE model.    N)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)CacheDynamicCacheEncoderDecoderCache),BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)Unpack)TransformersKwargsauto_docstringlogging)can_return_tuplemerge_with_config_defaults)capture_outputs   )BertCrossAttentionBertEmbeddingsBertEncoderBertForMaskedLMBertForMultipleChoiceBertForNextSentencePredictionBertForPreTrainingBertForPreTrainingOutputBertForQuestionAnsweringBertForSequenceClassificationBertForTokenClassification	BertLayerBertLMHeadModelBertLMPredictionHead	BertModel
BertPoolerBertSelfAttention   )ErnieConfigc                        e Zd ZdZ fdZ	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ed
ej                  fdZ
 xZS )ErnieEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                     t         |   |       |j                  | _        |j                  r0t        j                  |j
                  |j                        | _        y y )N)super__init__use_task_idnn	Embeddingtask_type_vocab_sizehidden_sizetask_type_embeddings)selfconfig	__class__s     x/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/ernie/modular_ernie.pyr3   zErnieEmbeddings.__init__A   sL     !--(*V5P5PRXRdRd(eD%     N	input_idstoken_type_idstask_type_idsposition_idsinputs_embedspast_key_values_lengthreturnc                 |   ||j                         }n|j                         d d }|\  }}	|| j                  d d ||	|z   f   }|t        | d      rT| j                  j	                  |j
                  d   d      }
t        j                  |
d|      }
|
j	                  ||	      }n:t        j                  |t        j                  | j                  j                        }|| j                  |      }| j                  |      }|j                  |j                        }||z   }| j                  |      }||z   }| j                  rR|:t        j                  |t        j                  | j                  j                        }| j!                  |      }||z  }| j#                  |      }| j%                  |      }|S )Nr@   r   r-   )dimindex)dtypedevice)sizerB   hasattrr@   expandshapetorchgatherzeroslongrK   word_embeddingstoken_type_embeddingstoposition_embeddingsr4   r9   	LayerNormdropout)r:   r?   r@   rA   rB   rC   rD   input_shape
batch_size
seq_lengthbuffered_token_type_idsrU   
embeddingsrW   r9   s                  r=   forwardzErnieEmbeddings.forwardH   s     #..*K',,.s3K!,
J,,Q0FVlIl0l-lmL
 !t-.*.*=*=*D*D\EWEWXYEZ\^*_'*/,,7NTU]i*j'!8!?!?
J!W!&[

SWSdSdSkSk!l  00;M $ : :> J &(()>)E)EF"%::
"66|D"55
 $ %KuzzRVRcRcRjRj k#'#<#<]#K ..J^^J/
\\*-
r>   )NNNNNr   )__name__
__module____qualname____doc__r3   rP   
LongTensorFloatTensorintTensorr_   __classcell__r<   s   @r=   r0   r0   >   s    Qf .226150426&'3##d*3 ((4/3 ''$.	3
 &&-3 ((4/3 !$3 
3r>   r0   c                       e Zd Zy)ErnieSelfAttentionNr`   ra   rb    r>   r=   rk   rk   ~       r>   rk   c                       e Zd Zy)ErnieCrossAttentionNrl   rm   r>   r=   rp   rp      rn   r>   rp   c                       e Zd Zy)
ErnieLayerNrl   rm   r>   r=   rr   rr      rn   r>   rr   c                       e Zd Zy)ErniePoolerNrl   rm   r>   r=   rt   rt      rn   r>   rt   c                       e Zd Zy)ErnieLMPredictionHeadNrl   rm   r>   r=   rv   rv      rn   r>   rv   c                       e Zd Zy)ErnieEncoderNrl   rm   r>   r=   rx   rx      rn   r>   rx   c                   n     e Zd ZeZdZdZdZdZdZ	dZ
eeedZ ej                           fd       Z xZS )ErniePreTrainedModelernieT)hidden_states
attentionscross_attentionsc                    t         |   |       t        |t              r t	        j
                  |j                         yt        |t              ryt	        j                  |j                  t        j                  |j                  j                  d         j                  d             t	        j
                  |j                         yy)zInitialize the weightsrG   )r-   rG   N)r2   _init_weights
isinstancerv   initzeros_biasr0   copy_rB   rP   arangerO   rN   r@   )r:   moduler<   s     r=   r   z"ErniePreTrainedModel._init_weights   s     	f%f34KK$0JJv**ELL9L9L9R9RSU9V,W,^,^_f,ghKK--. 1r>   )r`   ra   rb   r.   config_classbase_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendrr   rk   rp   _can_record_outputsrP   no_gradr   rh   ri   s   @r=   rz   rz      sX    L&*#N"&#(/ U]]_/ /r>   rz   c                       e Zd ZdgZd fd	Zeee	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  de
dz  dedz  dee   deej                     ez  fd                     Z xZS )
ErnieModelrr   c                     t         |   | |       || _        d| _        t	        |      | _        t        |      | _        |rt        |      nd | _	        | j                          y )NF)r2   r3   r;   gradient_checkpointingr0   r^   rx   encoderrt   pooler	post_init)r:   r;   add_pooling_layerr<   s      r=   r3   zErnieModel.__init__   sU    v&&+#)&1#F+->k&)D 	r>   Nr?   attention_maskr@   rA   rB   rC   encoder_hidden_statesencoder_attention_maskpast_key_values	use_cachekwargsrE   c           
         |du |duz  rt        d      | j                  j                  r|
|
n| j                  j                  }
nd}
|
rd|	b|| j                  j                  r4t        t        | j                        t        | j                              nt        | j                        }	|	|	j                         nd}| j                  ||||||      }| j                  |||||	      \  }} | j                  |f||||	|
|d|}|d   }| j                  | j                  |      nd}t        |||j                  	      S )
  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        Nz:You must specify exactly one of input_ids or inputs_embedsF)r;   r   )r?   rB   r@   rA   rC   rD   )r   r   embedding_outputr   r   )r   r   r   r   r   rB   )last_hidden_statepooler_outputr   )
ValueErrorr;   
is_decoderr   is_encoder_decoderr
   r	   get_seq_lengthr^   _create_attention_masksr   r   r   r   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   rD   r   encoder_outputssequence_outputpooled_outputs                    r=   r_   zErnieModel.forward   s~   0 -t";<YZZ;;!!%.%:	@U@UII0 )48V8V $L$DlZ^ZeZeFfg!5  FUE`!?!?!Afg??%)''#9 + 
 261M1M)#9-"7+ 2N 2
.. '$,,	
)"7#9+%	
 	
 *!,8<8OO4UY;-'+;;
 	
r>   )T)
NNNNNNNNNN)r`   ra   rb   _no_split_modulesr3   r   r   r   rP   rg   r   boolr   r   tupler   r_   rh   ri   s   @r=   r   r      s=   %   *..2.2-1,0-1596:(,!%H
<<$&H
 t+H
 t+	H

 ||d*H
 llT)H
 ||d*H
  %||d2H
 !&t 3H
 H
 $;H
 +,H
 
u||	K	KH
    H
r>   r   c                       e Zd Zy)ErnieForPreTrainingOutputNrl   rm   r>   r=   r   r     rn   r>   r   c                   b   e Zd ZdddZee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dee	   de
ej                     ez  fd              Zy)ErnieForPreTrainingcls.predictions.bias'ernie.embeddings.word_embeddings.weightzcls.predictions.decoder.biaszcls.predictions.decoder.weightNr?   r   r@   rA   rB   rC   labelsnext_sentence_labelr   rE   c	           
          | j                   |f|||||dd|	}
|
dd \  }}| j                  ||      \  }}d}|u|st               } ||j                  d| j                  j
                        |j                  d            } ||j                  dd      |j                  d            }||z   }t        ||||
j                  |
j                        S )a:  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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.

        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
        ```
        Tr   r@   rA   rB   rC   return_dictNr   rG   )lossprediction_logitsseq_relationship_logitsr|   r}   )	r{   clsr   viewr;   
vocab_sizer   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   outputsr   r   prediction_scoresseq_relationship_score
total_lossloss_fctmasked_lm_lossnext_sentence_losss                      r=   r_   zErnieForPreTraining.forward  s   ^ $**	
))'%'	
 	
 *1!&48HH_m4\11
"5"A')H%&7&<&<RAWAW&XZ`ZeZefhZijN!)*@*E*Eb!*LNaNfNfgiNj!k'*<<J(/$:!//))
 	
r>   NNNNNNNN)r`   ra   rb   _tied_weights_keysr   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r     s   (>*S
  *..2.2-1,0-1&*37H
<<$&H
 t+H
 t+	H

 ||d*H
 llT)H
 ||d*H
 t#H
 #\\D0H
 +,H
 
u||	8	8H
  H
r>   r   c                       e Zd Zee	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  deej                     dz  dedz  de	ej                  z  de
e   deej                     ez  fd              Zy)ErnieForCausalLMNr?   r   r@   rA   rB   rC   r   r   r   r   r   logits_to_keepr   rE   c                    |	d} | j                   |f||||||||
|dd
|}|j                  }t        |t              rt	        | d      n|}| j                  |dd|ddf         }d}|	* | j                  d||	| j                  j                  d|}t        |||j                  |j                  |j                  |j                        S )a  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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]`
        NFT)
r   r@   rA   rB   rC   r   r   r   r   r   )logitsr   r   )r   r   r   r|   r}   r~   rm   )r{   r   r   rf   slicer   loss_functionr;   r   r   r   r|   r}   r~   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   r   r   r   r|   slice_indicesr   r   s                      r=   r_   zErnieForCausalLM.forwardf  s    : I@J

A
))'%'"7#9+A
 A
  118B>SV8W~ot4]k-=!(;<=%4%%pVFt{{OeOepiopD0#33!//))$55
 	
r>   )NNNNNNNNNNNr   )r`   ra   rb   r   r   rP   rg   listr   rf   r   r   r   r   r_   rm   r>   r=   r   r   e  sM    *..2.2-1,0-1596:&*59!%-.=
<<$&=
 t+=
 t+	=

 ||d*=
 llT)=
 ||d*=
  %||d2=
 !&t 3=
 t#=
 ell+d2=
 $;=
 ell*=
 +,=
 
u||	@	@=
  =
r>   r   c                      e Zd ZdddZee	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dej                  dz  dee	   de
ej                     ez  fd              Zy)ErnieForMaskedLMr   r   r   Nr?   r   r@   rA   rB   rC   r   r   r   r   rE   c
                 @    | j                   |f|||||||dd|
}|d   }| j                  |      }d}|	Ft               } ||j                  d| j                  j
                        |	j                  d            }t        |||j                  |j                        S )as  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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]`
        T)r   r@   rA   rB   rC   r   r   r   r   NrG   r   r   r|   r}   )	r{   r   r   r   r;   r   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   r   r   r   r   s                   r=   r_   zErnieForMaskedLM.forward  s    4 $**
))'%'"7#9
 
 "!* HH_5')H%&7&<&<RAWAW&XZ`ZeZefhZijN$!//))	
 	
r>   )	NNNNNNNNN)r`   ra   rb   r   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r     s   (>*S
  *..2.2-1,0-1596:&*2
<<$&2
 t+2
 t+	2

 ||d*2
 llT)2
 ||d*2
  %||d22
 !&t 32
 t#2
 +,2
 
u||	~	-2
  2
r>   r   c                   8   e Zd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ee   d
e	ej                     e
z  fd              Zy)ErnieForNextSentencePredictionNr?   r   r@   rA   rB   rC   r   r   rE   c           
          | j                   |f|||||dd|}	|	d   }
| j                  |
      }d}|2t               } ||j                  dd      |j                  d            }t	        |||	j
                  |	j                        S )a  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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.

        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
        ```
        Tr   r-   NrG   r   r   )r{   r   r   r   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   seq_relationship_scoresr   r   s                 r=   r_   z&ErnieForNextSentencePrediction.forward  s    Z $**	
))'%'	
 	
  
"&((="9!')H!)*A*F*Fr1*Mv{{[]!_*#*!//))	
 	
r>   NNNNNNN)r`   ra   rb   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r     s     *..2.2-1,0-1&*D
<<$&D
 t+D
 t+	D

 ||d*D
 llT)D
 ||d*D
 t#D
 +,D
 
u||	:	:D
  D
r>   r   c                   8   e Zd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ee   d
e	ej                     e
z  fd              Zy)ErnieForSequenceClassificationNr?   r   r@   rA   rB   rC   r   r   rE   c           
          | j                   |f|||||dd|}	|	d   }
| j                  |
      }
| j                  |
      }d}|| j                  j                  | j
                  dk(  rd| j                  _        nl| j
                  dkD  rL|j                  t        j                  k(  s|j                  t        j                  k(  rd| j                  _        nd| j                  _        | j                  j                  dk(  rIt               }| j
                  dk(  r& ||j                         |j                               }n |||      }n| j                  j                  dk(  r=t               } ||j                  d| j
                        |j                  d            }n,| j                  j                  dk(  rt               } |||      }t        |||	j                   |	j"                  	      S )
a^  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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).
        Tr   r-   N
regressionsingle_label_classificationmulti_label_classificationrG   r   )r{   rY   
classifierr;   problem_type
num_labelsrJ   rP   rS   rf   r   squeezer   r   r   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   r   r   s                 r=   r_   z&ErnieForSequenceClassification.forward0  s   0 $**	
))'%'	
 	
  
]3/{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#FF3D))-JJ+-B @&++b/R))-II,./'!//))	
 	
r>   r   )r`   ra   rb   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r   /  s     *..2.2-1,0-1&*B
<<$&B
 t+B
 t+	B

 ||d*B
 llT)B
 ||d*B
 t#B
 +,B
 
u||	7	7B
  B
r>   r   c                   8   e Zd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ee   d
e	ej                     e
z  fd              Zy)ErnieForMultipleChoiceNr?   r   r@   rA   rB   rC   r   r   rE   c           
         ||j                   d   n|j                   d   }	|!|j                  d|j                  d            nd}|!|j                  d|j                  d            nd}|!|j                  d|j                  d            nd}|!|j                  d|j                  d            nd}|1|j                  d|j                  d      |j                  d            nd} | j                  |f|||||dd|}
|
d   }| j	                  |      }| j                  |      }|j                  d|	      }d}|t               } |||      }t        |||
j                  |
j                        S )a9	  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            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)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *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 `(batch_size, num_choices, sequence_length)`, *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 `(batch_size, num_choices, sequence_length)`, *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)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, 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.
        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-   rG   Tr   r   )
rO   r   rL   r{   rY   r   r   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   num_choicesr   r   r   reshaped_logitsr   r   s                   r=   r_   zErnieForMultipleChoice.forwardx  s   ` -6,Aiooa(}GZGZ[\G]>G>SINN2y~~b'9:Y]	M[Mg,,R1D1DR1HImqM[Mg,,R1D1DR1HImqGSG_|((\->->r-BCei ( r=#5#5b#9=;M;Mb;QR 	 $**	
))'%'	
 	
  
]3/ ++b+6')HOV4D("!//))	
 	
r>   r   )r`   ra   rb   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r   w  s     *..2.2-1,0-1&*U
<<$&U
 t+U
 t+	U

 ||d*U
 llT)U
 ||d*U
 t#U
 +,U
 
u||	8	8U
  U
r>   r   c                   8   e Zd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ee   d
e	ej                     e
z  fd              Zy)ErnieForTokenClassificationNr?   r   r@   rA   rB   rC   r   r   rE   c           
      J    | j                   |f|||||dd|}	|	d   }
| j                  |
      }
| j                  |
      }d}|<t               } ||j	                  d| j
                        |j	                  d            }t        |||	j                  |	j                        S )a  
        task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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]
        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]`.
        Tr   r   NrG   r   )	r{   rY   r   r   r   r   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   r   r   s                 r=   r_   z#ErnieForTokenClassification.forward  s    , $**	
))'%'	
 	
 "!*,,71')HFKKDOO<fkk"oND$!//))	
 	
r>   r   )r`   ra   rb   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r     s     *..2.2-1,0-1&*.
<<$&.
 t+.
 t+	.

 ||d*.
 llT).
 ||d*.
 t#.
 +,.
 
u||	4	4.
  .
r>   r   c                   X   e Zd Zee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ee   de	ej                     e
z  fd              Zy)ErnieForQuestionAnsweringNr?   r   r@   rA   rB   rC   start_positionsend_positionsr   rE   c	           
          | j                   |f|||||dd|	}
|
d   }| j                  |      }|j                  dd      \  }}|j                  d      j	                         }|j                  d      j	                         }d}||t        |j                               dkD  r|j                  d      }t        |j                               dkD  r|j                  d      }|j                  d      }|j                  d|      }|j                  d|      }t        |      } |||      } |||      }||z   d	z  }t        ||||
j                  |
j                  
      S )r   Tr   r   r-   rG   )rH   N)ignore_indexr   )r   start_logits
end_logitsr|   r}   )r{   
qa_outputssplitr   
contiguouslenrL   clampr   r   r|   r}   )r:   r?   r   r@   rA   rB   rC   r   r   r   r   r   r   r   r   r   ignored_indexr   
start_lossend_losss                       r=   r_   z!ErnieForQuestionAnswering.forward  s   * $**	
))'%'	
 	
 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J+%!!//))
 	
r>   r   )r`   ra   rb   r   r   rP   rg   r   r   r   r   r_   rm   r>   r=   r   r     s     *..2.2-1,0-1/3-1<
<<$&<
 t+<
 t+	<

 ||d*<
 llT)<
 ||d*<
 ,<
 ||d*<
 +,<
 
u||	;	;<
  <
r>   r   )
r   r   r   r   r   r   r   r   r   rz   )Nrc   rP   torch.nnr5   r   r   r    r   r   cache_utilsr   r	   r
   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   processing_utilsr   utilsr   r   r   utils.genericr   r   utils.output_capturingr   bert.modeling_bertr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   configuration_ernier.   
get_loggerr`   loggerr0   rk   rp   rr   rt   rv   rx   rz   r   r   r   r   r   r   r   r   r   r   __all__rm   r>   r=   <module>r     s      A A & C C	 	 	 . & @ @ I 5    & - 
		H	%=n =@	* 		, 		 		* 		0 		; 	 /? / /2[
 [
|	 8 	P
, P
f@
 @
F:
 :
zG
%B G
TE
%B E
PX
2 X
v1
"< 1
h?
 8 ?
Dr>   