
    gf                    $   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m
Z
 ddlmZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZ dd
lmZmZ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'm(Z(m)Z)m*Z* ddl+m,Z,  e'            rddl-m.Z.  e)j/        e0          Z1dZ2dZ3g dZ4dej5        de6fdZ7 G d de
j8                  Z9 G d de
j8                  Z: G d de
j;                  Z< G d de<          Z= G d de<          Z>e<e>e=d Z? G d! d"e
j;                  Z@ G d# d$e
j;                  ZA G d% d&e
j;                  ZB G d' d(e!          ZCd)ZDd*ZEd+ZF G d, d-eC          ZG G d. d/eC          ZH e%d0eD           G d1 d2eC                      ZI e%d3eD           G d4 d5eCe                      ZJ e%d6eD           G d7 d8eC                      ZK e%d9eD           G d: d;eC                      ZL G d< d=eC          ZM G d> d?eCe          ZNdS )@zPyTorch MBART model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GenerationMixin)_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_end_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )MBartConfig)_flash_attention_forwardzfacebook/mbart-large-cc25r#   )r"      i   	input_idspad_token_idc                    |                                  }|t          d          |                    |dk    |           |                    |                              d          dz
                      d          }|                    d|                                          }|ddddf                                          |ddddf<   ||dddf<   |S )z
    Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not
    have a single `decoder_start_token_id` in contrast to other Bart-like models.
    Nz1self.model.config.pad_token_id has to be defined.ir"   dimr   )clone
ValueErrormasked_fill_nesum	unsqueezegathersqueeze)r&   r'   prev_output_tokensindex_of_eosdecoder_start_tokenss        d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/mbart/modeling_mbart.pyshift_tokens_rightr8   F   s    
 #**LMMM##$6$$>MMM&)),77;;;BBQFQQRTUUL-44QEEMMOO 2111crc6 : @ @ B Bqqq!""u3qqq!t    c                   L     e Zd ZdZdedef fdZd	dej        def fdZ xZ	S )
MBartLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                 j    d| _         t                                          || j         z   |           d S N   )offsetsuper__init__)selfr<   r=   	__class__s      r7   rC   z(MBartLearnedPositionalEmbedding.__init__`   s3     $+5}EEEEEr9   r   r&   past_key_values_lengthc                     |j         dd         \  }}t          j        |||z   t          j        | j        j                                      |d          }t                                          || j	        z             S )z3`input_ids' shape is expected to be [bsz x seqlen].Nr@   )dtypedevicer+   )
shapetorcharangelongweightrI   expandrB   forwardrA   )rD   r&   rF   bszseq_len	positionsrE   s         r7   rP   z'MBartLearnedPositionalEmbedding.forwardf   sv     !rr*WL"$:W$DEJ_c_j_q
 
 

&b// 	 wwy4;6777r9   )r   )
__name__
__module____qualname____doc__intrC   rK   TensorrP   __classcell__rE   s   @r7   r;   r;   [   s         Fs F3 F F F F F F8 8 8s 8 8 8 8 8 8 8 8 8 8r9   r;   c            
       \     e Zd ZdZd
dedededee         f fdZdej	        f fd	Z
 xZS )MBartScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
          ?r<   r=   padding_idxembed_scalec                 \    t                                          |||           || _        d S N)rB   rC   r`   )rD   r<   r=   r_   r`   rE   s        r7   rC   z!MBartScaledWordEmbedding.__init__w   s-    DDD&r9   r&   c                 V    t                                          |          | j        z  S rb   )rB   rP   r`   )rD   r&   rE   s     r7   rP   z MBartScaledWordEmbedding.forward{   s!    wwy))D,<<<r9   )r^   )rT   rU   rV   rW   rX   r   floatrC   rK   rY   rP   rZ   r[   s   @r7   r]   r]   r   s         ' 's '3 'S '_ghm_n ' ' ' ' ' '= = = = = = = = = = =r9   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 )MBartAttentionz=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   )rB   rC   rh   ri   rj   head_dimrn   r-   scalingrk   rm   r   Lineark_projv_projq_projout_proj)	rD   rh   ri   rj   rk   rl   rm   rn   rE   s	           r7   rC   zMBartAttention.__init__   s    	""!Y.MI%$.883dn 3 3%.3 3 3   }d*$"i	94@@@i	94@@@i	94@@@	)YTBBBr9   tensorrR   rQ   c                     |                     ||| j        | j                                      dd                                          S )Nr"   r@   )viewri   rq   	transpose
contiguousrD   rx   rR   rQ   s       r7   _shapezMBartAttention._shape   s<    {{3GGQQRSUVWWbbdddr9   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsreturnc                 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 )#Input shape: Batch x Time x ChannelNr   r@   r"   r+   r)   z$Attention weights should be of size 	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptraining `attn_output` should be of size )sizerv   rr   rJ   r~   rt   ru   rK   catrk   ri   rq   rz   reshapebmmr{   r-   r   
functionalsoftmaxrj   r   rh   rw   )rD   r   r   r   r   r   r   is_cross_attentionrQ   tgt_len_query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r7   rP   zMBartAttention.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Ar9   )rg   FTFNNNNNF)rT   rU   rV   rW   rX   rd   boolr   r#   rC   rK   rY   r~   r   rP   rZ   r[   s   @r7   rf   rf      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r9   rf   c                   2    e Zd ZdZ 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 )MBartFlashAttention2aF  
    MBart flash attention module. This module inherits from `MBartAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S rb   )rB   rC   r   _flash_attn_uses_top_left_mask)rD   argskwargsrE   s      r7   rC   zMBartFlashAttention2.__init__'  s9    $)&)))
 3V2W2W.W+++r9   rx   rR   rQ   c                 F    |                     ||| j        | j                  S rb   )rz   ri   rq   r}   s       r7   _reshapezMBartFlashAttention2._reshape/  s    {{3GGGr9   NFr   r   r   r   r   r   r   c           
      R   |rt          d          |d u}|                                \  }}	}
|                     |                     |          d|          }|r^|\|d         j        d         |j        d         k    r:|d                             dd          }|d                             dd          }ng|rV|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j	        |d                             dd          |gd          }t          j	        |d                             dd          |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j
        r,|                    dd          |                    dd          f}|j        d         }|||d         j        d         z  }|j        }|t          j        k    rt          j                    rt          j                    }n3t          | j        d          r| j        j        }n| j        j        j        }t&                              d	| d
           |                    |          }|                    |          }|                    |          }t-          |||||	| j        r| j        nd| j        | j                  }|                    ||	d          }|                     |          }|sd }|||fS )NzAMBartFlashAttention2 attention does not support output_attentionsr+   r   r@   r"   r)   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .rg   )rj   rm   use_top_left_mask)r-   r   r   rv   rJ   r{   rt   ru   rK   r   rk   rH   float32is_autocast_enabledget_autocast_gpu_dtypehasattrrn   r   rN   loggerwarning_oncetor$   r   rj   rm   r   r   rw   )rD   r   r   r   r   r   r   r   rQ   q_lenr   r   r   r   
kv_seq_leninput_dtypetarget_dtyper   r   s                      r7   rP   zMBartFlashAttention2.forward2  s     	b`aaa .T9%**,,UA }}T[[%?%?SII 	N*q!'*.>.DQ.GGG (*44Q::J)!,66q!<<LL 	Nt{{3C'D'Db#NNJ==5E)F)FCPPLL't{{='A'A2sKKJ==])C)CRMMLN1$5$?$?1$E$Ez#RXYZZZJ 9nQ&7&A&A!Q&G&G%V\]^^^LL t{{='A'A2sKKJ==])C)CRMML? 	X )221a88,:P:PQRTU:V:VWN%b)
%.+1"55J #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.$(M:DLLsn"A	
 	
 	
 "))#ub99mmK00  	 LL.88r9   r   )rT   rU   rV   rW   rC   rK   rY   rX   r   r   r   r   rP   rZ   r[   s   @r7   r   r     s;        X X X X XHu| Hc H H H H H 488<1526"'i9 i9|i9 #5<0i9 !u|!45	i9
 !.i9 "%,/i9  i9 
u|Xel3XeEL>Q5RR	Si9 i9 i9 i9 i9 i9 i9 i9r9   r   c                   
    e Z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 fd
Z xZ	S )MBartSdpaAttentionNFr   r   r   r   r   r   r   c                    |s|At                               d           t                                          ||||||          S |du}|                                \  }}	}
|                     |          }|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        r
||	dk    rd	nd
}t          j        j                            ||||| j        r| j        nd|          }|                                || j        |	| j        fk    r5t+          d|| j        |	| j        f d|                                           |                    dd          }|                    ||	| j                  }|                     |          }|d|fS )r   Na  MBartModel is using MBartSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r   r   r   r   r@   r"   r+   r)   TFrg   )	attn_mask	dropout_prm   r   r   )r   r   rB   rP   r   rv   rJ   r~   rt   ru   rK   r   rk   rm   r   r   scaled_dot_product_attentionr   rj   ri   rq   r-   r{   r   rh   rw   )rD   r   r   r   r   r   r   r   rQ   r   r   r   r   r   rm   r   rE   s                   r7   rP   zMBartSdpaAttention.forward  sK     	 ;l   77??!1-- /"3 #    .T9',,..Wa {{=11 	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{{<#>>
 !N`~/E'TU++DD[`	 h)FF$&*m<dll G 
 
 #t~w!NNN)CRVR_3` ) )$$&&) )  
 "++Aq11 "))#wGGmmK00D.00r9   r   )
rT   rU   rV   rK   rY   r   r   r   rP   rZ   r[   s   @r7   r   r     s         488<1526"'f1 f1|f1 #5<0f1 !u|!45	f1
 !.f1 "%,/f1  f1 
u|Xel3XeEL>Q5RR	Sf1 f1 f1 f1 f1 f1 f1 f1 f1 f1r9   r   )eagersdpaflash_attention_2c                   l     e Zd Zdef fdZ	 d
dej        dej        dej        dedej        f
d	Z xZ	S )MBartEncoderLayerrn   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   )rB   rC   d_modelrh   MBART_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rD   rn   rE   s     r7   rC   zMBartEncoderLayer.__init__  s    01LMn4,	
 
 
 %'L$@$@!~#F$>?"(";9T^V-CDD9V3T^DD "T^ < <r9   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   r   rj   r   r   r   r   r   r   rH   rK   float16isinfanyisnanfinfor   clamp)
rD   r   r   r   r   residualr   r   clamp_valueoutputss
             r7   rP   zMBartEncoderLayer.forward#  s   $ !11-@@)-')+/	 *8 *
 *
&|Q --mt|VZVc-dd =0 --m<<**488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0%-//K&&**,, 005M0J0J0N0N0P0P 0  +m&9::>EK!KK<[YYYM " 	'&Gr9   )F)
rT   rU   rV   r#   rC   rK   rY   r   rP   rZ   r[   s   @r7   r   r     s        ={ = = = = = =. #(0 0|0 0 	0
  0 
0 0 0 0 0 0 0 0r9   r   c                   "    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j        fdZ
 xZS )MBartDecoderLayerrn   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   )rB   rC   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     r7   rC   zMBartDecoderLayer.__init__W  s*   01LMn4,
 
 
 ~#F$>?"(";$&L$@$@!3F4OPN*,
 
 
 (*|DN'C'C$9T^V-CDD9V3T^DD "T^ < <r9   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   r   r   rj   r   r   r   r   r   r   r   r   )rD   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                     r7   rP   zMBartDecoderLayer.forwardt  s,   < !11-@@ :H9S>"1"#5#5Y] >Bnn'3)+/ ?M ?
 ?
;(*; --mt|VZVc-dd =0 (,$! ,$H 88GGM @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 !24P P !--m<<**488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0 " 	?)+=>>G 	,)++Gr9   )NNNNNNFT)rT   rU   rV   r#   rC   rK   rY   r   r   r   rP   rZ   r[   s   @r7   r   r   V  s(       ={ = = = = = =@ 268<9=26=A8<,1$(W W|W !.W  (5	W
 !) 6W "%,/W %-U\$:W !u|!45W $D>W D>W 
W W W W W W W Wr9   r   c                   X     e Zd ZdZdedededef fdZdej        dej        fd	Z	 xZ
S )
MBartClassificationHeadz-Head for sentence-level classification tasks.	input_dim	inner_dimnum_classespooler_dropoutc                     t                                                       t          j        ||          | _        t          j        |          | _        t          j        ||          | _        d S )N)r   )rB   rC   r   rs   denseDropoutrj   rw   )rD   r   r   r   r   rE   s        r7   rC   z MBartClassificationHead.__init__  sY     	Yy)44
zN333	)[99r9   r   r   c                     |                      |          }|                     |          }t          j        |          }|                      |          }|                     |          }|S rb   )rj   r   rK   tanhrw   )rD   r   s     r7   rP   zMBartClassificationHead.forward  s[    ]33

=11
=11]33m44r9   )rT   rU   rV   rW   rX   rd   rC   rK   rY   rP   rZ   r[   s   @r7   r   r     s        77
:
: 
: 	
:
 
: 
: 
: 
: 
: 
:U\ el        r9   r   c                   F    e Zd ZeZdZdZddgZdZdZ	d Z
ed             ZdS )MBartPreTrainedModelmodelTr   rf   c                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S 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   rN   datanormal_rl   zero_	Embeddingr_   )rD   moduler  s      r7   _init_weightsz"MBartPreTrainedModel._init_weights  s    k"fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r9   c                     | j         j        }t          j        g ddddd|gg| j                  }|                    |          |d}|S )N)r      
      r@   r   r%      r@   rI   )r   r&   )rn   r'   rK   rx   rI   r/   )rD   	pad_tokenr&   dummy_inputss       r7   r  z!MBartPreTrainedModel.dummy_inputs  sa    K,	L"2"2"2Q2q)4L!MVZVabbb	'll955"
 
 r9   N)rT   rU   rV   r#   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpar  propertyr   r9   r7   r   r     sf        L&*#,.>?!N	? 	? 	?   X  r9   r   aJ  
    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 ([`MBartConfig`]):
            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.
u  
    Translation example:

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

    >>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro")
    >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-en-ro")

    >>> example_english_phrase = "42 is the answer"
    >>> inputs = tokenizer(example_english_phrase, return_tensors="pt")

    >>> # Translate
    >>> generated_ids = model.generate(**inputs, num_beams=4, max_length=5)
    >>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
    '42 este răspuns'
    ```

    Mask filling example:

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

    >>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-cc25")
    >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")

    >>> # de_DE is the language symbol id <LID> for German
    >>> TXT = "</s> Meine Freunde sind <mask> nett aber sie essen zu viel Kuchen. </s> de_DE"

    >>> input_ids = tokenizer([TXT], add_special_tokens=False, return_tensors="pt")["input_ids"]
    >>> logits = model(input_ids).logits

    >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
    >>> probs = logits[0, masked_index].softmax(dim=0)
    >>> values, predictions = probs.topk(5)

    >>> tokenizer.decode(predictions).split()
    ['nett', 'sehr', 'ganz', 'nicht', 'so']
    ```
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)
        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)

            MBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
            varies according to source and target language, *e.g.* 25004 for *en_XX*, and 25003 for *de_DE*. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            For translation and summarization training, `decoder_input_ids` should be provided. If no
            `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
            for denoising pre-training following the paper.
        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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f         fdZ xZS )MBartEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`MBartEncoderLayer`].

    Args:
        config: MBartConfig
        embed_tokens (nn.Embedding): output embedding
    Nrn   embed_tokensc                    t                                                     j        | _        j        | _        j        }j        | _        j        | _	        j
        rt          j        |          nd}t          j        || j        |          | _        ||j        | j        _        t#          j        |          | _        t'          j        fdt+          j                  D                       | _        | _        t'          j        |          | _        t'          j        j                  | _        d| _        |                                  d S )Nr^   r`   c                 .    g | ]}t                    S r  )r   .0r   rn   s     r7   
<listcomp>z)MBartEncoder.__init__.<locals>.<listcomp>  "    $e$e$e1%6v%>%>$e$e$er9   F)rB   rC   rj   encoder_layerdrop	layerdropr   r'   r_   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtr]   
vocab_sizer  rN   r;   embed_positionsr   
ModuleListrangeencoder_layerslayersrn   r   layernorm_embedding
layer_normgradient_checkpointing	post_init)rD   rn   r  rh   r`   rE   s    `   r7   rC   zMBartEncoder.__init__  s<      ~1N	!.$*$B!.4.DMdi	***#4y$*:
 
 
 #'3':D$>* 
  
 m$e$e$e$efNcHdHd$e$e$eff#%<	#:#: ,v~66&+#r9   c                 p    | j         r,t          | j        dd          r|                                  d S d S d S )Nr5  F)r  getattrrn   gradient_checkpointing_enablerD   s    r7   ._backward_compatibility_gradient_checkpointingz;MBartEncoder._backward_compatibility_gradient_checkpointing  sP    / 	1GDKIach4i4i 	1..00000	1 	1 	1 	1r9   r&   r   	head_maskinputs_embedsr   output_hidden_statesreturn_dictr   c                    ||n| j         j        }||n| j         j        }||n| j         j        }||t	          d          |&|}|j        }	|                    d|	d                   }n!||dddddf         }nt	          d          ||                     |          }|                     |          }
||
	                    |j
                  z   }|                     |          }t          j                            || j        | j                  }|X| j         j        dk    r	d|v r|nd}n?| j         j        dk    r||st#          ||j                  }nt'          ||j                  }|rd	nd}|rd	nd}|p|                                d         t+          | j                  k    r@t	          d
t+          | j                   d|                                d          d          t/          | j                  D ]\  }}|r||fz   }d}| j        r!t1          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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)
            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   r   r  z&The head_mask should be specified for  layers, but it is for r   FT)NN)r   r   r"   c              3      K   | ]}||V  	d S rb   r  r#  vs     r7   	<genexpr>z'MBartEncoder.forward.<locals>.<genexpr>T  s(      eeqWXWdWdWdWdWdeer9   last_hidden_stater   
attentions)!rn   r   r>  use_return_dictr-   rJ   rz   r  r.  r   rI   r3  r   r   rj   r   r   r   rH   r   r   lenr2  	enumeraterK   randr'  r5  _gradient_checkpointing_func__call__r4  tupler   )rD   r&   r   r<  r=  r   r>  r?  inputinput_shape	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                      r7   rP   zMBartEncoder.forward  s   \ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]  ]%>cddd"E+K!r;r?;;II&!!!!QQQ(+EETUUU  --i88M((//	%	]5I(J(JJ00??--mt|VZVc-dd %{/3FFF343F3FD1V;;	@QZk@Q "E^UbUh!i!i "<NML_!`!`3=0:d  ~~"c$+&6&666 /S=M=M / /!((+/ / /   #,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66 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r9   rb   )NNNNNNN)rT   rU   rV   rW   r#   r   r   r	  rC   r;  rK   
LongTensorrY   FloatTensorr   r   r   r   rP   rZ   r[   s   @r7   r  r    s.         { (2<:P      >1 1 1 '+15,059,0/3&*K
 K
#K
 !.K
 EL)	K

   12K
 $D>K
 'tnK
 d^K
 
uo%	&K
 K
 K
 K
 K
 K
 K
 K
r9   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f         fdZ xZS )MBartDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MBartDecoderLayer`]

    Args:
        config: MBartConfig
        embed_tokens (nn.Embedding): output embedding
    Nrn   r  c                    t                                                     j        | _        j        | _        j        | _        j        | _        j	        rt          j        j                  nd}t          j        j        | j        |          | _        ||j        | j        _        t#          j        j                  | _        t'          j        fdt+          j                  D                       | _        | _        t'          j        j                  | _        t'          j        j                  | _        d| _        |                                  d S )Nr^   r   c                 .    g | ]}t                    S r  )r   r"  s     r7   r$  z)MBartDecoder.__init__.<locals>.<listcomp>v  r%  r9   F)rB   rC   rj   decoder_layerdropr'  r'   r_   r(  max_target_positionsr*  r+  r,  r   r]   r-  r  rN   r;   r.  r   r/  r0  decoder_layersr2  rn   r   r3  r4  r5  r6  )rD   rn   r  r`   rE   s    `  r7   rC   zMBartDecoder.__init__c  s=      ~1!.$*$B!393IRdi///s4v~t/?[
 
 
 #'3':D$>*N 
  
 m$e$e$e$efNcHdHd$e$e$eff#%<#?#? ,v~66&+#r9   c                     | j         S rb   r  r:  s    r7   get_input_embeddingsz!MBartDecoder.get_input_embeddings  s      r9   c                     || _         d S rb   rd  rD   values     r7   set_input_embeddingsz!MBartDecoder.set_input_embeddings  s    !r9   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          |3|}|                                }|                    d|d                   }n=|,|                                dd         }|dddddf         }nt          d          ||d         d         j        d         nd}|| 	                    |          }| j         j
        dk    r|d|v r|nd}n9| j         j
        dk    r|
s|t          ||||          }nt          ||||          }|j|h| j         j
        dk    r	d|v r|nd}nO| j         j
        dk    r"| |
st          ||j        |d         	          }nt          ||j        |d         	          }|                     ||          }||                    |j                  z   }|                     |          }t(          j                            || j        | j        
          }| j        r%| j        r|	rt2                              d           d}	|rdnd}|
rdnd}|
r|dnd}|	rdnd}t7          ||gddg          D ]z\  }}|s|                                d         t9          | j                  k    rCt          d| dt9          | j                   d|                                d          d          {t=          | j                  D ]\  }}|r||fz  }| j        r t?          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tK          d |||||fD                       S tM          |||||          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   )r   r   z[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...Fr  r<  rj  zThe `z` should be specified for rA  r   )r   r   r   r   r   r   r   r   r   r"   c              3      K   | ]}||V  	d S rb   r  rC  s     r7   rE  z'MBartDecoder.forward.<locals>.<genexpr>k  s0        =  === r9   )rG  rk  r   rH  cross_attentions)'rn   r   r>  r   rI  r-   r   rz   rJ   r  r   r   r   r   rH   r   r.  r   rI   r3  r   r   rj   r   r5  r   r   ziprJ  r2  rK  rK   rL  r'  rM  rN  r4  rO  r   )rD   r&   r   r   r   r<  rj  rk  r=  r   r   r>  r?  rP  rQ  rF   rS   r   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cacher   	mask_namerU  decoder_layerrX  r   rY  
next_caches                                 r7   rP   zMBartDecoder.forward  s6   ` 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]  ]%>sttt"E**,,K!r;r?;;II&',,..ss3K!!!!QQQ(+EEdeee DSC^!3A!6!<Q!?!?de  --i88M;+/BBB0>0JqTbObOb^^imNN[-77@Q7VjVr H&	 NN ?]<R N
 !,1G1S{/3FFFCDH^C^C^)?)?dh&&1V;;@T@\ev@\ *M*!''O* * *&& *D*M,?UW* * *&
 ((0FGG	%	]5I(J(JJ00??--mt|VZVc-dd& 	"4= 	" "##q   "	 #7@BBD0:d&7h<Q<]rrdh#,6RR$ %(4H(IKYoKp$q$q 	 	 Iy$>>##A&#dk*:*:::$3	 3 3SEUEU 3 3%NN,,Q/3 3 3   #,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-=,??(66   	2-!11+4>''$
 	  '5FXlm     
 9+&+%1
 
 
 	
r9   rb   )NNNNNNNNNNNN)rT   rU   rV   rW   r#   r   r   r	  rC   re  ri  rK   rZ  rY   r[  r   r   r   r   rP   rZ   r[   s   @r7   r]  r]  Z  s         { (2<:P      :! ! !" " "
 '+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
 
u??	@p
 p
 p
 p
 p
 p
 p
 p
r9   r]  zSThe bare MBART Model outputting raw hidden-states without any specific head on top.c            &       j    e Zd ZddgZdef fdZd Zd Zd Z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                                   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eeej                 f         f d                        Z xZS )
MBartModelzencoder.embed_tokens.weightzdecoder.embed_tokens.weightrn   c                 t   t                                          |           |j        |j        }}|j        rt          j        |j                  nd}t          ||j        ||          | _	        t          || j	                  | _        t          || j	                  | _        |                                  d S )Nr^   r   )rB   rC   r'   r-  r*  r+  r,  r   r]   sharedr  encoderr]  decoderr6  )rD   rn   r_   r-  r`   rE   s        r7   rC   zMBartModel.__init__  s       "("5v7HZ393IRdi///s.z6>;doppp#FDK88#FDK88 	r9   c                     | j         S rb   )rz  r:  s    r7   re  zMBartModel.get_input_embeddings  s
    {r9   c                 X    || _         | j         | j        _        | j         | j        _        d S rb   )rz  r{  r  r|  rg  s     r7   ri  zMBartModel.set_input_embeddings  s'    $(K!$(K!!!r9   c                     | j         S rb   )r{  r:  s    r7   get_encoderzMBartModel.get_encoder  
    |r9   c                     | j         S rb   r|  r:  s    r7   get_decoderzMBartModel.get_decoder  r  r9   c                     | j         j        rf|                     | j        j        |                                            |                     | j        j        |                                            d S d S rb   )rn   tie_word_embeddings_tie_or_clone_weightsr{  r  re  r|  r:  s    r7   _tie_weightszMBartModel._tie_weights  sp    ;* 	_&&t|'@$B[B[B]B]^^^&&t|'@$B[B[B]B]^^^^^	_ 	_r9   )
checkpointoutput_typer  expected_outputNr&   r   decoder_input_idsdecoder_attention_maskr<  decoder_head_maskrj  encoder_outputsrk  r=  decoder_inputs_embedsr   r   r>  r?  r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }||n| j         j        }||t          || 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 )N)r&   r   r<  r=  r   r>  r?  r   r"   r@   rF  r&   r   r   r   r<  rj  rk  r=  r   r   r>  r?  )rG  rk  decoder_hidden_statesdecoder_attentionsrn  encoder_last_hidden_stater   encoder_attentions)rn   r   r>  r   rI  r8   r'   r{  r  r   rJ  r|  r   rG  rk  r   rH  rn  )rD   r&   r   r  r  r<  r  rj  r  rk  r=  r  r   r   r>  r?  decoder_outputss                    r7   rP   zMBartModel.forward  s   2 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B] $)>)F 29dk>V W W""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	
 	
 	
 		
r9   NNNNNNNNNNNNNNN)rT   rU   rV   _tied_weights_keysr#   rC   re  ri  r  r  r  r   MBART_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPErK   rZ  r   rY   r   r[  r   r   rP   rZ   r[   s   @r7   rx  rx  y  sj       
 89VW{        0 0 0
    _ _ _
 +*+ABB&&$.	   '+158<=A,0487;EIEI59=A$(,0/3&*!L
 L
#L
 !.L
 $E$45	L

 !))9 :L
 EL)L
 $EL1L
 'u|4L
 "%e.?(@"ABL
 "%e.?(@"ABL
   12L
  ((9:L
 D>L
 $D>L
 'tnL
  d^!L
" 
!5):#;;	<#L
 L
 L
  CBL
 L
 L
 L
 L
r9   rx  zvThe MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.c            )           e Zd ZdZ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	e
ddfdZ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                                   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eeej                 f         f"d!                                    Z dej        fd"Z!e"d#             Z# xZ$S )&MBartForConditionalGenerationr   final_logits_bias)!model.encoder.embed_tokens.weight!model.decoder.embed_tokens.weightlm_head.weightrn   c                 l   t                                          |           t          |          | _        |                     dt          j        d| j        j        j        f                     t          j
        |j        | j        j        j        d          | _        |                                  d S )Nr  r"   Frp   )rB   rC   rx  r   register_bufferrK   zerosrz  r<   r   rs   r   lm_headr6  r   s     r7   rC   z&MBartForConditionalGeneration.__init__  s       ''
0%+q$*BSBb>c2d2deeey1B1QX]^^^ 	r9   c                 4    | j                                         S rb   )r   r  r:  s    r7   r  z)MBartForConditionalGeneration.get_encoder      z%%'''r9   c                 4    | j                                         S rb   )r   r  r:  s    r7   r  z)MBartForConditionalGeneration.get_decoder  r  r9   Nnew_num_tokenspad_to_multiple_ofr   c                     t                                          ||          }|                     |j        j        d                    |S )Nr   )rB   resize_token_embeddings_resize_final_logits_biasrN   rJ   )rD   r  r  new_embeddingsrE   s       r7   r  z5MBartForConditionalGeneration.resize_token_embeddings  sB    88I[\\&&~'<'B1'EFFFr9   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  rJ   rK   r  rI   r   r  )rD   r  old_num_tokensnew_bias
extra_biass        r7   r  z7MBartForConditionalGeneration._resize_final_logits_bias  s    /5b9^++-aaa..@AHHa.)H%IRVRhRopppJy$"8*!E1MMMH0(;;;;;r9   c                     | j         S rb   r  r:  s    r7   get_output_embeddingsz3MBartForConditionalGeneration.get_output_embeddings  r  r9   c                     || _         d S rb   r  rD   r  s     r7   set_output_embeddingsz3MBartForConditionalGeneration.set_output_embeddings      %r9   r  r  r&   r   r  r  r<  r  rj  r  rk  r=  r  labelsr   r   r>  r?  c                 t   ||n| j         j        }|<|rt                              d           d}||t	          || 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  r  r  r<  r  rj  rk  r=  r  r   r   r>  r?  r   r+   r"   	losslogitsrk  r  r  rn  r  r   r  )rn   rI  r   warningr8   r'   r   r  r  r	   rz   r-  r   rk  r  r  rn  r  r   r  )rD   r&   r   r  r  r<  r  rj  r  rk  r=  r  r  r   r   r>  r?  r   	lm_logitsmasked_lm_lossloss_fctoutputs                         r7   rP   z%MBartForConditionalGeneration.forward"  s   > &1%<kk$+B] mklllI (-B-J$6vt{?W$X$X!**)/+#9/!5+'"7/!5#  
 
" LL,,t/EE	'))H%XinnR9O&P&PRXR]R]^`RaRabbN 	Z\GABBK/F3A3M^%..SYY#3")"?&9$5&-&G")"?&9

 

 

 
	
r9   c                 6    t          || j        j                  S rb   )r8   rn   r'   )rD   r  s     r7   %prepare_decoder_input_ids_from_labelszCMBartForConditionalGeneration.prepare_decoder_input_ids_from_labelsr  s    !&$+*BCCCr9   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_selectr   rI   r#  
past_statebeam_idxs     r7   rE  z?MBartForConditionalGeneration._reorder_cache.<locals>.<genexpr>{  sC      rrU_j--aZ=N1O1OPPrrrrrrr9   r@   rO  rk  r  reordered_past
layer_pasts    `  r7   _reorder_cachez,MBartForConditionalGeneration._reorder_cacheu  sm    ) 	 	JrrrrcmnpopnpcqrrrrrQRR.! NN r9   rb   NNNNNNNNNNNNNNNN)%rT   rU   rV   r  _keys_to_ignore_on_load_missingr  r#   rC   r  r  rX   r   r   r	  r  r  r  r  r   r  r!   r   r  r   MBART_GENERATION_EXAMPLErK   rZ  rY   r   r[  r   r   rP   r  staticmethodr  rZ   r[   s   @r7   r  r    s!       
  ':&;#uuu{      ( ( (( ( ( c xX[} hjht      
< < < < < <  & & & +*+ABB?YYY011 '+158<=A,0487;EIEI59=A-1$(,0/3&*#K
 K
#K
 !.K
 $E$45	K

 !))9 :K
 EL)K
 $EL1K
 'u|4K
 "%e.?(@"ABK
 "%e.?(@"ABK
   12K
  ((9:K
 )*K
 D>K
 $D>K
  'tn!K
" d^#K
$ 
e&7 88	9%K
 K
 K
 21 ZY CBK
ZDEL D D D D   \    r9   r  z
    MBart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
    tasks.
    c            %           e Zd ZddgZdef fdZ 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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ee
f         f d                        Z xZS )MBartForSequenceClassificationr  r  rn   c                      t                      j        |fi | t          |          | _        t	          |j        |j        |j        |j                  | _        | 	                                 d S rb   )
rB   rC   rx  r   r   r   
num_labelsclassifier_dropoutclassification_headr6  )rD   rn   r   rE   s      r7   rC   z'MBartForSequenceClassification.__init__  sq    **6***''
#:NN%	$
 $
  	r9   r  r  r  Nr&   r   r  r  r<  r  rj  r  r=  r  r  r   r   r>  r?  r   c                 R   ||n| j         j        }|d}||	t          d| j        j                   |                     |||||||||	|
||||          }|d         }|                    | j         j                                      |j	                  }t          t          j        |                    d                              dk    rt          d          ||ddf                             |                    d          d|                    d                    dddddf         }|                     |          }d}||                    |j	                  }| j         j        p| j         j        dk    rd	| j         _        nS| j         j        dk    r7|j        t          j        k    s|j        t          j        k    rd
| j         _        nd| j         _        | j         j        d	k    r\t/                      }| j         j        dk    r1 ||                                |                                          }n |||          }n| j         j        d
k    rLt3                      } ||                    d| j         j                  |                    d                    }n*| j         j        dk    rt5                      } |||          }|s|f|dd         z   }||f|z   n|S t7          |||j        |j        |j        |j        |j         |j!        |j"        	  	        S )a3  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NFz8Passing input embeddings is currently not supported for r   r  r  r<  r  rj  r  r=  r  r   r   r>  r?  r   r"   z7All examples must have the same number of <eos> tokens.r+   
regressionsingle_label_classificationmulti_label_classificationr  )#rn   rI  NotImplementedErrorrE   rT   r   eqeos_token_idr   rI   rJ  rK   unique_consecutiver0   r-   rz   r   r  problem_typer  rH   rM   rX   r
   r3   r	   r   r   rk  r  r  rn  r  r   r  )rD   r&   r   r  r  r<  r  rj  r  r=  r  r  r   r   r>  r?  r   r   eos_masksentence_representationr  r  r  r  s                           r7   rP   z&MBartForSequenceClassification.forward  sR   < &1%<kk$+B]I!:%d4>Kbdd   **)/#9/!5+'"7/!5#  
 
   
<< 899<<]=QRRu'Q8899A==VWWW"/!!!"<"A"A-BTBTUVBWBWY[]j]o]opr]s]s"t"tAAr111H#
 ))*ABBYYv}--F{'/;)Q../;DK,,[+a//V\UZ5O5OSYS_chclSlSl/LDK,,/KDK,{'<77"99;)Q..#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB0F G GUWYY)-III,..x// 	FY,F)-)9TGf$$vE.#3")"?&9$5&-&G")"?&9

 

 

 
	
r9   r  )rT   rU   rV   r  r#   rC   r   r  r   r  r   r  rK   rZ  r   rY   r   r[  r   r   r   rP   rZ   r[   s   @r7   r  r    s        >?bc{       +*+ABB&3$   '+158<=A,0487;=A59=A-1$(,0/3&*!`
 `
#`
 !.`
 $E$45	`

 !))9 :`
 EL)`
 $EL1`
 'u|4`
 "$u'8"9:`
   12`
  ((9:`
 )*`
 D>`
 $D>`
 'tn`
  d^!`
" 
u55	6#`
 `
 `
  CB`
 `
 `
 `
 `
r9   r  z
    MBART Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c            '       &    e Zd ZddgZ fdZ 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j                          d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ee	f         f"d                        Z xZS )MBartForQuestionAnsweringr  r  c                    t                                          |           d|_        |j        | _        t          |          | _        t          j        |j        |j                  | _        | 	                                 d S r?   )
rB   rC   r  rx  r   r   rs   hidden_size
qa_outputsr6  r   s     r7   rC   z"MBartForQuestionAnswering.__init__  sm        +''
)F$68IJJ 	r9   r  Nr&   r   r  r  r<  r  rj  r  start_positionsend_positionsr=  r  r   r   r>  r?  r   c                    ||n| j         j        }|	|
d}|                     ||||||||||||||          }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}|	|
t          |	                                          dk    r|	                    d          }	t          |
                                          dk    r|
                    d          }
|                    d          }|		                    d|          }	|
	                    d|          }
t          |          } |||	          } |||
          }||z   d	z  }|s||f|dd         z   }||f|z   n|S t          ||||j        |j        |j        |j        |j        |j        |j        

  
        S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        NFr  r   r"   r+   r)   )ignore_indexr@   )
r  start_logits
end_logitsrk  r  r  rn  r  r   r  )rn   rI  r   r  splitr3   r|   rJ  r   r   r	   r   rk  r  r  rn  r  r   r  )rD   r&   r   r  r  r<  r  rj  r  r  r  r=  r  r   r   r>  r?  r   sequence_outputr  r  r  
total_lossignored_indexr  
start_lossend_lossr  s                               r7   rP   z!MBartForQuestionAnswering.forward  s[   H &1%<kk$+B]&=+DI**)/#9/!5+'"7/!5#  
 
" "!*11#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEO)//=AAM']CCCH!,@@Jx
M::H$x/14J 	R F 0:/EZMF**6Q2%!#3")"?&9$5&-&G")"?&9
 
 
 	
r9   r  )rT   rU   rV   r  rC   r   r  r   r  r   r  rK   rY   r   rZ  r   r[  r   r   r   rP   rZ   r[   s   @r7   r  r    s        >?bc
 
 
 
 
 +*+ABB&7$   #'158<=A,0487;=A6:4859=A$(,0/3&*#\
 \
<\
 !.\
 $E$45	\

 !))9 :\
 EL)\
 $EL1\
 'u|4\
 "$u'8"9:\
 "%"23\
   01\
   12\
  ((9:\
 D>\
 $D>\
  'tn!\
" d^#\
$ 
u99	:%\
 \
 \
  CB\
 \
 \
 \
 \
r9   r  c                   (     e Zd ZdZ fdZd Z xZS )MBartDecoderWrapperz
    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 rb   )rB   rC   r]  r|  r   s     r7   rC   zMBartDecoderWrapper.__init__  s.       #F++r9   c                      | j         |i |S rb   r  )rD   r   r   s      r7   rP   zMBartDecoderWrapper.forward  s    t|T,V,,,r9   )rT   rU   rV   rW   rC   rP   rZ   r[   s   @r7   r  r    sQ         
, , , , ,- - - - - - -r9   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 )MBartForCausalLMr  c                 *   t          j        |          }d|_        d|_        t	                                          |           t          |          | _        t          j	        |j
        |j        d          | _        |                                  d S )NTFrp   )copydeepcopyrk   is_encoder_decoderrB   rC   r  r   r   rs   r  r-  r  r6  r   s     r7   rC   zMBartForCausalLM.__init__  s    v&& $)!   (00
y!3V5FUSSS 	r9   c                 $    | j         j        j        S rb   r   r|  r  r:  s    r7   re  z%MBartForCausalLM.get_input_embeddings  s    z!..r9   c                 (    || j         j        _        d S rb   r	  rg  s     r7   ri  z%MBartForCausalLM.set_input_embeddings  s    */
'''r9   c                     | j         S rb   r  r:  s    r7   r  z&MBartForCausalLM.get_output_embeddings  r  r9   c                     || _         d S rb   r  r  s     r7   r  z&MBartForCausalLM.set_output_embeddings  r  r9   c                     || j         _        d S rb   r   r|  )rD   r|  s     r7   set_decoderzMBartForCausalLM.set_decoder  s    $
r9   c                     | j         j        S rb   r  r:  s    r7   r  zMBartForCausalLM.get_decoder  s    z!!r9   r  Nr&   r   r   r   r<  rj  rk  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, MBartForCausalLM

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")
        >>> model = MBartForCausalLM.from_pretrained("facebook/mbart-large-cc25", 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  rk  r   rH  rn  )rn   r   r>  rI  r   r|  r  r   rI   r	   rz   r-  r   rk  r   rH  rn  )rD   r&   r   r   r   r<  rj  rk  r=  r  r   r   r>  r?  r   r  r  r  r  s                      r7   rP   zMBartForCausalLM.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
 
 
 	
r9   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     r7   rE  z2MBartForCausalLM._reorder_cache.<locals>.<genexpr>E  sC      nnU_j--aZ=N1O1OPPnnnnnnr9   r  r  s    `  r7   r  zMBartForCausalLM._reorder_cache@  sQ    ) 	 	Jnnnncmnnnnn NN r9   )NNNNNNNNNNNNN)rT   rU   rV   r  rC   re  ri  r  r  r  r  r!   r   r  rK   rZ  r   rY   r[  r   r   r   r   rP   r  r  rZ   r[   s   @r7   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
`   \    r9   r  )OrW   r  r+  typingr   r   r   r   rK   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   
generationr   modeling_attn_mask_utilsr   r   r   r   modeling_outputsr   r   r   r   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r    r!   configuration_mbartr#   modeling_flash_attention_utilsr$   
get_loggerrT   r   r  r  r  rY   rX   r8   r	  r;   r]   Modulerf   r   r   r   r   r   r   r   MBART_START_DOCSTRINGr  r  r  r]  rx  r  r  r  r  r  r  r9   r7   <module>r"     sg       / / / / / / / / / / / /            A A A A A A A A A A ! ! ! ! ! ! ) ) ) ) ) )                             . - - - - -	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 - , , , , ,  KJJJJJJ 
	H	%	%1  & %, c    *8 8 8 8 8bl 8 8 8.
= 
= 
= 
= 
=r| 
= 
= 
=[B [B [B [B [BRY [B [B [B~|9 |9 |9 |9 |9> |9 |9 |9@g1 g1 g1 g1 g1 g1 g1 g1V -  C C C C C	 C C CLu u u u u	 u u ur    bi   0    ?   <  ' R] @y
 y
 y
 y
 y
' y
 y
 y
x\
 \
 \
 \
 \
' \
 \
 \
~ Y v
 v
 v
 v
 v
% v
 v
	 v
r | D D D D D$8/ D D	 DN   w
 w
 w
 w
 w
%9 w
 w
 w
t   r
 r
 r
 r
 r
 4 r
 r
 r
l- - - - -. - - -y y y y y+_ y y y y yr9   