
    Ngp                        d dl mZ d dlmZ d dlmZ d dlmZ d dlm	c m
Z d dlmZm	Z	 d dlmZ  G d d	e          Z G d
 de	j                  ZdS )    )annotations)Iterable)Enum)AnyN)Tensornn)SentenceTransformerc                  $    e Zd ZdZd Zd Zd ZdS )SiameseDistanceMetricz#The metric for the contrastive lossc                0    t          j        | |d          S )N   pFpairwise_distancexys     h/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/losses/ContrastiveLoss.py<lambda>zSiameseDistanceMetric.<lambda>       Q0A;;;     c                0    t          j        | |d          S )N   r   r   r   s     r   r   zSiameseDistanceMetric.<lambda>   r   r   c                2    dt          j        | |          z
  S )Nr   )r   cosine_similarityr   s     r   r   zSiameseDistanceMetric.<lambda>   s    1q':1a'@'@#@ r   N)__name__
__module____qualname____doc__	EUCLIDEAN	MANHATTANCOSINE_DISTANCE r   r   r   r      s,        --;;I;;I@@OOOr   r   c                  Z     e Zd Zej        ddfd fdZddZddZedd            Z	 xZ
S )ContrastiveLoss      ?Tmodelr	   marginfloatsize_averageboolreturnNonec                    t                                                       || _        || _        || _        || _        dS )a	  
        Contrastive loss. Expects as input two texts and a label of either 0 or 1. If the label == 1, then the distance between the
        two embeddings is reduced. If the label == 0, then the distance between the embeddings is increased.

        Args:
            model: SentenceTransformer model
            distance_metric: Function that returns a distance between
                two embeddings. The class SiameseDistanceMetric contains
                pre-defined metrices that can be used
            margin: Negative samples (label == 0) should have a distance
                of at least the margin value.
            size_average: Average by the size of the mini-batch.

        References:
            * Further information: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
            * `Training Examples > Quora Duplicate Questions <../../examples/training/quora_duplicate_questions/README.html>`_

        Requirements:
            1. (anchor, positive/negative) pairs

        Inputs:
            +-----------------------------------------------+------------------------------+
            | Texts                                         | Labels                       |
            +===============================================+==============================+
            | (anchor, positive/negative) pairs             | 1 if positive, 0 if negative |
            +-----------------------------------------------+------------------------------+

        Relations:
            - :class:`OnlineContrastiveLoss` is similar, but uses hard positive and hard negative pairs.
            It often yields better results.

        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."],
                    "label": [1, 0],
                })
                loss = losses.ContrastiveLoss(model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        N)super__init__distance_metricr*   r)   r,   )selfr)   r3   r*   r,   	__class__s        r   r2   zContrastiveLoss.__init__   s@    v 	.
(r   dict[str, Any]c                    | j         j        }t          t                                                    D ]\  }}|| j         k    rd| } n|| j        | j        dS )NzSiameseDistanceMetric.)r3   r*   r,   )r3   r   varsr   itemsr*   r,   )r4   distance_metric_namenamevalues       r   get_config_dictzContrastiveLoss.get_config_dictW   st    #3< 566<<>> 	 	KD%,,,'F'F'F$ - $84;`d`qrrrr   sentence_featuresIterable[dict[str, Tensor]]labelsr   c                     fd|D             }t          |          dk    sJ |\  }}                     ||          }d|                                |                    d          z  d|z
                                  t	          j         j        |z
                                d          z  z   z  } j        r|                                n|	                                S )Nc                F    g | ]}                     |          d          S )sentence_embedding)r)   ).0sentence_featurer4   s     r   
<listcomp>z+ContrastiveLoss.forward.<locals>.<listcomp>a   s-    mmmGW

+,,-ABmmmr   r   r(   r   )
lenr3   r+   powr   relur*   r,   meansum)r4   r>   r@   reps
rep_anchor	rep_other	distanceslossess   `       r   forwardzContrastiveLoss.forward`   s    mmmm[lmmm4yyA~~~~ $
I((Y??	LLNNY]]1---V0B0B0D0Dqvdk\eNeGfGfGjGjklGmGm0mm
 !% 1Cv{{}}}vzz||Cr   strc                    dS )Na~  
@inproceedings{hadsell2006dimensionality,
    author={Hadsell, R. and Chopra, S. and LeCun, Y.},
    booktitle={2006 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'06)},
    title={Dimensionality Reduction by Learning an Invariant Mapping},
    year={2006},
    volume={2},
    number={},
    pages={1735-1742},
    doi={10.1109/CVPR.2006.100}
}
r%   )r4   s    r   citationzContrastiveLoss.citationj   s     r   )r)   r	   r*   r+   r,   r-   r.   r/   )r.   r6   )r>   r?   r@   r   r.   r   )r.   rR   )r   r   r    r   r$   r2   r=   rQ   propertyrT   __classcell__)r5   s   @r   r'   r'      s         .=!?) ?) ?) ?) ?) ?) ?)Bs s s sD D D D    X    r   r'   )
__future__r   collections.abcr   enumr   typingr   torch.nn.functionalr   
functionalr   torchr   )sentence_transformers.SentenceTransformerr	   r   Moduler'   r%   r   r   <module>r`      s   " " " " " " $ $ $ $ $ $                              I I I I I IA A A A AD A A Ab b b b bbi b b b b br   