o
    Zh                    @   s  d Z ddl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/m0Z0 ddl1m2Z2 e rddlm3Z3 e,4e5Z6de	j7de8de8fddZ9G dd dej:Z;G dd dej:Z<G dd dej=Z>G dd  d e>Z?G d!d" d"e>Z@e>e@e?d#ZAG d$d% d%ej=ZBG d&d' d'ej=ZCG d(d) d)ej=ZDe)G d*d+ d+e'ZEG d,d- d-eEZFG d.d/ d/eEZGG d0d1 d1eEZHG d2d3 d3eEZIe)G d4d5 d5eEZJe)d6d7G d8d9 d9eEeZKe)d:d7G d;d< d<eEZLe)G d=d> d>eEZMG d?d@ d@eEZNe)dAd7G dBdC dCeEeZOg dDZPdS )EzPyTorch BART 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   )
BartConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forward	input_idspad_token_iddecoder_start_token_idc                 C   sh   |  | j}| ddddf  |ddddf< ||dddf< |du r*td||dk| |S )z1
    Shift input ids one token to the right.
    Nr    r   z1self.model.config.pad_token_id has to be defined.i)Z	new_zerosshapeclone
ValueErrorZmasked_fill_)r%   r&   r'   Zshifted_input_ids r,   U/var/www/auris/lib/python3.10/site-packages/transformers/models/bart/modeling_bart.pyshift_tokens_rightD   s   (r.   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 )BartLearnedPositionalEmbeddingzN
    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__)selfr0   r1   	__class__r,   r-   r6   Y   s   z'BartLearnedPositionalEmbedding.__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].Nr3   )dtypedevicer(   r   )r)   torcharangelongweightr=   expandZ	unsqueezer5   forwardr4   )r7   r%   r:   r;   bszZseq_lenr8   r,   r-   rC   _   s   
z&BartLearnedPositionalEmbedding.forwardr   N)
__name__
__module____qualname____doc__intr6   r>   TensorrC   __classcell__r,   r,   r8   r-   r/   T   s    (r/   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 )BartScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
          ?r0   r1   padding_idxembed_scalec                    s   t  ||| || _d S N)r5   r6   rP   )r7   r0   r1   rO   rP   r8   r,   r-   r6   r   s   
z BartScaledWordEmbedding.__init__r%   c                    s   t  || j S rQ   )r5   rC   rP   )r7   r%   r8   r,   r-   rC   v   s   zBartScaledWordEmbedding.forward)rN   )rF   rG   rH   rI   rJ   r   floatr6   r>   rK   rC   rL   r,   r,   r8   r-   rM   m   s    $rM   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 )BartAttentionz=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.rY   )r5   r6   rU   rV   rW   head_dimr[   r+   scalingrX   rZ   r\   loggerwarning_oncer9   rF   r   Lineark_projv_projq_projout_proj)	r7   rU   rV   rW   rX   rY   rZ   r[   r\   r8   r,   r-   r6   }   s0   


zBartAttention.__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    r3   rm   Tz$Attention weights should be of size z	, but is dimz/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizere   viewrV   r^   	transposer_   
isinstancer   
is_updatedgetr\   cross_attention_cacheself_attention_cache	key_cachevalue_cacherc   rd   updatereshaper>   Zbmmr+   r)   r   
functionalZsoftmaxrW   ru   rU   rf   )r7   rg   rh   ri   rj   rk   rl   rm   is_cross_attentionrD   tgt_len_query_statesrz   curr_past_key_valuecurrent_states
key_statesvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr,   r,   r-   rC      s   "








&
"

zBartAttention.forward)rT   FTFNNNNNNFN)rF   rG   rH   rI   rJ   rR   boolr   r!   r6   r>   rK   r   r   rC   rL   r,   r,   r8   r-   rS   z   s`    	*	rS   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 )BartFlashAttention2aD  
    Bart flash attention module. This module inherits from `BartAttention` 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 rQ   )r5   r6   r   _flash_attn_uses_top_left_maskr7   argskwargsr8   r,   r-   r6     s   zBartFlashAttention2.__init__NFrg   rh   ri   rj   rk   rl   rm   rn   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 )NzBartSdpaAttention2 attention does not support `output_attentions`. Use the argument `attn_implementation='eager'` when loading the model.r(   r    r3   rm   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 .rT   )rW   rZ   Zuse_top_left_mask)&r+   rv   re   rw   rV   r^   ry   r   rz   r{   r\   r|   r}   r~   r   rc   rd   rx   r   r<   r>   Zfloat32Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr[   r   rA   r`   ra   tor$   ru   rW   rZ   r   r   rf   )r7   rg   rh   ri   rj   rk   rl   rm   r   rD   Zq_lenr   r   rz   r   r   r   r   Zinput_dtypeZtarget_dtyper   r,   r,   r-   rC   &  sv   











zBartFlashAttention2.forwardr   )rF   rG   rH   rI   r6   r>   rK   r   r   r   r   rC   rL   r,   r,   r8   r-   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 )BartSdpaAttentionNFrg   rh   ri   rj   rk   rl   rm   rn   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 )ro   a  BartModel is using BartSdpaAttention, 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.)rh   ri   rj   rl   rm   Nr(   r    r3   rm   Trp   cudaFrT   )	attn_maskZ	dropout_prZ   )#r`   ra   r5   rC   rv   re   rw   rV   r^   rx   ry   r   rz   r{   r\   r|   r}   r~   r   rc   rd   r   r)   r=   type
contiguousrZ   r>   r   r   Zscaled_dot_product_attentionru   rW   rU   rf   )r7   rg   rh   ri   rj   rk   rl   rm   r   rD   r   r   r   rz   r   r   r   r   causal_maskrZ   r   r8   r,   r-   rC     sr   "


&	

zBartSdpaAttention.forwardr   )rF   rG   rH   r>   rK   r   r   r   r   rC   rL   r,   r,   r8   r-   r     s0    	r   )eagersdpaflash_attention_2c                       sh   e Zd Zddedee f fddZ	ddejdejd	ejd
ee	 de
ejeej f f
ddZ  ZS )BartEncoderLayerNr[   r\   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)rU   rV   rW   r[   r\   )r5   r6   d_modelrU   BART_ATTENTION_CLASSES_attn_implementationZencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrW   r   activation_functionactivation_fnactivation_dropoutrb   Zencoder_ffn_dimfc1fc2final_layer_normr7   r[   r\   r8   r,   r-   r6     s    
zBartEncoderLayer.__init__Frg   rj   rk   rl   rn   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rvt| sdt| rvt|jjd }tj|| |d}|f}	|r|	|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.
        )rg   rj   rk   rl   rs   i  )minmax)r   r   r   rW   ru   r   r   r   r   r   r   r<   r>   Zfloat16isinfanyisnanfinfor   clamp)
r7   rg   rj   rk   rl   residualr   r   Zclamp_valueoutputsr,   r,   r-   rC     s8   



zBartEncoderLayer.forwardrQ   F)rF   rG   rH   r!   r   rJ   r6   r>   FloatTensorr   r   rC   rL   r,   r,   r8   r-   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ejeeejejf  f fddZ  ZS )BartDecoderLayerNr[   r\   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)rU   rV   rW   rX   rZ   r[   r\   )rW   rX   r[   r\   )r5   r6   r   rU   r   r   Zdecoder_attention_headsr   r   rW   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrb   Zdecoder_ffn_dimr   r   r   r   r8   r,   r-   r6   F  s6   
	zBartDecoderLayer.__init__FTrg   rj   encoder_hidden_statesencoder_attention_maskrk   cross_attn_layer_head_maskri   rl   	use_cacherm   rn   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.
        )rg   ri   rj   rk   rl   rm   rs   N)rg   rh   rj   rk   ri   rl   )r   r   r   rW   ru   r   r   r   r   r   r   r   r   )r7   rg   rj   r   r   rk   r   ri   rl   r   rm   r   Zself_attn_weightsZcross_attn_weightsr   r,   r,   r-   rC   e  sN   "




zBartDecoderLayer.forwardrQ   )	NNNNNNFTN)rF   rG   rH   r!   r   rJ   r6   r>   rK   r   r   r   r   rC   rL   r,   r,   r8   r-   r   E  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 )BartClassificationHeadz-Head for sentence-level classification tasks.	input_dim	inner_dimnum_classespooler_dropoutc                    s8   t    t||| _tj|d| _t||| _d S )N)rt   )r5   r6   r   rb   denseZDropoutrW   rf   )r7   r   r   r   r   r8   r,   r-   r6     s   
zBartClassificationHead.__init__rg   rn   c                 C   s6   |  |}| |}t|}|  |}| |}|S rQ   )rW   r   r>   tanhrf   )r7   rg   r,   r,   r-   rC     s   




zBartClassificationHead.forward)rF   rG   rH   rI   rJ   rR   r6   r>   rK   rC   rL   r,   r,   r8   r-   r     s    r   c                   @   s   e Zd ZeZdZdZddgZddgZ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 )BartPreTrainedModelmodelTzencoder.versionzdecoder.versionr   r   past_key_valuesc                 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 )NrT   )meanstdrN   )r[   Zinit_stdry   r   rb   rA   dataZnormal_rY   Zzero_	EmbeddingrO   r   Zfill_)r7   moduler   r,   r,   r-   _init_weights  s   

z!BartPreTrainedModel._init_weightsc                 C   s>   | j j}tjg ddddd|gg| jd}|||d}|S )N)r      
      r3   r         r3   r=   )rj   r%   )r[   r&   r>   Ztensorr=   ne)r7   Z	pad_tokenr%   dummy_inputsr,   r,   r-   r     s   "z BartPreTrainedModel.dummy_inputsFrj   r"   input_tensorrm   rl   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   rT   Zflex_attentionr   Fr   )inputs_embedsr:   Zis_trainingr    r(   )sequence_lengthtarget_lengthr<   rm   
batch_size)r   ZxpuZnpu)r[   r   r   ry   r>   rK   r#   get_seq_lengthZis_compileabler   Z_ignore_causal_mask_sdparu   r<   r)   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr=   r   r   r   Z_unmask_unattended)r7   rj   r   rm   r   rl   Zpast_seen_tokensZusing_compilable_cacher<   r   r   r   	min_dtyper,   r,   r-   _update_causal_mask  sT   




z'BartPreTrainedModel._update_causal_maskr   r   r<   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_valuer<   r=   r    )Zdiagonalr   r(   r   )rr   r>   r   r   fullr=   Ztriur?   r   rB   r*   r)   r   Zmasked_fill)rj   r   r   r<   rm   r   r   r   r   Zmask_lengthZpadding_maskr,   r,   r-   r   =  s,    $
6  zIBartPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_positionNr   )rF   rG   rH   r!   Zconfig_classbase_model_prefixZsupports_gradient_checkpointingZ"_keys_to_ignore_on_load_unexpectedZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_static_cacher   propertyr   r   r>   rK   r   r   r   staticmethodrJ   r<   r   r,   r,   r,   r-   r     sP    

Dr   c                   @      e Zd Zdd ZdS )PretrainedBartModelc                 C      t dt d S Nz_The class `PretrainedBartModel` has been depreciated, please use `BartPreTrainedModel` instead.warningswarnFutureWarningr7   r,   r,   r-   __init_subclass__w     z%PretrainedBartModel.__init_subclass__NrF   rG   rH   r   r,   r,   r,   r-   r   v      r   c                   @   r   )BartPretrainedModelc                 C   r   r   r   r   r,   r,   r-   r     r   z%BartPretrainedModel.__init_subclass__Nr   r,   r,   r,   r-   r   ~  r   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 dee dee deeef fddZ  ZS )BartEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`BartEncoderLayer`].

    Args:
        config: BartConfig
        embed_tokens (nn.Embedding): output embedding
    Nr[   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 | _ jdk| _ jdk| _t|| _d| _|   d S )NrN   rP   c                       g | ]}t  |d qS )r\   )r   .0ir[   r,   r-   
<listcomp>      z(BartEncoder.__init__.<locals>.<listcomp>r   r   F)r5   r6   rW   Zencoder_layerdrop	layerdropr   r&   rO   max_position_embeddingsZmax_source_positionsscale_embeddingmathsqrtrM   
vocab_sizer   rA   r/   embed_positionsr   
ModuleListrangeZencoder_layerslayersr   _use_flash_attention_2	_use_sdpar   layernorm_embeddinggradient_checkpointing	post_init)r7   r[   r   rU   rP   r8   r   r-   r6     s,   
 zBartEncoder.__init__c                 C      | j S rQ   r   r   r,   r,   r-   get_input_embeddings     z BartEncoder.get_input_embeddingsc                 C   
   || _ d S rQ   r  r7   valuer,   r,   r-   set_input_embeddings     
z BartEncoder.set_input_embeddingsr%   rj   	head_maskr   rl   output_hidden_statesreturn_dictrn   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:|}|d|jd }n|durJ|dddddf }ntd|du rW| |}| |}	|		|j
}	||	 }
| |
}
tjj|
| j| jd}
|dur| jrd|v r|nd}n| j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 }
|r*||d f }q|r3||
f }|sBt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_embedsrs   r   r,   z&The head_mask should be specified for  layers, but it is for r   FT)NN)rk   rl   r    c                 s       | ]	}|d ur|V  qd S rQ   r,   r   vr,   r,   r-   	<genexpr><  s    z&BartEncoder.forward.<locals>.<genexpr>last_hidden_staterg   
attentions)!r[   rl   r  use_return_dictr+   rw   r)   r   r  r   r=   r  r   r   rW   ru   r
  r  r   r<   r   rv   lenr	  	enumerater>   randr   r  _gradient_checkpointing_func__call__tupler   )r7   r%   rj   r  r   rl   r  r  inputZ	embed_posrg   Zencoder_statesZall_attentionsidxZencoder_layerZto_dropdropout_probabilitylayer_outputsr,   r,   r-   rC     s   .







zBartEncoder.forwardrQ   )NNNNNNN)rF   rG   rH   rI   r!   r   r   r   r6   r  r  r>   
LongTensorrK   r   r   r   r   r   rC   rL   r,   r,   r8   r-   r     s:    	
	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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 )BartDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BartDecoderLayer`]

    Args:
        config: BartConfig
        embed_tokens (nn.Embedding): output embedding
    Nr[   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 | _ jdk| _ jdk| _t j| _d| _|   d S )NrN   r   c                    r   r   )r   r   r   r,   r-   r   ^  r   z(BartDecoder.__init__.<locals>.<listcomp>r   r   F)r5   r6   rW   Zdecoder_layerdropr   r&   rO   r  Zmax_target_positionsr  r  r  r   rM   r  r   rA   r/   r  r   r  r  Zdecoder_layersr	  r   r
  r  r   r  r  r  )r7   r[   r   rP   r8   r   r-   r6   K  s*   
 zBartDecoder.__init__c                 C   r  rQ   r  r   r,   r,   r-   r  h  r  z BartDecoder.get_input_embeddingsc                 C   r  rQ   r  r  r,   r,   r-   r  k  r  z BartDecoder.set_input_embeddingsr%   rj   r   r   r  cross_attn_head_maskr   r   r   rl   r  r  rm   rn   c           "      C   s<  |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}| jr7| jr7|	r7td d}	|du |duA rCt	d|durP|
d|jd }|du rY| |}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rd|v r|nd}n| j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rW| d t'| j(krWt	d| dt'| j( d| d  dq-t)| j(D ]\}}|rj||f7 }| jr{t*g }|| j+k r{q^| 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 }q^|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.
        NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer(   TzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r   )r   )r;   rs   r,   r  r0  zThe `z` should be specified for r  r   )	rj   r   r   rk   r   ri   rl   r   rm   r
   r    r3   c                 s   r  rQ   r,   r  r,   r,   r-   r  c  s    z&BartDecoder.forward.<locals>.<genexpr>)r!  r   rg   r"  cross_attentions)1r[   rl   r  r   r#  r  ru   r`   ra   r+   rw   r)   r   ry   r   r   Zfrom_legacy_cacherv   r   r>   r?   r=   r   Zonesr}   r   r
  r  r   r<   r   r  r*  r   r  r   r   rW   zipr$  r	  r%  r&  r   r'  r(  Zto_legacy_cacher)  r   )"r7   r%   rj   r   r   r  r0  r   r   r   rl   r  r  rm   Zreturn_legacy_cacher   Z
seq_lengthr:   Zmask_seq_lengthZself_attn_cacher   r;   rg   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacher   Z	mask_namer+  Zdecoder_layerr,  r-  Z
next_cacher,   r,   r-   rC   n  s  T

	






zBartDecoder.forwardrQ   )NNNNNNNNNNNNN)rF   rG   rH   rI   r!   r   r   r   r6   r  r  r>   r.  rK   r   r   r   r   r   r   rC   rL   r,   r,   r8   r-   r/  B  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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  ZS )%	BartModelencoder.embed_tokens.weightdecoder.embed_tokens.weightr[   c                    sl   t  | |j|j}}|jrt|jnd}t||j||d| _	t
|| j	| _t|| j	| _|   d S )NrN   r   )r5   r6   r&   r  r  r  r  r   rM   sharedr   encoderr/  decoderr  )r7   r[   rO   r  rP   r8   r,   r-   r6   u  s   zBartModel.__init__c                 C   s   | j jrB| jjjtdkr.| jjjjtdkr.| | j	j| jj | | j| jj d S | | j	j| j | | jj| j d S d S )Nmeta)
r[   tie_word_embeddingsr6  rA   r=   r>   r8  r   _tie_or_clone_weightsr7  r   r,   r,   r-   _tie_weights  s   zBartModel._tie_weightsc                 C   r  rQ   )r6  r   r,   r,   r-   r    r  zBartModel.get_input_embeddingsc                 C   s   || _ | j | j_| j | j_d S rQ   )r6  r7  r   r8  r  r,   r,   r-   r    s   
zBartModel.set_input_embeddingsc                 C   r  rQ   )r7  r   r,   r,   r-   get_encoder  r  zBartModel.get_encoderc                 C   r  rQ   r8  r   r,   r,   r-   get_decoder  r  zBartModel.get_decoderNr%   rj   decoder_input_idsdecoder_attention_maskr  decoder_head_maskr0  encoder_outputsr   r   decoder_inputs_embedsr   rl   r  r  rm   rn   c                 C   sJ  |du r|du r|du rt dt|| jj| jj}|dur |n| jj}|dur*|n| jj}|dur4|n| jj}|dur>|n| jj}|du rS| j	||||
|||d}n$|rwt
|tswt|d t|dkrh|d ndt|dkrs|d ndd}| j|||d ||||	||||||d}|s|| S t|j|j|j|j|j|j|j|jd	S )
$  
        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**.
        NzIf no `decoder_input_ids` or `decoder_inputs_embeds` are passed, `input_ids` cannot be `None`. Please pass either `input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.)r%   rj   r  r   rl   r  r  r   r    r3   r   r%   rj   r   r   r  r0  r   r   r   rl   r  r  rm   )r!  r   decoder_hidden_statesdecoder_attentionsr1  encoder_last_hidden_stater   encoder_attentions)r+   r.   r[   r&   r'   rl   r  r   r#  r7  ry   r   r$  r8  r   r!  r   rg   r"  r1  )r7   r%   rj   r@  rA  r  rB  r0  rC  r   r   rD  r   rl   r  r  rm   Zdecoder_outputsr,   r,   r-   rC     sp   3
zBartModel.forwardNNNNNNNNNNNNNNNN)rF   rG   rH   _tied_weights_keysr!   r6   r<  r  r  r=  r?  r   r   r>   r.  rK   r   r   r   r   r   r   rC   rL   r,   r,   r8   r-   r3  q  sx    	

r3  zV
    The BART Model with a language modeling head. Can be used for summarization.
    )Zcustom_introc                (       s  e Zd ZdZg dZdgZdef fddZdd Zd	d
 Z		d2d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dd Ze																	d3d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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d&ejfd.d/Zed0d1 Z   Z!S )4BartForConditionalGenerationr   )r4  r5  lm_head.weightfinal_logits_biasr[   c                    sX   t  | t|| _| dtd| jjjf t	j
|j| jjjdd| _|   d S )NrO  r    Fr]   )r5   r6   r3  r   register_bufferr>   zerosr6  r0   r   rb   r   lm_headr  r7   r[   r8   r,   r-   r6     s
   
z%BartForConditionalGeneration.__init__c                 C   
   | j  S rQ   )r   r=  r   r,   r,   r-   r=  '  r  z(BartForConditionalGeneration.get_encoderc                 C   rT  rQ   )r   r?  r   r,   r,   r-   r?  *  r  z(BartForConditionalGeneration.get_decoderNTnew_num_tokenspad_to_multiple_ofmean_resizingrn   c                    s&   t  |||}| |jjd  |S )Nr   )r5   resize_token_embeddings_resize_final_logits_biasrA   r)   )r7   rU  rV  rW  new_embeddingsr8   r,   r-   rX  -  s   z4BartForConditionalGeneration.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   rq   rO  )rO  r)   r>   rQ  r=   catrP  )r7   rU  Zold_num_tokensZnew_biasZ
extra_biasr,   r,   r-   rY  4  s   z6BartForConditionalGeneration._resize_final_logits_biasc                 C   r  rQ   rR  r   r,   r,   r-   get_output_embeddings=  r  z2BartForConditionalGeneration.get_output_embeddingsc                 C   r  rQ   r\  r7   rZ  r,   r,   r-   set_output_embeddings@  r  z2BartForConditionalGeneration.set_output_embeddingsc                 C   s,   | j jr| j  | | j| jj d S d S rQ   )r[   r:  r   r<  r;  rR  r6  r   r,   r,   r-   r<  C  s   
z)BartForConditionalGeneration._tie_weightsr%   rj   r@  rA  r  rB  r0  rC  r   r   rD  labelsr   rl   r  r  rm   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 j}| j|f||||||||	|
||||||d}| |d }|| j	
|j }d}|durm|
|j}t }||d| j j|d}|s|f|dd  }|dur|f| S |S t|||j|j|j|j|j|j|jd	S )	aa  
        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, 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 summarization:

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

        >>> model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")

        >>> ARTICLE_TO_SUMMARIZE = (
        ...     "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
        ...     "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
        ...     "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
        ... )
        >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="pt")

        >>> # Generate Summary
        >>> summary_ids = model.generate(inputs["input_ids"], num_beams=2, min_length=0, max_length=20)
        >>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        'PG&E scheduled the blackouts in response to forecasts for high winds amid dry conditions'
        ```

        Mask filling example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
        >>> model = BartForConditionalGeneration.from_pretrained("facebook/bart-base")

        >>> TXT = "My friends are <mask> but they eat too many carbs."
        >>> input_ids = tokenizer([TXT], 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()
        ['not', 'good', 'healthy', 'great', 'very']
        ```
        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)rj   r@  rC  rA  r  rB  r0  r   r   rD  r   rl   r  r  rm   r   r(   r    	losslogitsr   rG  rH  r1  rI  r   rJ  )r[   r#  r`   warningr.   r&   r'   r   rR  rO  r   r=   r   rw   r  r   r   rG  rH  r1  rI  r   rJ  )r7   r%   rj   r@  rA  r  rB  r0  rC  r   r   rD  r`  r   rl   r  r  rm   r   Z	lm_logitsZmasked_lm_lossloss_fctoutputr,   r,   r-   rC   H  sb   _
z$BartForConditionalGeneration.forwardc                 C   s   t || jj| jjS rQ   )r.   r[   r&   r'   )r7   r`  r,   r,   r-   %prepare_decoder_input_ids_from_labels  s   zBBartForConditionalGeneration.prepare_decoder_input_ids_from_labelsc                    sB   d}| D ]}|t  fdd|d d D |dd   f7 }q|S )Nr,   c                 3   $    | ]}| d  |jV  qdS rE   Zindex_selectr   r=   r   Z
past_statebeam_idxr,   r-   r       " z>BartForConditionalGeneration._reorder_cache.<locals>.<genexpr>r3   r)  r   rl  Zreordered_pastZ
layer_pastr,   rk  r-   _reorder_cache  s   
z+BartForConditionalGeneration._reorder_cache)NTNNNNNNNNNNNNNNNNN)"rF   rG   rH   r   rL  Z_keys_to_ignore_on_load_missingr!   r6   r=  r?  rJ   r   r   r   r   rX  rY  r]  r_  r<  r   r>   r.  rK   r   r   r   r   r   rC   rg  r   rp  rL   r,   r,   r8   r-   rM    s    			

 rM  z
    Bart 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 )BartForSequenceClassificationr4  r5  r[   c                    sB   t  j|fi | t|| _t|j|j|j|j| _| 	  d S rQ   )
r5   r6   r3  r   r   r   
num_labelsZclassifier_dropoutclassification_headr  )r7   r[   r   r8   r,   r-   r6     s   
z&BartForSequenceClassification.__init__Nr%   rj   r@  rA  r  rB  r0  rC  r   rD  r`  r   rl   r  r  rm   rn   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 rj   r@  rA  r  rB  r0  rC  r   rD  r   rl   r  r  rm   r   r    z7All examples must have the same number of <eos> tokens.r(   Z
regressionZsingle_label_classificationZmulti_label_classificationra  )#r[   r#  NotImplementedErrorr9   rF   r   eqZeos_token_idr   r=   r$  r>   Zunique_consecutivesumr+   rw   rv   rt  Zproblem_typers  r<   r@   rJ   r	   squeezer   r   r   r   rG  rH  r1  rI  r   rJ  )r7   r%   rj   r@  rA  r  rB  r0  rC  r   rD  r`  r   rl   r  r  rm   r   rg   Zeos_maskZsentence_representationrc  rb  re  rf  r,   r,   r-   rC     s   4$

$

z%BartForSequenceClassification.forwardrK  )rF   rG   rH   rL  r!   r6   r   r   r>   r.  rK   r   r   r   r   r   r   rC   rL   r,   r,   r8   r-   rr    sn    	

rr  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 )BartForQuestionAnsweringr4  r5  c                    sB   t  | d|_|j| _t|| _t|j|j| _| 	  d S r2   )
r5   r6   rs  r3  r   r   rb   hidden_size
qa_outputsr  rS  r8   r,   r-   r6     s   
z!BartForQuestionAnswering.__init__Nr%   rj   r@  rA  r  rB  r0  rC  start_positionsend_positionsr   rD  r   rl   r  r  rm   rn   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 )rE  NFru  r   r    r(   rq   )Zignore_indexr3   )
rb  start_logits
end_logitsr   rG  rH  r1  rI  r   rJ  )r[   r#  r   r|  splitry  r   r$  rv   r   r   r   r   rG  rH  r1  rI  r   rJ  )r7   r%   rj   r@  rA  r  rB  r0  rC  r}  r~  r   rD  r   rl   r  r  rm   r   Zsequence_outputrc  r  r  Z
total_lossZignored_indexre  Z
start_lossZend_lossrf  r,   r,   r-   rC     sr   2







z BartForQuestionAnswering.forwardrq  )rF   rG   rH   rL  r6   r   r   r>   rK   r.  r   r   r   r   r   r   rC   rL   r,   r,   r8   r-   rz    st    	

rz  c                       s(   e Zd ZdZ fddZdd Z  ZS )BartDecoderWrapperz
    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 rQ   )r5   r6   r/  r8  rS  r8   r,   r-   r6     s   zBartDecoderWrapper.__init__c                 O   s   | j |i |S rQ   r>  r   r,   r,   r-   rC     s   zBartDecoderWrapper.forward)rF   rG   rH   rI   r6   rC   rL   r,   r,   r8   r-   r  	  s    r  zu
    BART decoder with a language modeling head on top (linear layer with weights tied to the input embeddings).
    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 )%BartForCausalLMrN  c                    sN   t |}d|_d|_t | t|| _tj	|j
|jdd| _|   d S )NTFr]   )copydeepcopyrX   Zis_encoder_decoderr5   r6   r  r   r   rb   r{  r  rR  r  rS  r8   r,   r-   r6     s   

zBartForCausalLM.__init__c                 C   s
   | j jjS rQ   r   r8  r   r   r,   r,   r-   r  +  r  z$BartForCausalLM.get_input_embeddingsc                 C   s   || j j_d S rQ   r  r  r,   r,   r-   r  .  s   z$BartForCausalLM.set_input_embeddingsc                 C   r  rQ   r\  r   r,   r,   r-   r]  1  r  z%BartForCausalLM.get_output_embeddingsc                 C   r  rQ   r\  r^  r,   r,   r-   r_  4  r  z%BartForCausalLM.set_output_embeddingsc                 C   s   || j _d S rQ   r   r8  )r7   r8  r,   r,   r-   set_decoder7  s   zBartForCausalLM.set_decoderc                 C   s   | j jS rQ   r  r   r,   r,   r-   r?  :  s   zBartForCausalLM.get_decoderNr%   rj   r   r   r  r0  r   r   r`  r   rl   r  r  rm   rn   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, BartForCausalLM

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
        >>> model = BartForCausalLM.from_pretrained("facebook/bart-base", 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
        ```NrF  r   r(   r    )rb  rc  r   rg   r"  r1  )r[   rl   r  r#  r   r8  rR  r   r=   r   rw   r  r   r   rg   r"  r1  )r7   r%   rj   r   r   r  r0  r   r   r`  r   rl   r  r  rm   r   rc  rb  re  rf  r,   r,   r-   rC   =  sH   .zBartForCausalLM.forwardc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr,   c                 3   rh  rE   ri  rj  rk  r,   r-   r    rm  z1BartForCausalLM._reorder_cache.<locals>.<genexpr>rn  ro  r,   rk  r-   rp    s   zBartForCausalLM._reorder_cache)NNNNNNNNNNNNNN)rF   rG   rH   rL  r6   r  r  r]  r_  r  r?  r   r   r>   r.  rK   r   r   r   r   r   r   rC   r   rp  rL   r,   r,   r8   r-   r    sr    	

Yr  )r  rM  rz  rr  r3  r   r   r   )QrI   r  r  r   typingr   r   r   r   r>   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_bartr!   Z!torch.nn.attention.flex_attentionr"   Zintegrations.flex_attentionr#   r$   Z
get_loggerrF   r`   rK   rJ   r.   r   r/   rM   ModulerS   r   r   r   r   r   r   r   r   r   r   r/  r3  rM  rr  rz  r  r  __all__r,   r,   r,   r-   <module>   s   $	
 wjGv # =  1 # U   