
    fTh                    0   S r SSKrSSKrSSKrSSKJrJrJrJr  SSK	r	SSK
r	SSK	Jr  SSKJrJrJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJrJr  SSKJrJ r J!r!J"r"J#r#J$r$J%r%  SSK&J'r'  SSK(J)r)J*r*J+r+J,r,  SSK-J.r.  \*" 5       (       a  SSK/J0r0  SSK1J2r2  \" 5       (       a  SSKJ3r3  \,Rh                  " \55      r6S\	Rn                  S\8S\84S jr9 " S S\Rt                  5      r; " S S\Rt                  5      r< " S S\Rz                  5      r> " S S\>5      r? " S  S!\>5      r@\>\@\?S".rA " S# S$\Rz                  5      rB " S% S&\Rz                  5      rC " S' S(\Rz                  5      rD\) " S) S*\'5      5       rE " S+ S,\E5      rF " S- S.\E5      rG " S/ S0\E5      rH " S1 S2\E5      rI\) " S3 S4\E5      5       rJ\)" S5S69 " S7 S8\E\5      5       rK\)" S9S69 " S: S;\E5      5       rL\) " S< S=\E5      5       rM " S> S?\E5      rN\)" S@S69 " SA SB\E\5      5       rO/ SCQrPg)DzPyTorch BART model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )
BartConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forward	input_idspad_token_iddecoder_start_token_idc                     U R                  U R                  5      nU SS2SS24   R                  5       USS2SS24'   X#SS2S4'   Uc  [        S5      eUR	                  US:H  U5        U$ )z)
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       ^/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/bart/modeling_bart.pyshift_tokens_rightr2   D   sz     "++IOO<(CRC0668ae4adLMM""#4#<lK    c                      ^  \ rS rSrSrS\S\4U 4S jjrSS\R                  S\S\R                  4U 4S	 jjjr	S
r
U =r$ )BartLearnedPositionalEmbeddingT   zF
This module learns positional embeddings up to a fixed maximum size.
num_embeddingsembedding_dimc                 L   > SU l         [        TU ]	  XR                   -   U5        g N   )offsetsuper__init__)selfr7   r8   	__class__s      r1   r>   'BartLearnedPositionalEmbedding.__init__Y   s"     ++5}Er3   r&   past_key_values_lengthposition_idsc                   > Uc]  UR                   SS u  pE[        R                  " X"U-   [        R                  U R                  R
                  S9R                  US5      nOUR                  S5      n[        TU ]%  X0R                  -   5      $ )z3`input_ids' shape is expected to be [bsz x seqlen].Nr;   )dtypedevicer*   r   )r,   torcharangelongweightrF   expand	unsqueezer=   forwardr<   )r?   r&   rB   rC   bszseq_lenr@   s         r1   rM   &BartLearnedPositionalEmbedding.forward_   s     $??2A.LC <<&(HPUPZPZcgcncncucufS"o  (11!4Lw|kk9::r3   )r<   r   N)__name__
__module____qualname____firstlineno____doc__intr>   rG   TensorrM   __static_attributes____classcell__r@   s   @r1   r5   r5   T   sH    Fs F3 F; ;s ;^c^j^j ; ;r3   r5   c            
       r   ^  \ rS rSrSrSS\S\S\S\\   4U 4S jjjrS\	R                  4U 4S	 jjrS
rU =r$ )BartScaledWordEmbeddingm   zT
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
r7   r8   padding_idxembed_scalec                 2   > [         TU ]  XU5        X@l        g N)r=   r>   r`   )r?   r7   r8   r_   r`   r@   s        r1   r>    BartScaledWordEmbedding.__init__r   s    D&r3   r&   c                 <   > [         TU ]  U5      U R                  -  $ rb   )r=   rM   r`   )r?   r&   r@   s     r1   rM   BartScaledWordEmbedding.forwardv   s    wy)D,<,<<<r3   r`   )      ?)rR   rS   rT   rU   rV   rW   r   floatr>   rG   rX   rM   rY   rZ   r[   s   @r1   r]   r]   m   sJ    's '3 'S '_ghm_n ' '= = =r3   r]   c                     ^  \ rS rSrSr      SS\S\S\S\S\S\S	\\	   S
\\   4U 4S jjjr
      SS\R                  S\\R                     S\\   S\\R                     S\\R                     S\S\\R                     S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )BartAttentionz   z=Multi-headed attention from 'Attention Is All You Need' paper	embed_dim	num_headsdropout
is_decoderbias	is_causalconfig	layer_idxc	                 t  > [         T	U ]  5         Xl        X l        X0l        X-  U l        Xpl        U R
                  U-  U R                  :w  a  [        SU R                   SU S35      eU R
                  S-  U l        X@l	        X`l
        Xl        Uc>  U R                  (       a-  [        R                  SU R                  R                   S35        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        g )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.rp   )r=   r>   rl   rm   rn   head_dimrr   r.   scalingro   rq   rs   loggerwarning_oncer@   rR   r   Lineark_projv_projq_projout_proj)
r?   rl   rm   rn   ro   rp   rq   rr   rs   r@   s
            r1   r>   BartAttention.__init__}   s    	""!.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	4@ii	4@ii	4@		)TBr3   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionreturnc                 
   USLnUR                  5       u  pnU R                  U5      R                  U	SU R                  U R                  5      R                  SS5      nXR                  -  nUb]  [        U[        5      (       aF  UR                  R                  U R                  5      nU(       a  UR                  nOUR                  nOUnU(       a  UOUnU(       a=  Ub:  W(       a3  WR                  U R                     nUR                  U R                     nOU R!                  U5      nU R#                  U5      nUR                  U	SU R                  U R                  5      R                  SS5      nUR                  U	SU R                  U R                  5      R                  SS5      nUbN  U(       d  UOSnWR%                  UUU R                  SU05      u  nnU(       a  SUR                  U R                  '   XR                  -  SU R                  4nUR&                  " U6 nUR&                  " U6 nUR&                  " U6 nUR                  S5      n[(        R*                  " UUR                  SS5      5      nUR                  5       XR                  -  U
U4:w  a.  [-        SXR                  -  U
U4 SUR                  5        35      eUb]  USS2SS2SS2SUR.                  S	   24   nUR                  XR                  U
U5      U-   nUR                  XR                  -  U
U5      n[0        R2                  R5                  USS
9nUb  UR                  5       U R                  4:w  a*  [-        SU R                  4 SUR                  5        35      eUR                  SSSS5      UR                  XR                  U
U5      -  nUR                  XR                  -  U
U5      nU(       a=  UR                  XR                  U
U5      nUR                  XR                  -  U
U5      nOSn[0        R2                  R7                  UU R6                  U R8                  S9n[(        R*                  " UU5      nUR                  5       XR                  -  XR                  4:w  a7  [-        SXR                  -  XR                  4 SUR                  5        35      eUR                  XR                  XR                  5      nUR                  SS5      nUR'                  XU R:                  5      nU R=                  U5      nUUU4$ )#Input shape: Batch x Time x ChannelNr*   r!   r;   r   Tz$Attention weights should be of size z	, but is dimz/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizer}   viewrm   rv   	transposerw   
isinstancer   
is_updatedgetrs   cross_attention_cacheself_attention_cache	key_cachevalue_cacher{   r|   updatereshaperG   bmmr.   r,   r   
functionalsoftmaxrn   r   rl   r~   )r?   r   r   r   r   r   r   r   is_cross_attentionrN   tgt_len_query_statesr   curr_past_key_valuecurrent_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                           r1   rM   BartAttention.forward   s    .T9',,.a {{=166sBPTP]P]^hhijlmn#ll2%.*=>>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,66t~~FJ.::4>>JL^4J;;~6L#b$..$--PZZ[\^_`J',,S"dnndmmT^^_`bcdL)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=NN*B>
#++Z8''4
#++Z8//!$yyz/C/CAq/IJ3#7'"JJ6nn8LgW^7_6` a %%'(* 
 %+Aq!5Kz7G7G7K5K,KLN',,S..'7SVddL',,S>>-A7GTL}},,\r,B&##%$..):: Et~~FWEX Y',,./1  +//2q!<|?P?PQTVdVdfmov?wwL',,S>>-A7GTL
 %1$5$5c>>7T[$\!055cNN6JGU\]L$(!]]**<4<<RVR_R_*`
ii
L9#"6!OO2C..4H'S`S`3a2b c$$&') 
 "&&sNNG]]S!++Aq1 "))#GmmK01>AAr3   )rr   rn   rl   rv   rq   ro   r{   rs   rm   r~   r}   rw   r|   )        FTFNNNNNNFN)rR   rS   rT   rU   rV   rW   rh   boolr   r"   r>   rG   rX   r   r   rM   rY   rZ   r[   s   @r1   rj   rj   z   sY   G  '+#'%C%C %C 	%C
 %C %C %C $%C C=%C %CT 48*.1526"'15pB||pB #5<<0pB !	pB
 !.pB "%,,/pB  pB !.pB 
u||Xell3XeELL>Q5RR	SpB pBr3   rj   c                   B  ^  \ rS rSrSrU 4S jr      SS\R                  S\\R                     S\\	   S\\R                     S\\R                     S	\
S
\\R                     S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )BartFlashAttention2i  a4  
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                 D   > [         TU ]  " U0 UD6  [        5       U l        g rb   )r=   r>   r   _flash_attn_uses_top_left_mask)r?   argskwargsr@   s      r1   r>   BartFlashAttention2.__init__  s#    $)&)
 /P.Q+r3   r   r   r   r   r   r   r   r   c                    U(       a  [        S5      eUS LnUR                  5       u  pnU R                  U5      R                  U	SU R                  U R
                  5      nUb]  [        U[        5      (       aF  UR                  R                  U R                  5      nU(       a  UR                  nOUR                  nOUnU(       a  UOUnU(       a=  Ub:  W(       a3  WR                  U R                     nUR                  U R                     nOU R                  U5      nU R!                  U5      nUR                  U	SU R                  U R
                  5      R#                  SS5      nUR                  U	SU R                  U R
                  5      R#                  SS5      nUbN  U(       d  UOS nWR%                  UUU R                  SU05      u  nnU(       a  SUR                  U R                  '   UR#                  SS5      nUR#                  SS5      nUR&                  nU[(        R*                  :X  a  [(        R,                  " 5       (       a  [(        R.                  " 5       nOR[1        U R2                  S5      (       a  U R2                  R4                  nO U R                  R6                  R&                  n[8        R;                  SU S	35        UR=                  U5      nUR=                  U5      nUR=                  U5      n[?        UUUUU
U R@                  (       a  U RB                  OS
U RD                  U RF                  S9nURI                  XS5      nU RK                  U5      nUS U4$ )NzBartSdpaAttention2 attention does not support `output_attentions`. Use the argument `attn_implementation='eager'` when loading the model.r*   r!   r;   r   T_pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .r   )rn   rq   use_top_left_mask)&r.   r   r}   r   rm   rv   r   r   r   r   rs   r   r   r   r   r{   r|   r   r   rE   rG   float32is_autocast_enabledget_autocast_gpu_dtypehasattrrr   r   rJ   rx   ry   tor%   r   rn   rq   r   r   r~   )r?   r   r   r   r   r   r   r   r   rN   q_lenr   r   r   r   r   r   r   input_dtypetarget_dtyper   s                        r1   rM   BartFlashAttention2.forward&  s    Y  .T9%**,A {{=166sBPTP]P]^%.*=>>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,66t~~FJ.::4>>JL^4J;;~6L#b$..$--PZZ[\^_`J',,S"dnndmmT^^_`bcdL)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=  ))!Q/
#--a3 #((%--'((**$;;=&?@@#{{BB#{{1177 >$ (??<8L#|4J'??<8L.$(MMDLLsnn"AA	
 "))#b9mmK0D.00r3   )r   r   )rR   rS   rT   rU   rV   r>   rG   rX   r   r   r   r   rM   rY   rZ   r[   s   @r1   r   r     s    R 48*.1526"'15e1||e1 #5<<0e1 !	e1
 !.e1 "%,,/e1  e1 !.e1 
u||Xell3XeELL>Q5RR	Se1 e1r3   r   c                   8  ^  \ rS rSr      SS\R
                  S\\R
                     S\\   S\\R
                     S\\R
                     S\S\\R
                     S	\	\R
                  \\R
                     \\	\R
                        4   4U 4S
 jjjr
SrU =r$ )BartSdpaAttentioni  r   r   r   r   r   r   r   r   c           	        > U(       a'  [         R                  S5        [        TU ]  UUUUUUS9$ USLnUR	                  5       u  pnU R                  U5      R                  U	SU R                  U R                  5      R                  SS5      nUb]  [        U[        5      (       aF  UR                  R                  U R                  5      nU(       a  UR                  nOUR                   nOUnU(       a  UOUnU(       a=  Ub:  W(       a3  WR"                  U R                     nUR$                  U R                     nOU R'                  U5      nU R)                  U5      nUR                  U	SU R                  U R                  5      R                  SS5      nUR                  U	SU R                  U R                  5      R                  SS5      nUbN  U(       d  UOSnWR+                  UUU R                  SU05      u  nnU(       a  SUR                  U R                  '   SnUb  USS2SS2SS2SUR,                  S	   24   nUR.                  R0                  S
:X  a3  Ub0  UR3                  5       nUR3                  5       nUR3                  5       nU R4                  (       a  Uc  U
S:  a  SOSn[6        R8                  R:                  R=                  UUUUU R>                  (       a  U R@                  OSUS9nUR                  SS5      R3                  5       nUR                  XU RB                  5      nU RE                  U5      nUSU4$ )r   a  BartModel is using BartSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` . Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r   r   r   Nr*   r!   r;   r   Tr   cudaFr   )	attn_mask	dropout_prq   )#rx   ry   r=   rM   r   r}   r   rm   rv   r   r   r   r   r   rs   r   r   r   r   r{   r|   r   r,   rF   type
contiguousrq   rG   r   r   scaled_dot_product_attentionr   rn   rl   r~   )r?   r   r   r   r   r   r   r   r   rN   r   r   r   r   r   r   r   r   causal_maskrq   r   r@   s                        r1   rM   BartSdpaAttention.forward  s    l 7?!1--"3- #   .T9',,.a {{=166sBPTP]P]^hhijlmn%.*=>>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,66t~~FJ.::4>>JL^4J;;~6L#b$..$--PZZ[\^_`J',,S"dnndmmT^^_`bcdL)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=%(Aq2HJ4D4DR4H2H)HIK ##v-+2I'224L#..0J'224L
 !NN{/BwQR{DX]	 hh))FF!&*mmdll G 
 "++Aq1<<> "&&sT^^DmmK0D.00r3    r   )rR   rS   rT   rU   rG   rX   r   r   r   r   rM   rY   rZ   r[   s   @r1   r   r     s     48*.1526"'15e1||e1 #5<<0e1 !	e1
 !.e1 "%,,/e1  e1 !.e1 
u||Xell3XeELL>Q5RR	Se1 e1r3   r   )eagersdpaflash_attention_2c                      ^  \ rS rSrSS\S\\   4U 4S jjjr SS\R                  S\R                  S\R                  S\\
   S	\\R                  \\R                     4   4
S
 jjrSrU =r$ )BartEncoderLayeri  rr   rs   c                   > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  UUS9U l        [        R                  " U R                  5      U l        UR                  U l        [        UR                     U l        UR                   U l        [        R"                  " U R                  UR$                  5      U l        [        R"                  " UR$                  U R                  5      U l        [        R                  " U R                  5      U l        g )N)rl   rm   rn   rr   rs   )r=   r>   d_modelrl   BART_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrn   r   activation_functionactivation_fnactivation_dropoutrz   encoder_ffn_dimfc1fc2final_layer_normr?   rr   rs   r@   s      r1   r>   BartEncoderLayer.__init__  s    /0K0KLnn44,,
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r3   r   r   r   r   r   c                    UnU R                  UUUUS9u  pn[        R                  R                  XR                  U R                  S9nXQ-   nU R                  U5      nUnU R                  U R                  U5      5      n[        R                  R                  XR                  U R                  S9nU R                  U5      n[        R                  R                  XR                  U R                  S9nXQ-   nU R                  U5      nUR                  [        R                  :X  a  [        R                  " U5      R                  5       (       d)  [        R                   " U5      R                  5       (       aC  [        R"                  " UR                  5      R$                  S-
  n[        R&                  " X* US9nU4n	U(       a  X4-  n	U	$ )aW  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`): attention mask of size
        `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
    layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
        `(encoder_attention_heads,)`.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
)r   r   r   r   r   i  )minmax)r   r   r   rn   r   r   r   r   r   r   r   rE   rG   float16isinfanyisnanfinfor   clamp)
r?   r   r   r   r   residualr   r   clamp_valueoutputss
             r1   rM   BartEncoderLayer.forward  s   $ !)-')+/	 *8 *
&Q --m||VZVcVc-d 011-@ **488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0--m<%--/KK&**,,M0J0N0N0P0P++m&9&9:>>EK!KK<[YM "&Gr3   )	r   r   rn   rl   r   r   r   r   r   rb   F)rR   rS   rT   rU   r"   r   rW   r>   rG   FloatTensorr   r   rM   rY   rZ   r[   s   @r1   r   r     s    =z =hsm = =0 -20((0 ))0 **	0
 $D>0 
u  (5+<+<"==	>0 0r3   r   c                     ^  \ rS rSrSS\S\\   4U 4S jjjr         SS\R                  S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\
   S\\   S\\   S\\R                     S\\R                  \\\R                  \R                  4      4   4S jjrSrU =r$ )BartDecoderLayeriE  rr   rs   c           
      T  > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  SSUUS9U l        UR                  U l	        [        UR                     U l        UR                  U l        [        R                  " U R                  5      U l        [        UR
                     " U R                  UR                  UR                  SUUS9U l        [        R                  " U R                  5      U l        [        R&                  " U R                  UR(                  5      U l        [        R&                  " UR(                  U R                  5      U l        [        R                  " U R                  5      U l        g )NT)rl   rm   rn   ro   rq   rr   rs   )rn   ro   rr   rs   )r=   r>   r   rl   r   r   decoder_attention_headsr   r   rn   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrz   decoder_ffn_dimr   r   r   r   s      r1   r>   BartDecoderLayer.__init__F  s6   /0K0KLnn44,,
 ~~#F$>$>?"(";";$&LL$@!263N3NONN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r3   r   r   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   r   c           	          UnU R                  UUUUUU
S9u  pn[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nSnUb`  UnU R                  UUUUUUS9u  pn[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nUnU R                  U R                  U5      5      n[        R                  R                  XR                  U R                  S9nU R                  U5      n[        R                  R                  XR                  U R                  S9nX-   nU R                  U5      nU4nU(       a  XU4-  nU	(       a  X4-  nU$ )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.
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
        cache in the correct position and to infer the complete sequence length.
)r   r   r   r   r   r   r   N)r   r   r   r   r   r   )r   r   r   rn   r   r   r   r   r   r   r   r   r   )r?   r   r   r   r   r   r  r   r   r  r   r   self_attn_weightscross_attn_weightsr   s                  r1   rM   BartDecoderLayer.forwarde  s   D ! <@>>'))+/) <J <
8. --m||VZVcVc-d 011-@ " ,$H@D@Q@Q+!65 :-"3 AR A=M~ MM11-<<Z^ZgZg1hM$4M 88GM !**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0--m< "+=>>G((Gr3   )r   r   rn   rl   r   r   r   r   r   r   r   rb   )	NNNNNNFTN)rR   rS   rT   rU   r"   r   rW   r>   rG   rX   r   r   r   r   rM   rY   rZ   r[   s   @r1   r   r   E  s1   =z =hsm = =D 268<9=26=A*.,1$(15S||S !.S  (5	S
 !) 6S "%,,/S %-U\\$:S !S $D>S D>S !.S 
u  (51B1BEDUDU1U+V"WW	XS Sr3   r   c                   z   ^  \ rS rSrSrS\S\S\S\4U 4S jjrS\R                  S	\R                  4S
 jr
SrU =r$ )BartClassificationHeadi  z-Head for sentence-level classification tasks.	input_dim	inner_dimnum_classespooler_dropoutc                    > [         TU ]  5         [        R                  " X5      U l        [        R
                  " US9U l        [        R                  " X#5      U l        g )N)r   )r=   r>   r   rz   denseDropoutrn   r~   )r?   r	  r
  r  r  r@   s        r1   r>   BartClassificationHead.__init__  s@     	YYy4
zzN3		)9r3   r   r   c                     U R                  U5      nU R                  U5      n[        R                  " U5      nU R                  U5      nU R	                  U5      nU$ rb   )rn   r  rG   tanhr~   )r?   r   s     r1   rM   BartClassificationHead.forward  sN    ]3

=1

=1]3m4r3   )r  rn   r~   )rR   rS   rT   rU   rV   rW   rh   r>   rG   rX   rM   rY   rZ   r[   s   @r1   r  r    sQ    7
:
: 
: 	
:
 
:U\\ ell  r3   r  c                   ,   \ rS rSr\rSrSrSS/rSS/r	Sr
SrSrSrSrS	 r\S
 5       r SS\\R(                  S4   S\R(                  S\R(                  S\S\4
S jjr\S\R(                  S\S\S\R4                  S\R(                  S\4S j5       rSrg)BartPreTrainedModeli  modelTzencoder.versionzdecoder.versionr   r   past_key_valuesc                    U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g [        U[        R                  5      (       aJ  UR
                  R                  R                  S5        UR                  R                  R                  5         g g )Nr   )meanstdrg   )rr   init_stdr   r   rz   rJ   datanormal_rp   zero_	Embeddingr_   r   fill_)r?   moduler  s      r1   _init_weights!BartPreTrainedModel._init_weights  s   kk""fbii((MM&&CS&9{{&  &&( '--MM&&CS&9!!-""6#5#56<<> .--MM$$S)KK""$ .r3   c                     U R                   R                  n[        R                  " / SQSSSSU//U R                  S9nUR                  U5      US.nU$ )N)r      
      r;   r         r;   rF   )r   r&   )rr   r'   rG   tensorrF   ne)r?   	pad_tokenr&   dummy_inputss       r1   r.   BartPreTrainedModel.dummy_inputs  sW    KK,,	LL"2Q2q)4L!MVZVaVab	'll95"
 r3   r   r#   input_tensorr   r   c           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nr   r   flex_attentionr   Fr   )inputs_embedsrB   is_trainingr!   r*   )sequence_lengthtarget_lengthrE   r   
batch_size)r   xpunpu)rr   r   r   r   rG   rX   r$   get_seq_lengthis_compileabler   _ignore_causal_mask_sdpar   rE   r,   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrF   r   r   r   _unmask_unattended)r?   r   r0  r   r  r   past_seen_tokensusing_compilable_cacherE   r5  r6  r   	min_dtypes                r1   _update_causal_mask'BartPreTrainedModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr3   r5  r6  rE   r7  c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
Nr'  )
fill_valuerE   rF   r!   )diagonalr*  r*   r   )r   rG   r   r   fullrF   triurH   r   rK   r-   r,   r   masked_fill)r   r5  r6  rE   r   r7  r   r   rB  mask_lengthpadding_masks              r1   r>  IBartPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position=  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 r3   r   Nr   )rR   rS   rT   rU   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_sdpa_supports_cache_class_supports_static_cacher"  propertyr.  r   rG   rX   r   r   rC  staticmethodrW   rE   r>  rY   r   r3   r1   r  r    s   L&*#*;=N)O&,.AB"3!N !%    #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r3   r  c                       \ rS rSrS rSrg)PretrainedBartModeliv  c                 :    [         R                  " S[        5        g Nz_The class `PretrainedBartModel` has been depreciated, please use `BartPreTrainedModel` instead.warningswarnFutureWarningr?   s    r1   __init_subclass__%PretrainedBartModel.__init_subclass__w      m	
r3   r   NrR   rS   rT   rU   rc  rY   r   r3   r1   r[  r[  v      
r3   r[  c                       \ rS rSrS rSrg)BartPretrainedModeli~  c                 :    [         R                  " S[        5        g r]  r^  rb  s    r1   rc  %BartPretrainedModel.__init_subclass__  re  r3   r   Nrf  r   r3   r1   ri  ri  ~  rg  r3   ri  c                   "  ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S r
S r       SS\\R                     S	\\R                     S
\\R                     S\\R                     S\\   S\\   S\\   S\\\4   4S jjrSrU =r$ )BartEncoderi  z
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`BartEncoderLayer`].

Args:
    config: BartConfig
    embed_tokens (nn.Embedding): output embedding
rr   embed_tokensc           
        > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  nUR                  U l        UR                  U l	        UR                  (       a  [        R                  " U5      OSn[        UR                  X0R                  US9U l        Ub  UR                   U R                  l        [#        UR                  U5      U l        [&        R(                  " [+        UR,                  5       Vs/ s H  n[/        XS9PM     sn5      U l        UR2                  S:H  U l        UR2                  S:H  U l        [&        R8                  " U5      U l        SU l        U R?                  5         g s  snf Nrg   rf   )rs   r   r   F) r=   r>   rn   encoder_layerdrop	layerdropr   r'   r_   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtr]   
vocab_sizern  rJ   r5   embed_positionsr   
ModuleListrangeencoder_layersr   layersr   _use_flash_attention_2	_use_sdpar   layernorm_embeddinggradient_checkpointing	post_init)r?   rr   rn  rl   r`   ir@   s         r1   r>   BartEncoder.__init__  s?    ~~11NN	!..$*$B$B!.4.D.Ddii	*#3y*:*:
 #'3':':D$=** 
 mmTYZ`ZoZoTp$qTpq%5f%JTp$qr&,&A&AEX&X#44>#%<<	#: &+# %rs   Fc                     U R                   $ rb   rn  rb  s    r1   get_input_embeddings BartEncoder.get_input_embeddings         r3   c                     Xl         g rb   r  r?   values     r1   set_input_embeddings BartEncoder.set_input_embeddings      !r3   r&   r   	head_maskr3  r   output_hidden_statesreturn_dictr   c                 0   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUb"  UnUR                  SUR                  S   5      nOUb  USS2SS2S4   nO[	        S5      eUc  U R                  U5      nU R                  U5      n	U	R                  UR                  5      n	XI-   n
U R                  U
5      n
[        R                  R                  XR                  U R                  S9n
Ubb  U R                   (       a  SU;   a  UOSnOFU R"                  (       a   Uc  U(       d  [%        X$R&                  5      nO[)        X$R&                  5      nU(       a  SOSnU(       a  SOSnUb`  UR+                  5       S   [-        U R.                  5      :w  a6  [	        S[-        U R.                  5       S	UR+                  5       S    S
35      e[1        U R.                  5       H  u  pU(       a  X4-   nSnU R                  (       a(  [2        R4                  " / 5      nUU R6                  :  a  SnU(       a  SnO^U R8                  (       a8  U R                  (       a'  U R;                  UR<                  U
UUb  X=   OSU5      nOU" U
UUb  X=   OSUS9nUS   n
U(       d  M  UUS   4-   nM     U(       a  X4-   nU(       d  [?        S XU4 5       5      $ [A        XUS9$ )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   .   #    U  H  oc  M  Uv   M     g 7frb   r   .0vs     r1   	<genexpr>&BartEncoder.forward.<locals>.<genexpr><  s     e$Sq$Ss   	last_hidden_stater   
attentions)!rr   r   r  use_return_dictr.   r   r,   rn  ry  r   rF   r  r   r   rn   r   r~  r  r   rE   r   r   lenr}  	enumeraterG   randrr  r  _gradient_checkpointing_func__call__tupler   )r?   r&   r   r  r3  r   r  r  input	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r1   rM   BartEncoder.forward  s	   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]  ]%>cdd"E!r9??2+>?I&!!Q(+ETUU  --i8M((/	LL!5!56	%100?--m||VZVcVc-d %**343FDI$5>O "E^UhUh!i "<NL_L_!`30d  ~~"s4;;'78 <S=M<N O!(+,A/ 
 #,DKK"8C#!/2B!BG}}&+jjn#&7"G ,..4==$($E$E%..%&+4+@d)%M %2%&;D;PVZ*;	%M !.a 0  !/=3C2E!EA #9D  +.>>Ne]N$Seee+Vd
 	
r3   )r~  r  rn   ry  rn  r  rr  r  r}  rt  r_   rb   )NNNNNNN)rR   rS   rT   rU   rV   r"   r   r   r  r>   r  r  rG   
LongTensorrX   r   r   r   r   r   rM   rY   rZ   r[   s   @r1   rm  rm    s    z ",,9O  >!"
 1515,059,0/3&*J
E,,-J
 !.J
 ELL)	J

   1 12J
 $D>J
 'tnJ
 d^J
 
uo%	&J
 J
r3   rm  c                     ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S r
S r             SS\\R                     S	\\R                     S
\\R                     S\\R                     S\\R                     S\\R                     S\\\R                        S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4S jjrSrU =r$ )BartDecoderiB  z
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BartDecoderLayer`]

Args:
    config: BartConfig
    embed_tokens (nn.Embedding): output embedding
rr   rn  c           
      T  > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  U l        UR                  U l        UR                  (       a   [        R                  " UR                  5      OSn[        UR                  UR                  U R                  US9U l        Ub  UR                   U R                  l        [#        UR                  UR                  5      U l        [&        R(                  " [+        UR,                  5       Vs/ s H  n[/        XS9PM     sn5      U l        UR2                  S:H  U l        UR2                  S:H  U l        [&        R8                  " UR                  5      U l        SU l        U R?                  5         g s  snf rp  ) r=   r>   rn   decoder_layerdroprr  r'   r_   rs  max_target_positionsru  rv  rw  r   r]   rx  rn  rJ   r5   ry  r   rz  r{  decoder_layersr   r}  r   r~  r  r   r  r  r  )r?   rr   rn  r`   r  r@   s        r1   r>   BartDecoder.__init__K  sH    ~~11!..$*$B$B!393I3Idii/s3v~~t/?/?[
 #'3':':D$=**NN 
 mmTYZ`ZoZoTp$qTpq%5f%JTp$qr&,&A&AEX&X#44>#%<<#? &+# %rs   !F%c                     U R                   $ rb   r  rb  s    r1   r   BartDecoder.get_input_embeddingsh  r  r3   c                     Xl         g rb   r  r  s     r1   r   BartDecoder.set_input_embeddingsk  r  r3   r&   r   r   r   r  cross_attn_head_maskr  r3  r  r   r  r  r   r   c                 	   U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nU R
                  (       a/  U R                  (       a  U	(       a  [        R                  S5        Sn	USL USL-  (       a  [        S5      eUb  UR                  SUR                  S   5      nUc  U R                  U5      nSnU	(       aB  [        U[        5      (       d-  Sn[        R                  S5        [        R                   " U5      nUR#                  5       SS u  nnUb  UR%                  5       OSnUc#  [&        R(                  " UUU-   UR*                  S	9nUc4  [-        5       (       d%  UU-   n[&        R.                  " UUUR*                  S	9n[        U[        5      (       a  UR0                  OUnU R3                  UUUUU
5      nUbd  Uba  U R4                  (       a  SU;   a  UOSnOEU R6                  (       a   Uc  U
(       d  [9        UUR:                  US
9nO[=        XHR:                  US
9nU R?                  [@        UUS9nURC                  UR*                  5      nUU-   nU RE                  U5      n[F        RH                  RK                  UU RJ                  U R                  S9nU(       a  SOSnU
(       a  SOSnU
(       a  Ub  SOSnSn[M        XV/SS/5       Hn  u  nnUc  M  UR#                  5       S   [O        U RP                  5      :w  d  M7  [        SU S[O        U RP                  5       SUR#                  5       S    S35      e   [S        U RP                  5       H  u  nnU(       a  UU4-  nU R                  (       a(  [&        RT                  " / 5      nUU RV                  :  a  ML  U R
                  (       aG  U R                  (       a6  U RY                  URZ                  UUUUUb  UU   OSUb  UU   OSSU
U	U5      n OU" UUUUUb  UU   OSUb  UU   OSUU
U	US9
n U S   nU	(       a  U U
(       a  SOS   nU
(       d  M  UU S   4-  nUc  M  UU S   4-  nGM      U(       a  UU4-  nU	(       a  UOSn!U(       a  UR]                  5       n!U(       d  [_        S UU!UUU4 5       5      $ [a        UU!UUUS9$ )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.
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
        cache in the correct position and to infer the complete sequence length.
NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer*   TzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r*  )r   )rC   r   r   r  r  zThe `z` should be specified for r  r   )	r   r   r   r   r  r   r   r  r   r   r!   r;   c              3   0   #    U  H  nUc  M  Uv   M     g 7frb   r   r  s     r1   r  &BartDecoder.forward.<locals>.<genexpr>c  s      mA ms   	)r  r  r   r  cross_attentions)1rr   r   r  r  r  r  r   rx   ry   r.   r   r,   rn  r   r   r   from_legacy_cacher   r:  rG   rH   rF   r   onesr   rC  r~  r  r   rE   r   ry  r  r   r  r   r   rn   zipr  r}  r  r  rr  r  r  to_legacy_cacher  r   )"r?   r&   r   r   r   r  r  r  r3  r  r   r  r  r   return_legacy_cacher7  
seq_lengthrB   mask_seq_lengthself_attn_cacher   rC   r   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cacher   	mask_namer  decoder_layerr  r  
next_caches"                                     r1   rM   BartDecoder.forwardn  sH   h 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]&&4==##p "	 -t";<stt !r9??2+>?I  --i8M $Z??"&\
 2CCOTO!.!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !*B*D*D4zAO"ZZ
OML`L`aN /+>?? 00  	
 ..
 !,1G1S**CDH^C^)?dh&$8$@IZ *M*!''&*& *D*,?,?*&
 ++E3IXf+g#}';';<%400?--mt||VZVcVc-d #7BD0d&7<Q<]rdh! %((IKYoKp$q Iy$>>#A&3t{{+;<$	{*DSEUDV W%NN,Q/03  %r #,DKK"8C#!m%55!}}&+jjn#&7**t}} $ A A!**!)*&/&;IcN1E1Q(-W[%"! !.!#.*?+A7@7LYs^RV5I5U,S1[_#2&7'#1! *!,M%28I1q%Q"  =#3"55(4(]1-=,??(_ #9d  -!11+4'$
(88:J '5FXlm  
 9+&+%1
 	
r3   )r~  r  rn   ry  rn  r  rr  r  r}  r  r_   rb   )NNNNNNNNNNNNN)rR   rS   rT   rU   rV   r"   r   r   r  r>   r  r  rG   r  rX   r   r   r   r   r   r   rM   rY   rZ   r[   s   @r1   r  r  B  s}   z ",,9O  :!"
 1515=A=A,07;=A59$(,0/3&*59@
E,,-@
 !.@
  ((9(9:	@

 !))9)9 :@
 ELL)@
 'u||4@
 "$u'8'8"9:@
   1 12@
 D>@
 $D>@
 'tn@
 d^@
 !!1!12@
 
u??	@@
 @
r3   r  c            &       8  ^  \ rS rSrSS/rS\4U 4S jjrS rS rS r	S	 r
S
 r\                SS\\R                     S\\R                      S\\R                     S\\R                     S\\R                      S\\R                      S\\R                      S\\\R$                        S\\\R$                        S\\R$                     S\\R$                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4"S jj5       rSrU =r$ )	BartModeliq  encoder.embed_tokens.weightdecoder.embed_tokens.weightrr   c                 r  > [         TU ]  U5        UR                  UR                  p2UR                  (       a   [
        R                  " UR                  5      OSn[        X1R                  X$S9U l	        [        XR                  5      U l        [        XR                  5      U l        U R                  5         g )Nrg   rf   )r=   r>   r'   rx  ru  rv  rw  r   r]   sharedrm  encoderr  decoderr  )r?   rr   r_   rx  r`   r@   s        r1   r>   BartModel.__init__u  s}     "("5"5v7H7HZ393I3Idii/s-j..+o"6;;7"6;;7 	r3   c                    U R                   R                  (       GaF  U R                  R                  R                  [
        R                  " S5      :X  a  U R                  R                  R                  R                  [
        R                  " S5      :w  ak  U R                  U R                  R                  U R                  R                  5        U R                  U R                  U R                  R                  5        g U R                  U R                  R                  U R                  5        U R                  U R                  R                  U R                  5        g g )Nmeta)
rr   tie_word_embeddingsr  rJ   rF   rG   r  rn  _tie_or_clone_weightsr  rb  s    r1   _tie_weightsBartModel._tie_weights  s    ;;***{{!!((ELL- ,,++2299U\\&=QQ**4<<+D+DdllF_F_`**4;;8Q8QR**4<<+D+DdkkR**4<<+D+DdkkR +r3   c                     U R                   $ rb   )r  rb  s    r1   r  BartModel.get_input_embeddings  s    {{r3   c                 |    Xl         U R                   U R                  l        U R                   U R                  l        g rb   )r  r  rn  r  r  s     r1   r  BartModel.set_input_embeddings  s'    $(KK!$(KK!r3   c                     U R                   $ rb   )r  rb  s    r1   get_encoderBartModel.get_encoder      ||r3   c                     U R                   $ rb   r  rb  s    r1   get_decoderBartModel.get_decoder  r  r3   r&   r   decoder_input_idsdecoder_attention_maskr  decoder_head_maskr  encoder_outputsr  r3  decoder_inputs_embedsr  r   r  r  r   r   c                 T   UcE  UcB  Uc  [        S5      e[        XR                  R                  U R                  R                  5      nUb  UOU R                  R
                  nUb  UOU R                  R                  nUb  UOU R                  R                  nUb  UOU R                  R                  nUc  U R                  UUUU
UUUS9nORU(       aK  [        U[        5      (       d6  [        US   [        U5      S:  a  US   OS[        U5      S:  a  US   OSS9nU R                  UUUS   UUUU	UUUUUUS9nU(       d  UU-   $ [        UR                  UR                   UR"                  UR$                  UR&                  UR                  UR"                  UR$                  S	9$ )
t  
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Indices of decoder input sequence tokens in the vocabulary.

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

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

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

    For translation and summarization training, `decoder_input_ids` should be provided. If no
    `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
    for denoising pre-training following the paper.
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.

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

    - 1 indicates the head is **not masked**,
    - 0 indicates the head is **masked**.
NzIf no `decoder_input_ids` or `decoder_inputs_embeds` are passed, `input_ids` cannot be `None`. Please pass either `input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.)r&   r   r  r3  r   r  r  r   r!   r;   r  r&   r   r   r   r  r  r  r3  r  r   r  r  r   )r  r  decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentions)r.   r2   rr   r'   r(   r   r  r  r  r  r   r   r  r  r   r  r  r   r  r  )r?   r&   r   r  r  r  r  r  r  r  r3  r  r  r   r  r  r   decoder_outputss                     r1   rM   BartModel.forward  s   f $)>)F  U  !3;;33T[[5W5W! 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]""ll#-#+"3%9' + O O_!M!M-"1!"4474H14Loa0RV14_1E1I?1-tO ,,'1"1!"4#1'!5+//!5#) ' 
  "_44!-??+;;"1"?"?.99,==&5&G&G"1"?"?.99	
 		
r3   )r  r  r  NNNNNNNNNNNNNNNN)rR   rS   rT   rU   _tied_weights_keysr"   r>   r  r  r  r  r  r   r   rG   r  rX   r   r   r   r   r   r   rM   rY   rZ   r[   s   @r1   r  r  q  s   79VWz 
S0
  15158<=A,0487;=A=A59=A$(,0/3&*59#t
E,,-t
 !.t
 $E$4$45	t

 !))9)9 :t
 ELL)t
 $ELL1t
 'u||4t
 "$u'8'8"9:t
 "$u'8'8"9:t
   1 12t
  ((9(9:t
 D>t
 $D>t
 'tnt
  d^!t
" !!1!12#t
$ 
u((	)%t
 t
r3   r  zV
    The BART Model with a language modeling head. Can be used for summarization.
    )custom_introc            (         ^  \ rS rSrSr/ SQrS/rS\4U 4S jjrS r	S r
 S(S
\S\\   S\S\R                  4U 4S jjjrS
\SS	4S jrS rS rS r\                 S)S\\R.                     S\\R0                     S\\R.                     S\\R.                     S\\R0                     S\\R0                     S\\R0                     S\\\R4                        S\\\R4                        S\\R4                     S\\R4                     S\\R.                     S\\   S \\   S!\\   S"\\   S#\\R.                     S\\\4   4$S$ jj5       rS\R0                  4S% jr\ S& 5       r!S'r"U =r#$ )*BartForConditionalGenerationi  r  )r  r  lm_head.weightfinal_logits_biasrr   c                 v  > [         TU ]  U5        [        U5      U l        U R	                  S[
        R                  " SU R                  R                  R                  45      5        [        R                  " UR                  U R                  R                  R                  SS9U l        U R                  5         g )Nr  r!   Fru   )r=   r>   r  r  register_bufferrG   zerosr  r7   r   rz   r   lm_headr  r?   rr   r@   s     r1   r>   %BartForConditionalGeneration.__init__  s     v&
0%++q$**BSBSBbBb>c2deyy1B1B1Q1QX]^ 	r3   c                 6    U R                   R                  5       $ rb   )r  r  rb  s    r1   r  (BartForConditionalGeneration.get_encoder'      zz%%''r3   c                 6    U R                   R                  5       $ rb   )r  r  rb  s    r1   r  (BartForConditionalGeneration.get_decoder*  r  r3   Nnew_num_tokenspad_to_multiple_ofmean_resizingr   c                 x   > [         TU ]  XU5      nU R                  UR                  R                  S   5        U$ )Nr   )r=   resize_token_embeddings_resize_final_logits_biasrJ   r,   )r?   r  r  r  new_embeddingsr@   s        r1   r  4BartForConditionalGeneration.resize_token_embeddings-  s<     8]jk&&~'<'<'B'B1'EFr3   c                 ,   U R                   R                  S   nX::  a  U R                   S S 2S U24   nON[        R                  " SX-
  4U R                   R                  S9n[        R
                  " U R                   U/SS9nU R                  SU5        g )Nr*   r!   r*  r   r  )r  r,   rG   r  rF   catr  )r?   r  old_num_tokensnew_bias
extra_biass        r1   r  6BartForConditionalGeneration._resize_final_logits_bias4  s    //55b9+--a..@AHa)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r3   c                     U R                   $ rb   r  rb  s    r1   get_output_embeddings2BartForConditionalGeneration.get_output_embeddings=  r  r3   c                     Xl         g rb   r  r?   r  s     r1   set_output_embeddings2BartForConditionalGeneration.set_output_embeddings@      %r3   c                     U R                   R                  (       aK  U R                  R                  5         U R	                  U R
                  U R                  R                  5        g g rb   )rr   r  r  r  r  r  r  rb  s    r1   r  )BartForConditionalGeneration._tie_weightsC  sB    ;;**JJ##%&&t||TZZ5F5FG +r3   r&   r   r  r  r  r  r  r  r  r3  r  labelsr  r   r  r  r   c                 R   Ub  UOU R                   R                  nUbX  U(       a  [        R                  S5        SnUc7  Uc4  [	        XR                   R
                  U R                   R                  5      nU R                  UUUUUUUUU	U
UUUUUUS9nU R                  US   5      nUU R                  R                  UR                  5      -   nSnUba  UR                  UR                  5      n[        5       nU" UR                  SU R                   R                  5      UR                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                   UR"                  UR$                  UR&                  UR(                  UR*                  UR,                  S9	$ )	a  
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Indices of decoder input sequence tokens in the vocabulary.

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

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

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

    For translation and summarization training, `decoder_input_ids` should be provided. If no
    `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
    for denoising pre-training following the paper.
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.

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

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

Example summarization:

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

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

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

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

Mask filling example:

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

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

>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
>>> logits = model(input_ids).logits

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

>>> tokenizer.decode(predictions).split()
['not', 'good', 'healthy', 'great', 'very']
```
NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r   r  r  r  r  r  r  r  r3  r  r  r   r  r  r   r   r*   r!   	losslogitsr  r  r  r  r  r   r  )rr   r  rx   warningr2   r'   r(   r  r  r  r   rF   r	   r   rx  r   r  r  r  r  r  r   r  )r?   r&   r   r  r  r  r  r  r  r  r3  r  r$  r  r   r  r  r   r   	lm_logitsmasked_lm_lossloss_fctoutputs                          r1   rM   $BartForConditionalGeneration.forwardH  s   ~ &1%<k$++B]B]klI (-B-J$6KK44dkk6X6X%! **)/+#9/!5+'"7/!5#)!  
& LL,	 6 6 9 9):J:J KK	YYy//0F')H%innR9O9O&PRXR]R]^`RabN\GABK/F3A3M^%.YSYY#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r3   c                 j    [        XR                  R                  U R                  R                  5      $ rb   )r2   rr   r'   r(   )r?   r$  s     r1   %prepare_decoder_input_ids_from_labelsBBartForConditionalGeneration.prepare_decoder_input_ids_from_labels  s#    !&++*B*BDKKDfDfggr3   c                 b   ^ SnU  H%  nU[        U4S jUS S  5       5      USS  -   4-  nM'     U$ )Nr   c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7frQ   index_selectr   rF   r  
past_statebeam_idxs     r1   r  >BartForConditionalGeneration._reorder_cache.<locals>.<genexpr>  s1     rcqU_--aZ=N=N1OPPcq   7:r;   r  r  r8  reordered_past
layer_pasts    `  r1   _reorder_cache+BartForConditionalGeneration._reorder_cache  sO    )JrcmnpopcqrrQR.! N * r3   r  r  )NTNNNNNNNNNNNNNNNNN)$rR   rS   rT   rU   rO  r  _keys_to_ignore_on_load_missingr"   r>   r  r  rW   r   r   r   r  r  r  r  r  r  r   rG   r  rX   r   r   r   r   r   rM   r0  rY  r?  rY   rZ   r[   s   @r1   r  r    sm     i':&;#z (( dh!7?}\`	 < < <&H
  15158<=A,0487;=A=A59=A-1$(,0/3&*59%S
E,,-S
 !.S
 $E$4$45	S

 !))9)9 :S
 ELL)S
 $ELL1S
 'u||4S
 "$u'8'8"9:S
 "$u'8'8"9:S
   1 12S
  ((9(9:S
 ))*S
 D>S
 $D>S
  'tn!S
" d^#S
$ !!1!12%S
& 
uo%	&'S
 S
jhELL h  r3   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            &         ^  \ rS rSrSS/rS\4U 4S jjr\                SS\\	R                     S\\	R                     S\\	R                     S	\\	R                     S
\\	R                     S\\	R                     S\\	R                     S\\\	R                        S\\	R                     S\\	R                     S\\	R                     S\\   S\\   S\\   S\\   S\\	R                     S\\\4   4"S jj5       rSrU =r$ )BartForSequenceClassificationi  r  r  rr   c                    > [         TU ]  " U40 UD6  [        U5      U l        [	        UR
                  UR
                  UR                  UR                  5      U l        U R                  5         g rb   )
r=   r>   r  r  r  r   
num_labelsclassifier_dropoutclassification_headr  )r?   rr   r   r@   s      r1   r>   &BartForSequenceClassification.__init__  sZ    *6*v&
#9NNNN%%	$
  	r3   r&   r   r  r  r  r  r  r  r3  r  r$  r  r   r  r  r   r   c                    Ub  UOU R                   R                  nUb  SnUc%  U	b"  [        SU R                  R                   35      eU R                  UUUUUUUUU	U
UUUUUS9nUS   nUR                  U R                   R                  5      R                  UR                  5      n[        [        R                  " UR                  S5      5      5      S:  a  [        S5      eUUSS24   R                  UR!                  S5      SUR!                  S5      5      SS2SSS24   nU R#                  U5      nSnUGb  UR                  UR                  5      nU R                   R$                  c  U R                   R&                  S:X  a  S	U R                   l        OyU R                   R&                  S:  aN  UR(                  [        R*                  :X  d  UR(                  [        R,                  :X  a  S
U R                   l        OSU R                   l        U R                   R$                  S	:X  aT  [/        5       nU R                   R&                  S:X  a&  U" UR1                  5       UR1                  5       5      nOU" UU5      nOU R                   R$                  S
:X  aG  [3        5       nU" UR                  SU R                   R&                  5      UR                  S5      5      nO-U R                   R$                  S:X  a  [5        5       nU" UU5      nU(       d  U4USS -   nUb  U4U-   $ U$ [7        UUUR8                  UR:                  UR<                  UR>                  UR@                  URB                  URD                  S9	$ )a  
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Indices of decoder input sequence tokens in the vocabulary.

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

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

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

    For translation and summarization training, `decoder_input_ids` should be provided. If no
    `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
    for denoising pre-training following the paper.
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.

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

    - 1 indicates the head is **not masked**,
    - 0 indicates the head is **masked**.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
    Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
    config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
NFz8Passing input embeddings is currently not supported for r   r  r  r  r  r  r  r3  r  r  r   r  r  r   r   r!   z7All examples must have the same number of <eos> tokens.r*   
regressionsingle_label_classificationmulti_label_classificationr&  )#rr   r  NotImplementedErrorr@   rR   r  eqeos_token_idr   rF   r  rG   unique_consecutivesumr.   r   r   rI  problem_typerG  rE   rI   rW   r
   squeezer	   r   r   r  r  r  r  r  r   r  )r?   r&   r   r  r  r  r  r  r  r3  r  r$  r  r   r  r  r   r   r   eos_masksentence_representationr(  r'  r,  r-  s                            r1   rM   %BartForSequenceClassification.forward  s"   h &1%<k$++B]B]I!:%J4>>KbKbJcd  **)/#9/!5+'"7/!5#)  
"  
<< 8 89<<]=Q=QRu''Q89A=VWW"/!"<"A"A-BTBTUVBWY[]j]o]opr]s"tr1H#
 ))*ABYYv}}-F{{''/;;))Q./;DKK,[[++a/V\\UZZ5OSYS_S_chclclSl/LDKK,/KDKK,{{''<7"9;;))Q.#FNN$4fnn6FGD#FF3D))-JJ+-B0F0F GUWY))-II,./Y,F)-)9TGf$EvE.#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r3   )rI  r  r  )rR   rS   rT   rU   r  r"   r>   r   r   rG   r  rX   r   r   r   r   r   r   rM   rY   rZ   r[   s   @r1   rE  rE    s    89VWz   15158<=A,0487;=A59=A-1$(,0/3&*59#}
E,,-}
 !.}
 $E$4$45	}

 !))9)9 :}
 ELL)}
 $ELL1}
 'u||4}
 "$u'8'8"9:}
   1 12}
  ((9(9:}
 ))*}
 D>}
 $D>}
 'tn}
  d^!}
" !!1!12#}
$ 
u55	6%}
 }
r3   rE  c            (       ,  ^  \ rS rSrSS/rU 4S jr\                 SS\\R                     S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\R                     S\\\R                        S\\R                     S\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4$S jj5       rSrU =r$ )BartForQuestionAnsweringi  r  r  c                    > [         TU ]  U5        SUl        UR                  U l        [        U5      U l        [
        R                  " UR                  UR                  5      U l        U R                  5         g r:   )
r=   r>   rG  r  r  r   rz   hidden_size
qa_outputsr  r  s     r1   r>   !BartForQuestionAnswering.__init__  s[      ++v&
))F$6$68I8IJ 	r3   r&   r   r  r  r  r  r  r  start_positionsend_positionsr3  r  r  r   r  r  r   r   c                    Ub  UOU R                   R                  nU	b  U
b  SnU R                  UUUUUUUUUUUUUUUS9nUS   nU R                  U5      nUR	                  SSS9u  nnUR                  S5      R                  5       nUR                  S5      R                  5       nSnU	b  U
b  [        U	R                  5       5      S:  a  U	R                  S5      n	[        U
R                  5       5      S:  a  U
R                  S5      n
UR                  S5      nU	R                  SU5      n	U
R                  SU5      n
[        US9nU" UU	5      nU" UU
5      nUU-   S	-  nU(       d  UU4USS -   nUb  U4U-   $ U$ [        UUUUR                  UR                  UR                  UR                  UR                   UR"                  UR$                  S
9
$ )r  NFrL  r   r!   r*   r   )ignore_indexr;   )
r'  start_logits
end_logitsr  r  r  r  r  r   r  )rr   r  r  r^  splitrV  r   r  r   r   r	   r   r  r  r  r  r  r   r  )r?   r&   r   r  r  r  r  r  r  r`  ra  r3  r  r  r   r  r  r   r   sequence_outputr(  rd  re  
total_lossignored_indexr,  
start_lossend_lossr-  s                                r1   rM    BartForQuestionAnswering.forward  s   d &1%<k$++B]B]&=+DI**)/#9/!5+'"7/!5#)  
$ "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J F 0:/EZMF*Q6Q2%!#33")"?"?&99$55&-&G&G")"?"?&99
 	
r3   )r  rG  r^  rB  )rR   rS   rT   rU   r  r>   r   r   rG   rX   r  r   r   r   r   r   r   rM   rY   rZ   r[   s   @r1   r[  r[    s   79VW
  -1158<=A,0487;=A6:4859=A$(,0/3&*59%q
ELL)q
 !.q
 $E$4$45	q

 !))9)9 :q
 ELL)q
 $ELL1q
 'u||4q
 "$u'8'8"9:q
 "%"2"23q
   0 01q
   1 12q
  ((9(9:q
 D>q
 $D>q
  'tn!q
" d^#q
$ !!1!12%q
& 
u99	:'q
 q
r3   r[  c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )BartDecoderWrapperi	  z
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                 D   > [         TU ]  U5        [        U5      U l        g rb   )r=   r>   r  r  r  s     r1   r>   BartDecoderWrapper.__init__  s     "6*r3   c                 &    U R                   " U0 UD6$ rb   r  )r?   r   r   s      r1   rM   BartDecoderWrapper.forward  s    ||T,V,,r3   r  )	rR   rS   rT   rU   rV   r>   rM   rY   rZ   r[   s   @r1   rn  rn  	  s    
+- -r3   rn  zu
    BART decoder with a language modeling head on top (linear layer with weights tied to the input embeddings).
    c            "         ^  \ rS rSrS/rU 4S jrS rS rS rS r	S r
S	 r\              SS
\\R                     S\\R                      S\\R"                     S\\R"                     S\\R                      S\\R                      S\\\R"                        S\\R"                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4S jj5       r\S 5       rSrU =r$ )BartForCausalLMi  r  c                 
  > [         R                  " U5      nSUl        SUl        [        TU ]  U5        [        U5      U l        [        R                  " UR                  UR                  SS9U l        U R                  5         g )NTFru   )copydeepcopyro   is_encoder_decoderr=   r>   rn  r  r   rz   r]  rx  r  r  r  s     r1   r>   BartForCausalLM.__init__  sf    v& $)! '/
yy!3!3V5F5FUS 	r3   c                 B    U R                   R                  R                  $ rb   r  r  rn  rb  s    r1   r  $BartForCausalLM.get_input_embeddings+  s    zz!!...r3   c                 8    XR                   R                  l        g rb   r{  r  s     r1   r  $BartForCausalLM.set_input_embeddings.  s    */

'r3   c                     U R                   $ rb   r  rb  s    r1   r  %BartForCausalLM.get_output_embeddings1  r  r3   c                     Xl         g rb   r  r  s     r1   r  %BartForCausalLM.set_output_embeddings4  r!  r3   c                 $    XR                   l        g rb   r  r  )r?   r  s     r1   set_decoderBartForCausalLM.set_decoder7  s    $

r3   c                 .    U R                   R                  $ rb   r  rb  s    r1   r  BartForCausalLM.get_decoder:  s    zz!!!r3   r&   r   r   r   r  r  r  r3  r$  r  r   r  r  r   r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU R                  R                  UUUUUUUUU
UUUUS9nU R                  US   5      nSnU	ba  U	R                  UR                  5      n	[        5       nU" UR                  SU R                   R                  5      U	R                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                  UR                   S9$ )a  
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

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

Example:

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

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
>>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
```Nr  r   r*   r!   )r'  r(  r  r   r  r  )rr   r   r  r  r  r  r  r   rF   r	   r   rx  r   r  r   r  r  )r?   r&   r   r   r   r  r  r  r3  r$  r  r   r  r  r   r   r(  r'  r,  r-  s                       r1   rM   BartForCausalLM.forward=  s[   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **$$)"7#9!5+'/!5#) % 
  gaj)YYv}}-F')HFKKDKK,B,BCV[[QS_UDY,F'+'7D7V#CVC0#33!//))$55
 	
r3   c                 P   ^ SnU  H  nU[        U4S jU 5       5      4-  nM     U$ )Nr   c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7frQ   r4  r6  s     r1   r  1BartForCausalLM._reorder_cache.<locals>.<genexpr>  s1     ncmU_--aZ=N=N1OPPcmr:  r;  r<  s    `  r1   r?  BartForCausalLM._reorder_cache  s8    )Jncmnn N * r3   rA  )NNNNNNNNNNNNNN)rR   rS   rT   rU   r  r>   r  r  r  r  r  r  r   r   rG   r  rX   r   r   r   r   r   r   rM   rY  r?  rY   rZ   r[   s   @r1   rt  rt    s    ++
/0&%"  1515=A>B,07;=A59-1$(,0/3&*59W
E,,-W
 !.W
  ((9(9:	W

 !)):): ;W
 ELL)W
 'u||4W
 "$u'8'8"9:W
   1 12W
 ))*W
 D>W
 $D>W
 'tnW
 d^W
 !!1!12W
  
u77	8!W
 W
r  r3   rt  )rt  r  r[  rE  r  r  ri  r[  )QrV   rv  rv  r_  typingr   r   r   r   rG   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   r   r   modeling_flash_attention_utilsr   r   modeling_outputsr   r   r   r   r   r   r   modeling_utilsr   utilsr   r   r   r    configuration_bartr"   !torch.nn.attention.flex_attentionr#   integrations.flex_attentionr$   r%   
get_loggerrR   rx   rX   rW   r2   r  r5   r]   Modulerj   r   r   r   r   r   r  r  r[  ri  rm  r  r  r  rE  r[  rn  rt  __all__r   r3   r1   <module>r     s       / /    A A ! 5 ) 
 i   .  +  !!;J J 
		H	%%,, c [^  ;R\\ ;2
=bll 
=ZBBII ZBzt1- t1nf1 f1T , Dryy DNsryy slRYY 0 _/ _ _D
- 

- 
y
% y
xl
% l
^	 _
# _
 _
D 
Q#6 Q
Qh N
$7 N
N
b A
2 A
 A
H-, - 
B)? B
BJ	r3   