
    9i7                       S SK r S SKrS SKrS SKrS SKJr  S SKJrJr  S SK	r	S SK
Js  Jr  S SKr	S SKrS SK	JrJrJrJr  S SKJrJr  S SKJr  S SKJrJrJrJrJr  S SKJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'  S S	K(J)r)  S S
K*J+r+  S SK,J-r-  S SK.J/r/  S SK0J1r1J2r2  S SK3J4r4  S SK5J6r6  S SK7J8r8  S SK9J:r:  S SK;J<r<J=r=J>r>  \RZ                  R                  5         \-R                  " 5       rASrBSrCS rD " S S\R                  5      rF " S S\R                  5      rG " S S\R                  5      rH " S S\R                  5      rI " S S\R                  5      rJ " S  S!\R                  5      rK " S" S#\R                  5      rL " S$ S%\R                  5      rM " S& S'\R                  5      rN " S( S)\R                  5      rO " S* S+\R                  5      rP " S, S-\R                  5      rQ " S. S/\R                  5      rR " S0 S1\R                  5      rS " S2 S3\R                  5      rT " S4 S5\)5      rU\ " S6 S7\5      5       rV " S8 S9\U5      rW " S: S;\U5      rX " S< S=\U5      rY " S> S?\R                  5      rZ " S@ SA\U5      r[ " SB SC\U5      r\ " SD SE\U5      r] " SF SG\U5      r^ " SH SI\U5      r_ " SJ SK\U5      r` " SL SM\U5      ra " SN SO\2\)5      rb\4R                  " \8R                  \/R                  SP9 " SQ SR\b5      5       rfg)S    N)	dataclass)OptionalTuple)Tensordevicedtypenn)CrossEntropyLossMSELoss)ACT2FN)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardreplace_return_docstrings)	)BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)
BertConfig)logging)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)parse_labels_in_order)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layerr   BertTokenizerc           
          SSK nSSKnSSKn[        R                  R                  U5      n[        R                  SR                  U5      5        UR                  R                  U5      n/ n/ n	U Hf  u  p[        R                  SR                  X5      5        UR                  R                  Xj5      nUR                  U
5        U	R                  U5        Mh     [        X5       GH  u  pU
R!                  S5      n
[#        S U
 5       5      (       a5  [        R                  SR                  SR%                  U
5      5      5        Mc  U nU
 H  nUR'                  S	U5      (       a  UR!                  S
U5      nOU/nUS   S:X  d	  US   S:X  a  [)        US5      nOZUS   S:X  d	  US   S:X  a  [)        US5      nO;US   S:X  a  [)        US5      nO%US   S:X  a  [)        US5      nO [)        XS   5      n[-        U5      S:  d  M  [/        US   5      nUU   nM     WSS S:X  a  [)        US5      nOUS:X  a  UR1                  U5      n UR2                  UR2                  :X  d"   SUR2                   SUR2                   S35       e [        R                  SR                  U
5      5        [8        R:                  " U5      Ul        GM     U $ ! [         a    [        R                  S5        e f = f! [*         a8    [        R                  SR                  SR%                  U
5      5      5         GM  f = f! [4         a1  nU=R6                  UR2                  UR2                  4-  sl        e SnAff = f)z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z(Converting TensorFlow checkpoint from {}z"Loading TF weight {} with shape {}/c              3   ,   #    U  H
  nUS ;   v   M     g7f))adam_vadam_mAdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepN ).0ns     k/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/multi_modal/mgeo/backbone.py	<genexpr>*load_tf_weights_in_bert.<locals>.<genexpr>M   s%       a  
 
 s   zSkipping {}z[A-Za-z]+_\d+z_(\d+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifier      i_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight {})renumpy
tensorflowImportErrorloggererrorospathabspathinfoformattrainlist_variablesload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorch
from_numpydata)modelconfigtf_checkpoint_pathrC   nptftf_path	init_varsnamesarraysnamer\   arraypointerm_namescope_namesnumes                     r4   load_tf_weights_in_bertrr   0   s&   
 ggoo01G
KK:AA'JK''0IEF 8??LM&&w5Te	 ! 5)zz#      KK,,SXXd^<=F||,f55 hhy&9%h1~)[^w-F!'84Q=0KNf4L!'62Q#33!'84Q7*!'<8%g1~>G ;1$+a.)!#,+ , #$<=(gx0GxLL'E	,Y.?}KXY,
 	299$?@''.[ *\ LA  Q	
 	Z & KK 4 4SXXd^ DE  	FFw}}ekk22F	s5   K )K4<L9!K14=L65L69
M4,M//M4c                   L   ^  \ rS rSrSrU 4S jr           SS jrSrU =r$ )GisEmbeddingsz   zGConstruct the embeddings from word, position and token_type embeddings.c                   > [         TU ]  5         [        R                  " UR                  UR
                  SS9U l        [        R                  " UR                  UR
                  5      U l        [        R                  " UR                  UR
                  SS9U l
        [        R                  " UR                  UR
                  SS9U l        [        R                  " UR                  UR
                  SS9U l        [        R                  " UR                  UR
                  SS9U l        [        R                  " UR"                  UR
                  SS9U l        [        R                  " UR&                  UR
                  SS9U l        [+        US5      (       a  [        R                  " UR,                  UR
                  SS9U l        [        R                  " UR0                  UR
                  SS9U l        [        R                  " UR4                  UR
                  SS9U l        [        R8                  " UR
                  UR:                  S9U l        [        R<                  " UR>                  5      U l         U RC                  S[D        RF                  " UR                  5      RI                  S5      5        [K        USS5      U l&        Xl'        g )	Nr   padding_idxprov_vocab_sizeepsposition_idsrA   position_embedding_typeabsolute)(super__init__r	   	Embedding
vocab_sizehidden_sizeword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddingsrel_type_vocab_sizerel_type_embeddingsabsolute_x_vocab_sizeabsolute_x_embeddingsabsolute_y_vocab_sizeabsolute_y_embeddingsrelative_x_vocab_sizerelative_x_embeddingsrelative_y_vocab_sizerelative_y_embeddingshasattrry   prov_embeddingscity_vocab_sizecity_embeddingsdist_vocab_sizedist_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferr_   arangeexpandrW   r   rc   selfrc   	__class__s     r4   r   GisEmbeddings.__init__}   s9   !||v11q B#%<<0N0N060B0B$D %'\\""F$6$6A&G"#%<<&&(:(:$K %'\\((&*<*<!&M"%'\\((&*<*<!&M"%'\\((&*<*<!&M"%'\\((&*<*<!&M"6,--#%<<&&(:(:$KD #%<<&&(:(:$KD #%<<&&(:(:$KD 
 F$9$9;zz&"<"<= 	LL778??H	J (/v/H/9(;$     c                 X   Ub  UR                  5       nOUR                  5       S S nUS   nUc  U R                  S S 2X]U-   24   nUc8  [        R                  " U[        R                  U R                  R
                  S9nUc  U R                  U5      nU R                  U5      nXN-   nU R                  S:X  a  U R                  U5      nUU-  nXR                  U5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nXR                  US S 2S S 2S4   5      -  nU	b9  XR                  U	5      -  nXR!                  U
5      -  nXR#                  U5      -  nU R%                  U5      nU R'                  U5      nU$ )Nr~   rA   r   r   r   r   r@      )sizer|   r_   zeroslongr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   	input_idstoken_type_idsr|   inputs_embedspast_key_values_lengthrel_type_idsabsolute_position_idsrelative_position_idsprov_idscity_idsdist_idsinput_shape
seq_lengthr   
embeddingsr   s                    r4   forwardGisEmbeddings.forward   s     #..*K',,.s3K ^
,,Q-C/EEF .F.F GL !"[[5::d6G6G6N6NPN   00;M $ : :> J":
'':5"&":":<"H--J..|<<
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
001Fq!GHHI 2J K 	K
..x88J..x88J..x88J^^J/
\\*-
r   )r   r   r   r   rc   r   r   r   r   r   r   r   r   r   r   )NNNNr   NNNNNN	__name__
__module____qualname____firstlineno____doc__r   r   __static_attributes____classcell__r   s   @r4   rt   rt   z   s9    Q(V #!"'(!&*&*= =r   rt   c                   F   ^  \ rS rSrSrU 4S jr        SS jrSrU =r$ )BertEmbeddings   zGConstruct the embeddings from word, position and token_type
embeddings.c                   > [         TU ]  5         [        R                  " UR                  UR
                  UR                  S9U l        [        R                  " UR                  UR
                  5      U l	        [        R                  " UR                  UR
                  5      U l        [        R                  " UR
                  UR                  S9U l        [        R                  " UR                  5      U l        U R#                  S[$        R&                  " UR                  5      R)                  S5      5        [+        USS5      U l        Xl        g )Nrw   rz   r|   r}   r   r   )r   r   r	   r   r   r   pad_token_idr   r   r   r   r   r   r   r   r   r   r   r_   r   r   rW   r   rc   r   s     r4   r   BertEmbeddings.__init__   s
   !||++ - $&<<0N0N060B0B$D %'\\&2H2H282D2D&F"
 F$9$9;zz&"<"<= 	LL778??H	J (/v/H/9(;$ r   c	                    Ub  UR                  5       n	OUR                  5       S S n	U	S   n
Uc  U R                  S S 2XZU-   24   nUc8  [        R                  " U	[        R                  U R                  R
                  S9nUc  U R                  U5      nU R                  U5      nXK-   nU R                  S:X  a  U R                  U5      nX-  nU R                  U5      nU R                  U5      nU$ )Nr~   rA   r   r   )r   r|   r_   r   r   r   r   r   r   r   r   r   )r   r   r   r|   r   r   r   r   r   r   r   r   r   r   s                 r4   r   BertEmbeddings.forward  s     #..*K',,.s3K ^
,,Q-C/EEF .F.F GL !"[[5::d6G6G6N6NPN   00;M $ : :> J":
'':5"&":":<"H-J^^J/
\\*-
r   )r   rc   r   r   r   r   r   )NNNNr   NNNr   r   s   @r4   r   r      s1    8 #!"'(!&*&*$ $r   r   c                   \   ^  \ rS rSrU 4S jrS rS rS rS rS r	      S
S jr
S	rU =r$ )BertSelfAttentioni-  c                   > [         TU ]  5         Xl        UR                  UR                  -  S:w  a5  [        US5      (       d$  [        SUR                  UR                  4-  5      eUR                  U l        [        UR                  UR                  -  5      U l        U R                  U R                  -  U l	        [        R                  " UR                  U R                  5      U l        U(       aa  [        R                  " UR                  U R                  5      U l        [        R                  " UR                  U R                  5      U l        O`[        R                  " UR                  U R                  5      U l        [        R                  " UR                  U R                  5      U l        [        R                   " UR"                  5      U l        ['        USS5      U l        U R(                  S:X  d  U R(                  S:X  aG  UR*                  U l        [        R,                  " SUR*                  -  S	-
  U R                  5      U l        S
U l        g )Nr   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)r   r   relative_keyrelative_key_queryr@   rA   F)r   r   rc   r   num_attention_headsr   
ValueErrorrZ   attention_head_sizeall_head_sizer	   Linearqueryencoder_widthkeyvaluer   attention_probs_dropout_probr   rW   r   r   r   distance_embeddingsave_attentionr   rc   is_cross_attentionr   s      r4   r   BertSelfAttention.__init__/  s    : ::a?(I* I*##V%?%?@AB B
 $*#=#= #&v'9'9)/)C)C(D $E !558P8PPYYv1143E3EF
yy!5!5t7I7IJDH6#7#79K9KLDJyy!3!3T5G5GHDH6#5#5t7I7IJDJzz&"E"EF'.v/H/9(;$ ''>9T=Y=Y]q=q+1+I+ID(&(llF222Q6(('*D# $r   c                     Xl         g Nattn_gradients)r   r   s     r4   save_attn_gradients%BertSelfAttention.save_attn_gradientsQ  s    ,r   c                     U R                   $ r   r   r   s    r4   get_attn_gradients$BertSelfAttention.get_attn_gradientsT  s    """r   c                     Xl         g r   attention_map)r   r   s     r4   save_attention_map$BertSelfAttention.save_attention_mapW  s    *r   c                     U R                   $ r   r   r   s    r4   get_attention_map#BertSelfAttention.get_attention_mapZ  s    !!!r   c                     UR                  5       S S U R                  U R                  4-   nUR                  " U6 nUR	                  SSSS5      $ )Nr~   r   r@   rA   r   )r   r   r   viewpermute)r   xnew_x_shapes      r4   transpose_for_scores&BertSelfAttention.transpose_for_scores]  sS    ffhsmt'?'?'+'?'?'A AFFK yyAq!$$r   c                    U R                  U5      nUS Ln	U	(       aC  U R                  U R                  U5      5      n
U R                  U R                  U5      5      nUnOUbu  U R                  U R                  U5      5      n
U R                  U R                  U5      5      n[        R
                  " US   U
/SS9n
[        R
                  " US   U/SS9nO@U R                  U R                  U5      5      n
U R                  U R                  U5      5      nU R                  U5      nX4n[        R                  " UU
R                  SS5      5      nU R                  S:X  d  U R                  S:X  GaD  UR                  5       S   n[        R                  " U[        R                  UR                  S	9R                  SS5      n[        R                  " U[        R                  UR                  S	9R                  SS5      nUU-
  nU R                  UU R                  -   S-
  5      nUR!                  UR"                  S
9nU R                  S:X  a  [        R$                  " SUU5      nUU-   nOHU R                  S:X  a8  [        R$                  " SUU5      n[        R$                  " SU
U5      nUU-   U-   nU[&        R(                  " U R*                  5      -  nUb  X-   n[,        R.                  " SS9" U5      nU	(       a=  U R0                  (       a,  U R3                  U5        UR5                  U R6                  5        U R9                  U5      nUb  UU-  n[        R                  " UU5      nUR;                  SSSS5      R=                  5       nUR                  5       S S U R>                  4-   nUR                  " U6 nU(       a  UU4OU4nUU4-   nU$ )Nr   r@   dimrA   r~   r   r   r   r   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r   r   r   r   r_   catmatmulr[   r   r   r   r   r   r   r   r   tor   einsummathsqrtr   r	   Softmaxr   r   register_hookr   r   r   
contiguousr   )r   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsmixed_query_layerr   	key_layervalue_layerquery_layerattention_scoresr   position_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probsattention_probs_droppedcontext_layernew_context_layer_shapeoutputss                              r4   r   BertSelfAttention.forwardc  s    !JJ}5
 3$>11./1I33

013K3N'11$((=2IJI33DJJ}4MNK		>!#4i"@aHI))^A%6$D!LK11$((=2IJI33DJJ}4MNK//0AB#1 !<<(1(;(;B(CE ''>9T=Y=Y]q=q&++-a0J"\\%**$++--1T"a[  #\\%**$++--1T!R[  &6H#'#:#:4777!;$= #7#:#:!'' $; $)  ++~=+0<<$k3G,I(#36N#N --1EE16$k3G2I./4||$i1E0G,#36T#TWs#s +dii$$/& &%/@ **,-=>$"5"5##O4))$*B*BC #',,"?  &=	&I#%<kJ%--aAq9DDF"/"4"4"6s";?" #"%**,CD (9 !"$?L>O 	 ^..r   )r   r   r   r   rc   r   r   r   r   r   r   r   r   r   NNNNNF)r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r4   r   r   -  sB     $D-#+"% "#a ar   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertSelfOutputi  c                 (  > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " UR                  UR                  S9U l        [        R                  " UR                  5      U l
        g Nrz   )r   r   r	   r   r   denser   r   r   r   r   r   s     r4   r   BertSelfOutput.__init__  sc    YYv1163E3EF
F$9$9;zz&"<"<=r   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r(  r   r   r   r
  input_tensors      r4   r   BertSelfOutput.forward  5    

=1]3}'CDr   r   r(  r   r   r   r   r   r   r   r   r   r   s   @r4   r%  r%        > r   r%  c                   H   ^  \ rS rSrSU 4S jjrS r      SS jrSrU =r$ )BertAttentioni  c                    > [         TU ]  5         [        X5      U l        [	        U5      U l        [        5       U l        g r   )r   r   r   r   r%  outputsetpruned_headsr   s      r4   r   BertAttention.__init__  s0    %fA	$V,Er   c                 6   [        U5      S:X  a  g [        XR                  R                  U R                  R                  U R
                  5      u  p[        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l	        [        U R                  R                  USS9U R                  l        U R                  R                  [        U5      -
  U R                  l        U R                  R                  U R                  R                  -  U R                  l        U R
                  R                  U5      U l        g )Nr   rA   r   )rY   r&   r   r   r   r8  r'   r   r   r   r6  r(  r   union)r   headsindexs      r4   prune_headsBertAttention.prune_heads  s   u:?79900II))4+<+<>
 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EI )		%"&))"?"?$))B_B_"_		 --33E:r   c           	      p    U R                  UUUUUUU5      nU R                  US   U5      n	U	4USS  -   n
U
$ )Nr   rA   )r   r6  )r   r
  r  r  r  r  r  r  self_outputsattention_outputr!  s              r4   r   BertAttention.forward  s\     yy!"
  ;;|AF# #AB'(r   )r6  r8  r   Fr#  )	r   r   r   r   r   r>  r   r   r   r   s   @r4   r4  r4    s+    ";, "# r   r4  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertIntermediatei  c                   > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        [        UR                  [        5      (       a  [        UR                     U l        g UR                  U l        g r   )r   r   r	   r   r   intermediate_sizer(  
isinstance
hidden_actstrr   intermediate_act_fnr   s     r4   r   BertIntermediate.__init__  s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$r   c                 J    U R                  U5      nU R                  U5      nU$ r   r(  rL  r   r
  s     r4   r   BertIntermediate.forward  s&    

=100?r   rO  r1  r   s   @r4   rF  rF    s    9 r   rF  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )
BertOutputi  c                 (  > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        [        R                  " UR
                  UR                  S9U l        [        R                  " UR                  5      U l        g r'  )r   r   r	   r   rH  r   r(  r   r   r   r   r   r   s     r4   r   BertOutput.__init__  sc    YYv779K9KL
F$9$9;zz&"<"<=r   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r+  r,  s      r4   r   BertOutput.forward$  r/  r   r0  r1  r   s   @r4   rS  rS    r2  r   rS  c                   D   ^  \ rS rSrU 4S jr      SS jrS rSrU =r$ )	BertLayeri+  c                 0  > [         TU ]  5         Xl        UR                  U l        SU l        [        U5      U l        X!R                  :  U l        U R                  (       a  X l	        [        USS9U l
        [        U5      U l        [        U5      U l        g )NrA   T)r   )r   r   rc   chunk_size_feed_forwardseq_len_dimr4  	attentionfusion_layerhas_cross_attention	layer_numcrossattentionrF  intermediaterS  r6  )r   rc   r`  r   s      r4   r   BertLayer.__init__-  s    '-'E'E$&v.$-1D1D$D ##&N"/4#1D,V4 (r   c                 f   Ub  US S OS nU R                  UUUUUS9n	U	S   n
U	SS nU	S   nU R                  (       a  Uc   S5       e[        U5      [        :X  a  U R	                  U
UUX@R
                  U R                  R                  -
  [        U5      -     XPR
                  U R                  R                  -
  [        U5      -     US9nUS   n
XSS -   nO U R	                  U
UUUUUS9nUS   n
XSS -   n[        U R                  U R                  U R                  U
5      nU4U-   nX4-   nU$ )Nr@   )r  r  r   rA   r~   z>encoder_hidden_states must be given for cross-attention layers)r  )r]  r_  typelistra  r`  rc   r^  rY   r%   feed_forward_chunkr[  r\  )r   r
  r  r  r  r  r  r  self_attn_past_key_valueself_attention_outputsrB  r!  present_key_valuecross_attention_outputslayer_outputs                  r4   r   BertLayer.forward<  s    9G8R $2 3423$5X\ 	!!%/3 "0 "
 2!4(2.226##(4v6vv4)*d2*.*=*=$")>>-1[[-E-E,F,/0E,F+G H +NN.2kk.F.F-G-01F-G,H I '8 +> +' $;1#= !Ab$AA +/*=*=$")*&7 +> +' $;1#= !%  11H1H151M1M151A1A1AC  "W,11r   c                 J    U R                  U5      nU R                  X!5      nU$ r   )rb  r6  )r   rB  intermediate_outputrl  s       r4   rg  BertLayer.feed_forward_chunk  s)    "//0@A{{#6Ir   )	r]  r[  rc   ra  r_  rb  r`  r6  r\  r#  )	r   r   r   r   r   r   rg  r   r   r   s   @r4   rY  rY  +  s-    )$ "#BH r   rY  c                   F   ^  \ rS rSrU 4S jr          SS jrSrU =r$ )BertEncoderi  c           	         > [         TU ]  5         Xl        [        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        g s  snf r   )	r   r   rc   r	   
ModuleListrangenum_hidden_layersrY  layer)r   rc   ir   s      r4   r   BertEncoder.__init__  sK    ]]+01I1I+JK+JaYv!+JKM
Ks   Ac           
        ^^ U	(       a  SOS nT(       a  SOS nT(       a  U R                   R                  (       a  SOS nU(       a  SOS nUS:X  a  SnU R                   R                  nOpUS:X  a  SnU R                   R                  nOQUS:X  a-  U R                   R                  nU R                   R                  nOUS:X  a  SnU R                   R                  n[	        WW5       H  nU R
                  U   nU	(       a  X4-   nUb  UU   OS nUb  UU   OS m[        U R                   SS5      (       ak  U R                  (       aZ  U(       a  [        R                  S	5        SnUU4S
 jn[        R                  R                  R                  U" U5      UUUUU5      nOU" UUUUUTT5      nUS   nU(       a	  UUS   4-  nT(       d  M  UUS   4-   nM     U	(       a  X4-   nU
(       d  [        S UUUUU4 5       5      $ [        UUUUUS9$ )Nr1   textr   r   fusionmulti_modalgradient_checkpointingFzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...c                    >^  U UU4S jnU$ )Nc                     > T" / U QTPTP76 $ r   r1   )inputsmoduler  r  s    r4   custom_forwardJBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forward  s&    %  9v  9~  9&7 9 9r   r1   )r  r  r  r  s   ` r4   create_custom_forward2BertEncoder.forward.<locals>.create_custom_forward  s    9 *)r   r~   rA   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r1   )r2   vs     r4   r5   &BertEncoder.forward.<locals>.<genexpr>  s"        %q   %s   	)last_hidden_statepast_key_valuesr
  
attentionscross_attentions)rc   add_cross_attentionr^  rv  ru  rw  rW   trainingrG   warnr_   utils
checkpointtupler   )r   r
  r  r  r  r  r  	use_cacher  output_hidden_statesreturn_dictmodeall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cachestart_layeroutput_layerrx  layer_modulelayer_head_maskr  layer_outputsr  s           `              @r4   r   BertEncoder.forward  sF    #7BD$5b44;;#B#B 
HL 	 $-R$6>K;;33LW_K;;88LX++22K;;88L]"K;;88L{L1A::a=L#$58I$I!.7.CilO%1 -7;  t{{$< "&--KK/0 !&I* !& 6 6 A A),7!"#)*! !-!"#)*"%! *!,M"}R'8&;;"  &9!!$=( '(#c 2h   14E E  "!#$%       9+.+*1
 	
r   )rc   rw  )
NNNNNNFFTr}  r1  r   s   @r4   rr  rr    s5    M "#"j
 j
r   rr  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )
BertPooleri  c                    > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " 5       U l        g r   )r   r   r	   r   r   r(  Tanh
activationr   s     r4   r   BertPooler.__init__  s9    YYv1163E3EF
'')r   c                 \    US S 2S4   nU R                  U5      nU R                  U5      nU$ Nr   )r(  r  )r   r
  first_token_tensorpooled_outputs       r4   r   BertPooler.forward  s6     +1a40

#566r   )r  r(  r1  r   s   @r4   r  r    s    $
 r   r  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertPredictionHeadTransformi  c                 p  > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        UR                  [        5      (       a  [        UR                     U l
        OUR                  U l
        [        R                  " UR                  UR                  S9U l        g r'  )r   r   r	   r   r   r(  rI  rJ  rK  r   transform_act_fnr   r   r   s     r4   r   $BertPredictionHeadTransform.__init__  s    YYv1163E3EF
f''--$*6+<+<$=D!$*$5$5D!F$9$9;r   c                 l    U R                  U5      nU R                  U5      nU R                  U5      nU$ r   )r(  r  r   rP  s     r4   r   #BertPredictionHeadTransform.forward  s4    

=1--m<}5r   )r   r(  r  r1  r   s   @r4   r  r    s    ; r   r  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertLMPredictionHeadi  c                 H  > [         TU ]  5         [        U5      U l        [        R
                  " UR                  UR                  SS9U l        [        R                  " [        R                  " UR                  5      5      U l        U R                  U R                  l        g NF)r<   )r   r   r  	transformr	   r   r   r   decoder	Parameterr_   r   r<   r   s     r4   r   BertLMPredictionHead.__init__   sr    4V< yy 1 1? LLV->->!?@	 !IIr   c                 J    U R                  U5      nU R                  U5      nU$ r   r  r  rP  s     r4   r   BertLMPredictionHead.forward.  $    }5]3r   r<   r  r  r1  r   s   @r4   r  r    s    & r   r  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertOnlyMLMHeadi4  c                 B   > [         TU ]  5         [        U5      U l        g r   )r   r   r  predictionsr   s     r4   r   BertOnlyMLMHead.__init__6  s    /7r   c                 (    U R                  U5      nU$ r   r  )r   sequence_outputprediction_scoress      r4   r   BertOnlyMLMHead.forward:  s     ,,_=  r   r  r1  r   s   @r4   r  r  4  s    8! !r   r  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertOnlyNSPHeadi?  c                 n   > [         TU ]  5         [        R                  " UR                  S5      U l        g Nr@   )r   r   r	   r   r   seq_relationshipr   s     r4   r   BertOnlyNSPHead.__init__A  s'     "		&*<*<a @r   c                 (    U R                  U5      nU$ r   r  )r   r  seq_relationship_scores      r4   r   BertOnlyNSPHead.forwardE  s    !%!6!6}!E%%r   r  r1  r   s   @r4   r  r  ?  s    A& &r   r  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertPreTrainingHeadsiJ  c                    > [         TU ]  5         [        U5      U l        [        R
                  " UR                  S5      U l        g r  )r   r   r  r  r	   r   r   r  r   s     r4   r   BertPreTrainingHeads.__init__L  s4    /7 "		&*<*<a @r   c                 L    U R                  U5      nU R                  U5      nX44$ r   r  r  )r   r  r  r  r  s        r4   r   BertPreTrainingHeads.forwardQ  s-     ,,_=!%!6!6}!E 88r   r  r1  r   s   @r4   r  r  J  s    A
9 9r   r  c                   0    \ rS rSrSr\r\rSr	S/r
S rSrg)BertPreTrainedModeliW  z
An abstract class to handle weights initialization and a simple interface
for downloading and loading pretrained models.
bertr|   c                 H   [        U[        R                  [        R                  45      (       a9  UR                  R
                  R                  SU R                  R                  S9  Oh[        U[        R                  5      (       aI  UR                  R
                  R                  5         UR                  R
                  R                  S5        [        U[        R                  5      (       a3  UR                  b%  UR                  R
                  R                  5         ggg)zInitialize the weights         meanstd      ?N)rI  r	   r   r   r9   ra   normal_rc   initializer_ranger   r<   zero_fill_r   r  s     r4   _init_weights!BertPreTrainedModel._init_weightsb  s    fryy",,788 MM&&dkk;; ' =--KK""$MM$$S)fbii((V[[-DKK""$ .E(r   r1   N)r   r   r   r   r   r   config_classrr   load_tf_weightsbase_model_prefix_keys_to_ignore_on_load_missingr  r   r1   r   r4   r  r  W  s'    
 L-O'6&7#%r   r  c                       \ rS rSr% SrSr\\R                     \	S'   Sr
\R                  \	S'   Sr\R                  \	S'   Sr\\\R                        \	S'   Sr\\\R                        \	S'   S	rg)
BertForPreTrainingOutputip  a  
Output type of :class:`~transformers.BertForPreTraining`. Args:
    loss (`optional`, returned when ``labels`` is provided,
    ``torch.FloatTensor`` of shape :obj:`(1,)`):
        Total loss as the sum of the masked language modeling loss and the
        next sequence prediction (classification) loss.
    prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size,
    sequence_length, config.vocab_size)`):
        Prediction scores of the language modeling head (scores for each
        vocabulary token before SoftMax).
    seq_relationship_logits (:obj:`torch.FloatTensor` of shape
    :obj:`(batch_size, 2)`):
        Prediction scores of the next sequence prediction (classification)
        head (scores of True/False continuation before SoftMax).
    hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned
    when ``output_hidden_states=True`` is passed or when
    ``config.output_hidden_states=True``):
        Tuple of :obj:`torch.FloatTensor` (one for the output of the
        embeddings + one for the output of each layer) of shape
        :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of
        the model at the output of each layer plus the initial embedding
        outputs.
    attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when
    ``output_attentions=True`` is passed or when
    ``config.output_attentions=True``):
        Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
        :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
        Attentions weights after the attention softmax, used to compute the
        weighted average in the self-attention heads.
Nlossprediction_logitsseq_relationship_logitsr
  r  r1   )r   r   r   r   r   r  r   r_   FloatTensor__annotations__r  r  r
  r   r  r   r1   r   r4   r  r  p  st    > )-D(5$$
%,+/u((/15U..58<M8E%"3"345<59Ju00129r   r  c            
          ^  \ rS rSrSrSU 4S jjrS rS rS rS\	S\
\   S	\S
\S\	4
S jr                      SS jrSrU =r$ )	BertModeli  a  
Noted that the bert model here is slightly updated from original bert, so we
maintain the code here independently. The Bert Model transformer outputting
raw hidden-states without any specific head on top.

This model inherits from [`PreTrainedModel`]. Check the superclass
documentation for the generic methods the library implements for all its
model (such as downloading or saving, resizing the input embeddings, pruning
heads etc.)

This model is also a PyTorch
[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
subclass. Use it as a regular PyTorch Module and refer to the PyTorch
documentation for all matter related to general usage and behavior.

Parameters:
    config ([`BertConfig`]): Model configuration class with all the
    parameters of the model.
        Initializing with a config file does not load the weights associated
        with the model, only the configuration. Check out the
        [`~PreTrainedModel.from_pretrained`] method to load the model
        weights.

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

To behave as an decoder the model needs to be initialized with the
`is_decoder` argument of the configuration set to `True`. To be used in a
Seq2Seq model, the model needs to initialized with both `is_decoder`
argument and `add_cross_attention` set to `True`; an `encoder_hidden_states`
is then expected as an input to the forward pass.


c                   > [         TU ]  U5        Xl        UR                  S:X  a  [	        U5      U l        O[        U5      U l        [        U5      U l        U(       a  [        U5      OS U l
        U R                  5         g r  )r   r   rc   gis_embeddingr   r   rt   rr  encoderr  poolerinit_weights)r   rc   add_pooling_layerr   s      r4   r   BertModel.__init__  sc     1$,V4DO+F3DO"6*,=j(4r   c                 .    U R                   R                  $ r   r   r   r   s    r4   get_input_embeddingsBertModel.get_input_embeddings  s    ...r   c                 $    XR                   l        g r   r  )r   r   s     r4   set_input_embeddingsBertModel.set_input_embeddings  s    */'r   c                     UR                  5        H7  u  p#U R                  R                  U   R                  R	                  U5        M9     g)z
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
N)itemsr  rw  r]  r>  )r   heads_to_prunerw  r<  s       r4   _prune_headsBertModel._prune_heads  s<    
 +002LELLu%//;;EB 3r   r  r   r   
is_decoderreturnc                    UR                  5       S:X  a  USS2SSS2SS24   nGO:UR                  5       S:X  Ga  U(       a  Uu  pg[        R                  " XsS9nUSSSS24   R                  XgS5      USSS2S4   :*  n	U	R	                  UR
                  5      n	U	R                  S   UR                  S   :  aV  UR                  S   U	R                  S   -
  n
[        R                  " [        R                  " XgU
4UU	R
                  S9U	/SS9n	U	SS2SSS2SS24   USS2SSSS24   -  nO2USS2SSSS24   nO$[        S	R                  X!R                  5      5      eUR	                  U R
                  S
9nSU-
  S-  nU$ )a  
Makes broadcastable attention and causal masks so that future and masked
tokens are ignored.

Arguments:
    attention_mask (:obj:`torch.Tensor`):
        Mask with ones indicating tokens to attend to, zeros for tokens
        to ignore.
    input_shape (:obj:`Tuple[int]`):
        The shape of the input to the model.
    device: (:obj:`torch.device`):
        The device of the input to the model.

Returns:
    :obj:`torch.Tensor` The extended attention mask, with a the same
    dtype as :obj:`attention_mask.dtype`.
r   Nr@   r   rA   )r   r   r~   )axiszAWrong shape for input_ids (shape {}) or attention_mask (shape {})r   r  g     )r   r_   r   repeatr  r   r\   r  onesr   rM   )r   r  r   r   r  extended_attention_mask
batch_sizer   seq_idscausal_maskprefix_seq_lens              r4   get_extended_attention_mask%BertModel.get_extended_attention_mask  s   . 1$&4Qa]&C#!Q& )4&
,,zA%dD!m4;;A/29$4-2HI
 *nn^-A-AB$$Q'.*>*>q*AA%3%9%9&(..q1&2N"'))!JJ!+ H'-&1&7&79 (  	#K +6a6:Aq7A +BDRSTSWSWYZT[ E\+\'
 +9D$9I*J'S%9%9:< < #:"<"<** #= ##&)@#@H"L&&r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU(       a  Ub  UOU R                   R                  nOSnUb  Ub  [        S5      eUb"  UR                  5       nUu  nnUR                  nO[Ub%  UR                  5       SS nUu  nnUR                  nO3Ub%  UR                  5       SS nUu  nnUR                  nO[        S5      eU
b  U
S   S   R                  S   OSnUc  [        R                  " UUU-   4US9nUc$  [        R                  " U[        R                  US	9nU R                  UUUU5      nUb  [        U5      [        :X  a  US   R                  5       u  nnnOUR                  5       u  nnnUU4n [        U	5      [        :X  a"  U	 V!s/ s H  n!U R!                  U!5      PM     n"n!O>U	c'  [        R                  " U US9n	U R!                  U	5      n"OU R!                  U	5      n"OSn"U R#                  UU R                   R$                  5      nUc  U R'                  UUUUUUUUUUUS
9n#OUn#U R)                  U#UUUU"U
UUUUUS9n$U$S   n%U R*                  b  U R+                  U%5      OSn&U(       d
  U%U&4U$SS -   $ [-        U%U&U$R.                  U$R0                  U$R2                  U$R4                  S9$ s  sn!f )a  
Args:
input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length)`):
    Indices of input sequence tokens in the vocabulary.

    Indices can be obtained using [`BertTokenizer`]. See
    [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`]
    for details.

    [What are input IDs?](../glossary#input-ids)
attention_mask (`torch.FloatTensor` of shape `((batch_size, sequence_length)`, *optional*):
    Mask to avoid performing attention on padding token indices. Mask
    values selected in `[0, 1]`:

    - 1 for tokens that are **not masked**,
    - 0 for tokens that are **masked**.

    [What are attention masks?](../glossary#attention-mask)
token_type_ids (`torch.LongTensor` of shape `((batch_size, 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)
position_ids (`torch.LongTensor` of shape `((batch_size, 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)
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers,
num_heads)`, *optional*):
    Mask to nullify selected heads of the self-attention modules. Mask
    values selected in `[0, 1]`:

    - 1 indicates the head is **not masked**,
    - 0 indicates the head is **masked**.

inputs_embeds (`torch.FloatTensor` of shape `((batch_size, 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.
output_attentions (`bool`, *optional*):
    Whether or not to return the attentions tensors of all attention
    layers. See `attentions` under returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
    Whether or not to return the hidden states of all layers. See
    `hidden_states` under returned tensors for more detail.
return_dict (`bool`, *optional*):
    Whether or not to return a [`~file_utils.ModelOutput`] instead of a
    plain tuple.
encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size,
sequence_length, hidden_size)`, *optional*):
    Sequence of hidden-states at the output of the last layer of the
    encoder. Used in the cross-attention if the model is configured as a
    decoder.
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size,
sequence_length)`, *optional*):
    Mask to avoid performing attention on the padding token indices of
    the encoder input. This mask is used in the cross-attention if the
    model is configured as a decoder. Mask values selected in `[0, 1]`:

    - 1 for tokens that are **not masked**,
    - 0 for tokens that are **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))` of length
`config.n_layers` with each tuple having 4 tensors of shape
`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
    Contains precomputed key and value hidden states of the attention
    blocks. Can be used to speed up decoding.

    If `past_key_values` are used, the user can optionally input only
    the last `decoder_input_ids` (those that don't have their past key
    value states given to this model) of shape `(batch_size, 1)` instead
    of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
    If set to `True`, `past_key_values` key value states are returned
    and can be used to speed up decoding (see `past_key_values`).
Others (**kwargs)
    some additional parameters might passed in from upstream pipeline,
    which not influence the results.
NFzDYou cannot specify both input_ids and inputs_embeds at the same timer~   zGYou have to specify either input_ids or inputs_embeds or encoder_embedsr   r@   r  r   )r   r|   r   r   r   r   r   r   r   r   r   )
r  r  r  r  r  r  r  r  r  r  rA   r  pooler_outputr  r
  r  r  )rc   r  r  use_return_dictr  r   r   r   r\   r_   r  r   r   r  re  rf  invert_attention_maskget_head_maskrv  r   r  r  r   r  r
  r  r  )'r   r   r  r   r|   r  r   encoder_embedsr  r  r  r  r  r  r  r  r  r   r   r   r   r   r   r   r  r   r   r   r  encoder_batch_sizeencoder_sequence_length_encoder_hidden_shapemaskencoder_extended_attention_maskembedding_outputencoder_outputsr  r  s'                                          r4   r   BertModel.forward)  s   ^ 2C1N-TXT_T_TqTq$8$D KK,, 	 &1%<k$++B]B]%.%:	@U@UII ]%>V  "#..*K%0"J
%%F&',,.s3K%0"J
"))F'(--/4K%0"J
#**FY  "- "1!3A!6!<!<"34 	 !"ZZj+AABN !"[[5::f>N 150P0PK1= !,)*d2AVBtv ?"$;Q BWA[A[ B>"$;Q$6$;$=  *+t3 !73 6 ..t4 6 0 3/ (/).(*9&262L2L*3,/ 372L2L*3,/ /3+ &&y'+{{'D'DF	 !##)-+'=)&;&;!!!  /    .,,2"7#B+/!5# ' 
 *!, $ 7 =A 	 #]3oab6III;-'+;;)77&11,==
 	
y3s   K=)rc   r   r  r  )T)NNNNNNNNNNNNNNFr}  NNNNNN)r   r   r   r   r   r   r  r  r  r   r   rZ   r   boolr  r   r   r   r   s   @r4   r  r    s    %N/0CJ'& J'16sJ'EKJ'04J'9?J'\ "#!""/r
 r
r   r  c                   T   ^  \ rS rSrU 4S jrS rS r           SS jrSrU =r	$ )BertForPreTrainingi  c                    > [         TU ]  U5        [        U5      U l        [	        U5      U l        U R                  5         g r   )r   r   r  r  r  clsr  r   s     r4   r   BertForPreTraining.__init__   s4     f%	'/r   c                 B    U R                   R                  R                  $ r   r/  r  r  r   s    r4   get_output_embeddings(BertForPreTraining.get_output_embeddings(      xx##+++r   c                 8    XR                   R                  l        g r   r2  r   new_embeddingss     r4   set_output_embeddings(BertForPreTraining.set_output_embeddings+      '5$r   c                    Ub  UOU R                   R                  nU R                  UUUUUUU	U
US9	nUSS u  pU R                  X5      u  nnSnUbv  Ubs  [	        5       nU" UR                  SU R                   R                  5      UR                  S5      5      nU" UR                  SS5      UR                  S5      5      nUU-   nU(       d  UU4USS -   nUb  U4U-   $ U$ [        UUUUR                  UR                  S9$ )aU  
labels (:obj:`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 :obj:`input_ids` docstring) Indices should be in ``[0, 1]``:
    - 0 indicates sequence B is a continuation of sequence A,
    - 1 indicates sequence B is a random sequence.
kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
    Used to hide legacy arguments that have been deprecated.
Returns:
Example:
    >>> from transformers import BertTokenizer, BertForPreTraining
    >>> import torch
    >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
    >>> model = BertForPreTraining.from_pretrained('bert-base-uncased')
    >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
    >>> outputs = model(**inputs)
    >>> prediction_logits = outputs.prediction_logits
    >>> seq_relationship_logits = outputs.seq_relationship_logits
Nr  r   r|   r  r   r  r  r  r@   r~   )r  r  r  r
  r  )
rc   r  r  r/  r
   r   r   r  r
  r  )r   r   r  r   r|   r  r   labelsnext_sentence_labelr  r  r  r!  r  r  r  r  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr6  s                         r4   r   BertForPreTraining.forward.  sZ   J &1%<k$++B]B]))))%'/!5#  

 *1!&48HH5,11 
"5"A')H%!&&r4;;+A+ABB!N "*&++B2#((,". (*<<J')?@712;NF!+!7  N D=CD (/$:!//))
 	
r   r  r/  NNNNNNNNNNN)
r   r   r   r   r   r3  r9  r   r   r   r   s   @r4   r-  r-    sA    ,6
  !M
 M
r   r-  c                      ^  \ rS rSrS/rSS/rU 4S jrS rS r                    SS jr	  SS	 jr
S
 rSrU =r$ )BertLMHeadModeli~  r  r|   predictions.decoder.biasc                    > [         TU ]  U5        [        USS9U l        [	        U5      U l        U R                  5         g NFr  r   r   r  r  r  r/  r  r   s     r4   r   BertLMHeadModel.__init__  6     f>	"6*r   c                 B    U R                   R                  R                  $ r   r2  r   s    r4   r3  %BertLMHeadModel.get_output_embeddings  r5  r   c                 8    XR                   R                  l        g r   r2  r7  s     r4   r9  %BertLMHeadModel.set_output_embeddings  r;  r   c                    Ub  UOU R                   R                  nU	b  SnU R                  UUUUUUUUU
UUUUUUS9nUS   nU R                  U5      nU(       a  USS2SS2SS24   R	                  5       $ SnU	b  USS2SS2SS24   R	                  5       nU	SS2SS24   R	                  5       n	[        US9nU" UR                  SU R                   R                  5      U	R                  S5      5      nUR                  UR                  S5      S5      R                  S5      nUbQ  [        R                  " [        R                  " WSS9U-  SS9* nUU	S	:g  -  R                  S5      nSU-
  U-  UU-  -   nU(       d  U4US
S -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                   UR"                  S9$ )a	  
encoder_hidden_states  (:obj:`torch.FloatTensor` of shape
:obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
    Sequence of hidden-states at the output of the last layer of the
    encoder. Used in the cross-attention if the model is configured as a
    decoder.
encoder_attention_mask (:obj:`torch.FloatTensor` of shape
:obj:`(batch_size, sequence_length)`, `optional`):
    Mask to avoid performing attention on the padding token indices of
    the encoder input. This mask is used in the cross-attention if the
    model is configured as a decoder. Mask values selected in ``[0,
    1]``: - 1 for tokens that are **not masked**, - 0 for tokens that
    are **masked**.
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
sequence_length)`, `optional`):
    Labels for computing the left-to-right language modeling loss (next
    word prediction). Indices should be in ``[-100, 0, ...,
    config.vocab_size]`` (see ``input_ids`` docstring) Tokens with
    indices set to ``-100`` are ignored (masked), the loss is only
    computed for the tokens with labels n ``[0, ...,
    config.vocab_size]``
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length
:obj:`config.n_layers` with each tuple having 4 tensors of shape
:obj:`(batch_size, num_heads, sequence_length - 1,
embed_size_per_head)`):
    Contains precomputed key and value hidden states of the attention
    blocks. Can be used to speed up decoding. If :obj:`past_key_values`
    are used, the user can optionally input only the last
    :obj:`decoder_input_ids` (those that don't have their past key value
    states given to this model) of shape :obj:`(batch_size, 1)` instead
    of all :obj:`decoder_input_ids` of shape :obj:`(batch_size,
    sequence_length)`.
use_cache (:obj:`bool`, `optional`):
    If set to :obj:`True`, :obj:`past_key_values` key value states are
    returned and can be used to speed up decoding (see
    :obj:`past_key_values`).

Returns:

Example:
    >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
    >>> import torch
    >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
    >>> config = BertConfig.from_pretrained("bert-base-cased")
    >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
    >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
    >>> outputs = model(**inputs)
    >>> prediction_logits = outputs.logits
NF)r  r   r|   r  r   r  r  r  r  r  r  r  r  r  r   r~   rA   )	reductionr   r@   )r  logitsr  r
  r  r  )rc   r  r  r/  r	  r
   r   r   r   sumr_   Flog_softmaxr   r  r
  r  r  )r   r   r  r   r|   r  r   r  r  r>  r  r  r  r  r  r  rU  r  soft_labelsalphareturn_logitsr!  r  r  lm_lossshifted_prediction_scoresrA  loss_distillr6  s                                r4   r   BertLMHeadModel.forward  s   P &1%<k$++B]B]I))))%'"7#9+/!5#!  
$ "!* HH_5$QQY/::<<(9! >=:<>=>?;@ )AAK &AqrE]--/F')<H)..r4;;3I3IJB!G ll#4#9#9!#<bAEEaHG"!II7R@;N L )FdN;@@CL5yG+el.BBG'*WQR[8F-4-@WK&(LfL0$#33!//))$55
 	
r   c                     UR                   nUc  UR                  U5      nUb  US S 2SS 24   nUUUUR                  SS 5      UR                  SS 5      SS.$ )Nr~   r  r  T)r   r  r  r  r  r  )r\   new_onesget)r   r   pastr  model_kwargsr   s         r4   prepare_inputs_for_generation-BertLMHeadModel.prepare_inputs_for_generation  su    
  oo!&//<N !!RS&)I 4d;5t<
 	
r   c                 P   ^ SnU H  nU[        U4S jU 5       5      4-  nM     U$ )Nr1   c              3   H   >#    U  H  nUR                  S T5      v   M     g7f)r   N)index_select)r2   
past_statebeam_idxs     r4   r5   1BertLMHeadModel._reorder_cache.<locals>.<genexpr>7  s(      %.",J ''844",s   ")r  )r   re  rm  reordered_past
layer_pasts     `  r4   _reorder_cacheBertLMHeadModel._reorder_cache4  s=    Ju %.",%.  . 1 1N  r   rE  )NNNNNNNNNNNNNNTr  r}  Nr   F)NN)r   r   r   r   "_keys_to_ignore_on_load_unexpectedr  r   r3  r9  r   rg  rq  r   r   r   s   @r4   rH  rH  ~  s    *3&4'#,6
 "#!+B
L ,059
: r   rH  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )GisBertLMPredictionHeadi=  c                    > [         TU ]  5         [        U5      U l        [        R
                  " UR                  USS9U l        [        R                  " [        R                  " U5      5      U l        U R                  U R                  l        g r  )r   r   r  r  r	   r   r   r  r  r_   r   r<   )r   rc   r   r   s      r4   r    GisBertLMPredictionHead.__init__?  sa    4V< yy!3!3ZeLLLZ!89	 !IIr   c                 J    U R                  U5      nU R                  U5      nU$ r   r  rP  s     r4   r   GisBertLMPredictionHead.forwardL  r  r   r  r1  r   s   @r4   ru  ru  =  s    & r   ru  c                   ~   ^  \ rS rSrS/rSS/rU 4S jr                         S	S jr S
S jrSr	U =r
$ )BertForGisMaskedLMiR  r  r|   rI  c                   > [         TU ]  U5        [        USS9U l        [	        XR
                  5      U l        [	        UUR                  5      U l        [	        UUR                  5      U l
        [	        XR                  5      U l        [	        XR                  5      U l        [	        XR                  5      U l        [	        XR                  5      U l        [	        XR"                  5      U l        [	        XR"                  5      U l        [	        XR(                  5      U l        [	        XR(                  5      U l        Xl        U R1                  5         g rK  )r   r   r  r  ru  r   cls_geom_idr   cls_geom_typer   cls_rel_typer   cls_absolute_position_x1cls_absolute_position_x2r   cls_absolute_position_y1cls_absolute_position_y2r   cls_relative_position_x1cls_relative_position_x2r   cls_relative_position_y1cls_relative_position_y2rc   r  r   s     r4   r   BertForGisMaskedLM.__init__Y  s$    f>	26;L;LM4V5;5K5KM3F4:4N4NP(?00)2%(?00)2%(?00)2%(?00)2%(?00)2%(?00)2%(?00)2%(?00)2%r   c                    Ub  UOU R                   R                  nU R                  UUUUUUUUU	UUUUUUUUS9nUS   nU R                  U5      n[	        5       nU" UR                  SU R                   R                  5      U
R                  S5      5      nU R                  U R                  U R                  U R                  U R                  U R                  U R                  U R                  U R                  U R                   /
nUUUSS2SS2S4   USS2SS2S4   USS2SS2S4   USS2SS2S4   USS2SS2S4   USS2SS2S4   USS2SS2S4   USS2SS2S4   /
n U R                   R"                  U R                   R$                  U R                   R&                  U R                   R&                  U R                   R(                  U R                   R(                  U R                   R*                  U R                   R*                  U R                   R,                  U R                   R,                  /
n![/        UU U!5       H?  u  n"n#n$U#c  M  U"" U5      n%UU" U%R                  SU$5      U#R                  S5      5      -  nMA     U(       d  U4USS -   n&Ub  U4U&-   $ U&$ [1        UUUR2                  UR4                  S9$ )	a  
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
sequence_length)`, `optional`):
    Labels for computing the masked language modeling loss. Indices
    should be in ``[-100, 0, ..., config.vocab_size]`` (see
    ``input_ids`` docstring) Tokens with indices set to ``-100`` are
    ignored (masked), the loss is only computed for the tokens with
    labels in ``[0, ..., config.vocab_size]``
Nr  r   r|   r  r   r!  r  r  r  r  r  r  r  r   r   r   r   r~   r@   rA   r   r  rW  r
  r  )rc   r  r  r}  r
   r   r   r~  r  r  r  r  r  r  r  r  r  r   r   r   r   r   r   rR   r   r
  r  )'r   r   r  r   r|   r  r   r!  r  r  r>  r  r  r  r  r  r[  r\  r]  r   r   r   token_type_ids_labelrel_type_ids_labelabsolute_position_ids_labelrelative_position_ids_labelr!  r  r  rA  rB  positions_clspositions_labelpositions_sizemyclsmylabelsmysizemyprediction_scoresr6  s'                                          r4   r   BertForGisMaskedLM.forwardu  s   L &1%<k$++B]B]))))%')"7#9/!5#!%"7"7#  
( "!* ,,_=#%!""2t{{'='=>KKO
  1 1))4+H+H))4+H+H))4+H+H))4+H+H
 !"4'1())* +,G1HIIJ -K'1())* +,G1HIIJ -K'1())* +,G1HIIJ -K'1())* +,G1HIIJ -K
  KK'')H)HKK--KK--KK--KK--KK--KK--KK--KK--

 (+=/+9(;#E8V#&+O&<#(',,R8(--:K#M M	(; '*WQR[8F!/!; $& HAGH $!//))	
 	
r   c                    UR                   nUS   nU R                  R                  c   S5       eUR                  UR                   S   S45      n[        R
                  " X&/SS9n[        R                  " US4U R                  R                  [        R                  UR                  S9n[        R
                  " X/SS9nXS.$ Nr   z.The PAD token should be defined for generationrA   r~   r   r   )r   r  	r\   rc   r   	new_zerosr_   r  fullr   r   r   r   r  rf  r   effective_batch_sizepadding_maskdummy_tokens           r4   rg  0BertForGisMaskedLM.prepare_inputs_for_generation  s      oo*1~ {{''3e5ee3%//1E1Ea1H!0LMN#ArJjj"6!:!%!9!9',zz(1(8(8: IIy6A>	&IIr   )r  r  r  r  r  r}  r~  r  r  r  r  r  rc   )NNNNNNNNNNNNNFr}  Nr   FNNNNNNNr   )r   r   r   r   rs  r  r   r   rg  r   r   r   s   @r4   r{  r{  R  s    *3&4'#< "#!""!$($(5v
t 6:J Jr   r{  c                      ^  \ rS rSrS/rSS/rU 4S jrS rS r                     SS jr	 SS	 jr
S
rU =r$ )BertForMaskedLMi  r  r|   rI  c                    > [         TU ]  U5        [        USS9U l        [	        U5      U l        U R                  5         g rK  rM  r   s     r4   r   BertForMaskedLM.__init__  rO  r   c                 B    U R                   R                  R                  $ r   r2  r   s    r4   r3  %BertForMaskedLM.get_output_embeddings  r5  r   c                 8    XR                   R                  l        g r   r2  r7  s     r4   r9  %BertForMaskedLM.set_output_embeddings  r;  r   c                 f   Ub  UOU R                   R                  nU R                  UUUUUUUUU	UUUUUUUUS9nUS   nU R                  U5      nU(       a  U$ SnU
bF  [	        5       nU" UR                  SU R                   R                  5      U
R                  S5      5      nUbP  [        R                  " [        R                  " USS9U-  SS9* nUU
S:g     R                  5       nSU-
  U-  UU-  -   nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S	9$ )
a  
labels (:obj:`torch.LongTensor` of shape :obj:`(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]``
Nr  r   r~   r   rV  rA   r@   r  )rc   r  r  r/  r
   r   r   r_   rX  rY  rZ  r  r   r
  r  )r   r   r  r   r|   r  r   r!  r  r  r>  r  r  r  r  r  r[  r\  r]  r   r   r   r!  r  r  rB  rA  r`  r6  s                                r4   r   BertForMaskedLM.forward  s   > &1%<k$++B]B]))))%')"7#9/!5#!%"7"7#  
( "!* HH_5$$')H%!&&r4;;+A+ABB!N "!II/R8;FBP PL'$7<<>L %&)78:?,:NON '*WQR[8F!/!; $& HAGH $!//))	
 	
r   c                    UR                   nUS   nU R                  R                  c   S5       eUR                  UR                   S   S45      n[        R
                  " X&/SS9n[        R                  " US4U R                  R                  [        R                  UR                  S9n[        R
                  " X/SS9nXS.$ r  r  r  s           r4   rg  -BertForMaskedLM.prepare_inputs_for_generationk  s      oo*1~ {{''3e5ee3%//1E1Ea1H!0LMN#ArJjj"6!:!%!9!9',zz(1(8(8: IIy6A>	&IIr   rE  )NNNNNNNNNNNNNFr}  Nr   FNNNr   )r   r   r   r   rs  r  r   r3  r9  r   rg  r   r   r   s   @r4   r  r    s    *3&4'#,6
 "#!""-S
n 6:J Jr   r  c                   F   ^  \ rS rSrU 4S jr          SS jrSrU =r$ )BertForNextSentencePredictioni  c                    > [         TU ]  U5        [        U5      U l        [	        U5      U l        U R                  5         g r   )r   r   r  r  r  r/  r  r   s     r4   r   &BertForNextSentencePrediction.__init__  s4     f%	"6*r   c                 v   U
b  U
OU R                   R                  n
U R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nSnUb2  [	        5       nU" UR                  SS5      UR                  S5      5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S9$ )u7  
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
    Labels for computing the next sequenåce prediction (classification) loss. Input should be a sequence pair
    (see ``input_ids`` docstring). Indices should be in ``[0, 1]``:
    - 0 indicates sequence B is a continuation of sequence A,
    - 1 indicates sequence B is a random sequence.
Returns:

Example:
    >>> from transformers import BertTokenizer, BertForNextSentencePrediction
    >>> import torch
    >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
    >>> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')
    >>> 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
Nr=  rA   r~   r@   r  )	rc   r  r  r/  r
   r   r   r
  r  )r   r   r  r   r|   r  r   r>  r  r  r  kwargsr!  r  seq_relationship_scoresrC  rA  r6  s                     r4   r   %BertForNextSentencePrediction.forward  s   B &1%<k$++B]B]))))%'/!5#  

  
"&((="9!')H!)',,R3V[[_"F -0712;>F!3!? (* LEKL +#*!//))	
 	
r   rE  
NNNNNNNNNNr1  r   s   @r4   r  r    s4     ##!""&%) C
 C
r   r  c                   F   ^  \ rS rSrU 4S jr          SS jrSrU =r$ )BertForSequenceClassificationi  c                 0  > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  5      U l        [
        R                  " UR                  UR                  5      U l        U R                  5         g r   r   r   
num_labelsr  r  r	   r   r   r   r   r   r?   r  r   s     r4   r   &BertForSequenceClassification.__init__  si      ++f%	zz&"<"<=))F$6$68I8IJr   c                 0   U
b  U
OU R                   R                  n
U R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nU R	                  U5      nSnUb~  U R
                  S:X  a2  [        5       nU" UR                  S5      UR                  S5      5      nO<[        5       nU" UR                  SU R
                  5      UR                  S5      5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S9$ )a~  
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
    Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
    config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
    If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Nr=  rA   r~   r@   r  )rc   r  r  r   r?   r  r   r   r
   r   r
  r  )r   r   r  r   r|   r  r   r>  r  r  r  r!  r  rW  r  rA  r6  s                    r4   r   %BertForSequenceClassification.forward  s+   & &1%<k$++B]B]))))%'/!5#  

  
]3/!#"9BRA+-KKDOO4fkk"oG Z'!"+-F*.*:THv%FF'!//))	
 	
r   r  r?   r   r  r  r1  r   s   @r4   r  r    s2     !:
 :
r   r  c                   F   ^  \ rS rSrU 4S jr          SS jrSrU =r$ )BertForMultipleChoicei  c                    > [         TU ]  U5        [        U5      U l        [        R
                  " UR                  5      U l        [        R                  " UR                  S5      U l
        U R                  5         g )NrA   )r   r   r  r  r	   r   r   r   r   r   r?   r  r   s     r4   r   BertForMultipleChoice.__init__  sV     f%	zz&"<"<=))F$6$6:r   c                 Z   U
b  U
OU R                   R                  n
Ub  UR                  S   OUR                  S   nUb!  UR                  SUR	                  S5      5      OSnUb!  UR                  SUR	                  S5      5      OSnUb!  UR                  SUR	                  S5      5      OSnUb!  UR                  SUR	                  S5      5      OSnUb1  UR                  SUR	                  S5      UR	                  S5      5      OSnU R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nU R                  U5      nUR                  SU5      nSnUb  [        5       nU" X5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S9$ )a<  
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
`optional`):
    Labels for computing the multiple choice classification loss.
    Indices should be in ``[0, ..., num_choices-1]`` where
    :obj:`num_choices` is the size of the second dimension of the input
    tensors. (See :obj:`input_ids` above)
NrA   r~   r   r=  r@   r  )rc   r  r\   r   r   r  r   r?   r
   r   r
  r  )r   r   r  r   r|   r  r   r>  r  r  r  num_choicesr!  r  rW  reshaped_logitsr  rA  r6  s                      r4   r   BertForMultipleChoice.forward$  s   * &1%<k$++B]B]'  oo-:-@-@-C 	 (1'< NN	r"$BF 	 )7(B (,,#%HL 	
 )7(B (,,#%HL 	 +7*B $((!!"%'HL 	
 ( r=#5#5b#9,11"57.2 	
 ))))%'/!5#  

  
]3/ ++b+6')HO4D%(712;6F*.*:THv%FF("!//))	
 	
r   )r  r?   r   r  r1  r   s   @r4   r  r    s4     !H
 H
r   r  c                   L   ^  \ rS rSrS/rU 4S jr          SS jrSrU =r$ )BertForTokenClassificationio  r  c                 .  > [         TU ]  U5        UR                  U l        [        USS9U l        [
        R                  " UR                  5      U l        [
        R                  " UR                  UR                  5      U l        U R                  5         g rK  r  r   s     r4   r   #BertForTokenClassification.__init__s  sk      ++f>	zz&"<"<=))F$6$68I8IJr   c                    U
b  U
OU R                   R                  n
U R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nU R	                  U5      nSnUb  [        5       nUb  UR                  S5      S:H  nUR                  SU R                  5      n[        R                  " UUR                  S5      [        R                  " UR                  5      R                  U5      5      nU" UU5      nO2U" UR                  SU R                  5      UR                  S5      5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S9$ )z
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
sequence_length)`, `optional`):
    Labels for computing the token classification loss. Indices should
    be in ``[0, ..., config.num_labels - 1]``.
Nr=  r   r~   rA   r@   r  )rc   r  r  r   r?   r
   r   r  r_   wheretensorignore_indextype_asr   r
  r  )r   r   r  r   r|   r  r   r>  r  r  r  r!  r  rW  r  rA  active_lossactive_logitsactive_labelsr6  s                       r4   r   "BertForTokenClassification.forward}  sr   & &1%<k$++B]B]))))%'/!5#  

 "!*,,71')H),11"5: &B @ %RLL!6!67??G!I  }=KKDOO4fkk"oG Z'!"+-F*.*:THv%FF$!//))	
 	
r   r  r  	r   r   r   r   rs  r   r   r   r   r   s   @r4   r  r  o  s:    *3& !>
 >
r   r  c                   N   ^  \ rS rSrS/rU 4S jr           SS jrSrU =r$ )BertForQuestionAnsweringi  r  c                    > [         TU ]  U5        UR                  U l        [        USS9U l        [
        R                  " UR                  UR                  5      U l        U R                  5         g rK  )
r   r   r  r  r  r	   r   r   
qa_outputsr  r   s     r4   r   !BertForQuestionAnswering.__init__  sU      ++f>	))F$6$68I8IJr   c                    Ub  UOU R                   R                  nU R                  UUUUUUU	U
US9	nUS   nU R                  U5      nUR	                  SSS9u  nnUR                  S5      nUR                  S5      nSnUb  Ub  [        UR                  5       5      S:  a  UR                  S5      n[        UR                  5       5      S:  a  UR                  S5      nUR                  S5      nUR                  SU5        UR                  SU5        [        US9nU" X5      nU" UU5      nUU-   S-  nU(       d  UU4USS -   nUb  U4U-   $ U$ [        UUUUR                  UR                  S	9$ )
a  
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
`optional`):
    Labels for position (index) of the start of the labelled span for
    computing the token classification loss. Positions are clamped to
    the length of the sequence (:obj:`sequence_length`). Position
    outside of the sequence are not taken into account for computing the
    loss.
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
`optional`):
    Labels for position (index) of the end of the labelled span for
    computing the token classification loss. Positions are clamped to
    the length of the sequence (:obj:`sequence_length`). Position
    outside of the sequence are not taken into account for computing the
    loss.
Nr=  r   rA   r~   r   )r  r@   )r  start_logits
end_logitsr
  r  )rc   r  r  r  rS   squeezerY   r   clamp_r
   r   r
  r  )r   r   r  r   r|   r  r   start_positionsend_positionsr  r  r  r!  r  rW  r  r  r@  ignored_indexrA  
start_lossend_lossr6  s                          r4   r    BertForQuestionAnswering.forward  s   < &1%<k$++B]B]))))%'/!5#  

 "!*1#)<<r<#: j#++B/''+

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M""1m4  M2']CH!,@J
M:H$x/14J"J/'!"+=F!+!7  N D=CD ,%!!//))
 	
r   )r  r  r  rF  r  r   s   @r4   r  r    s?    *3& !O
 O
r   r  c                   d   ^  \ rS rSrSr\rSrSrS/r	U 4S jr
S rSS jr\U 4S	 j5       rS
rU =r$ )MGeoPreTrainedModeli	  r  r  Tr|   c                 b   > [         TU ]  " UR                  40 UD6  [         [        U ]  U5        g r   )r   r   name_or_pathr   )r   rc   r  r   s      r4   r   MGeoPreTrainedModel.__init__(	  s*    ,,77eT#F+r   c                    [        U[        R                  5      (       ak  UR                  R                  R                  SU R                  R                  S9  UR                  b%  UR                  R                  R                  5         gg[        U[        R                  5      (       ax  UR                  R                  R                  SU R                  R                  S9  UR                  b2  UR                  R                  UR                     R                  5         gg[        U[        R                  5      (       aJ  UR                  R                  R                  5         UR                  R                  R                  S5        gg)zInitialize the weightsr  r  Nr  )rI  r	   r   r9   ra   r  rc   r  r<   r  r   rx   r   r  r  s     r4   r  !MGeoPreTrainedModel._init_weights,	  s   fbii(( MM&&dkk;; ' ={{&  &&( '--MM&&dkk;; ' =!!-""6#5#56<<> .--KK""$MM$$S) .r   c                 <    [        U[        5      (       a  X!l        g g r   )rI  rr  r~  )r   r  r   s      r4   _set_gradient_checkpointing/MGeoPreTrainedModel._set_gradient_checkpointing>	  s    fk**,1) +r   c                    > UR                  SS5      nUR                  SS5      n[        X#40 UD6nUc  [        S0 UD6nU " U5      nO[        [        U ]  " SSU0UD6nX&l        U$ )ah  Instantiate the model.

Args:
    kwargs: Input args.
            model_dir: The model dir used to load the checkpoint and the
            label information. num_labels: An optional arg to tell the
            model how many classes to initialize.
                            Method will call utils.parse_label_mapping
                            if num_labels not supplied. If num_labels is
                            not found, the model will use the default
                            setting (2 classes).

Returns:
    The loaded model, which is initialized by
    transformers.PreTrainedModel.from_pretrained
	model_dirNcfgpretrained_model_name_or_pathr1   )popr$   r   r   r   from_pretrainedr  )r/  r  r  r  
model_argsrc   rb   r   s          r4   _instantiate MGeoPreTrainedModel._instantiateB	  s~    & JJ{D1	jj%*9DVD
-*-FKE%5 G.7G;EGE#r   r1   rD  )r   r   r   r   r   r   r  r  supports_gradient_checkpointingr  r   r  r  classmethodr  r   r   r   s   @r4   r  r  	  sG    
 L&*#'6&7#,*$2  r   r  )module_namec                   ~   ^  \ rS rSr   S
S\S\S\4U 4S jjjr                   SS jrS r	S r
S	rU =r$ )MGeoib	  rc   finetune_modegis_numc                   > [         TU ]  U5        X l        Xl        [	        XS9U l        U R                  S:X  a  [        R                  " UR                  5      n[	        USS9U l        U R                  R                  5        H
  nSUl
        M     [        R                  " UR                  U R                  R                  5      U l        [        R                  " X6R                  5      U l        U R#                  5         g )NrL  multi-modalF)r   r   r  rc   r  text_encoderr   	from_dictgis_encoder
parametersrequires_gradr	   r   r   gis2textr   gis_typer  )	r   rc   r  r  r  r  
gis_configparamr   s	           r4   r   MGeo.__init__e	  s     	 *%9 .#--f.@.@AJ(uMD))446&+# 7IIj&<&<&*kk&=&=?DMLL2H2HIDMr   c           	         U R                   S:X  aa  Ub^  [        U5      S:  aO  / n/ nU HE  nUR                  U R                  " SSSS.UD6R                  5        UR                  US   5        MG     U(       a  U R
                  R                  UUUS9nOU R
                  R                  US9nU R                   S:X  a  Ub  [        U5      S:  a  U/nU/nU Vs/ s H  nU R                  U5      PM     nn[        WWU5       H;  u  nnnUR                  U R                  UU-   5      5        UR                  U5        M=     [        R                  " US	S
9n[        R                  " USS
9n OUnUn U R                  U UUUUSS9n!U(       d  U!$ [        U!R                  U!R                  U!R                  U!R                  U!R                   U!R"                  S9$ s  snf )Nr  r   Tr{  )r  r  r  )r   r|   r   )r   rA   r   r~   )r  r!  r  r  r  r  r  r1   )r  rY   rQ   r  r  r  r   r  rR   r  r_   r  r"   r  r  r
  r  r  r6  )"r   r   r  r   r|   r  r   r!  r  r  r  r  r  r  r  r  r  gis_listgis_tpuse_token_typegis_embsgis_attsgisr(  embsattsgtptp_embgegagt	merge_embmerge_attentionr)  s"                                     r4   r   MGeo.forward~	  s   ( .83GCMMHH$$ ,F ,'*,,=,=? $4 56	  
 #00;;#)-  <    $00;;#  <  ' .83GCMM$%D"#D4:;FSdmmC(FF;!(Hf=
BDMM"r'23B > 		$A.I#ii"5O(I,O++*$/!5# ,  ""+-??)77+;;)77&11,==
 	
) <s   Gc                     US   $ )Nr  r1   r   r!  s     r4   extract_sequence_outputsMGeo.extract_sequence_outputs	  s    *++r   c                     US   $ )Nr  r1   r  s     r4   extract_pooled_outputsMGeo.extract_pooled_outputs	  s    ''r   )rc   r  r  r  r  r  )single-modalrA   F)NNNNNNNNNNNNNNFr$  NNF)r   r   r   r   r   rK  rZ   r   r   r  r"  r   r   r   s   @r4   r  r  b	  s    
 '5 !#(	# #  4 ##!"#&*'+ $"&%)  #$'GR,( (r   r  )gr  rI   randomwarningsdataclassesr   typingr   r   r_   torch.nn.functionalr	   
functionalrY  torch.utils.checkpointtransformersr   r   r   torch.nnr
   r   transformers.activationsr   transformers.file_utilsr   r   r   r   r   transformers.modeling_outputsr   r   r   r   r   r   r   r   r   transformers.modeling_utilsr   +transformers.models.bert.configuration_bertr   transformers.utilsr   modelscope.metainfor   modelscope.modelsr   r    modelscope.models.builderr!   modelscope.outputsr"   modelscope.utils.constantr#   modelscope.utils.nlp.utilsr$   modelscope.utils.torch_utilsr%   r&   r'   set_verbosity_error
get_loggerrG   _CONFIG_FOR_DOC_TOKENIZER_FOR_DOCrr   Modulert   r   r   r%  r4  rF  rS  rY  rr  r  r  r  r  r  r  r  r  r  r-  rH  ru  r{  r  r  r  r  r  r  r  register_modulebackbonemgeor  r1   r   r4   <module>rC     s    	   ! "      + + . +@ @   8 B & & / , ; + <> >    ( ( *				$ GTjBII jZCRYY CLW		 WtRYY  1BII 1hryy    X		 Xvr
")) r
j  ")) &299 ,!bii !&bii &
9299 
9%/ %2 $:{ $: $:NC
# C
L]
, ]
@|) |~bii *lJ, lJ^|J) |J~M
$7 M
`F
$7 F
RS
/ S
lL
!4 L
^\
2 \
~B*o BJ FKK@h( h( Ah(r   