
    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 jr" " S S\RF                  5      r$ " S S\RF                  5      r% " S S\RF                  5      r& " S S\RF                  5      r' " S S\RF                  5      r( " S S\RF                  5      r) " S S \RF                  5      r* " S! S"\RF                  5      r+ " S# S$\RF                  5      r, " S% S&\\
5      r-\R\                  " \R^                  \R`                  S'9 " S( S)\-5      5       r1g)+zPyTorch XLM-RoBERTa 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   )XLMRobertaConfigr   c                     U R                  U5      R                  5       n[        R                  " USS9R	                  U5      U-   U-  nUR                  5       U-   $ )z
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
are ignored. This is modified from fairseq's `utils.make_positions`.

Args:
    x: torch.Tensor x:

Returns: torch.Tensor
r   dim)neinttorchcumsumtype_aslong)	input_idspadding_idxpast_key_values_lengthmaskincremental_indicess        j/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/xlm_roberta/backbone.py"create_position_ids_from_input_idsr#   -   s[     <<$((*D <<!4<<TB347;<##%33    c                   F   ^  \ rS rSrSrU 4S jr     SS jrS rSrU =r	$ )XLMRobertaEmbeddingsA   zN
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
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        U R'                  S[(        R.                  " U R0                  R3                  5       [(        R4                  S9S	S
9  UR                  U l        [        R                  " UR                  UR
                  U R6                  S9U l	        g )N)r   epsposition_embedding_typeabsoluteposition_ids)r   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_bufferr   arangeexpandzerosr-   sizer   r   selfconfig	__class__s     r"   r4   XLMRobertaEmbeddings.__init__G   sy   !||++ - $&<<0N0N060B0B$D %'\\&2H2H282D2D&F"
 F$9$9;zz&"<"<='.v/H/9(;$ 	LL778??H	J 	KK))..0

C 	 	 "..#%<<**(($* r$   c                    Uc+  Ub  [        XR                  U5      nOU R                  U5      nUb  UR                  5       nOUR                  5       S S nUS   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   r1   devicer,   )r#   r   &create_position_ids_from_inputs_embedsrH   hasattrr/   rF   r   rG   r   r-   rP   r9   r=   r+   r;   r>   rB   )rJ   r   r/   r-   inputs_embedsr   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr=   
embeddingsr;   s                r"   forwardXLMRobertaEmbeddings.forwardj   s]    $A//1G I  $JJ! #  #..*K',,.s3K ^
 !t-..*.*=*=a*n*M'3J3Q3QNJ400!A!&**,,33"5
   00;M $ : :> J":
'':5"&":":<"H-J^^J/
\\*-
r$   c                    UR                  5       SS nUS   n[        R                  " U R                  S-   X0R                  -   S-   [        R                  UR
                  S9nUR                  S5      R                  U5      $ )z
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

Args:
    inputs_embeds: torch.Tensor

Returns: torch.Tensor
Nr.   r   rO   r   )rH   r   rE   r   r   rP   	unsqueezerF   )rJ   rS   rT   sequence_lengthr-   s        r"   rQ   ;XLMRobertaEmbeddings.create_position_ids_from_inputs_embeds   s}     $((*3B/%a.||q ...2** ''	)
 %%a(//<<r$   )r>   rB   r   r+   r;   r=   r9   )NNNNr   )
__name__
__module____qualname____firstlineno____doc__r4   rY   rQ   __static_attributes____classcell__rL   s   @r"   r&   r&   A   s/    
!*H #!"'(0d= =r$   r&   c                      ^  \ rS rSrS	U 4S jjrS\R                  S\R                  4S jr      S
S\R                  4S jjrSr	U =r
$ )XLMRobertaSelfAttention   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   )r3   r4   r7   num_attention_headsrR   
ValueErrorr   attention_head_sizeall_head_sizer   Linearquerykeyvaluer@   attention_probs_dropout_probrB   rC   r+   r:   r5   distance_embedding
is_decoderrJ   rK   r+   rL   s      r"   r4    XLMRobertaSelfAttention.__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# !++r$   xreturnc                     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   ro   r      )rH   rp   rr   viewpermute)rJ   r}   new_x_shapes      r"   transpose_for_scores,XLMRobertaSelfAttention.transpose_for_scores   sS    ffhsmt'?'?'+'?'?'A AFF;yyAq!$$r$   hidden_statesc                 X   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S L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a  UR                  S   U
R                  S   nnU(       aB  [        R                  " US-
  [        R                  UR                  S	9R                  SS5      nO>[        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[0        R2                  R5                  USS9nU R7                  U5      nUb  UU-  n[        R                  " UU5      nUR9                  SSSS5      R;                  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   ro   r   r.   rm   rn   rO   r0   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) ru   r   rv   rw   r   catrz   matmul	transposer+   shapetensorr   rP   r   rE   ry   r:   tor1   einsummathsqrtrr   r   
functionalsoftmaxrB   r   
contiguousrH   rs   )rJ   r   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	use_cacheattention_scoresquery_length
key_length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                               r"   rY   XLMRobertaSelfAttention.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'2'8'8';Y__Q=O*L!&N**(//"1 26b! 
 "' **(//"1 26b!  #\\%**$++--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r$   )rs   rr   ry   rB   rz   rv   r:   rp   r+   ru   rw   NNNNNNF)r_   r`   ra   rb   r4   r   Tensorr   rY   rd   re   rf   s   @r"   rh   rh      sP    ,8%ell %u|| % "#t||t tr$   rh   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	$ )XLMRobertaSelfOutputiM  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)   )r3   r4   r   rt   r7   denser>   r?   r@   rA   rB   rI   s     r"   r4   XLMRobertaSelfOutput.__init__O  sc    YYv1163E3EF
F$9$9;zz&"<"<=r$   r   input_tensorr~   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   rB   r>   rJ   r   r   s      r"   rY   XLMRobertaSelfOutput.forwardV  5    

=1]3}'CDr$   r>   r   rB   
r_   r`   ra   rb   r4   r   r   rY   rd   re   rf   s   @r"   r   r   M  5    >U\\ #ll/4|| r$   r   c                   d   ^  \ rS rSrSU 4S jjrS r      SS\R                  4S jjrSr	U =r
$ )	XLMRobertaAttentioni_  c                 |   > [         TU ]  5         [        XS9U l        [	        U5      U l        [        5       U l        g )Nr+   )r3   r4   rh   rJ   r   outputsetpruned_headsr{   s      r"   r4   XLMRobertaAttention.__init__a  s4    +E	*62Er$   c                 6   [        U5      S:X  a  g [        XR                  R                  U R                  R                  U R
                  5      u  p[        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l	        [        U R                  R                  USS9U R                  l        U R                  R                  [        U5      -
  U R                  l        U R                  R                  U R                  R                  -  U R                  l        U R
                  R                  U5      U l        g )Nr   r   r   )lenr   rJ   rp   rr   r   r   ru   rv   rw   r   r   rs   union)rJ   headsindexs      r"   prune_headsXLMRobertaAttention.prune_headsh  s   u:?79900II))4+<+<>
 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EI )		%"&))"?"?$))B_B_"_		 --33E:r$   r   c           	      p    U R                  UUUUUUU5      nU R                  US   U5      n	U	4USS  -   n
U
$ )Nr   r   )rJ   r   )rJ   r   r   r   r   r   r   r   self_outputsattention_outputr   s              r"   rY   XLMRobertaAttention.forward{  s\     yy!"
  ;;|AF# #AB'(r$   )r   r   rJ   r   r   )r_   r`   ra   rb   r4   r   r   r   rY   rd   re   rf   s   @r"   r   r   _  s7    ";, "#|| r$   r   c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )XLMRobertaIntermediatei  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   )r3   r4   r   rt   r7   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrI   s     r"   r4   XLMRobertaIntermediate.__init__  s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$r$   r   r~   c                 J    U R                  U5      nU R                  U5      nU$ r   r   r   )rJ   r   s     r"   rY   XLMRobertaIntermediate.forward  s&    

=100?r$   r   r   rf   s   @r"   r   r     s(    9U\\ ell  r$   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	$ )XLMRobertaOutputi  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   )r3   r4   r   rt   r   r7   r   r>   r?   r@   rA   rB   rI   s     r"   r4   XLMRobertaOutput.__init__  sc    YYv779K9KL
F$9$9;zz&"<"<=r$   r   r   r~   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r   s      r"   rY   XLMRobertaOutput.forward  r   r$   r   r   rf   s   @r"   r   r     r   r$   r   c                   `   ^  \ rS rSrU 4S jr      SS\R                  4S jjrS rSr	U =r
$ )XLMRobertaLayeri  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   )r3   r4   chunk_size_feed_forwardseq_len_dimr   	attentionrz   add_cross_attentionrq   crossattentionr   intermediater   r   rI   s     r"   r4   XLMRobertaLayer.__init__  s    '-'E'E$,V4 ++#)#=#= ##?? fZ[  #6
#<D26:&v.r$   r   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$ )
Nro   )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   rz   rR   rq   r   r   feed_forward_chunkr   r   )rJ   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                    r"   rY   XLMRobertaLayer.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r$   c                 J    U R                  U5      nU R                  X!5      nU$ r   )r   r   )rJ   r   intermediate_outputr   s       r"   r   "XLMRobertaLayer.feed_forward_chunk  s)    "//0@A{{#6Ir$   )r   r   r   r   r   rz   r   r   r   )r_   r`   ra   rb   r4   r   r   rY   r   rd   re   rf   s   @r"   r   r     s:    /( "#C||CJ r$   r   c                   `   ^  \ rS rSrU 4S jr         SS\R                  4S jjrSrU =r	$ )XLMRobertaEncoderi  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)
r3   r4   rK   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)rJ   rK   _rL   s      r"   r4   XLMRobertaEncoder.__init__  sV    ]].3F4L4L.MN.M_V$.MNP
&+# Os   A&r   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    r"   custom_forwardPXLMRobertaEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardE  s&    %  9v  9~  9&7 9 9r$   r	  )r  r  r   r   s   ` r"   create_custom_forward8XLMRobertaEncoder.forward.<locals>.create_custom_forwardC  s    9 *)r$   r   r.   r   ro   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r	  ).0vs     r"   	<genexpr>,XLMRobertaEncoder.forward.<locals>.<genexpr>l  s"        %q   %s   	)last_hidden_statepast_key_valuesr   
attentionscross_attentions)rK   r   	enumerater  r  trainingloggerwarningr   utils
checkpointtupler   )rJ   r   r   r   r   r   r  r   r   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           `           @r"   rY   XLMRobertaEncoder.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
 	
r$   )rK   r  r  )	NNNNNNFFTr   rf   s   @r"   r   r     s>    , "#"Y
||Y
 Y
r$   r   c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )XLMRobertaPooleri}  c                    > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " 5       U l        g r   )r3   r4   r   rt   r7   r   Tanh
activationrI   s     r"   r4   XLMRobertaPooler.__init__  s9    YYv1163E3EF
'')r$   r   r~   c                 \    US S 2S4   nU R                  U5      nU R                  U5      nU$ )Nr   )r   r1  )rJ   r   first_token_tensorpooled_outputs       r"   rY   XLMRobertaPooler.forward  s6     +1a40

#566r$   )r1  r   r   rf   s   @r"   r.  r.  }  s(    $
U\\ ell  r$   r.  c                   \   ^  \ rS rSrSr\rSrSr/ r	S r
S
S jrS r\U 4S j5       rS	rU =r$ )XLMRobertaPreTrainedModeli  zz
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
robertaTc                    [        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   rt   weightdatanormal_rK   initializer_rangebiaszero_r5   r   r>   fill_)rJ   r  s     r"   _init_weights'XLMRobertaPreTrainedModel._init_weights  s   fbii(( MM&&dkk;; ' ={{&  &&( '--MM&&dkk;; ' =!!-""6#5#56<<> .--KK""$MM$$S) .r$   c                 <    [        U[        5      (       a  X!l        g g r   )r   r   r  )rJ   r  rw   s      r"   _set_gradient_checkpointing5XLMRobertaPreTrainedModel._set_gradient_checkpointing  s    f/00,1) 1r$   c                     UR                   (       dS  U R                   Vs/ s H  nX2;  d  M
  UPM     snU l        U R                   Vs/ s H  nX2;  d  M
  UPM     snU l        ggs  snf s  snf )z!Remove some keys from ignore listN)tie_word_embeddings_keys_to_ignore_on_save_keys_to_ignore_on_load_missing)rJ   rK   del_keys_to_ignoreks       r"   update_keys_to_ignore/XLMRobertaPreTrainedModel.update_keys_to_ignore  sv    ))  77,7a. 7,D(
  ??4?a. ?4D0 *,4s   	A&A&		A+A+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   r3   r   from_pretrainedrR  )clskwargsrR  rS  
model_argsrK   modelrL   s          r"   _instantiate&XLMRobertaPreTrainedModel._instantiate  s~     JJ{D1	jj%*9DVD
%3
3FKE%5 G.7G;EGE#r$   )rL  rK  )F)r_   r`   ra   rb   rc   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modulesrD  rG  rO  classmethodr[  rd   re   rf   s   @r"   r8  r8    sD    
 $L!&*#*$2  r$   r8  )	group_keymodule_namec                   l   ^  \ rS rSrSrS/rS
U 4S jjrS rS rS r	             SS jr
S	rU =r$ )XLMRobertaModeli  a  

The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
all you need*_ 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.

.. _*Attention is all you need*: https://arxiv.org/abs/1706.03762

r-   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   )
r3   r4   rK   r&   rX   r   encoderr.  pooler	post_init)rJ   rK   add_pooling_layerrL   s      r"   r4   XLMRobertaModel.__init__  sJ     .v6(02C&v. 	r$   c                 .    U R                   R                  $ r   rX   r9   )rJ   s    r"   get_input_embeddings$XLMRobertaModel.get_input_embeddings  s    ...r$   c                 $    XR                   l        g r   rm  )rJ   rw   s     r"   set_input_embeddings$XLMRobertaModel.set_input_embeddings  s    */'r$   c                     UR                  5        H7  u  p#U R                  R                  U   R                  R	                  U5        M9     g)z
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
N)itemsrg  r  r   r   )rJ   heads_to_pruner  r   s       r"   _prune_headsXLMRobertaModel._prune_heads  s<    
 +002LELLu%//;;EB 3r$   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.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$ )a3  
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`).
NFzDYou cannot specify both input_ids and inputs_embeds at the same timer.   z5You have to specify either input_ids or inputs_embedsr   ro   )rP   r/   rO   )r   r-   r/   rS   r   )	r   r   r   r   r  r   r   r"  r#  r   )r  pooler_outputr  r   r  r  )rK   r   r"  use_return_dictrz   r   rq   rH   rP   r   r   onesrR   rX   r/   rF   rG   r   get_extended_attention_maskinvert_attention_maskget_head_maskr  rg  rh  r   r  r   r  r  )rJ   r   r   r/   r-   r   rS   r   r   r  r   r   r"  r#  rT   
batch_sizerU   rP   r   rV   rW   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr  encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputr5  s                                  r"   rY   XLMRobertaModel.forward
  sS   v 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1)
 ;;!!&;&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,==
 	
r$   )rK   rX   rg  rh  )T)NNNNNNNNNNNNN)r_   r`   ra   rb   rc   rL  r4   rn  rq  rv  rY   rd   re   rf   s   @r"   re  re    s]     (7&7#
/0C "#!F
 F
r$   re  )r   )2rc   r   r   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_DOCr#   Moduler&   rh   r   r   r   r   r   r   r.  r8  register_modulebackbonexlm_robertare  r	  r$   r"   <module>r     sA    !      + 7 & / , ; + . <> > ,	$ ?@4(l=299 l=`Xbii Xx299 $2")) 2lRYY "ryy $[bii [~b
		 b
Lryy "H
O HV nn&*<*<>t
/ t
>t
r$   