
    9i                        S r SSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SSK	J
r
  SSK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KJr  SSKJrJrJr  SSKJr  \" 5       rSr " S S\R@                  5      r! " S S\R@                  5      r" " S S\R@                  5      r# " S S\R@                  5      r$ " S S\R@                  5      r% " S S\R@                  5      r& " S S\R@                  5      r' " S S \R@                  5      r( " S! S"\R@                  5      r) " S# S$\\5      r*\RV                  " \RX                  \
RZ                  S%9 " S& S'\*5      5       r.g)(zPyTorch MegatronBERT model.    N)nn)ACT2FN)PreTrainedModel)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)
get_logger)parse_labels_in_order)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer   )MegatronBertConfigr   c                   \   ^  \ rS rSrSrU 4S jr     SS\R                  4S jjrSr	U =r
$ )MegatronBertEmbeddings+   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                  5      U l        U R                  S[         R"                  " UR                  5      R%                  S5      5        ['        USS5      U l        g )N)padding_idxposition_ids)r   position_embedding_typeabsolute)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddingsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandgetattrr   selfconfig	__class__s     l/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/megatron_bert/backbone.pyr   MegatronBertEmbeddings.__init__.   s    !||++ - $&<<0N0N060B0B$D %'\\&2H2H282D2D&F" zz&"<"<= 	LL778??H	J (/v/H/9(;$    returnc                    Ub  UR                  5       nOUR                  5       S S nUS   nUc  U R                  S S 2XWU-   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XH-   n	U R                  S:X  a  U R                  U5      n
X-  n	U R                  U	5      n	U	$ )Nr   r   dtypedevicer   )sizer   r+   zeroslongr:   r"   r&   r   r$   r)   )r0   	input_idstoken_type_idsr   inputs_embedspast_key_values_lengthinput_shape
seq_lengthr&   
embeddingsr$   s              r3   forwardMegatronBertEmbeddings.forwardH   s     #..*K',,.s3K ^
,,Q-C/EEF .F.F GL !"[[5::d6G6G6N6NPN   00;M $ : :> J":
'':5"&":":<"H-J \\*-
r5   )r)   r   r$   r&   r"   )NNNNr   )__name__
__module____qualname____firstlineno____doc__r   r+   TensorrE   __static_attributes____classcell__r2   s   @r3   r   r   +   s4    Q;8  $ 
$ $r5   r   c                   |   ^  \ rS rSrSU 4S jjrS\R                  S\R                  4S jr      S	S jrSr	U =r
$ )
MegatronBertSelfAttentionp   c                   > [         TU ]  5         UR                  UR                  -  S:w  a7  [	        US5      (       d&  [        SUR                   SUR                   S3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        [        R                  " UR                  U R                  5      U l        [        R                  " UR                  U R                  5      U l        [        R                  " UR                  5      U l        U=(       d    [#        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        UR,                  U l        g )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r   r   relative_keyrelative_key_query   r   )r   r   r    num_attention_headshasattr
ValueErrorintattention_head_sizeall_head_sizer   Linearquerykeyvaluer'   attention_probs_dropout_probr)   r.   r   r#   r   distance_embedding
is_decoder)r0   r1   r   r2   s      r3   r   "MegatronBertSelfAttention.__init__r   s    : ::a?(I* I*#F$6$6#7 8 445Q89 9 $*#=#= #&v'9'9)/)C)C(D $E !558P8PPYYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF'> (;'-zC;$''>9T=Y=Y]q=q+1+I+ID(&(llF222Q6(('*D# !++r5   xr6   c                     UR                  5       S S U R                  U R                  4-   nUR                  U5      nUR	                  SSSS5      $ )Nr   r   rX   r      )r;   rY   r]   viewpermute)r0   rg   new_x_shapes      r3   transpose_for_scores.MegatronBertSelfAttention.transpose_for_scores   sS    ffhsmt'?'?'+'?'?'A AFF;yyAq!$$r5   c                    U R                  U5      nUS Ln	U	(       a  Ub  US   n
US   nUnGO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U R                  (       a  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[.        R0                  R3                  USS9nU R5                  U5      nUb  UU-  n[        R                  " UU5      nUR7                  SSSS5      R9                  5       nUR                  5       S S U R:                  4-   nUR                  U5      nU(       a  UU4OU4nU R                  (       a  UU4-   nU$ )Nr   r   rX   dimr   rV   rW   r8   )r9   zbhld,lrd->bhlrzbhrd,lrd->bhlrri   )r`   rm   ra   rb   r+   catre   matmul	transposer   r;   r,   r=   r:   rj   rd   r#   tor9   einsummathsqrtr]   r   
functionalsoftmaxr)   rk   
contiguousr^   )r0   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsmixed_query_layeris_cross_attention	key_layervalue_layerquery_layerattention_scoresrC   position_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapeoutputss                             r3   rE   !MegatronBertSelfAttention.forward   s    !JJ}5
 3$>."<&q)I(+K3N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?? (5N !<<(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$$/& &%/@ --//0@b/I ,,7  -	9O_kB%--aAq9DDF"/"4"4"6s";?" #"%**+BC (9 !"$?L>O 	 ?? 22Gr5   )r^   r]   rd   r)   re   ra   r#   rY   r   r`   rb   NNNNNNF)rG   rH   rI   rJ   r   r+   rL   rm   rE   rM   rN   rO   s   @r3   rQ   rQ   p   sC    ,8%ell %u|| % "#k kr5   rQ   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MegatronBertSelfOutputi  c                    > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " UR                  5      U l        g r   )	r   r   r   r_   r    denser'   r(   r)   r/   s     r3   r   MegatronBertSelfOutput.__init__  sB    YYv1163E3EF
zz&"<"<=r5   c                 N    U R                  U5      nU R                  U5      nX!-   $ r   r   r)   )r0   r}   residuals      r3   rE   MegatronBertSelfOutput.forward
  s'    

=1]3''r5   r   rG   rH   rI   rJ   r   rE   rM   rN   rO   s   @r3   r   r     s    >
( (r5   r   c                   D   ^  \ rS rSrU 4S jrS r      SS jrSrU =r$ )MegatronBertAttentioni  c                    > [         TU ]  5         [        R                  " UR                  UR
                  S9U l        [        U5      U l        [        U5      U l
        [        5       U l        g )Neps)r   r   r   	LayerNormr    layer_norm_epslnrQ   r0   r   outputsetpruned_headsr/   s     r3   r   MegatronBertAttention.__init__  sN    ,,v11v7L7LM-f5	,V4Er5   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   r   rp   )lenr   r0   rY   r]   r   r   r`   ra   rb   r   r   r^   union)r0   headsindexs      r3   prune_heads!MegatronBertAttention.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:r5   c           	          U R                  U5      n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   r   )r   r0   r   )r0   r}   r~   r   r   r   r   r   
ln_outputsself_outputsattention_outputr   s               r3   rE   MegatronBertAttention.forward-  sj     WW]+
yy!"
  ;;|AF# #AB'(r5   )r   r   r   r0   r   )	rG   rH   rI   rJ   r   r   rE   rM   rN   rO   s   @r3   r   r     s+    ";, "# r5   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MegatronBertIntermediateiH  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     r3   r   !MegatronBertIntermediate.__init__J  s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$r5   c                 J    U R                  U5      nU R                  U5      nU$ r   r   r   )r0   r}   s     r3   rE    MegatronBertIntermediate.forwardR  s&    

=100?r5   r   r   rO   s   @r3   r   r   H  s    9 r5   r   c                   z   ^  \ rS rSrU 4S jrS\R                  S\R                  S\R                  4S jrSrU =r	$ )MegatronBertOutputiY  c                    > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        [        R                  " UR                  5      U l	        g r   )
r   r   r   r_   r   r    r   r'   r(   r)   r/   s     r3   r   MegatronBertOutput.__init__[  sB    YYv779K9KL
zz&"<"<=r5   r}   input_tensorr6   c                 N    U R                  U5      nU R                  U5      nX!-   $ r   r   )r0   r}   r   s      r3   rE   MegatronBertOutput.forward`  s'    

=1]3++r5   r   )
rG   rH   rI   rJ   r   r+   rL   rE   rM   rN   rO   s   @r3   r   r   Y  s5    >
,U\\ ,#ll,/4||, ,r5   r   c                   D   ^  \ rS rSrU 4S jr      SS jrS rSrU =r$ )MegatronBertLayerih  c                   > [         TU ]  5         UR                  U l        SU l        [	        U5      U l        UR                  U l        UR                  U l        U R                  (       a/  U R                  (       d  [        U  S35      e[	        U5      U l	        [        R                  " UR                  UR                  S9U l        [        U5      U l        [#        U5      U l        g )Nr   z> should be used as a decoder model if cross attention is addedr   )r   r   chunk_size_feed_forwardseq_len_dimr   	attentionre   add_cross_attention	TypeErrorcrossattentionr   r   r    r   r   r   intermediater   r   r/   s     r3   r   MegatronBertLayer.__init__j  s    '-'E'E$.v6 ++#)#=#= ##??fZ[  #8"?D,,v11v7L7LM4V<(0r5   c           	         Ub  US S OS nU R                  UUUUUS9n	U	S   n
U R                  (       a  U	SS nU	S   nOU	SS  nS nU R                  (       aZ  UbW  [        U S5      (       d  [        SU  S35      eUb  US	S  OS nU R	                  U
UUUUUU5      nUS   n
XSS -   nUS   nWU-   n[        U R                  U R                  U R                  U
5      nU4U-   nU R                  (       a  UW4-   nU$ )
NrX   )r   r   r   r   r   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`rr   )	r   re   rZ   AttributeErrorr   r   feed_forward_chunkr   r   )r0   r}   r~   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputs                    r3   rE   MegatronBertLayer.forward{  s    9G8R $2 3423$5X\ 	!!%/3 "0 "
 2!4 ??,Qr2G 6r :,G (,$??4@4!122$=dV DD DE E '2 )7)8< &&*&9&9 %&)!'#  7q9"! G ,C2+F( 14P P01H1H151M1M151A1A1AC  "W, ??!2 55Gr5   c                 l    U R                  U5      nU R                  U5      nU R                  X15      nU$ r   )r   r   r   )r0   r   	ln_outputintermediate_outputr   s        r3   r   $MegatronBertLayer.feed_forward_chunk  s7    GG,-	"//	:{{#6Ir5   )	r   r   r   r   r   re   r   r   r   r   )	rG   rH   rI   rJ   r   rE   r   rM   rN   rO   s   @r3   r   r   h  s-    1( "#CJ r5   r   c                   D   ^  \ rS rSrU 4S jr         SS jrSrU =r$ )MegatronBertEncoderi  c                 2  > [         TU ]  5         Xl        [        R                  " [        UR                  5       Vs/ s H  n[        U5      PM     sn5      U l        [        R                  " UR                  UR                  S9U l        SU l        g s  snf )Nr   F)r   r   r1   r   
ModuleListrangenum_hidden_layersr   layerr   r    r   r   gradient_checkpointing)r0   r1   _r2   s      r3   r   MegatronBertEncoder.__init__  sy    ]]/4V5M5M/N$
/N!f%/N$
 
 ,,v11v7L7LM&+#$
s   Bc           
      N  ^^ 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 R                  5       H  u  nnU	(       a  X4-   nUb  X?   OS nUb  UU   OS mU R                  (       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U R                   R                  (       d  M  UUS   4-   nM     U R                  U5      nU	(       a  X4-   nU
(       d  [        S	 UUUUU4 5       5      $ [        UUUUUS
9$ )N zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    >^  U UU4S jnU$ )Nc                     > T" / U QTPTP76 $ r   r   )inputsmoduler   r   s    r3   custom_forwardRMegatronBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forward  s&    %  9v  9~  9&7 9 9r5   r   )r   r   r   r   s   ` r3   create_custom_forward:MegatronBertEncoder.forward.<locals>.create_custom_forward  s    9 *)r5   r   r   r   rX   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r   ).0vs     r3   	<genexpr>.MegatronBertEncoder.forward.<locals>.<genexpr>'  s"        %q   %s   	)last_hidden_statepast_key_valuesr}   
attentionscross_attentions)r1   r   	enumerater   r   trainingloggerwarningr+   utils
checkpointr   tupler
   )r0   r}   r~   r   r   r   r  	use_cacher   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputsr   s           `           @r3   rE   MegatronBertEncoder.forward  s    #7BD$5b44;;#B#B 
HL 	 $-R$(4OA|#$58I$I!.7.CilO%1 -7;  **t}}NNt !&I* !& 6 6 A A),7!"#)*! !-!"#)*"%! *!,M"}R'8&;;"  &9!!$=( '(#;;222+?%a(C, ,,(k  5r . 14E E  "!#$%       ,+.+*1
 	
r5   )r1   r   r   r   )	NNNNNNFFTr   rO   s   @r3   r   r     s1    
, "#"_
 _
r5   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MegatronBertPooleri8  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     r3   r   MegatronBertPooler.__init__:  s9    YYv1163E3EF
'')r5   c                 \    US S 2S4   nU R                  U5      nU R                  U5      nU$ )Nr   )r   r  )r0   r}   first_token_tensorpooled_outputs       r3   rE   MegatronBertPooler.forward?  s6     +1a40

#566r5   )r  r   r   rO   s   @r3   r  r  8  s    $
 r5   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$ )MegatronBertPreTrainedModeliH  zz
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
bertTr   c                 b   > [         TU ]  " UR                  40 UD6  [         [        U ]  U5        g r   )r   r   name_or_pathr   )r0   r1   kwargsr2   s      r3   r   $MegatronBertPreTrainedModel.__init__S  s*    ,,77eT#F+r5   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 weightsg        )meanstdg      ?N)r   r   r_   r   weightdatanormal_r1   initializer_ranger   biaszero_fill_)r0   r   s     r3   _init_weights)MegatronBertPreTrainedModel._init_weightsW  s    fryy",,788 MM&&dkk;; ' =--KK""$MM$$S)fbii((V[[-DKK""$ .E(r5   c                 <    [        U[        5      (       a  X!l        g g r   )r   r   r   )r0   r   rb   s      r3   _set_gradient_checkpointing7MegatronBertPreTrainedModel._set_gradient_checkpointingd  s    f122,1) 3r5   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$ )a   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_pathr   )popr   r   r   r   from_pretrainedr8  )clsr&  r8  r9  
model_argsr1   modelr2   s          r3   _instantiate(MegatronBertPreTrainedModel._instantiateh  s~     JJ{D1	jj%*9DVD
'5*5FKE%5 G.7G;EGE#r5   r   )F)rG   rH   rI   rJ   rK   r   config_classbase_model_prefixsupports_gradient_checkpointing_keys_to_ignore_on_load_missingr   r2  r5  classmethodr@  rM   rN   rO   s   @r3   r"  r"  H  sG    
 &L&*#'6&7#,%2  r5   r"  )	group_keymodule_namec                   n   ^  \ rS rSrSrS
U 4S jjrS rS rS r             SS\	4S jjr
S	rU =r$ )MegatronBertModeli  ah  The bare MegatronBert 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 ([`MegatronBertConfig`]): 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5      U l        [        U5      U l        U(       a  [        U5      OS U l        U R                  5         g r   )
r   r   r1   r   rD   r   encoderr  pooler	post_init)r0   r1   add_pooling_layerr2   s      r3   r   MegatronBertModel.__init__  sJ     08*624E(04 	r5   c                 .    U R                   R                  $ r   rD   r"   )r0   s    r3   get_input_embeddings&MegatronBertModel.get_input_embeddings  s    ...r5   c                 $    XR                   l        g r   rR  )r0   rb   s     r3   set_input_embeddings&MegatronBertModel.set_input_embeddings  s    */'r5   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)itemsrL  r   r   r   )r0   heads_to_pruner   r   s       r3   _prune_headsMegatronBertModel._prune_heads  s<    
 +002LELLu%//;;EB 3r5   r6   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 R                   R                  (       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O"Ub  UR                  5       SS nO[        S5      eUu  nnUb  UR                  OUR                  n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                  X/U5      nU R                   R                  (       aE  UbB  UR                  5       u  nnnUU4nUc  [        R                  " UUS9nU R                  U5      nOSnU R!                  UU R                   R"                  5      nU R%                  UUUUUS
9nU R'                  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R.                  UR0                  UR2                  S9$ )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   z5You have to specify either input_ids or inputs_embedsr   rX   )r:   r8   )r>   r   r?   r@   rA   )	r~   r   r   r   r  r  r   r  r  r   )r   pooler_outputr  r}   r  r  )r1   r   r  use_return_dictre   r  r[   r;   r:   shaper+   onesr<   r=   get_extended_attention_maskinvert_attention_maskget_head_maskr   rD   rL  rM  r
   r  r}   r  r  )r0   r>   r~   r?   r   r   r@   r   r   r  r  r   r  r  r&  rB   
batch_sizerC   r:   rA   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputr  s                                 r3   rE   MegatronBertModel.forward  s   H 2C1N-TXT_T_TqTq$8$D KK,, 	 &1%<k$++B]B];;!!%.%:	@U@UII ]%>V  "#..*K&',,.s3KGI I "-
J%.%:!!@T@T "- "1!3A!6!<!<"34 	 !"ZZj+AABN !"[[5::f>N
 150P0P11
 ;;!!&;&G=R=W=W >: 7$6$;$= %-).(*9&.2.H.H&/(+ /3+ &&y'+{{'D'DF	  ??%)'#9 + 
 ,,2"7#B+/!5# ' 
 *!, $ 7 =A 	 #]3oab6III+-'+;;)77&11,==
 	
r5   )r1   rD   rL  rM  )T)NNNNNNNNNNNNN)rG   rH   rI   rJ   rK   r   rS  rV  r[  r
   rE   rM   rN   rO   s   @r3   rJ  rJ    s]    2
/0C ##!"&*'+ $"&%) G
 :G
 G
r5   rJ  )/rK   rx   r+   torch.utils.checkpointr   transformers.activationsr   transformers.modeling_utilsr   modelscope.metainfor   modelscope.modelsr   r   modelscope.models.builderr	   modelscope.outputsr
   modelscope.utils.constantr   modelscope.utils.loggerr   modelscope.utils.nlp.utilsr   modelscope.utils.torch_utilsr   r   r   configurationr   r  _CONFIG_FOR_DOCModuler   rQ   r   r   r   r   r   r   r  r"  register_modulebackbonemegatron_bertrJ  r   r5   r3   <module>r     s3    #     + 7 & / , ; + . <> > .	&ARYY AJO		 Of
(RYY 
(3BII 3nryy ", ,\		 \~m
")) m
b  9*o 9x nn&*>*>@{
3 {
@{
r5   