3
O4W^£¾  ã               @   s’  d dl Z d dlZd dlmZ d dlmZ ddlmZmZ ddlm	Z	m
Z
mZmZmZmZmZ ddlmZ ddlmZ d	Zd	Zd	Zydd
lmZ W n ek
r¨   dZY nX yddlmZ W n ek
rÒ   dZY nX yddlmZ W n ek
rü   dZY nX G dd„ deƒZejaeZG dd„ deƒZeƒ ZG dd„ deƒZG dd„ deƒZ i a!i a"i a#da$da%edd�Z&d a'dd„ Z(dd„ Z)dd„ Z*dd„ Z+d d!„ Z,d"d#„ Z-d$d%„ Z.d&d'„ Z/d(d)„ Z0d*d+„ Z1d,d-„ Z2d.d/„ Z3d0d1„ Z4ej5fd2d3„Z6de&dedfdd4fd5d6„Z7de&fd7d8„Z8ej5fd9d:„Z9ej5fd;d<„Z:ej5fd=d>„Z;ej5d fd?d@„Z<ej5d fdAdB„Z=ej5d fdCdD„Z>dej5d fdEdF„Z?ej5dd fdGdH„Z@ej5dfdIdJ„ZAejBej5dfdKdL„ZCejBej5dfdMdN„ZDejBej5dfdOdP„ZEejBej5dd fdQdR„ZFejBej5dfdSdT„ZGej5dfdUdV„ZHej5dfdWdX„ZIdd ej5dfdYdZ„ZJdd ej5dfd[d\„ZKejBej5dfd]d^„ZLejBej5dfd_d`„ZMej5dfdadb„ZNde&dfdcdd„ZOdS )gé    N)Ústring_classes)Ú	timedeltaé   )Ú
rendezvousÚregister_rendezvous_handler)ÚAllreduceOptionsÚAllreduceCoalescedOptionsÚBroadcastOptionsÚGatherOptionsÚReduceOptionsÚReduceScatterOptionsÚScatterOptions)ÚReduceOp)ÚPrefixStoreT)ÚProcessGroupMPIF)ÚProcessGroupNCCL)ÚProcessGroupGlooc               @   s,   e Zd ZdZdZdZdZdZdZdd„ Z	d	S )
ÚBackenda¡  
    An enum-like class of available backends: GLOO, NCCL, and MPI.

    The values of this class are lowercase strings, e.g., ``"gloo"``. They can
    be accessed as attributes, e.g., ``Backend.NCCL``.

    This class can be directly called to parse the string, e.g.,
    ``Backend(backend_str)`` will check if ``backend_str`` is valid, and
    return the parsed lowercase string if so. It also accepts uppercase strings,
    e.g., ``Backend("GLOO")`` returns ``"gloo"``.

    .. note:: The entry ``Backend.UNDEFINED`` is present but only used as
              initial value of some fields. Users should neither use it directly
              nor assume its existence.
    Z	undefinedZglooZncclZmpiZtcpc             C   sZ   t |tƒstdj|ƒƒ‚tt|jƒ tjƒ}|tjkr>tdƒ‚n|tjkrVtdj|ƒƒ‚|S )Nz*Backend name must be a string, but got: {}ziTCP backend has been deprecated. Please use Gloo or MPI backend for collective operations on CPU tensors.zInvalid backend: '{}')	Ú
isinstancer   Ú
ValueErrorÚformatÚgetattrr   ÚupperÚ	UNDEFINEDÚTCP)ÚclsÚnameÚvalue© r   úC/tmp/pip-build-e66j97b2/torch/torch/distributed/distributed_c10d.pyÚ__new__B   s    



zBackend.__new__N)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚGLOOÚNCCLÚMPIr   r    r   r   r   r   r   ,   s   r   c               @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú	reduce_opz·
    Deprecated enum-like class for reduction operations: ``SUM``, ``PRODUCT``,
    ``MIN``, and ``MAX``.

    :class:`~torch.distributed.ReduceOp` is recommended to use instead.
    c             C   s0   x"t jjƒ D ]\}}t| ||ƒ qW t j| _d S )N)r   Ú__members__ÚitemsÚsetattr)ÚselfÚkÚvr   r   r   Ú__init__^   s    zreduce_op.__init__c             C   s   t jdƒ tj| |ƒS )NzXtorch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead)ÚwarningsÚwarnÚobjectÚ__getattribute__)r,   Úkeyr   r   r   r3   d   s    
zreduce_op.__getattribute__N)r!   r"   r#   r$   r/   r3   r   r   r   r   r(   V   s   r(   c               @   s   e Zd Zeƒ ZdS )ÚgroupN)r!   r"   r#   r2   ÚWORLDr   r   r   r   r5   l   s   r5   c               @   s   e Zd ZejZeƒ ZdS )ÚGroupMemberN)r!   r"   r#   r5   r6   r2   ÚNON_GROUP_MEMBERr   r   r   r   r7   p   s   r7   é   )Úminutesc             C   s   | t jkrdS | t jkS )zS
    Helper that checks if the current process's rank is not in a given group

    F)r7   r6   r8   )r5   r   r   r   Ú_rank_not_in_group�   s    
r;   c             C   sT   | t jkrtdƒ‚| tkr"tdƒ‚yt|  | }W n tk
rN   tdƒ‚Y nX |S )z`
    Helper that gets a given group's local rank in the group from a given global
    rank

    z;group.WORLD does not have local rank to global rank mappingzThe given group does not existz(The global rank is not part of the group)r7   r6   ÚRuntimeErrorÚ_pg_group_ranksÚKeyError)r5   ÚrankÚ
group_rankr   r   r   Ú_get_group_rank—   s    
rA   c             C   sH   | t jkrtdƒ‚t|  }x |jƒ D ]\}}||kr$|S q$W tdƒ‚dS )z`
    Helper that gets a given group's global rank from a given local rank in the
    group

    z;group.WORLD does not have local rank to global rank mappingz'The group rank is not part of the groupN)r7   r6   r<   r=   r*   )r5   r@   Zgroup_rank_mapr?   Zgrp_rankr   r   r   Ú_get_global_rank©   s    
rB   c               C   s   t dk	stdƒ‚dS )za
    Helper that checks if the default ProcessGroup has been initializd, with
    assertion

    Nz(Default process group is not initialized)Ú_default_pgÚAssertionErrorr   r   r   r   Ú_check_default_pg¹   s    
rE   c             C   s4   | t jkrtƒ  tjƒ S | tkr(tdƒ‚tt|  ƒS )z6
    Helper that gets a given group's world size

    zThe given group does not exist)r7   r6   rE   rC   Úsizer=   r<   Úlen)r5   r   r   r   Ú_get_group_sizeÃ   s    
rH   c             C   s   t | tjƒstdj|ƒƒ‚dS )zP
    Helper to check that the parameter ``param_name`` is a single tensor.

    zNInvalid function argument. Expected parameter `{}` to be of type torch.Tensor.N)r   ÚtorchÚTensorr<   r   )ÚparamÚ
param_namer   r   r   Ú_check_single_tensorÐ   s    rM   c             C   s2   t | tƒ s tdd„ | D ƒƒ r.tdj|ƒƒ‚dS )zR
    Helper to check that the parameter ``param_name`` is a list of tensors.

    c             s   s   | ]}t |tjƒV  qd S )N)r   rI   rJ   )Ú.0Úpr   r   r   ú	<genexpr>à   s    z%_check_tensor_list.<locals>.<genexpr>zTInvalid function argument. Expected parameter `{}` to be of type List[torch.Tensor].N)r   ÚlistÚallr<   r   )rK   rL   r   r   r   Ú_check_tensor_listÚ   s    rS   c               C   s   t S )z2
    Checks if the MPI backend is available.

    )Ú_MPI_AVAILABLEr   r   r   r   Úis_mpi_availableå   s    rU   c               C   s   t S )z3
    Checks if the NCCL backend is available.

    )Ú_NCCL_AVAILABLEr   r   r   r   Úis_nccl_availableí   s    rW   c               C   s   t S )z3
    Checks if the Gloo backend is available.

    )Ú_GLOO_AVAILABLEr   r   r   r   Úis_gloo_availableõ   s    rY   c               C   s   t dk	S )zE
    Checking if the default process group has been initialized

    N)rC   r   r   r   r   Úis_initializedý   s    rZ   c               C   s   t ƒ stdƒ‚tS )zJ
    Getting the default process group created by init_process_group

    z\Default process group has not been initialized, please make sure to call init_process_group.)rZ   r<   rC   r   r   r   r   Ú_get_default_group  s    r[   c              C   s   t ƒ stdƒ‚tt \} }|S )zB
    Getting the default store created by init_process_group

    z\Default process group has not been initialized, please make sure to call init_process_group.)rZ   r<   Ú_pg_maprC   )Ú_Údefault_storer   r   r   Ú_get_default_store  s    r_   c             C   s:   t ƒ  | tjkrt}n| }t|ƒr*tdƒ‚tj|dƒd S )a‡  
    Returns the backend of the given process group.

    Arguments:
        group (ProcessGroup, optional): The process group to work on. The
            default is the general main process group. If another specific group
            is specified, the calling process must be part of :attr:`group`.

    Returns:
        The backend of the given process group as a lower case string.

    zInvalid process group specifiedNr   )rE   r7   r6   rC   r;   r<   r\   Úget)r5   Úpgr   r   r   Úget_backend  s    
rb   Ú c          	   C   s\  t |tƒstdƒ‚tdk	r"tdƒ‚|dks:|dks:tdƒ‚|dk	rd|dksRtdƒ‚|dksptdƒ‚n|dkrpd}t| ƒ} | tjkrœtddg tjd||d
�an’|dk�r|}|dkrÌ|dkrÌ|dj||ƒ7 }n0|dkrä|dj|ƒ7 }n|dk� rü|dj|ƒ7 }t	t
|ƒƒ\}}}|j|ƒ t||g | |||d
�add„ ttjƒ ƒD ƒtt< tt d a|adS )a9	  
    Initializes the default distributed process group, and this will also
    initialize the distributed package.

    There are 2 main ways to initialize a process group:
        1. Specify ``store``, ``rank``, and ``world_size`` explicitly.
        2. Specify ``init_method`` (a URL string) which indicates where/how
           to discover peers. Optionally specify ``rank`` and ``world_size``,
           or encode all required parameters in the URL and omit them.
        If neither is specified, ``init_method`` is assumed to be "env://".


    Arguments:
        backend (str or Backend): The backend to use. Depending on
            build-time configurations, valid values include ``mpi``, ``gloo``,
            and ``nccl``. This field should be given as a lowercase string
            (e.g., ``"gloo"``), which can also be accessed via
            :class:`Backend` attributes (e.g., ``Backend.GLOO``). If using
            multiple processes per machine with ``nccl`` backend, each process
            must have exclusive access to every GPU it uses, as sharing GPUs
            between processes can result in deadlocks.
        init_method (str, optional): URL specifying how to initialize the
                                     process group. Default is "env://" if no
                                     ``init_method`` or ``store`` is specified.
                                     Mutually exclusive with ``store``.
        world_size (int, optional): Number of processes participating in
                                    the job. Required if ``store`` is specified.
        rank (int, optional): Rank of the current process.
                              Required if ``store`` is specified.
        store(Store, optional): Key/value store accessible to all workers, used
                                to exchange connection/address information.
                                Mutually exclusive with ``init_method``.
        timeout (timedelta, optional): Timeout for operations executed against
            the process group. Default value equals 30 minutes.
            This is only applicable for the ``gloo`` backend.
        group_name (str, optional, deprecated): Group name.

    To enable ``backend == Backend.MPI``, PyTorch needs to built from source
    on a system that supports MPI. The same applies to NCCL as well.

    z9Expected timeout argument to be of typedatetime.timedeltaNz5trying to initialize the default process group twice!z*Cannot specify both init_method and store.r   z*world_size must be positive if using storez(rank must be non-negative if using storezenv://r   )Ú
group_nameÚtimeoutz?rank={}&world_size={}z?rank={}z?world_size={}c             S   s   i | ]
}||“qS r   r   )rN   Úir   r   r   ú
<dictcomp>œ  s    z&init_process_group.<locals>.<dictcomp>éÿÿÿÿrh   rh   rh   rh   rh   )r   r   r<   rC   rD   r   r'   Ú_new_process_group_helperr   Únextr   Zset_timeoutÚrangerF   r=   r\   Ú_backendÚ_default_pg_init_method)ÚbackendZinit_methodre   Ú
world_sizer?   Ústorerd   Úurlr   r   r   Úinit_process_group4  sT    5





rr   c             C   s4  |st tƒ}td7 a|tjƒ kr(tdƒ‚t|tƒs:tdƒ‚t|ƒdk}t|ƒ}|tj	kr’t
ƒ sftdƒ‚tj|ƒ}|sztjS tj	dft|< |t|< nž|s¬tjƒ }	|	|kr¬tjS t||ƒ}
|tjkrèt|
|| |d�}tj|ft|< |t|< nH|tjk�r(tƒ �stdƒ‚t|
|| ƒ}tj|ft|< |t|< ntd	ƒ‚|S )
aV  
    Create a new distributed process group.

    This function must be called by ALL processes in the global group, even if
    the calling process is not part of the newly created group. In that case,
    this function returns GroupMember.NON_GROUP_MEMBER.

    This function is called with ``group_ranks == []`` for the default group.
    r   zTThe specified group name has already been created, please use a different group namez9Expected timeout argument to be of typedatetime.timedeltar   z-Distributed package doesn't have MPI built inN)re   z.Distributed package doesn't have NCCL built inz(Unsupported distributed backend by group)ÚstrÚ_group_countÚ	_pg_namesÚvaluesr<   r   r   rG   r   r'   rU   r   Úcreater7   r8   r\   rC   r?   r   r%   r   r&   rW   r   )ro   r?   Zgroup_ranksrn   rp   rd   re   Zis_default_groupra   Úglobal_rankZprefix_storer   r   r   ri   ¡  sR    







ri   c             C   s€   | t jkrdS | t jkrt}n| }tj|dƒdkr:tdƒ‚| t jkrjdadatjƒ  t	jƒ  t
jƒ  dant|= t	|= t
|= dS )a}  
    Destroy a given process group, and deinitialize the distributed package

    Arguments:
        group (ProcessGroup, optional): The process group to be destroyed, if
                                        group.WORLD is given, all process
                                        groups including the default one will
                                        be destroyed.
    NzInvalid process group specifiedr   )r7   r8   r6   rC   r\   r`   r<   rm   Úclearru   r=   rt   )r5   ra   r   r   r   Údestroy_process_groupñ  s"    



rz   c             C   s2   t | ƒrdS tƒ  | tjkr$tjƒ S t| tjƒ ƒS )a�  
    Returns the rank of current process group

    Rank is a unique identifier assigned to each process within a distributed
    process group. They are always consecutive integers ranging from 0 to
    ``world_size``.

    Arguments:
        group (ProcessGroup, optional): The process group to work on

    Returns:
        The rank of the process group
        -1, if not part of the group

    r   rh   )r;   rE   r7   r6   rC   r?   rA   )r5   r   r   r   Úget_rank#  s    
r{   c             C   s   t | ƒrdS t| ƒS )zû
    Returns the number of processes in the current process group

    Arguments:
        group (ProcessGroup, optional): The process group to work on

    Returns:
        The world size of the process group
        -1, if not part of the group

    r   rh   )r;   rH   )r5   r   r   r   Úget_world_size=  s    r|   c             C   sT   t | dƒ t|ƒrdS |tjkr6tƒ  tj| g||ƒS t||ƒ}|j| g||ƒS dS )ag  
    Sends a tensor asynchronously.

    Arguments:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank.
        group (ProcessGroup, optional): The process group to work on
        tag (int, optional): Tag to match send with remote recv

    Returns:
        A distributed request object.
        None, if not part of the group

    ÚtensorN)rM   r;   r7   r6   rE   rC   ÚsendrA   )r}   Údstr5   ÚtagÚgroup_dst_rankr   r   r   ÚisendO  s    


r‚   c             C   sT   t | dƒ t|ƒrdS |tjkr6tƒ  tj| g||ƒS t||ƒ}|j| g||ƒS dS )ax  
    Receives a tensor asynchronously.

    Arguments:
        tensor (Tensor): Tensor to fill with received data.
        src (int): Source rank.
        group (ProcessGroup, optional): The process group to work on
        tag (int, optional): Tag to match recv with remote send

    Returns:
        A distributed request object.
        None, if not part of the group

    r}   N)rM   r;   r7   r6   rE   rC   ÚrecvrA   )r}   Úsrcr5   r€   Úgroup_src_rankr   r   r   Úirecvm  s    


r†   c             C   s^   t | dƒ t|ƒrdS |tjkr<tƒ  tj| g||ƒjƒ  nt||ƒ}|j| g||ƒjƒ  dS )a  
    Sends a tensor synchronously.

    Arguments:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank.
        group (ProcessGroup, optional): The process group to work on
        tag (int, optional): Tag to match send with remote recv

    r}   N)	rM   r;   r7   r6   rE   rC   r~   ÚwaitrA   )r}   r   r5   r€   r�   r   r   r   r~   ‹  s    


r~   c             C   s¶   t | dƒ t|ƒrdS |tjkr,tƒ  t}n|}|dkrp|j| g|ƒ}|jƒ  |jƒ }|tjkrd|S t	||ƒS nB|tjkr�|j
| g||ƒjƒ  nt||ƒ}|j
| g||ƒjƒ  |S dS )a§  
    Receives a tensor synchronously.

    Arguments:
        tensor (Tensor): Tensor to fill with received data.
        src (int, optional): Source rank. Will receive from any
            process if unspecified.
        group (ProcessGroup, optional): The process group to work on
        tag (int, optional): Tag to match recv with remote send

    Returns:
        Sender rank
        -1, if not part of the group

    r}   r   Nrh   )rM   r;   r7   r6   rE   rC   Zrecv_anysourcer‡   Zsource_rankrB   rƒ   rA   )r}   r„   r5   r€   ra   ÚworkZsrc_rankr…   r   r   r   rƒ   ¥  s&    




rƒ   c             C   sl   t |ƒrdS tƒ }||_||_|tjkr<tƒ  tj| |ƒ}nt	||ƒ}||_|j| |ƒ}|r`|S |j
ƒ  dS )a  
    Broadcasts the tensor to the whole group with multiple GPU tensors
    per node.

    ``tensor`` must have the same number of elements in all the GPUs from
    all processes participating in the collective. each tensor in the list must
    be on a different GPU

    Only nccl and gloo backend are currently supported
    tensors should only be GPU tensors

    Arguments:
        tensor_list (List[Tensor]): Tensors that participate in the collective
            operation. If ``src`` is the rank, then the specified ``src_tensor``
            element of ``tensor_list`` (``tensor_list[src_tensor]``) will be
            broadcast to all other tensors (on different GPUs) in the src process
            and all tensors in ``tensor_list`` of other non-src processes.
            You also need to make sure that ``len(tensor_list)`` is the same
            for all the distributed processes calling this function.

        src (int): Source rank.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op
        src_tensor (int, optional): Source tensor rank within ``tensor_list``

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    N)r;   r	   ÚrootRankÚ
rootTensorr7   r6   rE   rC   Ú	broadcastrA   r‡   )Útensor_listr„   r5   Úasync_opZ
src_tensorÚoptsrˆ   r…   r   r   r   Úbroadcast_multigpuÓ  s    #

r�   c             C   sz   t | dƒ t|ƒrdS tƒ }||_d|_|tjkrHtƒ  tj	| g|ƒ}nt
||ƒ}||_|j	| g|ƒ}|rn|S |jƒ  dS )at  
    Broadcasts the tensor to the whole group.

    ``tensor`` must have the same number of elements in all processes
    participating in the collective.

    Arguments:
        tensor (Tensor): Data to be sent if ``src`` is the rank of current
            process, and tensor to be used to save received data otherwise.
        src (int): Source rank.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    r}   Nr   )rM   r;   r	   r‰   rŠ   r7   r6   rE   rC   r‹   rA   r‡   )r}   r„   r5   r�   rŽ   rˆ   r…   r   r   r   r‹   
  s    


r‹   c             C   sV   t |ƒrdS tƒ }||_|tjkr6tƒ  tj| |ƒ}n|j| |ƒ}|rJ|S |jƒ  dS )a]  
    Reduces the tensor data across all machines in such a way that all get
    the final result. This function reduces a number of tensors on every node,
    while each tensor resides on different GPUs.
    Therefore, the input tensor in the tensor list needs to be GPU tensors.
    Also, each tensor in the tensor list needs to reside on a different GPU.

    After the call, all ``tensor`` in ``tensor_list`` is going to be bitwise
    identical in all processes.

    Only nccl and gloo backend is currently supported
    tensors should only be GPU tensors

    Arguments:
        tensor list (List[Tensor]): List of input and output tensors of
            the collective. The function operates in-place and requires that
            each tensor to be a GPU tensor on different GPUs.
            You also need to make sure that ``len(tensor_list)`` is the same for
            all the distributed processes calling this function.
        op (optional): One of the values from
            ``torch.distributed.ReduceOp``
            enum.  Specifies an operation used for element-wise reductions.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    N)	r;   r   ÚreduceOpr7   r6   rE   rC   Ú	allreducer‡   )rŒ   Úopr5   r�   rŽ   rˆ   r   r   r   Úall_reduce_multigpu5  s    "
r“   c             C   sd   t | dƒ t|ƒrdS tƒ }||_|tjkrBtƒ  tj| g|ƒ}n|j| g|ƒ}|rX|S |j	ƒ  dS )aä  
    Reduces the tensor data across all machines in such a way that all get
    the final result.

    After the call ``tensor`` is going to be bitwise identical in all processes.

    Arguments:
        tensor (Tensor): Input and output of the collective. The function
            operates in-place.
        op (optional): One of the values from
            ``torch.distributed.ReduceOp``
            enum.  Specifies an operation used for element-wise reductions.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    r}   N)
rM   r;   r   r�   r7   r6   rE   rC   r‘   r‡   )r}   r’   r5   r�   rŽ   rˆ   r   r   r   Ú
all_reduceh  s    

r”   c             C   s`   t | dƒ t|ƒrdS tƒ }||_|tjkr@tƒ  tj| |ƒ}n|j| |ƒ}|rT|S |j	ƒ  dS )aF  
    WARNING: at this time individual shape checking is not implemented across nodes.
    For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
    rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce
    operation will proceed without complaint and return erroneous outputs. This lack
    of shape checking results in significant performance improvements but users of this
    function should take extra care to ensure that each node passes in tensors whose
    shapes match across nodes.

    Reduces each tensor in tensors (residing on the same device) across all machines
    in such a way that all get the final result.

    After the call each tensor in tensors is going to bitwise identical
    in all processes.

    Arguments:
        tensors (List[Tensor]): Input and output of the collective. The function
            operates in-place.
        op (Optional[ReduceOp]): One of the values from
            ``torch.distributed.ReduceOp`` enum. Specifies an operation used for
            element-wise reductions.
        group (Optional[ProcessGroup]): The process group to work on.
        async_op (Optional[bool]): Whether this op should be an async op.

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group.

    r}   N)
rS   r;   r   r�   r7   r6   rE   rC   Zallreduce_coalescedr‡   )Ztensorsr’   r5   r�   rŽ   rˆ   r   r   r   Úall_reduce_coalesced’  s    !

r•   c       	      C   sr   t |ƒrdS tƒ }||_||_||_|tjkrBtƒ  tj	| |ƒ}nt
||ƒ}||_|j	| |ƒ}|rf|S |jƒ  dS )a©  
    Reduces the tensor data on multiple GPUs across all machines. Each tensor
    in ``tensor_list`` should reside on a separate GPU

    Only the GPU of ``tensor_list[dst_tensor]`` on the process with rank ``dst``
    is going to receive the final result.

    Only nccl backend is currently supported
    tensors should only be GPU tensors

    Arguments:
        tensor_list (List[Tensor]): Input and output GPU tensors of the
            collective. The function operates in-place.
            You also need to make sure that ``len(tensor_list)`` is the same for
            all the distributed processes calling this function.
        dst (int): Destination rank
        op (optional): One of the values from
            ``torch.distributed.ReduceOp``
            enum.  Specifies an operation used for element-wise reductions.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op
        dst_tensor (int, optional): Destination tensor rank within
                                    ``tensor_list``

    Returns:
        Async work handle, if async_op is set to True.
        None, otherwise

    N)r;   r   r�   r‰   rŠ   r7   r6   rE   rC   ÚreducerA   r‡   )	rŒ   r   r’   r5   r�   Z
dst_tensorrŽ   rˆ   r�   r   r   r   Úreduce_multigpuÅ  s    #

r—   c             C   sz   t | dƒ t|ƒrdS tƒ }||_||_|tjkrHtƒ  tj	| g|ƒ}nt
||ƒ}||_|j	| g|ƒ}|rn|S |jƒ  dS )aÔ  
    Reduces the tensor data across all machines.

    Only the process with rank ``dst`` is going to receive the final result.

    Arguments:
        tensor (Tensor): Input and output of the collective. The function
            operates in-place.
        dst (int): Destination rank
        op (optional): One of the values from
            ``torch.distributed.ReduceOp``
            enum.  Specifies an operation used for element-wise reductions.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    r}   N)rM   r;   r   r�   r‰   r7   r6   rE   rC   r–   rA   r‡   )r}   r   r’   r5   r�   rŽ   rˆ   r�   r   r   r   r–   þ  s    


r–   c             C   sJ   t |ƒrdS |tjkr*tƒ  tj| |ƒ}n|j| |ƒ}|r>|S |jƒ  dS )a  
    Gathers tensors from the whole group in a list.
    Each tensor in ``tensor_list`` should reside on a separate GPU

    Only nccl backend is currently supported
    tensors should only be GPU tensors

    Arguments:
        output_tensor_lists (List[List[Tensor]]): Output lists. It should
            contain correctly-sized tensors on each GPU to be used for output
            of the collective, e.g. ``output_tensor_lists[i]`` contains the
            all_gather result that resides on the GPU of
            ``input_tensor_list[i]``.

            Note that each element of ``output_tensor_lists`` has the size of
            ``world_size * len(input_tensor_list)``, since the function all
            gathers the result from every single GPU in the group. To interpret
            each element of ``output_tensor_lists[i]``, note that
            ``input_tensor_list[j]`` of rank k will be appear in
            ``output_tensor_lists[i][k * world_size + j]``

            Also note that ``len(output_tensor_lists)``, and the size of each
            element in ``output_tensor_lists`` (each element is a list,
            therefore ``len(output_tensor_lists[i])``) need to be the same
            for all the distributed processes calling this function.

        input_tensor_list (List[Tensor]): List of tensors(on different GPUs) to
            be broadcast from current process.
            Note that ``len(input_tensor_list)`` needs to be the same for
            all the distributed processes calling this function.

        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    N)r;   r7   r6   rE   rC   Ú	allgatherr‡   )Zoutput_tensor_listsZinput_tensor_listr5   r�   rˆ   r   r   r   Úall_gather_multigpu-  s    +
r™   c             C   sf   t | dƒ t|dƒ t|ƒr dS |tjkrBtƒ  tj| g|gƒ}n|j| g|gƒ}|rZ|S |jƒ  dS )a-  
    Gathers tensors from the whole group in a list.

    Arguments:
        tensor_list (list[Tensor]): Output list. It should contain
            correctly-sized tensors to be used for output of the collective.
        tensor (Tensor): Tensor to be broadcast from current process.
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    rŒ   r}   N)	rS   rM   r;   r7   r6   rE   rC   r˜   r‡   )rŒ   r}   r5   r�   rˆ   r   r   r   Ú
all_gatherg  s    


rš   c             C   sÆ   t | dƒ |rt|dƒ ng }t|ƒr*dS tƒ }||krR|sDtdƒ‚| g}|g}n|r^tdƒ‚| g}g }tƒ }||_|tjkr”t	ƒ  t
j|||ƒ}	nt||ƒ}
|
|_|j|||ƒ}	|rº|	S |	jƒ  dS )az  
    Gathers a list of tensors in a single process.

    Arguments:
        tensor (Tensor): Input tensor.
        gather_list (list[Tensor], optional): List of appropriately-sized
            tensors to use for gathered data (default is None, must be specified
            on the destination rank)
        dst (int, optional): Destination rank (default is 0)
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    r}   Úgather_listNz?Argument ``gather_list`` must be specified on destination rank.zHArgument ``gather_list`` must NOT be specified on non-destination ranks.)rM   rS   r;   r{   r   r
   r‰   r7   r6   rE   rC   ÚgatherrA   r‡   )r}   r›   r   r5   r�   Úmy_rankÚinput_tensorsÚoutput_tensorsrŽ   rˆ   r�   r   r   r   rœ   ‹  s6    


rœ   c             C   sÆ   t | dƒ |rt|dƒ ng }t|ƒr*dS tƒ }||krR|sDtdƒ‚|g}| g}n|r^tdƒ‚g }| g}tƒ }||_|tjkr”t	ƒ  t
j|||ƒ}	nt||ƒ}
|
|_|j|||ƒ}	|rº|	S |	jƒ  dS )až  
    Scatters a list of tensors to all processes in a group.

    Each process will receive exactly one tensor and store its data in the
    ``tensor`` argument.

    Arguments:
        tensor (Tensor): Output tensor.
        scatter_list (list[Tensor]): List of tensors to scatter (default is
            None, must be specified on the source rank)
        src (int): Source rank (default is 0)
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group

    r}   Úscatter_listNz;Argument ``scatter_list`` must be specified on source rank.zDArgument ``scatter_list`` must NOT be specified on non-source ranks.)rM   rS   r;   r{   r   r   r‰   r7   r6   rE   rC   ÚscatterrA   r‡   )r}   r    r„   r5   r�   r�   rž   rŸ   rŽ   rˆ   r…   r   r   r   r¡   Ë  s6    


r¡   c             C   sZ   t |ƒrdS tƒ }||_|tjkr8tƒ  tj| ||ƒ}n|j| ||ƒ}|rN|S |jƒ  dS )aS  
    Reduce and scatter a list of tensors to the whole group.  Only nccl backend
    is currently supported.

    Each tensor in ``output_tensor_list`` should reside on a separate GPU, as
    should each list of tensors in ``input_tensor_lists``.

    Arguments:
        output_tensor_list (List[Tensor]): Output tensors (on different GPUs)
            to receive the result of the operation.

            Note that ``len(output_tensor_list)`` needs to be the same for all
            the distributed processes calling this function.

        input_tensor_lists (List[List[Tensor]]): Input lists.  It should
            contain correctly-sized tensors on each GPU to be used for input of
            the collective, e.g. ``input_tensor_lists[i]`` contains the
            reduce_scatter input that resides on the GPU of
            ``output_tensor_list[i]``.

            Note that each element of ``input_tensor_lists`` has the size of
            ``world_size * len(output_tensor_list)``, since the function
            scatters the result from every single GPU in the group.  To
            interpret each element of ``input_tensor_lists[i]``, note that
            ``output_tensor_list[j]`` of rank k receives the reduce-scattered
            result from ``input_tensor_lists[i][k * world_size + j]``

            Also note that ``len(input_tensor_lists)``, and the size of each
            element in ``input_tensor_lists`` (each element is a list,
            therefore ``len(input_tensor_lists[i])``) need to be the same for
            all the distributed processes calling this function.

        group (ProcessGroup, optional): The process group to work on.
        async_op (bool, optional): Whether this op should be an async op.

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group.

    N)	r;   r   r�   r7   r6   rE   rC   Úreduce_scatterr‡   )Zoutput_tensor_listZinput_tensor_listsr’   r5   r�   rŽ   rˆ   r   r   r   Úreduce_scatter_multigpu  s"    -
r£   c             C   sv   t | dƒ t|dƒ t|ƒr dS tƒ }||_|tjkrPtƒ  tj	| g|g|ƒ}n|j	| g|g|ƒ}|rj|S |j
ƒ  dS )aâ  
    Reduces, then scatters a list of tensors to all processes in a group.

    Arguments:
        output (Tensor): Output tensor.
        input_list (list[Tensor]): List of tensors to reduce and scatter.
        group (ProcessGroup, optional): The process group to work on.
        async_op (bool, optional): Whether this op should be an async op.

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group.

    ÚoutputÚ
input_listN)rM   rS   r;   r   r�   r7   r6   rE   rC   r¢   r‡   )r¤   r¥   r’   r5   r�   rŽ   rˆ   r   r   r   r¢   T  s    


r¢   c             C   sB   t | ƒrdS | tjkr&tƒ  tjƒ }n| jƒ }|r6|S |jƒ  dS )aÛ  
    Synchronizes all processes.

    This collective blocks processes until the whole group enters this function,
    if async_op is False, or if async work handle is called on wait().

    Arguments:
        group (ProcessGroup, optional): The process group to work on
        async_op (bool, optional): Whether this op should be an async op

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group
    N)r;   r7   r6   rE   rC   Úbarrierr‡   )r5   r�   rˆ   r   r   r   r¦   {  s    

r¦   c             C   sÜ   t ƒ  tt \}}tjƒ }tjƒ }|s*|}| dk	r’t| ƒ} t| ƒ}||krRtdƒ‚x$| D ]}|dk sl||krXtdƒ‚qXW || krŒ| j|ƒ}	q¦d}	nt	t
|ƒƒ} |}|}	t|ƒ}t||	| |||d�}
dd„ t| ƒD ƒt|
< |
S )aW  
    Creates a new distributed group.

    This function requires that all processes in the main group (i.e. all
    processes that are part of the distributed job) enter this function, even
    if they are not going to be members of the group. Additionally, groups
    should be created in the same order in all processes.

    Arguments:
        ranks (list[int]): List of ranks of group members.
        timeout (timedelta, optional): Timeout for operations executed against
            the process group. Default value equals 30 minutes.
            This is only applicable for the ``gloo`` backend.
        backend (str or Backend, optional): The backend to use. Depending on
            build-time configurations, valid values are ``gloo`` and ``nccl``.
            By default uses the same backend as the global group. This field
            should be given as a lowercase string (e.g., ``"gloo"``), which can
            also be accessed via :class:`Backend` attributes (e.g.,
            ``Backend.GLOO``).

    Returns:
        A handle of distributed group that can be given to collective calls.
    Nz^the new group's world size should be less or equal to the world size set by init_process_groupr   zRThe new group's rank should be within the the world_size set by init_process_group)re   c             S   s   i | ]\}}||“qS r   r   )rN   r@   rx   r   r   r   rg   ß  s   znew_group.<locals>.<dictcomp>)rE   r\   rC   r?   rF   ÚsortedrG   r<   ÚindexrQ   rk   r   ri   Ú	enumerater=   )Zranksre   rn   Zdefault_backendr^   rx   Zglobal_world_sizeZgroup_world_sizer?   r@   ra   r   r   r   Ú	new_groupš  s<    
rª   rh   rh   )PrI   r0   Z
torch._sixr   Údatetimer   r   r   rc   r   r   r	   r
   r   r   r   r   r   rT   rV   rX   r   ÚImportErrorr   r   r2   r   r   rl   Zdist_backendr(   r5   r7   r\   ru   r=   rC   rm   Z_default_pg_timeoutrt   r;   rA   rB   rE   rH   rM   rS   rU   rW   rY   rZ   r[   r_   r6   rb   rr   ri   rz   r{   r|   r‚   r†   r~   rƒ   r�   r‹   ZSUMr“   r”   r•   r—   r–   r™   rš   rœ   r¡   r£   r¢   r¦   rª   r   r   r   r   Ú<module>   sà   $	


&	



lJ2-5)1(26-9"=@E#