o
    pi                     @   s^   d dl Z 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MeanReducer)common_functions   )BaseMetricLossFunctionc                       s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )InstanceLossz
    Implementation of  Dual-Path Convolutional Image-Text Embeddings with Instance Loss, ACM TOMM 2020
    https://arxiv.org/abs/1711.05535
    using cross-entropy loss for every sample if label is not available, else use given label.
    @   c                    s8   t  jdi | t| t || _| jdgdd d S )NgammaF)list_of_namesis_stat )super__init__c_fassert_distance_typer   r   add_to_recordable_attributes)selfr   kwargs	__class__r   `/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_metric_learning/losses/instance_loss.pyr      s   
zInstanceLoss.__init__c           
      C   s   t | t | t |||| | || j }|d u r$t |}n	tj|dd\}}t	j
||dd}	d|	t |ddiS )NT)return_inversenone)	reductionlosselement)lossesindicesreduction_type)r   labels_requiredindices_tuple_not_supportedref_not_supporteddistancer   torch_arange_from_sizetorchuniqueFcross_entropy)
r   
embeddingslabelsindices_tupleref_emb
ref_labelssim1	sim_label_r   r   r   r   compute_loss   s   

zInstanceLoss.compute_lossc                 C      t  S Nr   r   r   r   r   get_default_reducer,      z InstanceLoss.get_default_reducerc                 C   r4   r5   r   r6   r   r   r   get_default_distance/   r8   z!InstanceLoss.get_default_distance)r   )	__name__
__module____qualname____doc__r   r3   r7   r9   __classcell__r   r   r   r   r
   
   s    	r
   )r'   torch.nn.functionalnn
functionalr)   	distancesr   reducersr   utilsr   r   base_metric_loss_functionr	   r
   r   r   r   r   <module>   s    