a
    ÞñhÝ ã                   @   s  d dl Z d dlZd dlZd dlm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mZ ddlmZ dd	lmZ d
Zd
Zd
ZzddlmZ W n ey¾   dZY n0 zddlmZ W n eyæ   dZY n0 zddlmZ W n e�y   dZY n0 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)d a*dd„ Z+dd„ Z,dd„ Z-dd„ Z.dd „ Z/d!d"„ Z0d#d$„ Z1d%d&„ Z2d'd(„ Z3d)d*„ Z4d+d,„ Z5d-d.„ Z6d/d0„ Z7e#j8fd1d2„Z9ded3d3dd4fd5d6„Z:defd7d8„Z;e#j8fd9d:„Z<e#j8fd;d<„Z=e#j8fd=d>„Z>e#j8d fd?d@„Z?e#j8d fdAdB„Z@e#j8d fdCdD„ZAde#j8d fdEdF„ZBe#j8dd fdGdH„ZCe#j8dfdIdJ„ZDejEe#j8dfdKdL„ZFejEe#j8dfdMdN„ZGejEe#j8dfdOdP„ZHejEe#j8dd fdQdR„ZIejEe#j8dfdSdT„ZJe#j8dfdUdV„ZKdWdX„ ZLdYdZ„ ZMe#j8fd[d\„ZNdd e#j8fd]d^„ZOe#j8fd_d`„ZPe#j8dfdadb„ZQe#j8dfdcdd„ZRdedf„ ZSdd e#j8dfdgdh„ZTdd e#j8dfdidj„ZUejEe#j8dfdkdl„ZVejEe#j8dfdmdn„ZWdde#j8dfdodp„ZXe#j8dfdqdr„ZYe#j8dfdsdt„ZZdedfdudv„Z[dS )wé    N)Ústring_classes)Ú	timedeltaé   )Údefault_pg_timeout)Ú
rendezvousÚregister_rendezvous_handler)ÚAllreduceOptionsÚAllreduceCoalescedOptionsÚAllToAllOptionsÚBroadcastOptionsÚGatherOptionsÚReduceOptionsÚReduceScatterOptionsÚScatterOptions)ÚReduceOp)ÚPrefixStoreT)ÚProcessGroupMPIF)ÚProcessGroupNCCL)ÚProcessGroupGlooc                   @   s8   e Zd ZdZdZdZdZdZdZdd„ Z	e
d	d
„ ƒZdS )ÚBackendaÀ  
    An enum-like class of available backends: GLOO, NCCL, MPI, and other registered
    backends.

    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   s~   t |tƒstd |¡ƒ‚tt| ¡ tjƒ}|tjkr>tdƒ‚n<|tjkrXtd |¡ƒ‚n"|tj	krz|tj
krz|tjkrz|}|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ÚGLOOÚNCCLÚMPI)ÚclsÚnameÚvalue© r#   úb/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/distributed/distributed_c10d.pyÚ__new__F   s    



zBackend.__new__c                 C   s   t t| ¡ |ƒ dS )a}  
        Registers a new backend.

        This class method is used by 3rd party cpp extension to register new backend.

        Arguments:
            name (str): Backend name matching with the one in `init_process_group()`.
            func (function): Function handler that instantiates the backend.
                             The function should be implemented in the backend cpp extension
                             and takes four arguments, including prefix_store, rank,
                             world_size, and timeout.

        .. note:: This support of 3rd party backend is experimental and subject to change.

        N)Úsetattrr   r   )r    r!   Úfuncr#   r#   r$   Úregister_backendU   s    zBackend.register_backendN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r%   Úclassmethodr(   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   s,   t j ¡ D ]\}}t| ||ƒ q
t j| _d S ©N)r   Ú__members__Úitemsr&   )ÚselfÚkÚvr#   r#   r$   Ú__init__w   s    zreduce_op.__init__c                 C   s   t  d¡ t | |¡S )NzXtorch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead)ÚwarningsÚwarnÚobjectÚ__getattribute__)r2   Úkeyr#   r#   r$   r9   }   s    
zreduce_op.__getattribute__N)r)   r*   r+   r,   r5   r9   r#   r#   r#   r$   r.   o   s   r.   c                   @   s   e Zd Zeƒ ZdS )ÚgroupN)r)   r*   r+   r8   ÚWORLDr#   r#   r#   r$   r;   …   s   r;   c                   @   s   e Zd ZejZeƒ ZdS )ÚGroupMemberN)r)   r*   r+   r;   r<   r8   ÚNON_GROUP_MEMBERr#   r#   r#   r$   r=   ‰   s   r=   c                 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)r=   r<   r>   ©r;   r#   r#   r$   Ú_rank_not_in_group    s    
r@   c                 C   s`   | t ju rtdƒ‚| tvr"tdƒ‚zt|  | }W n( tyZ   td|› d| › �ƒd‚Y n0 |S )z`
    Helper that gets a given group's local rank in the group from a given global
    rank

    ú;group.WORLD does not have local rank to global rank mappingúThe given group does not existzThe global rank z is not part of the group N)r=   r<   ÚRuntimeErrorÚ_pg_group_ranksÚKeyError)r;   ÚrankÚ
group_rankr#   r#   r$   Ú_get_group_rankª   s    
rH   c                 C   sH   | t ju rtdƒ‚t|  }| ¡ D ]\}}||kr"|  S q"tdƒ‚dS )z`
    Helper that gets a given group's global rank from a given local rank in the
    group

    rA   z'The group rank is not part of the groupN)r=   r<   rC   rD   r1   )r;   rG   Zgroup_rank_maprF   Zgrp_rankr#   r#   r$   Ú_get_global_rank¼   s    

rI   c                   C   s   t dusJ dƒ‚dS )zb
    Helper that checks if the default ProcessGroup has been initialized, with
    assertion

    Nz(Default process group is not initialized©Ú_default_pgr#   r#   r#   r$   Ú_check_default_pgÌ   s    
ÿrL   c                 C   s4   | t ju rtƒ  t ¡ S | tvr(tdƒ‚tt|  ƒS )z6
    Helper that gets a given group's world size

    rB   )r=   r<   rL   rK   ÚsizerD   rC   Úlenr?   r#   r#   r$   Ú_get_group_sizeÖ   s    
rO   c                 C   s   t | tjƒstd |¡ƒ‚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ÚTensorrC   r   ©ÚparamÚ
param_namer#   r#   r$   Ú_check_single_tensorã   s    ÿrU   c                 C   s.   t | tƒrtdd„ | D ƒƒs*td |¡ƒ‚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 r/   )r   rP   rQ   )Ú.0Úpr#   r#   r$   Ú	<genexpr>ó   ó    z%_check_tensor_list.<locals>.<genexpr>zTInvalid function argument. Expected parameter `{}` to be of type List[torch.Tensor].N)r   ÚlistÚallrC   r   rR   r#   r#   r$   Ú_check_tensor_listí   s    
ÿÿr\   c                   C   s   t S )z2
    Checks if the MPI backend is available.

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

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

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

    NrJ   r#   r#   r#   r$   Úis_initialized  s    rc   c                   C   s   t ƒ stdƒ‚tS )zJ
    Getting the default process group created by init_process_group

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

    rd   )rc   rC   Ú_pg_maprK   )Ú_Údefault_storer#   r#   r$   Ú_get_default_store#  s    ri   c                 C   s:   t ƒ  | tjkrt}n| }t|ƒr*tdƒ‚t |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.

    úInvalid process group specifiedNr   )rL   r=   r<   rK   r@   rC   rf   Úget©r;   Úpgr#   r#   r$   Úget_backend/  s    
rn   éÿÿÿÿÚ c              	   C   s8  t |tƒstdƒ‚tdur"tdƒ‚|du s:|du s:J dƒ‚|durd|dksRJ dƒ‚|dkspJ dƒ‚n|du rpd}t| ƒ} | tjkr¾|d	ks’|d	kr¤t d
 ||¡¡ t	d	d	g tjd||d�anF|du rît
||||d�}t|ƒ\}}}| |¡ t	||g | |||d�add„ tt ¡ ƒD ƒtt< tt d a|atƒ  dS )a�  
    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 applicable for the ``gloo`` backend. For ``nccl``, this is
            applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
            or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When
            ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the
            process will block and wait for collectives to complete before
            throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,
            this is the duration after which collectives will be aborted
            asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``
            will provide errors to the user which can be caught and handled,
            but due to its blocking nature, it has a performance overhead. On
            the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has little
            performance overhead, but crashes the process on errors. This is
            done since CUDA execution is async and it is no longer safe to
            continue executing user code since failed async NCCL operations
            might result in subsequent CUDA operations to run on corrupted
            data. Only one of these two environment variables should be set.
        group_name (str, optional, deprecated): Group name.

    To enable ``backend == Backend.MPI``, PyTorch needs to be built from source
    on a system that supports MPI.

    ú9Expected 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://ro   zfFor MPI backend, world_size ({}) and rank ({}) are ignored since they are assigned by the MPI runtime.)Ú
group_nameÚtimeout©rs   c                 S   s   i | ]
}||“qS r#   r#   ©rV   Úir#   r#   r$   Ú
<dictcomp>À  rY   z&init_process_group.<locals>.<dictcomp>)r   r   rC   rK   r   r   r6   r7   r   Ú_new_process_group_helperr   ÚnextZset_timeoutÚrangerM   rD   rf   Ú_backendÚ_default_pg_init_methodÚbarrier)ÚbackendZinit_methodrs   Ú
world_sizerF   Ústorerr   Zrendezvous_iteratorr#   r#   r$   Úinit_process_groupG  s`    E
ÿ
þÿù
ÿ
ù	r�   c                 C   sZ  |st tƒ}td7 a|t ¡ v r(tdƒ‚t|tƒs:tdƒ‚t|ƒdk}t|ƒ}|tj	kr’t
ƒ sftdƒ‚t |¡}|sztjS tj	dft|< |t|< nÄ|s¬t ¡ }	|	|vr¬tjS t||ƒ}
|tjkrèt|
|| |d�}tj|ft|< |t|< nn|tjk�r*tƒ �stdƒ‚t|
|| |ƒ}tj|ft|< |t|< n,tt| ¡ ƒ|
|| |ƒ}||ft|< |t|< |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 namerq   r   z†Distributed package doesn't have MPI built in. MPI is only included if you build PyTorch from source on a host that has MPI installed.Nrt   z.Distributed package doesn't have NCCL built in)ÚstrÚ_group_countÚ	_pg_namesÚvaluesrC   r   r   rN   r   r   r^   r   Úcreater=   r>   rf   rK   rF   r   r   r   r   r`   r   r   r   )r   rF   Zgroup_ranksr~   r€   rr   rs   Zis_default_grouprm   Úglobal_rankZprefix_storer#   r#   r$   rx   É  sj    

ÿ



ü
ü
ürx   c                 C   s€   | t jkrdS | t jkrt}n| }t |d¡du r:tdƒ‚| t jkrjdadat ¡  t	 ¡  t
 ¡  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.
    Nrj   r   )r=   r>   r<   rK   rf   rk   rC   r|   Úclearr„   rD   rƒ   rl   r#   r#   r$   Údestroy_process_group#  s"    



r‰   c                 C   s2   t | ƒrdS tƒ  | tjkr$t ¡ S t| t ¡ ƒ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

    ro   )r@   rL   r=   r<   rK   rF   rH   r?   r#   r#   r$   Úget_rankU  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

    ro   )r@   rO   r?   r#   r#   r$   Úget_world_sizeo  s    r‹   c                 C   sT   t | dƒ t|ƒrdS |tjkr6tƒ  t | g||¡S t||ƒ}| | 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)rU   r@   r=   r<   rL   rK   ÚsendrH   ©rŒ   Údstr;   ÚtagÚgroup_dst_rankr#   r#   r$   Úisend�  s    


r’   c                 C   sT   t | dƒ t|ƒrdS |tjkr6tƒ  t | g||¡S t||ƒ}| | 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)rU   r@   r=   r<   rL   rK   ÚrecvrH   )rŒ   Úsrcr;   r�   Úgroup_src_rankr#   r#   r$   ÚirecvŸ  s    


r–   c                 C   s^   t | dƒ t|ƒrdS |tjkr<tƒ  t | g||¡ ¡  nt||ƒ}| | g||¡ ¡  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)	rU   r@   r=   r<   rL   rK   r�   ÚwaitrH   rŽ   r#   r#   r$   r�   ½  s    


r�   c                 C   s¶   t | dƒ t|ƒrdS |tjkr,tƒ  t}n|}|du rp| | g|¡}| ¡  | ¡ }|tjkrd|S t	||ƒS nB|tjkr�| 
| g||¡ ¡  nt||ƒ}| 
| g||¡ ¡  |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Œ   ro   N)rU   r@   r=   r<   rL   rK   Zrecv_anysourcer—   Z_source_rankrI   r“   rH   )rŒ   r”   r;   r�   rm   ÚworkZsrc_rankr•   r#   r#   r$   r“   ×  s&    




r“   c                 C   sl   t |ƒrdS tƒ }||_||_|tjkr<tƒ  t | |¡}nt	||ƒ}||_| | |¡}|r`|S | 
¡  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Ú
rootTensorr=   r<   rL   rK   Ú	broadcastrH   r—   )Útensor_listr”   r;   Ú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 	| g|¡}nt
||ƒ}||_| 	| g|¡}|rn|S | ¡  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   )rU   r@   r   r™   rš   r=   r<   rL   rK   r›   rH   r—   )rŒ   r”   r;   r�   rž   r˜   r•   r#   r#   r$   r›   <  s    


r›   c                 C   sV   t |ƒrdS tƒ }||_|tjkr6tƒ  t | |¡}n| | |¡}|rJ|S | ¡  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   ÚreduceOpr=   r<   rL   rK   Ú	allreducer—   )rœ   Úopr;   r�   rž   r˜   r#   r#   r$   Úall_reduce_multigpug  s    "
r£   c                 C   sd   t | dƒ t|ƒrdS tƒ }||_|tjkrBtƒ  t | g|¡}n| | g|¡}|rX|S | 	¡  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)
rU   r@   r   r    r=   r<   rL   rK   r¡   r—   )rŒ   r¢   r;   r�   rž   r˜   r#   r#   r$   Ú
all_reduceš  s    

r¤   c                 C   s`   t | dƒ t|ƒrdS tƒ }||_|tjkr@tƒ  t | |¡}n| | |¡}|rT|S | 	¡  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)
r\   r@   r	   r    r=   r<   rL   rK   Zallreduce_coalescedr—   )Ztensorsr¢   r;   r�   rž   r˜   r#   r#   r$   Úall_reduce_coalescedÄ  s    !

r¥   c           	      C   sr   t |ƒrdS tƒ }||_||_||_|tjkrBtƒ  t 	| |¡}nt
||ƒ}||_| 	| |¡}|rf|S | ¡  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š   r=   r<   rL   rK   ÚreducerH   r—   )	rœ   r�   r¢   r;   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 	| g|¡}nt
||ƒ}||_| 	| g|¡}|rn|S | ¡  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)rU   r@   r   r    r™   r=   r<   rL   rK   r¦   rH   r—   )rŒ   r�   r¢   r;   r�   rž   r˜   r‘   r#   r#   r$   r¦   0  s    


r¦   c                 C   sJ   t |ƒrdS |tjkr*tƒ  t | |¡}n| | |¡}|r>|S | ¡  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@   r=   r<   rL   rK   Ú	allgatherr—   )Úoutput_tensor_listsÚinput_tensor_listr;   r�   r˜   r#   r#   r$   Úall_gather_multigpu_  s    +
r«   c                 C   s8   t  | ¡}tj |¡}t |¡}t | ¡ g¡}||fS r/   )ÚpickleÚdumpsrP   ZByteStorageÚfrom_bufferÚ
ByteTensorÚ
LongTensorZnumel)ÚobjÚbufferZbyte_storageZbyte_tensorÚ
local_sizer#   r#   r$   Ú_object_to_tensor™  s
    

r´   c                 C   s"   |   ¡  ¡ d |… }t |¡}|S r/   )ÚnumpyÚtobytesr¬   Úloads)rŒ   Útensor_sizeÚbufÚoutr#   r#   r$   Ú_tensor_to_object¡  s    
r»   c                    s&  t |ƒrdS t|ƒ\}}t|ƒ}tƒ }|tjk}|rJ| |¡| |¡ }}t|d�}tj	|t
d� |rj|nd¡‰‡fdd„t|ƒD ƒ}	t|	||d� t|	ƒ‰| ˆ¡ tjˆ| tjd� |rÂ|nd¡‰ ‡ ‡fdd„t|ƒD ƒ}
t|
||d� t|
ƒD ]*\}}| tj¡}|	| }t||ƒ| |< qödS )a  
    Gathers picklable objects from the whole group into a list. Similar to
    :func:`all_gather`, but Python objects can be passed in. Note that the object
    must be picklable in order to be gathered.

    Arguments:
        object_list (list[Any]): Output list. It should be correctly sized as the
            size of the group for this collective and will contain the output.
        object (Any): Pickable Python object to be broadcast from current process.
        group (ProcessGroup, optional): The process group to work on

    Returns:
        None. If the calling rank is part of this group, the output of the
        collective will be populated into the input ``object_list``. If the
        calling rank is not part of the group, the passed in ``object_list`` will
        be unmodified.

    .. note:: Note that this API differs slightly from the :func:`all_gather`
        collective since it does not provide an ``async_op`` handle and thus
        will be a blocking call.

    .. warning::
        :func:`all_gather_object` uses ``pickle`` module implicitly, which is
        known to be insecure. It is possible to construct malicious pickle data
        which will execute arbitrary code during unpickling. Only call this
        function with data you trust.
    Nr?   ©ZdtypeÚcpuc                    s   g | ]}ˆ | j d d�‘qS ©r   )Zdim©Z	unsqueezeru   ©Úobject_sizes_tensorr#   r$   Ú
<listcomp>Ò  s   z%all_gather_object.<locals>.<listcomp>c                    s$   g | ]}ˆ ˆ| ˆ|d   … ‘qS ©r   r#   ru   ©Úcoalesced_output_tensorÚmax_object_sizer#   r$   rÂ   Þ  s   ÿ)r@   r´   rn   rŠ   r   r   Útor‹   rP   ÚzerosÚintrz   Ú
all_gatherÚmaxÚresize_ÚemptyÚuint8Ú	enumerateÚtyper¯   r»   )Úobject_listr±   r;   Úinput_tensorr³   Úgroup_backendÚmy_rankÚis_nccl_backendÚ
group_sizeÚobject_size_listÚoutput_tensorsrv   rŒ   r¸   r#   ©rÅ   rÆ   rÁ   r$   Úall_gather_object§  s>    


ÿ
ÿ

ÿ
þþrÚ   c                    sZ  t |ƒrdS tƒ }t|||ƒ t| ƒ\}}t|ƒ}|tjk}|rV| |¡| |¡ }}t|d�}	t	j
|	td� |rv|nd¡‰‡fdd„t|	ƒD ƒ}
t|
||d� t|
ƒ‰| ˆ¡ ||krôt	jˆ|	 t	jd� |rÖ|nd¡‰ ‡ ‡fdd„t|	ƒD ƒ}t|||k�r|nd||d� ||k�r dS t|ƒD ],\}}| t	j¡}|
| }t||ƒ||< �q(dS )	aB  
    Gathers picklable objects from the whole group in a single process.
    Similar to :func:`gather`, but Python objects can be passed in. Note that the
    object must be picklable in order to be gathered.

    Arguments:
        obj (Any): Input object. Must be picklable.
        object_gather_list (list[Any]): Output list. On the ``dst`` rank, it
            should be correctly sized as the size of the group for this
            collective and will contain the output. Must be ``None`` on non-dst
            ranks. (default is ``None``)
        dst (int, optional): Destination rank. (default is 0)
        group: (ProcessGroup, optional): The process group to work on.

    Returns:
        None. On the ``dst`` rank, ``object_gather_list`` will contain the
        output of the collective.

    .. note:: Note that this API differs slightly from the gather collective
        since it does not provide an async_op handle and thus will be a blocking
        call.

    .. note:: Note that this API is not supported when using the NCCL backend.

    .. warning::
        :func:`gather_object` uses ``pickle`` module implicitly, which is
        known to be insecure. It is possible to construct malicious pickle data
        which will execute arbitrary code during unpickling. Only call this
        function with data you trust.
    Nr?   r¼   r½   c                    s   g | ]}ˆ | j d d�‘qS r¾   r¿   ru   rÀ   r#   r$   rÂ     s   z!gather_object.<locals>.<listcomp>c                    s$   g | ]}ˆ ˆ| ˆ|d   … ‘qS rÃ   r#   ru   rÄ   r#   r$   rÂ   )  s   ÿ)Úgather_listr�   r;   )r@   rŠ   Ú_validate_output_list_for_rankr´   rn   r   r   rÇ   r‹   rP   rÈ   rÉ   rz   rÊ   rË   rÌ   rÍ   rÎ   ÚgatherrÏ   rÐ   r¯   r»   )r±   Zobject_gather_listr�   r;   rÔ   rÒ   r³   rÓ   rÕ   rÖ   r×   rØ   rv   rŒ   r¸   r#   rÙ   r$   Úgather_objectê  sP    


ÿ
ÿ

ÿ
þþü
rÞ   c                 C   s  t |ƒrdS tƒ }||kr<tdd„ | D ƒŽ \}}t |¡}nt t| ƒ¡}t|ƒ}|tj	k}|rj| 
|¡}t|||d� ||krŒt |¡}	nt t |¡ ¡ ¡}	|r®|	 
|¡}	t|	||d� d}
||k�rt|ƒD ]:\}}|	|
|
| … }| tj¡}|
|7 }
t||ƒ| |< qÒdS )aÛ  
    Broadcasts picklable objects in ``object_list`` to the whole group. Similar
    to :func:`broadcast`, but Python objects can be passed in.
    Note that all objects in ``object_list`` must be picklable in order to be
    broadcasted.

    Arguments:
        object_list (List[Any]): List of input objects to broadcast.
            Each object must be picklable. Only objects on the ``src`` rank will
            be broadcast, but each rank must provide lists of equal sizes.
        src (int): Source rank from which to broadcast ``object_list``.
        group: (ProcessGroup, optional): The process group to work on.

    Returns:
        ``None``. If rank is part of the group, ``object_list`` will contain the
        broadcasted objects from ``src`` rank.

    .. note:: Note that this API differs slightly from the broadcast collective
        since it does not provide an ``async_op`` handle and thus will be a
        blocking call.

    .. warning::
        :func:`broadcast_object_list` uses ``pickle`` module implicitly, which
        is known to be insecure. It is possible to construct malicious pickle
        data which will execute arbitrary code during unpickling. Only call this
        function with data you trust.
    Nc                 S   s   g | ]}t |ƒ‘qS r#   )r´   )rV   r±   r#   r#   r$   rÂ   ^  rY   z)broadcast_object_list.<locals>.<listcomp>)r”   r;   r   )r@   rŠ   ÚziprP   Úcatr°   rN   rn   r   r   rÇ   r›   r¯   ÚsumÚitemrÏ   rÐ   r»   )rÑ   r”   r;   rÔ   rœ   Z	size_listrÁ   rÓ   rÕ   Zobject_tensorÚoffsetrv   Zobj_sizeZobj_viewr#   r#   r$   Úbroadcast_object_list<  s2    



rä   c                 C   sf   t | dƒ t|dƒ t|ƒr dS |tjkrBtƒ  t | g|g¡}n| | g|g¡}|rZ|S | ¡  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)	r\   rU   r@   r=   r<   rL   rK   r¨   r—   )rœ   rŒ   r;   r�   r˜   r#   r#   r$   rÊ   ~  s    


rÊ   c                 C   sz   t |ƒrdS t|dƒ t| tƒs(tdƒ‚| D ]}t|dƒ q,|tjkrZtƒ  t 	| |¡}n| 	| |¡}|rn|S | 
¡  dS )as  
    Gathers input tensors from the whole group in a list in a coalesced manner.

    Arguments:
        output_tensor_lists (list[list[Tensor]]): Output list. It should contain
            correctly-sized tensors to be used for output of the collective.
        input_tensor_list (list[Tensor]): Tensors to be broadcast from
            current process. At least one tensor has to be non empty.
        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

    Example:
        we have 2 process groups, 2 ranks.
        rank 0 passes:
            input_tensor_list = [[[1, 1], [1, 1]], [2], [3, 3]]
            output_tensor_lists =
               [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
                [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
        rank 1 passes:
            input_tensor_list = [[[3, 3], [3, 3]], [5], [1, 1]]
            output_tensor_lists =
               [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
                [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
        both rank 0 and 1 get:
            output_tensor_lists =
               [[[1, 1], [1, 1]], [2], [3, 3]],
                [[3, 3], [3, 3]], [5], [1, 1]]].

    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
    all_gather_coalesced 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.
    Nrœ   z?Invalid function argument: output_tensor_lists should be a listr©   )r@   r\   r   rZ   rC   r=   r<   rL   rK   Zallgather_coalescedr—   )r©   rª   r;   r�   Úoutput_tensor_listr˜   r#   r#   r$   Úall_gather_coalesced¡  s     .


ÿræ   c                 C   s&   || kr|s"t dƒ‚n|r"t dƒ‚d S )Nz?Argument ``gather_list`` must be specified on destination rank.zHArgument ``gather_list`` must NOT be specified on non-destination ranks.)r   )rÔ   r�   rÛ   r#   r#   r$   rÜ   ä  s    ÿÿrÜ   c                 C   s²   t | dƒ |rt|dƒ ng }t|ƒr*dS tƒ }t|||ƒ ||krJ|gng }| g}tƒ }||_|tjkr€t	ƒ  t
 |||¡}	nt||ƒ}
|
|_| |||¡}	|r¦|	S |	 ¡  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Œ   rÛ   N)rU   r\   r@   rŠ   rÜ   r   r™   r=   r<   rL   rK   rÝ   rH   r—   )rŒ   rÛ   r�   r;   r�   rÔ   rØ   Úinput_tensorsrž   r˜   r‘   r#   r#   r$   rÝ   ñ  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
 |||¡}	nt||ƒ}
|
|_| |||¡}	|rº|	S |	 ¡  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.)rU   r\   r@   rŠ   r   r   r™   r=   r<   rL   rK   ÚscatterrH   r—   )rŒ   rè   r”   r;   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 | ||¡}n| | ||¡}|rN|S | ¡  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    r=   r<   rL   rK   Úreduce_scatterr—   )rå   Zinput_tensor_listsr¢   r;   r�   rž   r˜   r#   r#   r$   Úreduce_scatter_multigpuj  s&    -
ýýrë   c                 C   sv   t | dƒ t|dƒ t|ƒr dS tƒ }||_|tjkrPtƒ  t 	| g|g|¡}n| 	| g|g|¡}|rj|S | 
¡  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)rU   r\   r@   r   r    r=   r<   rL   rK   rê   r—   )rì   rí   r¢   r;   r�   rž   r˜   r#   r#   r$   rê   ±  s    


rê   c                 C   s�   t |ƒrdS tƒ }t| dƒ t|dƒ |du r2g n|}|du rBg n|}|tjkrjtƒ  t | ||||¡}n| | ||||¡}|r„|S | ¡  dS )a«  
    Each process splits input tensor and then scatters the split list
    to all processes in a group. Then concatenate the received tensors from all
    the processes in the group and return single output tensor.

    Arguments:
        output (Tensor): Gathered cancatenated output tensor.
        input (Tensor): Input tensor to scatter.
        output_split_sizes: (list[Int], optional): Output split sizes for dim 0
            if specified None or empty, dim 0 of ``output`` tensor must divide
            equally by ``world_size``.
        input_split_sizes: (list[Int], optional): Input split sizes for dim 0
            if specified None or empty, dim 0 of ``input`` tensor must divide
            equally by ``world_size``.
        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.

    .. warning::
        `all_to_all_single` is experimental and subject to change.

    Examples:
        >>> input = torch.arange(4) + rank * 4
        >>> input
        tensor([0, 1, 2, 3])     # Rank 0
        tensor([4, 5, 6, 7])     # Rank 1
        tensor([8, 9, 10, 11])   # Rank 2
        tensor([12, 13, 14, 15]) # Rank 3
        >>> output = torch.empty([4], dtype=torch.int64)
        >>> dist.all_to_all_single(output, input)
        >>> output
        tensor([0, 4, 8, 12])    # Rank 0
        tensor([1, 5, 9, 13])    # Rank 1
        tensor([2, 6, 10, 14])   # Rank 2
        tensor([3, 7, 11, 15])   # Rank 3

        >>> # Essentially, it is similar to following operation:
        >>> scatter_list = list(input.chunk(world_size))
        >>> gather_list  = list(output.chunk(world_size))
        >>> for i in range(world_size):
        >>>   dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)

        >>> # Another example with uneven split
        >>> input
        tensor([0, 1, 2, 3, 4, 5])                                       # Rank 0
        tensor([10, 11, 12, 13, 14, 15, 16, 17, 18])                     # Rank 1
        tensor([20, 21, 22, 23, 24])                                     # Rank 2
        tensor([30, 31, 32, 33, 34, 35, 36])                             # Rank 3
        >>> input_splits
        [2, 2, 1, 1]                                                     # Rank 0
        [3, 2, 2, 2]                                                     # Rank 1
        [2, 1, 1, 1]                                                     # Rank 2
        [2, 2, 2, 1]                                                     # Rank 3
        >>> output_splits
        [2, 3, 2, 2]                                                     # Rank 0
        [2, 2, 1, 2]                                                     # Rank 1
        [1, 2, 1, 2]                                                     # Rank 2
        [1, 2, 1, 1]                                                     # Rank 3
        >>> output = ...
        >>> dist.all_to_all_single(output, input, output_splits, input_splits)
        >>> output
        tensor([ 0,  1, 10, 11, 12, 20, 21, 30, 31])                     # Rank 0
        tensor([ 2,  3, 13, 14, 22, 32, 33])                             # Rank 1
        tensor([ 4, 15, 16, 23, 34, 35])                                 # Rank 2
        tensor([ 5, 17, 18, 24, 36])                                     # Rank 3
    Nrì   Úinput)	r@   r
   rU   r=   r<   rL   rK   Zalltoall_baser—   )rì   rî   Zoutput_split_sizesZinput_split_sizesr;   r�   rž   r˜   r#   r#   r$   Úall_to_all_singleØ  s    K


rï   c                 C   sh   t |ƒrdS tƒ }t| dƒ t|dƒ |tjkrFtƒ  t | ||¡}n| | ||¡}|r\|S | ¡  dS )a¬  
    Each process scatters list of input tensors to all processes in a group and
    return gathered list of tensors in output list.

    Arguments:
        output_tensor_list (list[Tensor]): List of tensors to be gathered one
            per rank.
        input_tensor_list (list[Tensor]): List of tensors to scatter one per 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.

    .. warning::
        `all_to_all` is experimental and subject to change.

    Examples:
        >>> input = torch.arange(4) + rank * 4
        >>> input = list(input.chunk(4))
        >>> input
        [tensor([0]), tensor([1]), tensor([2]), tensor([3])]     # Rank 0
        [tensor([4]), tensor([5]), tensor([6]), tensor([7])]     # Rank 1
        [tensor([8]), tensor([9]), tensor([10]), tensor([11])]   # Rank 2
        [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3
        >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
        >>> dist.all_to_all(output, input)
        >>> output
        [tensor([0]), tensor([4]), tensor([8]), tensor([12])]    # Rank 0
        [tensor([1]), tensor([5]), tensor([9]), tensor([13])]    # Rank 1
        [tensor([2]), tensor([6]), tensor([10]), tensor([14])]   # Rank 2
        [tensor([3]), tensor([7]), tensor([11]), tensor([15])]   # Rank 3

        >>> # Essentially, it is similar to following operation:
        >>> scatter_list = input
        >>> gather_list  = output
        >>> for i in range(world_size):
        >>>   dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)

        >>> input
        tensor([0, 1, 2, 3, 4, 5])                                       # Rank 0
        tensor([10, 11, 12, 13, 14, 15, 16, 17, 18])                     # Rank 1
        tensor([20, 21, 22, 23, 24])                                     # Rank 2
        tensor([30, 31, 32, 33, 34, 35, 36])                             # Rank 3
        >>> input_splits
        [2, 2, 1, 1]                                                     # Rank 0
        [3, 2, 2, 2]                                                     # Rank 1
        [2, 1, 1, 1]                                                     # Rank 2
        [2, 2, 2, 1]                                                     # Rank 3
        >>> output_splits
        [2, 3, 2, 2]                                                     # Rank 0
        [2, 2, 1, 2]                                                     # Rank 1
        [1, 2, 1, 2]                                                     # Rank 2
        [1, 2, 1, 1]                                                     # Rank 3
        >>> input = list(input.split(input_splits))
        >>> input
        [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])]                   # Rank 0
        [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1
        [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])]                 # Rank 2
        [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])]         # Rank 3
        >>> output = ...
        >>> dist.all_to_all(output, input)
        >>> output
        [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])]   # Rank 0
        [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])]           # Rank 1
        [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])]              # Rank 2
        [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])]                  # Rank 3
    Nrå   rª   )	r@   r
   r\   r=   r<   rL   rK   Zalltoallr—   )rå   rª   r;   r�   rž   r˜   r#   r#   r$   Ú
all_to_all7  s    I


rð   c                 C   sB   t | ƒrdS | tjkr&tƒ  t ¡ }n|  ¡ }|r6|S | ¡  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@   r=   r<   rL   rK   r}   r—   )r;   r�   r˜   r#   r#   r$   r}   “  s    

r}   c                 C   sÞ   t ƒ  tt \}}t ¡ }t ¡ }|s*|}| durŽt| ƒ} t| ƒ}||krRtdƒ‚| D ]}|dk sj||krVtdƒ‚qV|| v rˆ|  |¡}	q¢d}	nt	t
|ƒƒ} |}|}	t|ƒ}t||	| |||d�}
dd„ t| ƒD ƒt|
< tƒ  |
S )aŸ  
    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. If ``None``, will be
            set to all ranks. Default is ``None``.
        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_grouprt   c                 S   s   i | ]\}}||“qS r#   r#   )rV   rG   r‡   r#   r#   r$   rw   ø  s   ÿznew_group.<locals>.<dictcomp>)rL   rf   rK   rF   rM   ÚsortedrN   rC   ÚindexrZ   rz   r   rx   rÏ   rD   r}   )Zranksrs   r~   Zdefault_backendrh   r‡   Zglobal_world_sizeZgroup_world_sizerF   rG   rm   r#   r#   r$   Ú	new_group²  sB    
ûþ
ró   )\r¬   rP   r6   Z
torch._sixr   Údatetimer   Ú	constantsr   r   r   rp   r   r	   r
   r   r   r   r   r   r   r   r]   r_   ra   r   ÚImportErrorr   r   r8   r   r   r{   Zdist_backendr.   r;   r=   rf   r„   rD   rK   r|   rƒ   r@   rH   rI   rL   rO   rU   r\   r^   r`   rb   rc   re   ri   r<   rn   r�   rx   r‰   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ë   rê   rï   rð   r}   ró   r#   r#   r#   r$   Ú<module>   s.  (



<	


ú
 ú
Z2ý
 ý
 ý
ý
0ü
9ý
,ý
4ý
+ý
5û
;ü
1ý
:CRDý
%ý
Cü
8ü
Dü
Iü
)û
aý
\ÿ
