distributed_c10d.py 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242
  1. import contextlib
  2. import io
  3. import logging
  4. import os
  5. import pickle
  6. import time
  7. import warnings
  8. from datetime import timedelta
  9. from typing import Callable, Dict, Optional, Tuple, Union
  10. import torch
  11. from torch._C._distributed_c10d import (
  12. AllreduceCoalescedOptions,
  13. AllreduceOptions,
  14. AllToAllOptions,
  15. BarrierOptions,
  16. BroadcastOptions,
  17. GatherOptions,
  18. PrefixStore,
  19. ProcessGroup,
  20. ReduceOp,
  21. ReduceOptions,
  22. ReduceScatterOptions,
  23. ScatterOptions,
  24. Store,
  25. DebugLevel,
  26. get_debug_level,
  27. )
  28. from torch._six import string_classes
  29. from .constants import default_pg_timeout
  30. from .rendezvous import register_rendezvous_handler, rendezvous # noqa: F401
  31. # This module is wildcard imported from torch.distributed.
  32. # TODO: specify __all__
  33. _MPI_AVAILABLE = True
  34. _NCCL_AVAILABLE = True
  35. _GLOO_AVAILABLE = True
  36. _pickler = pickle.Pickler
  37. _unpickler = pickle.Unpickler
  38. try:
  39. from torch._C._distributed_c10d import ProcessGroupMPI
  40. except ImportError:
  41. _MPI_AVAILABLE = False
  42. try:
  43. from torch._C._distributed_c10d import ProcessGroupNCCL
  44. except ImportError:
  45. _NCCL_AVAILABLE = False
  46. try:
  47. from torch._C._distributed_c10d import ProcessGroupGloo
  48. from torch._C._distributed_c10d import _ProcessGroupWrapper
  49. except ImportError:
  50. _GLOO_AVAILABLE = False
  51. logger = logging.getLogger(__name__)
  52. PG_WRAPPER_STORE_PREFIX = "pg_wrapper"
  53. # Some reduce ops are not supported by complex numbers and will result in an error.
  54. # We currently provide complex support to the distributed API by viewing
  55. # complex tensors as real (torch.view_as_real), meaning that calling
  56. # these unsupported ops will return garbage values rather than error out.
  57. # (e.g. max(2+3i, 3+2i) = 3+3i)
  58. # We'd like calls to unsupported ops to error out accordingly,
  59. # rather than returning garbage values.
  60. def supports_complex(reduceOp: ReduceOp) -> bool:
  61. denyList = [
  62. ReduceOp.MAX,
  63. ReduceOp.MIN,
  64. ReduceOp.PRODUCT,
  65. ReduceOp.BAND,
  66. ReduceOp.BOR,
  67. ReduceOp.BXOR,
  68. ]
  69. return reduceOp not in denyList
  70. class Backend(object):
  71. """
  72. An enum-like class of available backends: GLOO, NCCL, MPI, and other registered
  73. backends.
  74. The values of this class are lowercase strings, e.g., ``"gloo"``. They can
  75. be accessed as attributes, e.g., ``Backend.NCCL``.
  76. This class can be directly called to parse the string, e.g.,
  77. ``Backend(backend_str)`` will check if ``backend_str`` is valid, and
  78. return the parsed lowercase string if so. It also accepts uppercase strings,
  79. e.g., ``Backend("GLOO")`` returns ``"gloo"``.
  80. .. note:: The entry ``Backend.UNDEFINED`` is present but only used as
  81. initial value of some fields. Users should neither use it directly
  82. nor assume its existence.
  83. """
  84. UNDEFINED = "undefined"
  85. GLOO = "gloo"
  86. NCCL = "nccl"
  87. MPI = "mpi"
  88. TCP = "tcp"
  89. _plugins: Dict[str, Callable] = {}
  90. def __new__(cls, name: str):
  91. if not isinstance(name, string_classes):
  92. raise ValueError("Backend name must be a string, but got: {}".format(name))
  93. value = getattr(Backend, name.upper(), Backend.UNDEFINED)
  94. if value == Backend.TCP:
  95. raise ValueError(
  96. "TCP backend has been deprecated. Please use "
  97. "Gloo or MPI backend for collective operations "
  98. "on CPU tensors."
  99. )
  100. elif value == Backend.UNDEFINED:
  101. raise ValueError("Invalid backend: '{}'".format(name))
  102. elif value != Backend.GLOO and value != Backend.NCCL and value != Backend.MPI:
  103. value = name.lower()
  104. return value
  105. @classmethod
  106. def register_backend(cls, name, func):
  107. """
  108. Registers a new backend with the given name and instantiating function.
  109. This class method is used by 3rd party ``ProcessGroup`` extension to
  110. register new backends.
  111. Args:
  112. name (str): Backend name of the ``ProcessGroup`` extension. It
  113. should match the one in ``init_process_group()``.
  114. func (function): Function handler that instantiates the backend.
  115. The function should be implemented in the backend
  116. extension and takes four arguments, including
  117. ``store``, ``rank``, ``world_size``, and ``timeout``.
  118. .. note:: This support of 3rd party backend is experimental and subject to change.
  119. """
  120. assert not hasattr(Backend, name.upper()), (
  121. f"{name.upper()} c10d backend already exist"
  122. )
  123. assert name.upper() not in Backend._plugins, (
  124. f"{name.upper()} c10d backend creator function already exist"
  125. )
  126. setattr(Backend, name.upper(), name.upper())
  127. Backend._plugins[name.upper()] = func
  128. # `_backend`, `dist_backend`, and `reduce_op` are here to maintain backward
  129. # compatibility with pre-c10d distributed package.
  130. # TODO: remove them when users are ready to take a hard dependency on PyTorch 1.
  131. _backend: str = Backend.UNDEFINED
  132. dist_backend = Backend
  133. class _reduce_op(object):
  134. r"""
  135. Deprecated enum-like class for reduction operations: ``SUM``, ``PRODUCT``,
  136. ``MIN``, and ``MAX``.
  137. :class:`~torch.distributed.ReduceOp` is recommended to use instead.
  138. """
  139. def __init__(self):
  140. # __members__ is a dict storing key-value pairs for enum classes
  141. for k, v in ReduceOp.__members__.items():
  142. setattr(self, k, v)
  143. self.__members__ = ReduceOp.__members__
  144. def __getattribute__(self, key):
  145. warnings.warn(
  146. "torch.distributed.reduce_op is deprecated, please use "
  147. "torch.distributed.ReduceOp instead"
  148. )
  149. return object.__getattribute__(self, key)
  150. reduce_op = _reduce_op()
  151. class group(object):
  152. # Points to the default PG once initialized.
  153. WORLD: Optional[ProcessGroup] = None
  154. class GroupMember(object):
  155. # Alias to group.WORLD for backward compatibility
  156. WORLD = group.WORLD
  157. NON_GROUP_MEMBER = object()
  158. # Cached process groups
  159. # For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
  160. # For MPI pg, it is a map from ProcessGroup to (Backend, None)
  161. _pg_map: Dict[ProcessGroup, Tuple[str, Optional[Store]]] = {}
  162. # Process group's names, map from ProcessGroup to str
  163. _pg_names: Dict[ProcessGroup, str] = {}
  164. # Process group's global rank to local rank mapping
  165. _pg_group_ranks: Dict[ProcessGroup, Dict[int, int]] = {}
  166. # Default process group state
  167. _default_pg_init_method = None
  168. # Process group count for default naming
  169. _group_count = 0
  170. STORE_BASED_BARRIER_PREFIX = "store_based_barrier_key"
  171. def _store_based_barrier(rank, store, timeout):
  172. """
  173. Barrier based on store which is used for synchronizing processes after
  174. ``init_process_group`` or ``new_group``. Intended to be used only with
  175. those two methods and is not a generic alternative to ``barrier()``.
  176. """
  177. store_key = "{}:{}".format(STORE_BASED_BARRIER_PREFIX, _group_count)
  178. store.add(store_key, 1)
  179. logger.info("Added key: {} to store for rank: {}".format(store_key, rank))
  180. # Now wait for all workers to check in with the store.
  181. world_size = get_world_size()
  182. # Use 'add' instead of 'get' since for some store implementations 'add'
  183. # doesn't work well with 'get'. Ideally the store implementations should
  184. # be fixed, but for backward compatiblity reasons it is risky to change
  185. # the store implementations. Once, we completely migrate away from these
  186. # legacy stores, we can use 'get' here instead.
  187. worker_count = store.add(store_key, 0)
  188. start = time.time()
  189. log_time = time.time()
  190. while worker_count != world_size:
  191. time.sleep(0.01)
  192. worker_count = store.add(store_key, 0)
  193. # Print status periodically to keep track.
  194. if timedelta(seconds=(time.time() - log_time)) > timedelta(seconds=10):
  195. logger.info(
  196. "Waiting in store based barrier to initialize process group for "
  197. "rank: {}, key: {} (world_size={}, worker_count={}, timeout={})".format(
  198. rank, store_key, world_size, worker_count, timeout
  199. )
  200. )
  201. log_time = time.time()
  202. if timedelta(seconds=(time.time() - start)) > timeout:
  203. raise RuntimeError(
  204. "Timed out initializing process group in store based barrier on "
  205. "rank: {}, for key: {} (world_size={}, worker_count={}, timeout={})".format(
  206. rank, store_key, world_size, worker_count, timeout
  207. )
  208. )
  209. logger.info(
  210. f"Rank {rank}: Completed store-based barrier for key:{store_key} with {world_size} nodes."
  211. )
  212. def _rank_not_in_group(group: ProcessGroup):
  213. """
  214. Helper that checks if the current process's rank is not in a given group.
  215. """
  216. if group is None:
  217. return False
  218. return group == GroupMember.NON_GROUP_MEMBER
  219. def _warn_not_in_group(op_name):
  220. global_rank = -1 if GroupMember.WORLD is None else GroupMember.WORLD.rank()
  221. warnings.warn(
  222. f"Running {op_name} on global rank {global_rank} which does not "
  223. "belong to the given group."
  224. )
  225. def _get_group_rank(group: ProcessGroup, rank):
  226. """
  227. Helper that gets a given group's local rank in the group from a given global
  228. rank.
  229. """
  230. if group is GroupMember.WORLD:
  231. raise RuntimeError(
  232. "group.WORLD does not have local rank to global " "rank mapping"
  233. )
  234. if group not in _pg_group_ranks:
  235. raise RuntimeError("The given group does not exist")
  236. try:
  237. group_rank = _pg_group_ranks[group][rank]
  238. except KeyError:
  239. raise RuntimeError(
  240. f"The global rank {rank} is not part of the group {group}"
  241. ) from None
  242. return group_rank
  243. def _get_global_rank(group, group_rank):
  244. """
  245. Helper that gets a given group's global rank from a given local rank in the
  246. group.
  247. """
  248. if group is GroupMember.WORLD:
  249. raise RuntimeError(
  250. "group.WORLD does not have local rank to global " "rank mapping"
  251. )
  252. group_rank_map = _pg_group_ranks[group]
  253. for rank, grp_rank in group_rank_map.items():
  254. if grp_rank == group_rank:
  255. return rank
  256. raise RuntimeError("The group rank is not part of the group")
  257. def _get_group_size(group):
  258. """
  259. Helper that gets a given group's world size.
  260. """
  261. if group is GroupMember.WORLD or group is None:
  262. default_pg = _get_default_group()
  263. return default_pg.size()
  264. return group.size()
  265. def _check_single_tensor(param, param_name):
  266. """
  267. Helper to check that the parameter ``param_name`` is a single tensor.
  268. """
  269. if not isinstance(param, torch.Tensor):
  270. raise RuntimeError(
  271. "Invalid function argument. Expected parameter `{}` "
  272. "to be of type torch.Tensor.".format(param_name)
  273. )
  274. def _check_tensor_list(param, param_name):
  275. """
  276. Helper to check that the parameter ``param_name`` is a list of tensors.
  277. """
  278. if not isinstance(param, list) or not all(
  279. isinstance(p, torch.Tensor) for p in param
  280. ):
  281. raise RuntimeError(
  282. "Invalid function argument. Expected parameter `{}` "
  283. "to be of type List[torch.Tensor].".format(param_name)
  284. )
  285. def _check_op(op):
  286. """
  287. Helper to check that the ``op`` is either isend or irecv.
  288. """
  289. if op not in [isend, irecv]:
  290. raise RuntimeError(
  291. "Invalid ``op``. Expected ``op`` "
  292. "to be of type ``torch.distributed.isend`` or "
  293. "``torch.distributed.irecv``."
  294. )
  295. def _check_p2p_op_list(p2p_op_list):
  296. """
  297. Helper to check that the ``p2p_op_list`` is a list of P2POp instances and
  298. all ops use the same backend.
  299. """
  300. if not isinstance(p2p_op_list, list) or not all(
  301. isinstance(p2p_op, P2POp) for p2p_op in p2p_op_list
  302. ):
  303. raise RuntimeError(
  304. "Invalid ``p2p_op_list``. Each op is expected to "
  305. "to be of type ``torch.distributed.P2POp``."
  306. )
  307. backend = get_backend(p2p_op_list[0].group)
  308. if not all(backend == get_backend(p2p_op.group) for p2p_op in p2p_op_list):
  309. raise RuntimeError("All groups need to use the same backend.")
  310. def is_mpi_available():
  311. """
  312. Checks if the MPI backend is available.
  313. """
  314. return _MPI_AVAILABLE
  315. def is_nccl_available():
  316. """
  317. Checks if the NCCL backend is available.
  318. """
  319. return _NCCL_AVAILABLE
  320. def is_gloo_available():
  321. """
  322. Checks if the Gloo backend is available.
  323. """
  324. return _GLOO_AVAILABLE
  325. def is_initialized():
  326. """
  327. Checking if the default process group has been initialized
  328. """
  329. return GroupMember.WORLD is not None
  330. def is_torchelastic_launched():
  331. """
  332. Checks whether this process was launched with ``torch.distributed.elastic``
  333. (aka torchelastic). The existence of ``TORCHELASTIC_RUN_ID`` environment
  334. variable is used as a proxy to determine whether the current process
  335. was launched with torchelastic. This is a reasonable proxy since
  336. ``TORCHELASTIC_RUN_ID`` maps to the rendezvous id which is always a
  337. non-null value indicating the job id for peer discovery purposes..
  338. """
  339. return os.getenv("TORCHELASTIC_RUN_ID") is not None
  340. def _get_default_group():
  341. """
  342. Getting the default process group created by init_process_group
  343. """
  344. if not is_initialized():
  345. raise RuntimeError(
  346. "Default process group has not been initialized, "
  347. "please make sure to call init_process_group."
  348. )
  349. return GroupMember.WORLD
  350. def _get_default_store():
  351. """
  352. Getting the default store created by init_process_group
  353. """
  354. if not is_initialized():
  355. raise RuntimeError(
  356. "Default process group has not been initialized, "
  357. "please make sure to call init_process_group."
  358. )
  359. default_pg = _get_default_group()
  360. _, default_store = _pg_map[default_pg]
  361. return default_store
  362. def _update_default_pg(pg):
  363. GroupMember.WORLD = group.WORLD = pg
  364. def get_backend(group=None):
  365. """
  366. Returns the backend of the given process group.
  367. Args:
  368. group (ProcessGroup, optional): The process group to work on. The
  369. default is the general main process group. If another specific group
  370. is specified, the calling process must be part of :attr:`group`.
  371. Returns:
  372. The backend of the given process group as a lower case string.
  373. """
  374. if group is None:
  375. pg = _get_default_group()
  376. else:
  377. pg = group
  378. if _rank_not_in_group(pg):
  379. raise RuntimeError("Invalid process group specified")
  380. pg_store = _pg_map.get(pg, None)
  381. assert pg_store is not None
  382. return pg_store[0]
  383. def init_process_group(
  384. backend,
  385. init_method=None,
  386. timeout=default_pg_timeout,
  387. world_size=-1,
  388. rank=-1,
  389. store=None,
  390. group_name="",
  391. pg_options=None,
  392. ):
  393. """
  394. Initializes the default distributed process group, and this will also
  395. initialize the distributed package.
  396. There are 2 main ways to initialize a process group:
  397. 1. Specify ``store``, ``rank``, and ``world_size`` explicitly.
  398. 2. Specify ``init_method`` (a URL string) which indicates where/how
  399. to discover peers. Optionally specify ``rank`` and ``world_size``,
  400. or encode all required parameters in the URL and omit them.
  401. If neither is specified, ``init_method`` is assumed to be "env://".
  402. Args:
  403. backend (str or Backend): The backend to use. Depending on
  404. build-time configurations, valid values include ``mpi``, ``gloo``,
  405. and ``nccl``. This field should be given as a lowercase string
  406. (e.g., ``"gloo"``), which can also be accessed via
  407. :class:`Backend` attributes (e.g., ``Backend.GLOO``). If using
  408. multiple processes per machine with ``nccl`` backend, each process
  409. must have exclusive access to every GPU it uses, as sharing GPUs
  410. between processes can result in deadlocks.
  411. init_method (str, optional): URL specifying how to initialize the
  412. process group. Default is "env://" if no
  413. ``init_method`` or ``store`` is specified.
  414. Mutually exclusive with ``store``.
  415. world_size (int, optional): Number of processes participating in
  416. the job. Required if ``store`` is specified.
  417. rank (int, optional): Rank of the current process (it should be a
  418. number between 0 and ``world_size``-1).
  419. Required if ``store`` is specified.
  420. store(Store, optional): Key/value store accessible to all workers, used
  421. to exchange connection/address information.
  422. Mutually exclusive with ``init_method``.
  423. timeout (timedelta, optional): Timeout for operations executed against
  424. the process group. Default value equals 30 minutes.
  425. This is applicable for the ``gloo`` backend. For ``nccl``, this is
  426. applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
  427. or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When
  428. ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the
  429. process will block and wait for collectives to complete before
  430. throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,
  431. this is the duration after which collectives will be aborted
  432. asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``
  433. will provide errors to the user which can be caught and handled,
  434. but due to its blocking nature, it has a performance overhead. On
  435. the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has very little
  436. performance overhead, but crashes the process on errors. This is
  437. done since CUDA execution is async and it is no longer safe to
  438. continue executing user code since failed async NCCL operations
  439. might result in subsequent CUDA operations running on corrupted
  440. data. Only one of these two environment variables should be set.
  441. group_name (str, optional, deprecated): Group name.
  442. pg_options (ProcessGroupOptions, optional): process group options
  443. specifying what additional options need to be passed in during
  444. the construction of specific process groups. As of now, the only
  445. options we support is ``ProcessGroupNCCL.Options`` for the ``nccl``
  446. backend, ``is_high_priority_stream`` can be specified so that
  447. the nccl backend can pick up high priority cuda streams when
  448. there're compute kernels waiting.
  449. .. note:: To enable ``backend == Backend.MPI``, PyTorch needs to be built from source
  450. on a system that supports MPI.
  451. """
  452. global _pg_group_ranks
  453. global _backend
  454. global _default_pg_init_method
  455. if not isinstance(timeout, timedelta):
  456. raise RuntimeError(
  457. "Expected timeout argument to be of type" "datetime.timedelta"
  458. )
  459. if GroupMember.WORLD is not None:
  460. raise RuntimeError("trying to initialize the default process group " "twice!")
  461. assert (store is None) or (
  462. init_method is None
  463. ), "Cannot specify both init_method and store."
  464. if store is not None:
  465. assert world_size > 0, "world_size must be positive if using store"
  466. assert rank >= 0, "rank must be non-negative if using store"
  467. elif init_method is None:
  468. init_method = "env://"
  469. backend = Backend(backend)
  470. if backend == Backend.MPI:
  471. if world_size != -1 or rank != -1:
  472. warnings.warn(
  473. "For MPI backend, world_size ({}) and rank ({}) "
  474. "are ignored since they are assigned by the "
  475. "MPI runtime.".format(world_size, rank)
  476. )
  477. default_pg = _new_process_group_helper(
  478. -1, -1, [], Backend.MPI, None, group_name=group_name, timeout=timeout
  479. )
  480. _update_default_pg(default_pg)
  481. else:
  482. # backward compatible API
  483. if store is None:
  484. rendezvous_iterator = rendezvous(
  485. init_method, rank, world_size, timeout=timeout
  486. )
  487. store, rank, world_size = next(rendezvous_iterator)
  488. store.set_timeout(timeout)
  489. # Use a PrefixStore to avoid accidental overrides of keys used by
  490. # different systems (e.g. RPC) in case the store is multi-tenant.
  491. store = PrefixStore("default_pg", store)
  492. default_pg = _new_process_group_helper(
  493. world_size,
  494. rank,
  495. [],
  496. backend,
  497. store,
  498. pg_options=pg_options,
  499. group_name=group_name,
  500. timeout=timeout,
  501. )
  502. _update_default_pg(default_pg)
  503. _pg_group_ranks[GroupMember.WORLD] = {i: i for i in range(GroupMember.WORLD.size())} # type: ignore[attr-defined, index]
  504. _backend = _pg_map[GroupMember.WORLD][0] # type: ignore[index]
  505. _default_pg_init_method = init_method
  506. # barrier at the end to ensure that once we return from this method, all
  507. # process groups including global variables are updated correctly on all
  508. # ranks.
  509. if backend == Backend.MPI:
  510. # MPI backend doesn't use store.
  511. barrier()
  512. else:
  513. # Use store based barrier here since barrier() used a bunch of
  514. # default devices and messes up NCCL internal state.
  515. _store_based_barrier(rank, store, timeout)
  516. # Set sequence numbers for gloo and nccl process groups.
  517. if get_backend(default_pg) in [Backend.GLOO, Backend.NCCL]:
  518. default_pg._set_sequence_number_for_group()
  519. def _new_process_group_helper(
  520. world_size,
  521. rank,
  522. group_ranks,
  523. backend,
  524. store,
  525. pg_options=None,
  526. group_name=None,
  527. timeout=default_pg_timeout,
  528. ):
  529. """
  530. Create a new distributed process group.
  531. This function must be called by ALL processes in the global group, even if
  532. the calling process is not part of the newly created group. In that case,
  533. this function returns GroupMember.NON_GROUP_MEMBER.
  534. This function is called with ``group_ranks == []`` for the default group.
  535. """
  536. global _pg_map
  537. global _group_count
  538. global _pg_names
  539. if not group_name:
  540. group_name = str(_group_count)
  541. _group_count += 1
  542. if group_name in _pg_names.values():
  543. raise RuntimeError(
  544. "The specified group name has already been "
  545. "created, please use a different group name"
  546. )
  547. if not isinstance(timeout, timedelta):
  548. raise RuntimeError(
  549. "Expected timeout argument to be of type" "datetime.timedelta"
  550. )
  551. # The list of group ranks is empty if we're creating the default group.
  552. is_default_group = len(group_ranks) == 0
  553. backend = Backend(backend)
  554. pg: Union[ProcessGroupGloo, ProcessGroupMPI, ProcessGroupNCCL]
  555. if backend == Backend.MPI:
  556. if not is_mpi_available():
  557. raise RuntimeError(
  558. "Distributed package doesn't have MPI built in."
  559. " MPI is only included if you build PyTorch from"
  560. " source on a host that has MPI installed."
  561. )
  562. pg = ProcessGroupMPI.create(group_ranks)
  563. if not pg:
  564. return GroupMember.NON_GROUP_MEMBER
  565. _pg_map[pg] = (Backend.MPI, None)
  566. _pg_names[pg] = group_name
  567. else:
  568. # If this is a subgroup (which means group_ranks is specified),
  569. # we check if the current process is a member of the new group.
  570. if not is_default_group:
  571. global_rank = _get_default_group().rank()
  572. if global_rank not in group_ranks:
  573. return GroupMember.NON_GROUP_MEMBER
  574. # Use the group name as prefix in the default store, such that
  575. # a single store can be reused by multiple groups.
  576. prefix_store = PrefixStore(group_name, store)
  577. if backend == Backend.GLOO:
  578. if pg_options is not None:
  579. raise RuntimeError("GLOO options not supported")
  580. pg = ProcessGroupGloo(prefix_store, rank, world_size, timeout=timeout)
  581. # In debug mode and if GLOO is available, wrap in a wrapper PG that
  582. # enables enhanced collective checking for debugability.
  583. if get_debug_level() == DebugLevel.DETAIL:
  584. if not _GLOO_AVAILABLE:
  585. logger.info(
  586. """TORCH_DISTRIBUTED_DEBUG was set to DETAIL, but
  587. GLOO is not available. Build with Gloo to
  588. create a wrapper process group in debug mode
  589. to aid collective desynchronization debugging."""
  590. )
  591. else:
  592. pg = _create_process_group_wrapper(
  593. wrapped_pg=pg,
  594. store_prefix=group_name,
  595. store=store,
  596. rank=rank,
  597. world_size=world_size,
  598. timeout=timeout,
  599. )
  600. _pg_map[pg] = (Backend.GLOO, store)
  601. _pg_names[pg] = group_name
  602. elif backend == Backend.NCCL:
  603. if not is_nccl_available():
  604. raise RuntimeError("Distributed package doesn't have NCCL " "built in")
  605. if pg_options is not None:
  606. assert isinstance(
  607. pg_options, ProcessGroupNCCL.Options
  608. ), "Expected pg_options argument to be of type ProcessGroupNCCL.Options"
  609. else:
  610. # default pg_options for NCCL
  611. pg_options = ProcessGroupNCCL.Options()
  612. pg_options.is_high_priority_stream = False
  613. pg_options._timeout = timeout
  614. pg = ProcessGroupNCCL(prefix_store, rank, world_size, pg_options)
  615. # In debug mode and if GLOO is available, wrap in a wrapper PG that
  616. # enables enhanced collective checking for debugability.
  617. if get_debug_level() == DebugLevel.DETAIL:
  618. if not _GLOO_AVAILABLE:
  619. logger.info(
  620. """TORCH_DISTRIBUTED_DEBUG was set to DETAIL, but
  621. GLOO is not available. Build with Gloo to
  622. create a wrapper process group in debug mode
  623. to aid collective desynchronization debugging."""
  624. )
  625. else:
  626. pg = _create_process_group_wrapper(
  627. wrapped_pg=pg,
  628. store_prefix=group_name,
  629. store=store,
  630. rank=rank,
  631. world_size=world_size,
  632. timeout=timeout,
  633. )
  634. _pg_map[pg] = (Backend.NCCL, store)
  635. _pg_names[pg] = group_name
  636. else:
  637. assert backend.upper() in Backend._plugins, (
  638. f"unknown c10d backend type {backend.upper()}"
  639. )
  640. pg = Backend._plugins[backend.upper()](
  641. prefix_store, rank, world_size, timeout
  642. )
  643. _pg_map[pg] = (backend, store)
  644. _pg_names[pg] = group_name
  645. return pg
  646. def destroy_process_group(group=None):
  647. """
  648. Destroy a given process group, and deinitialize the distributed package
  649. Args:
  650. group (ProcessGroup, optional): The process group to be destroyed, if
  651. group.WORLD is given, all process
  652. groups including the default one will
  653. be destroyed.
  654. """
  655. global _pg_map
  656. global _pg_names
  657. global _pg_group_ranks
  658. global _default_pg_init_method
  659. global _group_count
  660. if group == GroupMember.NON_GROUP_MEMBER:
  661. return
  662. if group is None:
  663. pg = GroupMember.WORLD
  664. else:
  665. pg = group
  666. assert pg is not None
  667. if _pg_map.get(pg, None) is None:
  668. raise RuntimeError("Invalid process group specified")
  669. if group is None or group == GroupMember.WORLD:
  670. _update_default_pg(None)
  671. _default_pg_init_method = None
  672. _pg_map.clear()
  673. _pg_names.clear()
  674. _pg_group_ranks.clear()
  675. # when process group doesn't have an explicit name (only WORLD (default)
  676. # process group can have an explicit name), we use global _group_counter
  677. # to generate the name. We need to reset the counter on destruction to
  678. # allow consistent value to be generated when we re-create process
  679. # groups after some trainers recover from failure
  680. #
  681. # We only reset this when WORLD is being destroyed because if this
  682. # process group is in good state, we aren't dealing with failures.
  683. _group_count = 0
  684. else:
  685. del _pg_map[pg]
  686. del _pg_names[pg]
  687. del _pg_group_ranks[pg]
  688. def get_rank(group=None):
  689. """
  690. Returns the rank of the current process in the provided ``group`` or the
  691. default group if none was provided.
  692. Rank is a unique identifier assigned to each process within a distributed
  693. process group. They are always consecutive integers ranging from 0 to
  694. ``world_size``.
  695. Args:
  696. group (ProcessGroup, optional): The process group to work on. If None,
  697. the default process group will be used.
  698. Returns:
  699. The rank of the process group
  700. -1, if not part of the group
  701. """
  702. if _rank_not_in_group(group):
  703. return -1
  704. default_pg = _get_default_group()
  705. if group is None or group is GroupMember.WORLD:
  706. return default_pg.rank()
  707. return _get_group_rank(group, default_pg.rank())
  708. def get_world_size(group=None):
  709. """
  710. Returns the number of processes in the current process group
  711. Args:
  712. group (ProcessGroup, optional): The process group to work on. If None,
  713. the default process group will be used.
  714. Returns:
  715. The world size of the process group
  716. -1, if not part of the group
  717. """
  718. if _rank_not_in_group(group):
  719. return -1
  720. return _get_group_size(group)
  721. def isend(tensor, dst, group=None, tag=0):
  722. """
  723. Sends a tensor asynchronously.
  724. .. warning::
  725. Modifying ``tensor`` before the request completes causes undefined
  726. behavior.
  727. Args:
  728. tensor (Tensor): Tensor to send.
  729. dst (int): Destination rank.
  730. group (ProcessGroup, optional): The process group to work on. If None,
  731. the default process group will be used.
  732. tag (int, optional): Tag to match send with remote recv
  733. Returns:
  734. A distributed request object.
  735. None, if not part of the group
  736. """
  737. _check_single_tensor(tensor, "tensor")
  738. if _rank_not_in_group(group):
  739. _warn_not_in_group("isend")
  740. return
  741. if group is None or group is GroupMember.WORLD:
  742. default_pg = _get_default_group()
  743. return default_pg.send([tensor], dst, tag)
  744. else:
  745. group_dst_rank = _get_group_rank(group, dst)
  746. return group.send([tensor], group_dst_rank, tag)
  747. def irecv(tensor, src=None, group=None, tag=0):
  748. """
  749. Receives a tensor asynchronously.
  750. Args:
  751. tensor (Tensor): Tensor to fill with received data.
  752. src (int, optional): Source rank. Will receive from any
  753. process if unspecified.
  754. group (ProcessGroup, optional): The process group to work on. If None,
  755. the default process group will be used.
  756. tag (int, optional): Tag to match recv with remote send
  757. Returns:
  758. A distributed request object.
  759. None, if not part of the group
  760. """
  761. _check_single_tensor(tensor, "tensor")
  762. if _rank_not_in_group(group):
  763. _warn_not_in_group("irecv")
  764. return
  765. if group is None or group is GroupMember.WORLD:
  766. pg = _get_default_group()
  767. else:
  768. pg = group
  769. if src is None:
  770. return pg.recv_anysource([tensor], tag)
  771. else:
  772. if pg is GroupMember.WORLD:
  773. return pg.recv([tensor], src, tag)
  774. else:
  775. group_src_rank = _get_group_rank(pg, src)
  776. return pg.recv([tensor], group_src_rank, tag)
  777. def send(tensor, dst, group=None, tag=0):
  778. """
  779. Sends a tensor synchronously.
  780. Args:
  781. tensor (Tensor): Tensor to send.
  782. dst (int): Destination rank.
  783. group (ProcessGroup, optional): The process group to work on. If None,
  784. the default process group will be used.
  785. tag (int, optional): Tag to match send with remote recv
  786. """
  787. _check_single_tensor(tensor, "tensor")
  788. if _rank_not_in_group(group):
  789. _warn_not_in_group("send")
  790. return
  791. if group is None or group is GroupMember.WORLD:
  792. default_pg = _get_default_group()
  793. default_pg.send([tensor], dst, tag).wait()
  794. else:
  795. group_dst_rank = _get_group_rank(group, dst)
  796. group.send([tensor], group_dst_rank, tag).wait()
  797. def recv(tensor, src=None, group=None, tag=0):
  798. """
  799. Receives a tensor synchronously.
  800. Args:
  801. tensor (Tensor): Tensor to fill with received data.
  802. src (int, optional): Source rank. Will receive from any
  803. process if unspecified.
  804. group (ProcessGroup, optional): The process group to work on. If None,
  805. the default process group will be used.
  806. tag (int, optional): Tag to match recv with remote send
  807. Returns:
  808. Sender rank
  809. -1, if not part of the group
  810. """
  811. _check_single_tensor(tensor, "tensor")
  812. if _rank_not_in_group(group):
  813. _warn_not_in_group("recv")
  814. return -1
  815. if group is None:
  816. pg = _get_default_group()
  817. else:
  818. pg = group
  819. if src is None:
  820. work = pg.recv_anysource([tensor], tag)
  821. work.wait()
  822. src_rank = work._source_rank()
  823. if group is None or group is GroupMember.WORLD:
  824. return src_rank
  825. else:
  826. return _get_global_rank(pg, src_rank)
  827. else:
  828. if group is None or group is GroupMember.WORLD:
  829. pg.recv([tensor], src, tag).wait()
  830. else:
  831. group_src_rank = _get_group_rank(pg, src)
  832. pg.recv([tensor], group_src_rank, tag).wait()
  833. return src
  834. class P2POp(object):
  835. """
  836. A class to build point-to-point operations for ``batch_isend_irecv``.
  837. This class builds the type of P2P operation, communication buffer, peer rank,
  838. Process Group group, and tag. Instances of this class will be passed to
  839. ``batch_isend_irecv`` for point-to-point communications.
  840. Args:
  841. op (callable): A function to send data to or receive data from a peer process.
  842. The type of ``op`` is either ``torch.distributed.isend`` or
  843. ``torch.distributed.irecv``.
  844. tensor (Tensor): Tensor to send or receive.
  845. peer (int): Destination or source rank.
  846. group (ProcessGroup, optional): The process group to work on. If None,
  847. the default process group will be used.
  848. tag (int, optional): Tag to match send with recv.
  849. """
  850. def __init__(self, op, tensor, peer, group=None, tag=0):
  851. self.op = op
  852. self.tensor = tensor
  853. self.peer = peer
  854. self.group = group
  855. self.tag = tag
  856. def __new__(cls, op, tensor, peer, group=None, tag=0):
  857. _check_op(op)
  858. _check_single_tensor(tensor, "tensor")
  859. return object.__new__(cls)
  860. @contextlib.contextmanager
  861. def _batch_p2p_manager(backend):
  862. if backend == Backend.NCCL:
  863. ProcessGroupNCCL._group_start()
  864. try:
  865. yield
  866. finally:
  867. if backend == Backend.NCCL:
  868. ProcessGroupNCCL._group_end()
  869. def batch_isend_irecv(p2p_op_list):
  870. """
  871. Send or Receive a batch of tensors asynchronously and return a list of requests.
  872. Process each of the operations in ``p2p_op_list`` and return the corresponding
  873. requests. NCCL and Gloo backend are currently supported.
  874. Args:
  875. p2p_op_list: A list of point-to-point operations(type of each operator is
  876. ``torch.distributed.P2POp``). The order of the isend/irecv in the list
  877. matters and it needs to match with corresponding isend/irecv on the
  878. remote end.
  879. Returns:
  880. A list of distributed request objects returned by calling the corresponding
  881. op in the op_list.
  882. Examples:
  883. >>> send_tensor = torch.arange(2) + 2 * rank
  884. >>> recv_tensor = torch.randn(2)
  885. >>> send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1)%world_size)
  886. >>> recv_op = dist.P2POp(dist.irecv, recv_tensor, (rank - 1 + world_size)%world_size)
  887. >>> reqs = batch_isend_irecv([send_op, recv_op])
  888. >>> for req in reqs:
  889. >>> req.wait()
  890. >>> recv_tensor
  891. tensor([2, 3]) # Rank 0
  892. tensor([0, 1]) # Rank 1
  893. .. note:: Note that when this API is used with the NCCL PG backend, users must set
  894. the current GPU device with `torch.cuda.set_device`, otherwise it will
  895. lead to unexpected hang issues.
  896. In addition, if this API is the first collective call in the ``group``
  897. passed to ``dist.P2POp``, all ranks of the ``group`` must participate in
  898. this API call; otherwise, the behavior is undefined. If this API call is
  899. not the first collective call in the ``group``, batched P2P operations
  900. involving only a subset of ranks of the ``group`` are allowed.
  901. """
  902. _check_p2p_op_list(p2p_op_list)
  903. backend = get_backend(p2p_op_list[0].group)
  904. reqs = []
  905. with _batch_p2p_manager(backend):
  906. for p2p_op in p2p_op_list:
  907. op = p2p_op.op
  908. tensor = p2p_op.tensor
  909. peer = p2p_op.peer
  910. curr_group = p2p_op.group
  911. tag = p2p_op.tag
  912. ret = op(tensor, peer, curr_group, tag)
  913. if ret is not None:
  914. reqs.append(ret)
  915. return reqs
  916. def broadcast_multigpu(tensor_list, src, group=None, async_op=False, src_tensor=0):
  917. """
  918. Broadcasts the tensor to the whole group with multiple GPU tensors
  919. per node.
  920. ``tensor`` must have the same number of elements in all the GPUs from
  921. all processes participating in the collective. each tensor in the list must
  922. be on a different GPU
  923. Only nccl and gloo backend are currently supported
  924. tensors should only be GPU tensors
  925. Args:
  926. tensor_list (List[Tensor]): Tensors that participate in the collective
  927. operation. If ``src`` is the rank, then the specified ``src_tensor``
  928. element of ``tensor_list`` (``tensor_list[src_tensor]``) will be
  929. broadcast to all other tensors (on different GPUs) in the src process
  930. and all tensors in ``tensor_list`` of other non-src processes.
  931. You also need to make sure that ``len(tensor_list)`` is the same
  932. for all the distributed processes calling this function.
  933. src (int): Source rank.
  934. group (ProcessGroup, optional): The process group to work on. If None,
  935. the default process group will be used.
  936. async_op (bool, optional): Whether this op should be an async op
  937. src_tensor (int, optional): Source tensor rank within ``tensor_list``
  938. Returns:
  939. Async work handle, if async_op is set to True.
  940. None, if not async_op or if not part of the group
  941. """
  942. if _rank_not_in_group(group):
  943. _warn_not_in_group("broadcast_multigpu")
  944. return
  945. opts = BroadcastOptions()
  946. opts.rootRank = src
  947. opts.rootTensor = src_tensor
  948. if group is None or group is GroupMember.WORLD:
  949. default_pg = _get_default_group()
  950. work = default_pg.broadcast(tensor_list, opts)
  951. else:
  952. group_src_rank = _get_group_rank(group, src)
  953. opts.rootRank = group_src_rank
  954. work = group.broadcast(tensor_list, opts)
  955. if async_op:
  956. return work
  957. else:
  958. work.wait()
  959. def broadcast(tensor, src, group=None, async_op=False):
  960. """
  961. Broadcasts the tensor to the whole group.
  962. ``tensor`` must have the same number of elements in all processes
  963. participating in the collective.
  964. Args:
  965. tensor (Tensor): Data to be sent if ``src`` is the rank of current
  966. process, and tensor to be used to save received data otherwise.
  967. src (int): Source rank.
  968. group (ProcessGroup, optional): The process group to work on. If None,
  969. the default process group will be used.
  970. async_op (bool, optional): Whether this op should be an async op
  971. Returns:
  972. Async work handle, if async_op is set to True.
  973. None, if not async_op or if not part of the group
  974. """
  975. _check_single_tensor(tensor, "tensor")
  976. if _rank_not_in_group(group):
  977. _warn_not_in_group("broadcast")
  978. return
  979. opts = BroadcastOptions()
  980. opts.rootRank = src
  981. opts.rootTensor = 0
  982. if group is None or group is GroupMember.WORLD:
  983. default_pg = _get_default_group()
  984. work = default_pg.broadcast([tensor], opts)
  985. else:
  986. group_src_rank = _get_group_rank(group, src)
  987. opts.rootRank = group_src_rank
  988. work = group.broadcast([tensor], opts)
  989. if async_op:
  990. return work
  991. else:
  992. work.wait()
  993. def all_reduce_multigpu(tensor_list, op=ReduceOp.SUM, group=None, async_op=False):
  994. r"""
  995. Reduces the tensor data across all machines in such a way that all get
  996. the final result. This function reduces a number of tensors on every node,
  997. while each tensor resides on different GPUs.
  998. Therefore, the input tensor in the tensor list needs to be GPU tensors.
  999. Also, each tensor in the tensor list needs to reside on a different GPU.
  1000. After the call, all ``tensor`` in ``tensor_list`` is going to be bitwise
  1001. identical in all processes.
  1002. Complex tensors are supported.
  1003. Only nccl and gloo backend is currently supported
  1004. tensors should only be GPU tensors
  1005. Args:
  1006. tensor_list (List[Tensor]): List of input and output tensors of
  1007. the collective. The function operates in-place and requires that
  1008. each tensor to be a GPU tensor on different GPUs.
  1009. You also need to make sure that ``len(tensor_list)`` is the same for
  1010. all the distributed processes calling this function.
  1011. op (optional): One of the values from
  1012. ``torch.distributed.ReduceOp``
  1013. enum. Specifies an operation used for element-wise reductions.
  1014. group (ProcessGroup, optional): The process group to work on. If
  1015. ``None``, the default process group will be used.
  1016. async_op (bool, optional): Whether this op should be an async op
  1017. Returns:
  1018. Async work handle, if async_op is set to True.
  1019. None, if not async_op or if not part of the group
  1020. """
  1021. if _rank_not_in_group(group):
  1022. return
  1023. tensor_list = [
  1024. t if not t.is_complex() else torch.view_as_real(t) for t in tensor_list
  1025. ]
  1026. opts = AllreduceOptions()
  1027. opts.reduceOp = op
  1028. if group is None:
  1029. default_pg = _get_default_group()
  1030. work = default_pg.allreduce(tensor_list, opts)
  1031. else:
  1032. work = group.allreduce(tensor_list, opts)
  1033. if async_op:
  1034. return work
  1035. else:
  1036. work.wait()
  1037. def all_reduce(tensor, op=ReduceOp.SUM, group=None, async_op=False):
  1038. """
  1039. Reduces the tensor data across all machines in such a way that all get
  1040. the final result.
  1041. After the call ``tensor`` is going to be bitwise identical in all processes.
  1042. Complex tensors are supported.
  1043. Args:
  1044. tensor (Tensor): Input and output of the collective. The function
  1045. operates in-place.
  1046. op (optional): One of the values from
  1047. ``torch.distributed.ReduceOp``
  1048. enum. Specifies an operation used for element-wise reductions.
  1049. group (ProcessGroup, optional): The process group to work on. If None,
  1050. the default process group will be used.
  1051. async_op (bool, optional): Whether this op should be an async op
  1052. Returns:
  1053. Async work handle, if async_op is set to True.
  1054. None, if not async_op or if not part of the group
  1055. Examples:
  1056. >>> # All tensors below are of torch.int64 type.
  1057. >>> # We have 2 process groups, 2 ranks.
  1058. >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
  1059. >>> tensor
  1060. tensor([1, 2]) # Rank 0
  1061. tensor([3, 4]) # Rank 1
  1062. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  1063. >>> tensor
  1064. tensor([4, 6]) # Rank 0
  1065. tensor([4, 6]) # Rank 1
  1066. >>> # All tensors below are of torch.cfloat type.
  1067. >>> # We have 2 process groups, 2 ranks.
  1068. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j)
  1069. >>> tensor
  1070. tensor([1.+1.j, 2.+2.j]) # Rank 0
  1071. tensor([3.+3.j, 4.+4.j]) # Rank 1
  1072. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  1073. >>> tensor
  1074. tensor([4.+4.j, 6.+6.j]) # Rank 0
  1075. tensor([4.+4.j, 6.+6.j]) # Rank 1
  1076. """
  1077. _check_single_tensor(tensor, "tensor")
  1078. if _rank_not_in_group(group):
  1079. _warn_not_in_group("all_reduce")
  1080. return
  1081. if tensor.is_complex():
  1082. if not supports_complex(op):
  1083. raise RuntimeError(f"all_reduce does not support {op} on complex tensors")
  1084. tensor = torch.view_as_real(tensor)
  1085. opts = AllreduceOptions()
  1086. opts.reduceOp = op
  1087. if group is None:
  1088. default_pg = _get_default_group()
  1089. work = default_pg.allreduce([tensor], opts)
  1090. else:
  1091. work = group.allreduce([tensor], opts)
  1092. if async_op:
  1093. return work
  1094. else:
  1095. work.wait()
  1096. def all_reduce_coalesced(tensors, op=ReduceOp.SUM, group=None, async_op=False):
  1097. """
  1098. WARNING: at this time individual shape checking is not implemented across nodes.
  1099. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  1100. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce
  1101. operation will proceed without complaint and return erroneous outputs. This lack
  1102. of shape checking results in significant performance improvements but users of this
  1103. function should take extra care to ensure that each node passes in tensors whose
  1104. shapes match across nodes.
  1105. Reduces each tensor in tensors (residing on the same device) across all machines
  1106. in such a way that all get the final result.
  1107. After the call each tensor in tensors is going to bitwise identical
  1108. in all processes.
  1109. Complex tensors are supported.
  1110. Args:
  1111. tensors (List[Tensor]): Input and output of the collective. The function
  1112. operates in-place.
  1113. op (Optional[ReduceOp]): One of the values from
  1114. ``torch.distributed.ReduceOp`` enum. Specifies an operation used for
  1115. element-wise reductions.
  1116. group (ProcessGroup, optional): The process group to work on. If None,
  1117. the default process group will be used.
  1118. async_op (Optional[bool]): Whether this op should be an async op.
  1119. Returns:
  1120. Async work handle, if async_op is set to True.
  1121. None, if not async_op or if not part of the group.
  1122. """
  1123. _check_tensor_list(tensors, "tensor")
  1124. if _rank_not_in_group(group):
  1125. _warn_not_in_group("all_reduce_coalesced")
  1126. return
  1127. if any([t.is_complex() for t in tensors]) and not supports_complex(op):
  1128. raise RuntimeError(f"all_reduce does not support {op} on complex tensors")
  1129. tensors = [t if not t.is_complex() else torch.view_as_real(t) for t in tensors]
  1130. opts = AllreduceCoalescedOptions()
  1131. opts.reduceOp = op
  1132. if group is None:
  1133. default_pg = _get_default_group()
  1134. work = default_pg.allreduce_coalesced(tensors, opts)
  1135. else:
  1136. work = group.allreduce_coalesced(tensors, opts)
  1137. if async_op:
  1138. return work.get_future()
  1139. else:
  1140. work.wait()
  1141. def reduce_multigpu(
  1142. tensor_list, dst, op=ReduceOp.SUM, group=None, async_op=False, dst_tensor=0
  1143. ):
  1144. """
  1145. Reduces the tensor data on multiple GPUs across all machines. Each tensor
  1146. in ``tensor_list`` should reside on a separate GPU
  1147. Only the GPU of ``tensor_list[dst_tensor]`` on the process with rank ``dst``
  1148. is going to receive the final result.
  1149. Only nccl backend is currently supported
  1150. tensors should only be GPU tensors
  1151. Args:
  1152. tensor_list (List[Tensor]): Input and output GPU tensors of the
  1153. collective. The function operates in-place.
  1154. You also need to make sure that ``len(tensor_list)`` is the same for
  1155. all the distributed processes calling this function.
  1156. dst (int): Destination rank
  1157. op (optional): One of the values from
  1158. ``torch.distributed.ReduceOp``
  1159. enum. Specifies an operation used for element-wise reductions.
  1160. group (ProcessGroup, optional): The process group to work on. If None,
  1161. the default process group will be used.
  1162. async_op (bool, optional): Whether this op should be an async op
  1163. dst_tensor (int, optional): Destination tensor rank within
  1164. ``tensor_list``
  1165. Returns:
  1166. Async work handle, if async_op is set to True.
  1167. None, otherwise
  1168. """
  1169. if _rank_not_in_group(group):
  1170. _warn_not_in_group("reduce_multigpu")
  1171. return
  1172. opts = ReduceOptions()
  1173. opts.reduceOp = op
  1174. opts.rootRank = dst
  1175. opts.rootTensor = dst_tensor
  1176. if group is None or group is GroupMember.WORLD:
  1177. default_pg = _get_default_group()
  1178. work = default_pg.reduce(tensor_list, opts)
  1179. else:
  1180. group_dst_rank = _get_group_rank(group, dst)
  1181. opts.rootRank = group_dst_rank
  1182. work = group.reduce(tensor_list, opts)
  1183. if async_op:
  1184. return work
  1185. else:
  1186. work.wait()
  1187. def reduce(tensor, dst, op=ReduceOp.SUM, group=None, async_op=False):
  1188. """
  1189. Reduces the tensor data across all machines.
  1190. Only the process with rank ``dst`` is going to receive the final result.
  1191. Args:
  1192. tensor (Tensor): Input and output of the collective. The function
  1193. operates in-place.
  1194. dst (int): Destination rank
  1195. op (optional): One of the values from
  1196. ``torch.distributed.ReduceOp``
  1197. enum. Specifies an operation used for element-wise reductions.
  1198. group (ProcessGroup, optional): The process group to work on. If None,
  1199. the default process group will be used.
  1200. async_op (bool, optional): Whether this op should be an async op
  1201. Returns:
  1202. Async work handle, if async_op is set to True.
  1203. None, if not async_op or if not part of the group
  1204. """
  1205. _check_single_tensor(tensor, "tensor")
  1206. if _rank_not_in_group(group):
  1207. _warn_not_in_group("reduce")
  1208. return
  1209. opts = ReduceOptions()
  1210. opts.reduceOp = op
  1211. opts.rootRank = dst
  1212. if group is None or group is GroupMember.WORLD:
  1213. default_pg = _get_default_group()
  1214. work = default_pg.reduce([tensor], opts)
  1215. else:
  1216. group_dst_rank = _get_group_rank(group, dst)
  1217. opts.rootRank = group_dst_rank
  1218. work = group.reduce([tensor], opts)
  1219. if async_op:
  1220. return work
  1221. else:
  1222. work.wait()
  1223. def all_gather_multigpu(
  1224. output_tensor_lists, input_tensor_list, group=None, async_op=False
  1225. ):
  1226. """
  1227. Gathers tensors from the whole group in a list.
  1228. Each tensor in ``tensor_list`` should reside on a separate GPU
  1229. Only nccl backend is currently supported
  1230. tensors should only be GPU tensors
  1231. Complex tensors are supported.
  1232. Args:
  1233. output_tensor_lists (List[List[Tensor]]): Output lists. It should
  1234. contain correctly-sized tensors on each GPU to be used for output
  1235. of the collective, e.g. ``output_tensor_lists[i]`` contains the
  1236. all_gather result that resides on the GPU of
  1237. ``input_tensor_list[i]``.
  1238. Note that each element of ``output_tensor_lists`` has the size of
  1239. ``world_size * len(input_tensor_list)``, since the function all
  1240. gathers the result from every single GPU in the group. To interpret
  1241. each element of ``output_tensor_lists[i]``, note that
  1242. ``input_tensor_list[j]`` of rank k will be appear in
  1243. ``output_tensor_lists[i][k * world_size + j]``
  1244. Also note that ``len(output_tensor_lists)``, and the size of each
  1245. element in ``output_tensor_lists`` (each element is a list,
  1246. therefore ``len(output_tensor_lists[i])``) need to be the same
  1247. for all the distributed processes calling this function.
  1248. input_tensor_list (List[Tensor]): List of tensors(on different GPUs) to
  1249. be broadcast from current process.
  1250. Note that ``len(input_tensor_list)`` needs to be the same for
  1251. all the distributed processes calling this function.
  1252. group (ProcessGroup, optional): The process group to work on. If None,
  1253. the default process group will be used.
  1254. async_op (bool, optional): Whether this op should be an async op
  1255. Returns:
  1256. Async work handle, if async_op is set to True.
  1257. None, if not async_op or if not part of the group
  1258. """
  1259. if _rank_not_in_group(group):
  1260. _warn_not_in_group("all_gather_multigpu")
  1261. return
  1262. output_tensor_lists = [
  1263. [t if not t.is_complex() else torch.view_as_real(t) for t in l]
  1264. for l in output_tensor_lists
  1265. ]
  1266. input_tensor_list = [
  1267. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  1268. ]
  1269. if group is None:
  1270. default_pg = _get_default_group()
  1271. work = default_pg.allgather(output_tensor_lists, input_tensor_list)
  1272. else:
  1273. work = group.allgather(output_tensor_lists, input_tensor_list)
  1274. if async_op:
  1275. return work
  1276. else:
  1277. work.wait()
  1278. def _object_to_tensor(obj):
  1279. f = io.BytesIO()
  1280. _pickler(f).dump(obj)
  1281. byte_storage = torch.ByteStorage.from_buffer(f.getvalue()) # type: ignore[attr-defined]
  1282. # Do not replace `torch.ByteTensor` or `torch.LongTensor` with torch.tensor and specifying dtype.
  1283. # Otherwise, it will casue 100X slowdown.
  1284. # See: https://github.com/pytorch/pytorch/issues/65696
  1285. byte_tensor = torch.ByteTensor(byte_storage)
  1286. local_size = torch.LongTensor([byte_tensor.numel()])
  1287. return byte_tensor, local_size
  1288. def _tensor_to_object(tensor, tensor_size):
  1289. buf = tensor.numpy().tobytes()[:tensor_size]
  1290. return _unpickler(io.BytesIO(buf)).load()
  1291. def _check_for_nccl_backend(group):
  1292. pg = group or _get_default_group()
  1293. # Gate PG wrapper check on Gloo availability.
  1294. if _GLOO_AVAILABLE:
  1295. # It is not expected for PG to be wrapped many times, but support it just
  1296. # in case
  1297. while isinstance(pg, _ProcessGroupWrapper):
  1298. pg = pg.wrapped_pg
  1299. return (
  1300. is_nccl_available() and
  1301. isinstance(pg, ProcessGroupNCCL)
  1302. )
  1303. def all_gather_object(object_list, obj, group=None):
  1304. """
  1305. Gathers picklable objects from the whole group into a list. Similar to
  1306. :func:`all_gather`, but Python objects can be passed in. Note that the object
  1307. must be picklable in order to be gathered.
  1308. Args:
  1309. object_list (list[Any]): Output list. It should be correctly sized as the
  1310. size of the group for this collective and will contain the output.
  1311. object (Any): Pickable Python object to be broadcast from current process.
  1312. group (ProcessGroup, optional): The process group to work on. If None,
  1313. the default process group will be used. Default is ``None``.
  1314. Returns:
  1315. None. If the calling rank is part of this group, the output of the
  1316. collective will be populated into the input ``object_list``. If the
  1317. calling rank is not part of the group, the passed in ``object_list`` will
  1318. be unmodified.
  1319. .. note:: Note that this API differs slightly from the :func:`all_gather`
  1320. collective since it does not provide an ``async_op`` handle and thus
  1321. will be a blocking call.
  1322. .. note:: For NCCL-based processed groups, internal tensor representations
  1323. of objects must be moved to the GPU device before communication takes
  1324. place. In this case, the device used is given by
  1325. ``torch.cuda.current_device()`` and it is the user's responsiblity to
  1326. ensure that this is set so that each rank has an individual GPU, via
  1327. ``torch.cuda.set_device()``.
  1328. .. warning::
  1329. :func:`all_gather_object` uses ``pickle`` module implicitly, which is
  1330. known to be insecure. It is possible to construct malicious pickle data
  1331. which will execute arbitrary code during unpickling. Only call this
  1332. function with data you trust.
  1333. Example::
  1334. >>> # Note: Process group initialization omitted on each rank.
  1335. >>> import torch.distributed as dist
  1336. >>> # Assumes world_size of 3.
  1337. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  1338. >>> output = [None for _ in gather_objects]
  1339. >>> dist.all_gather_object(output, gather_objects[dist.get_rank()])
  1340. >>> output
  1341. ['foo', 12, {1: 2}]
  1342. """
  1343. if _rank_not_in_group(group):
  1344. _warn_not_in_group("all_gather_object")
  1345. return
  1346. input_tensor, local_size = _object_to_tensor(obj)
  1347. current_device = torch.device("cpu")
  1348. is_nccl_backend = _check_for_nccl_backend(group)
  1349. if is_nccl_backend:
  1350. # See note about using torch.cuda.current_device() here in docstring.
  1351. # We cannot simply use my_rank since rank == device is not necessarily
  1352. # true.
  1353. current_device = torch.device("cuda", torch.cuda.current_device())
  1354. input_tensor = input_tensor.to(current_device)
  1355. local_size = local_size.to(current_device)
  1356. # Gather all local sizes. This is so that we can find the max size, and index
  1357. # until the correct size when deserializing the tensors.
  1358. group_size = get_world_size(group=group)
  1359. object_sizes_tensor = torch.zeros(
  1360. group_size, dtype=torch.long, device=current_device
  1361. )
  1362. object_size_list = [
  1363. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  1364. ]
  1365. # Allgather tensor sizes
  1366. all_gather(object_size_list, local_size, group=group)
  1367. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  1368. # Resize tensor to max size across all ranks.
  1369. input_tensor.resize_(max_object_size)
  1370. coalesced_output_tensor = torch.empty(
  1371. max_object_size * group_size, dtype=torch.uint8, device=current_device
  1372. )
  1373. # Output tensors are nonoverlapping views of coalesced_output_tensor
  1374. output_tensors = [
  1375. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  1376. for i in range(group_size)
  1377. ]
  1378. all_gather(output_tensors, input_tensor, group=group)
  1379. # Deserialize outputs back to object.
  1380. for i, tensor in enumerate(output_tensors):
  1381. tensor = tensor.type(torch.uint8)
  1382. if tensor.device != torch.device("cpu"):
  1383. tensor = tensor.cpu()
  1384. tensor_size = object_size_list[i]
  1385. object_list[i] = _tensor_to_object(tensor, tensor_size)
  1386. def gather_object(obj, object_gather_list=None, dst=0, group=None):
  1387. """
  1388. Gathers picklable objects from the whole group in a single process.
  1389. Similar to :func:`gather`, but Python objects can be passed in. Note that the
  1390. object must be picklable in order to be gathered.
  1391. Args:
  1392. obj (Any): Input object. Must be picklable.
  1393. object_gather_list (list[Any]): Output list. On the ``dst`` rank, it
  1394. should be correctly sized as the size of the group for this
  1395. collective and will contain the output. Must be ``None`` on non-dst
  1396. ranks. (default is ``None``)
  1397. dst (int, optional): Destination rank. (default is 0)
  1398. group: (ProcessGroup, optional): The process group to work on. If None,
  1399. the default process group will be used. Default is ``None``.
  1400. Returns:
  1401. None. On the ``dst`` rank, ``object_gather_list`` will contain the
  1402. output of the collective.
  1403. .. note:: Note that this API differs slightly from the gather collective
  1404. since it does not provide an async_op handle and thus will be a blocking
  1405. call.
  1406. .. note:: For NCCL-based processed groups, internal tensor representations
  1407. of objects must be moved to the GPU device before communication takes
  1408. place. In this case, the device used is given by
  1409. ``torch.cuda.current_device()`` and it is the user's responsiblity to
  1410. ensure that this is set so that each rank has an individual GPU, via
  1411. ``torch.cuda.set_device()``.
  1412. .. warning::
  1413. :func:`gather_object` uses ``pickle`` module implicitly, which is
  1414. known to be insecure. It is possible to construct malicious pickle data
  1415. which will execute arbitrary code during unpickling. Only call this
  1416. function with data you trust.
  1417. Example::
  1418. >>> # Note: Process group initialization omitted on each rank.
  1419. >>> import torch.distributed as dist
  1420. >>> # Assumes world_size of 3.
  1421. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  1422. >>> output = [None for _ in gather_objects]
  1423. >>> dist.gather_object(
  1424. gather_objects[dist.get_rank()],
  1425. output if dist.get_rank() == 0 else None,
  1426. dst=0
  1427. )
  1428. >>> # On rank 0
  1429. >>> output
  1430. ['foo', 12, {1: 2}]
  1431. """
  1432. if _rank_not_in_group(group):
  1433. _warn_not_in_group("gather_object")
  1434. return
  1435. # Ensure object_gather_list is specified appopriately.
  1436. my_rank = get_rank()
  1437. _validate_output_list_for_rank(my_rank, dst, object_gather_list)
  1438. input_tensor, local_size = _object_to_tensor(obj)
  1439. current_device = torch.device("cpu")
  1440. is_nccl_backend = _check_for_nccl_backend(group)
  1441. if is_nccl_backend:
  1442. current_device = torch.device("cuda", torch.cuda.current_device())
  1443. input_tensor = input_tensor.to(current_device)
  1444. local_size = local_size.to(current_device)
  1445. # Gather all local sizes. This is so that we can find the max size, and index
  1446. # until the correct size when deserializing the tensors.
  1447. group_size = get_world_size(group=group)
  1448. object_sizes_tensor = torch.zeros(
  1449. group_size, dtype=torch.long, device=current_device
  1450. )
  1451. object_size_list = [
  1452. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  1453. ]
  1454. # Allgather tensor sizes. An all-gather is needed here despite this being a
  1455. # gather, since each rank needs to broadcast a tensor of the same (maximal)
  1456. # size.
  1457. all_gather(object_size_list, local_size, group=group)
  1458. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  1459. # Resize tensor to max size across all ranks.
  1460. input_tensor.resize_(max_object_size)
  1461. # Avoid populating output tensors if the result won't be gathered on this rank.
  1462. if my_rank == dst:
  1463. coalesced_output_tensor = torch.empty(
  1464. max_object_size * group_size, dtype=torch.uint8, device=current_device
  1465. )
  1466. # Output tensors are nonoverlapping views of coalesced_output_tensor
  1467. output_tensors = [
  1468. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  1469. for i in range(group_size)
  1470. ]
  1471. # All ranks call gather with equal-sized tensors.
  1472. gather(
  1473. input_tensor,
  1474. gather_list=output_tensors if my_rank == dst else None,
  1475. dst=dst,
  1476. group=group,
  1477. )
  1478. if my_rank != dst:
  1479. return
  1480. for i, tensor in enumerate(output_tensors):
  1481. tensor = tensor.type(torch.uint8)
  1482. if tensor.device != torch.device("cpu"):
  1483. tensor = tensor.cpu()
  1484. tensor_size = object_size_list[i]
  1485. object_gather_list[i] = _tensor_to_object(tensor, tensor_size)
  1486. def broadcast_object_list(object_list, src=0, group=None, device=None):
  1487. """
  1488. Broadcasts picklable objects in ``object_list`` to the whole group. Similar
  1489. to :func:`broadcast`, but Python objects can be passed in.
  1490. Note that all objects in ``object_list`` must be picklable in order to be
  1491. broadcasted.
  1492. Args:
  1493. object_list (List[Any]): List of input objects to broadcast.
  1494. Each object must be picklable. Only objects on the ``src`` rank will
  1495. be broadcast, but each rank must provide lists of equal sizes.
  1496. src (int): Source rank from which to broadcast ``object_list``.
  1497. group: (ProcessGroup, optional): The process group to work on. If None,
  1498. the default process group will be used. Default is ``None``.
  1499. device (``torch.device``, optional): If not None, the objects are
  1500. serialized and converted to tensors which are moved to the
  1501. ``device`` before broadcasting. Default is ``None``.
  1502. Returns:
  1503. ``None``. If rank is part of the group, ``object_list`` will contain the
  1504. broadcasted objects from ``src`` rank.
  1505. .. note:: For NCCL-based processed groups, internal tensor representations
  1506. of objects must be moved to the GPU device before communication takes
  1507. place. In this case, the device used is given by
  1508. ``torch.cuda.current_device()`` and it is the user's responsiblity to
  1509. ensure that this is set so that each rank has an individual GPU, via
  1510. ``torch.cuda.set_device()``.
  1511. .. note:: Note that this API differs slightly from the :func:`all_gather`
  1512. collective since it does not provide an ``async_op`` handle and thus
  1513. will be a blocking call.
  1514. .. warning::
  1515. :func:`broadcast_object_list` uses ``pickle`` module implicitly, which
  1516. is known to be insecure. It is possible to construct malicious pickle
  1517. data which will execute arbitrary code during unpickling. Only call this
  1518. function with data you trust.
  1519. Example::
  1520. >>> # Note: Process group initialization omitted on each rank.
  1521. >>> import torch.distributed as dist
  1522. >>> if dist.get_rank() == 0:
  1523. >>> # Assumes world_size of 3.
  1524. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  1525. >>> else:
  1526. >>> objects = [None, None, None]
  1527. >>> # Assumes backend is not NCCL
  1528. >>> device = torch.device("cpu")
  1529. >>> dist.broadcast_object_list(objects, src=0, device=device)
  1530. >>> objects
  1531. ['foo', 12, {1: 2}]
  1532. """
  1533. if _rank_not_in_group(group):
  1534. _warn_not_in_group("broadcast_object_list")
  1535. return
  1536. my_rank = get_rank()
  1537. # Serialize object_list elements to tensors on src rank.
  1538. if my_rank == src:
  1539. tensor_list, size_list = zip(*[_object_to_tensor(obj) for obj in object_list])
  1540. object_sizes_tensor = torch.cat(size_list)
  1541. else:
  1542. object_sizes_tensor = torch.empty(len(object_list), dtype=torch.long)
  1543. # Current device selection.
  1544. # To preserve backwards compatibility, ``device`` is default to ``None``
  1545. # in which case we run current logic of device selection, i.e.
  1546. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  1547. # case it is not ``None`` we move the size and object tensors to be
  1548. # broadcasted to this device.
  1549. is_nccl_backend = _check_for_nccl_backend(group)
  1550. current_device = None
  1551. if device is not None:
  1552. if is_nccl_backend and device.type != "cuda":
  1553. raise ValueError("device type must be cuda for nccl backend")
  1554. current_device = device
  1555. else:
  1556. current_device = torch.device("cpu")
  1557. if is_nccl_backend:
  1558. # See note about using torch.cuda.current_device() here in
  1559. # docstring. We cannot simply use my_rank since rank == device is
  1560. # not necessarily true.
  1561. current_device = torch.device("cuda", torch.cuda.current_device())
  1562. if is_nccl_backend:
  1563. object_sizes_tensor = object_sizes_tensor.to(current_device)
  1564. # Broadcast object sizes
  1565. broadcast(object_sizes_tensor, src=src, group=group)
  1566. # Concatenate and broadcast serialized object tensors
  1567. if my_rank == src:
  1568. object_tensor = torch.cat(tensor_list)
  1569. else:
  1570. object_tensor = torch.empty( # type: ignore[call-overload]
  1571. torch.sum(object_sizes_tensor).item(), # type: ignore[arg-type]
  1572. dtype=torch.uint8,
  1573. )
  1574. if is_nccl_backend:
  1575. object_tensor = object_tensor.to(current_device)
  1576. broadcast(object_tensor, src=src, group=group)
  1577. # Deserialize objects using their stored sizes.
  1578. offset = 0
  1579. if my_rank != src:
  1580. for i, obj_size in enumerate(object_sizes_tensor):
  1581. obj_view = object_tensor[offset : offset + obj_size]
  1582. obj_view = obj_view.type(torch.uint8)
  1583. if obj_view.device != torch.device("cpu"):
  1584. obj_view = obj_view.cpu()
  1585. offset += obj_size
  1586. object_list[i] = _tensor_to_object(obj_view, obj_size)
  1587. def scatter_object_list(
  1588. scatter_object_output_list, scatter_object_input_list, src=0, group=None
  1589. ):
  1590. """
  1591. Scatters picklable objects in ``scatter_object_input_list`` to the whole
  1592. group. Similar to :func:`scatter`, but Python objects can be passed in. On
  1593. each rank, the scattered object will be stored as the first element of
  1594. ``scatter_object_output_list``. Note that all objects in
  1595. ``scatter_object_input_list`` must be picklable in order to be scattered.
  1596. Args:
  1597. scatter_object_output_list (List[Any]): Non-empty list whose first
  1598. element will store the object scattered to this rank.
  1599. scatter_object_input_list (List[Any]): List of input objects to scatter.
  1600. Each object must be picklable. Only objects on the ``src`` rank will
  1601. be scattered, and the argument can be ``None`` for non-src ranks.
  1602. src (int): Source rank from which to scatter
  1603. ``scatter_object_input_list``.
  1604. group: (ProcessGroup, optional): The process group to work on. If None,
  1605. the default process group will be used. Default is ``None``.
  1606. Returns:
  1607. ``None``. If rank is part of the group, ``scatter_object_output_list``
  1608. will have its first element set to the scattered object for this rank.
  1609. .. note:: Note that this API differs slightly from the scatter collective
  1610. since it does not provide an ``async_op`` handle and thus will be a
  1611. blocking call.
  1612. .. note:: Note that this API does not support the NCCL backend, as the
  1613. tensor-based scatter collective is not supported by ProcessGroupNCCL.
  1614. .. warning::
  1615. :func:`scatter_object_list` uses ``pickle`` module implicitly, which
  1616. is known to be insecure. It is possible to construct malicious pickle
  1617. data which will execute arbitrary code during unpickling. Only call this
  1618. function with data you trust.
  1619. Example::
  1620. >>> # Note: Process group initialization omitted on each rank.
  1621. >>> import torch.distributed as dist
  1622. >>> if dist.get_rank() == 0:
  1623. >>> # Assumes world_size of 3.
  1624. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  1625. >>> else:
  1626. >>> # Can be any list on non-src ranks, elements are not used.
  1627. >>> objects = [None, None, None]
  1628. >>> output_list = [None]
  1629. >>> dist.scatter_object_list(output_list, objects, src=0)
  1630. >>> # Rank i gets objects[i]. For example, on rank 2:
  1631. >>> output_list
  1632. [{1: 2}]
  1633. """
  1634. if _rank_not_in_group(group):
  1635. _warn_not_in_group("scatter_object_list")
  1636. return
  1637. if (
  1638. not isinstance(scatter_object_output_list, list)
  1639. or len(scatter_object_output_list) < 1
  1640. ):
  1641. raise RuntimeError(
  1642. "Expected argument scatter_object_output_list to be a list of size at least 1."
  1643. )
  1644. my_rank = get_rank(group)
  1645. if my_rank == src:
  1646. tensor_list, tensor_sizes = zip(
  1647. *[_object_to_tensor(obj) for obj in scatter_object_input_list]
  1648. )
  1649. tensor_list, tensor_sizes = list(tensor_list), list(tensor_sizes)
  1650. # Src rank broadcasts the maximum tensor size. This is because all ranks are
  1651. # expected to call into scatter() with equal-sized tensors.
  1652. if my_rank == src:
  1653. max_tensor_size = max(tensor_sizes)
  1654. for tensor in tensor_list:
  1655. tensor.resize_(max_tensor_size)
  1656. else:
  1657. max_tensor_size = torch.tensor([0], dtype=torch.long)
  1658. broadcast(max_tensor_size, src=src, group=group)
  1659. # Scatter actual serialized objects
  1660. output_tensor = torch.empty(max_tensor_size.item(), dtype=torch.uint8)
  1661. scatter(
  1662. output_tensor,
  1663. scatter_list=None if my_rank != src else tensor_list,
  1664. src=src,
  1665. group=group,
  1666. )
  1667. # Scatter per-object sizes to trim tensors when deserializing back to object
  1668. obj_tensor_size = torch.tensor([0], dtype=torch.long)
  1669. scatter(
  1670. obj_tensor_size,
  1671. scatter_list=None if my_rank != src else tensor_sizes,
  1672. src=src,
  1673. group=group,
  1674. )
  1675. # Deserialize back to object
  1676. scatter_object_output_list[0] = _tensor_to_object(output_tensor, obj_tensor_size)
  1677. def all_gather(tensor_list, tensor, group=None, async_op=False):
  1678. """
  1679. Gathers tensors from the whole group in a list.
  1680. Complex tensors are supported.
  1681. Args:
  1682. tensor_list (list[Tensor]): Output list. It should contain
  1683. correctly-sized tensors to be used for output of the collective.
  1684. tensor (Tensor): Tensor to be broadcast from current process.
  1685. group (ProcessGroup, optional): The process group to work on. If None,
  1686. the default process group will be used.
  1687. async_op (bool, optional): Whether this op should be an async op
  1688. Returns:
  1689. Async work handle, if async_op is set to True.
  1690. None, if not async_op or if not part of the group
  1691. Examples:
  1692. >>> # All tensors below are of torch.int64 dtype.
  1693. >>> # We have 2 process groups, 2 ranks.
  1694. >>> tensor_list = [torch.zeros(2, dtype=torch.int64) for _ in range(2)]
  1695. >>> tensor_list
  1696. [tensor([0, 0]), tensor([0, 0])] # Rank 0 and 1
  1697. >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
  1698. >>> tensor
  1699. tensor([1, 2]) # Rank 0
  1700. tensor([3, 4]) # Rank 1
  1701. >>> dist.all_gather(tensor_list, tensor)
  1702. >>> tensor_list
  1703. [tensor([1, 2]), tensor([3, 4])] # Rank 0
  1704. [tensor([1, 2]), tensor([3, 4])] # Rank 1
  1705. >>> # All tensors below are of torch.cfloat dtype.
  1706. >>> # We have 2 process groups, 2 ranks.
  1707. >>> tensor_list = [torch.zeros(2, dtype=torch.cfloat) for _ in range(2)]
  1708. >>> tensor_list
  1709. [tensor([0.+0.j, 0.+0.j]), tensor([0.+0.j, 0.+0.j])] # Rank 0 and 1
  1710. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j)
  1711. >>> tensor
  1712. tensor([1.+1.j, 2.+2.j]) # Rank 0
  1713. tensor([3.+3.j, 4.+4.j]) # Rank 1
  1714. >>> dist.all_gather(tensor_list, tensor)
  1715. >>> tensor_list
  1716. [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 0
  1717. [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 1
  1718. """
  1719. _check_tensor_list(tensor_list, "tensor_list")
  1720. _check_single_tensor(tensor, "tensor")
  1721. if _rank_not_in_group(group):
  1722. _warn_not_in_group("all_gather")
  1723. return
  1724. tensor_list = [
  1725. t if not t.is_complex() else torch.view_as_real(t) for t in tensor_list
  1726. ]
  1727. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  1728. if group is None:
  1729. default_pg = _get_default_group()
  1730. work = default_pg.allgather([tensor_list], [tensor])
  1731. else:
  1732. work = group.allgather([tensor_list], [tensor])
  1733. if async_op:
  1734. return work
  1735. else:
  1736. work.wait()
  1737. def _all_gather_base(output_tensor, input_tensor, group=None, async_op=False):
  1738. """
  1739. Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
  1740. Args:
  1741. output_tensor (Tensor): Output tensor. It should contain
  1742. correctly-sized tensors to be used for output of the collective.
  1743. input_tensor (Tensor): Tensor to be broadcast from current process.
  1744. group (ProcessGroup, optional): The process group to work on. If None,
  1745. the default process group will be used.
  1746. async_op (bool, optional): Whether this op should be an async op
  1747. Returns:
  1748. Async work handle, if async_op is set to True.
  1749. None, if not async_op or if not part of the group
  1750. Examples:
  1751. >>> # All tensors below are of torch.int64 dtype.
  1752. >>> # We have 2 process groups, 2 ranks.
  1753. >>> output_tensor = torch.zeros(2, dtype=torch.int64)
  1754. >>> output_tensor
  1755. [tensor([0, 0])] # Rank 0 and 1
  1756. >>> tensor = torch.arange(1, dtype=torch.int64) + 1 + rank
  1757. >>> tensor
  1758. tensor([1]) # Rank 0
  1759. tensor([2]) # Rank 1
  1760. >>> dist.all_gather_base(output_tensor, tensor)
  1761. >>> output_tensor
  1762. tensor([1,2]) # Rank 0
  1763. tensor([1,2]) # Rank 1
  1764. .. warning::
  1765. `_all_gather_base` is experimental and subject to change.
  1766. It is the caller's responsibility to ensure the output_tensor
  1767. is correctly sized.
  1768. """
  1769. _check_single_tensor(input_tensor, "input_tensor")
  1770. _check_single_tensor(output_tensor, "output_tensor")
  1771. if _rank_not_in_group(group):
  1772. _warn_not_in_group("_all_gather_base")
  1773. return
  1774. output_tensor = (
  1775. output_tensor
  1776. if not output_tensor.is_complex()
  1777. else torch.view_as_real(output_tensor)
  1778. )
  1779. input_tensor = (
  1780. input_tensor
  1781. if not input_tensor.is_complex()
  1782. else torch.view_as_real(input_tensor)
  1783. )
  1784. if group is None:
  1785. default_pg = _get_default_group()
  1786. work = default_pg._allgather_base(output_tensor, input_tensor)
  1787. else:
  1788. work = group._allgather_base(output_tensor, input_tensor)
  1789. if async_op:
  1790. return work
  1791. else:
  1792. work.wait()
  1793. def all_gather_coalesced(
  1794. output_tensor_lists, input_tensor_list, group=None, async_op=False
  1795. ):
  1796. """
  1797. Gathers input tensors from the whole group in a list in a coalesced manner.
  1798. Complex tensors are supported.
  1799. Args:
  1800. output_tensor_lists (list[list[Tensor]]): Output list. It should contain
  1801. correctly-sized tensors to be used for output of the collective.
  1802. input_tensor_list (list[Tensor]): Tensors to be broadcast from
  1803. current process. At least one tensor has to be non empty.
  1804. group (ProcessGroup, optional): The process group to work on. If None,
  1805. the default process group will be used.
  1806. async_op (bool, optional): Whether this op should be an async op.
  1807. Returns:
  1808. Async work handle, if async_op is set to True.
  1809. None, if not async_op or if not part of the group
  1810. Example:
  1811. we have 2 process groups, 2 ranks.
  1812. rank 0 passes:
  1813. input_tensor_list = [[[1, 1], [1, 1]], [2], [3, 3]]
  1814. output_tensor_lists =
  1815. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  1816. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  1817. rank 1 passes:
  1818. input_tensor_list = [[[3, 3], [3, 3]], [5], [1, 1]]
  1819. output_tensor_lists =
  1820. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  1821. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  1822. both rank 0 and 1 get:
  1823. output_tensor_lists =
  1824. [[[1, 1], [1, 1]], [2], [3, 3]],
  1825. [[3, 3], [3, 3]], [5], [1, 1]]].
  1826. WARNING: at this time individual shape checking is not implemented across nodes.
  1827. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  1828. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the
  1829. all_gather_coalesced operation will proceed without complaint and return
  1830. erroneous outputs. This lack of shape checking results in significant
  1831. performance improvements but users of this function should take extra care
  1832. to ensure that each node passes in tensors whose shapes match across nodes.
  1833. """
  1834. # We only check basic compatibility with C++ params here, C++ code will
  1835. # do shape and type checking.
  1836. if _rank_not_in_group(group):
  1837. _warn_not_in_group("all_gather_coalesced")
  1838. return
  1839. _check_tensor_list(input_tensor_list, "tensor_list")
  1840. if not isinstance(output_tensor_lists, list):
  1841. raise RuntimeError(
  1842. "Invalid function argument: " "output_tensor_lists should be a list"
  1843. )
  1844. for output_tensor_list in output_tensor_lists:
  1845. _check_tensor_list(output_tensor_list, "output_tensor_lists")
  1846. output_tensor_lists = [
  1847. [t if not t.is_complex() else torch.view_as_real(t) for t in l]
  1848. for l in output_tensor_lists
  1849. ]
  1850. input_tensor_list = [
  1851. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  1852. ]
  1853. if group is None:
  1854. default_pg = _get_default_group()
  1855. work = default_pg.allgather_coalesced(output_tensor_lists, input_tensor_list)
  1856. else:
  1857. work = group.allgather_coalesced(output_tensor_lists, input_tensor_list)
  1858. if async_op:
  1859. return work.get_future()
  1860. else:
  1861. work.wait()
  1862. def _validate_output_list_for_rank(my_rank, dst, gather_list):
  1863. if dst == my_rank:
  1864. if not gather_list:
  1865. raise ValueError(
  1866. "Argument ``gather_list`` must be specified on destination rank."
  1867. )
  1868. elif gather_list:
  1869. raise ValueError(
  1870. "Argument ``gather_list`` must NOT be specified "
  1871. "on non-destination ranks."
  1872. )
  1873. def gather(tensor, gather_list=None, dst=0, group=None, async_op=False):
  1874. """
  1875. Gathers a list of tensors in a single process.
  1876. Args:
  1877. tensor (Tensor): Input tensor.
  1878. gather_list (list[Tensor], optional): List of appropriately-sized
  1879. tensors to use for gathered data (default is None, must be specified
  1880. on the destination rank)
  1881. dst (int, optional): Destination rank (default is 0)
  1882. group (ProcessGroup, optional): The process group to work on. If None,
  1883. the default process group will be used.
  1884. async_op (bool, optional): Whether this op should be an async op
  1885. Returns:
  1886. Async work handle, if async_op is set to True.
  1887. None, if not async_op or if not part of the group
  1888. """
  1889. _check_single_tensor(tensor, "tensor")
  1890. # Parameter ``gather_list`` may be left unspecified on non-dst ranks.
  1891. if gather_list:
  1892. _check_tensor_list(gather_list, "gather_list")
  1893. else:
  1894. gather_list = []
  1895. if _rank_not_in_group(group):
  1896. _warn_not_in_group("gather")
  1897. return
  1898. my_rank = get_rank()
  1899. _validate_output_list_for_rank(my_rank, dst, gather_list)
  1900. output_tensors = [gather_list] if dst == my_rank else []
  1901. input_tensors = [tensor]
  1902. opts = GatherOptions()
  1903. opts.rootRank = dst
  1904. if group is None or group is GroupMember.WORLD:
  1905. default_pg = _get_default_group()
  1906. work = default_pg.gather(output_tensors, input_tensors, opts)
  1907. else:
  1908. group_dst_rank = _get_group_rank(group, dst)
  1909. opts.rootRank = group_dst_rank
  1910. work = group.gather(output_tensors, input_tensors, opts)
  1911. if async_op:
  1912. return work
  1913. else:
  1914. work.wait()
  1915. def scatter(tensor, scatter_list=None, src=0, group=None, async_op=False):
  1916. """
  1917. Scatters a list of tensors to all processes in a group.
  1918. Each process will receive exactly one tensor and store its data in the
  1919. ``tensor`` argument.
  1920. Complex tensors are supported.
  1921. Args:
  1922. tensor (Tensor): Output tensor.
  1923. scatter_list (list[Tensor]): List of tensors to scatter (default is
  1924. None, must be specified on the source rank)
  1925. src (int): Source rank (default is 0)
  1926. group (ProcessGroup, optional): The process group to work on. If None,
  1927. the default process group will be used.
  1928. async_op (bool, optional): Whether this op should be an async op
  1929. Returns:
  1930. Async work handle, if async_op is set to True.
  1931. None, if not async_op or if not part of the group
  1932. """
  1933. _check_single_tensor(tensor, "tensor")
  1934. # Parameter ``scatter_list`` may be left unspecified on non-src ranks.
  1935. if scatter_list:
  1936. _check_tensor_list(scatter_list, "scatter_list")
  1937. else:
  1938. scatter_list = []
  1939. if _rank_not_in_group(group):
  1940. _warn_not_in_group("scatter")
  1941. return
  1942. scatter_list = [
  1943. t if not t.is_complex() else torch.view_as_real(t) for t in scatter_list
  1944. ]
  1945. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  1946. my_rank = get_rank()
  1947. if src == my_rank:
  1948. if not scatter_list:
  1949. raise ValueError(
  1950. "Argument ``scatter_list`` must be specified " "on source rank."
  1951. )
  1952. input_tensors = [scatter_list]
  1953. output_tensors = [tensor]
  1954. else:
  1955. if scatter_list:
  1956. raise ValueError(
  1957. "Argument ``scatter_list`` must NOT be specified "
  1958. "on non-source ranks."
  1959. )
  1960. input_tensors = []
  1961. output_tensors = [tensor]
  1962. opts = ScatterOptions()
  1963. opts.rootRank = src
  1964. if group is None or group is GroupMember.WORLD:
  1965. default_pg = _get_default_group()
  1966. work = default_pg.scatter(output_tensors, input_tensors, opts)
  1967. else:
  1968. group_src_rank = _get_group_rank(group, src)
  1969. opts.rootRank = group_src_rank
  1970. work = group.scatter(output_tensors, input_tensors, opts)
  1971. if async_op:
  1972. return work
  1973. else:
  1974. work.wait()
  1975. def reduce_scatter_multigpu(
  1976. output_tensor_list, input_tensor_lists, op=ReduceOp.SUM, group=None, async_op=False
  1977. ):
  1978. """
  1979. Reduce and scatter a list of tensors to the whole group. Only nccl backend
  1980. is currently supported.
  1981. Each tensor in ``output_tensor_list`` should reside on a separate GPU, as
  1982. should each list of tensors in ``input_tensor_lists``.
  1983. Args:
  1984. output_tensor_list (List[Tensor]): Output tensors (on different GPUs)
  1985. to receive the result of the operation.
  1986. Note that ``len(output_tensor_list)`` needs to be the same for all
  1987. the distributed processes calling this function.
  1988. input_tensor_lists (List[List[Tensor]]): Input lists. It should
  1989. contain correctly-sized tensors on each GPU to be used for input of
  1990. the collective, e.g. ``input_tensor_lists[i]`` contains the
  1991. reduce_scatter input that resides on the GPU of
  1992. ``output_tensor_list[i]``.
  1993. Note that each element of ``input_tensor_lists`` has the size of
  1994. ``world_size * len(output_tensor_list)``, since the function
  1995. scatters the result from every single GPU in the group. To
  1996. interpret each element of ``input_tensor_lists[i]``, note that
  1997. ``output_tensor_list[j]`` of rank k receives the reduce-scattered
  1998. result from ``input_tensor_lists[i][k * world_size + j]``
  1999. Also note that ``len(input_tensor_lists)``, and the size of each
  2000. element in ``input_tensor_lists`` (each element is a list,
  2001. therefore ``len(input_tensor_lists[i])``) need to be the same for
  2002. all the distributed processes calling this function.
  2003. group (ProcessGroup, optional): The process group to work on. If None,
  2004. the default process group will be used.
  2005. async_op (bool, optional): Whether this op should be an async op.
  2006. Returns:
  2007. Async work handle, if async_op is set to True.
  2008. None, if not async_op or if not part of the group.
  2009. """
  2010. if _rank_not_in_group(group):
  2011. _warn_not_in_group("reduce_scatter_multigpu")
  2012. return
  2013. opts = ReduceScatterOptions()
  2014. opts.reduceOp = op
  2015. if group is None:
  2016. default_pg = _get_default_group()
  2017. work = default_pg.reduce_scatter(output_tensor_list, input_tensor_lists, opts)
  2018. else:
  2019. work = group.reduce_scatter(output_tensor_list, input_tensor_lists, opts)
  2020. if async_op:
  2021. return work
  2022. else:
  2023. work.wait()
  2024. def reduce_scatter(output, input_list, op=ReduceOp.SUM, group=None, async_op=False):
  2025. """
  2026. Reduces, then scatters a list of tensors to all processes in a group.
  2027. Args:
  2028. output (Tensor): Output tensor.
  2029. input_list (list[Tensor]): List of tensors to reduce and scatter.
  2030. group (ProcessGroup, optional): The process group to work on. If None,
  2031. the default process group will be used.
  2032. async_op (bool, optional): Whether this op should be an async op.
  2033. Returns:
  2034. Async work handle, if async_op is set to True.
  2035. None, if not async_op or if not part of the group.
  2036. """
  2037. _check_single_tensor(output, "output")
  2038. _check_tensor_list(input_list, "input_list")
  2039. if _rank_not_in_group(group):
  2040. _warn_not_in_group("reduce_scatter")
  2041. return
  2042. opts = ReduceScatterOptions()
  2043. opts.reduceOp = op
  2044. if group is None:
  2045. default_pg = _get_default_group()
  2046. work = default_pg.reduce_scatter([output], [input_list], opts)
  2047. else:
  2048. work = group.reduce_scatter([output], [input_list], opts)
  2049. if async_op:
  2050. return work
  2051. else:
  2052. work.wait()
  2053. def _reduce_scatter_base(output, input, op=ReduceOp.SUM, group=None, async_op=False):
  2054. """
  2055. Reduces, then scatters a flattened tensor to all processes in a group.
  2056. Args:
  2057. output (Tensor): Output tensor.
  2058. input (Tensor): Input tensor that is of size output tensor size times world size
  2059. group (ProcessGroup, optional): The process group to work on. If None,
  2060. the default process group will be used.
  2061. async_op (bool, optional): Whether this op should be an async op.
  2062. Returns:
  2063. Async work handle, if async_op is set to True.
  2064. None, if not async_op or if not part of the group.
  2065. """
  2066. _check_single_tensor(output, "output")
  2067. _check_single_tensor(input, "input")
  2068. if _rank_not_in_group(group):
  2069. _warn_not_in_group("_reduce_scatter_base")
  2070. return
  2071. opts = ReduceScatterOptions()
  2072. opts.reduceOp = op
  2073. if group is None:
  2074. default_pg = _get_default_group()
  2075. work = default_pg._reduce_scatter_base(output, input, opts)
  2076. else:
  2077. work = group._reduce_scatter_base(output, input, opts)
  2078. if async_op:
  2079. return work
  2080. else:
  2081. work.wait()
  2082. def all_to_all_single(
  2083. output,
  2084. input,
  2085. output_split_sizes=None,
  2086. input_split_sizes=None,
  2087. group=None,
  2088. async_op=False,
  2089. ):
  2090. """
  2091. Each process splits input tensor and then scatters the split list
  2092. to all processes in a group. Then concatenate the received tensors from all
  2093. the processes in the group and return single output tensor.
  2094. Complex tensors are supported.
  2095. Args:
  2096. output (Tensor): Gathered cancatenated output tensor.
  2097. input (Tensor): Input tensor to scatter.
  2098. output_split_sizes: (list[Int], optional): Output split sizes for dim 0
  2099. if specified None or empty, dim 0 of ``output`` tensor must divide
  2100. equally by ``world_size``.
  2101. input_split_sizes: (list[Int], optional): Input split sizes for dim 0
  2102. if specified None or empty, dim 0 of ``input`` tensor must divide
  2103. equally by ``world_size``.
  2104. group (ProcessGroup, optional): The process group to work on. If None,
  2105. the default process group will be used.
  2106. async_op (bool, optional): Whether this op should be an async op.
  2107. Returns:
  2108. Async work handle, if async_op is set to True.
  2109. None, if not async_op or if not part of the group.
  2110. .. warning::
  2111. `all_to_all_single` is experimental and subject to change.
  2112. Examples:
  2113. >>> input = torch.arange(4) + rank * 4
  2114. >>> input
  2115. tensor([0, 1, 2, 3]) # Rank 0
  2116. tensor([4, 5, 6, 7]) # Rank 1
  2117. tensor([8, 9, 10, 11]) # Rank 2
  2118. tensor([12, 13, 14, 15]) # Rank 3
  2119. >>> output = torch.empty([4], dtype=torch.int64)
  2120. >>> dist.all_to_all_single(output, input)
  2121. >>> output
  2122. tensor([0, 4, 8, 12]) # Rank 0
  2123. tensor([1, 5, 9, 13]) # Rank 1
  2124. tensor([2, 6, 10, 14]) # Rank 2
  2125. tensor([3, 7, 11, 15]) # Rank 3
  2126. >>> # Essentially, it is similar to following operation:
  2127. >>> scatter_list = list(input.chunk(world_size))
  2128. >>> gather_list = list(output.chunk(world_size))
  2129. >>> for i in range(world_size):
  2130. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)
  2131. >>> # Another example with uneven split
  2132. >>> input
  2133. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  2134. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  2135. tensor([20, 21, 22, 23, 24]) # Rank 2
  2136. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  2137. >>> input_splits
  2138. [2, 2, 1, 1] # Rank 0
  2139. [3, 2, 2, 2] # Rank 1
  2140. [2, 1, 1, 1] # Rank 2
  2141. [2, 2, 2, 1] # Rank 3
  2142. >>> output_splits
  2143. [2, 3, 2, 2] # Rank 0
  2144. [2, 2, 1, 2] # Rank 1
  2145. [1, 2, 1, 2] # Rank 2
  2146. [1, 2, 1, 1] # Rank 3
  2147. >>> output = ...
  2148. >>> dist.all_to_all_single(output, input, output_splits, input_splits)
  2149. >>> output
  2150. tensor([ 0, 1, 10, 11, 12, 20, 21, 30, 31]) # Rank 0
  2151. tensor([ 2, 3, 13, 14, 22, 32, 33]) # Rank 1
  2152. tensor([ 4, 15, 16, 23, 34, 35]) # Rank 2
  2153. tensor([ 5, 17, 18, 24, 36]) # Rank 3
  2154. >>> # Another example with tensors of torch.cfloat type.
  2155. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
  2156. >>> input
  2157. tensor([1+1j, 2+2j, 3+3j, 4+4j]) # Rank 0
  2158. tensor([5+5j, 6+6j, 7+7j, 8+8j]) # Rank 1
  2159. tensor([9+9j, 10+10j, 11+11j, 12+12j]) # Rank 2
  2160. tensor([13+13j, 14+14j, 15+15j, 16+16j]) # Rank 3
  2161. >>> output = torch.empty([4], dtype=torch.int64)
  2162. >>> dist.all_to_all_single(output, input)
  2163. >>> output
  2164. tensor([1+1j, 5+5j, 9+9j, 13+13j]) # Rank 0
  2165. tensor([2+2j, 6+6j, 10+10j, 14+14j]) # Rank 1
  2166. tensor([3+3j, 7+7j, 11+11j, 15+15j]) # Rank 2
  2167. tensor([4+4j, 8+8j, 12+12j, 16+16j]) # Rank 3
  2168. """
  2169. if _rank_not_in_group(group):
  2170. _warn_not_in_group("all_to_all_single")
  2171. return
  2172. opts = AllToAllOptions()
  2173. _check_single_tensor(output, "output")
  2174. _check_single_tensor(input, "input")
  2175. if input.is_complex():
  2176. input = torch.view_as_real(input)
  2177. if output.is_complex():
  2178. output = torch.view_as_real(output)
  2179. output_split_sizes = [] if output_split_sizes is None else output_split_sizes
  2180. input_split_sizes = [] if input_split_sizes is None else input_split_sizes
  2181. if group is None:
  2182. default_pg = _get_default_group()
  2183. work = default_pg.alltoall_base(
  2184. output, input, output_split_sizes, input_split_sizes, opts
  2185. )
  2186. else:
  2187. work = group.alltoall_base(
  2188. output, input, output_split_sizes, input_split_sizes, opts
  2189. )
  2190. if async_op:
  2191. return work
  2192. else:
  2193. work.wait()
  2194. def all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False):
  2195. """
  2196. Each process scatters list of input tensors to all processes in a group and
  2197. return gathered list of tensors in output list.
  2198. Complex tensors are supported.
  2199. Args:
  2200. output_tensor_list (list[Tensor]): List of tensors to be gathered one
  2201. per rank.
  2202. input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
  2203. group (ProcessGroup, optional): The process group to work on. If None,
  2204. the default process group will be used.
  2205. async_op (bool, optional): Whether this op should be an async op.
  2206. Returns:
  2207. Async work handle, if async_op is set to True.
  2208. None, if not async_op or if not part of the group.
  2209. .. warning::
  2210. `all_to_all` is experimental and subject to change.
  2211. Examples:
  2212. >>> input = torch.arange(4) + rank * 4
  2213. >>> input = list(input.chunk(4))
  2214. >>> input
  2215. [tensor([0]), tensor([1]), tensor([2]), tensor([3])] # Rank 0
  2216. [tensor([4]), tensor([5]), tensor([6]), tensor([7])] # Rank 1
  2217. [tensor([8]), tensor([9]), tensor([10]), tensor([11])] # Rank 2
  2218. [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3
  2219. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  2220. >>> dist.all_to_all(output, input)
  2221. >>> output
  2222. [tensor([0]), tensor([4]), tensor([8]), tensor([12])] # Rank 0
  2223. [tensor([1]), tensor([5]), tensor([9]), tensor([13])] # Rank 1
  2224. [tensor([2]), tensor([6]), tensor([10]), tensor([14])] # Rank 2
  2225. [tensor([3]), tensor([7]), tensor([11]), tensor([15])] # Rank 3
  2226. >>> # Essentially, it is similar to following operation:
  2227. >>> scatter_list = input
  2228. >>> gather_list = output
  2229. >>> for i in range(world_size):
  2230. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)
  2231. >>> input
  2232. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  2233. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  2234. tensor([20, 21, 22, 23, 24]) # Rank 2
  2235. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  2236. >>> input_splits
  2237. [2, 2, 1, 1] # Rank 0
  2238. [3, 2, 2, 2] # Rank 1
  2239. [2, 1, 1, 1] # Rank 2
  2240. [2, 2, 2, 1] # Rank 3
  2241. >>> output_splits
  2242. [2, 3, 2, 2] # Rank 0
  2243. [2, 2, 1, 2] # Rank 1
  2244. [1, 2, 1, 2] # Rank 2
  2245. [1, 2, 1, 1] # Rank 3
  2246. >>> input = list(input.split(input_splits))
  2247. >>> input
  2248. [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])] # Rank 0
  2249. [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1
  2250. [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])] # Rank 2
  2251. [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])] # Rank 3
  2252. >>> output = ...
  2253. >>> dist.all_to_all(output, input)
  2254. >>> output
  2255. [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])] # Rank 0
  2256. [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])] # Rank 1
  2257. [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])] # Rank 2
  2258. [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])] # Rank 3
  2259. >>> # Another example with tensors of torch.cfloat type.
  2260. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
  2261. >>> input = list(input.chunk(4))
  2262. >>> input
  2263. [tensor([1+1j]), tensor([2+2j]), tensor([3+3j]), tensor([4+4j])] # Rank 0
  2264. [tensor([5+5j]), tensor([6+6j]), tensor([7+7j]), tensor([8+8j])] # Rank 1
  2265. [tensor([9+9j]), tensor([10+10j]), tensor([11+11j]), tensor([12+12j])] # Rank 2
  2266. [tensor([13+13j]), tensor([14+14j]), tensor([15+15j]), tensor([16+16j])] # Rank 3
  2267. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  2268. >>> dist.all_to_all(output, input)
  2269. >>> output
  2270. [tensor([1+1j]), tensor([5+5j]), tensor([9+9j]), tensor([13+13j])] # Rank 0
  2271. [tensor([2+2j]), tensor([6+6j]), tensor([10+10j]), tensor([14+14j])] # Rank 1
  2272. [tensor([3+3j]), tensor([7+7j]), tensor([11+11j]), tensor([15+15j])] # Rank 2
  2273. [tensor([4+4j]), tensor([8+8j]), tensor([12+12j]), tensor([16+16j])] # Rank 3
  2274. """
  2275. if _rank_not_in_group(group):
  2276. _warn_not_in_group("all_to_all")
  2277. return
  2278. opts = AllToAllOptions()
  2279. _check_tensor_list(output_tensor_list, "output_tensor_list")
  2280. _check_tensor_list(input_tensor_list, "input_tensor_list")
  2281. input_tensor_list = [
  2282. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  2283. ]
  2284. output_tensor_list = [
  2285. t if not t.is_complex() else torch.view_as_real(t) for t in output_tensor_list
  2286. ]
  2287. if group is None:
  2288. default_pg = _get_default_group()
  2289. work = default_pg.alltoall(output_tensor_list, input_tensor_list, opts)
  2290. else:
  2291. work = group.alltoall(output_tensor_list, input_tensor_list, opts)
  2292. if async_op:
  2293. return work
  2294. else:
  2295. work.wait()
  2296. def barrier(group=GroupMember.WORLD, async_op=False, device_ids=None):
  2297. """
  2298. Synchronizes all processes.
  2299. This collective blocks processes until the whole group enters this function,
  2300. if async_op is False, or if async work handle is called on wait().
  2301. Args:
  2302. group (ProcessGroup, optional): The process group to work on. If None,
  2303. the default process group will be used.
  2304. async_op (bool, optional): Whether this op should be an async op
  2305. device_ids ([int], optional): List of device/GPU ids.
  2306. Valid only for NCCL backend.
  2307. Returns:
  2308. Async work handle, if async_op is set to True.
  2309. None, if not async_op or if not part of the group
  2310. """
  2311. if _rank_not_in_group(group):
  2312. _warn_not_in_group("barrier")
  2313. return
  2314. opts = BarrierOptions()
  2315. if device_ids is not None:
  2316. if get_backend(group) != Backend.NCCL:
  2317. raise RuntimeError(
  2318. "Function argument device_ids not supported "
  2319. "for the selected backend {}".format(get_backend(group))
  2320. )
  2321. if isinstance(device_ids, list):
  2322. opts.device_ids = device_ids
  2323. else:
  2324. raise RuntimeError(
  2325. "Invalid function argument: " "device_ids type should be List[int]"
  2326. )
  2327. if group is None:
  2328. default_pg = _get_default_group()
  2329. work = default_pg.barrier(opts=opts)
  2330. else:
  2331. work = group.barrier(opts=opts)
  2332. if async_op:
  2333. return work
  2334. else:
  2335. work.wait()
  2336. def monitored_barrier(group=GroupMember.WORLD, timeout=None, wait_all_ranks=False):
  2337. """
  2338. Synchronizes all processes similar to ``torch.distributed.barrier``, but takes
  2339. a configurable timeout and is able to report ranks that did not pass this
  2340. barrier within that timeout. Specifically, for non-zero ranks, will block
  2341. until a send/recv is processed from rank 0. Rank 0 will block until all send
  2342. /recv from other ranks are processed, and will report failures for ranks
  2343. that failed to respond in time. Note that if one rank does not reach the
  2344. monitored_barrier (for example due to a hang), all other ranks would fail
  2345. in monitored_barrier.
  2346. This collective will block all processes/ranks in the group, until the
  2347. whole group exits the function successfully, making it useful for debugging
  2348. and synchronizing. However, it can have a performance impact and should only
  2349. be used for debugging or scenarios that require full synchronization points
  2350. on the host-side. For debugging purposees, this barrier can be inserted
  2351. before the application's collective calls to check if any ranks are
  2352. desynchronized.
  2353. .. note:: Note that this collective is only supported with the GLOO backend.
  2354. Args:
  2355. group (ProcessGroup, optional): The process group to work on. If
  2356. ``None``, the default process group will be used.
  2357. timeout (datetime.timedelta, optional): Timeout for monitored_barrier.
  2358. If ``None``, the default process group timeout will be used.
  2359. wait_all_ranks (bool, optional): Whether to collect all failed ranks or
  2360. not. By default, this is ``False`` and ``monitored_barrier`` on rank 0
  2361. will throw on the first failed rank it encounters in order to fail
  2362. fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will
  2363. collect all failed ranks and throw an error containing information
  2364. about all failed ranks.
  2365. Returns:
  2366. ``None``.
  2367. Example::
  2368. >>> # Note: Process group initialization omitted on each rank.
  2369. >>> import torch.distributed as dist
  2370. >>> if dist.get_rank() != 1:
  2371. >>> dist.monitored_barrier() # Raises exception indicating that
  2372. >>> # rank 1 did not call into monitored_barrier.
  2373. >>> # Example with wait_all_ranks=True
  2374. >>> if dist.get_rank() == 0:
  2375. >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception
  2376. >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into
  2377. >>> # monitored_barrier.
  2378. """
  2379. # Need to call rank not in group before using the group, otherwise
  2380. # "Invalid process group" error is raised.
  2381. if _rank_not_in_group(group):
  2382. _warn_not_in_group("monitored_barrier")
  2383. return
  2384. if get_backend(group) != Backend.GLOO:
  2385. raise RuntimeError("monitored_barrier is only implemented for GLOO backend.")
  2386. if timeout is None:
  2387. timeout = default_pg_timeout
  2388. group_to_use = _get_default_group() if group is None else group
  2389. return group_to_use.monitored_barrier(timeout, wait_all_ranks=wait_all_ranks)
  2390. def _create_process_group_wrapper(
  2391. wrapped_pg: ProcessGroup,
  2392. store_prefix: str,
  2393. store: Store,
  2394. rank: int,
  2395. world_size: int,
  2396. timeout: timedelta = default_pg_timeout,
  2397. ):
  2398. # Create a separate prefix store for the helper process group.
  2399. prefix = f"{PG_WRAPPER_STORE_PREFIX}:{store_prefix}"
  2400. store = PrefixStore(prefix, store)
  2401. helper_pg = ProcessGroupGloo(store, rank, world_size, timeout=timeout)
  2402. # Wrap the underlying pg with ProcessGroupWrapper.
  2403. wrapped_pg = _ProcessGroupWrapper(wrapped_pg, helper_pg)
  2404. return wrapped_pg
  2405. def new_group(ranks=None, timeout=default_pg_timeout, backend=None, pg_options=None):
  2406. """
  2407. Creates a new distributed group.
  2408. This function requires that all processes in the main group (i.e. all
  2409. processes that are part of the distributed job) enter this function, even
  2410. if they are not going to be members of the group. Additionally, groups
  2411. should be created in the same order in all processes.
  2412. .. warning::
  2413. Using multiple process groups with the ``NCCL`` backend concurrently
  2414. is not safe and the user should perform explicit synchronization in
  2415. their application to ensure only one process group is used at a time.
  2416. This means collectives from one process group should have completed
  2417. execution on the device (not just enqueued since CUDA execution is
  2418. async) before collectives from another process group are enqueued.
  2419. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  2420. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  2421. -multiple-nccl-communicators-concurrently>`_ for more details.
  2422. Args:
  2423. ranks (list[int]): List of ranks of group members. If ``None``, will be
  2424. set to all ranks. Default is ``None``.
  2425. timeout (timedelta, optional): Timeout for operations executed against
  2426. the process group. Default value equals 30 minutes.
  2427. This is applicable for the ``gloo`` backend. For ``nccl``, this is
  2428. applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
  2429. or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When
  2430. ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the
  2431. process will block and wait for collectives to complete before
  2432. throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,
  2433. this is the duration after which collectives will be aborted
  2434. asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``
  2435. will provide errors to the user which can be caught and handled,
  2436. but due to its blocking nature, it has a performance overhead. On
  2437. the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has very little
  2438. performance overhead, but crashes the process on errors. This is
  2439. done since CUDA execution is async and it is no longer safe to
  2440. continue executing user code since failed async NCCL operations
  2441. might result in subsequent CUDA operations running on corrupted
  2442. data. Only one of these two environment variables should be set.
  2443. backend (str or Backend, optional): The backend to use. Depending on
  2444. build-time configurations, valid values are ``gloo`` and ``nccl``.
  2445. By default uses the same backend as the global group. This field
  2446. should be given as a lowercase string (e.g., ``"gloo"``), which can
  2447. also be accessed via :class:`Backend` attributes (e.g.,
  2448. ``Backend.GLOO``). If ``None`` is passed in, the backend
  2449. corresponding to the default process group will be used. Default is
  2450. ``None``.
  2451. pg_options (ProcessGroupOptions, optional): process group options
  2452. specifying what additional options need to be passed in during
  2453. the construction of specific process groups. i.e. for the ``nccl``
  2454. backend, ``is_high_priority_stream`` can be specified so that
  2455. process group can pick up high priority cuda streams.
  2456. Returns:
  2457. A handle of distributed group that can be given to collective calls.
  2458. """
  2459. global _pg_group_ranks
  2460. default_pg = _get_default_group()
  2461. default_backend, default_store = _pg_map[default_pg]
  2462. global_rank = default_pg.rank()
  2463. global_world_size = default_pg.size()
  2464. # Default to the same backend as the global process group
  2465. # if the backend is not specified.
  2466. if not backend:
  2467. backend = default_backend
  2468. # checks the input ranks
  2469. if ranks is not None:
  2470. ranks = sorted(ranks)
  2471. group_world_size = len(ranks)
  2472. if group_world_size > global_world_size:
  2473. raise RuntimeError(
  2474. "the new group's world size should be less or "
  2475. "equal to the world size set by "
  2476. "init_process_group"
  2477. )
  2478. # check ranks' sanity
  2479. for rank in ranks:
  2480. if rank < 0 or rank >= global_world_size:
  2481. raise RuntimeError(
  2482. "The new group's rank should be within the "
  2483. "the world_size set by init_process_group"
  2484. )
  2485. if global_rank in ranks:
  2486. group_rank = ranks.index(global_rank)
  2487. else:
  2488. group_rank = None
  2489. else:
  2490. ranks = list(range(global_world_size))
  2491. group_world_size = global_world_size
  2492. group_rank = global_rank
  2493. backend = Backend(backend)
  2494. pg = _new_process_group_helper(
  2495. group_world_size,
  2496. group_rank,
  2497. ranks,
  2498. backend,
  2499. default_store,
  2500. pg_options=pg_options,
  2501. timeout=timeout,
  2502. )
  2503. # Create the global rank to group rank mapping
  2504. _pg_group_ranks[pg] = {
  2505. global_rank: group_rank for group_rank, global_rank in enumerate(ranks)
  2506. }
  2507. # barrier at the end to ensure that once we return from this method, all
  2508. # process groups including global variables are updated correctly on all
  2509. # ranks.
  2510. if backend == Backend.MPI:
  2511. # MPI doesn't have store.
  2512. barrier()
  2513. else:
  2514. # Use store based barrier here since barrier() used a bunch of
  2515. # default devices and messes up NCCL internal state.
  2516. _store_based_barrier(global_rank, default_store, timeout)
  2517. # Set sequence numbers for gloo and nccl process groups.
  2518. if pg != GroupMember.NON_GROUP_MEMBER and get_backend(pg) in [
  2519. Backend.GLOO,
  2520. Backend.NCCL,
  2521. ]:
  2522. pg._set_sequence_number_for_group()
  2523. return pg
  2524. def new_subgroups(
  2525. group_size=None,
  2526. group=None,
  2527. timeout=default_pg_timeout,
  2528. backend=None,
  2529. pg_options=None,
  2530. ):
  2531. """
  2532. Creates GPU subgroups of equal size. By default, it creates intra-machine subgroups,
  2533. where each of which contains all the ranks of a machine, based on the assumption
  2534. that each machine has the same number of CUDA devices.
  2535. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  2536. It requires that all processes in the main group (i.e. all
  2537. processes that are part of the distributed job) enter this function, even
  2538. if they are not going to be members of the group.
  2539. .. warning::
  2540. This API only works when CUDA is available.
  2541. .. warning::
  2542. If ``group_size`` is passed in, the world size must be divisible by ``group_size``.
  2543. If no ``group_size`` is passed in, and not all the machines have the same number
  2544. of devices, the subgroup division will be different across nodes and can cause
  2545. unexpected behaviors.
  2546. .. warning::
  2547. Using multiple process groups with the ``NCCL`` backend concurrently
  2548. is not safe and the user should perform explicit synchronization in
  2549. their application to ensure only one process group is used at a time.
  2550. This means collectives from one process group should have completed
  2551. execution on the device (not just enqueued since CUDA execution is
  2552. async) before collectives from another process group are enqueued.
  2553. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  2554. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  2555. -multiple-nccl-communicators-concurrently>`_ for more details.
  2556. Args:
  2557. group_size (int, optional): The size of each subgroup. If ``None``,
  2558. the default subgroup size is equal to the number of devices on each machine,
  2559. based on the assumption that each machine has exactly the same
  2560. number of devices. Default is ``None``.
  2561. timeout (timedelta, optional): Timeout for operations executed against
  2562. the process group. Default value equals 30 minutes.
  2563. This is applicable for the ``gloo`` backend. For ``nccl``, this is
  2564. applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
  2565. or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When
  2566. ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the
  2567. process will block and wait for collectives to complete before
  2568. throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,
  2569. this is the duration after which collectives will be aborted
  2570. asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``
  2571. will provide errors to the user which can be caught and handled,
  2572. but due to its blocking nature, it has a performance overhead. On
  2573. the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has very little
  2574. performance overhead, but crashes the process on errors. This is
  2575. done since CUDA execution is async and it is no longer safe to
  2576. continue executing user code since failed async NCCL operations
  2577. might result in subsequent CUDA operations running on corrupted
  2578. data. Only one of these two environment variables should be set.
  2579. backend (str or Backend, optional): The backend to use. Depending on
  2580. build-time configurations, valid values are ``gloo`` and ``nccl``.
  2581. By default uses the same backend as the global group. This field
  2582. should be given as a lowercase string (e.g., ``"gloo"``), which can
  2583. also be accessed via :class:`Backend` attributes (e.g.,
  2584. ``Backend.GLOO``). If ``None`` is passed in, the backend
  2585. corresponding to the default process group will be used. Default is
  2586. ``None``.
  2587. pg_options (ProcessGroupOptions, optional): process group options
  2588. specifying what additional options need to be passed in during
  2589. the construction of specific process groups. i.e. for the ``nccl``
  2590. backend, ``is_high_priority_stream`` can be specified so that
  2591. process group can pick up high priority cuda streams.
  2592. Returns:
  2593. The subgroup containing the current rank, and all the subgroups used for cleanup.
  2594. Examples:
  2595. >>> # Create intra-machine subgroups.
  2596. >>> cur_subgroup, subgroups = dist.new_subgroups()
  2597. >>> # Allreduce within the machine.
  2598. >>> rank = dist.get_rank()
  2599. >>> tensor = torch.ones(1, device=rank) * rank
  2600. >>> dist.all_reduce(tensor, group=cur_subgroup)
  2601. >>> tensor
  2602. tensor([8]) # Assume 8 is the number of CUDA devices per machine.
  2603. >>> # Cleanup.
  2604. >>> for subgroup in subgroups:
  2605. >>> dist.destroy_process_group(subgroup)
  2606. """
  2607. if not torch.cuda.is_available():
  2608. raise ValueError("Subgroups can only be created when CUDA is available")
  2609. if group_size is None:
  2610. group_size = torch.cuda.device_count()
  2611. world_size = get_world_size()
  2612. if world_size < group_size:
  2613. raise ValueError("The arg 'group_size' must not exceed the world size")
  2614. if world_size % group_size != 0:
  2615. raise ValueError("The world size must be divisible by 'group_size'")
  2616. subgroups = []
  2617. cur_subgroup = None
  2618. for subgroup_id in range(world_size // group_size):
  2619. start_rank = subgroup_id * group_size
  2620. end_rank = start_rank + group_size
  2621. ranks_in_subgroup = list(range(start_rank, end_rank))
  2622. subgroup = new_group(
  2623. ranks=ranks_in_subgroup,
  2624. timeout=timeout,
  2625. backend=backend,
  2626. pg_options=pg_options,
  2627. )
  2628. subgroups.append(subgroup)
  2629. rank = get_rank()
  2630. if rank in ranks_in_subgroup:
  2631. cur_subgroup = subgroup
  2632. logger.info(
  2633. "Rank {} is assigned to subgroup {}".format(rank, ranks_in_subgroup)
  2634. )
  2635. return cur_subgroup, subgroups
  2636. def new_subgroups_by_enumeration(
  2637. ranks_per_subgroup_list,
  2638. timeout=default_pg_timeout,
  2639. backend=None,
  2640. pg_options=None,
  2641. ):
  2642. """
  2643. Creates GPU subgroups by dividing the global world, where the division is specified by
  2644. a nested list of ranks. The subgroups cannot have overlap, and some ranks may not have
  2645. to be in any subgroup.
  2646. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  2647. It requires that all processes in the main group (i.e. all
  2648. processes that are part of the distributed job) enter this function, even
  2649. if they are not going to be members of the group.
  2650. .. warning::
  2651. Using multiple process groups with the ``NCCL`` backend concurrently
  2652. is not safe and the user should perform explicit synchronization in
  2653. their application to ensure only one process group is used at a time.
  2654. This means collectives from one process group should have completed
  2655. execution on the device (not just enqueued since CUDA execution is
  2656. async) before collectives from another process group are enqueued.
  2657. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  2658. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  2659. -multiple-nccl-communicators-concurrently>`_ for more details.
  2660. Args:
  2661. ranks_per_subgroup_list (list[list[int]]): A nested list of ranks of
  2662. group members.
  2663. timeout (timedelta, optional): Timeout for operations executed against
  2664. the process group. Default value equals 30 minutes.
  2665. This is applicable for the ``gloo`` backend. For ``nccl``, this is
  2666. applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
  2667. or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When
  2668. ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the
  2669. process will block and wait for collectives to complete before
  2670. throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,
  2671. this is the duration after which collectives will be aborted
  2672. asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``
  2673. will provide errors to the user which can be caught and handled,
  2674. but due to its blocking nature, it has a performance overhead. On
  2675. the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has very little
  2676. performance overhead, but crashes the process on errors. This is
  2677. done since CUDA execution is async and it is no longer safe to
  2678. continue executing user code since failed async NCCL operations
  2679. might result in subsequent CUDA operations running on corrupted
  2680. data. Only one of these two environment variables should be set.
  2681. backend (str or Backend, optional): The backend to use. Depending on
  2682. build-time configurations, valid values are ``gloo`` and ``nccl``.
  2683. By default uses the same backend as the global group. This field
  2684. should be given as a lowercase string (e.g., ``"gloo"``), which can
  2685. also be accessed via :class:`Backend` attributes (e.g.,
  2686. ``Backend.GLOO``). If ``None`` is passed in, the backend
  2687. corresponding to the default process group will be used. Default is
  2688. ``None``.
  2689. pg_options (ProcessGroupOptions, optional): process group options
  2690. specifying what additional options need to be passed in during
  2691. the construction of specific process groups. i.e. for the ``nccl``
  2692. backend, ``is_high_priority_stream`` can be specified so that
  2693. process group can pick up high priority cuda streams.
  2694. Returns:
  2695. The subgroup containing the current rank, and all the subgroups used for cleanup.
  2696. Examples:
  2697. >>> # Create two subgroups, where each has 2 processes.
  2698. >>> cur_subgroup, subgroups = dist.new_subgroups(ranks=[[0, 2], [1, 3]])
  2699. >>> rank = dist.get_rank()
  2700. >>> tensor = torch.ones(1, device=rank) * rank
  2701. >>> dist.all_reduce(tensor, group=cur_subgroup)
  2702. >>> tensor
  2703. tensor([2]) # Subgroup 0: ranks 0 and 2
  2704. tensor([4]) # Subgroup 1: ranks 1 and 3
  2705. """
  2706. if not torch.cuda.is_available():
  2707. raise ValueError("Subgroups can only be created when CUDA is available")
  2708. if ranks_per_subgroup_list is None or len(ranks_per_subgroup_list) == 0:
  2709. raise ValueError("The arg 'ranks_per_subgroup_list' cannot be empty")
  2710. world_size = get_world_size()
  2711. subgroups = []
  2712. cur_subgroup = None
  2713. # Create a mapping from rank to subgroup to check if there is any subgroup overlap.
  2714. rank_to_ranks_dict = {} # type: ignore[var-annotated]
  2715. for ranks in ranks_per_subgroup_list:
  2716. subgroup = new_group(
  2717. ranks=ranks,
  2718. timeout=timeout,
  2719. backend=backend,
  2720. pg_options=pg_options,
  2721. )
  2722. subgroups.append(subgroup)
  2723. my_rank = get_rank()
  2724. for rank in ranks:
  2725. if rank in rank_to_ranks_dict:
  2726. raise ValueError(
  2727. "Rank {} has appeared in both subgroup {} and {}".format(
  2728. rank, rank_to_ranks_dict[rank], ranks
  2729. )
  2730. )
  2731. rank_to_ranks_dict[rank] = ranks
  2732. if my_rank == rank:
  2733. cur_subgroup = subgroup
  2734. logger.info("Rank {} is assigned to subgroup {}".format(rank, ranks))
  2735. return cur_subgroup, subgroups