o  i @sLddlmZddlmZddlZddlmZddlm Z Gddde Z dS)) annotations)warnN) functional)_Losscs.eZdZdZddfd d ZdddZZS)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 ? temperaturefloat batch_sizeintreturnNonecs(t||_|dkrtddSdS)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 rz`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__Z/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/losses/contrastive.pyr!s  zContrastiveLoss.__init__input torch.TensortargetcCsVt|jdkst|jdkrtd|jd|jd|j|jkr.td|jd|jdt|j|j}|jd}tj|d|dtj d}t | tj |j}tj ||gdd }tj|d |ddd }t||}t|| } tj || gdd } t| |} |t||} t| tj| 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)lenshape ValueErrortorch as_tensorr todeviceeyeboolclonetyper catFcosine_similarity unsqueezediagexplogsum)rrrZtemperature_tensorr Znegatives_maskreprZ sim_matrixZsim_ijZsim_jiZ positivesZ nominator denominatorZ loss_partialrrrforward1s.   zContrastiveLoss.forward)rr)r r r r r r)rrrrr r)__name__ __module__ __qualname____doc__rr3 __classcell__rrrrrs r) __future__rwarningsrr!torch.nnrr*torch.nn.modules.lossrrrrrrs