
    Ng0                        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          Z G d	 d
ej                  ZdS )    )annotations)IterableN)Tensornn)util)SentenceTransformerc                  D    e Zd ZdZed	d            Zed
d	d            ZdS )$BatchHardTripletLossDistanceFunctionz`This class defines distance functions, that can be used with Batch[All/Hard/SemiHard]TripletLoss
embeddingsr   returnc                2    dt          j        | |           z
  S )zWCompute the 2D matrix of cosine distances (1-cosine_similarity) between all embeddings.   )r   pytorch_cos_sim)r   s    m/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/losses/BatchHardTripletLoss.pycosine_distancez4BatchHardTripletLossDistanceFunction.cosine_distance   s     4'
J????    Fc                   t          j        | |                                           }t          j        |          }|                    d          d|z  z
  |                    d          z   }d||dk     <   |sI|                    d                                          }||dz  z   }d|z
  t          j        |          z  }|S )a  
        Compute the 2D matrix of eucledian distances between all the embeddings.
        Args:
            embeddings: tensor of shape (batch_size, embed_dim)
            squared: Boolean. If true, output is the pairwise squared euclidean distance matrix.
                     If false, output is the pairwise euclidean distance matrix.
        Returns:
            pairwise_distances: tensor of shape (batch_size, batch_size)
        r   g       @r   gؗҜ<      ?)torchmatmultdiag	unsqueezeeqfloatsqrt)r   squareddot_productsquare_norm	distancesmasks         r   eucledian_distancez7BatchHardTripletLossDistanceFunction.eucledian_distance   s     l:z||~~>>
 j--
  ))!,,s[/@@;CXCXYZC[C[[	 $%	)a-  	= <<??((**D!D5L0Ituz)'<'<<Ir   N)r   r   r   r   )F)__name__
__module____qualname____doc__staticmethodr   r"    r   r   r
   r
      sa        jj@ @ @ \@ " " " " \" " "r   r
   c                       e Zd Zej        dfd fdZddZddZedd            Z	edd            Z
edd            Zedd            Z xZS )BatchHardTripletLoss   modelr   marginr   r   Nonec                r    t                                                       || _        || _        || _        dS )a>  
        BatchHardTripletLoss takes a batch with (sentence, label) pairs and computes the loss for all possible, valid
        triplets, i.e., anchor and positive must have the same label, anchor and negative a different label. It then looks
        for the hardest positive and the hardest negatives.
        The labels must be integers, with same label indicating sentences from the same class. Your train dataset
        must contain at least 2 examples per label class.

        Args:
            model: SentenceTransformer model
            distance_metric: Function that returns a distance between
                two embeddings. The class SiameseDistanceMetric contains
                pre-defined metrics that can be used
            margin: Negative samples should be at least margin further
                apart from the anchor than the positive.

        Definitions:
            :Easy triplets: Triplets which have a loss of 0 because
                ``distance(anchor, positive) + margin < distance(anchor, negative)``.
            :Hard triplets: Triplets where the negative is closer to the anchor than the positive, i.e.,
                ``distance(anchor, negative) < distance(anchor, positive)``.
            :Semi-hard triplets: Triplets where the negative is not closer to the anchor than the positive, but which
                still have a positive loss, i.e., ``distance(anchor, positive) < distance(anchor, negative) + margin``.

        References:
            * Source: https://github.com/NegatioN/OnlineMiningTripletLoss/blob/master/online_triplet_loss/losses.py
            * Paper: In Defense of the Triplet Loss for Person Re-Identification, https://arxiv.org/abs/1703.07737
            * Blog post: https://omoindrot.github.io/triplet-loss

        Requirements:
            1. Each sentence must be labeled with a class.
            2. Your dataset must contain at least 2 examples per labels class.
            3. Your dataset should contain hard positives and negatives.

        Inputs:
            +------------------+--------+
            | Texts            | Labels |
            +==================+========+
            | single sentences | class  |
            +------------------+--------+

        Recommendations:
            - Use ``BatchSamplers.GROUP_BY_LABEL`` (:class:`docs <sentence_transformers.training_args.BatchSamplers>`) to
              ensure that each batch contains 2+ examples per label class.

        Relations:
            * :class:`BatchAllTripletLoss` uses all possible, valid triplets, rather than only the hardest positive and negative samples.
            * :class:`BatchSemiHardTripletLoss` uses only semi-hard triplets, valid triplets, rather than only the hardest positive and negative samples.
            * :class:`BatchHardSoftMarginTripletLoss` does not require setting a margin, while this loss does.

        Example:
            ::

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

                model = SentenceTransformer("microsoft/mpnet-base")
                # E.g. 0: sports, 1: economy, 2: politics
                train_dataset = Dataset.from_dict({
                    "sentence": [
                        "He played a great game.",
                        "The stock is up 20%",
                        "They won 2-1.",
                        "The last goal was amazing.",
                        "They all voted against the bill.",
                    ],
                    "label": [0, 1, 0, 0, 2],
                })
                loss = losses.BatchHardTripletLoss(model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        N)super__init__sentence_embeddertriplet_margindistance_metric)selfr,   r4   r-   	__class__s       r   r1   zBatchHardTripletLoss.__init__;   s:    d 	!&$.r   sentence_featuresIterable[dict[str, Tensor]]labelsr   c                p    |                      |d                   d         }|                     ||          S )Nr   sentence_embedding)r2   batch_hard_triplet_loss)r5   r7   r9   reps       r   forwardzBatchHardTripletLoss.forward   s7    $$%6q%9::;OP++FC888r   r   c                   |                      |          }t                              |                                          }||z  }|                    dd          \  }}t                              |                                          }|                    dd          \  }	}||	d|z
  z  z   }
|
                    dd          \  }}||z
  | j        z   }d||dk     <   |                                }|S )ab  Build the triplet loss over a batch of embeddings.
        For each anchor, we get the hardest positive and hardest negative to form a triplet.
        Args:
            labels: labels of the batch, of size (batch_size,)
            embeddings: tensor of shape (batch_size, embed_dim)
            margin: margin for triplet loss
            squared: Boolean. If true, output is the pairwise squared euclidean distance matrix.
                     If false, output is the pairwise euclidean distance matrix.
        Returns:
            Label_Sentence_Triplet: scalar tensor containing the triplet loss
        r   T)keepdimr   r   )	r4   r*    get_anchor_positive_triplet_maskr   max get_anchor_negative_triplet_maskminr3   mean)r5   r9   r   pairwise_distmask_anchor_positiveanchor_positive_disthardest_positive_dist_mask_anchor_negativemax_anchor_negative_distanchor_negative_disthardest_negative_disttltriplet_losss                 r   r<   z,BatchHardTripletLoss.batch_hard_triplet_loss   s    ,,Z88  4TTU[\\bbdd  4mC $8#;#;At#;#L#L q  4TTU[\\bbdd '4&7&74&7&H&H# !,/G3QeKe/ff $8#;#;At#;#L#L q #%::T=PP26
wwyyr   c                   t          j        |                     d          | j                                                  }| }|                    d          }|                    d          }|                    d          }||z  |z  }|                     d          |                     d          k    }|                    d          }|                    d          }	|	 |z  }
|
|z  S )a1  Return a 3D mask where mask[a, p, n] is True iff the triplet (a, p, n) is valid.
        A triplet (i, j, k) is valid if:
            - i, j, k are distinct
            - labels[i] == labels[j] and labels[i] != labels[k]
        Args:
            labels: tf.int32 `Tensor` with shape [batch_size]
        r   device   r   r   eyesizerS   boolr   )r9   indices_equalindices_not_equali_not_equal_ji_not_equal_kj_not_equal_kdistinct_indiceslabel_equal	i_equal_j	i_equal_kvalid_labelss              r   get_triplet_maskz%BatchHardTripletLoss.get_triplet_mask   s     	&++a..GGGLLNN*N)33A66)33A66)33A66)M9]J&&q))V-=-=a-@-@@))!,,	))!,,	!zI-...r   c                    t          j        |                     d          | j                                                  }| }|                     d          |                     d          k    }||z  S )a  Return a 2D mask where mask[a, p] is True iff a and p are distinct and have same label.
        Args:
            labels: tf.int32 `Tensor` with shape [batch_size]
        Returns:
            mask: tf.bool `Tensor` with shape [batch_size, batch_size]
        r   rR   r   rU   )r9   rY   rZ   labels_equals       r   rA   z5BatchHardTripletLoss.get_anchor_positive_triplet_mask   sl     	&++a..GGGLLNN*N ''**f.>.>q.A.AA///r   c                \    |                      d          |                      d          k     S )zReturn a 2D mask where mask[a, n] is True iff a and n have distinct labels.
        Args:
            labels: tf.int32 `Tensor` with shape [batch_size]
        Returns:
            mask: tf.bool `Tensor` with shape [batch_size, batch_size]
        r   r   )r   )r9   s    r   rC   z5BatchHardTripletLoss.get_anchor_negative_triplet_mask   s.     !!!$$(8(8(;(;;<<r   strc                    dS )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(   )r5   s    r   citationzBatchHardTripletLoss.citation   s    	 	r   )r,   r   r-   r   r   r.   )r7   r8   r9   r   )r9   r   r   r   r   r   )r9   r   r   r   )r   rg   )r#   r$   r%   r
   r"   r1   r>   r<   r'   rc   rA   rC   propertyri   __classcell__)r6   s   @r   r*   r*   :   s         =O	U/ U/ U/ U/ U/ U/ U/n9 9 9 9) ) ) )V / / / \/2 0 0 0 \0$ 
= 
= 
= \
= 
 
 
 X
 
 
 
 
r   r*   )
__future__r   collections.abcr   r   r   r   sentence_transformersr   )sentence_transformers.SentenceTransformerr   r
   Moduler*   r(   r   r   <module>rq      s    " " " " " " $ $ $ $ $ $          & & & & & & I I I I I I+ + + + + + + +\P P P P P29 P P P P Pr   