
    fThS5                       S r SSKrSSKrSSKJrJrJrJ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Jr  SS	KJr  SS
KJrJr  SSKJrJrJrJrJr  SSKJ r   SSK!J"r"J#r#J$r$J%r%  SSK&J'r'  \#" 5       (       a  SSK(J)r)  SSK*J+r+  \%RX                  " \-5      r.S\
R^                  S\0S\04S jr1 " S S\Rd                  5      r3 " S S\Rh                  5      r5 " S S\Rh                  5      r6S\50r7 " S S\Rh                  5      r8\" " S S \ 5      5       r9 " S! S"\95      r: " S# S$\95      r;\" " S% S&\95      5       r<\"" S'S(9 " S) S*\9\5      5       r= " S+ S,\95      r> " S- S.\9\5      r?/ S/Qr@g)0z=PyTorch MarianMTModel model, ported from the Marian C++ repo.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter_prepare_4d_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )MarianConfig)	BlockMask)make_flex_block_causal_mask	input_idspad_token_iddecoder_start_token_idc                     U R                  U R                  5      nU SS2SS24   R                  5       USS2SS24'   X#SS2S4'   Uc  [        S5      eUR	                  US:H  U5        U$ )z)
Shift input ids one token to the right.
Nr   r   z1self.model.config.pad_token_id has to be defined.i)	new_zerosshapeclone
ValueErrormasked_fill_)r   r   r    shifted_input_idss       b/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/marian/modeling_marian.pyshift_tokens_rightr*   =   sz     "++IOO<(CRC0668ae4adLMM""#4#<lK    c            
          ^  \ rS rSrSrSS\S\S\\   SS4U 4S jjjrS	 r\	R                  " 5        SS
\	R                  S\S\\	R                     S\	R                  4U 4S jjj5       rSrU =r$ )#MarianSinusoidalPositionalEmbeddingM   zDThis module produces sinusoidal positional embeddings of any length.Nnum_positionsembedding_dimpadding_idxreturnc                 $   > [         TU ]  X5        g N)super__init__)selfr/   r0   r1   	__class__s       r)   r6   ,MarianSinusoidalPositionalEmbedding.__init__P   s    6r+   c                    U R                   R                  u  p[        R                  " [	        U5       VVs/ s H?  n[	        U5       Vs/ s H%  oC[        R
                  " SSUS-  -  U-  5      -  PM'     snPMA     snn5      n[        R                  " XU R                   R                  SS9nUS-  S:X  a  US-  OUS-  S-   n[        R                  " [        R                  " USS2SSS24   5      5      USS2SU24'   [        R                  " [        R                  " USS2SSS24   5      5      USS2US24'   [        R                  " USS9U l         gs  snf s  snnf )	z
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
the 2nd half of the vector. [dim // 2:]
i'     F)dtyperequires_gradr   r   N)r=   )weightr$   nparrayrangepowertorchemptyr<   FloatTensorsincosr   	Parameter)r7   n_posdimposjposition_encoutsentinels           r)   _init_weight0MarianSinusoidalPositionalEmbedding._init_weightS   s*   
 [[&&
xxX]^cXdeXdQTsLABHHUAaL3$677LXde
 kk%DKK,=,=US"Qw!|3!8#(a"..rvvl1add76K/LMAqzM!--bff\!QTT'5J.KLAxyLll3e< Mes   E

,E6E
E
input_ids_shapepast_key_values_lengthposition_idsc                    > UcB  USS u  pE[         R                  " X"U-   [         R                  U R                  R                  S9n[
        TU ]  U5      $ )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr;   )r<   device)rC   arangelongr>   rV   r5   forward)r7   rR   rS   rT   bszseq_lenr8   s         r)   rY   +MarianSinusoidalPositionalEmbedding.forwardb   sX    
 *2A.LC <<&(HPUPZPZcgcncncucuL w|,,r+   )r>   r4   r   N)__name__
__module____qualname____firstlineno____doc__intr   r6   rP   rC   no_gradSizeTensorrY   __static_attributes____classcell__r8   s   @r)   r-   r-   M   s    N7c 7# 7HUXM 7ei 7 7= ]]_sw	-$zz	-CF	-ZbchcocoZp	-		- 	-r+   r-   c                     ^  \ rS rSrSr      SS\S\S\S\S\S\S	\\	   S
\\   4U 4S jjjr
      SS\R                  S\\R                     S\\   S\\R                     S\\R                     S\S\\R                     S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )MarianAttentionp   z=Multi-headed attention from 'Attention Is All You Need' paper	embed_dim	num_headsdropout
is_decoderbias	is_causalconfig	layer_idxc	                 t  > [         T	U ]  5         Xl        X l        X0l        X-  U l        Xpl        U R
                  U-  U R                  :w  a  [        SU R                   SU S35      eU R
                  S-  U l        X@l	        X`l
        Xl        Uc>  U R                  (       a-  [        R                  SU R                  R                   S35        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        g )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.rq   )r5   r6   rm   rn   ro   head_dimrs   r&   scalingrp   rr   rt   loggerwarning_oncer8   r^   r   Lineark_projv_projq_projout_proj)
r7   rm   rn   ro   rp   rq   rr   rs   rt   r8   s
            r)   r6   MarianAttention.__init__s   s    	""!.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	4@ii	4@ii	4@		)TBr+   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionr2   c                 
   USLnUR                  5       u  pnU R                  U5      R                  U	SU R                  U R                  5      R                  SS5      nXR                  -  nUb]  [        U[        5      (       aF  UR                  R                  U R                  5      nU(       a  UR                  nOUR                  nOUnU(       a  UOUnU(       a=  Ub:  W(       a3  WR                  U R                     nUR                  U R                     nOU R!                  U5      nU R#                  U5      nUR                  U	SU R                  U R                  5      R                  SS5      nUR                  U	SU R                  U R                  5      R                  SS5      nUbN  U(       d  UOSnWR%                  UUU R                  SU05      u  nnU(       a  SUR                  U R                  '   XR                  -  SU R                  4nUR&                  " U6 nUR&                  " U6 nUR&                  " U6 nUR                  S5      n[(        R*                  " UUR                  SS5      5      nUR                  5       XR                  -  U
U4:w  a.  [-        SXR                  -  U
U4 SUR                  5        35      eUb]  USS2SS2SS2SUR.                  S	   24   nUR                  XR                  U
U5      U-   nUR                  XR                  -  U
U5      n[0        R2                  R5                  USS
9nUb  UR                  5       U R                  4:w  a*  [-        SU R                  4 SUR                  5        35      eUR                  SSSS5      UR                  XR                  U
U5      -  nUR                  XR                  -  U
U5      nU(       a=  UR                  XR                  U
U5      nUR                  XR                  -  U
U5      nOSn[0        R2                  R7                  UU R6                  U R8                  S9n[(        R*                  " UU5      nUR                  5       XR                  -  XR                  4:w  a7  [-        SXR                  -  XR                  4 SUR                  5        35      eUR                  XR                  XR                  5      nUR                  SS5      nUR'                  XU R:                  5      nU R=                  U5      nUUU4$ )z#Input shape: Batch x Time x ChannelNr"   r   r;   r   Tz$Attention weights should be of size z	, but is rJ   z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizer~   viewrn   rw   	transposerx   
isinstancer   
is_updatedgetrt   cross_attention_cacheself_attention_cache	key_cachevalue_cacher|   r}   updatereshaperC   bmmr&   r$   r   
functionalsoftmaxro   r   rm   r   )r7   r   r   r   r   r   r   r   is_cross_attentionrZ   tgt_len_query_statesr   curr_past_key_valuecurrent_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                           r)   rY   MarianAttention.forward   s    .T9',,.a {{=166sBPTP]P]^hhijlmn#ll2%.*=>>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,66t~~FJ.::4>>JL^4J;;~6L#b$..$--PZZ[\^_`J',,S"dnndmmT^^_`bcdL)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=NN*B>
#++Z8''4
#++Z8//!$yyz/C/CAq/IJ3#7'"JJ6nn8LgW^7_6` a %%'(* 
 %+Aq!5Kz7G7G7K5K,KLN',,S..'7SVddL',,S>>-A7GTL}},,\r,B&##%$..):: Et~~FWEX Y',,./1  +//2q!<|?P?PQTVdVdfmov?wwL',,S>>-A7GTL
 %1$5$5c>>7T[$\!055cNN6JGU\]L$(!]]**<4<<RVR_R_*`
ii
L9#"6!OO2C..4H'S`S`3a2b c$$&') 
 "&&sNNG]]S!++Aq1 "))#GmmK01>AAr+   )rs   ro   rm   rw   rr   rp   r|   rt   rn   r   r~   rx   r}   )        FTFNN)NNNNFN)r^   r_   r`   ra   rb   rc   floatboolr   r   r6   rC   rf   r   r   rY   rg   rh   ri   s   @r)   rk   rk   p   sY   G  )-#'%C%C %C 	%C
 %C %C %C &%C C=%C %CT 48*.1526"'15pB||pB #5<<0pB !	pB
 !.pB "%,,/pB  pB !.pB 
u||Xell3XeELL>Q5RR	SpB pBr+   rk   c                      ^  \ rS rSrSS\S\\   4U 4S jjjr SS\R                  S\R                  S\R                  S\\
   S	\\R                  \\R                     4   4
S
 jjrSrU =r$ )MarianEncoderLayeri  rs   rt   c                   > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  UUS9U l        [        R                  " U R                  5      U l        UR                  U l        [        UR                     U l        UR                   U l        [        R"                  " U R                  UR$                  5      U l        [        R"                  " UR$                  U R                  5      U l        [        R                  " U R                  5      U l        g )N)rm   rn   ro   rs   rt   )r5   r6   d_modelrm   MARIAN_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normro   r
   activation_functionactivation_fnactivation_dropoutr{   encoder_ffn_dimfc1fc2final_layer_normr7   rs   rt   r8   s      r)   r6   MarianEncoderLayer.__init__  s    1&2M2MNnn44,,
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r+   r   r   r   r   r2   c                    UnU R                  UUUUS9u  pn[        R                  R                  XR                  U R                  S9nXQ-   nU R                  U5      nUnU R                  U R                  U5      5      n[        R                  R                  XR                  U R                  S9nU R                  U5      n[        R                  R                  XR                  U R                  S9nXQ-   nU R                  U5      nUR                  [        R                  :X  a  [        R                  " U5      R                  5       (       d)  [        R                   " U5      R                  5       (       aC  [        R"                  " UR                  5      R$                  S-
  n[        R&                  " X* US9nU4n	U(       a  X4-  n	U	$ )aW  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`): attention mask of size
        `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
    layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
        `(encoder_attention_heads,)`.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
)r   r   r   r   r   i  )minmax)r   r   r   ro   r   r   r   r   r   r   r   r<   rC   float16isinfanyisnanfinfor   clamp)
r7   r   r   r   r   residualr   r   clamp_valueoutputss
             r)   rY   MarianEncoderLayer.forward"  s   $ !)-')+/	 *8 *
&Q --m||VZVcVc-d 011-@ **488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0--m<%--/KK&**,,M0J0N0N0P0P++m&9&9:>>EK!KK<[YM "&Gr+   )	r   r   ro   rm   r   r   r   r   r   r4   F)r^   r_   r`   ra   r   r   rc   r6   rC   rE   r   r   rY   rg   rh   ri   s   @r)   r   r     s    =| = = =0 -20((0 ))0 **	0
 $D>0 
u  (5+<+<"==	>0 0r+   r   eagerc                     ^  \ rS rSrSS\S\\   4U 4S jjjr         SS\R                  S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\
   S\\   S\\   S\\R                     S\\R                  \\\R                  \R                  4      4   4S jjrSrU =r$ )MarianDecoderLayeriY  rs   rt   c           
      T  > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  SSUUS9U l        UR                  U l	        [        UR                     U l        UR                  U l        [        R                  " U R                  5      U l        [        UR
                     " U R                  UR                  UR                  SUUS9U l        [        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        g )NT)rm   rn   ro   rp   rr   rs   rt   )ro   rp   rs   rt   )r5   r6   r   rm   r   r   decoder_attention_headsr   r   ro   r
   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr{   decoder_ffn_dimr   r   r   r   s      r)   r6   MarianDecoderLayer.__init__Z  s6   1&2M2MNnn44,,
 ~~#F$>$>?"(";";$&LL$@!4V5P5PQNN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r+   r   r   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   r2   c           	          UnU R                  UUUUUU
S9u  pn[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nSnUb`  UnU R                  UUUUUUS9u  pn[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nUnU R                  U R                  U5      5      n[        R                  R                  XR                  U R                  S9nU R                  U5      n[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nU4nU(       a  XU4-  nU	(       a  X4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`): attention mask of size
        `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
    encoder_hidden_states (`torch.FloatTensor`):
        cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
    encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
        `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
    layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
        `(encoder_attention_heads,)`.
    cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
        size `(decoder_attention_heads,)`.
    past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
        cache in the correct position and to infer the complete sequence length.
)r   r   r   r   r   r   r   N)r   r   r   r   r   r   )r   r   r   ro   r   r   r   r   r   r   r   r   r   )r7   r   r   r   r   r   r   r   r   r   r   r   self_attn_weightscross_attn_weightsr   s                  r)   rY   MarianDecoderLayer.forwardy  s   D ! <@>>'))+/) <J <
8. --m||VZVcVc-d 011-@ " ,$H@D@Q@Q+!65 :-"3 AR A=M~ MM11-<<Z^ZgZg1hM$4M 88GM !**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0--m< "+=>>G((Gr+   )r   r   ro   rm   r   r   r   r   r   r   r   r4   )	NNNNNNFTN)r^   r_   r`   ra   r   r   rc   r6   rC   rf   r   r   r   rE   rY   rg   rh   ri   s   @r)   r   r   Y  s1   =| = = =D 268<9=26=A*.,1$(15S||S !.S  (5	S
 !) 6S "%,,/S %-U\\$:S !S $D>S D>S !.S 
u  (51B1BEDUDU1U+V"WW	XS Sr+   r   c                   L   \ rS rSr\rSrSrSrSr	S\
\R                  \R                  \4   4S jr SS\
\R"                  S4   S\R"                  S	\R"                  S
\S\4
S jjr\S\R"                  S\S\S\R.                  S	\R"                  S\4S j5       r\S 5       rSrg)MarianPreTrainedModeli  modelTmodulec                 @   U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        5      (       a  UR                  5         g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g [        U[        R                  5      (       aJ  UR
                  R                  R                  S5        UR                  R                  R                  5         g g )Nr   )meanstd      ?)rs   init_stdr   r   r{   r>   datanormal_rq   zero_r-   rP   	Embeddingr1   r   fill_)r7   r   r   s      r)   _init_weights#MarianPreTrainedModel._init_weights  s"   kk""fbii((MM&&CS&9{{&  &&( ' CDD!--MM&&CS&9!!-""6#5#56<<> .--MM$$S)KK""$ .r+   r   r   input_tensorr   past_key_valuesr   c           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nflash_attention_2r   flex_attentionr   Fsdpa)inputs_embedsrS   is_trainingr   r"   )sequence_lengthtarget_lengthr<   r   
batch_size)cudaxpunpu)rs   r   r   r   rC   rf   r   get_seq_lengthis_compileabler   _ignore_causal_mask_sdpar   r<   r$   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrV   typer   r   _unmask_unattended)r7   r   r   r   r   r   past_seen_tokensusing_compilable_cacher<   r   r   causal_mask	min_dtypes                r)   _update_causal_mask)MarianPreTrainedModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr+   r   r   r<   r   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
N   )
fill_valuer<   rV   r   )diagonalrV   r"   r   )rJ   rC   r   r   fullrV   triurW   r   expandr%   r$   tomasked_fill)r   r   r   r<   r   r   kwargsr	  r
  mask_lengthpadding_masks              r)   r  KMarianPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position,  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 r+   c                     U R                   R                  n[        R                  " / SQSSSSU//U R                  S9nUR                  U5      UUS.nU$ )N)r      
   r  r;   r         r;   r  )r   r   decoder_input_ids)rs   r   rC   tensorrV   ne)r7   	pad_tokenr   dummy_inputss       r)   r$  "MarianPreTrainedModel.dummy_inputsd  sZ    KK,,	LL"2Q2q)4L!MVZVaVab	'll95"!*

 r+    Nr   )r^   r_   r`   ra   r   config_classbase_model_prefixsupports_gradient_checkpointing_supports_cache_class_supports_static_cacher   r   r{   r   r-   r   rC   rf   r   r   r  staticmethodrc   r<   r  propertyr$  rg   r&  r+   r)   r   r     s   L&*# !%E"))R\\Cf*f$g %. #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4l  r+   r   c                   <  ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S r
S r       SS\\R                     S	\\R                     S
\\R                     S\\R                     S\\   S\\   S\\   S\\\R                     \4   4S jjrSrU =r$ )MarianEncoderip  z
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`MarianEncoderLayer`].

Args:
    config: MarianConfig
    embed_tokens (nn.Embedding): output embedding
rs   embed_tokensc                   > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  nUR                  U l        UR                  U l	        UR                  (       a  [        R                  " U5      OSU l        Ub  X l        O0[        R                   " UR"                  X0R                  5      U l        [%        UR                  X0R                  5      U l        [        R(                  " [+        UR,                  5       Vs/ s H  n[/        U5      PM     sn5      U l        SU l        U R5                  5         g s  snf )Nr   F)r5   r6   ro   encoder_layerdrop	layerdropr   r   r1   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtembed_scaler0  r   r   
vocab_sizer-   embed_positions
ModuleListrA   encoder_layersr   layersgradient_checkpointing	post_init)r7   rs   r0  rm   r   r8   s        r)   r6   MarianEncoder.__init__z  s     ~~11NN	!..$*$B$B!393I3I499Y/s# , "V->->	K[K[ \DB**I7G7G 
 mmvOdOdIe$fIeA%7%?Ie$fg&+#	 %gs   Ec                     U R                   $ r4   r0  r7   s    r)   get_input_embeddings"MarianEncoder.get_input_embeddings         r+   c                     Xl         g r4   rC  r7   values     r)   set_input_embeddings"MarianEncoder.set_input_embeddings      !r+   r   r   	head_maskr   r   output_hidden_statesreturn_dictr2   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b  Ub  [	        S5      eUb7  U R                  X5        UR                  5       nUR                  SUS   5      nO"Ub  UR                  5       SS nO[	        S5      eUc  U R                  U5      U R                  -  nU R                  U5      n	XI-   n
[        R                  R                  XR                  U R                  S9n
Ub  [        X$R                   5      nU(       a  SOSnU(       a  SOSnUb\  UR                  5       S   [#        U R$                  5      :X  d2   S[#        U R$                  5       S	UR                  5       S    S
35       e['        U R$                  5       H  u  pU(       a  X4-   nSnU R                  (       a(  [(        R*                  " / 5      nUU R,                  :  a  SnU(       a  SnO^U R.                  (       a8  U R                  (       a'  U R1                  UR2                  U
UUb  X=   OSU5      nOU" U
UUb  X=   OSUS9nUS   n
U(       d  M  UUS   4-   nM     U(       a  X4-   nU(       d  [5        S XU4 5       5      $ [7        XUS9$ )a  
Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
        provide it.

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

        [What are input IDs?](../glossary#input-ids)
    attention_mask (`torch.Tensor` 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)
    head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
        Mask to nullify selected heads of the 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 [`~utils.ModelOutput`] instead of a plain tuple.
NzDYou cannot specify both input_ids and inputs_embeds at the same timer"   z5You have to specify either input_ids or inputs_embedsr   r&  r   z&The head_mask should be specified for  layers, but it is for .FT)NN)r   r   r   c              3   .   #    U  H  oc  M  Uv   M     g 7fr4   r&  .0vs     r)   	<genexpr>(MarianEncoder.forward.<locals>.<genexpr>  s     e$Sq$Ss   	last_hidden_stater   
attentions)rs   r   rO  use_return_dictr&   %warn_if_padding_and_no_attention_maskr   r   r0  r9  r;  r   r   ro   r   r   r<   lenr>  	enumeraterC   randr3  r?  _gradient_checkpointing_func__call__tupler   )r7   r   r   rN  r   r   rO  rP  input_shape	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r)   rY   MarianEncoder.forward  s   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]  ]%>cdd"66yQ#..*K!r;r?;I&',,.s3KTUU  --i84;K;KKM((5	%1--m||VZVcVc-d %7H[H[\N30d  >>#A&3t{{+;< 8T[[9I8JJabkbpbpbrstbuavvwx< #,DKK"8C#!/2B!BG}}&+jjn#&7"G ,..4==$($E$E%..%&+4+@d)%M %2%&;D;PVZ*;	%M !.a 0  !/=3C2E!EA #9D  +.>>Ne]N$Seee+Vd
 	
r+   )	ro   r;  r9  r0  r?  r3  r>  r5  r1   r4   )NNNNNNN)r^   r_   r`   ra   rb   r   r   r   r   r6   rE  rK  rC   
LongTensorrf   rE   r   r   r   r   rY   rg   rh   ri   s   @r)   r/  r/  p  s    | 8BLL;Q  2!"
 1559,059,0/3&*~
E,,-~
 !!1!12~
 ELL)	~

   1 12~
 $D>~
 'tn~
 d^~
 
uU\\"O3	4~
 ~
r+   r/  c                     ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S r
S r             SS\\R                     S	\\R                     S
\\R                     S\\R                     S\\R                     S\\R                     S\\\\R                           S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\R                     \4   4S jjrSrU =r$ )MarianDecoderi  z
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MarianDecoderLayer`]

Args:
    config: MarianConfig
    embed_tokens (nn.Embedding): output embedding
rs   r0  c           
        > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  U l        UR                  U l        UR                  (       a   [        R                  " UR                  5      OSU l        Ub  X l        O;[        R                   " UR"                  UR                  U R                  5      U l        [%        UR                  UR                  U R                  5      U l        [        R(                  " [+        UR,                  5       Vs/ s H  n[/        XS9PM     sn5      U l        SU l        U R5                  5         g s  snf )Nr   )rt   F)r5   r6   ro   decoder_layerdropr3  r   r1   r4  max_target_positionsr6  r7  r8  r   r9  r0  r   r   decoder_vocab_sizer-   r;  r<  rA   decoder_layersr   r>  r?  r@  )r7   rs   r0  ir8   s       r)   r6   MarianDecoder.__init__#  s	    ~~11!..$*$B$B!8>8N8N499V^^4TW# , "V-F-FX\XhXh iDB**FNND<L<L 
 mmV[\b\q\qVr$sVrQR%7%LVr$st&+#	 %ts   )E c                     U R                   $ r4   rC  rD  s    r)   rE  "MarianDecoder.get_input_embeddings9  rG  r+   c                     Xl         g r4   rC  rI  s     r)   rK  "MarianDecoder.set_input_embeddings<  rM  r+   r   r   r   r   rN  cross_attn_head_maskr   r   r   r   rO  rP  r   r2   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b  UOU R                   R                  nU R
                  (       a/  U R                  (       a  U	(       a  [        R                  S5        Sn	USL USL-  (       a  [        S5      eUb  UR                  SUR                  S   5      nUc  U R                  U5      nXR                  -  nSnU	(       aB  [        U[        5      (       d-  Sn[        R                  S5        [         R"                  " U5      nUR%                  5       SS u  nnUb  UR'                  5       OSnUc#  [(        R*                  " UUU-   UR,                  S	9nUc4  [/        5       (       d%  UU-   n[(        R0                  " UUUR,                  S	9n[        U[         5      (       a  UR2                  OUnU R5                  UUUUU
5      nUb  Ub  [7        UUR8                  US
9nU R;                  UU4UUS9nUU-   n[<        R>                  RA                  UU R@                  U R                  S9nU(       a  SOSnU
(       a  SOSnU
(       a  Ub  SOSnSn[C        XV/SS/5       Hj  u  nnUc  M  UR%                  5       S   [E        U RF                  5      :X  a  M7   SU S[E        U RF                  5       SUR%                  5       S    S35       e   [I        U RF                  5       H  u  nnU(       a  UU4-  nU R                  (       a(  [(        RJ                  " / 5      nUU RL                  :  a  ML  U R
                  (       aG  U R                  (       a6  U RO                  URP                  UUUUUb  UU   OSUb  UU   OSSU
U	U5      n OU" UUUUUb  UU   OSUb  UU   OSUU
U	US9
n U S   nU	(       a  U U
(       a  SOS   nU
(       d  M  UU S   4-  nUc  M  UU S   4-  nGM      U(       a  UU4-  nU	(       a  UOSn!U(       a  URS                  5       n!U(       d  [U        S UU!UUU4 5       5      $ [W        UU!UUUS9$ )a|  
Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
        provide it.

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

        [What are input IDs?](../glossary#input-ids)
    attention_mask (`torch.Tensor` 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)
    encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
        Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
        of the decoder.
    encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
        Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. 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)
    head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
        Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

    cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
        Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
        cross-attention on hidden heads. Mask values selected in `[0, 1]`:

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

    past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
        shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
        shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

        Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
        cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential 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)`.
    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 [`~utils.ModelOutput`] instead of a plain tuple.
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
        cache in the correct position and to infer the complete sequence length.
NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer"   TzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r  )r   )rT   r   r&  rN  r}  zThe `z` should be specified for rR  rS  )	r   r   r   r   r   r   r   r   r   r	   r   r;   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr4   r&  rU  s     r)   rX  (MarianDecoder.forward.<locals>.<genexpr>)  s      mA ms   	)r[  r   r   r\  cross_attentions),rs   r   rO  r   r]  r?  r   ry   rz   r&   r   r$   r0  r9  r   r   r   from_legacy_cacher   r   rC   rW   rV   r   onesr   r  r   r<   r;  r   r   ro   zipr_  r>  r`  ra  r3  rb  rc  to_legacy_cacherd  r   )"r7   r   r   r   r   rN  r}  r   r   r   r   rO  rP  r   return_legacy_cacher   
seq_lengthrS   mask_seq_lengthself_attn_cacher	  rT   r   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cache	attn_mask	mask_nameri  decoder_layerrl  rm  
next_caches"                                     r)   rY   MarianDecoder.forward?  s   h 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]&&4==##p "	 -t";<stt !r9??2+>?I  --i8M &(8(88 $Z??"&\
 2CCOTO!.!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !*B*D*D4zAO"ZZ
OML`L`aN /+>?? 00  	
 ..
 !,1G1S%?&##"&" ++$&<> , 
 &4--mt||VZVcVc-d #7BD0d&7<Q<]rdh! %((IKYoKp$q Iy$ ~~'*s4;;/?@ I;&@T[[AQ@R S!(+,A/@ %r #,DKK"8C#!m%55!}}&+jjn#&7**t}} $ A A!**!)*&/&;IcN1E1Q(-W[%"! !.!#.*?+A7@7LYs^RV5I5U,S1[_#2&7'#1! *!,M%28I1q%Q"  =#3"55(4(]1-=,??(_ #9d  -!11+4'$
(88:J '5FXlm  
 9+&+%1
 	
r+   )	ro   r;  r9  r0  r?  r3  r>  rt  r1   r4   )NNNNNNNNNNNNN)r^   r_   r`   ra   rb   r   r   r   r   r6   rE  rK  rC   ro  rf   rE   r   r   r   r   rY   rg   rh   ri   s   @r)   rq  rq    s   | 8BLL;Q  ,!"
 1515=A=A,07;EI59$(,0/3&*15u
E,,-u
 !.u
  ((9(9:	u

 !))9)9 :u
 ELL)u
 'u||4u
 "%e.?.?(@"ABu
   1 12u
 D>u
 $D>u
 'tnu
 d^u
 !.u
 
uU\\"$MM	Nu
 u
r+   rq  c            $       j  ^  \ rS rSrSS/rS\4U 4S jjrS rS rS r	S	 r
S
 rS rS\S\R                  4S jr\                S!S\\R(                     S\\R*                     S\\R(                     S\\R*                     S\\R*                     S\\R*                     S\\R*                     S\\\\R*                     \4      S\\\\R2                           S\\R2                     S\\R2                     S\\   S\\   S\\   S\\   S\\R*                     S\4"S jj5       rS rU =r$ )"MarianModeli7  zencoder.embed_tokens.weightzdecoder.embed_tokens.weightrs   c                   > [         TU ]  U5        UR                  UR                  p2[        R
                  " X1R                  U5      U l        U R                  R                  (       a  U R                  =pEOG[        R                  " U R                  5      n[        R                  " U R                  5      nS U l        [        X5      U l        [        X5      U l        U R!                  5         g r4   )r5   r6   r   r:  r   r   r   sharedrs    share_encoder_decoder_embeddingscopydeepcopyr/  encoderrq  decoderr@  )r7   rs   r1   r:  encoder_embed_tokensdecoder_embed_tokensr8   s         r)   r6   MarianModel.__init__;  s     "("5"5v7H7HZ ll:~~{K;;77:>++E #7 $(==#= #'==#= DK$VB$VB 	r+   c                 >    U R                  5       R                  5       $ r4   )get_encoderrE  rD  s    r)   rE   MarianModel.get_input_embeddingsQ  s    !6688r+   c                     U R                   R                  (       a=  Xl        U R                  U R                  l        U R                  U R
                  l        g XR                  l        g r4   )rs   r  r  r  r0  r  rI  s     r)   rK   MarianModel.set_input_embeddingsU  s>    ;;77K(,DLL%(,DLL%(-LL%r+   c                     U R                   R                  (       a  [        S5      eU R                  5       R	                  5       $ )Nz`get_decoder_input_embeddings` should not be called if `config.share_encoder_decoder_embeddings` is `True`. Please use `get_input_embeddings` instead.)rs   r  r&   get_decoderrE  rD  s    r)   get_decoder_input_embeddings(MarianModel.get_decoder_input_embeddings]  s<    ;;77H  !6688r+   c                 p    U R                   R                  (       a  [        S5      eXR                  l        g )Na   `config.share_encoder_decoder_embeddings` is set to `True` meaning the decoder input embeddings are shared with the encoder. In order to set the decoder input embeddings, you should simply set the encoder input embeddings by calling `set_input_embeddings` with the appropriate embeddings.)rs   r  r&   r  r0  rI  s     r)   set_decoder_input_embeddings(MarianModel.set_decoder_input_embeddingse  s.    ;;77r 
 %*!r+   c                     U R                   $ r4   )r  rD  s    r)   r  MarianModel.get_encodern      ||r+   c                     U R                   $ r4   r  rD  s    r)   r  MarianModel.get_decoderq  r  r+   new_num_tokensr2   c                     U R                   R                  (       a  [        S5      eU R                  5       nU R	                  X!5      nU R                  U5        U R                  5       nUc  U$ XR                   l        U R                  5         U$ Nz`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` is `True`. Please use `resize_token_embeddings` instead.)rs   r  r&   r  _get_resized_embeddingsr  ru  tie_weights)r7   r  old_embeddingsnew_embeddingsmodel_embedss        r)   resize_decoder_token_embeddings+MarianModel.resize_decoder_token_embeddingst  s    ;;77K 
 ::<55nU)).988:! *8& 	r+   r   r   r   decoder_attention_maskrN  decoder_head_maskr}  encoder_outputsr   r   decoder_inputs_embedsr   r   rO  rP  r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUc  U R                  UUUU
UUUS9nORU(       aK  [        U[        5      (       d6  [        US   [        U5      S:  a  US   OS[        U5      S:  a  US   OSS9nU R                  UUUS   UUUU	UUUUUUS9nU(       d  UU-   $ [        UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  S9$ )	a?  
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Indices of decoder input sequence tokens in the vocabulary.

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

    [What are decoder input IDs?](../glossary#decoder-input-ids)

    Marian uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
    `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
    `past_key_values`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
    1]`:

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

Example:

```python
>>> from transformers import AutoTokenizer, MarianModel

>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> model = MarianModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")

>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer(
...     "<pad> Studien haben gezeigt dass es hilfreich ist einen Hund zu besitzen",
...     return_tensors="pt",
...     add_special_tokens=False,
... )
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 26, 512]
```N)r   r   rN  r   r   rO  rP  r   r   r;   rZ  r   r   r   r   rN  r}  r   r   r   r   rO  rP  r   )r[  r   decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentions)rs   r   rO  r   r]  r  r   r   r_  r  r   r[  r   r   r\  r  )r7   r   r   r   r  rN  r  r}  r  r   r   r  r   r   rO  rP  r   decoder_outputss                     r)   rY   MarianModel.forward  s   | 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]""ll#-#+"3%9' + O O_!M!M-"1!"4474H14Loa0RV14_1E1I?1-tO ,,'1"1!"4#1'!5+//!5#) ' 
  "_44!-??+;;"1"?"?.99,==&5&G&G"1"?"?.99	
 		
r+   )r  r  r  )NNNNNNNNNNNNNNNN)r^   r_   r`   ra   _tied_weights_keysr   r6   rE  rK  r  r  r  r  rc   r   r   r  r   r   rC   ro  rf   r   r   r   rE   r   r   rY   rg   rh   ri   s   @r)   r  r  7  s   79VW| ,9.9*c bll 0  15158<9=,0487;QUEI59=A$(,0/3&*15#s
E,,-s
 !.s
 $E$4$45	s

 !) 6s
 ELL)s
 $ELL1s
 'u||4s
 "%ell(;_(L"MNs
 "%e.?.?(@"ABs
   1 12s
  ((9(9:s
 D>s
 $D>s
 'tns
  d^!s
" !.#s
$ 
%s
 s
r+   r  zX
    The Marian Model with a language modeling head. Can be used for summarization.
    )custom_introc            &       B  ^  \ rS rSrSr/ SQrSS/r/ SQrS\4U 4S jjr	S	 r
S
 r S-S\S\\   S\S\R                   4U 4S jjjrS.S\S\R                   4S jjrS rS\SS4S jrS rS\R                   4S jrS r\                 S/S\\R4                     S\\R6                     S\\R4                     S\\R6                     S\\R6                     S\\R6                     S\\R6                     S\\\\R6                     \4      S \\\\R>                           S!\\R>                     S"\\R>                     S#\\R4                     S$\\   S%\\   S&\\   S'\\   S(\\R6                     S\ 4$S) jj5       r!S#\R6                  4S* jr"\#S+ 5       r$S,r%U =r&$ )0MarianMTModeli  r   )final_logits_biaszencoder.embed_positions.weightzdecoder.embed_positions.weightz$model.encoder.embed_positions.weightz$model.decoder.embed_positions.weight)z!model.encoder.embed_tokens.weightz!model.decoder.embed_tokens.weightlm_head.weightrs   c                 P  > [         TU ]  U5        [        U5      U l        UR                  (       a  UR
                  OUR                  nU R                  S[        R                  " SU45      5        [        R                  " UR                  USS9U l        U R                  5         g )Nr  r   Frv   )r5   r6   r  r   r  r:  ru  register_bufferrC   zerosr   r{   r   lm_headr@  )r7   rs   target_vocab_sizer8   s      r)   r6   MarianMTModel.__init__  s~      (
171X1XF--^d^w^w0%++qBS>T2UVyy1BO 	r+   c                 6    U R                   R                  5       $ r4   )r   r  rD  s    r)   r  MarianMTModel.get_encoder      zz%%''r+   c                 6    U R                   R                  5       $ r4   )r   r  rD  s    r)   r  MarianMTModel.get_decoder   r  r+   Nr  pad_to_multiple_ofmean_resizingr2   c                    > [         TU ]  XU5      nU R                  R                  (       a  U R	                  U5        U$ r4   )r5   resize_token_embeddingsrs   r  _resize_final_logits_bias)r7   r  r  r  r  r8   s        r)   r  %MarianMTModel.resize_token_embeddings#  s8     8]jk;;77**>:r+   c                    U R                  5       nU R                  XAU5      nU R                  U5        UR                  R                  S   nU R
                  R                  (       a  XR
                  l        U R
                  R                  (       a^  U R                  5       bM  U R
                  R                  (       d2  U R                  5       nU R                  Xa5      nU R                  U5        U R                  5       $ )Nr   )rE  r  rK  r>   r$   rs   r  ru  get_output_embeddingstie_word_embeddings_get_resized_lm_headset_output_embeddings)r7   r  r  argsr  r  old_lm_headnew_lm_heads           r)   _resize_token_embeddings&MarianMTModel._resize_token_embeddings,  s    22455nVhi!!.1'..44Q7;;77-;KK* KK88**,8KK33446K33KPK&&{3((**r+   c                 :   U R                   R                  (       a  [        S5      eU R                  R	                  5       nU R                  X!5      nU R                  R                  U5        U R                  5       bM  U R                   R                  (       d2  U R                  5       nU R                  XA5      nU R                  U5        U R                  R	                  5       nUc  U$ XR                   l        U R                  5         U R                  U5        U$ r  )rs   r  r&   r   r  r  r  r  r  r  r  ru  r  r  )r7   r  r  r  r  r  r  s          r)   r  -MarianMTModel.resize_decoder_token_embeddingsB  s    ;;77K 
 @@B55nU

//? %%'3DKK<[<[446K33KPK&&{3zz>>@! *8& 	&&~6r+   c                 ,   U R                   R                  S   nX::  a  U R                   S S 2S U24   nON[        R                  " SX-
  4U R                   R                  S9n[        R
                  " U R                   U/SS9nU R                  SU5        g )Nr"   r   r  r   r  )r  r$   rC   r  rV   catr  )r7   r  old_num_tokensnew_bias
extra_biass        r)   r  'MarianMTModel._resize_final_logits_biasb  s    //55b9+--a..@AHa)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r+   c                     U R                   $ r4   r  rD  s    r)   r  #MarianMTModel.get_output_embeddingsk  r  r+   r  c                     Xl         g r4   r  r7   r  s     r)   r  #MarianMTModel.set_output_embeddingsn      %r+   c                 r   U R                  5       nUbK  [        U R                  SS5      (       a/  U R                  5       R	                  5       nU R                  X5        [        U R                  SS5      (       a  [        U R                  SS5      (       ag  [        X R                  5      (       a  [        X R                  5      n U R                  U R                  U R                  U R                  S5      nX0l        U R                  5        H&  n[        US5      (       d  M  UR                  5         M(     g)	z
Tie the weights between the input embeddings and the output embeddings.

If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the
weights instead.
Nr  Tis_encoder_decoderFtie_encoder_decoderr  _tie_weights)r  getattrrs   r  rE  _tie_or_clone_weightshasattrr(  _tie_encoder_decoder_weightsr  r  _dynamic_tied_weights_keysmodulesr  )r7   output_embeddingsword_embeddingstied_weightsr   s        r)   r  MarianMTModel.tie_weightsq  s     !668(WT[[BWY]-^-^"..0EEGO&&'8J4;; 4e<<VkmrAsAst3344t%;%;<<<dllD,B,BIL /;+llnFv~..##% %r+   r   r   r   r  rN  r  r}  r  r   r   r  labelsr   r   rO  rP  r   c                    Ub  UOU R                   R                  nUbX  U(       a  [        R                  S5        SnUc7  Uc4  [	        XR                   R
                  U R                   R                  5      nU R                  UUUUUUUUU	U
UUUUUUS9nU R                  US   5      U R                  -   nSnUbF  [        5       nU" UR                  SU R                   R                  5      UR                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                   UR"                  UR$                  UR&                  UR(                  S9	$ )	u0  
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Indices of decoder input sequence tokens in the vocabulary.

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

    [What are decoder input IDs?](../glossary#decoder-input-ids)

    Marian uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
    `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
    `past_key_values`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
    1]`:

    - 1 indicates the head is **not masked**,
    - 0 indicates the head is **masked**.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
    Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
    config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
    (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

Example:

```python
>>> from transformers import AutoTokenizer, MarianMTModel

>>> src = "fr"  # source language
>>> trg = "en"  # target language

>>> model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
>>> model = MarianMTModel.from_pretrained(model_name)
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)

>>> sample_text = "où est l'arrêt de bus ?"
>>> batch = tokenizer([sample_text], return_tensors="pt")

>>> generated_ids = model.generate(**batch)
>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
"Where's the bus stop?"
```
NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r   r   r  r  rN  r  r}  r   r   r  r   r   rO  rP  r   r   r"   r   )	losslogitsr   r  r  r  r  r   r  )rs   r]  ry   warningr*   r   r    r   r  r  r   r   ru  r   r   r  r  r  r  r   r  )r7   r   r   r   r  rN  r  r}  r  r   r   r  r  r   r   rO  rP  r   r   	lm_logitsmasked_lm_lossloss_fctoutputs                          r)   rY   MarianMTModel.forward  s   F &1%<k$++B]B]klI (-B-J$6KK44dkk6X6X%! **)/+#9/!5+'"7/!5#)!  
$ LL,t/E/EE	')H%innR9W9W&XZ`ZeZefhZijN\GABK/F3A3M^%.YSYY#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r+   c                 j    [        XR                  R                  U R                  R                  5      $ r4   )r*   rs   r   r    )r7   r  s     r)   %prepare_decoder_input_ids_from_labels3MarianMTModel.prepare_decoder_input_ids_from_labels  s#    !&++*B*BDKKDfDfggr+   c                 b   ^ SnU  H%  nU[        U4S jUS S  5       5      USS  -   4-  nM'     U$ )Nr&  c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7fr]   index_selectr  rV   rV  
past_statebeam_idxs     r)   rX  /MarianMTModel._reorder_cache.<locals>.<genexpr>  s1     rcqU_--aZ=N=N1OPPcq   7:r;   rd  r   r  reordered_past
layer_pasts    `  r)   _reorder_cacheMarianMTModel._reorder_cache  sO    )JrcmnpopcqrrQR.! N * r+   )r  r  r   )NTr4   )NNNNNNNNNNNNNNNNN)'r^   r_   r`   ra   r(  _keys_to_ignore_on_load_missing_keys_to_ignore_on_saver  r   r6   r  r  rc   r   r   r   r   r  r  r  r  r  r  r  r   rC   ro  rf   r   r   r   rE   r   rY   r  r,  r  rg   rh   ri   s   @r)   r  r    s     '#
  FGmnu	| 	(( dh!7?}\`	 +s +_a_k_k +,@< < <&BLL &&8  15158<9=,0487;QUEI59=A-1$(,0/3&*15%t
E,,-t
 !.t
 $E$4$45	t

 !) 6t
 ELL)t
 $ELL1t
 'u||4t
 "%ell(;_(L"MNt
 "%e.?.?(@"ABt
   1 12t
  ((9(9:t
 ))*t
 D>t
 $D>t
  'tn!t
" d^#t
$ !.%t
& 
't
 t
lhELL h  r+   r  c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )MarianDecoderWrapperi  z
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
used in combination with the [`EncoderDecoderModel`] framework.
c                 D   > [         TU ]  U5        [        U5      U l        g r4   )r5   r6   rq  r  r7   rs   r8   s     r)   r6   MarianDecoderWrapper.__init__  s     $V,r+   c                 &    U R                   " U0 UD6$ r4   r  )r7   r  r  s      r)   rY   MarianDecoderWrapper.forward  s    ||T,V,,r+   r  )	r^   r_   r`   ra   rb   r6   rY   rg   rh   ri   s   @r)   r$  r$    s    
-- -r+   r$  c            "         ^  \ rS rSrS/rU 4S jrS rS rS rS r	S r
S	 r\              SS
\\R                     S\\R                      S\\R"                     S\\R"                     S\\R                      S\\R                      S\\\R"                        S\\R"                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4S jj5       r\S 5       rSrU =r$ )MarianForCausalLMi#  r  c                 
  > [         R                  " U5      nSUl        SUl        [        TU ]  U5        [        U5      U l        [        R                  " UR                  UR                  SS9U l        U R                  5         g )NTFrv   )r  r  rp   r  r5   r6   r$  r   r   r{   hidden_sizer:  r  r@  r&  s     r)   r6   MarianForCausalLM.__init__&  sf    v& $)! )&1
yy!3!3V5F5FUS 	r+   c                 B    U R                   R                  R                  $ r4   r   r  r0  rD  s    r)   rE  &MarianForCausalLM.get_input_embeddings2  s    zz!!...r+   c                 8    XR                   R                  l        g r4   r0  rI  s     r)   rK  &MarianForCausalLM.set_input_embeddings5  s    */

'r+   c                     U R                   $ r4   r  rD  s    r)   r  'MarianForCausalLM.get_output_embeddings8  r  r+   c                     Xl         g r4   r  r  s     r)   r  'MarianForCausalLM.set_output_embeddings;  r  r+   c                 $    XR                   l        g r4   r   r  )r7   r  s     r)   set_decoderMarianForCausalLM.set_decoder>  s    $

r+   c                 .    U R                   R                  $ r4   r9  rD  s    r)   r  MarianForCausalLM.get_decoderA  s    zz!!!r+   r   r   r   r   rN  r}  r   r   r  r   r   rO  rP  r   r2   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                  UUUUUUUUU
UUUUS9nU R                  US   5      nSnU	ba  U	R                  UR                  5      n	[        5       nU" UR                  SU R                   R                  5      U	R                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                  UR                   S9$ )a  
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

    - 1 indicates the head is **not masked**,
    - 0 indicates the head is **masked**.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
    Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
    config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
    (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

Example:

```python
>>> from transformers import AutoTokenizer, MarianForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-fr-en")
>>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-fr-en", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
```Nr  r   r"   r   )r  r  r   r   r\  r  )rs   r   rO  r]  r   r  r  r  rV   r   r   r:  r   r   r   r\  r  )r7   r   r   r   r   rN  r}  r   r   r  r   r   rO  rP  r   r   r  r  r  r  s                       r)   rY   MarianForCausalLM.forwardD  s[   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **$$)"7#9!5+'/!5#) % 
  gaj)YYv}}-F')HFKKDKK,B,BCV[[QS_UDY,F'+'7D7V#CVC0#33!//))$55
 	
r+   c                 P   ^ SnU  H  nU[        U4S jU 5       5      4-  nM     U$ )Nr&  c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7fr]   r  r  s     r)   rX  3MarianForCausalLM._reorder_cache.<locals>.<genexpr>  s1     ncmU_--aZ=N=N1OPPcmr  r  r  s    `  r)   r   MarianForCausalLM._reorder_cache  s8    )Jncmnn N * r+   )r  r   )NNNNNNNNNNNNNN)r^   r_   r`   ra   r  r6   rE  rK  r  r  r:  r  r   r   rC   ro  rf   rE   r   r   r   r   r   rY   r,  r  rg   rh   ri   s   @r)   r+  r+  #  s   *+
/0&%"  1515=A>B,07;=A59-1$(,0/3&*59W
E,,-W
 !.W
  ((9(9:	W

 !)):): ;W
 ELL)W
 'u||4W
 "$u'8'8"9:W
   1 12W
 ))*W
 D>W
 $D>W
 'tnW
 d^W
 !!1!12W
  
u77	8!W
 W
r  r+   r+  )r+  r  r  r   )Arb   r  r7  typingr   r   r   r   numpyr?   rC   torch.utils.checkpointr   torch.nnr   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   r   configuration_marianr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerr^   ry   rf   rc   r*   r   r-   Modulerk   r   r   r   r   r/  rq  r  r  r$  r+  __all__r&  r+   r)   <module>rU     s   D   / /     % ! 5 )  .  /  !!;J 
		H	%%,, c [^  -",, -FZBbii ZB|D DN $_5 s sl ]O ] ]@g
) g
TZ
) Z
z H
' H
 H
V 
H)? H
HX-0 -B- BJ Yr+   