L ihZUdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlmZddlmZddlmZmZmZmZmZddlmZddlZddlmZddlmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3dd l4m5Z5dd l6m7Z7dd l8m9Z9m:Z:dd l;mZ>m?Z?d dl@mAZAmBZBd dlCmDZDmCZCgdZEdZFdZGdZHdZIdZJe jZLe jZNddZOeO ddlmPZPdeP_QeEdgz ZE ddlmSZSdeS_QeEdgz ZE ddlmTZTmUZUdeU_QeEdgz ZE ddlmVZVdeV_QeEdgz ZE ddlmWZWdeW_QeEd gz ZEejeYZZd!Z[d"e.de\fd#Z]Gd$d%e^Z_Gd&d'Z`Gd(d)ZaeaZbGd*d+ZcGd,d-Zdiaeefe-ege^e2ffehd.<iaiefe-e^fehd/<iajefe-efekekffehd0<ialefe-e^fehd1<damianefe^eoe-fehd2<iapefe-e^fehd3<daqee^ehd4<Gd5d6Zreras Gd7d8etZuGd9d:eu;ZvGd<d=eu;Zwd>e_defd?Zxd@eddfdAZydazee^ehdB<dCZ{dd:ee-de^fdDZ|dd:ee-dejfdEZ~dd:ee-deoe^fdFZe?edGHf ddIZd:ee-de\fdJZddKZd:e-dLekdekfdMZd:e-dNekdekfdOZedPeQdekfdRZd:ee-deoekfdSZdekfdTZdUe^dekfdVZdWeoekdXe^de^fdYZddZZdd[Zdd:ee-de-fd\Z dd:e-dLeekdNeekd]e\dekf d^Zd:e-d_ekd`e^fdaZdej j"fdbZddcZdddZddeZde\fdfZde\fdgZde\fdhZde\fdiZde\fdjZd>e^de\fdkZde\fdlZde\fdmZdekfdnZde-fdoZde2fdpZddqZdd:ee-de^fdrZdd:ee-de_fdsZdtee^ejfde^fduZdve-dekfdwZdd:ee-defe^effdxZdeoefe^effdyZdekfdzZdd{eekdekfd|Zd@eddfd}Zdd@ed:ee-ddfd~Ze>e? dd>ee^dee^d@eedekd_ekdee2dUe^deedeeejekfddfdZdZ ddZdd:ee-fdZdd:ee-fdZdd:ee-dekfdZdd:ee-dekfdZ ddejfdeekd:ee-dXekdeekdee3f dZ ddejfdeekd:ee-dXekdeekdee3f dZe> ddejfdeekd:ee-dXekdeekddf dZe> ddejfdeekd:ee-dXekdeekdekf dZGdde3ZGddZejt dd:ee-dteejde\fdZGddZejt dd:ee-dteejfdZdeoecdeoe3fdZe> ddejfdeekd:ee-de\deekf dZe>e.jddfdZe>edeQe.jddfdZe>de.jdddfdejfdeekd:ee-de\deekf dZdZdZe>ddZe> ddedeeoedeekd:ee-deekf dZe> ddeoedeekd:ee-dteejdeekde\f dZe> ddeoedeekd:ee-dteejdeekde\f dZe> ddeoedeekd:ee-dteejdeekf dZe> ddeoedeeoedeekd:ee-deekf dZe>ddZe>ddZe>edeQddZe>edeQ ddZdZe> ddejfdeeoejfdeekd:ee-de\deekf dZe> ddejfdeeoejfdeekd:ee-de\deekf dZe>e.jddfdZe>e.jddfdZedeQe.jddfdZe> dd„Ze>ddÄZe>ewjddfd:ee-fdĄZewjddfd:ee-fdńZeBfdejjjde^de2d_ekdekd@ef dȄZdWeoekde^fdɄZdWeoekdekfdʄZd˄Zdd>ee^de_fd̄Zde\fd̈́Ze? ddee-deeod@eedeedee^dee-f dфZe? ddeejfd҄Z ddeejfdӄZ ddԄZ ddՄZdXe^dWeoekdee-fdքZdXe^dWeoekdekde-fd؄Zdve-de^fdلZdve-de^fdڄZdve-de2fdۄZy#eR$rdZFYwxYw#eR$rdZGYwxYw#eR$rdZHYwxYw#eR$rdZIYwxYw#eR$rdZJYwxYw)z,Distributed Collective Communication (c10d).N) namedtuple) timedelta)AnyCallableOptional TYPE_CHECKINGUnion) deprecated)_DistStoreError)_DistributedBackendOptions_register_process_group_resolve_process_group_unregister_all_process_groups_unregister_process_groupAllgatherOptionsAllreduceCoalescedOptionsAllreduceOptionsAllToAllOptionsBarrierOptionsBroadcastOptions DebugLevel GatherOptionsget_debug_level PrefixStore ProcessGroupReduceOp ReduceOptionsReduceScatterOptionsScatterOptionsStoreWork)+set_pytorch_distributed_envs_from_justknobs) _WaitCounter)handle_torch_functionhas_torch_function)not_none)_exception_logger _time_logger)default_pg_nccl_timeoutdefault_pg_timeout)register_rendezvous_handler rendezvous)JBackend BackendConfig GroupMemberP2POp all_gatherall_gather_coalescedall_gather_object all_reduceall_reduce_coalesced all_to_allall_to_all_singlebarrierbatch_isend_irecv broadcastsend_object_listrecv_object_listbroadcast_object_listdestroy_process_groupgather gather_objectget_backend_config get_backendget_default_backend_for_deviceget_rankget_world_size get_pg_countgroupinit_process_groupirecvis_gloo_availableis_initializedis_mpi_availableis_backend_availableis_nccl_availableis_torchelastic_launchedis_ucc_availableis_xccl_availableisendmonitored_barrier new_group new_subgroupsnew_subgroups_by_enumerationrecvreducereduce_scatterscatterscatter_object_listsendsupports_complexrrrrrrrrrrrrr rrr!r+get_group_rankget_global_rankget_process_group_ranks reduce_opall_gather_into_tensorreduce_scatter_tensorget_node_local_rank split_groupTreturnctttttt t tttttttttg}|D] }d|_ y)N"torch.distributed.distributed_c10d)rrrrrrrrrrrrr rrr! __module__)_public_types_to_change_moduletypes h/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py_export_c_typesrnsR!  !&"$/?>?)ProcessGroupMPIrirpF)ProcessGroupNCCLrq)_ProcessGroupWrapperProcessGroupGloors)ProcessGroupUCCrt)ProcessGroupXCCLru pg_wrapperreduceOpctjtjtjtjtj tj g}||vS)z8Return true if reduce ops is supported. False otherwise.)rMAXMINPRODUCTBANDBORBXOR)rwdenyLists rmr^r^sD      H 8 ##roc BeZdZUdZdZdZdZdZdZdZ e dd d gZ iZ e ee fed <eeee eegZeee ed Ze eefed <eddgedge dgeddgeddgiZe eeefed<eej*jeej*j eej*j e ej*jeej*jeej*jiZe eej*fed<defdZe ddeeeeefddfdZy)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. undefinedgloonccluccmpixccl_BackendPlugin creator_fn extended_api_plugins)cpucudaxpumpsdefault_device_backend_maprrrbackend_capabilitybackend_type_mapnamect|ts tdtt|j tj }|tj k(r|j}|S).Create and return a new instance of the class.z0Backend constructor parameter must be string-ish) isinstancestr ValueErrorgetattrr.upper UNDEFINEDlower)clsrvalues rm__new__zBackend.__new__%sP$$OP Pw/@/@A G%% %JJLE roNdevicesrgctt|js-tt|j|j |j tj vr-tj j |j |;|D]6}|tjvs|j tj|<8tjjtj|j <|=tjd|dddgtj|j <nTt|t r#|gtj|j <n!|tj|j <tj#||tj$|j<y)au Register a new backend with the given name and instantiating function. This class method is used by 3rd party ``ProcessGroup`` extension to register new backends. Args: name (str): Backend name of the ``ProcessGroup`` extension. It should match the one in ``init_process_group()``. func (function): Function handler that instantiates the backend. The function should be implemented in the backend extension and takes four arguments, including ``store``, ``rank``, ``world_size``, and ``timeout``. extended_api (bool, optional): Whether the backend supports extended argument structure. Default: ``False``. If set to ``True``, the backend will get an instance of ``c10d::DistributedBackendOptions``, and a process group options object as defined by the backend implementation. device (str or list of str, optional): device type this backend supports, e.g. "cpu", "cuda", etc. If `None`, assuming both "cpu" and "cuda" .. note:: This support of 3rd party backend is experimental and subject to change. NDevice capability of zl unspecified, assuming `cpu` and `cuda`. Please specify it via the `devices` argument of `register_backend`.rr)hasattrr.rsetattrr backend_listappendrr BackendTypeCUSTOMrwarningswarnrrrrr)rrfuncrrdevices rmregister_backendzBackend.register_backend/sWBw - GTZZ\4::< 8 :: N2>1I1I1P1P  . ? MM'v.&&  9>vG & &tzz| 4  %8?yG & &tzz| 47>G & &tzz| 4)0)?)?l)S&ro)FN)__name__rj __qualname____doc__rGLOONCCLUCCMPIXCCLrrrdictr__annotations__rrrlistrrrr classmethodrr rrormr.r.s$I D D C C D 0<2PQN*,Hd3&',tT4c:L 2S#X ufo vh ug eV_ eV_ 0S$s)^, <++55 l&&++ l&&++ l&&++ \ % % ) ) \ % % ) ) =d3 8 8893 37 ;T %T#Y/0 ;T  ;T;Tror.c8eZdZdZdefdZdZdeeeffdZ y)r/zBackend configuration class.backendc i|_t|}|tjk(rVtj j j} tj|}t||j|<nC|jtjvrHtj|j}t|}tj|||_nd|jvrd|d}|jj!dD]q}|j!d}t#|dk7rtd |d ||\} }| |jvrtd | d |d |t||j| <sn/t%j&d |dt|}|||d|_t(j+d|jy#t$rtd|ddwxYw)Init.zWe 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: ":,:...". e.g. 'cpu:gloo,cuda:nccl',zEInvalid device:backend pairing: z. zDuplicate device type z9 in backend string: rzp unknown, assuming `cpu` and `cuda`. You can specify it in `device:backend` format in `init_process_group` call.)rrrzUsing backend config: %s)device_backend_maprr.rtorch_C_get_acceleratorrlrKeyErrorrrrrrfromkeyssplitlenrrloggerinfo) selfr device_type backend_strsupported_devices backend_valbackend_str_error_messagedevice_backend_pair_strdevice_backend_pairrs rm__init__zBackendConfig.__init__qs.68g, g'' ' ((335::K %@@M 7>{7K'' 4]]_ 4 4 4!( : :7==? K !'*K&*mm4E{&SD # GMMO # -\\c[ded)g % ,3==?+@+@+E C'&=&C&CC&H#*+q0$&&=%>bAZ@[]#6T444$0999@ D]C^`3:'2B''/ C$ MM'y1--  "'*K"#"'D #  .0G0GHi  .{m<^_  s +G G:cbdjd|jjDS)z8Return all the device:backend pairs separated by commas.rc30K|]\}}|d|yw)rNr).0rrs rm z)BackendConfig.__repr__..s$ &5fgvhay ! s)joinritemsrs rm__repr__zBackendConfig.__repr__s/xx 9=9P9P9V9V9X   rorgc|jS)z!Return backend map of the device.)rrs rmget_device_backend_mapz$BackendConfig.get_device_backend_map&&&roN) rrjrrr.rrrrrrrormr/r/ns0&@I@ID 'S'\(:'ror/c8eZdZdZddZededZy) _reduce_opz Deprecated enum-like class. For reduction operations: ``SUM``, ``PRODUCT``, ``MIN``, and ``MAX``. :class:`~torch.distributed.ReduceOp` is recommended to use instead. NctjjjD]\}}t |||tjj|_yN)r RedOpType __members__rr)rkvs rmrz_reduce_op.__init__sJ&&2288: DAq D!Q  #--99roz\`torch.distributed.reduce_op` is deprecated, please use `torch.distributed.ReduceOp` insteadcategoryc.tj||Sr)object__getattribute__)rkeys rmrz_reduce_op.__getattribute__s &&tS11rorgN)rrjrrrr FutureWarningrrrormrrs-:  : 2  2rorceZdZdZ d dedej deedee dedeef dZ d dedej deedee dedeef d Z fd Z xZ S) r1ac 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. optensorpeerrHtag group_peerc||_||_t||_t |j||d|_||_t |j|||_y)rT return_globalN)rr_group_or_default_grouprH_canonicalize_group_rankrrr)rrrrrHrrs rmrzP2POp.__init__sT ,U3 , JJj  24::tZProcZt|t|dtj|S)rr) _check_op_check_single_tensorrr)rrrrrHrrs rmrz P2POp.__new__s$ " VX.~~c""roc t|j}|jj}|jr|jjnd}d|vr|}|j }n!d|vr|j }|}nt |Sd|d|d|d|d|jjd |jjd S) N default_pgr]rXzP2POp(z pg=z , group_src=z , group_dst=z, z, )) rErHrr group_namersuperrrshapedtype)r my_group_rankop_namersd __class__s rmrzP2POp.__repr__s , ''"".2jjTZZ**l W AA w AA7#% %yZL QC|A3cRVR]R]RcRcQddfgkgrgrgxgxfyyz{{roNNrN)rrjrrrrTensorrintrrrr __classcell__)rs@rmr1r1s.#(,$(Q Q Qsm Q  % Q  QSMQ.#(,$( #  #  #sm #  % #  #SM # | |ror1c neZdZdZ d dedej deej deedee f dZ y) _CollOpa A class to capture collective operations. Args: op (Callable): A collective function, e.g. ``torch.distributed.all_reduce``. tensor (Tensor): Tensor to operate on. dst_tensor (Tensor, optional): Provided when source and destination tensors are not the same. redop (ReduceOp, optional): reduce operation. root (int, optional): root of broadcast or reduce. Nrr dst_tensorredoprootcJ||_||_||_||_||_yr)rrrrr)rrrrrrs rmrz_CollOp.__init__+s' $  ro)NNN) rrjrrrrr rrr rrrormrrs] .2$("     U\\*  !  sm ror_pg_map _pg_names_pg_group_ranks_pg_backend_config _tags_to_pg _pg_to_tag_backendceZdZdZddZedeefdZejddZede ee e e fffdZede ee ffdZede ee eefffd Zede ee ffd Zedefd Zejd eddfd Zede e eeffdZede ee ffdZede eeeffdZedee e effdZy)_Worldz Container class for c10d process group state. This is used during registration and lookup of PG state. .. warning:: This is an experimental API intended to expose the inner workings of c10d and is subject to change.. rgNc d|_i|_yr) _default_pg_pg_coalesce_staters rmrz_World.__init__QsEGroc|jS)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. rrs rmrz_World.default_pgUsroc||_yrr rrs rmrz_World.default_pg_s  roctS)a  Provide Mapping from ProcessGroup to backend name and store. For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store) For MPI pg, it is a map from ProcessGroup to (Backend, None) TODO don't expose the map, expose fine grained ops )rrs rmpg_mapz _World.pg_mapcs roctS)z Process group's names, map from ProcessGroup to str. TODO don't expose the map, expose fine grained ops )rrs rmpg_namesz_World.pg_namesps roctS)z Process group's global rank to local rank mapping. TODO don't expose the map, expose fine grained ops )rrs rmpg_group_ranksz_World.pg_group_rankszs roctS)zm Process group's backend config. TODO don't expose the map, expose fine grained ops )rrs rmpg_backend_configz_World.pg_backend_configs "!roctS)z| Process group count for default naming. TODO don't expose group_count, use something else instead  _group_countrs rm group_countz_World.group_counts rorc|ay)zKUse to compute the name of ProcessGroups when using global synchronization.Nr,r"s rmr.z_World.group_counts  roctSr)rrs rm tags_to_pgz_World.tags_to_pgs roctSr)rrs rm pg_to_tagz_World.pg_to_tags roc|jSr)rrs rmpg_coalesce_statez_World.pg_coalesce_staterroc hg}td}|jjD]}|j|}|j |j ||j |j|t||k7rt|jngt||jd|S)z Return a list of dict with process groups and backends. Along with their unique IDs and configurations (types and ranks). N)pg_namepg_descbackend_configranks group_sizer.) _get_group_sizer$keysr(rr& group_descr*rrr.)r config_infodefault_pg_sizepgr:s rmpg_config_infoz_World.pg_config_infos-/ )$/++""$ B''+E   #}}R0!}}&*&<&%A B"4 c(9#:""S Dd<&8!894 c 12'4 d7m(C#D''T#s(^ 4rorc\eZdZdZedeefdZejdeefdZy) _WorldMetazm Meta class of ``group`` and ``GroupMember``. Allows them to have the class property ``WORLD``. rgc"tjSr_worldr)rs rmWORLDz_WorldMeta.WORLDs   rorAc|t_yrrI)rrAs rmrKz_WorldMeta.WORLDs roN) rrjrrrCrrrKrDrrormrGrGsK!h|,!! \\x -rorGceZdZdZy)rHzGroup class. Placeholder.N)rrjrrrrormrHrHs#rorH) metaclassceZdZdZdZy)r0zGroup member class.iN)rrjrrNON_GROUP_MEMBERrrormr0r0s ror0rc|tjk(r5tttst j dtStStS)NzSAttempted to get default timeout for nccl backend, but NCCL support is not compiled)r.rrr*rrrr+rs rm_get_default_timeoutrSs>',,19= MMe & %&&!!rotimeoutc@t|tstd|y)Nz@Expected timeout argument to be of type datetime.timedelta, got )rr TypeErrorrTs rm_check_valid_timeoutrXs( gy )Nwi X   *ro_default_pg_init_methodstore_based_barrier_keyc|xs t}t|tsKtjdt |dt|t rytdt |d |j}t|dk(r|dj St|dk(rytjd|vry|dj S)aB .. note:: This is an internal helper and does not have backward compatibility, please use with caution. Return the device type to use with ``group`` for object collectives or barrier. There are selection rules: 1. If user specifies exactly one backend in ``init_process_group`` call: use that backend 2. Else if user specifies multiple "device:backend" pairs in init_process_group: If "cpu" is among those pairs, use "cpu" (because the object is in cpu memory); Otherwise, use the first backend (sort of a random pick). Args: group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. Returns: str: The device type to use for object collective with ``group``. You are using a Backend w as a ProcessGroup. This usage is deprecated since PyTorch 2.0. Please use a public API of PyTorch Distributed instead.rz$Expecting a ProcessGroup, but got a .r'r) _get_default_grouprrrrrlrsr _device_typesrrr)rHrs rm_get_object_coll_deviceras.  )')E e\ * &tE{m4. .  e- .CDK=PQRS S !!G 7|qqz W  e  'qzroctjd|xs t}t|ts>tjdt |dt dtjdS |j}t|dk(r|dSt|dk(r td tjd|vrtjd}n|d}tjd |d |S) a$ .. note:: This method will be deprecated, it only stays for backward-compatiblity reason. Alternatives: - If you need to find a device for object collectives, please use `_get_object_coll_device(group)`. - If you need to query the device types supported by group, please use `_device_capability(group)`. Return the device type registered with ``group``. For example, if `init_process_group("nccl", ...)` was called, the returned value would be `torch.device("cuda")`. Errors out if no device has been registered. Args: group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. Returns: torch.device: The device type registered with ``group``. a`_get_pg_default_device` will be deprecated, it only stays for backward-compatiblity reason. If you need to find a device for object collectives, please use `_get_object_coll_device`. If you need to query the device types supported by group, please use `_device_capability(group)`. r\r]) stacklevelrr'rzXDefault 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.) rrr_rrrlrrrr`r RuntimeError)rHrrvs rm_get_pg_default_devicergBs4 MM (  )')E e\ *  &tE{m4. .   ||E"" !!G 7|qqz W  &  << ' )e$BB  ==?DA0 0  rocp|xs t}|jDcgc]}|jc}Scc}w)a Return the device type(s) supported by ``group``. Args: group (ProcessGroup, optional): The process group to query. If None, the default process group will be used. Returns: List[str]: A list of device types supported by ``group``. )r_r`rl)rHrs rm_device_capabilityris0  )')E&+&9&9 :FFKK :: :s3 secondsctd|}|j|dtjd|||}|j|d}|d} ||k(r|j | dt |t d|dz z }tj} |j| g| tjd|||y#t$r} |j|d}tjd tj| z |||||| t tj| z |kDrtd |d |d |d|d|d| d Yd} ~ nd} ~ wwxYw)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()``. rr'z#Added key: %s to store for rank: %srz :last_worker1rjirkzWaiting 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=rNz@Rank %s: Completed store-based barrier for key:%s with %s nodes.) STORE_BASED_BARRIER_PREFIXaddrdebugsetmaxrtimewaitreDistStoreErrorr) rankstorerrendezvous_countrTlogging_interval store_key world_size worker_countlast_worker_keystartes rm_store_based_barrierrs ..a |h z !K {:,.DUGL MMroz`torch.distributed.distributed_c10d._get_global_rank` is deprecated, please use `torch.distributed.distributed_c10d.get_global_rank` insteadrct||S)z1Use get_global_rank as this method is deprecated.)r`)rHrws rm_get_global_rankr+s 5$ ''rocnttj|xs tj S)a Get all ranks associated with ``group``. Args: group (Optional[ProcessGroup]): ProcessGroup to get all ranks from. If None, the default process group will be used. Returns: List of global ranks ordered by group rank. )rrJr(r_r=rs rmrara5s, %%e&C/A/CDIIK LLroc~|tjus|t}|jS|jS)zGet a given group's world size.)r0rKr_sizerHrs rmr<r<Cs5 !!!U]')   ::<rorc8t|}|jSr)rr)rrHs rm_get_group_size_by_namerKs ": .E ::<ror:rcLt||}| td|jSN)_find_pg_by_ranks_and_tagrr)r:rrHs rm$_resolve_group_name_by_ranks_and_tagrPs+ &c5 1E }n   rocnt|tjstd|dt |dy)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)rrr rVrl)param param_names rmrrYs? eU\\ *? |L5k]) /   +roc t|tstd|dt|dt d|Ds5td|dt|d|Dcgc] }t|c}dycc}w)z=Check that the parameter ``param_name`` is a list of tensors.rz2` of type List[torch.Tensor] but got rc3PK|]}t|tj ywr)rrr )rps rmrz%_check_tensor_list..is<Au||,roc6|ttfvr tdy)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)rSrJr)rs rmrrs% % +   roct|trtd|Ds td|djtfd|Ds tdy)zx Check that the ``p2p_op_list`` is a list of P2POp instances. Also, check that all ops use the same group. c3<K|]}t|tywr)rr1)rp2p_ops rmrz%_check_p2p_op_list..s4&, 65!4zZInvalid ``p2p_op_list``. Each op is expected to to be of type ``torch.distributed.P2POp``.rc3<K|]}|jk(ywrr)rrrHs rmrz%_check_p2p_op_list..s?u $?sz#All ops need to use the same group.N)rrrrrH) p2p_op_listrHs @rm_check_p2p_op_listrsh k4 (40;41 9  N E ?;? ?>?? @roctS)z&Check if the MPI backend is available.)_MPI_AVAILABLErrormrMrM roctS)z'Check if the NCCL backend is available.)_NCCL_AVAILABLErrormrOrO roctS)z'Check if the Gloo backend is available.)_GLOO_AVAILABLErrormrKrKrroctS)z&Check if the UCC backend is available.)_UCC_AVAILABLErrormrQrQrroctS)z'Check if the XCCL backend is available.)_XCCL_AVAILABLErrormrRrRrrocttjd|jdd}|r|S|jtj vS)aF Check backend availability. Checks if the given backend is available and supports the built-in backends or third-party backends through function ``Backend.register_backend``. Args: backend (str): Backend name. Returns: bool: Returns true if the backend is available otherwise false. is_ _availableN)rr distributedrr.r)ravailable_funcs rmrNrNsLU..#gmmo5Fj0QSWXN ==?g22 22roc&tjduS)z8Check if the default process group has been initialized.N)r0rKrrormrLrLs   D ((roc0tjdduS)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)osgetenvrrormrPrPs 99* +4 77roc@ttjddS)NTORCH_DIST_INIT_BARRIER0)r rrrrorm_is_barrier_after_initr s ryy2C8 99rocts tdtrttj Stj S)zrBr<ra)rHrAs rm_get_pg_configrsC  &$&B*2.==,R0"2&(,  rocxtjjDcgc] }t|}}|Scc}w)zA Return the pg configuration of all the process groups. )rJr$r=r)rAr?s rm_get_all_pg_configsrs= &,]]%7%7%9)!r)K) )s7c"tjS)z/ Return the number of process groups. )rJr.rrormrGrGs   ro fallback_rankcdtjvrttjdS| t|Std)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.)renvironr re)rs rmreresH rzz!2::l+,,  "=!!  k roc4tjjD]w}|j}t j d|vs'|j t j d}tsVt|tsg|j|yy)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. rN) rJr$r=r`rrrrOrrq_add_ephemeral_timeout)rTrArrs rm"_add_ephemeral_timeout_for_all_pgsrsq&mm  "8"" << 7 *ooell6&:;G "z';K'L..w7 8roc| t}t|r tdt|tsJ|j }t }tjd|vrOtrE|jtjd}t|tr|j|tjd|vr{|jtjd}tr"t|tr|j|n+tr!t|tr|j|t|dk(rt!j"d|D]}|j%|y)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 Nrrrrz:Set timeout is now only supported for either nccl or gloo.)r_rrrrr`rrrrrKrrsrprOrqrrr_set_default_timeout)rTrHrbackendsrs rm_set_pg_timeoutrs&( }"$% :;; e\ ** *!!GuH ||Eg%*;*=$$U\\%%89 g/ 0 LL ! ||Fw&$$U\\&%9:  :g7G#H LL !  Z9I%J LL ! 8} RS.$$W-.ro init_methodr|rx pg_options device_idc tj tdtdtj vr(t jjj| |Jd||dkDsJd|dk\s Jd|d}t jj} t|tr-| td t j| j|}||jd k7r| |j| jk7rtd |d | d |j td|j t jj#k\r.td |dt jj#dt$j'd||+|)t(j*j-|j}|d}t)|}| t/|}t1| t3gd}|t(j4k(rP|dk7s|dk7rt7j8d|d|dt;ddg|t=||d\} } t?| n||W|dk(rddl m!} | }n8tEtG||||} tI| \}}}|jK|tMd|}t;||g||||||d \} } t?| tOtjjQDcic]}||c}tRjTtj<tRjVtGtjda,|a-tj\dt_d fd!}|t_.tad"k(rCt$jcd#|t(j4k(r teytg|||||yycc}w)$a Initialize the default distributed process group. This will also initialize the distributed package. There are 2 main ways to initialize a process group: 1. Specify ``store``, ``rank``, and ``world_size`` explicitly. 2. Specify ``init_method`` (a URL string) which indicates where/how to discover peers. Optionally specify ``rank`` and ``world_size``, or encode all required parameters in the URL and omit them. If neither is specified, ``init_method`` is assumed to be "env://". Args: backend (str or Backend, optional): The backend to use. Depending on build-time configurations, valid values include ``mpi``, ``gloo``, ``nccl``, ``ucc``, ``xccl`` 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``, ``xccl`` for ``xpu``. 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. Default backend for the device can be queried with :func:`get_default_backend_for_device`. 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 available options to config nccl, See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-t device_id (torch.device | int, optional): a single, specific device this process will work on, 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. If an `int` is provided, the API assumes that the accelerator type at compile time will be used. .. 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 ":,:", 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.rz*world_size must be positive if using storez(rank must be non-negative if using storezenv://zdevice_id is an int, but no accelerator support is found from the current compilation. Please use a different compiled version that supports your accelerator.rz device_id z? does not match the current compilation's accelerator support: zI. Please use a different compiled version that supports your accelerator.z"Please use a device_id with index.z\ is out of range. Please use a device index less than the number of accelerators available: r^zUsing device: %srFuse_hashed_namerzFor MPI backend, world_size (z ) and rank (z9) are ignored since they are assigned by the MPI runtime.r)rTr>fake) FakeStorerW)backend_optionsrTr r>z[rank]ctj}tjxt_} ||t_|j }dj fd|j dD}tjj|tjjy#|t_wxYw)N c3:K|]}|dk7rd|ndyw)rz: Nr)rrexcepthook_prefixs rmrzFinit_process_group.._distributed_excepthook.. s. ?@17 !A3 ' : s) sysstderrioStringIOgetvaluerrwriteflush)args old_stderrbufmsgrold_hooks rm_distributed_excepthookz3init_process_group.._distributed_excepthooksZZ ;;=( S $ dO#CJllnii DGIIdO     $CJs B99 Cr'VPerforming barrier after ProcessGroup initialization since TORCH_DIST_INIT_BARRIER = 1)4r0rKrr"rmodulesr_dynamo trace_rulesclear_lru_cache acceleratorcurrent_acceleratorrr rrlindex device_countrrr.rrrSrX_process_group_namerrr_new_process_group_helperr r+torch.testing._internal.distributed.fake_pgrr-r&next set_timeoutrrangerrJr(r$rrY excepthookrErrqr9r)rrrTr|rwrxrrr accrrrrendezvous_iteratorir!rr s @@rmrIrIsP$PQQ/1#++% !!113 M{24 3 A~KKK~qyDDDy       / / 1C)S! ;Z LL95 5!8 ;)..CHH4YK'fgjfklZZ  ?? "AB B ??e//<<> >YK(99>9J9J9W9W9Y8ZZ[]   KK"I. 904488H gG&w/! %R?J'++  trz MM/ |<vN  2     G #  A :& =& Q! &0[)4W'#+//B*C'tZ!!'* e4E1      &#  A :&{((--/00  10F+++,}}Xk&7&789!J Z:: j5IJ**  j5IJ    s$B,, B87B8c |tjjvr td| &| j| j dk(r tdt ||dvr(t||} | rtj| \} } | | fS| dn| } t|dk(}tr(tjrtt}nd}|sStj}||vr7|r#|jtjt j"dfSt%|d|} t'| ||}t)|}d t+|vrd t+|vr|t,j.vs Jd ||t,j0k(rt,j2|j5jvr+|j7t&j8j2n`|j7t&j8j:n5|j7t,j.|nt,j2|j<jvr*|j7t&j8j2nt,j>jArvtCtEt,j>jA}||j<jvrS|j7t&j8jFn)|j7t&j8j:| r| |_ |j5jID]\}}t%|d| }|t,jJk(rtMs tOd tQjR|}t&j8jJ}|st j"dfcS|jd k(r@|jUd k(r,t'||j|jU}|j7|n|t,j:k(rbtWs tOdtY||||}||jZ_.||jZ_/t&j8j:}n{|t,j2k(rtas tOd|Ftc|tdjfsJd|jh|k7r1tkjldntejf}d|_7||_4|r||_8ts||_:||_.||_/te||||}t&j8j2}n|t,jvk(r5tyr+t{||||}t&j8jv}nP|t,j|k(rgts tOdtjf}||_.||_/||_4t||||}t&j8j|}n|jt,j>vsJd|jt,j>|j}|j}|j}t&j8jF}|s |||||}n=t}||_E||_F||_G||_H||_I||_.|||}|t,j:k(r#tc|tXsJ|jn5|t,j2k(r"tc|tdsJ|jtt |t&r|}n@|t,j:t,j2t,jvfvs |jt,j>vrHttjk(r-tstjdnt||||||}tt|j5jdk(rK|j5jAD](}|jtj|||*n)|jtj||||J| J|j||j| | r=|j| jr"|j| }|j| || ftj|<|tj|<t||t+|tj|<|dvr5d|}tjjdgj|nd|}tjj|gj||tj|<|| fS)a` Create a new distributed process group. This function must be called by ALL processes in the global group, even if the calling process is not part of the newly created group. In that case, this function returns GroupMember.NON_GROUP_MEMBER. This function is called with ``global_ranks_in_group == []`` for the default group. zTThe specified group name has already been created, please use a different group nameNrzKinit_process_group device_id parameter must be an accelerator with an indexrrr/rrzUnknown 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.rz.Distributed package doesn't have Gloo built inrWz.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 inzUnknown c10d backend type aTORCH_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.)r8 store_prefixrxrwr|rTr'ptd:ruser:)brJr&valuesrr)rlrXrr$rrLr_r6r:rwperform_nocolor_splitr0rPrrr/rr.rrrr_set_default_backendrrrrr=r.iterrrrrMrerpcreaterrKrsoptionsglobal_ranks_in_grouprrOrrqOptions_timeoutrris_high_priority_streamr9_process_group_color split_colorrrQrtrrRrurrrr rxrr;rTgroup_id_set_sequence_number_for_group issubclassrrDETAILrrr_create_process_group_wrapperrr_register_backendrr_set_group_name_set_group_descrr7eager_connect_single_devicer r*r1 setdefaultrr3)r;rrFrrxrrrTpg_tagr r>existing_groupr prefix_storeis_default_groupr9rrAr9custom_backendrrbackend_prefix_store backend_class backend_typebackend_pluginrrdist_backend_opts eager_backends rmr,r,=s 0V__++-- 9  )//"9Y^^u=T Y  ! Z26;PQ $mmN;OA|!</ / * 2 J01Q6.0@@&'9';<   (*//1 3 3001C1E1U1UV//5 5*Q/7L$B #7+N #g,3c'l#:'222U6KG94UU2 g'' '||~DDFMMOO'' (@(@(E(EF'' (@(@(E(EF  # #G$<$<<CCE E  # #L$<$<$A$A B    " " $!$w'7'7'<'<'>"?@N!B!B!I!I!KK'' (@(@(G(GH  # #L$<$<$A$A B&-DDFLLN^P  +fXQ<F '++ %#%"@ ,223HIM'3377L "33T99wwyB2779?!(!&&(!&&( '' 5 GLL (%&"#STT,$j*gM;PM ! ! 7/9M ! ! ,'3388L GLL ($&"#STT*!/3C3K3KL^L#++w6MM_ #3":":"<:?7'.O $-7*.B)/+5JO 1)3O &,$j*oM(3388L GKK ',<,> ,$j*gM(3377L GLL ($&"#STT.668O4IO 1)3O &'.O $,$j*oM(3388L$$&'*:*:: ,[->->-@,AB :%--k.?.?.ABN'22J)66L'33::L *(*j'! %?$@!*>!'/9!,/9!,,3!)-7!*:O!7 *+ >>  8 8 : GLL (m-=> >>  8 8 : d=)< 8B  GLL',, D D  "g&6&66 J$5$55&KKR%B#0%/2'#- ' %M s>88:AACD E J(??AFFH X$$U\\&%9<W X  U\\&1<O}^PB  !! !  !! !z"z"R__Y/BB 2 11)<!,/FMM"$FOOBJ+#&~#6FR   |$$$R,33B7!   ,33B7!FR | roc|tjk(ry|tj}n|}|Jtjj |d t dt|tk(r |jr|j||tjk(r%ttjddD]}|jtdtjjtjjtj jtj"jtj$jtj&jtj(jt+dt_y|jtj|=tj|=tj |=tj"|=|tj(j/vr&t1j2dtj(|=tj$j |}tj$|=|V tj&|j5||j7dr"tj&d j5|t;|j<y#t8$rY!wxYw) ay Destroy a given process group, and deinitialize the distributed package. Args: group (ProcessGroup, optional): The process group to be destroyed, if group.WORLD is given, all process groups including the default one will be destroyed. Nrc(tj|SrrJr&xs rmz'destroy_process_group..6??1+=roTrreverserzfSome coalesced collectives haven't been launched when ProcessGroup is destroyed. They will be cleaned.r>r)r0rPrKrJr$rrrlr _has_hooks_wait_for_pending_workssortedr&shutdownrclearr(r*r3r1r5rr.r=rrremove startswith Exceptionrr)rHrApg_to_shutdownrs rmr?r?jsS ,,, }     >> }}T"*:;; Bx<BMMO ""$ }!2!22% OO!=t  &N  # # % & 4  ##%  &&( !  &&(&( MM"  OOB   ! !" %  $ $R ( ))..0 0 MMC ((,""2&   R ? !!#&--b1>>&)%%b)004 ""--0  sAK>> L  L c|tjk(ry|xstj}|Jtjj |d t d |jtjd}||tjk(rytr t|tr|jttj ddD]}|j#tr t|tr|j%t'dtjj)tj j)tj*j)tj,j)tj.j)tj0j)tj2j)t5dt_y|j#tj|=tj |=tj*|=tj,|=|tj2j9vr&t;j<dtj2|=tj.j |}tj.|=|V tj0|j?||jAd r"tj0d j?|tE|jFy#t$rd}YwxYw#tB$rY3wxYw) aE Abort a given process group. If group.WORLD (i.e. `None`) is given, all process groups including the default one will be aborted. Args: group (ProcessGroup, optional): The process group to be aborted. .. note:: this API is experimental and currently only works with the NCCL backend. .. note:: this API should be used with `TORCH_NCCL_ASYNC_ERROR_HANDLING` turned off (i.e. set to 0). Otherwise, ProcessGroupNCCL's watchdog may automatically handle errors or timeouts for you including aborting the ProcessGroup. Nz6Invalid process group specified or has been destroyed.rc(tj|Srrcrds rmrfz&_abort_process_group..rgroTrhrzdSome coalesced collectives haven't been launched when ProcessGroup is aborted. They will be cleaned.r>r)$r0rPrKrJr$rrrrrrerOrrq _group_startrlr&abort _group_endrrnr(r*r3r1r5rr.r=rrrorprqrr)rHrAr pg_to_abortrs rm_abort_process_grouprys$ ,,,  #+##B >> }}T"*QRR//%,,v"67 }!2!22  :g7G#H  "! OO!=t  K       :g7G#H    4  ##%  &&( !  &&(&(  MM"  OOB   ! !" %  $ $R ( ))..0 0 MMA ((,""2&   R ? !!#&--b1>>&)%%b)004 ""--0u p  s%$MAM MM M"!M"ct|ryt}||tjur|j St ||j S)a Return the rank of the current process in the provided ``group``, default otherwise. Rank is a unique identifier assigned to each process within a distributed process group. They are always consecutive integers ranging from 0 to ``world_size``. Args: group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. Returns: The rank of the process group -1, if not part of the group r)rr_r0rKrwr_rs rmrErE sJ"% #%J }!2!22  %!2 33roc0t|ryt|S)a4 Return the number of processes in the current process group. Args: group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. Returns: The world size of the process group -1, if not part of the group r)rr<rs rmrFrF6 s%  5 !!rordst group_dstct|}t|||}t|dt|r t dy|j rt j|}|j|g||S)a] Send a tensor asynchronously. .. warning:: Modifying ``tensor`` before the request completes causes undefined behavior. .. warning:: ``tag`` is not supported with the NCCL backend. Unlike send, which is blocking, isend allows src == dst rank, i.e. send to self. Args: tensor (Tensor): Tensor to send. dst (int): Destination rank on global process group (regardless of ``group`` argument) group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. tag (int, optional): Tag to match send with remote recv group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst`` Returns: A distributed request object. None, if not part of the group rrSN) rrrrrrr view_as_realr])rr|rHrr}s rmrSrSI sk@ $E *E(Y?I*% 7# ##F+ ::vh 3 //rosrc group_srcct|dt|r tdy|jrt j |}t |}|||j|g|St|||}|j|g||S)aH Receives a tensor asynchronously. .. warning:: ``tag`` is not supported with the NCCL backend. Unlike recv, which is blocking, irecv allows src == dst rank, i.e. recv from self. Args: tensor (Tensor): Tensor to fill with received data. src (int, optional): Source rank on global process group (regardless of ``group`` argument). Will receive from any process if unspecified. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. tag (int, optional): Tag to match recv with remote send group_src (int, optional): Destination rank on ``group``. Invalid to specify both ``src`` and ``group_src``. Returns: A distributed request object. None, if not part of the group rrJN) rrrrrrrrecv_anysourcerrX)rrrHrrs rmrJrJv s:*% 7# ##F+ #E *E {y(##VHc22,UCC zz6(Is33roct|}t|||}t||dt||||}||j yy)a Send a tensor synchronously. .. warning:: ``tag`` is not supported with the NCCL backend. Args: tensor (Tensor): Tensor to send. dst (int): Destination rank on global process group (regardless of ``group`` argument). Destination rank should not be the same as the rank of the current process. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. tag (int, optional): Tag to match send with remote recv group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst``. destination)rHrr}N)rrrrSru)rr|rHrr}works rmr]r] sL0 $E *E(Y?I =9 u# CD  roct|||||}|y|j|6||j}t|}t ||dt ||}|S)a Receives a tensor synchronously. .. warning:: ``tag`` is not supported with the NCCL backend. Args: tensor (Tensor): Tensor to fill with received data. src (int, optional): Source rank on global process group (regardless of ``group`` argument). Will receive from any process if unspecified. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. tag (int, optional): Tag to match recv with remote send group_src (int, optional): Destination rank on ``group``. Invalid to specify both ``src`` and ``group_src``. Returns: Sender rank -1, if not part of the group )rrHrrrsource)rJru _source_rankrrr`)rrrHrrrs rmrXrX sg6 S3) LD |IIK {  ))+I'.UIx8eY/ JroceZdZdZy) _IllegalWorkc*|dvrtd|dy)N) is_success exceptionru source_rankrresult synchronizezIllegal to call z on IllegalWork objectr)rrs rmrz_IllegalWork.__getattribute__ s,   /v5KLM M roN)rrjrrrrormrr s Nrorc.eZdZddZddeefdZdZy)_CoalescingManagerNcg|_yr)worksrs rmrz_CoalescingManager.__init__ s !# rorc@|r|jj|yyr)rrrrs rmrz_CoalescingManager.append s  JJ  d # rocF|jD]}|jyr)rrurs rmruz_CoalescingManager.wait sJJ D IIK rorr)rrjrrrr!rrurrormrr s$$8D>$ror async_opsc#K|xs t}tjj|g}|r t d|r|j |t }|d}tjj|}|r|dj}|tk(r[|Dcgc]}|j}}t} t|dj| _|| _|j!|| }n|t"k(rng} g} |D]A}| j%|j| j%t|j&Ct)} || _|j+| | }n|t,k(rg} g} |D]A}| j%|j| j%t|j&Ct/} t|dj| _|| _|j1| | | }nt3d|d|d|r|j5|}|r|j%|y||j7yycc}ww)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 coalescingNrz>> # xdoctest: +SKIP("no rank") >>> # Synchronous ops >>> with _time_estimator() as cm: >>> for i in range(num_colls): >>> dist.all_reduce(tensors[i]) >>> # estimate time is stored in cm.estimated_time .. warning:: :func:`_time_estimator` currently only support NCCL backend but it can easily be extended to other backends. Also a NCCL communicator needs to be created because only with a real communicator can we do accurate estimation. The communicator internally has knowledge about the links it runs on (e.g. intra-node or inter-node, whether the links are NVLink or PCI-e or IB). zMcollective time estimator is not supported in the current version of backend N) r_rgrsupports_time_estimateNotImplementedError_start_time_estimater_end_time_estimater)rHrrrs rm_time_estimatorrl sB  )')E  4-e4F  (G  ) )![\c[d e     "  B H224BsA=A?rc t||dj}| t}|djj}dt dt ttffd}t|tk(r|j|jret||d5}|D]<}|j|jf|j|jd||> ddd|j Sg}|D]P}|j|jf|j|jd||}|s@|j#|R|S#1swYj SxYw) 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. rNrrgcL|jtk(rdnd}||jiS)Nr}r)rrSr)rrs rm peer_kwargz%batch_isend_irecv..peer_kwarg s"UUe^kR]]##roT)r)rHr)rrHr_rrr1rrr rlrrsupports_coalescingrrrrr)rrHrrrrreqsrs rmr:r: s[T{# N E }"$ ^ " " ) )F$u$c3h$ E{l"u'9'9&'A'U'U $ ? 2%  MM ,, !(   xx! "F699 llJJV$ D  D! " - xxs AEEasync_opcZt|}t|||d}t|dt|r t dyt }||_d|_||_|jrtj|}|j|g|}|r|S||jyy)ad Broadcasts the tensor to the whole group. ``tensor`` must have the same number of elements in all processes participating in the collective. Args: tensor (Tensor): Data to be sent if ``src`` is the rank of current process, and tensor to be used to save received data otherwise. src (int): Source rank on global process group (regardless of ``group`` argument). group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op group_src (int): Source rank on ``group``. Must specify one of ``group_src`` and ``src`` but not both. Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group Frrr;Nr)rrrrrrrootRank rootTensorrrrrr;ru)rrrHrroptsrs rmr;r; s: $E *E(YeTI*% ;'  DDMDODL ##F+ ??F8T *D    rocn|f}t|rtt|||||St|dt |r t dy|j r/t|std|dtj|}t}||_ ||_ | t}|tj j#vrBt%t|d|d}tj |j'||r t)Sy|j+|g|}|r|S||j-yy)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 rrHrrr5Nall_reduce does not support  on complex tensors)r%r$r5rrrrr^rrrrrwrr_rJr5r=rrr allreduceru)rrrHr relevant_argsrcollrs rmr5r5 s-lIM-($      *% <( #;B4?RST T##F+  DDMDL }"$ ((--//z64T:  '..t4 > ! ??F8T *D    roz`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-functionsct|tjr|g}t|dt |t |r t dytd|Drt|std|d|Dcgc])}|js|ntj|+}}t}||_ ||_|xs t}|j!||}|r|j#S||j%yycc}w)a WARNING: at this time individual shape checking is not implemented across nodes. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce operation will proceed without complaint and return erroneous outputs. This lack of shape checking results in significant performance improvements but users of this function should take extra care to ensure that each node passes in tensors whose shapes match across nodes. Reduces each tensor in tensors (residing on the same device) across all machines in such a way that all get the final result. After the call each tensor in tensors is going to bitwise identical in all processes. Complex tensors are supported. Args: tensors (Union[List[Tensor], Tensor]): Input and output of the collective. The function operates in-place. op (Optional[ReduceOp]): One of the values from ``torch.distributed.ReduceOp`` enum. Specifies an operation used for element-wise reductions. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (Optional[bool]): Whether this op should be an async op. Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group. rr6Nc3<K|]}|jywr)r)rts rmrz'all_reduce_coalesced.. s +a1<<> +rrr)rrr rrrranyr^rrrrrwrr_r get_futureru)rrrHrrrrs rmr6r6 sR'5<<()w)"7+% 12 +7 ++4DR4H7t;NOPPKRSa qE,>,>q,AASGS $ &DDMDL  )')E  $ $Wd 3D     Ts<.D ct|}t|||d}t|dt|r t dyt }||_||_||_|j|g|}|r|S||jyy)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 FrrrYN) rrrrrrrwrrrYru)rr|rrHrr}rrs rmrYrY s@ $E *E(YeTI*% 8$ ?DDMDMDL <<$ 'D    roctdj5tj}t |j |t jj|j}t j|j|}ttjk(rwtrmt!|}|t"j$k(rOt j&j(j+|g}t,j/d|j1|t j2|j1gj|}||fcdddS#1swYyxYw)Nz+pytorch.wait_counter.c10d._object_to_tensorz)_object_to_tensor size: %s hash value: %s)r#guardrBytesIO_picklerdumpr ByteStorage _from_bufferr ByteTensortorrrOrOrCr.rrr _hash_tensorsrwarningnumel LongTensor) rrrHf byte_storage byte_tensorrhash local_sizes rm_object_to_tensorr s C D J J L' JJL ((55ajjlC &&|477?   1 1 16G6I!%(G',,&xx11?? N?%%' %%{'8'8':&;<??G J&%'''s EE,,E5c>tdj5ttjk(rwt rmt |}|tjk(rOtjjj|g}tjd|j||j!}|j#j%d|}t't)j*|j-cdddS#1swYyxYw)Nz+pytorch.wait_counter.c10d._tensor_to_objectz)_tensor_to_object size: %s hash value: %s)r#rrrrOrOrCr.rrrrrrrrrnumpytobytes _unpicklerrrload)r tensor_sizerHrrrs rm_tensor_to_objectr s C D J J L 2   1 1 16G6I!%(G',,&xx11??I?QUlln$$&| 4"**S/*//1 2 2 2s C/DDct|r tdyt|}t|||\}}t |}t j |t j|}t|Dcgc]}||jd} }t| ||tt| j} |j| t j| |zt j |} t|Dcgc]}| | |z| |dzz} }t| ||t#| D]9\}} | j%t j } | |}t'| ||||<;ycc}wcc}w)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 responsibility to ensure that this is set so that each rank has an individual GPU, via ``torch.cuda.set_device()``. .. warning:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] r4Nrrrrdimr')rrrarrFrzeroslongr0 unsqueezer2r rsitemresize_emptyuint8 enumeraterlr) object_listrrHcurrent_device input_tensorrr;object_sizes_tensorr4object_size_listmax_object_sizecoalesced_output_tensoroutput_tensorsrrs rmr4r4 st% ./,U3N0neLL* e,J++%**^:?z9J45A((Q(/59#./4467O)#kk*$EKK z"  ! 3oQ6OPN~|59~.G 6U[[)&q) *6;F AG%s 2E4E9robject_gather_listct|}||d}t|||d}t|r tdy|j }t |||t |}t|||\}}t|} tj| tj|} t| D cgc]} | | jd} } t| ||tt!| j#} |j%| ||k(rMtj&| | ztj(|}t| D cgc]} || | z| | d zz}} t+|||k(rnd|| ||k7ry|Jd t-D]9\} }|j/tj(}| | }t1||||| <;ycc} wcc} w) a Gathers picklable objects from the whole group in a single process. Similar to :func:`gather`, but Python objects can be passed in. Note that the object must be picklable in order to be gathered. Args: obj (Any): Input object. Must be picklable. object_gather_list (list[Any]): Output list. On the ``dst`` rank, it should be correctly sized as the size of the group for this collective and will contain the output. Must be ``None`` on non-dst ranks. (default is ``None``) dst (int, optional): Destination rank on global process group (regardless of ``group`` argument). (If both ``dst`` and ``group_dst`` are None, default is global rank 0) group: (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. Default is ``None``. group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst`` Returns: None. On the ``dst`` rank, ``object_gather_list`` will contain the output of the collective. .. note:: Note that this API differs slightly from the gather collective since it does not provide an async_op handle and thus will be a blocking call. .. note:: For NCCL-based processed groups, internal tensor representations of objects must be moved to the GPU device before communication takes place. In this case, the device used is given by ``torch.cuda.current_device()`` and it is the user's responsibility to ensure that this is set so that each rank has an individual GPU, via ``torch.cuda.set_device()``. .. warning:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] NrFrrArrrr') gather_listr}rHz+Must provide object_gather_list on dst rank)rrrrrw_validate_output_list_for_rankrarrFrrrr0rr2r rsrrrrr@rrlr)rrr|rHr}rrrrr;rr4rrrrrrs rmrArA sP $E *E {y((YeTI% ?+JJLM"=)=OP,U3N0neLL* e,J++%**^:?z9J45A((Q(/ 59#./4467O) !"'++ j ( N#  :&  $Oa$7/QQRU:S T   &3y&@Nd   !  )X+XX )~.N 6U[[)&q) 1&+u M1N?  s /G  Gr use_batchc t|}t|||}t||dt|r t dy|xs t |}t |Dcgc]}t|||c}\}} tj| } |r:ttt| ||gjjnt| ||t!|dk(r|d} ntj|} |r:ttt| ||gjjyt| ||ycc}w)aF 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 use_batch (bool, optional): If True, use batch p2p operations instead of regular send operations. This avoids initializing 2-rank communicators and uses existing entire group communicators. See batch_isend_irecv for usage and assumptions. Default is ``False``. 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:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] rr<NrrH)r}rHr'r)rrrrrraziprrcatr:r1rSrrur]r) rr|rHrr}rrr tensor_list size_listr object_tensors rmr<r< s!R $E *E(Y?I =9% -.=6u=N CN OC C 7 OK ))I. 5-)5 Q R #% IUC  ;1#A  +.  5-IU K L #% ]iu=3 PsEct|}t|||}t||dt|r t dy|xs t |}t jt|t j|}|rHttt|||gj}|jt||} nt!|||} t jt j"|j%t j&|} |rHttt| ||gj}|jt||} nt!| ||} | | k(sJdd} t)|D]A\} }| | | |z}|j+t j&}| |z } t-||||| <C| S) ab 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``. use_batch (bool, optional): If True, use batch p2p operations instead of regular send operations. This avoids initializing 2-rank communicators and uses existing entire group communicators. See batch_isend_irecv for usage and assumptions. Default is ``False``. 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:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] rr=rrr)rHrz6Mismatch in return ranks for object sizes and objects.r)rrrrrrarrrrr:r1rJrrur`rXsumrrrrlr)rrrHrrrrrr rank_sizesr rank_objectsoffsetr4obj_sizeobj_views rmr=r=v sP $E *E(Y?I 84% -.=6u=N++ K >  '(     #%  $UI6 -UiP KK %&++-kkM  !(     #%  &ui8 M)L  %@ %F !45F 8 &8*;<==-(*8XuE A F roc ht|}||d}t|||d}t|r tdy|xs t |}|j }||k(r:t |Dcgc]}t|||c}\}} tj| } n/tjt|tj|} t| ||||k(r*tdk(r|d} n]tj|} nGtjtj| jtj |} t| ||d} ||k7rPt#| D]A\} }| | | |z}|j%tj }| |z } t'||||| <Cyycc}w) aj 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:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] NrFrr>rrrHr')rrrrrarwrrrrrrrr;r rrrrlr)rrrHrrrrrrrrrr r4r rs rmr>r>sT $E *E {y((YeTI% 23=6u=NJJLM !!$GR S^U; S"  Y$ii 2#kk  EJJ~  !YeD  ! { q 'NM!IIk2M II) * / / 1++! my> F !$%89 JKAx$Vfx.?@H}}U[[1H h F.x5IKN  J";Ts%F/scatter_object_output_listscatter_object_input_listc |t|}||d}t|||d}t|r tdyt |t rt |dkr td|j}t|}||k(rk| tdt|Dcgc]}t|||c}\}} t |t | } }t| } |D]} | j| n'tjdgtj | } t#| || tj$| j'tj(| } t+| ||k7rdn|| tjdgtj | } t+| ||k7rdn || t-| | ||d<ycc}w) a Scatters picklable objects in ``scatter_object_input_list`` to the whole group. Similar to :func:`scatter`, but Python objects can be passed in. On each rank, the scattered object will be stored as the first element of ``scatter_object_output_list``. Note that all objects in ``scatter_object_input_list`` must be picklable in order to be scattered. Args: scatter_object_output_list (List[Any]): Non-empty list whose first element will store the object scattered to this rank. scatter_object_input_list (List[Any], 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:: Object collectives have a number of serious performance and scalability limitations. See :ref:`object_collectives` for details. .. 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}] NrFrr\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_listrr) scatter_listrrH)rrrrrrrrrwrarrrsrrrrr;rrrr[r)rrrrHrr pg_devicerr tensor_sizesmax_tensor_sizer output_tensorobj_tensor_sizes rmr\r\sH $E *E {y((YeTI% 01 14 8 ) *Q . [  JJLM'.I ! $ ,M %(5"#y%8% ! \ %)$5tL7I\ l+! ,F NN? + , ,,s%**YO o%@KKekk)M *i7T[ llA3ejjKO *i7T\ %6%q!KsF9c|f}t|rtt|||||St|dt |dt ||t |r tdy|Dcgc])}|js|ntj|+}}|js|ntj|}|xs t}t}||_ |j|g|g|}|r|S||jyycc}w)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 rHrrrr2N)r%r$r2rrrrrrrrr_rr allgatherru)rrrHrrrrrs rmr2r2 s~IM-($       {M2*";7% <(EP?@U%7%7%::K",,.VE4F4Fv4NF  )')E  DDL ??K=6(D 9D    s#.Dc|f}t|rtt|||||St|dt|dt |r t dy|j s|ntj|}|j s|ntj|}t}||_ |xs t}|tjjvr@tt||}tj|j!||r t#Sy|j%|||}|r|S||j'yy)aN 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 rrrrcN)r%r$rcrrrrrrrrr_rJr5r=rrr_allgather_baseru)rrrHrrrrrs rmrcrcqsEl"OM-($ "      ~68% 34'')     .&&(     -  DDL  )')E ((--//-|]K  '..t4 > !   d CD    roz`torch.distributed._all_gather_base` is a private function and will be deprecated. Please use `torch.distributed.all_gather_into_tensor` instead.ct||||S)a$ Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor. Args: output_tensor (Tensor): Output tensor. It should contain correctly-sized tensors to be used for output of the collective. input_tensor (Tensor): Tensor to be broadcast from current process. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group .. warning:: `_all_gather_base` is a private function. Users should use `all_gather_into_tensor` instead. )rc)rrrHrs rm_all_gather_baser s6 "-uh OOroz`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 t|r tdyt|dt|t |t s t d|D]}t|dt||Dcgc]7}|Dcgc])}|js|ntj|+c}9}}}|Dcgc])}|js|ntj|+}}|xs t}t}||_ |j|||}|r|jS||jyycc}wcc}}wcc}w)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. r3Ninput_tensor_listz?Invalid function argument: output_tensor_lists should be a listoutput_tensor_lists)rrrrrrrVrrrr_rrallgather_coalescedrru) r#r"rHroutput_tensor_listlrrrs rmr3r3sUn% 12(*=>"#45 )4 0 M  2;-/DE&'9:; % FGG!,,.e&8&8&; ;G EV?@U%7%7%::  )')E  DDL  $ $%8:KT RD      Hs- D=6.D8 $D=0.E8D=cD||k(r|s tdy|r tdy)Nz?Argument ``gather_list`` must be specified on destination rank.zHArgument ``gather_list`` must NOT be specified on non-destination ranks.r)my_rankr|rs rmrrTs; g~Q   V   rorct|d|r t|dng}t||t|}t |r t dy||d}t |||d}|j}t|||||k(r|gng}|g}t} || _ || _ |j||| } |r| S| | jyy)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 rrr@NrFr)rrrrrrrrwrrrrr@ru) rrr|rHrr}rr input_tensorsrrs rmr@r@`sb*; 6 "6;7 #E *E% 8$ {y((YeTIJJLM"=)[I&/=&@k]bNHM ?DDMDL << t >> # 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 rrNrFrr[z;Argument ``scatter_list`` must be specified on source rank.zDArgument ``scatter_list`` must NOT be specified on non-source ranks.)rrrrrrrrrrrwrrrrr[ru) rrrrHrrrrr*rrrs rmr[r[sXp*<8 "6<8 #E *E {y((YeTI% 9%DP?@U%7%7%::L",,.VE4F4Fv4NFJJLMM!M &   V     DDMDL == =D    ;s%.D:ct|dt|dt||t|r t dyt }||_||_|xs t}|j|g|g|}|r|S||jyy)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_listrZN) rrrrrrrwrr_rZru)r-r.rrHrrrs rmrZrZs(*z<0"6:6% +,  !DDMDL  )')E   :, =D    roc |f}t|rtt||||||St|dt|dt |r t dyt }||_||_|xs t}|tjjvrBtt|||d}tj|j||r tSy|j!|||}|r|S||j#yy)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 rr-inputrdN)r%r$rdrrrrrwrr_rJr5r=rrr_reduce_scatter_baseru) r-r0rrHrrrrrs rmrdrdGsnHM-($ !     *(% 23  !DDMDL  )')E ((--//,eVRF  '..t4 > !  % %feT :D    roz`torch.distributed._reduce_scatter_base` is a private function and will be deprecated. Please use `torch.distributed.reduce_scatter_tensor` instead.c t|||||S)a Reduces, then scatters a flattened tensor to all processes in a group. Args: output (Tensor): Output tensor. input (Tensor): Input tensor that is of size output tensor size times world size group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op. Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group. .. warning:: `_reduce_scatter_base` is a private function. Users should use `reduce_scatter_tensor` instead. )rd)r-r0rrHrs rmr1r1s2 !E8 DDroc |f}t|rtt|||||||St|r t dyt }||_t|dt|dt|||jrtj|}|jrtj|}|gn|}|gn|}|xs t}|j|||||}|r|S||jyy)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_sizesinput_split_sizesrHrr8Nr-r0)r%r$r8rrrrrrrrrr_ alltoall_baseru) r-r0r4r5rHrrrrs rmr8r8sPHM-($    1/  % ./  DDL*("651 ""5) ##F+19?Q/7=N  )')E   )+>> # 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 r7Nr%r") rrrrrrrrrr_alltoallru)r%r"rHrrrrs rmr7r7]sz% <(  DDL)+?@(*=>"#57HIEV?@U%7%7%::EW?@U%7%7%::  )')E >>,.? FD    s .C..C3c|xs t}t|r tdyt}||_t j j}t|tr0||_ t j|j|d|_ nt|dd|j|_ ng|jdk(st|dk(rt jd|_ n/||_ |j!dk(rt#j$d|j'|}|r|S||j)yy)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. Only one id is expected. 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. .. note:: `ProcessGroupNCCL` implements barrier as an all_reduce of a 1-element tensor. A device must be chosen for allocating this tensor. The device choice is made by checking in this order (1) the first device passed to `device_ids` arg of barrier if not None, (2) the device passed to init_process_group if not None, (3) the device that was first used with this process group, if another collective with tensor inputs has been performed, (4) the device index indicated by the global rank mod local device count. r9Nrr6rz|barrier(): using the device under current context. You can specify `device_id` in `init_process_group` to mute this warning.)r)r_rrrrrrrrr device_idsrrlrr6rarwrrr9ru)rHrr:rrrs rmr9r9s6  )')E% 9%  DDLXX & & (F*d#$ll6;; 1 > )4 0 <++  !8!?5!Hll5)  ::<1  MM\  ==d= #D    rocnt|r tdyt|tjk7r t d|t t|}n5t|tr%tjd|dt|}t|| tn|}|j||S)a Synchronize processes similar to ``torch.distributed.barrier``, but consider a configurable timeout. It is able to report ranks that did not pass this barrier within the provided timeout. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0. Rank 0 will block until all send /recv from other ranks are processed, and will report failures for ranks that failed to respond in time. Note that if one rank does not reach the monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier. This collective will block all processes/ranks in the group, until the whole group exits the function successfully, making it useful for debugging and synchronizing. However, it can have a performance impact and should only be used for debugging or scenarios that require full synchronization points on the host-side. For debugging purposes, this barrier can be inserted before the application's collective calls to check if any ranks are desynchronized. .. note:: Note that this collective is only supported with the GLOO backend. Args: group (ProcessGroup, optional): The process group to work on. If ``None``, the default process group will be used. timeout (datetime.timedelta, optional): Timeout for monitored_barrier. If ``None``, the default process group timeout will be used. wait_all_ranks (bool, optional): Whether to collect all failed ranks or not. By default, this is ``False`` and ``monitored_barrier`` on rank 0 will throw on the first failed rank it encounters in order to fail fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will collect all failed ranks and throw an error containing information about all failed ranks. Returns: ``None``. Example:: >>> # xdoctest: +SKIP("need process group init") >>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() != 1: >>> dist.monitored_barrier() # Raises exception indicating that >>> # rank 1 did not call into monitored_barrier. >>> # Example with wait_all_ranks=True >>> if dist.get_rank() == 0: >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into >>> # monitored_barrier. rTNz7monitored_barrier is only implemented for GLOO backend.zGPlease specify timeout arg as a timedelta. Converting current value of z assuming it represents secondsrk)wait_all_ranks)rrrCr.rrrSrfloatrrrrXr_rT)rHrTr< group_to_uses rmrTrTsl% ./5W\\)RSS&{5'9: GU #  ++2)3R T G,!+0=%'eL  ) ) * ror8r=ctsJdtd|}t||}t||||}t ||}|S)Nz5ProcessGroupWrapper unsupported without GLOO backend.rrW)rPG_WRAPPER_STORE_PREFIXrrsrr)r8r=rxrwr|rTprefix helper_pgs rmrPrPksS SSS? ((, 8F  &E j'JI%j)&?@AJ <<j'2E J T T VVroct|}t|}dtjtjdzdz z}t ||z}|S)Nrr')rErctypessizeofc_intabs)r: hash_value max_c_intcolors rmrJrJsJ %LEeJ fmmFLL1A59:I  Oi 'E Lroc|r t|}|Sttj}txjdz c_|SNr')rKrrJr.)r:r r7s rmr+r+s@$U+ Nf(()a NrocB|stt}t|Sr)rCr_r.rRs rm_get_backend_from_strrXs  023 7 roc2tjdSdS)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_r6rrorm_is_safe_to_splitrZs'(88@5JdJro parent_pg split_ranksr>c|t|dk(r tdt}|j}|s t d|j }|j }|s|}|tjvrtd|dtj|} | jD cic]\}} | | } }} | vrtd|d|| |} |jtjd } | r | js t d t| d r!||jd | j!}tj"|\}}t%|}t'|}| | j(}| t+|}t-||d}|D]r}t|dk(r td t||kDr tdt|tt/|k7r tdt1|}| |vsp|}nt3|d}|j5|||||}|y|Dcgc]}| | }}||_|jtjd }|j7|j8|k(sJd|d|j8||j;ftj"|<|tj<|<t?||tA|tjB|<d|}tjDjG|gjI||tjJ|<tM|D cic]\} }||  c}} tj|<|Scc} }wcc}wcc}} w)aW Create a new process group split from the given parent process group. warning:: This is an experimental API. Only the ``NCCL`` and custom plugin backends are supported. Other backends will raise an error. Users of this API must guarantee 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 guarantee 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): 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. 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`. Nrz#split_ranks cannot be None or emptyzNNo device associated with the default pg, not safe to split any process groupsrz is not registeredrz! is not part of the parent group rzQNo backend for the parent process group or its backend does not support splittingcomm_split_countz:split:zthe 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 )rTrrr>zgroup name should be set to z but got r>)'rrr_r6rerwrrJr(rrrrr7rr>r^r$r.r/rErSrXrrrlr+rfrMrget_group_storer&r rr*r1rUrr3r)r[r\rTrr>rr rglobal_world_sizeparent_global_to_group_ranksrparent_group_to_global_ranksparent_group_rankparent_backendparent_backend_strrrr9my_grouprfrsplit_pgrwglobal_ranks_in_my_groupsplit_backend_classrVs rmrfrfsNc+.!3>??$%J**I  \  //#K")  ---6),>?@@#)#8#8#C (D'I'I'K$ #K K$ $ 66;-'H T  5[A++ELL,@AN !B!B _  ~12z7I!,,-W^5T5T5V4WX "MM)4()G"7+N#++ &w/! 1~H"  { q >? ? { / /l  { s3{#34 4JK K[)  +"H  %XuEJ$$  %HOWXt ` 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 available options to config nccl, See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-tuse_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 overlapping process groups. To avoid that, make sure all ranks follow the same global creation order. N)use_local_synchronizationr>r )_new_group_with_tag)r:rTrrrkr>r s rmrUrUNs*\   ";  roc t}| |j}n"|j||jk(sJdtj|\} } |j } |j } |s| }t |}| t|}t||r-|t jk(r td| t|vry|[t|}t|} | | kDr td|D]}|dks|| k\std| |vr|j| }nd}ntt!| }| } | }t#||}t%| |||| |||||| \}}t'|D cic]\}} | | c} }tj(|<t+d k(r`t,j/d |t jk(r t1|S|r|n| }|r t|n t3}t5 |||||Scc} }w) 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_grouprzNThe new group's rank should be within the world_size set by init_process_groupr )rrTrVr r>r'r")r_r6rJr$rwrr.rSrXrrrErlrr)rr0r+r,rr(rrrr9rFr)r:rTrrrVrkr>r rdefault_backendrrr`group_world_sizerwrrrAr barrier_storer|s rmrlrlsZ$$%J..  # # /J666 H 6&,]]:%>"O]//#K") !gG&w/! gkk !L   5!8 u u: / /%   Dax4#44 ?  % [1JJU,-., $U>> # 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) zDefault 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.rzThe arg 'group_size' (z) must be positiverz") must not exceed the world size (rzThe world size (z#) must be divisible by 'group_size=')rTrrr>) rr is_availablerr*rFrar0rrW) r;rHrTrrr>r|r:r4ranks_per_subgroup_lists rmrVrV%s$Tzz&&(9  ZZ,,. Q1*=OPQQe,JJ$ZL0RS]R^^_ `  J!#zl*N:-q Q  $% 0E+0CJ +K&'a!j.! (  s?C c <|t|dk(r tdg}d}i}|D]s}t|||||} |j| t } |D]A} | |vrtd| d|| d|||| <| | k(s)| }t j d| |Cu||fS) 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 Nrz1The arg 'ranks_per_subgroup_list' cannot be empty)r:rTrrr>zRank z has appeared in both subgroup z and z"Rank %s is assigned to subgroup %s)rrrUrrErr) rtrTrrr> subgroups cur_subgrouprank_to_ranks_dictr:subgroupr(rws rmrWrWsp&#.E*F!*KLMMIL(O!!   "* OD)) D6!@ASTXAY@ZZ_`e_fg(- t $$'  @$N OO(  ""roc>t|dkDr'|jds|jdsd|}tjj |gD]D}|j t|k7r t |tfd|D}|sB|cSy)Nrr>r?c3&K|]}|v ywrr)rrrs rmrz,_find_pg_by_ranks_and_tag..s31 #3s)rrprJr1rrrar)rr:rHgoodrs @rmrrs 3x!|CNN623>>';RcUm""&&sB/ ::<3u: % -e4 3U33 L rostridect||zdk(sJdt|d|dt}d}|t|k(r|j}||vs:Jdtdt||D]}||||z}||vs|}|Jdt |}t ||}||S|dk(r t dt||S) NrzRanks length (z) must be divisible by stride (rz(rankset doesn't include the current noderz-Cannot automatically create PG with empty tag)rV)rrEcopyr0rlrrrl)rr:r~r(my_ranksr4rank_setrAs rm#_find_or_create_pg_by_ranks_and_tagrs u: ! # U $CF81M #jGH U::<("N$NN"q#e*f- $AQV,H("# $#O%OO#hH "3 1B ~  byHII x 44rocNtj|}|jd}|S)z&Return the tag associated with ``pg``.r?)rJr3 removeprefix)rArs rm_get_group_tagrs'   2 C  7 #C JrocBtjj|dS)NNone)rJr&rrAs rmrrs ??  r6 **roc.tj|dSrV)rJr$rs rm_get_process_group_storer!s == Q rorr)NNF) NNNrrNrNN)NNNNNr )NN)NNFN)NNNN)NNNNF)NF)NNNFN)NNNF)NNNNFNN)NNNNNFNN)NNNNNN)rcollections.abc collections contextlibrNrErrloggingrpicklerrtrrdatetimertypingrrrrr typing_extensionsr rtorch._Cr rvtorch._C._distributed_c10dr r rrrrrrrrrrrrrrrrrrr r!torch._utils_internalr" torch.monitorr#torch.overridesr$r%torch.utils._typing_utilsr& c10d_loggerr(r) constantsr*r+r-r,__all__rrrrrPicklerr Unpicklerrrnrprj ImportErrorrqrrrsrtru getLoggerrrr@boolr^rr.r/rrbr1rrrrErrrr rr-rrrrrrJrlrGrHr0rSrXrYrorarrgrirrrr_r`rrrar<rrrrrrrabcIterablerrrrrMrOrKrQrRrNrLrPrr_rrrBrCrDrrrrGrerrrIr:r,r?ryrErFr rSrJr]rXrrcontextmanagerrrrr:r;SUMr5r6rYrrr4rAr<r=r>r\r2rcr r3rr@r[rZrdr1r8r7rKr9rTrrrPrKrJr+rXrZrfrUrlrVrWrrrrrrrormrs;2   "@@( 60N&E.8B?K Z >>    ?.:!EO !""G;"F "##GQ"F "##G:!EO !""G;"F "##G   8 $& $x $D $TcTDM'M'`220 L C|C|L:24lE#u*-- .3%' 4 c! "'68lDcN238.0Ds*+0 -/ T#tL)) */&( Ds" #((3-||~ i"$j$J "' "i " # $ *.#-6>8L#9>S>BK(<"8KELLK\ ;h|4 ;S ;r* A AAH1h|411$,$S$S$8N<NSNSN8 N  (S(  ( M8L#9 Md3i Mc S    8L#9\"& $  #    4  C C 4114( @&$ 4 4 $ 4 3#3$3()) 8$ 8:: !L ! E 6 )h|4))(*x -**45ell1B+C.| (<0 DcN T$sCx.1cx}48 8d86(.Y(.x /E(.QU(.V !!%#'! $48]O c]]O#]Oi ]O ]O  ]O E? ]O]O ]OellC/01]O ]O]O@ :  jZ T1,!7T1nW1 6W1t4H\*4c46"(<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 N4 N   $(%)\ L !\ U\\ "\\\@44  $(%)*5 L !*5 U\\ "*5*5ZL4;L4:L^$(# / LL/ #/ L !/ / } //f",,dU``H J  &.\\: :|||$(# 0 LL0 #0 L ! 0  0 } 00h', 2[G[G|/3$(# }N }N c+}N #}N L ! }N } }N}N@$(%)# r>cr> #r> L !r> U\\ " r> } r>  r>r>j$(%)# KcK #K L !K U\\ " K } K  KK\$(%)# ~Jc~J #~J L !~J U\\ " ~J } ~J~JB6:$(# B $S B'S 2B #B L ! B } BBJ__FffT E  P  P0 J BGO Of  15$(# N LLN$u||,-N #N L ! N  N } NNd26$(# d LLd4 -.d #d L ! d  d } ddP*2,,dU&&T,4LLu``H D  ,4<|+ ++  % ekNOONOsZ2g'g5h0hh'g21g25h?hh hhhh*)h*