o
    {i                  	   @   s   d dl mZmZmZmZ d dlZd dlmZ d dl	m
Z ddlmZmZ ddeeejf ded	eeejf fd
dZdejdeded	eej fddZddejdee d	eej fddZdS )    )AnyDictListOptionalN)
functional   )get_default_process_groupget_world_sizeT
input_dictaveragereturnc                 C   s   t  }|dkr	| S t > g }g }t|  D ]}|| || |  qtj|dd}t| |r9|| }dd t	||D }W d   |S 1 sNw   Y  |S )aG  
    Reduce the values in the dictionary from all processes so that all processes
    have the averaged results. Returns a dictionary with the same fields as
    the input dictionary, after reduction.

    Args:
        input_dict (dict): all the values will be reduced
        average (bool): whether to do average or sum
    r   r   dimc                 S   s   i | ]\}}||qS  r   ).0kvr   r   [/data/cameron/keygrip/volume_dino_tracks/dinov3/distributed/torch_distributed_primitives.py
<dictcomp>'       zreduce_dict.<locals>.<dictcomp>N)
r	   torchno_gradsortedkeysappendstackdist
all_reducezip)r
   r   
world_sizenamesvaluesr   Zstacked_valuesreduced_dictr   r   r   reduce_dict   s$   




r#   resultgroupr   c                    s(    fddt |D }t| | |S )Nc                       g | ]}t  qS r   r   
zeros_liker   _r$   r   r   
<listcomp>,   r   z._simple_gather_all_tensors.<locals>.<listcomp>)ranger   
all_gather)r$   r%   r   gathered_resultr   r+   r   _simple_gather_all_tensors+   s   r0   c                    sN  |du rt  }|  } t }tj|d | jdkrt| ||S tj| j	| j
d  fddt|D }tj| |d t|jddjtfdd	|D }|rXt| ||S g }    }t|D ]}|d ||  qft| |fd
dt|D }t|| t|D ]\}	}
dd |
D }||	 | ||	< q|S )a  
    Copied from https://github.com/Lightning-AI/torchmetrics/blob/master/src/torchmetrics/utilities/distributed.py
    Gather all tensors from several ddp processes onto a list that is broadcasted to all processes.

    Works on tensors that have the same number of dimensions, but where each dimension may differ. In this case
    tensors are padded, gathered and then trimmed to secure equal workload for all processes.

    Args:
        result: the value to sync
        group: the process group to gather results from. Defaults to all processes (world)

    Return:
        list with size equal to the process group where element i corresponds to result tensor from process i
    N)r%   r   )devicec                    r&   r   r'   r)   )
local_sizer   r   r,   O   r   z&gather_all_tensors.<locals>.<listcomp>r   c                 3   s    | ]	}t | kV  qd S N)all)r   ls)max_sizer   r   	<genexpr>R   s    z%gather_all_tensors.<locals>.<genexpr>c                    r&   r   r'   r)   )result_paddedr   r   r,   _   r   c                 S   s   g | ]}t |qS r   )slice)r   dim_sizer   r   r   r,   b   s    )r   
contiguousr	   r   barrierndimr0   r   tensorshaper1   r-   r.   r   maxr!   r4   detachcpureversedr   itemFpad	enumerate)r$   r%   r   Zlocal_sizesZall_sizes_equalZpad_dimsZpad_byvalr/   idxZ	item_sizeZslice_paramr   )r2   r6   r8   r   gather_all_tensors1   s4   

rJ   )Tr3   )typingr   r   r   r   r   torch.distributeddistributedr   torch.nnr   rE   torch_distributed_wrapperr   r	   Tensorboolr#   intr0   rJ   r   r   r   r   <module>   s   ,"(