distributed_c10d.py 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541
  1. # mypy: allow-untyped-defs
  2. """Distributed Collective Communication (c10d)."""
  3. import itertools
  4. import collections.abc
  5. import contextlib
  6. import hashlib
  7. import io
  8. import logging
  9. import os
  10. import pickle
  11. import sys
  12. import time
  13. import warnings
  14. from collections import namedtuple
  15. from datetime import timedelta
  16. from typing import Any, Callable, Dict, Optional, Tuple, Union, List, TYPE_CHECKING
  17. from typing_extensions import deprecated
  18. import torch
  19. from torch._C._distributed_c10d import (
  20. AllgatherOptions,
  21. AllreduceCoalescedOptions,
  22. AllreduceOptions,
  23. AllToAllOptions,
  24. _DistributedBackendOptions,
  25. BarrierOptions,
  26. BroadcastOptions,
  27. GatherOptions,
  28. PrefixStore,
  29. ProcessGroup,
  30. ReduceOp,
  31. ReduceOptions,
  32. ReduceScatterOptions,
  33. ScatterOptions,
  34. Store,
  35. DebugLevel,
  36. get_debug_level,
  37. Work,
  38. _register_process_group,
  39. _resolve_process_group,
  40. _unregister_all_process_groups,
  41. _unregister_process_group,
  42. )
  43. from torch._utils_internal import set_pytorch_distributed_envs_from_justknobs
  44. from .constants import default_pg_timeout, default_pg_nccl_timeout
  45. from .c10d_logger import _exception_logger, _time_logger
  46. from .rendezvous import register_rendezvous_handler, rendezvous # noqa: F401
  47. from ..utils._typing_utils import not_none
  48. DistStoreError = torch._C._DistStoreError
  49. __all__ = [
  50. 'Backend', 'BackendConfig', 'GroupMember', 'P2POp', 'all_gather', 'all_gather_coalesced',
  51. 'all_gather_object', 'all_reduce',
  52. 'all_reduce_coalesced', 'all_to_all',
  53. 'all_to_all_single', 'barrier', 'batch_isend_irecv', 'broadcast', 'send_object_list',
  54. 'recv_object_list', 'broadcast_object_list', 'destroy_process_group',
  55. 'gather', 'gather_object', 'get_backend_config', 'get_backend', 'get_rank',
  56. 'get_world_size', 'get_pg_count', 'group', 'init_process_group', 'irecv',
  57. 'is_gloo_available', 'is_initialized', 'is_mpi_available', 'is_backend_available',
  58. 'is_nccl_available', 'is_torchelastic_launched', 'is_ucc_available',
  59. 'isend', 'monitored_barrier', 'new_group', 'new_subgroups',
  60. 'new_subgroups_by_enumeration', 'recv', 'reduce',
  61. 'reduce_scatter', 'scatter',
  62. 'scatter_object_list', 'send', 'supports_complex',
  63. 'AllreduceCoalescedOptions', 'AllreduceOptions', 'AllToAllOptions',
  64. 'BarrierOptions', 'BroadcastOptions', 'GatherOptions', 'PrefixStore',
  65. 'ProcessGroup', 'ReduceOp', 'ReduceOptions', 'ReduceScatterOptions',
  66. 'ScatterOptions', 'Store', 'DebugLevel', 'get_debug_level', 'Work',
  67. 'default_pg_timeout', 'get_group_rank', 'get_global_rank', 'get_process_group_ranks',
  68. 'reduce_op', 'all_gather_into_tensor', 'reduce_scatter_tensor', 'get_node_local_rank',
  69. ]
  70. _MPI_AVAILABLE = True
  71. _NCCL_AVAILABLE = True
  72. _GLOO_AVAILABLE = True
  73. _UCC_AVAILABLE = True
  74. _pickler = pickle.Pickler
  75. _unpickler = pickle.Unpickler
  76. # Change __module__ of all imported types from torch._C._distributed_c10d that are public
  77. def _export_c_types() -> None:
  78. _public_types_to_change_module = [
  79. AllreduceCoalescedOptions,
  80. AllreduceOptions,
  81. AllToAllOptions,
  82. BarrierOptions,
  83. BroadcastOptions,
  84. GatherOptions,
  85. PrefixStore,
  86. ProcessGroup,
  87. ReduceOp,
  88. ReduceOptions,
  89. ReduceScatterOptions,
  90. ScatterOptions,
  91. Store,
  92. DebugLevel,
  93. get_debug_level,
  94. Work
  95. ]
  96. for type in _public_types_to_change_module:
  97. type.__module__ = "torch.distributed.distributed_c10d"
  98. _export_c_types()
  99. try:
  100. from torch._C._distributed_c10d import ProcessGroupMPI
  101. ProcessGroupMPI.__module__ = "torch.distributed.distributed_c10d"
  102. __all__ += ["ProcessGroupMPI"]
  103. except ImportError:
  104. _MPI_AVAILABLE = False
  105. try:
  106. from torch._C._distributed_c10d import ProcessGroupNCCL
  107. from torch._C._distributed_c10d import ProcessGroupCudaP2P
  108. ProcessGroupNCCL.__module__ = "torch.distributed.distributed_c10d"
  109. ProcessGroupCudaP2P.__module__ = "torch.distributed.distributed_c10d"
  110. __all__ += ["ProcessGroupNCCL", "ProcessGroupCudaP2P"]
  111. except ImportError:
  112. _NCCL_AVAILABLE = False
  113. try:
  114. from torch._C._distributed_c10d import ProcessGroupGloo
  115. from torch._C._distributed_c10d import _ProcessGroupWrapper
  116. ProcessGroupGloo.__module__ = "torch.distributed.distributed_c10d"
  117. __all__ += ["ProcessGroupGloo"]
  118. except ImportError:
  119. _GLOO_AVAILABLE = False
  120. try:
  121. from torch._C._distributed_c10d import ProcessGroupUCC
  122. ProcessGroupUCC.__module__ = "torch.distributed.distributed_c10d"
  123. __all__ += ["ProcessGroupUCC"]
  124. except ImportError:
  125. _UCC_AVAILABLE = False
  126. logger = logging.getLogger(__name__)
  127. PG_WRAPPER_STORE_PREFIX = "pg_wrapper"
  128. # Some reduce ops are not supported by complex numbers and will result in an error.
  129. # We currently provide complex support to the distributed API by viewing
  130. # complex tensors as real (torch.view_as_real), meaning that calling
  131. # these unsupported ops will return garbage values rather than error out.
  132. # (e.g. max(2+3i, 3+2i) = 3+3i)
  133. # We'd like calls to unsupported ops to error out accordingly,
  134. # rather than returning garbage values.
  135. def supports_complex(reduceOp: ReduceOp) -> bool:
  136. """Return true if reduce ops is supported. False otherwise."""
  137. denyList = [
  138. ReduceOp.MAX,
  139. ReduceOp.MIN,
  140. ReduceOp.PRODUCT,
  141. ReduceOp.BAND,
  142. ReduceOp.BOR,
  143. ReduceOp.BXOR,
  144. ]
  145. return reduceOp not in denyList
  146. class Backend(str):
  147. """
  148. An enum-like class for backends.
  149. Available backends: GLOO, NCCL, UCC, MPI, and other registered backends.
  150. The values of this class are lowercase strings, e.g., ``"gloo"``. They can
  151. be accessed as attributes, e.g., ``Backend.NCCL``.
  152. This class can be directly called to parse the string, e.g.,
  153. ``Backend(backend_str)`` will check if ``backend_str`` is valid, and
  154. return the parsed lowercase string if so. It also accepts uppercase strings,
  155. e.g., ``Backend("GLOO")`` returns ``"gloo"``.
  156. .. note:: The entry ``Backend.UNDEFINED`` is present but only used as
  157. initial value of some fields. Users should neither use it directly
  158. nor assume its existence.
  159. """
  160. UNDEFINED = "undefined"
  161. GLOO = "gloo"
  162. NCCL = "nccl"
  163. UCC = "ucc"
  164. MPI = "mpi"
  165. _BackendPlugin = namedtuple("_BackendPlugin", ["creator_fn", "extended_api"])
  166. _plugins: Dict[str, _BackendPlugin] = {}
  167. backend_list = [UNDEFINED, GLOO, NCCL, UCC, MPI]
  168. default_device_backend_map: Dict[str, str] = {
  169. 'cpu' : GLOO,
  170. 'cuda' : NCCL,
  171. }
  172. backend_capability: Dict[str, List[str]] = {
  173. GLOO : ["cpu", "cuda"],
  174. NCCL : ["cuda"],
  175. UCC : ["cpu", "cuda"],
  176. MPI : ["cpu", "cuda"],
  177. }
  178. backend_type_map: Dict[str, ProcessGroup.BackendType] = {
  179. UNDEFINED: ProcessGroup.BackendType.UNDEFINED,
  180. GLOO : ProcessGroup.BackendType.GLOO,
  181. NCCL: ProcessGroup.BackendType.NCCL,
  182. UCC: ProcessGroup.BackendType.UCC,
  183. }
  184. def __new__(cls, name: str):
  185. """Create and return a new instance of the class."""
  186. if not isinstance(name, str):
  187. raise ValueError("Backend constructor parameter must be string-ish")
  188. value = getattr(Backend, name.upper(), Backend.UNDEFINED)
  189. if value == Backend.UNDEFINED:
  190. value = name.lower()
  191. return value
  192. @classmethod
  193. def register_backend(cls, name, func, extended_api=False, devices: Optional[Union[str, List[str]]] = None) -> None:
  194. """
  195. Register a new backend with the given name and instantiating function.
  196. This class method is used by 3rd party ``ProcessGroup`` extension to
  197. register new backends.
  198. Args:
  199. name (str): Backend name of the ``ProcessGroup`` extension. It
  200. should match the one in ``init_process_group()``.
  201. func (function): Function handler that instantiates the backend.
  202. The function should be implemented in the backend
  203. extension and takes four arguments, including
  204. ``store``, ``rank``, ``world_size``, and ``timeout``.
  205. extended_api (bool, optional): Whether the backend supports extended argument structure.
  206. Default: ``False``. If set to ``True``, the backend
  207. will get an instance of ``c10d::DistributedBackendOptions``, and
  208. a process group options object as defined by the backend implementation.
  209. device (str or list of str, optional): device type this backend
  210. supports, e.g. "cpu", "cuda", etc. If `None`,
  211. assuming both "cpu" and "cuda"
  212. .. note:: This support of 3rd party backend is experimental and subject to change.
  213. """
  214. # Allow UCC plugin if Pytorch is not built with native support.
  215. # TODO: remove this exception once UCC plugin is fully deprecated.
  216. if (name != Backend.UCC or (name == Backend.UCC and is_ucc_available())):
  217. assert not hasattr(Backend, name.upper()), (
  218. f"{name.upper()} c10d backend already exist"
  219. )
  220. assert name.upper() not in Backend._plugins, (
  221. f"{name.upper()} c10d backend creator function already exist"
  222. )
  223. setattr(Backend, name.upper(), name.lower())
  224. Backend.backend_list.append(name.lower())
  225. if devices is not None:
  226. for device in devices:
  227. if device != 'cpu' and device != 'cuda':
  228. Backend.default_device_backend_map[device] = name.lower()
  229. Backend.backend_type_map[name.lower()] = ProcessGroup.BackendType.CUSTOM
  230. # Update device capability matrix in Backend class
  231. if devices is None:
  232. # This is more of a backward support for groups like `threaded`:
  233. # assume default devices "cpu" and "cuda", but warn
  234. warnings.warn(
  235. f"Device capability of {name} unspecified, assuming `cpu` and "
  236. "`cuda`. Please specify it via the `devices` argument of "
  237. "`register_backend`."
  238. )
  239. Backend.backend_capability[name.lower()] = ["cpu", "cuda"]
  240. elif isinstance(devices, str):
  241. # Single device string specified. Simply convert to list.
  242. Backend.backend_capability[name.lower()] = [devices]
  243. else:
  244. Backend.backend_capability[name.lower()] = devices
  245. Backend._plugins[name.upper()] = Backend._BackendPlugin(func, extended_api)
  246. class BackendConfig:
  247. """Backend configuration class."""
  248. def __init__(self, backend: Backend):
  249. """Init."""
  250. self.device_backend_map: Dict[str, Backend] = {}
  251. backend = str(backend)
  252. if backend == Backend.UNDEFINED:
  253. # default config when backend is not specified
  254. # supported since PyTorch 2.0
  255. for device, default_backend in Backend.default_device_backend_map.items():
  256. if is_backend_available(default_backend):
  257. if default_backend == Backend.NCCL and not torch.cuda.is_available():
  258. continue
  259. self.device_backend_map[device] = Backend(default_backend)
  260. elif backend.lower() in Backend.backend_list:
  261. # Cases for when backend is a single string (without device types)
  262. # e.g. "nccl", "gloo", "ucc", "mpi"
  263. supported_devices = Backend.backend_capability[backend.lower()]
  264. backend_val = Backend(backend)
  265. self.device_backend_map = dict.fromkeys(supported_devices, backend_val)
  266. elif ":" in backend.lower():
  267. # Backend specified in "device:backend" format
  268. # make sure the backend string is in the correct format
  269. # "{device_type1}:{backend1},{device_type2}:{backend2}"
  270. # e.g. "cpu:gloo,cuda:nccl"
  271. backend_str_error_message = f"""The custom backend string argument is invalid: {backend}.
  272. Custom backend string is an experimental feature where the backend string must be in the format:
  273. "<device_type1>:<backend1>,<device_type2>:<backend2>...". e.g. 'cpu:gloo,cuda:nccl'"""
  274. # parse the backend string and populate the device_backend_map
  275. for device_backend_pair_str in backend.lower().split(","):
  276. device_backend_pair = device_backend_pair_str.split(":")
  277. if len(device_backend_pair) != 2:
  278. raise ValueError(f"Invalid device:backend pairing: \
  279. {device_backend_pair_str}. {backend_str_error_message}")
  280. device, backend = device_backend_pair
  281. if device in self.device_backend_map:
  282. raise ValueError(f"Duplicate device type {device} \
  283. in backend string: {backend}. {backend_str_error_message}")
  284. self.device_backend_map[device] = Backend(backend)
  285. else:
  286. # User specified a single backend name whose device capability is
  287. # unknown, assuming it can support the default devices of PyTorch
  288. # (cpu and cuda)
  289. warnings.warn(
  290. f"Device capability of {backend} unknown, assuming `cpu` and "
  291. "`cuda`. You can specify it in `device:backend` format in "
  292. "`init_process_group` call."
  293. )
  294. backend_val = Backend(backend)
  295. self.device_backend_map = {
  296. "cpu" : backend_val,
  297. "cuda" : backend_val,
  298. "xpu" : backend_val,
  299. }
  300. logger.info(
  301. "Using backend config: %s", self.device_backend_map
  302. )
  303. def __repr__(self):
  304. """Return all the device:backend pairs separated by commas."""
  305. return ",".join(f"{device}:{backend}" for device, backend in self.device_backend_map.items())
  306. def get_device_backend_map(self) -> Dict[str, Backend]:
  307. """Return backend map of the device."""
  308. return self.device_backend_map
  309. class _reduce_op:
  310. r"""
  311. Deprecated enum-like class.
  312. For reduction operations: ``SUM``, ``PRODUCT``, ``MIN``, and ``MAX``.
  313. :class:`~torch.distributed.ReduceOp` is recommended to use instead.
  314. """
  315. def __init__(self):
  316. # __members__ is a dict storing key-value pairs for enum classes
  317. for k, v in ReduceOp.RedOpType.__members__.items():
  318. setattr(self, k, v)
  319. self.__members__ = ReduceOp.RedOpType.__members__
  320. @deprecated(
  321. "`torch.distributed.reduce_op` is deprecated, "
  322. "please use `torch.distributed.ReduceOp` instead",
  323. category=FutureWarning,
  324. )
  325. def __getattribute__(self, key):
  326. return object.__getattribute__(self, key)
  327. reduce_op = _reduce_op()
  328. class P2POp:
  329. """
  330. A class to build point-to-point operations for ``batch_isend_irecv``.
  331. This class builds the type of P2P operation, communication buffer, peer rank,
  332. Process Group, and tag. Instances of this class will be passed to
  333. ``batch_isend_irecv`` for point-to-point communications.
  334. Args:
  335. op (Callable): A function to send data to or receive data from a peer process.
  336. The type of ``op`` is either ``torch.distributed.isend`` or
  337. ``torch.distributed.irecv``.
  338. tensor (Tensor): Tensor to send or receive.
  339. peer (int): Destination or source rank.
  340. group (ProcessGroup, optional): The process group to work on. If None,
  341. the default process group will be used.
  342. tag (int, optional): Tag to match send with recv.
  343. """
  344. def __init__(self, op: Callable, tensor: torch.Tensor, peer: int,
  345. group: Optional[ProcessGroup] = None, tag: int = 0):
  346. """Init."""
  347. self.op = op
  348. self.tensor = tensor
  349. self.peer = peer
  350. self.group = group
  351. self.tag = tag
  352. def __new__(cls, op: Callable, tensor: torch.Tensor, peer: int,
  353. group: Optional[ProcessGroup] = None, tag: int = 0):
  354. """Create and return a new instance of the class."""
  355. _check_op(op)
  356. _check_single_tensor(tensor, "tensor")
  357. return object.__new__(cls)
  358. def __repr__(self):
  359. my_group_rank = get_rank(self.group)
  360. peer_group_rank = get_group_rank(self.group, self.peer) if self.group else self.peer
  361. op_name = self.op.__name__
  362. group_name = self.group.group_name if self.group else "default_pg"
  363. if "send" in op_name:
  364. s = my_group_rank
  365. d = peer_group_rank
  366. elif "recv" in op_name:
  367. s = peer_group_rank
  368. d = my_group_rank
  369. else:
  370. return super().__repr__()
  371. return f"P2POp({op_name} pg={group_name}, s={s}, d={d}, {self.tensor.shape}, {self.tensor.dtype})"
  372. class _CollOp:
  373. """
  374. A class to capture collective operations.
  375. Args:
  376. op (Callable): A collective function, e.g. ``torch.distributed.all_reduce``.
  377. tensor (Tensor): Tensor to operate on.
  378. dst_tensor (Tensor, optional): Provided when source and destinaton tensors are not the same.
  379. redop (ReduceOp, optional): reduce operation.
  380. root (int, optional): root of broadcast or reduce.
  381. """
  382. def __init__(self, op: Callable, tensor: torch.Tensor, dst_tensor: Optional[torch.Tensor] = None,
  383. redop: Optional[ReduceOp] = None, root: Optional[int] = None):
  384. self.op = op
  385. self.tensor = tensor
  386. self.dst_tensor = dst_tensor
  387. self.redop = redop
  388. self.root = root
  389. # DO NOT USE THESE FIELDS DIRECTLY.
  390. # Use them through the _world object to make sure the _world override mechanism
  391. _pg_map: Dict[ProcessGroup, Tuple[str, Store]] = {}
  392. _pg_names: Dict[ProcessGroup, str] = {}
  393. _pg_group_ranks: Dict[ProcessGroup, Dict[int, int]] = {}
  394. # For a pg, it is a map from ProcessGroup to BackendConfig
  395. _pg_backend_config: Dict[ProcessGroup, str] = {}
  396. _group_count = 0
  397. _tags_to_pg: Dict[str, List[ProcessGroup]] = {}
  398. _pg_to_tag: Dict[ProcessGroup, str] = {}
  399. _backend: Optional[str] = None
  400. class _World:
  401. """
  402. Container class for c10d process group state.
  403. This is used during registration and lookup of PG state.
  404. .. warning:: This is an experimental API intended to expose the inner workings
  405. of c10d and is subject to change..
  406. """
  407. def __init__(self):
  408. self._default_pg = None
  409. self._pg_coalesce_state: Dict[ProcessGroup, List[_CollOp]] = {}
  410. self._pg_default_device: Dict[ProcessGroup, torch.device] = {}
  411. @property
  412. def default_pg(self) -> Optional[ProcessGroup]:
  413. """
  414. Process group that includes all ranks of the cluster.
  415. This default ProcessGroup is used by c10d APIs when a ProcessGroup is needed
  416. but None is provided.
  417. """
  418. return self._default_pg
  419. @default_pg.setter
  420. def default_pg(self, value) -> None:
  421. self._default_pg = value
  422. @property
  423. def pg_map(self) -> Dict[ProcessGroup, Tuple[str, Store]]:
  424. """
  425. Provide Mapping from ProcessGroup to backend name and store.
  426. For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
  427. For MPI pg, it is a map from ProcessGroup to (Backend, None)
  428. TODO don't expose the map, expose fine grained ops
  429. """
  430. global _pg_map
  431. return _pg_map
  432. @property
  433. def pg_names(self) -> Dict[ProcessGroup, str]:
  434. """
  435. Process group's names, map from ProcessGroup to str.
  436. TODO don't expose the map, expose fine grained ops
  437. """
  438. global _pg_names
  439. return _pg_names
  440. @property
  441. def pg_group_ranks(self) -> Dict[ProcessGroup, Dict[int, int]]:
  442. """
  443. Process group's global rank to local rank mapping.
  444. TODO don't expose the map, expose fine grained ops
  445. """
  446. global _pg_group_ranks
  447. return _pg_group_ranks
  448. @property
  449. def pg_backend_config(self) -> Dict[ProcessGroup, str]:
  450. """
  451. Process group's backend config.
  452. TODO don't expose the map, expose fine grained ops
  453. """
  454. global _pg_backend_config
  455. return _pg_backend_config
  456. @property
  457. def group_count(self) -> int:
  458. """
  459. Process group count for default naming.
  460. TODO don't expose group_count, use something else instead
  461. """
  462. global _group_count
  463. return _group_count
  464. @group_count.setter
  465. def group_count(self, value: int) -> None:
  466. """Use to compute the name of ProcessGroups when using global synchronization."""
  467. global _group_count
  468. _group_count = value
  469. @property
  470. def tags_to_pg(self) -> Dict[str, List[ProcessGroup]]:
  471. global _tags_to_pg
  472. return _tags_to_pg
  473. @property
  474. def pg_to_tag(self) -> Dict[ProcessGroup, str]:
  475. global _pg_to_tag
  476. return _pg_to_tag
  477. @property
  478. def pg_coalesce_state(self) -> Dict[ProcessGroup, List[_CollOp]]:
  479. return self._pg_coalesce_state
  480. @property
  481. def pg_default_device(self) -> Dict[ProcessGroup, torch.device]:
  482. return self._pg_default_device
  483. @property
  484. def pg_config_info(self) -> List[Dict[str, Any]]:
  485. """
  486. Return a list of dict with process groups and backends.
  487. Along with their unique IDs and configurations (types and ranks).
  488. """
  489. config_info: List[Dict[str, Any]] = []
  490. default_pg_size = _get_group_size(None)
  491. for pg in self.pg_map.keys():
  492. ranks = self.pg_group_ranks[pg]
  493. config_info.append(
  494. {
  495. "pg_name": self.pg_names[pg],
  496. "pg_desc": pg.group_desc,
  497. "backend_config": self.pg_backend_config[pg],
  498. "ranks": list(ranks.keys())
  499. if len(ranks) != default_pg_size
  500. else [], # 'ranks' is an empty list when all ranks are involved in a pg
  501. "group_size": len(ranks),
  502. "group_count": self.group_count,
  503. }
  504. )
  505. return config_info
  506. _world = _World()
  507. """Holds the singleton instance of ``_World`` used by c10. Experimental extension point to override it"""
  508. class _WorldMeta(type):
  509. """
  510. Meta class of ``group`` and ``GroupMember``.
  511. Allows them to have the class property ``WORLD``.
  512. """
  513. # Points to the default PG once initialized.
  514. @property
  515. def WORLD(cls) -> Optional[ProcessGroup]:
  516. return _world.default_pg
  517. @WORLD.setter
  518. def WORLD(cls, pg: Optional[ProcessGroup]):
  519. _world.default_pg = pg
  520. class group(metaclass=_WorldMeta):
  521. """Group class. Placeholder."""
  522. pass
  523. class GroupMember(metaclass=_WorldMeta):
  524. """Group member class."""
  525. NON_GROUP_MEMBER = -100
  526. def _get_default_timeout(backend: Backend) -> timedelta:
  527. # see note on nccl vs other backend timeout (constants.py)
  528. if backend == Backend.NCCL:
  529. if not isinstance(default_pg_nccl_timeout, timedelta):
  530. # TODO moco benchmark on CPU initializes pgnccl backend today, triggered this assert in CI before it was
  531. # changed to be a warning. We should fix the moco model.
  532. warnings.warn("Attempted to get default timeout for nccl backend, but NCCL support is not compiled")
  533. return default_pg_timeout
  534. return default_pg_nccl_timeout
  535. else:
  536. return default_pg_timeout
  537. def _check_valid_timeout(timeout: Any) -> None:
  538. if not isinstance(timeout, timedelta):
  539. raise TypeError(
  540. f"Expected timeout argument to be of type datetime.timedelta, got {timeout}"
  541. )
  542. # Default process group state
  543. _default_pg_init_method: Optional[str] = None
  544. STORE_BASED_BARRIER_PREFIX = "store_based_barrier_key"
  545. def _get_pg_default_device(group: Optional[ProcessGroup] = None) -> torch.device:
  546. """
  547. Return the device to use with ``group`` for control flow usage (object collectives, barrier).
  548. There are selection rules:
  549. 1. If user specifies exactly one backend in ``init_process_group`` call:
  550. use that backend
  551. 2. Else if user specifies multiple "device:backend" pairs in init_process_group:
  552. If "cpu" is among those pairs, use "cpu" (because the object is in cpu memory);
  553. Otherwise, use the first backend (sort of a random pick).
  554. Args:
  555. group (ProcessGroup, optional): The process group to work on. If None,
  556. the default process group will be used.
  557. Returns:
  558. torch.device: The device to use with ``group``.
  559. """
  560. group = group or _get_default_group()
  561. if group in _world.pg_default_device:
  562. # Previously searched and cached; just return
  563. return _world.pg_default_device[group]
  564. if not isinstance(group, ProcessGroup):
  565. # Provide backward compatibility to cases where `group` passed in is
  566. # actually a Backend (like `ProcessGroupGloo`) rather than a
  567. # `ProcessGroup` in PT 2.0 sense
  568. warnings.warn(
  569. f"You are using a Backend {type(group)} as a ProcessGroup. "
  570. "This usage is deprecated since PyTorch 2.0. Please use a public API "
  571. "of PyTorch Distributed instead.",
  572. FutureWarning,
  573. stacklevel=3,
  574. )
  575. # Most users create Gloo with private API for object collectives
  576. _world.pg_default_device[group] = torch.device("cpu")
  577. return _world.pg_default_device[group]
  578. """
  579. ``group._device_types`` is a property pybind that returns the devices
  580. ("cpu", "cuda", etc) supported by ``group``. Can be multiple if the
  581. ``group`` supports multiple devices.
  582. """
  583. devices = group._device_types
  584. if len(devices) == 1:
  585. # User fixed exactly one backend in `init_process_group`
  586. _world.pg_default_device[group] = devices[0]
  587. elif len(devices) == 0:
  588. # No backend has been registered with this PG (maybe because no
  589. # collective has been run?) We pick cpu as the default and hopefully
  590. # this would lazily init Gloo or other available cpu backend.
  591. _world.pg_default_device[group] = torch.device("cpu")
  592. elif torch.device("cpu") in devices:
  593. # There are multiple backends in this PG and cpu is among them.
  594. # cpu is preferred as the object is in cpu memory. No need for device
  595. # copy.
  596. _world.pg_default_device[group] = torch.device("cpu")
  597. else:
  598. # No cpu in the backend list. Randomly pick the first backend
  599. _world.pg_default_device[group] = devices[0]
  600. logger.info(
  601. "Using device %s for object "
  602. "collectives.", _world.pg_default_device[group]
  603. )
  604. return _world.pg_default_device[group]
  605. @_time_logger
  606. def _store_based_barrier(rank, store, group_name, rendezvous_count, timeout, logging_interval=timedelta(seconds=10)) -> None:
  607. """
  608. Store based barrier for synchronizing processes.
  609. Barrier based on store which is used for synchronizing processes after
  610. ``init_process_group`` or ``new_group``. Intended to be used only with
  611. those two methods and is not a generic alternative to ``barrier()``.
  612. """
  613. store_key = f"{STORE_BASED_BARRIER_PREFIX}:{group_name}"
  614. store.add(store_key, 1)
  615. logger.debug("Added key: %s to store for rank: %s", store_key, rank)
  616. # Now wait for all workers to check in with the store.
  617. world_size = rendezvous_count
  618. worker_count = store.add(store_key, 0)
  619. last_worker_key = f"{store_key}:last_worker"
  620. if worker_count == world_size:
  621. store.set(last_worker_key, "1")
  622. # adjust the timeout to be at least 10secs + 1sec per thousand ranks to reduce the odds of timeout
  623. # this value was empirically found while scale testing.
  624. logging_interval = max(logging_interval, timedelta(seconds=10 + world_size / 1000))
  625. start = time.time()
  626. while True:
  627. try:
  628. # This will throw an exception after the logging_interval in which we print out
  629. # the status of the group or time out officially, throwing runtime error
  630. store.wait([last_worker_key], logging_interval)
  631. break
  632. except RuntimeError as e:
  633. worker_count = store.add(store_key, 0)
  634. # Print status periodically to keep track.
  635. logger.debug(
  636. "Waiting in store based barrier to initialize process group for "
  637. "rank: %s, key: %s (world_size=%s, num_workers_joined=%s, timeout=%s error=%s)",
  638. rank, store_key, world_size, worker_count, timeout, e
  639. )
  640. if timedelta(seconds=(time.time() - start)) > timeout:
  641. raise DistStoreError( # noqa: B904
  642. "Timed out initializing process group in store based barrier on "
  643. f"rank {rank}, for key: {store_key} (world_size={world_size}, "
  644. f"num_workers_joined={worker_count}, timeout={timeout} error={e})"
  645. )
  646. logger.info(
  647. "Rank %s: Completed store-based barrier for key:%s with %s nodes.", rank, store_key, world_size
  648. )
  649. def _rank_not_in_group(group: Optional[ProcessGroup]) -> bool:
  650. """Check if the current process's rank is not in a given group."""
  651. if group is None:
  652. return False
  653. return group == GroupMember.NON_GROUP_MEMBER
  654. def _warn_not_in_group(op_name) -> None:
  655. global_rank = -1 if GroupMember.WORLD is None else GroupMember.WORLD.rank()
  656. warnings.warn(
  657. f"Running {op_name} on global rank {global_rank} which does not "
  658. "belong to the given group."
  659. )
  660. def get_group_rank(group: ProcessGroup, global_rank: int) -> int:
  661. """
  662. Translate a global rank into a group rank.
  663. ``global_rank`` must be part of ``group`` otherwise this raises RuntimeError.
  664. Args:
  665. group (ProcessGroup): ProcessGroup to find the relative rank.
  666. global_rank (int): Global rank to query.
  667. Returns:
  668. Group rank of ``global_rank`` relative to ``group``
  669. N.B. calling this function on the default process group returns identity
  670. """
  671. if group is GroupMember.WORLD:
  672. return global_rank
  673. if group not in _world.pg_group_ranks:
  674. raise ValueError(f"Group {group} is not registered, please create group with torch.distributed.new_group API")
  675. group_ranks = _world.pg_group_ranks[group]
  676. if global_rank not in group_ranks:
  677. raise ValueError(f"Global rank {global_rank} is not part of group {group}")
  678. return group_ranks[global_rank]
  679. def get_global_rank(group: ProcessGroup, group_rank: int) -> int:
  680. """
  681. Translate a group rank into a global rank.
  682. ``group_rank`` must be part of `group` otherwise this raises RuntimeError.
  683. Args:
  684. group (ProcessGroup): ProcessGroup to find the global rank from.
  685. group_rank (int): Group rank to query.
  686. Returns:
  687. Global rank of ``group_rank`` relative to ``group``
  688. N.B. calling this function on the default process group returns identity
  689. """
  690. if group is GroupMember.WORLD:
  691. return group_rank
  692. if group not in _world.pg_group_ranks:
  693. raise ValueError(f"Group {group} is not registered, please create group with torch.distributed.new_group API")
  694. for rank, grp_rank in _world.pg_group_ranks[group].items():
  695. if grp_rank == group_rank:
  696. return rank
  697. raise ValueError(f"Group rank {group_rank} is not part of group {group}")
  698. # TODO: remove this once the ecosystem moves away from it.
  699. @deprecated(
  700. "`torch.distributed.distributed_c10d._get_global_rank` is deprecated, "
  701. "please use `torch.distributed.distributed_c10d.get_global_rank` instead",
  702. category=FutureWarning,
  703. )
  704. def _get_global_rank(group, rank) -> int:
  705. """Use get_global_rank as this method is deprecated."""
  706. return get_global_rank(group, rank)
  707. def get_process_group_ranks(group: ProcessGroup) -> List[int]:
  708. """
  709. Get all ranks associated with ``group``.
  710. Args:
  711. group (ProcessGroup): ProcessGroup to get all ranks from.
  712. Returns:
  713. List of global ranks ordered by group rank.
  714. """
  715. return list(_world.pg_group_ranks[group].keys())
  716. def _get_group_size(group) -> int:
  717. """Get a given group's world size."""
  718. if group is GroupMember.WORLD or group is None:
  719. default_pg = _get_default_group()
  720. return default_pg.size()
  721. return group.size()
  722. def _get_group_size_by_name(group_name: str) -> int:
  723. group = _resolve_process_group(group_name)
  724. return group.size()
  725. def _resolve_group_name_by_ranks_and_tag(ranks: List[int], tag: str) -> str:
  726. # TODO(yifu): remove this function once ranks + tag is not a supported
  727. # identifier for process group for functional collectives.
  728. group = _find_pg_by_ranks_and_tag(tag, ranks)
  729. if group is None:
  730. raise ValueError("")
  731. return group.group_name
  732. def _check_single_tensor(param, param_name) -> None:
  733. """Check that the parameter ``param_name`` is a single tensor."""
  734. if not isinstance(param, torch.Tensor):
  735. raise TypeError(
  736. f"""Invalid function argument. Expected parameter `{param_name}` of type torch.Tensor
  737. but got {type(param)} instead."""
  738. )
  739. def _check_tensor_list(param, param_name) -> None:
  740. """Check that the parameter ``param_name`` is a list of tensors."""
  741. if not isinstance(param, list):
  742. raise TypeError(
  743. f"""Invalid function argument. Expected parameter `{param_name}` of type List[torch.Tensor]
  744. but got {type(param)} instead."""
  745. )
  746. elif not all(isinstance(p, torch.Tensor) for p in param):
  747. raise TypeError(
  748. f"""Invalid function argument. Expected parameter `{param_name}` of type List[torch.Tensor]
  749. but got {type(param)} with elements of type {[type(p) for p in param]}."""
  750. )
  751. def _as_iterable(obj) -> collections.abc.Iterable:
  752. return obj if isinstance(obj, list) else (obj,)
  753. def _ensure_all_tensors_same_dtype(*tensors) -> None:
  754. last_dtype = None
  755. for tensor in itertools.chain.from_iterable(map(_as_iterable, tensors)):
  756. tensor_dtype = tensor.dtype
  757. # Mixing complex and its element type is allowed
  758. if tensor_dtype.is_complex:
  759. tensor_dtype = torch.float32 if tensor_dtype == torch.complex64 else torch.complex128
  760. if last_dtype is None:
  761. last_dtype = tensor_dtype
  762. else:
  763. if last_dtype != tensor_dtype:
  764. raise ValueError(
  765. "Invalid usage of tensors with different dtypes"
  766. f"Found {last_dtype} and {tensor.dtype}"
  767. )
  768. def _check_op(op) -> None:
  769. """Check that the ``op`` is either isend or irecv."""
  770. if op not in [isend, irecv]:
  771. raise ValueError(
  772. "Invalid ``op``. Expected ``op`` "
  773. "to be of type ``torch.distributed.isend`` or "
  774. "``torch.distributed.irecv``."
  775. )
  776. def _check_p2p_op_list(p2p_op_list) -> None:
  777. """
  778. Check that the ``p2p_op_list`` is a list of P2POp instances.
  779. Also, check that all ops use the same group.
  780. """
  781. if not isinstance(p2p_op_list, list) or not all(
  782. isinstance(p2p_op, P2POp) for p2p_op in p2p_op_list
  783. ):
  784. raise ValueError(
  785. "Invalid ``p2p_op_list``. Each op is expected to "
  786. "to be of type ``torch.distributed.P2POp``."
  787. )
  788. group = p2p_op_list[0].group
  789. if not all(group == p2p_op.group for p2p_op in p2p_op_list):
  790. raise ValueError("All ops need to use the same group.")
  791. def is_mpi_available() -> bool:
  792. """Check if the MPI backend is available."""
  793. return _MPI_AVAILABLE
  794. def is_nccl_available() -> bool:
  795. """Check if the NCCL backend is available."""
  796. return _NCCL_AVAILABLE
  797. def is_gloo_available() -> bool:
  798. """Check if the Gloo backend is available."""
  799. return _GLOO_AVAILABLE
  800. def is_ucc_available() -> bool:
  801. """Check if the UCC backend is available."""
  802. return _UCC_AVAILABLE
  803. def is_backend_available(backend: str) -> bool:
  804. """
  805. Check backend availability.
  806. Checks if the given backend is available and supports the built-in backends or
  807. third-party backends through function ``Backend.register_backend``.
  808. Args:
  809. backend (str): Backend name.
  810. Returns:
  811. bool: Returns true if the backend is available otherwise false.
  812. """
  813. # If the backend has an ``is_backend_available`` function, return the result of that function directly
  814. available_func = getattr(torch.distributed, f"is_{backend.lower()}_available", None)
  815. if available_func:
  816. return available_func()
  817. return backend.lower() in Backend.backend_list
  818. def is_initialized() -> bool:
  819. """Check if the default process group has been initialized."""
  820. return GroupMember.WORLD is not None
  821. def is_torchelastic_launched() -> bool:
  822. """
  823. Check whether this process was launched with ``torch.distributed.elastic`` (aka torchelastic).
  824. The existence of ``TORCHELASTIC_RUN_ID`` environment
  825. variable is used as a proxy to determine whether the current process
  826. was launched with torchelastic. This is a reasonable proxy since
  827. ``TORCHELASTIC_RUN_ID`` maps to the rendezvous id which is always a
  828. non-null value indicating the job id for peer discovery purposes..
  829. """
  830. return os.getenv("TORCHELASTIC_RUN_ID") is not None
  831. def _is_barrier_after_init() -> int:
  832. # Environment variable to control whether process group should perform a
  833. # barrier after its init. Default value is 0, i.e. no barrier. If you
  834. # experience issue with this setting, you may set
  835. # `TORCH_DIST_INIT_BARRIER=1` to add the barrier.
  836. return int(os.getenv("TORCH_DIST_INIT_BARRIER", "0"))
  837. def _get_default_group() -> ProcessGroup:
  838. """Get the default process group created by init_process_group."""
  839. if not is_initialized():
  840. raise ValueError(
  841. "Default process group has not been initialized, "
  842. "please make sure to call init_process_group."
  843. )
  844. if TYPE_CHECKING:
  845. return not_none(GroupMember.WORLD)
  846. else:
  847. return GroupMember.WORLD
  848. def _get_default_store() -> Store:
  849. """Get the default store created by init_process_group."""
  850. if not is_initialized():
  851. raise ValueError(
  852. "Default process group has not been initialized, "
  853. "please make sure to call init_process_group."
  854. )
  855. default_pg = _get_default_group()
  856. _, default_store = _world.pg_map[default_pg]
  857. return default_store
  858. def _update_default_pg(pg) -> None:
  859. _world.default_pg = pg
  860. rank = pg.rank() if pg is not None and pg != GroupMember.NON_GROUP_MEMBER else -1
  861. torch._C._distributed_c10d._set_global_rank(rank)
  862. def get_backend_config(group: Optional[ProcessGroup] = None) -> str:
  863. """
  864. Return the backend configuration of the given process group.
  865. Args:
  866. group (ProcessGroup, optional): The process group to work on. The
  867. default is the general main process group. If another specific group
  868. is specified, the calling process must be part of :attr:`group`.
  869. Returns:
  870. The backend configuration of the given process group as a lower case string.
  871. """
  872. if group is None:
  873. pg = _get_default_group()
  874. else:
  875. pg = group
  876. if _rank_not_in_group(pg):
  877. raise ValueError("Invalid process group specified")
  878. backend_config = _world.pg_backend_config.get(pg)
  879. return str(not_none(backend_config))
  880. def get_backend(group: Optional[ProcessGroup] = None) -> Backend:
  881. """
  882. Return the backend of the given process group.
  883. Args:
  884. group (ProcessGroup, optional): The process group to work on. The
  885. default is the general main process group. If another specific group
  886. is specified, the calling process must be part of :attr:`group`.
  887. Returns:
  888. The backend of the given process group as a lower case string.
  889. """
  890. if group is None:
  891. pg = _get_default_group()
  892. else:
  893. pg = group
  894. if _rank_not_in_group(pg):
  895. raise ValueError("Invalid process group specified")
  896. pg_store = _world.pg_map[pg] if pg in _world.pg_map else None
  897. return Backend(not_none(pg_store)[0])
  898. def _get_process_group_uid(pg: ProcessGroup) -> int:
  899. backend = None
  900. try:
  901. backend = pg._get_backend(torch.device("cuda"))
  902. except RuntimeError:
  903. pass
  904. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  905. return backend.uid
  906. return -1
  907. def _get_pg_config(group: Optional[ProcessGroup] = None) -> Dict[str, Any]:
  908. """
  909. Return the pg configuration of the given process group.
  910. """
  911. if group is None:
  912. pg = _get_default_group()
  913. else:
  914. pg = group
  915. return {
  916. "pg_name": _get_process_group_name(pg),
  917. "pg_desc": pg.group_desc,
  918. "backend_config": get_backend_config(pg),
  919. "pg_size": _get_group_size(pg),
  920. "ranks": get_process_group_ranks(pg),
  921. }
  922. def _get_all_pg_configs() -> List[Dict[str, Any]]:
  923. """
  924. Return the pg configuration of all the process groups.
  925. """
  926. config_info: List[Dict[str, Any]] = []
  927. for pg in _world.pg_map.keys():
  928. config_info.append(_get_pg_config(pg))
  929. return config_info
  930. def get_pg_count() -> int:
  931. """
  932. Return the number of process groups.
  933. """
  934. return _world.group_count
  935. def get_node_local_rank(fallback_rank: Optional[int] = None) -> int:
  936. """
  937. Return the local rank of the current process relative to the node.
  938. Semantically, this is a useful concept for mapping processes to devices.
  939. For example, on a node with 8 accelerator you could use the node local rank to decide
  940. which accelerator device to bind the process to.
  941. In practice, the actual assignment of node local ranks is handled by the process launcher outside of pytorch,
  942. and communicated via the `LOCAL_RANK` environment variable.
  943. Torchrun will automatically populate `LOCAL_RANK`, but other launchers may not. If `LOCAL_RANK` is unspecified,
  944. this API will fall back to the provided kwarg 'fallback_rank' if specified, otherwise it will raise an error. The
  945. intent is to allow writing an application that runs either in single or multi device contexts without error.
  946. """
  947. if "LOCAL_RANK" in os.environ:
  948. return int(os.environ["LOCAL_RANK"])
  949. elif fallback_rank is not None:
  950. return int(fallback_rank)
  951. raise RuntimeError(
  952. "LOCAL_RANK is not in the environment. Consider passing fallback_rank to allow `get_node_local_rank` to work, "
  953. "assuming you are not running in a multi-device context and want the code to run locally instead."
  954. )
  955. def _set_pg_timeout(timeout: timedelta, group: Optional[ProcessGroup] = None) -> None:
  956. """
  957. Set the timeout for the given process group when users want to use a different timeout instead of
  958. default values.
  959. Args:
  960. timeout (timedelta): Timeout for operations executed against the process group which
  961. users want to set. Default value is 10 minutes for NCCL and 30 minutes for other backends.
  962. This is the duration after which collectives will be aborted asynchronously and the process will crash.
  963. This is done since CUDA execution is async and it is no longer safe to continue executing user code since
  964. failed async NCCL operations might result in subsequent CUDA operations running on corrupted data.
  965. When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.
  966. group (ProcessGroup, optional): The process group to work on. The
  967. default is the general main process group. If another specific group
  968. is specified, the calling process must be part of :attr:`group`.
  969. Returns:
  970. None
  971. """
  972. if group is None:
  973. group = _get_default_group()
  974. if _rank_not_in_group(group):
  975. raise ValueError("Invalid process group specified")
  976. assert isinstance(group, ProcessGroup)
  977. devices = group._device_types
  978. backends = set()
  979. if torch.device("cpu") in devices and is_gloo_available():
  980. backend = group._get_backend(torch.device("cpu"))
  981. if isinstance(backend, ProcessGroupGloo):
  982. backends.add(backend)
  983. if torch.device("cuda") in devices:
  984. backend = group._get_backend(torch.device("cuda"))
  985. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  986. backends.add(backend) # type: ignore[arg-type]
  987. elif is_gloo_available() and isinstance(backend, ProcessGroupGloo):
  988. backends.add(backend) # type: ignore[arg-type]
  989. if len(backends) == 0:
  990. warnings.warn("Set timeout is now only supported for either nccl or gloo.")
  991. for backend in backends:
  992. backend._set_default_timeout(timeout)
  993. @_exception_logger
  994. @_time_logger
  995. def init_process_group(
  996. backend: Optional[str] = None,
  997. init_method: Optional[str] = None,
  998. timeout: Optional[timedelta] = None,
  999. world_size: int = -1,
  1000. rank: int = -1,
  1001. store: Optional[Store] = None,
  1002. group_name: str = "",
  1003. pg_options: Optional[Any] = None,
  1004. device_id: Optional[torch.device] = None,
  1005. ) -> None:
  1006. """
  1007. Initialize the default distributed process group.
  1008. This will also initialize the distributed package.
  1009. There are 2 main ways to initialize a process group:
  1010. 1. Specify ``store``, ``rank``, and ``world_size`` explicitly.
  1011. 2. Specify ``init_method`` (a URL string) which indicates where/how
  1012. to discover peers. Optionally specify ``rank`` and ``world_size``,
  1013. or encode all required parameters in the URL and omit them.
  1014. If neither is specified, ``init_method`` is assumed to be "env://".
  1015. Args:
  1016. backend (str or Backend, optional): The backend to use. Depending on
  1017. build-time configurations, valid values include ``mpi``, ``gloo``,
  1018. ``nccl``, and ``ucc``. If the backend is not provided, then both a ``gloo``
  1019. and ``nccl`` backend will be created, see notes below for how multiple
  1020. backends are managed. This field can be given as a lowercase string
  1021. (e.g., ``"gloo"``), which can also be accessed via
  1022. :class:`Backend` attributes (e.g., ``Backend.GLOO``). If using
  1023. multiple processes per machine with ``nccl`` backend, each process
  1024. must have exclusive access to every GPU it uses, as sharing GPUs
  1025. between processes can result in deadlocks. ``ucc`` backend is
  1026. experimental.
  1027. init_method (str, optional): URL specifying how to initialize the
  1028. process group. Default is "env://" if no
  1029. ``init_method`` or ``store`` is specified.
  1030. Mutually exclusive with ``store``.
  1031. world_size (int, optional): Number of processes participating in
  1032. the job. Required if ``store`` is specified.
  1033. rank (int, optional): Rank of the current process (it should be a
  1034. number between 0 and ``world_size``-1).
  1035. Required if ``store`` is specified.
  1036. store(Store, optional): Key/value store accessible to all workers, used
  1037. to exchange connection/address information.
  1038. Mutually exclusive with ``init_method``.
  1039. timeout (timedelta, optional): Timeout for operations executed against
  1040. the process group. Default value is 10 minutes for NCCL and 30 minutes for other backends.
  1041. This is the duration after which collectives will be aborted asynchronously and the process will crash.
  1042. This is done since CUDA execution is async and it is no longer safe to continue executing user code since
  1043. failed async NCCL operations might result in subsequent CUDA operations running on corrupted data.
  1044. When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.
  1045. group_name (str, optional, deprecated): Group name. This argument is ignored
  1046. pg_options (ProcessGroupOptions, optional): process group options
  1047. specifying what additional options need to be passed in during
  1048. the construction of specific process groups. As of now, the only
  1049. options we support is ``ProcessGroupNCCL.Options`` for the ``nccl``
  1050. backend, ``is_high_priority_stream`` can be specified so that
  1051. the nccl backend can pick up high priority cuda streams when
  1052. there're compute kernels waiting.
  1053. device_id (torch.device, optional): a single, specific device
  1054. to "bind" this process to, allowing for backend-specific
  1055. optimizations. Currently this has two effects, only under
  1056. NCCL: the communicator is immediately formed (calling
  1057. ``ncclCommInit*`` immediately rather than the normal lazy
  1058. call) and sub-groups will use ``ncclCommSplit`` when
  1059. possible to avoid unnecessary overhead of group creation. If you
  1060. want to know NCCL initialization error early, you can also use this
  1061. field.
  1062. .. note:: To enable ``backend == Backend.MPI``, PyTorch needs to be built from source
  1063. on a system that supports MPI.
  1064. .. note:: Support for multiple backends is experimental. Currently when no backend is
  1065. specified, both ``gloo`` and ``nccl`` backends will be created. The ``gloo`` backend
  1066. will be used for collectives with CPU tensors and the ``nccl`` backend will be used
  1067. for collectives with CUDA tensors. A custom backend can be specified by passing in
  1068. a string with format "<device_type>:<backend_name>,<device_type>:<backend_name>", e.g.
  1069. "cpu:gloo,cuda:custom_backend".
  1070. """
  1071. global _world
  1072. global _backend
  1073. global _default_pg_init_method
  1074. if GroupMember.WORLD is not None:
  1075. raise ValueError("trying to initialize the default process group twice!")
  1076. set_pytorch_distributed_envs_from_justknobs()
  1077. # Depending on the import order, some trace_rules functions may be evaluated
  1078. # during the import phase. In such a case, these functions may not correctly
  1079. # add the distributed related rules due to import circular dependency.
  1080. # We need to clear the lru_cache during the runtime to ensure the correctness
  1081. # of these trace_rules.
  1082. #
  1083. # Since this API must be called before all distributed code being compiled,
  1084. # clearing the cache here should be safe.
  1085. if "torch._dynamo" in sys.modules:
  1086. torch._dynamo.trace_rules.clear_lru_cache()
  1087. assert (store is None) or (
  1088. init_method is None
  1089. ), "Cannot specify both init_method and store."
  1090. if store is not None:
  1091. assert world_size > 0, "world_size must be positive if using store"
  1092. assert rank >= 0, "rank must be non-negative if using store"
  1093. elif init_method is None:
  1094. init_method = "env://"
  1095. if backend:
  1096. backend = Backend(backend)
  1097. else:
  1098. backend = Backend("undefined")
  1099. if timeout is None:
  1100. timeout = _get_default_timeout(backend)
  1101. _check_valid_timeout(timeout)
  1102. """
  1103. Group name is not visible to users unless they access
  1104. internals of c10d. This means we can ignore the value
  1105. they provide as it not exposed in a public way.
  1106. """
  1107. group_name = _process_group_name([], use_hashed_name=False)
  1108. if backend == Backend.MPI:
  1109. if world_size != -1 or rank != -1:
  1110. warnings.warn(
  1111. f"For MPI backend, world_size ({world_size}) and rank ({rank}) "
  1112. "are ignored since they are assigned by the "
  1113. "MPI runtime."
  1114. )
  1115. default_pg, _ = _new_process_group_helper(
  1116. -1, -1, [], backend, None, group_name, timeout=timeout, group_desc="default_pg"
  1117. )
  1118. _update_default_pg(default_pg)
  1119. else:
  1120. # backward compatible API
  1121. if store is None:
  1122. rendezvous_iterator = rendezvous(
  1123. not_none(init_method), rank, world_size, timeout=timeout
  1124. )
  1125. store, rank, world_size = next(rendezvous_iterator)
  1126. store.set_timeout(timeout)
  1127. # Use a PrefixStore to avoid accidental overrides of keys used by
  1128. # different systems (e.g. RPC) in case the store is multi-tenant.
  1129. store = PrefixStore("default_pg", store)
  1130. default_pg, _ = _new_process_group_helper(
  1131. world_size,
  1132. rank,
  1133. [],
  1134. backend,
  1135. store,
  1136. group_name,
  1137. pg_options=pg_options,
  1138. timeout=timeout,
  1139. device_id=device_id,
  1140. group_desc="default_pg"
  1141. )
  1142. _update_default_pg(default_pg)
  1143. _world.pg_group_ranks[GroupMember.WORLD] = {i: i for i in range(GroupMember.WORLD.size())} # type: ignore[attr-defined, index]
  1144. _backend = _world.pg_map[not_none(GroupMember.WORLD)][0]
  1145. _default_pg_init_method = init_method
  1146. old_hook = sys.excepthook
  1147. excepthook_prefix = f"[rank{get_rank()}]"
  1148. def _distributed_excepthook(*args):
  1149. old_stderr = sys.stderr
  1150. sys.stderr = buf = io.StringIO()
  1151. try:
  1152. old_hook(*args)
  1153. finally:
  1154. sys.stderr = old_stderr
  1155. msg = buf.getvalue()
  1156. msg = "\n".join(f"{excepthook_prefix}: {s}" if s != "" else "" for s in msg.split("\n"))
  1157. sys.stderr.write(msg)
  1158. sys.stderr.flush()
  1159. sys.excepthook = _distributed_excepthook
  1160. if _is_barrier_after_init() == 1:
  1161. # barrier at the end to ensure that once we return from this method, all
  1162. # process groups including global variables (if any) are updated
  1163. # correctly on all ranks.
  1164. # Update 04/2023: for large-scale runs, this barrier (esp. store-based
  1165. # barrier) may be costly and/or unscalable. Also, in a lot of cases,
  1166. # these barriers may be unnecessary, as proven by a green CI after
  1167. # removal. An environment variable `TORCH_DIST_INIT_BARRIER` has been
  1168. # added which enables this barrier only when set to 1.
  1169. logger.debug(
  1170. "Performing barrier after ProcessGroup initialization since "
  1171. "TORCH_DIST_INIT_BARRIER = 1"
  1172. )
  1173. if backend == Backend.MPI:
  1174. # MPI backend doesn't use store.
  1175. barrier()
  1176. else:
  1177. # Use store based barrier here since barrier() used a bunch of
  1178. # default devices and messes up NCCL internal state.
  1179. _store_based_barrier(rank, store, group_name, world_size, timeout)
  1180. def _get_split_source(pg):
  1181. split_from = None
  1182. if pg.bound_device_id:
  1183. split_from = pg._get_backend(pg.bound_device_id)
  1184. elif pg is _world.default_pg:
  1185. try:
  1186. split_from = pg._get_backend(torch.device("cuda"))
  1187. except RuntimeError:
  1188. # no cuda device associated with this backend
  1189. pass
  1190. if not split_from or not split_from.supports_splitting:
  1191. return None
  1192. # If necessary, find a backend to split from by peeling process
  1193. # group wrappers from our potentially wrapped process group.
  1194. while _GLOO_AVAILABLE and isinstance(split_from, _ProcessGroupWrapper):
  1195. split_from = split_from.wrapped_pg
  1196. return split_from
  1197. def _shutdown_backend(pg):
  1198. """
  1199. Try to shut down the backend of a process group.
  1200. Currently, only ProcessGroupNCCL backend is supported.
  1201. No op for other backends.
  1202. """
  1203. backend = None
  1204. try:
  1205. backend = pg._get_backend(torch.device("cuda"))
  1206. except RuntimeError:
  1207. pass
  1208. if is_nccl_available() and isinstance(backend, (ProcessGroupNCCL, ProcessGroupCudaP2P)):
  1209. # explictly call shutdown to ensure that NCCL resources are released
  1210. backend._shutdown()
  1211. def _new_process_group_helper(
  1212. group_size,
  1213. group_rank,
  1214. global_ranks_in_group,
  1215. backend,
  1216. store,
  1217. group_name,
  1218. pg_options=None,
  1219. timeout=None,
  1220. pg_tag=None,
  1221. device_id=None,
  1222. group_desc=None,
  1223. ):
  1224. """
  1225. Create a new distributed process group.
  1226. This function must be called by ALL processes in the global group, even if
  1227. the calling process is not part of the newly created group. In that case,
  1228. this function returns GroupMember.NON_GROUP_MEMBER.
  1229. This function is called with ``global_ranks_in_group == []`` for the default group.
  1230. """
  1231. global _world
  1232. if group_name in _world.pg_names.values():
  1233. raise ValueError(
  1234. "The specified group name has already been "
  1235. "created, please use a different group name"
  1236. )
  1237. if device_id is not None and (device_id.index is None or device_id.type != 'cuda'):
  1238. raise ValueError("init_process_group device_id parameter must be a cuda device with an "
  1239. "id, e.g. cuda:0, not just cuda or cpu")
  1240. # Note: _new_process_group_helper is only called from init_process_group, which always provides a timeout value
  1241. _check_valid_timeout(timeout)
  1242. if pg_tag not in [None, ""]:
  1243. # creating with the same tag and rank set results in the same underlying PG
  1244. existing_group = _find_pg_by_ranks_and_tag(pg_tag, global_ranks_in_group)
  1245. if existing_group:
  1246. _, prefix_store = _world.pg_map[existing_group]
  1247. return existing_group, prefix_store
  1248. group_desc = "undefined" if group_desc is None else group_desc
  1249. # The list of group ranks is empty if we're creating the default group.
  1250. is_default_group = len(global_ranks_in_group) == 0
  1251. # nccl and potentially other backends allow creation of
  1252. # communicators based on pre-existing ones, which can save
  1253. # initialization time. Due to lazy initialization of
  1254. # communicators in some backends, we have to be careful and only
  1255. # split when we *know* the backends already are connected _on all
  1256. # ranks_. We can only know this if the group we are making is the
  1257. # entire world or if we have bound a device id to the world (which
  1258. # causes early connection initialization).
  1259. if (is_initialized() and
  1260. (len(global_ranks_in_group) == _get_default_group().size() or _get_default_group().bound_device_id)):
  1261. split_from = _get_split_source(_get_default_group())
  1262. else:
  1263. split_from = None
  1264. # If this is a subgroup (which means group_ranks is specified),
  1265. # we check if the current process is a member of the new group.
  1266. if not is_default_group:
  1267. global_rank = _get_default_group().rank()
  1268. if global_rank not in global_ranks_in_group:
  1269. # If we are using `ncclCommSplit` (or similar split from
  1270. # other APIs) to create the communicator, we will need to
  1271. # call `ncclCommSplit` on *all* ranks in this new group's
  1272. # parent group, even those not in the new group. This is
  1273. # a requirement of the NCCL API as otherwise we would get
  1274. # out of sync.
  1275. if split_from:
  1276. split_from.perform_nocolor_split(_get_default_group().bound_device_id)
  1277. return GroupMember.NON_GROUP_MEMBER, None
  1278. prefix_store = PrefixStore(f"{group_name}/", store)
  1279. base_pg_options = ProcessGroup.Options(backend=str(backend))
  1280. base_pg_options._timeout = timeout
  1281. pg: ProcessGroup = ProcessGroup(prefix_store, group_rank, group_size, base_pg_options)
  1282. if device_id:
  1283. pg.bound_device_id = device_id
  1284. backend_config = BackendConfig(backend)
  1285. backend_class: torch._C._distributed_c10d.Backend
  1286. for device, backend_str in backend_config.get_device_backend_map().items():
  1287. # Use the group name as prefix in the default store, such that
  1288. # a single store can be reused by multiple groups.
  1289. backend_prefix_store = PrefixStore(f"{device}/", prefix_store)
  1290. if backend_str == Backend.MPI:
  1291. if not is_mpi_available():
  1292. raise RuntimeError(
  1293. "Distributed package doesn't have MPI built in."
  1294. " MPI is only included if you build PyTorch from"
  1295. " source on a host that has MPI installed."
  1296. )
  1297. backend_class = ProcessGroupMPI.create(global_ranks_in_group)
  1298. backend_type = ProcessGroup.BackendType.MPI
  1299. if not backend_class:
  1300. return GroupMember.NON_GROUP_MEMBER, None
  1301. # create new process group with accurate rank and size
  1302. if pg.rank() == -1 and pg.size() == -1:
  1303. pg = ProcessGroup(backend_prefix_store, backend_class.rank(), backend_class.size(), base_pg_options)
  1304. elif backend_str == Backend.GLOO:
  1305. # TODO: remove this check after lazy initialization is supported
  1306. # if pg_options is not None:
  1307. # raise RuntimeError("GLOO options not supported")
  1308. backend_class = ProcessGroupGloo(backend_prefix_store, group_rank, group_size, timeout=timeout)
  1309. backend_type = ProcessGroup.BackendType.GLOO
  1310. elif backend_str == Backend.NCCL:
  1311. if not is_nccl_available():
  1312. raise RuntimeError("Distributed package doesn't have NCCL built in")
  1313. if pg_options is not None:
  1314. assert isinstance(
  1315. pg_options, ProcessGroupNCCL.Options
  1316. ), "Expected pg_options argument to be of type ProcessGroupNCCL.Options"
  1317. if pg_options._timeout != timeout:
  1318. warnings.warn(
  1319. "pg_options._timeout was specified, "
  1320. "but timeout kwarg has a default value that will always override it. "
  1321. )
  1322. else:
  1323. # default pg_options for NCCL
  1324. pg_options = ProcessGroupNCCL.Options()
  1325. pg_options.is_high_priority_stream = False
  1326. pg_options._timeout = timeout
  1327. if split_from:
  1328. pg_options.split_from = split_from
  1329. pg_options.split_color = _process_group_color(global_ranks_in_group)
  1330. pg_options.global_ranks_in_group = global_ranks_in_group
  1331. pg_options.group_name = group_name
  1332. backend_class = ProcessGroupNCCL(
  1333. backend_prefix_store, group_rank, group_size, pg_options)
  1334. backend_type = ProcessGroup.BackendType.NCCL
  1335. elif backend_str == Backend.UCC and is_ucc_available():
  1336. # TODO: once UCC plugin is fully deprecated, remove
  1337. # is_ucc_available() from above elif-condition and raise
  1338. # RuntimeError if is_ucc_available() returns false.
  1339. backend_class = ProcessGroupUCC(backend_prefix_store, group_rank, group_size, timeout=timeout)
  1340. backend_type = ProcessGroup.BackendType.UCC
  1341. else:
  1342. assert backend_str.upper() in Backend._plugins, (
  1343. f"Unknown c10d backend type {backend_str.upper()}"
  1344. )
  1345. backend_plugin = Backend._plugins[backend_str.upper()]
  1346. creator_fn = backend_plugin.creator_fn
  1347. extended_api = backend_plugin.extended_api
  1348. backend_type = ProcessGroup.BackendType.CUSTOM
  1349. if not extended_api:
  1350. backend_class = creator_fn(backend_prefix_store, group_rank, group_size, timeout)
  1351. else:
  1352. dist_backend_opts = _DistributedBackendOptions()
  1353. dist_backend_opts.store = backend_prefix_store
  1354. dist_backend_opts.group_rank = group_rank
  1355. dist_backend_opts.group_size = group_size
  1356. dist_backend_opts.timeout = timeout
  1357. dist_backend_opts.group_id = group_name
  1358. dist_backend_opts.global_ranks_in_group = global_ranks_in_group
  1359. backend_class = creator_fn(dist_backend_opts, pg_options)
  1360. # Set sequence numbers for gloo and nccl backends.
  1361. if backend_str == Backend.GLOO:
  1362. assert isinstance(backend_class, ProcessGroupGloo)
  1363. backend_class._set_sequence_number_for_group()
  1364. elif backend_str == Backend.NCCL:
  1365. assert isinstance(backend_class, ProcessGroupNCCL)
  1366. backend_class._set_sequence_number_for_group()
  1367. # If the type is a subclass of ProcessGroup then return this process group immediately
  1368. # TODO: This defaults to the old behavior for PythonProcessGroups which overwrites the
  1369. # ProcessGroup instance
  1370. if issubclass(type(backend_class), ProcessGroup):
  1371. pg = backend_class # type: ignore[assignment]
  1372. break
  1373. # Process group wrapper initialization for supported PGs when TORCH_DISTRIBUTED_DEBUG is set
  1374. if backend_str in [Backend.GLOO, Backend.NCCL, Backend.UCC] or backend_str.upper() in Backend._plugins:
  1375. # In debug mode and if GLOO is available, wrap in a wrapper PG that
  1376. # enables enhanced collective checking for debuggability.
  1377. if get_debug_level() == DebugLevel.DETAIL:
  1378. if not _GLOO_AVAILABLE:
  1379. logger.info(
  1380. """TORCH_DISTRIBUTED_DEBUG was set to DETAIL, but
  1381. GLOO is not available. Build with Gloo to
  1382. create a wrapper process group in debug mode
  1383. to aid collective desynchronization debugging."""
  1384. )
  1385. else:
  1386. backend_class = _create_process_group_wrapper(
  1387. wrapped_pg=backend_class,
  1388. store_prefix=group_name,
  1389. store=backend_prefix_store,
  1390. rank=group_rank,
  1391. world_size=group_size,
  1392. timeout=timeout,
  1393. )
  1394. # register only a single backend when all get_device_backend_map values are the same
  1395. if len(set(backend_config.get_device_backend_map().values())) == 1:
  1396. for device in backend_config.get_device_backend_map().keys():
  1397. pg._register_backend(torch.device(device), backend_type, backend_class)
  1398. # break out of outer loop to not create any more backends
  1399. break
  1400. pg._register_backend(torch.device(device), backend_type, backend_class)
  1401. # set group_name and group_dsec to backend
  1402. assert group_name is not None
  1403. assert group_desc is not None
  1404. pg._set_group_name(group_name)
  1405. pg._set_group_desc(group_desc)
  1406. if device_id and pg._get_backend(device_id).supports_splitting:
  1407. eager_backend = pg._get_backend(device_id)
  1408. eager_backend.eager_connect_single_device(device_id)
  1409. # update global state
  1410. _world.pg_map[pg] = (backend, prefix_store)
  1411. _world.pg_names[pg] = group_name
  1412. _register_process_group(group_name, pg)
  1413. _world.pg_backend_config[pg] = str(backend_config)
  1414. # "" is the default tag for user PGs
  1415. if pg_tag in [None, ""]:
  1416. pg_tag = f"ptd:{group_name}"
  1417. _world.tags_to_pg.setdefault("", []).append(pg)
  1418. else:
  1419. pg_tag = f"user:{pg_tag}"
  1420. _world.tags_to_pg.setdefault(pg_tag, []).append(pg)
  1421. _world.pg_to_tag[pg] = pg_tag
  1422. return pg, prefix_store
  1423. def destroy_process_group(group: Optional[ProcessGroup] = None):
  1424. """
  1425. Destroy a given process group, and deinitialize the distributed package.
  1426. Args:
  1427. group (ProcessGroup, optional): The process group to be destroyed, if
  1428. group.WORLD is given, all process
  1429. groups including the default one will
  1430. be destroyed.
  1431. """
  1432. global _world
  1433. if group == GroupMember.NON_GROUP_MEMBER:
  1434. return
  1435. if group is None:
  1436. pg = GroupMember.WORLD
  1437. else:
  1438. pg = group
  1439. assert pg is not None
  1440. if _world.pg_map.get(pg, None) is None:
  1441. raise ValueError("Invalid process group specified")
  1442. # When users register Python onCompletion hooks, those hooks will run on a
  1443. # different thread than the main thread. Today, the ProcessGroup dtor does
  1444. # wait for that thread. However, the dtor might finish after the Python
  1445. # Interpreter exits. After that grabbing the GIL for the Python hook will crash.
  1446. # We can either revive the interpreter when running hooks or keep the main one
  1447. # alive until all works and hooks are done. The current implementation does the
  1448. # latter. Therefore, we explicitly call _wait_for_pending_works() here to wait
  1449. # for the pending hooks to finish.
  1450. if pg.name().lower() == "nccl" and pg._has_hooks():
  1451. pg._wait_for_pending_works()
  1452. if group is None or group == GroupMember.WORLD:
  1453. # shutdown all backends in the order of pg names. shutting down in order because
  1454. # ncclCommAbort() was a 'collective' call in some versions of NCCL.
  1455. for pg_to_shutdown in sorted(_world.pg_names, key=lambda x: _world.pg_names[x], reverse=True):
  1456. _shutdown_backend(pg_to_shutdown)
  1457. _update_default_pg(None)
  1458. _world.pg_map.clear()
  1459. _world.pg_names.clear()
  1460. _world.pg_group_ranks.clear()
  1461. _world.pg_backend_config.clear()
  1462. _world.pg_to_tag.clear()
  1463. _world.tags_to_pg.clear()
  1464. _world.pg_coalesce_state.clear()
  1465. _world.pg_default_device.clear()
  1466. _unregister_all_process_groups()
  1467. # when process group doesn't have an explicit name (only WORLD (default)
  1468. # process group can have an explicit name), we use global _world.group_count
  1469. # to generate the name. We need to reset the counter on destruction to
  1470. # allow consistent value to be generated when we re-create process
  1471. # groups after some trainers recover from failure
  1472. #
  1473. # We only reset this when WORLD is being destroyed because if this
  1474. # process group is in good state, we aren't dealing with failures.
  1475. _world.group_count = 0
  1476. else:
  1477. _shutdown_backend(pg)
  1478. del _world.pg_map[pg]
  1479. del _world.pg_names[pg]
  1480. del _world.pg_group_ranks[pg]
  1481. del _world.pg_backend_config[pg]
  1482. if pg in _world.pg_default_device:
  1483. del _world.pg_default_device[pg]
  1484. if pg in _world.pg_coalesce_state.keys():
  1485. warnings.warn(
  1486. "Some coalesced collectives haven't been launched when "
  1487. "ProcessGroup is destroyed. They will be cleaned."
  1488. )
  1489. del _world.pg_coalesce_state[pg]
  1490. tag = _world.pg_to_tag.get(pg)
  1491. del _world.pg_to_tag[pg]
  1492. if tag is not None:
  1493. try:
  1494. _world.tags_to_pg[tag].remove(pg)
  1495. if tag.startswith("ptd:"):
  1496. _world.tags_to_pg[""].remove(pg)
  1497. except Exception:
  1498. pass
  1499. _unregister_process_group(pg.group_name)
  1500. def get_rank(group: Optional[ProcessGroup] = None) -> int:
  1501. """
  1502. Return the rank of the current process in the provided ``group``, default otherwise.
  1503. Rank is a unique identifier assigned to each process within a distributed
  1504. process group. They are always consecutive integers ranging from 0 to
  1505. ``world_size``.
  1506. Args:
  1507. group (ProcessGroup, optional): The process group to work on. If None,
  1508. the default process group will be used.
  1509. Returns:
  1510. The rank of the process group
  1511. -1, if not part of the group
  1512. """
  1513. if _rank_not_in_group(group):
  1514. return -1
  1515. default_pg = _get_default_group()
  1516. if group is None or group is GroupMember.WORLD:
  1517. return default_pg.rank()
  1518. return get_group_rank(group, default_pg.rank())
  1519. def get_world_size(group: Optional[ProcessGroup] = None) -> int:
  1520. """
  1521. Return the number of processes in the current process group.
  1522. Args:
  1523. group (ProcessGroup, optional): The process group to work on. If None,
  1524. the default process group will be used.
  1525. Returns:
  1526. The world size of the process group
  1527. -1, if not part of the group
  1528. """
  1529. if _rank_not_in_group(group):
  1530. return -1
  1531. return _get_group_size(group)
  1532. def isend(tensor: torch.Tensor, dst: int, group: Optional[ProcessGroup] = None, tag: int = 0) -> Optional[Work]:
  1533. """
  1534. Send a tensor asynchronously.
  1535. .. warning::
  1536. Modifying ``tensor`` before the request completes causes undefined
  1537. behavior.
  1538. .. warning::
  1539. ``tag`` is not supported with the NCCL backend.
  1540. Args:
  1541. tensor (Tensor): Tensor to send.
  1542. dst (int): Destination rank on global process group (regardless of ``group`` argument)
  1543. group (ProcessGroup, optional): The process group to work on. If None,
  1544. the default process group will be used.
  1545. tag (int, optional): Tag to match send with remote recv
  1546. Returns:
  1547. A distributed request object.
  1548. None, if not part of the group
  1549. """
  1550. _check_single_tensor(tensor, "tensor")
  1551. if _rank_not_in_group(group):
  1552. _warn_not_in_group("isend")
  1553. return None
  1554. if tensor.is_complex():
  1555. tensor = torch.view_as_real(tensor)
  1556. if group is None or group is GroupMember.WORLD:
  1557. pg = _get_default_group()
  1558. else:
  1559. pg = group
  1560. dst = get_group_rank(pg, dst)
  1561. return pg.send([tensor], dst, tag)
  1562. def irecv(tensor: torch.Tensor, src: Optional[int] = None, group: Optional[ProcessGroup] = None, tag: int = 0) -> Optional[Work]:
  1563. """
  1564. Receives a tensor asynchronously.
  1565. .. warning::
  1566. ``tag`` is not supported with the NCCL backend.
  1567. Args:
  1568. tensor (Tensor): Tensor to fill with received data.
  1569. src (int, optional): Source rank on global process group (regardless of ``group`` argument).
  1570. Will receive from any process if unspecified.
  1571. group (ProcessGroup, optional): The process group to work on. If None,
  1572. the default process group will be used.
  1573. tag (int, optional): Tag to match recv with remote send
  1574. Returns:
  1575. A distributed request object.
  1576. None, if not part of the group
  1577. """
  1578. _check_single_tensor(tensor, "tensor")
  1579. if _rank_not_in_group(group):
  1580. _warn_not_in_group("irecv")
  1581. return None
  1582. if tensor.is_complex():
  1583. tensor = torch.view_as_real(tensor)
  1584. if group is None or group is GroupMember.WORLD:
  1585. pg = _get_default_group()
  1586. else:
  1587. pg = group
  1588. if src is None:
  1589. return pg.recv_anysource([tensor], tag)
  1590. else:
  1591. if pg is GroupMember.WORLD:
  1592. return pg.recv([tensor], src, tag)
  1593. else:
  1594. group_src_rank = get_group_rank(pg, src)
  1595. return pg.recv([tensor], group_src_rank, tag)
  1596. @_exception_logger
  1597. def send(tensor: torch.Tensor, dst: int, group: Optional[ProcessGroup] = None, tag: int = 0) -> None:
  1598. """
  1599. Send a tensor synchronously.
  1600. .. warning::
  1601. ``tag`` is not supported with the NCCL backend.
  1602. Args:
  1603. tensor (Tensor): Tensor to send.
  1604. dst (int): Destination rank on global process group (regardless of ``group`` argument).
  1605. Destination rank should not be the same as the rank of the current process.
  1606. group (ProcessGroup, optional): The process group to work on. If None,
  1607. the default process group will be used.
  1608. tag (int, optional): Tag to match send with remote recv
  1609. """
  1610. if get_rank() == dst:
  1611. raise ValueError(
  1612. "Invalid destination rank: destination rank should not be the same as "
  1613. "the rank of the current process."
  1614. )
  1615. _check_single_tensor(tensor, "tensor")
  1616. if _rank_not_in_group(group):
  1617. _warn_not_in_group("send")
  1618. return None
  1619. if tensor.is_complex():
  1620. tensor = torch.view_as_real(tensor)
  1621. if group is None or group is GroupMember.WORLD:
  1622. default_pg = _get_default_group()
  1623. default_pg.send([tensor], dst, tag).wait()
  1624. else:
  1625. group_dst_rank = get_group_rank(group, dst)
  1626. group.send([tensor], group_dst_rank, tag).wait()
  1627. @_exception_logger
  1628. def recv(tensor: torch.Tensor, src: Optional[int] = None, group: Optional[ProcessGroup] = None, tag: int = 0) -> int:
  1629. """
  1630. Receives a tensor synchronously.
  1631. .. warning::
  1632. ``tag`` is not supported with the NCCL backend.
  1633. Args:
  1634. tensor (Tensor): Tensor to fill with received data.
  1635. src (int, optional): Source rank on global process group (regardless of ``group`` argument).
  1636. Will receive from any process if unspecified.
  1637. group (ProcessGroup, optional): The process group to work on. If None,
  1638. the default process group will be used.
  1639. tag (int, optional): Tag to match recv with remote send
  1640. Returns:
  1641. Sender rank
  1642. -1, if not part of the group
  1643. """
  1644. _check_single_tensor(tensor, "tensor")
  1645. if _rank_not_in_group(group):
  1646. _warn_not_in_group("recv")
  1647. return -1
  1648. if tensor.is_complex():
  1649. tensor = torch.view_as_real(tensor)
  1650. if group is None:
  1651. pg = _get_default_group()
  1652. else:
  1653. pg = group
  1654. if src is None:
  1655. work = pg.recv_anysource([tensor], tag)
  1656. work.wait()
  1657. src_rank = work._source_rank()
  1658. if group is None or group is GroupMember.WORLD:
  1659. return src_rank
  1660. else:
  1661. return get_global_rank(pg, src_rank)
  1662. else:
  1663. if group is None or group is GroupMember.WORLD:
  1664. pg.recv([tensor], src, tag).wait()
  1665. else:
  1666. group_src_rank = get_group_rank(pg, src)
  1667. pg.recv([tensor], group_src_rank, tag).wait()
  1668. return src
  1669. class _IllegalWork(Work):
  1670. def __getattribute__(self, name):
  1671. if name in ["is_success", "exception", "wait", "source_rank", "_source_rank", "result", "synchronize"]:
  1672. raise ValueError(f"Illegal to call {name} on IllegalWork object")
  1673. class _CoalescingManager:
  1674. def __init__(self):
  1675. self.works: List[Work] = []
  1676. def append(self, work: Work):
  1677. if work:
  1678. self.works.append(work)
  1679. def wait(self):
  1680. for work in self.works:
  1681. work.wait()
  1682. @contextlib.contextmanager
  1683. def _coalescing_manager(
  1684. group: Optional[ProcessGroup] = None,
  1685. device: Optional[torch.device] = None,
  1686. async_ops: Optional[bool] = False,
  1687. ):
  1688. """
  1689. Context manager used to coalesce collectives or P2P operations when possible.
  1690. Args:
  1691. group (`ProcessGroup`, optional): The process group to work on. If None,
  1692. the default process group will be used.
  1693. device (`torch.device`, optional): Default is None, set to a device if
  1694. there isn't a `**_coalesced` implementation by the backend.
  1695. async_ops (`bool`, optional): whether the coalesced ops are async ops.
  1696. Examples:
  1697. >>> # xdoctest: +SKIP("no rank")
  1698. >>> # Synchronous ops
  1699. >>> with _coalescing_manager():
  1700. >>> for i in range(num_colls):
  1701. >>> dist.all_reduce(tensors[i])
  1702. >>> # Asynchronous ops
  1703. >>> with _coalescing_manager(async_ops=True) as cm:
  1704. >>> for i in range(num_colls):
  1705. >>> dist.all_reduce(tensors[i])
  1706. >>> cm.wait()
  1707. .. warning::
  1708. :func:`_coalescing_manager` currently do not support coalescing
  1709. all-reduces with different reduce operators, e.g. `ReduceOp.SUM` mixed
  1710. with `ReduceOp.PRODUCT`.
  1711. """
  1712. group = group or _get_default_group()
  1713. op_list = _world.pg_coalesce_state.setdefault(group, [])
  1714. if op_list:
  1715. raise ValueError("ProcessGroup has non-empty op list at the start of coalescing")
  1716. if device:
  1717. group._start_coalescing(device)
  1718. cm = _CoalescingManager()
  1719. yield cm
  1720. op_list = _world.pg_coalesce_state.pop(group)
  1721. if op_list:
  1722. # Collectives supporting "Fast Path" coalescing are captured.
  1723. # See implementation in corresponding collective APIs.
  1724. # Currently supported:
  1725. # - coalesced `all_reduce`
  1726. # - coalesced `all_gather_into_tensor`
  1727. # - coalesced `reduce_scatter_tensor`
  1728. op0 = op_list[0].op
  1729. if op0 == all_reduce:
  1730. tensors = []
  1731. for op in op_list:
  1732. tensors.append(op.tensor)
  1733. all_reduce_opts = AllreduceCoalescedOptions()
  1734. all_reduce_opts.reduceOp = not_none(op_list[0].redop)
  1735. work = group.allreduce_coalesced(tensors, all_reduce_opts)
  1736. elif op0 == all_gather_into_tensor:
  1737. inputs = []
  1738. outputs = []
  1739. for op in op_list:
  1740. inputs.append(op.tensor)
  1741. outputs.append(not_none(op.dst_tensor))
  1742. work = group.allgather_into_tensor_coalesced(outputs, inputs)
  1743. elif op0 == reduce_scatter_tensor:
  1744. inputs = []
  1745. outputs = []
  1746. for op in op_list:
  1747. inputs.append(op.tensor)
  1748. outputs.append(not_none(op.dst_tensor))
  1749. reduce_opts = ReduceScatterOptions()
  1750. reduce_opts.reduceOp = not_none(op_list[0].redop)
  1751. work = group.reduce_scatter_tensor_coalesced(outputs, inputs, reduce_opts)
  1752. else:
  1753. raise AssertionError(
  1754. f"Coalescing manager does not support fast-path coalescing of {op0}, "
  1755. f"yet {op0} is still recorded in op list. This is an internal error of c10d."
  1756. )
  1757. if device:
  1758. # Old style of letting each coll inside the context manager to call into C++ counterpart via python binding
  1759. work = group._end_coalescing(device)
  1760. if async_ops:
  1761. cm.append(work) # type: ignore[possibly-undefined]
  1762. else:
  1763. work.wait() # type: ignore[possibly-undefined]
  1764. def batch_isend_irecv(p2p_op_list):
  1765. """
  1766. Send or Receive a batch of tensors asynchronously and return a list of requests.
  1767. Process each of the operations in ``p2p_op_list`` and return the corresponding
  1768. requests. NCCL, Gloo, and UCC backend are currently supported.
  1769. Args:
  1770. p2p_op_list: A list of point-to-point operations(type of each operator is
  1771. ``torch.distributed.P2POp``). The order of the isend/irecv in the list
  1772. matters and it needs to match with corresponding isend/irecv on the
  1773. remote end.
  1774. Returns:
  1775. A list of distributed request objects returned by calling the corresponding
  1776. op in the op_list.
  1777. Examples:
  1778. >>> # xdoctest: +SKIP("no rank")
  1779. >>> send_tensor = torch.arange(2, dtype=torch.float32) + 2 * rank
  1780. >>> recv_tensor = torch.randn(2, dtype=torch.float32)
  1781. >>> send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1)%world_size)
  1782. >>> recv_op = dist.P2POp(dist.irecv, recv_tensor, (rank - 1 + world_size)%world_size)
  1783. >>> reqs = batch_isend_irecv([send_op, recv_op])
  1784. >>> for req in reqs:
  1785. >>> req.wait()
  1786. >>> recv_tensor
  1787. tensor([2, 3]) # Rank 0
  1788. tensor([0, 1]) # Rank 1
  1789. .. note:: Note that when this API is used with the NCCL PG backend, users must set
  1790. the current GPU device with `torch.cuda.set_device`, otherwise it will
  1791. lead to unexpected hang issues.
  1792. In addition, if this API is the first collective call in the ``group``
  1793. passed to ``dist.P2POp``, all ranks of the ``group`` must participate in
  1794. this API call; otherwise, the behavior is undefined. If this API call is
  1795. not the first collective call in the ``group``, batched P2P operations
  1796. involving only a subset of ranks of the ``group`` are allowed.
  1797. """
  1798. _check_p2p_op_list(p2p_op_list)
  1799. group = p2p_op_list[0].group
  1800. device = p2p_op_list[0].tensor.device
  1801. if device.type == "cuda":
  1802. # NCCL style coalescing
  1803. with _coalescing_manager(group, device, async_ops=True) as cm:
  1804. for p2p_op in p2p_op_list:
  1805. p2p_op.op(p2p_op.tensor, p2p_op.peer, p2p_op.group, p2p_op.tag)
  1806. return cm.works
  1807. else:
  1808. # Backward support for Gloo
  1809. reqs = []
  1810. for p2p_op in p2p_op_list:
  1811. work = p2p_op.op(p2p_op.tensor, p2p_op.peer, p2p_op.group, p2p_op.tag)
  1812. if work:
  1813. reqs.append(work)
  1814. return reqs
  1815. @_exception_logger
  1816. def broadcast(tensor, src, group=None, async_op=False):
  1817. """
  1818. Broadcasts the tensor to the whole group.
  1819. ``tensor`` must have the same number of elements in all processes
  1820. participating in the collective.
  1821. Args:
  1822. tensor (Tensor): Data to be sent if ``src`` is the rank of current
  1823. process, and tensor to be used to save received data otherwise.
  1824. src (int): Source rank on global process group (regardless of ``group`` argument).
  1825. group (ProcessGroup, optional): The process group to work on. If None,
  1826. the default process group will be used.
  1827. async_op (bool, optional): Whether this op should be an async op
  1828. Returns:
  1829. Async work handle, if async_op is set to True.
  1830. None, if not async_op or if not part of the group
  1831. """
  1832. _check_single_tensor(tensor, "tensor")
  1833. if _rank_not_in_group(group):
  1834. _warn_not_in_group("broadcast")
  1835. return
  1836. opts = BroadcastOptions()
  1837. opts.rootRank = src
  1838. opts.rootTensor = 0
  1839. opts.asyncOp = async_op
  1840. if group is None or group is GroupMember.WORLD:
  1841. default_pg = _get_default_group()
  1842. work = default_pg.broadcast([tensor], opts)
  1843. else:
  1844. group_src_rank = get_group_rank(group, src)
  1845. opts.rootRank = group_src_rank
  1846. work = group.broadcast([tensor], opts)
  1847. if async_op:
  1848. return work
  1849. else:
  1850. work.wait()
  1851. @_exception_logger
  1852. def all_reduce(tensor, op=ReduceOp.SUM, group=None, async_op=False):
  1853. """
  1854. Reduces the tensor data across all machines in a way that all get the final result.
  1855. After the call ``tensor`` is going to be bitwise identical in all processes.
  1856. Complex tensors are supported.
  1857. Args:
  1858. tensor (Tensor): Input and output of the collective. The function
  1859. operates in-place.
  1860. op (optional): One of the values from
  1861. ``torch.distributed.ReduceOp``
  1862. enum. Specifies an operation used for element-wise reductions.
  1863. group (ProcessGroup, optional): The process group to work on. If None,
  1864. the default process group will be used.
  1865. async_op (bool, optional): Whether this op should be an async op
  1866. Returns:
  1867. Async work handle, if async_op is set to True.
  1868. None, if not async_op or if not part of the group
  1869. Examples:
  1870. >>> # xdoctest: +SKIP("no rank")
  1871. >>> # All tensors below are of torch.int64 type.
  1872. >>> # We have 2 process groups, 2 ranks.
  1873. >>> device = torch.device(f'cuda:{rank}')
  1874. >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  1875. >>> tensor
  1876. tensor([1, 2], device='cuda:0') # Rank 0
  1877. tensor([3, 4], device='cuda:1') # Rank 1
  1878. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  1879. >>> tensor
  1880. tensor([4, 6], device='cuda:0') # Rank 0
  1881. tensor([4, 6], device='cuda:1') # Rank 1
  1882. >>> # All tensors below are of torch.cfloat type.
  1883. >>> # We have 2 process groups, 2 ranks.
  1884. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat, device=device) + 2 * rank * (1+1j)
  1885. >>> tensor
  1886. tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
  1887. tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
  1888. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  1889. >>> tensor
  1890. tensor([4.+4.j, 6.+6.j], device='cuda:0') # Rank 0
  1891. tensor([4.+4.j, 6.+6.j], device='cuda:1') # Rank 1
  1892. """
  1893. _check_single_tensor(tensor, "tensor")
  1894. if _rank_not_in_group(group):
  1895. _warn_not_in_group("all_reduce")
  1896. return
  1897. if tensor.is_complex():
  1898. if not supports_complex(op):
  1899. raise ValueError(f"all_reduce does not support {op} on complex tensors")
  1900. tensor = torch.view_as_real(tensor)
  1901. opts = AllreduceOptions()
  1902. opts.reduceOp = op
  1903. if group is None:
  1904. group = _get_default_group()
  1905. if group in _world.pg_coalesce_state.keys():
  1906. # We are in coalescing context, do not issue single operation, just append a collective representation
  1907. coll = _CollOp(all_reduce, tensor, None, op, None)
  1908. _world.pg_coalesce_state[group].append(coll)
  1909. if async_op:
  1910. return _IllegalWork()
  1911. else:
  1912. return None
  1913. work = group.allreduce([tensor], opts)
  1914. if async_op:
  1915. return work
  1916. else:
  1917. work.wait()
  1918. @_exception_logger
  1919. @deprecated(
  1920. "`torch.distributed.all_reduce_coalesced` will be deprecated. If you must "
  1921. "use it, please revisit our documentation later at "
  1922. "https://pytorch.org/docs/main/distributed.html#collective-functions",
  1923. category=FutureWarning,
  1924. )
  1925. def all_reduce_coalesced(tensors, op=ReduceOp.SUM, group=None, async_op=False):
  1926. """
  1927. WARNING: at this time individual shape checking is not implemented across nodes.
  1928. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  1929. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce
  1930. operation will proceed without complaint and return erroneous outputs. This lack
  1931. of shape checking results in significant performance improvements but users of this
  1932. function should take extra care to ensure that each node passes in tensors whose
  1933. shapes match across nodes.
  1934. Reduces each tensor in tensors (residing on the same device) across all machines
  1935. in such a way that all get the final result.
  1936. After the call each tensor in tensors is going to bitwise identical
  1937. in all processes.
  1938. Complex tensors are supported.
  1939. Args:
  1940. tensors (Union[List[Tensor], Tensor]): Input and output of the collective.
  1941. The function operates in-place.
  1942. op (Optional[ReduceOp]): One of the values from
  1943. ``torch.distributed.ReduceOp`` enum. Specifies an operation used for
  1944. element-wise reductions.
  1945. group (ProcessGroup, optional): The process group to work on. If None,
  1946. the default process group will be used.
  1947. async_op (Optional[bool]): Whether this op should be an async op.
  1948. Returns:
  1949. Async work handle, if async_op is set to True.
  1950. None, if not async_op or if not part of the group.
  1951. """
  1952. if isinstance(tensors, torch.Tensor):
  1953. tensors = [tensors]
  1954. _check_tensor_list(tensors, "tensor")
  1955. _ensure_all_tensors_same_dtype(tensors)
  1956. if _rank_not_in_group(group):
  1957. _warn_not_in_group("all_reduce_coalesced")
  1958. return
  1959. if any(t.is_complex() for t in tensors) and not supports_complex(op):
  1960. raise ValueError(f"all_reduce does not support {op} on complex tensors")
  1961. tensors = [t if not t.is_complex() else torch.view_as_real(t) for t in tensors]
  1962. opts = AllreduceCoalescedOptions()
  1963. opts.reduceOp = op
  1964. if group is None:
  1965. default_pg = _get_default_group()
  1966. work = default_pg.allreduce_coalesced(tensors, opts)
  1967. else:
  1968. work = group.allreduce_coalesced(tensors, opts)
  1969. if async_op:
  1970. return work.get_future()
  1971. else:
  1972. work.wait()
  1973. @_exception_logger
  1974. def reduce(tensor, dst, op=ReduceOp.SUM, group=None, async_op=False):
  1975. """
  1976. Reduces the tensor data across all machines.
  1977. Only the process with rank ``dst`` is going to receive the final result.
  1978. Args:
  1979. tensor (Tensor): Input and output of the collective. The function
  1980. operates in-place.
  1981. dst (int): Destination rank on global process group (regardless of ``group`` argument)
  1982. op (optional): One of the values from
  1983. ``torch.distributed.ReduceOp``
  1984. enum. Specifies an operation used for element-wise reductions.
  1985. group (ProcessGroup, optional): The process group to work on. If None,
  1986. the default process group will be used.
  1987. async_op (bool, optional): Whether this op should be an async op
  1988. Returns:
  1989. Async work handle, if async_op is set to True.
  1990. None, if not async_op or if not part of the group
  1991. """
  1992. _check_single_tensor(tensor, "tensor")
  1993. if _rank_not_in_group(group):
  1994. _warn_not_in_group("reduce")
  1995. return
  1996. opts = ReduceOptions()
  1997. opts.reduceOp = op
  1998. opts.rootRank = dst
  1999. if group is None or group is GroupMember.WORLD:
  2000. default_pg = _get_default_group()
  2001. work = default_pg.reduce([tensor], opts)
  2002. else:
  2003. group_dst_rank = get_group_rank(group, dst)
  2004. opts.rootRank = group_dst_rank
  2005. work = group.reduce([tensor], opts)
  2006. if async_op:
  2007. return work
  2008. else:
  2009. work.wait()
  2010. def _object_to_tensor(obj, device, group):
  2011. f = io.BytesIO()
  2012. _pickler(f).dump(obj)
  2013. byte_storage = torch.ByteStorage._from_buffer(f.getvalue()) # type: ignore[attr-defined]
  2014. # Do not replace `torch.ByteTensor` or `torch.LongTensor` with torch.tensor and specifying dtype.
  2015. # Otherwise, it will casue 100X slowdown.
  2016. # See: https://github.com/pytorch/pytorch/issues/65696
  2017. byte_tensor = torch.ByteTensor(byte_storage).to(device)
  2018. if get_debug_level() == DebugLevel.DETAIL and is_nccl_available():
  2019. backend = get_backend(group)
  2020. if backend == Backend.NCCL:
  2021. hash = torch._C._distributed_c10d._hash_tensors([byte_tensor])
  2022. logger.warning("_object_to_tensor size: %s hash value: %s", byte_tensor.numel(), hash)
  2023. local_size = torch.LongTensor([byte_tensor.numel()]).to(device)
  2024. return byte_tensor, local_size
  2025. def _tensor_to_object(tensor, tensor_size, group):
  2026. if get_debug_level() == DebugLevel.DETAIL and is_nccl_available():
  2027. backend = get_backend(group)
  2028. if backend == Backend.NCCL:
  2029. hash = torch._C._distributed_c10d._hash_tensors([tensor])
  2030. logger.warning("_tensor_to_object size: %s hash value: %s", tensor.numel(), hash)
  2031. tensor = tensor.cpu()
  2032. buf = tensor.numpy().tobytes()[:tensor_size]
  2033. return _unpickler(io.BytesIO(buf)).load()
  2034. @_exception_logger
  2035. def all_gather_object(object_list, obj, group=None):
  2036. """
  2037. Gathers picklable objects from the whole group into a list.
  2038. Similar to :func:`all_gather`, but Python objects can be passed in.
  2039. Note that the object must be picklable in order to be gathered.
  2040. Args:
  2041. object_list (list[Any]): Output list. It should be correctly sized as the
  2042. size of the group for this collective and will contain the output.
  2043. obj (Any): Pickable Python object to be broadcast from current process.
  2044. group (ProcessGroup, optional): The process group to work on. If None,
  2045. the default process group will be used. Default is ``None``.
  2046. Returns:
  2047. None. If the calling rank is part of this group, the output of the
  2048. collective will be populated into the input ``object_list``. If the
  2049. calling rank is not part of the group, the passed in ``object_list`` will
  2050. be unmodified.
  2051. .. note:: Note that this API differs slightly from the :func:`all_gather`
  2052. collective since it does not provide an ``async_op`` handle and thus
  2053. will be a blocking call.
  2054. .. note:: For NCCL-based processed groups, internal tensor representations
  2055. of objects must be moved to the GPU device before communication takes
  2056. place. In this case, the device used is given by
  2057. ``torch.cuda.current_device()`` and it is the user's responsiblity to
  2058. ensure that this is set so that each rank has an individual GPU, via
  2059. ``torch.cuda.set_device()``.
  2060. .. warning::
  2061. :func:`all_gather_object` uses ``pickle`` module implicitly, which is
  2062. known to be insecure. It is possible to construct malicious pickle data
  2063. which will execute arbitrary code during unpickling. Only call this
  2064. function with data you trust.
  2065. .. warning::
  2066. Calling :func:`all_gather_object` with GPU tensors is not well supported
  2067. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2068. pickled. Please consider using :func:`all_gather` instead.
  2069. Example::
  2070. >>> # xdoctest: +SKIP("need process group init")
  2071. >>> # Note: Process group initialization omitted on each rank.
  2072. >>> import torch.distributed as dist
  2073. >>> # Assumes world_size of 3.
  2074. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  2075. >>> output = [None for _ in gather_objects]
  2076. >>> dist.all_gather_object(output, gather_objects[dist.get_rank()])
  2077. >>> output
  2078. ['foo', 12, {1: 2}]
  2079. """
  2080. if _rank_not_in_group(group):
  2081. _warn_not_in_group("all_gather_object")
  2082. return
  2083. current_device = _get_pg_default_device(group)
  2084. input_tensor, local_size = _object_to_tensor(obj, current_device, group)
  2085. # Gather all local sizes. This is so that we can find the max size, and index
  2086. # until the correct size when deserializing the tensors.
  2087. group_size = get_world_size(group=group)
  2088. object_sizes_tensor = torch.zeros(
  2089. group_size, dtype=torch.long, device=current_device
  2090. )
  2091. object_size_list = [
  2092. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  2093. ]
  2094. # Allgather tensor sizes
  2095. all_gather(object_size_list, local_size, group=group)
  2096. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  2097. # Resize tensor to max size across all ranks.
  2098. input_tensor.resize_(max_object_size)
  2099. coalesced_output_tensor = torch.empty(
  2100. max_object_size * group_size, dtype=torch.uint8, device=current_device
  2101. )
  2102. # Output tensors are nonoverlapping views of coalesced_output_tensor
  2103. output_tensors = [
  2104. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  2105. for i in range(group_size)
  2106. ]
  2107. all_gather(output_tensors, input_tensor, group=group)
  2108. # Deserialize outputs back to object.
  2109. for i, tensor in enumerate(output_tensors):
  2110. tensor = tensor.type(torch.uint8)
  2111. tensor_size = object_size_list[i]
  2112. object_list[i] = _tensor_to_object(tensor, tensor_size, group)
  2113. @_exception_logger
  2114. def gather_object(obj, object_gather_list=None, dst=0, group=None):
  2115. """
  2116. Gathers picklable objects from the whole group in a single process.
  2117. Similar to :func:`gather`, but Python objects can be passed in. Note that the
  2118. object must be picklable in order to be gathered.
  2119. Args:
  2120. obj (Any): Input object. Must be picklable.
  2121. object_gather_list (list[Any]): Output list. On the ``dst`` rank, it
  2122. should be correctly sized as the size of the group for this
  2123. collective and will contain the output. Must be ``None`` on non-dst
  2124. ranks. (default is ``None``)
  2125. dst (int, optional): Destination rank on global process group (regardless of ``group`` argument). (default is 0)
  2126. group: (ProcessGroup, optional): The process group to work on. If None,
  2127. the default process group will be used. Default is ``None``.
  2128. Returns:
  2129. None. On the ``dst`` rank, ``object_gather_list`` will contain the
  2130. output of the collective.
  2131. .. note:: Note that this API differs slightly from the gather collective
  2132. since it does not provide an async_op handle and thus will be a blocking
  2133. call.
  2134. .. note:: For NCCL-based processed groups, internal tensor representations
  2135. of objects must be moved to the GPU device before communication takes
  2136. place. In this case, the device used is given by
  2137. ``torch.cuda.current_device()`` and it is the user's responsiblity to
  2138. ensure that this is set so that each rank has an individual GPU, via
  2139. ``torch.cuda.set_device()``.
  2140. .. warning::
  2141. :func:`gather_object` uses ``pickle`` module implicitly, which is
  2142. known to be insecure. It is possible to construct malicious pickle data
  2143. which will execute arbitrary code during unpickling. Only call this
  2144. function with data you trust.
  2145. .. warning::
  2146. Calling :func:`gather_object` with GPU tensors is not well supported
  2147. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2148. pickled. Please consider using :func:`gather` instead.
  2149. Example::
  2150. >>> # xdoctest: +SKIP("need process group init")
  2151. >>> # Note: Process group initialization omitted on each rank.
  2152. >>> import torch.distributed as dist
  2153. >>> # Assumes world_size of 3.
  2154. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  2155. >>> output = [None for _ in gather_objects]
  2156. >>> dist.gather_object(
  2157. ... gather_objects[dist.get_rank()],
  2158. ... output if dist.get_rank() == 0 else None,
  2159. ... dst=0
  2160. ... )
  2161. >>> # On rank 0
  2162. >>> output
  2163. ['foo', 12, {1: 2}]
  2164. """
  2165. if _rank_not_in_group(group):
  2166. _warn_not_in_group("gather_object")
  2167. return
  2168. # Ensure object_gather_list is specified appropriately.
  2169. my_rank = get_rank()
  2170. _validate_output_list_for_rank(my_rank, dst, object_gather_list)
  2171. current_device = _get_pg_default_device(group)
  2172. input_tensor, local_size = _object_to_tensor(obj, current_device, group)
  2173. # Gather all local sizes. This is so that we can find the max size, and index
  2174. # until the correct size when deserializing the tensors.
  2175. group_size = get_world_size(group=group)
  2176. object_sizes_tensor = torch.zeros(
  2177. group_size, dtype=torch.long, device=current_device
  2178. )
  2179. object_size_list = [
  2180. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  2181. ]
  2182. # Allgather tensor sizes. An all-gather is needed here despite this being a
  2183. # gather, since each rank needs to broadcast a tensor of the same (maximal)
  2184. # size.
  2185. all_gather(object_size_list, local_size, group=group)
  2186. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  2187. # Resize tensor to max size across all ranks.
  2188. input_tensor.resize_(max_object_size)
  2189. # Avoid populating output tensors if the result won't be gathered on this rank.
  2190. if my_rank == dst:
  2191. coalesced_output_tensor = torch.empty(
  2192. max_object_size * group_size, dtype=torch.uint8, device=current_device
  2193. )
  2194. # Output tensors are nonoverlapping views of coalesced_output_tensor
  2195. output_tensors = [
  2196. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  2197. for i in range(group_size)
  2198. ]
  2199. # All ranks call gather with equal-sized tensors.
  2200. gather(
  2201. input_tensor,
  2202. gather_list=output_tensors if my_rank == dst else None, # type: ignore[possibly-undefined]
  2203. dst=dst,
  2204. group=group,
  2205. )
  2206. if my_rank != dst:
  2207. return
  2208. for i, tensor in enumerate(output_tensors):
  2209. tensor = tensor.type(torch.uint8)
  2210. tensor_size = object_size_list[i]
  2211. object_gather_list[i] = _tensor_to_object(tensor, tensor_size, group)
  2212. @_exception_logger
  2213. def send_object_list(object_list, dst, group=None, device=None):
  2214. """
  2215. Sends picklable objects in ``object_list`` synchronously.
  2216. Similar to :func:`send`, but Python objects can be passed in.
  2217. Note that all objects in ``object_list`` must be picklable in order to be
  2218. sent.
  2219. Args:
  2220. object_list (List[Any]): List of input objects to sent.
  2221. Each object must be picklable. Receiver must provide lists of equal sizes.
  2222. dst (int): Destination rank to send ``object_list`` to.
  2223. Destination rank is based on global process group (regardless of ``group`` argument)
  2224. group: (ProcessGroup, optional): The process group to work on. If None,
  2225. the default process group will be used. Default is ``None``.
  2226. device (``torch.device``, optional): If not None, the objects are
  2227. serialized and converted to tensors which are moved to the
  2228. ``device`` before sending. Default is ``None``.
  2229. Returns:
  2230. ``None``.
  2231. .. note:: For NCCL-based process groups, internal tensor representations
  2232. of objects must be moved to the GPU device before communication takes
  2233. place. In this case, the device used is given by
  2234. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2235. ensure that this is set so that each rank has an individual GPU, via
  2236. ``torch.cuda.set_device()``.
  2237. .. warning::
  2238. :func:`send_object_list` uses ``pickle`` module implicitly, which
  2239. is known to be insecure. It is possible to construct malicious pickle
  2240. data which will execute arbitrary code during unpickling. Only call this
  2241. function with data you trust.
  2242. .. warning::
  2243. Calling :func:`send_object_list` with GPU tensors is not well supported
  2244. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2245. pickled. Please consider using :func:`send` instead.
  2246. Example::
  2247. >>> # xdoctest: +SKIP("need process group init")
  2248. >>> # Note: Process group initialization omitted on each rank.
  2249. >>> import torch.distributed as dist
  2250. >>> # Assumes backend is not NCCL
  2251. >>> device = torch.device("cpu")
  2252. >>> if dist.get_rank() == 0:
  2253. >>> # Assumes world_size of 2.
  2254. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  2255. >>> dist.send_object_list(objects, dst=1, device=device)
  2256. >>> else:
  2257. >>> objects = [None, None, None]
  2258. >>> dist.recv_object_list(objects, src=0, device=device)
  2259. >>> objects
  2260. ['foo', 12, {1: 2}]
  2261. """
  2262. if get_rank() == dst:
  2263. raise ValueError(
  2264. "Invalid destination rank: destination rank should not be the same as "
  2265. "the rank of the current process."
  2266. )
  2267. if _rank_not_in_group(group):
  2268. _warn_not_in_group("send_object_list")
  2269. return
  2270. # Current device selection.
  2271. # To preserve backwards compatibility, ``device`` is default to ``None``
  2272. # in which case we run current logic of device selection, i.e.
  2273. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  2274. # case it is not ``None`` we move the size and object tensors to be
  2275. # sent to this device.
  2276. current_device = device or _get_pg_default_device(group)
  2277. # Serialize object_list elements to tensors on src rank.
  2278. tensor_list, size_list = zip(*[_object_to_tensor(obj, current_device, group) for obj in object_list])
  2279. object_sizes_tensor = torch.cat(size_list)
  2280. # Send object sizes
  2281. send(object_sizes_tensor, dst=dst, group=group)
  2282. # Concatenate and send serialized object tensors
  2283. # Note: torch.cat will do an extra memory copy to the current device, if the tensor_list
  2284. # has only one element, we can skip the copy.
  2285. if len(tensor_list) == 1: # type: ignore[possibly-undefined]
  2286. object_tensor = tensor_list[0]
  2287. else:
  2288. object_tensor = torch.cat(tensor_list)
  2289. send(object_tensor, dst=dst, group=group)
  2290. @_exception_logger
  2291. def recv_object_list(object_list, src=None, group=None, device=None):
  2292. """
  2293. Receives picklable objects in ``object_list`` synchronously.
  2294. Similar to :func:`recv`, but can receive Python objects.
  2295. Args:
  2296. object_list (List[Any]): List of objects to receive into.
  2297. Must provide a list of sizes equal to the size of the list being sent.
  2298. src (int, optional): Source rank from which to recv ``object_list``.
  2299. Source rank is based on global process group (regardless of ``group`` argument)
  2300. Will receive from any rank if set to None. Default is ``None``.
  2301. group: (ProcessGroup, optional): The process group to work on. If None,
  2302. the default process group will be used. Default is ``None``.
  2303. device (``torch.device``, optional): If not None, receives on this device.
  2304. Default is ``None``.
  2305. Returns:
  2306. Sender rank. -1 if rank is not part of the group. If rank is part of the group,
  2307. ``object_list`` will contain the sent objects from ``src`` rank.
  2308. .. note:: For NCCL-based process groups, internal tensor representations
  2309. of objects must be moved to the GPU device before communication takes
  2310. place. In this case, the device used is given by
  2311. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2312. ensure that this is set so that each rank has an individual GPU, via
  2313. ``torch.cuda.set_device()``.
  2314. .. warning::
  2315. :func:`recv_object_list` uses ``pickle`` module implicitly, which
  2316. is known to be insecure. It is possible to construct malicious pickle
  2317. data which will execute arbitrary code during unpickling. Only call this
  2318. function with data you trust.
  2319. .. warning::
  2320. Calling :func:`recv_object_list` with GPU tensors is not well supported
  2321. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2322. pickled. Please consider using :func:`recv` instead.
  2323. Example::
  2324. >>> # xdoctest: +SKIP("need process group init")
  2325. >>> # Note: Process group initialization omitted on each rank.
  2326. >>> import torch.distributed as dist
  2327. >>> # Assumes backend is not NCCL
  2328. >>> device = torch.device("cpu")
  2329. >>> if dist.get_rank() == 0:
  2330. >>> # Assumes world_size of 2.
  2331. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  2332. >>> dist.send_object_list(objects, dst=1, device=device)
  2333. >>> else:
  2334. >>> objects = [None, None, None]
  2335. >>> dist.recv_object_list(objects, src=0, device=device)
  2336. >>> objects
  2337. ['foo', 12, {1: 2}]
  2338. """
  2339. if _rank_not_in_group(group):
  2340. _warn_not_in_group("recv_object_list")
  2341. return -1
  2342. # Current device selection.
  2343. # To preserve backwards compatibility, ``device`` is default to ``None``
  2344. # in which case we run current logic of device selection, i.e.
  2345. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  2346. # case it is not ``None`` we move the size and object tensors to be
  2347. # received to this device.
  2348. current_device = device or _get_pg_default_device(group)
  2349. object_sizes_tensor = torch.empty(len(object_list), dtype=torch.long, device=current_device)
  2350. # Receive object sizes
  2351. rank_sizes = recv(object_sizes_tensor, src=src, group=group)
  2352. # Tensor to receive serialized objects into.
  2353. object_tensor = torch.empty( # type: ignore[call-overload]
  2354. torch.sum(object_sizes_tensor).item(), # type: ignore[arg-type]
  2355. dtype=torch.uint8,
  2356. device=current_device
  2357. )
  2358. rank_objects = recv(object_tensor, src=src, group=group)
  2359. assert rank_sizes == rank_objects, "Mismatch in return ranks for object sizes and objects."
  2360. # Deserialize objects using their stored sizes.
  2361. offset = 0
  2362. for i, obj_size in enumerate(object_sizes_tensor):
  2363. obj_view = object_tensor[offset : offset + obj_size]
  2364. obj_view = obj_view.type(torch.uint8)
  2365. offset += obj_size
  2366. object_list[i] = _tensor_to_object(obj_view, obj_size, group)
  2367. return rank_objects
  2368. @_exception_logger
  2369. def broadcast_object_list(object_list, src=0, group=None, device=None):
  2370. """
  2371. Broadcasts picklable objects in ``object_list`` to the whole group.
  2372. Similar to :func:`broadcast`, but Python objects can be passed in.
  2373. Note that all objects in ``object_list`` must be picklable in order to be
  2374. broadcasted.
  2375. Args:
  2376. object_list (List[Any]): List of input objects to broadcast.
  2377. Each object must be picklable. Only objects on the ``src`` rank will
  2378. be broadcast, but each rank must provide lists of equal sizes.
  2379. src (int): Source rank from which to broadcast ``object_list``.
  2380. Source rank is based on global process group (regardless of ``group`` argument)
  2381. group: (ProcessGroup, optional): The process group to work on. If None,
  2382. the default process group will be used. Default is ``None``.
  2383. device (``torch.device``, optional): If not None, the objects are
  2384. serialized and converted to tensors which are moved to the
  2385. ``device`` before broadcasting. Default is ``None``.
  2386. Returns:
  2387. ``None``. If rank is part of the group, ``object_list`` will contain the
  2388. broadcasted objects from ``src`` rank.
  2389. .. note:: For NCCL-based process groups, internal tensor representations
  2390. of objects must be moved to the GPU device before communication takes
  2391. place. In this case, the device used is given by
  2392. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2393. ensure that this is set so that each rank has an individual GPU, via
  2394. ``torch.cuda.set_device()``.
  2395. .. note:: Note that this API differs slightly from the :func:`broadcast`
  2396. collective since it does not provide an ``async_op`` handle and thus
  2397. will be a blocking call.
  2398. .. warning::
  2399. :func:`broadcast_object_list` uses ``pickle`` module implicitly, which
  2400. is known to be insecure. It is possible to construct malicious pickle
  2401. data which will execute arbitrary code during unpickling. Only call this
  2402. function with data you trust.
  2403. .. warning::
  2404. Calling :func:`broadcast_object_list` with GPU tensors is not well supported
  2405. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2406. pickled. Please consider using :func:`broadcast` instead.
  2407. Example::
  2408. >>> # xdoctest: +SKIP("need process group init")
  2409. >>> # Note: Process group initialization omitted on each rank.
  2410. >>> import torch.distributed as dist
  2411. >>> if dist.get_rank() == 0:
  2412. >>> # Assumes world_size of 3.
  2413. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  2414. >>> else:
  2415. >>> objects = [None, None, None]
  2416. >>> # Assumes backend is not NCCL
  2417. >>> device = torch.device("cpu")
  2418. >>> dist.broadcast_object_list(objects, src=0, device=device)
  2419. >>> objects
  2420. ['foo', 12, {1: 2}]
  2421. """
  2422. if _rank_not_in_group(group):
  2423. _warn_not_in_group("broadcast_object_list")
  2424. return
  2425. # Current device selection.
  2426. # To preserve backwards compatibility, ``device`` is default to ``None``
  2427. # in which case we run current logic of device selection, i.e.
  2428. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  2429. # case it is not ``None`` we move the size and object tensors to be
  2430. # broadcasted to this device.
  2431. current_device = device or _get_pg_default_device(group)
  2432. my_rank = get_rank()
  2433. # Serialize object_list elements to tensors on src rank.
  2434. if my_rank == src:
  2435. tensor_list, size_list = zip(*[_object_to_tensor(obj, current_device, group) for obj in object_list])
  2436. object_sizes_tensor = torch.cat(size_list)
  2437. else:
  2438. object_sizes_tensor = torch.empty(len(object_list), dtype=torch.long, device=current_device)
  2439. # Broadcast object sizes
  2440. broadcast(object_sizes_tensor, src=src, group=group)
  2441. # Concatenate and broadcast serialized object tensors
  2442. # Note: torch.cat will do an extra memory copy to the current device, if the tensor_list
  2443. # has only one element, we can skip the copy.
  2444. if my_rank == src:
  2445. if len(tensor_list) == 1: # type: ignore[possibly-undefined]
  2446. object_tensor = tensor_list[0]
  2447. else:
  2448. object_tensor = torch.cat(tensor_list)
  2449. else:
  2450. object_tensor = torch.empty( # type: ignore[call-overload]
  2451. torch.sum(object_sizes_tensor).item(), # type: ignore[arg-type]
  2452. dtype=torch.uint8,
  2453. device=current_device
  2454. )
  2455. broadcast(object_tensor, src=src, group=group)
  2456. # Deserialize objects using their stored sizes.
  2457. offset = 0
  2458. if my_rank != src:
  2459. for i, obj_size in enumerate(object_sizes_tensor):
  2460. obj_view = object_tensor[offset : offset + obj_size]
  2461. obj_view = obj_view.type(torch.uint8)
  2462. offset += obj_size
  2463. object_list[i] = _tensor_to_object(obj_view, obj_size, group)
  2464. @_exception_logger
  2465. def scatter_object_list(
  2466. scatter_object_output_list, scatter_object_input_list, src=0, group=None
  2467. ):
  2468. """
  2469. Scatters picklable objects in ``scatter_object_input_list`` to the whole group.
  2470. Similar to :func:`scatter`, but Python objects can be passed in. On
  2471. each rank, the scattered object will be stored as the first element of
  2472. ``scatter_object_output_list``. Note that all objects in
  2473. ``scatter_object_input_list`` must be picklable in order to be scattered.
  2474. Args:
  2475. scatter_object_output_list (List[Any]): Non-empty list whose first
  2476. element will store the object scattered to this rank.
  2477. scatter_object_input_list (List[Any]): List of input objects to scatter.
  2478. Each object must be picklable. Only objects on the ``src`` rank will
  2479. be scattered, and the argument can be ``None`` for non-src ranks.
  2480. src (int): Source rank from which to scatter ``scatter_object_input_list``.
  2481. Source rank is based on global process group (regardless of ``group`` argument).
  2482. group: (ProcessGroup, optional): The process group to work on. If None,
  2483. the default process group will be used. Default is ``None``.
  2484. Returns:
  2485. ``None``. If rank is part of the group, ``scatter_object_output_list``
  2486. will have its first element set to the scattered object for this rank.
  2487. .. note:: Note that this API differs slightly from the scatter collective
  2488. since it does not provide an ``async_op`` handle and thus will be a
  2489. blocking call.
  2490. .. warning::
  2491. :func:`scatter_object_list` uses ``pickle`` module implicitly, which
  2492. is known to be insecure. It is possible to construct malicious pickle
  2493. data which will execute arbitrary code during unpickling. Only call this
  2494. function with data you trust.
  2495. .. warning::
  2496. Calling :func:`scatter_object_list` with GPU tensors is not well supported
  2497. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2498. pickled. Please consider using :func:`scatter` instead.
  2499. Example::
  2500. >>> # xdoctest: +SKIP("need process group init")
  2501. >>> # Note: Process group initialization omitted on each rank.
  2502. >>> import torch.distributed as dist
  2503. >>> if dist.get_rank() == 0:
  2504. >>> # Assumes world_size of 3.
  2505. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  2506. >>> else:
  2507. >>> # Can be any list on non-src ranks, elements are not used.
  2508. >>> objects = [None, None, None]
  2509. >>> output_list = [None]
  2510. >>> dist.scatter_object_list(output_list, objects, src=0)
  2511. >>> # Rank i gets objects[i]. For example, on rank 2:
  2512. >>> output_list
  2513. [{1: 2}]
  2514. """
  2515. if _rank_not_in_group(group):
  2516. _warn_not_in_group("scatter_object_list")
  2517. return
  2518. if (
  2519. not isinstance(scatter_object_output_list, list)
  2520. or len(scatter_object_output_list) < 1
  2521. ):
  2522. raise ValueError(
  2523. "Expected argument scatter_object_output_list to be a list of size at least 1."
  2524. )
  2525. my_rank = get_rank()
  2526. pg_device = _get_pg_default_device(group)
  2527. if my_rank == src:
  2528. tensor_list, tensor_sizes = zip(
  2529. *[_object_to_tensor(obj, pg_device, group) for obj in scatter_object_input_list]
  2530. )
  2531. tensor_list, tensor_sizes = list(tensor_list), list(tensor_sizes)
  2532. # Src rank broadcasts the maximum tensor size. This is because all ranks are
  2533. # expected to call into scatter() with equal-sized tensors.
  2534. if my_rank == src:
  2535. max_tensor_size = max(tensor_sizes) # type: ignore[possibly-undefined]
  2536. for tensor in tensor_list: # type: ignore[possibly-undefined]
  2537. tensor.resize_(max_tensor_size)
  2538. else:
  2539. max_tensor_size = torch.tensor([0], dtype=torch.long, device=pg_device)
  2540. broadcast(max_tensor_size, src=src, group=group)
  2541. # Scatter actual serialized objects
  2542. output_tensor = torch.empty(max_tensor_size.item(), dtype=torch.uint8, device=pg_device)
  2543. scatter(
  2544. output_tensor,
  2545. scatter_list=None if my_rank != src else tensor_list, # type: ignore[possibly-undefined]
  2546. src=src,
  2547. group=group,
  2548. )
  2549. # Scatter per-object sizes to trim tensors when deserializing back to object
  2550. obj_tensor_size = torch.tensor([0], dtype=torch.long, device=pg_device)
  2551. scatter(
  2552. obj_tensor_size,
  2553. scatter_list=None if my_rank != src else tensor_sizes, # type: ignore[possibly-undefined]
  2554. src=src,
  2555. group=group,
  2556. )
  2557. # Deserialize back to object
  2558. scatter_object_output_list[0] = _tensor_to_object(output_tensor, obj_tensor_size, group)
  2559. @_exception_logger
  2560. def all_gather(tensor_list, tensor, group=None, async_op=False):
  2561. """
  2562. Gathers tensors from the whole group in a list.
  2563. Complex tensors are supported.
  2564. Args:
  2565. tensor_list (list[Tensor]): Output list. It should contain
  2566. correctly-sized tensors to be used for output of the collective.
  2567. tensor (Tensor): Tensor to be broadcast from current process.
  2568. group (ProcessGroup, optional): The process group to work on. If None,
  2569. the default process group will be used.
  2570. async_op (bool, optional): Whether this op should be an async op
  2571. Returns:
  2572. Async work handle, if async_op is set to True.
  2573. None, if not async_op or if not part of the group
  2574. Examples:
  2575. >>> # xdoctest: +SKIP("need process group init")
  2576. >>> # All tensors below are of torch.int64 dtype.
  2577. >>> # We have 2 process groups, 2 ranks.
  2578. >>> device = torch.device(f'cuda:{rank}')
  2579. >>> tensor_list = [torch.zeros(2, dtype=torch.int64, device=device) for _ in range(2)]
  2580. >>> tensor_list
  2581. [tensor([0, 0], device='cuda:0'), tensor([0, 0], device='cuda:0')] # Rank 0
  2582. [tensor([0, 0], device='cuda:0'), tensor([0, 0], device='cuda:1')] # Rank 1
  2583. >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  2584. >>> tensor
  2585. tensor([1, 2], device='cuda:0') # Rank 0
  2586. tensor([3, 4], device='cuda:1') # Rank 1
  2587. >>> dist.all_gather(tensor_list, tensor)
  2588. >>> tensor_list
  2589. [tensor([1, 2], device='cuda:0'), tensor([3, 4], device='cuda:0')] # Rank 0
  2590. [tensor([1, 2], device='cuda:1'), tensor([3, 4], device='cuda:1')] # Rank 1
  2591. >>> # All tensors below are of torch.cfloat dtype.
  2592. >>> # We have 2 process groups, 2 ranks.
  2593. >>> tensor_list = [torch.zeros(2, dtype=torch.cfloat, device=device) for _ in range(2)]
  2594. >>> tensor_list
  2595. [tensor([0.+0.j, 0.+0.j], device='cuda:0'), tensor([0.+0.j, 0.+0.j], device='cuda:0')] # Rank 0
  2596. [tensor([0.+0.j, 0.+0.j], device='cuda:1'), tensor([0.+0.j, 0.+0.j], device='cuda:1')] # Rank 1
  2597. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat, device=device) + 2 * rank * (1+1j)
  2598. >>> tensor
  2599. tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
  2600. tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
  2601. >>> dist.all_gather(tensor_list, tensor)
  2602. >>> tensor_list
  2603. [tensor([1.+1.j, 2.+2.j], device='cuda:0'), tensor([3.+3.j, 4.+4.j], device='cuda:0')] # Rank 0
  2604. [tensor([1.+1.j, 2.+2.j], device='cuda:1'), tensor([3.+3.j, 4.+4.j], device='cuda:1')] # Rank 1
  2605. """
  2606. _check_tensor_list(tensor_list, "tensor_list")
  2607. _check_single_tensor(tensor, "tensor")
  2608. _ensure_all_tensors_same_dtype(tensor_list, tensor)
  2609. if _rank_not_in_group(group):
  2610. _warn_not_in_group("all_gather")
  2611. return
  2612. tensor_list = [
  2613. t if not t.is_complex() else torch.view_as_real(t) for t in tensor_list
  2614. ]
  2615. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  2616. if group is None:
  2617. default_pg = _get_default_group()
  2618. work = default_pg.allgather([tensor_list], [tensor])
  2619. else:
  2620. work = group.allgather([tensor_list], [tensor])
  2621. if async_op:
  2622. return work
  2623. else:
  2624. work.wait()
  2625. @_exception_logger
  2626. def all_gather_into_tensor(output_tensor, input_tensor, group=None, async_op=False):
  2627. """
  2628. Gather tensors from all ranks and put them in a single output tensor.
  2629. Args:
  2630. output_tensor (Tensor): Output tensor to accommodate tensor elements
  2631. from all ranks. It must be correctly sized to have one of the
  2632. following forms:
  2633. (i) a concatenation of all the input tensors along the primary
  2634. dimension; for definition of "concatenation", see ``torch.cat()``;
  2635. (ii) a stack of all the input tensors along the primary dimension;
  2636. for definition of "stack", see ``torch.stack()``.
  2637. Examples below may better explain the supported output forms.
  2638. input_tensor (Tensor): Tensor to be gathered from current rank.
  2639. Different from the ``all_gather`` API, the input tensors in this
  2640. API must have the same size across all ranks.
  2641. group (ProcessGroup, optional): The process group to work on. If None,
  2642. the default process group will be used.
  2643. async_op (bool, optional): Whether this op should be an async op
  2644. Returns:
  2645. Async work handle, if async_op is set to True.
  2646. None, if not async_op or if not part of the group
  2647. Examples:
  2648. >>> # xdoctest: +SKIP("need process group init")
  2649. >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
  2650. >>> # We have two ranks.
  2651. >>> device = torch.device(f'cuda:{rank}')
  2652. >>> tensor_in = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  2653. >>> tensor_in
  2654. tensor([1, 2], device='cuda:0') # Rank 0
  2655. tensor([3, 4], device='cuda:1') # Rank 1
  2656. >>> # Output in concatenation form
  2657. >>> tensor_out = torch.zeros(world_size * 2, dtype=torch.int64, device=device)
  2658. >>> dist.all_gather_into_tensor(tensor_out, tensor_in)
  2659. >>> tensor_out
  2660. tensor([1, 2, 3, 4], device='cuda:0') # Rank 0
  2661. tensor([1, 2, 3, 4], device='cuda:1') # Rank 1
  2662. >>> # Output in stack form
  2663. >>> tensor_out2 = torch.zeros(world_size, 2, dtype=torch.int64, device=device)
  2664. >>> dist.all_gather_into_tensor(tensor_out2, tensor_in)
  2665. >>> tensor_out2
  2666. tensor([[1, 2],
  2667. [3, 4]], device='cuda:0') # Rank 0
  2668. tensor([[1, 2],
  2669. [3, 4]], device='cuda:1') # Rank 1
  2670. .. warning::
  2671. The Gloo backend does not support this API.
  2672. """
  2673. _check_single_tensor(input_tensor, "input_tensor")
  2674. _check_single_tensor(output_tensor, "output_tensor")
  2675. if _rank_not_in_group(group):
  2676. _warn_not_in_group("all_gather_into_tensor")
  2677. return
  2678. output_tensor = (
  2679. output_tensor
  2680. if not output_tensor.is_complex()
  2681. else torch.view_as_real(output_tensor)
  2682. )
  2683. input_tensor = (
  2684. input_tensor
  2685. if not input_tensor.is_complex()
  2686. else torch.view_as_real(input_tensor)
  2687. )
  2688. opts = AllgatherOptions()
  2689. opts.asyncOp = async_op
  2690. group = group or _get_default_group()
  2691. if group in _world.pg_coalesce_state.keys():
  2692. # We are in coalescing context, do not issue single operation, just append a collective representation
  2693. coll = _CollOp(all_gather_into_tensor, input_tensor, output_tensor)
  2694. _world.pg_coalesce_state[group].append(coll)
  2695. if async_op:
  2696. return _IllegalWork()
  2697. else:
  2698. return None
  2699. work = group._allgather_base(output_tensor, input_tensor, opts)
  2700. if async_op:
  2701. return work
  2702. else:
  2703. work.wait()
  2704. @_exception_logger
  2705. @deprecated(
  2706. "`torch.distributed._all_gather_base` is a private function and will be deprecated. "
  2707. "Please use `torch.distributed.all_gather_into_tensor` instead.",
  2708. category=FutureWarning,
  2709. )
  2710. def _all_gather_base(output_tensor, input_tensor, group=None, async_op=False):
  2711. """
  2712. Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
  2713. Args:
  2714. output_tensor (Tensor): Output tensor. It should contain
  2715. correctly-sized tensors to be used for output of the collective.
  2716. input_tensor (Tensor): Tensor to be broadcast from current process.
  2717. group (ProcessGroup, optional): The process group to work on. If None,
  2718. the default process group will be used.
  2719. async_op (bool, optional): Whether this op should be an async op
  2720. Returns:
  2721. Async work handle, if async_op is set to True.
  2722. None, if not async_op or if not part of the group
  2723. .. warning::
  2724. `_all_gather_base` is a private function. Users should use
  2725. `all_gather_into_tensor` instead.
  2726. """
  2727. return all_gather_into_tensor(output_tensor, input_tensor, group, async_op)
  2728. @_exception_logger
  2729. @deprecated(
  2730. "`torch.distributed.all_gather_coalesced` will be deprecated. If you must use it, "
  2731. "please revisit our documentation later at "
  2732. "https://pytorch.org/docs/main/distributed.html#collective-functions",
  2733. category=FutureWarning,
  2734. )
  2735. def all_gather_coalesced(
  2736. output_tensor_lists, input_tensor_list, group=None, async_op=False
  2737. ):
  2738. """
  2739. Gathers input tensors from the whole group in a list in a coalesced manner.
  2740. Complex tensors are supported.
  2741. Args:
  2742. output_tensor_lists (list[list[Tensor]]): Output list. It should contain
  2743. correctly-sized tensors to be used for output of the collective.
  2744. input_tensor_list (list[Tensor]): Tensors to be broadcast from
  2745. current process. At least one tensor has to be non empty.
  2746. group (ProcessGroup, optional): The process group to work on. If None,
  2747. the default process group will be used.
  2748. async_op (bool, optional): Whether this op should be an async op.
  2749. Returns:
  2750. Async work handle, if async_op is set to True.
  2751. None, if not async_op or if not part of the group
  2752. Example:
  2753. we have 2 process groups, 2 ranks.
  2754. rank 0 passes:
  2755. input_tensor_list = [[[1, 1], [1, 1]], [2], [3, 3]]
  2756. output_tensor_lists =
  2757. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  2758. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  2759. rank 1 passes:
  2760. input_tensor_list = [[[3, 3], [3, 3]], [5], [1, 1]]
  2761. output_tensor_lists =
  2762. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  2763. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  2764. both rank 0 and 1 get:
  2765. output_tensor_lists =
  2766. [[[1, 1], [1, 1]], [2], [3, 3]],
  2767. [[3, 3], [3, 3]], [5], [1, 1]]].
  2768. WARNING: at this time individual shape checking is not implemented across nodes.
  2769. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  2770. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the
  2771. all_gather_coalesced operation will proceed without complaint and return
  2772. erroneous outputs. This lack of shape checking results in significant
  2773. performance improvements but users of this function should take extra care
  2774. to ensure that each node passes in tensors whose shapes match across nodes.
  2775. """
  2776. # We only check basic compatibility with C++ params here, C++ code will
  2777. # do shape and type checking.
  2778. if _rank_not_in_group(group):
  2779. _warn_not_in_group("all_gather_coalesced")
  2780. return
  2781. _check_tensor_list(input_tensor_list, "input_tensor_list")
  2782. _ensure_all_tensors_same_dtype(input_tensor_list)
  2783. if not isinstance(output_tensor_lists, list):
  2784. raise TypeError(
  2785. "Invalid function argument: output_tensor_lists should be a list"
  2786. )
  2787. for output_tensor_list in output_tensor_lists:
  2788. _check_tensor_list(output_tensor_list, "output_tensor_lists")
  2789. _ensure_all_tensors_same_dtype(output_tensor_list)
  2790. output_tensor_lists = [
  2791. [t if not t.is_complex() else torch.view_as_real(t) for t in l]
  2792. for l in output_tensor_lists
  2793. ]
  2794. input_tensor_list = [
  2795. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  2796. ]
  2797. if group is None:
  2798. default_pg = _get_default_group()
  2799. work = default_pg.allgather_coalesced(output_tensor_lists, input_tensor_list)
  2800. else:
  2801. work = group.allgather_coalesced(output_tensor_lists, input_tensor_list)
  2802. if async_op:
  2803. return work.get_future()
  2804. else:
  2805. work.wait()
  2806. def _validate_output_list_for_rank(my_rank, dst, gather_list):
  2807. if dst == my_rank:
  2808. if not gather_list:
  2809. raise ValueError(
  2810. "Argument ``gather_list`` must be specified on destination rank."
  2811. )
  2812. elif gather_list:
  2813. raise ValueError(
  2814. "Argument ``gather_list`` must NOT be specified "
  2815. "on non-destination ranks."
  2816. )
  2817. @_exception_logger
  2818. def gather(tensor, gather_list=None, dst=0, group=None, async_op=False):
  2819. """
  2820. Gathers a list of tensors in a single process.
  2821. Args:
  2822. tensor (Tensor): Input tensor.
  2823. gather_list (list[Tensor], optional): List of appropriately-sized
  2824. tensors to use for gathered data (default is None, must be specified
  2825. on the destination rank)
  2826. dst (int, optional): Destination rank on global process group (regardless of ``group`` argument). (default is 0)
  2827. group (ProcessGroup, optional): The process group to work on. If None,
  2828. the default process group will be used.
  2829. async_op (bool, optional): Whether this op should be an async op
  2830. Returns:
  2831. Async work handle, if async_op is set to True.
  2832. None, if not async_op or if not part of the group
  2833. """
  2834. _check_single_tensor(tensor, "tensor")
  2835. # Parameter ``gather_list`` may be left unspecified on non-dst ranks.
  2836. if gather_list:
  2837. _check_tensor_list(gather_list, "gather_list")
  2838. else:
  2839. gather_list = []
  2840. _ensure_all_tensors_same_dtype(tensor, gather_list)
  2841. if _rank_not_in_group(group):
  2842. _warn_not_in_group("gather")
  2843. return
  2844. my_rank = get_rank()
  2845. _validate_output_list_for_rank(my_rank, dst, gather_list)
  2846. output_tensors = [gather_list] if dst == my_rank else []
  2847. input_tensors = [tensor]
  2848. opts = GatherOptions()
  2849. opts.rootRank = dst
  2850. if group is None or group is GroupMember.WORLD:
  2851. default_pg = _get_default_group()
  2852. work = default_pg.gather(output_tensors, input_tensors, opts)
  2853. else:
  2854. group_dst_rank = get_group_rank(group, dst)
  2855. opts.rootRank = group_dst_rank
  2856. work = group.gather(output_tensors, input_tensors, opts)
  2857. if async_op:
  2858. return work
  2859. else:
  2860. work.wait()
  2861. @_exception_logger
  2862. def scatter(tensor, scatter_list=None, src=0, group=None, async_op=False):
  2863. """
  2864. Scatters a list of tensors to all processes in a group.
  2865. Each process will receive exactly one tensor and store its data in the
  2866. ``tensor`` argument.
  2867. Complex tensors are supported.
  2868. Args:
  2869. tensor (Tensor): Output tensor.
  2870. scatter_list (list[Tensor]): List of tensors to scatter (default is
  2871. None, must be specified on the source rank)
  2872. src (int): Source rank on global process group (regardless of ``group`` argument).
  2873. Default is 0
  2874. group (ProcessGroup, optional): The process group to work on. If None,
  2875. the default process group will be used.
  2876. async_op (bool, optional): Whether this op should be an async op
  2877. Returns:
  2878. Async work handle, if async_op is set to True.
  2879. None, if not async_op or if not part of the group
  2880. .. note:: Note that all Tensors in scatter_list must have the same size.
  2881. Example::
  2882. >>> # xdoctest: +SKIP("need process group init")
  2883. >>> # Note: Process group initialization omitted on each rank.
  2884. >>> import torch.distributed as dist
  2885. >>> tensor_size = 2
  2886. >>> t_ones = torch.ones(tensor_size)
  2887. >>> t_fives = torch.ones(tensor_size) * 5
  2888. >>> output_tensor = torch.zeros(tensor_size)
  2889. >>> if dist.get_rank() == 0:
  2890. >>> # Assumes world_size of 2.
  2891. >>> # Only tensors, all of which must be the same size.
  2892. >>> scatter_list = [t_ones, t_fives]
  2893. >>> else:
  2894. >>> scatter_list = None
  2895. >>> dist.scatter(output_tensor, scatter_list, src=0)
  2896. >>> # Rank i gets scatter_list[i]. For example, on rank 1:
  2897. >>> output_tensor
  2898. tensor([5., 5.])
  2899. """
  2900. _check_single_tensor(tensor, "tensor")
  2901. # Parameter ``scatter_list`` may be left unspecified on non-src ranks.
  2902. if scatter_list:
  2903. _check_tensor_list(scatter_list, "scatter_list")
  2904. else:
  2905. scatter_list = []
  2906. _ensure_all_tensors_same_dtype(tensor, scatter_list)
  2907. if _rank_not_in_group(group):
  2908. _warn_not_in_group("scatter")
  2909. return
  2910. scatter_list = [
  2911. t if not t.is_complex() else torch.view_as_real(t) for t in scatter_list
  2912. ]
  2913. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  2914. my_rank = get_rank()
  2915. if src == my_rank:
  2916. if not scatter_list:
  2917. raise ValueError(
  2918. "Argument ``scatter_list`` must be specified on source rank."
  2919. )
  2920. input_tensors = [scatter_list]
  2921. output_tensors = [tensor]
  2922. else:
  2923. if scatter_list:
  2924. raise ValueError(
  2925. "Argument ``scatter_list`` must NOT be specified "
  2926. "on non-source ranks."
  2927. )
  2928. input_tensors = []
  2929. output_tensors = [tensor]
  2930. opts = ScatterOptions()
  2931. opts.rootRank = src
  2932. opts.asyncOp = async_op
  2933. if group is None or group is GroupMember.WORLD:
  2934. default_pg = _get_default_group()
  2935. work = default_pg.scatter(output_tensors, input_tensors, opts)
  2936. else:
  2937. group_src_rank = get_group_rank(group, src)
  2938. opts.rootRank = group_src_rank
  2939. work = group.scatter(output_tensors, input_tensors, opts)
  2940. if async_op:
  2941. return work
  2942. else:
  2943. work.wait()
  2944. @_exception_logger
  2945. def reduce_scatter(output, input_list, op=ReduceOp.SUM, group=None, async_op=False):
  2946. """
  2947. Reduces, then scatters a list of tensors to all processes in a group.
  2948. Args:
  2949. output (Tensor): Output tensor.
  2950. input_list (list[Tensor]): List of tensors to reduce and scatter.
  2951. op (optional): One of the values from
  2952. ``torch.distributed.ReduceOp``
  2953. enum. Specifies an operation used for element-wise reductions.
  2954. group (ProcessGroup, optional): The process group to work on. If None,
  2955. the default process group will be used.
  2956. async_op (bool, optional): Whether this op should be an async op.
  2957. Returns:
  2958. Async work handle, if async_op is set to True.
  2959. None, if not async_op or if not part of the group.
  2960. """
  2961. _check_single_tensor(output, "output")
  2962. _check_tensor_list(input_list, "input_list")
  2963. _ensure_all_tensors_same_dtype(output, input_list)
  2964. if _rank_not_in_group(group):
  2965. _warn_not_in_group("reduce_scatter")
  2966. return
  2967. opts = ReduceScatterOptions()
  2968. opts.reduceOp = op
  2969. if group is None:
  2970. default_pg = _get_default_group()
  2971. work = default_pg.reduce_scatter([output], [input_list], opts)
  2972. else:
  2973. work = group.reduce_scatter([output], [input_list], opts)
  2974. if async_op:
  2975. return work
  2976. else:
  2977. work.wait()
  2978. @_exception_logger
  2979. def reduce_scatter_tensor(output, input, op=ReduceOp.SUM, group=None, async_op=False):
  2980. """
  2981. Reduces, then scatters a tensor to all ranks in a group.
  2982. Args:
  2983. output (Tensor): Output tensor. It should have the same size across all
  2984. ranks.
  2985. input (Tensor): Input tensor to be reduced and scattered. Its size
  2986. should be output tensor size times the world size. The input tensor
  2987. can have one of the following shapes:
  2988. (i) a concatenation of the output tensors along the primary
  2989. dimension, or
  2990. (ii) a stack of the output tensors along the primary dimension.
  2991. For definition of "concatenation", see ``torch.cat()``.
  2992. For definition of "stack", see ``torch.stack()``.
  2993. group (ProcessGroup, optional): The process group to work on. If None,
  2994. the default process group will be used.
  2995. async_op (bool, optional): Whether this op should be an async op.
  2996. Returns:
  2997. Async work handle, if async_op is set to True.
  2998. None, if not async_op or if not part of the group.
  2999. Examples:
  3000. >>> # xdoctest: +SKIP("need process group init")
  3001. >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
  3002. >>> # We have two ranks.
  3003. >>> device = torch.device(f'cuda:{rank}')
  3004. >>> tensor_out = torch.zeros(2, dtype=torch.int64, device=device)
  3005. >>> # Input in concatenation form
  3006. >>> tensor_in = torch.arange(world_size * 2, dtype=torch.int64, device=device)
  3007. >>> tensor_in
  3008. tensor([0, 1, 2, 3], device='cuda:0') # Rank 0
  3009. tensor([0, 1, 2, 3], device='cuda:1') # Rank 1
  3010. >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
  3011. >>> tensor_out
  3012. tensor([0, 2], device='cuda:0') # Rank 0
  3013. tensor([4, 6], device='cuda:1') # Rank 1
  3014. >>> # Input in stack form
  3015. >>> tensor_in = torch.reshape(tensor_in, (world_size, 2))
  3016. >>> tensor_in
  3017. tensor([[0, 1],
  3018. [2, 3]], device='cuda:0') # Rank 0
  3019. tensor([[0, 1],
  3020. [2, 3]], device='cuda:1') # Rank 1
  3021. >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
  3022. >>> tensor_out
  3023. tensor([0, 2], device='cuda:0') # Rank 0
  3024. tensor([4, 6], device='cuda:1') # Rank 1
  3025. .. warning::
  3026. The Gloo backend does not support this API.
  3027. """
  3028. _check_single_tensor(output, "output")
  3029. _check_single_tensor(input, "input")
  3030. if _rank_not_in_group(group):
  3031. _warn_not_in_group("reduce_scatter_tensor")
  3032. return
  3033. opts = ReduceScatterOptions()
  3034. opts.reduceOp = op
  3035. opts.asyncOp = async_op
  3036. group = group or _get_default_group()
  3037. # Check if we are in coalescing context
  3038. # If we are, do not issue single operation, just append a collective representation
  3039. if group in _world.pg_coalesce_state.keys():
  3040. coll = _CollOp(reduce_scatter_tensor, input, output, op, None)
  3041. _world.pg_coalesce_state[group].append(coll)
  3042. if async_op:
  3043. return _IllegalWork()
  3044. else:
  3045. return None
  3046. work = group._reduce_scatter_base(output, input, opts)
  3047. if async_op:
  3048. return work
  3049. else:
  3050. work.wait()
  3051. @deprecated(
  3052. "`torch.distributed._reduce_scatter_base` is a private function and will be deprecated. "
  3053. "Please use `torch.distributed.reduce_scatter_tensor` instead.",
  3054. category=FutureWarning,
  3055. )
  3056. def _reduce_scatter_base(output, input, op=ReduceOp.SUM, group=None, async_op=False):
  3057. """
  3058. Reduces, then scatters a flattened tensor to all processes in a group.
  3059. Args:
  3060. output (Tensor): Output tensor.
  3061. input (Tensor): Input tensor that is of size output tensor size times world size
  3062. group (ProcessGroup, optional): The process group to work on. If None,
  3063. the default process group will be used.
  3064. async_op (bool, optional): Whether this op should be an async op.
  3065. Returns:
  3066. Async work handle, if async_op is set to True.
  3067. None, if not async_op or if not part of the group.
  3068. .. warning::
  3069. `_reduce_scatter_base` is a private function. Users should use
  3070. `reduce_scatter_tensor` instead.
  3071. """
  3072. return reduce_scatter_tensor(output, input, op, group, async_op)
  3073. @_exception_logger
  3074. def all_to_all_single(
  3075. output,
  3076. input,
  3077. output_split_sizes=None,
  3078. input_split_sizes=None,
  3079. group=None,
  3080. async_op=False,
  3081. ):
  3082. """
  3083. Split input tensor and then scatter the split list to all processes in a group.
  3084. Later the received tensors are concatenated from all the processes in the group
  3085. and returned as a single output tensor.
  3086. Complex tensors are supported.
  3087. Args:
  3088. output (Tensor): Gathered concatenated output tensor.
  3089. input (Tensor): Input tensor to scatter.
  3090. output_split_sizes: (list[Int], optional): Output split sizes for dim 0
  3091. if specified None or empty, dim 0 of ``output`` tensor must divide
  3092. equally by ``world_size``.
  3093. input_split_sizes: (list[Int], optional): Input split sizes for dim 0
  3094. if specified None or empty, dim 0 of ``input`` tensor must divide
  3095. equally by ``world_size``.
  3096. group (ProcessGroup, optional): The process group to work on. If None,
  3097. the default process group will be used.
  3098. async_op (bool, optional): Whether this op should be an async op.
  3099. Returns:
  3100. Async work handle, if async_op is set to True.
  3101. None, if not async_op or if not part of the group.
  3102. .. warning::
  3103. `all_to_all_single` is experimental and subject to change.
  3104. Examples:
  3105. >>> # xdoctest: +SKIP("Undefined rank")
  3106. >>> input = torch.arange(4) + rank * 4
  3107. >>> input
  3108. tensor([0, 1, 2, 3]) # Rank 0
  3109. tensor([4, 5, 6, 7]) # Rank 1
  3110. tensor([8, 9, 10, 11]) # Rank 2
  3111. tensor([12, 13, 14, 15]) # Rank 3
  3112. >>> output = torch.empty([4], dtype=torch.int64)
  3113. >>> dist.all_to_all_single(output, input)
  3114. >>> output
  3115. tensor([0, 4, 8, 12]) # Rank 0
  3116. tensor([1, 5, 9, 13]) # Rank 1
  3117. tensor([2, 6, 10, 14]) # Rank 2
  3118. tensor([3, 7, 11, 15]) # Rank 3
  3119. >>> # Essentially, it is similar to following operation:
  3120. >>> scatter_list = list(input.chunk(world_size))
  3121. >>> gather_list = list(output.chunk(world_size))
  3122. >>> for i in range(world_size):
  3123. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)
  3124. >>> # Another example with uneven split
  3125. >>> input
  3126. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  3127. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  3128. tensor([20, 21, 22, 23, 24]) # Rank 2
  3129. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  3130. >>> input_splits
  3131. [2, 2, 1, 1] # Rank 0
  3132. [3, 2, 2, 2] # Rank 1
  3133. [2, 1, 1, 1] # Rank 2
  3134. [2, 2, 2, 1] # Rank 3
  3135. >>> output_splits
  3136. [2, 3, 2, 2] # Rank 0
  3137. [2, 2, 1, 2] # Rank 1
  3138. [1, 2, 1, 2] # Rank 2
  3139. [1, 2, 1, 1] # Rank 3
  3140. >>> output = ...
  3141. >>> dist.all_to_all_single(output, input, output_splits, input_splits)
  3142. >>> output
  3143. tensor([ 0, 1, 10, 11, 12, 20, 21, 30, 31]) # Rank 0
  3144. tensor([ 2, 3, 13, 14, 22, 32, 33]) # Rank 1
  3145. tensor([ 4, 15, 16, 23, 34, 35]) # Rank 2
  3146. tensor([ 5, 17, 18, 24, 36]) # Rank 3
  3147. >>> # Another example with tensors of torch.cfloat type.
  3148. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
  3149. >>> input
  3150. tensor([1+1j, 2+2j, 3+3j, 4+4j]) # Rank 0
  3151. tensor([5+5j, 6+6j, 7+7j, 8+8j]) # Rank 1
  3152. tensor([9+9j, 10+10j, 11+11j, 12+12j]) # Rank 2
  3153. tensor([13+13j, 14+14j, 15+15j, 16+16j]) # Rank 3
  3154. >>> output = torch.empty([4], dtype=torch.int64)
  3155. >>> dist.all_to_all_single(output, input)
  3156. >>> output
  3157. tensor([1+1j, 5+5j, 9+9j, 13+13j]) # Rank 0
  3158. tensor([2+2j, 6+6j, 10+10j, 14+14j]) # Rank 1
  3159. tensor([3+3j, 7+7j, 11+11j, 15+15j]) # Rank 2
  3160. tensor([4+4j, 8+8j, 12+12j, 16+16j]) # Rank 3
  3161. """
  3162. if _rank_not_in_group(group):
  3163. _warn_not_in_group("all_to_all_single")
  3164. return
  3165. opts = AllToAllOptions()
  3166. _check_single_tensor(output, "output")
  3167. _check_single_tensor(input, "input")
  3168. _ensure_all_tensors_same_dtype(output, input)
  3169. if input.is_complex():
  3170. input = torch.view_as_real(input)
  3171. if output.is_complex():
  3172. output = torch.view_as_real(output)
  3173. output_split_sizes = [] if output_split_sizes is None else output_split_sizes
  3174. input_split_sizes = [] if input_split_sizes is None else input_split_sizes
  3175. if group is None:
  3176. default_pg = _get_default_group()
  3177. work = default_pg.alltoall_base(
  3178. output, input, output_split_sizes, input_split_sizes, opts
  3179. )
  3180. else:
  3181. work = group.alltoall_base(
  3182. output, input, output_split_sizes, input_split_sizes, opts
  3183. )
  3184. if async_op:
  3185. return work
  3186. else:
  3187. work.wait()
  3188. @_exception_logger
  3189. def all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False):
  3190. """
  3191. Scatters list of input tensors to all processes in a group and return gathered list of tensors in output list.
  3192. Complex tensors are supported.
  3193. Args:
  3194. output_tensor_list (list[Tensor]): List of tensors to be gathered one
  3195. per rank.
  3196. input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
  3197. group (ProcessGroup, optional): The process group to work on. If None,
  3198. the default process group will be used.
  3199. async_op (bool, optional): Whether this op should be an async op.
  3200. Returns:
  3201. Async work handle, if async_op is set to True.
  3202. None, if not async_op or if not part of the group.
  3203. .. warning::
  3204. `all_to_all` is experimental and subject to change.
  3205. Examples:
  3206. >>> # xdoctest: +SKIP("Undefined rank")
  3207. >>> input = torch.arange(4) + rank * 4
  3208. >>> input = list(input.chunk(4))
  3209. >>> input
  3210. [tensor([0]), tensor([1]), tensor([2]), tensor([3])] # Rank 0
  3211. [tensor([4]), tensor([5]), tensor([6]), tensor([7])] # Rank 1
  3212. [tensor([8]), tensor([9]), tensor([10]), tensor([11])] # Rank 2
  3213. [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3
  3214. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  3215. >>> dist.all_to_all(output, input)
  3216. >>> output
  3217. [tensor([0]), tensor([4]), tensor([8]), tensor([12])] # Rank 0
  3218. [tensor([1]), tensor([5]), tensor([9]), tensor([13])] # Rank 1
  3219. [tensor([2]), tensor([6]), tensor([10]), tensor([14])] # Rank 2
  3220. [tensor([3]), tensor([7]), tensor([11]), tensor([15])] # Rank 3
  3221. >>> # Essentially, it is similar to following operation:
  3222. >>> scatter_list = input
  3223. >>> gather_list = output
  3224. >>> for i in range(world_size):
  3225. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src=i)
  3226. >>> input
  3227. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  3228. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  3229. tensor([20, 21, 22, 23, 24]) # Rank 2
  3230. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  3231. >>> input_splits
  3232. [2, 2, 1, 1] # Rank 0
  3233. [3, 2, 2, 2] # Rank 1
  3234. [2, 1, 1, 1] # Rank 2
  3235. [2, 2, 2, 1] # Rank 3
  3236. >>> output_splits
  3237. [2, 3, 2, 2] # Rank 0
  3238. [2, 2, 1, 2] # Rank 1
  3239. [1, 2, 1, 2] # Rank 2
  3240. [1, 2, 1, 1] # Rank 3
  3241. >>> input = list(input.split(input_splits))
  3242. >>> input
  3243. [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])] # Rank 0
  3244. [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1
  3245. [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])] # Rank 2
  3246. [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])] # Rank 3
  3247. >>> output = ...
  3248. >>> dist.all_to_all(output, input)
  3249. >>> output
  3250. [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])] # Rank 0
  3251. [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])] # Rank 1
  3252. [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])] # Rank 2
  3253. [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])] # Rank 3
  3254. >>> # Another example with tensors of torch.cfloat type.
  3255. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j)
  3256. >>> input = list(input.chunk(4))
  3257. >>> input
  3258. [tensor([1+1j]), tensor([2+2j]), tensor([3+3j]), tensor([4+4j])] # Rank 0
  3259. [tensor([5+5j]), tensor([6+6j]), tensor([7+7j]), tensor([8+8j])] # Rank 1
  3260. [tensor([9+9j]), tensor([10+10j]), tensor([11+11j]), tensor([12+12j])] # Rank 2
  3261. [tensor([13+13j]), tensor([14+14j]), tensor([15+15j]), tensor([16+16j])] # Rank 3
  3262. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  3263. >>> dist.all_to_all(output, input)
  3264. >>> output
  3265. [tensor([1+1j]), tensor([5+5j]), tensor([9+9j]), tensor([13+13j])] # Rank 0
  3266. [tensor([2+2j]), tensor([6+6j]), tensor([10+10j]), tensor([14+14j])] # Rank 1
  3267. [tensor([3+3j]), tensor([7+7j]), tensor([11+11j]), tensor([15+15j])] # Rank 2
  3268. [tensor([4+4j]), tensor([8+8j]), tensor([12+12j]), tensor([16+16j])] # Rank 3
  3269. """
  3270. if _rank_not_in_group(group):
  3271. _warn_not_in_group("all_to_all")
  3272. return
  3273. opts = AllToAllOptions()
  3274. _check_tensor_list(output_tensor_list, "output_tensor_list")
  3275. _check_tensor_list(input_tensor_list, "input_tensor_list")
  3276. _ensure_all_tensors_same_dtype(output_tensor_list, input_tensor_list)
  3277. input_tensor_list = [
  3278. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  3279. ]
  3280. output_tensor_list = [
  3281. t if not t.is_complex() else torch.view_as_real(t) for t in output_tensor_list
  3282. ]
  3283. if group is None:
  3284. default_pg = _get_default_group()
  3285. work = default_pg.alltoall(output_tensor_list, input_tensor_list, opts)
  3286. else:
  3287. work = group.alltoall(output_tensor_list, input_tensor_list, opts)
  3288. if async_op:
  3289. return work
  3290. else:
  3291. work.wait()
  3292. @_exception_logger
  3293. def barrier(group=GroupMember.WORLD, async_op=False, device_ids=None):
  3294. """
  3295. Synchronize all processes.
  3296. This collective blocks processes until the whole group enters this function,
  3297. if async_op is False, or if async work handle is called on wait().
  3298. Args:
  3299. group (ProcessGroup, optional): The process group to work on. If None,
  3300. the default process group will be used.
  3301. async_op (bool, optional): Whether this op should be an async op
  3302. device_ids ([int], optional): List of device/GPU ids.
  3303. Returns:
  3304. Async work handle, if async_op is set to True.
  3305. None, if not async_op or if not part of the group
  3306. .. note:: `ProcessGroupNCCL` now relies on stream synchronization instead of
  3307. device synchronization to block the CPU. Thus, please do not assume that
  3308. `barrier()` would perform a device synchronization.
  3309. """
  3310. if _rank_not_in_group(group):
  3311. _warn_not_in_group("barrier")
  3312. return
  3313. opts = BarrierOptions()
  3314. opts.device = _get_pg_default_device(group)
  3315. if device_ids is not None:
  3316. if isinstance(device_ids, list):
  3317. opts.device_ids = device_ids
  3318. else:
  3319. raise TypeError(
  3320. "Invalid function argument: device_ids type should be List[int]"
  3321. )
  3322. if group is None:
  3323. default_pg = _get_default_group()
  3324. work = default_pg.barrier(opts=opts)
  3325. else:
  3326. work = group.barrier(opts=opts)
  3327. if async_op:
  3328. return work
  3329. else:
  3330. work.wait()
  3331. def monitored_barrier(group=GroupMember.WORLD, timeout=None, wait_all_ranks=False):
  3332. """
  3333. Synchronize processes similar to ``torch.distributed.barrier``, but consider a configurable timeout.
  3334. It is able to report ranks that did not pass this barrier within the provided timeout.
  3335. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0.
  3336. Rank 0 will block until all send /recv from other ranks are processed, and will report
  3337. failures for ranks that failed to respond in time. Note that if one rank does not reach the
  3338. monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier.
  3339. This collective will block all processes/ranks in the group, until the
  3340. whole group exits the function successfully, making it useful for debugging
  3341. and synchronizing. However, it can have a performance impact and should only
  3342. be used for debugging or scenarios that require full synchronization points
  3343. on the host-side. For debugging purposes, this barrier can be inserted
  3344. before the application's collective calls to check if any ranks are
  3345. desynchronized.
  3346. .. note:: Note that this collective is only supported with the GLOO backend.
  3347. Args:
  3348. group (ProcessGroup, optional): The process group to work on. If
  3349. ``None``, the default process group will be used.
  3350. timeout (datetime.timedelta, optional): Timeout for monitored_barrier.
  3351. If ``None``, the default process group timeout will be used.
  3352. wait_all_ranks (bool, optional): Whether to collect all failed ranks or
  3353. not. By default, this is ``False`` and ``monitored_barrier`` on rank 0
  3354. will throw on the first failed rank it encounters in order to fail
  3355. fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will
  3356. collect all failed ranks and throw an error containing information
  3357. about all failed ranks.
  3358. Returns:
  3359. ``None``.
  3360. Example::
  3361. >>> # xdoctest: +SKIP("need process group init")
  3362. >>> # Note: Process group initialization omitted on each rank.
  3363. >>> import torch.distributed as dist
  3364. >>> if dist.get_rank() != 1:
  3365. >>> dist.monitored_barrier() # Raises exception indicating that
  3366. >>> # rank 1 did not call into monitored_barrier.
  3367. >>> # Example with wait_all_ranks=True
  3368. >>> if dist.get_rank() == 0:
  3369. >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception
  3370. >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into
  3371. >>> # monitored_barrier.
  3372. """
  3373. # Need to call rank not in group before using the group, otherwise
  3374. # "Invalid process group" error is raised.
  3375. if _rank_not_in_group(group):
  3376. _warn_not_in_group("monitored_barrier")
  3377. return
  3378. if get_backend(group) != Backend.GLOO:
  3379. raise ValueError("monitored_barrier is only implemented for GLOO backend.")
  3380. if timeout is None:
  3381. timeout = _get_default_timeout(get_backend(group))
  3382. elif isinstance(timeout, float):
  3383. # TODO(whc) aparently some existing test case for monitored_barrier passes in a timeout in float format?
  3384. warnings.warn(
  3385. "Please specify timeout arg as a timedelta. "
  3386. f"Converting current value of {timeout} assuming it represents seconds",
  3387. )
  3388. timeout = timedelta(seconds=timeout)
  3389. _check_valid_timeout(timeout)
  3390. group_to_use = _get_default_group() if group is None else group
  3391. return group_to_use.monitored_barrier(timeout, wait_all_ranks=wait_all_ranks)
  3392. def _create_process_group_wrapper(
  3393. wrapped_pg: torch._C._distributed_c10d.Backend,
  3394. store_prefix: str,
  3395. store: Store,
  3396. rank: int,
  3397. world_size: int,
  3398. timeout: timedelta = default_pg_timeout,
  3399. ):
  3400. assert _GLOO_AVAILABLE, "ProcessGroupWrapper unsupported without GLOO backend."
  3401. # (whc) this appears to be just for the gloo backend? if so, `default_pg_timeout` is appropriate...
  3402. # Create a separate prefix store for the helper process group.
  3403. prefix = f"{PG_WRAPPER_STORE_PREFIX}:{store_prefix}"
  3404. store = PrefixStore(prefix, store)
  3405. helper_pg = ProcessGroupGloo(store, rank, world_size, timeout=timeout)
  3406. # Wrap the underlying pg with ProcessGroupWrapper.
  3407. wrapped_pg = _ProcessGroupWrapper(wrapped_pg, helper_pg)
  3408. return wrapped_pg
  3409. # helper function for deterministically hashing a list of ranks
  3410. def _hash_ranks(ranks: List[int]):
  3411. return hashlib.sha1(bytes("_".join(map(str, ranks)), "utf-8")).hexdigest()
  3412. # Takes a list of ranks and computes an integer color
  3413. def _process_group_color(ranks: List[int]) -> int:
  3414. # Convert our hash to an int, but avoid negative numbers by shifting a bit.
  3415. return int(_hash_ranks(ranks), 16) % (sys.maxsize >> 1)
  3416. def _process_group_name(ranks, use_hashed_name):
  3417. global _world
  3418. if use_hashed_name:
  3419. pg_name = _hash_ranks(ranks)
  3420. while pg_name in _world.pg_names.values():
  3421. pg_name = hashlib.sha1(bytes(pg_name + "_", "utf-8")).hexdigest()
  3422. else:
  3423. pg_name = str(_world.group_count)
  3424. _world.group_count += 1
  3425. return pg_name
  3426. def _get_backend_from_str(backend: Optional[str] = None) -> Backend:
  3427. # Default to the same backend as the global process group
  3428. # if backend is not specified.
  3429. if not backend:
  3430. backend = get_backend(_get_default_group())
  3431. return Backend(backend)
  3432. @_time_logger
  3433. def new_group(ranks=None, timeout=None, backend=None, pg_options=None, use_local_synchronization=False, group_desc=None):
  3434. """
  3435. Create a new distributed group.
  3436. This function requires that all processes in the main group (i.e. all
  3437. processes that are part of the distributed job) enter this function, even
  3438. if they are not going to be members of the group. Additionally, groups
  3439. should be created in the same order in all processes.
  3440. .. warning::
  3441. Using multiple process groups with the ``NCCL`` backend concurrently
  3442. is not safe and the user should perform explicit synchronization in
  3443. their application to ensure only one process group is used at a time.
  3444. This means collectives from one process group should have completed
  3445. execution on the device (not just enqueued since CUDA execution is
  3446. async) before collectives from another process group are enqueued.
  3447. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  3448. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  3449. -multiple-nccl-communicators-concurrently>`_ for more details.
  3450. Args:
  3451. ranks (list[int]): List of ranks of group members. If ``None``, will be
  3452. set to all ranks. Default is ``None``.
  3453. timeout (timedelta, optional): see `init_process_group` for details and default value.
  3454. backend (str or Backend, optional): The backend to use. Depending on
  3455. build-time configurations, valid values are ``gloo`` and ``nccl``.
  3456. By default uses the same backend as the global group. This field
  3457. should be given as a lowercase string (e.g., ``"gloo"``), which can
  3458. also be accessed via :class:`Backend` attributes (e.g.,
  3459. ``Backend.GLOO``). If ``None`` is passed in, the backend
  3460. corresponding to the default process group will be used. Default is
  3461. ``None``.
  3462. pg_options (ProcessGroupOptions, optional): process group options
  3463. specifying what additional options need to be passed in during
  3464. the construction of specific process groups. i.e. for the ``nccl``
  3465. backend, ``is_high_priority_stream`` can be specified so that
  3466. process group can pick up high priority cuda streams.
  3467. use_local_synchronization (bool, optional): perform a group-local
  3468. barrier at the end of the process group creation. This is different
  3469. in that non-member ranks don't need to call into API and don't
  3470. join the barrier.
  3471. group_desc (str, optional): a string to describe the process group.
  3472. Returns:
  3473. A handle of distributed group that can be given to collective calls or
  3474. GroupMember.NON_GROUP_MEMBER if the rank is not part of ``ranks``.
  3475. N.B. use_local_synchronization doesn't work with MPI.
  3476. N.B. While use_local_synchronization=True can be significantly faster with larger
  3477. clusters and small process groups, care must be taken since it changes cluster behavior
  3478. as non-member ranks don't join the group barrier().
  3479. N.B. use_local_synchronization=True can lead to deadlocks when each rank creates
  3480. multiple overlaping process groups. To avoid that, make sure all ranks follow the
  3481. same global creation order.
  3482. """
  3483. return _new_group_with_tag(
  3484. ranks,
  3485. timeout,
  3486. backend,
  3487. pg_options,
  3488. None,
  3489. use_local_synchronization=use_local_synchronization,
  3490. group_desc=group_desc,
  3491. )
  3492. def _new_group_with_tag(
  3493. ranks=None,
  3494. timeout=None,
  3495. backend=None,
  3496. pg_options=None,
  3497. pg_tag=None,
  3498. use_local_synchronization=False,
  3499. group_desc=None
  3500. ):
  3501. """
  3502. Variant of ``new_group`` that exposes tag creation.
  3503. :: N.B. The mechanism is experimental and tied to the functional collectives effort, see
  3504. ``torch.distributed._functional_collectives`` for reference on how to use it.
  3505. """
  3506. global _world
  3507. default_pg = _get_default_group()
  3508. default_backend, default_store = _world.pg_map[default_pg]
  3509. global_rank = default_pg.rank()
  3510. global_world_size = default_pg.size()
  3511. # Default to the same backend as the global process group
  3512. # if the backend is not specified.
  3513. if not backend:
  3514. backend = default_backend
  3515. backend = Backend(backend)
  3516. # this timeout defaulting/validation is used for all the new_groups/new_subgroups variants,
  3517. # which may just pass their timeout value (or None)
  3518. if timeout is None:
  3519. timeout = _get_default_timeout(backend)
  3520. _check_valid_timeout(timeout)
  3521. if use_local_synchronization:
  3522. # MPI backend doesn't have have a way for us to perform a partial sync
  3523. if backend == Backend.MPI:
  3524. raise ValueError("MPI backend doesn't support use_local_synchronization=True")
  3525. if ranks is not None and get_rank() not in ranks:
  3526. return None
  3527. # checks the input ranks
  3528. if ranks is not None:
  3529. ranks = sorted(ranks)
  3530. group_world_size = len(ranks)
  3531. if group_world_size > global_world_size:
  3532. raise ValueError(
  3533. "the new group's world size should be less or "
  3534. "equal to the world size set by "
  3535. "init_process_group"
  3536. )
  3537. # check ranks' sanity
  3538. for rank in ranks:
  3539. if rank < 0 or rank >= global_world_size:
  3540. raise ValueError(
  3541. "The new group's rank should be within "
  3542. "the world_size set by init_process_group"
  3543. )
  3544. if global_rank in ranks:
  3545. group_rank = ranks.index(global_rank)
  3546. else:
  3547. group_rank = None
  3548. else:
  3549. ranks = list(range(global_world_size))
  3550. group_world_size = global_world_size
  3551. group_rank = global_rank
  3552. group_name = _process_group_name(ranks, use_hashed_name=use_local_synchronization)
  3553. pg, pg_store = _new_process_group_helper(
  3554. group_world_size,
  3555. group_rank,
  3556. ranks,
  3557. backend,
  3558. default_store,
  3559. group_name,
  3560. pg_options=pg_options,
  3561. timeout=timeout,
  3562. pg_tag=pg_tag,
  3563. group_desc=group_desc
  3564. )
  3565. # Create the global rank to group rank mapping
  3566. _world.pg_group_ranks[pg] = {
  3567. global_rank: group_rank for group_rank, global_rank in enumerate(ranks)
  3568. }
  3569. if _is_barrier_after_init() == 1:
  3570. # barrier at the end to ensure that once we return from this method, all
  3571. # process groups including global variables (if any) are updated
  3572. # correctly on all ranks.
  3573. # Update 04/2023: for large-scale runs, this barrier (esp. store-based
  3574. # barrier) may be costly and/or unscalable. Also, in a lot of cases,
  3575. # these barriers may be unnecessary, as proven by a green CI after
  3576. # removal. An environment variable `TORCH_DIST_INIT_BARRIER` has been
  3577. # added which enables this barrier only when set to 1.
  3578. logger.info(
  3579. "Performing barrier after ProcessGroup initialization since "
  3580. "TORCH_DIST_INIT_BARRIER = 1"
  3581. )
  3582. if backend == Backend.MPI:
  3583. # MPI doesn't have store.
  3584. barrier()
  3585. else:
  3586. barrier_store = pg_store if use_local_synchronization else default_store
  3587. world_size = len(ranks) if use_local_synchronization else get_world_size()
  3588. # Use store based barrier here since barrier() used a bunch of
  3589. # default devices and messes up NCCL internal state.
  3590. _store_based_barrier(global_rank, barrier_store, group_name, world_size, timeout)
  3591. return pg
  3592. def new_subgroups(
  3593. group_size=None,
  3594. group=None,
  3595. timeout=None,
  3596. backend=None,
  3597. pg_options=None,
  3598. group_desc=None,
  3599. ):
  3600. """
  3601. Create subgroups of equal size.
  3602. By default, it creates intra-machine subgroups,
  3603. where each of which contains all the ranks of a machine, based on the assumption
  3604. that each machine has the same number of devices.
  3605. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  3606. It requires that all processes in the main group (i.e. all
  3607. processes that are part of the distributed job) enter this function, even
  3608. if they are not going to be members of the group.
  3609. .. warning::
  3610. If ``group_size`` is passed in, the world size must be divisible by ``group_size``.
  3611. If no ``group_size`` is passed in, it believe that you are creating a group based
  3612. on CUDA and determining the group size by number of CUDA devices, and if not all
  3613. the machines have the same number of devices, the subgroup division will be
  3614. different across nodes and can cause unexpected behaviors. Therefore, if you are
  3615. creating a subgroup that does not depend on CUDA (such as Gloo on CPU), please
  3616. pass in ``group_size`` correctly.
  3617. .. warning::
  3618. Using multiple process groups with the ``NCCL`` backend concurrently
  3619. is not safe and the user should perform explicit synchronization in
  3620. their application to ensure only one process group is used at a time.
  3621. This means collectives from one process group should have completed
  3622. execution on the device (not just enqueued since CUDA execution is
  3623. async) before collectives from another process group are enqueued.
  3624. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  3625. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  3626. -multiple-nccl-communicators-concurrently>`_ for more details.
  3627. Args:
  3628. group_size (int, optional): The size of each subgroup. If ``None``,
  3629. the default subgroup size is equal to the number of devices on each machine,
  3630. based on the assumption that each machine has exactly the same
  3631. number of devices. Default is ``None``.
  3632. timeout (timedelta, optional): see `init_process_group` for details and default value.
  3633. backend (str or Backend, optional): The backend to use. Depending on
  3634. build-time configurations, valid values are ``gloo`` and ``nccl``.
  3635. By default uses the same backend as the global group. This field
  3636. should be given as a lowercase string (e.g., ``"gloo"``), which can
  3637. also be accessed via :class:`Backend` attributes (e.g.,
  3638. ``Backend.GLOO``). If ``None`` is passed in, the backend
  3639. corresponding to the default process group will be used. Default is
  3640. ``None``.
  3641. pg_options (ProcessGroupOptions, optional): process group options
  3642. specifying what additional options need to be passed in during
  3643. the construction of specific process groups. i.e. for the ``nccl``
  3644. backend, ``is_high_priority_stream`` can be specified so that
  3645. process group can pick up high priority cuda streams.
  3646. group_desc (str, optional): A string describing the group. Each subgroup will
  3647. inherit its group_desc
  3648. Returns:
  3649. The subgroup containing the current rank, and all the subgroups used for cleanup.
  3650. Examples:
  3651. >>> # Create intra-machine subgroups.
  3652. >>> # xdoctest: +SKIP("need process group init")
  3653. >>> cur_subgroup, subgroups = dist.new_subgroups()
  3654. >>> # Allreduce within the machine.
  3655. >>> rank = dist.get_rank()
  3656. >>> tensor = torch.ones(1, device=rank) * rank
  3657. >>> dist.all_reduce(tensor, group=cur_subgroup)
  3658. >>> tensor
  3659. tensor([28]) # Assume 8 CUDA devices per machine. 28 is sum(range(8)).
  3660. >>> # Cleanup.
  3661. >>> for subgroup in subgroups:
  3662. >>> dist.destroy_process_group(subgroup)
  3663. """
  3664. if group_size is None:
  3665. if not torch.cuda.is_available():
  3666. raise ValueError("Default group size only takes effect when CUDA is available."
  3667. "If your subgroup using a backend that does not depend on CUDA,"
  3668. "please pass in 'group_size' correctly.")
  3669. group_size = torch.cuda.device_count()
  3670. if group_size <= 0:
  3671. raise ValueError(f"The arg 'group_size' ({group_size}) must be positive")
  3672. world_size = get_world_size()
  3673. if world_size < group_size:
  3674. raise ValueError(f"The arg 'group_size' ({group_size}) must not exceed the world size ({world_size})")
  3675. if world_size % group_size != 0:
  3676. raise ValueError("The world size must be divisible by 'group_size'")
  3677. subgroups = []
  3678. cur_subgroup = None
  3679. for subgroup_id in range(world_size // group_size):
  3680. start_rank = subgroup_id * group_size
  3681. end_rank = start_rank + group_size
  3682. ranks_in_subgroup = list(range(start_rank, end_rank))
  3683. subgroup = new_group(
  3684. ranks=ranks_in_subgroup,
  3685. timeout=timeout,
  3686. backend=backend,
  3687. pg_options=pg_options,
  3688. group_desc=group_desc,
  3689. )
  3690. subgroups.append(subgroup)
  3691. rank = get_rank()
  3692. if rank in ranks_in_subgroup:
  3693. cur_subgroup = subgroup
  3694. logger.info(
  3695. "Rank %s is assigned to subgroup %s",
  3696. rank, ranks_in_subgroup
  3697. )
  3698. return cur_subgroup, subgroups
  3699. def new_subgroups_by_enumeration(
  3700. ranks_per_subgroup_list,
  3701. timeout=None,
  3702. backend=None,
  3703. pg_options=None,
  3704. group_desc=None,
  3705. ):
  3706. """
  3707. Create subgroups by dividing the global world.
  3708. The division is specified by a nested list of ranks. The subgroups cannot have
  3709. overlap, and some ranks may not have to be in any subgroup.
  3710. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  3711. It requires that all processes in the main group (i.e. all
  3712. processes that are part of the distributed job) enter this function, even
  3713. if they are not going to be members of the group.
  3714. .. warning::
  3715. Using multiple process groups with the ``NCCL`` backend concurrently
  3716. is not safe and the user should perform explicit synchronization in
  3717. their application to ensure only one process group is used at a time.
  3718. This means collectives from one process group should have completed
  3719. execution on the device (not just enqueued since CUDA execution is
  3720. async) before collectives from another process group are enqueued.
  3721. See `Using multiple NCCL communicators concurrently <https://docs.nvid
  3722. ia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using
  3723. -multiple-nccl-communicators-concurrently>`_ for more details.
  3724. Args:
  3725. ranks_per_subgroup_list (list[list[int]]): A nested list of ranks of
  3726. group members.
  3727. timeout (timedelta, optional): see `init_process_group` for details and default value.
  3728. backend (str or Backend, optional): The backend to use. Depending on
  3729. build-time configurations, valid values are ``gloo`` and ``nccl``.
  3730. By default uses the same backend as the global group. This field
  3731. should be given as a lowercase string (e.g., ``"gloo"``), which can
  3732. also be accessed via :class:`Backend` attributes (e.g.,
  3733. ``Backend.GLOO``). If ``None`` is passed in, the backend
  3734. corresponding to the default process group will be used. Default is
  3735. ``None``.
  3736. pg_options (ProcessGroupOptions, optional): process group options
  3737. specifying what additional options need to be passed in during
  3738. the construction of specific process groups. i.e. for the ``nccl``
  3739. backend, ``is_high_priority_stream`` can be specified so that
  3740. process group can pick up high priority cuda streams.
  3741. group_desc (str, optional): A string describing the group. Each subgroup will
  3742. inherit its group_desc.
  3743. Returns:
  3744. The subgroup containing the current rank, and all the subgroups used for cleanup.
  3745. Examples:
  3746. >>> # Create two subgroups, where each has 2 processes.
  3747. >>> # xdoctest: +SKIP("need process group init")
  3748. >>> cur_subgroup, subgroups = dist.new_subgroups(ranks=[[0, 2], [1, 3]])
  3749. >>> rank = dist.get_rank()
  3750. >>> tensor = torch.ones(1, device=rank) * rank
  3751. >>> dist.all_reduce(tensor, group=cur_subgroup)
  3752. >>> tensor
  3753. tensor([2]) # Subgroup 0: ranks 0 and 2
  3754. tensor([4]) # Subgroup 1: ranks 1 and 3
  3755. """
  3756. if ranks_per_subgroup_list is None or len(ranks_per_subgroup_list) == 0:
  3757. raise ValueError("The arg 'ranks_per_subgroup_list' cannot be empty")
  3758. subgroups = []
  3759. cur_subgroup = None
  3760. # Create a mapping from rank to subgroup to check if there is any subgroup overlap.
  3761. rank_to_ranks_dict = {} # type: ignore[var-annotated]
  3762. for ranks in ranks_per_subgroup_list:
  3763. subgroup = new_group(
  3764. ranks=ranks,
  3765. timeout=timeout,
  3766. backend=backend,
  3767. pg_options=pg_options,
  3768. group_desc=group_desc,
  3769. )
  3770. subgroups.append(subgroup)
  3771. my_rank = get_rank()
  3772. for rank in ranks:
  3773. if rank in rank_to_ranks_dict:
  3774. raise ValueError(
  3775. f"Rank {rank} has appeared in both subgroup {rank_to_ranks_dict[rank]} and {ranks}"
  3776. )
  3777. rank_to_ranks_dict[rank] = ranks
  3778. if my_rank == rank:
  3779. cur_subgroup = subgroup
  3780. logger.info("Rank %s is assigned to subgroup %s", rank, ranks)
  3781. return cur_subgroup, subgroups
  3782. def _find_pg_by_ranks_and_tag(tag: str, ranks: List[int]) -> Optional[ProcessGroup]:
  3783. if len(tag) > 0 and not tag.startswith("ptd:") and not tag.startswith("user:"):
  3784. tag = f"user:{tag}"
  3785. for group in _world.tags_to_pg.get(tag, []):
  3786. if group.size() != len(ranks):
  3787. continue
  3788. group_ranks = get_process_group_ranks(group)
  3789. good = all(r in group_ranks for r in ranks)
  3790. if good:
  3791. return group
  3792. return None
  3793. def _find_or_create_pg_by_ranks_and_tag(tag: str, ranks: List[int], stride: int) -> ProcessGroup:
  3794. assert len(ranks) % stride == 0, f"Ranks length ({len(ranks)}) must be divisible by stride ({stride})"
  3795. my_rank = get_rank()
  3796. my_ranks = None
  3797. if stride == len(ranks):
  3798. my_ranks = ranks.copy()
  3799. assert my_rank in my_ranks, "rankset doesn't include the current node"
  3800. else:
  3801. for i in range(0, len(ranks), stride):
  3802. rank_set = ranks[i : i + stride]
  3803. if my_rank in rank_set:
  3804. my_ranks = rank_set
  3805. assert my_ranks is not None, "rankset doesn't include the current node"
  3806. my_ranks.sort()
  3807. pg = _find_pg_by_ranks_and_tag(tag, my_ranks)
  3808. if pg is not None:
  3809. return pg
  3810. if tag == "":
  3811. raise ValueError("Cannot automatically create PG with empty tag")
  3812. # TODO copy settings and timeout from default PG
  3813. return _new_group_with_tag(my_ranks, pg_tag=tag)
  3814. def _get_group_tag(pg: ProcessGroup) -> str:
  3815. """Return the tag associated with ``pg``."""
  3816. tag = _world.pg_to_tag[pg]
  3817. if tag.startswith("user:"):
  3818. tag = tag[5:]
  3819. return tag
  3820. def _get_process_group_name(pg: ProcessGroup) -> str:
  3821. return _world.pg_names.get(pg, "None")
  3822. def _get_process_group_store(pg: ProcessGroup) -> Store:
  3823. return _world.pg_map[pg][1]
  3824. # This ops are not friendly to TorchDynamo. So, we decide to disallow these ops
  3825. # in FX graph, allowing them to run them on eager, with torch.compile.
  3826. dynamo_unsupported_distributed_c10d_ops = [
  3827. recv,
  3828. all_gather_object,
  3829. all_gather_coalesced,
  3830. all_to_all_single,
  3831. all_reduce,
  3832. gather_object,
  3833. all_to_all,
  3834. all_reduce_coalesced,
  3835. gather,
  3836. send_object_list,
  3837. recv_object_list,
  3838. broadcast_object_list,
  3839. barrier,
  3840. scatter,
  3841. scatter_object_list,
  3842. reduce,
  3843. all_gather,
  3844. reduce_scatter,
  3845. all_gather_into_tensor,
  3846. broadcast,
  3847. reduce_scatter_tensor,
  3848. send,
  3849. ]