o
    ϯi:                     @   sl   d dl mZ d dlZd dlmZ d dlmZ d dlm  m	Z
 d dlmZ d dlmZ G dd dejZdS )    )OptionalN)differentiable_all_gather)set_attributesc                	       s\   e Zd ZdZ		ddejdeej deddf fdd	Zd
e	j
de	j
de	j
fddZ  ZS )SimCLRz
    A Simple Framework for Contrastive Learning of Visual Representations
    Details can be found from:
    https://arxiv.org/abs/2002.05709
    NQ?mlpbackbonetemperaturereturnc                    s&   t    tjd t| t  d S )Nz"PYTORCHVIDEO.model.SimCLR.__init__)super__init__torch_C_log_api_usage_oncer   locals)selfr   r   r	   	__class__ N/home/ubuntu/.local/lib/python3.10/site-packages/pytorchvideo/models/simclr.pyr      s   
zSimCLR.__init__x1x2c                 C   s   | j dur
|  |}| |}tj|ddd}| j dur!|  |}| |}tj|ddd}tjt|dd}td||g}|| j	}|
d}t rWt rWt }nd}ttt|| |d |  |j}tjj||}|S )aP  
        Args:
            x1 (torch.tensor): a batch of image with augmentation. The input tensor
                shape should able to be feed into the backbone.
            x2 (torch.tensor): the size batch of image with different augmentation. The
                input tensor shape should able to be feed into the backbone.
        N      )pdimr   )r   z	nc,kc->nk)r   r   F	normalizer   catr   einsumdivr	   sizedistis_availableis_initializedget_ranktensorlistrangelongtodevicenn
functionalcross_entropy)r   r   r   prod
batch_size
device_indgtlossr   r   r   forward    s.   







zSimCLR.forward)Nr   )__name__
__module____qualname____doc__r,   Moduler   floatr   r   Tensorr4   __classcell__r   r   r   r   r      s    	$r   )typingr   r   torch.distributeddistributedr"   torch.nnr,   torch.nn.functionalr-   r   fvcore.nn.distributedr   pytorchvideo.layers.utilsr   r9   r   r   r   r   r   <module>   s   