U
    ,-eE                    @   s6  d Z ddlZddlZddlmZmZmZmZmZm	Z	 ddl
Z
ddlZ
ddl
mZ ddlmZmZmZ ddlmZ ddlmZmZmZmZmZmZ dd	lmZ dd
lmZmZmZm Z m!Z!m"Z" ddl#m$Z$ e!%e&Z'dZ(dZ)dddgZ*e
j+e,dddZ-d:e
j.e
j/e
j0e,dddZ1d;e
j+e
j/ee, dddZ2G dd dej3Z4G dd dej5Z6G dd dej5Z7G d d! d!ej5Z8G d"d# d#ej5Z9G d$d% d%eZ:d&Z;d'Z<d(Z=G d)d* d*e:Z>G d+d, d,e:Z?ed-e;G d.d/ d/e:Z@ed0e;G d1d2 d2e:ZAed3e;G d4d5 d5e:ZBG d6d7 d7e:ZCG d8d9 d9e:ZDdS )<z PyTorch PLBART model.    N)AnyDictListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_end_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )PLBartConfigzuclanlp/plbart-baser   zuclanlp/plbart-cs-javazuclanlp/plbart-multi_task-all)	input_idspad_token_idc                 C   s   |   }|dkrtd||dk| ||jddd d}|d| }|ddddf   |ddddf< ||dddf< |S )z
    Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not
    have a single `decoder_start_token_id` in contrast to other Bart-like models.
    Nz1self.model.config.pad_token_id has to be defined.ir   dimr   )clone
ValueErrormasked_fill_nesumZ	unsqueezegathersqueeze)r   r   Zprev_output_tokensZindex_of_eosZdecoder_start_tokens r)   k/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/plbart/modeling_plbart.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.   r   N)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_maskQ   s    "
 r@   )r?   r-   r>   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         ?)r7   r<   r9   Zmasked_fillr2   boolr4   r5   )r?   r-   r>   r=   src_lenZexpanded_maskZinverted_maskr)   r)   r*   _expand_maskc   s
    *rD   c                       s@   e Zd ZdZeed fddZd	ejed fddZ  Z	S )
 PLBartLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    )num_embeddingsembedding_dimc                    s   d| _ t || j  | d S )N   )offsetsuper__init__)selfrF   rG   	__class__r)   r*   rK   w   s    z)PLBartLearnedPositionalEmbedding.__init__r   )r   r/   c                    sH   |j dd \}}tj||| tj| jjd|d}t || j	 S )z3`input_ids' shape is expected to be [bsz x seqlen].NrH   r1   r!   )
shaper2   r6   longweightr.   r<   rJ   forwardrI   )rL   r   r/   r=   seq_len	positionsrM   r)   r*   rR   }   s        z(PLBartLearnedPositionalEmbedding.forward)r   )
__name__
__module____qualname____doc__intrK   r2   TensorrR   __classcell__r)   r)   rM   r*   rE   r   s   rE   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 )PLBartAttentionz=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      ࿩rb   )rJ   rK   r^   r_   r`   head_dimr#   scalingra   r   Lineark_projv_projq_projout_proj)rL   r^   r_   r`   ra   rb   rM   r)   r*   rK      s    

zPLBartAttention.__init__)tensorrS   r=   c                 C   s    | ||| j| jdd S )Nr   rH   )r8   r_   rd   	transpose
contiguous)rL   rk   rS   r=   r)   r)   r*   _shape   s    zPLBartAttention._shapeN)hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionsreturnc                 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   rH   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 )r7   ri   re   rO   rn   rg   rh   r2   r:   ra   r_   rd   r8   ZreshapeZbmmrl   r#   r   
functionalZsoftmaxr`   rx   r^   rj   )rL   ro   rp   rq   rr   rs   rt   Zis_cross_attentionr=   r>   _Zquery_statesZ
key_statesZvalue_statesZ
proj_shaperC   attn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr)   r)   r*   rR      s~    





" 
zPLBartAttention.forward)r]   FT)NNNNF)rU   rV   rW   rX   rY   floatrB   rK   r2   rZ   rn   r   r   rR   r[   r)   r)   rM   r*   r\      s4           r\   c                	       sT   e Zd Zed fddZdejejejee e	ejeej f dddZ
  ZS )	PLBartEncoderLayer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)r^   r_   r`   )rJ   rK   d_modelr^   r\   Zencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normr`   r   activation_functionactivation_fnactivation_dropoutrf   Zencoder_ffn_dimfc1fc2final_layer_normrL   r   rM   r)   r*   rK   %  s    
zPLBartEncoderLayer.__init__F)ro   rr   rs   rt   ru   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.
        )ro   rr   rs   rt   rv   i  )r5   max)r   r   ry   r`   rx   r   r   r   r   r   r   r-   r2   Zfloat16isinfanyisnanr4   r   clamp)
rL   ro   rr   rs   rt   residualr{   rz   Zclamp_valueoutputsr)   r)   r*   rR   5  s8    



zPLBartEncoderLayer.forward)F)rU   rV   rW   r   rK   r2   FloatTensorr   rB   r   rR   r[   r)   r)   rM   r*   r}   $  s    r}   c                       s   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ej
eeej
ej
f  f d
dd	Z  ZS )PLBartDecoderLayerr~   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)r^   r_   r`   ra   )r`   ra   )rJ   rK   r   r^   r\   Zdecoder_attention_headsr   r   r`   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrf   Zdecoder_ffn_dimr   r   r   r   rM   r)   r*   rK   j  s,    
zPLBartDecoderLayer.__init__NFT)
ro   rr   encoder_hidden_statesencoder_attention_maskrs   cross_attn_layer_head_maskrq   rt   	use_cacheru   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.
        NrH   )ro   rq   rr   rs   rt   rv   )ro   rp   rr   rs   rq   rt   )r   r   ry   r`   rx   r   r   r   r   r   r   r   r   )rL   ro   rr   r   r   rs   r   rq   rt   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*   rR     sT    




zPLBartDecoderLayer.forward)NNNNNNFT)rU   rV   rW   r   rK   r2   rZ   r   r   rB   r   rR   r[   r)   r)   rM   r*   r   i  s*           r   c                       s@   e Zd ZdZeeeed fddZejejdddZ	  Z
S )PLBartClassificationHeadz-Head for sentence-level classification tasks.)	input_dim	inner_dimnum_classespooler_dropoutc                    s8   t    t||| _tj|d| _t||| _d S )N)rw   )rJ   rK   r   rf   denseZDropoutr`   rj   )rL   r   r   r   r   rM   r)   r*   rK     s    
z!PLBartClassificationHead.__init__)ro   ru   c                 C   s6   |  |}| |}t|}|  |}| |}|S N)r`   r   r2   tanhrj   )rL   ro   r)   r)   r*   rR     s    




z PLBartClassificationHead.forward)rU   rV   rW   rX   rY   r|   rK   r2   rZ   rR   r[   r)   r)   rM   r*   r     s   r   c                   @   s2   e Zd ZeZdZdZddgZdd Zddd	Z	d
S )PLBartPreTrainedModelmodelTr   r}   c                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )Nr]   )Zmeanstd)r   Zinit_std
isinstancer   rf   rQ   dataZnormal_rb   Zzero_	Embeddingpadding_idx)rL   moduler   r)   r)   r*   _init_weights  s    

z#PLBartPreTrainedModel._init_weightsFc                 C   s   t |ttfr||_d S r   )r   PLBartDecoderPLBartEncodergradient_checkpointing)rL   r   valuer)   r)   r*   _set_gradient_checkpointing  s    z1PLBartPreTrainedModel._set_gradient_checkpointingN)F)
rU   rV   rW   r   config_classbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   r   r)   r)   r)   r*   r     s   r   aK  
    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 ([`PLBartConfig`]):
            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.
aA  
    Mask-filling example:

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

    >>> model = PLBartForConditionalGeneration.from_pretrained("uclanlp/plbart-base")
    >>> tokenizer = AutoTokenizer.from_pretrained("uclanlp/plbart-base")

    >>> # en_XX is the language symbol id <LID> for English
    >>> TXT = "<s> Is 0 the <mask> Fibonacci number ? </s> en_XX"
    >>> input_ids = tokenizer([TXT], add_special_tokens=False, return_tensors="pt").input_ids

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

    >>> tokenizer.decode(predictions).split()
    ['first', 'same', 'highest', 'result', 'number']
    ```
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`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
            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`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
            See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.

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

            PLBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
            varies according to source and target language, *e.g.* 50003 for *en_XX*, and 50001 for *java*. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            For translation and summarization training, `decoder_input_ids` should be provided. If no
            `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
            for denoising pre-training following the paper.
        decoder_attention_mask (:
            obj:*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 (:
            obj:*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 (:
            obj:*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 (:
            obj:*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 (:
            obj:*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                       s   e Zd ZdZdeeej d fddZdd Z	dd	 Z
dejeej eej eej ee ee ee eeef d
ddZ  ZS )r   z
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`PLBartEncoderLayer`].

    Args:
        config: PLBartConfig
        embed_tokens (nn.Embedding): output embedding
    Nr   embed_tokensc                    s   t     j| _ j| _ j} j| _ j| _	 j
rBt|nd| _t j|| j| _|d k	rn|j| j_t j|| _t fddt jD | _t|| _d| _|   d S )NrA   c                    s   g | ]}t  qS r)   )r}   .0rz   r~   r)   r*   
<listcomp>  s     z*PLBartEncoder.__init__.<locals>.<listcomp>F)rJ   rK   r`   Zencoder_layerdrop	layerdropr   r   r   max_position_embeddingsZmax_source_positionsscale_embeddingmathsqrtembed_scaler   r   
vocab_sizer   rQ   rE   embed_positions
ModuleListrangeZencoder_layerslayersr   layernorm_embeddingr   	post_init)rL   r   r   r^   rM   r~   r*   rK     s$    
 zPLBartEncoder.__init__c                 C   s   | j S r   r   rL   r)   r)   r*   get_input_embeddings  s    z"PLBartEncoder.get_input_embeddingsc                 C   s
   || _ d S r   r   rL   r   r)   r)   r*   set_input_embeddings  s    z"PLBartEncoder.set_input_embeddings)r   rr   	head_maskinputs_embedsrt   output_hidden_statesreturn_dictru   c                    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nH|dk	rv|}|d|jd }n(|dk	r|dddddf }ntd|dkr| || j }| 	|}	|	
|j}	||	 }
| |
}
tjj|
| j| jd}
|dk	r
t||j}|rdnd} r"dnd}|dk	rl| d t| jkrlt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 }
 rv||d f }qv|rZ||
f }|sxt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_embedsrv   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 r   r)   inputs)r   rt   r)   r*   custom_forward,  s    zLPLBartEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr)   r   r   rt   r   r*   create_custom_forward+  s    z4PLBartEncoder.forward.<locals>.create_custom_forward)rs   rt   r   c                 s   s   | ]}|d k	r|V  qd S r   r)   r   vr)   r)   r*   	<genexpr>H  s      z(PLBartEncoder.forward.<locals>.<genexpr>last_hidden_statero   
attentions)r   rt   r   use_return_dictr#   r8   rO   r   r   r   r9   r.   r   r   ry   r`   rx   rD   r-   r7   lenr   	enumerater2   randr   r   utils
checkpointtupler   )rL   r   rr   r   r   rt   r   r   inputZ	embed_posro   Zencoder_statesZall_attentionsidxZencoder_layerZto_dropdropout_probabilitylayer_outputsr   r)   r   r*   rR     s    .







  zPLBartEncoder.forward)N)NNNNNNN)rU   rV   rW   rX   r   r   r   r   rK   r   r   r2   
LongTensorrZ   r   rB   r   r   r   rR   r[   r)   r)   rM   r*   r     s*   	       
r   c                       s   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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 ee ee ee eeef dddZ  ZS )r   z
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PLBartDecoderLayer`]

    Args:
        config: PLBartConfig
        embed_tokens (nn.Embedding): output embedding
    Nr   c                    s   t     j| _ j| _ j| _ j| _ j	r>t
 jnd| _t j j| j| _|d k	rl|j| j_t j j| _t fddt jD | _t j| _d| _|   d S )NrA   c                    s   g | ]}t  qS r)   )r   r   r~   r)   r*   r   i  s     z*PLBartDecoder.__init__.<locals>.<listcomp>F)rJ   rK   r`   Zdecoder_layerdropr   r   r   r   Zmax_target_positionsr   r   r   r   r   r   r   r   r   rQ   rE   r   r   r   Zdecoder_layersr   r   r   r   r   )rL   r   r   rM   r~   r*   rK   X  s"    
 zPLBartDecoder.__init__c                 C   s   | j S r   r   r   r)   r)   r*   r   p  s    z"PLBartDecoder.get_input_embeddingsc                 C   s
   || _ d S r   r   r   r)   r)   r*   r   s  s    z"PLBartDecoder.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/   r>   )r@   r-   r.   rD   r9   )rL   rr   input_shaper   r/   Zcombined_attention_maskZexpanded_attn_maskr)   r)   r*   _prepare_decoder_attention_maskv  s    z-PLBartDecoder._prepare_decoder_attention_mask)r   rr   r   r   r   cross_attn_head_maskpast_key_valuesr   r   rt   r   r   ru   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	rj|dk	rjtdn\|dk	r|}|j}|d|d }n8|dk	r| dd }|dddddf }ntd|dk	r|d d jd nd}|dkr| 	|| j
 }| ||||}|dk	r4|dk	r4t||j|d d}| ||}||j}|| }| |}tjj|| j| jd}| jr| jrrtd	 d
|rd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\}}|rh||f7 }| jrtg }|| jk rqN|dk	r|| 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	r4|| nd| d	}|d }rh|| r^dnd f7 } rN||d f7 }|dk	rN||d f7 }qN|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 the decoder to avoid performing
                cross-attention on hidden heads. Mask values selected in `[0, 1]`:

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

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

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

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
                shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
                `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
                control over how to convert `input_ids` indices into associated vectors than the model's internal
                embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer!   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   rH   r   rv   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr)   r   r   zThe `z` should be specified for r   r   c                    s    fdd}|S )Nc                     s    | f S r   r)   r   )r   rt   r   r)   r*   r   -  s    zLPLBartDecoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr)   r   rt   r   r   r*   r   ,  s    z4PLBartDecoder.forward.<locals>.create_custom_forward)rr   r   r   rs   r   rq   rt   r   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r)   r   r)   r)   r*   r   \  s   z(PLBartDecoder.forward.<locals>.<genexpr>)r   r   ro   r   cross_attentions)$r   rt   r   r   r   r#   rO   r8   r7   r   r   r   rD   r-   r   r9   r.   r   r   ry   r`   rx   r   loggerZwarning_oncezipr   r   r   r2   r   r   r   r   r   r   )rL   r   rr   r   r   r   r   r   r   r   rt   r   r   r   r   r/   rT   ro   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacheZ	attn_maskZ	mask_namer   Zdecoder_layerr   rq   r   r   Z
next_cacher)   r   r*   rR     s    P
   

$



zPLBartDecoder.forward)N)NNNNNNNNNNNN)rU   rV   rW   rX   r   r   r   r   rK   r   r   r   r2   r   rZ   r   r   rB   r   r   r   rR   r[   r)   r)   rM   r*   r   O  s@               
r   zTThe bare PLBART 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
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j ef dddZ  ZS )PLBartModelencoder.embed_tokens.weightdecoder.embed_tokens.weightr~   c                    sT   t  | |j|j }}t||j|| _t|| j| _	t
|| j| _|   d S r   )rJ   rK   r   r   r   r   r   sharedr   encoderr   decoderinit_weights)rL   r   r   r   rM   r)   r*   rK   q  s    zPLBartModel.__init__c                 C   s   | j S r   )r   r   r)   r)   r*   r   |  s    z PLBartModel.get_input_embeddingsc                 C   s   || _ | j | j_| j | j_d S r   )r   r   r   r   r   r)   r)   r*   r     s    
z PLBartModel.set_input_embeddingsc                 C   s   | j S r   )r   r   r)   r)   r*   get_encoder  s    zPLBartModel.get_encoderc                 C   s   | j S r   r   r   r)   r)   r*   get_decoder  s    zPLBartModel.get_decoderr   output_typer   N)r   rr   decoder_input_idsdecoder_attention_maskr   decoder_head_maskr   encoder_outputsr   r   decoder_inputs_embedsr   rt   r   r   ru   c                 C   s4  |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rn|d krnt|| j j}|d kr| 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 )N)r   rr   r   r   rt   r   r   r   r   rH   r   r   rr   r   r   r   r   r   r   r   rt   r   r   )r   r   decoder_hidden_statesdecoder_attentionsr   encoder_last_hidden_stater   encoder_attentions)r   rt   r   r   r   r+   r   r   r   r   r   r   r   r   r   ro   r   r   )rL   r   rr   r   r   r   r  r   r  r   r   r  r   rt   r   r   Zdecoder_outputsr)   r)   r*   rR     sb    
zPLBartModel.forward)NNNNNNNNNNNNNNN)rU   rV   rW   _tied_weights_keysr   rK   r   r   r   r   r   PLBART_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r2   r   rZ   r   r   rB   r   r   rR   r[   r)   r)   rM   r*   r   j  sZ                  r   zlThe PLBART Model with a language modeling head. Can be used for code-to-text, text-to-code and code-to-code.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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j ef dddZ!d&ejeeej  eej eej eej eej ee eeej  e"e#e$f d	ddZ%ejdd d!Z&e'd"d# Z(  Z)S )'PLBartForConditionalGenerationr   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   Frc   )rJ   rK   r   r   register_bufferr2   r;   r   rF   r   rf   r   lm_headr   r   rM   r)   r*   rK     s
    
z'PLBartForConditionalGeneration.__init__c                 C   s
   | j  S r   )r   r   r   r)   r)   r*   r     s    z*PLBartForConditionalGeneration.get_encoderc                 C   s
   | j  S r   )r   r   r   r)   r)   r*   r     s    z*PLBartForConditionalGeneration.get_decoderN)new_num_tokenspad_to_multiple_ofru   c                    s$   t  ||}| |jjd  |S )Nr   )rJ   resize_token_embeddings_resize_final_logits_biasrQ   rO   )rL   r  r  new_embeddingsrM   r)   r*   r    s    z6PLBartForConditionalGeneration.resize_token_embeddings)r  ru   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   r0   r   r  )r  rO   r2   r;   r.   r:   r  )rL   r  Zold_num_tokensZnew_biasZ
extra_biasr)   r)   r*   r    s    z8PLBartForConditionalGeneration._resize_final_logits_biasc                 C   s   | j S r   r  r   r)   r)   r*   get_output_embeddings  s    z4PLBartForConditionalGeneration.get_output_embeddingsc                 C   s
   || _ d S r   r  rL   r  r)   r)   r*   set_output_embeddings  s    z4PLBartForConditionalGeneration.set_output_embeddingsr   r   )r   rr   r   r   r   r  r   r  r   r   r  labelsr   rt   r   r   ru   c                 C   s  |dk	r|n| j j}|dk	r:|dkr:|dkr:t|| j j}| j|||||||||	|
|||||d}| |d }|| j|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:

        N)rr   r   r  r   r   r  r   r   r   r  r   rt   r   r   r   r!   r   	losslogitsr   r  r  r   r  r   r  )r   r   r+   r   r   r  r  r9   r.   r
   r8   r   r   r   r  r  r   r  r   r  )rL   r   rr   r   r   r   r  r   r  r   r   r  r  r   rt   r   r   r   Z	lm_logitsZmasked_lm_lossloss_fctoutputr)   r)   r*   rR   
  sR    z&PLBartForConditionalGeneration.forward)	r   r   rr   r   r  r   r   r  ru   c	           
   
   K   s4   |d k	r|d d dd f }d ||||||||d	S )Nr!   )	r   r  r   r   rr   r   r  r   r   r)   )
rL   r   r   rr   r   r  r   r   r  kwargsr)   r)   r*   prepare_inputs_for_generationX  s    z<PLBartForConditionalGeneration.prepare_inputs_for_generation)r  c                 C   s   t || jjS r   )r+   r   r   )rL   r  r)   r)   r*   %prepare_decoder_input_ids_from_labelst  s    zDPLBartForConditionalGeneration.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_selectr9   r.   r   Z
past_statebeam_idxr)   r*   r   }  s     z@PLBartForConditionalGeneration._reorder_cache.<locals>.<genexpr>rH   r   r   r)  Zreordered_pastZ
layer_pastr)   r(  r*   _reorder_cachew  s    
z-PLBartForConditionalGeneration._reorder_cache)N)NNNNNNNNNNNNNNNN)NNNNNNN)*rU   rV   rW   r   Z_keys_to_ignore_on_load_missingr	  r   rK   r   r   rY   r   r   r   r  r  r  r  r   r
  r   r   r  r   PLBART_GENERATION_EXAMPLEr2   r   rZ   r   r   rB   r   r   rR   r   strr   r#  r$  staticmethodr,  r[   r)   r)   rM   r*   r    s   
	
                N       
r  z
    PLBart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for code
    classification.
    c                       s   e Zd ZddgZed fddZeeee	e
edd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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 )PLBartForSequenceClassificationr   r   r~   c                    s>   t  j|f| t|| _t|j|j|j|j| _| 	  d S r   )
rJ   rK   r   r   r   r   
num_labelsZclassifier_dropoutclassification_headr   )rL   r   r"  rM   r)   r*   rK     s    
z(PLBartForSequenceClassification.__init__r   N)r   rr   r   r   r   r  r   r  r   r  r  r   rt   r   r   ru   c                 C   sN  |dk	r|n| j j}|dk	r d}|dkrB|	dk	rBtd| jj | j|||||||||	|
||||d}|d }|| j j|j	}t
t|ddkrtd||ddf |dd|ddddddf }| |}d}|dk	r||j	}| j jdkrd| j jdkr(d	| j _n<| j jdkr\|jtjksR|jtjkr\d
| j _nd| j _| j jd	krt }| j jdkr|| | }n
|||}nP| j jd
krt }||d| j j|d}n| j jdkrt }|||}|s&|f|dd  }|dk	r"|f| S |S t|||j|j|j|j|j |j!|j"d	S )a3  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NFz8Passing input embeddings is currently not supported for )rr   r   r   r   r  r   r  r   r  r   rt   r   r   r   r   z7All examples must have the same number of <eos> tokens.r!   Z
regressionZsingle_label_classificationZmulti_label_classificationr  )#r   r   NotImplementedErrorrN   rU   r   eqZeos_token_idr9   r.   r   r2   Zunique_consecutiver&   r#   r8   r7   r2  Zproblem_typer1  r-   rP   rY   r   r(   r
   r	   r   r   r  r  r   r  r   r  )rL   r   rr   r   r   r   r  r   r  r   r  r  r   rt   r   r   r   ro   Zeos_maskZsentence_representationr  r  r   r!  r)   r)   r*   rR     s    *


*

z'PLBartForSequenceClassification.forward)NNNNNNNNNNNNNNN)rU   rV   rW   r	  r   rK   r   r
  r   r  r   r  r2   r   r   rZ   r   r   rB   r   r   rR   r[   r)   r)   rM   r*   r0    sR                  
r0  c                       s(   e Zd ZdZ fddZdd Z  ZS )PLBartDecoderWrapperz
    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 r   )rJ   rK   r   r   r   rM   r)   r*   rK     s    zPLBartDecoderWrapper.__init__c                 O   s   | j ||S r   r   )rL   argsr"  r)   r)   r*   rR     s    zPLBartDecoderWrapper.forward)rU   rV   rW   rX   rK   rR   r[   r)   r)   rM   r*   r5    s   r5  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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 )PLBartForCausalLMr  c                    sN   t |}d|_d|_t | t|| _tj	|j
|jdd| _|   d S )NTFrc   )copydeepcopyra   Zis_encoder_decoderrJ   rK   r5  r   r   rf   Zhidden_sizer   r  r   r   rM   r)   r*   rK     s    

zPLBartForCausalLM.__init__c                 C   s
   | j jjS r   r   r   r   r   r)   r)   r*   r   #  s    z&PLBartForCausalLM.get_input_embeddingsc                 C   s   || j j_d S r   r:  r   r)   r)   r*   r   &  s    z&PLBartForCausalLM.set_input_embeddingsc                 C   s   | j S r   r  r   r)   r)   r*   r  )  s    z'PLBartForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r   r  r  r)   r)   r*   r  ,  s    z'PLBartForCausalLM.set_output_embeddingsc                 C   s   || j _d S r   r   r   )rL   r   r)   r)   r*   set_decoder/  s    zPLBartForCausalLM.set_decoderc                 C   s   | j jS r   r;  r   r)   r)   r*   r   2  s    zPLBartForCausalLM.get_decoderr  N)r   rr   r   r   r   r   r   r   r  r   rt   r   r   ru   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, PLBartForCausalLM

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

        >>> logits = outputs.logits
        >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
        >>> list(logits.shape) == expected_shape
        True
        ```Nr  r   r!   r   )r  r  r   ro   r   r   )r   rt   r   r   r   r   r  r9   r.   r
   r8   r   r   r   ro   r   r   )rL   r   rr   r   r   r   r   r   r   r  r   rt   r   r   r   r  r  r   r!  r)   r)   r*   rR   5  sF    fzPLBartForCausalLM.forwardc                 K   s:   |d kr| |j}|r,|d d dd f }||||dS )Nr!   )r   rr   r   r   )Znew_onesrO   )rL   r   r   rr   r   r"  r)   r)   r*   r#    s    z/PLBartForCausalLM.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     z3PLBartForCausalLM._reorder_cache.<locals>.<genexpr>r*  r+  r)   r(  r*   r,    s    z PLBartForCausalLM._reorder_cache)NNNNNNNNNNNNN)NNN)rU   rV   rW   r	  rK   r   r   r  r  r<  r   r   r   r  r2   r   r   rZ   r   r   rB   r   r   rR   r#  r/  r,  r[   r)   r)   rM   r*   r7    sZ   
             
      
r7  )r   )N)ErX   r8  r   typingr   r   r   r   r   r   r2   Ztorch.utils.checkpointr   Ztorch.nnr	   r
   r   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   r   r   r   r   r   r   r   Zconfiguration_plbartr   Z
get_loggerrU   r   r  r  Z$PLBART_PRETRAINED_MODEL_ARCHIVE_LISTrZ   rY   r+   Sizer-   r.   r@   rD   r   rE   Moduler\   r}   r   r   r   ZPLBART_START_DOCSTRINGr-  r
  r   r   r   r  r0  r5  r7  r)   r)   r)   r*   <module>   sz      
	     Evd 8  q !{