
    fTh0                       S 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r
SSK
Jr  SSK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  SSK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(J)r)  SSK*J+r+  \%RX                  " \-5      r.S\
R^                  S\0S\04S jr1 " S S\Rd                  5      r3 " S S\Rh                  5      r5S\50r6 " S S\Rh                  5      r7 " S S\Rh                  5      r8\" " S S \ 5      5       r9 " S! S"\95      r: " S# S$\95      r;\" " S% S&\95      5       r<\"" S'S(9 " S) S*\9\5      5       r= " S+ S,\95      r> " S- S.\9\5      r?/ S/Qr@g)0zPyTorch PEGASUS model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter_prepare_4d_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )PegasusConfig)	BlockMask)make_flex_block_causal_mask	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       d/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/pegasus/modeling_pegasus.pyshift_tokens_rightr*   =   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\S\S\\   SS4U 4S jjjrS	 r\	R                  " 5        SS
\	R                  S\S\\	R                     S\	R                  4U 4S jjj5       rSrU =r$ )$PegasusSinusoidalPositionalEmbeddingN   zDThis module produces sinusoidal positional embeddings of any length.Nnum_positionsembedding_dimpadding_idxreturnc                 $   > [         TU ]  X5        g N)super__init__)selfr/   r0   r1   	__class__s       r)   r6   -PegasusSinusoidalPositionalEmbedding.__init__Q   s    6r+   c                    U R                   R                  u  p[        R                  " [	        U5       VVs/ s H?  n[	        U5       Vs/ s H%  oC[        R
                  " SSUS-  -  U-  5      -  PM'     snPMA     snn5      n[        R                  " XU R                   R                  SS9nUS-  S:X  a  US-  OUS-  S-   n[        R                  " [        R                  " USS2SSS24   5      5      USS2SU24'   [        R                  " [        R                  " USS2SSS24   5      5      USS2US24'   [        R                  " USS9U l         gs  snf s  snnf )	z
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
the 2nd half of the vector. [dim // 2:]
i'     F)dtyperequires_gradr   r   N)r=   )weightr$   nparrayrangepowertorchemptyr<   FloatTensorsincosr   	Parameter)r7   n_posdimposjposition_encoutsentinels           r)   _init_weight1PegasusSinusoidalPositionalEmbedding._init_weightT   s*   
 [[&&
xxX]^cXdeXdQTsLABHHUAaL3$677LXde
 kk%DKK,=,=US"Qw!|3!8#(a"..rvvl1add76K/LMAqzM!--bff\!QTT'5J.KLAxyLll3e< Mes   E

,E6E
E
input_ids_shapepast_key_values_lengthposition_idsc                    > UcB  USS u  pE[         R                  " X"U-   [         R                  U R                  R                  S9n[
        TU ]  U5      $ )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr;   )r<   device)rC   arangelongr>   rV   r5   forward)r7   rR   rS   rT   bszseq_lenr8   s         r)   rY   ,PegasusSinusoidalPositionalEmbedding.forwardc   sX    
 *2A.LC <<&(HPUPZPZcgcncncucuL w|,,r+   )r>   r4   r   N)__name__
__module____qualname____firstlineno____doc__intr   r6   rP   rC   no_gradSizeTensorrY   __static_attributes____classcell__r8   s   @r)   r-   r-   N   s    N7c 7# 7HUXM 7ei 7 7= ]]_sw	-$zz	-CF	-ZbchcocoZp	-		- 	-r+   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$ )PegasusAttentionq   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.rq   )r5   r6   rm   rn   ro   head_dimrs   r&   scalingrp   rr   rt   loggerwarning_oncer8   r^   r   Lineark_projv_projq_projout_proj)
r7   rm   rn   ro   rp   rq   rr   rs   rt   r8   s
            r)   r6   PegasusAttention.__init__t   s    	""!.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	4@ii	4@ii	4@		)TBr+   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionr2   c                 
   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$ )z#Input shape: Batch x Time x ChannelNr"   r   r;   r   Tz$Attention weights should be of size z	, but is rJ   z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizer~   viewrn   rw   	transposerx   
isinstancer   
is_updatedgetrt   cross_attention_cacheself_attention_cache	key_cachevalue_cacher|   r}   updatereshaperC   bmmr&   r$   r   
functionalsoftmaxro   r   rm   r   )r7   r   r   r   r   r   r   r   is_cross_attentionrZ   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                           r)   rY   PegasusAttention.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Ar+   )rs   ro   rm   rw   rr   rp   r|   rt   rn   r   r~   rx   r}   )        FTFNN)NNNNFN)r^   r_   r`   ra   rb   rc   floatboolr   r   r6   rC   rf   r   r   rY   rg   rh   ri   s   @r)   rk   rk   q   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r+   rk   eagerc                      ^  \ rS rSrS\4U 4S jjr SS\R                  S\R                  S\R                  S\S\R                  4
S	 jjr	S
r
U =r$ )PegasusEncoderLayeri  rs   c                   > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  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)rm   rn   ro   rs   )r5   r6   d_modelrm   PEGASUS_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normro   r
   activation_functionactivation_fnactivation_dropoutr{   encoder_ffn_dimfc1fc2final_layer_normr7   rs   r8   s     r)   r6   PegasusEncoderLayer.__init__  s    263N3NOnn44,,	
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r+   r   r   r   r   r2   c                    UnU R                  U5      nU R                  UUUUS9u  pn[        R                  R	                  XR                  U R
                  S9nXQ-   nUnU R                  U5      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                  [        R                  :X  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   r   ro   r   r   r   r   r   r   r<   rC   float16finfor   clamp)
r7   r   r   r   r   residualr   r   clamp_valueoutputss
             r)   rY   PegasusEncoderLayer.forward%  sV   $ !11-@)-')+/	 *8 *
&Q --m||VZVcVc-d 0 --m<**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0%--/++m&9&9:>>EK!KK<[YM "&Gr+   )	r   r   ro   rm   r   r   r   r   r   F)r^   r_   r`   ra   r   r6   rC   rf   r   rY   rg   rh   ri   s   @r)   r   r     s^    =} =. #(.||. . 	.
  . 
. .r+   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                  4S jjrSrU =r$ )PegasusDecoderLayeriW  rs   rt   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)rm   rn   ro   rp   rr   rs   rt   )ro   rp   rs   rt   )r5   r6   r   rm   r   r   decoder_attention_headsr   r   ro   r
   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr{   decoder_ffn_dimr   r   r   )r7   rs   rt   r8   s      r)   r6   PegasusDecoderLayer.__init__X  s6   263N3NOnn44,,
 ~~#F$>$>?"(";";$&LL$@!5f6Q6QRNN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r+   r   r   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   r2   c           	          UnU R                  U5      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SnUb`  UnU R                  U5      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nU R                  U5      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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   r   ro   r   r   r   r   r   r   r   r   )r7   r   r   r   r   r   r   r   r   r   r   r   self_attn_weightscross_attn_weightsr   s                  r)   rY   PegasusDecoderLayer.forwardw  s   D !11-@ <@>>'))+/) <J <
8. --m||VZVcVc-d 0 " ,$H 88GM AE@Q@Q+!65 :-"3 AR A=M~ MM11-<<Z^ZgZg1hM$4M !--m<**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0 "+=>>G((Gr+   )r   r   ro   rm   r   r   r   r   r   r   r   r4   )	NNNNNNFTN)r^   r_   r`   ra   r   r   rc   r6   rC   rf   r   r   rY   rg   rh   ri   s   @r)   r   r   W  s
   =} =# = =D 268<9=26=A*.,1$(15T||T !.T  (5	T
 !) 6T "%,,/T %-U\\$:T !T $D>T D>T !.T 
T Tr+   r   c                       \ rS rSr\rSrSrS r SS\	\
R                  S4   S\
R                  S\
R                  S	\S
\4
S jjr\S\
R                  S\S\S\
R"                  S\
R                  S\4S j5       rSrg)PegasusPreTrainedModeli  modelTc                 @   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[        5      (       a  UR                  5         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std      ?)rs   init_stdr   r   r{   r>   datanormal_rq   zero_r-   rP   	Embeddingr1   r   fill_)r7   moduler   s      r)   _init_weights$PegasusPreTrainedModel._init_weights  s"   kk""fbii((MM&&CS&9{{&  &&( ' DEE!--MM&&CS&9!!-""6#5#56<<> .--MM$$S)KK""$ .r+   r   r   input_tensorr   past_key_valuesr   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$ )Nflash_attention_2r   flex_attentionr   Fsdpa)inputs_embedsrS   is_trainingr   r"   )sequence_lengthtarget_lengthr<   r   
batch_size)cudaxpunpu)rs   r   anyr   rC   rf   r   get_seq_lengthis_compileabler   _ignore_causal_mask_sdpar   r<   r$   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrV   typer   r   _unmask_unattended)r7   r   r   r   r   r   past_seen_tokensusing_compilable_cacher<   r   r   causal_mask	min_dtypes                r)   _update_causal_mask*PegasusPreTrainedModel._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r+   r   r   r<   r   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.
N   )
fill_valuer<   rV   r   )diagonalrV   r"   r   )rJ   rC   r   r   fullrV   triurW   r   expandr%   r$   tomasked_fill)r   r   r   r<   r   r   kwargsr  r  mask_lengthpadding_masks              r)   r  LPegasusPreTrainedModel._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 r+    Nr   )r^   r_   r`   ra   r   config_classbase_model_prefixsupports_gradient_checkpointingr   r   rC   rf   r   r   r	  staticmethodrc   r<   r  rg   r  r+   r)   r   r     s     L&*#%. #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r+   r   c                      ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S\
4S jrS\R                  4S	 jr       SS
 jrSrU =r$ )PegasusEncoderib  z
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`PegasusEncoderLayer`].

Args:
    config: PegasusConfig
    embed_tokens (nn.Embedding): output embedding
rs   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U l        Ub  X l        O0[        R                   " UR"                  X0R                  5      U l        [%        UR                  UU R                  5      U l        [        R(                  " [+        UR,                  5       Vs/ s H  n[/        U5      PM     sn5      U l        [        R2                  " UR
                  5      U l        SU l        U R9                  5         g s  snf )Nr   F)r5   r6   ro   encoder_layerdrop	layerdropr   r   r1   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtembed_scaler   r   r   
vocab_sizer-   embed_positions
ModuleListrA   encoder_layersr   layersr   
layer_normgradient_checkpointing	post_init)r7   rs   r   rm   r   r8   s        r)   r6   PegasusEncoder.__init__l  s    ~~11NN	!..$*$B$B!393I3I499Y/s# , "V->->	K[K[ \DC** 

 mm%PVPePeJf$gJfQ%8%@Jf$gh,,v~~6&+# %hs   E4new_num_position_embeddingsc                 \   [         R                  SU S35        XR                  l        [	        U R                  R                  U R                  R
                  U R                  5      U l        U R                  R                  5         U R                  R                  U R                  5        g  
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
config.max_position_embeddings`.

Arguments:
    new_num_position_embeddings (`int`):
        The number of new position embeddings. If position embeddings are learned, increasing the size will add
        newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
        position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
        add correct vectors at the end following the position encoding algorithm, whereas reducing the size
        will remove vectors from the end.
z(Setting `config.max_position_embeddings=z`...Nry   infors   r$  r-   r   r1   r+  rP   r  rV   r7   r3  s     r)   resize_position_embeddings)PegasusEncoder.resize_position_embeddings       	>?Z>[[_`a.I+CKK//KK 

 	))+,r+   r2   c                     U R                   $ z(
Returns the position embeddings matrix
r+  r7   s    r)   get_position_embeddings&PegasusEncoder.get_position_embeddings       ###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b  [	        S5      eUb7  U R                  X5        UR                  5       nUR                  SUS   5      nO"Ub  UR                  5       SS nO[	        S5      eUc  U R                  U5      U R                  -  nU R                  U5      n	XI-   n
[        R                  R                  XR                  U R                  S9n
Ub  [        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['        U R$                  5       H  u  pU(       a  X4-   nSnU R                  (       a(  [(        R*                  " / 5      nUU R,                  :  a  SnU(       a  SnO^U R.                  (       a8  U R                  (       a'  U R1                  UR2                  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 R5                  U
5      n
U(       a  X4-   nU(       d  [7        S XU4 5       5      $ [9        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 .FT)NN)r   r   r   c              3   .   #    U  H  oc  M  Uv   M     g 7fr4   r  .0vs     r)   	<genexpr>)PegasusEncoder.forward.<locals>.<genexpr>&  s     e$Sq$Ss   	last_hidden_stater   
attentions)rs   r   output_hidden_statesuse_return_dictr&   %warn_if_padding_and_no_attention_maskr   r   r   r)  r+  r   r   ro   r   r   r<   lenr.  	enumeraterC   randr#  r0  _gradient_checkpointing_func__call__r/  tupler   )r7   r   r   	head_maskr   r   rP  return_dictinput_shape	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r)   rY   PegasusEncoder.forward  s   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]  ]%>cdd"66yQ#..*K!r;r?;I&',,.s3KTUU  --i84;K;KKM((5	%1--m||VZVcVc-d %7H[H[\N30d  ~~"c$++&66 <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 6+.>>Ne]N$Seee+Vd
 	
r+   )
ro   r+  r)  r   r0  r/  r#  r.  r%  r1   r4   )NNNNNNN)r^   r_   r`   ra   rb   r   r   r   r   r6   rc   r:  rA  rY   rg   rh   ri   s   @r)   r  r  b  sh    } HR\\<R  8-c -0$ $ !C
 C
r+   r  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\4S	 jrS
\R                  4S jr             SS jrSrU =r$ )PegasusDecoderi,  z
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]

Args:
    config: PegasusConfig
    embed_tokens (nn.Embedding): output embedding
rs   r   c           
        > [         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U l        Ub  X l        O;[        R                   " UR"                  UR                  U R                  5      U l        [%        UR                  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        [        R2                  " UR                  5      U l        SU l        U R9                  5         g s  snf )Nr   )rt   F)r5   r6   ro   decoder_layerdropr#  r   r1   r$  max_target_positionsr&  r'  r(  r   r)  r   r   r   r*  r-   r+  r,  rA   decoder_layersr   r.  r   r/  r0  r1  )r7   rs   r   ir8   s       r)   r6   PegasusDecoder.__init__5  s    ~~11!..$*$B$B!8>8N8N499V^^4TW# , "V->->PTP`P` aDC**NN 

 mmW\]c]r]rWs$tWsRS%8%MWs$tu,,v~~6&+# %us   )Fc                     U R                   $ r4   r   r@  s    r)   get_input_embeddings#PegasusDecoder.get_input_embeddingsN  s       r+   c                     Xl         g r4   rn  r7   values     r)   set_input_embeddings#PegasusDecoder.set_input_embeddingsQ  s    !r+   r3  c                 \   [         R                  SU S35        XR                  l        [	        U R                  R                  U R                  R
                  U R                  5      U l        U R                  R                  5         U R                  R                  U R                  5        gr5  r7  r9  s     r)   r:  )PegasusDecoder.resize_position_embeddingsT  r<  r+   r2   c                     U R                   $ r>  r?  r@  s    r)   rA  &PegasusDecoder.get_position_embeddingsl  rC  r+   c                 F	   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XR                  -  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[(        R0                  " UUUR,                  S	9n[        U[         5      (       a  UR2                  OUnU R5                  UUUUU
5      nUb  Ub  [7        XHR8                  US
9nU R;                  UU4UUS9nUU-   n[<        R>                  RA                  UU R@                  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[C        XV/SS/5       Hn  u  nnUc  M  UR%                  5       S   [E        U RF                  5      :w  d  M7  [        SU S[E        U RF                  5       SUR%                  5       S    S35      e   [I        U RF                  5       H  u  nnU(       a  UU4-  nU R                  (       a(  [(        RJ                  " / 5      nUU RL                  :  a  ML  U R
                  (       aG  U R                  (       a6  U RO                  URP                  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 RS                  U5      nU(       a  UU4-  nU	(       a  UOSn!U(       a  URU                  5       n!U(       d  [W        S UU!UUU4 5       5      $ [Y        UU!UUUS9$ )ax  
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 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   )rT   r   r  rY  cross_attn_head_maskzThe `z` should be specified for rE  rF  )	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r4   r  rH  s     r)   rK  )PegasusDecoder.forward.<locals>.<genexpr>[  s      mA ms   	)rN  r   r   rO  cross_attentions)-rs   r   rP  r   rQ  r0  r   ry   rz   r&   r   r$   r   r)  r   r   r   from_legacy_cacher   r   rC   rW   rV   r   onesr   r	  r   r<   r+  r   r   ro   ziprS  r.  rT  rU  r#  rV  rW  r/  to_legacy_cacherX  r   )"r7   r   r   r   r   rY  r{  r   r   r   r   rP  rZ  r   return_legacy_cacher   
seq_lengthrS   mask_seq_lengthself_attn_cacher  	positionsr   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cache	attn_mask	mask_namer_  decoder_layerrb  rc  
next_caches"                                     r)   rY   PegasusDecoder.forwardr  s   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 &(8(88 $Z??"&\
 2CCOTO!.!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !*B*D*D4zAO"ZZ
OML`L`aN /+>?? 00  	
 ..
 !,1G1S%?&(;(;Z&"
 ((*j)ACYhv(w	%	1--mt||VZVcVc-d #7BD0d&7<Q<]rdh! %((IKYoKp$q Iy$>>#A&#dkk*::$	{*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-=,??(_ #9b 6  -!11+4'$
(88:J '5FXlm  
 9+&+%1
 	
r+   )
ro   r+  r)  r   r0  r/  r#  r.  ri  r1   r4   )NNNNNNNNNNNNN)r^   r_   r`   ra   rb   r   r   r   r   r6   ro  rt  rc   r:  rA  rY   rg   rh   ri   s   @r)   rf  rf  ,  s    } HR\\<R  2!"-c -0$ $ "#!!t
 t
r+   rf  c            &       h  ^  \ 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
\4S jrS\\R                     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\\   S\\   S\\   S\\   S\\R(                     S\\\4   4"S jj5       rSrU =r$ )!PegasusModelii  encoder.embed_tokens.weightdecoder.embed_tokens.weightrs   c                 &  > [         TU ]  U5        UR                  UR                  p2[        R
                  " X1R                  U5      U l        [        XR                  5      U l	        [        XR                  5      U l        U R                  5         g r4   )r5   r6   r   r*  r   r   r   sharedr  encoderrf  decoderr1  )r7   rs   r1   r*  r8   s       r)   r6   PegasusModel.__init__m  se     "("5"5v7H7HZll:~~{K%fkk:%fkk: 	r+   c                     U R                   $ r4   )r  r@  s    r)   ro  !PegasusModel.get_input_embeddingsy  s    {{r+   c                 |    Xl         U R                   U R                  l        U R                   U R                  l        g r4   )r  r  r   r  rr  s     r)   rt  !PegasusModel.set_input_embeddings|  s'    $(KK!$(KK!r+   c                     U R                   $ r4   )r  r@  s    r)   get_encoderPegasusModel.get_encoder      ||r+   c                     U R                   $ r4   r  r@  s    r)   get_decoderPegasusModel.get_decoder  r  r+   r3  c                     XR                   l        U R                  R                  U5        U R                  R                  U5        gr6  N)rs   r$  r  r:  r  r9  s     r)   r:  'PegasusModel.resize_position_embeddings  s5     /J+//0KL//0KLr+   r2   c                 j    U R                   R                  5       U R                  R                  5       4$ r>  )r  rA  r  r@  s    r)   rA  $PegasusModel.get_position_embeddings  s)     4468\8\8^__r+   r   r   decoder_input_idsdecoder_attention_maskrY  decoder_head_maskr{  encoder_outputsr   r   decoder_inputs_embedsr   r   rP  rZ  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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$ )	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)

    Pegasus uses the `pad_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`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
    1]`:

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

Example:

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
>>> model = PegasusModel.from_pretrained("google/pegasus-large")

>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 4, 1024]
```N)r   r   rY  r   r   rP  rZ  r   r   r;   rM  r   r   r   r   rY  r{  r   r   r   r   rP  rZ  r   )rN  r   decoder_hidden_statesdecoder_attentionsr~  encoder_last_hidden_stater   encoder_attentions)rs   r   rP  r   rQ  r  r   r   rS  r  r   rN  r   r   rO  r~  )r7   r   r   r  r  rY  r  r{  r  r   r   r  r   r   rP  rZ  r   decoder_outputss                     r)   rY   PegasusModel.forward  s   v 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	
 		
r+   )r  r  r  )NNNNNNNNNNNNNNNN)r^   r_   r`   ra   _tied_weights_keysr   r6   ro  rt  r  r  rc   r:  r   r   r   rA  r   r   rC   rf   rE   r   r   r   rY   rg   rh   ri   s   @r)   r  r  i  s   79VW
} 
0
Mc M"`r||)< `  -115489=,0487;>B>B048<$(,0/3&*15#p
ELL)p
 !.p
 $ELL1	p

 !) 6p
 ELL)p
 $ELL1p
 'u||4p
 "%(9(9":;p
 "%(9(9":;p
  -p
  (5p
 D>p
 $D>p
 'tnp
  d^!p
" !.#p
$ 
u((	)%p
 p
r+   r  zY
    The PEGASUS Model with a language modeling head. Can be used for summarization.
    )custom_introc            (         ^  \ rS rSrSrS/r/ SQ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\4S jrS\\R                     4S jr\                 S+S\\R2                     S\\R2                     S\\R2                     S\\R2                     S\\R2                     S\\R2                     S\\R2                     S\\\R4                        S\\\R4                        S\\R2                     S\\R2                     S \\R2                     S!\\   S"\\   S#\\   S$\\   S%\\R2                     S\\\4   4$S& jj5       rS \R2                  4S' jr\S( 5       r S)r!U =r"$ ),PegasusForConditionalGenerationi  r   final_logits_bias)r  r  lm_head.weightrs   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   Frv   )r5   r6   r  r   register_bufferrC   zerosr  num_embeddingsr   r{   r   lm_headr1  r   s     r)   r6   (PegasusForConditionalGeneration.__init__  s     !&)
0%++q$**BSBSBbBb>c2deyy1B1B1Q1QX]^ 	r+   c                 6    U R                   R                  5       $ r4   )r   r  r@  s    r)   r  +PegasusForConditionalGeneration.get_encoder%      zz%%''r+   c                 6    U R                   R                  5       $ r4   )r   r  r@  s    r)   r  +PegasusForConditionalGeneration.get_decoder(  r  r+   Nnew_num_tokenspad_to_multiple_ofmean_resizingr2   c                 x   > [         TU ]  XU5      nU R                  UR                  R                  S   5        U$ )Nr   )r5   resize_token_embeddings_resize_final_logits_biasr>   r$   )r7   r  r  r  new_embeddingsr8   s        r)   r  7PegasusForConditionalGeneration.resize_token_embeddings+  s<     8]jk&&~'<'<'B'B1'EFr+   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$   rC   r  rV   catr  )r7   r  old_num_tokensnew_bias
extra_biass        r)   r  9PegasusForConditionalGeneration._resize_final_logits_bias2  s    //55b9+--a..@AHa)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r+   c                     U R                   $ r4   r  r@  s    r)   get_output_embeddings5PegasusForConditionalGeneration.get_output_embeddings;  r  r+   c                     Xl         g r4   r  r7   r  s     r)   set_output_embeddings5PegasusForConditionalGeneration.set_output_embeddings>      %r+   r3  c                     XR                   l        U R                  R                  R	                  U5        U R                  R
                  R	                  U5        gr  )rs   r$  r   r  r:  r  r9  s     r)   r:  :PegasusForConditionalGeneration.resize_position_embeddingsA  sA     /J+

556QR

556QRr+   c                     U R                   R                  R                  5       U R                   R                  R                  5       4$ r>  )r   r  rA  r  r@  s    r)   rA  7PegasusForConditionalGeneration.get_position_embeddingsR  s5     

""::<djj>P>P>h>h>jkkr+   r   r   r  r  rY  r  r{  r  r   r   r  labelsr   r   rP  rZ  r   c                    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      U R                  -   nSnUbF  [        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)

    Pegasus uses the `pad_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`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
    Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
    be used by default.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
    Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
    1]`:

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

Example Summarization:

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

>>> model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-xsum")

>>> 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"])
>>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"California's largest electricity provider has turned off power to hundreds of thousands of customers."
```
NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r   r  r  r  rY  r  r{  r   r   r  r   r   rP  rZ  r   r   r"   r   )	losslogitsr   r  r  r~  r  r   r  )rs   rQ  ry   warningr*   r   r    r   r  r  r   r   r*  r   r   r  r  r~  r  r   r  )r7   r   r   r  r  rY  r  r{  r  r   r   r  r  r   r   rP  rZ  r   r   	lm_logitsmasked_lm_lossloss_fctoutputs                          r)   rY   'PegasusForConditionalGeneration.forwardX  s   H &1%<k$++B]B]klI (-B-J$6KK44dkk6X6X%! **)/+#9/!5+'"7/!5#)!  
$ LL,t/E/EE	')H%innR9O9O&PRXR]R]^`RabN\GABK/F3A3M^%.YSYY#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r+   c                 j    [        XR                  R                  U R                  R                  5      $ r4   )r*   rs   r   r    )r7   r  s     r)   %prepare_decoder_input_ids_from_labelsEPegasusForConditionalGeneration.prepare_decoder_input_ids_from_labels  s#    !&++*B*BDKKDfDfggr+   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r]   index_selectr  rV   rI  
past_statebeam_idxs     r)   rK  APegasusForConditionalGeneration._reorder_cache.<locals>.<genexpr>  s1     rcqU_--aZ=N=N1OPPcq   7:r;   rX  r   r  reordered_past
layer_pasts    `  r)   _reorder_cache.PegasusForConditionalGeneration._reorder_cache  sO    )JrcmnpopcqrrQR.! N * r+   r  r   )NT)NNNNNNNNNNNNNNNNN)#r^   r_   r`   ra   r  _keys_to_ignore_on_load_missingr  r   r6   r  r  rc   r   r   r   r   r  r  r  r  r:  r   rA  r   rC   rf   rE   r   r   rY   r  r  r  rg   rh   ri   s   @r)   r  r    s~     ':&;#i} (( dh!7?}\`	 < < <&Sc S"lr||)< l  -115489=,0487;>B>B048<)-$(,0/3&*15%u
ELL)u
 !.u
 $ELL1	u

 !) 6u
 ELL)u
 $ELL1u
 'u||4u
 "%(9(9":;u
 "%(9(9":;u
  -u
  (5u
 &u
 D>u
 $D>u
  'tn!u
" d^#u
$ !.%u
& 
uo%	&'u
 u
nhELL h  r+   r  c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )PegasusDecoderWrapperi  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 r4   )r5   r6   rf  r  r   s     r)   r6   PegasusDecoderWrapper.__init__  s     %f-r+   c                 &    U R                   " U0 UD6$ r4   r  )r7   argsr  s      r)   rY   PegasusDecoderWrapper.forward  s    ||T,V,,r+   r  )	r^   r_   r`   ra   rb   r6   rY   rg   rh   ri   s   @r)   r  r    s    
.- -r+   r  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
\R                  4S jrS\4S j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 $ ) PegasusForCausalLMi  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 )NTFrv   )copydeepcopyrp   is_encoder_decoderr5   r6   r  r   r   r{   hidden_sizer*  r  r1  r   s     r)   r6   PegasusForCausalLM.__init__  sf    v& $)! *62
yy!3!3V5F5FUS 	r+   c                 B    U R                   R                  R                  $ r4   r   r  r   r@  s    r)   ro  'PegasusForCausalLM.get_input_embeddings  s    zz!!...r+   c                 8    XR                   R                  l        g r4   r  rr  s     r)   rt  'PegasusForCausalLM.set_input_embeddings   s    */

'r+   c                     U R                   $ r4   r  r@  s    r)   r  (PegasusForCausalLM.get_output_embeddings  r  r+   c                     Xl         g r4   r  r  s     r)   r  (PegasusForCausalLM.set_output_embeddings  r  r+   c                 $    XR                   l        g r4   r   r  )r7   r  s     r)   set_decoderPegasusForCausalLM.set_decoder	  s    $

r+   c                 .    U R                   R                  $ r4   r  r@  s    r)   r  PegasusForCausalLM.get_decoder  s    zz!!!r+   r2   c                 J    U R                   R                  R                  5       $ r>  )r   r  rA  r@  s    r)   rA  *PegasusForCausalLM.get_position_embeddings  s     zz!!99;;r+   r3  c                 n    XR                   l        U R                  R                  R	                  U5        gr  )rs   r$  r   r  r:  r9  s     r)   r:  -PegasusForCausalLM.resize_position_embeddings  s(     /J+

556QRr+   r   r   r   r   rY  r{  r   r   r  r   r   rP  rZ  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, PegasusForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
>>> model = PegasusForCausalLM.from_pretrained("google/pegasus-large", 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   rO  r~  )rs   r   rP  rQ  r   r  r  r  rV   r   r   r*  r   r   r   rO  r~  )r7   r   r   r   r   rY  r{  r   r   r  r   r   rP  rZ  r   r   r  r  r  r  s                       r)   rY   PegasusForCausalLM.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
 	
r+   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r]   r  r  s     r)   rK  4PegasusForCausalLM._reorder_cache.<locals>.<genexpr>  s1     ncmU_--aZ=N=N1OPPcmr  r  r  s    `  r)   r  !PegasusForCausalLM._reorder_cache  s8    )Jncmnn N * r+   r   )NNNNNNNNNNNNNN)!r^   r_   r`   ra   r  r6   ro  rt  r  r  r  r  r   r   rA  rc   r:  r   r   rC   
LongTensorrf   rE   r   r   r   r   r   rY   r  r  rg   rh   ri   s   @r)   r
  r
    s   *+
/0&%"< <Sc S   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  r+   r
  )r
  r  r  r   )Arb   r  r'  typingr   r   r   r   numpyr?   rC   torch.utils.checkpointr   torch.nnr   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   r   configuration_pegasusr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerr^   ry   rf   rc   r*   r   r-   Modulerk   r   r   r   r   r  rf  r  r  r  r
  __all__r  r+   r)   <module>r<     s      / /     % ! 5 )  .  1  !!;J 
		H	%%,, c [^ "-2<< -FZBryy ZBz %&67 A")) AJt")) tn P_ P PfG
+ G
Tz
+ z
z	 e
) e
 e
P 
E&<o E
ER-2 -Y/ Yx nr+   