U
    tPh                     @  sL   d dl mZ d dlmZ d dlZd dlmZ d dlm	Z	 G dd de	Z
dS )    )annotations)warnN)
functional)_Lossc                      s>   e Zd ZdZddddd fdd	Zd
d
d
dddZ  ZS )ContrastiveLossa  
    Compute the Contrastive loss defined in:

        Chen, Ting, et al. "A simple framework for contrastive learning of visual representations." International
        conference on machine learning. PMLR, 2020. (http://proceedings.mlr.press/v119/chen20j.html)

    Adapted from:
        https://github.com/Sara-Ahmed/SiT/blob/1aacd6adcd39b71efc903d16b4e9095b97dda76f/losses.py#L5

          ?floatintNone)temperature
batch_sizereturnc                   s$   t    || _|dkr td dS )a&  
        Args:
            temperature: Can be scaled between 0 and 1 for learning from negative samples, ideally set to 0.5.

        Raises:
            ValueError: When an input of dimension length > 2 is passed
            ValueError: When input and target are of different shapes

        r   z`batch_size is no longer required to be set. It will be estimated dynamically in the forward callN)super__init__r   r   )selfr   r   	__class__ M/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/losses/contrastive.pyr   !   s    

zContrastiveLoss.__init__ztorch.Tensor)inputtargetr   c                 C  sV  t |jdkst |jdkr6td|j d|j d|j|jkr\td|j d|j dt| j|j}|jd }tj|d |d tj	d }t
|tj|j}tj||gdd	}tj|d
|ddd	}t||}t|| }	tj||	gdd	}
t|
| }|t||  }t|tj|d
d	  }t|d|  S )zr
        Args:
            input: the shape should be B[F].
            target: the shape should be B[F].
           zLEither target or input has dimensions greater than 2 where target shape is (z) and input shape is ()z"ground truth has differing shape (z) from input (r   )dtype)dim   )lenshape
ValueErrortorch	as_tensorr   todeviceeyeboolclonetyper	   catFcosine_similarity	unsqueezediagexplogsum)r   r   r   Ztemperature_tensorr   Znegatives_maskreprZ
sim_matrixZsim_ijZsim_jiZ	positivesZ	nominatordenominatorZloss_partialr   r   r   forward1   s&    
zContrastiveLoss.forward)r   r   )__name__
__module____qualname____doc__r   r2   __classcell__r   r   r   r   r      s   r   )
__future__r   warningsr   r    torch.nnr   r)   torch.nn.modules.lossr   r   r   r   r   r   <module>   s
   