Ë
    l^(h6  ã                  ó¢   — 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y)é    )Úannotations)ÚIterable)ÚEnum)ÚAnyN)ÚTensorÚnn)ÚSentenceTransformerc                  ó"   — e Zd ZdZd„ Zd„ Zd„ Zy)ÚTripletDistanceMetriczThe metric for the triplet lossc                ó4   — dt        j                  | |«      z
  S )Né   )ÚFÚcosine_similarity©ÚxÚys     úf/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/losses/TripletLoss.pyú<lambda>zTripletDistanceMetric.<lambda>   s   € ˜!œa×1Ñ1°!°QÓ7Ñ7€ ó    c                ó2   — t        j                  | |d¬«      S )Né   ©Úp©r   Úpairwise_distancer   s     r   r   zTripletDistanceMetric.<lambda>   ó   € œQ×0Ñ0°°A¸Ô;€ r   c                ó2   — t        j                  | |d¬«      S )Nr   r   r   r   s     r   r   zTripletDistanceMetric.<lambda>   r   r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚCOSINEÚ	EUCLIDEANÚ	MANHATTAN© r   r   r   r      s   „ Ù)á7€FÙ;€IÙ;�Ir   r   c                  óf   ‡ — e Zd Zej                  df	 	 	 	 	 dˆ fd„Zdd„Zdd„Zed	d„«       Z	ˆ xZ
S )
ÚTripletLossé   c                óL   •— t         ‰| �  «        || _        || _        || _        y)a¤  
        This class implements triplet loss. Given a triplet of (anchor, positive, negative),
        the loss minimizes the distance between anchor and positive while it maximizes the distance
        between anchor and negative. It compute the following loss function:

        ``loss = max(||anchor - positive|| - ||anchor - negative|| + margin, 0)``.

        Margin is an important hyperparameter and needs to be tuned respectively.

        Args:
            model: SentenceTransformerModel
            distance_metric: Function to compute distance between two
                embeddings. The class TripletDistanceMetric contains
                common distance metrices that can be used.
            triplet_margin: The negative should be at least this much
                further away from the anchor than the positive.

        References:
            - For further details, see: https://en.wikipedia.org/wiki/Triplet_loss

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

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

        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."],
                    "negative": ["It's quite rainy, sadly.", "She walked to the store."],
                })
                loss = losses.TripletLoss(model=model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        N)ÚsuperÚ__init__ÚmodelÚdistance_metricÚtriplet_margin)Úselfr,   r-   r.   Ú	__class__s       €r   r+   zTripletLoss.__init__   s(   ø€ ôl 	‰ÑÔØˆŒ
Ø.ˆÔØ,ˆÕr   c                ó  — |D �cg c]  }| j                  |«      d   ‘Œ }}|\  }}}| j                  ||«      }| j                  ||«      }	t        j                  ||	z
  | j                  z   «      }
|
j                  «       S c c}w )NÚsentence_embedding)r,   r-   r   Úrelur.   Úmean)r/   Úsentence_featuresÚlabelsÚsentence_featureÚrepsÚ
rep_anchorÚrep_posÚrep_negÚdistance_posÚdistance_negÚlossess              r   ÚforwardzTripletLoss.forwardQ   s†   € Ø[lÖmÐGW�—
‘
Ð+Ó,Ð-AÓBÐmˆÐmà'+Ñ$ˆ
�G˜WØ×+Ñ+¨J¸Ó@ˆØ×+Ñ+¨J¸Ó@ˆä—‘˜ |Ñ3°d×6IÑ6IÑIÓJˆØ�{‰{‹}Ðùò ns   …Bc                óÂ   — | j                   j                  }t        t        «      j	                  «       D ]  \  }}|| j                   k(  sŒd|› �} n || j
                  dœS )NzTripletDistanceMetric.)r-   r.   )r-   r   Úvarsr   Úitemsr.   )r/   Údistance_metric_nameÚnameÚvalues       r   Úget_config_dictzTripletLoss.get_config_dict[   sg   € Ø#×3Ñ3×<Ñ<ÐÜÔ 5Ó6×<Ñ<Ó>ò 	‰KˆD�%Ø˜×,Ñ,Ó,Ø)?À¸vÐ'FÐ$Ùð	ð
 $8È4×K^ÑK^Ñ_Ð_r   c                 ó   — y)Na  
@misc{hermans2017defense,
    title={In Defense of the Triplet Loss for Person Re-Identification},
    author={Alexander Hermans and Lucas Beyer and Bastian Leibe},
    year={2017},
    eprint={1703.07737},
    archivePrefix={arXiv},
    primaryClass={cs.CV}
}
r%   )r/   s    r   ÚcitationzTripletLoss.citationd   s   € ð	r   )r,   r	   r.   ÚfloatÚreturnÚNone)r5   zIterable[dict[str, Tensor]]r6   r   rJ   r   )rJ   zdict[str, Any])rJ   Ústr)r   r   r    r   r#   r+   r?   rF   ÚpropertyrH   Ú__classcell__)r0   s   @r   r'   r'      sL   ø„ à:O×:YÑ:YÐstð9-Ø(ð9-Økpð9-à	õ9-óvó`ð ò
ó ô
r   r'   )Ú
__future__r   Úcollections.abcr   Úenumr   Útypingr   Útorch.nn.functionalr   Ú
functionalr   Útorchr   Ú)sentence_transformers.SentenceTransformerr	   r   ÚModuler'   r%   r   r   ú<module>rX      s;   ðÝ "å $Ý Ý ç Ð ß å Iô<˜Dô <ôZ�"—)‘)õ Zr   