Ë
    l^(hÔ(  ã                  ó²   — d dl mZ d dlZd dlmZ d dlmZmZ d dlm	Z	m
Z
mZmZ d dlmZ d dlmZ  ej"                  e«      Z G d„ d	ej(                  «      Zy)
é    )ÚannotationsN)ÚIterable)ÚTensorÚnn)Ú
AutoConfigÚAutoModelForCausalLMÚAutoTokenizerÚPreTrainedModel)ÚSentenceTransformer)ÚStaticEmbeddingc                  óT   ‡ — e Zd Z	 d	 	 	 	 	 	 	 dˆ fd„Zdd„Zdd„Zed	d„«       Zˆ xZS )
ÚDenoisingAutoEncoderLossc                ó,  •— t         ‰	| �  «        t        |d   t        «      rt	        d«      ‚|| _        |j                  | _        |d   j                  j                  j                  }|€	|sJ d«       ‚|r|rt        j                  d«       |}t        j                  |«      | _        t        | j                  t!        | j                  «      «       | _        t%        j                  |«      }d|_        d|_        d|i}	 t+        j                  |fi |¤Ž| _        |d   j                  j                  j0                  |j0                  k(  sJ d
«       ‚| j                  j2                  €^| j                  j4                  | j                  _        | j,                  j                  j6                  | j,                  j                  _        t;        t        j                  |«      «      t;        | j                  «      k7  rt        j                  d«       |rù| j"                  rJ d«       ‚t;        | j                  «      t;        | j                  «      k7  rT| j                  | _        | j,                  j=                  t;        | j                  «      «       t        j                  d«       | j,                  j>                  }	 tA        jB                  |d   j                  | j,                  jD                  |   | j,                  j>                  «       yy# t        $ r }t        j/                  d|› d	�«       |‚d}~ww xY w# tF        $ rS tA        jB                  |d   j                  | j,                  jD                  |   | j,                  j>                  |«       Y yw xY w)a[  
        This loss expects as input a pairs of damaged sentences and the corresponding original ones.
        During training, the decoder reconstructs the original sentences from the encoded sentence embeddings.
        Here the argument 'decoder_name_or_path' indicates the pretrained model (supported by Hugging Face) to be used as the decoder.
        Since decoding process is included, here the decoder should have a class called XXXLMHead (in the context of Hugging Face's Transformers).
        The 'tie_encoder_decoder' flag indicates whether to tie the trainable parameters of encoder and decoder,
        which is shown beneficial to model performance while limiting the amount of required memory.
        Only when the encoder and decoder are from the same architecture, can the flag 'tie_encoder_decoder' work.

        The data generation process (i.e. the 'damaging' process) has already been implemented in ``DenoisingAutoEncoderDataset``,
        allowing you to only provide regular sentences.

        Args:
            model (SentenceTransformer): The SentenceTransformer model.
            decoder_name_or_path (str, optional): Model name or path for initializing a decoder (compatible with Hugging Face's Transformers). Defaults to None.
            tie_encoder_decoder (bool): Whether to tie the trainable parameters of encoder and decoder. Defaults to True.

        References:
            * TSDAE paper: https://arxiv.org/pdf/2104.06979.pdf
            * `Unsupervised Learning > TSDAE <../../../examples/sentence_transformer/unsupervised_learning/TSDAE/README.html>`_

        Requirements:
            1. The decoder should have a class called XXXLMHead (in the context of Hugging Face's Transformers)
            2. Should use a large corpus

        Inputs:
            +------------------------------------------------------+--------+
            | Texts                                                | Labels |
            +======================================================+========+
            | (damaged\_sentence, original\_sentence) pairs        | none   |
            +------------------------------------------------------+--------+
            | sentence fed through ``DenoisingAutoEncoderDataset`` | none   |
            +------------------------------------------------------+--------+

        Example:
            ::

                from sentence_transformers import SentenceTransformer, losses
                from sentence_transformers.datasets import DenoisingAutoEncoderDataset
                from torch.utils.data import DataLoader

                model_name = "bert-base-cased"
                model = SentenceTransformer(model_name)
                train_sentences = [
                    "First training sentence", "Second training sentence", "Third training sentence", "Fourth training sentence",
                ]
                batch_size = 2
                train_dataset = DenoisingAutoEncoderDataset(train_sentences)
                train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)
                train_loss = losses.DenoisingAutoEncoderLoss(
                    model, decoder_name_or_path=model_name, tie_encoder_decoder=True
                )
                model.fit(
                    train_objectives=[(train_dataloader, train_loss)],
                    epochs=10,
                )
        r   zgDenoisingAutoEncoderLoss is not compatible with a SentenceTransformer model based on a StaticEmbedding.NzOMust indicate the decoder_name_or_path argument when tie_encoder_decoder=False!zHWhen tie_encoder_decoder=True, the decoder_name_or_path will be invalid.TÚconfigzModel name or path "zc" does not support being as a decoder. Please make sure the decoder model has an "XXXLMHead" class.zHidden sizes do not match!znWARNING: The vocabulary of the encoder has been changed. One might need to change the decoder vocabulary, too.z@The tokenizers should be the same when tie_encoder_decoder=True.zˆSince the encoder vocabulary has been changed and --tie_encoder_decoder=True, now the new vocabulary has also been used for the decoder.)$ÚsuperÚ__init__Ú
isinstancer   Ú
ValueErrorÚencoderÚ	tokenizerÚtokenizer_encoderÚ
auto_modelr   Ú_name_or_pathÚloggerÚwarningr	   Úfrom_pretrainedÚtokenizer_decoderÚtypeÚneed_retokenizationr   Ú
is_decoderÚadd_cross_attentionr   ÚdecoderÚerrorÚhidden_sizeÚ	pad_tokenÚ	eos_tokenÚeos_token_idÚpad_token_idÚlenÚresize_token_embeddingsÚbase_model_prefixr
   Ú_tie_encoder_decoder_weightsÚ_modulesÚ	TypeError)
ÚselfÚmodelÚdecoder_name_or_pathÚtie_encoder_decoderÚencoder_name_or_pathÚdecoder_configÚkwargs_decoderÚeÚdecoder_base_model_prefixÚ	__class__s
            €ús/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/losses/DenoisingAutoEncoderLoss.pyr   z!DenoisingAutoEncoderLoss.__init__   s  ø€ ôx 	‰ÑÔä�e˜A‘h¤Ô0ÜØyóð ð ˆŒØ!&§¡ˆÔà$ Q™x×2Ñ2×9Ñ9×GÑGÐØÐ'á#ðaà`óaØ#áÙ#Ü—‘ÐiÔjØ#7Ð ä!.×!>Ñ!>Ð?SÓ!TˆÔÜ'1°$×2HÑ2HÌ$Èt×OeÑOeÓJfÓ'gÐ#gˆÔ ä#×3Ñ3Ð4HÓIˆØ$(ˆÔ!Ø-1ˆÔ*Ø" NÐ3ˆð	Ü/×?Ñ?Ð@TÑgÐXfÑgˆDŒLð �Q‰x×"Ñ"×)Ñ)×5Ñ5¸×9SÑ9SÒSÐqÐUqÓqÐSØ×!Ñ!×+Ñ+Ð3à/3×/EÑ/E×/OÑ/OˆD×"Ñ"Ô,Ø/3¯|©|×/BÑ/B×/OÑ/OˆD�L‰L×ÑÔ,äŒ}×,Ñ,Ð-AÓBÓCÄsÈ4×KaÑKaÓGbÒbÜ�N‰Nð Aôñ Ø×/Ò/ÐsÐ1sÓsÐ/Ü�4×)Ñ)Ó*¬c°$×2HÑ2HÓ.IÒIØ)-×)?Ñ)?�Ô&Ø—‘×4Ñ4´S¸×9OÑ9OÓ5PÔQÜ—‘ð _ôð )-¯©×(FÑ(FÐ%ðä×<Ñ<Ø˜!‘H×'Ñ'Ø—L‘L×)Ñ)Ð*CÑDØ—L‘L×2Ñ2õð øô! ò 	Ü�L‰LØ&Ð';Ð&<ð  =`ð  aôð ˆGûð		ûô@ ò ä×<Ñ<Ø˜!‘H×'Ñ'Ø—L‘L×)Ñ)Ð*CÑDØ—L‘L×2Ñ2Ø(ö	ðús,   Ä L Ê:AL7 Ì	L4ÌL/Ì/L4Ì7ANÎNc                ó®   — |d   }|j                   }| j                  j                  |dd¬«      }| j                  |dddd ¬«      j	                  |«      }|S )NÚ	input_idsT)Úskip_special_tokensÚclean_up_tokenization_spacesÚlongest_firstÚpt)ÚpaddingÚ
truncationÚreturn_tensorsÚ
max_length)Údevicer   Úbatch_decoder   Úto)r/   Úsentence_featuresr;   rD   Úsentences_decodedÚretokenizeds         r9   Ú
retokenizez#DenoisingAutoEncoderLoss.retokenize’   ss   € Ø% kÑ2ˆ	Ø×!Ñ!ˆØ ×2Ñ2×?Ñ?Ø¨4Èdð @ó 
Ðð ×,Ñ,Ø t¸ÐX\Ðimð -ó 
ç
‰"ˆV‹*ð 	ð Ðó    c           
     ó"  — t        |«      \  }}| j                  r| j                  |«      }| j                  |«      d   }|d   j                  d   }|d   j                  «       d d …d |dz
  …f   }|d   d d …dd …f   }| j                  |d d |d d …d f   |d   d d …dd…f   d d d¬«      }	|	d   }
t        j                  | j                  j                  ¬«      } ||
j                  d	|
j                  d	   «      |j                  d	«      «      }|S )
NÚsentence_embeddingr;   é   Úattention_maskr   F)r;   Úinputs_embedsrO   Úencoder_hidden_statesÚencoder_attention_maskÚlabelsÚreturn_dictÚ	use_cache)Úignore_indexéÿÿÿÿ)Útupler   rJ   r   ÚshapeÚcloner"   r   ÚCrossEntropyLossr   r(   ÚviewÚreshape)r/   rG   rS   Úsource_featuresÚtarget_featuresÚrepsÚtarget_lengthÚdecoder_input_idsÚ	label_idsÚdecoder_outputsÚ	lm_logitsÚce_loss_fctÚlosss                r9   Úforwardz DenoisingAutoEncoderLoss.forward�   s6  € Ü+0Ð1BÓ+CÑ(ˆ˜Ø×#Ò#ð #Ÿo™o¨oÓ>ˆOØ�|‰|˜OÓ,Ð-AÑBˆð (¨Ñ4×:Ñ:¸1Ñ=ˆØ+¨KÑ8×>Ñ>Ó@ÂÐDWÀmÐVWÑFWÐDWÐAWÑXÐØ# KÑ0²°A±B°Ñ7ˆ	ð Ÿ,™,Ø'ØØØ"&¢q¨$ w¡-Ø#2Ð3CÑ#DÂQÈÈ!ÈÀVÑ#LØØØð 'ó 	
ˆð $ AÑ&ˆ	Ü×)Ñ)°t×7MÑ7M×7ZÑ7ZÔ[ˆÙ˜9Ÿ>™>¨"¨i¯o©o¸bÑ.AÓBÀI×DUÑDUÐVXÓDYÓZˆØˆrK   c                 ó   — y)Na  
@inproceedings{wang-2021-TSDAE,
    title = "TSDAE: Using Transformer-based Sequential Denoising Auto-Encoderfor Unsupervised Sentence Embedding Learning",
    author = "Wang, Kexin and Reimers, Nils and Gurevych, Iryna",
    booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2021",
    month = nov,
    year = "2021",
    address = "Punta Cana, Dominican Republic",
    publisher = "Association for Computational Linguistics",
    pages = "671--688",
    url = "https://arxiv.org/abs/2104.06979",
}
© )r/   s    r9   Úcitationz!DenoisingAutoEncoderLoss.citation¼   s   € ðrK   )NT)r0   r   r1   z
str | Noner2   ÚboolÚreturnÚNone)rG   údict[str, Tensor]rm   ro   )rG   zIterable[dict[str, Tensor]]rS   r   rm   r   )rm   Ústr)	Ú__name__Ú
__module__Ú__qualname__r   rJ   rh   Úpropertyrk   Ú__classcell__)r8   s   @r9   r   r      sO   ø„ àosð@Ø(ð@Ø@Jð@Øhlð@à	õ@óD	óð> òó ôrK   r   )Ú
__future__r   ÚloggingÚcollections.abcr   Útorchr   r   Útransformersr   r   r	   r
   Úsentence_transformersr   Úsentence_transformers.modelsr   Ú	getLoggerrq   r   ÚModuler   rj   rK   r9   ú<module>r      sA   ðÝ "ã Ý $ç ß YÓ Yå 5Ý 8à	ˆ×	Ñ	˜8Ó	$€ô{˜rŸy™yõ {rK   