Ë
    l^(h-  ã                  ó‚   — d dl mZ d dlmZ d dlmZ d dlZd dlmZmZ d dl	m
Z
 d dlmZ  G d„ d	ej                  «      Zy)
é    )Úannotations)ÚIterable)ÚAnyN)ÚTensorÚnn)Úutil)ÚSentenceTransformerc                  ó\   ‡ — e Zd Zdej                  fdˆ fd„Zdd„Zdd„Zed	d„«       Z	ˆ xZ
S )
Ú
CoSENTLossg      4@c                óL   •— t         ‰| �  «        || _        || _        || _        y)aÍ  
        This class implements CoSENT (Cosine Sentence) loss.
        It expects that each of the InputExamples consists of a pair of texts and a float valued label, representing
        the expected similarity score between the pair.

        It computes the following loss function:

        ``loss = logsum(1+exp(s(i,j)-s(k,l))+exp...)``, where ``(i,j)`` and ``(k,l)`` are any of the input pairs in the
        batch such that the expected similarity of ``(i,j)`` is greater than ``(k,l)``. The summation is over all possible
        pairs of input pairs in the batch that match this condition.

        Anecdotal experiments show that this loss function produces a more powerful training signal than :class:`CosineSimilarityLoss`,
        resulting in faster convergence and a final model with superior performance. Consequently, CoSENTLoss may be used
        as a drop-in replacement for :class:`CosineSimilarityLoss` in any training script.

        Args:
            model: SentenceTransformerModel
            similarity_fct: Function to compute the PAIRWISE similarity
                between embeddings. Default is
                ``util.pairwise_cos_sim``.
            scale: Output of similarity function is multiplied by scale
                value. Represents the inverse temperature.

        References:
            - For further details, see: https://kexue.fm/archives/8847

        Requirements:
            - Sentence pairs with corresponding similarity scores in range of the similarity function. Default is [-1,1].

        Inputs:
            +--------------------------------+------------------------+
            | Texts                          | Labels                 |
            +================================+========================+
            | (sentence_A, sentence_B) pairs | float similarity score |
            +--------------------------------+------------------------+

        Relations:
            - :class:`AnglELoss` is CoSENTLoss with ``pairwise_angle_sim`` as the metric, rather than ``pairwise_cos_sim``.
            - :class:`CosineSimilarityLoss` seems to produce a weaker training signal than CoSENTLoss. In our experiments, CoSENTLoss is recommended.

        Example:
            ::

                from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses
                from datasets import Dataset

                model = SentenceTransformer("microsoft/mpnet-base")
                train_dataset = Dataset.from_dict({
                    "sentence1": ["It's nice weather outside today.", "He drove to work."],
                    "sentence2": ["It's so sunny.", "She walked to the store."],
                    "score": [1.0, 0.3],
                })
                loss = losses.CoSENTLoss(model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        N)ÚsuperÚ__init__ÚmodelÚsimilarity_fctÚscale)Úselfr   r   r   Ú	__class__s       €úe/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/losses/CoSENTLoss.pyr   zCoSENTLoss.__init__   s'   ø€ ô| 	‰ÑÔØˆŒ
Ø,ˆÔØˆ�
ó    c                óø  — |D �cg c]  }| j                  |«      d   ‘Œ }}| j                  |d   |d   «      }|| j                  z  }|d d …d f   |d d d …f   z
  }|d d …d f   |d d d …f   k  }|j                  «       }|d|z
  dz  z
  }t	        j
                  t	        j                  d«      j                  |j                  «      |j                  d«      fd¬«      }t	        j                  |d¬«      }|S c c}w )NÚsentence_embeddingr   é   g   ¢”mBéÿÿÿÿ)Údim)r   r   r   ÚfloatÚtorchÚcatÚzerosÚtoÚdeviceÚviewÚ	logsumexp)r   Úsentence_featuresÚlabelsÚsentence_featureÚ
embeddingsÚscoresÚlosss          r   ÚforwardzCoSENTLoss.forwardQ   sö   € ØarÖsÐM]�d—j‘jÐ!1Ó2Ð3GÓHÐsˆ
Ðsà×$Ñ$ Z°¡]°J¸q±MÓBˆØ˜$Ÿ*™*Ñ$ˆØš˜4˜‘ 6¨$²¨'¡?Ñ2ˆð š˜4˜‘ 6¨$²¨'¡?Ñ2ˆØ—‘“ˆð ˜1˜v™:¨Ñ-Ñ-ˆô —‘œEŸK™K¨›N×-Ñ-¨f¯m©mÓ<¸f¿k¹kÈ"»oÐNÐTUÔVˆÜ�‰˜v¨1Ô-ˆàˆùò# ts   …C7c                óH   — | j                   | j                  j                  dœS )N)r   r   )r   r   Ú__name__©r   s    r   Úget_config_dictzCoSENTLoss.get_config_dicte   s   € ØŸ™°t×7JÑ7J×7SÑ7SÑTÐTr   c                 ó   — y)NzÎ
@online{kexuefm-8847,
    title={CoSENT: A more efficient sentence vector scheme than Sentence-BERT},
    author={Su Jianlin},
    year={2022},
    month={Jan},
    url={https://kexue.fm/archives/8847},
}
© r,   s    r   ÚcitationzCoSENTLoss.citationh   s   € ðr   )r   r	   r   r   ÚreturnÚNone)r#   zIterable[dict[str, Tensor]]r$   r   r1   r   )r1   zdict[str, Any])r1   Ústr)r+   Ú
__module__Ú__qualname__r   Úpairwise_cos_simr   r)   r-   Úpropertyr0   Ú__classcell__)r   s   @r   r   r      s5   ø„ ØBFÐW[×WlÑWlö AóFó(Uð ò	ó ô	r   r   )Ú
__future__r   Úcollections.abcr   Útypingr   r   r   r   Úsentence_transformersr   Ú)sentence_transformers.SentenceTransformerr	   ÚModuler   r/   r   r   ú<module>r?      s,   ðÝ "å $Ý ã ß å &Ý Iôe�—‘õ er   