
    9i                     
   S 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	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 S\	RN                  5      r( " S S\	RN                  5      r) " S S\	RN                  5      r* " S S\	RN                  5      r+ " S S\	RN                  5      r, " S S\	RN                  5      r- " S S\	RN                  5      r. " S  S!\	RN                  5      r/ " S" S#\	RN                  5      r0 " S$ S%\\5      r1\ " S& S'\5      5       r2\Rf                  " \Rh                  \Rj                  S(9 " S) S*\15      5       r6g)+zRPyTorch StructBERT model. mainly copied from :module:`~transformers.modeling_bert`    N)	dataclass)OptionalUnion)version)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   )SbertConfigc                   B   ^  \ rS rSrSrU 4S jr      SS jrSrU =r$ )SbertEmbeddings-   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SS5      U l        U R'                  S[(        R*                  " UR                  5      R-                  S5      5        [.        R0                  " [(        R2                  5      [.        R0                  " S5      :  a`  U R'                  S[(        R4                  " U R6                  R9                  5       [(        R:                  U R6                  R<                  S	9S
S9  g g )N)padding_idxepsposition_embedding_typeabsoluteposition_ids)r   z1.6.0token_type_idsdtypedeviceF)
persistent)super__init__nn	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutgetattrr   register_buffertorcharangeexpandr   parse__version__zerosr   sizelongr$   selfconfig	__class__s     i/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/structbert/backbone.pyr'   SbertEmbeddings.__init__0   sx   !||++ - $&<<0N0N060B0B$D %'\\&2H2H282D2D&F"
 F$9$9;zz&"<"<='.v/H/9(;$ 	LL778??H	J ==**+gmmG.DD   %%**,**,,335 ! !  E    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XXU-   24   nUcv  [        U S5      (       a-  U R                  S S 2S U24   n	U	R	                  US   U5      n
U
nO8[
        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(       d  U$ X4$ )Nr    r   r!   r   r"   r   )r?   r   hasattrr!   r;   r9   r>   r@   r$   r-   r1   r   r/   r2   r6   )rB   	input_idsr!   r   inputs_embedspast_key_values_lengthreturn_inputs_embedsinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr1   
embeddingsr/   s                 rE   forwardSbertEmbeddings.forwardQ   sa     #..*K',,.s3K ^
,,Q-C/EEF .F.F GL !t-..*.*=*=a*n*M'3J3Q3QNJ400!A!&**,,33"5
   00;M $ : :> J":
'':5"&":":<"H-J^^J/
\\*-
#,,rG   )r2   r6   r   r/   r1   r-   )NNNNr   F)	__name__
__module____qualname____firstlineno____doc__r'   rS   __static_attributes____classcell__rD   s   @rE   r   r   -   s*    QD #!"'(%*0- 0-rG   r   c                   D   ^  \ rS rSrU 4S jrS r      SS jrSrU =r$ )SbertSelfAttention   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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_headsrI   
ValueErrorintattention_head_sizeall_head_sizer(   Linearquerykeyvaluer4   attention_probs_dropout_probr6   r7   r   r.   r)   distance_embedding
is_decoderrA   s     rE   r'   SbertSelfAttention.__init__   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'.v/H/9(;$ ''>9T=Y=Y]q=q+1+I+ID(&(llF222Q6(('*D# !++rG   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   re   r      )r?   rf   ri   viewpermute)rB   xnew_x_shapes      rE   transpose_for_scores'SbertSelfAttention.transpose_for_scores   sS    ffhsmt'?'?'+'?'?'A AFFK yyAq!$$rG   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                  " SS9" U5      nU R3                  U5      nUb  UU-  n[        R                  " UU5      nUR5                  SSSS5      R7                  5       nUR                  5       S S U R8                  4-   nUR                  " U6 nU(       a  UU4OU4nU R                  (       a  UU4-   nU$ )Nr   r   re   dimr    rc   rd   r"   )r#   zbhld,lrd->bhlrzbhrd,lrd->bhlrrt   )rl   ry   rm   rn   r9   catrq   matmul	transposer   r?   r:   r@   r$   ru   rp   r.   tor#   einsummathsqrtri   r(   Softmaxr6   rv   
contiguousrj   )rB   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_scoresrO   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                             rE   rS   SbertSelfAttention.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$$/& &%/@ **,-=> ,,7  -	9O_kB%--aAq9DDF"/"4"4"6s";?" #"%**,CD (9 !"$?L>O 	 ?? 22GrG   )rj   ri   rp   r6   rq   rm   r.   rf   r   rl   rn   NNNNNF)	rU   rV   rW   rX   r'   ry   rS   rZ   r[   r\   s   @rE   r^   r^      s-    ,:% "#k krG   r^   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertSelfOutputi  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 Nr   )r&   r'   r(   rk   r+   denser2   r3   r4   r5   r6   rA   s     rE   r'   SbertSelfOutput.__init__  sc    YYv1163E3EF
F$9$9;zz&"<"<=rG   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ Nr   r6   r2   rB   r   input_tensors      rE   rS   SbertSelfOutput.forward   5    

=1]3}'CDrG   r2   r   r6   rU   rV   rW   rX   r'   rS   rZ   r[   r\   s   @rE   r   r         > rG   r   c                   D   ^  \ rS rSrU 4S jrS r      SS jrSrU =r$ )SbertAttentioni'  c                    > [         TU ]  5         [        U5      U l        [	        U5      U l        [        5       U l        g r   )r&   r'   r^   rB   r   outputsetpruned_headsrA   s     rE   r'   SbertAttention.__init__)  s0    &v.	%f-ErG   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   r|   )lenr   rB   rf   ri   r   r   rl   rm   rn   r   r   rj   union)rB   headsindexs      rE   prune_headsSbertAttention.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:rG   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   r   )rB   r   )rB   r   r   r   r   r   r   r   self_outputsattention_outputr   s              rE   rS   SbertAttention.forwardB  s\     yy!"
  ;;|AF# #AB'(rG   )r   r   rB   r   )	rU   rV   rW   rX   r'   r   rS   rZ   r[   r\   s   @rE   r   r   '  s+    ";, "# rG   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertIntermediatei[  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(   rk   r+   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrA   s     rE   r'   SbertIntermediate.__init__]  s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$rG   c                 J    U R                  U5      nU R                  U5      nU$ r   r   r   )rB   r   s     rE   rS   SbertIntermediate.forwarde  s&    

=100?rG   r   r   r\   s   @rE   r   r   [  s    9 rG   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertOutputik  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(   rk   r   r+   r   r2   r3   r4   r5   r6   rA   s     rE   r'   SbertOutput.__init__m  sc    YYv779K9KL
F$9$9;zz&"<"<=rG   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r   s      rE   rS   SbertOutput.forwardt  r   rG   r   r   r\   s   @rE   r   r   k  r   rG   r   c                   D   ^  \ rS rSrU 4S jr      SS jrS rSrU =r$ )
SbertLayeri{  c                 v  > [         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	        [        U5      U l        [        U5      U l        g )Nr   z> should be used as a decoder model if cross attention is added)r&   r'   chunk_size_feed_forwardseq_len_dimr   	attentionrq   add_cross_attentionrg   crossattentionr   intermediater   r   rA   s     rE   r'   SbertLayer.__init__}  s    '-'E'E$'/ ++#)#=#= ##?? fZ[  #1"8D-f5!&)rG   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$ )
Nre   )r   r   r   r   r    r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r~   )	r   rq   rI   rg   r   r   feed_forward_chunkr   r   )rB   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                    rE   rS   SbertLayer.forward  s    9G8R $2 3423$5X\ 	!!%/3 "0 "
 2!4 ??,Qr2G 6r :,G (,$??4@4!122 =dV DJ KL L '2 )7)8< &&*&9&9 %&)!'#  7q9"! G ,C2+F( 14P P01H1H151M1M151A1A1AC  "W, ??!2 55GrG   c                 J    U R                  U5      nU R                  X!5      nU$ r   )r   r   )rB   r   intermediate_outputr   s       rE   r   SbertLayer.feed_forward_chunk  s)    "//0@A{{#6IrG   )r   r   r   r   r   rq   r   r   r   )	rU   rV   rW   rX   r'   rS   r   rZ   r[   r\   s   @rE   r   r   {  s-    *& "#CJ rG   r   c                   D   ^  \ rS rSrU 4S jr         SS jrSrU =r$ )SbertEncoderi  c                    > [         TU ]  5         Xl        [        R                  " [        UR                  5       Vs/ s H  n[        U5      PM     sn5      U l        SU l	        g s  snf )NF)
r&   r'   rC   r(   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)rB   rC   _rD   s      rE   r'   SbertEncoder.__init__  sV    ]]).v/G/G)HI)HAZ)HIK
&+# Js   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 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	(       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    rE   custom_forwardKSbertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forward  s&    %  9v  9~  9&7 9 9rG   r   )r   r   r   r   s   ` rE   create_custom_forward3SbertEncoder.forward.<locals>.create_custom_forward  s    9 *)rG   r   r    r   re   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r   ).0vs     rE   	<genexpr>'SbertEncoder.forward.<locals>.<genexpr>-  s"        %q   %s   	)last_hidden_statepast_key_valuesr   
attentionscross_attentions)rC   r   	enumerater   r   trainingloggerwarningr9   utils
checkpointtupler   )rB   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           `           @rE   rS   SbertEncoder.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, ,,(e  5j   14E E  "!#$%       ,+.+*1
 	
rG   )rC   r   r   )	NNNNNNFFTr   r\   s   @rE   r   r     s1    , "#"Y
 Y
rG   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertPooleri=  c                    > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " 5       U l        g r   )r&   r'   r(   rk   r+   r   Tanh
activationrA   s     rE   r'   SbertPooler.__init__?  s9    YYv1163E3EF
'')rG   c                 \    US S 2S4   nU R                  U5      nU R                  U5      nU$ )Nr   )r   r!  )rB   r   first_token_tensorpooled_outputs       rE   rS   SbertPooler.forwardD  s6     +1a40

#566rG   )r!  r   r   r\   s   @rE   r  r  =  s    $
 rG   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$ )SbertPreTrainedModeliM  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
   )rB   rC   kwargsrD   s      rE   r'   SbertPreTrainedModel.__init__X  s*    ,,77eT#F+rG   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 weightsg        )meanstdNg      ?)r   r(   rk   weightdatanormal_rC   initializer_rangebiaszero_r)   r   r2   fill_)rB   r   s     rE   _init_weights"SbertPreTrainedModel._init_weights\  s   fbii(( MM&&dkk;; ' ={{&  &&( '--MM&&dkk;; ' =!!-""6#5#56<<> .--KK""$MM$$S) .rG   c                 <    [        U[        5      (       a  X!l        g g r   )r   r   r   )rB   r   rn   s      rE   _set_gradient_checkpointing0SbertPreTrainedModel._set_gradient_checkpointingn  s    fl++,1) ,rG   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U$ [        [        U ]  " SSU0UD6n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 is not input.
            label2id: An optional label2id mapping, which will cover the label2id in configuration (if exists).

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_pretrained)clsr,  r>  r?  
model_argsrC   modelrD   s          rE   _instantiate!SbertPreTrainedModel._instantiater  s     JJ{D1	jj%*9DVD
 .:.FKE  %5 G.7G;EGErG   r   )F)rU   rV   rW   rX   rY   r   config_classbase_model_prefixsupports_gradient_checkpointing_keys_to_ignore_on_load_missingr'   r8  r;  classmethodrF  rZ   r[   r\   s   @rE   r(  r(  M  sG    
 L&*#'6&7#,*$2  rG   r(  c                   x    \ rS rSr% Sr\R                  \S'   Sr\	\
\\R                  4      \S'   Sr\\S'   Srg))AttentionBackboneModelOutputWithEmbeddingi  Nembedding_outputlogitsr,  r   )rU   rV   rW   rX   rO  r9   FloatTensor__annotations__rP  r   r   r  r,  dictrZ   r   rG   rE   rN  rN    s<    *.e''.8<FHU5%"3"3345<FDrG   rN  )module_namec                   n   ^  \ rS rSrSrS
S\4U 4S jjjrS rS rS r	             SS jr
S	rU =r$ )
SbertModeli  a  The StructBERT Model transformer outputting raw hidden-states without any specific head on top.

This model inherits from :class:`~transformers.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 (:class:`~modelscope.models.nlp.structbert.SbertConfig`): 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 :meth:`~transformers.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 :obj:`is_decoder` argument of the configuration
set to :obj:`True`. To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`
argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
input to the forward pass.
rC   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'   rC   r   rR   r   encoderr  poolerinit_weights)rB   rC   add_pooling_layerr,  rD   s       rE   r'   SbertModel.__init__  sI     )&1#F+->k&)DrG   c                 .    U R                   R                  $ r   rR   r-   )rB   s    rE   get_input_embeddingsSbertModel.get_input_embeddings  s    ...rG   c                 $    XR                   l        g r   r^  )rB   rn   s     rE   set_input_embeddingsSbertModel.set_input_embeddings  s    */'rG   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)itemsrX  r   r   r   )rB   heads_to_pruner   r   s       rE   _prune_headsSbertModel._prune_heads  s<    
 +002LELLu%//;;EB 3rG   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cs  [        U R                  S	5      (       a4  U R                  R                  SS2SU24   nUR                  UU5      nUnO$[        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S9u  n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4-   $ [1        UU UR2                  UR4                  UR6                  UR8                  US9$ )u  
Args:
    input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary.

        Indices can be obtained using :class:`~modelscope.models.nlp.structbert.SbertTokenizer`. See
        :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__`
        for details.

    attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(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**.

    token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(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.

    position_ids (:obj:`torch.LongTensor` of shape :obj:`(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]``.

    head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(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 (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`,
        `optional`):
        Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
        representation. This is useful if you want more control over how to convert :obj:`input_ids` indices
        into associated vectors than the model's internal embedding lookup matrix.
    output_attentions (:obj:`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 (:obj:`bool`, `optional`):
        Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors
        for more detail.
    return_dict (:obj:`bool`, `optional`):
        Whether or not to return a :class:`~transformers.ModelOutput` instead of a plain tuple.
    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**.
    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:
    Returns `modelscope.outputs.AttentionBackboneModelOutputWithEmbedding`

Examples:
    >>> from modelscope.models import Model
    >>> from modelscope.preprocessors import Preprocessor
    >>> model = Model.from_pretrained('damo/nlp_structbert_backbone_base_std', task='backbone')
    >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_structbert_backbone_base_std')
    >>> print(model(**preprocessor('这是个测试')))
NFzDYou cannot specify both input_ids and inputs_embeds at the same timer    z5You have to specify either input_ids or inputs_embedsr   re   )r$   r!   r"   T)rJ   r   r!   rK   rL   rM   )	r   r   r   r   r  r  r   r  r  r   )r  pooler_outputr  r   r  r	  rO  )rC   r   r  use_return_dictrq   r  rg   r?   r$   shaper9   onesrI   rR   r!   r;   r>   r@   get_extended_attention_maskinvert_attention_maskget_head_maskr   rX  rY  rN  r  r   r  r	  )!rB   rJ   r   r!   r   r   rK   r   r   r  r  r   r  r  r,  rN   
batch_sizerO   r$   rL   rP   rQ   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskrO  original_embedsencoder_outputssequence_outputr%  s!                                    rE   rS   SbertModel.forward  sw   | 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 !t(899*.//*H*H MTISMT JT +U'3J3Q3Q
4,0!A!&uzz&"B
 150P0P11
 ;;!!&;&G=R=W=W >: 7$6$;$= %-).(*9&.2.H.H&/(+ /3+ &&y'+{{'D'DF	 -1OO%)'#9!% -< -
)/ ,,2"7#B+/!5# ' 
 *!, $ 7 =A 	 #!#%4QR%89<K;NO O 9-'+;;)77&11,==,. 	.rG   )rC   rR   rX  rY  )T)NNNNNNNNNNNNN)rU   rV   rW   rX   rY   r   r'   r_  rb  rg  rS   rZ   r[   r\   s   @rE   rV  rV    s^    8	{ 	 	/0C ##!"&*'+ $"&%) K. K.rG   rV  )7rY   r   dataclassesr   typingr   r   r9   torch.nnr(   torch.utils.checkpoint	packagingr   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  Moduler   r^   r   r   r   r   r   r   r  r(  rN  register_modulebackbone
structbertrV  r   rG   rE   <module>r     sP  " Y  ! "     + 7 & / , ; + . <> > '	T-bii T-nP Pfbii  1RYY 1h		  "))  Z Zzb
299 b
J"))  >: >B 0L   F4E4EFA.% A. GA.rG   