o
    Zh                    @   s  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mZ dd	lmZ dd
lmZmZmZ ddl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+ ddl,m-Z- e) rddl.m/Z/ ddl0m1Z1 e rddlm2Z2 e+3e4Z5dej6de7fddZ8G dd de
j9Z:G dd de
j9Z;G dd de
j<Z=G dd de=Z>G d d! d!e=Z?e=e?e>d"Z@G d#d$ d$e
j<ZAG d%d& d&e
j<ZBG d'd( d(e
j<ZCe(G d)d* d*e&ZDG d+d, d,eDZEG d-d. d.eDZFe(G d/d0 d0eDZGe(d1d2G d3d4 d4eDeZHe(d5d2G d6d7 d7eDZIe(G d8d9 d9eDZJG d:d; d;eDZKG d<d= d=eDeZLg d>ZMdS )?zPyTorch MBART model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )MBartConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forward	input_idspad_token_idc                 C   s   |   }|du rtd||dk| ||jddd 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
ValueErrorZmasked_fill_nesum	unsqueezegathersqueeze)r%   r&   Zprev_output_tokensZindex_of_eosZdecoder_start_tokens r1   W/var/www/auris/lib/python3.10/site-packages/transformers/models/mbart/modeling_mbart.pyshift_tokens_rightC   s   (r3   c                       sJ   e Zd ZdZdedef fddZddejd	ed
ejf fddZ  Z	S )MBartLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                    s   d| _ t || j  | d S N   )offsetsuper__init__)selfr5   r6   	__class__r1   r2   r;   ]   s   z(MBartLearnedPositionalEmbedding.__init__r   Nr%   past_key_values_lengthposition_idsc                    s\   |du r |j dd \}}tj||| tj| jjd|d}n|d}t 	|| j
 S )z3`input_ids' shape is expected to be [bsz x seqlen].Nr8   )dtypedevicer)   r   )shapetorcharangelongweightrB   expandr.   r:   forwardr9   )r<   r%   r?   r@   bszZseq_lenr=   r1   r2   rI   c   s   
z'MBartLearnedPositionalEmbedding.forwardr   N)
__name__
__module____qualname____doc__intr;   rD   TensorrI   __classcell__r1   r1   r=   r2   r4   X   s    (r4   c                
       sL   e Zd ZdZddedededee f fddZd	ej	f fd
dZ
  ZS )MBartScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
          ?r5   r6   padding_idxembed_scalec                    s   t  ||| || _d S N)r:   r;   rV   )r<   r5   r6   rU   rV   r=   r1   r2   r;   w   s   
z!MBartScaledWordEmbedding.__init__r%   c                    s   t  || j S rW   )r:   rI   rV   )r<   r%   r=   r1   r2   rI   {   s   z MBartScaledWordEmbedding.forward)rT   )rL   rM   rN   rO   rP   r   floatr;   rD   rQ   rI   rR   r1   r1   r=   r2   rS   r   s    $rS   c                       s   e Zd ZdZ						ddededed	ed
ededee dee f fddZ							dde
jdee
j dee dee
j dee
j dedee
j dee
jee
j eee
j  f fddZ  ZS )MBartAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfig	layer_idxc	           	         s   t    || _|| _|| _|| | _|| _| j| | jkr*td| j d| d| jd | _|| _	|| _
|| _|d u rK| j	rKtd| jj d tj|||d| _tj|||d| _tj|||d| _tj|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.r_   )r:   r;   r[   r\   r]   head_dimra   r+   scalingr^   r`   rb   loggerwarning_oncer>   rL   r   Lineark_projv_projq_projout_proj)	r<   r[   r\   r]   r^   r_   r`   ra   rb   r=   r1   r2   r;      s0   


zMBartAttention.__init__hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionreturnc                 C   sv  |du}|  \}	}
}| ||	d| j| jdd}|| j }|dur=t|tr;|j	
| j}|r7|j}n|j}n|}|rA|n|}|rX|durX|rX|j| j }|j| j }nE| |}| |}||	d| j| jdd}||	d| j| jdd}|dur|s|nd}|||| jd|i\}}|rd|j	| j< |	| j d| jf}|j| }|j| }|j| }| d}t||dd}|  |	| j |
|fkrtd|	| j |
|f d|   |dur|ddddddd|jd	 f }||	| j|
|| }||	| j |
|}tjj|dd
}|durN|  | jfkr3td| jf d|   |dddd||	| j|
| }||	| j |
|}|re||	| j|
|}||	| j |
|}nd}tjj|| j| jd}t||}|  |	| j |
| jfkrtd|	| j |
| jf d|   ||	| j|
| j}|dd}||	|
| j}| |}|||fS )#Input shape: Batch x Time x ChannelNr)   r    r8   rs   Tz$Attention weights should be of size z	, but is r'   z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizerk   viewr\   rd   	transposere   
isinstancer   
is_updatedgetrb   cross_attention_cacheself_attention_cache	key_cachevalue_cacheri   rj   updatereshaperD   Zbmmr+   rC   r   
functionalZsoftmaxr]   ry   r[   rl   )r<   rm   rn   ro   rp   rq   rr   rs   is_cross_attentionrJ   tgt_len_query_statesr~   curr_past_key_valuecurrent_states
key_statesvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr1   r1   r2   rI      s   "








&
"

zMBartAttention.forward)rZ   FTFNNNNNNFN)rL   rM   rN   rO   rP   rX   boolr   r!   r;   rD   rQ   r   r   rI   rR   r1   r1   r=   r2   rY      s`    	*	rY   c                       s   e Zd ZdZ fddZ						ddejdeej dee d	eej d
eej de	deej de
ejeej ee
ej  f fddZ  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                    s   t  j|i | t | _d S rW   )r:   r;   r   _flash_attn_uses_top_left_maskr<   argskwargsr=   r1   r2   r;   %  s   zMBartFlashAttention2.__init__NFrm   rn   ro   rp   rq   rr   rs   rt   c              
   C   s  |rt d|d u}| \}	}
}| ||	d| j| j}|d ur:t|tr8|j	| j
}|r4|j}n|j}n|}|r>|n|}|rU|d urU|rU|j| j
 }|j| j
 }nE| |}| |}||	d| j| jdd}||	d| j| jdd}|d ur|s|nd }|||| j
d|i\}}|rd|j| j
< |dd}|dd}|j}|tjkrt rt }nt| jdr| jj}n| jjj}td| d	 ||}||}||}t|||||
| j r| j!nd
| j"| j#d}|$|	|
d}| %|}|d |fS )NzMBartSdpaAttention2 attention does not support `output_attentions`. Use the argument `attn_implementation='eager'` when loading the model.r)   r    r8   rs   T_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 .rZ   )r]   r`   Zuse_top_left_mask)&r+   rz   rk   r{   r\   rd   r}   r   r~   r   rb   r   r   r   r   ri   rj   r|   r   rA   rD   Zfloat32Zis_autocast_enabledZget_autocast_gpu_dtypehasattrra   r   rG   rf   rg   tor$   ry   r]   r`   r   r   rl   )r<   rm   rn   ro   rp   rq   rr   rs   r   rJ   Zq_lenr   r   r~   r   r   r   r   Zinput_dtypeZtarget_dtyper   r1   r1   r2   rI   -  sv   











zMBartFlashAttention2.forwardr   )rL   rM   rN   rO   r;   rD   rQ   r   r   r   r   rI   rR   r1   r1   r=   r2   r     s4    	r   c                       s   e Zd Z						ddejdeej dee deej deej ded	eej d
eejeej eeej  f f fddZ	  Z
S )MBartSdpaAttentionNFrm   rn   ro   rp   rq   rr   rs   rt   c                    s,  |rt d t j||||||dS |du}| \}	}
}| ||	d| j| j	dd}|durKt
|trI|j| j}|rE|j}n|j}n|}|rO|n|}|rf|durf|rf|j| j }|j| j }nE| |}| |}||	d| j| j	dd}||	d| j| j	dd}|dur|s|nd}|||| jd|i\}}|rd|j| j< d}|dur|ddddddd|jd	 f }|jjd
kr|dur| }| }| }| jr|du r|
dkrdnd}tjjj||||| jr| j nd|d}|	dd }||	|
| j!}| "|}|d|fS )ru   a  MBartModel is using MBartSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` . 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.)rn   ro   rp   rr   rs   Nr)   r    r8   rs   Trv   cudaFrZ   )	attn_maskZ	dropout_pr`   )#rf   rg   r:   rI   rz   rk   r{   r\   rd   r|   r}   r   r~   r   rb   r   r   r   r   ri   rj   r   rC   rB   type
contiguousr`   rD   r   r   Zscaled_dot_product_attentionry   r]   r[   rl   )r<   rm   rn   ro   rp   rq   rr   rs   r   rJ   r   r   r   r~   r   r   r   r   causal_maskr`   r   r=   r1   r2   rI     sr   "


&	

zMBartSdpaAttention.forwardr   )rL   rM   rN   rD   rQ   r   r   r   r   rI   rR   r1   r1   r=   r2   r     s0    	r   )eagersdpaflash_attention_2c                       sL   e Zd Zdef fddZ	ddejdejdejded	ejf
d
dZ  Z	S )MBartEncoderLayerra   c                    s   t    |j| _t|j | j|j|j|d| _t	
| j| _|j| _t|j | _|j| _t	| j|j| _t	|j| j| _t	
| j| _d S )N)r[   r\   r]   ra   )r:   r;   d_modelr[   MBART_ATTENTION_CLASSES_attn_implementationZencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normr]   r   activation_functionactivation_fnactivation_dropoutrh   Zencoder_ffn_dimfc1fc2final_layer_normr<   ra   r=   r1   r2   r;     s   
zMBartEncoderLayer.__init__Frm   rp   rq   rr   rt   c           
      C   s   |}|  |}| j||||d\}}}tjj|| j| jd}|| }|}| |}| | |}tjj|| j	| jd}| 
|}tjj|| j| jd}|| }|jtjkrht|jjd }tj|| |d}|f}	|rr|	|f7 }	|	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.
        )rm   rp   rq   rr   rw   i  )minmax)r   r   r   r   r]   ry   r   r   r   r   r   rA   rD   Zfloat16finfor   clamp)
r<   rm   rp   rq   rr   residualr   r   Zclamp_valueoutputsr1   r1   r2   rI     s0   



zMBartEncoderLayer.forwardF)
rL   rM   rN   r!   r;   rD   rQ   r   rI   rR   r1   r1   r=   r2   r     s    r   c                       s   e Zd Zddedee f fd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	 dee
 dee
 deej dejfddZ  ZS )MBartDecoderLayerNra   rb   c              	      s   t    |j| _t|j | j|j|jdd||d| _|j	| _	t
|j | _|j| _t| j| _t|j | j|j|jd||d| _t| j| _t| j|j| _t|j| j| _t| j| _d S )NT)r[   r\   r]   r^   r`   ra   rb   )r]   r^   ra   rb   )r:   r;   r   r[   r   r   Zdecoder_attention_headsr   r   r]   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrh   Zdecoder_ffn_dimr   r   r   )r<   ra   rb   r=   r1   r2   r;   K  s6   
	zMBartDecoderLayer.__init__FTrm   rp   encoder_hidden_statesencoder_attention_maskrq   cross_attn_layer_head_maskro   rr   	use_cachers   rt   c                 C   s   |}|  |}| j||||||
d\}}}tjj|| j| jd}|| }d}|durN|}| |}| j||||||d\}}}tjj|| j| jd}|| }|}| |}| 	| 
|}tjj|| j| jd}| |}tjj|| j| jd}|| }|f}|r|||f7 }|	r||f7 }|S )a8  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size `(decoder_attention_heads,)`.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
                cache in the correct position and to infer the complete sequence length.
        )rm   ro   rp   rq   rr   rs   rw   N)rm   rn   rp   rq   ro   rr   )r   r   r   r   r]   ry   r   r   r   r   r   r   r   )r<   rm   rp   r   r   rq   r   ro   rr   r   rs   r   Zself_attn_weightsZcross_attn_weightsr   r1   r1   r2   rI   j  sN   "




zMBartDecoderLayer.forwardrW   )	NNNNNNFTN)rL   rM   rN   r!   r   rP   r;   rD   rQ   r   r   rI   rR   r1   r1   r=   r2   r   J  sD    "	
r   c                       sH   e Zd ZdZdedededef fddZdejd	ejfd
dZ	  Z
S )MBartClassificationHeadz-Head for sentence-level classification tasks.	input_dim	inner_dimnum_classespooler_dropoutc                    s8   t    t||| _tj|d| _t||| _d S )N)rx   )r:   r;   r   rh   denseZDropoutr]   rl   )r<   r   r   r   r   r=   r1   r2   r;     s   
z MBartClassificationHead.__init__rm   rt   c                 C   s6   |  |}| |}t|}|  |}| |}|S rW   )r]   r   rD   tanhrl   )r<   rm   r1   r1   r2   rI     s   




zMBartClassificationHead.forward)rL   rM   rN   rO   rP   rX   r;   rD   rQ   rI   rR   r1   r1   r=   r2   r     s    r   c                   @   s   e Zd ZeZdZdZg dZdZdZ	dZ
dZdd Zedd Z	dd	eejd
f dejdejdedef
ddZed	ejdededejdejdefddZdS )MBartPreTrainedModelmodelT)r   r   rY   c                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|tjrX|jjd |jj	  d S d S )NrZ   )meanstdrT   )ra   Zinit_stdr}   r   rh   rG   dataZnormal_r_   Zzero_	EmbeddingrU   r   Zfill_)r<   moduler   r1   r1   r2   _init_weights  s   

z"MBartPreTrainedModel._init_weightsc                 C   s>   | j j}tjg ddddd|gg| jd}|||d}|S )N)r      
      r8   r         r8   rB   )rp   r%   )ra   r&   rD   ZtensorrB   r,   )r<   Z	pad_tokenr%   dummy_inputsr1   r1   r2   r     s   "z!MBartPreTrainedModel.dummy_inputsFrp   r"   input_tensorrs   past_key_valuesrr   c                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )Nr   rZ   Zflex_attentionr   Fr   )inputs_embedsr?   Zis_trainingr    r)   )sequence_lengthtarget_lengthrA   rs   
batch_size)r   ZxpuZnpu)ra   r   anyr}   rD   rQ   r#   get_seq_lengthZis_compileabler   Z_ignore_causal_mask_sdpary   rA   rC   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrB   r   r   r   Z_unmask_unattended)r<   rp   r   rs   r   rr   Zpast_seen_tokensZusing_compilable_cacherA   r   r   r   	min_dtyper1   r1   r2   _update_causal_mask  sT   




z(MBartPreTrainedModel._update_causal_maskr   r   rA   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )Z
fill_valuerA   rB   r    )Zdiagonalr   r)   r   )r(   rD   r   r   fullrB   ZtriurE   r   rH   r*   rC   r   Zmasked_fill)rp   r   r   rA   rs   r   r   r   r   Zmask_lengthZpadding_maskr1   r1   r2   r   B  s,    $
6  zJMBartPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_positionNr   )rL   rM   rN   r!   Zconfig_classbase_model_prefixsupports_gradient_checkpointingZ_no_split_modulesZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_static_cacher   propertyr   r   rD   rQ   r   r   r   staticmethodrP   rA   r   r1   r1   r1   r2   r     sL    

Dr   c                       s   e Zd ZdZddedeej f fddZdd Z								d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ef fddZ  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
    Nra   embed_tokensc                    s   t     j| _ j| _ j} j| _ j| _	 j
r!t|nd}t j|| j|d| _|d ur7|j| j_t j|| _t fddt jD | _ | _t|| _t j| _d| _|   d S )NrT   rV   c                    s   g | ]}t  qS r1   )r   ).0r   ra   r1   r2   
<listcomp>  s    z)MBartEncoder.__init__.<locals>.<listcomp>F)r:   r;   r]   Zencoder_layerdrop	layerdropr   r&   rU   max_position_embeddingsZmax_source_positionsscale_embeddingmathsqrtrS   
vocab_sizer   rG   r4   embed_positionsr   
ModuleListrangeZencoder_layerslayersra   r   layernorm_embedding
layer_normgradient_checkpointing	post_init)r<   ra   r   r[   rV   r=   r   r2   r;     s,   
 zMBartEncoder.__init__c                 C   s(   | j rt| jddr|   d S d S d S )Nr   F)r   getattrra   Zgradient_checkpointing_enabler<   r1   r1   r2   ._backward_compatibility_gradient_checkpointing  s   z;MBartEncoder._backward_compatibility_gradient_checkpointingr%   rp   	head_maskr   rr   output_hidden_statesreturn_dictrt   c                 C   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur*|dur*td|dur<|}|j}	|d|	d }n|durL|dddddf }ntd|du rY| |}| |}
||
	|j
 }| |}tjj|| j| jd}|dur| j jdkrd|v r|nd}n| j jdkr|du r|st||j}nt||j}|rd	nd}|rd	nd}|dur| d t| jkrtd
t| j d| d  dt| jD ]\\}}|r||f }d}| jrtg }|| jk rd}|rd}n1| jr| jr| |j|||dur|| nd|}n||||dur|| nd|d}|d }|r0||d f }q| |}|r>||f }|sMtdd |||fD S t |||d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_embedsrw   r   r   r   r1   z&The head_mask should be specified for  layers, but it is for r   FT)NN)rq   rr   r    c                 s       | ]	}|d ur|V  qd S rW   r1   r   vr1   r1   r2   	<genexpr>1  s    z'MBartEncoder.forward.<locals>.<genexpr>last_hidden_staterm   
attentions)!ra   rr   r   use_return_dictr+   rC   r{   r   r   r   rB   r   r   r   r]   ry   r   r   rA   r   rz   lenr   	enumeraterD   randr   r   _gradient_checkpointing_func__call__r   tupler   )r<   r%   rp   r   r   rr   r   r  inputZinput_shapeZ	embed_posrm   Zencoder_statesZall_attentionsidxZencoder_layerZto_dropdropout_probabilitylayer_outputsr1   r1   r2   rI     s   .








zMBartEncoder.forwardrW   )NNNNNNN)rL   rM   rN   rO   r!   r   r   r   r;   r   rD   
LongTensorrQ   FloatTensorr   r   r   r   rI   rR   r1   r1   r=   r2   r   {  s8    	
	r   c                       s   e Zd ZdZddedeej f fddZdd Z	d	d
 Z
													d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j dee dee dee dee deej deeef fddZ  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
    Nra   r   c                    s   t     j| _ j| _ j| _ j| _ j	rt
 jnd}t j j| j|d| _|d ur6|j| j_t j j| _t fddt jD | _ | _t j| _t j| _d| _|   d S )NrT   r   c                    s   g | ]}t  |d qS ))rb   )r   )r   ir   r1   r2   r   S  s    z)MBartDecoder.__init__.<locals>.<listcomp>F)r:   r;   r]   Zdecoder_layerdropr   r&   rU   r   Zmax_target_positionsr   r   r   r   rS   r   r   rG   r4   r   r   r   r   Zdecoder_layersr   ra   r   r   r   r   r   )r<   ra   r   rV   r=   r   r2   r;   @  s*   
 zMBartDecoder.__init__c                 C      | j S rW   r   r   r1   r1   r2   get_input_embeddings]     z!MBartDecoder.get_input_embeddingsc                 C   
   || _ d S rW   r  r<   valuer1   r1   r2   set_input_embeddings`     
z!MBartDecoder.set_input_embeddingsr%   rp   r   r   r   cross_attn_head_maskr   r   r   rr   r   r  rs   rt   c           "      C   sN  |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}|du |duA r4td|durA|d|jd }|du rJ| |}| j	rY| j
rY|	rYtd d}	d}|	rnt|tsnd}td t|}| dd \}}|dur| nd}|du rtj||| |jd	}|du rt s|| }tj|||jd	}t|tr|jn|}| |||||
}|dur|dur| j jd
krd|v r|nd}n| j jdkr|du r|
st||j|d}nt||j|d}| jt||d}|| |j }| !|}t"j#j$|| j$| j
d}|rdnd}|
rdnd}|
r$|dur$dnd}d}t%||gddgD ]+\}}|dur[| d t&| j'kr[td| dt&| j' d| d  dq1t(| j'D ]\}}|rn||f7 }| j
rt)g }|| j*k rqb| j	r| j
r| +|j,|||||dur|| nd|dur|| ndd|
|	|} n ||||||dur|| nd|dur|| nd||
|	|d
} | d }|	r| |
rdnd }|
r|| d f7 }|dur|| d f7 }qb| -|}|r||f7 }|	r|nd}!|r|. }!|st/dd ||!|||fD S t0||!|||dS )a4  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                of the decoder.
            encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
                Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
                selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

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

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

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

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
                cache in the correct position and to infer the complete sequence length.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer)   z[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...FTzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r   r   r   )r   )r@   rw   r1   r   r"  zThe `z` should be specified for r  r   )	rp   r   r   rq   r   ro   rr   r   rs   r
   r    r8   c                 s   r  rW   r1   r  r1   r1   r2   r  X  s    z'MBartDecoder.forward.<locals>.<genexpr>)r  r   rm   r	  cross_attentions)1ra   rr   r   r   r
  r+   r{   rC   r   r   ry   rf   rg   r}   r   r   Zfrom_legacy_cacherz   r   rD   rE   rB   r   Zonesr   r   r   r   rA   r   r   r  r   r   r   r   r]   zipr  r   r  r  r   r  r  r   Zto_legacy_cacher  r   )"r<   r%   rp   r   r   r   r"  r   r   r   rr   r   r  rs   Zreturn_legacy_cacher   Z
seq_lengthr?   Zmask_seq_lengthZself_attn_cacher   r@   rm   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacher   Z	mask_namer  Zdecoder_layerr  r  Z
next_cacher1   r1   r2   rI   c  s  T

	







zMBartDecoder.forwardrW   )NNNNNNNNNNNNN)rL   rM   rN   rO   r!   r   r   r   r;   r  r   rD   r  rQ   r  r   r   r   r   rI   rR   r1   r1   r=   r2   r  7  s^    	

r  c                '       s<  e Zd ZddgZdef fddZdd Zdd	 Zd
d Zdd Z	dd Z
e																d$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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j d!eeeej f f"d"d#Z  ZS )%
MBartModelzencoder.embed_tokens.weightzdecoder.embed_tokens.weightra   c                    sl   t  | |j|j}}|jrt|jnd}t||j||d| _	t
|| j	| _t|| j	| _|   d S )NrT   r   )r:   r;   r&   r   r   r   r   r   rS   sharedr   encoderr  decoderr   )r<   ra   rU   r   rV   r=   r1   r2   r;   j  s   zMBartModel.__init__c                 C   r  rW   )r&  r   r1   r1   r2   r  w  r  zMBartModel.get_input_embeddingsc                 C   s   || _ | j | j_| j | j_d S rW   )r&  r'  r   r(  r  r1   r1   r2   r   z  s   
zMBartModel.set_input_embeddingsc                 C   r  rW   )r'  r   r1   r1   r2   get_encoder  r  zMBartModel.get_encoderc                 C   r  rW   r(  r   r1   r1   r2   get_decoder  r  zMBartModel.get_decoderc                 C   s8   | j jr| | jj|   | | jj|   d S d S rW   )ra   Ztie_word_embeddingsZ_tie_or_clone_weightsr'  r   r  r(  r   r1   r1   r2   _tie_weights  s   zMBartModel._tie_weightsNr%   rp   decoder_input_idsdecoder_attention_maskr   decoder_head_maskr"  encoder_outputsr   r   decoder_inputs_embedsr   rr   r   r  rs   rt   c                 C   s4  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur$|n| j j}|du r7|du r7t|| j j}|du rH| j||||
|||d}n$|rlt|t	slt	|d t
|dkr]|d ndt
|dkrh|d ndd}| j|||d ||||	||||||d}|s|| S t|j|j|j|j|j|j|j|jdS )	a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

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

            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.
        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**.
        N)r%   rp   r   r   rr   r   r  r   r    r8   r  r%   rp   r   r   r   r"  r   r   r   rr   r   r  rs   )r  r   decoder_hidden_statesdecoder_attentionsr#  encoder_last_hidden_stater   encoder_attentions)ra   rr   r   r   r
  r3   r&   r'  r}   r   r  r(  r   r  r   rm   r	  r#  )r<   r%   rp   r-  r.  r   r/  r"  r0  r   r   r1  r   rr   r   r  rs   Zdecoder_outputsr1   r1   r2   rI     sd   /
zMBartModel.forwardNNNNNNNNNNNNNNNN)rL   rM   rN   _tied_weights_keysr!   r;   r  r   r)  r+  r,  r   r   rD   r  rQ   r   r  r   r   r   rI   rR   r1   r1   r=   r2   r%  f  sx    	
r%  z
    The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.
    )Zcustom_introc                )       s  e Zd ZdZdgZg dZdef fddZdd Zd	d
 Z		d0de
dee
 dedejf fddZde
ddfddZdd Zdd Ze																	d1d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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j deeeej f f$d*d+Zd$ejfd,d-Zed.d/ Z  ZS )2MBartForConditionalGenerationr   final_logits_bias)!model.encoder.embed_tokens.weight!model.decoder.embed_tokens.weightlm_head.weightra   c                    sX   t  | t|| _| dtd| jjjf t	j
|j| jjjdd| _|   d S )Nr:  r    Frc   )r:   r;   r%  r   register_bufferrD   zerosr&  r5   r   rh   r   lm_headr   r   r=   r1   r2   r;     s
   
z&MBartForConditionalGeneration.__init__c                 C   
   | j  S rW   )r   r)  r   r1   r1   r2   r)  
  r!  z)MBartForConditionalGeneration.get_encoderc                 C   rA  rW   )r   r+  r   r1   r1   r2   r+    r!  z)MBartForConditionalGeneration.get_decoderNTnew_num_tokenspad_to_multiple_ofmean_resizingrt   c                    s&   t  |||}| |jjd  |S )Nr   )r:   resize_token_embeddings_resize_final_logits_biasrG   rC   )r<   rB  rC  rD  new_embeddingsr=   r1   r2   rE    s   z5MBartForConditionalGeneration.resize_token_embeddingsc                 C   sj   | j jd }||kr| j d d d |f }ntjd|| f| j jd}tj| j |gdd}| d| d S )Nr)   r    r   r'   r:  )r:  rC   rD   r?  rB   catr>  )r<   rB  Zold_num_tokensZnew_biasZ
extra_biasr1   r1   r2   rF    s   z7MBartForConditionalGeneration._resize_final_logits_biasc                 C   r  rW   r@  r   r1   r1   r2   get_output_embeddings   r  z3MBartForConditionalGeneration.get_output_embeddingsc                 C   r  rW   rI  r<   rG  r1   r1   r2   set_output_embeddings#  r!  z3MBartForConditionalGeneration.set_output_embeddingsr%   rp   r-  r.  r   r/  r"  r0  r   r   r1  labelsr   rr   r   r  rs   c                 C   s  |dur|n| j j}|dur&|rtd d}|du r&|du r&t|| j j}| j|f||||||||	|
||||||d}| |d | j }d}|dur^t	 }||
d| j j|
d}|st|f|dd  }|durr|f| S |S t|||j|j|j|j|j|j|jd	S )	u  
        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.
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
            1]`:

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

        Example Translation:

        ```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']
        ```
        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)rp   r-  r0  r.  r   r/  r"  r   r   r1  r   rr   r   r  rs   r   r)   r    	losslogitsr   r3  r4  r#  r5  r   r6  )ra   r
  rf   warningr3   r&   r   r@  r:  r   r{   r   r   r   r3  r4  r#  r5  r   r6  )r<   r%   rp   r-  r.  r   r/  r"  r0  r   r   r1  rM  r   rr   r   r  rs   r   Z	lm_logitsZmasked_lm_lossloss_fctoutputr1   r1   r2   rI   &  sZ   [
z%MBartForConditionalGeneration.forwardc                 C   s   t || jjS rW   )r3   ra   r&   )r<   rM  r1   r1   r2   %prepare_decoder_input_ids_from_labels     zCMBartForConditionalGeneration.prepare_decoder_input_ids_from_labelsc                    sB   d}| D ]}|t  fdd|d d D |dd   f7 }q|S )Nr1   c                 3   $    | ]}| d  |jV  qdS rK   Zindex_selectr   rB   r   Z
past_statebeam_idxr1   r2   r       " z?MBartForConditionalGeneration._reorder_cache.<locals>.<genexpr>r8   r  r   rZ  Zreordered_pastZ
layer_pastr1   rY  r2   _reorder_cache  s   
z,MBartForConditionalGeneration._reorder_cache)NTNNNNNNNNNNNNNNNNN) rL   rM   rN   r   Z_keys_to_ignore_on_load_missingr8  r!   r;   r)  r+  rP   r   r   r   r   rE  rF  rJ  rL  r   rD   r  rQ   r   r  r   r   rI   rT  r   r^  rR   r1   r1   r=   r2   r9    s    			
 r9  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                &       s  e Zd ZddgZdef fddZe																d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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j	 deeef f"ddZ  ZS )MBartForSequenceClassificationr;  r<  ra   c                    sB   t  j|fi | t|| _t|j|j|j|j| _| 	  d S rW   )
r:   r;   r%  r   r   r   
num_labelsZclassifier_dropoutclassification_headr   )r<   ra   r   r=   r1   r2   r;     s   
z'MBartForSequenceClassification.__init__Nr%   rp   r-  r.  r   r/  r"  r0  r   r1  rM  r   rr   r   r  rs   rt   c                 C   s<  |dur|n| j j}|durd}|du r!|	dur!td| jj | j|||||||||	|
|||||d}|d }|| j j|j	}t
t|ddkrTtd||ddf |dd|ddddddf }| |}d}|dur||j	}| j jdu r| j jdkrd	| j _n| j jdkr|jtjks|jtjkrd
| j _nd| j _| j jd	krt }| j jdkr|| | }n,|||}n&| j jd
krt }||d| j j|d}n| j jdkrt }|||}|s
|f|dd  }|dur|f| S |S t|||j|j|j|j|j |j!|j"d	S )aN  
        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)

            Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
            is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

            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.

            If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *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 rp   r-  r.  r   r/  r"  r0  r   r1  r   rr   r   r  rs   r   r    z7All examples must have the same number of <eos> tokens.r)   Z
regressionZsingle_label_classificationZmulti_label_classificationrN  )#ra   r
  NotImplementedErrorr>   rL   r   eqZeos_token_idr   rB   r  rD   Zunique_consecutiver-   r+   r{   rz   rb  Zproblem_typera  rA   rF   rP   r	   r0   r   r   r   r   r3  r4  r#  r5  r   r6  )r<   r%   rp   r-  r.  r   r/  r"  r0  r   r1  rM  r   rr   r   r  rs   r   rm   Zeos_maskZsentence_representationrP  rO  rR  rS  r1   r1   r2   rI     s   5$

$

z&MBartForSequenceClassification.forwardr7  )rL   rM   rN   r8  r!   r;   r   r   rD   r  rQ   r   r  r   r   r   r   rI   rR   r1   r1   r=   r2   r`    sn    	

r`  c                (       s  e Zd ZddgZ fddZe																	d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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j	 deeef f$ddZ  ZS )MBartForQuestionAnsweringr;  r<  c                    sB   t  | d|_|j| _t|| _t|j|j| _| 	  d S r7   )
r:   r;   ra  r%  r   r   rh   hidden_size
qa_outputsr   r   r=   r1   r2   r;   ^  s   
z"MBartForQuestionAnswering.__init__Nr%   rp   r-  r.  r   r/  r"  r0  start_positionsend_positionsr   r1  r   rr   r   r  rs   rt   c                 C   s|  |dur|n| j j}|	dur|
durd}| j|||||||||||||||d}|d }| |}|jddd\}}|d }|d }d}|	dur|
durt|	 dkr_|	d}	t|
 dkrl|
d}
|d}|		d|}	|
	d|}
t
|d}|||	}|||
}|| d	 }|s||f|dd  }|dur|f| S |S t||||j|j|j|j|j|j|jd

S )a$  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

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

            Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
            is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

            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.

            If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.
        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**.
        NFrc  r   r    r)   r'   )Zignore_indexr8   )
rO  start_logits
end_logitsr   r3  r4  r#  r5  r   r6  )ra   r
  r   rh  splitr0   r   r  rz   r   r   r   r   r3  r4  r#  r5  r   r6  )r<   r%   rp   r-  r.  r   r/  r"  r0  ri  rj  r   r1  r   rr   r   r  rs   r   Zsequence_outputrP  rk  rl  Z
total_lossZignored_indexrR  Z
start_lossZend_lossrS  r1   r1   r2   rI   j  sr   3







z!MBartForQuestionAnswering.forwardr_  )rL   rM   rN   r8  r;   r   r   rD   rQ   r  r   r  r   r   r   r   rI   rR   r1   r1   r=   r2   rf  Z  st    	

rf  c                       s(   e Zd ZdZ fddZdd Z  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                    s   t  | t|| _d S rW   )r:   r;   r  r(  r   r=   r1   r2   r;     s   zMBartDecoderWrapper.__init__c                 O   s   | j |i |S rW   r*  r   r1   r1   r2   rI     s   zMBartDecoderWrapper.forward)rL   rM   rN   rO   r;   rI   rR   r1   r1   r=   r2   rn    s    rn  c                "       s  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
e														d$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 dee dee dee deej deeef fd d!Zed"d# Z  ZS )%MBartForCausalLMr=  c                    sN   t |}d|_d|_t | t|| _tj	|j
|jdd| _|   d S )NTFrc   )copydeepcopyr^   Zis_encoder_decoderr:   r;   rn  r   r   rh   rg  r   r@  r   r   r=   r1   r2   r;     s   

zMBartForCausalLM.__init__c                 C   s
   | j jjS rW   r   r(  r   r   r1   r1   r2   r    r!  z%MBartForCausalLM.get_input_embeddingsc                 C   s   || j j_d S rW   rr  r  r1   r1   r2   r     rU  z%MBartForCausalLM.set_input_embeddingsc                 C   r  rW   rI  r   r1   r1   r2   rJ    r  z&MBartForCausalLM.get_output_embeddingsc                 C   r  rW   rI  rK  r1   r1   r2   rL    r!  z&MBartForCausalLM.set_output_embeddingsc                 C   s   || j _d S rW   r   r(  )r<   r(  r1   r1   r2   set_decoder  s   zMBartForCausalLM.set_decoderc                 C   s   | j jS rW   rs  r   r1   r1   r2   r+    s   zMBartForCausalLM.get_decoderNr%   rp   r   r   r   r"  r   r   rM  r   rr   r   r  rs   rt   c                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| jj|||||||||
||||d}| |d }d}|	durU|	|j}	t	 }||
d| j j|	
d}|sk|f|dd  }|duri|f| S |S t|||j|j|j|jdS )a  
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

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

        Example:

        ```python
        >>> from transformers import AutoTokenizer, 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
        ```Nr2  r   r)   r    )rO  rP  r   rm   r	  r#  )ra   rr   r   r
  r   r(  r@  r   rB   r   r{   r   r   r   rm   r	  r#  )r<   r%   rp   r   r   r   r"  r   r   rM  r   rr   r   r  rs   r   rP  rO  rR  rS  r1   r1   r2   rI     sH   .zMBartForCausalLM.forwardc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr1   c                 3   rV  rK   rW  rX  rY  r1   r2   r  p  r[  z2MBartForCausalLM._reorder_cache.<locals>.<genexpr>r\  r]  r1   rY  r2   r^  k  s   zMBartForCausalLM._reorder_cache)NNNNNNNNNNNNNN)rL   rM   rN   r8  r;   r  r   rJ  rL  rt  r+  r   r   rD   r  rQ   r  r   r   r   r   r   rI   r   r^  rR   r1   r1   r=   r2   ro    sr    	

Yro  )ro  r9  rf  r`  r%  r   )NrO   rp  r   typingr   r   r   r   rD   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zactivationsr   Zcache_utilsr   r   Z
generationr   Zmodeling_attn_mask_utilsr   r   r   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   Zconfiguration_mbartr!   Z!torch.nn.attention.flex_attentionr"   Zintegrations.flex_attentionr#   r$   Z
get_loggerrL   rf   rQ   rP   r3   r   r4   rS   ModulerY   r   r   r   r   r   r   r   r   r  r%  r9  r`  rf  rn  ro  __all__r1   r1   r1   r2   <module>   s   $	
 xjDx ! =  1  G   