
    i                     j   d Z ddlZddlZddlmZ ddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4  e-jj                  e6      Z7dejp                  de9de9fdZ: G d dejv                        Z<	 	 d<dejz                  dejp                  dejp                  dejp                  d ejp                  dz  d!e>dz  d"e>d#e'e)   fd$Z? G d% d&ejz                        Z@ G d' d(e      ZA G d) d*e      ZBe* G d+ d,e%             ZC G d- d.eC      ZD G d/ d0eC      ZEe* G d1 d2eC             ZF e*d34       G d5 d6eCe             ZG G d7 d8eC      ZH G d9 d:eCe      ZIg d;ZJy)=zPyTorch PEGASUS model.    N)Callable)nn)CrossEntropyLoss   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torchdynamo_compilinglogging)merge_with_config_defaults)OutputRecordercapture_outputs   )PegasusConfig	input_idspad_token_iddecoder_start_token_idc                     | j                  | j                        }| ddddf   j                         |ddddf<   ||dddf<   |t        d      |j	                  |dk(  |       |S )z1
    Shift input ids one token to the right.
    Nr!   r   z1self.model.config.pad_token_id has to be defined.i)	new_zerosshapeclone
ValueErrormasked_fill_)r#   r$   r%   shifted_input_idss       }/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/pegasus/modeling_pegasus.pyshift_tokens_rightr/   9   s}     "++IOO<(CRC0668ae4adLMM""#4#<lK    c            
            e Zd ZdZddedededz  ddf fdZd Z ej                         	 dd	ej                  d
edej                  dz  dej                  f fd       Z xZS )$PegasusSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.Nnum_positionsembedding_dimpadding_idxreturnc                 *    t         |   ||d       y )NT)_freeze)super__init__)selfr3   r4   r5   	__class__s       r.   r:   z-PegasusSinusoidalPositionalEmbedding.__init__M   s    tDr0   c                    | j                   j                  \  }}t        j                  t	        |      D cg c];  }t	        |      D cg c]$  }|t        j
                  dd|dz  z  |z        z  & c}= c}}      }t        j                  ||| j                   j                  d      }|dz  dk(  r|dz  n|dz  dz   }t        j                  t        j                  |dddddf               |ddd|f<   t        j                  t        j                  |dddddf               |dd|df<   |S c c}w c c}}w )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)weightr)   nparrayrangepowertorchemptyr?   FloatTensorsincos)r;   n_posdimposjposition_encoutsentinels           r.   create_weightz2PegasusSinusoidalPositionalEmbedding.create_weightP   s   
 [[&&
sxxX]^cXdeQTsLAcBHHUAaL3$677Le
 kk%DKK,=,=US"Qw!|3!8#(a"..rvvl1add76K/LMAqzM!--bff\!QTT'5J.KLAxyL
 Mes   D>
	)D92D>
9D>
input_ids_shapepast_key_values_lengthposition_idsc                     |F|dd \  }}t        j                  |||z   t         j                  | j                  j                        }t
        |   |      S )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr>   )r?   device)rF   arangelongrA   rW   r9   forward)r;   rS   rT   rU   bszseq_lenr<   s         r.   rZ   z,PegasusSinusoidalPositionalEmbedding.forward_   s]    
 *2A.LC <<&(>(HPUPZPZcgcncncucuL w|,,r0   N)r   N)__name__
__module____qualname____doc__intr:   rR   rF   no_gradSizeTensorrZ   __classcell__r<   s   @r.   r2   r2   J   s    NEc E# ECRVJ Ebf E U]]_pt	-$zz	-CF	-Z_ZfZfimZm	-		- 	-r0   r2   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr'         r>   r   rL   ptrainingr!   )
sizerF   matmul	transposer   
functionalsoftmaxrn   ru   
contiguous)
rh   ri   rj   rk   rl   rm   rn   ro   attn_weightsattn_outputs
             r.   eager_attention_forwardr~   m   s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r0   c                       e Zd ZdZ	 	 	 	 	 	 ddedededededed	edz  d
edz  f fdZ	 	 	 dde	j                  de	j                  dz  dedz  de	j                  dz  dee   dee	j                  e	j                  dz  f   fdZ xZS )PegasusAttentionz=Multi-headed attention from 'Attention Is All You Need' paperN	embed_dim	num_headsrn   
is_decoderbias	is_causalconfig	layer_idxc	                    t         	|           || _        || _        || _        ||z  | _        || _        | j
                  |z  | j                  k7  rt        d| j                   d| d      | j
                  dz  | _        || _	        || _
        || _        |9| j                  r-t        j                  d| j                  j                   d       t!        j"                  |||      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).rq   zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.r   )r9   r:   r   r   rn   head_dimr   r+   rm   r   r   r   loggerwarning_oncer<   r^   r   Lineark_projv_projq_projout_proj)
r;   r   r   rn   r   r   r   r   r   r<   s
            r.   r:   zPegasusAttention.__init__   s$    	""!Y.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	94@ii	94@ii	94@		)YTBr0   hidden_stateskey_value_statespast_key_valuesrl   ro   r6   c                    |du}|j                   dd }g |d| j                  }| j                  |      j                  |      j	                  dd      }	d}
|St        |t              rA|j                  j                  | j                        }
|r|j                  }n|j                  }n|}|r|n|}|rK|I|
rGj                  | j                     j                  }|j                  | j                     j                  }n| j                  |      }| j!                  |      }g |j                   dd d| j                  }|j                  |      j	                  dd      }|j                  |      j	                  dd      }|Kj#                  ||| j                        \  }}|r)t        |t              rd|j                  | j                  <   t%        j&                  | j(                  j*                  t,              } || |	|||f| j.                  sdn| j0                  | j2                  d|\  }} |j4                  g |d j7                         }| j9                  |      }||fS )	z#Input shape: Batch x Time x ChannelNr'   r!   r>   FT        )rn   rm   )r)   r   r   viewrx   
isinstancer   
is_updatedgetr   cross_attention_cacheself_attention_cachelayerskeysvaluesr   r   updater   get_interfacer   _attn_implementationr~   ru   rn   rm   reshaper{   r   )r;   r   r   r   rl   ro   is_cross_attentioninput_shapehidden_shapequery_statesr   curr_past_key_valuescurrent_states
key_statesvalue_stateskv_shapeattention_interfacer}   r|   s                      r.   rZ   zPegasusAttention.forward   sd    .T9 $))#2.88b8$--8 {{=166|DNNqRST
&/+>?,77;;DNNK
%+:+P+P(+:+O+O('6$-?)]/"=*-44T^^DIIJ/66t~~FMML^4J;;~6LF--cr2FBFFH#2<<QBJ',,X6@@AFL*+?+F+FzS_aeaoao+p(
L%*_FY*ZAEO..t~~>(?(M(MKK,,.E)
 %8	%
  $}}C$,,LL	%
 	%
!\ *k));;;;FFHmmK0L((r0   )r   FTFNNNNN)r^   r_   r`   ra   rb   floatboolr"   r:   rF   re   r	   r   r   tuplerZ   rf   rg   s   @r.   r   r      s   G  '+ $%C%C %C 	%C
 %C %C %C $%C :%CT 15(,.2H)||H)  ,,-H) 	H)
 t+H) -.H) 
u||U\\D00	1H)r0   r   c                   ~     e Zd Zdef fdZdej                  dej                  dee   dej                  fdZ	 xZ
S )PegasusEncoderLayerr   c                 h   t         |           |j                  | _        t	        | j                  |j
                  |j                  |      | _        t        j                  | j                        | _
        |j                  | _        t        |j                     | _        |j                  | _        t        j                   | j                  |j"                        | _        t        j                   |j"                  | j                        | _        t        j                  | j                        | _        y )N)r   r   rn   r   )r9   r:   d_modelr   r   encoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrn   r   activation_functionactivation_fnactivation_dropoutr   encoder_ffn_dimfc1fc2final_layer_normr;   r   r<   s     r.   r:   zPegasusEncoderLayer.__init__  s    )nn44,,	
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r0   r   rl   ro   r6   c                     |}| j                  |      } | j                  d||d|\  }}t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|j                  t        j                  k(  rEt        j                  |j                        j                  dz
  }t        j                   || |      }|S )a>  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
        )r   rl   rs   i  )minmax )r   r   r   ry   rn   ru   r   r   r   r   r   r?   rF   float16finfor   clamp)r;   r   rl   ro   residual_clamp_values          r.   rZ   zPegasusEncoderLayer.forward  sT    !11-@)4>> 
')
 
q
 --mt||VZVcVc-d =0 --m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0%--/++m&9&9:>>EK!KKK<[YMr0   )r^   r_   r`   r"   r:   rF   re   r   r   rZ   rf   rg   s   @r.   r   r      sL    =} =$"||" " +,	"
 
"r0   r   c                        e Zd Zddededz  f fdZ	 	 	 	 	 ddej                  dej                  dz  dej                  dz  dej                  dz  d	edz  d
e	dz  de
e   dej                  fdZ xZS )PegasusDecoderLayerNr   r   c           	         t         |           |j                  | _        t	        | j                  |j
                  |j                  dd||      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                        | _        t	        | j                  |j
                  |j                  d||      | _        t        j                  | j                        | _        t        j$                  | j                  |j&                        | _        t        j$                  |j&                  | j                        | _        t        j                  | j                        | _        y )NT)r   r   rn   r   r   r   r   )rn   r   r   r   )r9   r:   r   r   r   decoder_attention_headsr   r   rn   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr   decoder_ffn_dimr   r   r   )r;   r   r   r<   s      r.   r:   zPegasusDecoderLayer.__init__:  s    )nn44,,
 ~~#F$>$>?"(";";$&LL$@!,NN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r0   r   rl   encoder_hidden_statesencoder_attention_maskr   	use_cachero   r6   c                    |}| j                  |      } | j                  d|||d|\  }}	t        j                  j	                  || j                  | j
                        }||z   }|h|}| j                  |      } | j                  d||||d|\  }}	t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            past_key_values (`Cache`): cached past key and value projection states
        )r   r   rl   rs   )r   r   rl   r   r   )r   r   r   ry   rn   ru   r   r   r   r   r   r   r   )
r;   r   rl   r   r   r   r   ro   r   r   s
             r.   rZ   zPegasusDecoderLayer.forwardY  s   * !11-@ *4>> 
'+)
 	
q --mt||VZVcVc-d =0 !,$H 88GM0t00  +!65 /	 
  M1 MM11-4<<Z^ZgZg1hM$}4M !--m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0r0   r]   )NNNNT)r^   r_   r`   r"   rb   r:   rF   re   r	   r   r   r   rZ   rf   rg   s   @r.   r   r   9  s    =} =t =D /3596:(,!%:||: t+:  %||d2	:
 !&t 3: : $;: +,: 
:r0   r   c                   j     e Zd ZU eed<   dZdZdZdZdZ	dZ
 ej                          fd       Z xZS )PegasusPreTrainedModelr   modelTc                    t         |   |       t        |t              r/t	        j
                  |j                  |j                                y t        |t              r t	        j                  |j                         y y r]   )r9   _init_weightsr   r2   initcopy_rA   rR   PegasusForConditionalGenerationzeros_final_logits_bias)r;   rh   r<   s     r.   r   z$PegasusPreTrainedModel._init_weights  sY    f%fBCJJv}}f&:&:&<= ?@KK001 Ar0   )r^   r_   r`   r"   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphrF   rc   r   rf   rg   s   @r.   r   r     sF    &*#N!U]]_2 2r0   r   c                        e Zd ZdZeedZdef fdZde	fdZ
dej                  fdZeee	 	 	 dd	ee   defd
                     Z xZS )PegasusEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`PegasusEncoderLayer`].

    Args:
        config: PegasusConfig
        embed_tokens (nn.Embedding): output embedding
    )r   
attentionsr   c                    t         |   |       |j                  | _        |j                  | _        |j
                  }|j                  | _        |j                  | _	        |j                  rt        j                  |      nd| _        t        j                  |j                   || j                        | _        t%        |j                  || j                        | _        t        j(                  t+        |j,                        D cg c]  }t/        |       c}      | _        t        j2                  |j
                        | _        d| _        | j9                          y c c}w )N      ?F)r9   r:   rn   encoder_layerdrop	layerdropr   r$   r5   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtembed_scaler   	Embedding
vocab_sizeembed_tokensr2   embed_positions
ModuleListrD   encoder_layersr   r   r   
layer_normgradient_checkpointing	post_init)r;   r   r   r   r<   s       r.   r:   zPegasusEncoder.__init__  s    ~~11NN	!..$*$B$B!393I3I499Y/sLL):):ItGWGWXC** 

 mm%PVPePeJf$gQ%8%@$gh,,v~~6&+# %hs   Enew_num_position_embeddingsc                    t         j                  d| d       || j                  _        t	        | j                  j                  | j                  j
                  | j                        | _        t        j                  | j                  j                  | j                  j                                | j                  j                  | j                         y  
        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r   infor   r   r2   r   r5   r   r   r   rA   rR   torW   r;   r   s     r.   resize_position_embeddingsz)PegasusEncoder.resize_position_embeddings       	>?Z>[[_`a.I+CKK//KK 

 	

4''..0D0D0R0R0TU,r0   r6   c                     | j                   S z8
        Returns the position embeddings matrix
        r   r;   s    r.   get_position_embeddingsz&PegasusEncoder.get_position_embeddings       ###r0   ro   c                 F   |d u |d uz  rt        d      || j                  |      | j                  z  }|j                  d d }| j	                  |      }||z   }t
        j                  j                  || j                  | j                        }t        | j                  ||      }t        | j                        D ]F  \  }}	d}
| j                  r&t        j                  g       }|| j                  k  rd}
|
r= |	||fi |}H | j!                  |      }t#        |      S )Nz:You must specify exactly one of input_ids or inputs_embedsr'   rs   )r   inputs_embedsrl   FT)last_hidden_state)r+   r   r   r)   r   r   ry   rn   ru   r   r   	enumerater   rF   randr   r   r   )r;   r#   rl   r  ro   r   	embed_posr   idxencoder_layerto_dropdropout_probabilitys               r.   rZ   zPegasusEncoder.forward  s3    -t";<YZZ  --i84;K;KKM#))#2.((5	%	1--mt||VZVcVc-d2;;')
 #,DKK"8 	CG}}&+jjn#&7"G -!"! !	 6+
 	
r0   r   )r^   r_   r`   ra   r   r   _can_record_outputsr"   r:   rb   r  r   r   r  r   r    r   r   r   r   rZ   rf   rg   s   @r.   r   r     s     -&
} 2-c -0$ $   	-

 +,-
 
-
    -
r0   r   c                        e Zd ZdZe eedd       eedd      dZdef fdZ	d	e
fd
Zdej                  fdZeee	 	 	 	 	 	 	 ddee   defd                     Z xZS )PegasusDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]

    Args:
        config: PegasusConfig
        embed_tokens (nn.Embedding): output embedding
    r!   r   )index
layer_namer   )r   r   cross_attentionsr   c           	         t         |   |       |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  rt        j                  |j                        nd| _        t        j                  |j                   |j                  | j                        | _        t%        |j                  |j                  | j                        | _        t        j(                  t+        |j,                        D cg c]  }t/        ||       c}      | _        t        j2                  |j                        | _        d| _        | j9                          y c c}w )Nr   )r   F)r9   r:   rn   decoder_layerdropr   r$   r5   r   max_target_positionsr   r   r   r   r   r   r   r   r   r2   r   r   rD   decoder_layersr   r   r   r   r   r   )r;   r   ir<   s      r.   r:   zPegasusDecoder.__init__1  s    ~~11!..$*$B$B!8>8N8N499V^^4TWLL):):FNNDL\L\]C**NN 

 mmW\]c]r]rWs$tRS%81%M$tu,,v~~6&+# %us   E3r   c                    t         j                  d| d       || j                  _        t	        | j                  j                  | j                  j
                  | j                        | _        t        j                  | j                  j                  | j                  j                                | j                  j                  | j                         yr  r  r  s     r.   r  z)PegasusDecoder.resize_position_embeddingsG  r  r0   r6   c                     | j                   S r
  r  r  s    r.   r  z&PegasusDecoder.get_position_embeddings_  r  r0   ro   c                 t   |d u |d uz  rt        d      || j                  |      }|| j                  z  }|rd|b|| j                  j                  r4t        t        | j                        t        | j                              nt        | j                        }|j                         d d \  }	}
||j                         nd}t        j                  |
|j                        |z   }|1t               s'||
z   }t        j                  |	||j                        }t        |t
              r|j                  n|}t!        | j                  |||      }t#        | j                  |||      }| j%                  |	|
f||      }||z   }t&        j(                  j+                  || j*                  | j,                  	      }t/        | j0                        D ]E  \  }}| j,                  r%t        j2                  g       }|| j4                  k  r7 ||||f|||d
|}G | j7                  |      }t9        ||      S )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time)r   r'   r   rW   )r   r  rl   r   )r   r  rl   r   )rU   rs   )r   r   r   )r  r   )r+   r   r   r   is_encoder_decoderr   r
   rv   get_seq_lengthrF   rX   rW   r   onesr   r   r   r   r   r   ry   rn   ru   r  r   r  r   r   r   )r;   r#   rl   r   r   r   r  r   ro   
batch_size
seq_lengthrT   rU   mask_seq_lengthself_attn_cachecausal_mask	positionsr   r  decoder_layerr  s                        r.   rZ   zPegasusDecoder.forwarde  sQ    -t";<stt  --i8M &(8(88 0 )48V8V $L$DlZ^ZeZeFfg!5  "/!3!3!5cr!:
JETE`!?!?!Afg||J}7K7KLOee!*B*D4zAO"ZZ
OML`L`aN /+>? 00  	 );;')+	
 ";;;'1"7	"
 ((*j)ACYht(u	%	1--mt||VZVcVc-d"+DKK"8 	C}}&+jjn#&7)% (> /# M	" 68++
 	
r0   )NNNNNNN)r^   r_   r`   ra   r   r   r   r  r"   r:   rb   r  r   r   r  r   r    r   r   r   r   rZ   rf   rg   s   @r.   r  r  "  s     -$%5Q;W*+;1Q_`} ,-c -0$ $   "#S
 +,S
 
3S
    S
r0   r  c                       e Zd ZdddZdef fdZd Zd ZdefdZ	d	e
ej                     fd
Zee	 	 	 	 	 	 	 	 	 ddej"                  dz  dej"                  dz  dej"                  dz  dej"                  dz  de
ej$                     dz  dedz  dej"                  dz  dej"                  dz  dedz  dee   d	e
ez  fd              Z xZS )PegasusModelzshared.weight)zdecoder.embed_tokens.weightzencoder.embed_tokens.weightr   c                     t         |   |       |j                  |j                  }}t	        j
                  ||j                  |      | _        t        |      | _	        t        |      | _        | j                          y r]   )r9   r:   r$   r   r   r   r   sharedr   encoderr  decoderr   )r;   r   r5   r   r<   s       r.   r:   zPegasusModel.__init__  sa     "("5"5v7H7HZll:v~~{K%f-%f- 	r0   c                     | j                   S r]   )r5  r  s    r.   get_input_embeddingsz!PegasusModel.get_input_embeddings  s    {{r0   c                 ~    || _         | j                   | j                  _        | j                   | j                  _        y r]   )r5  r6  r   r7  r;   rk   s     r.   set_input_embeddingsz!PegasusModel.set_input_embeddings  s)    $(KK!$(KK!r0   r   c                     || j                   _        | j                  j                  |       | j                  j                  |       yr  N)r   r   r6  r  r7  r  s     r.   r  z'PegasusModel.resize_position_embeddings  s7     /J+//0KL//0KLr0   r6   c                 j    | j                   j                         | j                  j                         fS r
  )r6  r  r7  r  s    r.   r  z$PegasusModel.get_position_embeddings  s)     4468\8\8^__r0   Nr#   rl   decoder_input_idsdecoder_attention_maskencoder_outputsr   r  decoder_inputs_embedsr   ro   c
                    | | j                   d	|||d|
}nGt        |t              s7t        |d   t        |      dkD  r|d   ndt        |      dkD  r|d   nd      } | j                  d	|||d   ||||	d|
}t        |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                        S )
aE  
        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.

        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#   rl   r  r   r!   r>   )r  r   r   r#   rl   r   r   r   r  r   )r  r   decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentionsr   )r6  r   r   lenr7  r   r  r   r   r   r  )r;   r#   rl   r@  rA  rB  r   r  rC  r   ro   decoder_outputss               r.   rZ   zPegasusModel.forward  s   ` "*dll #-+ 	O O_=-"1!"4474H14Loa0RV14_1E1I?1-tO '$,, 	
'1"1!"4#1+/	
 	
 "-??+;;"1"?"?.99,==&5&G&G"1"?"?.99	
 		
r0   )	NNNNNNNNN)r^   r_   r`   _tied_weights_keysr"   r:   r9  r<  rb   r  r   r   r   r  r   r   rF   re   rH   r	   r   r   r   r   rZ   rf   rg   s   @r.   r3  r3    sZ    (7'6

} 
0
Mc M"`r||)< `  *..2156:;?(,-159!%R
<<$&R
 t+R
 !<<$.	R

 !&t 3R
 u001D8R
 R
 ||d*R
  %||d2R
 $;R
 +,R
 
#	#R
  R
r0   r3  zY
    The PEGASUS Model with a language modeling head. Can be used for summarization.
    )custom_introc                   "    e Zd ZdZdgZddiZdef fdZ	 dded	edz  d
e	de
j                  f fdZdeddfdZdefdZdee
j                     fdZee	 	 	 	 	 	 	 	 	 	 ddej(                  dz  dej(                  dz  dej(                  dz  dej(                  dz  deej*                     dz  dedz  dej(                  dz  dej(                  dz  dej(                  dz  de	dz  dee   deez  fd              Zdej(                  fdZ xZS ) r   r   r   lm_head.weightzmodel.shared.weightr   c                 x   t         |   |       t        |      | _        | j	                  dt        j                  d| j                  j                  j                  f             t        j                  |j                  | j                  j                  j                  d      | _        | j                          y )Nr   r!   Fr   )r9   r:   r3  r   register_bufferrF   zerosr5  num_embeddingsr   r   r   lm_headr   r   s     r.   r:   z(PegasusForConditionalGeneration.__init__S  s     !&)
0%++q$**BSBSBbBb>c2deyy1B1B1Q1QX]^ 	r0   Nnew_num_tokenspad_to_multiple_ofmean_resizingr6   c                 z    t         |   |||      }| j                  |j                  j                  d          |S )Nr   )r9   resize_token_embeddings_resize_final_logits_biasrA   r)   )r;   rU  rV  rW  new_embeddingsr<   s        r.   rY  z7PegasusForConditionalGeneration.resize_token_embeddings\  s?     8I[]jk&&~'<'<'B'B1'EFr0   c                 6   | j                   j                  d   }||k  r| j                   d d d |f   }nSt        j                  d||z
  f| j                   j                        }t        j
                  | j                   |gd      }| j                  d|       y )Nr'   r!   r'  rr   r   )r   r)   rF   rR  rW   catrQ  )r;   rU  old_num_tokensnew_bias
extra_biass        r.   rZ  z9PegasusForConditionalGeneration._resize_final_logits_biasc  s    //55b9^+--a..@AHa.)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r0   r   c                     || j                   _        | j                  j                  j	                  |       | j                  j
                  j	                  |       yr>  )r   r   r   r6  r  r7  r  s     r.   r  z:PegasusForConditionalGeneration.resize_position_embeddingsl  sC     /J+

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

556QRr0   c                     | j                   j                  j                         | j                   j                  j                         fS r
  )r   r6  r  r7  r  s    r.   r  z7PegasusForConditionalGeneration.get_position_embeddings}  s5     

""::<djj>P>P>h>h>jkkr0   r#   rl   r@  rA  rB  r   r  rC  labelsr   ro   c                 z   |	R|
rt         j                  d       d}
|7|5t        |	| j                  j                  | j                  j
                        } | j                  |f||||||||
d|}| j                  |j                        | j                  z   }d}|	Ft               } ||j                  d| j                  j                        |	j                  d            }t        |||j                  |j                  |j                   |j"                  |j$                  |j&                  |j(                  	      S )a	  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

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

            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.
        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)rl   r@  rB  rA  r   r  rC  r   r'   )	losslogitsr   rF  rG  r  rH  r   rI  )r   warningr/   r   r$   r%   r   rT  r  r   r   r   r   r   r   rF  rG  r  rH  r   rI  )r;   r#   rl   r@  rA  rB  r   r  rC  rc  r   ro   outputs	lm_logitsmasked_lm_lossloss_fcts                   r.   rZ   z'PegasusForConditionalGeneration.forward  sB   r klI (-B-J$6DKK44dkk6X6X%! '1djj'
)/+#9+'"7'
 '
 LL!:!:;d>T>TT	')H%innR9O9O&PRXR]R]^`RabN#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r0   c                 l    t        || j                  j                  | j                  j                        S r]   )r/   r   r$   r%   )r;   rc  s     r.   %prepare_decoder_input_ids_from_labelszEPegasusForConditionalGeneration.prepare_decoder_input_ids_from_labels  s%    !&$++*B*BDKKDfDfggr0   )NT)
NNNNNNNNNN)r^   r_   r`   r   _keys_to_ignore_on_load_missingrL  r"   r:   rb   r   r   r   rY  rZ  r  r   r  r   r   rF   re   rH   r	   r   r   r   rZ   rm  rf   rg   s   @r.   r   r   G  s     ':&;#/}  ae!7:TzY]	< < <Sc S"lr||)< l  *..2156:;?(,-159&*!%]
<<$&]
 t+]
 !<<$.	]

 !&t 3]
 u001D8]
 ]
 ||d*]
  %||d2]
 t#]
 $;]
 +,]
 
	 ]
  ]
~hELL hr0   r   c                   (     e Zd ZdZ fdZd Z xZS )PegasusDecoderWrapperz
    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         |   |       t        |      | _        | j	                          y r]   )r9   r:   r  r7  r   r   s     r.   r:   zPegasusDecoderWrapper.__init__  s&     %f-r0   c                 &     | j                   |i |S r]   )r7  )r;   argsro   s      r.   rZ   zPegasusDecoderWrapper.forward  s    t||T,V,,r0   )r^   r_   r`   ra   r:   rZ   rf   rg   s   @r.   rp  rp    s    

-r0   rp  c                       e Zd ZddiZ fdZd Zd Zdej                  fdZ	de
fd	Zee	 	 	 	 	 	 	 	 	 ddej                  d
z  dej                   d
z  dej"                  d
z  dej"                  d
z  ded
z  dej"                  d
z  dej                  d
z  ded
z  de
ej                   z  dee   deez  fd              Z xZS )PegasusForCausalLMrO  z!model.decoder.embed_tokens.weightc                    t        j                  |      }d|_        d|_        t        |   |       t        |      | _        t        j                  |j                  |j                  d      | _        | j                          y )NTFr   )copydeepcopyr   r(  r9   r:   rp  r   r   r   hidden_sizer   rT  r   r   s     r.   r:   zPegasusForCausalLM.__init__  sf    v& $)! *62
yy!3!3V5F5FUS 	r0   c                 B    | j                   j                  j                  S r]   r   r7  r   r  s    r.   r9  z'PegasusForCausalLM.get_input_embeddings	  s    zz!!...r0   c                 :    || j                   j                  _        y r]   r{  r;  s     r.   r<  z'PegasusForCausalLM.set_input_embeddings  s    */

'r0   r6   c                 J    | j                   j                  j                         S r
  )r   r7  r  r  s    r.   r  z*PegasusForCausalLM.get_position_embeddings  s     zz!!99;;r0   r   c                 p    || j                   _        | j                  j                  j	                  |       yr>  )r   r   r   r7  r  r  s     r.   r  z-PegasusForCausalLM.resize_position_embeddings  s*     /J+

556QRr0   Nr#   rl   r   r   r   r  rc  r   logits_to_keepro   c
                     | j                   j                  d|||||||d|
}|d   }t        |	t              rt	        |	 d      n|	}| j                  |dd|ddf         }d}|a|j                  |j                        }t               } ||j                  d| j                  j                        |j                  d            }t        |||j                  |j                  |j                  |j                         S )aJ  
        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")
        >>> 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
        ```rE  r   Nr'   )re  rf  r   r   r   r  r   )r   r7  r   rb   slicerT  r  rW   r   r   r   r   r   r   r   r   r  )r;   r#   rl   r   r   r   r  rc  r   r  ro   rh  r   slice_indicesrf  re  rk  s                    r.   rZ   zPegasusForCausalLM.forward%  s   N >PTZZ=O=O 	>
)"7#9+'	>
 	>
  
8B>SV8W~ot4]kmA}a,?@AYYv}}-F')HFKKDKK,B,BCV[[QS_UD0#33!//))$55
 	
r0   )	NNNNNNNNr   )r^   r_   r`   rL  r:   r9  r<  r   r   r  rb   r  r   r   rF   
LongTensorre   rH   r	   r   r   r   r   r   rZ   rf   rg   s   @r.   ru  ru    sM   =
/0< <Sc S   .2.2:>;?(,26*.!%-.A
##d*A
 t+A
  %0047	A

 !& 1 1D 8A
 A
 ((4/A
   4'A
 $;A
 ell*A
 +,A
 
2	2A
  A
r0   ru  )ru  r   r3  r   )Nr   )Kra   rw  r   collections.abcr   numpyrB   rF   r   torch.nnr    r   r   activationsr   cache_utilsr	   r
   r   
generationr   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   utils.output_capturingr   r    configuration_pegasusr"   
get_loggerr^   r   re   rb   r/   r   r2   Moduler   r~   r   r   r   r   r   r  r3  r   rp  ru  __all__r   r0   r.   <module>r     s      $    % & ! C C ) J B 9  G &  8 E 0 
		H	%%,, c [^ "-2<< -R !%II%<<% 
% <<	%
 LL4'% T\% % '(%:r)ryy r)l54 5rZ4 Zz 2_ 2 2$v
+ v
rY
+ Y
x E
) E
 E
P 
Yh&<o Yh
Yhz-2 -q
/ q
h nr0   