Team Ai
Apppublic

xdecoder/Instruct-X-Decoder

sourceHugging Faceafl-3.0updated 3y agoView on Hugging Face
163likes
it_contrastive.cpython-38.pyc22 linesDownload Raw Back to __pycache__
1U

2E$�c�@s\ddlZddlmZddlmmZdd�Zdd�Zdd�Ze�	�dd	��Z3dd4d�ZdS)
�NcCs5tj��S)N)�torch�distributed�is_initialized�rr�6/data/arXiv/demo/Demo/xdecoder/utils/it_contrastive.py�is_dist_initializedsrcCst�rtj��SdS)N�)rrr�get_world_sizerrrrr	s6r	csPt�dkrL�fdd�tt��D�}tj�|���|tj��<tj|dd���S)Nrcsg|]}t����qSr)r�7zeros_like��.0�_��xrr�8<listcomp>sz#all_gather_grad.<locals>.<listcomp>r��dim)r	�rangerr�9all_gather�get_rank�cat)rZall_xrrr�all_gather_grad
s10rcsJt�dkrF�fdd�ttj���D�}tjj|�dd�tj|dd���S)z�11    Performs all_gather operation on the provided tensors.12    *** Warning ***: torch.distributed.all_gather has no gradient.13    rcsg|]}t����qSr)r�	ones_liker��tensorrrrs�z%all_gather_nograd.<locals>.<listcomp>F)�async_oprr)r	rrrrr)rZtensors_gatherrrr�all_gather_nograds1415�rcCst|�}t|�}t�||���}||}|dkrl|dkrltj|jd|jd�}t�||�}t�|��|�}n�t|�}t|�}|�	d�|�	d�k}	|�	d�|�	d�k}16t�17|	|18�}t�|tj|dd��|��}t�|��tj|��dd��|��}||dt
�S)Nr)�device)�����r)rrrr�)rr�matmul�t�arange�shaper�F�
cross_entropy�reshape�19logical_or�sum�log_softmaxr	)Z20image_featZ	text_feat�temperature�image_idZtext_id�logits�gtZloss1Zloss2Zgt_imageZgt_textrrr�image_text_contrastive_loss$s "*r.)NN)r�torch.nn�nnZtorch.nn.functional�21functionalr$rr	r�no_gradrr.rrrr�<module>s22