
    i                        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                  d     e Zd Zdej                  fd fdZddZd	dZd
dZe	dd       Z
 xZS )MultipleNegativesRankingLossg      4@c                ~    t         |           || _        || _        || _        t        j                         | _        y)a  
        Given a list of (anchor, positive) pairs or (anchor, positive, negative) triplets, this loss optimizes the following:

        1. Given an anchor (e.g. a question), assign the highest similarity to the corresponding positive (i.e. answer)
           out of every single positive and negative (e.g. all answers) in the batch.

        If you provide the optional negatives, they will all be used as extra options from which the model must pick the
        correct positive. Within reason, the harder this "picking" is, the stronger the model will become. Because of
        this, a higher batch size results in more in-batch negatives, which then increases performance (to a point).

        This loss function works great to train embeddings for retrieval setups where you have positive pairs
        (e.g. (query, answer)) as it will sample in each batch ``n-1`` negative docs randomly.

        This loss is also known as InfoNCE loss, SimCSE loss, Cross-Entropy Loss with in-batch negatives, or simply
        in-batch negatives loss.

        Args:
            model: SentenceTransformer model
            scale: Output of similarity function is multiplied by scale
                value
            similarity_fct: similarity function between sentence
                embeddings. By default, cos_sim. Can also be set to dot
                product (and then set scale to 1)

        References:
            - Efficient Natural Language Response Suggestion for Smart Reply, Section 4.4: https://arxiv.org/pdf/1705.00652.pdf
            - `Training Examples > Natural Language Inference <../../../examples/sentence_transformer/training/nli/README.html>`_
            - `Training Examples > Paraphrase Data <../../../examples/sentence_transformer/training/paraphrases/README.html>`_
            - `Training Examples > Quora Duplicate Questions <../../../examples/sentence_transformer/training/quora_duplicate_questions/README.html>`_
            - `Training Examples > MS MARCO <../../../examples/sentence_transformer/training/ms_marco/README.html>`_
            - `Unsupervised Learning > SimCSE <../../../examples/sentence_transformer/unsupervised_learning/SimCSE/README.html>`_
            - `Unsupervised Learning > GenQ <../../../examples/sentence_transformer/unsupervised_learning/query_generation/README.html>`_

        Requirements:
            1. (anchor, positive) pairs or (anchor, positive, negative) triplets

        Inputs:
            +-------------------------------------------------+--------+
            | Texts                                           | Labels |
            +=================================================+========+
            | (anchor, positive) pairs                        | none   |
            +-------------------------------------------------+--------+
            | (anchor, positive, negative) triplets           | none   |
            +-------------------------------------------------+--------+
            | (anchor, positive, negative_1, ..., negative_n) | none   |
            +-------------------------------------------------+--------+

        Recommendations:
            - Use ``BatchSamplers.NO_DUPLICATES`` (:class:`docs <sentence_transformers.training_args.BatchSamplers>`) to
              ensure that no in-batch negatives are duplicates of the anchor or positive samples.

        Relations:
            - :class:`CachedMultipleNegativesRankingLoss` is equivalent to this loss, but it uses caching that allows for
              much higher batch sizes (and thus better performance) without extra memory usage. However, it is slightly
              slower.
            - :class:`MultipleNegativesSymmetricRankingLoss` is equivalent to this loss, but with an additional loss term.
            - :class:`GISTEmbedLoss` is equivalent to this loss, but uses a guide model to guide the in-batch negative
              sample selection. `GISTEmbedLoss` yields a stronger training signal at the cost of some training overhead.

        Example:
            ::

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

                model = SentenceTransformer("microsoft/mpnet-base")
                train_dataset = Dataset.from_dict({
                    "anchor": ["It's nice weather outside today.", "He drove to work."],
                    "positive": ["It's so sunny.", "He took the car to the office."],
                })
                loss = losses.MultipleNegativesRankingLoss(model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        N)super__init__modelscalesimilarity_fctr   CrossEntropyLosscross_entropy_loss)selfr   r   r   	__class__s       w/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/sentence_transformers/losses/MultipleNegativesRankingLoss.pyr   z%MultipleNegativesRankingLoss.__init__   s8    ` 	

,"$"5"5"7    c                r    |D cg c]  }| j                  |      d    }}| j                  ||      S c c}w )Nsentence_embedding)r   compute_loss_from_embeddings)r   sentence_featureslabelssentence_feature
embeddingss        r   forwardz$MultipleNegativesRankingLoss.forwardd   s?    arsM]djj!123GHs
s00VDD ts   4c                    |d   }t        j                  |dd       }| j                  ||      | j                  z  }t        j                  d|j                  d      |j                        }| j                  ||      S )z
        Compute the multiple negatives ranking loss from embeddings.

        Args:
            embeddings: List of embeddings

        Returns:
            Loss value
        r      N)device)torchcatr   r   arangesizer"   r   )r   r   r   anchors
candidatesscoresrange_labelss          r   r   z9MultipleNegativesRankingLoss.compute_loss_from_embeddingsj   sq     Q-YYz!"~.
 $$Wj9DJJF
 ||Av{{1~fmmL&&v|<<r   c                H    | j                   | j                  j                  dS )N)r   r   )r   r   __name__r   s    r   get_config_dictz,MultipleNegativesRankingLoss.get_config_dict   s    t7J7J7S7STTr   c                     y)Nat  
@misc{henderson2017efficient,
    title={Efficient Natural Language Response Suggestion for Smart Reply},
    author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
    year={2017},
    eprint={1705.00652},
    archivePrefix={arXiv},
    primaryClass={cs.CL}
}
 r-   s    r   citationz%MultipleNegativesRankingLoss.citation   s    	r   )r   r	   r   floatreturnNone)r   zIterable[dict[str, Tensor]]r   r   r3   r   )r   zlist[Tensor]r   r   r3   r   )r3   zdict[str, Any])r3   str)r,   
__module____qualname__r   cos_simr   r   r   r.   propertyr1   __classcell__)r   s   @r   r   r      s;    BFW[WcWc T8lE=2U 
 
r   r   )
__future__r   collections.abcr   typingr   r#   r   r   sentence_transformersr   )sentence_transformers.SentenceTransformerr	   Moduler   r0   r   r   <module>rA      s,    " $    & ID299 Dr   