o
    èp©iO  ã                   @   sV   d dl m  mZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ G dd	„ d	eƒZdS )
é    Né   ©ÚCosineSimilarity)Úcommon_functions)Úconvert_to_pairsé   )ÚBaseMetricLossFunctionc                       s:   e Zd ZdZ				d‡ fdd„	Zdd„ Zd	d
„ Z‡  ZS )ÚThresholdConsistentMarginLosszH
    Implements the TCM loss from: https://arxiv.org/abs/2307.04047
    ç      ð?çÍÌÌÌÌÌì?ç      à?c                    s:   t ƒ jdi |¤Ž t | t¡ || _|| _|| _|| _d S )N© )	ÚsuperÚ__init__Úc_fÚassert_distance_typer   Úlambda_plusÚlambda_minusÚmargin_plusÚmargin_minus)Úselfr   r   r   r   Úkwargs©Ú	__class__r   ú[/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_metric_learning/losses/tcm_loss.pyr      s   
z&ThresholdConsistentMarginLoss.__init__c                 C   s   t ƒ S )Nr   )r   r   r   r   Úget_default_distance   s   z2ThresholdConsistentMarginLoss.get_default_distancec                 C   sì   t |||ƒ\}}}}	|| || }}|| ||	 }}	t ||¡}
t ||	¡}|
| jk}| j|
 |  ¡ }| ¡ }| ¡ dkrBdn|| }|| jk}|| j |  ¡ }| ¡ }| ¡ dkr`dn|| }| j| | j|  }d|d ddœiS )Nr   ÚlossÚalready_reduced)ÚlossesÚindicesÚreduction_type)r   ÚFÚcosine_similarityr   Úsumr   r   r   )r   Ú
embeddingsÚlabelsÚindices_tupleÚref_embÚ
ref_labelsÚapÚpÚanÚnÚpos_simsÚneg_simsÚs_lte_mÚtcm_pos_numÚtcm_pos_denomÚpos_tcmÚs_gte_mÚtcm_neg_numÚtcm_neg_denomÚneg_tcmÚtcm_lossr   r   r   Úcompute_loss    s(   

ýÿz*ThresholdConsistentMarginLoss.compute_loss)r
   r
   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r8   Ú__classcell__r   r   r   r   r	   	   s    ûr	   )Útorch.nn.functionalÚnnÚ
functionalr!   Ú	distancesr   Úutilsr   r   Úutils.loss_and_miner_utilsr   Úbase_metric_loss_functionr   r	   r   r   r   r   Ú<module>   s    