U
    9%e                 H   @   s
  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlZ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mZmZmZmZmZmZ d dlZd dlmZmZmZmZmZmZmZmZm Z 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,m-Z- dd	l.m/Z/m.Z. d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQgHZ0dRZ1dRZ2dRZ3dRZ4ej5Z6ej7Z8dSdT Z9e9  z d dUlm:Z: dVe:_;e0dWg7 Z0W n e<k
r   dXZ1Y nX z d dYlm=Z= dVe=_;e0dZg7 Z0W n e<k
rB   dXZ2Y nX z,d d[lm>Z> d d\lm?Z? dVe>_;e0d]g7 Z0W n e<k
r   dXZ3Y nX z d d^lm@Z@ dVe@_;e0d_g7 Z0W n e<k
r   dXZ4Y nX eAeBZCd`ZDe!eEdadbd:ZFG dcd
 d
ZGG ddd dZHG dedf dfZIeI ZJG dgd dZKG dhdi diZLi aMee eeNee% f f eOdj< i aPee eNf eOdk< i aQee eeReRf f eOdl< i aSee eNf eOdm< d aTi aUeeNee  f eOdn< i aVee eNf eOdo< G dpdq dqZWeW aXG drds dseYZZG dtd# d#eZduZ[G dvd deZduZ\da]dwZ^dee  dxdydzZ_e-ed{d|fd}d~Z`e dxddZadd Zbe eReRdddLZce eReRdddMZddd Zee dxddNZfdd Zgdd Zhdd ZiejjjkdddZlddddZmdd Zndd ZoeEddd(ZpeEddd*ZqeEddd&ZreEddd,ZseNeEddd)ZteEddd'ZueEddd+ZveRdddZwdd Zxdd Zydd Zzdee  eNdddZ{dee  eNddd Z|e, e-dde*dddddfeeNeGf eeN eeReRee% eNee ddd$Z}dde*dfddZ~dee  dxddZd ee  eRddd!Zdee  eRddd"ZdejeRee  eRe(ddd-ZdejeeR ee  eRe(ddd%Ze,dejeRee  eRdddd9Ze,dejeeR ee  eReRddd2ZG dd de(ZG dd dZejdee  eej eeE dddZdd Ze,dddZe,dddZe,e!jddXfddZe,e!jddXfddZe,e!jddXfddZe,e!jddXd fdd4Ze,e!jddXfdd3Ze,d	ddZdd̄ Zdd΄ Ze,d
ddZe,dddZe,dddZe,ddd8Ze,dddZe,dddPZe,dddքZe,dddZddل Ze,dddZe,ddd7Ze,e!jddXfdd6Ze,e!jddXfdd5Ze,e!jddXfddQZe!jddXfddZe,dddZe,dddZe,e\jdXdfddZe\jddXfdd.Ze*fe eNe%eReRedddZdd ZdeeN eGdddZe-de*dddXfdd/Zde*ddddXfddZdde*ddfdd0Ze*ddfdd1ZeNeeR e dddZeNeeR eRe dddZe eNdddZe eNdddZeeeeeeeeeeeeeeeeeeeeeeeeegZdS (      N)
namedtuple)	timedelta)AnyCallableDictOptionalTupleUnionList)AllreduceCoalescedOptionsAllreduceOptionsAllToAllOptions_DistributedBackendOptionsBarrierOptionsBroadcastOptionsGatherOptionsPrefixStoreProcessGroupReduceOpReduceOptionsReduceScatterOptionsScatterOptionsStore
DebugLevelget_debug_levelWork   )default_pg_timeout)_exception_logger_time_logger)register_rendezvous_handler
rendezvousBackendBackendConfigGroupMemberP2POp
all_gatherall_gather_coalescedall_gather_multigpuall_gather_object
all_reduceall_reduce_coalescedall_reduce_multigpu
all_to_allall_to_all_singlebarrierbatch_isend_irecv	broadcastbroadcast_multigpubroadcast_object_listdestroy_process_groupgathergather_objectget_backend_configget_backendget_rankget_world_sizegroupinit_process_groupirecvis_gloo_availableis_initializedis_mpi_availableis_backend_availableis_nccl_availableis_torchelastic_launchedis_ucc_availableisendmonitored_barrier	new_groupnew_subgroupsnew_subgroups_by_enumerationrecvreducereduce_multigpureduce_scatterreduce_scatter_multigpuscatterscatter_object_listsendsupports_complexr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   get_group_rankget_global_rankget_process_group_ranks	reduce_opall_gather_into_tensorreduce_scatter_tensorTc                  C   s8   t ttttttttt	t
tttttg} | D ]
}d|_q(d S )N"torch.distributed.distributed_c10d)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
__module__)Z_public_types_to_change_moduletype r\   a/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py_export_c_typesF   s&    r^   )ProcessGroupMPIrY   r_   F)ProcessGroupNCCLr`   )ProcessGroupGloo)_ProcessGroupWrapperra   )ProcessGroupUCCrc   Z
pg_wrapper)reduceOpreturnc                 C   s$   t jt jt jt jt jt jg}| |kS N)r   MAXZMINZPRODUCTZBANDZBORZBXOR)rd   ZdenyListr\   r\   r]   rR      s    c                   @   s  e Zd ZU dZdZdZdZdZdZe	ddd	gZ
i Zeee
f ed
< eeeeegZeedZeeef ed< eddgedgeddgedgiZeeee f ed< eejjeejjeejjeejjiZeeejf ed< edddZedeeeee f  dddZdS )r"   a  
    An enum-like class of available backends: GLOO, NCCL, UCC, 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.
    	undefinedZglooncclZuccZmpi_BackendPlugin
creator_fnextended_api_plugins)cpucudadefault_device_backend_maprn   ro   backend_capabilitybackend_type_map)namec                 C   s@   t |tstd| tt| tj}|tjkr<| }|S )Nz(Backend name must be a string, but got: )
isinstancestr
ValueErrorgetattrr"   upper	UNDEFINEDlower)clsrs   valuer\   r\   r]   __new__   s    

zBackend.__new__FN)devicesc                 C   s4  |t jks|t jkr:t r:tt | r:t|  d| t jksZt|  dtt | |  t j	
|  |dk	r|D ]"}|dkr|dkr| t j|< qtjjt j| < |dkrtd| d ddgt j| < n,t|tr|gt j| < n|t j| < t ||t j| < dS )av  
        Registers a new backend with the given name and instantiating function.

        This class method is used by 3rd party ``ProcessGroup`` extension to
        register new backends.

        Args:
            name (str): Backend name of the ``ProcessGroup`` extension. It
                        should match the one in ``init_process_group()``.
            func (function): Function handler that instantiates the backend.
                             The function should be implemented in the backend
                             extension and takes four arguments, including
                             ``store``, ``rank``, ``world_size``, and ``timeout``.
            extended_api (bool, optional): Whether the backend supports extended argument structure.
                                           Default: ``False``. If set to ``True``, the backend
                                           will get an instance of ``c10d::DistributedBackendOptions``, and
                                           a process group options object as defined by the backend implementation.
            device (str or list of str, optional): device type this backend
                            supports, e.g. "cpu", "cuda", etc. If `None`,
                            assuming both "cpu" and "cuda"

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

        z c10d backend already existz, c10d backend creator function already existNrn   ro   Device capability of zl unspecified, assuming `cpu` and `cuda`. Please specify it via the `devices` argument of `register_backend`.)r"   UCCrD   hasattrrx   AssertionErrorrm   setattrrz   backend_listappendrp   r   BackendTypeCUSTOMrr   warningswarnrq   rt   ru   rj   )r{   rs   funcrl   r~   devicer\   r\   r]   register_backend   s.    
zBackend.register_backend)FN)__name__rZ   __qualname____doc__ry   GLOONCCLr   MPIr   rj   rm   r   ru   __annotations__r   rp   rq   r
   r   r   rr   r}   classmethodr   r	   r   r\   r\   r\   r]   r"      sB   
        	c                   @   s2   e Zd Zeeef dddZdd Zdd ZdS )	r#   backendc                    sH  i | _ |tjkr<tjD ]"}ttj| rtj| | j |< qn| tjkrvtj|  }t|  fdd|D | _ nd| kr
d| d}| dD ]h}|d}t	|dkrt
d| d	| |\}}|| j krt
d
| d| d	| t|| j |< qn(td| d t|    d| _ td| j   d S )Nc                    s   i | ]
}| qS r\   r\   ).0r   Zbackend_valr\   r]   
<dictcomp>  s     z*BackendConfig.__init__.<locals>.<dictcomp>:z/The custom backend string argument is invalid: z.
                Custom backend string is an experimental feature where the backend string must be in the format:
                "<device_type1>:<backend1>,<device_type2>:<backend2>...". e.g. 'cpu:gloo,cuda:nccl',   zEInvalid device:backend pairing:                                      z. zDuplicate device type z9                                      in backend string: r   zp unknown, assuming `cpu` and `cuda`. You can specify it in `device:backend` format in `init_process_group` call.)rn   ro   ZxpuzUsing backend config: )device_backend_mapr"   ry   rp   rA   rz   r   rq   splitlenrv   r   r   loggerinfo)selfr   r   Zsupported_devicesZbackend_str_error_messageZdevice_backend_pair_strZdevice_backend_pairr\   r   r]   __init__  sP    








zBackendConfig.__init__c                 C   s   d dd | j D S )Nr   c                 s   s    | ]\}}| d | V  qdS )r   Nr\   )r   r   r   r\   r\   r]   	<genexpr>G  s     z)BackendConfig.__repr__.<locals>.<genexpr>)joinr   itemsr   r\   r\   r]   __repr__E  s    zBackendConfig.__repr__c                 C   s   | j S rf   )r   r   r\   r\   r]   get_device_backend_mapI  s    z$BackendConfig.get_device_backend_mapN)	r   rZ   r   r	   ru   r"   r   r   r   r\   r\   r\   r]   r#   
  s   9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   t jj D ]\}}t| || qt jj| _d S rf   )r   Z	RedOpType__members__r   r   )r   kvr\   r\   r]   r   T  s    z_reduce_op.__init__c                 C   s   t d t| |S )NzXtorch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead)r   r   object__getattribute__)r   keyr\   r\   r]   r   Z  s    z_reduce_op.__getattribute__N)r   rZ   r   r   r   r   r\   r\   r\   r]   r   L  s   r   c                   @   sL   e Zd ZdZd	eejeee	 edddZ
d
eejeee	 edddZdS )r%   a  
    A class to build point-to-point operations for ``batch_isend_irecv``.

    This class builds the type of P2P operation, communication buffer, peer rank,
    Process Group, and tag. Instances of this class will be passed to
    ``batch_isend_irecv`` for point-to-point communications.

    Args:
        op (Callable): A function to send data to or receive data from a peer process.
            The type of ``op`` is either ``torch.distributed.isend`` or
            ``torch.distributed.irecv``.
        tensor (Tensor): Tensor to send or receive.
        peer (int): Destination or source rank.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        tag (int, optional): Tag to match send with recv.
    Nr   optensorpeerr;   tagc                 C   s"   || _ || _|| _|| _|| _d S rf   r   )r   r   r   r   r;   r   r\   r\   r]   r   x  s
    zP2POp.__init__c                 C   s   t | t|d t| S )Nr   )	_check_op_check_single_tensorr   r}   )r{   r   r   r   r;   r   r\   r\   r]   r}     s    
zP2POp.__new__)Nr   )Nr   )r   rZ   r   r   r   torchTensorintr   r   r   r}   r\   r\   r\   r]   r%   e  s      
 	   
 c                   @   s8   e Zd ZdZdeejeej ee ee	 dddZ
dS )_CollOpa  
    A class to capture collective operations.

    Args:
        op (Callable): A collective function, e.g. ``torch.distributed.all_reduce``.
        tensor (Tensor): Tensor to operate on.
        dst_tensor (Tensor, optional): Provided when source and destinaton tensors are not the same.
        redop (ReduceOp, optional): reduce operation.
        root (int, optional): root of broadcast or reduce.
    Nr   r   
dst_tensorredoprootc                 C   s"   || _ || _|| _|| _|| _d S rf   r   )r   r   r   r   r   r   r\   r\   r]   r     s
    z_CollOp.__init__)NNN)r   rZ   r   r   r   r   r   r   r   r   r   r\   r\   r\   r]   r     s        r   _pg_map	_pg_names_pg_group_ranks_pg_backend_config_tags_to_pg
_pg_to_tagc                   @   sn  e Zd ZdZdd Zedd Zejdd Zeee	e
eee f f ddd	Zeee	ef dd
dZeee	eeef f dddZeee	ef dddZeedddZejdd Zeeeee	 f dddZeee	ef dddZeee	eeeef  f dddZeee	ejf dddZeeeeeeef f  dddZdS )_Worldz
    Container class for c10d process group state.
    This is used during registration and lookup of PG state.

    .. warning:: This is an experimental API intended to expose the inner workings
       of c10d and is subject to change..
    c                 C   s   d | _ i | _i | _d S rf   )_default_pg_pg_coalesce_state_pg_default_devicer   r\   r\   r]   r     s    z_World.__init__c                 C   s   | j S )z
        The default ProcessGroup includes all ranks of the cluster.
        This is used by c10d APIs when a ProcessGroup is needed but None is provided.
        r   r   r\   r\   r]   
default_pg  s    z_World.default_pgc                 C   s
   || _ d S rf   r   r   r|   r\   r\   r]   r     s    re   c                 C   s   t S )z
        Cached process groups
        For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
        For MPI pg, it is a map from ProcessGroup to (Backend, None)

        TODO don't expose the map, expose fine grained ops
        )r   r   r\   r\   r]   pg_map  s    
z_World.pg_mapc                 C   s   t S )z
        Process group's names, map from ProcessGroup to str.

        TODO don't expose the map, expose fine grained ops
        )r   r   r\   r\   r]   pg_names  s    z_World.pg_namesc                 C   s   t S )z~
        Process group's global rank to local rank mapping
        TODO don't expose the map, expose fine grained ops
        )r   r   r\   r\   r]   pg_group_ranks  s    z_World.pg_group_ranksc                 C   s   t S )zk
        Process group's backend config
        TODO don't expose the map, expose fine grained ops
        )r   r   r\   r\   r]   pg_backend_config  s    z_World.pg_backend_configc                 C   s   t S )z|
        Process group count for default naming.

        TODO don't expose group_count, use something else instead
        _group_countr   r\   r\   r]   group_count  s    z_World.group_countc                 C   s   |a dS )zk
        Count is used when computing the name of ProcessGroups when using global synchronization.
        Nr   r   r\   r\   r]   r     s    c                 C   s   t S rf   )r   r   r\   r\   r]   
tags_to_pg  s    z_World.tags_to_pgc                 C   s   t S rf   )r   r   r\   r\   r]   	pg_to_tag   s    z_World.pg_to_tagc                 C   s   | j S rf   )r   r   r\   r\   r]   pg_coalesce_state  s    z_World.pg_coalesce_statec                 C   s   | j S rf   )r   r   r\   r\   r]   pg_default_device	  s    z_World.pg_default_devicec                 C   sT   g }| j  D ]@\}}tj|d  }|| ||| j| | j| d q|S )z
        Returns a list of dict with process groups and backends with their unique IDs
        and configurations (types and ranks).
        r   )Zpg_idZ
backend_idbackend_configranks)	r   r   r"   rr   r   Z_idZ_backend_idr   r   )r   Zconfig_infopgr   backend_typer\   r\   r]   pg_config_info  s    z_World.pg_config_infoN)r   rZ   r   r   r   propertyr   setterr   r   r   ru   r   r   r   r   r   r   r   r   r
   r   r   r	   r   r%   r   r   r   r   r   r\   r\   r\   r]   r     s8   

$	 	
$r   c                   @   s>   e Zd ZdZeee dddZejee dddZdS )
_WorldMetazh
    Meta class of ``group`` and ``GroupMember`` so they
    can have the class property ``WORLD``.
    r   c                 C   s   t jS rf   _worldr   )r{   r\   r\   r]   WORLD+  s    z_WorldMeta.WORLDr   c                 C   s
   |t _d S rf   r   )r{   r   r\   r\   r]   r   /  s    N)	r   rZ   r   r   r   r   r   r   r   r\   r\   r\   r]   r   %  s
   r   c                   @   s   e Zd ZdS )r;   N)r   rZ   r   r\   r\   r\   r]   r;   3  s   )	metaclassc                   @   s   e Zd ZdZdS )r$   iN)r   rZ   r   NON_GROUP_MEMBERr\   r\   r\   r]   r$   6  s   Zstore_based_barrier_keyr;   c                 C   s   | pt  } | tjkrtj|  S t| tsXtdt|  d t	dtj| < tj|  S | j
}t|dkrz|d tj| < nLt|dkrt	dtj| < n.t	d|krt	dtj| < n|d tj| < tdtj|   d tj|  S )a  
    Returns the device to use with ``group`` for control flow usage (object collectives, barrier).
    There are selection rules:
        1. If user specifies exactly one backend in ``init_process_group`` call:
            use that backend
        2. Else if user specifies multiple "device:backend" pairs in init_process_group:
            If "cpu" is among those pairs, use "cpu" (because the object is in cpu memory);
            Otherwise, use the first backend (sort of a random pick).

    Args:
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.

    Returns:
        torch.device: The device to use with ``group``.

    zYou are using a Backend zw as a ProcessGroup. This usage is deprecated since PyTorch 2.0. Please use a public API of PyTorch Distributed instead.rn   r   r   zUsing device z for object collectives.)_get_default_groupr   r   rt   r   r   r   r[   r   r   Z_device_typesr   r   r   )r;   r~   r\   r\   r]   _get_pg_default_device?  s*    




r   
   secondsc                 C   s   t  d| }||d td||  |}||d}| d}	||krV||	d t }
z||	g| W qW q^ tk
r } zP||d}td| |||| tt |
 d|krtd		| ||||W 5 d
}~X Y q^X q^td| || d
S )z
    Barrier based on store which is used for synchronizing processes after
    ``init_process_group`` or ``new_group``. Intended to be used only with
    those two methods and is not a generic alternative to ``barrier()``.
    r   r   z#Added key: %s to store for rank: %sr   z:last_worker1zWaiting in store based barrier to initialize process group for rank: %s, key: %s (world_size=%s, num_workers_joined=%s, timeout=%s)r   zTimed out initializing process group in store based barrier on rank {}, for key: {} (world_size={}, num_workers_joined={}, timeout={})Nz@Rank %s: Completed store-based barrier for key:%s with %s nodes.)
STORE_BASED_BARRIER_PREFIXaddr   r   settimewaitRuntimeErrorr   format)rankstore
group_nameZrendezvous_counttimeoutZlogging_intervalZ	store_key
world_sizeZworker_countZlast_worker_keystarter\   r\   r]   _store_based_barrier  sL    
           r   c                 C   s   | dkrdS | t jkS )zS
    Helper that checks if the current process's rank is not in a given group.
    NF)r$   r   r   r\   r\   r]   _rank_not_in_group  s    r   c                 C   s4   t jd krdnt j }td|  d| d d S )NzRunning z on global rank z* which does not belong to the given group.)r$   r   r   r   r   )Zop_nameglobal_rankr\   r\   r]   _warn_not_in_group  s    r   )r;   r   re   c                 C   sV   | t jkr|S | tjkr(td|  dtj|  }||krNtd| d|  || S )a  
    Translate a global rank into a group rank.

    ``global_rank`` must be part of ``group`` otherwise this raises RuntimeError.

    Args:
        group (ProcessGroup): ProcessGroup to find the relative rank.
        global_rank (int): Global rank to query.

    Returns:
        Group rank of ``global_rank`` relative to ``group``

    N.B. calling this function on the default process group returns identity
    Group L is not registered, please create group with torch.distributed.new_group APIzGlobal rank  is not part of group )r$   r   r   r   r   )r;   r   group_ranksr\   r\   r]   rS     s    


)r;   
group_rankre   c                 C   sh   | t jkr|S | tjkr(td|  dtj|   D ]\}}||kr6|  S q6td| d|  dS )a  
    Translate a group rank into a global rank.

    ``group_rank`` must be part of `group` otherwise this raises RuntimeError.

    Args:
        group (ProcessGroup): ProcessGroup to find the global rank from.
        group_rank (int): Group rank to query.

    Returns:
        Global rank of ``group_rank`` relative to ``group``

    N.B. calling this function on the default process group returns identity
    r  r  zGroup rank r  N)r$   r   r   r   r   r   )r;   r  r   Zgrp_rankr\   r\   r]   rT     s    


c                 C   s   t d t| |S )z@
    This method is deprecated, please use get_global_rank.
    ztorch.distributed.distributed_c10d._get_global_rank is deprecated please use torch.distributed.distributed_c10d.get_global_rank instead)r   r   rT   )r;   r   r\   r\   r]   _get_global_rank  s    r  c                 C   s   t tj|   S )z
    Get all ranks associated with ``group``.

    Args:
        group (ProcessGroup): ProcessGroup to get all ranks from.

    Returns:
        List of global ranks ordered by group rank.
    )listr   r   keysr   r\   r\   r]   rU      s    
c                 C   s(   | t jks| dkr t }| S |  S )z6
    Helper that gets a given group's world size.
    N)r$   r   r   sizer;   r   r\   r\   r]   _get_group_size  s    r  c                 C   s    t | tjstd| ddS )zO
    Helper to check that the parameter ``param_name`` is a single tensor.
    /Invalid function argument. Expected parameter `z` to be of type torch.Tensor.N)rt   r   r   r   param
param_namer\   r\   r]   r     s    
r   c                 C   s0   t | trtdd | D s,td| ddS )zQ
    Helper to check that the parameter ``param_name`` is a list of tensors.
    c                 s   s   | ]}t |tjV  qd S rf   )rt   r   r   )r   pr\   r\   r]   r   $  s    z%_check_tensor_list.<locals>.<genexpr>r  z#` to be of type List[torch.Tensor].N)rt   r  allr   r  r\   r\   r]   _check_tensor_list   s    
r  r   c                 C   s   t | tr| S | fS rf   )rt   r  )objr\   r\   r]   _as_iterable+  s    r  c                  G   sl   d }t jtt|  D ]R}|j}|jr:|tjkr4tjntj	}|d krH|}q||krt
d| d|j qd S )Nz4Invalid usage of tensors with different dtypesFound z and  )	itertoolschainmapr  dtype
is_complexr   Z	complex64Zfloat32Z
complex128r   )tensorsZ
last_dtyper   Ztensor_dtyper\   r\   r]   _ensure_all_tensors_same_dtype.  s    r  c                 C   s   | t tfkrtddS )zC
    Helper to check that the ``op`` is either isend or irecv.
    ziInvalid ``op``. Expected ``op`` to be of type ``torch.distributed.isend`` or ``torch.distributed.irecv``.N)rE   r=   r   )r   r\   r\   r]   r   @  s    r   c                    sP   t | trtdd | D s$td| d j t fdd| D sLtddS )zs
    Helper to check that the ``p2p_op_list`` is a list of P2POp instances and
    all ops use the same group.
    c                 s   s   | ]}t |tV  qd S rf   )rt   r%   r   p2p_opr\   r\   r]   r   Q  s    z%_check_p2p_op_list.<locals>.<genexpr>zZInvalid ``p2p_op_list``. Each op is expected to to be of type ``torch.distributed.P2POp``.r   c                 3   s   | ]} |j kV  qd S rf   r   r  r   r\   r]   r   Z  s     z#All ops need to use the same group.N)rt   r  r  r   r;   )p2p_op_listr\   r   r]   _check_p2p_op_listL  s    
r  c                   C   s   t S )z1
    Checks if the MPI backend is available.
    )_MPI_AVAILABLEr\   r\   r\   r]   r@   ^  s    c                   C   s   t S )z2
    Checks if the NCCL backend is available.
    )_NCCL_AVAILABLEr\   r\   r\   r]   rB   e  s    c                   C   s   t S )z2
    Checks if the Gloo backend is available.
    )_GLOO_AVAILABLEr\   r\   r\   r]   r>   l  s    c                   C   s   t S )z1
    Checks if the UCC backend is available.
    )_UCC_AVAILABLEr\   r\   r\   r]   rD   s  s    )r   re   c                 C   s2   t tjd|   dd}|r$| S |  tjkS )a%  
    Checks if the given backend is available and supports the built-in backends or
    third-party backends through function ``Backend.register_backend``.

    Args:
        backend (str): Backend name.
    Returns:
        bool: Returns true if the backend is available otherwise false.
    is_Z
_availableN)rw   r   distributedrz   r"   r   )r   Zavailable_funcr\   r\   r]   rA   z  s    c                   C   s
   t jdk	S )zD
    Checking if the default process group has been initialized
    N)r$   r   r\   r\   r\   r]   r?     s    c                   C   s   t ddk	S )a  
    Checks whether this process was launched with ``torch.distributed.elastic``
    (aka torchelastic). The existence of ``TORCHELASTIC_RUN_ID`` environment
    variable is used as a proxy to determine whether the current process
    was launched with torchelastic. This is a reasonable proxy since
    ``TORCHELASTIC_RUN_ID`` maps to the rendezvous id which is always a
    non-null value indicating the job id for peer discovery purposes..
    ZTORCHELASTIC_RUN_IDN)osgetenvr\   r\   r\   r]   rC     s    	c                   C   s   t tddS )NZTORCH_DIST_INIT_BARRIER0)r   r&  r'  r\   r\   r\   r]   _is_barrier_after_init  s    r)  c                   C   s   t  stdtjS )zI
    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.)r?   r   r$   r   r\   r\   r\   r]   r     s
    r   c                  C   s&   t  stdt } tj|  \}}|S )zA
    Getting the default store created by init_process_group
    r*  )r?   r   r   r   r   )r   _default_storer\   r\   r]   _get_default_store  s    r-  c                 C   s
   | t _d S rf   r   r   r\   r\   r]   _update_default_pg  s    r.  )r;   re   c                 C   sD   | d krt  }n| }t|r$tdtj|}|d k	s<tt|S )NInvalid process group specified)r   r   r   r   r   getr   ru   )r;   r   r   r\   r\   r]   r7     s    c                 C   sP   | dkrt  }n| }t|r$td|tjkr8tj| nd}|dk	sHt|d S )a  
    Returns the backend of the given process group.

    Args:
        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.

    Nr/  r   )r   r   r   r   r   r   )r;   r   pg_storer\   r\   r]   r8     s    r    )r   init_methodr   r   r   r   r   
pg_optionsc              
   C   s  t |tstdtjdk	r$td|dks<|dks<td|dk	rf|dksTtd|dksrtdn|dkrrd}| rt| } ntd	} tg d
d}| tjkr|dks|dkrt	
d| d| d tddg | d||d\}}	t| n`|dkr&t||||d}
t|
\}}}|| td|}t||g | ||||d\}}	t| dd ttj D tjtj< tjtj d a|at dkrtd | tjkrt  n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://".


    Args:
        backend (str or Backend, optional): The backend to use. Depending on
            build-time configurations, valid values include ``mpi``, ``gloo``,
            ``nccl``, and ``ucc``. If the backend is not provided, then both a ``gloo``
            and ``nccl`` backend will be created, see notes below for how multiple
            backends are managed. This field can 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. ``ucc`` backend is
            experimental.
        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 (it should be a
                              number between 0 and ``world_size``-1).
                              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 very 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 running on corrupted
            data. Only one of these two environment variables should be set.
            For ``ucc``, blocking wait is supported similar to NCCL. However,
            async error handling is done differently since with UCC we have
            progress thread and not watch-dog thread.
        group_name (str, optional, deprecated): Group name. This argument is ignored
        pg_options (ProcessGroupOptions, optional): process group options
            specifying what additional options need to be passed in during
            the construction of specific process groups. As of now, the only
            options we support is ``ProcessGroupNCCL.Options`` for the ``nccl``
            backend, ``is_high_priority_stream`` can be specified so that
            the nccl backend can pick up high priority cuda streams when
            there're compute kernels waiting.

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

    .. note:: Support for multiple backends is experimental. Currently when no backend is
        specified, both ``gloo`` and ``nccl`` backends will be created. The ``gloo`` backend
        will be used for collectives with CPU tensors and the ``nccl`` backend will be used
        for collectives with CUDA tensors. A custom backend can be specified by passing in
        a string with format "<device_type>:<backend_name>,<device_type>:<backend_name>", e.g.
        "cpu:gloo,cuda:custom_backend".

    :Expected timeout argument to be of type datetime.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://rh   Fuse_hashed_namer   zFor MPI backend, world_size (z) and rank (z9) are ignored since they are assigned by the MPI runtime.)r   r   r   r   )r4  r   r   c                 S   s   i | ]
}||qS r\   r\   r   ir\   r\   r]   r     s      z&init_process_group.<locals>.<dictcomp>r   VPerforming barrier after ProcessGroup initialization since TORCH_DIST_INIT_BARRIER = 1)rt   r   r   r$   r   r   r"   _process_group_namer   r   r   _new_process_group_helperr.  r!   nextZset_timeoutr   ranger	  r   r   r   Z_backend_default_pg_init_methodr)  r   r   r/   r   )r   r3  r   r   r   r   r   r4  r   r+  Zrendezvous_iteratorr\   r\   r]   r<     s    ^



      


   



 	c	              	   C   s  |t j krtdt|ts(td|dkrTt||}	|	rTt j|	 \}
}|	|fS t|dk}|st	 
 }||krtjdfS t| d|}tjt|d}||_t||| |}t|}|  D ]\}}t| d|}|tjkrTt stdt|}tjj}|stj  S |
 d	kr| d	krt||
 | |}nN|tjkr|t||| |d
}tjj}n&|tjkrt std|dk	rt|t jst!dnt  }d|_"||_t ||| |}tjj}n|tj#krt$ rt%||| |d
}tjj#}n|& tj'ks6t!d|&  tj'|&  }|j(}|j)}tjj*}|sn|||| |}n4t+ }||_,||_-| |_.||_/||_0||_1|||}|tjtjfkr|2  t3t4|tr|} q~|tjtjtj#fkr t5 t6j7kr t8st9:d nt;||||| |d}tt<|  dkrh| = D ]}|>t?@||| qF q~|>t?@||| q||ft j|< |t j|< t|t jA|< |dkrd| }t jBCdg D| n
d| }t jBC|g D| |t jE|< ||fS )a`  
    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 ``global_ranks_in_group == []`` for the default group.
    zTThe specified group name has already been created, please use a different group namer5  )Nr2  r   N/r   zDistributed package doesn't have MPI built in. MPI is only included if you build PyTorch from source on a host that has MPI installed.r   r8  z.Distributed package doesn't have NCCL built inzCExpected pg_options argument to be of type ProcessGroupNCCL.OptionsFzUnknown c10d backend type a  TORCH_DISTRIBUTED_DEBUG was set to DETAIL, but
                                GLOO is not available. Build with Gloo to
                                create a wrapper process group in debug mode
                                to aid collective desynchronization debugging.
wrapped_pgstore_prefixr   r   r   r   r   ptd:r2  user:)Fr   r   valuesr   rt   r   _find_pg_by_ranks_and_tagr   r   r   r   r$   r   r   r   Optionsru   _timeoutr#   r   r   r"   r   r@   r_   creater   r	  r   ra   r   rB   r`   r   Zis_high_priority_streamr   rD   rc   rx   rm   rk   rl   r   r   r   r  
group_sizer   Zgroup_idglobal_ranks_in_groupZ_set_sequence_number_for_group
issubclassr[   r   r   ZDETAILr"  r   r   _create_process_group_wrapperr   r  Z_register_backendr   r   r   r   
setdefaultr   r   )rL  r  rM  r   r   r4  r   r   pg_tagZexisting_groupr+  Zprefix_storeZis_default_groupr   Zbase_pg_optionsr   r   r   Zbackend_strZbackend_prefix_storeZbackend_classr   Zbackend_pluginrk   rl   Zdist_backend_optsr\   r\   r]   r=    s    






 








r=  c                 C   s  | t jkrdS | dkrt j}n| }|dk	s.ttj|ddkrHtd| 	 dkrh|
 rh|  | dksz| t jkrtd tj  tj  tj  tj  tj  tj  tj  tj  dt_ntj|= tj|= tj|= tj|= |tjkrtj|= |tj kr0td tj|= tj|}tj|= |dk	rz0tj| | |dr|tjd | W n tk
r   Y nX dS )ax  
    Destroy a given process group, and deinitialize the distributed package

    Args:
        group (ProcessGroup, optional): The process group to be destroyed, if
                                        group.WORLD is given, all process
                                        groups including the default one will
                                        be destroyed.
    Nr/  ri   r   zfSome coalesced collectives haven't been launched when ProcessGroup is destroyed. They will be cleaned.rE  r2  )r$   r   r   r   r   r   r0  r   rs   rz   Z
_has_hooksZ_wait_for_pending_worksr.  clearr   r   r   r   r   r   r   r   r  r   r   remove
startswith	Exception)r;   r   r   r\   r\   r]   r4   X  sR    











c                 C   s:   t | rdS t }| dks$| tjkr,| S t| | S )a  
    Returns the rank of the current process in the provided ``group`` or the
    default group if none was provided.

    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``.

    Args:
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.

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

    r   N)r   r   r$   r   r   rS   r
  r\   r\   r]   r9     s    c                 C   s   t | rdS t| S )a4  
    Returns the number of processes in the current process group

    Args:
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.

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

    r   )r   r  r   r\   r\   r]   r:     s    )r   dstr;   r   re   c                 C   sd   t | d t|rtd dS |dks0|tjkrFt }|| g||S t||}|| g||S dS )aY  
    Sends a tensor asynchronously.

    .. warning::
        Modifying ``tensor`` before the request completes causes undefined
        behavior.

    .. warning::
        ``tag`` is not supported with the NCCL backend.

    Args:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        tag (int, optional): Tag to match send with remote recv

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

    r   rE   N)r   r   r   r$   r   r   rQ   rS   r   rV  r;   r   r   group_dst_rankr\   r\   r]   rE     s    

)r   srcr;   r   re   c                 C   s   t | d t|rtd dS |dks0|tjkr8t }n|}|dkrR|| g|S |tjkrl|| g||S t||}|| g||S dS )a?  
    Receives a tensor asynchronously.

    .. warning::
        ``tag`` is not supported with the NCCL backend.

    Args:
        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. If None,
            the default process group will be used.
        tag (int, optional): Tag to match recv with remote send

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

    r   r=   N)	r   r   r   r$   r   r   recv_anysourcerJ   rS   )r   rY  r;   r   r   group_src_rankr\   r\   r]   r=     s    


c                 C   s   t  |krtdt| d t|r0td dS |dksB|tjkr^t }|| g||	  nt
||}|| g||	  dS )a  
    Sends a tensor synchronously.

    Args:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank. Destination rank should not be the same
        as the rank of the current process.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        tag (int, optional): Tag to match send with remote recv

    zeInvalid destination rank: destination rank should not be the same as the rank of the current process.r   rQ   N)r9   rv   r   r   r   r$   r   r   rQ   r   rS   rW  r\   r\   r]   rQ   "  s    


c                 C   s   t | d t|rtd dS |dkr.t }n|}|dkrz|| g|}|  | }|dksj|tjkrn|S t	||S nJ|dks|tjkr|
| g||  nt||}|
| g||  |S dS )a  
    Receives a tensor synchronously.

    Args:
        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. If None,
            the default process group will be used.
        tag (int, optional): Tag to match recv with remote send

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

    r   rJ   r   N)r   r   r   r   rZ  r   _source_rankr$   r   rT   rJ   rS   )r   rY  r;   r   r   workZsrc_rankr[  r\   r\   r]   rJ   B  s&    

c                   @   s   e Zd Zdd ZdS )_IllegalWorkc                 C   s   |dkrt d| dd S )N)Z
is_success	exceptionr   Zsource_rankr\  resultZsynchronizezIllegal to call z on IllegalWork object)r   )r   rs   r\   r\   r]   r   p  s    z_IllegalWork.__getattribute__N)r   rZ   r   r   r\   r\   r\   r]   r^  o  s   r^  c                   @   s*   e Zd Zdd ZedddZdd ZdS )	_CoalescingManagerc                 C   s
   g | _ d S rf   )worksr   r\   r\   r]   r   v  s    z_CoalescingManager.__init__)r]  c                 C   s   |r| j | d S rf   )rb  r   r   r]  r\   r\   r]   r   y  s    z_CoalescingManager.appendc                 C   s   | j D ]}|  qd S rf   )rb  r   rc  r\   r\   r]   r   }  s    
z_CoalescingManager.waitN)r   rZ   r   r   r   r   r   r\   r\   r\   r]   ra  u  s   ra  )r;   r   	async_opsc                 c   sv  | pt  } tj| g }|r$td|r2| | t }|V  tj| }|rH|d j}|t	krg }|D ]}|
|j qjt }|d j|_| ||}	n|tkrg }
g }|D ]}|

|j |
|j q| ||
}	nl|tkr2g }
g }|D ].}|

|j |
|j t }|d j|_q| ||
|}	ntd| d| d|rX| |}	|rj|
|	 n|	  dS )a<  
    A context manager used to coalesce collectives or P2P operations when possible.

    Args:
        group (`ProcessGroup`, optional): The process group to work on. If None,
            the default process group will be used.
        device (`torch.device`, optional): Default is None, set to a device if
            there isn't a `**_coalesced` implementation by the backend.
        async_ops (`bool`, optional): whether the coalesced ops are async ops.

    Examples:
        >>> # xdoctest: +SKIP("no rank")
        >>> # Synchronous ops
        >>> with _coalescing_manager():
        >>>     for i in range(num_colls):
        >>>         dist.all_reduce(tensors[i])
        >>> # Asynchronous ops
        >>> with _coalescing_manager(async_ops=True) as cm:
        >>>     for i in range(num_colls):
        >>>         dist.all_reduce(tensors[i])
        >>> cm.wait()

    .. warning::
       :func:`_coalescing_manager` currently do not support coalescing
       all-reduces with different reduce operators, e.g.  `ReduceOp.SUM` mixed
       with `ReduceOp.PRODUCT`.
    z=ProcessGroup has non-empty op list at the start of coalescingr   z<Coalescing manager does not support fast-path coalescing of z, yet zA is still recorded in op list. This is an internal error of c10d.N)r   r   r   rP  r   Z_start_coalescingra  popr   r*   r   r   r   r   rd   allreduce_coalescedrW   r   Zallgather_into_tensor_coalescedrX   r   Zreduce_scatter_tensor_coalescedr   Z_end_coalescingr   )r;   r   rd  op_listcmZop0r  r   optsr]  inputsoutputsr\   r\   r]   _coalescing_manager  sT    !




rl  c              	   C   s   t |  | d j}| d jj}|jdkrjt||dd(}| D ]}||j|j|j|j q<W 5 Q R X |j	S g }| D ]*}||j|j|j|j}|rr|
| qr|S dS )a  
    Send or Receive a batch of tensors asynchronously and return a list of requests.

    Process each of the operations in ``p2p_op_list`` and return the corresponding
    requests. NCCL, Gloo, and UCC backend are currently supported.

    Args:
        p2p_op_list: A list of point-to-point operations(type of each operator is
            ``torch.distributed.P2POp``). The order of the isend/irecv in the list
            matters and it needs to match with corresponding isend/irecv on the
            remote end.

    Returns:
        A list of distributed request objects returned by calling the corresponding
        op in the op_list.

    Examples:
        >>> # xdoctest: +SKIP("no rank")
        >>> send_tensor = torch.arange(2) + 2 * rank
        >>> recv_tensor = torch.randn(2)
        >>> send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1)%world_size)
        >>> recv_op = dist.P2POp(dist.irecv, recv_tensor, (rank - 1 + world_size)%world_size)
        >>> reqs = batch_isend_irecv([send_op, recv_op])
        >>> for req in reqs:
        >>>     req.wait()
        >>> recv_tensor
        tensor([2, 3])     # Rank 0
        tensor([0, 1])     # Rank 1

    .. note:: Note that when this API is used with the NCCL PG backend, users must set
        the current GPU device with `torch.cuda.set_device`, otherwise it will
        lead to unexpected hang issues.

        In addition, if this API is the first collective call in the ``group``
        passed to ``dist.P2POp``, all ranks of the ``group`` must participate in
        this API call; otherwise, the behavior is undefined. If this API call is
        not the first collective call in the ``group``, batched P2P operations
        involving only a subset of ranks of the ``group`` are allowed.
    r   ro   T)rd  N)r  r;   r   r   r[   rl  r   r   r   rb  r   )r  r;   r   rh  r  reqsr]  r\   r\   r]   r0     s    (

$c           	      C   s   t d t|rtd dS t }||_||_|dksB|tjkrVt	 }|
| |}nt||}||_|
| |}|rz|S |  dS )aP  
    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

    Args:
        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. If None,
            the default process group will be used.
        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

    ztorch.distributed.broadcast_multigpu will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#multi-gpu-collective-functionsr2   N)r   r   r   r   r   rootRank
rootTensorr$   r   r   r1   rS   r   )	tensor_listrY  r;   async_opZ
src_tensorri  r   r]  r[  r\   r\   r]   r2     s$    !
c                 C   s   t | d t|rtd dS t }||_d|_|dksB|tjkrXt }|	| g|}nt
||}||_|	| g|}|r~|S |  dS )a  
    Broadcasts the tensor to the whole group.

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

    Args:
        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. If None,
            the default process group will be used.
        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   r1   Nr   )r   r   r   r   rn  ro  r$   r   r   r1   rS   r   )r   rY  r;   rq  ri  r   r]  r[  r\   r\   r]   r1   R  s     

c                 C   sl   t d t|rdS dd | D } t }||_|dkrLt }|| |}n|| |}|r`|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.

    Complex tensors are supported.

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

    Args:
        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. If
            ``None``, the default process group will be used.
        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

    ztorch.distributed.all_reduce_multigpu will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#multi-gpu-collective-functionsNc                 S   s"   g | ]}|  s|nt|qS r\   r  r   view_as_realr   tr\   r\   r]   
<listcomp>  s    z'all_reduce_multigpu.<locals>.<listcomp>)r   r   r   r   rd   r   	allreducer   )rp  r   r;   rq  ri  r   r]  r\   r\   r]   r,   |  s"    #c                 C   s   t | d t|rtd dS |  rHt|s>td| dt| } t }||_	|dkrbt
 }|tj krtt| d|d}tj| | |rt S dS || g|}|r|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.

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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

    Examples:
        >>> # xdoctest: +SKIP("no rank")
        >>> # All tensors below are of torch.int64 type.
        >>> # We have 2 process groups, 2 ranks.
        >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
        >>> tensor
        tensor([1, 2]) # Rank 0
        tensor([3, 4]) # Rank 1
        >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
        >>> tensor
        tensor([4, 6]) # Rank 0
        tensor([4, 6]) # Rank 1

        >>> # All tensors below are of torch.cfloat type.
        >>> # We have 2 process groups, 2 ranks.
        >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j)
        >>> tensor
        tensor([1.+1.j, 2.+2.j]) # Rank 0
        tensor([3.+3.j, 4.+4.j]) # Rank 1
        >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
        >>> tensor
        tensor([4.+4.j, 6.+6.j]) # Rank 0
        tensor([4.+4.j, 6.+6.j]) # Rank 1

    r   r*   Nall_reduce does not support  on complex tensors)r   r   r   r  rR   r   r   rs  r   rd   r   r   r   r  r   r*   r   r^  rw  r   )r   r   r;   rq  ri  collr]  r\   r\   r]   r*     s,    1

c                 C   s   t d t| d t|  t|r0td dS tdd | D rZt|sZtd| dd	d
 | D } t	 }||_
|dkrt }|| |}n|| |}|r| S |  dS )a  
    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.

    Complex tensors are supported.

    Args:
        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 (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        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.

    ztorch.distributed.all_reduce_coalesced will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#collective-functionsr   r+   Nc                 s   s   | ]}|  V  qd S rf   )r  rt  r\   r\   r]   r   6  s     z'all_reduce_coalesced.<locals>.<genexpr>rx  ry  c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv  9  s     z(all_reduce_coalesced.<locals>.<listcomp>)r   r   r  r  r   r   anyrR   r   r   rd   r   rf  
get_futurer   )r  r   r;   rq  ri  r   r]  r\   r\   r]   r+   	  s(    "
c           
      C   s   t d t|rtd dS t }||_||_||_|dksH|tj	kr\t
 }|| |}nt||}	|	|_|| |}|r|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

    Args:
        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. If None,
            the default process group will be used.
        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

    ztorch.distributed.reduce_multigpu will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#multi-gpu-collective-functionsrL   N)r   r   r   r   r   rd   rn  ro  r$   r   r   rK   rS   r   )
rp  rV  r   r;   rq  r   ri  r   r]  rX  r\   r\   r]   rL   H  s&    "
c           	      C   s   t | d t|rtd dS t }||_||_|dksB|tjkrXt }|	| g|}nt
||}||_|	| g|}|r~|S |  dS )a  
    Reduces the tensor data across all machines.

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

    Args:
        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. If None,
            the default process group will be used.
        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   rK   N)r   r   r   r   rd   rn  r$   r   r   rK   rS   r   )	r   rV  r   r;   rq  ri  r   r]  rX  r\   r\   r]   rK     s     

c                 C   sv   t d t|rtd dS dd | D } dd |D }|dkrVt }|| |}n|| |}|rj|S |  dS )ak  
    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

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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

    ztorch.distributed.all_gather_multigpu will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#multi-gpu-collective-functionsr(   Nc                 S   s   g | ]}d d |D qS )c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv    s     z2all_gather_multigpu.<locals>.<listcomp>.<listcomp>r\   r   lr\   r\   r]   rv    s   z'all_gather_multigpu.<locals>.<listcomp>c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv    s    )r   r   r   r   r   	allgatherr   )output_tensor_listsinput_tensor_listr;   rq  r   r]  r\   r\   r]   r(     s&    .c                 C   sT   t  }t||  tj| }t|	|}t
| g	|}||fS rf   )ioBytesIO_picklerdumpr   ZByteStorageZ_from_buffergetvalueZ
ByteTensortoZ
LongTensorZnumel)r  r   fZbyte_storageZbyte_tensor
local_sizer\   r\   r]   _object_to_tensor  s    r  c                 C   s.   |   } |   d | }tt| S rf   )rn   numpytobytes
_unpicklerr  r  load)r   tensor_sizebufr\   r\   r]   _tensor_to_object	  s    r  c                    s  t |rtd dS t|}t||\}}t|d}tj|tj|dfddt|D }t	|||d t
t| | tj| tj|d  fddt|D }t	|||d t|D ]B\}	}
|
tj}
|
jtdkr|
 }
||	 }t|
|| |	< qd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.

    Args:
        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.
        obj (Any): Pickable Python object to be broadcast from current process.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used. Default is ``None``.

    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.

    .. note:: For NCCL-based processed groups, internal tensor representations
        of objects must be moved to the GPU device before communication takes
        place. In this case, the device used is given by
        ``torch.cuda.current_device()`` and it is the user's responsiblity to
        ensure that this is set so that each rank has an individual GPU, via
        ``torch.cuda.set_device()``.

    .. 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.

    .. warning::
        Calling :func:`all_gather_object` with GPU tensors is not well supported
        and inefficient as it incurs GPU -> CPU transfer since tensors would be
        pickled. Please consider using :func:`all_gather` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> # Assumes world_size of 3.
        >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
        >>> output = [None for _ in gather_objects]
        >>> dist.all_gather_object(output, gather_objects[dist.get_rank()])
        >>> output
        ['foo', 12, {1: 2}]
    r)   Nr   r  r   c                    s   g | ]} | j d dqS r   )dimZ	unsqueezer9  object_sizes_tensorr\   r]   rv  S	  s    z%all_gather_object.<locals>.<listcomp>c                    s$   g | ]} | |d    qS r   r\   r9  coalesced_output_tensormax_object_sizer\   r]   rv  _	  s   rn   )r   r   r   r  r:   r   zeroslongr?  r&   r   maxitemresize_emptyuint8	enumerater[   r   rn   r  )object_listr  r;   current_deviceinput_tensorr  rL  object_size_listoutput_tensorsr:  r   r  r\   r  r  r  r]   r)   	  s@    5
  

  c                    s,  t |rtd dS t }t||| t|}t| |\}}t|d}tj|tj	|dfddt
|D }	t|	||d tt|	 | ||krtj| tj|d  fddt
|D }
t|||kr|
nd||d ||krdS t|
D ]*\}}|tj}|	| }t||||< qdS )	a
  
    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.

    Args:
        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. If None,
            the default process group will be used. Default is ``None``.

    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:: For NCCL-based processed groups, internal tensor representations
        of objects must be moved to the GPU device before communication takes
        place. In this case, the device used is given by
        ``torch.cuda.current_device()`` and it is the user's responsiblity to
        ensure that this is set so that each rank has an individual GPU, via
        ``torch.cuda.set_device()``.

    .. 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.

    .. warning::
        Calling :func:`gather_object` with GPU tensors is not well supported
        and inefficient as it incurs GPU -> CPU transfer since tensors would be
        pickled. Please consider using :func:`gather` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> # Assumes world_size of 3.
        >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
        >>> output = [None for _ in gather_objects]
        >>> dist.gather_object(
        ...     gather_objects[dist.get_rank()],
        ...     output if dist.get_rank() == 0 else None,
        ...     dst=0
        ... )
        >>> # On rank 0
        >>> output
        ['foo', 12, {1: 2}]
    r6   Nr   r  c                    s   g | ]} | j d dqS r  r  r9  r  r\   r]   rv  	  s    z!gather_object.<locals>.<listcomp>c                    s$   g | ]} | |d    qS r  r\   r9  r  r\   r]   rv  	  s   )gather_listrV  r;   )r   r   r9   _validate_output_list_for_rankr   r  r:   r   r  r  r?  r&   r   r  r  r  r  r  r5   r  r[   r  )r  Zobject_gather_listrV  r;   my_rankr  r  r  rL  r  r  r:  r   r  r\   r  r]   r6   m	  sP    ;
  

  c                    s<  t |rtd dS |pt| t }||krTt fdd| D  \}}t|}ntjt| tj	 d}t
|||d ||krt|dkr|d }qt|}ntjt| tj d}t
|||d d}	||kr8t|D ]T\}
}||	|	|  }|tj}|jtd	kr | }|	|7 }	t||| |
< qd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.

    Args:
        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. If None,
            the default process group will be used. Default is ``None``.
        device (``torch.device``, optional): If not None, the objects are
            serialized and converted to tensors which are moved to the
            ``device`` before broadcasting. Default is ``None``.

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

    .. note:: For NCCL-based process groups, internal tensor representations
        of objects must be moved to the GPU device before communication takes
        place. In this case, the device used is given by
        ``torch.cuda.current_device()`` and it is the user's responsibility to
        ensure that this is set so that each rank has an individual GPU, via
        ``torch.cuda.set_device()``.

    .. 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:`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.

    .. warning::
        Calling :func:`broadcast_object_list` with GPU tensors is not well supported
        and inefficient as it incurs GPU -> CPU transfer since tensors would be
        pickled. Please consider using :func:`broadcast` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 3.
        >>>     objects = ["foo", 12, {1: 2}] # any picklable object
        >>> else:
        >>>     objects = [None, None, None]
        >>> # Assumes backend is not NCCL
        >>> device = torch.device("cpu")
        >>> dist.broadcast_object_list(objects, src=0, device=device)
        >>> objects
        ['foo', 12, {1: 2}]
    r3   Nc                    s   g | ]}t | qS r\   r  r   r  r  r\   r]   rv  %
  s     z)broadcast_object_list.<locals>.<listcomp>r  rY  r;   r   r   rn   )r   r   r   r9   zipr   catr  r   r  r1   sumr  r  r  r[   r   rn   r  )r  rY  r;   r   r  rp  Z	size_listr  Zobject_tensoroffsetr:  Zobj_sizeZobj_viewr\   r  r]   r3   	  s:    <

c                    s2  t |rtd dS t| tr*t| dk r2tdt }t| ||krtt fdd|D  \}}t|t| }}||krt	|}|D ]}|
| qntjdgtj d}t|||d	 tj| tj d}	t|	||krdn|||d
 tjdgtj d}
t|
||krdn|||d
 t|	|
| d< dS )a
  
    Scatters picklable objects in ``scatter_object_input_list`` to the whole
    group. Similar to :func:`scatter`, but Python objects can be passed in. On
    each rank, the scattered object will be stored as the first element of
    ``scatter_object_output_list``. Note that all objects in
    ``scatter_object_input_list`` must be picklable in order to be scattered.

    Args:
        scatter_object_output_list (List[Any]): Non-empty list whose first
            element will store the object scattered to this rank.
        scatter_object_input_list (List[Any]): List of input objects to scatter.
            Each object must be picklable. Only objects on the ``src`` rank will
            be scattered, and the argument can be ``None`` for non-src ranks.
        src (int): Source rank from which to scatter
            ``scatter_object_input_list``.
        group: (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used. Default is ``None``.

    Returns:
        ``None``. If rank is part of the group, ``scatter_object_output_list``
        will have its first element set to the scattered object for this rank.

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

    .. warning::
        :func:`scatter_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.

    .. warning::
        Calling :func:`scatter_object_list` with GPU tensors is not well supported
        and inefficient as it incurs GPU -> CPU transfer since tensors would be
        pickled. Please consider using :func:`scatter` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 3.
        >>>     objects = ["foo", 12, {1: 2}] # any picklable object
        >>> else:
        >>>     # Can be any list on non-src ranks, elements are not used.
        >>>     objects = [None, None, None]
        >>> output_list = [None]
        >>> dist.scatter_object_list(output_list, objects, src=0)
        >>> # Rank i gets objects[i]. For example, on rank 2:
        >>> output_list
        [{1: 2}]
    rP   Nr   zMExpected argument scatter_object_output_list to be a list of size at least 1.c                    s   g | ]}t | qS r\   r  r  Z	pg_devicer\   r]   rv  
  s     z'scatter_object_list.<locals>.<listcomp>r   r  r  )scatter_listrY  r;   )r   r   rt   r  r   r   r9   r   r  r  r  r   r   r  r1   r  r  r  rO   r  )Zscatter_object_output_listZscatter_object_input_listrY  r;   r  rp  Ztensor_sizesZmax_tensor_sizer   output_tensorZobj_tensor_sizer\   r  r]   rP   I
  sL    9
c                 C   s   t | d t|d t| | t|r2td dS dd | D } | sL|nt|}|dkrvt }|	| g|g}n|	| g|g}|r|S |
  dS )a  
    Gathers tensors from the whole group in a list.

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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

    Examples:
        >>> # xdoctest: +SKIP("need process group init")
        >>> # All tensors below are of torch.int64 dtype.
        >>> # We have 2 process groups, 2 ranks.
        >>> tensor_list = [torch.zeros(2, dtype=torch.int64) for _ in range(2)]
        >>> tensor_list
        [tensor([0, 0]), tensor([0, 0])] # Rank 0 and 1
        >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
        >>> tensor
        tensor([1, 2]) # Rank 0
        tensor([3, 4]) # Rank 1
        >>> dist.all_gather(tensor_list, tensor)
        >>> tensor_list
        [tensor([1, 2]), tensor([3, 4])] # Rank 0
        [tensor([1, 2]), tensor([3, 4])] # Rank 1

        >>> # All tensors below are of torch.cfloat dtype.
        >>> # We have 2 process groups, 2 ranks.
        >>> tensor_list = [torch.zeros(2, dtype=torch.cfloat) for _ in range(2)]
        >>> tensor_list
        [tensor([0.+0.j, 0.+0.j]), tensor([0.+0.j, 0.+0.j])] # Rank 0 and 1
        >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j)
        >>> tensor
        tensor([1.+1.j, 2.+2.j]) # Rank 0
        tensor([3.+3.j, 4.+4.j]) # Rank 1
        >>> dist.all_gather(tensor_list, tensor)
        >>> tensor_list
        [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 0
        [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 1

    rp  r   r&   Nc                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv  
  s    zall_gather.<locals>.<listcomp>)r  r   r  r   r   r  r   rs  r   r  r   )rp  r   r;   rq  r   r]  r\   r\   r]   r&   
  s"    2


c                 C   s   t |d t | d t|r(td dS |  s4| nt| } | sJ|nt|}|p\t }|tj	 krt
t|| }tj| | |rt S dS || |}|r|S |  dS )aH	  
    Gather tensors from all ranks and put them in a single output tensor.

    Args:
        output_tensor (Tensor): Output tensor to accommodate tensor elements
            from all ranks. It must be correctly sized to have one of the
            following forms:
            (i) a concatenation of all the input tensors along the primary
            dimension; for definition of "concatenation", see ``torch.cat()``;
            (ii) a stack of all the input tensors along the primary dimension;
            for definition of "stack", see ``torch.stack()``.
            Examples below may better explain the supported output forms.
        input_tensor (Tensor): Tensor to be gathered from current rank.
            Different from the ``all_gather`` API, the input tensors in this
            API must have the same size across all ranks.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        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

    Examples:
        >>> # xdoctest: +SKIP("need process group init")
        >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
        >>> # We have two ranks.
        >>> device = torch.device(f'cuda:{rank}')
        >>> tensor_in = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
        >>> tensor_in
        tensor([1, 2], device='cuda:0') # Rank 0
        tensor([3, 4], device='cuda:1') # Rank 1
        >>> # Output in concatenation form
        >>> tensor_out = torch.zeros(world_size * 2, dtype=torch.int64, device=device)
        >>> dist.all_gather_into_tensor(tensor_out, tensor_in)
        >>> tensor_out
        tensor([1, 2, 3, 4], device='cuda:0') # Rank 0
        tensor([1, 2, 3, 4], device='cuda:1') # Rank 1
        >>> # Output in stack form
        >>> tensor_out2 = torch.zeros(world_size, 2, dtype=torch.int64, device=device)
        >>> dist.all_gather_into_tensor(tensor_out2, tensor_in)
        >>> tensor_out2
        tensor([[1, 2],
                [3, 4]], device='cuda:0') # Rank 0
        tensor([[1, 2],
                [3, 4]], device='cuda:1') # Rank 1

    .. warning::
        The Gloo backend does not support this API.

    r  r  rW   N)r   r   r   r  r   rs  r   r   r   r  r   rW   r   r^  Z_allgather_baser   )r  r  r;   rq  rz  r]  r\   r\   r]   rW      s0    5


c                 C   s   t d t| |||S )a$  
    Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.

    Args:
        output_tensor (Tensor): Output tensor. It should contain
            correctly-sized tensors to be used for output of the collective.
        input_tensor (Tensor): Tensor to be broadcast from current process.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        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_gather_base` is a private function. Users should use
        `all_gather_into_tensor` instead.

    ztorch.distributed._all_gather_base is a private function and will be deprecated. Please use torch.distributed.all_gather_into_tensor instead.)r   r   rW   )r  r  r;   rq  r\   r\   r]   _all_gather_baseY  s    r  c                 C   s   t d t|rtd dS t|d t| t| tsBtd| D ]}t|d t| qFdd | D } d	d |D }|dkrt	 }|
| |}n|
| |}|r| S |  dS )
a  
    Gathers input tensors from the whole group in a list in a coalesced manner.

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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.
    ztorch.distributed.all_gather_coalesced will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#collective-functionsr'   Nr  z?Invalid function argument: output_tensor_lists should be a listr  c                 S   s   g | ]}d d |D qS )c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv    s     z3all_gather_coalesced.<locals>.<listcomp>.<listcomp>r\   r}  r\   r\   r]   rv    s   z(all_gather_coalesced.<locals>.<listcomp>c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv    s    )r   r   r   r   r  r  rt   r  r   r   Zallgather_coalescedr|  r   )r  r  r;   rq  output_tensor_listr   r]  r\   r\   r]   r'   w  s8    /



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.)rv   )r  rV  r  r\   r\   r]   r    s    r  c                 C   s   t | d |rt|d ng }t| | t|r<td dS t }t||| ||kr\|gng }| g}t }||_|dks|t	j
krt }	|	|||}
nt||}||_||||}
|r|
S |
  dS )a  
    Gathers a list of tensors in a single process.

    Args:
        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. If None,
            the default process group will be used.
        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  r5   N)r   r  r  r   r   r9   r  r   rn  r$   r   r   r5   rS   r   )r   r  rV  r;   rq  r  r  input_tensorsri  r   r]  rX  r\   r\   r]   r5     s.    


c                 C   s  t | d |rt|d ng }t| | t|r<td dS dd |D }|  sV| nt| } t }||kr|szt	d|g}| g}n|rt	dg }| g}t
 }||_|dks|tjkrt }	|	|||}
nt||}||_||||}
|r|
S |
  dS )	ac  
    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.

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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

    .. note:: Note that all Tensors in scatter_list must have the same size.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> tensor_size = 2
        >>> t_ones = torch.ones(tensor_size)
        >>> t_fives = torch.ones(tensor_size) * 5
        >>> output_tensor = torch.zeros(tensor_size)
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 2.
        >>>     # Only tensors, all of which must be the same size.
        >>>     scatter_list = [t_ones, t_fives]
        >>> else:
        >>>     scatter_list = None
        >>> dist.scatter(output_tensor, scatter_list, src=0)
        >>> # Rank i gets scatter_list[i]. For example, on rank 1:
        >>> output_tensor
        tensor([5., 5.])

    r   r  rO   Nc                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv  K  s    zscatter.<locals>.<listcomp>z;Argument ``scatter_list`` must be specified on source rank.zDArgument ``scatter_list`` must NOT be specified on non-source ranks.)r   r  r  r   r   r  r   rs  r9   rv   r   rn  r$   r   r   rO   rS   r   )r   r  rY  r;   rq  r  r  r  ri  r   r]  r[  r\   r\   r]   rO     sJ    -


c                 C   sj   t d t|rtd dS t }||_|dkrHt }|| ||}n|| ||}|r^|S |  dS )a  
    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``.

    Args:
        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. If None,
            the default process group will be used.
        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.

    ztorch.distributed.reduce_scatter_multigpu will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/master/distributed.html#multi-gpu-collective-functionsrN   N)	r   r   r   r   r   rd   r   rM   r   )r  Zinput_tensor_listsr   r;   rq  ri  r   r]  r\   r\   r]   rN   r  s    -c                 C   s   t | d t|d t| | t|r2td dS t }||_|dkr`t }|| g|g|}n|| g|g|}|rz|S |	  dS )a  
    Reduces, then scatters a list of tensors to all processes in a group.

    Args:
        output (Tensor): Output tensor.
        input_list (list[Tensor]): List of tensors to reduce and scatter.
        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. If None,
            the default process group will be used.
        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_listrM   N)
r   r  r  r   r   r   rd   r   rM   r   )r  r  r   r;   rq  ri  r   r]  r\   r\   r]   rM     s    


c                 C   s   t | d t |d t|r(td dS t }||_|p<t }|tj krzt	t
|| |d}tj| | |rvt S dS || ||}|r|S |  dS )a  
    Reduces, then scatters a tensor to all ranks in a group.

    Args:
        output (Tensor): Output tensor. It should have the same size across all
            ranks.
        input (Tensor): Input tensor to be reduced and scattered. Its size
            should be output tensor size times the world size. The input tensor
            can have one of the following shapes:
            (i) a concatenation of the output tensors along the primary
            dimension, or
            (ii) a stack of the output tensors along the primary dimension.
            For definition of "concatenation", see ``torch.cat()``.
            For definition of "stack", see ``torch.stack()``.
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        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.

    Examples:
        >>> # xdoctest: +SKIP("need process group init")
        >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
        >>> # We have two ranks.
        >>> device = torch.device(f'cuda:{rank}')
        >>> tensor_out = torch.zeros(2, dtype=torch.int64, device=device)
        >>> # Input in concatenation form
        >>> tensor_in = torch.arange(world_size * 2, dtype=torch.int64, device=device)
        >>> tensor_in
        tensor([0, 1, 2, 3], device='cuda:0') # Rank 0
        tensor([0, 1, 2, 3], device='cuda:1') # Rank 1
        >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
        >>> tensor_out
        tensor([0, 2], device='cuda:0') # Rank 0
        tensor([4, 6], device='cuda:1') # Rank 1
        >>> # Input in stack form
        >>> tensor_in = torch.reshape(tensor_in, (world_size, 2))
        >>> tensor_in
        tensor([[0, 1],
                [2, 3]], device='cuda:0') # Rank 0
        tensor([[0, 1],
                [2, 3]], device='cuda:1') # Rank 1
        >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
        >>> tensor_out
        tensor([0, 2], device='cuda:0') # Rank 0
        tensor([4, 6], device='cuda:1') # Rank 1

    .. warning::
        The Gloo backend does not support this API.

    r  inputrX   N)r   r   r   r   rd   r   r   r   r  r   rX   r   r^  _reduce_scatter_baser   )r  r  r   r;   rq  ri  rz  r]  r\   r\   r]   rX     s$    7


c                 C   s   t d t| ||||S )a  
    Reduces, then scatters a flattened tensor to all processes in a group.

    Args:
        output (Tensor): Output tensor.
        input (Tensor): Input tensor that is of size output tensor size times world size
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        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::
        `_reduce_scatter_base` is a private function. Users should use
        `reduce_scatter_tensor` instead.

    ztorch.distributed._reduce_scatter_base is a private function and will be deprecated. Please use torch.distributed.reduce_scatter_tensor instead.)r   r   rX   )r  r  r   r;   rq  r\   r\   r]   r  7  s    r  c           	      C   s   t |rtd dS t }t| d t|d t| | | rJt|}|  r\t| } |dkrhg n|}|dkrxg n|}|dkrt }|	| ||||}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.

    Complex tensors are supported.

    Args:
        output (Tensor): Gathered concatenated 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. If None,
            the default process group will be used.
        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:
        >>> # xdoctest: +SKIP("Undefined rank")
        >>> 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


        >>> # Another example with tensors of torch.cfloat type.
        >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
        >>> input
        tensor([1+1j, 2+2j, 3+3j, 4+4j])                                # Rank 0
        tensor([5+5j, 6+6j, 7+7j, 8+8j])                                # Rank 1
        tensor([9+9j, 10+10j, 11+11j, 12+12j])                          # Rank 2
        tensor([13+13j, 14+14j, 15+15j, 16+16j])                        # Rank 3
        >>> output = torch.empty([4], dtype=torch.int64)
        >>> dist.all_to_all_single(output, input)
        >>> output
        tensor([1+1j, 5+5j, 9+9j, 13+13j])                              # Rank 0
        tensor([2+2j, 6+6j, 10+10j, 14+14j])                            # Rank 1
        tensor([3+3j, 7+7j, 11+11j, 15+15j])                            # Rank 2
        tensor([4+4j, 8+8j, 12+12j, 16+16j])                            # Rank 3
    r.   Nr  r  )r   r   r   r   r  r  r   rs  r   Zalltoall_baser   )	r  r  Zoutput_split_sizesZinput_split_sizesr;   rq  ri  r   r]  r\   r\   r]   r.   S  s@    b




        c                 C   s   t |rtd dS t }t| d t|d t| | dd |D }dd | D } |dkrrt }|| ||}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.

    Complex tensors are supported.

    Args:
        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. If None,
            the default process group will be used.
        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:
        >>> # xdoctest: +SKIP("Undefined rank")
        >>> 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

        >>> # Another example with tensors of torch.cfloat type.
        >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
        >>> input = list(input.chunk(4))
        >>> input
        [tensor([1+1j]), tensor([2+2j]), tensor([3+3j]), tensor([4+4j])]            # Rank 0
        [tensor([5+5j]), tensor([6+6j]), tensor([7+7j]), tensor([8+8j])]            # Rank 1
        [tensor([9+9j]), tensor([10+10j]), tensor([11+11j]), tensor([12+12j])]      # Rank 2
        [tensor([13+13j]), tensor([14+14j]), tensor([15+15j]), tensor([16+16j])]    # Rank 3
        >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
        >>> dist.all_to_all(output, input)
        >>> output
        [tensor([1+1j]), tensor([5+5j]), tensor([9+9j]), tensor([13+13j])]          # Rank 0
        [tensor([2+2j]), tensor([6+6j]), tensor([10+10j]), tensor([14+14j])]        # Rank 1
        [tensor([3+3j]), tensor([7+7j]), tensor([11+11j]), tensor([15+15j])]        # Rank 2
        [tensor([4+4j]), tensor([8+8j]), tensor([12+12j]), tensor([16+16j])]        # Rank 3

    r-   Nr  r  c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv  ;  s    zall_to_all.<locals>.<listcomp>c                 S   s"   g | ]}|  s|nt|qS r\   rr  rt  r\   r\   r]   rv  >  s    )r   r   r   r  r  r   Zalltoallr   )r  r  r;   rq  ri  r   r]  r\   r\   r]   r-     s(    \


c                 C   s   t | rtd dS t }t| |_|dk	rFt|tr>||_ntd| dkrbt	 }|j
|d}n| j
|d}|rv|S |  dS )aR  
    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().

    Args:
        group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
        async_op (bool, optional): Whether this op should be an async op
        device_ids ([int], optional): List of device/GPU ids.

    Returns:
        Async work handle, if async_op is set to True.
        None, if not async_op or if not part of the group
    r/   Nz>Invalid function argument: device_ids type should be List[int])ri  )r   r   r   r   r   rt   r  
device_idsr   r   r/   r   )r;   rq  r  ri  r   r]  r\   r\   r]   r/   M  s$    

c                 C   sV   t | rtd dS t| tjkr*td|dkr6t}| dkrDt n| }|j||dS )a	  
    Synchronizes all processes similar to ``torch.distributed.barrier``, but takes
    a configurable timeout and is able to report ranks that did not pass this
    barrier within that timeout. Specifically, for non-zero ranks, will block
    until a send/recv is processed from rank 0. Rank 0 will block until all send
    /recv from other ranks are processed, and will report failures for ranks
    that failed to respond in time. Note that if one rank does not reach the
    monitored_barrier (for example due to a hang), all other ranks would fail
    in monitored_barrier.

    This collective will block all processes/ranks in the group, until the
    whole group exits the function successfully, making it useful for debugging
    and synchronizing. However, it can have a performance impact and should only
    be used for debugging or scenarios that require full synchronization points
    on the host-side. For debugging purposes, this barrier can be inserted
    before the application's collective calls to check if any ranks are
    desynchronized.

    .. note:: Note that this collective is only supported with the GLOO backend.

    Args:
        group (ProcessGroup, optional): The process group to work on. If
            ``None``, the default process group will be used.
        timeout (datetime.timedelta, optional): Timeout for monitored_barrier.
            If ``None``, the default process group timeout will be used.
        wait_all_ranks (bool, optional): Whether to collect all failed ranks or
            not. By default, this is ``False`` and ``monitored_barrier`` on rank 0
            will throw on the first failed rank it encounters in order to fail
            fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will
            collect all failed ranks and throw an error containing information
            about all failed ranks.

    Returns:
        ``None``.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> if dist.get_rank() != 1:
        >>>     dist.monitored_barrier() # Raises exception indicating that
        >>> # rank 1 did not call into monitored_barrier.
        >>> # Example with wait_all_ranks=True
        >>> if dist.get_rank() == 0:
        >>>     dist.monitored_barrier(wait_all_ranks=True) # Raises exception
        >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into
        >>> # monitored_barrier.
    rF   Nz7monitored_barrier is only implemented for GLOO backend.)wait_all_ranks)	r   r   r8   r"   r   r   r   r   rF   )r;   r   r  Zgroup_to_user\   r\   r]   rF   z  s    4rB  c                 C   s6   t  d| }t||}t||||d}t| |} | S )Nr   r8  )PG_WRAPPER_STORE_PREFIXr   ra   rb   )rC  rD  r   r   r   r   prefixZ	helper_pgr\   r\   r]   rO    s
    	

rO  c                 C   sj   |rNt tdtt| d }|tj	 krft t|d d }q$nttj
}t j
d7  _
|S )Nr+  zutf-8r   )hashlibsha1bytesr   r  ru   	hexdigestr   r   rG  r   )r   r7  Zpg_namer\   r\   r]   r<    s     
r<  c                 C   s   | st t } t| S rf   )r8   r   r"   r   r\   r\   r]   _get_backend_from_str  s    
r  c                 C   s   t | |||d|d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.

    .. warning::
        Using multiple process groups with the ``NCCL`` backend concurrently
        is not safe and the user should perform explicit synchronization in
        their application to ensure only one process group is used at a time.
        This means collectives from one process group should have completed
        execution on the device (not just enqueued since CUDA execution is
        async) before collectives from another process group are enqueued.
        See `Using multiple NCCL communicators concurrently <https://docs.nvid
        ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
        -multiple-nccl-communicators-concurrently>`_ for more details.

    Args:
        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 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 very 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 running on corrupted
            data. Only one of these two environment variables should be set.
        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``). If ``None`` is passed in, the backend
            corresponding to the default process group will be used. Default is
            ``None``.
        pg_options (ProcessGroupOptions, optional): process group options
            specifying what additional options need to be passed in during
            the construction of specific process groups. i.e. for the ``nccl``
            backend, ``is_high_priority_stream`` can be specified so that
            process group can pick up high priority cuda streams.
        use_local_synchronization (bool, optional): perform a group-local
            barrier at the end of the process group creation. This is different
            in that non-member ranks don't need to call into API and don't
            join the barrier.

    Returns:
        A handle of distributed group that can be given to collective calls or None if the rank is not part of ``ranks``.

    N.B. use_local_synchronization doesn't work with MPI.

    N.B. While use_local_synchronization=True can be significantly faster with larger
    clusters and small process groups, care must be taken since it changes cluster behavior
    as non-member ranks don't join the group barrier().

    N.B. use_local_synchronization=True can lead to deadlocks when each rank creates
    multiple overlaping process groups. To avoid that, make sure all ranks follow the
    same global creation order.
    N)use_local_synchronization)_new_group_with_tag)r   r   r   r4  r  r\   r\   r]   rG     s    Ic                 C   sz  t  }tj| \}}| }	| }
|s,|}t|}|r`|tjkrJtd| dk	r`t | kr`dS | dk	rt	| } t
| }||
krtd| D ]}|dk s||
krtdq|	| kr| |	}qd}ntt|
} |
}|	}t| |d}t||| ||||||d	\}}dd	 t| D tj|< t d
krvtd |tjkrDt  n2|rN|n|}|r`t
| nt }t|	|||| |S )z
    This is a variant of ``new_group`` that exposes tag creation.

    :: N.B. The mechanism is experimental and tied to the functional collectives effort, see
    ``torch.distributed._functional_collectives`` for reference on how to use it.
    z:MPI backend doesn't support use_local_synchronization=TrueNz^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_groupr6  )r   r4  r   rQ  c                 S   s   i | ]\}}||qS r\   r\   )r   r  r   r\   r\   r]   r   u  s     z'_new_group_with_tag.<locals>.<dictcomp>r   r;  )r   r   r   r   r	  r"   r   r   r9   sortedr   indexr  r?  r<  r=  r  r   r)  r   r   r/   r:   r   )r   r   r   r4  rQ  r  r   Zdefault_backendr,  r   Zglobal_world_sizeZgroup_world_sizer   r  r   r   r1  Zbarrier_storer   r\   r\   r]   r  +  sn    

	r  c                 C   s   | dkr$t j stdt j } | dkr<td|  dt }|| k r`td|  d| d||  dkrttdg }d}t||  D ]\}||  }	|	|  }
tt|	|
}t||||d	}|	| t
 }||kr|}td
|| q||fS )a  
    Creates subgroups of equal size. By default, it creates intra-machine subgroups,
    where each of which contains all the ranks of a machine, based on the assumption
    that each machine has the same number of devices.

    This is a convenience API that calls ``new_group`` to generate multiple subgroups.
    It 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.

    .. warning::
        If ``group_size`` is passed in, the world size must be divisible by ``group_size``.
        If no ``group_size`` is passed in, it believe that you are creating a group based
        on CUDA and determining the group size by number of CUDA devices, and if not all
        the machines have the same number of devices, the subgroup division will be
        different across nodes and can cause unexpected behaviors. Therefore, if you are
        creating a subgroup that does not depend on CUDA (such as Gloo on CPU), please
        pass in ``group_size`` correctly.

    .. warning::
        Using multiple process groups with the ``NCCL`` backend concurrently
        is not safe and the user should perform explicit synchronization in
        their application to ensure only one process group is used at a time.
        This means collectives from one process group should have completed
        execution on the device (not just enqueued since CUDA execution is
        async) before collectives from another process group are enqueued.
        See `Using multiple NCCL communicators concurrently <https://docs.nvid
        ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
        -multiple-nccl-communicators-concurrently>`_ for more details.

    Args:
        group_size (int, optional): The size of each subgroup. If ``None``,
            the default subgroup size is equal to the number of devices on each machine,
            based on the assumption that each machine has exactly the same
            number of devices. Default is ``None``.
        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 very 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 running on corrupted
            data. Only one of these two environment variables should be set.
        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``). If ``None`` is passed in, the backend
            corresponding to the default process group will be used. Default is
            ``None``.
        pg_options (ProcessGroupOptions, optional): process group options
            specifying what additional options need to be passed in during
            the construction of specific process groups. i.e. for the ``nccl``
            backend, ``is_high_priority_stream`` can be specified so that
            process group can pick up high priority cuda streams.

    Returns:
        The subgroup containing the current rank, and all the subgroups used for cleanup.

    Examples:
        >>> # Create intra-machine subgroups.
        >>> # xdoctest: +SKIP("need process group init")
        >>> cur_subgroup, subgroups = dist.new_subgroups()
        >>> # Allreduce within the machine.
        >>> rank = dist.get_rank()
        >>> tensor = torch.ones(1, device=rank) * rank
        >>> dist.all_reduce(tensor, group=cur_subgroup)
        >>> tensor
        tensor([8])     # Assume 8 is the number of CUDA devices per machine.
        >>> # Cleanup.
        >>> for subgroup in subgroups:
        >>>     dist.destroy_process_group(subgroup)
    NzDefault group size only takes effect when CUDA is available.If your subgroup using a backend that does not depend on CUDA,please pass in 'group_size' correctly.r   zThe arg 'group_size' (z) must be positivez") must not exceed the world size ()z0The world size must be divisible by 'group_size'r   r   r   r4  "Rank %s is assigned to subgroup %s)r   ro   Zis_availablerv   Zdevice_countr:   r?  r  rG   r   r9   r   r   )rL  r;   r   r   r4  r   	subgroupscur_subgroupZsubgroup_idZ
start_rankZend_rankZranks_in_subgroupsubgroupr   r\   r\   r]   rH     sB    [


 c              	   C   s   | dkst | dkrtdg }d}i }| D ]v}t||||d}|| t }	|D ]L}
|
|kr~td|
 d||
  d| |||
< |	|
krT|}td|
| qTq,||fS )	a[  
    Creates subgroups by dividing the global world, where the division is specified by
    a nested list of ranks. The subgroups cannot have overlap, and some ranks may not have
    to be in any subgroup.

    This is a convenience API that calls ``new_group`` to generate multiple subgroups.
    It 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.

    .. warning::
        Using multiple process groups with the ``NCCL`` backend concurrently
        is not safe and the user should perform explicit synchronization in
        their application to ensure only one process group is used at a time.
        This means collectives from one process group should have completed
        execution on the device (not just enqueued since CUDA execution is
        async) before collectives from another process group are enqueued.
        See `Using multiple NCCL communicators concurrently <https://docs.nvid
        ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
        -multiple-nccl-communicators-concurrently>`_ for more details.

    Args:
        ranks_per_subgroup_list (list[list[int]]): A nested list of ranks of
            group members.
        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 very 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 running on corrupted
            data. Only one of these two environment variables should be set.
         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``). If ``None`` is passed in, the backend
             corresponding to the default process group will be used. Default is
             ``None``.
        pg_options (ProcessGroupOptions, optional): process group options
            specifying what additional options need to be passed in during
            the construction of specific process groups. i.e. for the ``nccl``
            backend, ``is_high_priority_stream`` can be specified so that
            process group can pick up high priority cuda streams.

    Returns:
        The subgroup containing the current rank, and all the subgroups used for cleanup.

    Examples:
        >>> # Create two subgroups, where each has 2 processes.
        >>> # xdoctest: +SKIP("need process group init")
        >>> cur_subgroup, subgroups = dist.new_subgroups(ranks=[[0, 2], [1, 3]])
        >>> rank = dist.get_rank()
        >>> tensor = torch.ones(1, device=rank) * rank
        >>> dist.all_reduce(tensor, group=cur_subgroup)
        >>> tensor
        tensor([2])     # Subgroup 0: ranks 0 and 2
        tensor([4])     # Subgroup 1: ranks 1 and 3
    Nr   z1The arg 'ranks_per_subgroup_list' cannot be emptyr  zRank z has appeared in both subgroup z and r  )r   rv   rG   r   r9   r   r   )Zranks_per_subgroup_listr   r   r4  r  r  Zrank_to_ranks_dictr   r  r  r   r\   r\   r]   rI     s0    L
)r   r   re   c                    s~   t | dkr*| ds*| ds*d|  } tj| g D ]@}| t |krNq8t| t fdd|D }|r8|  S q8d S )Nr   rE  rF  c                 3   s   | ]}| kV  qd S rf   r\   )r   rr  r\   r]   r     s     z,_find_pg_by_ranks_and_tag.<locals>.<genexpr>)r   rT  r   r   r0  r	  rU   r  )r   r   r;   Zgoodr\   r  r]   rH    s     

rH  )r   r   stridere   c                 C   s   t || dks*tdt | d| dt }d }|t |krZ| }||kstdnBtdt ||D ] }||||  }||krj|}qj|d k	std|  t| |}|d k	r|S | dkrtdt|| dS )	Nr   zRanks length (z) must be divisible by stride (r  z(rankset doesn't include the current noder2  z-Cannot automatically create PG with empty tag)rQ  )	r   r   r9   copyr?  sortrH  rv   r  )r   r   r  r  Zmy_ranksr:  Zrank_setr   r\   r\   r]   #_find_or_create_pg_by_ranks_and_tag  s$    *
r  )r   re   c                 C   s$   t j|  }|dr |dd }|S )z1
    Returns the tag associated with ``pg``.
    rF     N)r   r   rT  )r   r   r\   r\   r]   _get_group_tag  s    

r  c                 C   s
   t j|  S rf   )r   r   r   r\   r\   r]   _get_process_group_name  s    r  )N)N)N)N)N)N)Nr   )NNr   )Nr   )NNr   )NNF)NFr   )NF)NF)N)Nr   N)r   NN)r   N)NF)NF)NF)NF)Nr   NF)Nr   NF)NNNF)NF)N)r  collections.abccollections
contextlibr  r  loggingr&  pickler   r   r   datetimer   typingr   r   r   r   r   r	   r
   r   Ztorch._C._distributed_c10dr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   	constantsr   Zc10d_loggerr   r   r!   r    __all__r   r!  r"  r#  Picklerr  	Unpicklerr  r^   r_   rZ   ImportErrorr`   ra   rb   rc   	getLoggerr   r   r  boolrR   r"   r#   r   rV   r%   r   r   ru   r   r   r   r   r   r   r   r   r   r   r[   r   r;   r$   r@  r   r   r   r   r   rS   rT   r  rU   r  r   r  abcIterabler  r  r   r  r@   rB   r>   rD   rA   r?   rC   r)  r   r-  r.  r7   r8   r<   r=  r4   r9   r:   r   rE   r=   rQ   rJ   r^  ra  contextmanagerr   rl  r0   r2   r1   ZSUMr,   r*   r+   rL   rK   r(   r  r  r)   r6   r3   rP   r&   rW   r  r'   r  r5   rO   rN   rM   rX   r  r.   r-   r   r/   rF   rO  r<  r  rG   r  rH   rI   rH  r  r  r  Z'dynamo_unsupported_distributed_c10d_opsr\   r\   r\   r]   <module>   s   $L                                                     





xB" zC/	


 @
 7P $$'"&,  X;;)<O>   =,  K[mm  lIX  V6_  E)T    v,HK
i
 
i	