U
    ,-eA                    @   s  d Z ddlZddlZddlmZmZmZmZ ddlZ	ddl
Z
ddl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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  e!e"Z#dZ$dZ%dgZ&e
j'e(e(dddZ)d3e
j*e
j+e
j,e(dddZ-d4e
j'e
j+ee( dddZ.G dd dej/Z0G dd dej1Z2G dd dej1Z3G dd dej1Z4G d d! d!eZ5d"Z6d#Z7d$Z8G d%d& d&e5Z9G d'd( d(e5Z:ed)e6G d*d+ d+e5Z;ed,e6G d-d. d.e5Z<G d/d0 d0e5Z=G d1d2 d2e5Z>dS )5z PyTorch PEGASUS model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)add_end_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )PegasusConfigzgoogle/pegasus-larger   )	input_idspad_token_iddecoder_start_token_idc                 C   sh   |  | j}| ddddf  |ddddf< ||dddf< |dkrTtd||dk| |S )z1
    Shift input ids one token to the right.
    Nr   r   z1self.model.config.pad_token_id has to be defined.i)Z	new_zerosshapeclone
ValueErrormasked_fill_)r   r   r   Zshifted_input_ids r   m/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/pegasus/modeling_pegasus.pyshift_tokens_right;   s    (r!   )input_ids_shapedtypedevicepast_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    r$   r   r   r   r#   r$   dimN)torchfullfinfominarangesizer   viewtocatzerosexpand)r"   r#   r$   r%   bsztgt_lenmaskZ	mask_condr   r   r    _make_causal_maskL   s    "
 r8   )r7   r#   r6   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)r/   r4   r1   Zmasked_fillr*   boolr,   r-   )r7   r#   r6   r5   src_lenZexpanded_maskZinverted_maskr   r   r    _expand_mask^   s
    *r<   c                       sn   e Zd ZdZdeeee dd fddZeej	ej	dddZ
e dejeejd
 fddZ  ZS )$PegasusSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.N)num_positionsembedding_dimpadding_idxreturnc                    s    t  || | | j| _d S N)super__init___init_weightweight)selfr>   r?   r@   	__class__r   r    rD   p   s    z-PegasusSinusoidalPositionalEmbedding.__init__)outrA   c              	      s   | j \} t fddt|D }d| _ d dkr@ d n
 d d }tt|dddddf | ddd|f< tt|dddddf | dd|df< | 	  | S )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:]
        c                    s$   g | ]  fd dt D qS )c              	      s(   g | ] }t d d|d     qS )i'     )nppower).0j)r)   posr   r    
<listcomp>|   s     zPPegasusSinusoidalPositionalEmbedding._init_weight.<locals>.<listcomp>.<listcomp>)range)rN   r(   )rP   r    rQ   |   s     zEPegasusSinusoidalPositionalEmbedding._init_weight.<locals>.<listcomp>FrK   r   r   N)
r   rL   arrayrR   Zrequires_gradr*   FloatTensorsincosZdetach_)rJ   Zn_posZposition_encsentinelr   r(   r    rE   t   s    
 22z1PegasusSinusoidalPositionalEmbedding._init_weightr   )r"   r%   rA   c                    s8   |dd \}}t j||| t j| jjd}t |S )z3`input_ids_shape` is expected to be [bsz x seqlen].NrK   r'   )r*   r.   longrF   r$   rC   forward)rG   r"   r%   r5   seq_len	positionsrH   r   r    rY      s       z,PegasusSinusoidalPositionalEmbedding.forward)N)r   )__name__
__module____qualname____doc__intr   rD   staticmethodr   	ParameterrE   r*   Zno_gradSizeTensorrY   __classcell__r   r   rH   r    r=   m   s   r=   c                       s   e Zd ZdZdeeeeed fddZej	eedd	d
Z
dej	eej	 eeej	  eej	 eej	 eeej	eej	 eeej	  f dddZ  ZS )PegasusAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FT)	embed_dim	num_headsdropout
is_decoderbiasc                    s   t    || _|| _|| _|| | _| j| | jkrNtd| j d| d| jd | _|| _t	j
|||d| _t	j
|||d| _t	j
|||d| _t	j
|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩rl   )rC   rD   rh   ri   rj   head_dimr   scalingrk   r   Lineark_projv_projq_projout_proj)rG   rh   ri   rj   rk   rl   rH   r   r    rD      s    

zPegasusAttention.__init__)tensorrZ   r5   c                 C   s    | ||| j| jdd S )Nr   rK   )r0   ri   rn   	transpose
contiguous)rG   ru   rZ   r5   r   r   r    _shape   s    zPegasusAttention._shapeN)hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsrA   c                 C   sx  |dk	}|  \}}	}
| || j }|r\|dk	r\|d jd |jd kr\|d }|d }n|r| | |d|}| | |d|}n|dk	r| | |d|}| | |d|}tj|d |gdd}tj|d |gdd}n(| | |d|}| | |d|}| j	r ||f}|| j
 d| jf}| ||	|j| }|j| }|j| }| d}t||dd}|  || j
 |	|fkrtd|| j
 |	|f d|   |dk	r |  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|dk	r|  | j
fkrhtd
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|r||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkr4td|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )z#Input shape: Batch x Time x ChannelNr   rK   r   r   r(   z$Attention weights should be of size z	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )r/   rs   ro   r   rx   rq   rr   r*   r2   rk   ri   rn   r0   ZreshapeZbmmrv   r   r   
functionalZsoftmaxrj   r   rh   rt   )rG   ry   rz   r{   r|   r}   r~   Zis_cross_attentionr5   r6   _Zquery_statesZ
key_statesZvalue_statesZ
proj_shaper;   attn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr   r   r    rY      s~    





" 
zPegasusAttention.forward)rg   FT)NNNNF)r\   r]   r^   r_   r`   floatr:   rD   r*   rd   rx   r   r   rY   re   r   r   rH   r    rf      s4           rf   c                       sB   e Zd Zed fddZdejejejeejdddZ  Z	S )	PegasusEncoderLayerconfigc                    s   t    |j| _t| j|j|jd| _t	| j| _
|j| _t|j | _|j| _t| j|j| _t|j| j| _t	| j| _d S )N)rh   ri   rj   )rC   rD   d_modelrh   rf   Zencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrj   r	   activation_functionactivation_fnactivation_dropoutrp   Zencoder_ffn_dimfc1fc2final_layer_normrG   r   rH   r   r    rD   ,  s    
zPegasusEncoderLayer.__init__F)ry   r|   r}   r~   rA   c           
      C   s  |}|  |}| j||||d\}}}tjj|| j| jd}|| }|}| |}| | |}tjj|| j	| jd}| 
|}tjj|| j| jd}|| }|jtjkrt| st| rt|jjd }tj|| |d}|f}	|r|	|f7 }	|	S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )ry   r|   r}   r~   r   i  )r-   max)r   r   r   r   rj   r   r   r   r   r   r   r#   r*   Zfloat16isinfanyisnanr,   r   clamp)
rG   ry   r|   r}   r~   residualr   r   Zclamp_valueoutputsr   r   r    rY   <  s8    



zPegasusEncoderLayer.forward)F)
r\   r]   r^   r   rD   r*   rd   r:   rY   re   r   r   rH   r    r   +  s    r   c                       sx   e Zd Zed fddZd
ejeej eej eej eej eej eeej  ee	 ee	 ejd
dd	Z
  ZS )PegasusDecoderLayerr   c                    s   t    |j| _t| j|j|jdd| _|j| _t	|j
 | _|j| _t| j| _t| j|j|jdd| _t| j| _t| j|j| _t|j| j| _t| j| _d S )NT)rh   ri   rj   rk   )rj   rk   )rC   rD   r   rh   rf   Zdecoder_attention_headsr   r   rj   r	   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrp   Zdecoder_ffn_dimr   r   r   r   rH   r   r    rD   q  s,    
zPegasusDecoderLayer.__init__NFT)
ry   r|   encoder_hidden_statesencoder_attention_maskr}   cross_attn_layer_head_maskr{   r~   	use_cacherA   c
                 C   s^  |}
|  |}|dk	r"|dd nd}| j|||||d\}}}tjj|| j| jd}|
| }d}d}|dk	r|}
| |}|dk	r|dd nd}| j||||||d\}}}tjj|| j| jd}|
| }|| }|}
| |}| 	| 
|}tjj|| j| jd}| |}tjj|| j| jd}|
| }|f}|rJ|||f7 }|	rZ||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            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.
        NrK   )ry   r{   r|   r}   r~   r   )ry   rz   r|   r}   r{   r~   )r   r   r   r   rj   r   r   r   r   r   r   r   r   )rG   ry   r|   r   r   r}   r   r{   r~   r   r   Zself_attn_past_key_valueZself_attn_weightsZpresent_key_valueZcross_attn_present_key_valueZcross_attn_weightsZcross_attn_past_key_valuer   r   r   r    rY     sT    




zPegasusDecoderLayer.forward)NNNNNNFT)r\   r]   r^   r   rD   r*   rd   r   r   r:   rY   re   r   r   rH   r    r   p  s*           r   c                   @   s*   e Zd ZeZdZdZdd Zd	ddZdS )
PegasusPreTrainedModelmodelTc                 C   s   | j j}t|tjr>|jjjd|d |jd k	r|jj	  nFt|t
rJn:t|tjr|jjjd|d |jd k	r|jj|j 	  d S )Nrg   )Zmeanstd)r   Zinit_std
isinstancer   rp   rF   dataZnormal_rl   Zzero_r=   	Embeddingr@   )rG   moduler   r   r   r    _init_weights  s    


z$PegasusPreTrainedModel._init_weightsFc                 C   s   t |ttfr||_d S rB   )r   PegasusDecoderPegasusEncodergradient_checkpointing)rG   r   valuer   r   r    _set_gradient_checkpointing  s    z2PegasusPreTrainedModel._set_gradient_checkpointingN)F)	r\   r]   r^   r   config_classbase_model_prefixZsupports_gradient_checkpointingr   r   r   r   r   r    r     s
   r   aL  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

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

    ```python
    >>> from transformers import AutoTokenizer, 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."
    ```
aa  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       sX   e Zd ZdZdeeej d fddZe	dddZ
ejd	d
dZdddZ  ZS )r   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
    Nr   embed_tokensc                    s   t     j| _ j| _ j} j| _ j| _	 j
rBt|nd| _|d k	rX|| _nt j|| j| _t j|| j| _t fddt jD | _t j| _d| _|   d S )Nr9   c                    s   g | ]}t  qS r   )r   rN   r   r   r   r    rQ     s     z+PegasusEncoder.__init__.<locals>.<listcomp>F)rC   rD   rj   Zencoder_layerdrop	layerdropr   r   r@   max_position_embeddingsZmax_source_positionsscale_embeddingmathsqrtembed_scaler   r   r   
vocab_sizer=   embed_positions
ModuleListrR   Zencoder_layerslayersr   
layer_normr   	post_init)rG   r   r   rh   rH   r   r    rD     s&     zPegasusEncoder.__init__new_num_position_embeddingsc                 C   sD   t d| d || j_t| jj| jj| j| _| j| j	 dS   
        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
loggerinfor   r   r=   r   r@   r   r1   r$   rG   r   r   r   r    resize_position_embeddings  s    z)PegasusEncoder.resize_position_embeddingsrA   c                 C   s   | j S z8
        Returns the position embeddings matrix
        r   rG   r   r   r    get_position_embeddings  s    z&PegasusEncoder.get_position_embeddingsc                    s   dk	r n| j j |dk	r |n| j j}|dk	r4|n| j j}|dk	rV|dk	rVtdnP|dk	r| || | }|d|d }n"|dk	r| dd }ntd|dkr| || j	 }| 
|}	||	 }
tjj|
| j| jd}
|dk	rt||j}|rdnd} rdnd}|dk	r\| d t| jkr\tdt| j d	| d  d
t| jD ]\}}|r~||
f }d}| jrtg }|| jk rd}|rd}nr| jr| jr fdd}tjj|||
||dk	r|| nd}n"||
||dk	r|| nd d}|d }
 rf||d f }qf| |
}
|rT||
f }|srtdd |
||fD S t|
||dS )a~  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

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

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

            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr   r   r   z&The head_mask should be specified for  layers, but it is for .FT)NNc                    s    fdd}|S )Nc                     s    | f S rB   r   inputs)r   r~   r   r    custom_forward(  s    zMPegasusEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   r   r   r~   r   r    create_custom_forward'  s    z5PegasusEncoder.forward.<locals>.create_custom_forward)r}   r~   r   c                 s   s   | ]}|d k	r|V  qd S rB   r   rN   vr   r   r    	<genexpr>F  s      z)PegasusEncoder.forward.<locals>.<genexpr>last_hidden_statery   
attentions)r   r~   output_hidden_statesuse_return_dictr   Z%warn_if_padding_and_no_attention_maskr/   r0   r   r   r   r   r   rj   r   r<   r#   lenr   	enumerater*   randr   r   utils
checkpointr   tupler
   )rG   r   r|   	head_maskinputs_embedsr~   r   return_dictinput_shapeZ	embed_posry   Zencoder_statesZall_attentionsidxZencoder_layerZto_dropdropout_probabilitylayer_outputsr   r   r   r    rY     s    .






  zPegasusEncoder.forward)N)NNNNNNN)r\   r]   r^   r_   r   r   r   r   rD   r`   r   r   rY   re   r   r   rH   r    r   }  s   	       r   c                       sp   e Zd ZdZdeeej d fddZdd Z	dd	 Z
d
d ZedddZejdddZdddZ  ZS )r   z
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]

    Args:
        config: PegasusConfig
        embed_tokens (nn.Embedding): output embedding
    Nr   c                    s   t     j| _ j| _ j| _ j| _ j	r>t
 jnd| _|d k	rT|| _nt j j| j| _t j j| j| _t fddt jD | _t j| _d| _|   d S )Nr9   c                    s   g | ]}t  qS r   )r   r   r   r   r    rQ   g  s     z+PegasusDecoder.__init__.<locals>.<listcomp>F)rC   rD   rj   Zdecoder_layerdropr   r   r@   r   Zmax_target_positionsr   r   r   r   r   r   r   r   r   r=   r   r   rR   Zdecoder_layersr   r   r   r   r   )rG   r   r   rH   r   r    rD   U  s$     zPegasusDecoder.__init__c                 C   s   | j S rB   r   r   r   r   r    get_input_embeddingsn  s    z#PegasusDecoder.get_input_embeddingsc                 C   s
   || _ d S rB   r   rG   r   r   r   r    set_input_embeddingsq  s    z#PegasusDecoder.set_input_embeddingsc                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr   r   )r$   r%   r6   )r8   r#   r$   r<   r1   )rG   r|   r   r   r%   Zcombined_attention_maskZexpanded_attn_maskr   r   r    _prepare_decoder_attention_masku  s    z.PegasusDecoder._prepare_decoder_attention_maskr   c                 C   sD   t d| d || j_t| jj| jj| j| _| j| j	 dS r   r   r   r   r   r    r     s    z)PegasusDecoder.resize_position_embeddingsr   c                 C   s   | j S r   r   r   r   r   r    r     s    z&PegasusDecoder.get_position_embeddingsc                    s   dk	r n| j j |dk	r |n| j j}dk	r4n| j j|dk	rH|n| j j}|dk	rj|dk	rjtdnD|dk	r| }|d|d }n"|dk	r| dd }ntd|dk	r|d d jd nd}|dkr| 	|| j
 }| ||||}|dk	r|dk	rt||j|d d}| ||}|| }tjj|| j| jd}| jrj| jrjrjtd	 d
|rtdnd} rdnd} r|dk	rdnd}rdnd}t||gddgD ]V\}}|dk	r| d t| jkrtd| dt| j d| d  dqt| jD ]F\}}|r:||f7 }| jr\tg }|| jk r\q |dk	rn|| nd}| jr| jrև fdd}tjj|||||||dk	r|| nd|dk	r|| ndd}n>||||||dk	r|| nd|dk	r|| nd| d	}|d }r:|| r0dnd f7 } r ||d f7 }|dk	r ||d f7 }q | |}|r||f7 }r|nd}|st dd |||||fD S t!|||||dS )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

                [What are attention masks?](../glossary#attention-mask)
            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.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   rK   r   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r   cross_attn_head_maskzThe `z` should be specified for r   r   c                    s    fdd}|S )Nc                     s    | f S rB   r   r   )r   r~   r   r   r    r   D  s    zMPegasusDecoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   r   r~   r   r   r    r   C  s    z5PegasusDecoder.forward.<locals>.create_custom_forward)r|   r   r   r}   r   r{   r~   r   r   r   c                 s   s   | ]}|d k	r|V  qd S rB   r   r   r   r   r    r   u  s   z)PegasusDecoder.forward.<locals>.<genexpr>)r   past_key_valuesry   r   cross_attentions)"r   r~   r   r   r   r   r/   r0   r   r   r   r   r<   r#   r   r   r   rj   r   r   r   Zwarning_oncezipr   r   r   r*   r   r   r   r   r   r   r   )rG   r   r|   r   r   r   r   r   r   r   r~   r   r   r   r%   r[   ry   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacheZ	attn_maskZ	mask_namer   Zdecoder_layerr   r{   r   r   Z
next_cacher   r   r    rY     s    P
   
$




zPegasusDecoder.forward)N)NNNNNNNNNNNN)r\   r]   r^   r_   r   r   r   r   rD   r   r   r   r`   r   r   rY   re   r   r   rH   r    r   L  s(               r   zUThe bare PEGASUS Model outputting raw hidden-states without any specific head on top.c                       s  e Zd ZddgZed fddZdd Zdd	 Zd
d Zdd Z	e
dddZeej dddZeeeeeddeej eej eej eej eej eej eej eeej  eeej  eej eej ee ee ee ee eeef dddZ  ZS )PegasusModelencoder.embed_tokens.weightdecoder.embed_tokens.weightr   c                    sT   t  | |j|j }}t||j|| _t|| j| _	t
|| j| _|   d S rB   )rC   rD   r   r   r   r   r   sharedr   encoderr   decoderr   )rG   r   r@   r   rH   r   r    rD     s    zPegasusModel.__init__c                 C   s   | j S rB   )r   r   r   r   r    r     s    z!PegasusModel.get_input_embeddingsc                 C   s   || _ | j | j_| j | j_d S rB   )r   r   r   r   r   r   r   r    r     s    
z!PegasusModel.set_input_embeddingsc                 C   s   | j S rB   )r   r   r   r   r    get_encoder  s    zPegasusModel.get_encoderc                 C   s   | j S rB   r   r   r   r   r    get_decoder  s    zPegasusModel.get_decoderr   c                 C   s$   || j _| j| | j| dS r   N)r   r   r   r   r   r   r   r   r    r     s    z'PegasusModel.resize_position_embeddingsr   c                 C   s   | j  | j fS r   )r   r   r   r   r   r   r    r     s    z$PegasusModel.get_position_embeddingsoutput_typer   N)r   r|   decoder_input_idsdecoder_attention_maskr   decoder_head_maskr   encoder_outputsr   r   decoder_inputs_embedsr   r~   r   r   rA   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|dk	rH|n| j j}|dkrr| j||||
|||d}nH|rt|tst|d t|dkr|d ndt|dkr|d ndd}| j	|||d ||||	|||||d}|s|| S t
|j|j|j|j|j|j|j|jdS )	a  
        Returns:

        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|   r   r   r~   r   r   r   r   rK   r   r   r|   r   r   r   r   r   r   r   r~   r   r   )r   r   decoder_hidden_statesdecoder_attentionsr   encoder_last_hidden_stater   encoder_attentions)r   r~   r   r   r   r   r   r
   r   r   r   r   r   ry   r   r   )rG   r   r|   r  r  r   r  r   r  r   r   r	  r   r~   r   r   Zdecoder_outputsr   r   r    rY     s^    (
zPegasusModel.forward)NNNNNNNNNNNNNNN)r\   r]   r^   _tied_weights_keysr   rD   r   r   r   r  r`   r   r   r   r   r   r   PEGASUS_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r*   rd   rT   r:   r   rY   re   r   r   rH   r    r     sV   
               
r   zOThe PEGASUS Model with a language modeling head. Can be used for summarization.c                       s  e Zd ZdZdgZdddgZed fddZd	d
 Zdd Z	d)e
ee
 ejd fddZe
ddddZdd Zdd Ze
dddZeej dddZeeeeedeed*eej eej eej eej eej eej eej eeej  eeej  eej eej eej ee ee ee ee e eef dd d!Z!d+d"d#Z"ejd$d%d&Z#e$d'd( Z%  Z&S ),PegasusForConditionalGenerationr   final_logits_biasr   r   lm_head.weightr   c                    sX   t  | t|| _| dtd| jjjf t	j
|j| jjjdd| _|   d S )Nr  r   Frm   )rC   rD   r   r   register_bufferr*   r3   r   Znum_embeddingsr   rp   r   lm_headr   r   rH   r   r    rD   #  s
    
z(PegasusForConditionalGeneration.__init__c                 C   s
   | j  S rB   )r   r   r   r   r   r    r   ,  s    z+PegasusForConditionalGeneration.get_encoderc                 C   s
   | j  S rB   )r   r  r   r   r   r    r  /  s    z+PegasusForConditionalGeneration.get_decoderN)new_num_tokenspad_to_multiple_ofrA   c                    s$   t  ||}| |jjd  |S )Nr   )rC   resize_token_embeddings_resize_final_logits_biasrF   r   )rG   r  r  new_embeddingsrH   r   r    r  2  s    z7PegasusForConditionalGeneration.resize_token_embeddings)r  rA   c                 C   sj   | j jd }||kr,| j d d d |f }n.tjd|| f| j jd}tj| j |gdd}| d| d S )Nr   r   r&   r(   r  )r  r   r*   r3   r$   r2   r  )rG   r  Zold_num_tokensZnew_biasZ
extra_biasr   r   r    r  7  s    z9PegasusForConditionalGeneration._resize_final_logits_biasc                 C   s   | j S rB   r  r   r   r   r    get_output_embeddings@  s    z5PegasusForConditionalGeneration.get_output_embeddingsc                 C   s
   || _ d S rB   r  rG   r  r   r   r    set_output_embeddingsC  s    z5PegasusForConditionalGeneration.set_output_embeddingsr   c                 C   s(   || j _| jj| | jj| dS r  )r   r   r   r   r   r   r   r   r   r    r   F  s    z:PegasusForConditionalGeneration.resize_position_embeddingsr   c                 C   s   | j j | j j fS r   )r   r   r   r   r   r   r   r    r   W  s    z7PegasusForConditionalGeneration.get_position_embeddingsr  )r   r|   r  r  r   r  r   r  r   r   r	  labelsr   r~   r   r   rA   c                 C   s  |dk	r|n| j j}|dk	rR|r*td d}|dkrR|dkrRt|| j j| j j}| j|||||||||	|
|||||d}| |d | j	 }d}|dk	rt
 }||d| j j|d}|s|f|dd  }|dk	r|f| S |S t|||j|j|j|j|j|j|jd	S )	a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)r|   r  r  r  r   r  r   r   r   r	  r   r~   r   r   r   r   r   )	losslogitsr   r  r  r   r  r   r  )r   r   r   warningr!   r   r   r   r  r  r   r0   r   r   r   r  r  r   r  r   r  )rG   r   r|   r  r  r   r  r   r  r   r   r	  r   r   r~   r   r   r   Z	lm_logitsZmasked_lm_lossloss_fctoutputr   r   r    rY   ]  s^    
  z'PegasusForConditionalGeneration.forwardc	           
   
   K   s4   |d k	r|d d dd f }d ||||||||d	S )Nr   )	r   r  r   r  r|   r   r  r   r   r   )
rG   r  r   r|   r   r  r   r   r  kwargsr   r   r    prepare_inputs_for_generation  s    z=PegasusForConditionalGeneration.prepare_inputs_for_generation)r   c                 C   s   t || jj| jjS rB   )r!   r   r   r   )rG   r   r   r   r    %prepare_decoder_input_ids_from_labels  s    zEPegasusForConditionalGeneration.prepare_decoder_input_ids_from_labelsc                    sB   d}| D ]4}|t  fdd|d d D |dd   f7 }q|S )Nr   c                 3   s"   | ]}| d  |jV  qdS r   NZindex_selectr1   r$   rN   Z
past_statebeam_idxr   r    r     s     zAPegasusForConditionalGeneration._reorder_cache.<locals>.<genexpr>rK   r   r   r-  Zreordered_pastZ
layer_pastr   r,  r    _reorder_cache  s    
z.PegasusForConditionalGeneration._reorder_cache)N)NNNNNNNNNNNNNNNN)NNNNNNN)'r\   r]   r^   r   Z_keys_to_ignore_on_load_missingr  r   rD   r   r  r`   r   r   r   r  r  r  r  r   r   r   r   r  r   r   r  r   PEGASUS_GENERATION_EXAMPLEr*   rd   rT   r:   r   rY   r'  r(  ra   r0  re   r   r   rH   r    r    sz   
		
                
R       
r  c                       s(   e Zd ZdZ fddZdd Z  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                    s   t  | t|| _d S rB   )rC   rD   r   r   r   rH   r   r    rD     s    zPegasusDecoderWrapper.__init__c                 O   s   | j ||S rB   r   )rG   argsr&  r   r   r    rY     s    zPegasusDecoderWrapper.forward)r\   r]   r^   r_   rD   rY   re   r   r   rH   r    r2    s   r2  c                       s
  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
ejdddZedddZeeeddejeej eej eej eej eej eeej  eej eej ee ee ee ee eeef dddZd ddZedd Z  Z S )!PegasusForCausalLMr  c                    sN   t |}d|_d|_t | t|| _tj	|j
|jdd| _|   d S )NTFrm   )copydeepcopyrk   Zis_encoder_decoderrC   rD   r2  r   r   rp   Zhidden_sizer   r  r   r   rH   r   r    rD     s    

zPegasusForCausalLM.__init__c                 C   s
   | j jjS rB   r   r   r   r   r   r   r    r     s    z'PegasusForCausalLM.get_input_embeddingsc                 C   s   || j j_d S rB   r7  r   r   r   r    r     s    z'PegasusForCausalLM.set_input_embeddingsc                 C   s   | j S rB   r  r   r   r   r    r    s    z(PegasusForCausalLM.get_output_embeddingsc                 C   s
   || _ d S rB   r  r  r   r   r    r    s    z(PegasusForCausalLM.set_output_embeddingsc                 C   s   || j _d S rB   r   r   )rG   r   r   r   r    set_decoder  s    zPegasusForCausalLM.set_decoderc                 C   s   | j jS rB   r8  r   r   r   r    r    s    zPegasusForCausalLM.get_decoderr   c                 C   s   | j j S r   )r   r   r   r   r   r   r    r   
  s    z*PegasusForCausalLM.get_position_embeddingsr   c                 C   s   || j _| jj| dS r  )r   r   r   r   r   r   r   r   r    r     s    z-PegasusForCausalLM.resize_position_embeddingsr  N)r   r|   r   r   r   r   r   r   r   r   r~   r   r   rA   c                 C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}| jj|||||||||
|||d}| |d }d}|	dk	r|	|j}	t	 }||
d| j j|	
d}|s|f|dd  }|dk	r|f| S |S t|||j|j|j|jdS )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

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

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

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

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

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

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

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

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

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, 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   ry   r   r   )r   r~   r   r   r   r   r  r1   r$   r   r0   r   r   r   ry   r   r   )rG   r   r|   r   r   r   r   r   r   r   r   r~   r   r   r   r"  r!  r$  r%  r   r   r    rY      sF    gzPegasusForCausalLM.forwardc                 K   s:   |d kr| |j}|r,|d d dd f }||||dS )Nr   )r   r|   r   r   )Znew_onesr   )rG   r   r   r|   r   r&  r   r   r    r'    s    z0PegasusForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ] }|t  fdd|D f7 }q|S )Nr   c                 3   s"   | ]}| d  |jV  qdS r)  r*  r+  r,  r   r    r     s     z4PegasusForCausalLM._reorder_cache.<locals>.<genexpr>r.  r/  r   r,  r    r0    s    z!PegasusForCausalLM._reorder_cache)NNNNNNNNNNNNN)NNN)!r\   r]   r^   r  rD   r   r   r  r  r9  r  r   r   r   r`   r   r   r   r  r*   Z
LongTensorr   rd   rT   r   r:   r   r   rY   r'  ra   r0  re   r   r   rH   r    r4    s^   
             
      
r4  )r   )N)?r_   r5  r   typingr   r   r   r   numpyrL   r*   Ztorch.utils.checkpointr   Ztorch.nnr   Zactivationsr	   Zmodeling_outputsr
   r   r   r   r   Zmodeling_utilsr   r   r   r   r   r   r   Zconfiguration_pegasusr   Z
get_loggerr\   r   Z_CHECKPOINT_FOR_DOCr  Z%PEGASUS_PRETRAINED_MODEL_ARCHIVE_LISTrd   r`   r!   rc   r#   r$   r8   r<   r   r=   Modulerf   r   r   r   ZPEGASUS_START_DOCSTRINGr1  r  r   r   r   r  r2  r4  r   r   r   r    <module>   sn   
    # EuZ P  9   >