
    gS                       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 dd	lmZmZmZmZ dd
lmZmZmZmZmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-  e(            rddl.m/Z/  e*j0        e1          Z2dZ3dZ4g dZ5dZ6dZ7dZ8dZ9dZ:dZ;de	j<        de=de=fdZ> G d dej?                  Z@ G d d ej?                  ZA G d! d"ejB                  ZC G d# d$eC          ZD G d% d&eC          ZEeCeEeDd'ZF G d( d)ejB                  ZG G d* d+ejB                  ZH G d, d-ejB                  ZI G d. d/e"          ZJ G d0 d1eJ          ZK G d2 d3eJ          ZLd4ZMd5ZNd6ZO G d7 d8eJ          ZP G d9 d:eJ          ZQ e&d;eM           G d< d=eJ                      ZR e&d>eM           G d? d@eJe                      ZS e&dAeM           G dB dCeJ                      ZT e&dDeM           G dE dFeJ                      ZU G dG dHeJ          ZV e&dIeM           G dJ dKeJe                      ZWdS )LzPyTorch BART model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GenerationMixin)_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_end_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )
BartConfig)_flash_attention_forwardzfacebook/bart-baser#   )r"      i   zvalhalla/bart-large-sst2        z
'POSITIVE'z%valhalla/bart-large-finetuned-squadv1gzG?z' nice puppet'	input_idspad_token_iddecoder_start_token_idc                     |                      | j                  }| ddddf                                         |ddddf<   ||dddf<   |t          d          |                    |dk    |           |S )z1
    Shift input ids one token to the right.
    Nr"   r   z1self.model.config.pad_token_id has to be defined.i)	new_zerosshapeclone
ValueErrormasked_fill_)r'   r(   r)   shifted_input_idss       b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/bart/modeling_bart.pyshift_tokens_rightr3   Q   s     "++IO<<(CRC06688aaae4aaadLMMM""#4#<lKKK    c                   L     e Zd ZdZdedef fdZd	dej        def fdZ xZ	S )
BartLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                 j    d| _         t                                          || j         z   |           d S N   )offsetsuper__init__)selfr7   r8   	__class__s      r2   r>   z'BartLearnedPositionalEmbedding.__init__f   s3     $+5}EEEEEr4   r   r'   past_key_values_lengthc                     |j         dd         \  }}t          j        |||z   t          j        | j        j                                      |d          }t                                          || j	        z             S )z3`input_ids' shape is expected to be [bsz x seqlen].Nr;   )dtypedevicer+   )
r-   torcharangelongweightrD   expandr=   forwardr<   )r?   r'   rA   bszseq_len	positionsr@   s         r2   rJ   z&BartLearnedPositionalEmbedding.forwardl   sv     !rr*WL"$:W$DEJ_c_j_q
 
 

&b// 	 wwy4;6777r4   )r   )
__name__
__module____qualname____doc__intr>   rE   TensorrJ   __classcell__r@   s   @r2   r6   r6   a   s         Fs F3 F F F F F F8 8 8s 8 8 8 8 8 8 8 8 8 8r4   r6   c            
       \     e Zd ZdZd
dedededee         f fdZdej	        f fd	Z
 xZS )BartScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
          ?r7   r8   padding_idxembed_scalec                 \    t                                          |||           || _        d S N)r=   r>   rZ   )r?   r7   r8   rY   rZ   r@   s        r2   r>   z BartScaledWordEmbedding.__init__|   s-    DDD&r4   r'   c                 V    t                                          |          | j        z  S r\   )r=   rJ   rZ   )r?   r'   r@   s     r2   rJ   zBartScaledWordEmbedding.forward   s!    wwy))D,<<<r4   )rX   )rN   rO   rP   rQ   rR   r   floatr>   rE   rS   rJ   rT   rU   s   @r2   rW   rW   w   s         ' 's '3 'S '_ghm_n ' ' ' ' ' '= = = = = = = = = = =r4   rW   c                   h    e Zd ZdZ	 	 	 	 	 ddededed	ed
ededee         f fdZ	de
j        dedefdZ	 	 	 	 	 dde
j        dee
j                 deee
j                          dee
j                 dee
j                 dedee
j        ee
j                 eee
j                          f         fdZ xZS )BartAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr&   FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfigc                 
   t                                                       || _        || _        || _        ||z  | _        || _        | j        |z  | j        k    rt          d| j         d| d          | j        dz  | _        || _	        || _
        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        t          j        |||          | _        d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩re   )r=   r>   ra   rb   rc   head_dimrg   r/   scalingrd   rf   r   Lineark_projv_projq_projout_proj)	r?   ra   rb   rc   rd   re   rf   rg   r@   s	           r2   r>   zBartAttention.__init__   s    	""!Y.MI%$.883dn 3 3%.3 3 3   }d*$"i	94@@@i	94@@@i	94@@@	)YTBBBr4   tensorrL   rK   c                     |                     ||| j        | j                                      dd                                          S )Nr"   r;   )viewrb   rj   	transpose
contiguousr?   rq   rL   rK   s       r2   _shapezBartAttention._shape   s<    {{3GGQQRSUVWWbbdddr4   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsreturnc                 Z
   |du}|                                 \  }}	}
|                     |          | j        z  }|r6|4|d         j        d         |j        d         k    r|d         }|d         }n>|rU|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j	        r||f}|| j
        z  d| j        f} |                     ||	|          j        | } |j        | } |j        | }|                     d          }t          j        ||                    dd                    }|                                 || j
        z  |	|fk    r2t!          d|| j
        z  |	|f d|                                            ||                                 |d|	|fk    r+t!          d	|d|	|f d|                                            |                    || j
        |	|          |z   }|                    || j
        z  |	|          }t"          j                            |d          }||                                 | j
        fk    r-t!          d
| j
        f d|                                            |                    dddd          |                    || j
        |	|          z  }|                    || j
        z  |	|          }|r=|                    || j
        |	|          }|                    || j
        z  |	|          }nd}t"          j                            || j        | j                  }t          j        ||          }|                                 || j
        z  |	| j        fk    r7t!          d|| j
        z  |	| j        f d|                                            |                    || j
        |	| j                  }|                    dd          }|                    ||	| j                  }|                     |          }|||fS )#Input shape: Batch x Time x ChannelNr   r;   r"   r+   dimz$Attention weights should be of size 	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptraining `attn_output` should be of size )sizero   rk   r-   rw   rm   rn   rE   catrd   rb   rj   rs   reshapebmmrt   r/   r   
functionalsoftmaxrc   r   ra   rp   )r?   rx   ry   rz   r{   r|   r}   is_cross_attentionrK   tgt_len_query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                       r2   rJ   zBartAttention.forward   s    .T9',,..Wa {{=11DL@ 	L*q!'*.>.DQ.GGG (*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7NDN*B>
Ct{{<#>>CZP'Z'4
+|+Z8//!$$yz/C/CAq/I/IJJ3#7'"JJJ*dn8LgW^7_ * * %%''* *  
 %""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (,,S$.'7SSVddL',,S4>-A7GTTL},,\r,BB&##%%$.)::: 1t~FW 1 1',,..1 1   +//2q!<<|?P?PQTVZVdfmov?w?wwL',,S4>-A7GTTL 	)
 %1$5$5c4>7T[$\$\!055cDN6JGU\]]LL$(!]**<4<RVR_*``
i
L99#"6!OOO)C$.4H'SWS`3a ) )$$&&) )  
 "&&sDNGT]SS!++Aq11 "))#wGGmmK001>AAr4   )r&   FTFNNNNNF)rN   rO   rP   rQ   rR   r^   boolr   r#   r>   rE   rS   rw   r   rJ   rT   rU   s   @r2   r`   r`      s       GG  '+C CC C 	C
 C C C $C C C C C C>eU\ eC ec e e e e 488<1526"'vB vB|vB #5<0vB !u|!45	vB
 !.vB "%,/vB  vB 
u|Xel3XeEL>Q5RR	SvB vB vB vB vB vB vB vBr4   r`   c                   2    e Zd ZdZ fdZdej        dedefdZ	 	 	 	 	 dd	ej        d
e	ej                 de	e
ej                          de	ej                 de	ej                 dede
ej        e	ej                 e	e
ej                          f         fdZ xZS )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                 b     t                      j        |i | t                       | _        d S r\   )r=   r>   r   _flash_attn_uses_top_left_mask)r?   argskwargsr@   s      r2   r>   zBartFlashAttention2.__init__*  s9    $)&)))
 3V2W2W.W+++r4   rq   rL   rK   c                 F    |                     ||| j        | j                  S r\   )rs   rb   rj   rv   s       r2   _reshapezBartFlashAttention2._reshape2  s    {{3GGGr4   NFrx   ry   rz   r{   r|   r}   r~   c           
      R   |rt          d          |d u}|                                \  }}	}
|                     |                     |          d|          }|r^|\|d         j        d         |j        d         k    r:|d                             dd          }|d                             dd          }ng|rV|                     |                     |          d|          }|                     |                     |          d|          }n||                     |                     |          d|          }|                     |                     |          d|          }t          j	        |d                             dd          |gd          }t          j	        |d                             dd          |gd          }nT|                     |                     |          d|          }|                     |                     |          d|          }| j
        r,|                    dd          |                    dd          f}|j        d         }|||d         j        d         z  }|j        }|t          j        k    rt          j                    rt          j                    }n3t          | j        d          r| j        j        }n| j        j        j        }t&                              d	| d
           |                    |          }|                    |          }|                    |          }t-          |||||	| j        r| j        nd| j        | j                  }|                    ||	d          }|                     |          }|sd }|||fS )Nz@BartFlashAttention2 attention does not support output_attentionsr+   r   r;   r"   r   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .r&   )rc   rf   use_top_left_mask)r/   r   r   ro   r-   rt   rm   rn   rE   r   rd   rC   float32is_autocast_enabledget_autocast_gpu_dtypehasattrrg   r   rH   loggerwarning_oncetor$   r   rc   rf   r   r   rp   )r?   rx   ry   rz   r{   r|   r}   r   rK   q_lenr   r   r   r   
kv_seq_leninput_dtypetarget_dtyper   r   s                      r2   rJ   zBartFlashAttention2.forward5  s     	a_``` .T9%**,,UA }}T[[%?%?SII 	N*q!'*.>.DQ.GGG (*44Q::J)!,66q!<<LL 	Nt{{3C'D'Db#NNJ==5E)F)FCPPLL't{{='A'A2sKKJ==])C)CRMMLN1$5$?$?1$E$Ez#RXYZZZJ 9nQ&7&A&A!Q&G&G%V\]^^^LL t{{='A'A2sKKJ==])C)CRMML? 	X )221a88,:P:PQRTU:V:VWN%b)
%.+1"55J #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.$(M:DLLsn"A	
 	
 	
 "))#ub99mmK00  	 LL.88r4   r   )rN   rO   rP   rQ   r>   rE   rS   rR   r   r   r   r   rJ   rT   rU   s   @r2   r   r   "  s;        X X X X XHu| Hc H H H H H 488<1526"'i9 i9|i9 #5<0i9 !u|!45	i9
 !.i9 "%,/i9  i9 
u|Xel3XeEL>Q5RR	Si9 i9 i9 i9 i9 i9 i9 i9r4   r   c                   
    e Zd Z	 	 	 	 	 ddej        deej                 deeej                          deej                 deej                 ded	eej        eej                 eeej                          f         f fd
Z xZ	S )BartSdpaAttentionNFrx   ry   rz   r{   r|   r}   r~   c                    |s|At                               d           t                                          ||||||          S |du}|                                \  }}	}
|                     |          }|r6|4|d         j        d         |j        d         k    r|d         }|d         }n>|rU|                     |                     |          d|          }|                     | 	                    |          d|          }n||                     |                     |          d|          }|                     | 	                    |          d|          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|          }|                     | 	                    |          d|          }| j        r||f}|                     ||	|          }| j        r
||	dk    rd	nd
}t          j        j                            ||||| j        r| j        nd|          }|                                || j        |	| j        fk    r5t+          d|| j        |	| j        f d|                                           |                    dd          }|                    ||	| j                  }|                     |          }|d|fS )r   Na  BartModel is using BartSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)ry   rz   r{   r|   r}   r   r;   r"   r+   r   TFr&   )	attn_mask	dropout_prf   r   r   )r   r   r=   rJ   r   ro   r-   rw   rm   rn   rE   r   rd   rf   r   r   scaled_dot_product_attentionr   rc   rb   rj   r/   rt   r   ra   rp   )r?   rx   ry   rz   r{   r|   r}   r   rK   r   r   r   r   r   rf   r   r@   s                   r2   rJ   zBartSdpaAttention.forward  sK     	 ;l   77??!1-- /"3 #    .T9',,..Wa {{=11 	L*q!'*.>.DQ.GGG (*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7N{{<#>>
 !N`~/E'TU++DD[`	 h)FF$&*m<dll G 
 
 #t~w!NNN)CRVR_3` ) )$$&&) )  
 "++Aq11 "))#wGGmmK00D.00r4   r   )
rN   rO   rP   rE   rS   r   r   r   rJ   rT   rU   s   @r2   r   r     s         488<1526"'f1 f1|f1 #5<0f1 !u|!45	f1
 !.f1 "%,/f1  f1 
u|Xel3XeEL>Q5RR	Sf1 f1 f1 f1 f1 f1 f1 f1 f1 f1r4   r   )eagersdpaflash_attention_2c                        e Zd Zdef fdZ	 d
dej        dej        dej        dee         de	ej        eej                 f         f
d	Z
 xZS )BartEncoderLayerrg   c                 *   t                                                       |j        | _        t	          |j                 | j        |j        |j        |          | _        t          j
        | j                  | _        |j        | _        t          |j                 | _        |j        | _        t          j        | j        |j                  | _        t          j        |j        | j                  | _        t          j
        | j                  | _        d S )N)ra   rb   rc   rg   )r=   r>   d_modelra   BART_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrc   r   activation_functionactivation_fnactivation_dropoutrl   encoder_ffn_dimfc1fc2final_layer_normr?   rg   r@   s     r2   r>   zBartEncoderLayer.__init__  s    /0KLn4,	
 
 
 %'L$@$@!~#F$>?"(";9T^V-CDD9V3T^DD "T^ < <r4   Frx   r{   r|   r}   r~   c                 |   |}|                      ||||          \  }}}t          j                            || j        | j                  }||z   }|                     |          }|}|                     |                     |                    }t          j                            || j        | j                  }| 	                    |          }t          j                            || j        | j                  }||z   }| 
                    |          }|j        t          j        k    rt          j        |                                          s&t          j        |                                          r9t          j        |j                  j        dz
  }t          j        || |          }|f}	|r|	|fz  }	|	S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )rx   r{   r|   r}   r   i  )minmax)r   r   r   rc   r   r   r   r   r   r   r   rC   rE   float16isinfanyisnanfinfor   clamp)
r?   rx   r{   r|   r}   residualr   r   clamp_valueoutputss
             r2   rJ   zBartEncoderLayer.forward%  s   $ !)-')+/	 *8 *
 *
&|Q --mt|VZVc-dd =011-@@ **488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0--m<<%-//K&&**,, 005M0J0J0N0N0P0P 0  +m&9::>EK!KK<[YYYM " 	'&Gr4   )F)rN   rO   rP   r#   r>   rE   FloatTensorr   r   r   rJ   rT   rU   s   @r2   r   r     s        =z = = = = = =. -20 0(0 )0 *	0
 $D>0 
u (5+<"==	>0 0 0 0 0 0 0 0r4   r   c                   b    e Zd Zdef fdZ	 	 	 	 	 	 	 	 ddej        deej                 deej                 d	eej                 d
eej                 deej                 deeej                          dee	         dee	         deej
        eeej
        ej
        f                  f         fdZ xZS )BartDecoderLayerrg   c                    t                                                       |j        | _        t	          |j                 | j        |j        |j        dd|          | _        |j	        | _	        t          |j                 | _        |j        | _        t          j        | j                  | _        t	          |j                 | j        |j        |j        d|          | _        t          j        | j                  | _        t          j        | j        |j                  | _        t          j        |j        | j                  | _        t          j        | j                  | _        d S )NT)ra   rb   rc   rd   rf   rg   )rc   rd   rg   )r=   r>   r   ra   r   r   decoder_attention_headsr   r   rc   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrl   decoder_ffn_dimr   r   r   r   s     r2   r>   zBartDecoderLayer.__init__Y  s*   /0KLn4,
 
 
 ~#F$>?"(";$&L$@$@!263NON*,
 
 
 (*|DN'C'C$9T^V-CDD9V3T^DD "T^ < <r4   NFTrx   r{   encoder_hidden_statesencoder_attention_maskr|   cross_attn_layer_head_maskrz   r}   	use_cacher~   c
                 x   |}
|
|dd         nd}|                      |||||          \  }}}t          j                            || j        | j                  }|
|z   }|                     |          }d}d}|z|}
|
|dd         nd}|                     ||||||          \  }}}t          j                            || j        | j                  }|
|z   }|                     |          }||z   }|}
|                     | 	                    |                    }t          j                            || j
        | j                  }|                     |          }t          j                            || j        | j                  }|
|z   }|                     |          }|f}|r|||fz  }|	r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size `(decoder_attention_heads,)`.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        Nr;   )rx   rz   r{   r|   r}   r   r   )rx   ry   r{   r|   rz   r}   )r   r   r   rc   r   r   r   r   r   r   r   r   r   )r?   rx   r{   r   r   r|   r   rz   r}   r   r   self_attn_past_key_valueself_attn_weightspresent_key_valuecross_attn_present_key_valuecross_attn_weightscross_attn_past_key_valuer   s                     r2   rJ   zBartDecoderLayer.forwardv  s,   < ! :H9S>"1"#5#5Y] >Bnn'3)+/ ?M ?
 ?
;(*; --mt|VZVc-dd =011-@@ (,$! ,$H @N?Yrss(;(;_c%NRN_N_+!65 :8"3 O` O OKM-/K M11-4<Z^Zg1hhM$}4M 88GGM !24P P !**488M+B+BCC--mt?Vaean-oo//--mt|VZVc-dd =0--m<< " 	?)+=>>G 	,)++Gr4   )NNNNNNFT)rN   rO   rP   r#   r>   rE   rS   r   r   r   r   rJ   rT   rU   s   @r2   r   r   X  sH       =z = = = = = =@ 268<9=26=A8<,1$(W W|W !.W  (5	W
 !) 6W "%,/W %-U\$:W !u|!45W $D>W D>W 
u (51BEDU1U+V"WW	XW W W W W W W Wr4   r   c                   X     e Zd ZdZdedededef fdZdej        dej        fd	Z	 xZ
S )
BartClassificationHeadz-Head for sentence-level classification tasks.	input_dim	inner_dimnum_classespooler_dropoutc                     t                                                       t          j        ||          | _        t          j        |          | _        t          j        ||          | _        d S )N)r   )r=   r>   r   rl   denseDropoutrc   rp   )r?   r   r   r   r   r@   s        r2   r>   zBartClassificationHead.__init__  sY     	Yy)44
zN333	)[99r4   rx   r~   c                     |                      |          }|                     |          }t          j        |          }|                      |          }|                     |          }|S r\   )rc   r   rE   tanhrp   )r?   rx   s     r2   rJ   zBartClassificationHead.forward  s[    ]33

=11
=11]33m44r4   )rN   rO   rP   rQ   rR   r^   r>   rE   rS   rJ   rT   rU   s   @r2   r   r     s        77
:
: 
: 	
:
 
: 
: 
: 
: 
: 
:U\ el        r4   r   c                   R    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ed	             Zd
S )BartPreTrainedModelmodelTzencoder.versionzdecoder.versionr   r   past_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr&   )meanstd)rg   init_std
isinstancer   rl   rH   datanormal_re   zero_	EmbeddingrY   )r?   moduler   s      r2   _init_weightsz!BartPreTrainedModel._init_weights  s    k"fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r4   c                     | j         j        }t          j        g ddddd|gg| j                  }|                    |          |d}|S )N)r      
      r;   r   r%      r;   rD   )r{   r'   )rg   r(   rE   rq   rD   ne)r?   	pad_tokenr'   dummy_inputss       r2   r  z BartPreTrainedModel.dummy_inputs  sa    K,	L"2"2"2Q2q)4L!MVZVabbb	'll955"
 
 r4   N)rN   rO   rP   r#   config_classbase_model_prefixsupports_gradient_checkpointing"_keys_to_ignore_on_load_unexpected_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpar  propertyr   r4   r2   r   r     sx        L&*#*;=N)O&,.AB"3!N	? 	? 	?   X  r4   r   c                       e Zd Zd ZdS )PretrainedBartModelc                 :    t          j        dt                     d S Nz_The class `PretrainedBartModel` has been depreciated, please use `BartPreTrainedModel` instead.warningswarnFutureWarningr?   s    r2   __init_subclass__z%PretrainedBartModel.__init_subclass__	  &    m	
 	
 	
 	
 	
r4   NrN   rO   rP   r%  r  r4   r2   r  r    #        
 
 
 
 
r4   r  c                       e Zd Zd ZdS )BartPretrainedModelc                 :    t          j        dt                     d S r  r   r$  s    r2   r%  z%BartPretrainedModel.__init_subclass__  r&  r4   Nr'  r  r4   r2   r*  r*    r(  r4   r*  aI  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`BartConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a!  
    Summarization example:

    ```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']
    ```
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

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

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

            [What are attention masks?](../glossary#attention-mask)
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

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

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

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

        decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:

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

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

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

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

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

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert `input_ids` indices into associated vectors
            than the model's internal embedding lookup matrix.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       e Zd ZdZddedeej                 f fdZd Z	d Z
	 	 	 	 	 	 	 ddej        d	eej                 d
eej                 deej                 dee         dee         dee         deeef         fdZ x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
    Nrg   embed_tokensc                    t                                                     j        | _        j        | _        j        }j        | _        j        | _	        j
        rt          j        |          nd}t          j        || j        |          | _        ||j        | j        _        t#          j        |          | _        t'          j        fdt+          j                  D                       | _        j        dk    | _        j        dk    | _        t'          j        |          | _        d| _        |                                  d S )NrX   rZ   c                 .    g | ]}t                    S r  )r   .0r   rg   s     r2   
<listcomp>z(BartEncoder.__init__.<locals>.<listcomp>  "    $d$d$d!%5f%=%=$d$d$dr4   r   r   F)r=   r>   rc   encoder_layerdrop	layerdropr   r(   rY   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtrW   
vocab_sizer.  rH   r6   embed_positionsr   
ModuleListrangeencoder_layerslayersr   _use_flash_attention_2	_use_sdpar   layernorm_embeddinggradient_checkpointing	post_init)r?   rg   r.  ra   rZ   r@   s    `   r2   r>   zBartEncoder.__init__  sB      ~1N	!.$*$B!.4.DMdi	***#3y$*:
 
 
 #'3':D$=* 
  
 m$d$d$d$duVMbGcGc$d$d$dee&,&AEX&X#4>#%<	#:#: &+#r4   c                     | j         S r\   r.  r$  s    r2   get_input_embeddingsz BartEncoder.get_input_embeddings        r4   c                     || _         d S r\   rI  r?   values     r2   set_input_embeddingsz BartEncoder.set_input_embeddings      !r4   r'   r{   	head_maskinputs_embedsr}   output_hidden_statesreturn_dictr~   c                    ||n| j         j        }||n| j         j        }||n| j         j        }||t	          d          |$|}|                    d|j        d                   }n!||dddddf         }nt	          d          ||                     |          }|                     |          }	|		                    |j
                  }	||	z   }
|                     |
          }
t          j                            |
| j        | j                  }
|F| j        r	d|v r|nd}n6| j        r||st%          ||j                  }nt)          ||j                  }|rdnd}|rdnd}|p|                                d         t-          | j                  k    r@t	          dt-          | j                   d	|                                d          d
          t1          | j                  D ]\  }}|r||
fz   }d}| j        r!t3          j        g           }|| j        k     rd}|rd}nX| j        r0| j        r)|                     |j        |
||||         nd|          }n ||
||||         nd|          }|d         }
|r||d         fz   }|r||
fz   }|st?          d |
||fD                       S tA          |
||          S )a~  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

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

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

            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzDYou cannot specify both input_ids and inputs_embeds at the same timer+   z5You have to specify either input_ids or inputs_embedsr   r   r  z&The head_mask should be specified for  layers, but it is for r   FT)NN)r|   r}   r"   c              3      K   | ]}||V  	d S r\   r  r3  vs     r2   	<genexpr>z&BartEncoder.forward.<locals>.<genexpr>k  s(      eeqWXWdWdWdWdWdeer4   last_hidden_staterx   
attentions)!rg   r}   rS  use_return_dictr/   rs   r-   r.  r>  r   rD   rE  r   r   rc   r   rC  rD  r   rC   r   r   lenrB  	enumeraterE   randr7  rF  _gradient_checkpointing_func__call__tupler   )r?   r'   r{   rQ  rR  r}   rS  rT  input	embed_posrx   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r2   rJ   zBartEncoder.forward  s   \ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]  ]%>cddd"E!r9?2+>??II&!!!!QQQ(+EETUUU  --i88M((//	LL!566	%	100??--mt|VZVc-dd %* 	a343F3FD aI$5>O$5 "E^UbUh!i!i "<NML_!`!`3=0:d  ~~"s4;'7'788 /S=M=M / /!((+/ / /  
 #,DK"8"8  	F  	FC# C!/=2B!BG} #&+jnn#&77"G 1 ,. 4= $($E$E%.%&+4+@3d)% %MM %2M%&;D;P3VZ*;	% % %M !.a 0  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r4   r\   )NNNNNNN)rN   rO   rP   rQ   r#   r   r   r  r>   rJ  rO  rE   
LongTensorrS   r   r   r   r   r   rJ   rT   rU   s   @r2   r-  r-    s=         z ",9O      >! ! !" " "
 '+15,059,0/3&*J
 J
#J
 !.J
 EL)	J

   12J
 $D>J
 'tnJ
 d^J
 
uo%	&J
 J
 J
 J
 J
 J
 J
 J
r4   r-  c                       e Zd ZdZddedeej                 f fdZd Z	d Z
	 	 	 	 	 	 	 	 	 	 	 	 ddej        d	eej                 d
eej                 deej                 deej                 deej                 deeej                          deej                 dee         dee         dee         dee         deeef         fdZ xZS )BartDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BartDecoderLayer`]

    Args:
        config: BartConfig
        embed_tokens (nn.Embedding): output embedding
    Nrg   r.  c                    t                                                     j        | _        j        | _        j        | _        j        | _        j	        rt          j        j                  nd}t          j        j        | j        |          | _        ||j        | j        _        t#          j        j                  | _        t'          j        fdt+          j                  D                       | _        j        dk    | _        j        dk    | _        t'          j        j                  | _        d| _        |                                  d S )NrX   r0  c                 .    g | ]}t                    S r  )r   r2  s     r2   r4  z(BartDecoder.__init__.<locals>.<listcomp>  r5  r4   r   r   F)r=   r>   rc   decoder_layerdropr7  r(   rY   r8  max_target_positionsr:  r;  r<  r   rW   r=  r.  rH   r6   r>  r   r?  r@  decoder_layersrB  r   rC  rD  r   rE  rF  rG  )r?   rg   r.  rZ   r@   s    `  r2   r>   zBartDecoder.__init__z  sC      ~1!.$*$B!393IRdi///s3v~t/?[
 
 
 #'3':D$=*N 
  
 m$d$d$d$duVMbGcGc$d$d$dee&,&AEX&X#4>#%<#?#? &+#r4   c                     | j         S r\   rI  r$  s    r2   rJ  z BartDecoder.get_input_embeddings  rK  r4   c                     || _         d S r\   rI  rM  s     r2   rO  z BartDecoder.set_input_embeddings  rP  r4   r'   r{   r   r   rQ  cross_attn_head_maskr   rR  r   r}   rS  rT  r~   c                    |
|
n| j         j        }
||n| j         j        }|	|	n| j         j        }	||n| j         j        }||t          d          |&|}|j        }|                    d|d                   }n=|,|                                dd         }|dddddf         }nt          d          ||d         d         j        d         nd}|| 	                    |          }| j
        r|d|v r|nd}n0| j        r|
s|t          ||||          }nt          ||||          }|X|V| j
        r	d|v r|nd}nF| j        r"| |
st          ||j        |d                   }nt!          ||j        |d                   }|                     ||          }|                    |j                  }||z   }|                     |          }t*          j                            || j        | j                  }| j        r%| j        r|	rt4                              d	           d
}	|rdnd}|
rdnd}|
r|dnd}|	rdnd}t9          ||gddg          D ]z\  }}|s|                                d         t;          | j                  k    rCt          d| dt;          | j                   d|                                d          d          {t?          | j                  D ]\  }}|r||fz  }| j        r tA          j!        g           }|| j"        k     r4|||         nd}| j        r?| j        r8| #                    |j$        |||||||         nd|||         ndd|
|	
  
        }n( ||||||||         nd|||         nd||
|		  	        }|d         }|	r|||
rdnd         fz  }|
r||d         fz  }|||d         fz  }|r||fz  }|	r|nd}|stK          d |||||fD                       S tM          |||||          S )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

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

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

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

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

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

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

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

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

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer+   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r;   )r   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr  rQ  rx  zThe `z` should be specified for rV  r   )r{   r   r   r|   r   rz   r}   r   r   r"   c              3      K   | ]}||V  	d S r\   r  rX  s     r2   rZ  z&BartDecoder.forward.<locals>.<genexpr>  s0        =  === r4   )r\  r   rx   r]  cross_attentions)'rg   r}   rS  r   r^  r/   r-   rs   r   r.  rC  rD  r   r   r   rC   r   r>  r   rD   rE  r   r   rc   r   rF  r   r   zipr_  rB  r`  rE   ra  r7  rb  rc  rd  r   )r?   r'   r{   r   r   rQ  rx  r   rR  r   r}   rS  rT  re  input_shaperA   rM   rx   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cacher   	mask_nameri  decoder_layerrl  rz   rm  
next_caches                                 r2   rJ   zBartDecoder.forward  s   ` 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]  ]%>sttt"E+K!r;r?;;II&',,..ss3K!!!!QQQ(+EEdeee DSC^!3A!6!<Q!?!?de  --e44M& 	0>0JqTbObOb^^imNN^ 	$5 	:N:V H&	 NN ?]<R N
 !,1G1S* CDH^C^C^)?)?dh&& $8$@IZ$@ *M*!''O* * *&& *D*M,?UW* * *&
 ((0FGG	LL!566	%	100??--mt|VZVc-dd& 	"4= 	" "##p   "	 #7@BBD0:d&7h<Q<]rrdh#,6RR$ %(4H(IKYoKp$q$q 	 	 Iy$>>##A&3t{+;+;<<$3	 3 3SEUEU 3 3%NN,,Q/3 3 3  
 #,DK"8"8 /	@ /	@C# 6!m%55!} &+jnn#&775D5P_S11VZN* t}  $ A A!*!")*&/&;IcNN1E1Q(--W[%! ! !.!#1*?+A7@7LYs^^RV5I5U,S11[_#1&7'! ! ! *!,M V"}:K5RQQQR'S&UU"  @=#3"55(4(]1-=,??(   	2-!11+4>''$
 	  '5FXlm     
 9+&+%1
 
 
 	
r4   r\   )NNNNNNNNNNNN)rN   rO   rP   rQ   r#   r   r   r  r>   rJ  rO  rE   rn  rS   r   r   r   r   r   r   rJ   rT   rU   s   @r2   rp  rp  q  s         z ",9O      :! ! !" " "
 '+15=A=A,07;=A59$(,0/3&*p
 p
#p
 !.p
  ((9:	p

 !))9 :p
 EL)p
 'u|4p
 "$u'8"9:p
   12p
 D>p
 $D>p
 'tnp
 d^p
 
u??	@p
 p
 p
 p
 p
 p
 p
 p
r4   rp  zRThe bare BART Model outputting raw hidden-states without any specific head on top.c            %       <    e Zd ZddgZdef fdZd Zd Zd Zd Z	d	 Z
 ee           eeeee
          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 deej                 deej                 deeej                          deeej                          deej                 deej                 dee         dee         dee         dee         deeef         f d                        Z xZS )	BartModelencoder.embed_tokens.weightdecoder.embed_tokens.weightrg   c                 t   t                                          |           |j        |j        }}|j        rt          j        |j                  nd}t          ||j        ||          | _	        t          || j	                  | _        t          || j	                  | _        |                                  d S )NrX   r0  )r=   r>   r(   r=  r:  r;  r<  r   rW   sharedr-  encoderrp  decoderrG  )r?   rg   rY   r=  rZ   r@   s        r2   r>   zBartModel.__init__  s       "("5v7HZ393IRdi///s-j&.+cnooo"64;77"64;77 	r4   c                     | j         j        rL|                     | j        j        | j                   |                     | j        j        | j                   d S d S r\   )rg   tie_word_embeddings_tie_or_clone_weightsr  r.  r  r  r$  s    r2   _tie_weightszBartModel._tie_weights  s\    ;* 	O&&t|'@$+NNN&&t|'@$+NNNNN	O 	Or4   c                     | j         S r\   )r  r$  s    r2   rJ  zBartModel.get_input_embeddings  s
    {r4   c                 X    || _         | j         | j        _        | j         | j        _        d S r\   )r  r  r.  r  rM  s     r2   rO  zBartModel.set_input_embeddings  s'    $(K!$(K!!!r4   c                     | j         S r\   )r  r$  s    r2   get_encoderzBartModel.get_encoder  
    |r4   c                     | j         S r\   r  r$  s    r2   get_decoderzBartModel.get_decoder  r  r4   )
checkpointoutput_typer  expected_outputNr'   r{   decoder_input_idsdecoder_attention_maskrQ  decoder_head_maskrx  encoder_outputsr   rR  decoder_inputs_embedsr   r}   rS  rT  r~   c                    |8|6|t          d          t          || j        j        | j        j                  }||n| j        j        }||n| j        j        }||n| j        j        }||n| j        j        }|| 	                    ||||
|||          }ne|rct          |t                    sNt          |d         t          |          dk    r|d         nd t          |          dk    r|d         nd           }|                     |||d         ||||	|||||          }|s||z   S t          |j        |j        |j        |j        |j        |j        |j        |j                  S )	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'   r{   rQ  rR  r}   rS  rT  r   r"   r;   r[  r'   r{   r   r   rQ  rx  r   rR  r   r}   rS  rT  )r\  r   decoder_hidden_statesdecoder_attentionsr{  encoder_last_hidden_stater   encoder_attentions)r/   r3   rg   r(   r)   r}   rS  r   r^  r  r  r   r_  r  r   r\  r   rx   r]  r{  )r?   r'   r{   r  r  rQ  r  rx  r  r   rR  r  r   r}   rS  rT  decoder_outputss                    r2   rJ   zBartModel.forward  s   6 $)>)F  U   !34;3T[5W! ! 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]""ll#-#+"3%9' +  OO  	O_!M!M 	-"1!"4474H4H14L4Loa00RV14_1E1E1I1I?1--t  O ,,'1"1!"4#1'!5+//!5# ' 
 
  	5"_44!-?+;"1"?.9,=&5&G"1"?.9	
 	
 	
 		
r4   NNNNNNNNNNNNNNN)rN   rO   rP   _tied_weights_keysr#   r>   r  rJ  rO  r  r  r   BART_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPErE   rn  r   rS   r   r   r   r   r   rJ   rT   rU   s   @r2   r  r    sX       
 89VWz      O O O
  0 0 0
     +*+@AA&&$.	   '+158<=A,0487;=A=A59=A$(,0/3&*!U
 U
#U
 !.U
 $E$45	U

 !))9 :U
 EL)U
 $EL1U
 'u|4U
 "$u'8"9:U
 "$u'8"9:U
   12U
  ((9:U
 D>U
 $D>U
 'tnU
  d^!U
" 
u((	)#U
 U
 U
  BAU
 U
 U
 U
 U
r4   r  zLThe BART Model with a language modeling head. Can be used for summarization.c            (           e Zd ZdZg dZdgZdef fdZd Zd Z	d$d	e
d
ee
         dej        f fdZd	e
ddfdZd Zd Z ee           eee           ee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%dej        deej                 deej                 deej                 deej                 deej                 deej                 deeej                          deeej                          deej                 deej                 deej                 dee         dee         dee         d ee         dee ef         f"d!                                    Z!dej        fd"Z"e#d#             Z$ xZ%S )&BartForConditionalGenerationr   )r  r  lm_head.weightfinal_logits_biasrg   c                 l   t                                          |           t          |          | _        |                     dt          j        d| j        j        j        f                     t          j
        |j        | j        j        j        d          | _        |                                  d S )Nr  r"   Fri   )r=   r>   r  r   register_bufferrE   zerosr  r7   r   rl   r   lm_headrG  r   s     r2   r>   z%BartForConditionalGeneration.__init__  s       v&&
0%+q$*BSBb>c2d2deeey1B1QX]^^^ 	r4   c                 4    | j                                         S r\   )r   r  r$  s    r2   r  z(BartForConditionalGeneration.get_encoder'      z%%'''r4   c                 4    | j                                         S r\   )r   r  r$  s    r2   r  z(BartForConditionalGeneration.get_decoder*  r  r4   Nnew_num_tokenspad_to_multiple_ofr~   c                     t                                          ||          }|                     |j        j        d                    |S )Nr   )r=   resize_token_embeddings_resize_final_logits_biasrH   r-   )r?   r  r  new_embeddingsr@   s       r2   r  z4BartForConditionalGeneration.resize_token_embeddings-  sB    88I[\\&&~'<'B1'EFFFr4   c                    | j         j        d         }||k    r| j         d d d |f         }nBt          j        d||z
  f| j         j                  }t          j        | j         |gd          }|                     d|           d S )Nr+   r"   r  r   r  )r  r-   rE   r  rD   r   r  )r?   r  old_num_tokensnew_bias
extra_biass        r2   r  z6BartForConditionalGeneration._resize_final_logits_bias2  s    /5b9^++-aaa..@AHHa.)H%IRVRhRopppJy$"8*!E1MMMH0(;;;;;r4   c                     | j         S r\   r  r$  s    r2   get_output_embeddingsz2BartForConditionalGeneration.get_output_embeddings;  r  r4   c                     || _         d S r\   r  r?   r  s     r2   set_output_embeddingsz2BartForConditionalGeneration.set_output_embeddings>      %r4   r  r  r'   r{   r  r  rQ  r  rx  r  r   rR  r  labelsr   r}   rS  rT  c                    ||n| j         j        }|G|rt                              d           d}|'|%t	          || j         j        | j         j                  }|                     |||||||||	|
|||||          }|                     |d                   }|| j	        
                    |j                  z   }d}|e|
                    |j                  }t                      } ||                    d| j         j                  |                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j        |j        |j        |j        	  	        S )	a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:
        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r{   r  r  r  rQ  r  rx  r   rR  r  r   r}   rS  rT  r   r+   r"   	losslogitsr   r  r  r{  r  r   r  )rg   r^  r   warningr3   r(   r)   r   r  r  r   rD   r	   rs   r=  r   r   r  r  r{  r  r   r  )r?   r'   r{   r  r  rQ  r  rx  r  r   rR  r  r  r   r}   rS  rT  r   	lm_logitsmasked_lm_lossloss_fctoutputs                         r2   rJ   z$BartForConditionalGeneration.forwardA  s   < &1%<kk$+B] mklllI (-B-J$6DK4dk6X% %! **)/+#9/!5+'"7/!5#  
 
$ LL,,	 6 9 9):J K KK	YYy/00F'))H%XinnR9O&P&PRXR]R]^`RaRabbN 	Z\GABBK/F3A3M^%..SYY#3")"?&9$5&-&G")"?&9

 

 

 
	
r4   c                 L    t          || j        j        | j        j                  S r\   )r3   rg   r(   r)   )r?   r  s     r2   %prepare_decoder_input_ids_from_labelszBBartForConditionalGeneration.prepare_decoder_input_ids_from_labels  s    !&$+*BDKDfgggr4   c                 z    d}| D ]4}|t          fd|d d         D                       |dd          z   fz  }5|S )Nr  c              3   t   K   | ]2}|                     d                     |j                            V  3dS r   Nindex_selectr   rD   r3  
past_statebeam_idxs     r2   rZ  z>BartForConditionalGeneration._reorder_cache.<locals>.<genexpr>  sC      rrU_j--aZ=N1O1OPPrrrrrrr4   r;   rd  r   r  reordered_past
layer_pasts    `  r2   _reorder_cachez+BartForConditionalGeneration._reorder_cache  sm    ) 	 	JrrrrcmnpopnpcqrrrrrQRR.! NN r4   r\   NNNNNNNNNNNNNNNN)&rN   rO   rP   r  r  _keys_to_ignore_on_load_missingr#   r>   r  r  rR   r   r   r  r  r  r  r  r   r  r!   r   r  r   BART_GENERATION_EXAMPLErE   rn  rS   r   r   r   r   r   rJ   r  staticmethodr  rT   rU   s   @r2   r  r    s         iii':&;#z      ( ( (( ( ( c xX[} hjht      
< < < < < <  & & & +*+@AA?YYY/00 '+158<=A,0487;=A=A59=A-1$(,0/3&*#O
 O
#O
 !.O
 $E$45	O

 !))9 :O
 EL)O
 $EL1O
 'u|4O
 "$u'8"9:O
 "$u'8"9:O
   12O
  ((9:O
 )*O
 D>O
 $D>O
  'tn!O
" d^#O
$ 
uo%	&%O
 O
 O
 10 ZY BAO
bhEL h h h h   \    r4   r  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            %           e Zd ZddgZdef fdZ ee           ee	e
eee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 d	eej                 d
eej                 deej                 deej                 deej                 deeej                          deej                 deej                 deej                 dee         dee         dee         dee         deee
f         f d                        Z xZS )BartForSequenceClassificationr  r  rg   c                      t                      j        |fi | t          |          | _        t	          |j        |j        |j        |j                  | _        | 	                                 d S r\   )
r=   r>   r  r   r   r   
num_labelsclassifier_dropoutclassification_headrG  )r?   rg   r   r@   s      r2   r>   z&BartForSequenceClassification.__init__  sq    **6***v&&
#9NN%	$
 $
  	r4   )r  r  r  r  expected_lossNr'   r{   r  r  rQ  r  rx  r  rR  r  r  r   r}   rS  rT  r~   c                 R   ||n| j         j        }|d}||	t          d| j        j                   |                     |||||||||	|
||||          }|d         }|                    | j         j                                      |j	                  }t          t          j        |                    d                              dk    rt          d          ||ddf                             |                    d          d|                    d                    dddddf         }|                     |          }d}||                    |j	                  }| j         j        p| j         j        dk    rd	| j         _        nS| j         j        dk    r7|j        t          j        k    s|j        t          j        k    rd
| j         _        nd| j         _        | j         j        d	k    r\t/                      }| j         j        dk    r1 ||                                |                                          }n |||          }n| j         j        d
k    rLt3                      } ||                    d| j         j                  |                    d                    }n*| j         j        dk    rt5                      } |||          }|s|f|dd         z   }||f|z   n|S t7          |||j        |j        |j        |j        |j         |j!        |j"        	  	        S )a3  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NFz8Passing input embeddings is currently not supported for r{   r  r  rQ  r  rx  r  rR  r  r   r}   rS  rT  r   r"   z7All examples must have the same number of <eos> tokens.r+   
regressionsingle_label_classificationmulti_label_classificationr  )#rg   r^  NotImplementedErrorr@   rN   r   eqeos_token_idr   rD   r_  rE   unique_consecutivesumr/   rs   r   r  problem_typer  rC   rG   rR   r
   squeezer	   r   r   r   r  r  r{  r  r   r  )r?   r'   r{   r  r  rQ  r  rx  r  rR  r  r  r   r}   rS  rT  r   rx   eos_masksentence_representationr  r  r  r  s                           r2   rJ   z%BartForSequenceClassification.forward  sR   > &1%<kk$+B]I!:%d4>Kbdd   **)/#9/!5+'"7/!5#  
 
   
<< 899<<]=QRRu'Q8899A==VWWW"/!!!"<"A"A-BTBTUVBWBWY[]j]o]opr]s]s"t"tAAr111H#
 ))*ABBYYv}--F{'/;)Q../;DK,,[+a//V\UZ5O5OSYS_chclSlSl/LDK,,/KDK,{'<77"99;)Q..#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB0F G GUWYY)-III,..x// 	FY,F)-)9TGf$$vE.#3")"?&9$5&-&G")"?&9

 

 

 
	
r4   r  )rN   rO   rP   r  r#   r>   r   r  r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSrE   rn  r   rS   r   r   r   r   r   rJ   rT   rU   s   @r2   r  r    s        89VWz       +*+@AA:3$2.   '+158<=A,0487;=A59=A-1$(,0/3&*!`
 `
#`
 !.`
 $E$45	`

 !))9 :`
 EL)`
 $EL1`
 'u|4`
 "$u'8"9:`
   12`
  ((9:`
 )*`
 D>`
 $D>`
 'tn`
  d^!`
" 
u55	6#`
 `
 `
  BA`
 `
 `
 `
 `
r4   r  z
    BART Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c            '       *    e Zd ZddgZ fdZ ee           eee	e
ee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 d	eej                 d
eej                 deej                 deej                 deeej                          deej                 deej                 deej                 deej                 dee         dee         dee         dee         deee	f         f"d                        Z xZS )BartForQuestionAnsweringr  r  c                    t                                          |           d|_        |j        | _        t          |          | _        t          j        |j        |j                  | _        | 	                                 d S r:   )
r=   r>   r  r  r   r   rl   hidden_size
qa_outputsrG  r   s     r2   r>   z!BartForQuestionAnswering.__init__0  sm        +v&&
)F$68IJJ 	r4   )r  r  r  r  r  Nr'   r{   r  r  rQ  r  rx  r  start_positionsend_positionsrR  r  r   r}   rS  rT  r~   c                    ||n| j         j        }|	|
d}|                     ||||||||||||||          }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}|	|
t          |	                                          dk    r|	                    d          }	t          |
                                          dk    r|
                    d          }
|                    d          }|		                    d|          }	|
	                    d|          }
t          |          } |||	          } |||
          }||z   d	z  }|s||f|dd         z   }||f|z   n|S t          ||||j        |j        |j        |j        |j        |j        |j        

  
        S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        NFr  r   r"   r+   r   )ignore_indexr;   )
r  start_logits
end_logitsr   r  r  r{  r  r   r  )rg   r^  r   r  splitr  ru   r_  r   r   r	   r   r   r  r  r{  r  r   r  )r?   r'   r{   r  r  rQ  r  rx  r  r  r  rR  r  r   r}   rS  rT  r   sequence_outputr  r	  r
  
total_lossignored_indexr  
start_lossend_lossr  s                               r2   rJ   z BartForQuestionAnswering.forward<  s[   J &1%<kk$+B]&=+DI**)/#9/!5+'"7/!5#  
 
" "!*11#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEO)//=AAM']CCCH!,@@Jx
M::H$x/14J 	R F 0:/EZMF**6Q2%!#3")"?&9$5&-&G")"?&9
 
 
 	
r4   r  )rN   rO   rP   r  r>   r   r  r   _CHECKPOINT_FOR_QAr   r  _QA_EXPECTED_LOSS_QA_EXPECTED_OUTPUTrE   rS   r   rn  r   r   r   r   r   rJ   rT   rU   s   @r2   r  r  &  s        89VW
 
 
 
 
 +*+@AA%7$'+   #'158<=A,0487;=A6:4859=A$(,0/3&*#\
 \
<\
 !.\
 $E$45	\

 !))9 :\
 EL)\
 $EL1\
 'u|4\
 "$u'8"9:\
 "%"23\
   01\
   12\
  ((9:\
 D>\
 $D>\
  'tn!\
" d^#\
$ 
u99	:%\
 \
 \
  BA\
 \
 \
 \
 \
r4   r  c                   (     e Zd ZdZ fdZd Z x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                 r    t                                          |           t          |          | _        d S r\   )r=   r>   rp  r  r   s     r2   r>   zBartDecoderWrapper.__init__  s.       "6**r4   c                      | j         |i |S r\   r  )r?   r   r   s      r2   rJ   zBartDecoderWrapper.forward  s    t|T,V,,,r4   )rN   rO   rP   rQ   r>   rJ   rT   rU   s   @r2   r  r    sQ         
+ + + + +- - - - - - -r4   r  zu
    BART decoder with a language modeling head on top (linear layer with weights tied to the input embeddings).
    c                        e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 eee	          	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 deej                 deeej                          deej                 deej                 dee         dee         dee         dee         deeef         fd            Zed             Z xZS )BartForCausalLMr  c                 *   t          j        |          }d|_        d|_        t	                                          |           t          |          | _        t          j	        |j
        |j        d          | _        |                                  d S )NTFri   )copydeepcopyrd   is_encoder_decoderr=   r>   r  r   r   rl   r  r=  r  rG  r   s     r2   r>   zBartForCausalLM.__init__  s    v&& $)!   '//
y!3V5FUSSS 	r4   c                 $    | j         j        j        S r\   r   r  r.  r$  s    r2   rJ  z$BartForCausalLM.get_input_embeddings  s    z!..r4   c                 (    || j         j        _        d S r\   r  rM  s     r2   rO  z$BartForCausalLM.set_input_embeddings  s    */
'''r4   c                     | j         S r\   r  r$  s    r2   r  z%BartForCausalLM.get_output_embeddings  r  r4   c                     || _         d S r\   r  r  s     r2   r  z%BartForCausalLM.set_output_embeddings  r  r4   c                     || j         _        d S r\   r   r  )r?   r  s     r2   set_decoderzBartForCausalLM.set_decoder  s    $
r4   c                     | j         j        S r\   r$  r$  s    r2   r  zBartForCausalLM.get_decoder  s    z!!r4   r  Nr'   r{   r   r   rQ  rx  r   rR  r  r   r}   rS  rT  r~   c                 <   ||n| j         j        }||n| j         j        }||n| j         j        }| j                            |||||||||
|||          }|                     |d                   }d}|	e|	                    |j                  }	t                      } ||
                    d| j         j                  |	
                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j                  S )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                if the model is configured as a decoder.
            encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
                in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

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

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

            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

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

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, 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
        ```Nr  r   r+   r"   )r  r  r   rx   r]  r{  )rg   r}   rS  r^  r   r  r  r   rD   r	   rs   r=  r   r   rx   r]  r{  )r?   r'   r{   r   r   rQ  rx  r   rR  r  r   r}   rS  rT  r   r  r  r  r  s                      r2   rJ   zBartForCausalLM.forward  se   L 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] *$$)"7#9!5+'/!5# % 
 
 gaj))YYv}--F'))H8FKKDK,BCCV[[QS__UUD 	DY,F'+'7D7V##VC0#3!/)$5
 
 
 	
r4   c                 T    d}| D ]!}|t          fd|D                       fz  }"|S )Nr  c              3   t   K   | ]2}|                     d                     |j                            V  3dS r  r  r  s     r2   rZ  z1BartForCausalLM._reorder_cache.<locals>.<genexpr>n  sC      nnU_j--aZ=N1O1OPPnnnnnnr4   r  r  s    `  r2   r  zBartForCausalLM._reorder_cachei  sQ    ) 	 	Jnnnncmnnnnn NN r4   )NNNNNNNNNNNNN)rN   rO   rP   r  r>   rJ  rO  r  r  r%  r  r!   r   r  rE   rn  r   rS   r   r   r   r   r   rJ   r  r  rT   rU   s   @r2   r  r    s        ++
 
 
 
 
/ / /0 0 0  & & &% % %" " " +L[jkkk '+15=A>B,07;=A59-1$(,0/3&*N
 N
#N
 !.N
  ((9:	N

 !)): ;N
 EL)N
 'u|4N
 "$u'8"9:N
   12N
 )*N
 D>N
 $D>N
 'tnN
 d^N
 
u77	8N
 N
 N
 lkN
`   \    r4   r  )XrQ   r  r;  r!  typingr   r   r   r   rE   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   
generationr   modeling_attn_mask_utilsr   r   r   r   modeling_outputsr   r   r   r   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r    r!   configuration_bartr#   modeling_flash_attention_utilsr$   
get_loggerrN   r   r  r  r  r  r  r  r  r  r  rS   rR   r3   r  r6   rW   Moduler`   r   r   r   r   r   r   r   r  r*  BART_START_DOCSTRINGr  r  r-  rp  r  r  r  r  r  r  r  r4   r2   <module>r8     s        / / / / / / / / / / / /            A A A A A A A A A A ! ! ! ! ! ! ) ) ) ) ) )                             . - - - - -	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 + * * * * *  KJJJJJJ 
	H	%	%*  %  +E ' )  =  & %, c [^     8 8 8 8 8R\ 8 8 8,
= 
= 
= 
= 
=bl 
= 
= 
=[B [B [B [B [BBI [B [B [B||9 |9 |9 |9 |9- |9 |9 |9~g1 g1 g1 g1 g1 g1 g1 g1V ,  C C C C Cry C C CLu u u u ury u u up    RY   0    /   @
 
 
 
 
- 
 
 

 
 
 
 
- 
 
 
  ) V_ Dy
 y
 y
 y
 y
% y
 y
 y
x\
 \
 \
 \
 \
% \
 \
 \
~ X 
 
 
 
 
# 
 
	 
D RTh H H H H H#6 H H HV   x
 x
 x
 x
 x
$7 x
 x
 x
v   s
 s
 s
 s
 s
2 s
 s
 s
l- - - - -, - - -  	 y y y y y)? y y y y yr4   