
    g}6                       d Z ddlZddlZddlmZmZmZmZ ddlZ	ddl
Z
ddlZ
ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z# ddl$m%Z%  e"j&        e'          Z(dZ)dZ*de
j+        de,de,fdZ- G d dej.                  Z/ G d dej0                  Z1 G d dej0                  Z2de1iZ3 G d dej0                  Z4 G d de          Z5d Z6d!Z7d"Z8 G d# d$e5          Z9 G d% d&e5          Z: e d'e6           G d( d)e5                      Z; e d*e6           G d+ d,e5e                      Z< G d- d.e5          Z= G d/ d0e5e          Z>dS )1z=PyTorch MarianMTModel model, ported from the Marian C++ repo.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)GenerationMixin)_prepare_4d_attention_mask!_prepare_4d_causal_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)add_end_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )MarianConfigr   zHelsinki-NLP/opus-mt-en-de	input_idspad_token_iddecoder_start_token_idc                     |                      | j                  }| ddddf                                         |ddddf<   ||dddf<   |t          d          |                    |dk    |           |S )z1
    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       f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/marian/modeling_marian.pyshift_tokens_rightr'   7   s     "++IO<<(CRC06688aaae4aaadLMMM""#4#<lKKK    c            	            e Zd ZdZddededee         ddf fdZedej	        dej	        fd	            Z
 ej                    ddej        dedej        f fd            Z xZS )#MarianSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.Nnum_positionsembedding_dimpadding_idxreturnc                     t                                          ||           |                     | j                  | _        d S N)super__init___init_weightweight)selfr+   r,   r-   	__class__s       r&   r2   z,MarianSinusoidalPositionalEmbedding.__init__J   s8    666''44r(   outc           	         | j         \  }t          j        fdt          |          D                       }d| _        dz  dk    rdz  ndz  dz   }t          j        t          j        |dddddf                             | ddd|f<   t          j        t          j        |dddddf                             | dd|df<   | 	                                 | S )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:]
        c                 J    g | ]fd t                    D             S )c           	      R    g | ]#}t          j        d d|dz  z  z            z  $S )i'     )nppower).0jdimposs     r&   
<listcomp>zOMarianSinusoidalPositionalEmbedding._init_weight.<locals>.<listcomp>.<listcomp>V   s7    LLLAcBHUAaL3$6777LLLr(   )range)r>   rA   r@   s    @r&   rB   zDMarianSinusoidalPositionalEmbedding._init_weight.<locals>.<listcomp>V   s9    eeeQTLLLLLsLLLeeer(   Fr;   r   r   N)
r!   r<   arrayrC   requires_gradtorchFloatTensorsincosdetach_)r7   n_posposition_encsentinelr@   s       @r&   r3   z0MarianSinusoidalPositionalEmbedding._init_weightN   s     Y
sxeeeeX]^cXdXdeee
 
 ""Qw!||3!88#(a".rvl111add76K/L/LMMAAAqzM!-bf\!!!QTT'5J.K.KLLAAAxyyL
r(   r   input_ids_shapepast_key_values_lengthc                     |dd         \  }}t          j        |||z   t           j        | j        j                  }t                                          |          S )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr;   )dtypedevice)rF   arangelongr4   rR   r1   forward)r5   rN   rO   bszseq_len	positionsr6   s         r&   rU   z+MarianSinusoidalPositionalEmbedding.forward_   s]     'rr*WL"$:W$DEJ_c_j_q
 
 
	 wwy)))r(   r0   )r   )__name__
__module____qualname____doc__intr   r2   staticmethodr   	Parameterr3   rF   no_gradSizeTensorrU   __classcell__r6   s   @r&   r*   r*   G   s        NN5 5c 5# 5HUXM 5ei 5 5 5 5 5 5 ", 2<    \  U]__* *uz *3 *W\Wc * * * * * _* * * * *r(   r*   c                   h    e Zd ZdZ	 	 	 	 	 ddededed	ed
ededee         f fdZ	de
j        dedefdZ	 	 	 	 	 dde
j        dee
j                 deee
j                          dee
j                 dee
j                 dedee
j        ee
j                 eee
j                          f         fdZ xZS )MarianAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfigc                 
   t                                                       || _        || _        || _        ||z  | _        || _        | j        |z  | j        k    rt          d| j         d| d          | j        dz  | _        || _	        || _
        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩rl   )r1   r2   rh   ri   rj   head_dimrn   r#   scalingrk   rm   r   Lineark_projv_projq_projout_proj)	r5   rh   ri   rj   rk   rl   rm   rn   r6   s	           r&   r2   zMarianAttention.__init__m   s    	""!Y.MI%$.883dn 3 3%.3 3 3   }d*$"i	94@@@i	94@@@i	94@@@	)YTBBBr(   tensorrW   rV   c                     |                     ||| j        | j                                      dd                                          S )Nr   r;   )viewri   rq   	transpose
contiguous)r5   rx   rW   rV   s       r&   _shapezMarianAttention._shape   s<    {{3GGQQRSUVWWbbdddr(   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsr.   c                 Z
   |du}|                                 \  }}	}
|                     |          | j        z  }|r6|4|d         j        d         |j        d         k    r|d         }|d         }n>|rU|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j	        r||f}|| j
        z  d| j        f} |                     ||	|          j        | } |j        | } |j        | }|                     d          }t          j        ||                    dd                    }|                                 || j
        z  |	|fk    r2t!          d|| j
        z  |	|f d|                                            ||                                 |d|	|fk    r+t!          d	|d|	|f d|                                            |                    || j
        |	|          |z   }|                    || j
        z  |	|          }t"          j                            |d          }||                                 | j
        fk    r-t!          d
| j
        f d|                                            |                    dddd          |                    || j
        |	|          z  }|                    || j
        z  |	|          }|r=|                    || j
        |	|          }|                    || j
        z  |	|          }nd}t"          j                            || j        | j                  }t          j        ||          }|                                 || j
        z  |	| j        fk    r7t!          d|| j
        z  |	| j        f d|                                            |                    || j
        |	| j                  }|                    dd          }|                    ||	| j                  }|                     |          }|||fS )z#Input shape: Batch x Time x ChannelNr   r;   r   r   r@   z$Attention weights should be of size z	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizerv   rr   r!   r}   rt   ru   rF   catrk   ri   rq   rz   reshapebmmr{   r#   r   
functionalsoftmaxrj   r   rh   rw   )r5   r~   r   r   r   r   r   is_cross_attentionrV   tgt_len_query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r&   rU   zMarianAttention.forward   s    .T9',,..Wa {{=11DL@ 	L*q!'*.>.DQ.GGG (*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7NDN*B>
Ct{{<#>>CZP'Z'4
+|+Z8//!$$yz/C/CAq/I/IJJ3#7'"JJJ*dn8LgW^7_ * * %%''* *  
 %""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (,,S$.'7SSVddL',,S4>-A7GTTL},,\r,BB&##%%$.)::: 1t~FW 1 1',,..1 1   +//2q!<<|?P?PQTVZVdfmov?w?wwL',,S4>-A7GTTL 	)
 %1$5$5c4>7T[$\$\!055cDN6JGU\]]LL$(!]**<4<RVR_*``
i
L99#"6!OOO)C$.4H'SWS`3a ) )$$&&) )  
 "&&sDNGT]SS!++Aq11 "))#wGGmmK001>AAr(   )rg   FTFN)NNNNF)rY   rZ   r[   r\   r]   floatboolr   r   r2   rF   rb   r}   r   rU   rc   rd   s   @r&   rf   rf   j   s       GG  )-C CC C 	C
 C C C &C C C C C C>eU\ eC ec e e e e 488<1526"'vB vB|vB #5<0vB !u|!45	vB
 !.vB "%,/vB  vB 
u|Xel3XeEL>Q5RR	SvB vB vB vB vB vB vB vBr(   rf   c                        e Zd Zdef fdZ	 d
dej        dej        dej        dee         de	ej        eej                 f         f
d	Z
 xZS )MarianEncoderLayerrn   c                 *   t                                                       |j        | _        t	          |j                 | j        |j        |j        |          | _        t          j
        | j                  | _        |j        | _        t          |j                 | _        |j        | _        t          j        | j        |j                  | _        t          j        |j        | j                  | _        t          j
        | j                  | _        d S )N)rh   ri   rj   rn   )r1   r2   d_modelrh   MARIAN_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrj   r
   activation_functionactivation_fnactivation_dropoutrs   encoder_ffn_dimfc1fc2final_layer_normr5   rn   r6   s     r&   r2   zMarianEncoderLayer.__init__
  s    1&2MNn4,	
 
 
 %'L$@$@!~#F$>?"(";9T^V-CDD9V3T^DD "T^ < <r(   Fr~   r   r   r   r.   c                 |   |}|                      ||||          \  }}}t          j                            || j        | j                  }||z   }|                     |          }|}|                     |                     |                    }t          j                            || j        | j                  }| 	                    |          }t          j                            || j        | j                  }||z   }| 
                    |          }|j        t          j        k    rt          j        |                                          s&t          j        |                                          r9t          j        |j                  j        dz
  }t          j        || |          }|f}	|r|	|fz  }	|	S )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.
            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   rj   r   r   r   r   r   r   r   rQ   rF   float16isinfanyisnanfinfor   clamp)
r5   r~   r   r   r   residualr   r   clamp_valueoutputss
             r&   rU   zMarianEncoderLayer.forward  s   $ !)-')+/	 *8 *
 *
&|Q --mt|VZVc-dd =011-@@ **488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0--m<<%-//K&&**,, 005M0J0J0N0N0P0P 0  +m&9::>EK!KK<[YYYM " 	'&Gr(   )F)rY   rZ   r[   r   r2   rF   rG   r   r   r   rU   rc   rd   s   @r&   r   r   	  s        =| = = = = = =. -20 0(0 )0 *	0
 $D>0 
u (5+<"==	>0 0 0 0 0 0 0 0r(   r   eagerc                   b    e Zd Zdef fdZ	 	 	 	 	 	 	 	 ddej        deej                 deej                 d	eej                 d
eej                 deej                 deeej                          dee	         dee	         deej
        eeej
        ej
        f                  f         fdZ xZS )MarianDecoderLayerrn   c                    t                                                       |j        | _        t	          |j                 | j        |j        |j        dd|          | _        |j	        | _	        t          |j                 | _        |j        | _        t          j        | j                  | _        t	          |j                 | j        |j        |j        d|          | _        t          j        | j                  | _        t          j        | j        |j                  | _        t          j        |j        | j                  | _        t          j        | j                  | _        d S )NT)rh   ri   rj   rk   rm   rn   )rj   rk   rn   )r1   r2   r   rh   r   r   decoder_attention_headsr   r   rj   r
   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrs   decoder_ffn_dimr   r   r   r   s     r&   r2   zMarianDecoderLayer.__init__T  s*   1&2MNn4,
 
 
 ~#F$>?"(";$&L$@$@!4V5PQN*,
 
 
 (*|DN'C'C$9T^V-CDD9V3T^DD "T^ < <r(   NFTr~   r   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher.   c
                 x   |}
|
|dd         nd}|                      |||||          \  }}}t          j                            || j        | j                  }|
|z   }|                     |          }d}d}|z|}
|
|dd         nd}|                     ||||||          \  }}}t          j                            || j        | j                  }|
|z   }|                     |          }||z   }|}
|                     | 	                    |                    }t          j                            || j
        | j                  }|                     |          }t          j                            || j        | j                  }|
|z   }|                     |          }|f}|r|||fz  }|	r||fz  }|S )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.
        Nr;   )r~   r   r   r   r   r   )r~   r   r   r   r   r   )r   r   r   rj   r   r   r   r   r   r   r   r   r   )r5   r~   r   r   r   r   r   r   r   r   r   self_attn_past_key_valueself_attn_weightspresent_key_valuecross_attn_present_key_valuecross_attn_weightscross_attn_past_key_valuer   s                     r&   rU   zMarianDecoderLayer.forwardq  s,   < ! :H9S>"1"#5#5Y] >Bnn'3)+/ ?M ?
 ?
;(*; --mt|VZVc-dd =011-@@ (,$! ,$H @N?Yrss(;(;_c%NRN_N_+!65 :8"3 O` O OKM-/K M11-4<Z^Zg1hhM$}4M 88GGM !24P P !**488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0--m<< " 	?)+=>>G 	,)++Gr(   )NNNNNNFT)rY   rZ   r[   r   r2   rF   rb   r   r   r   rG   rU   rc   rd   s   @r&   r   r   S  sH       =| = = = = = =@ 268<9=26=A8<,1$(W W|W !.W  (5	W
 !) 6W "%,/W %-U\$:W !u|!45W $D>W D>W 
u (51BEDU1U+V"WW	XW W W W W W W Wr(   r   c                   b    e Zd ZeZdZdZdeej	        ej
        ef         fdZed             ZdS )MarianPreTrainedModelmodelTmodulec                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t                    rd S t          |t          j                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nrg   )meanstd)rn   init_std
isinstancer   rs   r4   datanormal_rl   zero_r*   	Embeddingr-   )r5   r   r   s      r&   _init_weightsz#MarianPreTrainedModel._init_weights  s    k"fbi(( 		?M&&CS&999{& &&((((( '& CDD 	?D-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r(   c                     | j         j        }t          j        g ddddd|gg| j                  }|                    |          ||d}|S )N)r      
      r;   r         r;   rR   )r   r   decoder_input_ids)rn   r   rF   rx   rR   ne)r5   	pad_tokenr   dummy_inputss       r&   r   z"MarianPreTrainedModel.dummy_inputs  sd    K,	L"2"2"2Q2q)4L!MVZVabbb	'll955"!*
 

 r(   N)rY   rZ   r[   r   config_classbase_model_prefixsupports_gradient_checkpointingr   r   rs   r   r*   r   propertyr    r(   r&   r   r     sl        L&*#?E")R\Cf*f$g ? ? ? ?   X  r(   r   aK  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`MarianConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
u4  
    Pytorch version of marian-nmt's transformer.h (c++). Designed for the OPUS-NMT translation checkpoints. Available
    models are listed [here](https://huggingface.co/models?search=Helsinki-NLP).

    Examples:

    ```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?"
    ```
ah  
    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)
        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.
        head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

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

        decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the decoder. 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. Mask values selected in `[0,
            1]`:

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

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        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.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.
        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`).
        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.
c                       e Zd ZdZddedeej                 f fdZd Z	d Z
	 	 	 	 	 	 	 ddej        d	eej                 d
eej                 deej                 dee         dee         dee         deeej                 ef         fdZ xZS )MarianEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`MarianEncoderLayer`].

    Args:
        config: MarianConfig
        embed_tokens (nn.Embedding): output embedding
    Nrn   embed_tokensc                 @   t                                                     j        | _        j        | _        j        }j        | _        j        | _	        j
        rt          j        |          nd| _        ||| _        n%t          j        j        || j                  | _        t%          j        || j                  | _        t          j        fdt+          j                  D                       | _        d| _        |                                  d S )N      ?c                 .    g | ]}t                    S r   )r   r>   r   rn   s     r&   rB   z*MarianEncoder.__init__.<locals>.<listcomp>  "    $f$f$fA%7%?%?$f$f$fr(   F)r1   r2   rj   encoder_layerdrop	layerdropr   r   r-   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtembed_scaler   r   r   
vocab_sizer*   embed_positions
ModuleListrC   encoder_layerslayersgradient_checkpointing	post_init)r5   rn   r   rh   r6   s    `  r&   r2   zMarianEncoder.__init__w  s      ~1N	!.$*$B!393IR49Y///s# ,D "V->	4K[ \ \DB*It7G 
  
 m$f$f$f$fvOdIeIe$f$f$fgg&+#r(   c                     | j         S r0   r   r5   s    r&   get_input_embeddingsz"MarianEncoder.get_input_embeddings        r(   c                     || _         d S r0   r  r5   values     r&   set_input_embeddingsz"MarianEncoder.set_input_embeddings      !r(   r   r   	head_maskinputs_embedsr   output_hidden_statesreturn_dictr.   c                 >   ||n| j         j        }||n| j         j        }||n| j         j        }||t	          d          |G|                     ||           |                                }|                    d|d                   }n.||                                dd         }nt	          d          ||                     |          | j	        z  }| 
                    |          }	||	z   }
t          j                            |
| j        | j                  }
|t          ||j                  }|rdnd}|rdnd}|k|                                d         t#          | j                  k    s;J dt#          | j                   d	|                                d          d
            t'          | j                  D ]\  }}|r||
fz   }d}| j        r!t)          j        g           }|| j        k     rd}|rd}nX| j        r0| j        r)|                     |j        |
||||         nd|          }n ||
||||         nd|          }|d         }
|r||d         fz   }|r||
fz   }|st5          d |
||fD                       S t7          |
||          S )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      K   | ]}||V  	d S r0   r   r>   vs     r&   	<genexpr>z(MarianEncoder.forward.<locals>.<genexpr>  s(      eeqWXWdWdWdWdWdeer(   last_hidden_stater~   
attentions)rn   r   r  use_return_dictr#   %warn_if_padding_and_no_attention_maskr   rz   r   r   r   r   r   rj   r   r   rQ   lenr  	enumeraterF   randr   r  _gradient_checkpointing_func__call__tupler   )r5   r   r   r  r  r   r  r  input_shape	embed_posr~   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r&   rU   zMarianEncoder.forward  se   \ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]  ]%>cddd"66y.QQQ#..**K!r;r?;;II&',,..ss3KKTUUU  --i884;KKM((55	%	1--mt|VZVc-dd %7H[\\N3=0:d  >>##A&DK    wDK8H8Hwwajaoaoaqaqrsatwww   #,DK"8"8  	F  	FC# C!/=2B!BG} #&+jnn#&77"G 1 ,. 4= $($E$E%.%&+4+@3d)% %MM %2M%&;D;P3VZ*;	% % %M !.a 0  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r(   r0   )NNNNNNN)rY   rZ   r[   r\   r   r   r   r   r2   r  r  rF   
LongTensorrb   rG   r   r   r   r   rU   rc   rd   s   @r&   r   r   m  sE         | 8BL;Q      2! ! !" " "
 '+59,059,0/3&*~
 ~
#~
 !!12~
 EL)	~

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

    Args:
        config: MarianConfig
        embed_tokens (nn.Embedding): output embedding
    Nrn   r   c                 P   t                                                     j        | _        j        | _        j        | _        j        | _        j	        rt          j        j                  nd| _        ||| _        n*t          j        j        j        | j                  | _        t%          j        j        | j                  | _        t          j        fdt+          j                  D                       | _        d| _        |                                  d S )Nr   c                 .    g | ]}t                    S r   )r   r   s     r&   rB   z*MarianDecoder.__init__.<locals>.<listcomp>0  r   r(   F)r1   r2   rj   decoder_layerdropr   r   r-   r   max_target_positionsr   r   r   r   r   r   r   r   decoder_vocab_sizer*   r   r   rC   decoder_layersr  r  r  )r5   rn   r   r6   s    ` r&   r2   zMarianDecoder.__init__   s	      ~1!.$*$B!8>8NW49V^444TW# ,D "V-FX\Xh i iDB*FND<L 
  
 m$f$f$f$fvOdIeIe$f$f$fgg&+#r(   c                     | j         S r0   r  r  s    r&   r  z"MarianDecoder.get_input_embeddings6  r	  r(   c                     || _         d S r0   r  r  s     r&   r  z"MarianDecoder.set_input_embeddings9  r  r(   r   r   r   r   r  cross_attn_head_maskpast_key_valuesr  r   r   r  r  r.   c                    |
|
n| j         j        }
||n| j         j        }|	|	n| j         j        }	||n| j         j        }||t          d          |1|                                }|                    d|d                   }n.||                                dd         }nt          d          ||d         d         j        d         nd}|| 	                    |          | j
        z  }t          ||||          }||t          ||j        |d                   }|                     ||          }||z   }t          j                            || j        | j                  }| j        r%| j        r|	rt(                              d	           d
}	|rdnd}|
rdnd}|
r|dnd}|	rdnd}t-          ||gddg          D ]u\  }}|n|                                d         t/          | j                  k    s>J d| dt/          | j                   d|                                d          d            vt3          | j                  D ]\  }}|r||fz  }| j        r t5          j        g           }|| j        k     r4|||         nd}| j        r?| j        r8|                     |j        |||||||         nd|||         ndd|
|	
  
        }n( ||||||||         nd|||         nd||
|		  	        }|d         }|	r|||
rdnd         fz  }|
r||d         fz  }|||d         fz  }|r||fz  }|	r|nd}|st?          d |||||fD                       S tA          |||||          S )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.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r;   )r   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r  r9  zThe `z` should be specified for r  r  )r   r   r   r   r   r   r   r   r	   r   c              3      K   | ]}||V  	d S r0   r   r  s     r&   r  z(MarianDecoder.forward.<locals>.<genexpr>  s0        =  === r(   )r  r:  r~   r  cross_attentions)!rn   r   r  r   r  r#   r   rz   r!   r   r   r   r   rQ   r   r   r   rj   r   r  loggerwarning_oncezipr  r  r   rF   r!  r   r"  r#  r$  r   )r5   r   r   r   r   r  r9  r:  r  r   r   r  r  r%  rO   rX   r~   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cache	attn_mask	mask_namer)  decoder_layerr,  r   r-  
next_caches                                r&   rU   zMarianDecoder.forward<  s   ` 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]  ]%>sttt"#..**K!r;r?;;II&',,..ss3KKdeee DSC^!3A!6!<Q!?!?de  --i884;KKM:K8N
 

 !,1G1S%?&(;[QS_& & &"
 ((6LMM	%	1--mt|VZVc-dd& 	"4= 	" "##p   "	 #7@BBD0:d&7h<Q<]rrdh#,6RR$ %(4H(IKYoKp$q$q 	 	 Iy$ ~~''*s4;/?/?@@@/I / /T[AQAQ / /!((+/ / / A@@ #,DK"8"8 /	@ /	@C# 6!m%55!} &+jnn#&775D5P_S11VZN* t}  $ A A!*!")*&/&;IcNN1E1Q(--W[%! ! !.!#1*?+A7@7LYs^^RV5I5U,S11[_#1&7'! ! ! *!,M V"}:K5RQQQR'S&UU"  @=#3"55(4(]1-=,??(   	2-!11+4>''$
 	  '5FXlm     
 9+&+%1
 
 
 	
r(   r0   )NNNNNNNNNNNN)rY   rZ   r[   r\   r   r   r   r   r2   r  r  rF   r.  rb   rG   r   r   r   r   rU   rc   rd   s   @r&   r0  r0    s         | 8BL;Q      ,! ! !" " "
 '+15=A=A,07;EI59$(,0/3&*P
 P
#P
 !.P
  ((9:	P

 !))9 :P
 EL)P
 'u|4P
 "%e.?(@"ABP
   12P
 D>P
 $D>P
 'tnP
 d^P
 
uU\"$MM	NP
 P
 P
 P
 P
 P
 P
 P
r(   r0  zTThe bare Marian Model outputting raw hidden-states without any specific head on top.c            #       d    e Zd ZddgZdef fdZd Zd Zd Zd Z	d	 Z
d
 Zdedej        fdZ ee           eee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d dej        deej                 deej                 deej                 deej                 deej                 deej                 deeeej                 ef                  deeeej                                   deej                 deej                 dee         dee         dee         dee         def d                        Z xZS )!MarianModelzencoder.embed_tokens.weightzdecoder.embed_tokens.weightrn   c                    t                                          |           |j        |j        }}t	          j        ||j        |          | _        | j        j	        r
| j        x}}n9t          j        | j                  }t          j        | j                  }d | _        t          ||          | _        t          ||          | _        |                                  d S r0   )r1   r2   r   r   r   r   r   sharedrn    share_encoder_decoder_embeddingscopydeepcopyr   encoderr0  decoderr  )r5   rn   r-   r   encoder_embed_tokensdecoder_embed_tokensr6   s         r&   r2   zMarianModel.__init__  s       "("5v7HZ l:v~{KK;7 	:>+E #7#7 $(=#=#= #'=#=#= DK$V-ABB$V-ABB 	r(   c                 N    |                                                                  S r0   )get_encoderr  r  s    r&   r  z MarianModel.get_input_embeddings+  s     !!66888r(   c                     | j         j        r+|| _        | j        | j        _        | j        | j        _        d S || j        _        d S r0   )rn   rM  rL  rP  r   rQ  r  s     r&   r  z MarianModel.set_input_embeddings/  sD    ;7 	.DK(,DL%(,DL%%%(-DL%%%r(   c                     | j         j        rt          d          |                                                                 S )Nz`get_decoder_input_embeddings` should not be called if `config.share_encoder_decoder_embeddings` is `True`. Please use `get_input_embeddings` instead.)rn   rM  r#   get_decoderr  r  s    r&   get_decoder_input_embeddingsz(MarianModel.get_decoder_input_embeddings7  sG    ;7 	H   !!66888r(   c                 T    | j         j        rt          d          || j        _        d S )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.)rn   rM  r#   rQ  r   r  s     r&   set_decoder_input_embeddingsz(MarianModel.set_decoder_input_embeddings?  s9    ;7 	r  
 %*!!!r(   c                     | j         S r0   )rP  r  s    r&   rU  zMarianModel.get_encoderH  
    |r(   c                     | j         S r0   rQ  r  s    r&   rX  zMarianModel.get_decoderK  r]  r(   new_num_tokensr.   c                 *   | j         j        rt          d          |                                 }|                     ||          }|                     |           |                                 }||S || j         _        |                                  |S Nz`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` is `True`. Please use `resize_token_embeddings` instead.)rn   rM  r#   rY  _get_resized_embeddingsr[  r5  tie_weights)r5   r`  old_embeddingsnew_embeddingsmodel_embedss        r&   resize_decoder_token_embeddingsz+MarianModel.resize_decoder_token_embeddingsN  s    ;7 	K  
 ::<<55nnUU)).99988::! *8& 	r(   output_typer   Nr   r   r   decoder_attention_maskr  decoder_head_maskr9  encoder_outputsr:  r  decoder_inputs_embedsr   r   r  r  c                 d   ||n| j         j        }||n| j         j        }||n| j         j        }||n| j         j        }||                     ||||
|||          }ne|rct          |t                    sNt          |d         t          |          dk    r|d         ndt          |          dk    r|d         nd          }| 	                    |||d         ||||	|||||          }|s||z   S t          |j        |j        |j        |j        |j        |j        |j        |j                  S )	aX  
        Returns:

        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   r  r  r   r  r  r   r   r;   r  r   r   r   r   r  r9  r:  r  r   r   r  r  )r  r:  decoder_hidden_statesdecoder_attentionsr=  encoder_last_hidden_stater   encoder_attentions)rn   r   r  r   r  rP  r   r   r  rQ  r   r  r:  r~   r  r=  )r5   r   r   r   rk  r  rl  r9  rm  r:  r  rn  r   r   r  r  decoder_outputss                    r&   rU   zMarianModel.forwardf  s   V 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]""ll#-#+"3%9' +  OO  	O_!M!M 	-"1!"4474H4H14L4Loa00RV14_1E1E1I1I?1--t  O ,,'1"1!"4#1'!5+//!5# ' 
 
  	5"_44!-?+;"1"?.9,=&5&G"1"?.9	
 	
 	
 		
r(   )NNNNNNNNNNNNNNN) rY   rZ   r[   _tied_weights_keysr   r2   r  r  rY  r[  rU  rX  r]   r   r   rh  r   MARIAN_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCrF   r.  r   rb   r   r   r   rG   r   rU   rc   rd   s   @r&   rJ  rJ    s|        89VW|      ,9 9 9. . .9 9 9* * *    c bl    0 +*+BCC+=O\\\ '+158<9=,0487;QUEI59=A$(,0/3&*!^
 ^
#^
 !.^
 $E$45	^

 !) 6^
 EL)^
 $EL1^
 'u|4^
 "%el(;_(L"MN^
 "%e.?(@"AB^
   12^
  ((9:^
 D>^
 $D>^
 'tn^
  d^!^
" 
#^
 ^
 ^
 ]\ DC^
 ^
 ^
 ^
 ^
r(   rJ  zNThe Marian Model with a language modeling head. Can be used for summarization.c            &       4    e Zd ZdZg dZddgZg dZdef fdZd Z	d	 Z
d*dedee         dej        f fdZd*dedej        fdZd Zdedd
fdZd Zdej        fdZd Z ee           eee           ee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+dej        deej                 deej                 deej                 deej                 deej                 deej                 dee e!ej                 e"f                  dee!e!ej#                                   d eej#                 d!eej#                 d"eej                 d#ee$         d$ee$         d%ee$         d&ee$         def"d'                                    Z%d"ej        fd(Z&e'd)             Z( xZ)S ),MarianMTModelr   )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.weightrn   c                 Z   t                                          |           t          |          | _        |j        r|j        n|j        }|                     dt          j	        d|f                     t          j        |j        |d          | _        |                                  d S )Nr{  r   Frp   )r1   r2   rJ  r   rM  r   r5  register_bufferrF   zerosr   rs   r   lm_headr  )r5   rn   target_vocab_sizer6   s      r&   r2   zMarianMTModel.__init__  s        ((
171XwF--^d^w0%+qBS>T2U2UVVVy1BOOO 	r(   c                 4    | j                                         S r0   )r   rU  r  s    r&   rU  zMarianMTModel.get_encoder      z%%'''r(   c                 4    | j                                         S r0   )r   rX  r  s    r&   rX  zMarianMTModel.get_decoder  r  r(   Nr`  pad_to_multiple_ofr.   c                     t                                          ||          }| j        j        r|                     |           |S r0   )r1   resize_token_embeddingsrn   rM  _resize_final_logits_bias)r5   r`  r  rf  r6   s       r&   r  z%MarianMTModel.resize_token_embeddings  sD    88I[\\;7 	;**>:::r(   c                    |                                  }|                     |||          }|                     |           |j        j        d         }| j        j        r|| j        _        | j        j        r_|                                 K| j        j	        s?|                                 }| 
                    ||          }|                     |           |                                  S )Nr   )r  rc  r  r4   r!   rn   rM  r5  get_output_embeddingstie_word_embeddings_get_resized_lm_headset_output_embeddings)r5   r`  r  argsre  rf  old_lm_headnew_lm_heads           r&   _resize_token_embeddingsz&MarianMTModel._resize_token_embeddings  s    224455nnVhii!!.111'.4Q7;7 	<-;DK* K8	4**,,8K3 9 4466K33KPPK&&{333((***r(   c                 0   | j         j        rt          d          | j                                        }|                     ||          }| j                            |           |                                 K| j         j        s?|                                 }| 	                    ||          }| 
                    |           | j                                        }||S || j         _        |                                  |                     |           |S rb  )rn   rM  r#   r   rY  rc  r[  r  r  r  r  r5  rd  r  )r5   r`  re  rf  r  r  rg  s          r&   rh  z-MarianMTModel.resize_decoder_token_embeddings  s   ;7 	K  
 @@BB55nnUU
//??? %%''3DK<[34466K33KPPK&&{333z>>@@! *8& 	&&~666r(   c                    | j         j        d         }||k    r| j         d d d |f         }nBt          j        d||z
  f| j         j                  }t          j        | j         |gd          }|                     d|           d S )Nr   r   r   r   r{  )r{  r!   rF   r  rR   r   r~  )r5   r`  old_num_tokensnew_bias
extra_biass        r&   r  z'MarianMTModel._resize_final_logits_bias$  s    /5b9^++-aaa..@AHHa.)H%IRVRhRopppJy$"8*!E1MMMH0(;;;;;r(   c                     | j         S r0   r  r  s    r&   r  z#MarianMTModel.get_output_embeddings-  r]  r(   rf  c                     || _         d S r0   r  r5   rf  s     r&   r  z#MarianMTModel.set_output_embeddings0      %r(   c                 T   |                                  }|Rt          | j        dd          r<|                                                                 }|                     ||           t          | j        dd          rnt          | j        dd          rXt          | | j                  rt          | | j                  } |                     | j	        | j
        | j        d          }|| _        |                                 D ]&}t          |d          r|                                 'dS )	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_decoderrP  _tie_weights)r  getattrrn   rX  r  _tie_or_clone_weightshasattrr   _tie_encoder_decoder_weightsrP  rQ  _dynamic_tied_weights_keysmodulesr  )r5   output_embeddingsword_embeddingstied_weightsr   s        r&   rd  zMarianMTModel.tie_weights3  s/    !6688(WT[BWY]-^-^("..00EEGGO&&'8/JJJ4; 4e<< 		;VkmrAsAs 		;tT344 =tT%;<<<<dlD,BI L /;D+llnn 	& 	&Fv~.. &##%%%	& 	&r(   ri  r   r   r   rk  r  rl  r9  rm  r:  r  rn  labelsr   r   r  r  c                    ||n| j         j        }|G|rt                              d           d}|'|%t	          || j         j        | j         j                  }|                     |||||||||	|
|||||          }|                     |d                   | j	        z   }d}|Kt                      } ||                    d| j         j                  |                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j        |j        |j        |j        	  	        S )	a  
        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]`.

        Returns:

        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r   r   rm  rk  r  rl  r9  r:  r  rn  r   r   r  r  r   r   r   )	losslogitsr:  rq  rr  r=  rs  r   rt  )rn   r  r>  warningr'   r   r   r   r  r{  r   rz   r5  r   r:  rq  rr  r=  rs  r   rt  )r5   r   r   r   rk  r  rl  r9  rm  r:  r  rn  r  r   r   r  r  r   	lm_logitsmasked_lm_lossloss_fctoutputs                         r&   rU   zMarianMTModel.forwardO  s   > &1%<kk$+B] mklllI (-B-J$6DK4dk6X% %! **)/+#9/!5+'"7/!5#  
 
" LL,,t/EE	'))H%XinnR9W&X&XZ`ZeZefhZiZijjN 	Z\GABBK/F3A3M^%..SYY#3")"?&9$5&-&G")"?&9

 

 

 
	
r(   c                 L    t          || j        j        | j        j                  S r0   )r'   rn   r   r   )r5   r  s     r&   %prepare_decoder_input_ids_from_labelsz3MarianMTModel.prepare_decoder_input_ids_from_labels  s    !&$+*BDKDfgggr(   c                 z    d}| D ]4}|t          fd|d d         D                       |dd          z   fz  }5|S )Nr   c              3   t   K   | ]2}|                     d                     |j                            V  3dS r   Nindex_selecttorR   r>   
past_statebeam_idxs     r&   r  z/MarianMTModel._reorder_cache.<locals>.<genexpr>  sC      rrU_j--aZ=N1O1OPPrrrrrrr(   r;   r$  r:  r  reordered_past
layer_pasts    `  r&   _reorder_cachezMarianMTModel._reorder_cache  sm    ) 	 	JrrrrcmnpopnpcqrrrrrQRR.! NN r(   r0   )NNNNNNNNNNNNNNNN)*rY   rZ   r[   r   _keys_to_ignore_on_load_missing_keys_to_ignore_on_saverv  r   r2   rU  rX  r]   r   r   r   r  r  rh  r  r  r  rd  r   rw  r   r   rx  r   MARIAN_GENERATION_EXAMPLErF   r.  rb   r   r   r   rG   r   rU   r  r^   r  rc   rd   s   @r&   rz  rz    s         ' ' '#
  FGmnuuu	| 	 	 	 	 	 	( ( (( ( ( c xX[} hjht      + +s +_a_k + + + +,  @< < < < < <  &BL & & & && & &8 +*+BCC?YYY122 '+158<9=,0487;QUEI59=A-1$(,0/3&*#M
 M
#M
 !.M
 $E$45	M

 !) 6M
 EL)M
 $EL1M
 'u|4M
 "%el(;_(L"MNM
 "%e.?(@"ABM
   12M
  ((9:M
 )*M
 D>M
 $D>M
  'tn!M
" d^#M
$ 
%M
 M
 M
 32 ZY DCM
^hEL h h h h   \    r(   rz  c                   (     e Zd ZdZ fdZd Z xZS )MarianDecoderWrapperz
    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                 r    t                                          |           t          |          | _        d S r0   )r1   r2   r0  rQ  r   s     r&   r2   zMarianDecoderWrapper.__init__  s.       $V,,r(   c                      | j         |i |S r0   r_  )r5   r  kwargss      r&   rU   zMarianDecoderWrapper.forward  s    t|T,V,,,r(   )rY   rZ   r[   r\   r2   rU   rc   rd   s   @r&   r  r    sQ         
- - - - -- - - - - - -r(   r  c                        e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 eee	          	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 deej                 deeej                          deej                 deej                 dee         dee         dee         dee         deeef         fd            Zed             Z xZS )MarianForCausalLMr|  c                 *   t          j        |          }d|_        d|_        t	                                          |           t          |          | _        t          j	        |j
        |j        d          | _        |                                  d S )NTFrp   )rN  rO  rk   r  r1   r2   r  r   r   rs   hidden_sizer   r  r  r   s     r&   r2   zMarianForCausalLM.__init__  s    v&& $)!   )&11
y!3V5FUSSS 	r(   c                 $    | j         j        j        S r0   r   rQ  r   r  s    r&   r  z&MarianForCausalLM.get_input_embeddings  s    z!..r(   c                 (    || j         j        _        d S r0   r  r  s     r&   r  z&MarianForCausalLM.set_input_embeddings  s    */
'''r(   c                     | j         S r0   r  r  s    r&   r  z'MarianForCausalLM.get_output_embeddings  r]  r(   c                     || _         d S r0   r  r  s     r&   r  z'MarianForCausalLM.set_output_embeddings  r  r(   c                     || j         _        d S r0   r   rQ  )r5   rQ  s     r&   set_decoderzMarianForCausalLM.set_decoder  s    $
r(   c                     | j         j        S r0   r  r  s    r&   rX  zMarianForCausalLM.get_decoder  s    z!!r(   ri  Nr   r   r   r   r  r9  r:  r  r  r   r   r  r  r.   c                 <   ||n| j         j        }||n| j         j        }||n| j         j        }| j                            |||||||||
|||          }|                     |d                   }d}|	e|	                    |j                  }	t                      } ||
                    d| j         j                  |	
                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j                  S )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, 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]`:
            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. 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)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

                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)`.
            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]`.
            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`).

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            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.

        Returns:

        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
        ```Nrp  r   r   r   )r  r  r:  r~   r  r=  )rn   r   r  r  r   rQ  r  r  rR   r   rz   r   r   r:  r~   r  r=  )r5   r   r   r   r   r  r9  r:  r  r  r   r   r  r  r   r  r  r  r  s                      r&   rU   zMarianForCausalLM.forward  se   L 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] *$$)"7#9!5+'/!5# % 
 
 gaj))YYv}--F'))H8FKKDK,BCCV[[QS__UUD 	DY,F'+'7D7V##VC0#3!/)$5
 
 
 	
r(   c                 T    d}| D ]!}|t          fd|D                       fz  }"|S )Nr   c              3   t   K   | ]2}|                     d                     |j                            V  3dS r  r  r  s     r&   r  z3MarianForCausalLM._reorder_cache.<locals>.<genexpr>w  sC      nnU_j--aZ=N1O1OPPnnnnnnr(   r  r  s    `  r&   r  z MarianForCausalLM._reorder_cacher  sQ    ) 	 	Jnnnncmnnnnn NN r(   )NNNNNNNNNNNNN)rY   rZ   r[   rv  r2   r  r  r  r  r  rX  r   r   rx  rF   r.  r   rb   rG   r   r   r   r   rU   r^   r  rc   rd   s   @r&   r  r    s       *+
 
 
 
 
/ / /0 0 0  & & &% % %" " " +L[jkkk '+15=A>B,07;=A59-1$(,0/3&*N
 N
#N
 !.N
  ((9:	N

 !)): ;N
 EL)N
 'u|4N
 "$u'8"9:N
   12N
 )*N
 D>N
 $D>N
 'tnN
 d^N
 
u77	8N
 N
 N
 lkN
`   \    r(   r  )?r\   rN  r   typingr   r   r   r   numpyr<   rF   torch.utils.checkpointr   torch.nnr   activationsr
   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   r   r   configuration_marianr   
get_loggerrY   r>  rx  _CHECKPOINT_FOR_DOCrb   r]   r'   r   r*   Modulerf   r   r   r   r   MARIAN_START_DOCSTRINGr  rw  r   r0  rJ  rz  r  r  r   r(   r&   <module>r     sk   D C   / / / / / / / / / / / /                % % % % % % ! ! ! ! ! ! ) ) ) ) ) ) e e e e e e e e              . - - - - -              / . . . . . 
	H	%	% 2 %, c [^     * * * * *", * * *F[B [B [B [B [Bbi [B [B [B~C C C C C C C CL $_5 u u u u u u u up    O   <   2X vg
 g
 g
 g
 g
) g
 g
 g
Tu
 u
 u
 u
 u
) u
 u
 u
p Z\r t
 t
 t
 t
 t
' t
 t
 t
n TVl a a a a a)? a a aJ- - - - -0 - - -y y y y y- y y y y yr(   