Ë
    ÜÓ^jÄC  ã                   óè  — d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddlmZmZmZ ddlmZ ddlmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(  G d„ de"«      Z)e G d„ de«      «       Z* G d„ de «      Z+ G d„ de«      Z,e G d„ de*«      «       Z- ed¬ «       G d!„ d"e*e«      «       Z. G d#„ d$e«      Z/ G d%„ d&e$«      Z0 G d'„ d(e!«      Z1g d)¢Z2y)*zPyTorch PLBART model.é    N)Únn)ÚCrossEntropyLossé   )Úinitialization)ÚCache)ÚGenerationMixin)ÚBaseModelOutputÚSeq2SeqLMOutputÚSeq2SeqModelOutput)ÚPreTrainedModel)ÚUnpack)ÚTransformersKwargsÚauto_docstringÚcan_return_tuple)Úmerge_with_config_defaults)Úcapture_outputsé   )ÚBartClassificationHeadÚBartDecoderÚBartEncoderÚBartForCausalLMÚBartScaledWordEmbedding)Ú'BigBirdPegasusForSequenceClassification)Úshift_tokens_righté   )ÚPLBartConfigc                   ó   — e Zd Zy)ÚPLBartScaledWordEmbeddingN©Ú__name__Ú
__module__Ú__qualname__© ó    út/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/plbart/modular_plbart.pyr   r   /   ó   „ Ør$   r   c                   óF   ‡ — e Zd ZU eed<   dZdZddgZdZdZ	dZ
ˆ fd„Zˆ xZS )ÚPLBartPreTrainedModelÚconfigÚmodelTÚPLBartDecoderLayerÚPLBartEncoderLayerc                 ó„   •— t         ‰| �  |«       t        |t        «      r t	        j
                  |j                  «       y y ©N)ÚsuperÚ_init_weightsÚ
isinstanceÚPLBartForConditionalGenerationÚinitÚzeros_Úfinal_logits_bias)ÚselfÚmoduleÚ	__class__s     €r%   r0   z#PLBartPreTrainedModel._init_weights=   s2   ø€ Ü‰Ñ˜fÔ%Ü�fÔ<Ô=Ü�K‰K˜×0Ñ0Õ1ð >r$   )r    r!   r"   r   Ú__annotations__Úbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_supports_flash_attnÚ_supports_sdpaÚ_supports_flex_attnr0   Ú__classcell__©r8   s   @r%   r(   r(   3   s<   ø… àÓØÐØ&*Ð#Ø-Ð/CÐDÐØÐØ€NØÐ÷2ð 2r$   r(   c                   ó   — e Zd Zy)ÚPLBartEncoderNr   r#   r$   r%   rC   rC   C   r&   r$   rC   c                   ó   — e Zd Zy)ÚPLBartDecoderNr   r#   r$   r%   rE   rE   G   r&   r$   rE   c                   óŽ  ‡ — e Zd ZdddœZdefˆ fd„Zd„ Zd„ Zee	e
	 	 	 	 	 	 	 	 	 ddej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  deej                     dz  dedz  dej                  dz  dej                  dz  dedz  dee   deej                     ez  fd„«       «       «       Zˆ xZS )ÚPLBartModelzshared.weight)zencoder.embed_tokens.weightzdecoder.embed_tokens.weightr)   c                 óJ  •— t         ‰| �  |«       |j                  |j                  }}|j                  rt        j                  |j                  «      nd}t        ||j                  ||¬«      | _	        t        |«      | _        t        |«      | _        | j                  «        y )Ng      ð?)Úembed_scale)r/   Ú__init__Úpad_token_idÚ
vocab_sizeÚscale_embeddingÚmathÚsqrtÚd_modelr   ÚsharedrC   ÚencoderrE   ÚdecoderÚ	post_init)r6   r)   Úpadding_idxrL   rI   r8   s        €r%   rJ   zPLBartModel.__init__R   sz   ø€ Ü‰Ñ˜Ô à"(×"5Ñ"5°v×7HÑ7H�ZˆØ39×3IÒ3I”d—i‘i §¡Ô/ÈsˆÜ/°
¸F¿N¹NÈKÐepÔqˆŒä$ VÓ,ˆŒÜ$ VÓ,ˆŒà�‰Õr$   c                 ó   — | j                   S r.   )rQ   )r6   s    r%   Úget_input_embeddingsz PLBartModel.get_input_embeddings^   s   € Ø�{‰{Ðr$   c                 ó~   — || _         | j                   | j                  _        | j                   | j                  _        y r.   )rQ   rR   Úembed_tokensrS   )r6   Úvalues     r%   Úset_input_embeddingsz PLBartModel.set_input_embeddingsa   s)   € ØˆŒØ$(§K¡Kˆ�‰Ô!Ø$(§K¡Kˆ�‰Õ!r$   NÚ	input_idsÚattention_maskÚdecoder_input_idsÚdecoder_attention_maskÚencoder_outputsÚpast_key_valuesÚinputs_embedsÚdecoder_inputs_embedsÚ	use_cacheÚkwargsÚreturnc
                 ó
  — |€"|€ t        || j                  j                  «      }|€ | j                  d	|||dœ|
¤Ž}nGt	        |t
        «      s7t        |d   t        |«      dkD  r|d   ndt        |«      dkD  r|d   nd¬«      } | j                  d	|||d   ||||	dœ|
¤Ž}t        |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  ¬«      S )
a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`] 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.
        N)r\   r]   rb   r   r   r   )Úlast_hidden_stateÚhidden_statesÚ
attentions)r\   r]   Úencoder_hidden_statesÚencoder_attention_maskra   rb   rd   )rh   ra   Údecoder_hidden_statesÚdecoder_attentionsÚcross_attentionsÚencoder_last_hidden_staterk   Úencoder_attentionsr#   )r   r)   rK   rR   r1   r	   ÚlenrS   r   rh   ra   ri   rj   ro   )r6   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   Údecoder_outputss               r%   ÚforwardzPLBartModel.forwardf   s3  € ðP Ð$Ð)>Ð)FÜ 2°9¸d¿k¹k×>VÑ>VÓ WÐàÐ"Ø/;¨t¯|©|ð 0Ø#Ø-Ø+ñ0ð ñ	0‰Oô ˜O¬_Ô=Ü-Ø"1°!Ñ"4Ü47¸Ó4HÈ1Ò4L˜o¨aÒ0ÐRVÜ14°_Ó1EÈÒ1I˜?¨1Ò-ÈtôˆOð '˜$Ÿ,™,ð 	
Ø'Ø1Ø"1°!Ñ"4Ø#1Ø+Ø/Øñ	
ð ñ	
ˆô "Ø-×?Ñ?Ø+×;Ñ;Ø"1×"?Ñ"?Ø.×9Ñ9Ø,×=Ñ=Ø&5×&GÑ&GØ"1×"?Ñ"?Ø.×9Ñ9ô	
ð 		
r$   )	NNNNNNNNN)r    r!   r"   Ú_tied_weights_keysr   rJ   rW   r[   r   r   r   ÚtorchÚ
LongTensorÚTensorÚlistÚFloatTensorr   Úboolr   r   Útupler   rt   r@   rA   s   @r%   rG   rG   K   sP  ø„ ð (7Ø'6ñÐð

˜|õ 
òò0ð
  ØØð .2Ø26Ø59Ø6:Ø:>Ø(,Ø26Ø:>Ø!%ñJ
à×#Ñ# dÑ*ðJ
ð ×(Ñ(¨4Ñ/ðJ
ð !×+Ñ+¨dÑ2ð	J
ð
 !&§¡¨tÑ 3ðJ
ð ˜e×/Ñ/Ñ0°4Ñ7ðJ
ð  ™ðJ
ð ×(Ñ(¨4Ñ/ðJ
ð  %×0Ñ0°4Ñ7ðJ
ð ˜$‘;ðJ
ð Ð+Ñ,ðJ
ð 
ˆu�|‰|Ñ	Ð1Ñ	1òJ
ó ó ó  ôJ
r$   rG   zv
    The PLBART Model with a language modeling head. Can be used for code-to-text, text-to-code and code-to-code.
    )Úcustom_introc                   ó  ‡ — e Zd ZdZdgZddiZdefˆ fd„Z	 dded	edz  d
e	de
j                  fˆ fd„Zdeddfd„Zeee	 	 	 	 	 	 	 	 	 	 ddej$                  dz  dej$                  dz  dej$                  dz  dej&                  dz  deej*                     dz  dedz  dej*                  dz  dej*                  dz  dej&                  dz  de	dz  dee   deej&                     ez  fd„«       «       «       Zdej&                  fd„Zˆ xZS )r2   r*   r5   zlm_head.weightzmodel.shared.weightr)   c                 óx  •— t         ‰| �  |«       t        |«      | _        | j	                  dt        j                  d| j                  j                  j                  f«      «       t        j                  |j                  | j                  j                  j                  d¬«      | _        | j                  «        y )Nr5   r   F)Úbias)r/   rJ   rG   r*   Úregister_bufferrv   ÚzerosrQ   Únum_embeddingsr   ÚLinearrP   Úlm_headrT   )r6   r)   r8   s     €r%   rJ   z'PLBartForConditionalGeneration.__init__Â   s~   ø€ Ü‰Ñ˜Ô Ü  Ó(ˆŒ
Ø×ÑÐ0´%·+±+¸qÀ$Ç*Á*×BSÑBS×BbÑBbÐ>cÓ2dÔeÜ—y‘y §¡°·±×1BÑ1B×1QÑ1QÐX]Ô^ˆŒà�‰Õr$   NÚnew_num_tokensÚpad_to_multiple_ofÚmean_resizingrf   c                 óz   •— t         ‰| �  |||«      }| j                  |j                  j                  d   «       |S )Nr   )r/   Úresize_token_embeddingsÚ_resize_final_logits_biasÚweightÚshape)r6   r†   r‡   rˆ   Únew_embeddingsr8   s        €r%   rŠ   z6PLBartForConditionalGeneration.resize_token_embeddingsÊ   s?   ø€ ô ™Ñ8¸ÐI[Ð]jÓkˆØ×&Ñ& ~×'<Ñ'<×'BÑ'BÀ1Ñ'EÔFØÐr$   c                 ó6  — | j                   j                  d   }||k  r| j                   d d …d |…f   }nSt        j                  d||z
  f| j                   j                  ¬«      }t        j
                  | j                   |gd¬«      }| j                  d|«       y )Néÿÿÿÿr   )Údevice)Údimr5   )r5   r�   rv   r‚   r‘   Úcatr�   )r6   r†   Úold_num_tokensÚnew_biasÚ
extra_biass        r%   r‹   z8PLBartForConditionalGeneration._resize_final_logits_biasÑ   sŒ   € Ø×/Ñ/×5Ñ5°bÑ9ˆØ˜^Ò+Ø×-Ñ-ªa°°.°Ð.@ÑA‰HäŸ™ a¨¸.Ñ)HÐ%IÐRV×RhÑRh×RoÑRoÔpˆJÜ—y‘y $×"8Ñ"8¸*Ð!EÈ1ÔMˆHØ×ÑÐ0°(Õ;r$   r\   r]   r^   r_   r`   ra   rb   rc   Úlabelsrd   re   c                 óT  — |	�$|€"|€ t        |	| j                  j                  «      } | j                  |f||||||||
dœ|¤Ž}| j	                  |j
                  «      }|| j                  j                  |j                  «      z   }d}|	�Ft        «       } ||j                  d| j                  j                  «      |	j                  d«      «      }t        |||j                  |j                  |j                  |j                   |j"                  |j$                  |j&                  ¬«	      S )a 
  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`] 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.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example Mask-filling:

        ```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']
        ```
        N)r]   r^   r`   r_   ra   rb   rc   rd   r�   )	ÚlossÚlogitsra   rm   rn   ro   rp   rk   rq   )r   r)   rK   r*   r…   rh   r5   Útor‘   r   ÚviewrL   r
   ra   rm   rn   ro   rp   rk   rq   )r6   r\   r]   r^   r_   r`   ra   rb   rc   r—   rd   re   ÚoutputsÚ	lm_logitsÚmasked_lm_lossÚloss_fcts                   r%   rt   z&PLBartForConditionalGeneration.forwardÚ   s2  € ð@ ÐØ Ð(Ð-BÐ-JÜ$6°v¸t¿{¹{×?WÑ?WÓ$XÐ!à&0 d§j¡jØð'
à)Ø/Ø+Ø#9Ø+Ø'Ø"7Øñ'
ð ñ'
ˆð —L‘L ×!:Ñ!:Ó;ˆ	Ø × 6Ñ 6× 9Ñ 9¸)×:JÑ:JÓ KÑKˆ	àˆØÐÜ'Ó)ˆHÙ% i§n¡n°R¸¿¹×9OÑ9OÓ&PÐRX×R]ÑR]Ð^`ÓRaÓbˆNäØØØ#×3Ñ3Ø")×"?Ñ"?Ø&×9Ñ9Ø$×5Ñ5Ø&-×&GÑ&GØ")×"?Ñ"?Ø&×9Ñ9ô

ð 
	
r$   c                 óB   — t        || j                  j                  «      S r.   )r   r)   rK   )r6   r—   s     r%   Ú%prepare_decoder_input_ids_from_labelszDPLBartForConditionalGeneration.prepare_decoder_input_ids_from_labels>  s   € Ü! &¨$¯+©+×*BÑ*BÓCÐCr$   )NT)
NNNNNNNNNN)r    r!   r"   r:   Ú_keys_to_ignore_on_load_missingru   r   rJ   Úintr{   r   Ú	EmbeddingrŠ   r‹   r   r   r   rv   rw   rx   ry   rz   r   r   r   r|   r
   rt   r¢   r@   rA   s   @r%   r2   r2   ¶   sÅ  ø„ ð  ÐØ':Ð&;Ð#àÐ/ðÐð˜|õ ð aeñØ!ðØ7:¸T±zðØY]ðà	�‰õð<¸ð <Àó <ð  ØØð .2Ø26Ø59Ø6:Ø:>Ø(,Ø26Ø:>Ø&*Ø!%ñ_
à×#Ñ# dÑ*ð_
ð ×(Ñ(¨4Ñ/ð_
ð !×+Ñ+¨dÑ2ð	_
ð
 !&§¡¨tÑ 3ð_
ð ˜e×/Ñ/Ñ0°4Ñ7ð_
ð  ™ð_
ð ×(Ñ(¨4Ñ/ð_
ð  %×0Ñ0°4Ñ7ð_
ð —‘˜tÑ#ð_
ð ˜$‘;ð_
ð Ð+Ñ,ð_
ð 
ˆu�|‰|Ñ	˜Ñ	.ò_
ó ó ó  ð_
ðBD¸E¿L¹L÷ Dr$   r2   c                   ó   — e Zd Zy)ÚPLBartClassificationHeadNr   r#   r$   r%   r§   r§   B  r&   r$   r§   c                   ó   ‡ — e Zd Zˆ fd„Zˆ xZS )ÚPLBartForSequenceClassificationc                  ó:   •—  t        «       j                  di | ¤Ž y)a©  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`] 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.
        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).
        Nr#   ©r/   rt   ©Úsuper_kwargsr8   s    €r%   rt   z'PLBartForSequenceClassification.forwardG  s   ø€ ð4 	Œ‹�‰Ñ'˜,Ó'r$   )r    r!   r"   rt   r@   rA   s   @r%   r©   r©   F  s   ø„ ÷(ð (r$   r©   c                   ó2   ‡ — e Zd Zeeˆ fd„«       «       Zˆ xZS )ÚPLBartForCausalLMc                  ó:   •—  t        «       j                  di | ¤Ž y)aF  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("uclanlp/plbart-base")
        >>> model = PLBartForCausalLM.from_pretrained("uclanlp/plbart-base")
        >>> 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¬   s    €r%   rt   zPLBartForCausalLM.forwarde  s   ø€ ð2 	Œ‹�‰Ñ'˜,Ó'r$   )r    r!   r"   r   r   rt   r@   rA   s   @r%   r¯   r¯   d  s   ø„ ØØó(ó ó ô(r$   r¯   )r¯   r2   r©   rG   r(   )3Ú__doc__rN   rv   r   Útorch.nnr   Ú r   r3   Úcache_utilsr   Ú
generationr   Úmodeling_outputsr	   r
   r   Úmodeling_utilsr   Úprocessing_utilsr   Úutilsr   r   r   Úutils.genericr   Úutils.output_capturingr   Úbart.modeling_bartr   r   r   r   r   Ú(bigbird_pegasus.modeling_bigbird_pegasusr   Úmbart.modeling_mbartr   Úconfiguration_plbartr   r   r(   rC   rE   rG   r2   r§   r©   r¯   Ú__all__r#   r$   r%   ú<module>rÁ      s  ðñ ã ã Ý Ý %å &Ý  Ý )÷ñ õ
 .Ý &ß IÑ IÝ 7Ý 5÷õ õ _Ý 5Ý .ô	Ð 7ô 	ð ô2˜Oó 2ó ð2ô	�Kô 	ô	�Kô 	ð ôg
Ð'ó g
ó ðg
ñT ðôô
DDÐ%:¸Oó DDóð
DDôN	Ð5ô 	ô(Ð&Mô (ô<(˜ô (ò:�r$   