
    qi_                        d dl mZ d dlm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 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mZmZmZmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6  e/jn                  e8      Z9 G d dejt                        Z;	 	 dZdejt                  dejx                  dejx                  dejx                  dejx                  dz  de=dz  de=de(e-   fdZ> G d  d!ejt                        Z? G d" d#ejt                        Z@ G d$ d%ejt                        ZA G d& d'ejt                        ZB G d( d)ejt                        ZC G d* d+ejt                        ZD G d, d-e      ZE G d. d/ejt                        ZF G d0 d1ejt                        ZG G d2 d3ejt                        ZH G d4 d5ejt                        ZIe. G d6 d7e&             ZJ e.d89       G d: d;eJ             ZKe e.d<9       G d= d>e,                    ZL G d? d@ejt                        ZM e.dA9       G dB dCeJ             ZN G dD dEejt                        ZO e.dF9       G dG dHeJe             ZPe. G dI dJeJ             ZQ G dK dLejt                        ZR e.dM9       G dN dOeJ             ZS e.dP9       G dQ dReJ             ZTe. G dS dTeJ             ZUe. G dU dVeJ             ZVe. G dW dXeJ             ZWg dYZXy)[    )Callable)	dataclassN)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)GradientCheckpointingLayer)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward)ModelOutputTransformersKwargsauto_docstringlogging)can_return_tuplemerge_with_config_defaults)capture_outputs   )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         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        | j#                  dt%        j&                  |j                        j)                  d      d       | j#                  dt%        j*                  | j,                  j/                         t$        j0                        d       |j2                  | _        |j2                  r0t        j                  |j4                  |j
                        | _        y y )	N)padding_idxepsposition_idsr&   F)
persistenttoken_type_ids)dtype)super__init__nn	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandzerosr.   sizelonguse_task_idtask_type_vocab_sizetask_type_embeddingsselfconfig	__class__s     Z/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/ernie/modeling_ernie.pyr5   zErnieEmbeddings.__init__<   sX   !||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c %'\\&2H2H&J\J\%]"f&8&8f>S>STzz&"<"<=ELL)G)GHOOPWXej 	 	
 	ekk$*;*;*@*@*B%**Ubg 	 	
 "--(*V5P5PRXRdRd(eD%     N	input_idsr2   task_type_idsr.   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 )Nr0   r2   r   r&   )dimindex)r3   device)rJ   r.   hasattrr2   rH   shaperF   gatherrI   rK   r]   r;   r?   tor=   rL   rN   r@   rD   )rP   rU   r2   rV   r.   rW   rX   input_shape
batch_size
seq_lengthbuffered_token_type_idsr?   
embeddingsr=   rN   s                  rS   forwardzErnieEmbeddings.forwardP   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/
\\*-
rT   )NNNNNr   )__name__
__module____qualname____doc__r5   rF   
LongTensorFloatTensorintTensorrg   __classcell__rR   s   @rS   r)   r)   9   s    Qf, .226150426&'3##d*3 ((4/3 ''$.	3
 &&-3 ((4/3 !$3 
3rT   r)   modulequerykeyvalueattention_maskscalingrD   kwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr0            r   r[   )ptrainingr&   )
rJ   rF   matmul	transposer6   
functionalsoftmaxrD   r~   
contiguous)
rr   rs   rt   ru   rv   rw   rD   rx   attn_weightsattn_outputs
             rS   eager_attention_forwardr      s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$rT   c                        e Zd Zd
 fd	Z	 	 	 ddej
                  dej                  dz  dedz  dej
                  dz  dee	   de
ej
                     fd	Z xZS )ErnieSelfAttentionNc                 @   t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        | j                  dz  | _
        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                   |j"                        | _        |j&                  | _        || _        || _        y Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()rz   )r4   r5   r9   num_attention_headsr^   
ValueErrorrQ   rn   attention_head_sizeall_head_sizerw   r6   Linearrs   rt   ru   rB   attention_probs_dropout_probrD   
is_decoder	is_causal	layer_idxrP   rQ   r   r   rR   s       rS   r5   zErnieSelfAttention.__init__   sP    : ::a?PVXhHi#F$6$6#7 8 445Q8  #)#=#= #&v'9'9F<V<V'V#W !558P8PP//5YYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF ++""rT   hidden_statesrv   past_key_valuescache_positionrx   rY   c                    |j                   d d }g |d| j                  } | j                  |      j                  | j	                  dd      } | j                  |      j                  | j	                  dd      }	 | j                  |      j                  | j	                  dd      }
|A|}t        |t              r|j                  }|j                  |	|
| j                  d|i      \  }	}
t        j                  | j                  j                  t               } || ||	|
|f| j"                  sdn| j$                  j&                  | j(                  d|\  }} |j*                  g |d j-                         }||fS )Nr0   r&   r{   r           rD   rw   )r_   r   rs   viewr   rt   ru   
isinstancer   self_attention_cacheupdater   r   get_interfacerQ   _attn_implementationr   r~   rD   r}   rw   reshaper   )rP   r   rv   r   r   rx   rb   hidden_shapequery_layer	key_layervalue_layercurrent_past_key_valuesattention_interfacer   r   s                  rS   rg   zErnieSelfAttention.forward   s    $))#2.CCbC$*B*BC 5djj/44lCMMaQRS0DHH]+00,?II!QO	4djj/44lCMMaQRS&&5#/+>?*9*N*N' &=%C%C!>2	&"I{ )@(M(MKK,,.E)
 %8	%
  $}}C$,,..LL	%
 	%
!\ *k));;;;FFHL((rT   FNNNNrh   ri   rj   r5   rF   ro   rm   r   r   r    tuplerg   rp   rq   s   @rS   r   r      s}    #6 48(,.2-)||-) ))D0-) 	-)
 t+-) +,-) 
u||	-)rT   r   c                        e Zd Zd
 fd	Z	 	 	 ddej
                  dej                  dz  dej                  dz  dedz  dee	   de
ej
                     fd	Z xZS )ErnieCrossAttentionNc                    t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        | j                  dz  | _
        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                   |j"                        | _        || _        || _        y r   )r4   r5   r9   r   r^   r   rQ   rn   r   r   rw   r6   r   rs   rt   ru   rB   r   rD   r   r   r   s       rS   r5   zErnieCrossAttention.__init__   sC    : ::a?PVXhHi#F$6$6#7 8 445Q8  #)#=#= #&v'9'9F<V<V'V#W !558P8PP//5YYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF""rT   r   encoder_hidden_statesrv   r   rx   rY   c                 V   |j                   d d \  }}|j                   d   }||d| j                  f}	||d| j                  f}
 | j                  |      j                  |	 j	                  dd      }|%|j
                  j                  | j                        nd}|]|r[|j                  j                  | j                     j                  }|j                  j                  | j                     j                  }n | j                  |      j                  |
 j	                  dd      } | j                  |      j                  |
 j	                  dd      }|C|j                  j                  ||| j                        \  }}d|j
                  | j                  <   t        j                   | j"                  j$                  t&              } || ||||f| j(                  sdn| j*                  j,                  | j.                  d|\  }}|j1                  ||d      j3                         }||fS )Nr0   r&   r{   FTr   r   )r_   r   rs   r   r   
is_updatedgetr   cross_attention_cachelayerskeysvaluesrt   ru   r   r   r   rQ   r   r   r~   rD   r}   rw   r   r   )rP   r   r   rv   r   rx   bsztgt_lensrc_lenq_input_shapekv_input_shaper   r   r   r   r   r   r   s                     rS   rg   zErnieCrossAttention.forward  s    %**3B/W'--a0gr4+C+CDwD,D,DE 5djj/44mDNNqRSTGVGb_//33DNNChm
&:'==DDT^^TYYI)??FFt~~V]]K<!67<<nMWWXY[\]I@$**%:;@@.Q[[\]_`aK*)8)N)N)U)U{DNN*&	; >B**4>>:(?(M(MKK,,.E)
 %8	%
  $}}C$,,..LL	%
 	%
!\ "))#w;FFHL((rT   r   r   )rh   ri   rj   r5   rF   ro   rm   r   r   r    r   rg   rp   rq   s   @rS   r   r      s    #4 ;?376:2)||2)  %00472) ))D0	2)
 -t32) +,2) 
u||	2)rT   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 )ErnieSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr,   )r4   r5   r6   r   r9   denser@   rA   rB   rC   rD   rO   s     rS   r5   zErnieSelfOutput.__init__9  s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rT   r   input_tensorrY   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S Nr   rD   r@   rP   r   r   s      rS   rg   zErnieSelfOutput.forward?  7    

=1]3}|'CDrT   rh   ri   rj   r5   rF   ro   rg   rp   rq   s   @rS   r   r   8  1    >U\\  RWR^R^ rT   r   c                        e Zd Zd fd	Z	 	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dej
                  dz  d	ee	   d
e
ej
                     fdZ xZS )ErnieAttentionNc                     t         |           || _        |rt        nt        } ||||      | _        t        |      | _        y )Nr   r   )r4   r5   is_cross_attentionr   r   rP   r   output)rP   rQ   r   r   r   attention_classrR   s         rS   r5   zErnieAttention.__init__G  s=    "41C-I[#Fi9U	%f-rT   r   rv   r   encoder_attention_maskr   r   rx   rY   c                     | j                   s|n|} | j                  |f||||d|\  }}	| j                  ||      }||	fS )N)r   rv   r   r   )r   rP   r   )
rP   r   rv   r   r   r   r   rx   attention_outputr   s
             rS   rg   zErnieAttention.forwardN  sg     04/F/FLb)2*
"7)+)*
 *
&,  ;;'7G--rT   )FNFNNNNNr   rq   s   @rS   r   r   F  s    . 48:>;?(,.2.||. ))D0.  %0047	.
 !& 1 1D 8. . t+. +,. 
u||	.rT   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   )r4   r5   r6   r   r9   intermediate_sizer   r   
hidden_actstrr
   intermediate_act_fnrO   s     rS   r5   zErnieIntermediate.__init__f  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rT   r   rY   c                 J    | j                  |      }| j                  |      }|S r   )r   r   rP   r   s     rS   rg   zErnieIntermediate.forwardn  s&    

=100?rT   r   rq   s   @rS   r   r   e  s#    9U\\ ell rT   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   )r4   r5   r6   r   r   r9   r   r@   rA   rB   rC   rD   rO   s     rS   r5   zErnieOutput.__init__u  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rT   r   r   rY   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r   s      rS   rg   zErnieOutput.forward{  r   rT   r   rq   s   @rS   r   r   t  r   rT   r   c                        e Zd Zd fd	Z	 	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dej
                  dz  d	ee	   d
e
ej
                     fdZd Z xZS )
ErnieLayerNc                    t         |           |j                  | _        d| _        t	        ||j
                  |      | _        |j
                  | _        |j                  | _        | j                  r.| j
                  st        |  d      t	        |d|d      | _	        t        |      | _        t        |      | _        y )Nr&   r   z> should be used as a decoder model if cross attention is addedFT)r   r   r   )r4   r5   chunk_size_feed_forwardseq_len_dimr   r   	attentionadd_cross_attentionr   crossattentionr   intermediater   r   )rP   rQ   r   rR   s      rS   r5   zErnieLayer.__init__  s    '-'E'E$'&:K:KW`a ++#)#=#= ##?? D6)g!hii"0##'	#D .f5!&)rT   r   rv   r   r   r   r   rx   rY   c                 "    | j                   ||f||d|\  }}	|}
| j                  r:|8t        | d      st        d|  d       | j                  |d ||fd|i|\  }}	|}
t        | j                  | j                  | j                  |
      }|S )N)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   r^   r   r   r   feed_forward_chunkr   r   )rP   r   rv   r   r   r   r   rx   self_attention_output_r   cross_attention_outputlayer_outputs                rS   rg   zErnieLayer.forward  s     $24>>$
 ,)	$

 $
 q 1??4@4!12 =dV DD D 
 )<(;(;%%&	)
 !0) )%"A  60##T%A%A4CSCSUe
 rT   c                 L    | j                  |      }| j                  ||      }|S r   )r   r   )rP   r   intermediate_outputr   s       rS   r   zErnieLayer.feed_forward_chunk  s,    "//0@A{{#68HIrT   r   r   )rh   ri   rj   r5   rF   ro   rm   r   r   r    r   rg   r   rp   rq   s   @rS   r   r     s    *, 48:>;?(,.2'||' ))D0'  %0047	'
 !& 1 1D 8' ' t+' +,' 
u||	'RrT   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   )r4   r5   r6   r   r9   r   Tanh
activationrO   s     rS   r5   zErniePooler.__init__  s9    YYv1163E3EF
'')rT   r   rY   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r   )rP   r   first_token_tensorpooled_outputs       rS   rg   zErniePooler.forward  s6     +1a40

#566rT   r   rq   s   @rS   r   r     s#    $
U\\ ell rT   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   )r4   r5   r6   r   r9   r   r   r   r   r
   transform_act_fnr@   rA   rO   s     rS   r5   z%ErniePredictionHeadTransform.__init__  s{    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D!f&8&8f>S>STrT   r   rY   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r@   r   s     rS   rg   z$ErniePredictionHeadTransform.forward  s4    

=1--m<}5rT   r   rq   s   @rS   r   r     s$    UU\\ ell rT   r   c                   $     e Zd Z fdZd Z xZS )ErnieLMPredictionHeadc                    t         |           t        |      | _        t	        j
                  |j                  |j                  d      | _        t	        j                  t        j                  |j                              | _        y )NT)bias)r4   r5   r   	transformr6   r   r9   r8   decoder	ParameterrF   rI   r  rO   s     rS   r5   zErnieLMPredictionHead.__init__  s[    5f= yy!3!3V5F5FTRLLV->->!?@	rT   c                 J    | j                  |      }| j                  |      }|S r   )r  r  r   s     rS   rg   zErnieLMPredictionHead.forward  s$    }5]3rT   rh   ri   rj   r5   rg   rp   rq   s   @rS   r  r    s    ArT   r  c                       e Zd Z fdZ	 	 	 	 	 	 ddej
                  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j
                  dz  d
e	e
   deej
                     ez  fdZ xZS )ErnieEncoderc           	          t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        y c c}w )N)r   )	r4   r5   rQ   r6   
ModuleListrangenum_hidden_layersr   layer)rP   rQ   irR   s      rS   r5   zErnieEncoder.__init__  sF    ]]USYSkSkMl#mJv$C#mn
#ms   ANr   rv   r   r   r   	use_cacher   rx   rY   c                     t        | j                        D ]  \  }	}
 |
|||f|||d|} t        ||r|      S d       S )N)r   r   r   )last_hidden_stater   )	enumerater  r   )rP   r   rv   r   r   r   r  r   rx   r  layer_modules              rS   rg   zErnieEncoder.forward  sq      )4 		OA|(% (> /- M		 9+/8O
 	
>B
 	
rT   )NNNNNN)rh   ri   rj   r5   rF   ro   rm   r   boolr   r    r   r   rg   rp   rq   s   @rS   r  r    s    o 48:>;?(,!%.2
||
 ))D0
  %0047	

 !& 1 1D 8
 
 $;
 t+
 +,
 
u||	H	H
rT   r  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)r   
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 weightsr0   r/   N)r4   _init_weightsr   r  initzeros_r  r)   copy_r.   rF   rG   r_   rH   r2   )rP   rr   rR   s     rS   r  z"ErniePreTrainedModel._init_weights&  s     	f%f34KK$0JJv**ELL9L9L9R9RSU9V,W,^,^_f,ghKK--. 1rT   )rh   ri   rj   r'   config_classbase_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   r   r   _can_record_outputsrF   no_gradr  rp   rq   s   @rS   r  r    sX    L&*#N"&#(/ U]]_/ /rT   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
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
    )custom_introc                       e Zd ZdgZd fd	Zd Z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
j                  dz  dee   dee
j                     ez  fd                     Zd Z xZS )
ErnieModelr   c                     t         |   |       || _        d| _        t	        |      | _        t        |      | _        |rt        |      nd| _	        | j                          y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        FN)r4   r5   rQ   gradient_checkpointingr)   rf   r  encoderr   pooler	post_init)rP   rQ   add_pooling_layerrR   s      rS   r5   zErnieModel.__init__@  sU    
 	 &+#)&1#F+->k&)D 	rT   c                 .    | j                   j                  S r   rf   r;   rP   s    rS   get_input_embeddingszErnieModel.get_input_embeddingsQ  s    ...rT   c                 &    || j                   _        y r   r5  )rP   ru   s     rS   set_input_embeddingszErnieModel.set_input_embeddingsT  s    */'rT   NrU   rv   r2   rV   r.   rW   r   r   r   r  r   rx   rY   c                    | j                   j                  r|
|
n| j                   j                  }
nd}
| j                  r%| j                  r|
rt
        j                  d       d}
|
rd|	b|| j                   j                  r4t        t        | j                         t        | j                               nt        | j                         }	||t        d      |#| j                  ||       |j                         }n!||j                         dd }nt        d      |\  }}||j                  n|j                  }|	|	j                         nd}|t        j                   |||z   |	      }| 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]
        NFzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...)rQ   zDYou cannot specify both input_ids and inputs_embeds at the same timer0   z5You have to specify either input_ids or inputs_embedsr   )r]   )rU   r.   r2   rV   rW   rX   )rv   r   embedding_outputr   r   r   )rv   r   r   r   r  r   r.   )r  pooler_outputr   )rQ   r   r  r/  r~   loggerwarning_onceis_encoder_decoderr   r   r   %warn_if_padding_and_no_attention_maskrJ   r]   get_seq_lengthrF   rG   rf   _create_attention_masksr0  r1  r   r   )rP   rU   rv   r2   rV   r.   rW   r   r   r   r  r   rx   rb   rc   rd   r]   rX   r<  encoder_outputssequence_outputr   s                         rS   rg   zErnieModel.forwardW  s1   2 ;;!!%.%:	@U@UII&&4==##p "	0 )48V8V $L$DlZ^ZeZeFfg!5   ]%>cdd"66y.Q#..*K&',,.s3KTUU!,
J%.%:!!@T@TETE`!?!?!Afg!"\\*@BX[eBentuN??%)''#9 + 
 261M1M)#9-"7)+ 2N 2
.. '$,,

)"7#9+)%

 

 *!,8<8OO4UY;-'+;;
 	
rT   c                     | j                   j                  rt        | j                   ||||      }nt        | j                   ||      }|t        | j                   |||      }||fS )N)rQ   rW   rv   r   r   )rQ   rW   rv   )rQ   rW   rv   r   )rQ   r   r   r   )rP   rv   r   r<  r   r   r   s          rS   rC  z"ErnieModel._create_attention_masks  sx     ;;!!/{{.-- /N 7{{.-N "-%>{{.5&;	&" 555rT   )T)NNNNNNNNNNN)rh   ri   rj   _no_split_modulesr5   r7  r9  r$   r%   r!   rF   ro   r   r  r   r    r   r   rg   rC  rp   rq   s   @rS   r-  r-  1  sf    &"/0   *..2.2-1,0-1596:(,!%.2_
<<$&_
 t+_
 t+	_

 ||d*_
 llT)_
 ||d*_
  %||d2_
 !&t 3_
 _
 $;_
 t+_
 +,_
 
u||	K	K_
    _
B 6rT   r-  z1
    Output type of [`ErnieForPreTraining`].
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
eej                     dz  ed<   dZeej                     dz  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  )rh   ri   rj   rk   rJ  rF   rm   __annotations__rK  rL  r   r   r   rT   rS   rI  rI    s~    	 &*D%

d
")26u((4/68<U..5<59M5**+d2926Je''(4/6rT   rI  c                   $     e Zd Z fdZd Z xZS )ErniePreTrainingHeadsc                     t         |           t        |      | _        t	        j
                  |j                  d      | _        y Nr{   )r4   r5   r  predictionsr6   r   r9   seq_relationshiprO   s     rS   r5   zErniePreTrainingHeads.__init__  s4    08 "		&*<*<a @rT   c                 N    | j                  |      }| j                  |      }||fS r   )rS  rT  )rP   rE  r   prediction_scoresseq_relationship_scores        rS   rg   zErniePreTrainingHeads.forward  s0     ,,_=!%!6!6}!E "888rT   r	  rq   s   @rS   rP  rP    s    A
9rT   rP  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dZ fdZd 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 xZS )ErnieForPreTrainingcls.predictions.bias'ernie.embeddings.word_embeddings.weightcls.predictions.decoder.biascls.predictions.decoder.weightc                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )r4   r5   r-  r  rP  clsr2  rO   s     rS   r5   zErnieForPreTraining.__init__  s4     '
(0 	rT   c                 B    | j                   j                  j                  S r   r`  rS  r  r6  s    rS   get_output_embeddingsz)ErnieForPreTraining.get_output_embeddings      xx##+++rT   c                     || j                   j                  _        |j                  | j                   j                  _        y r   r`  rS  r  r  rP   new_embeddingss     rS   set_output_embeddingsz)ErnieForPreTraining.set_output_embeddings  ,    '5$$2$7$7!rT   NrU   rv   r2   rV   r.   rW   labelsnext_sentence_labelrx   rY   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rv   r2   rV   r.   rW   return_dictNr{   r0   )rJ  rK  rL  r   r  )	r  r`  r   r   rQ   r8   rI  r   r  )rP   rU   rv   r2   rV   r.   rW   rk  rl  rx   outputsrE  r   rV  rW  
total_lossloss_fctmasked_lm_lossnext_sentence_losss                      rS   rg   zErnieForPreTraining.forward  s   ^ $**	
))'%'	
 	
 *1!&48HH_m4\11
"5"A')H%&7&<&<RAWAW&XZ`ZeZefhZijN!)*@*E*Eb!*LNaNfNfgiNj!k'*<<J(/$:!//))
 	
rT   NNNNNNNN)rh   ri   rj   _tied_weights_keysr5   rc  ri  r#   r!   rF   ro   r   r    r   rI  rg   rp   rq   s   @rS   rY  rY    s#    )?*S
,8  *..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
rT   rY  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   )r4   r5   r  rS  rO   s     rS   r5   zErnieOnlyMLMHead.__init__m  s    08rT   rE  rY   c                 (    | j                  |      }|S r   )rS  )rP   rE  rV  s      rS   rg   zErnieOnlyMLMHead.forwardq  s     ,,_=  rT   r   rq   s   @rS   rx  rx  l  s#    9!u|| ! !rT   rx  zQ
    Ernie Model with a `language modeling` head on top for CLM fine-tuning.
    c            "           e Zd ZdddZ fdZd 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	j                  dz  dee	j                  z  dee   dee	j                     ez  fd              Z xZS )ErnieForCausalLMr[  rZ  )r^  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r3  
r4   r5   r   r>  warningr-  r  rx  r`  r2  rO   s     rS   r5   zErnieForCausalLM.__init__  sL       NNjk%@
#F+ 	rT   c                 B    | j                   j                  j                  S r   rb  r6  s    rS   rc  z&ErnieForCausalLM.get_output_embeddings  rd  rT   c                     || j                   j                  _        |j                  | j                   j                  _        y r   rf  rg  s     rS   ri  z&ErnieForCausalLM.set_output_embeddings  rj  rT   NrU   rv   r2   rV   r.   rW   r   r   rk  r   r  r   logits_to_keeprx   rY   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)rv   r2   rV   r.   rW   r   r   r   r  r   ro  )logitsrk  r8   )rJ  r  r   r   r  r  rN  )r  r  r   rn   slicer`  loss_functionrQ   r8   r   r   r   r  r  )rP   rU   rv   r2   rV   r.   rW   r   r   rk  r   r  r   r  rx   rp  r   slice_indicesr  rJ  s                       rS   rg   zErnieForCausalLM.forward  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
 	
rT   )NNNNNNNNNNNNr   )rh   ri   rj   rv  r5   rc  ri  r#   r!   rF   ro   listr  rn   r   r    r   r   rg   rp   rq   s   @rS   r|  r|  v  s    +T(>

,8  *..2.2-1,0-1596:&*59!%.2-.?
<<$&?
 t+?
 t+	?

 ||d*?
 llT)?
 ||d*?
  %||d2?
 !&t 3?
 t#?
 ell+d2?
 $;?
 t+?
 ell*?
 +,?
  
u||	@	@!?
  ?
rT   r|  c                       e Zd ZdddZ fdZd 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   dee	j                     ez  fd              Z xZS )ErnieForMaskedLMrZ  r[  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  rO   s     rS   r5   zErnieForMaskedLM.__init__  sR     NN1
  %@
#F+ 	rT   c                 B    | j                   j                  j                  S r   rb  r6  s    rS   rc  z&ErnieForMaskedLM.get_output_embeddings  rd  rT   c                     || j                   j                  _        |j                  | j                   j                  _        y r   rf  rg  s     rS   ri  z&ErnieForMaskedLM.set_output_embeddings  rj  rT   NrU   rv   r2   rV   r.   rW   r   r   rk  rx   rY   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)rv   r2   rV   r.   rW   r   r   ro  r   Nr0   rJ  r  r   r  )	r  r`  r   r   rQ   r8   r   r   r  )rP   rU   rv   r2   rV   r.   rW   r   r   rk  rx   rp  rE  rV  rs  rr  s                   rS   rg   zErnieForMaskedLM.forward  s    4 $**
))'%'"7#9
 
 "!* HH_5')H%&7&<&<RAWAW&XZ`ZeZefhZijN$!//))	
 	
rT   )	NNNNNNNNN)rh   ri   rj   rv  r5   rc  ri  r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   r  r    s,    )?*S
,8  *..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
rT   r  c                   $     e Zd Z fdZd Z xZS )ErnieOnlyNSPHeadc                 l    t         |           t        j                  |j                  d      | _        y rR  )r4   r5   r6   r   r9   rT  rO   s     rS   r5   zErnieOnlyNSPHead.__init__-  s'     "		&*<*<a @rT   c                 (    | j                  |      }|S r   )rT  )rP   r   rW  s      rS   rg   zErnieOnlyNSPHead.forward1  s    !%!6!6}!E%%rT   r	  rq   s   @rS   r  r  ,  s    A&rT   r  zU
    Ernie Model with a `next sentence prediction (classification)` head on top.
    c                   J    e Zd Z f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 xZS )ErnieForNextSentencePredictionc                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )r4   r5   r-  r  r  r`  r2  rO   s     rS   r5   z'ErnieForNextSentencePrediction.__init__<  s4     '
#F+ 	rT   NrU   rv   r2   rV   r.   rW   rk  rx   rY   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
        ```
        Trn  r&   Nr0   r{   r  )r  r`  r   r   r   r   r  )rP   rU   rv   r2   rV   r.   rW   rk  rx   rp  r   seq_relationship_scoresrt  rr  s                 rS   rg   z&ErnieForNextSentencePrediction.forwardE  s    Z $**	
))'%'	
 	
  
"&((="9!')H!)*A*F*Fr1*Mv{{[]!_*#*!//))	
 	
rT   NNNNNNN)rh   ri   rj   r5   r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   r  r  6  s      *..2.2-1,0-1&*D
<<$&D
 t+D
 t+	D

 ||d*D
 llT)D
 ||d*D
 t#D
 +,D
 
u||	:	:D
  D
rT   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                   J    e Zd Z f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 xZS )ErnieForSequenceClassificationc                 n   t         |   |       |j                  | _        || _        t	        |      | _        |j                  |j                  n|j                  }t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y r   )r4   r5   
num_labelsrQ   r-  r  classifier_dropoutrC   r6   rB   rD   r   r9   
classifierr2  rP   rQ   r  rR   s      rS   r5   z'ErnieForSequenceClassification.__init__  s      ++'
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rT   NrU   rv   r2   rV   r.   rW   rk  rx   rY   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).
        Trn  r&   N
regressionsingle_label_classificationmulti_label_classificationr0   r  )r  rD   r  rQ   problem_typer  r3   rF   rK   rn   r   squeezer   r   r   r   r   r  )rP   rU   rv   r2   rV   r.   rW   rk  rx   rp  r   r  rJ  rr  s                 rS   rg   z&ErnieForSequenceClassification.forward  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,./'!//))	
 	
rT   r  )rh   ri   rj   r5   r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   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
rT   r  c                   J    e Zd Z f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 xZS )ErnieForMultipleChoicec                 *   t         |   |       t        |      | _        |j                  |j                  n|j
                  }t        j                  |      | _        t        j                  |j                  d      | _        | j                          y )Nr&   )r4   r5   r-  r  r  rC   r6   rB   rD   r   r9   r  r2  r  s      rS   r5   zErnieForMultipleChoice.__init__  su     '
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$6: 	rT   NrU   rv   r2   rV   r.   rW   rk  rx   rY   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&   r0   Trn  r  )
r_   r   rJ   r  rD   r  r   r   r   r  )rP   rU   rv   r2   rV   r.   rW   rk  rx   num_choicesrp  r   r  reshaped_logitsrJ  rr  s                   rS   rg   zErnieForMultipleChoice.forward  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("!//))	
 	
rT   r  )rh   ri   rj   r5   r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   r  r    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
rT   r  c                   J    e Zd Z f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 xZS )ErnieForTokenClassificationc                 d   t         |   |       |j                  | _        t        |d      | _        |j
                  |j
                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        | j                          y NFr~  )r4   r5   r  r-  r  r  rC   r6   rB   rD   r   r9   r  r2  r  s      rS   r5   z$ErnieForTokenClassification.__init__V  s      ++%@
)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rT   NrU   rv   r2   rV   r.   rW   rk  rx   rY   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]`.
        Trn  r   Nr0   r  )	r  rD   r  r   r   r  r   r   r  )rP   rU   rv   r2   rV   r.   rW   rk  rx   rp  rE  r  rJ  rr  s                 rS   rg   z#ErnieForTokenClassification.forwardd  s    , $**	
))'%'	
 	
 "!*,,71')HFKKDOO<fkk"oND$!//))	
 	
rT   r  )rh   ri   rj   r5   r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   r  r  T  s      *..2.2-1,0-1&*.
<<$&.
 t+.
 t+	.

 ||d*.
 llT).
 ||d*.
 t#.
 +,.
 
u||	4	4.
  .
rT   r  c                   j    e Zd Z f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 xZS )ErnieForQuestionAnsweringc                     t         |   |       |j                  | _        t        |d      | _        t        j                  |j                  |j                        | _        | j                          y r  )
r4   r5   r  r-  r  r6   r   r9   
qa_outputsr2  rO   s     rS   r5   z"ErnieForQuestionAnswering.__init__  sU      ++%@
))F$6$68I8IJ 	rT   NrU   rv   r2   rV   r.   rW   start_positionsend_positionsrx   rY   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;  Trn  r   r&   r0   r|   N)ignore_indexr{   )rJ  start_logits
end_logitsr   r  )r  r  splitr  r   lenrJ   clampr   r   r   r  )rP   rU   rv   r2   rV   r.   rW   r  r  rx   rp  rE  r  r  r  rq  ignored_indexrr  
start_lossend_losss                       rS   rg   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+%!!//))
 	
rT   ru  )rh   ri   rj   r5   r#   r!   rF   ro   r   r    r   r   rg   rp   rq   s   @rS   r  r    s      *..2.2-1,0-1/3-1<
<<$&<
 t+<
 t+	<

 ||d*<
 llT)<
 ||d*<
 ,<
 ||d*<
 +,<
 
u||	;	;<
  <
rT   r  )
r|  r  r  r  rY  r  r  r  r-  r  )Nr   )Ycollections.abcr   dataclassesr   rF   torch.nnr6   r   r   r    r	   r  activationsr
   cache_utilsr   r   r   
generationr   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r    r!   r"   utils.genericr#   r$   utils.output_capturingr%   configuration_ernier'   
get_loggerrh   r>  Moduler)   ro   floatr   r   r   r   r   r   r   r   r   r   r  r  r  r-  rI  rP  rY  rx  r|  r  r  r  r  r  r  r  __all__rN  rT   rS   <module>r     s  * % !   A A & ! C C ) J 9
 
 
 G & 6 M M I 5 , 
		H	%Jbii Jf !%II%<<% 
% <<	%
 LL4'% T\% % '(%8F) F)RJ)")) J)Zbii .RYY .>		 ")) @+ @F")) 299 "BII  
299 
D /? / /2 	^6% ^6^6B 
7 7 7&	9BII 	9 `
. `
`
F!ryy ! 
Z
+_ Z

Z
z P
+ P
 P
f&ryy & 
P
%9 P

P
f T
%9 T
T
n e
1 e
 e
P ?
"6 ?
 ?
D I
 4 I
 I
XrT   