
    [Thg@                       % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKJr  SSKJr  SSKJrJrJrJrJr  SSKJr  SSKrSSKJr  SSKJrJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3  SS	K4J5r5  SS
K6J7r7  SSK8J9r9J:r:  SSK;J<r<  SSK=J>r>J?r?  SSK@JArAJBrB  SSKCJDrDJCrC  / SQrESrFSrGSrHSrISrJ\
R                  rL\
R                  rNSS jrO\O" 5          SSKJPrP  S\PlQ        \ES/-  rE SSKJSrS  S\SlQ        \ES/-  rE SSKJTrTJUrU  S\UlQ        \ES/-  rE SSKJVrV  S\VlQ        \ES/-  rE SSKJWrW  S\WlQ        \ES /-  rE\R                  " \Y5      rZS!r[S"\.S\\4S# jr] " S$ S%\^5      r_ " S& S'5      r` " S( S)5      ra\a" 5       rb " S* S+5      rc " S, S-5      rd0 qe\f\-\g\^\24   4   \hS.'   0 qi\f\-\^4   \hS/'   0 qj\f\-\f\k\k4   4   \hS0'   0 ql\f\-\^4   \hS1'   Sqm0 qn\f\^\o\-   4   \hS2'   0 qp\f\-\^4   \hS3'   Sqq\\^   \hS4'    " S5 S65      rr\r" 5       qs  " S7 S8\t5      ru " S9 S:\uS;9rv " S< S=\uS;9rwS>\_S\4S? jrxS@\SS4SA jrySqz\\^   \hSB'   SCr{SS:\\-   S\^4SD jjr|SS:\\-   S\R                  4SE jjr~SS:\\-   S\o\^   4SF jjr\?\" SGSH94 SSI jj5       rS:\\-   S\\4SJ jrSSK jrS:\-SL\kS\k4SM jrS:\-SN\kS\k4SO jr\" SP\SQ9S\k4SR j5       rS:\-S\o\k   4SS jrS\k4ST jrSU\^S\k4SV jrSW\o\k   SX\^S\^4SY jrSSZ jrSS[ jrSS:\\-   S\-4S\ jjr   SS:\-SL\\k   SN\\k   S]\\S\k4
S^ jjrS:\-S_\kS`\^4Sa jrS\GR                   GR"                  4Sb jrSSc jrSSd jrSSe jrS\\4Sf jrS\\4Sg jrS\\4Sh jrS\\4Si jrS\\4Sj jrS>\^S\\4Sk jrS\\4Sl jrS\\4Sm jrS\k4Sn jrS\-4So jrS\24Sp jrSSq jrSS:\\-   S\^4Sr jjrSS:\\-   S\_4Ss jjrSt\\^\R                  4   S\^4Su jrSv\-S\k4Sw jrSS:\\-   S\f\^\4   4Sx jjrS\o\f\^\4      4Sy jrS\k4Sz jrSS{\\k   S\k4S| jjrS@\SS4S} jrSS@\S:\\-   SS4S~ jjr\>\?         SS>\\^   S\\^   S@\\   S\kS_\kS\\2   SU\^S\\   S\\R                     SS4S jj5       5       rS r     SS jrSS:\\-   4S jjrSS:\\-   4S jjrSS:\\-   S\k4S jjrSS:\\-   S\k4S jjr    SS\GRf                  S\\k   S:\\-   SX\kS\\k   S\\3   4S jjr    SS\GRf                  S\\k   S:\\-   SX\kS\\k   S\\3   4S jjr\>    SS\GRf                  S\\k   S:\\-   SX\kS\\k   SS4S jj5       r\>    SS\GRf                  S\\k   S:\\-   SX\kS\\k   S\k4S jj5       r " S S\35      r " S S5      r\GRt                     SS:\\-   St\\R                     S\\\   4S jj5       rS\o\c   S\o\3   4S jr\>    SS\GRf                  S\\k   S:\\-   S\\S\\k   4
S jj5       r\>\.GR|                  SS4S j5       r\>\" S\SQ9\.GR|                  SS4S j5       5       r\>S\.GR|                  SSS4S\GRf                  S\\k   S:\\-   S\\S\\k   4
S jj5       rS rS r\>SS j5       r\>    SS\S\\o\      S\\k   S:\\-   S\\k   4
S jj5       r\>    SS\o\   S\\k   S:\\-   St\\R                     S\\k   4
S jj5       r\>    SS\o\   S\\k   S:\\-   St\\R                     S\\k   4
S jj5       r\>    SS\o\   S\\k   S:\\-   St\\R                     S\\k   4
S jj5       r\>    SS\o\   S\\o\      S\\k   S:\\-   S\\k   4
S jj5       r\>SS j5       r\>SS j5       r\>\" S\SQ9SS j5       5       r\>\" S\SQ9 SS j5       5       rS r\>     SS\GRf                  S\\o\GRf                        S\\k   S:\\-   S\\S\\k   4S jj5       r\>     SS\GRf                  S\\o\GRf                        S\\k   S:\\-   S\\S\\k   4S jj5       r\>\.GR|                  SS4S j5       r\>\.GR|                  SS4S j5       r\" S\SQ9\.GR|                  SS4S j5       r\>    SS j5       r\>SS j5       r\>\wGR                  SS4S:\\-   4S jj5       r\wGR                  SS4S:\\-   4S jjr\B4S\GR                  GR                  R                  S\^S\2S_\kS\kS@\4S jjrSW\o\k   S\^4S jrSW\o\k   S\k4S jrS rSS>\\^   S\_4S jjrS\\4S jr\?     SS\\-   S\\o   S@\\   S\\   S\\^   S\\-   4S jj5       r\?       SS\\R                     4S jj5       r        SS\\R                     4S jjr      SS jr    SS jrSX\^SW\o\k   S\\-   4S jrSX\^SW\o\k   S\kS\-4S jrSv\-S\^4S jrSv\-S\^4S jrSv\-S\24S jrg! \R a    SrF G	Nf = f! \R a    SrG G	Nf = f! \R a    SrH G	Nf = f! \R a    SrI G	N
f = f! \R a    SrJ G	Nf = f)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                      [         [        [        [        [        [
        [        [        [        [        [        [        [        [        [        [        /n U  H
  nSUl        M     g )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types     Z/var/www/auris/envauris/lib/python3.13/site-packages/torch/distributed/distributed_c10d.py_export_c_typesrn      sM    !!&"$ /> /    )ProcessGroupMPIri   rp   F)ProcessGroupNCCLrq   )_ProcessGroupWrapperProcessGroupGloors   )ProcessGroupUCCrt   )ProcessGroupXCCLru   
pg_wrapperreduceOpc                     [         R                  [         R                  [         R                  [         R                  [         R
                  [         R                  /nX;  $ )z8Return true if reduce ops is supported. False otherwise.)r   MAXMINPRODUCTBANDBORBXOR)rw   denyLists     rm   r^   r^      sB     	H ##ro   c                   N   \ rS rSr% SrSrSrSrSrSr	Sr
\" S	S
S/5      r0 r\\\4   \S'   \\\\
\\	/r\\\
S.r\\\4   \S'   \SS/\S/\
S/\SS/\	SS/0r\\\\   4   \S'   \\R,                  R
                  \\R,                  R                  \\R,                  R                  \
\R,                  R                  \\R,                  R                  \	\R,                  R                  0r\\\R,                  4   \S'   S\4S jr\  SS\\\\\   4      SS4S jj5       rSrg)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                     [        U[        5      (       d  [        S5      e[        [        UR                  5       [        R                  5      nU[        R                  :X  a  UR                  5       nU$ ).Create and return a new instance of the class.z0Backend constructor parameter must be string-ish)
isinstancestr
ValueErrorgetattrr.   upper	UNDEFINEDlower)clsr   values      rm   __new__Backend.__new__$  sS    $$$OPPw/@/@AG%%%JJLEro   Ndevicesrg   c                    [        [        UR                  5       5      (       d-  [        [        UR                  5       UR	                  5       5        UR	                  5       [        R
                  ;  a-  [        R
                  R                  UR	                  5       5        Ub:  U H4  nUS:w  d  M  US:w  d  M  UR	                  5       [        R                  U'   M6     [        R                  R                  [        R                  UR	                  5       '   Uc>  [        R                  " SU S35        SS/[        R                  UR	                  5       '   OY[        U[         5      (       a#  U/[        R                  UR	                  5       '   O!U[        R                  UR	                  5       '   [        R#                  X#5      [        R$                  UR                  5       '   g)a  
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   devices         rm   register_backendBackend.register_backend.  sT   B w

--GTZZ\4::<8::<w333  ''

5!U?v'7AEG66v> " 2>1I1I1P1P  . ? MM'v .& &
 9>vG&&tzz|4%%8?yG&&tzz|47>G&&tzz|4)0)?)?)S&ro    )FN)__name__rj   __qualname____firstlineno____doc__r   GLOONCCLUCCMPIXCCLr   r   r   dictr   __annotations__r   r   r   listr   r   r   r   classmethodr   r	   r   __static_attributes__r   ro   rm   r.   r.      s   $ IDD
C
CD 0<2PQN*,Hd3&',tT4c:L 2S#X  	ufovhugeV_eV_0S$s)^,  	<++55l&&++l&&++l&&++\%%))\%%))=d3 8 889 3  
 37;T
 %T#Y/0;T 
;T ;Tro   r.   c                   D    \ rS rSrSrS\4S jrS rS\\	\4   4S jr
Srg	)
r/   im  zBackend configuration class.backendc           	         0 U l         [        U5      nU[        R                  :X  aV  [        R
                  R                  5       R                  n [        R                  U   n[        U5      U R                   U'   GOJUR                  5       [        R                  ;   aG  [        R                  UR                  5          n[        U5      n[        R                  XE5      U l         OSUR                  5       ;   a  SU S3nUR                  5       R!                  S5       Hs  nUR!                  S5      n[#        U5      S:w  a  [        S	U S
U 35      eUu  pXR                   ;   a  [        SU	 SU S
U 35      e[        U5      U R                   U	'   Mu     O0[$        R&                  " SU S35        [        U5      nUUUS.U l         [(        R+                  SU R                   5        g! [         a    [        SU S35      Sef = f)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_acceleratorrl   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   s
             rm   __init__BackendConfig.__init__p  s"   68g,g'''  ((335::K%@@M7>{7K''4 ]]_ 4 44 !( : :7==? K!'*K&*mm4E&SD#GMMO#
 -\\c[d ed )g%
 ,3==?+@+@+E'&=&C&CC&H#*+q0$&&=%>bAZ@[]  #6444$0 999@	D]C^`  3:'2B''/ ,F$ MM'y 1- -
 "'*K"#"'D# 	.0G0GHi   .{m <^ _ 	s   +G( (Hc                 b    SR                  S U R                  R                  5        5       5      $ )z8Return all the device:backend pairs separated by commas.r   c              3   4   #    U  H  u  pU S U 3v   M     g7f)r   Nr   ).0r   r   s      rm   	<genexpr>)BackendConfig.__repr__.<locals>.<genexpr>  s!      
9Xofvhay!9Xs   )joinr   itemsr   s    rm   __repr__BackendConfig.__repr__  s/    xx 
9=9P9P9V9V9X
 
 	
ro   rg   c                     U R                   $ )z!Return backend map of the device.r   r   s    rm   get_device_backend_map$BackendConfig.get_device_backend_map      &&&ro   r   N)r   rj   r   r   r   r.   r   r   r   r   r   r   r   ro   rm   r/   r/   m  s0    &@I @ID
'S'\(: 'ro   r/   c                   <    \ rS rSrSrS	S jr\" S\S9S 5       rSr	g)

_reduce_opi  z
Deprecated enum-like class.

For reduction operations: ``SUM``, ``PRODUCT``, ``MIN``, and ``MAX``.

:class:`~torch.distributed.ReduceOp` is recommended to use instead.
Nc                     [         R                  R                  R                  5        H  u  p[	        XU5        M     [         R                  R                  U l        g N)r   	RedOpType__members__r   r   )r   kvs      rm   r   _reduce_op.__init__  sA    &&2288:DADQ ;#--99ro   z\`torch.distributed.reduce_op` is deprecated, please use `torch.distributed.ReduceOp` insteadcategoryc                 ,    [         R                  X5      $ r   )object__getattribute__)r   keys     rm   r   _reduce_op.__getattribute__  s     &&t11ro   )r   rg   N)
r   rj   r   r   r   r   r
   FutureWarningr   r   r   ro   rm   r   r     s-    : 	:
2
2ro   r   c                      ^  \ rS rSrSr    SS\S\R                  S\\	   S\\
   S\	S\\	   4S	 jjr    SS\S\R                  S\\	   S\\
   S\	S\\	   4S
 jjrU 4S jrSrU =r$ )r1   i  a'  
A class to build point-to-point operations for ``batch_isend_irecv``.

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

Args:
    op (Callable): A function to send data to or receive data from a peer process.
        The type of ``op`` is either ``torch.distributed.isend`` or
        ``torch.distributed.irecv``.
    tensor (Tensor): Tensor to send or receive.
    peer (int, 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.
optensorpeerrH   tag
group_peerc                     Xl         X l        [        U5      U l        [	        U R                  X6SS9U l        XPl        [	        U R                  X65      U l        g)r   Treturn_globalN)r   r   _group_or_default_grouprH   _canonicalize_group_rankr   r   r   )r   r   r   r   rH   r   r   s          rm   r   P2POp.__init__  sJ     ,U3
,JJ
	 24::tPro   c                 Z    [        U5        [        US5        [        R                  U 5      $ )r   r   )	_check_op_check_single_tensorr   r   )r   r   r   r   rH   r   r   s          rm   r   P2POp.__new__  s$     	"VX.~~c""ro   c                   > [        U R                  5      nU R                  R                  nU R                  (       a  U R                  R                  OSnSU;   a  UnU R
                  nO#SU;   a  U R
                  nUnO[        TU ]  5       $ SU SU SU SU SU R                  R                   S	U R                  R                   S
3$ )N
default_pgr]   rX   zP2POp(z pg=z, group_src=z, group_dst=z,  z, ))rE   rH   r   r   
group_namer   superr   r   shapedtype)r   my_group_rankop_namer  sd	__class__s         rm   r   P2POp.__repr__  s     ,''"".2jjTZZ**l
WAAwAA7#%%yZLQC|A3cRVR]R]RcRcQddfgkgrgrgxgxfyyz{{ro   )rH   r   r   r   r   r   NNr   N)r   rj   r   r   r   r   r   Tensorr   intr   r   r   r   r   __classcell__)r  s   @rm   r1   r1     s    . #(,$(QQ Q sm	Q
 %Q Q SMQ. #(,$(## # sm	#
 %# # SM#| |ro   r1   c                   z    \ rS rSrSr   SS\S\R                  S\\R                     S\\	   S\\
   4
S	 jjrS
rg)_CollOpi  ax  
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                 @    Xl         X l        X0l        X@l        XPl        g r   )r   r   r  r  r   )r   r   r   r  r  r   s         rm   r   _CollOp.__init__*  s     $
	ro   )r  r   r  r   r   )NNN)r   rj   r   r   r   r   r   r  r   r   r  r   r   r   ro   rm   r  r    sb    	 .2$("  U\\*	
 ! sm ro   r  _pg_map	_pg_names_pg_group_ranks_pg_backend_config_tags_to_pg
_pg_to_tag_backendc                      \ rS rSrSrSS jr\S\\   4S j5       r	\	R                  SS j5       r	\S\\\\\4   4   4S j5       r\S\\\4   4S	 j5       r\S\\\\\4   4   4S
 j5       r\S\\\4   4S j5       r\S\4S j5       r\R                  S\SS4S j5       r\S\\\\   4   4S j5       r\S\\\4   4S j5       r\S\\\\   4   4S j5       r\S\\\\4      4S j5       rSrg)_WorldiF  z
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..
rg   Nc                      S U l         0 U l        g r   _default_pg_pg_coalesce_stater   s    rm   r   _World.__init__P  s    EGro   c                     U 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   s    rm   r  _World.default_pgT  s     ro   c                     Xl         g r   r2  r   r   s     rm   r  r3  ^  s     ro   c                     [         $ )z
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   s    rm   pg_map_World.pg_mapb  s	     ro   c                     [         $ )zj
Process group's names, map from ProcessGroup to str.

TODO don't expose the map, expose fine grained ops
)r$  r   s    rm   pg_names_World.pg_nameso  s
     ro   c                     [         $ )zh
Process group's global rank to local rank mapping.

TODO don't expose the map, expose fine grained ops
)r%  r   s    rm   pg_group_ranks_World.pg_group_ranksy  s
     ro   c                     [         $ )zU
Process group's backend config.

TODO don't expose the map, expose fine grained ops
)r&  r   s    rm   pg_backend_config_World.pg_backend_config  s
     "!ro   c                     [         $ )zd
Process group count for default naming.

TODO don't expose group_count, use something else instead
_group_countr   s    rm   group_count_World.group_count  s
     ro   r   c                     Uq g)zKUse to compute the name of ProcessGroups when using global synchronization.NrC  r5  s     rm   rE  rF    s	     ro   c                     [         $ r   )r'  r   s    rm   
tags_to_pg_World.tags_to_pg  s
     ro   c                     [         $ r   )r(  r   s    rm   	pg_to_tag_World.pg_to_tag  s
     ro   c                     U R                   $ r   )r/  r   s    rm   pg_coalesce_state_World.pg_coalesce_state  r   ro   c           
      n   / n[        S5      nU R                  R                  5        H  nU R                  U   nUR	                  U R
                  U   UR                  U R                  U   [        U5      U:w  a  [        UR                  5       5      O/ [        U5      U R                  S.5        M     U$ )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_sizerE  )_get_group_sizer7  keysr=  r   r:  
group_descr@  r   r   rE  )r   config_infodefault_pg_sizepgrU  s        rm   pg_config_info_World.pg_config_info  s     -/)$/++""$B''+E#}}R0!}}&*&<&<R&@.1%jO.KUZZ\*QS"%e*#'#3#3	 % ro   r-  r   )r   rj   r   r   r   r   propertyr   r   r  setterr   tupler   r    r7  r:  r  r=  r@  rE  r   rI  rL  r  rO  r   r]  r   r   ro   rm   r+  r+  F  s   H  H\2     ! ! 
\5e+<<= 
 
 $|S01   \4S>%A B   "4c(9#: " " S      
 Dd<&8!89   4c 12   '4d7m(C#D ' ' T#s(^ 4  ro   r+  c                   h    \ rS rSrSr\S\\   4S j5       r\R                  S\\   4S j5       rSr
g)	
_WorldMetai  za
Meta class of ``group`` and ``GroupMember``.

Allows them to have the class property ``WORLD``.
rg   c                 "    [         R                  $ r   _worldr  )r   s    rm   WORLD_WorldMeta.WORLD  s       ro   r\  c                     U[         l        g r   re  )r   r\  s     rm   rg  rh    s
    ro   r   N)r   rj   r   r   r   r_  r   r   rg  r`  r   r   ro   rm   rc  rc    sK     !h|, ! ! \\x-  ro   rc  c                       \ rS rSrSrSrg)rH   i  zGroup class. Placeholder.r   N)r   rj   r   r   r   r   r   ro   rm   rH   rH     s    #ro   rH   )	metaclassc                       \ rS rSrSrSrSrg)r0   i  zGroup member class.ir   N)r   rj   r   r   r   NON_GROUP_MEMBERr   r   ro   rm   r0   r0     s    ro   r0   r   c                     U [         R                  :X  a;  [        [        [        5      (       d  [
        R                  " S5        [        $ [        $ [        $ )NzSAttempted to get default timeout for nccl backend, but NCCL support is not compiled)r.   r   r   r*   r   r   r   r+   r   s    rm   _get_default_timeoutrp    sA    ',,19== MMe &%&&!!ro   timeoutc                 J    [        U [        5      (       d  [        SU  35      eg )Nz@Expected timeout argument to be of type datetime.timedelta, got )r   r   	TypeErrorrq  s    rm   _check_valid_timeoutru    s+    gy))NwiX
 	
 *ro   _default_pg_init_methodstore_based_barrier_keyc                    U =(       d
    [        5       n [        U [        5      (       dQ  [        R                  " S[        U 5       S35        [        U [        5      (       a  g[        S[        U 5       S35      e U R                  n[        U5      S:X  a  US   R
                  $ [        U5      S:X  a  g[        R                  " S5      U;   a  gUS   R
                  $ )a  
.. 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   rl   rs   r   _device_typesr   r   r   )rH   r   s     rm   _get_object_coll_devicer~     s    . )')Ee\**&tE{m 4. .	
 e-..CDK=PQRSS
 !!G
7|qqz	W	 	e		'  qzro   c                    [         R                  " S5        U =(       d
    [        5       n [        U [        5      (       d=  [         R                  " S[        U 5       S3[        SS9  [        R                  " S5      $  U R                  n[        U5      S:X  a  US   $ [        U5      S:X  a  [        S	5      e[        R                  " S5      U;   a  [        R                  " S5      nOUS   n[         R                  " S
U S35        U$ )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)`. ry  rz     )
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   rl   r   r   r   r}  r   RuntimeError)rH   r   rvs      rm   _get_pg_default_devicer  A  s   4 MM	( )')Ee\** 	&tE{m 4. . 	
 ||E""
 !!G
7|qqz	W	&
 	
 <<')e$BB==?D A00	

 	ro   c                 ~    U =(       d
    [        5       n U R                   Vs/ s H  oR                  PM     sn$ s  snf )z
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``.
)r|  r}  rl   )rH   r   s     rm   _device_capabilityr    s4     )')E&+&9&9:&9FKK&9:::s   :
   secondsc                    [          SU 3nUR                  US5        [        R                  SX`5        UnUR                  US5      nU S3n	X:X  a  UR	                  U	S5        [        U[        SUS-  -   S	95      n[        R                  " 5       n
  UR                  U	/U5         [        R                  SU UU5        g! [         a  nUR                  US5      n[        R                  S
[        R                  " 5       U
-
  U UUUUU5        [        [        R                  " 5       U
-
  S	9U:  a  [        SU  SU SU SU SU SU S35      e SnAOSnAff = fM  )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1r  i  r  zWaiting 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_countrq  logging_interval	store_key
world_sizeworker_countlast_worker_keystartes               rm   _store_based_barrierr    s     ..a
|<I	IIi
LL6	H "J99Y*L"<0O!		/3' +YrJQUDU?U-VWIIKE
	 JJ(*:;. KKJ	-  	 99Y2LLL`		e#
 $))+"57'A$ 6YK}ZL Q**6z''RSQTTUW  B	 s   C 
EBEEc                 0    U c  gU [         R                  :H  $ )z<Check if the current process's rank is not in a given group.F)r0   rm  rH   s    rm   _rank_not_in_groupr    s    }K0000ro   c                     [         R                  c  SO[         R                  R                  5       n[        R                  " SU  SU S35        g )NzRunning z on global rank z* which does not belong to the given group.)r0   rg  r  r   r   )r  global_ranks     rm   _warn_not_in_groupr    sG    #))1"{7H7H7M7M7OKMM
7)+K= 9% 	%ro   r  c                     U [         R                  L a  U$ U [        R                  ;  a  [	        SU  S35      e[        R                  U    nX;  a  [	        SU SU  35      eX!   $ )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 )r0   rg  rf  r=  r   )rH   r  group_rankss      rm   r_   r_     sz     !!!F)))UGgh
 	
 ''.K%<}4J5'RSS##ro   
group_rankc                     U [         R                  L a  U$ U [        R                  ;  a  [	        SU  S35      e[        R                  U    R                  5        H  u  p#X1:X  d  M  Us  $    [	        SU SU  35      e)a{  
Translate a group rank into a global rank.

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

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

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

N.B. calling this function on the default process group returns identity
r  r  zGroup rank r  )r0   rg  rf  r=  r   r   )rH   r  r  grp_ranks       rm   r`   r`     s     !!!F)))UGgh
 	
 !//6<<>!K ? {:,.DUGL
MMro   z`torch.distributed.distributed_c10d._get_global_rank` is deprecated, please use `torch.distributed.distributed_c10d.get_global_rank` insteadr   c                     [        X5      $ )z1Use get_global_rank as this method is deprecated.)r`   )rH   r  s     rm   _get_global_rankr  *  s     5''ro   c                 V    [        [        R                  U    R                  5       5      $ )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   rf  r=  rX  r  s    rm   ra   ra   4  s#     %%e,11344ro   c                     U [         R                  L d  U c  [        5       nUR                  5       $ U R                  5       $ )zGet a given group's world size.)r0   rg  r|  sizerH   r  s     rm   rW  rW  A  s5    !!!U]')
  ::<ro   r  c                 8    [        U 5      nUR                  5       $ r   )r   r  )r  rH   s     rm   _get_group_size_by_namer  I  s    ":.E::<ro   rU  r   c                 L    [        X5      nUc  [        S5      eUR                  $ N )_find_pg_by_ranks_and_tagr   r  )rU  r   rH   s      rm   $_resolve_group_name_by_ranks_and_tagr  N  s)     &c1E}nro   c                 x    [        U [        R                  5      (       d  [        SU S[	        U 5       S35      eg)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  rs  rl   )param
param_names     rm   r	  r	  W  sB    eU\\**?
| L5k])/
 	
 +ro   c                    [        U [        5      (       d  [        SU S[        U 5       S35      e[	        S U  5       5      (       d8  [        SU S[        U 5       SU  Vs/ s H  n[        U5      PM     sn S35      egs  snf )z=Check that the parameter ``param_name`` is a list of tensors.r  z2` of type List[torch.Tensor]
             but got r  c              3   V   #    U  H  n[        U[        R                  5      v   M!     g 7fr   )r   r   r  )r   ps     rm   r   %_check_tensor_list.<locals>.<genexpr>g  s     <eAu||,,es   ')z with elements of type r{  N)r   r   rs  rl   all)r  r  r  s      rm   _check_tensor_listr  `  s    eT""?
| L5k])/
 	
 <e<<<?
| L5k]"9E:REq47E:R9SSTX
 	
 = ;Ss   !Bc                 F    U b  U [         R                  L a
  [        5       n U $ r   )r0   rg  r|  r  s    rm   r  r  n  s!    }!2!22"$Lro   r  c                     Ub  Ub  [        S5      e[        X5      nOUc  [        S5      e[        X5      nU(       a  U$ U$ )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.
z-Can't specify both group_rank and global_rankz&Must specify global_rank or group_rank)r   r`   r_   )rH   r  r  r  s       rm   r  r  t  sO     "LMM%e8EFF#E7
';7Z7ro   r  	rank_typec                 P    U R                  5       U:X  a  [        SU SU S35      eg )NzInvalid z rank: z@ rank should not be the same as the rank of the current process.)r  r   )rH   r  r  s      rm   _check_not_self_rankr    s9    zz|tyk 4/ /
 	
 ro   c                 6    [        U [        5      (       a  U $ U 4$ r   )r   r   )objs    rm   _as_iterabler    s    S$''33cV3ro   c                  `   S n[         R                  R                  [        [        U 5      5       H{  nUR
                  nUR                  (       a4  U[        R                  :X  a  [        R                  O[        R                  nUc  UnM[  X:w  d  Mb  [        SU SUR
                   35      e   g )Nz4Invalid usage of tensors with different dtypesFound z and  )	itertoolschainfrom_iterablemapr  r  
is_complexr   	complex64float32
complex128r   )tensors
last_dtyper   tensor_dtypes       rm   _ensure_all_tensors_same_dtyper    s    J////L'0JK||""!-!@eFVFV  %J) 'Lv||n>  Lro   c                 :    U [         [        4;  a  [        S5      eg)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)rS   rJ   r   )r   s    rm   r  r    s%    	%+
 	
  ro   c                    ^ [        U [        5      (       a  [        S U  5       5      (       d  [        S5      eU S   R                  m[        U4S jU  5       5      (       d  [        S5      eg)zl
Check that the ``p2p_op_list`` is a list of P2POp instances.

Also, check that all ops use the same group.
c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   )r   r1   )r   p2p_ops     rm   r   %_check_p2p_op_list.<locals>.<genexpr>  s      40;f
65!!s   zZInvalid ``p2p_op_list``. Each op is expected to to be of type ``torch.distributed.P2POp``.r   c              3   B   >#    U  H  nTUR                   :H  v   M     g 7fr   r  )r   r  rH   s     rm   r   r    s     ?;u$;s   z#All ops need to use the same group.N)r   r   r  r   rH   )p2p_op_listrH   s    @rm   _check_p2p_op_listr    ss     k4(( 40;4 1 1 9
 	

 N  E?;???>?? @ro   c                      [         $ )z&Check if the MPI backend is available.)_MPI_AVAILABLEr   ro   rm   rM   rM         ro   c                      [         $ )z'Check if the NCCL backend is available.)_NCCL_AVAILABLEr   ro   rm   rO   rO         ro   c                      [         $ )z'Check if the Gloo backend is available.)_GLOO_AVAILABLEr   ro   rm   rK   rK     r  ro   c                      [         $ )z&Check if the UCC backend is available.)_UCC_AVAILABLEr   ro   rm   rQ   rQ     r  ro   c                      [         $ )z'Check if the XCCL backend is available.)_XCCL_AVAILABLEr   ro   rm   rR   rR     r  ro   c                     [        [        R                  SU R                  5        S3S5      nU(       a  U" 5       $ U R                  5       [        R
                  ;   $ )a&  
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_funcs     rm   rN   rN     sL     U..#gmmo5Fj0QSWXN==?g2222ro   c                  &    [         R                  SL$ )z8Check if the default process group has been initialized.N)r0   rg  r   ro   rm   rL   rL     s    D((ro   c                  2    [         R                  " S5      SL$ )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getenvr   ro   rm   rP   rP     s     99*+477ro   c                  B    [        [        R                  " SS5      5      $ )NTORCH_DIST_INIT_BARRIER0)r  r  r  r   ro   rm   _is_barrier_after_initr    s    
 ryy2C899ro   c                      [        5       (       d  [        S5      e[        (       a  [        [        R
                  5      $ [        R
                  $ )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.)rL   r   r   r&   r0   rg  r   ro   rm   r|  r|    sA    ;
 	
 }))**   ro   c                  x    [        5       (       d  [        S5      e[        5       n [        R                  U    u  pU$ )z4Get the default store created by init_process_group.r  )rL   r   r|  rf  r7  )r  _default_stores      rm   _get_default_storer    s>    ;
 	
 $%J}}Z0Aro   c                     U [         l        U b$  U [        R                  :w  a  U R	                  5       OSn[
        R                  R                  R                  U5        g )Nr  )	rf  r  r0   rm  r  r   r   _distributed_c10d_set_global_rank)r\  r  s     rm   _update_default_pgr  (  sA    F21M1M+M2779SUD	HH//5ro   c                     U =(       d
    [        5       n[        U5      (       a  [        S5      e[        R                  R                  U5      n[        [        U5      5      $ )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   rf  r@  getr   r&   )rH   r\  rT  s      rm   rB   rB   .  sO     
	&$&B":;;--11"5Nx'((ro   c                     U =(       d
    [        5       n[        U5      (       a  [        S5      eU[        R                  ;   a  [        R                  U   OSn[        [        U5      S   5      $ )aa  
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   rf  r7  r.   r&   )rH   r\  pg_stores      rm   rC   rC   B  sY     
	&$&B":;;$&&--$7v}}R TH8H%a())ro   r   c                     [        U [        R                  5      (       a  U R                  nO [        R                  " U 5      R                  n[        R
                  R                  U5      nUc  [        SU  35      eU$ )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.

z,Default backend not registered for device : )r   r   r   rl   r.   r   r
  r   )r   
device_strr   s      rm   rD   rD   V  se     &%,,''[[
\\&)..
0044Z@GGxPQQNro   r\  c                     S n U R                  [        R                  " S5      5      n[	        5       (       a!  [        U[        5      (       a  UR                  $ g! [         a     N=f = f)Nr   r  )_get_backendr   r   r  rO   r   rq   uid)r\  r   s     rm   _get_process_group_uidr  m  s\    G//%,,v"67 z'3CDD{{	  s   %A 
A'&A'c                     U =(       d
    [        5       n[        U5      UR                  [        U5      [	        U5      [        U5      S.$ )z:
Return the pg configuration of the given process group.

)rR  rS  rT  pg_sizerU  )r|  _get_process_group_namerY  rB   rW  ra   )rH   r\  s     rm   _get_pg_configr  x  sC    
 
	&$&B*2.==,R0"2&(, ro   c                  ~    [         R                  R                  5        V s/ s H  n [        U 5      PM     nn U$ s  sn f )z9
Return the pg configuration of all the process groups.

)rf  r7  rX  r  )r\  rZ  s     rm   _get_all_pg_configsr    s@     &,]]%7%7%9)%9rr%9  ) )s   :c                  "    [         R                  $ )z'
Return the number of process groups.

)rf  rE  r   ro   rm   rG   rG     s    
 ro   fallback_rankc                     S[         R                  ;   a  [        [         R                  S   5      $ U b  [        U 5      $ [        S5      e)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_RANKzLOCAL_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  s    rm   re   re     sH      rzz!2::l+,,		"=!!
	k ro   c                 Z   [         R                  R                  5        H  nUR                  n[        R
                  " S5      U;   d  M+  UR                  [        R
                  " S5      5      n[        5       (       d  Ma  [        U[        5      (       d  Mx  UR                  U 5        M     g)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)rf  r7  rX  r}  r   r   r  rO   r   rq   _add_ephemeral_timeout)rq  r\  r   r   s       rm   "_add_ephemeral_timeout_for_all_pgsr     sr    & mm  """<<7*ooell6&:;G ""z';K'L'L..w7 #ro   c                 h   Uc
  [        5       n[        U5      (       a  [        S5      e[        U[        5      (       d   eUR
                  n[        5       n[        R                  " S5      U;   aZ  [        5       (       aK  UR                  [        R                  " S5      5      n[        U[        5      (       a  UR                  U5        [        R                  " S5      U;   a  UR                  [        R                  " S5      5      n[        5       (       a'  [        U[        5      (       a  UR                  U5        O5[        5       (       a&  [        U[        5      (       a  UR                  U5        [        U5      S:X  a  [         R"                  " S5        U H  nUR%                  U 5        M     g)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}  r  r   r   rK   r  rs   r  rO   rq   r   r   r   _set_default_timeout)rq  rH   r   backendsr   s        rm   _set_pg_timeoutr$    s9   ( }"$%  :;;e\****!!GuH||Eg%*;*=*=$$U\\%%89g/00LL!||Fw&$$U\\&%9::g7G#H#HLL!  Z9I%J%JLL!
8}RS$$W- ro   init_methodr  r  
pg_options	device_idc	                   ^^ [         R                  b  [        S5      e[        5         S[        R
                  ;   a(  [        R                  R                  R                  5         Ub
  Ub   S5       eUb  US:  d   S5       eUS:  d   S5       eOUc  SnU c,  Ub)  [        R                  R                  UR                  5      n U c  S	n [        U 5      n Uc  [        U 5      n[        U5         [!        / S
S9nU [        R"                  :X  aO  US:w  d  US:w  a  [$        R&                  " SU SU S35        [)        SS/ U [+        5       UUSS9u  p[-        U	5        OaUc?  [/        [1        U5      XCUS9n[3        U5      u  pTnUR5                  U5        [7        SU5      n[)        UU/ U UUUUUSS9
u  p[-        U	5        [9        [         R                  R;                  5       5       Vs0 s H  nX_M     sn[<        R>                  [         R                  '   [<        R@                  [1        [         R                  5         S   q!Uq"[        RF                  mS[I        5        S3mUU4S jnU[        l#        [K        5       S:X  aB  [L        RO                  S5        U [        R"                  :X  a  [Q        5         g[S        XEXcU5        ggs  snf )ag  
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_namer  zFor MPI backend, world_size (z) and rank (z9) are ignored since they are assigned by the MPI runtime.r  )rq  rY  rt  )backend_optionsrq  r'  rY  z[rank]c                    > [         R                  n[        R                  " 5       =[         l        n T" U 6   U[         l        UR	                  5       nSR                  U4S jUR                  S5       5       5      n[         R                  R                  U5        [         R                  R                  5         g ! U[         l        f = f)N
c              3   @   >#    U  H  oS :w  a  T SU 3OS v   M     g7f)r  z: Nr   )r   r  excepthook_prefixs     rm   r   Finit_process_group.<locals>._distributed_excepthook.<locals>.<genexpr>  s*      
DSq7 !A3':Os   )	sysstderrioStringIOgetvaluer   r   writeflush)args
old_stderrbufmsgr0  old_hooks       rm   _distributed_excepthook3init_process_group.<locals>._distributed_excepthook  s    ZZ
;;=(
S	$dO#CJllnii 
DGIIdO
 
 	



 $CJs   B; ;Cr'   VPerforming barrier after ProcessGroup initialization since TORCH_DIST_INIT_BARRIER = 1)*r0   rg  r   r"   r2  modulesr   _dynamotrace_rulesclear_lru_cacher.   r   r
  rl   rp  ru  _process_group_namer   r   r   _new_process_group_helperr    r  r-   r&   nextset_timeoutr   ranger  rf  r=  r7  r)  rv  
excepthookrE   r  r   r  r9   r  )r   r%  rq  r  r  r  r  r&  r'  r  r  rendezvous_iteratorir>  r0  r=  s                 @@rm   rI   rI     s   J $PQQ/1 #++%!!113M{2 43 A~KKK~qyDDDy		
 90 4488H
  gG&w/!
 %R?J'++trzMM/
|<v N  2G#	

 	:& =",%t# '++>&?#Eg&  e4E1&#

 	:& {((--/000A 	
00F+++, }}Xk&7&789!<H)~~H
|1- -CN1$ 	*	
 gkk!I !jgN' %50s   %Kc                    S nU R                   (       a  U R                  U R                   5      nO9U [        R                  L a&   U R                  [        R
                  " S5      5      nU(       a  UR                  (       d  g [        (       aC  [        U[        5      (       a.  UR                  n[        (       a  [        U[        5      (       a  M.  U$ ! [         a     Nuf = f)Nr   )bound_device_idr  rf  r  r   r   r  supports_splittingr  r   rr   
wrapped_pg)r\  
split_froms     rm   _get_split_sourcerR    s    J	__R%7%78
	v  	 	f)=>J
 Z:: /j5IJJ**
 /j5IJJ   		s   %C 
CCc           
         U[         R                  R                  5       ;   a  [        S5      eU	b(  U	R                  b  U	R
                  S:X  a  [        S5      e[        U5        US;  a*  [        X5      nU(       a  [         R                  U   u  pX4$ U
c  SOU
n
[        U5      S:H  n[        5       (       a-  [        5       R                  (       a  [        [        5       5      nOSnU(       dZ  [        5       R                  5       nUU;  a<  U(       a#  UR                  [        5       R                  5        [         R"                  S4$ [%        U S3U5      n['        UUU 5      n[)        U5      nS	[+        U5      ;  a  S
[+        U5      ;  a  U[,        R.                  ;   d
   SU 35       eU[,        R0                  :X  a  [,        R2                  UR5                  5       R                  5       ;   a+  UR7                  [&        R8                  R2                  5        GOiUR7                  [&        R8                  R:                  5        GO>UR7                  [,        R.                  U   5        GO[,        R2                  UR<                  R                  5       ;   a*  UR7                  [&        R8                  R2                  5        O[,        R>                  RA                  5       (       ax  [C        [E        [,        R>                  RA                  5       5      5      nUUR<                  R                  5       ;   a)  UR7                  [&        R8                  RF                  5        O)UR7                  [&        R8                  R:                  5        U	(       a  U	Ul        UR5                  5       RI                  5        GH~  u  nn[%        U S3U5      nU[,        RJ                  :X  a  [M        5       (       d  [O        S5      e[P        RR                  " U5      n[&        R8                  RJ                  nU(       d  [         R"                  S4s  $ UR                  5       S:X  aN  URU                  5       S:X  a:  ['        UUR                  5       URU                  5       5      nUR7                  U5        GOU[,        R:                  :X  a'  [W        UXUS9n[&        R8                  R:                  nGOmU[,        R2                  :X  a  [Y        5       (       d  [O        S5      eUbM  [[        U[\        R^                  5      (       d   S5       eUR`                  U:w  a  [b        Rd                  " S5        O[\        R^                  " 5       nSUl3        Xvl0        U(       a  Xl4        [k        U5      Ul6        X&l7        XVl8        []        UXU5      n[&        R8                  R2                  nGO{U[,        Rr                  :X  a6  [u        5       (       a'  [w        UXUS9n[&        R8                  Rr                  nGO1U[,        Rx                  :X  aA  [{        5       (       d  [O        S5      e[}        UX5      n[&        R8                  Rx                  nOUR                  5       [,        R>                  ;   d   SUR                  5        35       e[,        R>                  UR                  5          nUR                  nUR                  n[&        R8                  RF                  nU(       d  U" UXU5      nO=[        5       nUUlC        UUlD        U UlE        UUlF        UUlG        UUl7        U" UU5      nU[,        R:                  :X  a(  [[        U[V        5      (       d   eUR                  5         O;U[,        R2                  :X  a'  [[        U[\        5      (       d   eUR                  5         [        [        U5      [&        5      (       a  Un  GONU[,        R:                  [,        R2                  [,        Rr                  4;   d"  UR                  5       [,        R>                  ;   aK  [        5       [        R                  :X  a/  [        (       d  [        R                  S5        O[        UUUUU US9n[        [        UR5                  5       R                  5       5      5      S:X  aN  UR5                  5       RA                  5        H*  nUR                  [        R                  " U5      UU5        M,       O,UR                  [        R                  " U5      UU5        GM     Uc   eU
c   eUR                  U5        UR                  U
5        U	(       aB  UR                  U	5      R                  (       a"  UR                  U	5      nUR                  U	5        X=4[         R                  U'   U[         R                  U'   [        UU5        [+        U5      [         R                  U'   US;   a5  SU 3n[         R                  R                  S/ 5      R                  U5        OSU 3n[         R                  R                  U/ 5      R                  U5        U[         R                  U'   UU4$ )aH  
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 indexr  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.r  rt  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.)rP  store_prefixr  r  r  rq  r'   ptd:r  user:)`rf  r:  valuesr   indexrl   ru  r  r7  r   rL   r|  rN  rR  r  perform_nocolor_splitr0   rm  r   r   r/   r   r.   r   r   r   r   _set_default_backendr   r   r   r   rX  rG  iterr   r   r   rM   r  rp   creater  rs   rO   r   rq   Options_timeoutr   r   is_high_priority_streamrQ  _process_group_colorsplit_colorglobal_ranks_in_groupr  r   rQ   rt   r   rR   ru   r   r   r   r   r  r  rV  rq  group_id_set_sequence_number_for_group
issubclassr   r   DETAILr  r   r   _create_process_group_wrapperr  _register_backendr   r   _set_group_name_set_group_descr  rO  eager_connect_single_devicer   r@  rI  
setdefaultr   rL  )rV  r  rc  r   r  r  r+  rq  pg_tagr'  rY  existing_groupr  prefix_storeis_default_grouprQ  r  r\  rT  custom_backendr   r   backend_prefix_storebackend_classbackend_typebackend_pluginr   r   dist_backend_optseager_backends                                 rm   rF  rF  	  s   0 V__++--9
 	

 )//"9Y^^u=TY
 	

 !Z26Q$mmN;OA!// * 2
J 01Q6 .0@@&'9';<

 (*//133 001C1E1U1UV//55*Q/7L $B
 #7+N
#g,3c'l#:'222U6KG94UU2g''' ||~DDFMMOO''(@(@(E(EF''(@(@(E(EF##G$<$<W$EF <<><<CCEE##L$<$<$A$AB""$$!$w'7'7'<'<'>"?@N!B!B!I!I!KK''(@(@(G(GH##L$<$<$A$AB&-DDFLLN  +fXQ<F'++%#%%"@ 
 ,223HIM'3377L "33T99wwyB2779?!(!&&(!&&(
 ''5GLL( -$jgM (3388LGLL($&&"#STT*!/3C3K3KLL ^L #++w6MM_ #3":":"<:?7'.$-7*.B)/+ 5J1)3&,$joM (3388LGKK',<,>,>
 ,$jgM (3377LGLL($&&"#STT,$jM (3388L$$&'*:*:: ,[->->-@,AB: %--k.?.?.ABN'22J)66L'33::L *(*'! %?$@!*>!'/9!,/9!,,3!)-7!*:O!7 *+<o N ',,&m-=>>>>88:GLL(m-=>>>>88:
 d=)<88B GLL',,DD  "g&6&66  J$5$55&KKR %B#0%/2'#- '%M s>88:AACDEJ(??AFFH$$U\\&%9<W I 
U\\&1<Om  Or !!!!!!z"z"R__Y/BB	211)< !/FMM"$FOOBJ+#&~#6FR 
|$$$R,33B7!
  ,33B7!FR|ro   c                 D   U [         R                  :X  a  gU c  [         R                  nOU nUc   e[        R                  R                  US5      c  [        S5      e[        U5      [        :X  a%  UR                  5       (       a  UR                  5         U b  U [         R                  :X  Ga$  [        [        R                  S SS9 H  nUR                  5         M     [        S5        [        R                  R                  5         [        R                  R                  5         [        R                   R                  5         [        R"                  R                  5         [        R$                  R                  5         [        R&                  R                  5         [        R(                  R                  5         [+        5         S[        l        gUR                  5         [        R                  U	 [        R                  U	 [        R                   U	 [        R"                  U	 U[        R(                  R/                  5       ;   a'  [0        R2                  " S5        [        R(                  U	 [        R$                  R                  U5      n[        R$                  U	 Ub[   [        R&                  U   R5                  U5        UR7                  S5      (       a"  [        R&                  S	   R5                  U5        [;        UR<                  5        g! [8         a     N"f = f)
a]  
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                 (    [         R                  U    $ r   rf  r:  xs    rm   <lambda>'destroy_process_group.<locals>.<lambda>U      6??1+=ro   Tr   reverser   zfSome coalesced collectives haven't been launched when ProcessGroup is destroyed. They will be cleaned.rV  r  )r0   rm  rg  rf  r7  r
  r   rl   r   
_has_hooks_wait_for_pending_workssortedr:  shutdownr  clearr=  r@  rL  rI  rO  r   rE  rX  r   r   remove
startswith	Exceptionr   r  )rH   r\  pg_to_shutdownr   s       rm   r?   r?   .  sS    ,,,}>>}}T"*:;; Bx<BMMOO
""$}!2!22 %OO!=t
N ##%

 	4 ##%  &&( !  &&(&( 
MM"OOB!!"%$$R())..00MMC ((,""2&R ?!!#&--b1>>&))%%b)004 	""--0  s   "AL 
LLc                    U [         R                  :X  a  gU =(       d    [         R                  nUc   e[        R                  R                  US5      c  [        S5      e UR                  [        R                  " S5      5      nU b  U [         R                  :X  Ga  [        5       (       a%  [        U[        5      (       a  UR                  5         [        [        R                   S SS9 H  nUR#                  5         M     [        5       (       a%  [        U[        5      (       a  UR%                  5         ['        S5        [        R                  R)                  5         [        R                   R)                  5         [        R*                  R)                  5         [        R,                  R)                  5         [        R.                  R)                  5         [        R0                  R)                  5         [        R2                  R)                  5         [5        5         S[        l        gUR#                  5         [        R                  U	 [        R                   U	 [        R*                  U	 [        R,                  U	 U[        R2                  R9                  5       ;   a'  [:        R<                  " S5        [        R2                  U	 [        R.                  R                  U5      n[        R.                  U	 Ub[   [        R0                  U   R?                  U5        URA                  S	5      (       a"  [        R0                  S
   R?                  U5        [E        URF                  5        g! [         a    Sn GNf = f! [B         a     N5f = f)a  
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                 (    [         R                  U    $ r   r{  r|  s    rm   r~  &_abort_process_group.<locals>.<lambda>  r  ro   Tr  r   zdSome coalesced collectives haven't been launched when ProcessGroup is aborted. They will be cleaned.rV  r  )$r0   rm  rg  rf  r7  r
  r   r  r   r   r  rO   r   rq   _group_startr  r:  abort
_group_endr  r  r=  r@  rL  rI  rO  r   rE  rX  r   r   r  r  r  r   r  )rH   r\  r   pg_to_abortr   s        rm   _abort_process_groupr    s   $ ,,,		#+##B>>}}T"*QRR//%,,v"67 }!2!22
 :g7G#H#H  "!OO!=t
K 
 :g7G#H#H 4 ##%  &&( !  &&(&( 

MM"OOB!!"%$$R())..00MMA ((,""2&R ?!!#&--b1>>&))%%b)004 	""--0u  p  s%   !%M+ ;AM> +M;:M;>
N
Nc                     [        U 5      (       a  g[        5       nU b  U [        R                  L a  UR	                  5       $ [        XR	                  5       5      $ )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

r  )r  r|  r0   rg  r  r_   r  s     rm   rE   rE     sK    " %  #%J}!2!22  %!233ro   c                 :    [        U 5      (       a  g[        U 5      $ )a  
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

r  )r  rW  r  s    rm   rF   rF     s     %  5!!ro   r   dst	group_dstc                     [        U5      n[        X!U5      n[        U S5        [        U5      (       a  [	        S5        gU R                  5       (       a  [        R                  " U 5      n UR                  U /XC5      $ )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   rS   N)	r  r  r	  r  r  r  r   view_as_realr]   )r   r  rH   r   r  s        rm   rS   rS   	  sm    @ $E*E(Y?I*%  7###F+::vh	//ro   src	group_srcc                 .   [        U S5        [        U5      (       a  [        S5        gU R                  5       (       a  [        R
                  " U 5      n [        U5      nUc  Uc  UR                  U /U5      $ [        X!U5      nUR                  U /XC5      $ )a  
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   rJ   N)
r	  r  r  r  r   r  r  recv_anysourcer  rX   )r   r  rH   r   r  s        rm   rJ   rJ   :	  s    : *%  7###F+#E*E
{y(##VHc22,UC	zz6(I33ro   c                     [        U5      n[        X!U5      n[        X$S5        [        XX4S9nUb  UR	                  5         gg)af  
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)rH   r   r  N)r  r  r  rS   r  )r   r  rH   r   r  works         rm   r]   r]   g	  sD    0 $E*E(Y?I=9#CD		 ro   c                     [        XX#US9nUc  gUR                  5         Uc5  Uc  UR                  5       n[        U5      n[	        X$S5        [        X$5      nU$ )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  rH   r   r  r  source)rJ   r  _source_rankr  r  r`   )r   r  rH   r   r  r  s         rm   rX   rX   	  s_    6 )LD|IIK
{))+I'.Ux8e/Jro   c                       \ rS rSrS rSrg)_IllegalWorki	  c                 .    US;   a  [        SU S35      eg )N)
is_success	exceptionr  source_rankr  resultsynchronizezIllegal to call z on IllegalWork objectr   )r   r   s     rm   r   _IllegalWork.__getattribute__	  s,     
 
 /v5KLMM
ro   r   N)r   rj   r   r   r   r   r   ro   rm   r  r  	  s    
Nro   r  c                   2    \ rS rSrSS jrS\4S jrS rSrg)	_CoalescingManageri	  Nc                     / U l         g r   worksr   s    rm   r   _CoalescingManager.__init__	  s	    !#
ro   r  c                 J    U(       a  U R                   R                  U5        g g r   )r  r   r   r  s     rm   r   _CoalescingManager.append	  s    JJd# ro   c                 J    U R                    H  nUR                  5         M     g r   )r  r  r  s     rm   r  _CoalescingManager.wait	  s    JJDIIK ro   r  r   )	r   rj   r   r   r   r!   r   r  r   r   ro   rm   r  r  	  s    $$4 $ro   r  	async_opsc              #     #    U =(       d
    [        5       n [        R                  R                  U / 5      nU(       a  [	        S5      eU(       a  U R                  U5        [        5       nUv   [        R                  R                  U 5      nU(       Gax  US   R                  nU[        :X  aU  U Vs/ s H  ofR                  PM     nn[        5       n[        US   R                  5      Ul        U R                  Xx5      n	GO
U[         :X  a^  / n
/ nU HB  nU
R#                  UR                  5        UR#                  [        UR$                  5      5        MD     U R'                  X5      n	OU[(        :X  a  / n
/ nU HB  nU
R#                  UR                  5        UR#                  [        UR$                  5      5        MD     [+        5       n[        US   R                  5      Ul        U R-                  XU5      n	O[/        SU SU S35      eU(       a  U R1                  U5      n	U(       a  UR#                  W	5        gW	R3                  5         gs  snf 7f)a  
Context manager used to coalesce collectives or P2P operations when possible.

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

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

.. warning::
   :func:`_coalescing_manager` currently do not support coalescing
   all-reduces with different reduce operators, e.g.  `ReduceOp.SUM` mixed
   with `ReduceOp.PRODUCT`.
z=ProcessGroup has non-empty op list at the start of coalescingr   z<Coalescing manager does not support fast-path coalescing of z, yet zA is still recorded in op list. This is an internal error of c10d.N)r|  rf  rO  rm  r   _start_coalescingr  popr   r5   r   r   r&   r  rw   allreduce_coalescedrc   r   r  allgather_into_tensor_coalescedrd   r   reduce_scatter_tensor_coalescedAssertionError_end_coalescingr  )rH   r   r  op_listcmop0r   r  all_reduce_optsr  inputsoutputsreduce_optss                rm   _coalescing_managerr  	  s    B )')E&&11%<GK
 	
 '		B
H&&**51G ajmm*+237Ryy7G379O'/
0@0@'AO$,,WFD**FGbii(x67  88ID))FGbii(x67  /0K#+GAJ,<,<#=K 88+VD Nse Te\^ 
 $$V,
		$		C 4s   B0I2IFIr  c           	         [        U 5        U S   R                  nUc
  [        5       nU S   R                  R                  nS[
        S[        [        [        4   4S jn[        U5      [        :X  a  UR                  U5      R                  (       ab  [        XSS9 nU  H=  nUR                  " UR                  4UR                  UR                  S.U" U5      D6  M?     SSS5        UR                   $ / nU  HW  nUR                  " UR                  4UR                  UR                  S.U" U5      D6nU(       d  MF  UR#                  U5        MY     U$ ! , (       d  f       WR                   $ = f)	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   rg   c                 L    U R                   [        :X  a  SOSnXR                  0$ )Nr  r  )r   rS   r   )r   r   s     rm   
peer_kwarg%batch_isend_irecv.<locals>.peer_kwargS
  s     UUe^k]]##ro   T)r  )rH   r   )r  rH   r|  r   r   r1   r   r   r  rl   r   r  supports_coalescingr  r   r   r  r   )r  rH   r   r  r  r  reqsr  s           rm   r:   r:   #
  sM   T {#N  E}"$^""))F$u $c3h $ E{l"u'9'9&'A'U'U $?2%		MM ,,

 !(	 & @ xx !F99llJJ V$	D tD! " - @? xxs   AE
E.async_opc                    [        U5      n[        X!USS9n[        U S5        [        U5      (       a  [	        S5        g[        5       nXEl        SUl        X5l        UR                  U /U5      nU(       a  U$ UR                  5         g)a$  
Broadcasts the tensor to the whole group.

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

Args:
    tensor (Tensor): Data to be sent if ``src`` is the rank of current
        process, and tensor to be used to save received data otherwise.
    src (int): Source rank 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  r  r   rootRank
rootTensorasyncOpr;   r  )r   r  rH   r  r  optsr  s          rm   r;   r;   r
  sx    : $E*E(YeTI*%  ;'DMDOL??F8T*D		ro   c           	         U 4n[        U5      (       a  [        [        UU UUUS9$ [        U S5        [	        U5      (       a  [        S5        gU R                  5       (       a5  [        U5      (       d  [        SU S35      e[        R                  " U 5      n [        5       nXl        Uc
  [        5       nU[        R                  R!                  5       ;   aG  [#        [        U SUS5      n[        R                  U   R%                  U5        U(       a
  ['        5       $ gUR)                  U /U5      nU(       a  U$ UR+                  5         g)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   rH   r  r   r5   Nall_reduce does not support  on complex tensors)r%   r$   r5   r	  r  r  r  r^   r   r   r  r   rw   r|  rf  rO  rX  r  r   r  	allreducer  )r   r   rH   r  relevant_argsr  collr  s           rm   r5   r5   
  s%   l IM-(($
 	
 *%  <(##;B4?RSTT##F+DM}"$((--//z64T:  '..t4>!??F8T*D		ro   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                 R   [        U [        R                  5      (       a  U /n [        U S5        [	        U 5        [        U5      (       a  [        S5        g[        S U  5       5      (       a  [        U5      (       d  [        SU S35      eU  Vs/ s H/  oDR                  5       (       d  UO[        R                  " U5      PM1     n n[        5       nXl        U=(       d
    [        5       nUR                  X5      nU(       a  UR!                  5       $ UR#                  5         gs  snf )aN  
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   r6   Nc              3   @   #    U  H  oR                  5       v   M     g 7fr   )r  )r   ts     rm   r   'all_reduce_coalesced.<locals>.<genexpr>3  s     
+7a<<>>7s   r  r  )r   r   r  r  r  r  r  anyr^   r   r  r  r   rw   r|  r  
get_futurer  )r  r   rH   r  r  r  r  s          rm   r6   r6     s    R '5<<(()w)"7+%  12

+7
+++4DR4H4H7t;NOPPKRS7aqE,>,>q,AA7GS$&DM)')E$$W3D  		 Ts   6D$c                    [        U5      n[        X1USS9n[        U S5        [        U5      (       a  [	        S5        g[        5       nX&l        XVl        UR                  U /U5      nU(       a  U$ UR                  5         g)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   rY   N)
r  r  r	  r  r  r   rw   r  rY   r  )r   r  r   rH   r  r  r  r  s           rm   rY   rY   C  sq    @ $E*E(YeTI*%  8$?DMM<<$'D		ro   c                    [        S5      R                  5          [        R                  " 5       n[	        U5      R                  U 5        [        R                  R                  UR                  5       5      n[        R                  " U5      R                  U5      n[        5       [        R                  :X  a}  [        5       (       an  [!        U5      nU["        R$                  :X  aO  [        R&                  R(                  R+                  U/5      n[,        R/                  SUR1                  5       U5        [        R2                  " UR1                  5       /5      R                  U5      nXX4sS S S 5        $ ! , (       d  f       g = f)Nz+pytorch.wait_counter.c10d._object_to_tensorz)_object_to_tensor size: %s hash value: %s)r#   guardr4  BytesIO_picklerdumpr   ByteStorage_from_bufferr6  
ByteTensortor   r   rg  rO   rC   r.   r   r   r  _hash_tensorsr   warningnumel
LongTensor)	r  r   rH   fbyte_storagebyte_tensorr   hash
local_sizes	            rm   _object_to_tensorr  t  s   	C	D	J	J	LJJL((55ajjlC &&|477?
 1 116G6I6I!%(G',,&xx11??N?%%'
 %%{'8'8':&;<??G
&% 
M	L	Ls   EE55
Fc                 X   [        S5      R                  5          [        5       [        R                  :X  a}  [        5       (       an  [        U5      nU[        R                  :X  aO  [        R                  R                  R                  U /5      n[        R                  SU R                  5       U5        U R!                  5       n U R#                  5       R%                  5       S U n['        [(        R*                  " U5      5      R-                  5       sS S S 5        $ ! , (       d  f       g = f)Nz+pytorch.wait_counter.c10d._tensor_to_objectz)_tensor_to_object size: %s hash value: %s)r#   r  r   r   rg  rO   rC   r.   r   r   r   r  r  r   r  r  r   numpytobytes
_unpicklerr4  r  load)r   tensor_sizerH   r   r  r;  s         rm   _tensor_to_objectr    s    	C	D	J	J	L
 1 116G6I6I!%(G',,&xx11??I?QU lln$$&|4"**S/*//1 
M	L	Ls   C7D
D)c                    [        U5      (       a  [        S5        g[        U5      n[        XU5      u  pE[	        US9n[
        R                  " U[
        R                  US9n[        U5       Vs/ s H  oU   R                  SS9PM     n	n[        XUS9  [        [        U	5      R                  5       5      n
UR                  U
5        [
        R                  " X-  [
        R                   US9n[        U5       Vs/ s H  nXU-  XS-   -   PM     nn[        XUS9  [#        U5       H6  u  pUR%                  [
        R                   5      nX   n['        XU5      X'   M8     gs  snf s  snf )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}]
r4   Nr  r  r   r   dimr'   )r  r  r~  r  rF   r   zeroslongrI  	unsqueezer2   r  r  itemresize_emptyuint8	enumeraterl   r  )object_listr  rH   current_deviceinput_tensorr  rV  object_sizes_tensorrL  object_size_listmax_object_sizecoalesced_output_tensoroutput_tensorsr   r  s                  rm   r4   r4     sh   l %  ./,U3N0eLL  e,J++%**^ :?z9J9JAA((Q(/9J   59#./4467O)#kk$EKK z""A 	 ! 3oQ6OP"   ~59~.	U[[)&)*6F /%s   0E%=E*r  object_gather_listc                    [        U5      nUc  Uc  Sn[        X2USS9n[        U5      (       a  [        S5        g[	        5       n[        XeU5        [        U5      n[        XU5      u  p[        US9n
[        R                  " U
[        R                  US9n[        U
5       Vs/ s H  oU   R                  SS9PM     nn[        XUS9  [        [!        U5      R#                  5       5      nUR%                  U5        Xe:X  aK  [        R&                  " X-  [        R(                  US9n[        U
5       Vs/ s H  nXU-  XS	-   -   PM     nn[+        UXe:X  a  WOSUUS
9  Xe:w  a  gUc   S5       e[-        W5       H8  u  nnUR/                  [        R(                  5      nX   n[1        UUU5      X'   M:     gs  snf s  snf )aB
  
Gathers picklable objects from the whole group in a single process.

Similar to :func:`gather`, but Python objects can be passed in. Note that the
object must be picklable in order to be gathered.

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  rA   r  r  r   r'   )gather_listr  rH   z+Must provide object_gather_list on dst rank)r  r  r  r  rE   _validate_output_list_for_rankr~  r  rF   r   r  r  rI  r  r2   r  r  r  r  r  r  r@   r	  rl   r  )r  r  r  rH   r  
global_dstmy_global_rankr  r  r  rV  r  rL  r  r  r  r  r   r  s                      rm   rA   rA     s   H $E*E
{y()%itTJ%  ?+ ZN">?QR,U3N0eLL  e,J++%**^ :?z9J9JAA((Q(/9J   59#./4467O)#"'++(N#
 :&
& $a$7/QRU:ST& 	 

 &4&BN	 #)X+XX)~.	6U[[)&) 1&+u M /? 
s   $F96F>r
  c           
         [        U5      n[        X!U5      n[        X$S5        [        U5      (       a  [	        S5        gU=(       d    [        U5      n[        U  Vs/ s H  n[        XeU5      PM     sn6 u  px[        R                  " U5      n	[        XUS9  [        U5      S:X  a  US   n
O[        R                  " U5      n
[        XUS9  gs  snf )a	  
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<   N)r  rH   r'   r   )r  r  r  r  r  r~  zipr  r   catr]   r   )r
  r  rH   r   r  r  r  tensor_list	size_listr  object_tensors              rm   r<   r<   p  s    @ $E*E(Y?I=9%  -. =6u=N CN	O;C
C
7;	OK  ))I. 		?
 ;1#A		+.59 
Ps   Cc                 &   [        U5      (       a  [        S5        gU=(       d    [        U5      n[        R                  " [        U 5      [        R                  US9n[        XaX$S9n[        R                  " [        R                  " U5      R                  5       [        R                  US9n[        XX$S9n	Xy:X  d   S5       eSn
[        U5       H<  u  pXX-    nUR                  [        R                  5      nX-  n
[        XU5      X'   M>     U	$ )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=   r  r  )r  rH   r  z6Mismatch in return ranks for object sizes and objects.r   )r  r  r~  r   r  r   r  rX   sumr  r  r	  rl   r  )r
  r  rH   r   r  r  r  
rank_sizesr  rank_objectsoffsetrL  obj_sizeobj_views                 rm   r=   r=     s   ~ %  -. =6u=N++K

>
 )%UJ KK		%&++-kkM eQL% @% F !45 &*;<==-*8uE	 6
 ro   c           
      V   [        U5      nUc  Uc  Sn[        X!USS9n[        U5      (       a  [        S5        gU=(       d    [	        U5      n[        5       nXu:X  a<  [        U  Vs/ s H  n[        XU5      PM     sn6 u  p[        R                  " U
5      nO-[        R                  " [        U 5      [        R                  US9n[        XUS9  Xu:X  a,  [        W	5      S:X  a  U	S   nO][        R                  " U	5      nOF[        R                  " [        R                  " U5      R                  5       [        R                   US9n[        XUS9  SnXu:w  aL  [#        U5       H<  u  pXX-    nUR%                  [        R                   5      nX-  n['        UX5      X'   M>     ggs  snf )	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>   r  r  rH   r'   )r  r  r  r  r~  rE   r  r  r   r  r  r   r  r;   r  r  r  r	  rl   r  )r
  r  rH   r   r  
global_srcr  r  r  r  r  r  r  r"  rL  r#  r$  s                    rm   r>   r>   9  s   L $E*E
{y()%itTJ%  23 =6u=NZN#!$GRS{U;{S"
 $ii	2#kkEJJ~

 !?
 #{q 'NM!IIk2MII)*//1++!
 m59F#$%89KA$f.?@H}}U[[1HF.xIKN	 : $; Ts   'F&scatter_object_output_listscatter_object_input_listc           
      f   [        U5      nUc  Uc  Sn[        X2USS9n[        U5      (       a  [        S5        g[	        U [
        5      (       a  [        U 5      S:  a  [        S5      e[        5       n[        U5      nXe:X  an  Uc  [        S5      e[        U Vs/ s H  n[        XU5      PM     sn6 u  p[        U	5      [        U
5      p[        U
5      nU	 H  nUR                  U5        M     O%[        R                  " S/[        R                   US	9n[#        XUS
9  [        R$                  " UR'                  5       [        R(                  US	9n[+        UXe:w  a  SOW	UUS9  [        R                  " S/[        R                   US	9n[+        UXe:w  a  SOW
UUS9  [-        XU5      U S'   gs  snf )as
  
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_listr  r&  )scatter_listr  rH   )r  r  r  r  r   r   r   r   rE   r~  r  r  r  r  r   r   r  r;   r  r  r  r[   r  )r(  r)  r  rH   r  r'  r  	pg_devicer  r  tensor_sizesmax_tensor_sizer   output_tensorobj_tensor_sizes                  rm   r\   r\     s   @ $E*E
{y()%itTJ%  01 1488)*Q.[
 	
 ZN'.I#$,M  %( 54C "#%84%
! %)$5tL7I\ l+!FNN?+ "  ,,s%**YOoU; KKekk)M +9T{	 llA3ejjKO+9T|	 %6%q!Ks   F.c           	      (   U4n[        U5      (       a  [        [        UU UUUS9$ [        U S5        [	        US5        [        X5        [        U5      (       a  [        S5        gU  Vs/ s H/  oUR                  5       (       d  UO[        R                  " U5      PM1     n nUR                  5       (       d  UO[        R                  " U5      nU=(       d
    [        5       nUR                  U /U/5      nU(       a  U$ UR                  5         gs  snf )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

rH   r  r  r   r2   N)r%   r$   r2   r  r	  r  r  r  r  r   r  r|  	allgatherr  )r  r   rH   r  r  r  r  s          rm   r2   r2   9  s    ~ IM-(($
 	
 {M2*";7%  <( EPDOqU%7%7%::K   ",,..VE4F4Fv4NF)')E??K=6(3D		s   )6Dc           	         U4n[        U5      (       a  [        [        UU UUUS9$ [        US5        [        U S5        [	        U5      (       a  [        S5        gU R                  5       (       d  U O[        R                  " U 5      n UR                  5       (       d  UO[        R                  " U5      n[        5       nX5l
        U=(       d
    [        5       nU[        R                  R                  5       ;   aD  [        [        X5      n[        R                  U   R!                  U5        U(       a
  [#        5       $ gUR%                  XU5      nU(       a  U$ UR'                  5         g)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.

r2  r  r/  rc   N)r%   r$   rc   r	  r  r  r  r   r  r   r  r|  rf  rO  rX  r  r   r  _allgather_baser  )r/  r  rH   r  r  r  r  r  s           rm   rc   rc     s@   t "OM-(($"
 	
 ~68%  34 '')) 	.  &&(( 	-  DL)')E((--//-|K  '..t4>!  dCD		ro   z`torch.distributed._all_gather_base` is a private function and will be deprecated. Please use `torch.distributed.all_gather_into_tensor` instead.c                     [        XX#5      $ )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.

)rc   )r/  r  rH   r  s       rm   _all_gather_baser7    s    6 "-uOOro   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           
         [        U5      (       a  [        S5        g[        US5        [        U5        [	        U [
        5      (       d  [        S5      eU  H  n[        US5        [        U5        M     U  VVs/ s H@  nU Vs/ s H/  ofR                  5       (       d  UO[        R                  " U5      PM1     snPMB     n nnU Vs/ s H/  ofR                  5       (       d  UO[        R                  " U5      PM1     nnU=(       d
    [        5       nUR                  X5      nU(       a  UR                  5       $ UR                  5         gs  snf s  snnf s  snf )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.
r3   Ninput_tensor_listz?Invalid function argument: output_tensor_lists should be a listoutput_tensor_lists)r  r  r  r  r   r   rs  r  r   r  r|  allgather_coalescedr  r  )r:  r9  rH   r  output_tensor_listlr  r  s           rm   r3   r3   "  s?   n %  12(*=>"#45)400M
 	
 2-/DE&'9: 2 %$A FGGQ,,..e&8&8&;	;QG$  
 EVDUqU%7%7%::DU   )')E$$%8LD  		 	Hs   9
E6E9E6EEc                 X    X:X  a  U(       d  [        S5      eg U(       a  [        S5      eg )Nz?Argument ``gather_list`` must be specified on destination rank.zHArgument ``gather_list`` must NOT be specified on non-destination ranks.r  )my_rankr  r  s      rm   r  r  w  s9    
~Q   
V
 	
 
ro   r  c                    [        U S5        U(       a  [        US5        O/ n[        X5        [        U5      n[	        U5      (       a  [        S5        gUc  Uc  Sn[        X2USS9n[        X2USS9n[        5       n[        XvU5        Xg:X  a  U/O/ nU /n	[        5       n
XZl
        UR                  XU
5      nU(       a  U$ UR                  5         g)	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  r  r  rE   r  r   r  r@   r  )r   r  r  rH   r  r  r  r  r  input_tensorsr  r  s               rm   r@   r@     s    b * ;6"67#E*E%  8$
{y()%itTJ(YeTIZN">{K&0&Bk]NHM?DM<<t<D		ro   r+  c                    [        U S5        U(       a  [        US5        O/ n[        X5        [        U5      nUc  Uc  Sn[	        X2USS9n[	        X2USS9n[        U5      (       a  [        S5        gU Vs/ s H/  owR                  5       (       d  UO[        R                  " U5      PM1     nnU R                  5       (       d  U O[        R                  " U 5      n [        5       nXh:X  a  U(       d  [        S	5      eU/n	U /n
OU(       a  [        S
5      e/ n	U /n
[        5       nX[l        XKl        UR                  XU5      nU(       a  U$ UR!                  5         gs  snf )aS  
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  Fr[   z;Argument ``scatter_list`` must be specified on source rank.zDArgument ``scatter_list`` must NOT be specified on non-source ranks.)r	  r  r  r  r  r  r  r  r   r  rE   r   r   r  r  r[   r  )r   r+  r  rH   r  r  r'  r  r  rA  r  r  r  s                rm   r[   r[     sS   p *<8"68#E*E
{y()%itTJ(YeTI%  9%DPDPqU%7%7%::L   ",,..VE4F4Fv4NFZN#M  & V   DML===D		;s   76Ec                 $   [        U S5        [        US5        [        X5        [        U5      (       a  [	        S5        g[        5       nX%l        U=(       d
    [        5       nUR                  U /U/U5      nU(       a  U$ UR                  5         g)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_listrZ   N)
r	  r  r  r  r  r   rw   r|  rZ   r  )rD  rE  r   rH   r  r  r  s          rm   rZ   rZ   :  s{    ( *z<0"66%  +,!DM)')E:,=D		ro   c           
      0   U4n[        U5      (       a  [        [        UU UUUUS9$ [        U S5        [        US5        [	        U5      (       a  [        S5        g[        5       nX&l        XFl        U=(       d
    [        5       nU[        R                  R                  5       ;   aF  [        [        XUS5      n[        R                  U   R                  U5        U(       a
  [        5       $ gUR!                  XU5      nU(       a  U$ UR#                  5         g)a;  
Reduces, then scatters a tensor to all ranks in a group.

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

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

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

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

r  rD  inputrd   N)r%   r$   rd   r	  r  r  r   rw   r  r|  rf  rO  rX  r  r   r  _reduce_scatter_baser  )	rD  rG  r   rH   r  r  r  r  r  s	            rm   rd   rd   a  s    t HM-(($!
 	
 *(%  23!DML)')E ((--//,eRF  '..t4>!%%fT:D		ro   z`torch.distributed._reduce_scatter_base` is a private function and will be deprecated. Please use `torch.distributed.reduce_scatter_tensor` instead.c                     [        XX#U5      $ )at  
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.

)rd   )rD  rG  r   rH   r  s        rm   rH  rH    s    2 !8DDro   c                 *   U4n[        U5      (       a  [        [        UU UUUUUS9$ [        U5      (       a  [	        S5        g[        5       n[        U S5        [        US5        [        X5        UR                  5       (       a  [        R                  " U5      nU R                  5       (       a  [        R                  " U 5      n Uc  / OUnUc  / OUnU=(       d
    [        5       nUR                  XX#U5      nU(       a  U$ UR                  5         g)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_sizesrH   r  r8   NrD  rG  )r%   r$   r8   r  r  r   r	  r  r  r   r  r|  alltoall_baser  )	rD  rG  rK  rL  rH   r  r  r  r  s	            rm   r8   r8     s   P HM-(($1/	
 		
 %  ./D*("61""5)##F+19?Q/7=N)')E)dD 		ro   c                    [        U5      (       a  [        S5        g[        5       n[        U S5        [        US5        [	        X5        U Vs/ s H/  oUR                  5       (       d  UO[        R                  " U5      PM1     nnU  Vs/ s H/  oUR                  5       (       d  UO[        R                  " U5      PM1     n nU=(       d
    [        5       nUR                  XU5      nU(       a  U$ UR                  5         gs  snf s  snf )aY  
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

r7   Nr<  r9  )r  r  r   r  r  r  r   r  r|  alltoallr  )r<  r9  rH   r  r  r  r  s          rm   r7   r7   s  s    z %  <(D)+?@(*=>"#5I EVDUqU%7%7%::DU   EWDVqU%7%7%::DV   )')E>>,FD		s   6D
6Dc                 b   [        U 5      (       a  [        S5        g[        5       n[        R                  " [        U 5      5      Ul        Ub'  [        U[        5      (       a  X#l        O[        S5      eU =(       d
    [        5       n U R                  US9nU(       a  U$ UR                  5         g)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.
r9   Nz>Invalid function argument: device_ids type should be List[int])r  )r  r  r   r   r   r~  r   r   
device_idsrs  r|  r9   r  )rH   r  rQ  r  r  s        rm   r9   r9     s    , %  9%D,,6u=>DKj$''(OP  )')E==d=#D		ro   c                 |   [        U 5      (       a  [        S5        g[        U 5      [        R                  :w  a  [        S5      eUc  [        [        U 5      5      nO8[        U[        5      (       a#  [        R                  " SU S35        [        US9n[        U5        U c
  [        5       OU nUR                  XS9$ )aU	  
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.
rT   Nz7monitored_barrier is only implemented for GLOO backend.zGPlease specify timeout arg as a timedelta. Converting current value of z assuming it represents secondsr  )wait_all_ranks)r  r  rC   r.   r   r   rp  r   floatr   r   r   ru  r|  rT   )rH   rq  rS  group_to_uses       rm   rT   rT     s    l %  ./5W\\)RSS&{5'9:	GU	#	#++2)3RT	
 G,!+0=%'eL)) *  ro   rP  rU  c                     [         (       d   S5       e[         SU 3n[        Xb5      n[        X#XES9n[	        X5      n U $ )Nz5ProcessGroupWrapper unsupported without GLOO backend.r   rt  )r  PG_WRAPPER_STORE_PREFIXr   rs   rr   )rP  rU  r  r  r  rq  prefix	helper_pgs           rm   rh  rh  e  sM     ?SSS?
 ((,8F&E jJI%j<Jro   c                     SR                  [        [        U 5      5      nSR                  U[        [        [        R
                  5      5      /5      n[        R                  " [        US5      SS9R                  5       $ )Nr  zutf-8F)usedforsecurity)
r   r  r   r   rf  r:  hashlibsha1bytes	hexdigest)rU  	rank_join
unique_strs      rm   _hash_ranks_to_strrb  |  sX    XXc#uo.I9c#foo*>&?@AJ<<j'2EJTTVVro   c                     [        U 5      n [        U 5      nS[        R                  " [        R                  5      S-  S-
  -  n[        U5      U-  nU$ )Nr      r'   )ra  r  ctypessizeofc_intabs)rU  
hash_value	max_c_intcolors       rm   ra  ra    sJ    %LEeJ
 fmmFLL1A59:I
Oi'ELro   c                     U(       a  [        U 5      nU$ [        [        R                  5      n[        =R                  S-  sl        U$ Nr'   )rb  r   rf  rE  )rU  r*  rR  s      rm   rE  rE    s@     $U+
 N f(()aNro   c                 L    U (       d  [        [        5       5      n [        U 5      $ r   )rC   r|  r.   ro  s    rm   _get_backend_from_strro    s      0237ro   c                  4    [        5       R                  c  S$ 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.
FT)r|  rN  r   ro   rm   _is_safe_to_splitrq    s     '(88@5JdJro   	parent_pgsplit_ranksrY  c                 V	   Uc  [        S5      e[        5       nUR                  nU(       d  [        S5      e[        R
                  U   u  pxUR                  5       n	UR                  5       n
U (       d  Un U [        R                  ;  a  [        SU  S35      e[        R                  U    nUR                  5        V	Vs0 s H  u  pX_M	     nn	nW	U;  a  [        SU	 SU  35      eX   nU R                  [        R                  " S5      5      nU(       a&  UR                  (       a  [        U[        5      (       d  [        S	5      eUc  U R                    S
UR#                  5        3OUn[        R
                  U    u  nn[%        U5      n['        U5      nUb'  [        U[        R(                  5      (       d   S5       eOUR*                  nUc  [-        U5      n[/        U5        SnSnU H  n[1        U5      S:X  a  [        S5      e[1        U5      U
:  a  [        S5      e[1        U5      [1        [3        U5      5      :w  a  [        S5      e[5        U5      nUU;   d  Mv  UnUR7                  U5      n  O   Ub  US:X  a  UR9                  U5        g[;        USS9nU Vs/ s H  nUU   PM
     nn[=        U S3U5      n[?        UU[1        U5      5      n[>        R@                  RB                  nUUl        URE                  U5        X#l#        Xl$        [K        U5      Ul&        UUl'        UUl(        [        UU[1        U5      U5      nURS                  5         URU                  [        R                  " S5      UU5        Uc   eUc   eURW                  U5        URY                  U5        UR                  U5      nUR[                  U5        UU4[        R
                  U'   U[        R\                  U'   [_        UU5        [a        U5      [        Rb                  U'   SU 3n[        Rd                  Rg                  U/ 5      Ri                  U5        U[        Rj                  U'   [m        U5       VV	s0 s H  u  pX_M	     sn	n[        R                  U'   U$ s  snn	f s  snf s  sn	nf )a  
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 groupsr  z is not registeredr  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.Optionsr  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)  rT  rV  )7r   r|  rN  r  rf  r7  r  r  r=  r   r  r   r   rO  r   rq   rY  comm_split_countr.   r/   r^  optionsrp  ru  r   r  r  rY  rZ  rE  r   r   r   r   r[  r_  rQ  ra  rb  rc  r  re  ri  rj  rk  rl  r:  r   r   r@  rI  rm  r   rL  r	  )rr  rs  rq  r&  rY  r  r'  _default_backendr  r  global_world_sizeparent_global_to_group_ranksr  parent_group_to_global_ranksparent_group_rankparent_backendparent_backend_strr  r   rT  my_grouprf   r  r  global_ranks_in_my_grouprp  r\  ru  rt  rx  rn  s                                  rm   rf   rf     s   T 566 $%J**I\
 	
 '-mmJ&?#//#K")	---6),>?@@#)#8#8#C  (D'I'I'K$'K#K 	'K ! $
 66;-'HT
 	
 5A++ELL,@AN
 00.*:;;_
 	
  
 (G(G(I'JK  #MM)4()G"7+N*&6&>&>?? 	
Q	
?
 $++
 &w/! HJ"{q >??{//l  {s3{#344JKK[)+"H$**+<=J #  :+,,Y7$XuEJOWXxt <T BxX*Q/?L#HB
  ++00L"BL)!*1(;J'?J$&J$j#h-M 002f-|]K !!!!!!z"z" OOI.M--i8 !,/FMM"$FOOBJ+#&~#6FR J< F
  ,33B7!FR
 (11I'J!'J#J 	'J!F"
 I{$V  YZ!s   >R"R 5R%c                 "    [        U UUUSUUUS9$ )aY  
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_synchronizationrY  r'  )_new_group_with_tag)rU  rq  r   r&  r  rY  r'  s          rm   rU   rU   m  s*    ^ ";	 	ro   c                 F   [        5       nUc  UR                  nO#UR                  b  XxR                  :X  d   S5       e[        R                  U   u  pUR	                  5       nUR                  5       nU(       d  U	n[        U5      nUc  [        U5      n[        U5        U(       a1  U[        R                  :X  a  [        S5      eU b  [        5       U ;  a  gU b_  [        U 5      n [        U 5      nX:  a  [        S5      eU  H  nUS:  d  X:  d  M  [        S5      e   X;   a  U R                  U5      nOSnO[        [!        U5      5      n UnUn[#        XS9n[%        UUU UU
UUUUUUS9u  nn['        U 5       VVs0 s H  u  pX_M	     snn[        R(                  U'   [+        5       S	:X  ak  [,        R/                  S
5        U[        R                  :X  a  [1        5         U$ U(       a  UOU
nU(       a  [        U 5      O	[3        5       n[5        WUUUU5        U$ s  snnf )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+  rq  rn  r'  rY  r'   r@  )r|  rN  rf  r7  r  r  r.   rp  ru  r   r   rE   r  r   rY  r   rI  rE  rF  r	  r=  r  r   r   r9   rF   r  )rU  rq  r   r+  rn  r  rY  r'  r  default_backendr  r  rx  group_world_sizer  r  r  r\  r  barrier_storer  s                        rm   r  r    sH   $ $%J..			#	#	/666 	
H	
6 &,]]:%>"O//#K") !gG &w/! gkk!L  5!8 uu:/%  Dax44 ?   [1JJU,-., 
$UVJ,'LB  @I?O!?O$;J?O!F" 1$ 	*	
 gkk!I I )BH}M'@UnFVJ !]J
G I;!s   ?Hc           	      .   U cL  [         R                  R                  5       (       d  [        S5      e[         R                  R	                  5       n U S::  a  [        SU  S35      e[        5       nX`:  a  [        SU  SU S35      eX`-  S:w  a  [        S5      e/ nSn[        X`-  5       Hf  n	X-  n
X-   n[        [        X5      5      n[        UUUUUS	9nUR                  U5        [        5       nX;   d  MN  Un[        R                  S
X5        Mh     X4$ )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'rU  rq  r   r&  rY  "Rank %s is assigned to subgroup %s)r   r   is_availabler   device_countrF   rI  r   rU   r   rE   r   r   )rV  rH   rq  r   r&  rY  r  	subgroupscur_subgroupsubgroup_id
start_rankend_rankranks_in_subgroupsubgroupr  s                  rm   rV   rV   E  s<   P zz&&((9 
 ZZ,,.
Q1*=OPQQ!J$ZL0RS]R^^_`
 	
 !#KLLILZ56 -
* z!<=#!!
 	"z$#LKK<dV! 7$ ""ro   c           
      >   U b  [        U 5      S:X  a  [        S5      e/ nSn0 nU  Hr  n[        UUUUUS9n	UR                  U	5        [	        5       n
U HA  nX;   a  [        SU SX{    SU 35      eXU'   X:X  d  M)  U	n[
        R                  SX5        MC     Mt     Xe4$ )	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   rU   r   rE   r   r   )ranks_per_subgroup_listrq  r   r&  rY  r  r  rank_to_ranks_dictrU  r  r?  r  s               rm   rW   rW     s    p &#.E*F!*KLMMIL(!!
 	"*D) D6!@ASAY@ZZ_`e_fg  (-t$'@$N  )( ""ro   c                 h  ^ [        U 5      S:  a1  U R                  S5      (       d  U R                  S5      (       d  SU  3n [        R                  R	                  U / 5       HM  nUR                  5       [        U5      :w  a  M"  [        U5      m[        U4S jU 5       5      nU(       d  MK  Us  $    g )Nr   rV  rW  c              3   ,   >#    U  H	  oT;   v   M     g 7fr   r   )r   rr  s     rm   r   ,_find_pg_by_ranks_and_tag.<locals>.<genexpr>  s     3U#Us   )r   r  rf  rI  r
  r  ra   r  )r   rU  rH   goodr  s       @rm   r  r    s    
3x!|CNN6223>>';R;RcUm""&&sB/::<3u:%-e43U334L 0 ro   stridec                    [        U5      U-  S:X  d   S[        U5       SU S35       e[        5       nS nU[        U5      :X  a  UR                  5       nX4;   d   S5       eO6[        S[        U5      U5       H  nXXR-    nX6;   d  M  UnM     Uc   S5       e[	        U5      n[        X5      nUb  U$ U S:X  a  [        S5      e[        X@S9$ )	Nr   zRanks length (z) must be divisible by stride (r  z(rankset doesn't include the current noder  z-Cannot automatically create PG with empty tag)rn  )r   rE   copyrI  r  r  r   r  )r   rU  r  r?  my_ranksrL  rank_setr\  s           rm   #_find_or_create_pg_by_ranks_and_tagr    s     u:!# 
U$CF81M# jGHU::<"N$NN"q#e*f-A,H"# . #O%OO#hH	"3	1B	~	
byHIIx44ro   c                 N    [         R                  U    nUR                  S5      nU$ )z&Return the tag associated with ``pg``.rW  )rf  rL  removeprefix)r\  r   s     rm   _get_group_tagr  <  s'    


2
C


7
#CJro   c                 B    [         R                  R                  U S5      $ )NNone)rf  r:  r
  r\  s    rm   r  r  C  s    ??r6**ro   c                 .    [         R                  U    S   $ rm  )rf  r7  r  s    rm   _get_process_group_storer  G  s    ==Qro   r   r   )NNF)	NNNr  r  Nr  NN)NNNNNr  )NNFN)NNNN)NF)NNNFN)NNNF)NNNNFNN)NNNNNFNN)NNNNNN)r   collections.abccollections
contextlibre  r\  r4  r  loggingr  pickler2  r  r   r   datetimer   typingr   r   r   r   r	   typing_extensionsr
   r   torch._Cr   r  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  	Unpicklerr  rn   rp   rj   ImportErrorrq   rr   rs   rt   ru   	getLoggerr   r   rW  boolr^   r   r.   r/   r   rb   r1   r  r#  r   ra  r   r$  r%  r  r&  rD  r'  r   r(  r)  r+  rf  rl   rc  rH   r0   rp  ru  rv  r  r~  r   r  r  r  r  r  r_   r`   r   r  ra   rW  r  r  r	  r  r  r  r  abcIterabler  r  r  r  rM   rO   rK   rQ   rR   rN   rL   rP   r  r|  r  r  rB   rC   rD   r  r  r  rG   re   r   r$  rI   rR  rF  r?   r  rE   rF   r  rS   rJ   r]   rX   r  r  contextmanagerr  r:   r;   SUMr5   r6   rY   r  r  r4   rA   r<   r=   r>   r\   r2   rc   r7  r3   r  r@   r[   rZ   rd   rH  r8   r7   rg  r9   rT   r   r  rh  rb  ra  rE  ro  rq  rf   rU   r  rV   rW   r  r  r  r  r  r   ro   rm   <module>r     s   2     	   	  
   "  @ @ (  6     0 N & E . 8 B ?KZ >>
?.  :!EO!""G;"F"##GQ"F"##G:!EO!""G;"F"##G 
		8	$& 
$x 
$D 
$~Tc ~TBM' M'`2 20 L	C| C|L : 24lE#u*--	. 3%'	4c!" '68lDcN23 8.0 Ds*+ 0-/T#tL))* /&(
Ds"# ((3- | |~ 
 i "$j $J "' "i "
# 
$ 
 *. # -6 >8L#9 >S >BK(<"8 KELL K\;h|4 ;S	 ;  r*A 
A AH1h|4 1 1$, $S $S $8N< NS NS N8 N
(S (
(

5< 
5DI 
5c   
S	   

8L#9 \  "& $	88#8 8 	8
 	8.
 
C 
C 
411 4(
@&$ 
4 
4 
$ 
4 
3# 3$ 3() )

8$ 
8: :
!L 
!	E 	6)h|4 ) )(*x- * *(5ell1B+C  .|  (<0 DcN T$sCx.1 c x}  48	 8d 86(.Y (.x/E (.QU (.V !!%#'! $(,tOc]tO#tO i tO 	tO
 tO E?tO tO tO %tO 
tO  tOn: bJ	T1,!7 T1nW1 6 W1t4H\* 4c 46"(<0 "C "* $(#*0LL*0	#*0 L!*0 
	*0
 }*0 d^*0^ $(#*4LL*4	#*4 L!*4 
	*4
 }*4 d^*4Z  $(#LL	# L! 
	
 } 
 >  $(#$LL$	#$ L!$ 
	$
 }$ 	$ $NN4 N
 
 $(%) %UL!UU\\"U ~U UpL4; L4: L^  $(#+LL+	#+ L!+ 	+
 }+ +\ ",,dU ] ]@ J 	 &.\\ 7 7t  ||$(#-LL-	#- L!	-
 - }- -`',2 WG WGt  /3$(#yN	yN c+yN 
#yN L!	yN
 }yN yNx  $(%)#_:c_:	#_: L!_: U\\"	_:
 }_: _:D  $(%)#bcb	#b L!b U\\"	b
 }b bJ  $(%)#zJczJ	#zJ L!zJ U\\"	zJ
 }zJ zJz  6:$(#~ $S	~'S	2~ 
#~ L!	~
 }~ ~B [ [| h hV E
P P0 J 	 BGK K\	
  15$(#LLLL$u||,-L 
#L L!	L
 L }L L^  26$(#cLLc4-.c 
#c L!	c
 c }c cL *2,,dU # #L ,4LLu a aH D
 ,4<<te E
E.  
M M` r rj $/$5$5RV)L!) )Z %0$5$5LL!Lj ,**22  	
  .Wd3i WC W
S	 
c 
	8C= G K4 K (,"&#' $ $z%z$z i z 	z
 z lz zz 
#(,W %W Wv #(,z %z| 
p#j S#l3 tCy Xl=S 5	5#Y5(+55>|  + + +   %  qd  N  O  O  N  OsZ   3h h% h4 1i i h"!h"%h10h14i ?i iiii