
    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  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\RD                  5      r# " S S\RD                  5      r$ " S S\RD                  5      r% " S S\RD                  5      r& " S S\RD                  5      r' " S S\RD                  5      r( " S S\RD                  5      r) " S  S!\RD                  5      r* " S" S#\RD                  5      r+ " S$ S%\\
5      r,\RZ                  " \R\                  \R^                  S&9 " S' S(\,5      5       r0g))zPyTorch BERT model.     N)version)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   
BertConfigr   c                   @   ^  \ 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SS5      U l        U R'                  S[(        R*                  " UR                  5      R-                  S5      5        [.        R0                  " [(        R2                  5      [.        R0                  " S5      :  aK  U R'                  S[(        R4                  " U R6                  R9                  5       [(        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dtypeF)
persistent)super__init__r   	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longselfconfig	__class__s     c/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/bert/backbone.pyr%   BertEmbeddings.__init__/   se   !||++ - $&<<0N0N060B0B$D %'\\&2H2H282D2D&F"
 F$9$9;zz&"<"<= (/v/H/9(;$ 	LL778??H	J ==**+gmmG.DD   D--224EJJG  !  E    c                 d   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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
XJ-   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   r   r    r   r"   devicer   )r<   r   hasattrr    r8   r6   r;   r=   rG   r*   r.   r   r,   r/   r3   )r?   	input_idsr    r   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr.   
embeddingsr,   s                rB   forwardBertEmbeddings.forwardN   sU     #..*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/
\\*-
rD   )r/   r3   r   r,   r.   r*   )NNNNr   )	__name__
__module____qualname____firstlineno____doc__r%   rQ   __static_attributes____classcell__rA   s   @rB   r   r   ,   s'    Q@ #!"'(, ,rD   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$ )BertSelfAttention}   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_headsrH   
ValueErrorintattention_head_sizeall_head_sizer   Linearquerykeyvaluer1   attention_probs_dropout_probr3   r4   r   r+   r&   distance_embedding
is_decoderr?   r@   r   rA   s      rB   r%   BertSelfAttention.__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'> (;'-zC;$''>9T=Y=Y]q=q+1+I+ID(&(llF222Q6(('*D# !++rD   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   rc   r      )r<   rd   rg   viewpermute)r?   xnew_x_shapes      rB   transpose_for_scores&BertSelfAttention.transpose_for_scores   sS    ffhsmt'?'?'+'?'?'A AFFK yyAq!$$rD   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6 nU(       a  UU4OU4nU R                  (       a  UU4-   nU$ )Nr   r   rc   dimr   ra   rb   rF   r!   zbhld,lrd->bhlrzbhrd,lrd->bhlrrs   )rj   rx   rk   rl   r6   catro   matmul	transposer   r<   r7   r=   rG   rt   rn   r+   tor"   einsummathsqrtrg   r   
functionalsoftmaxr3   ru   
contiguousrh   )r?   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_scoresrM   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                             rB   rQ   BertSelfAttention.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";?" #"%**,CD (9 !"$?L>O 	 ?? 22GrD   )rh   rg   rn   r3   ro   rk   r+   rd   r   rj   rl   NNNNNNF)	rS   rT   rU   rV   r%   rx   rQ   rX   rY   rZ   s   @rB   r\   r\   }   s-    ,8% "#m mrD   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 Nr   )r$   r%   r   ri   r(   denser/   r0   r1   r2   r3   r>   s     rB   r%   BertSelfOutput.__init__  sc    YYv1163E3EF
F$9$9;zz&"<"<=rD   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r3   r/   r?   r   input_tensors      rB   rQ   BertSelfOutput.forward  5    

=1]3}'CDrD   r/   r   r3   rS   rT   rU   rV   r%   rQ   rX   rY   rZ   s   @rB   r   r         > rD   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S9U l        [	        U5      U l        [        5       U l        g )Nr   )r$   r%   r\   r?   r   outputsetpruned_headsrp   s      rB   r%   BertAttention.__init__#  s4    %E	$V,ErD   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   r?   rd   rg   r   r   rj   rk   rl   r   r   rh   union)r?   headsindexs      rB   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:rD   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   )r?   r   )r?   r   r   r   r   r   r   r   self_outputsattention_outputr   s              rB   rQ   BertAttention.forward=  s\     yy!"
  ;;|AF# #AB'(rD   )r   r   r?   r   r   )	rS   rT   rU   rV   r%   r   rQ   rX   rY   rZ   s   @rB   r   r   !  s+    ";, "# rD   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BertIntermediateiV  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   ri   r(   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr>   s     rB   r%   BertIntermediate.__init__X  s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$rD   c                 J    U R                  U5      nU R                  U5      nU$ r   r   r   )r?   r   s     rB   rQ   BertIntermediate.forward`  s&    

=100?rD   r   r   rZ   s   @rB   r   r   V  s    9 rD   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )
BertOutputif  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   ri   r   r(   r   r/   r0   r1   r2   r3   r>   s     rB   r%   BertOutput.__init__h  sc    YYv779K9KL
F$9$9;zz&"<"<=rD   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r   s      rB   rQ   BertOutput.forwardo  r   rD   r   r   rZ   s   @rB   r   r   f  r   rD   r   c                   D   ^  \ rS rSrU 4S jr      SS jrS rSrU =r$ )	BertLayeriv  c                 t  > [         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S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$   r%   chunk_size_feed_forwardseq_len_dimr   	attentionro   add_cross_attentionre   crossattentionr   intermediater   r   r>   s     rB   r%   BertLayer.__init__x  s    '-'E'E$&v. ++#)#=#= ##?? fZ[  #0
#<D,V4 (rD   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$ )
Nrc   )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   ro   rH   re   r   r   feed_forward_chunkr   r   )r?   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                    rB   rQ   BertLayer.forward  s    9G8R $2 3423$5X\ 	!!%/3 "0 "
 2!4 ??,Qr2G 6r :,G (,$??4@4!122 =dV D_ `  '2 )7)8< &&*&9&9 %&)!'#  7q9"! G ,C2+F( 14P P01H1H151M1M151A1A1AC  "W, ??!2 55GrD   c                 J    U R                  U5      nU R                  X!5      nU$ r   )r   r   )r?   r   intermediate_outputr   s       rB   r   BertLayer.feed_forward_chunk  s)    "//0@A{{#6IrD   )r   r   r   r   r   ro   r   r   r   )	rS   rT   rU   rV   r%   rQ   r   rX   rY   rZ   s   @rB   r   r   v  s-    )( "#DL rD   r   c                   D   ^  \ 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[        U5      PM     sn5      U l        SU l	        g s  snf )NF)
r$   r%   r@   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)r?   r@   _rA   s      rB   r%   BertEncoder.__init__  sV    ]](-f.F.F(GH(G1Yv(GHJ
&+# I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    rB   custom_forwardJBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forward  s&    %  9v  9~  9&7 9 9rD   r   )r   r   r   r   s   ` rB   create_custom_forward2BertEncoder.forward.<locals>.create_custom_forward  s    9 *)rD   r   r   r   rc   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r   ).0vs     rB   	<genexpr>&BertEncoder.forward.<locals>.<genexpr>*  s"        %q   %s   	)last_hidden_statepast_key_valuesr   
attentionscross_attentions)r@   r   	enumerater   r   trainingloggerwarningr6   utils
checkpointtupler   )r?   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           `           @rB   rQ   BertEncoder.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
 	
rD   )r@   r   r   )	NNNNNNFFTr   rZ   s   @rB   r   r     s1    , "#"Y
 Y
rD   r   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   ri   r(   r   Tanh
activationr>   s     rB   r%   BertPooler.__init__<  s9    YYv1163E3EF
'')rD   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       rB   rQ   BertPooler.forwardA  s6     +1a40

#566rD   )r"  r   r   rZ   s   @rB   r  r  :  s    $
 rD   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$ )BertPreTrainedModeliJ  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   )r?   r@   kwargsrA   s      rB   r%   BertPreTrainedModel.__init__U  s*    ,,77eT#F+rD   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   ri   weightdatanormal_r@   initializer_rangebiaszero_r&   r   r/   fill_)r?   r   s     rB   _init_weights!BertPreTrainedModel._init_weightsY  s   fbii(( MM&&dkk;; ' ={{&  &&( '--MM&&dkk;; ' =!!-""6#5#56<<> .--KK""$MM$$S) .rD   c                 <    [        U[        5      (       a  X!l        g g r   )r   r   r   )r?   r   rl   s      rB   _set_gradient_checkpointing/BertPreTrainedModel._set_gradient_checkpointingk  s    fk**,1) +rD   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_pretrainedr?  )clsr-  r?  r@  
model_argsr@   modelrA   s          rB   _instantiate BertPreTrainedModel._instantiateo  s~     JJ{D1	jj%*9DVD
-*-FKE%5 G.7G;EGE#rD   r   )F)rS   rT   rU   rV   rW   r   config_classbase_model_prefixsupports_gradient_checkpointing_keys_to_ignore_on_load_missingr%   r9  r<  classmethodrG  rX   rY   rZ   s   @rB   r)  r)  J  sG    
 L&*#'6&7#,*$2  rD   r)  )	group_keymodule_namec                      ^  \ rS rSrSrSU 4S jjr\SS j5       rS rS r	S r
             SS\4S	 jjrS
 rS rSrU =r$ )	BertModeli  ag  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        [        U5      U l        [	        U5      U l        U(       a  [        U5      OS U l        U R                  5         g r   )	r$   r%   r   rP   r   encoderr  pooler	post_init)r?   r@   add_pooling_layerrA   s      rB   r%   BertModel.__init__  sD     (0"6*,=j(4 	rD   c                 ,    [        S0 UD6nU " X25      nU$ )Nr   r   )rD  r?  rV  r@   rF  s        rB   rG  BertModel._instantiate  s    %f%F.rD   c                 .    U R                   R                  $ r   rP   r*   )r?   s    rB   get_input_embeddingsBertModel.get_input_embeddings  s    ...rD   c                 $    XR                   l        g r   r[  )r?   rl   s     rB   set_input_embeddingsBertModel.set_input_embeddings  s    */'rD   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)itemsrS  r   r   r   )r?   heads_to_pruner   r   s       rB   _prune_headsBertModel._prune_heads  s<    
 +002LELLu%//;;EB 3rD   returnc                    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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 -   $ [1        UUUR2                  UR4                  UR6                  UR8                  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   rc   )rG   r    rF   )rI   r   r    rJ   rK   )	r   r   r   r   r  r  r   r  r  r   )r  pooler_outputr  r   r	  r
  )r@   r   r  use_return_dictro   r  re   r<   rG   shaper6   onesrH   rP   r    r8   r;   r=   get_extended_attention_maskinvert_attention_maskget_head_maskr   rS  rT  r   r  r   r	  r
  ) r?   rI   r   r    r   r   rJ   r   r   r  r  r   r  r  r-  rL   
batch_sizerM   rG   rK   rN   rO   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputr&  s                                    rB   rQ   BertModel.forward  sU   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 !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	  ??%)'#9 + 
 ,,2"7#B+/!5# ' 
 *!, $ 7 =A 	 #]3oab6III+-'+;;)77&11,==
 	
rD   c                     US   $ )Nr  r   r?   r   s     rB   extract_sequence_outputs"BertModel.extract_sequence_outputs  s    *++rD   c                     US   $ )Nrh  r   rz  s     rB   extract_pooled_outputs BertModel.extract_pooled_outputs  s    ''rD   )rP   rS  rT  )T)NT)NNNNNNNNNNNNN)rS   rT   rU   rV   rW   r%   rM  rG  r\  r_  rd  r   rQ   r{  r~  rX   rY   rZ   s   @rB   rQ  rQ    s|    #J  
/0C ##!"&*'+ $"&%) O
 :O
b,( (rD   rQ  )1rW   r   r6   torch.utils.checkpoint	packagingr   r   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   r\   r   r   r   r   r   r   r  r)  register_modulebackboner*  rQ  r   rD   rB   <module>r     s0          + 7 & / , ; + . <> > &	NRYY NbQ		 QhRYY  2BII 2jryy    \		 \~b
")) b
J  >*o >B %..fkkJY(# Y( KY(rD   