
    rh*                    0   d Z ddlZddlZddlmZ ddl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 dd
l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+ ddl,m-Z-  e+j\                  e/      Z0 G d de
jb                        Z2 G d de
jb                        Z3 G d de
jb                        Z4de3iZ5 G d de
jb                        Z6 G d de
jb                        Z7 G d de
jb                        Z8 G d d e      Z9 G d! d"e
jb                        Z: G d# d$e
jb                        Z; G d% d&e
jb                        Z< G d' d(e
jb                        Z= G d) d*e
jb                        Z> G d+ d,e
jb                        Z? G d- d.e
jb                        Z@e* G d/ d0e#             ZAe e*d12       G d3 d4e)                    ZB e*d52       G d6 d7eA             ZC e*d82       G d9 d:eA             ZD e*d;2       G d< d=eAe             ZEe* G d> d?eA             ZF e*d@2       G dA dBeA             ZG e*dC2       G dD dEeA             ZHe* G dF dGeA             ZIe* G dH dIeA             ZJe* G dJ dKeA             ZKg dLZLy)MzPyTorch ERNIE model.    N)	dataclass)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)GradientCheckpointingLayer)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputauto_docstringlogging   )ErnieConfigc                        e Zd ZdZ fdZ	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     de	d	ej                  fd
Z xZS )ErnieEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j                  |j
                        | _        |j                  | _        |j                  r/t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                         | _        t        j"                  |j$                        | _        t)        |dd      | _        | j-                  dt/        j0                  |j                        j3                  d      d       | j-                  d	t/        j4                  | j6                  j9                         t.        j:                  
      d       y )N)padding_idx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_embeddingstype_vocab_sizetoken_type_embeddingsuse_task_idtask_type_vocab_sizetask_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutgetattrr(   register_buffertorcharangeexpandzerosr*   sizelongselfconfig	__class__s     {/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/ernie/modeling_ernie.pyr1   zErnieEmbeddings.__init__6   sf   !||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c %'\\&2H2H&J\J\%]"!--(*V5P5PRXRdRd(eD% f&8&8f>S>STzz&"<"<='.v7PR\']$ELL)G)GHOOPWXej 	 	
 	ekk$*;*;*@*@*B%**Ubg 	 	
    	input_idsr-   task_type_idsr*   inputs_embedspast_key_values_lengthreturnc                    ||j                         }n|j                         d d }|d   }|| j                  d d |||z   f   }|st        | d      r-| j                  d d d |f   }	|	j	                  |d   |      }
|
}n:t        j                  |t
        j                  | j                  j                        }|| j                  |      }| j                  |      }||z   }| j                  dk(  r| j                  |      }||z  }| j                  rR|:t        j                  |t
        j                  | j                  j                        }| j                  |      }||z  }| j                  |      }| j!                  |      }|S )Nr+   r    r-   r   r/   devicer)   )rI   r*   hasattrr-   rG   rE   rH   rJ   rX   r6   r:   r(   r8   r;   r=   r>   rB   )rL   rQ   r-   rR   r*   rS   rT   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr:   
embeddingsr8   r=   s                  rO   forwardzErnieEmbeddings.forwardL   s     #..*K',,.s3K ^
,,Q0FVlIl0l-lmL
 !t-.*.*=*=a*n*M'3J3Q3QR]^_R`bl3m0!A!&[

SWSdSdSkSk!l  00;M $ : :> J"%::
'':5"&":":<"H--J $ %KuzzRVRcRcRjRj k#'#<#<]#K ..J^^J/
\\*-
rP   )NNNNNr   )__name__
__module____qualname____doc__r1   r   rE   
LongTensorFloatTensorintTensorr_   __classcell__rN   s   @rO   r#   r#   3   s    Q
0 1559483759&'0E,,-0 !!1!120   0 01	0
 u//00   1 120 !$0 
0rP   r#   c                        e Zd Zd fd	Z	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     dee   dee	   deej
                     d	e
ej
                     fd
Z xZS )ErnieSelfAttentionc                    t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                        | _        |xs t#        |dd      | _        | j$                  dk(  s| j$                  d	k(  rF|j&                  | _        t        j(                  d
|j&                  z  dz
  | j                        | _        |j,                  | _        || _        y )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r(   r)   relative_keyrelative_key_query   r    )r0   r1   r4   num_attention_headsrY   
ValueErrorrf   attention_head_sizeall_head_sizer   Linearquerykeyvaluer@   attention_probs_dropout_probrB   rC   r(   r7   r2   distance_embedding
is_decoder	layer_idxrL   rM   r(   r}   rN   s       rO   r1   zErnieSelfAttention.__init__   s    : ::a?PVXhHi#F$6$6#7 8 445Q8 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PPYYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF'> (
'-zC
$ ''>9T=Y=Y]q=q+1+I+ID(&(ll1v7U7U3UXY3Y[_[s[s&tD# ++"rP   hidden_statesattention_mask	head_maskencoder_hidden_statespast_key_valueoutput_attentionscache_positionrU   c                 	   |j                   \  }}	}
| j                  |      }|j                  |d| j                  | j                        j                  dd      }|d u}|St        |t              rA|j                  j                  | j                        }|r|j                  }n|j                  }n|}|r|n|}|rK|IrGj                  | j                     j                  }|j                  | j                     j                  }n| j!                  |      }|j                  |d| j                  | j                        j                  dd      }| j#                  |      }|j                  |d| j                  | j                        j                  dd      }|D|s|nd }j%                  ||| j                  d|i      \  }}|rd|j                  | j                  <   t'        j(                  ||j                  dd            }| j*                  dk(  s| j*                  dk(  r|j                   d   |j                   d   }}|Dt'        j,                  |dz
  t&        j.                  |j0                  	      j                  dd      }n@t'        j2                  |t&        j.                  |j0                  	      j                  dd      }t'        j2                  |t&        j.                  |j0                  	      j                  dd      }||z
  }| j5                  || j6                  z   dz
        }|j9                  |j:                  
      }| j*                  dk(  rt'        j<                  d||      }||z   }nE| j*                  dk(  r6t'        j<                  d||      }t'        j<                  d||      }||z   |z   }|t?        j@                  | j                        z  }|||z   }tB        jD                  jG                  |d      }| jI                  |      }|||z  }t'        j(                  ||      }|jK                  dddd      jM                         }|jO                         d d | jP                  fz   }|j                  |      }||fS )Nr+   r    rq   r   Tro   rp   rW   r.   zbhld,lrd->bhlrzbhrd,lrd->bhlrdimr   r
   ))shaperw   viewrr   rt   	transpose
isinstancer   
is_updatedgetr}   cross_attention_cacheself_attention_cachelayerskeysvaluesrx   ry   updaterE   matmulr(   tensorrJ   rX   rF   r{   r7   tor/   einsummathsqrtr   
functionalsoftmaxrB   permute
contiguousrI   ru   )rL   r   r   r   r   r   r   r   
batch_sizer[   _query_layeris_cross_attentionr   curr_past_key_valuecurrent_states	key_layervalue_layerattention_scoresquery_length
key_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapes                                  rO   r_   zErnieSelfAttention.forward   sN    %2$7$7!
Jjj/!&&z2t7O7OQUQiQijttq
 3$>%.*=>+66::4>>J
%*8*N*N'*8*M*M'&4#2D.-."<+224>>BGGI-44T^^DKKK0I!z2t7O7OQUQiQijtt1I **^4K%**B 8 8$:R:Ri1o  )7It)<)C)C{DNN=M~<^*&	; &@DN--dnn= !<<Y5H5HR5PQ''>9T=Y=Y]q=q'2'8'8';Y__Q=O*L)!&j1nEJJWdWkWk!l!q!q" "'l%**UbUiUi!j!o!oprtu!v"\\*EJJ}OcOcdiijkmopN%6H#'#:#:8dFbFb;bef;f#g #7#:#:ARAR#:#S ++~=+0<<8H+Wk+l(#36N#N --1EE16>NP[]q1r./4||<LiYm/n,#36T#TWs#s +dii8P8P.QQ%/.@ --//0@b/I ,,7  -	9O_kB%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S%**+BCo--rP   NNNNNNFN)r`   ra   rb   r1   rE   rg   r   re   r   booltupler_   rh   ri   s   @rO   rk   rk      s    #< 7;15=A*.,115d.||d. !!2!23d. E--.	d.
  ((9(9:d. !d. $D>d. !.d. 
u||	d.rP   rk   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )ErnieSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr&   )r0   r1   r   rv   r4   denser>   r?   r@   rA   rB   rK   s     rO   r1   zErnieSelfOutput.__init__  s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rP   r   input_tensorrU   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S Nr   rB   r>   rL   r   r   s      rO   r_   zErnieSelfOutput.forward  7    

=1]3}|'CDrP   r`   ra   rb   r1   rE   rg   r_   rh   ri   s   @rO   r   r     1    >U\\  RWR^R^ rP   r   eagerc                        e Zd Zd fd	Zd Z	 	 	 	 	 	 ddej                  deej                     deej                     deej                     dee	   dee
   d	eej                     d
eej                     fdZ xZS )ErnieAttentionc                     t         |           t        |j                     |||      | _        t        |      | _        t               | _        y )Nr(   r}   )	r0   r1   ERNIE_SELF_ATTENTION_CLASSES_attn_implementationrL   r   outputsetpruned_headsr~   s       rO   r1   zErnieAttention.__init__  sF    01L1LM$;
	
 &f-ErP   c                 >   t        |      dk(  ry t        || j                  j                  | j                  j                  | j
                        \  }}t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _	        t        | j                  j                  |d      | j                  _        | j                  j                  t        |      z
  | j                  _        | j                  j                  | j                  j                  z  | j                  _        | j
                  j                  |      | _        y )Nr   r    r   )lenr   rL   rr   rt   r   r   rw   rx   ry   r   r   ru   union)rL   headsindexs      rO   prune_headszErnieAttention.prune_heads#  s   u:?749900$))2O2OQUQbQb
u
 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EE
(R		%"&))"?"?$))B_B_"_		 --33E:rP   r   r   r   r   r   r   r   rU   c           	      r    | j                  |||||||      }| j                  |d   |      }	|	f|dd  z   }
|
S )Nr   r   r   r   r   r   r   r    )rL   r   )rL   r   r   r   r   r   r   r   self_outputsattention_outputoutputss              rO   r_   zErnieAttention.forward5  s\     yy)"7)/) ! 
  ;;|AF#%QR(88rP   r   r   )r`   ra   rb   r1   r   rE   rg   r   re   r   r   r   r_   rh   ri   s   @rO   r   r     s    ";* 7;15=A*.,115|| !!2!23 E--.	
  ((9(9: ! $D> !. 
u||	rP   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )ErnieIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r0   r1   r   rv   r4   intermediate_sizer   r   
hidden_actstrr   intermediate_act_fnrK   s     rO   r1   zErnieIntermediate.__init__O  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rP   r   rU   c                 J    | j                  |      }| j                  |      }|S r   )r   r   rL   r   s     rO   r_   zErnieIntermediate.forwardW  s&    

=100?rP   r   ri   s   @rO   r   r   N  s#    9U\\ ell rP   r   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )ErnieOutputc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        y r   )r0   r1   r   rv   r   r4   r   r>   r?   r@   rA   rB   rK   s     rO   r1   zErnieOutput.__init___  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rP   r   r   rU   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r   s      rO   r_   zErnieOutput.forwarde  r   rP   r   ri   s   @rO   r   r   ^  r   rP   r   c                       e Zd Zd fd	Z	 	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     deej                     dee   dee	   d	eej
                     d
e
ej
                     fdZd Z xZS )
ErnieLayerc                 l   t         |           |j                  | _        d| _        t	        ||      | _        |j                  | _        |j                  | _        | j                  r-| j                  st        |  d      t	        |d|      | _	        t        |      | _        t        |      | _        y )Nr    r}   z> should be used as a decoder model if cross attention is addedr)   r   )r0   r1   chunk_size_feed_forwardseq_len_dimr   	attentionr|   add_cross_attentionrs   crossattentionr   intermediater   r   )rL   rM   r}   rN   s      rO   r1   zErnieLayer.__init__n  s    '-'E'E$')D ++#)#=#= ##?? D6)g!hii"0Q[gp"qD-f5!&)rP   r   r   r   r   encoder_attention_maskr   r   r   rU   c	           	      H   | j                  ||||||      }	|	d   }
|	dd  }| j                  rB|@t        | d      st        d|  d      | j	                  |
||||||      }|d   }
||dd  z   }t        | j                  | j                  | j                  |
      }|f|z   }|S )N)r   r   r   r   r   r   r    r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   )	r   r|   rY   rs   r   r   feed_forward_chunkr   r   )rL   r   r   r   r   r   r   r   r   self_attention_outputsr   r   cross_attention_outputslayer_outputs                 rO   r_   zErnieLayer.forward|  s    "&)/)) "0 "
 2!4(,??4@4!12 =dV DD D 
 '+&9&9 5#&;-"3- ': '#  7q9 7 ;;G0##T%A%A4CSCSUe
  /G+rP   c                 L    | j                  |      }| j                  ||      }|S r   )r   r   )rL   r   intermediate_outputr   s       rO   r   zErnieLayer.feed_forward_chunk  s,    "//0@A{{#68HIrP   r   )NNNNNFN)r`   ra   rb   r1   rE   rg   r   re   r   r   r   r_   r   rh   ri   s   @rO   r   r   m  s    *" 7;15=A>B*.,115-||- !!2!23- E--.	-
  ((9(9:- !)):): ;- !- $D>- !.- 
u||	-^rP   r   c                   f    e Zd Zd fd	Z	 	 	 	 	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     deej                     deeeej                           dee	   d	ee	   d
ee	   dee	   deej
                     de
eej
                     ef   fdZ xZS )ErnieEncoderc           	          t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        d| _	        y c c}w )Nr   F)
r0   r1   rM   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)rL   rM   r}   irN   s       rO   r1   zErnieEncoder.__init__  sQ    ]]USYSkSkMl#mJv$C#mn
&+# $ns   A%r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictr   rU   c                    |	rdnd }|rdnd }|r| j                   j                  rdnd }| j                  r%| j                  r|rt        j                  d       d}d}|rR| j                   j                  r<t        |t              s,t        j                  d       d}t        j                  |      }t        | j                        D ]W  \  }}|	r||fz   }|||   nd } |||||||||      }|d   }|s/||d   fz   }| j                   j                  sO||d	   fz   }Y |	r||fz   }|r|j                         }|
st        d
 |||||fD              S t        |||||      S )N zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.T)r   r   r   r   r   r    rq   c              3   $   K   | ]  }|| 
 y wr   r  ).0vs     rO   	<genexpr>z'ErnieEncoder.forward.<locals>.<genexpr>  s      
 = 
s   )last_hidden_stater  r   
attentionscross_attentions)rM   r   r  trainingloggerwarning_oncer|   r   r   r   from_legacy_cache	enumerater   to_legacy_cacher   r   )rL   r   r   r   r   r   r  r  r   r  r  r   all_hidden_statesall_self_attentionsall_cross_attentionsreturn_legacy_cacher  layer_modulelayer_head_masklayer_outputss                       rO   r_   zErnieEncoder.forward  s    #7BD$5b4%64;;;Z;Zr`d&&4==##p "	#//
?TY8Z\
 #'1CCOTO(4 	VOA|#$58H$H!.7.CilO(%'=."3-	M *!,M &9]1=M<O&O#;;22+?=QRCSBU+U(+	V.   1]4D D-==?O 
 "#%'(
 
 
 9+++*1
 	
rP   r   )
NNNNNNFFTN)r`   ra   rb   r1   rE   rg   r   re   r   r   r   r   r_   rh   ri   s   @rO   r   r     s"   , 7;15=A>BEI$(,1/4&*15R
||R
 !!2!23R
 E--.	R

  ((9(9:R
 !)):): ;R
 "%e.?.?(@"ABR
 D>R
 $D>R
 'tnR
 d^R
 !.R
 
uU\\"$MM	NR
rP   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )ErniePoolerc                     t         |           t        j                  |j                  |j                        | _        t        j                         | _        y r   )r0   r1   r   rv   r4   r   Tanh
activationrK   s     rO   r1   zErniePooler.__init__  s9    YYv1163E3EF
'')rP   r   rU   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r!  )rL   r   first_token_tensorpooled_outputs       rO   r_   zErniePooler.forward  s6     +1a40

#566rP   r   ri   s   @rO   r  r    s#    $
U\\ ell rP   r  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )ErniePredictionHeadTransformc                 h   t         |           t        j                  |j                  |j                        | _        t        |j                  t              rt        |j                     | _
        n|j                  | _
        t        j                  |j                  |j                        | _        y r   )r0   r1   r   rv   r4   r   r   r   r   r   transform_act_fnr>   r?   rK   s     rO   r1   z%ErniePredictionHeadTransform.__init__   s{    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D!f&8&8f>S>STrP   r   rU   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r(  r>   r   s     rO   r_   z$ErniePredictionHeadTransform.forward)  s4    

=1--m<}5rP   r   ri   s   @rO   r&  r&    s$    UU\\ ell rP   r&  c                   *     e Zd Z fdZd Zd Z xZS )ErnieLMPredictionHeadc                 H   t         |           t        |      | _        t	        j
                  |j                  |j                  d      | _        t	        j                  t        j                  |j                              | _        | j                  | j                  _        y )NF)bias)r0   r1   r&  	transformr   rv   r4   r3   decoder	ParameterrE   rH   r-  rK   s     rO   r1   zErnieLMPredictionHead.__init__2  sm    5f= yy!3!3V5F5FUSLLV->->!?@	 !IIrP   c                 :    | j                   | j                  _         y r   )r-  r/  rL   s    rO   _tie_weightsz"ErnieLMPredictionHead._tie_weights?  s     IIrP   c                 J    | j                  |      }| j                  |      }|S r   )r.  r/  r   s     rO   r_   zErnieLMPredictionHead.forwardB  s$    }5]3rP   )r`   ra   rb   r1   r3  r_   rh   ri   s   @rO   r+  r+  1  s    &&rP   r+  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )ErnieOnlyMLMHeadc                 B    t         |           t        |      | _        y r   )r0   r1   r+  predictionsrK   s     rO   r1   zErnieOnlyMLMHead.__init__J  s    08rP   sequence_outputrU   c                 (    | j                  |      }|S r   )r8  )rL   r9  prediction_scoress      rO   r_   zErnieOnlyMLMHead.forwardN  s     ,,_=  rP   r   ri   s   @rO   r6  r6  I  s#    9!u|| ! !rP   r6  c                   $     e Zd Z fdZd Z xZS )ErnieOnlyNSPHeadc                 l    t         |           t        j                  |j                  d      | _        y Nrq   )r0   r1   r   rv   r4   seq_relationshiprK   s     rO   r1   zErnieOnlyNSPHead.__init__U  s'     "		&*<*<a @rP   c                 (    | j                  |      }|S r   )r@  )rL   r$  seq_relationship_scores      rO   r_   zErnieOnlyNSPHead.forwardY  s    !%!6!6}!E%%rP   r`   ra   rb   r1   r_   rh   ri   s   @rO   r=  r=  T  s    A&rP   r=  c                   $     e Zd Z fdZd Z xZS )ErniePreTrainingHeadsc                     t         |           t        |      | _        t	        j
                  |j                  d      | _        y r?  )r0   r1   r+  r8  r   rv   r4   r@  rK   s     rO   r1   zErniePreTrainingHeads.__init__`  s4    08 "		&*<*<a @rP   c                 N    | j                  |      }| j                  |      }||fS r   )r8  r@  )rL   r9  r$  r;  rB  s        rO   r_   zErniePreTrainingHeads.forwarde  s0     ,,_=!%!6!6}!E "888rP   rC  ri   s   @rO   rE  rE  _  s    A
9rP   rE  c                   &    e Zd ZU eed<   dZdZd Zy)ErniePreTrainedModelrM   ernieTc                    t        |t        j                        rm|j                  j                  j                  d| j                  j                         |j                  %|j                  j                  j                          yyt        |t        j                        rz|j                  j                  j                  d| j                  j                         |j                  2|j                  j                  |j                     j                          yyt        |t        j                        rJ|j                  j                  j                          |j                  j                  j                  d       yy)zInitialize the weightsg        )meanstdNg      ?)r   r   rv   weightdatanormal_rM   initializer_ranger-  zero_r2   r%   r>   fill_)rL   modules     rO   _init_weightsz"ErniePreTrainedModel._init_weightsq  s   fbii( MM&&CT[[5R5R&S{{&  &&( '-MM&&CT[[5R5R&S!!-""6#5#56<<> .-KK""$MM$$S) .rP   N)r`   ra   rb   r!   __annotations__base_model_prefixsupports_gradient_checkpointingrU  r  rP   rO   rI  rI  k  s    &*#*rP   rI  z1
    Output type of [`ErnieForPreTraining`].
    )custom_introc                       e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeeej                        ed<   dZeeej                        ed<   y)ErnieForPreTrainingOutputa  
    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).
    Nlossprediction_logitsseq_relationship_logitsr   r  )r`   ra   rb   rc   r\  r   rE   re   rV  r]  r^  r   r   r  r  rP   rO   r[  r[    s~    	 )-D(5$$
%,59x 1 129;?Xe&7&78?8<M8E%"3"345<59Ju00129rP   r[  a  
    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://huggingface.co/papers/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
    c            "           e Zd Zd fd	Zd Zd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     dee	j                     d	ee	j                     d
ee	j                     dee	j                     dee	j                     dee	j                     deee	j                        dee   dee   dee   dee   deee	j                     ef   fd       Z xZS )
ErnieModelc                     t         |   |       || _        t        |      | _        t        |      | _        |rt        |      nd| _        | j                          y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)
r0   r1   rM   r#   r^   r   encoderr  pooler	post_init)rL   rM   add_pooling_layerrN   s      rO   r1   zErnieModel.__init__  sM    
 	 )&1#F+->k&)D 	rP   c                 .    | j                   j                  S r   r^   r6   r2  s    rO   get_input_embeddingszErnieModel.get_input_embeddings  s    ...rP   c                 &    || j                   _        y r   rg  )rL   ry   s     rO   set_input_embeddingszErnieModel.set_input_embeddings  s    */'rP   c                     |j                         D ]7  \  }}| j                  j                  |   j                  j	                  |       9 y)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)itemsrb  r   r   r   )rL   heads_to_pruner   r   s       rO   _prune_headszErnieModel._prune_heads  sE    
 +002 	CLE5LLu%//;;EB	CrP   rQ   r   r-   rR   r*   r   rS   r   r   r  r  r   r  r  rU   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j                   j                  r||n| j                   j
                  }nd}||t        d      |#| j                  ||       |j                         }n!||j                         dd }nt        d      |\  }}||j                  n|j                  }d}|
5t        |
t              s|
d   d   j                  d   n|
j                         }|t        j                  |||z   f|      }|pt!        | j"                  d	      r4| j"                  j$                  ddd|f   }|j'                  ||      }|}n&t        j(                  |t        j*                  |
      }| j-                  ||      }| j                   j                  rE|C|j                         \  }}}||f}|	t        j                  ||      }	| j/                  |	      }nd}| j1                  || j                   j2                        }| j#                  ||||||      }| j5                  ||||||
||||
      }|d   }| j6                  | j7                  |      nd}|s
||f|dd z   S t9        |||j:                  |j<                  |j>                  |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]
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer+   z5You have to specify either input_ids or inputs_embedsr   r   )rX   r-   rW   )rQ   r*   r-   rR   rS   rT   )	r   r   r   r   r  r  r   r  r  r    )r  pooler_outputr  r   r  r  )!rM   r   r  use_return_dictr|   r  rs   %warn_if_padding_and_no_attention_maskrI   rX   r   r   r   get_seq_lengthrE   onesrY   r^   r-   rG   rH   rJ   get_extended_attention_maskinvert_attention_maskget_head_maskr   rb  rc  r   r  r   r  r  ) rL   rQ   r   r-   rR   r*   r   rS   r   r   r  r  r   r  r  rZ   r   r[   rX   rT   r\   r]   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputsr9  r$  s                                    rO   r_   zErnieModel.forward  s4   2 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B];;!!%.%:	@U@UII ]%>cdd"66y.Q#..*K&',,.s3KTUU!,
J%.%:!!@T@T!"& "/59  "1%++B/$335 # !"ZZ*jCY6Y)ZdjkN!t(89*.//*H*HKZK*X'3J3Q3QR\^h3i0!A!&[

SY!Z 150P0PQ_al0m ;;!!&;&G=R=W=W=Y: 7$68O#P %-).4HQW)X&.2.H.HI_.`+.2+ &&y$++2O2OP	??%)''#9 + 
 ,,2"7#B+/!5# ' 
 *!,8<8OO4UY#]3oab6III;-'+;;)77&11,==
 	
rP   )T)NNNNNNNNNNNNNN)r`   ra   rb   r1   rh  rj  rn  r   r   rE   rg   listre   r   r   r   r   r_   rh   ri   s   @rO   r`  r`    s   "/0C  -1151504/3,0048<9==A$(,0/3&*z
ELL)z
 !.z
 !.	z

  -z
 u||,z
 ELL)z
  -z
  (5z
 !) 6z
 "$u'8'8"9:z
 D>z
 $D>z
 'tnz
 d^z
  
uU\\"$PP	Q!z
 z
rP   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                       e Zd ZddgZ fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     d	ee	j                     d
ee	j                     dee	j                     dee	j                     dee	j                     dee	j                     dee   dee   dee   deee	j                     ef   fd       Z xZS )ErnieForPreTrainingcls.predictions.decoder.biascls.predictions.decoder.weightc                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )r0   r1   r`  rJ  rE  clsrd  rK   s     rO   r1   zErnieForPreTraining.__init__R  s4     '
(0 	rP   c                 B    | j                   j                  j                  S r   r  r8  r/  r2  s    rO   get_output_embeddingsz)ErnieForPreTraining.get_output_embeddings\      xx##+++rP   c                     || j                   j                  _        |j                  | j                   j                  _        y r   r  r8  r/  r-  rL   new_embeddingss     rO   set_output_embeddingsz)ErnieForPreTraining.set_output_embeddings`  ,    '5$$2$7$7!rP   rQ   r   r-   rR   r*   r   rS   labelsnext_sentence_labelr   r  r  rU   c                    ||n| j                   j                  }| j                  ||||||||
||
      }|dd \  }}| j                  ||      \  }}d}|u|	st	               } ||j                  d| j                   j                        |j                  d            } ||j                  dd      |	j                  d            }||z   }|s||f|dd z   }||f|z   S |S 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
        ```
        N	r   r-   rR   r*   r   rS   r   r  r  rq   r+   )r\  r]  r^  r   r  )
rM   rr  rJ  r  r   r   r3   r[  r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r  r   r  r  r   r9  r$  r;  rB  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   s                          rO   r_   zErnieForPreTraining.forwardd  sJ   b &1%<k$++B]B]**))'%'/!5#  
 *1!&48HH_m4\11
"5"A')H%&7&<&<RAWAW&XZ`ZeZefhZijN!)*@*E*Eb!*LNaNfNfgiNj!k'*<<J')?@712;NF/9/EZMF*Q6Q(/$:!//))
 	
rP   NNNNNNNNNNNN)r`   ra   rb   _tied_weights_keysr1   r  r  r   r   rE   rg   r   r   r   r[  r_   rh   ri   s   @rO   r  r  H  sZ    9:Z[,8  -1151504/3,004)-6:,0/3&*S
ELL)S
 !.S
 !.	S

  -S
 u||,S
 ELL)S
  -S
 &S
 &ell3S
 $D>S
 'tnS
 d^S
 
uU\\"$==	>S
 S
rP   r  zQ
    Ernie Model with a `language modeling` head on top for CLM fine-tuning.
    c            $           e Zd ZddgZ fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     d	ee	j                     d
ee	j                     dee	j                     dee	j                     dee	j                     dee	j                     dee	j                     deee	j                        dee   dee   dee   dee   deee	j                     ef   f d       Z xZS )ErnieForCausalLMr  r  c                     t         |   |       |j                  st        j	                  d       t        |d      | _        t        |      | _        | j                          y )NzMIf you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`Fre  
r0   r1   r|   r  warningr`  rJ  r6  r  rd  rK   s     rO   r1   zErnieForCausalLM.__init__  sL       NNjk%@
#F+ 	rP   c                 B    | j                   j                  j                  S r   r  r2  s    rO   r  z&ErnieForCausalLM.get_output_embeddings  r  rP   c                     || j                   j                  _        |j                  | j                   j                  _        y r   r  r  s     rO   r  z&ErnieForCausalLM.set_output_embeddings  r  rP   rQ   r   r-   rR   r*   r   rS   r   r   r  r  r  r   r  r  rU   c                    ||n| j                   j                  }|
d}| j                  |||||||||	|||||      }|d   }| j                  |      }d}|
* | j                  ||
fd| j                   j
                  i|}|s|f|dd z   }||f|z   S |S 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]`
        NF)r   r-   rR   r*   r   rS   r   r   r  r  r   r  r  r   r3   rq   )r\  logitsr  r   r  r  )rM   rr  rJ  r  loss_functionr3   r   r  r   r  r  )rL   rQ   r   r-   rR   r*   r   rS   r   r   r  r  r  r   r  r  kwargsr   r9  r;  lm_lossr   s                         rO   r_   zErnieForCausalLM.forward  s#   > &1%<k$++B]B]I**))'%'"7#9+/!5#  
" "!* HH_5(d((!  ;;11 	G ')GABK7F,3,?WJ'KVK0$#33!//))$55
 	
rP   )NNNNNNNNNNNNNNN)r`   ra   rb   r  r1   r  r  r   r   rE   rg   r  r   r   r   r   r_   rh   ri   s   @rO   r  r    s    9:Z[
,8  -1151504/3,0048<9=)-8<$(,0/3&*!J
ELL)J
 !.J
 !.	J

  -J
 u||,J
 ELL)J
  -J
  (5J
 !) 6J
 &J
 "$u||"45J
 D>J
 $D>J
 'tnJ
  d^!J
$ 
uU\\"$EE	F%J
 J
rP   r  c                        e Zd ZddgZ fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     d	ee	j                     d
ee	j                     dee	j                     dee	j                     dee	j                     dee	j                     dee	j                     dee   dee   dee   deee	j                     ef   fd       ZddZedefd       Z xZS )ErnieForMaskedLMr  r  c                     t         |   |       |j                  rt        j	                  d       t        |d      | _        t        |      | _        | j                          y )NzlIf you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr  r  rK   s     rO   r1   zErnieForMaskedLM.__init__,  sR     NN1
  %@
#F+ 	rP   c                 B    | j                   j                  j                  S r   r  r2  s    rO   r  z&ErnieForMaskedLM.get_output_embeddings<  r  rP   c                     || j                   j                  _        |j                  | j                   j                  _        y r   r  r  s     rO   r  z&ErnieForMaskedLM.set_output_embeddings@  r  rP   rQ   r   r-   rR   r*   r   rS   r   r   r  r   r  r  rU   c                    ||n| j                   j                  }| j                  |||||||||	|||      }|d   }| j                  |      }d}|
Ft	               } ||j                  d| j                   j                        |
j                  d            }|s|f|dd z   }||f|z   S |S 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]`
        N)r   r-   rR   r*   r   rS   r   r   r   r  r  r   r+   rq   r\  r  r   r  )
rM   rr  rJ  r  r   r   r3   r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r   r   r  r   r  r  r   r9  r;  r  r  r   s                       rO   r_   zErnieForMaskedLM.forwardD  s   : &1%<k$++B]B]**))'%'"7#9/!5#  
 "!* HH_5')H%&7&<&<RAWAW&XZ`ZeZefhZijN')GABK7F3A3M^%.YSYY$!//))	
 	
rP   c                    |j                   }|d   }| j                  j                  t        d      t	        j
                  ||j                  |j                   d   df      gd      }t	        j                  |df| j                  j                  t        j                  |j                        }t	        j
                  ||gd      }||dS )Nr   z.The PAD token should be defined for generationr    r+   r   rW   )rQ   r   )
r   rM   r5   rs   rE   cat	new_zerosfullrJ   rX   )rL   rQ   r   model_kwargsrZ   effective_batch_sizedummy_tokens          rO   prepare_inputs_for_generationz.ErnieForMaskedLM.prepare_inputs_for_generation  s    oo*1~ ;;##+MNNNN4L4LnNbNbcdNeghMi4j#kqstjj!1%t{{'?'?uzzZcZjZj
 IIy+6A>	&.IIrP   c                      y)z
        Legacy correction: ErnieForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
        `prepare_inputs_for_generation` method.
        Fr  )r  s    rO   can_generatezErnieForMaskedLM.can_generate  s     rP   )NNNNNNNNNNNNNr   )r`   ra   rb   r  r1   r  r  r   r   rE   rg   r   r   r   r   r_   r  classmethodr  rh   ri   s   @rO   r  r  '  s   8:Z[ ,8  -1151504/3,0048<9=)-,0/3&*>
ELL)>
 !.>
 !.	>

  ->
 u||,>
 ELL)>
  ->
  (5>
 !) 6>
 &>
 $D>>
 'tn>
 d^>
 
uU\\"N2	3>
 >
BJ  T  rP   r  zU
    Ernie Model with a `next sentence prediction (classification)` head on top.
    c                   ~    e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
ee   dee   dee   de	e
ej                     ef   fd       Z xZS )ErnieForNextSentencePredictionc                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )r0   r1   r`  rJ  r=  r  rd  rK   s     rO   r1   z'ErnieForNextSentencePrediction.__init__  s4     '
#F+ 	rP   rQ   r   r-   rR   r*   r   rS   r  r   r  r  rU   c                    d|v r+t        j                  dt               |j                  d      }||n| j                  j
                  }| j                  ||||||||	|
|
      }|d   }| j                  |      }d}|2t               } ||j                  dd      |j                  d            }|s|f|dd z   }||f|z   S |S 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
        ```
        r  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.Nr  r    r+   rq   r  )warningswarnFutureWarningpoprM   rr  rJ  r  r   r   r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r   r  r  r  r   r$  seq_relationship_scoresr  r  r   s                      rO   r_   z&ErnieForNextSentencePrediction.forward  s    ` !F*MM%
 ZZ 56F%0%<k$++B]B]**))'%'/!5#  
  
"&((="9!')H!)*A*F*Fr1*Mv{{[]!_-/'!"+=F7I7U')F2a[aa*#*!//))	
 	
rP   NNNNNNNNNNN)r`   ra   rb   r1   r   r   rE   rg   r   r   r   r   r_   rh   ri   s   @rO   r  r    s+     -1151504/3,004)-,0/3&*X
ELL)X
 !.X
 !.	X

  -X
 u||,X
 ELL)X
  -X
 &X
 $D>X
 'tnX
 d^X
 
uU\\"$??	@X
 X
rP   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                   ~    e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
ee   dee   dee   de	e
ej                     ef   fd       Z xZS )ErnieForSequenceClassificationc                 n   t         |   |       |j                  | _        || _        t	        |      | _        |j                  |j                  n|j                  }t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y r   )r0   r1   
num_labelsrM   r`  rJ  classifier_dropoutrA   r   r@   rB   rv   r4   
classifierrd  rL   rM   r  rN   s      rO   r1   z'ErnieForSequenceClassification.__init__  s      ++'
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rP   rQ   r   r-   rR   r*   r   rS   r  r   r  r  rU   c                 B   ||n| j                   j                  }| j                  ||||||||	|
|
      }|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               } |||      }|s|f|dd z   }||f|z   S |S 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).
        Nr  r    
regressionsingle_label_classificationmulti_label_classificationr+   rq   r  )rM   rr  rJ  rB   r  problem_typer  r/   rE   rJ   rf   r	   squeezer   r   r   r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r   r  r  r   r$  r  r\  r  r   s                     rO   r_   z&ErnieForSequenceClassification.forward"  s   4 &1%<k$++B]B]**))'%'/!5#  
  
]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,./Y,F)-)9TGf$EvE'!//))	
 	
rP   r  )r`   ra   rb   r1   r   r   rE   rg   r   r   r   r   r_   rh   ri   s   @rO   r  r    s+     -1151504/3,004)-,0/3&*L
ELL)L
 !.L
 !.	L

  -L
 u||,L
 ELL)L
  -L
 &L
 $D>L
 'tnL
 d^L
 
uU\\"$<<	=L
 L
rP   r  c                   ~    e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
ee   dee   dee   de	e
ej                     ef   fd       Z xZS )ErnieForMultipleChoicec                 *   t         |   |       t        |      | _        |j                  |j                  n|j
                  }t        j                  |      | _        t        j                  |j                  d      | _        | j                          y )Nr    )r0   r1   r`  rJ  r  rA   r   r@   rB   rv   r4   r  rd  r  s      rO   r1   zErnieForMultipleChoice.__init__u  su     '
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$6: 	rP   rQ   r   r-   rR   r*   r   rS   r  r   r  r  rU   c                 N   ||n| j                   j                  }||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                  ||||||||	|
|
      }|d   }| j                  |      }| j                  |      }|j                  d|      }d}|t               } |||      }|s|f|dd z   }||f|z   S |S 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    r+   r   r  rq   r  )rM   rr  r   r   rI   rJ  rB   r  r   r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r   r  r  num_choicesr   r$  r  reshaped_logitsr\  r  r   s                       rO   r_   zErnieForMultipleChoice.forward  s   d &1%<k$++B]B],5,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 	 **))'%'/!5#  
  
]3/ ++b+6')HOV4D%''!"+5F)-)9TGf$EvE("!//))	
 	
rP   r  )r`   ra   rb   r1   r   r   rE   rg   r   r   r   r   r_   rh   ri   s   @rO   r  r  r  s+     -1151504/3,004)-,0/3&*_
ELL)_
 !._
 !.	_

  -_
 u||,_
 ELL)_
  -_
 &_
 $D>_
 'tn_
 d^_
 
uU\\"$==	>_
 _
rP   r  c                   ~    e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
ee   dee   dee   de	e
ej                     ef   fd       Z xZS )ErnieForTokenClassificationc                 d   t         |   |       |j                  | _        t        |d      | _        |j
                  |j
                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        | j                          y NFr  )r0   r1   r  r`  rJ  r  rA   r   r@   rB   rv   r4   r  rd  r  s      rO   r1   z$ErnieForTokenClassification.__init__  s      ++%@
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rP   rQ   r   r-   rR   r*   r   rS   r  r   r  r  rU   c                    ||n| j                   j                  }| j                  ||||||||	|
|
      }|d   }| j                  |      }| j	                  |      }d}|<t               } ||j                  d| j                        |j                  d            }|s|f|dd z   }||f|z   S |S 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]`.
        Nr  r   r+   rq   r  )rM   rr  rJ  rB   r  r   r   r  r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r   r  r  r   r9  r  r\  r  r   s                     rO   r_   z#ErnieForTokenClassification.forward  s    0 &1%<k$++B]B]**))'%'/!5#  
 "!*,,71')HFKKDOO<fkk"oNDY,F)-)9TGf$EvE$!//))	
 	
rP   r  )r`   ra   rb   r1   r   r   rE   rg   r   r   r   r   r_   rh   ri   s   @rO   r  r    s     -1151504/3,004)-,0/3&*9
ELL)9
 !.9
 !.	9

  -9
 u||,9
 ELL)9
  -9
 &9
 $D>9
 'tn9
 d^9
 
uU\\"$99	:9
 9
rP   r  c                       e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   de	e
ej                     ef   fd       Z xZS )ErnieForQuestionAnsweringc                     t         |   |       |j                  | _        t        |d      | _        t        j                  |j                  |j                        | _        | j                          y r  )
r0   r1   r  r`  rJ  r   rv   r4   
qa_outputsrd  rK   s     rO   r1   z"ErnieForQuestionAnswering.__init__6  sU      ++%@
))F$6$68I8IJ 	rP   rQ   r   r-   rR   r*   r   rS   start_positionsend_positionsr   r  r  rU   c                 *   ||n| j                   j                  }| j                  ||||||||
||
      }|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  }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                  	      S )
rp  Nr  r   r    r+   r   )ignore_indexrq   )r\  start_logits
end_logitsr   r  )rM   rr  rJ  r  splitr  r   r   rI   clampr   r   r   r  )rL   rQ   r   r-   rR   r*   r   rS   r  r  r   r  r  r   r9  r  r  r  r  ignored_indexr  
start_lossend_lossr   s                           rO   r_   z!ErnieForQuestionAnswering.forward@  s   . &1%<k$++B]B]**))'%'/!5#  
 "!*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"J/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
rP   r  )r`   ra   rb   r1   r   r   rE   rg   r   r   r   r   r_   rh   ri   s   @rO   r  r  3  sB     -1151504/3,0042604,0/3&*G
ELL)G
 !.G
 !.	G

  -G
 u||,G
 ELL)G
  -G
 "%,,/G
  -G
 $D>G
 'tnG
 d^G
 
uU\\"$@@	AG
 G
rP   r  )
r  r  r  r  r  r  r  r  r`  rI  )Mrc   r   r  dataclassesr   typingr   r   rE   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   cache_utilsr   r   
generationr   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   r   configuration_ernier!   
get_loggerr`   r  Moduler#   rk   r   r   r   r   r   r   r   r  r&  r+  r6  r=  rE  rI  r[  r`  r  r  r  r  r  r  r  r  __all__r  rP   rO   <module>r     s      ! "    A A ! 5 ) 9
 
 
 . l l 9 9 , 
		H	%Ibii IZ@. @.Hbii    2RYY 2l		  ")) A+ AJY
299 Y
z"))  299 $BII 0!ryy !&ryy &	9BII 	9 *? * *, : : :& 
^
% ^

^
B j
. j
j
Z 
d
+_ d

d
N t+ t tn 
d
%9 d

d
N ^
%9 ^
^
B o
1 o
 o
d J
"6 J
 J
Z T
 4 T
 T
nrP   