o
    hg@                    @   sN  U d 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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 ddlmZ ddlZddlm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.m/Z/m0Z0m1Z1m2Z2m3Z3 dd	l4m5Z5 dd
l6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z>m?Z? ddl@mAZAmBZB ddlCmDZDmCZC g dZEdZFdZGdZHdZIdZJe
jKZLe
jMZNdAddZOeO  zddlmPZP deP_QeEdg7 ZEW n eRy   dZFY nw zddlmSZS deS_QeEdg7 ZEW n eRy   dZGY nw zddlmTZTmUZU deU_QeEdg7 ZEW n eRy3   dZHY nw zddlmVZV deV_QeEdg7 ZEW n eRyP   dZIY nw zdd lmWZW deW_QeEd!g7 ZEW n eRym   dZJY nw eXeYZZd"Z[d#e.de\fd$d%Z]G d&d' d'e^Z_G d(d) d)Z`G d*d+ d+Zaea ZbG d,d- d-ZcG d.d/ d/Zdi aeefe-ege^e2f f ehd0< i aiefe-e^f ehd1< i ajefe-efekekf f ehd2< i alefe-e^f ehd3< dami anefe^eoe- f ehd4< i apefe-e^f ehd5< daqee^ ehd6< G d7d8 d8Zrer as	 G d9d: d:etZuG d;d< d<eud=ZvG d>d? d?eud=Zwd@e_defdAdBZxdCeddfdDdEZydazee^ ehdF< dGZ{dBd<ee- de^fdHdIZ|dBd<ee- dej}fdJdKZ~dBd<ee- deoe^ fdLdMZe?edNdOf	dAdPdQZd<ee- de\fdRdSZdAdTdUZd<e-dVekdekfdWdXZd<e-dYekdekfdZd[Zed\ed]dekfd^d_Zd<e-deoek fd`daZdekfdbdcZdde^dekfdedfZdgeoek dhe^de^fdidjZdAdkdlZdAdmdnZdBd<ee- de-fdodpZ			dCd<e-dVeek dYeek dqe\dekf
drdsZd<e-dtekdue^fdvdwZdejjfdxdyZdAdzd{ZdAd|d}ZdAd~dZde\fddZde\fddZde\fddZde\fddZde\fddZd@e^de\fddZde\fddZde\fddZdekfddZde-fddZde2fddZdAddZdBd<ee- de^fddZdBd<ee- de_fddZdee^ej}f de^fddZde-dekfddZdBd<ee- defe^ef fddZdeoefe^ef  fddZdekfddZdBdeek dekfddZdCeddfddZdBdCed<ee- ddfddZe>e?									dDd@ee^ dee^ dCee dekdtekdee2 dde^dee deej} ddfddZdd Z					dEddZdBd<ee- fddZdBd<ee- fddZdBd<ee- dekfddZdBd<ee- dekfddÄZ				dFdejdeek d<ee- dhekdeek dee3 fddȄZ				dFdejdeek d<ee- dhekdeek dee3 fdd̄Ze>				dFdejdeek d<ee- dhekdeek ddfdd΄Ze>				dFdejdeek d<ee- dhekdeek dekfddЄZG dd҄ de3ZG ddԄ dԃZej			dCd<ee- deej} dee\ fddׄZdeoec deoe3 fddڄZe>				dGdejdeek d<ee- de\deek f
dd݄Ze>e.jddfdd߄Ze>eded]e.jddfddZe>de.jdddfdejdeek d<ee- de\deek f
ddZdd Zdd Ze>dBddZe>				dHdedeeoe  deek d<ee- deek f
ddZe>				dHdeoe deek d<ee- deej} deek f
ddZe>				dHdeoe deek d<ee- deej} deek f
ddZe>				dHdeoe deek d<ee- deej} deek f
ddZe>				dHdeoe deeoe  deek d<ee- deek f
ddZe>dIddZe>dIddZe>eded]dIdd Ze>eded]	dIddZ͐dd Ze>					dJdejdeeoej  deek d<ee- de\deek fddZe>					dJdejd	eeoej  deek d<ee- de\deek fd
dZe>e.jddfddZe>e.jddfddZeded]e.jddfddZe>				dKddZe>dIddZe>ewjddfd<ee- fddZewjddfd<ee- fddZeBfdejjj_de^de2dtekdekdCefddZdgeoek de^fdd Zdgeoek dekfd!d"Zݐd#d$ ZސdBd@ee^ de_fd%d&Zde\fd'd(Ze?					dEd)ee- d*eeo dCee dee d+ee^ dee- fd,d-Ze?							dLdeej} fd.d/Z								dMdeej} fd0d1Z						dNd2d3Z				dHd4d5Zdhe^dgeoek dee- fd6d7Zdhe^dgeoek d8ekde-fd9d:Zde-de^fd;d<Zde-de^fd=d>Zde-de2fd?d@ZdS (O  z,Distributed Collective Communication (c10d).    N)
namedtuple)	timedelta)AnyCallableOptionalTYPE_CHECKINGUnion)
deprecated)_DistStoreError)_DistributedBackendOptions_register_process_group_resolve_process_group_unregister_all_process_groups_unregister_process_groupAllgatherOptionsAllreduceCoalescedOptionsAllreduceOptionsAllToAllOptionsBarrierOptionsBroadcastOptions
DebugLevelGatherOptionsget_debug_levelPrefixStoreProcessGroupReduceOpReduceOptionsReduceScatterOptionsScatterOptionsStoreWork)+set_pytorch_distributed_envs_from_justknobs)_WaitCounter)handle_torch_functionhas_torch_function)not_none   )_exception_logger_time_logger)default_pg_nccl_timeoutdefault_pg_timeout)register_rendezvous_handler
rendezvous)JBackendBackendConfigGroupMemberP2POp
all_gatherall_gather_coalescedall_gather_object
all_reduceall_reduce_coalesced
all_to_allall_to_all_singlebarrierbatch_isend_irecv	broadcastsend_object_listrecv_object_listbroadcast_object_listdestroy_process_groupgathergather_objectget_backend_configget_backendget_default_backend_for_deviceget_rankget_world_sizeget_pg_count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is_xccl_availableisendmonitored_barrier	new_groupnew_subgroupsnew_subgroups_by_enumerationrecvreducereduce_scatter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_tensorget_node_local_ranksplit_groupTreturnc                  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__)_public_types_to_change_moduletype rk   v/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/distributed/distributed_c10d.py_export_c_types   s(   rm   )ProcessGroupMPIrg   rn   F)ProcessGroupNCCLro   )_ProcessGroupWrapperProcessGroupGloorq   )ProcessGroupUCCrr   )ProcessGroupXCCLrs   
pg_wrapperreduceOpc                 C   s$   t jt jt jt jt jt jg}| |vS )z8Return true if reduce ops is supported. False otherwise.)r   MAXMINPRODUCTBANDBORBXOR)ru   denyListrk   rk   rl   r]      s   r]   c                   @   s4  e Zd ZU dZ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egZeee	dZeeef ed< eddgedge	dgeddged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	eejjeejjiZeeejf ed< defddZe		ddeeeee f  ddfddZdS )r-   a  
    An enum-like class for backends.

    Available backends: GLOO, NCCL, UCC, MPI, XCCL, 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.
    	undefinedgloonccluccmpixccl_BackendPlugin
creator_fnextended_api_pluginscpucudaxpudefault_device_backend_mapr   r   r   backend_capabilitybackend_type_mapnamec                 C   s:   t |ts	tdtt| tj}|tjkr| }|S ).Create and return a new instance of the class.z0Backend constructor parameter must be string-ish)
isinstancestr
ValueErrorgetattrr-   upper	UNDEFINEDlower)clsr   valuerk   rk   rl   __new__$  s   

zBackend.__new__FNdevicesrf   c                 C   s   t t| stt| |  | tjvr tj|  |dur8|D ]}|dkr7|dkr7| tj|< q&tj	j
tj| < |du rXtd| d ddgtj| < nt|trf|gtj| < n|tj| < t||tj| < dS )au  
        Register 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.

        Nr   r   Device capability of zl unspecified, assuming `cpu` and `cuda`. Please specify it via the `devices` argument of `register_backend`.)hasattrr-   r   setattrr   backend_listappendr   r   BackendTypeCUSTOMr   warningswarnr   r   r   r   r   )r   r   funcr   r   devicerk   rk   rl   register_backend.  s&   !

zBackend.register_backend)FN)__name__rh   __qualname____doc__r   GLOONCCLUCCMPIXCCLr   r   r   dictr   __annotations__r   r   r   listr   r   r   r   classmethodr   r   r   rk   rk   rk   rl   r-      sJ   
 		
r-   c                   @   s<   e Zd ZdZdefddZdd Zdeeef fdd	Z	d
S )r.   zBackend configuration class.backendc           
      C   sb  i | _ t|}|tjkr1tj j}ztj| }t|| j |< W n t	y0   t
d| ddw | tjv rKtj|  }t|}t||| _ n]d| v rd| d}| dD ]4}|d}t|dkrut
d	| d
| |\}	}|	| j v rt
d|	 d| d
| t|| j |	< q^ntd| d t|}|||d| _ td| j  dS )Init.zWe detected accelerator z on your machine. But we don't know which communication backend to use for this accelerator. Please specify the `backend` argument in the `init_process_group` call.N: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.r   zUsing backend config: %s)device_backend_mapr   r-   r   torch_C_get_acceleratorrj   r   KeyErrorr   r   r   r   r   fromkeyssplitlenr   r   loggerinfo)
selfr   device_typebackend_strsupported_devicesbackend_valbackend_str_error_messagedevice_backend_pair_strdevice_backend_pairr   rk   rk   rl   __init__p  sd   





zBackendConfig.__init__c                 C   s   d dd | j D S )z8Return all the device:backend pairs separated by commas.r   c                 s   s"    | ]\}}| d | V  qdS )r   Nrk   ).0r   r   rk   rk   rl   	<genexpr>  s    
z)BackendConfig.__repr__.<locals>.<genexpr>)joinr   itemsr   rk   rk   rl   __repr__  s   
zBackendConfig.__repr__rf   c                 C      | j S )z!Return backend map of the device.)r   r   rk   rk   rl   get_device_backend_map     z$BackendConfig.get_device_backend_mapN)
r   rh   r   r   r-   r   r   r   r   r   rk   rk   rk   rl   r.   m  s
    Br.   c                   @   s.   e Zd ZdZd
ddZeded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.
    rf   Nc                 C   s0   t jj D ]
\}}t| || qt jj| _d S N)r   	RedOpType__members__r   r   )r   kvrk   rk   rl   r     s   z_reduce_op.__init__z\`torch.distributed.reduce_op` is deprecated, please use `torch.distributed.ReduceOp` insteadcategoryc                 C   s   t | |S r   )object__getattribute__)r   keyrk   rk   rl   r     s   z_reduce_op.__getattribute__rf   N)r   rh   r   r   r   r	   FutureWarningr   rk   rk   rk   rl   r     s    
r   c                       s   e Zd ZdZ				ddedejdee dee	 ded	ee fd
dZ
				ddedejdee dee	 ded	ee fddZ fddZ  ZS )r0   ac  
    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, optional): 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.
        group_peer (int, optional): Destination or source rank.
    Nr   optensorpeerrG   tag
group_peerc                 C   sD   || _ || _t|| _t| j||dd| _|| _t| j||| _dS )r   Treturn_globalN)r   r   _group_or_default_grouprG   _canonicalize_group_rankr   r   r   )r   r   r   r   rG   r   r   rk   rk   rl   r     s   


zP2POp.__init__c                 C   s   t | t|d t| S )r   r   )	_check_op_check_single_tensorr   r   )r   r   r   r   rG   r   r   rk   rk   rl   r     s   


zP2POp.__new__c                    s   t | j}| jj}| jr| jjnd}d|v r|}| j}nd|v r&| j}|}nt  S d| d| d| d| d| jj	 d	| jj
 d
S )N
default_pgr\   rW   zP2POp(z pg=z, group_src=z, group_dst=z,  z, ))rD   rG   r   r   
group_namer   superr   r   shapedtype)r   my_group_rankop_namer   sd	__class__rk   rl   r     s   

2zP2POp.__repr__NNr   N)r   rh   r   r   r   r   Tensorr   intr   r   r   r   __classcell__rk   rk   r   rl   r0     sJ    

r0   c                   @   sF   e Zd ZdZ			d
dedejdeej dee dee	 f
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.
    Nr   r   
dst_tensorredoprootc                 C   s"   || _ || _|| _|| _|| _d S r   )r   r   r   r   r   )r   r   r   r   r   r   rk   rk   rl   r   *  s
   
z_CollOp.__init__)NNN)r   rh   r   r   r   r   r   r   r   r   r   rk   rk   rk   rl   r     s     r   _pg_map	_pg_names_pg_group_ranks_pg_backend_config_tags_to_pg
_pg_to_tag_backendc                   @   sV  e Zd ZdZdddZedee fddZej	dddZede
eeeef f fd	d
Zede
eef fddZede
ee
eef f fddZede
eef fddZedefddZej	deddfddZede
eee f fddZede
eef fddZede
eee f fddZedee
eef  f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..
    rf   Nc                 C   s   d | _ i | _d S r   )_default_pg_pg_coalesce_stater   rk   rk   rl   r   P  s   
z_World.__init__c                 C   r   )z
        Process group that includes all ranks of the cluster.

        This default ProcessGroup is used by c10d APIs when a ProcessGroup is needed
        but None is provided.
        r  r   rk   rk   rl   r   T  s   z_World.default_pgc                 C   s
   || _ d S r   r
  r   r   rk   rk   rl   r   ^     
c                 C      t S )a   
        Provide Mapping from ProcessGroup to backend name and store.

        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   rk   rk   rl   pg_mapb  s   z_World.pg_mapc                 C   r  )z
        Process group's names, map from ProcessGroup to str.

        TODO don't expose the map, expose fine grained ops
        )r  r   rk   rk   rl   pg_nameso     z_World.pg_namesc                 C   r  )z
        Process group's global rank to local rank mapping.

        TODO don't expose the map, expose fine grained ops
        )r  r   rk   rk   rl   pg_group_ranksy  r  z_World.pg_group_ranksc                 C   r  )zm
        Process group's backend config.

        TODO don't expose the map, expose fine grained ops
        )r  r   rk   rk   rl   pg_backend_config  r  z_World.pg_backend_configc                 C   r  )z|
        Process group count for default naming.

        TODO don't expose group_count, use something else instead
        _group_countr   rk   rk   rl   group_count  r  z_World.group_countr   c                 C   s   |a dS )zKUse to compute the name of ProcessGroups when using global synchronization.Nr  r  rk   rk   rl   r    s   c                 C   r  r   )r  r   rk   rk   rl   
tags_to_pg     z_World.tags_to_pgc                 C   r  r   )r  r   rk   rk   rl   	pg_to_tag  r  z_World.pg_to_tagc                 C   r   r   )r	  r   rk   rk   rl   pg_coalesce_state  r   z_World.pg_coalesce_statec              
   C   sn   g }t d}| j D ])}| j| }|| j| |j| j| t||kr*t	| ng t|| j
d q|S )z
        Return a list of dict with process groups and backends.

        Along with their unique IDs and configurations (types and ranks).
        N)pg_namepg_descbackend_configranks
group_sizer  )_get_group_sizer  keysr  r   r  
group_descr  r   r   r  )r   config_infodefault_pg_sizepgr  rk   rk   rl   pg_config_info  s   
z_World.pg_config_infor   )r   rh   r   r   r   propertyr   r   r   setterr   tupler   r   r  r  r   r  r  r  r   r  r  r   r  r   r%  rk   rk   rk   rl   r  F  s6    
		 	 			 r  c                   @   s>   e Zd ZdZedee fddZejdee fddZdS )
_WorldMetazm
    Meta class of ``group`` and ``GroupMember``.

    Allows them to have the class property ``WORLD``.
    rf   c                 C      t jS r   _worldr   )r   rk   rk   rl   WORLD  r   z_WorldMeta.WORLDr$  c                 C   s
   |t _d S r   r+  )r   r$  rk   rk   rl   r-    r  N)	r   rh   r   r   r&  r   r   r-  r'  rk   rk   rk   rl   r)    s    r)  c                   @   s   e Zd ZdZdS )rG   zGroup class. Placeholder.N)r   rh   r   r   rk   rk   rk   rl   rG     s    rG   )	metaclassc                   @   s   e Zd ZdZdZdS )r/   zGroup member class.iN)r   rh   r   r   NON_GROUP_MEMBERrk   rk   rk   rl   r/     s    r/   r   c                 C   s*   | t jkrtttstd tS tS tS )NzSAttempted to get default timeout for nccl backend, but NCCL support is not compiled)r-   r   r   r)   r   r   r   r*   r   rk   rk   rl   _get_default_timeout  s   

r1  timeoutc                 C   s   t | tstd|  d S )Nz@Expected timeout argument to be of type datetime.timedelta, got )r   r   	TypeErrorr2  rk   rk   rl   _check_valid_timeout  s
   
r5  _default_pg_init_methodstore_based_barrier_keyc                 C   s   | pt  } t| ts&tdt|  d t| trdS tdt|  d	 | j}t	|dkr5|d jS t	|dkr=dS t
d|v rFdS |d jS )aB  
    .. note:: This is an internal helper and does not have backward
        compatibility, please use with caution.

    Return the device type to use with ``group`` for object collectives or
    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:
        str: The device type to use for object collective with ``group``.

    You are using a Backend w as a ProcessGroup. This usage is deprecated since PyTorch 2.0. Please use a public API of PyTorch Distributed instead.r   z$Expecting a ProcessGroup, but got a .r&   r   )_get_default_groupr   r   r   r   rj   rq   r   _device_typesr   r   r   )rG   r   rk   rk   rl   _get_object_coll_device   s"   




r=  c                 C   s   t d | p	t } t| ts"t jdt|  dtdd tdS 	 | j	}t
|dkr0|d S t
|dkr:td	td|v rGtd}n|d }t d
| d |S )a$  
    .. note:: This method will be deprecated, it only stays for
        backward-compatiblity reason. Alternatives:

        - If you need to find a device for object collectives, please use
        `_get_object_coll_device(group)`.

        - If you need to query the device types supported by group, please use
        `_device_capability(group)`.

    Return the device type registered with ``group``.

    For example, if `init_process_group("nccl", ...)` was called, the returned
    value would be `torch.device("cuda")`.

    Errors out if no device has been registered.

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

    Returns:
        torch.device: The device type registered with ``group``.
    a  `_get_pg_default_device` will be deprecated, it only stays for backward-compatiblity reason. If you need to find a device for object collectives, please use `_get_object_coll_device`. If you need to query the device types supported by group, please use `_device_capability(group)`. r8  r9     )
stacklevelr   r&   r   zXDefault device not found, because no backend has been registered with this ProcessGroup.zqMultiple backends are registered with this ProcessGroup. We cannot determine which one is the default. Returning z#. Please consider using other APIs.)r   r   r;  r   r   rj   r   r   r   r<  r   RuntimeError)rG   r   rvrk   rk   rl   _get_pg_default_deviceA  s8   


rB  c                 C   s   | pt  } dd | jD S )a  
    Return the device type(s) supported by ``group``.

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

    Returns:
        List[str]: A list of device types supported by ``group``.
    c                 S      g | ]}|j qS rk   rj   )r   r   rk   rk   rl   
<listcomp>      z&_device_capability.<locals>.<listcomp>)r;  r<  rG   rk   rk   rl   _device_capability  s   
rH  
   secondsc                 C   s6  t  d| }||d td||  |}||d}| d}	||kr+||	d t|td|d  d	}t }
	 z	||	g| W nK t	y } z>||d}tdt |
 | ||||| tt |
 d	|krt
d|  d| d| d| d| d| dW Y d}~nd}~ww q<td| || dS )a  
    Store based barrier for synchronizing processes.

    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1rI  i  rJ  TzWaiting in store based barrier to initialize process group for %s secondsrank: %s, key: %s (world_size=%s, num_workers_joined=%s, timeout=%s error=%s)zDTimed out initializing process group in store based barrier on rank z, for key: z (world_size=z, num_workers_joined=z
, timeout=z error=r   Nz@Rank %s: Completed store-based barrier for key:%s with %s nodes.)STORE_BASED_BARRIER_PREFIXaddr   debugsetmaxr   timewaitr@  DistStoreErrorr   )rankstorer   rendezvous_countr2  logging_interval	store_key
world_sizeworker_countlast_worker_keystarterk   rk   rl   _store_based_barrier  sh   

r_  c                 C   s   | du rdS | t jkS )z<Check if the current process's rank is not in a given group.NF)r/   r/  rG  rk   rk   rl   _rank_not_in_group  s   
r`  c                 C   s4   t jd u 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-  rU  r   r   )r   global_rankrk   rk   rl   _warn_not_in_group  s   rc  rb  c                 C   sV   | t ju r|S | tjvrtd|  dtj|  }||vr't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 APIGlobal rank  is not part of group )r/   r-  r,  r  r   )rG   rb  group_ranksrk   rk   rl   r^     s   



r^   
group_rankc                 C   sd   | t ju r|S | tjvrtd|  dtj|   D ]\}}||kr'|  S qtd| d|  )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
    rd  re  zGroup rank rg  )r/   r-  r,  r  r   r   )rG   ri  rU  grp_rankrk   rk   rl   r_     s   


r_   z`torch.distributed.distributed_c10d._get_global_rank` is deprecated, please use `torch.distributed.distributed_c10d.get_global_rank` insteadr   c                 C   s
   t | |S )z1Use get_global_rank as this method is deprecated.)r_   )rG   rU  rk   rk   rl   _get_global_rank*  s   
rk  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.
    )r   r,  r  r   rG  rk   rk   rl   r`   4  s   
r`   c                 C   s(   | t ju s	| du rt }| S |  S )zGet a given group's world size.N)r/   r-  r;  sizerG   r   rk   rk   rl   r  A  s   r  r   c                 C   s   t | }| S r   )r   rl  )r   rG   rk   rk   rl   _get_group_size_by_nameI  s   rn  r  r   c                 C   s    t || }|d u rtd|jS N )_find_pg_by_ranks_and_tagr   r   )r  r   rG   rk   rk   rl   $_resolve_group_name_by_ranks_and_tagN  s   
rr  c                 C   s*   t | tjstd| dt|  ddS )z;Check that the parameter ``param_name`` is a single tensor./Invalid function argument. Expected parameter `z,` of type torch.Tensor
             but got 	 instead.N)r   r   r   r3  rj   param
param_namerk   rk   rl   r   W  s   r   c                 C   sd   t | tstd| dt|  dtdd | D s0td| dt|  ddd | D  d	d
S )z=Check that the parameter ``param_name`` is a list of tensors.rs  z2` of type List[torch.Tensor]
             but got rt  c                 s   s    | ]	}t |tjV  qd S r   )r   r   r   r   prk   rk   rl   r   g  s    z%_check_tensor_list.<locals>.<genexpr>z with elements of type c                 S      g | ]}t |qS rk   rD  rx  rk   rk   rl   rE  j      z&_check_tensor_list.<locals>.<listcomp>r:  N)r   r   r3  rj   allru  rk   rk   rl   _check_tensor_list`  s   
r}  c                 C   s   | d u s	| t ju rt } | S r   )r/   r-  r;  rG  rk   rk   rl   r   n  s   r   r   c                 C   sJ   |dur|durt dt| |}n|du rt dt| |}|r#|S |S )z
    Helper method to take _either_ a global rank or a group rank and produce a group rank.

    If 'return_global' is true, produce a global rank instead of a group rank.
    Nz-Can't specify both group_rank and global_rankz&Must specify global_rank or group_rank)r   r_   r^   )rG   rb  ri  r   rk   rk   rl   r   t  s   
r   rU  	rank_typec                 C   s&   |   |krtd| d| dd S )NzInvalid z rank: z@ rank should not be the same as the rank of the current process.)rU  r   )rG   rU  r~  rk   rk   rl   _check_not_self_rank  s
   r  c                 C   s   t | tr| S | fS r   )r   r   )objrk   rk   rl   _as_iterable  s   r  c                  G   sn   d }t jtt| D ])}|j}|jr|tjkrtj	ntj
}|d u r%|}q||kr4td| d|j qd S )Nz4Invalid usage of tensors with different dtypesFound z and  )	itertoolschainfrom_iterablemapr  r   
is_complexr   	complex64float32
complex128r   )tensors
last_dtyper   tensor_dtyperk   rk   rl   _ensure_all_tensors_same_dtype  s$   r  c                 C   s   | t tfvr
tddS )z/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)rR   rI   r   )r   rk   rk   rl   r     s
   r   c                    sP   t | trtdd | D std| d j t fdd| D s&tddS )zx
    Check that the ``p2p_op_list`` is a list of P2POp instances.

    Also, check that all ops use the same group.
    c                 s   s    | ]}t |tV  qd S r   )r   r0   r   p2p_oprk   rk   rl   r     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 r   rG  r  rG  rk   rl   r     s    z#All ops need to use the same group.N)r   r   r|  r   rG   )p2p_op_listrk   rG  rl   _check_p2p_op_list  s   
r  c                   C   r  )z&Check if the MPI backend is available.)_MPI_AVAILABLErk   rk   rk   rl   rL        rL   c                   C   r  )z'Check if the NCCL backend is available.)_NCCL_AVAILABLErk   rk   rk   rl   rN     r  rN   c                   C   r  )z'Check if the Gloo backend is available.)_GLOO_AVAILABLErk   rk   rk   rl   rJ     r  rJ   c                   C   r  )z&Check if the UCC backend is available.)_UCC_AVAILABLErk   rk   rk   rl   rP     r  rP   c                   C   r  )z'Check if the XCCL backend is available.)_XCCL_AVAILABLErk   rk   rk   rl   rQ     r  rQ   c                 C   s2   t tjd|   dd}|r| S |  tjv S )aF  
    Check backend availability.

    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_
_availableN)r   r   distributedr   r-   r   )r   available_funcrk   rk   rl   rM     s   rM   c                   C   s
   t jduS )z8Check if the default process group has been initialized.N)r/   r-  rk   rk   rk   rl   rK     r  rK   c                   C   s   t dduS )a  
    Check 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..
    TORCHELASTIC_RUN_IDN)osgetenvrk   rk   rk   rl   rO     s   
rO   c                   C   s   t tddS )NTORCH_DIST_INIT_BARRIER0)r   r  r  rk   rk   rk   rl   _is_barrier_after_init  s   r  c                   C   s"   t  stdtrttjS tjS )z<Get the default process group created by init_process_group.\Default process group has not been initialized, please make sure to call init_process_group.)rK   r   r   r%   r/   r-  rk   rk   rk   rl   r;    s   
r;  c                  C   s&   t  stdt } tj|  \}}|S )z4Get the default store created by init_process_group.r  )rK   r   r;  r,  r  )r   _default_storerk   rk   rl   _get_default_store  s   r  c                 C   s6   | t _| d ur| tjkr|  nd}tjj| d S )Nra  )	r,  r   r/   r/  rU  r   r   _distributed_c10d_set_global_rank)r$  rU  rk   rk   rl   _update_default_pg(  s   r  c                 C   s2   | pt  }t|rtdtj|}tt|S )a  
    Return the backend configuration 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 configuration of the given process group as a lower case string.

    Invalid process group specified)r;  r`  r   r,  r  getr   r%   )rG   r$  r  rk   rk   rl   rA   .  s
   
rA   c                 C   sB   | pt  }t|rtd|tjv rtj| nd}tt|d S )a  
    Return 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.

    r  Nr   )r;  r`  r   r,  r  r-   r%   )rG   r$  pg_storerk   rk   rl   rB   B  s
   
rB   r   c                 C   sF   t | tjr
| j}nt| j}tj|}|du r!td|  |S )z
    Return the default backend for the given device.

    Args:
        Union[str, torch.device]: The device to get the default backend for.

    Returns:
        The default backend for the given device as a lower case string.

    Nz,Default backend not registered for device : )r   r   r   rj   r-   r   r  r   )r   
device_strr   rk   rk   rl   rC   V  s   rC   r$  c                 C   sF   d }z
|  td}W n	 ty   Y nw t r!t|tr!|jS dS )Nr   ra  )_get_backendr   r   r@  rN   r   ro   uid)r$  r   rk   rk   rl   _get_process_group_uidm  s   r  c                 C   s,   | pt  }t||jt|t|t|dS )zB
    Return the pg configuration of the given process group.

    )r  r  r  pg_sizer  )r;  _get_process_group_namer!  rA   r  r`   )rG   r$  rk   rk   rl   _get_pg_configx  s   
r  c                  C   s   dd t j D } | S )zA
    Return the pg configuration of all the process groups.

    c                 S   rz  rk   )r  )r   r$  rk   rk   rl   rE    s    z'_get_all_pg_configs.<locals>.<listcomp>)r,  r  r   )r"  rk   rk   rl   _get_all_pg_configs  s   r  c                   C   r*  )z/
    Return the number of process groups.

    )r,  r  rk   rk   rk   rl   rF     s   rF   fallback_rankc                 C   s0   dt jv rtt jd S | durt| S td)a:  
    Return the local rank of the current process relative to the node.

    Semantically, this is a useful concept for mapping processes to devices.
    For example, on a node with 8 accelerator you could use the node local rank to decide
    which accelerator device to bind the process to.

    In practice, the actual assignment of node local ranks is handled by the process launcher outside of pytorch,
    and communicated via the `LOCAL_RANK` environment variable.

    Torchrun will automatically populate `LOCAL_RANK`, but other launchers may not.  If `LOCAL_RANK` is unspecified,
    this API will fall back to the provided kwarg 'fallback_rank' if specified, otherwise it will raise an error. The
    intent is to allow writing an application that runs either in single or multi device contexts without error.

    
LOCAL_RANKNzLOCAL_RANK is not in the environment. Consider passing fallback_rank to allow `get_node_local_rank` to work, assuming you are not running in a multi-device context and want the code to run locally instead.)r  environr   r@  )r  rk   rk   rl   rd     s   
rd   c                 C   sR   t j D ]!}|j}td|v r&|td}t r&t|t	r&|
|  qdS )a  
    This API adds an ephemeral timeout extension for all PGs locally
    on one rank. The timeout gets reset when the first collective issued
    after API called finished.
    NOTE: We only support to set timeout for cuda backends for now.
    NOTE: While this feature
    provides flexibility in specific scenarios, it introduces statefulness
    to timeout setting. Therefore, it is advisable to use this API sparingly
    and consider alternative approaches, such as directly setting the timeout
    or utilizing a barrier collective (one can set any timeout to the barrier),
    whenever feasible.

    Args:
        timeout (timedelta): The delta of timeout to extend.

    Returns:
        None.
    r   N)r,  r  r   r<  r   r   r  rN   r   ro   _add_ephemeral_timeout)r2  r$  r   r   rk   rk   rl   "_add_ephemeral_timeout_for_all_pgs  s   
r  c                 C   s   |du rt  }t|rtdt|tsJ |j}t }td|v r8t	 r8|
td}t|tr8|| td|v rb|
td}t rUt|trU|| nt	 rbt|trb|| t|dkrmtd |D ]}||  qodS )a  
    Set the timeout for the given process group when users want to use a different timeout instead of
    default values.

    Args:
        timeout (timedelta): Timeout for operations executed against the process group which
            users want to set. Default value is 10 minutes for NCCL and 30 minutes for other backends.
            This is the duration after which collectives will be aborted asynchronously and the process will crash.
            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.
            When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.

        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:
        None
    Nr  r   r   r   z:Set timeout is now only supported for either nccl or gloo.)r;  r`  r   r   r   r<  rP  r   r   rJ   r  rq   rN  rN   ro   r   r   r   _set_default_timeout)r2  rG   r   backendsr   rk   rk   rl   _set_pg_timeout  s,   



r  ra  rp  init_methodrZ  rV  
pg_options	device_idc	                    s8  t jdur	tdt  dtjv rtjj	  |du s#|du s#J d|dur8|dks/J d|dks7J dn|du r>d}| du rM|durMt
j|j} | du rSd	} t
| } |du r_t| }t| 	 tg d
d}| t
jkr|dksw|dkrtd| d| d tddg | t ||dd\}	}
t|	 n3|du rtt||||d}t|\}}}|| td|}t||g | |||||dd
\}	}
t|	 dd tt j D tjt j< tj tt j d a!|a"tj#dt$  d  fdd}|t_#t% dkrt&'d | t
jkrt(  dS t)||||| dS dS )a  
    Initialize the default distributed process group.

    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``, ``ucc``, or one that is registered by a third-party
            plugin.
            Since 2.6, if ``backend`` is not provided, c10d will use a backend
            registered for the device type indicated by the `device_id` kwarg
            (if provided). The known default registrations today are: ``nccl``
            for ``cuda``, ``gloo`` for ``cpu``.
            If neither ``backend`` nor ``device_id`` is provided, c10d will
            detect the accelerator on the run-time machine and use a backend
            registered for that detected accelerator (or ``cpu``).
            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 deadlock or NCCL invalid usage.
            ``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 is 10 minutes for NCCL and 30 minutes for other backends.
            This is the duration after which collectives will be aborted asynchronously and the process will crash.
            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.
            When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.

        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. For other availble options to config nccl,
            See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-t
        device_id (torch.device, optional): a single, specific device
            to "bind" this process to, allowing for backend-specific
            optimizations.  Currently this has two effects, only under
            NCCL: the communicator is immediately formed (calling
            ``ncclCommInit*`` immediately rather than the normal lazy
            call) and sub-groups will use ``ncclCommSplit`` when
            possible to avoid unnecessary overhead of group creation. If you
            want to know NCCL initialization error early, you can also use this
            field.

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

    Nz5trying to initialize the default process group twice!ztorch._dynamoz*Cannot specify both init_method and store.r   z*world_size must be positive if using storez(rank must be non-negative if using storezenv://r}   Fuse_hashed_namera  zFor MPI backend, world_size (z) and rank (z9) are ignored since they are assigned by the MPI runtime.r   )r2  r!  r4  )backend_optionsr2  r  r!  c                 S   s   i | ]}||qS rk   rk   r   irk   rk   rl   
<dictcomp>  s    z&init_process_group.<locals>.<dictcomp>z[rank]c                     sp   t j}t  t _}z	|   W |t _n|t _w | }d fdd|dD }t j| t j  d S )N
c                 3   s*    | ]}|d kr  d| nd V  qdS )rp  z: Nrk   )r   r   )excepthook_prefixrk   rl   r     s    
zFinit_process_group.<locals>._distributed_excepthook.<locals>.<genexpr>)	sysstderrioStringIOgetvaluer   r   writeflush)args
old_stderrbufmsgr  old_hookrk   rl   _distributed_excepthook  s   
z3init_process_group.<locals>._distributed_excepthookr&   VPerforming barrier after ProcessGroup initialization since TORCH_DIST_INIT_BARRIER = 1)*r/   r-  r   r!   r  modulesr   _dynamotrace_rulesclear_lru_cacher-   r   r  rj   r1  r5  _process_group_namer   r   r   _new_process_group_helperr   r  r,   r%   nextset_timeoutr   rangerl  r,  r  r  r  r6  
excepthookrD   r  r   rO  r8   r_  )r   r  r2  rZ  rU  rV  r   r  r  r   r  rendezvous_iteratorr  rk   r  rl   rH     s   
e








	
rH   c                 C   s~   d }| j r| | j }n| tju r%z
| td}W n	 ty$   Y nw |r*|js,d S tr=t	|t
r=|j}tr=t	|t
s3|S )Nr   )bound_device_idr  r,  r   r   r   r@  supports_splittingr  r   rp   
wrapped_pg)r$  
split_fromrk   rk   rl   _get_split_source  s   

r  c              	   C   sB  |t j v rtd|	dur|	jdu s|	jdkrtdt| |dvr7t||}|r7t j| \}}||fS |
du r=dn|
}
t	|dk}t
 rRt jrRtt }nd}|smt  }||vrm|rh|t j tjdfS t| d|}t||| }t|}d	t|vrd
t|vr|tjv sJ d| |tjkrtj|  v r|tjj nE|tjj n=|tj|  n4tj|j v r|tjj n$tj  rt!t"tj  }||j v r|tjj# n|tjj |	r|	|_| $ D ]\}}t| d|}|tj%krIt& st'dt()|}tjj%}|s+tjdf  S | dkrH|* dkrHt|| |* }|| n|tjkr\t+||| |d}tjj}n|tjkrt, sjt'd|durt-|t.j/szJ d|j0|krt12d nt./ }d|_3||_0|r||_4t5||_6||_7||_8t.||| |}tjj}nw|tj9krt: rt;||| |d}tjj9}n`|tj<krt= st'dt>||| }tjj<}nG|? tjv sJ d|?  tj|?  }|j@}|jA}tjj#}|s
|||| |}ntB }||_C||_D| |_E||_F||_G||_7|||}|tjkr7t-|t+s2J |H  n|tjkrIt-|t.sEJ |H  tIt|trU|} n[|tjtjtj9fv sh|? tjv rtJ tKjLkrtMsxtNOd n
tP||||| |d}t	tQ|  dkr|   D ]}|RtST||| q n|RtST||| q|dusJ |
dusJ |U| |V|
 |	r|W|	jXr|W|	}|Y|	 ||ft j|< |t j|< tZ|| t|t j[|< |dv r	d| }t j\]dg ^| nd| }t j\]|g ^| |t j_|< ||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 nameNr   zKinit_process_group device_id parameter must be an accelerator with an indexro  r}   r   /r   r   zUnknown backend type 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.ra  r4  z.Distributed package doesn't have NCCL built inzHExpected backend_options argument to be of type ProcessGroupNCCL.Optionszlbackend_options._timeout was specified, but timeout kwarg has a default value that will always override it. Fz.Distributed package doesn't have XCCL built inz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.)r  store_prefixrV  rU  rZ  r2  r&   ptd:rp  user:)`r,  r  valuesr   indexrj   r5  rq  r  r   rK   r;  r  r  rU  perform_nocolor_splitr/   r/  r   r   r.   r   r-   r   r   r   r   _set_default_backendr   r   r   r   r   r  iterr   r   r   rL   r@  rn   createrl  rq   rN   r   ro   Options_timeoutr   r   is_high_priority_streamr  _process_group_colorsplit_colorglobal_ranks_in_groupr   r   rP   rr   r   rQ   rs   r   r   r   r   rV  ri  r  r2  group_id_set_sequence_number_for_group
issubclassr   r   DETAILr  r   r   _create_process_group_wrapperrP  _register_backendr   r   _set_group_name_set_group_descr  r  eager_connect_single_devicer   r  r  
setdefaultr   r  )r  ri  r  r   rV  r   r  r2  pg_tagr  r!  existing_groupr  prefix_storeis_default_groupr  rb  r$  r  custom_backendr   r   backend_prefix_storebackend_classbackend_typebackend_pluginr   r   dist_backend_optseager_backendrk   rk   rl   r  	  sb  
























r  c                 C   s  | t jkrdS | du rt j}n| }|dusJ tj|ddu r$tdt|tkr2|	 r2|
  | du s;| t jkr{ttjdd ddD ]}|  qEtd tj  tj  tj  tj  tj  tj  tj  t  dt_dS |  tj|= tj|= tj|= tj|= |tj v rtd tj|= tj|}tj|= |durztj| | |d	rtjd
 | W n	 ty   Y nw t|j dS )ay  
    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  c                 S   
   t j|  S r   r,  r  xrk   rk   rl   <lambda>U     
 z'destroy_process_group.<locals>.<lambda>Tr   reverser   zfSome coalesced collectives haven't been launched when ProcessGroup is destroyed. They will be cleaned.r  rp  )r/   r/  r-  r,  r  r  r   rj   r   
_has_hooks_wait_for_pending_workssortedr  shutdownr  clearr  r  r  r  r  r   r  r   r   r   remove
startswith	Exceptionr   r   )rG   r$  pg_to_shutdownr   rk   rk   rl   r>   .  s^   













r>   c                 C   s  | t jkrdS | pt j}|dusJ tj|ddu rtdz
|t	d}W n t
y4   d}Y nw | du s>| t jkrt rJt|trJ|  ttjdd ddD ]}|  qTt rgt|trg|  td tj  tj  tj  tj  tj  tj  tj  t  dt_dS |  tj|= tj|= tj|= tj|= |tj v rtd	 tj|= tj|}tj|= |durztj| | | d
rtjd | W n	 t!y   Y nw t"|j# dS )aE  
    Abort a given process group. If group.WORLD (i.e. `None`) is given, all
    process groups including the default one will be aborted.

    Args:
        group (ProcessGroup, optional): The process group to be aborted.

    .. note:: this API is experimental and currently only works with the NCCL
        backend.

    .. note:: this API should be used with `TORCH_NCCL_ASYNC_ERROR_HANDLING`
        turned off (i.e. set to 0). Otherwise, ProcessGroupNCCL's watchdog may
        automatically handle errors or timeouts for you including aborting the
        ProcessGroup.
    Nz6Invalid process group specified or has been destroyed.r   c                 S   r  r   r  r  rk   rk   rl   r    r  z&_abort_process_group.<locals>.<lambda>Tr  r   zdSome coalesced collectives haven't been launched when ProcessGroup is aborted. They will be cleaned.r  rp  )$r/   r/  r-  r,  r  r  r   r  r   r   r@  rN   r   ro   _group_startr  r  abort
_group_endr  r  r  r  r  r  r  r   r  r   r   r   r  r  r  r   r   )rG   r$  r   pg_to_abortr   rk   rk   rl   _abort_process_group  sh   













r!  c                 C   s:   t | rdS t }| du s| tju r| S t| | S )a  
    Return the rank of the current process in the provided ``group``, default otherwise.

    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

    ra  N)r`  r;  r/   r-  rU  r^   rm  rk   rk   rl   rD     s   rD   c                 C   s   t | rdS t| S )a4  
    Return 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

    ra  )r`  r  rG  rk   rk   rl   rE     s   rE   r   dst	group_dstc                 C   sT   t |}t|||}t| d t|rtd dS |  r"t| } || g||S )a]  
    Send a tensor asynchronously.

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

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

    Unlike send, which is blocking, isend allows src == dst rank, i.e. send to self.

    Args:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank on global process group (regardless of ``group`` argument)
        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
        group_dst (int, optional): Destination rank on ``group``.  Invalid to specify both ``dst`` and ``group_dst``

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

    r   rR   N)	r   r   r   r`  rc  r  r   view_as_realr\   )r   r"  rG   r   r#  rk   rk   rl   rR   	  s    

rR   src	group_srcc                 C   sr   t | d t|rtd dS |  rt| } t|}|du r+|du r+|| g|S t|||}|	| g||S )aH  
    Receives a tensor asynchronously.

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

    Unlike recv, which is blocking, irecv allows src == dst rank, i.e. recv from self.

    Args:
        tensor (Tensor): Tensor to fill with received data.
        src (int, optional): Source rank on global process group (regardless of ``group`` argument).
            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
        group_src (int, optional): Destination rank on ``group``.  Invalid to specify both ``src`` and ``group_src``.

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

    r   rI   N)
r   r`  rc  r  r   r$  r   recv_anysourcer   rW   )r   r%  rG   r   r&  rk   rk   rl   rI   :	  s   

rI   c                 C   sH   t |}t|||}t||d t| |||d}|dur"|  dS dS )a  
    Send a tensor synchronously.

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

    Args:
        tensor (Tensor): Tensor to send.
        dst (int): Destination rank on global process group (regardless of ``group`` argument).
            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
        group_dst (int, optional): Destination rank on ``group``.  Invalid to specify both ``dst`` and ``group_dst``.

    destination)rG   r   r#  N)r   r   r  rR   rS  )r   r"  rG   r   r#  workrk   rk   rl   r\   g	  s   r\   c                 C   s`   t | ||||d}|du rdS |  |du r.|du r| }t|}t||d t||}|S )a  
    Receives a tensor synchronously.

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

    Args:
        tensor (Tensor): Tensor to fill with received data.
        src (int, optional): Source rank on global process group (regardless of ``group`` argument).
            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
        group_src (int, optional): Destination rank on ``group``.  Invalid to specify both ``src`` and ``group_src``.
    Returns:
        Sender rank
        -1, if not part of the group

    )r%  rG   r   r&  Nra  source)rI   rS  _source_rankr   r  r_   )r   r%  rG   r   r&  r)  rk   rk   rl   rW   	  s   
rW   c                   @   s   e Zd Zdd ZdS )_IllegalWorkc                 C   s   |dv rt d| dd S )N)
is_success	exceptionrS  source_rankr+  resultsynchronizezIllegal to call z on IllegalWork objectr   )r   r   rk   rk   rl   r   	  s   	z_IllegalWork.__getattribute__N)r   rh   r   r   rk   rk   rk   rl   r,  	  s    r,  c                   @   s,   e Zd Zd
ddZdefddZdd	 ZdS )_CoalescingManagerrf   Nc                 C   s
   g | _ d S r   )worksr   rk   rk   rl   r   	  s   
z_CoalescingManager.__init__r)  c                 C   s   |r
| j | d S d S r   )r4  r   r   r)  rk   rk   rl   r   	  s   z_CoalescingManager.appendc                 C   s   | j D ]}|  qd S r   )r4  rS  r5  rk   rk   rl   rS  	  s   

z_CoalescingManager.waitr   )r   rh   r   r   r    r   rS  rk   rk   rk   rl   r3  	  s    
r3  	async_opsc                 c   sv   | pt  } tj| g }|rtd|r| | t }|V  tj| }|r|d j}|t	krJdd |D }t
 }t|d j|_| ||}n[|tkrlg }	g }
|D ]}|	|j |
t|j qT| |
|	}n9|tkrg }	g }
|D ]}|	|j |
t|j qvt }t|d j|_| |
|	|}ntd| d| d|r| |}|r|| dS |  dS )	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   c                 S   rC  rk   )r   )r   r   rk   rk   rl   rE  	  rF  z'_coalescing_manager.<locals>.<listcomp>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  r   r   _start_coalescingr3  popr   r4   r   r%   r   ru   allreduce_coalescedrb   r   r   r   allgather_into_tensor_coalescedrc   r   reduce_scatter_tensor_coalescedAssertionError_end_coalescingrS  )rG   r   r6  op_listcmop0r  all_reduce_optsr)  inputsoutputsr   reduce_optsrk   rk   rl   _coalescing_manager	  sZ   
!


rE  r  c                 C   s  t |  | d j}|du rt }| d jj}dtdtttf fdd}t	|t
kra||jrat||dd }| D ]}|j|jf|j|jd	|| q9W d   |jS 1 sYw   Y  |jS g }| D ]}|j|jf|j|jd	||}|r|| qe|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, dtype=torch.float32) + 2 * rank
        >>> recv_tensor = torch.randn(2, dtype=torch.float32)
        >>> 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   Nr   rf   c                 S   s   | j tkrdnd}|| jiS )Nr#  r&  )r   rR   r   )r   r   rk   rk   rl   
peer_kwargS
  s   
z%batch_isend_irecv.<locals>.peer_kwargT)r6  )rG   r   )r  rG   r;  r   r   r0   r   r   r   rj   r   r  supports_coalescingrE  r   r   r4  r   )r  rG   r   rF  r?  r  reqsr)  rk   rk   rl   r9   #
  sH   *

		
r9   async_opc                 C   sp   t |}t|||dd}t| d t|rtd dS t }||_d|_||_|	| g|}|r2|S |
  dS )ad  
    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 on global process group (regardless of ``group`` argument).
        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
        group_src (int): Source rank on ``group``.  Must specify one of ``group_src``
            and ``src`` but not both.

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

    Fr   r   r:   Nr   )r   r   r   r`  rc  r   rootRank
rootTensorasyncOpr:   rS  )r   r%  rG   rI  r&  optsr)  rk   rk   rl   r:   r
  s   
r:   c                 C   s   | f}t |rtt|| |||dS t| d t|r td dS |  r5t|s0td| dt	
| } t }||_|du rBt }|tj v r`tt| d|d}tj| | |r^t S dS || g|}|rk|S |  dS )a  
    Reduces the tensor data across all machines in 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.
        >>> device = torch.device(f"cuda:{rank}")
        >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
        >>> tensor
        tensor([1, 2], device='cuda:0') # Rank 0
        tensor([3, 4], device='cuda:1') # Rank 1
        >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
        >>> tensor
        tensor([4, 6], device='cuda:0') # Rank 0
        tensor([4, 6], device='cuda:1') # 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, device=device
        ... ) + 2 * rank * (1 + 1j)
        >>> tensor
        tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
        tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
        >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
        >>> tensor
        tensor([4.+4.j, 6.+6.j], device='cuda:0') # Rank 0
        tensor([4.+4.j, 6.+6.j], device='cuda:1') # Rank 1

    r   rG   rI  r   r4   Nall_reduce does not support  on complex tensors)r$   r#   r4   r   r`  rc  r  r]   r   r   r$  r   ru   r;  r,  r  r   r   r   r,  	allreducerS  )r   r   rG   rI  relevant_argsrM  collr)  rk   rk   rl   r4   
  s@   6
	
r4   z`torch.distributed.all_reduce_coalesced` will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/main/distributed.html#collective-functionsc                 C   s   t | tjr	| g} t| d t|  t|rtd dS tdd | D r1t|s1t	d| ddd	 | D } t
 }||_|pBt }|| |}|rO| 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 (Union[List[Tensor], 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.

    r   r5   Nc                 s   s    | ]}|  V  qd S r   )r  r   trk   rk   rl   r   3      z'all_reduce_coalesced.<locals>.<genexpr>rO  rP  c                 S   "   g | ]}|  s
|nt|qS rk   r  r   r$  rT  rk   rk   rl   rE  6     " z(all_reduce_coalesced.<locals>.<listcomp>)r   r   r   r}  r  r`  rc  anyr]   r   r   ru   r;  r9  
get_futurerS  )r  r   rG   rI  rM  r)  rk   rk   rl   r5     s"   )

r5   c                 C   sj   t |}t|||dd}t| d t|rtd dS 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 on global process group (regardless of ``group`` argument)
        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
        group_dst (int): Destination rank on ``group``.  Must specify one of ``group_dst``
            and ``dst`` but not both.

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

    Fr   r   rX   N)
r   r   r   r`  rc  r   ru   rJ  rX   rS  )r   r"  r   rG   rI  r#  rM  r)  rk   rk   rl   rX   C  s    
rX   c           	      C   s   t d U t }t||  tj|	 }t
||}t tjkrEt rEt|}|tjkrEtjj|g}td| | t| g|}||fW  d    S 1 s^w   Y  d S )Nz+pytorch.wait_counter.c10d._object_to_tensorz)_object_to_tensor size: %s hash value: %s)r"   guardr  BytesIO_picklerdumpr   ByteStorage_from_bufferr  
ByteTensortor   r   r  rN   rB   r-   r   r   r  _hash_tensorsr   warningnumel
LongTensor)	r  r   rG   fbyte_storagebyte_tensorr   hash
local_sizerk   rk   rl   _object_to_tensort  s"   
$rm  c                 C   s   t d B t tjkr*t r*t|}|tjkr*t	j
j| g}td|  | |  } |   d | }tt| W  d    S 1 sKw   Y  d S )Nz+pytorch.wait_counter.c10d._tensor_to_objectz)_tensor_to_object size: %s hash value: %s)r"   r\  r   r   r  rN   rB   r-   r   r   r   r  rd  r   re  rf  r   numpytobytes
_unpicklerr  r]  load)r   tensor_sizerG   r   rk  r  rk   rk   rl   _tensor_to_object  s   

$rs  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 ]\}	}
|
tj}
||	 }t|
||| |	< qed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}]
    r3   NrG  r   r   c                       g | ]
} | j d dqS r   )dim	unsqueezer  object_sizes_tensorrk   rl   rE        z%all_gather_object.<locals>.<listcomp>c                    $   g | ]} | |d    qS r&   rk   r  coalesced_output_tensormax_object_sizerk   rl   rE        )r`  rc  r=  rm  rE   r   zeroslongr  r1   r   rQ  itemresize_emptyuint8	enumeraterj   rs  )object_listr  rG   current_deviceinput_tensorrl  r  object_size_listoutput_tensorsr  r   rr  rk   r  r  r{  rl   r3     s6   6


r3   r  object_gather_listc                    sl  t |}|du r|du rd}t|||dd}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r}t	j|
 t	j|d  fd
d	t|
D }t|||kr|nd||d ||krdS |dusJ d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 on global process group (regardless of ``group`` argument).
            (If both ``dst`` and ``group_dst`` are None, default is global rank 0)
        group: (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used. Default is ``None``.
        group_dst (int, optional): Destination rank on ``group``.  Invalid to specify both ``dst`` and ``group_dst``

    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}]
    Nr   Tr   r@   rG  rt  c                    ru  rv  rx  r  rz  rk   rl   rE  K  r|  z!gather_object.<locals>.<listcomp>c                    r}  r~  rk   r  r  rk   rl   rE  [  r  )gather_listr"  rG   z+Must provide object_gather_list on dst rank)r   r   r`  rc  rD   _validate_output_list_for_rankr=  rm  rE   r   r  r  r  r1   r   rQ  r  r  r  r  r?   r  rj   rs  )r  r  r"  rG   r#  
global_dstmy_global_rankr  r  rl  r  r  r  r  r   rr  rk   r  rl   r@     sT   D


r@   r  c           	         s   t t||}t|d trtd dS |pt t fdd| D  \}}t|}t	||d t
|dkrE|d }nt|}t	||d dS )	ar
  
    Sends picklable objects in ``object_list`` synchronously.

    Similar to :func:`send`, but Python objects can be passed in.
    Note that all objects in ``object_list`` must be picklable in order to be
    sent.

    Args:
        object_list (List[Any]): List of input objects to sent.
            Each object must be picklable. Receiver must provide lists of equal sizes.
        dst (int): Destination rank to send ``object_list`` to.
            Destination rank is based on global process group (regardless of ``group`` argument)
        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 sending. Default is ``None``.
        group_dst (int, optional): Destination rank on ``group``.
            Must specify one of ``dst`` and ``group_dst`` but not both
    Returns:
        ``None``.

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

    .. warning::
        :func:`send_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:`send_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:`send` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> # Assumes backend is not NCCL
        >>> device = torch.device("cpu")
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 2.
        >>>     objects = ["foo", 12, {1: 2}] # any picklable object
        >>>     dist.send_object_list(objects, dst=1, device=device)
        >>> else:
        >>>     objects = [None, None, None]
        >>>     dist.recv_object_list(objects, src=0, device=device)
        >>> objects
        ['foo', 12, {1: 2}]
    r(  r;   Nc                       g | ]}t | qS rk   rm  r   r  r  rG   rk   rl   rE        z$send_object_list.<locals>.<listcomp>)r#  rG   r&   r   )r   r   r  r`  rc  r=  zipr   catr\   r   )	r  r"  rG   r   r#  tensor_list	size_listr{  object_tensorrk   r  rl   r;   p  s    @


r;   c                 C   s   t |r
td dS |pt|}tjt| tj|d}t||||d}tjt|	 tj
|d}t||||d}	||	ksAJ dd}
t|D ]\}}||
|
|  }|tj
}|
|7 }
t|||| |< qG|	S )a
  
    Receives picklable objects in ``object_list`` synchronously.

    Similar to :func:`recv`, but can receive Python objects.

    Args:
        object_list (List[Any]): List of objects to receive into.
            Must provide a list of sizes equal to the size of the list being sent.
        src (int, optional): Source rank from which to recv ``object_list``.
            Source rank is based on global process group (regardless of ``group`` argument)
            Will receive from any rank if set to None. Default is ``None``.
        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, receives on this device.
            Default is ``None``.
        group_src (int, optional): Destination rank on ``group``.  Invalid to specify both ``src`` and ``group_src``.

    Returns:
        Sender rank. -1 if rank is not part of the group. If rank is part of the group,
        ``object_list`` will contain the sent 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()``.

    .. warning::
        :func:`recv_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:`recv_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:`recv` instead.

    Example::
        >>> # xdoctest: +SKIP("need process group init")
        >>> # Note: Process group initialization omitted on each rank.
        >>> import torch.distributed as dist
        >>> # Assumes backend is not NCCL
        >>> device = torch.device("cpu")
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 2.
        >>>     objects = ["foo", 12, {1: 2}] # any picklable object
        >>>     dist.send_object_list(objects, dst=1, device=device)
        >>> else:
        >>>     objects = [None, None, None]
        >>>     dist.recv_object_list(objects, src=0, device=device)
        >>> objects
        ['foo', 12, {1: 2}]
    r<   ra  rt  )r%  rG   r&  z6Mismatch in return ranks for object sizes and objects.r   )r`  rc  r=  r   r  r   r  rW   sumr  r  r  rj   rs  )r  r%  rG   r   r&  r  r{  
rank_sizesr  rank_objectsoffsetr  obj_sizeobj_viewrk   rk   rl   r<     s0   ?
r<   c                    sT  t |du r|du rd}t||dd}tr td dS |p%t t }||krAt fdd| D  \}}t|}	ntj	t
| tj d}	t|	|d	 ||krht
|d
krb|d }
nt|}
ntj	t|	 tj d}
t|
|d	 d}||krt|	D ] \}}|
|||  }|tj}||7 }t||| |< qdS dS )a  
    Broadcasts picklable objects in ``object_list`` to the whole group.

    Similar to :func:`broadcast`, but Python objects can be passed in.
    Note that all objects in ``object_list`` must be picklable in order to be
    broadcasted.

    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``.
            Source rank is based on global process group (regardless of ``group`` argument)
        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``.
        group_src (int): Source rank on ``group``.  Must not specify one of ``group_src``
            and ``src`` but not both.

    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:`broadcast`
        collective since it does not provide an ``async_op`` handle and thus
        will be a blocking call.

    .. warning::
        :func:`broadcast_object_list` uses ``pickle`` module implicitly, which
        is known to be insecure. It is possible to construct malicious pickle
        data which will execute arbitrary code during unpickling. Only call this
        function with data you trust.

    .. 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}]
    Nr   Tr   r=   c                    r  rk   r  r  r  rk   rl   rE    r  z)broadcast_object_list.<locals>.<listcomp>rt  r%  rG   r&   )r   r   r`  rc  r=  rD   r  r   r  r  r   r  r:   r  r  r  r  rj   rs  )r  r%  rG   r   r&  
global_srcr  r  r  r{  r  r  r  r  r  rk   r  rl   r=   9  sJ   F
r=   scatter_object_output_listscatter_object_input_listc                    sh  t   |du r|du rd}t ||dd}t r td dS t| tr+t| dk r/tdt }t	 ||krh|du rBtdt
 fd	d
|D  \}}t|t|}}t|}	|D ]}
|
|	 q_n
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rdn|| d t|| | d< dS )a3  
    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], optional): 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``.
            Source rank is based on global process group (regardless of ``group`` argument).
            (If both ``src`` and ``group_src`` are None, default is global rank 0)
        group: (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used. Default is ``None``.
        group_src (int, optional): Source rank on ``group``.  Invalid to specify both ``src`` and ``group_src``

    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}]
    Nr   Tr   r[   r&   zMExpected argument scatter_object_output_list to be a list of size at least 1.z;source rank must provide non-None scatter_object_input_listc                    s   g | ]}t | qS rk   r  r  rG   	pg_devicerk   rl   rE    s    
z'scatter_object_list.<locals>.<listcomp>rt  r  )scatter_listr%  rG   )r   r   r`  rc  r   r   r   r   rD   r=  r  rQ  r  r   r   r  r:   r  r  r  rZ   rs  )r  r  r%  rG   r&  r  r  r  tensor_sizesmax_tensor_sizer   output_tensorobj_tensor_sizerk   r  rl   r[     sf   @r[   c                 C   s   |f}t |rtt|| |||dS t| d t|d t| | t|r*td dS dd | D } | s7|nt	
|}|p@t }|| g|g}|rM|S |  dS )a
  
    Gathers tensors from the whole group in a list.

    Complex and uneven sized tensors are supported.

    Args:
        tensor_list (list[Tensor]): Output list. It should contain
            correctly-sized tensors to be used for output of the collective.
            Uneven sized tensors are supported.
        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.
        >>> device = torch.device(f"cuda:{rank}")
        >>> tensor_list = [
        ...     torch.zeros(2, dtype=torch.int64, device=device) for _ in range(2)
        ... ]
        >>> tensor_list
        [tensor([0, 0], device='cuda:0'), tensor([0, 0], device='cuda:0')] # Rank 0
        [tensor([0, 0], device='cuda:1'), tensor([0, 0], device='cuda:1')] # Rank 1
        >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
        >>> tensor
        tensor([1, 2], device='cuda:0') # Rank 0
        tensor([3, 4], device='cuda:1') # Rank 1
        >>> dist.all_gather(tensor_list, tensor)
        >>> tensor_list
        [tensor([1, 2], device='cuda:0'), tensor([3, 4], device='cuda:0')] # Rank 0
        [tensor([1, 2], device='cuda:1'), tensor([3, 4], device='cuda:1')] # 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, device=device) for _ in range(2)
        ... ]
        >>> tensor_list
        [tensor([0.+0.j, 0.+0.j], device='cuda:0'), tensor([0.+0.j, 0.+0.j], device='cuda:0')] # Rank 0
        [tensor([0.+0.j, 0.+0.j], device='cuda:1'), tensor([0.+0.j, 0.+0.j], device='cuda:1')] # Rank 1
        >>> tensor = torch.tensor(
        ...     [1 + 1j, 2 + 2j], dtype=torch.cfloat, device=device
        ... ) + 2 * rank * (1 + 1j)
        >>> tensor
        tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
        tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
        >>> dist.all_gather(tensor_list, tensor)
        >>> tensor_list
        [tensor([1.+1.j, 2.+2.j], device='cuda:0'), tensor([3.+3.j, 4.+4.j], device='cuda:0')] # Rank 0
        [tensor([1.+1.j, 2.+2.j], device='cuda:1'), tensor([3.+3.j, 4.+4.j], device='cuda:1')] # Rank 1

    rG   rI  r  r   r1   Nc                 S   rW  rk   rX  rT  rk   rk   rl   rE        zall_gather.<locals>.<listcomp>)r$   r#   r1   r}  r   r  r`  rc  r  r   r$  r;  	allgatherrS  )r  r   rG   rI  rR  r)  rk   rk   rl   r1   9  s2   ?
	


r1   c                 C   s   |f}t |rtt|| |||dS t|d t| d t|r%td dS |  s+| nt| } | s6|nt|}t	 }||_
|pEt }|tj v rbtt|| }tj| | |r`t S dS || ||}|rm|S |  dS )a	  
    Gather tensors from all ranks and put them in a single output tensor.

    This function requires all tensors to be the same size on each process.

    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  r  rb   N)r$   r#   rb   r   r`  rc  r  r   r$  r   rL  r;  r,  r  r   r   r   r,  _allgather_baserS  )r  r  rG   rI  rR  rM  rS  r)  rk   rk   rl   rb     sH   :
	

rb   z`torch.distributed._all_gather_base` is a private function and will be deprecated. Please use `torch.distributed.all_gather_into_tensor` instead.c                 C   s   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.

    )rb   )r  r  rG   rI  rk   rk   rl   _all_gather_base  s   r  z`torch.distributed.all_gather_coalesced` will be deprecated. If you must use it, please revisit our documentation later at https://pytorch.org/docs/main/distributed.html#collective-functionsc                 C   s   t |r
td dS t|d t| t| tstd| D ]}t|d t| qdd | D } dd |D }|p<t }|| |}|rI|	 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.
    r2   Ninput_tensor_listz?Invalid function argument: output_tensor_lists should be a listoutput_tensor_listsc                 S   s   g | ]	}d d |D qS )c                 S   rW  rk   rX  rT  rk   rk   rl   rE  g  rY  z3all_gather_coalesced.<locals>.<listcomp>.<listcomp>rk   )r   lrk   rk   rl   rE  f  s    z(all_gather_coalesced.<locals>.<listcomp>c                 S   rW  rk   rX  rT  rk   rk   rl   rE  j  r  )r`  rc  r}  r  r   r   r3  r;  allgather_coalescedr[  rS  )r  r  rG   rI  output_tensor_listr)  rk   rk   rl   r2   "  s.   7




r2   c                 C   s(   || kr|s
t dd S |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.r2  )my_rankr"  r  rk   rk   rl   r  w  s   r  r  c                 C   s   t | d |rt|d ng }t| | t|}t|r"td dS |du r,|du r,d}t|||dd}t|||dd}t }t||| ||krL|gng }| g}	t	 }
||
_
|||	|
}|rb|S |  dS )	a  
    Gathers a list of tensors in a single process.

    This function requires all tensors to be the same size on each process.

    Args:
        tensor (Tensor): Input tensor.
        gather_list (list[Tensor], optional): List of appropriately,
            same-sized tensors to use for gathered data
            (default is None, must be specified on the destination rank)
        dst (int, optional): Destination rank on global process group (regardless of ``group`` argument).
            (If both ``dst`` and ``group_dst`` are None, default is global rank 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
        group_dst (int, optional): Destination rank on ``group``.  Invalid to specify both ``dst`` and ``group_dst``

    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 gather_list must have the same size.

    Example::
        >>> # xdoctest: +SKIP("no rank")
        >>> # We have 2 process groups, 2 ranks.
        >>> tensor_size = 2
        >>> device = torch.device(f'cuda:{rank}')
        >>> tensor = torch.ones(tensor_size, device=device) + rank
        >>> if dist.get_rank() == 0:
        >>>     gather_list = [torch.zeros_like(tensor, device=device) for i in range(2)]
        >>> else:
        >>>     gather_list = None
        >>> dist.gather(tensor, gather_list, dst=0)
        >>> # Rank 0 gets gathered data.
        >>> gather_list
        [tensor([1., 1.], device='cuda:0'), tensor([2., 2.], device='cuda:0')] # Rank 0
        None                                                                   # Rank 1

    r   r  r?   Nr   Tr   F)r   r}  r  r   r`  rc  r   rD   r  r   rJ  r?   rS  )r   r  r"  rG   rI  r#  r  r  r  input_tensorsrM  r)  rk   rk   rl   r?     s.   
1
r?   r  c                 C   s  t | d |rt|d ng }t| | t|}|du r"|du r"d}t|||dd}t|||dd}t|r<td dS d	d
 |D }|  sI| nt	| } t
 }||krb|s[td|g}| g}	n|rhtdg }| g}	t }
||
_||
_||	||
}|r|S |  dS )a  
    Scatters a list of tensors to all processes in a group.

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

    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 on global process group (regardless of ``group`` argument).
            (If both ``src`` and ``group_src`` are None, default is global rank 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
        group_src (int, optional): Source rank on ``group``.  Invalid to specify both ``src`` and ``group_src``

    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
        >>> device = torch.device(f'cuda:{rank}')
        >>> output_tensor = torch.zeros(tensor_size, device=device)
        >>> if dist.get_rank() == 0:
        >>>     # Assumes world_size of 2.
        >>>     # Only tensors, all of which must be the same size.
        >>>     t_ones = torch.ones(tensor_size, device=device)
        >>>     t_fives = torch.ones(tensor_size, device=device) * 5
        >>>     scatter_list = [t_ones, t_fives]
        >>> else:
        >>>     scatter_list = None
        >>> dist.scatter(output_tensor, scatter_list, src=0)
        >>> # Rank i gets scatter_list[i].
        >>> output_tensor
        tensor([1., 1.], device='cuda:0') # Rank 0
        tensor([5., 5.], device='cuda:1') # Rank 1

    r   r  Nr   Tr   FrZ   c                 S   rW  rk   rX  rT  rk   rk   rl   rE    r  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`  rc  r  r   r$  rD   r   r   rJ  rL  rZ   rS  )r   r  r%  rG   rI  r&  r  r  r  r  rM  r)  rk   rk   rl   rZ     sL   
8
rZ   c                 C   sn   t | d t|d t| | t|rtd dS t }||_|p#t }|| g|g|}|r1|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_listrY   N)
r   r}  r  r`  rc  r   ru   r;  rY   rS  )r  r  r   rG   rI  rM  r)  rk   rk   rl   rY   :  s   



rY   c           	   	   C   s   |f}t |rtt|| ||||dS t| d t|d t|r&td dS t }||_||_|p3t	 }|t
j v rRtt|| |d}t
j| | |rPt 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.

    rN  r  inputrc   N)r$   r#   rc   r   r`  rc  r   ru   rL  r;  r,  r  r   r   r   r,  _reduce_scatter_baserS  )	r  r  r   rG   rI  rR  rM  rS  r)  rk   rk   rl   rc   a  s<   :



rc   z`torch.distributed._reduce_scatter_base` is a private function and will be deprecated. Please use `torch.distributed.reduce_scatter_tensor` instead.c                 C   s   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.

    )rc   )r  r  r   rG   rI  rk   rk   rl   r    s   r  c           	   
   C   s   |f}t |rtt|| |||||dS t|rtd dS t }t| d t|d t| | | r8t	
|}|  rAt	
| } |du rGg n|}|du rOg n|}|pUt }|| ||||}|rc|S |  dS )a  
    Split input tensor and then scatter the split list to all processes in a group.

    Later the received tensors are concatenated from all the processes in the group
    and returned as a 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
    )output_split_sizesinput_split_sizesrG   rI  r7   Nr  r  )r$   r#   r7   r`  rc  r   r   r  r  r   r$  r;  alltoall_baserS  )	r  r  r  r  rG   rI  rR  rM  r)  rk   rk   rl   r7     s@   h






r7   c                 C   s   t |r
td dS t }t| d t|d t| | dd |D }dd | D } |p.t }|| ||}|r:|S |  dS )a  
    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

    r6   Nr  r  c                 S   rW  rk   rX  rT  rk   rk   rl   rE    r  zall_to_all.<locals>.<listcomp>c                 S   rW  rk   rX  rT  rk   rk   rl   rE    r  )r`  rc  r   r}  r  r;  alltoallrS  )r  r  rG   rI  rM  r)  rk   rk   rl   r6   s  s$   ]



r6   c                 C   sv   t | r
td dS t }tt| |_|dur&t|tr"||_nt	d| p*t
 } | j|d}|r5|S |  dS )a  
    Synchronize 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

    .. note:: `ProcessGroupNCCL` now blocks the cpu thread till the completion of the barrier collective.
    r8   Nz>Invalid function argument: device_ids type should be List[int])rM  )r`  rc  r   r   r   r=  r   r   
device_idsr3  r;  r8   rS  )rG   rI  r  rM  r)  rk   rk   rl   r8     s    

r8   c                 C   s   t | r
td dS t| tjkrtd|du r tt| }nt|tr3t	
d| d t|d}t| | du r>t n| }|j||dS )a	  
    Synchronize processes similar to ``torch.distributed.barrier``, but consider a configurable timeout.

    It is able to report ranks that did not pass this barrier within the provided 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.
    rS   Nz7monitored_barrier is only implemented for GLOO backend.zGPlease specify timeout arg as a timedelta. Converting current value of z assuming it represents secondsrJ  )wait_all_ranks)r`  rc  rB   r-   r   r   r1  r   floatr   r   r   r5  r;  rS   )rG   r2  r  group_to_userk   rk   rl   rS     s&   6

rS   r  r  c                 C   sB   t sJ dt d| }t||}t||||d}t| |} | S )Nz5ProcessGroupWrapper unsupported without GLOO backend.r   r4  )r  PG_WRAPPER_STORE_PREFIXr   rq   rp   )r  r  rV  rU  rZ  r2  prefix	helper_pgrk   rk   rl   r  e  s   

r  c                 C   s@   d tt| }d |tttjg}tjt|ddd	 S )Nr  zutf-8F)usedforsecurity)
r   r  r   r   r,  r  hashlibsha1bytes	hexdigest)r  	rank_join
unique_strrk   rk   rl   _hash_ranks_to_str|  s   r  c                 C   s8   t | } t| }dttjd d  }t|| }|S )Nr      r&   )r(  rk  ctypessizeofc_intabs)r  
hash_value	max_c_intcolorrk   rk   rl   r    s
   r  c                 C   s,   |rt | }|S ttj}t jd7  _|S Nr&   )r  r   r,  r  )r  r  r  rk   rk   rl   r    s   
r  c                 C   s   | st t } t| S r   )rB   r;  r-   r0  rk   rk   rl   _get_backend_from_str  s   
r  c                   C   s   t  jdu rdS dS )z
    Checks if it is safe to split the any process group in the world.
    This is only safe if the default pg has a bound device id, otherwise
    users must be aware that a pg is only splittable after the first collective is
    issued.
    NFT)r;  r  rk   rk   rk   rl   _is_safe_to_split  s   r  	parent_pgsplit_ranksr!  c                    sB  |du rt dt }|j}|stdtj| \}}| }	| }
| s'|} | tjvr4t d|  dtj|  }dd |	 D  |	|vrPt d|	 d	|  ||	 }| 
td
}|rf|jrft|tsjtd|du rx| j d|  n|}tj|  \}}t|}t|}|durt|tjsJ dn|j}|du rt|}t| d}d}|D ]5}t|dkrt dt||
krt dt|tt|krt dt|}||v r|}||} nq|du s|dkr|| dS t|dd} fdd|D }t| d|}t||t|}tj j!}||_|"| ||_#||_$t%||_&||_'||_(t||t||}|)  |*td
|| |dusLJ |dusSJ |+| |,| |
|}|-| ||ftj|< |tj.|< t/|| t0|tj1|< d| }tj23|g 4| |tj5|< dd t6|D tj|< |S )a4  
    Create a new process group splitted from the given parent process group.

    warning:: This is an experimental API and only the ``NCCL`` backend supports this API.
    Other backends will raise an error.
    Users of this API must gurantee that all ranks in the parent group enter this API call,
    and the split of the sub groups is the same across all ranks in the parent group.

    Args:
        parent_pg (ProcessGroup, optional): The parent process group. If None,
            the default process group will be used. Users need to gurantee that
            the parent group is fully initialized (e.g, communicators are initialized)
        split_ranks (list[list[int]]): the split ranks, which is a list of list of ranks.
            Users need to make sure the validity of the split ranks such that one
            split (represented by one inner list of ints) does not overlap with any other split.
            Note that the ranks in each split is the group rank (instead of global rank)
            in the parent pg. For example, if the parent group has 4 ranks, and split_ranks can be
            [[0, 1], [2, 3]]. Note [[0,1]] is also a valid split, in which case ranks 2, 3 would
            return a non-group member.
        timeout (timedelta, optional): see `init_process_group` for details and default value.
        pg_options (ProcessGroupOptions, optional): only ProcessGroupNCCLOptions is supported now.
            specifying what additional options need to be passed in during
            the construction of specific process groups. i.e.``is_high_priority_stream``
            can be specified so that process group can pick up high priority cuda streams.
            For other availble options to config nccl,
            See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-t
        group_desc (str, optional): a string to describe the process group.

    Returns:
        ProcessGroup if the current rank is within one split/subgroup given by split_ranks,
        or None if the current rank is not part of any split_ranks`.

    Nzsplit_ranks cannot be NonezNNo device associated with the default pg, not safe to split any process groupsrd  z is not registeredc                 S      i | ]\}}||qS rk   rk   )r   rb  ri  rk   rk   rl   r        zsplit_group.<locals>.<dictcomp>rf  z! is not part of the parent group r   zQNo backend for the parent process group or its backend does not support splittingz:split:zCExpected pg_options argument to be of type ProcessGroupNCCL.Optionsra  r   zthe split group cannot be emptyzZthe split group's size should be less or equal to the world_size set by init_process_groupz+the split group cannot have duplicate ranksFr  c                    s   g | ]} | qS rk   rk   )r   rU  parent_group_to_global_ranksrk   rl   rE  8  r{  zsplit_group.<locals>.<listcomp>r  r  c                 S   r  rk   rk   r   ri  rb  rk   rk   rl   r  e  r  )7r   r;  r  r@  r,  r  rU  rl  r  r   r  r   r   r  r   ro   r!  comm_split_countr-   r.   r  optionsr1  r5  r   rP  r  r  r  r  r   r   r   r   r  r  r  r  r  r  r   r  r  r  r  r  r  r   r   r  r  r   r   r  r  )r  r  r2  r  r!  r   r  _default_backendr  rb  global_world_sizeparent_global_to_group_ranksparent_group_rankparent_backendparent_backend_strr  r   r  my_groupri  re   r   global_ranks_in_my_groupr  r$  r  r  r  r  rk   r  rl   re     s   *













re   c              
   C   s   t | |||d|||dS )aA  
    Create 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::
        Safe concurrent usage:
        When using multiple process groups with the ``NCCL`` backend, the user
        must ensure a globally consistent execution order of collectives across
        ranks.

        If multiple threads within a process issue collectives, explicit
        synchronization is necessary to ensure consistent ordering.

        When using async variants of torch.distributed communication APIs,
        a work object is returned and the communication kernel is
        enqueued on a separate CUDA stream, allowing overlap of communication
        and computation. Once one or more async ops have been issued on one process
        group, they must be synchronized with other cuda streams by calling `work.wait()`
        before using another process group.

        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): see `init_process_group` for details and default value.
        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. For other availble options to config nccl,
            See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-t
        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.
        group_desc (str, optional): a string to describe the process group.
        device_id (torch.device, optional): a single, specific device
            to "bind" this process to,  The `new_group` call will try to initialize
            a communication backend immediately for the device if this field is given.

    Returns:
        A handle of distributed group that can be given to collective calls or
        GroupMember.NON_GROUP_MEMBER 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_synchronizationr!  r  )_new_group_with_tag)r  r2  r   r  r  r!  r  rk   rk   rl   rT   m  s   OrT   c                 C   s  t  }|du r|j}n|jdur||jksJ dtj| \}	}
| }| }|s,|	}t|}|du r8t|}t| |rR|tj	krGt
d| durRt | vrRdS | durt| } t| }||krft
d| D ]}|dk sr||krvt
dqh|| v r| |}nd}n
tt|} |}|}t| |d}t||| ||
||||||d\}}d	d
 t| D tj|< t dkrtd |tj	krt  |S |r|n|
}|rt| nt }t||||| |S )z
    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.
    Nz:Mismatched bound device between new pg and the default pg.z:MPI backend doesn't support use_local_synchronization=Truez^the new group's world size should be less or equal to the world size set by init_process_groupr   zNThe new group's rank should be within the world_size set by init_process_groupr  )r  r2  r  r  r!  c                 S   r  rk   rk   r  rk   rk   rl   r  %  s    
z'_new_group_with_tag.<locals>.<dictcomp>r&   r  )r;  r  r,  r  rU  rl  r-   r1  r5  r   r   rD   r  r   r  r   r  r  r  r  r  r  r   r   r8   rE   r_  )r  r2  r   r  r  r  r!  r  r   default_backendr  rb  r  group_world_sizerU  ri  r   r$  r  barrier_storerZ  rk   rk   rl   r    s   



	


r  c                 C   s   | du rt j stdt j } | dkrtd|  dt }|| k r0td|  d| d||  dkr:tdg }d}t||  D ]/}	|	|  }
|
|  }tt|
|}t|||||d	}|	| t
 }||v rs|}td
|| qD||fS )aS  
    Create 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::
        See warning `Safe concurrent usage` for `new_group` API for important details about
        using multiple process groups concurrently in a safe manner.

    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): see `init_process_group` for details and default value.
        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.
        group_desc (str, optional): A string describing the group. Each subgroup will
            inherit its group_desc

    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([28])  # Assume 8 CUDA devices per machine.  28 is sum(range(8)).
        >>> # 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 (r   z0The world size must be divisible by 'group_size'r  r2  r   r  r!  "Rank %s is assigned to subgroup %s)r   r   is_availabler   device_countrE   r  r   rT   r   rD   r   r   )r  rG   r2  r   r  r!  rZ  	subgroupscur_subgroupsubgroup_id
start_rankend_rankranks_in_subgroupsubgrouprU  rk   rk   rl   rU   E  sF   H


rU   c              	   C   s   | du s
t | dkrtdg }d}i }| D ]<}t|||||d}	||	 t }
|D ]&}||v r@td| d||  d| |||< |
|krQ|	}td|| q+q||fS )	a	  
    Create subgroups by dividing the global world.

    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::
        See warning `Safe concurrent usage` for `new_group` API for important details about
        using multiple process groups concurrently in a safe manner.

    Args:
        ranks_per_subgroup_list (list[list[int]]): A nested list of ranks of
            group members.
        timeout (timedelta, optional): see `init_process_group` for details and default value.
        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.
        group_desc (str, optional): A string describing the group. Each subgroup will
            inherit its group_desc.

    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   r   rT   r   rD   r   r   )ranks_per_subgroup_listr2  r   r  r!  r  r  rank_to_ranks_dictr  r  r  rU  rk   rk   rl   rV     s6   8

rV   c                    s~   t | dkr| ds| dsd|  } tj| g D ] }| t |kr'qt| t fdd|D }|r<|  S qd S )Nr   r  r  c                 3   s    | ]}| v V  qd S r   rk   )r   rrh  rk   rl   r     rV  z,_find_pg_by_ranks_and_tag.<locals>.<genexpr>)r   r  r,  r  r  rl  r`   r|  )r   r  rG   goodrk   r  rl   rq    s    
rq  stridec                 C   s   t || dksJ dt | d| dt }d }|t |kr-| }||v s,J dn!tdt ||D ]}||||  }||v rE|}q5|d usNJ dt|}t| |}|d ur]|S | dkretdt|| dS )	Nr   zRanks length (z) must be divisible by stride (r   z(rankset doesn't include the current noderp  z-Cannot automatically create PG with empty tag)r  )r   rD   copyr  r  rq  r   r  )r   r  r  r  my_ranksr  rank_setr$  rk   rk   rl   #_find_or_create_pg_by_ranks_and_tag  s*   
r  c                 C   s   t j|  }|d}|S )z&Return the tag associated with ``pg``.r  )r,  r  removeprefix)r$  r   rk   rk   rl   _get_group_tag<  s   

r
  c                 C   s   t j| dS )NNone)r,  r  r  r$  rk   rk   rl   r  C     r  c                 C   s   t j|  d S r  )r,  r  r  rk   rk   rl   _get_process_group_storeG  r  r  r   r   )NNF)	NNNra  ra  Nrp  NN)NNNNNr   )NNFN)NNNN)NF)NNNFN)NNNF)NNNNFNN)NNNNNFNN)NNNNNN)r   collections.abccollections
contextlibr  r  r  r  loggingr  pickler  rR  r   r   datetimer   typingr   r   r   r   r   typing_extensionsr	   r   torch._Cr
   rT  torch._C._distributed_c10dr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    torch._utils_internalr!   torch.monitorr"   torch.overridesr#   r$   torch.utils._typing_utilsr%   c10d_loggerr'   r(   	constantsr)   r*   r,   r+   __all__r  r  r  r  r  Picklerr^  	Unpicklerrp  rm   rn   rh   ImportErrorro   rp   rq   rr   rs   	getLoggerr   r   r  boolr]   r   r-   r.   r   ra   r0   r   r   r   r(  r   r  r  r   r  r  r  r   r  r  r  r,  rj   r)  rG   r/   r1  r5  r6  rM  r=  r   rB  rH  r_  r`  rc  r^   r_   r   rk  r`   r  rn  rr  r   r}  r   r   r  abcIterabler  r  r   r  rL   rN   rJ   rP   rQ   rM   rK   rO   r  r;  r  r  rA   rB   rC   r  r  r  rF   rd   r  r  rH   r  r  r>   r!  rD   rE   r   rR   rI   r\   rW   r,  r3  contextmanagerrE  r9   r:   SUMr4   r5   rX   rm  rs  r3   r@   r;   r<   r=   r[   r1   rb   r  r2   r  r?   rZ   rY   rc   r  r7   r6   r-  r8   rS   r   r  r  r  r  r  r  r  re   rT   r  rU   rV   rq  r  r
  r  r  rk   rk   rk   rl   <module>   s  `M

 PFAND		

"+	
 x  'WZ
/
-'XO.`:0Z
|be}
 ^kNOf&d u-U
 >[~u"V