distributed_c10d.py 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354
  1. # mypy: allow-untyped-defs
  2. """Distributed Collective Communication (c10d)."""
  3. import collections.abc
  4. import contextlib
  5. import copy
  6. import ctypes
  7. import hashlib
  8. import io
  9. import itertools
  10. import logging
  11. import os
  12. import pickle
  13. import sys
  14. import time
  15. import warnings
  16. from collections import namedtuple
  17. from collections.abc import Callable
  18. from datetime import timedelta
  19. from typing import Any, NewType, TYPE_CHECKING
  20. from typing_extensions import deprecated
  21. import torch
  22. from torch._C import _DistStoreError as DistStoreError
  23. from torch._C._distributed_c10d import (
  24. _DistributedBackendOptions,
  25. _register_process_group,
  26. _resolve_process_group,
  27. _unregister_all_process_groups,
  28. _unregister_process_group,
  29. AllgatherOptions,
  30. AllreduceCoalescedOptions,
  31. AllreduceOptions,
  32. AllToAllOptions,
  33. BarrierOptions,
  34. BroadcastOptions,
  35. DebugLevel,
  36. GatherOptions,
  37. get_debug_level,
  38. PrefixStore,
  39. ProcessGroup,
  40. ReduceOp,
  41. ReduceOptions,
  42. ReduceScatterOptions,
  43. ScatterOptions,
  44. Store,
  45. Work,
  46. )
  47. from torch._utils_internal import set_pytorch_distributed_envs_from_justknobs
  48. from torch.monitor import _WaitCounter
  49. from torch.overrides import handle_torch_function, has_torch_function
  50. from torch.utils._typing_utils import not_none
  51. from . import config as dist_config
  52. from .c10d_logger import _exception_logger, _time_logger
  53. from .constants import default_pg_nccl_timeout, default_pg_timeout
  54. from .rendezvous import register_rendezvous_handler, rendezvous # noqa: F401
  55. __all__ = [
  56. "Backend",
  57. "BackendConfig",
  58. "GroupMember",
  59. "P2POp",
  60. "all_gather",
  61. "all_gather_coalesced",
  62. "all_gather_object",
  63. "all_reduce",
  64. "all_reduce_coalesced",
  65. "all_to_all",
  66. "all_to_all_single",
  67. "barrier",
  68. "batch_isend_irecv",
  69. "broadcast",
  70. "send_object_list",
  71. "recv_object_list",
  72. "broadcast_object_list",
  73. "destroy_process_group",
  74. "gather",
  75. "gather_object",
  76. "get_backend_config",
  77. "get_backend",
  78. "get_default_backend_for_device",
  79. "get_rank",
  80. "get_world_size",
  81. "get_pg_count",
  82. "group",
  83. "init_process_group",
  84. "irecv",
  85. "is_gloo_available",
  86. "is_initialized",
  87. "is_mpi_available",
  88. "is_backend_available",
  89. "is_nccl_available",
  90. "is_torchelastic_launched",
  91. "is_ucc_available",
  92. "is_xccl_available",
  93. "isend",
  94. "monitored_barrier",
  95. "new_group",
  96. "new_subgroups",
  97. "new_subgroups_by_enumeration",
  98. "recv",
  99. "reduce",
  100. "reduce_scatter",
  101. "scatter",
  102. "scatter_object_list",
  103. "send",
  104. "supports_complex",
  105. "AllreduceCoalescedOptions",
  106. "AllreduceOptions",
  107. "AllToAllOptions",
  108. "BarrierOptions",
  109. "BroadcastOptions",
  110. "GatherOptions",
  111. "GroupName",
  112. "PrefixStore",
  113. "ProcessGroup",
  114. "ReduceOp",
  115. "ReduceOptions",
  116. "ReduceScatterOptions",
  117. "ScatterOptions",
  118. "Store",
  119. "DebugLevel",
  120. "get_debug_level",
  121. "Work",
  122. "default_pg_timeout",
  123. "get_group_rank",
  124. "get_global_rank",
  125. "get_process_group_ranks",
  126. "reduce_op",
  127. "all_gather_into_tensor",
  128. "reduce_scatter_tensor",
  129. "get_node_local_rank",
  130. "split_group",
  131. "shrink_group",
  132. ]
  133. _MPI_AVAILABLE = True
  134. _NCCL_AVAILABLE = True
  135. _GLOO_AVAILABLE = True
  136. _UCC_AVAILABLE = True
  137. _XCCL_AVAILABLE = True
  138. try:
  139. # pyrefly: ignore [import-error, missing-import]
  140. from torchcomms._comms import _BackendWrapper, new_comm
  141. _TORCHCOMM_AVAILABLE = True
  142. except ImportError:
  143. _TORCHCOMM_AVAILABLE = False
  144. def _use_torchcomms_enabled() -> bool:
  145. """Check if torchcomms is enabled via config."""
  146. return _TORCHCOMM_AVAILABLE and dist_config.use_torchcomms
  147. _pickler = pickle.Pickler
  148. _unpickler = pickle.Unpickler
  149. GroupName = NewType("GroupName", str)
  150. # Change __module__ of all imported types from torch._C._distributed_c10d that are public
  151. def _export_c_types() -> None:
  152. _public_types_to_change_module = [
  153. AllreduceCoalescedOptions,
  154. AllreduceOptions,
  155. AllToAllOptions,
  156. BarrierOptions,
  157. BroadcastOptions,
  158. GatherOptions,
  159. PrefixStore,
  160. ProcessGroup,
  161. ReduceOp,
  162. ReduceOptions,
  163. ReduceScatterOptions,
  164. ScatterOptions,
  165. Store,
  166. DebugLevel,
  167. get_debug_level,
  168. Work,
  169. ]
  170. for type in _public_types_to_change_module:
  171. type.__module__ = "torch.distributed.distributed_c10d"
  172. _export_c_types()
  173. try:
  174. from torch._C._distributed_c10d import ProcessGroupMPI
  175. ProcessGroupMPI.__module__ = "torch.distributed.distributed_c10d"
  176. __all__ += ["ProcessGroupMPI"]
  177. except ImportError:
  178. _MPI_AVAILABLE = False
  179. try:
  180. from torch._C._distributed_c10d import ProcessGroupNCCL
  181. ProcessGroupNCCL.__module__ = "torch.distributed.distributed_c10d"
  182. __all__ += ["ProcessGroupNCCL"]
  183. except ImportError:
  184. _NCCL_AVAILABLE = False
  185. try:
  186. from torch._C._distributed_c10d import _ProcessGroupWrapper, ProcessGroupGloo
  187. ProcessGroupGloo.__module__ = "torch.distributed.distributed_c10d"
  188. __all__ += ["ProcessGroupGloo"]
  189. except ImportError:
  190. _GLOO_AVAILABLE = False
  191. try:
  192. from torch._C._distributed_c10d import ProcessGroupUCC
  193. ProcessGroupUCC.__module__ = "torch.distributed.distributed_c10d"
  194. __all__ += ["ProcessGroupUCC"]
  195. except ImportError:
  196. _UCC_AVAILABLE = False
  197. try:
  198. from torch._C._distributed_c10d import ProcessGroupXCCL
  199. ProcessGroupXCCL.__module__ = "torch.distributed.distributed_c10d"
  200. __all__ += ["ProcessGroupXCCL"]
  201. except ImportError:
  202. _XCCL_AVAILABLE = False
  203. logger = logging.getLogger(__name__)
  204. PG_WRAPPER_STORE_PREFIX = "pg_wrapper"
  205. # Some reduce ops are not supported by complex numbers and will result in an error.
  206. # We currently provide complex support to the distributed API by viewing
  207. # complex tensors as real (torch.view_as_real), meaning that calling
  208. # these unsupported ops will return garbage values rather than error out.
  209. # (e.g. max(2+3i, 3+2i) = 3+3i)
  210. # We'd like calls to unsupported ops to error out accordingly,
  211. # rather than returning garbage values.
  212. def supports_complex(reduceOp: ReduceOp) -> bool:
  213. """Return true if reduce ops is supported. False otherwise."""
  214. denyList = [
  215. ReduceOp.MAX,
  216. ReduceOp.MIN,
  217. ReduceOp.PRODUCT,
  218. ReduceOp.BAND,
  219. ReduceOp.BOR,
  220. ReduceOp.BXOR,
  221. ]
  222. return reduceOp not in denyList
  223. # TODO refactor into enum/strenum
  224. class Backend(str): # noqa: SLOT000
  225. """
  226. An enum-like class for backends.
  227. Available backends: GLOO, NCCL, UCC, MPI, XCCL, FAKE, and other registered backends.
  228. The values of this class are lowercase strings, e.g., ``"gloo"``. They can
  229. be accessed as attributes, e.g., ``Backend.NCCL``.
  230. This class can be directly called to parse the string, e.g.,
  231. ``Backend(backend_str)`` will check if ``backend_str`` is valid, and
  232. return the parsed lowercase string if so. It also accepts uppercase strings,
  233. e.g., ``Backend("GLOO")`` returns ``"gloo"``.
  234. .. note:: The entry ``Backend.UNDEFINED`` is present but only used as
  235. initial value of some fields. Users should neither use it directly
  236. nor assume its existence.
  237. """
  238. UNDEFINED = "undefined"
  239. GLOO = "gloo"
  240. NCCL = "nccl"
  241. UCC = "ucc"
  242. MPI = "mpi"
  243. XCCL = "xccl"
  244. FAKE = "fake"
  245. _BackendPlugin = namedtuple("_BackendPlugin", ["creator_fn", "extended_api"])
  246. _plugins: dict[str, _BackendPlugin] = {}
  247. backend_list = [UNDEFINED, GLOO, NCCL, XCCL, UCC, MPI, FAKE]
  248. # 3rd-party devices can register the default backend support here
  249. default_device_backend_map: dict[str, str] = {
  250. "cpu": GLOO,
  251. "cuda": NCCL,
  252. "xpu": XCCL,
  253. "mps": GLOO,
  254. }
  255. backend_capability: dict[str, list[str]] = {
  256. GLOO: ["cpu", "cuda"],
  257. NCCL: ["cuda"],
  258. XCCL: ["xpu"],
  259. UCC: ["cpu", "cuda"],
  260. MPI: ["cpu", "cuda"],
  261. FAKE: ["cpu", "cuda", "hpu", "xpu"],
  262. }
  263. backend_type_map: dict[str, ProcessGroup.BackendType] = {
  264. UNDEFINED: ProcessGroup.BackendType.UNDEFINED,
  265. GLOO: ProcessGroup.BackendType.GLOO,
  266. NCCL: ProcessGroup.BackendType.NCCL,
  267. XCCL: ProcessGroup.BackendType.XCCL,
  268. UCC: ProcessGroup.BackendType.UCC,
  269. MPI: ProcessGroup.BackendType.MPI,
  270. FAKE: ProcessGroup.BackendType.CUSTOM,
  271. }
  272. def __new__(cls, name: str):
  273. """Create and return a new instance of the class."""
  274. if not isinstance(name, str):
  275. raise ValueError("Backend constructor parameter must be string-ish")
  276. value = getattr(Backend, name.upper(), Backend.UNDEFINED)
  277. if value == Backend.UNDEFINED:
  278. value = name.lower()
  279. return value
  280. @classmethod
  281. def register_backend(
  282. cls,
  283. name,
  284. func,
  285. extended_api: bool = False,
  286. devices: str | list[str] | None = None,
  287. ) -> None:
  288. """
  289. Register a new backend with the given name and instantiating function.
  290. This class method is used by 3rd party ``ProcessGroup`` extension to
  291. register new backends.
  292. Args:
  293. name (str): Backend name of the ``ProcessGroup`` extension. It
  294. should match the one in ``init_process_group()``.
  295. func (function): Function handler that instantiates the backend.
  296. The function should be implemented in the backend
  297. extension and takes four arguments, including
  298. ``store``, ``rank``, ``world_size``, and ``timeout``.
  299. extended_api (bool, optional): Whether the backend supports extended argument structure.
  300. Default: ``False``. If set to ``True``, the backend
  301. will get an instance of ``c10d::DistributedBackendOptions``, and
  302. a process group options object as defined by the backend implementation.
  303. device (str or list of str, optional): device type this backend
  304. supports, e.g. "cpu", "cuda", etc. If `None`,
  305. assuming both "cpu" and "cuda"
  306. .. note:: This support of 3rd party backend is experimental and subject to change.
  307. """
  308. # This takes care of CUSTOM Out-of-tree backend types, update in backend_list indicates availability
  309. if not hasattr(Backend, name.upper()):
  310. setattr(Backend, name.upper(), name.lower())
  311. if name.lower() not in Backend.backend_list:
  312. Backend.backend_list.append(name.lower())
  313. if devices is not None:
  314. for device in devices:
  315. if device not in Backend.default_device_backend_map:
  316. Backend.default_device_backend_map[device] = name.lower()
  317. Backend.backend_type_map[name.lower()] = ProcessGroup.BackendType.CUSTOM
  318. # Update device capability matrix in Backend class
  319. if devices is None:
  320. # This is more of a backward support for groups like `threaded`:
  321. # assume default devices "cpu" and "cuda", but warn
  322. warnings.warn(
  323. f"Device capability of {name} unspecified, assuming `cpu` and "
  324. "`cuda` or `xpu`. Please specify it via the `devices` argument of "
  325. "`register_backend`.",
  326. stacklevel=2,
  327. )
  328. Backend.backend_capability[name.lower()] = (
  329. ["cpu", "cuda", "xpu"] if torch.xpu.is_available() else ["cpu", "cuda"]
  330. )
  331. elif isinstance(devices, str):
  332. # Single device string specified. Simply convert to list.
  333. Backend.backend_capability[name.lower()] = [devices]
  334. else:
  335. Backend.backend_capability[name.lower()] = devices
  336. Backend._plugins[name.upper()] = Backend._BackendPlugin(func, extended_api)
  337. class BackendConfig:
  338. """Backend configuration class."""
  339. def __init__(self, backend: Backend):
  340. """Init."""
  341. self.device_backend_map: dict[str, Backend] = {}
  342. # pyrefly: ignore [bad-assignment]
  343. backend = str(backend)
  344. if backend == Backend.UNDEFINED:
  345. # Detect the accelerator on the machine. If no accelerator is
  346. # available, it returns CPU.
  347. device_type = torch._C._get_accelerator().type
  348. try:
  349. backend_str = Backend.default_device_backend_map[device_type]
  350. self.device_backend_map[device_type] = Backend(backend_str)
  351. except KeyError:
  352. raise ValueError(
  353. f"We detected accelerator {device_type} on your machine. "
  354. f"But we don't know which communication backend to use for this accelerator. "
  355. f"Please specify the `backend` argument in the `init_process_group` call."
  356. ) from None
  357. elif backend.lower() in Backend.backend_list:
  358. # Cases for when backend is a single string (without device types)
  359. # e.g. "nccl", "gloo", "ucc", "mpi"
  360. supported_devices = Backend.backend_capability[backend.lower()]
  361. backend_val = Backend(backend)
  362. self.device_backend_map = dict.fromkeys(supported_devices, backend_val)
  363. elif ":" in backend.lower():
  364. # Backend specified in "device:backend" format
  365. # make sure the backend string is in the correct format
  366. # "{device_type1}:{backend1},{device_type2}:{backend2}"
  367. # e.g. "cpu:gloo,cuda:nccl"
  368. backend_str_error_message = f"""The custom backend string argument is invalid: {backend}.
  369. Custom backend string is an experimental feature where the backend string must be in the format:
  370. "<device_type1>:<backend1>,<device_type2>:<backend2>...". e.g. 'cpu:gloo,cuda:nccl'"""
  371. # parse the backend string and populate the device_backend_map
  372. for device_backend_pair_str in backend.lower().split(","):
  373. device_backend_pair = device_backend_pair_str.split(":")
  374. if len(device_backend_pair) != 2:
  375. raise ValueError(
  376. f"Invalid device:backend pairing: \
  377. {device_backend_pair_str}. {backend_str_error_message}"
  378. )
  379. # pyrefly: ignore [bad-assignment]
  380. device, backend = device_backend_pair
  381. if device in self.device_backend_map:
  382. raise ValueError(
  383. f"Duplicate device type {device} \
  384. in backend string: {backend}. {backend_str_error_message}"
  385. )
  386. self.device_backend_map[device] = Backend(backend)
  387. else:
  388. # User specified a single backend name whose device capability is
  389. # unknown, assuming it can support the default devices of PyTorch
  390. # (cpu and cuda)
  391. warnings.warn(
  392. f"Device capability of {backend} unknown, assuming `cpu` and "
  393. "`cuda`. You can specify it in `device:backend` format in "
  394. "`init_process_group` call.",
  395. stacklevel=2,
  396. )
  397. backend_val = Backend(backend)
  398. self.device_backend_map = {
  399. "cpu": backend_val,
  400. "cuda": backend_val,
  401. "xpu": backend_val,
  402. }
  403. logger.info("Using backend config: %s", self.device_backend_map)
  404. def __repr__(self):
  405. """Return all the device:backend pairs separated by commas."""
  406. return ",".join(
  407. f"{device}:{backend}" for device, backend in self.device_backend_map.items()
  408. )
  409. def get_device_backend_map(self) -> dict[str, Backend]:
  410. """Return backend map of the device."""
  411. return self.device_backend_map
  412. class _reduce_op:
  413. r"""
  414. Deprecated enum-like class.
  415. For reduction operations: ``SUM``, ``PRODUCT``, ``MIN``, and ``MAX``.
  416. :class:`~torch.distributed.ReduceOp` is recommended to use instead.
  417. """
  418. def __init__(self) -> None:
  419. # __members__ is a dict storing key-value pairs for enum classes
  420. for k, v in ReduceOp.RedOpType.__members__.items():
  421. setattr(self, k, v)
  422. self.__members__ = ReduceOp.RedOpType.__members__
  423. @deprecated(
  424. "`torch.distributed.reduce_op` is deprecated, "
  425. "please use `torch.distributed.ReduceOp` instead",
  426. category=FutureWarning,
  427. )
  428. def __getattribute__(self, key):
  429. return object.__getattribute__(self, key)
  430. reduce_op = _reduce_op()
  431. class P2POp:
  432. """
  433. A class to build point-to-point operations for ``batch_isend_irecv``.
  434. This class builds the type of P2P operation, communication buffer, peer rank,
  435. Process Group, and tag. Instances of this class will be passed to
  436. ``batch_isend_irecv`` for point-to-point communications.
  437. Args:
  438. op (Callable): A function to send data to or receive data from a peer process.
  439. The type of ``op`` is either ``torch.distributed.isend`` or
  440. ``torch.distributed.irecv``.
  441. tensor (Tensor): Tensor to send or receive.
  442. peer (int, optional): Destination or source rank.
  443. group (ProcessGroup, optional): The process group to work on. If None,
  444. the default process group will be used.
  445. tag (int, optional): Tag to match send with recv.
  446. group_peer (int, optional): Destination or source rank.
  447. """
  448. def __init__(
  449. self,
  450. op: Callable,
  451. tensor: torch.Tensor,
  452. peer: int | None = None,
  453. group: ProcessGroup | None = None,
  454. tag: int = 0,
  455. group_peer: int | None = None,
  456. ):
  457. """Init."""
  458. self.op = op
  459. self.tensor = tensor
  460. self.group = _group_or_default_group(group)
  461. self.peer = _canonicalize_group_rank(
  462. self.group, peer, group_peer, return_global=True
  463. )
  464. self.tag = tag
  465. self.group_peer = _canonicalize_group_rank(self.group, peer, group_peer)
  466. def __new__(
  467. cls,
  468. op: Callable,
  469. tensor: torch.Tensor,
  470. peer: int | None = None,
  471. group: ProcessGroup | None = None,
  472. tag: int = 0,
  473. group_peer: int | None = None,
  474. ):
  475. """Create and return a new instance of the class."""
  476. _check_op(op)
  477. _check_single_tensor(tensor, "tensor")
  478. return object.__new__(cls)
  479. def __repr__(self):
  480. my_group_rank = get_rank(self.group)
  481. op_name = self.op.__name__
  482. group_name = self.group.group_name if self.group else "default_pg"
  483. if "send" in op_name:
  484. s = my_group_rank
  485. d = self.group_peer
  486. elif "recv" in op_name:
  487. s = self.group_peer
  488. d = my_group_rank
  489. else:
  490. return super().__repr__()
  491. return f"P2POp({op_name} pg={group_name}, group_src={s}, group_dst={d}, {self.tensor.shape}, {self.tensor.dtype})"
  492. class _CollOp:
  493. """
  494. A class to capture collective operations.
  495. Args:
  496. op (Callable): A collective function, e.g. ``torch.distributed.all_reduce``.
  497. tensor (Tensor): Tensor to operate on.
  498. dst_tensor (Tensor, optional): Provided when source and destination tensors are not the same.
  499. redop (ReduceOp, optional): reduce operation.
  500. root (int, optional): root of broadcast or reduce.
  501. """
  502. def __init__(
  503. self,
  504. op: Callable,
  505. tensor: torch.Tensor,
  506. dst_tensor: torch.Tensor | None = None,
  507. redop: ReduceOp | None = None,
  508. root: int | None = None,
  509. ):
  510. self.op = op
  511. self.tensor = tensor
  512. self.dst_tensor = dst_tensor
  513. self.redop = redop
  514. self.root = root
  515. # DO NOT USE THESE FIELDS DIRECTLY.
  516. # Use them through the _world object to make sure the _world override mechanism
  517. _pg_map: dict[ProcessGroup, tuple[str, Store]] = {}
  518. _pg_names: dict[ProcessGroup, GroupName] = {}
  519. _pg_group_ranks: dict[ProcessGroup, dict[int, int]] = {}
  520. # For a pg, it is a map from ProcessGroup to BackendConfig
  521. _pg_backend_config: dict[ProcessGroup, str] = {}
  522. _group_count = 0
  523. _tags_to_pg: dict[str, list[ProcessGroup]] = {}
  524. _pg_to_tag: dict[ProcessGroup, str] = {}
  525. _backend: str | None = None
  526. class _World:
  527. """
  528. Container class for c10d process group state.
  529. This is used during registration and lookup of PG state.
  530. .. warning:: This is an experimental API intended to expose the inner workings
  531. of c10d and is subject to change..
  532. """
  533. def __init__(self) -> None:
  534. self._default_pg = None
  535. self._pg_coalesce_state: dict[ProcessGroup, list[_CollOp]] = {}
  536. self._comms: list[Any] = []
  537. @property
  538. def default_pg(self) -> ProcessGroup | None:
  539. """
  540. Process group that includes all ranks of the cluster.
  541. This default ProcessGroup is used by c10d APIs when a ProcessGroup is needed
  542. but None is provided.
  543. """
  544. return self._default_pg
  545. @default_pg.setter
  546. def default_pg(self, value) -> None:
  547. self._default_pg = value
  548. @property
  549. def pg_map(self) -> dict[ProcessGroup, tuple[str, Store]]:
  550. """
  551. Provide Mapping from ProcessGroup to backend name and store.
  552. For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
  553. For MPI pg, it is a map from ProcessGroup to (Backend, None)
  554. TODO don't expose the map, expose fine grained ops
  555. """
  556. global _pg_map
  557. return _pg_map
  558. @property
  559. def pg_names(self) -> dict[ProcessGroup, GroupName]:
  560. """
  561. Process group's names, map from ProcessGroup to str.
  562. TODO don't expose the map, expose fine grained ops
  563. """
  564. global _pg_names
  565. return _pg_names
  566. @property
  567. def pg_group_ranks(self) -> dict[ProcessGroup, dict[int, int]]:
  568. """
  569. Process group's global rank to local rank mapping.
  570. TODO don't expose the map, expose fine grained ops
  571. """
  572. global _pg_group_ranks
  573. return _pg_group_ranks
  574. @property
  575. def pg_backend_config(self) -> dict[ProcessGroup, str]:
  576. """
  577. Process group's backend config.
  578. TODO don't expose the map, expose fine grained ops
  579. """
  580. global _pg_backend_config
  581. return _pg_backend_config
  582. @property
  583. def group_count(self) -> int:
  584. """
  585. Process group count for default naming.
  586. TODO don't expose group_count, use something else instead
  587. """
  588. global _group_count
  589. return _group_count
  590. @group_count.setter
  591. def group_count(self, value: int) -> None:
  592. """Use to compute the name of ProcessGroups when using global synchronization."""
  593. global _group_count
  594. _group_count = value
  595. @property
  596. def tags_to_pg(self) -> dict[str, list[ProcessGroup]]:
  597. global _tags_to_pg
  598. return _tags_to_pg
  599. @property
  600. def pg_to_tag(self) -> dict[ProcessGroup, str]:
  601. global _pg_to_tag
  602. return _pg_to_tag
  603. @property
  604. def pg_coalesce_state(self) -> dict[ProcessGroup, list[_CollOp]]:
  605. return self._pg_coalesce_state
  606. @property
  607. def comms(self) -> list[Any]:
  608. return self._comms
  609. @property
  610. def pg_config_info(self) -> list[dict[str, Any]]:
  611. """
  612. Return a list of dict with process groups and backends.
  613. Along with their unique IDs and configurations (types and ranks).
  614. """
  615. config_info: list[dict[str, Any]] = []
  616. default_pg_size = _get_group_size(None)
  617. for pg in self.pg_map:
  618. ranks = self.pg_group_ranks[pg]
  619. config_info.append(
  620. {
  621. "pg_name": self.pg_names[pg],
  622. "pg_desc": pg.group_desc,
  623. "backend_config": self.pg_backend_config[pg],
  624. "ranks": (
  625. list(ranks.keys()) if len(ranks) != default_pg_size else []
  626. ), # 'ranks' is an empty list when all ranks are involved in a pg
  627. "group_size": len(ranks),
  628. "group_count": self.group_count,
  629. }
  630. )
  631. return config_info
  632. _world = _World()
  633. """Holds the singleton instance of ``_World`` used by c10. Experimental extension point to override it"""
  634. class _WorldMeta(type):
  635. """
  636. Meta class of ``group`` and ``GroupMember``.
  637. Allows them to have the class property ``WORLD``.
  638. """
  639. # Points to the default PG once initialized.
  640. @property
  641. def WORLD(cls) -> ProcessGroup | None:
  642. return _world.default_pg
  643. @WORLD.setter
  644. def WORLD(cls, pg: ProcessGroup | None):
  645. _world.default_pg = pg
  646. class group(metaclass=_WorldMeta):
  647. """Group class. Placeholder."""
  648. class GroupMember(metaclass=_WorldMeta):
  649. """Group member class."""
  650. NON_GROUP_MEMBER = -100
  651. def _get_default_timeout(backend: Backend) -> timedelta:
  652. # see note on nccl vs other backend timeout (constants.py)
  653. if backend == Backend.NCCL:
  654. if not isinstance(default_pg_nccl_timeout, timedelta):
  655. # TODO moco benchmark on CPU initializes pgnccl backend today, triggered this assert in CI before it was
  656. # changed to be a warning. We should fix the moco model.
  657. warnings.warn(
  658. "Attempted to get default timeout for nccl backend, but NCCL support is not compiled",
  659. stacklevel=2,
  660. )
  661. return default_pg_timeout
  662. return default_pg_nccl_timeout
  663. else:
  664. return default_pg_timeout
  665. def _check_valid_timeout(timeout: Any) -> None:
  666. if not isinstance(timeout, timedelta):
  667. raise TypeError(
  668. f"Expected timeout argument to be of type datetime.timedelta, got {timeout}"
  669. )
  670. # Default process group state
  671. _default_pg_init_method: str | None = None
  672. STORE_BASED_BARRIER_PREFIX = "store_based_barrier_key"
  673. def _get_object_coll_device(group: ProcessGroup | None = None) -> str:
  674. """
  675. .. note:: This is an internal helper and does not have backward
  676. compatibility, please use with caution.
  677. Return the device type to use with ``group`` for object collectives or
  678. barrier.
  679. There are selection rules:
  680. 1. If user specifies exactly one backend in ``init_process_group`` call:
  681. use that backend
  682. 2. Else if user specifies multiple "device:backend" pairs in init_process_group:
  683. If "cpu" is among those pairs, use "cpu" (because the object is in cpu memory);
  684. Otherwise, use the first backend (sort of a random pick).
  685. Args:
  686. group (ProcessGroup, optional): The process group to work on. If None,
  687. the default process group will be used.
  688. Returns:
  689. str: The device type to use for object collective with ``group``.
  690. """
  691. group = group or _get_default_group()
  692. if not isinstance(group, ProcessGroup):
  693. warnings.warn(
  694. f"You are using a Backend {type(group)} as a ProcessGroup. "
  695. "This usage is deprecated since PyTorch 2.0. Please use a public API "
  696. "of PyTorch Distributed instead.",
  697. stacklevel=2,
  698. )
  699. # Provide backward compatibility to cases where `group` passed in is
  700. # actually a Backend (like `ProcessGroupGloo`) rather than a
  701. # `ProcessGroup` in PT 2.0 sense
  702. if isinstance(group, ProcessGroupGloo):
  703. # RPC uses Gloo for object collectives
  704. return "cpu"
  705. else:
  706. raise ValueError(f"Expecting a ProcessGroup, but got a {type(group)}.")
  707. """
  708. ``group._device_types`` is a property pybind that returns the devices
  709. ("cpu", "cuda", etc) supported by ``group``. Can be multiple if the
  710. ``group`` supports multiple devices.
  711. """
  712. devices = group._device_types
  713. if len(devices) == 1:
  714. # User fixed exactly one backend in `init_process_group`
  715. return devices[0].type
  716. elif len(devices) == 0:
  717. # No backend has been registered with this PG (maybe because no
  718. # collective has been run?) We pick cpu as the default and hopefully
  719. # this would lazily init Gloo or other available cpu backend.
  720. return "cpu"
  721. elif torch.device("cpu") in devices:
  722. # There are multiple backends in this PG and cpu is among them.
  723. # cpu is preferred as the object is in cpu memory. No need for device
  724. # copy.
  725. return "cpu"
  726. else:
  727. # No cpu in the backend list. Randomly pick the first backend
  728. return devices[0].type
  729. def _get_pg_default_device(group: ProcessGroup | None = None) -> torch.device:
  730. """
  731. .. note:: This method will be deprecated, it only stays for
  732. backward-compatibility reason. Alternatives:
  733. - If you need to find a device for object collectives, please use
  734. `_get_object_coll_device(group)`.
  735. - If you need to query the device types supported by group, please use
  736. `_device_capability(group)`.
  737. Return the device type registered with ``group``.
  738. For example, if `init_process_group("nccl", ...)` was called, the returned
  739. value would be `torch.device("cuda")`.
  740. Errors out if no device has been registered.
  741. Args:
  742. group (ProcessGroup, optional): The process group to work on. If None,
  743. the default process group will be used.
  744. Returns:
  745. torch.device: The device type registered with ``group``.
  746. """
  747. warnings.warn(
  748. "`_get_pg_default_device` will be deprecated, it only stays for "
  749. "backward-compatibility reason. If you need to find a device for object "
  750. "collectives, please use `_get_object_coll_device`. If you need to query "
  751. "the device types supported by group, please use "
  752. "`_device_capability(group)`. ",
  753. stacklevel=2,
  754. )
  755. group = group or _get_default_group()
  756. if not isinstance(group, ProcessGroup):
  757. # Provide backward compatibility to cases where `group` passed in is
  758. # actually a Backend (like `ProcessGroupGloo`) rather than a
  759. # `ProcessGroup` in PT 2.0 sense
  760. warnings.warn(
  761. f"You are using a Backend {type(group)} as a ProcessGroup. "
  762. "This usage is deprecated since PyTorch 2.0. Please use a public API "
  763. "of PyTorch Distributed instead.",
  764. FutureWarning,
  765. stacklevel=3,
  766. )
  767. # Most users create Gloo with private API for object collectives
  768. return torch.device("cpu")
  769. """
  770. ``group._device_types`` is a property pybind that returns the devices
  771. ("cpu", "cuda", etc) supported by ``group``. Can be multiple if the
  772. ``group`` supports multiple devices.
  773. """
  774. devices = group._device_types
  775. if len(devices) == 1:
  776. # User fixed exactly one backend in `init_process_group`
  777. return devices[0]
  778. elif len(devices) == 0:
  779. raise RuntimeError(
  780. "Default device not found, because no backend has been registered "
  781. "with this ProcessGroup."
  782. )
  783. else:
  784. # There are multiple backends in this PG.
  785. if torch.device("cpu") in devices:
  786. rv = torch.device("cpu")
  787. else:
  788. rv = devices[0]
  789. warnings.warn(
  790. "Multiple backends are registered with this ProcessGroup. We cannot "
  791. f"determine which one is the default. Returning {rv}. "
  792. "Please consider using other APIs.",
  793. stacklevel=2,
  794. )
  795. return rv
  796. def _device_capability(group: ProcessGroup | None = None) -> list[str]:
  797. """
  798. Return the device type(s) supported by ``group``.
  799. Args:
  800. group (ProcessGroup, optional): The process group to query. If None,
  801. the default process group will be used.
  802. Returns:
  803. List[str]: A list of device types supported by ``group``.
  804. """
  805. group = group or _get_default_group()
  806. return [device.type for device in group._device_types]
  807. @_time_logger
  808. def _store_based_barrier(
  809. rank,
  810. store,
  811. group_name: GroupName,
  812. rendezvous_count,
  813. timeout,
  814. logging_interval=timedelta(seconds=10),
  815. ) -> None:
  816. """
  817. Store based barrier for synchronizing processes.
  818. Barrier based on store which is used for synchronizing processes after
  819. ``init_process_group`` or ``new_group``. Intended to be used only with
  820. those two methods and is not a generic alternative to ``barrier()``.
  821. """
  822. store_key = f"{STORE_BASED_BARRIER_PREFIX}:{group_name}"
  823. store.add(store_key, 1)
  824. logger.debug("Added key: %s to store for rank: %s", store_key, rank)
  825. # Now wait for all workers to check in with the store.
  826. world_size = rendezvous_count
  827. worker_count = store.add(store_key, 0)
  828. last_worker_key = f"{store_key}:last_worker"
  829. if worker_count == world_size:
  830. store.set(last_worker_key, "1")
  831. # adjust the timeout to be at least 10secs + 1sec per thousand ranks to reduce the odds of timeout
  832. # this value was empirically found while scale testing.
  833. logging_interval = max(logging_interval, timedelta(seconds=10 + world_size / 1000))
  834. start = time.time()
  835. while True:
  836. try:
  837. # This will throw an exception after the logging_interval in which we print out
  838. # the status of the group or time out officially, throwing runtime error
  839. store.wait([last_worker_key], logging_interval)
  840. break
  841. except RuntimeError as e:
  842. worker_count = store.add(store_key, 0)
  843. # Print status periodically to keep track.
  844. logger.debug( # noqa: G200
  845. "Waiting in store based barrier to initialize process group for %s seconds"
  846. "rank: %s, key: %s (world_size=%s, num_workers_joined=%s, timeout=%s error=%s)",
  847. time.time() - start,
  848. rank,
  849. store_key,
  850. world_size,
  851. worker_count,
  852. timeout,
  853. e,
  854. )
  855. if timedelta(seconds=(time.time() - start)) > timeout:
  856. raise DistStoreError( # noqa: B904
  857. "Timed out initializing process group in store based barrier on "
  858. f"rank {rank}, for key: {store_key} (world_size={world_size}, "
  859. f"num_workers_joined={worker_count}, timeout={timeout} error={e})"
  860. )
  861. logger.info(
  862. "Rank %s: Completed store-based barrier for key:%s with %s nodes.",
  863. rank,
  864. store_key,
  865. world_size,
  866. )
  867. def _rank_not_in_group(group: ProcessGroup | None) -> bool:
  868. """Check if the current process's rank is not in a given group."""
  869. if group is None:
  870. return False
  871. return group == GroupMember.NON_GROUP_MEMBER
  872. def _warn_not_in_group(op_name) -> None:
  873. global_rank = -1 if GroupMember.WORLD is None else GroupMember.WORLD.rank()
  874. warnings.warn(
  875. f"Running {op_name} on global rank {global_rank} which does not "
  876. "belong to the given group.",
  877. stacklevel=2,
  878. )
  879. def get_group_rank(group: ProcessGroup, global_rank: int) -> int:
  880. """
  881. Translate a global rank into a group rank.
  882. ``global_rank`` must be part of ``group`` otherwise this raises RuntimeError.
  883. Args:
  884. group (ProcessGroup): ProcessGroup to find the relative rank.
  885. global_rank (int): Global rank to query.
  886. Returns:
  887. Group rank of ``global_rank`` relative to ``group``
  888. N.B. calling this function on the default process group returns identity
  889. """
  890. if group is GroupMember.WORLD:
  891. return global_rank
  892. if group not in _world.pg_group_ranks:
  893. raise ValueError(
  894. f"Group {group} is not registered, please create group with torch.distributed.new_group API"
  895. )
  896. group_ranks = _world.pg_group_ranks[group]
  897. if global_rank not in group_ranks:
  898. raise ValueError(f"Global rank {global_rank} is not part of group {group}")
  899. return group_ranks[global_rank]
  900. def get_global_rank(group: ProcessGroup, group_rank: int) -> int:
  901. """
  902. Translate a group rank into a global rank.
  903. ``group_rank`` must be part of `group` otherwise this raises RuntimeError.
  904. Args:
  905. group (ProcessGroup): ProcessGroup to find the global rank from.
  906. group_rank (int): Group rank to query.
  907. Returns:
  908. Global rank of ``group_rank`` relative to ``group``
  909. N.B. calling this function on the default process group returns identity
  910. """
  911. if group is GroupMember.WORLD:
  912. return group_rank
  913. if group not in _world.pg_group_ranks:
  914. raise ValueError(
  915. f"Group {group} is not registered, please create group with torch.distributed.new_group API"
  916. )
  917. for rank, grp_rank in _world.pg_group_ranks[group].items():
  918. if grp_rank == group_rank:
  919. return rank
  920. raise ValueError(f"Group rank {group_rank} is not part of group {group}")
  921. # TODO: remove this once the ecosystem moves away from it.
  922. @deprecated(
  923. "`torch.distributed.distributed_c10d._get_global_rank` is deprecated, "
  924. "please use `torch.distributed.distributed_c10d.get_global_rank` instead",
  925. category=FutureWarning,
  926. )
  927. def _get_global_rank(group, rank) -> int:
  928. """Use get_global_rank as this method is deprecated."""
  929. return get_global_rank(group, rank)
  930. def get_process_group_ranks(group: ProcessGroup | None) -> list[int]:
  931. """
  932. Get all ranks associated with ``group``.
  933. Args:
  934. group (Optional[ProcessGroup]): ProcessGroup to get all ranks from.
  935. If None, the default process group will be used.
  936. Returns:
  937. List of global ranks ordered by group rank.
  938. """
  939. return list(_world.pg_group_ranks[group or _get_default_group()].keys())
  940. def _get_group_size(group: ProcessGroup | None) -> int:
  941. """Get a given group's world size."""
  942. if group is GroupMember.WORLD or group is None:
  943. default_pg = _get_default_group()
  944. return default_pg.size()
  945. return group.size()
  946. def _get_group_size_by_name(group_name: GroupName) -> int:
  947. group = _resolve_process_group(group_name)
  948. return group.size()
  949. def _resolve_group_name_by_ranks_and_tag(ranks: list[int], tag: str) -> GroupName:
  950. # TODO(yifu): remove this function once ranks + tag is not a supported
  951. # identifier for process group for functional collectives.
  952. group = _find_pg_by_ranks_and_tag(tag, ranks)
  953. if group is None:
  954. raise ValueError("")
  955. return group.group_name
  956. def _check_single_tensor(param, param_name: str) -> None:
  957. """Check that the parameter ``param_name`` is a single tensor."""
  958. if not isinstance(param, torch.Tensor):
  959. raise TypeError(
  960. f"""Invalid function argument. Expected parameter `{param_name}` of type torch.Tensor
  961. but got {type(param)} instead."""
  962. )
  963. def _check_tensor_list(param, param_name: str) -> None:
  964. """Check that the parameter ``param_name`` is a list of tensors."""
  965. if not isinstance(param, list):
  966. raise TypeError(
  967. f"""Invalid function argument. Expected parameter `{param_name}` of type List[torch.Tensor]
  968. but got {type(param)} instead."""
  969. )
  970. elif not all(isinstance(p, torch.Tensor) for p in param):
  971. raise TypeError(
  972. f"""Invalid function argument. Expected parameter `{param_name}` of type List[torch.Tensor]
  973. but got {type(param)} with elements of type {[type(p) for p in param]}."""
  974. )
  975. def _group_or_default_group(group: ProcessGroup | None = None) -> ProcessGroup:
  976. if group is None or group is GroupMember.WORLD:
  977. group = _get_default_group()
  978. return group
  979. def _canonicalize_group_rank(
  980. group: ProcessGroup,
  981. global_rank: int | None = None,
  982. group_rank: int | None = None,
  983. return_global: bool = False,
  984. ) -> int:
  985. """
  986. Helper method to take _either_ a global rank or a group rank and produce a group rank.
  987. If 'return_global' is true, produce a global rank instead of a group rank.
  988. """
  989. if group_rank is not None:
  990. if global_rank is not None:
  991. raise ValueError("Can't specify both group_rank and global_rank")
  992. if return_global:
  993. return get_global_rank(group, group_rank)
  994. else:
  995. if global_rank is None:
  996. raise ValueError("Must specify global_rank or group_rank")
  997. if return_global:
  998. return global_rank
  999. group_rank = get_group_rank(group, global_rank)
  1000. return group_rank
  1001. def _check_not_self_rank(group: ProcessGroup, rank: int, rank_type: str):
  1002. if group.rank() == rank:
  1003. raise ValueError(
  1004. f"Invalid {rank_type} rank: {rank_type} rank should not be the same as "
  1005. "the rank of the current process."
  1006. )
  1007. def _as_iterable(obj) -> collections.abc.Iterable:
  1008. return obj if isinstance(obj, list) else (obj,)
  1009. def _ensure_all_tensors_same_dtype(*tensors) -> None:
  1010. last_dtype = None
  1011. for tensor in itertools.chain.from_iterable(map(_as_iterable, tensors)):
  1012. tensor_dtype = tensor.dtype
  1013. # Mixing complex and its element type is allowed
  1014. if tensor_dtype.is_complex:
  1015. tensor_dtype = (
  1016. torch.float32 if tensor_dtype == torch.complex64 else torch.complex128
  1017. )
  1018. if last_dtype is None:
  1019. last_dtype = tensor_dtype
  1020. else:
  1021. if last_dtype != tensor_dtype:
  1022. raise ValueError(
  1023. "Invalid usage of tensors with different dtypes"
  1024. f"Found {last_dtype} and {tensor.dtype}"
  1025. )
  1026. def _check_op(op) -> None:
  1027. """Check that the ``op`` is either isend or irecv."""
  1028. if op not in [isend, irecv]:
  1029. raise ValueError(
  1030. "Invalid ``op``. Expected ``op`` "
  1031. "to be of type ``torch.distributed.isend`` or "
  1032. "``torch.distributed.irecv``."
  1033. )
  1034. def _check_p2p_op_list(p2p_op_list) -> None:
  1035. """
  1036. Check that the ``p2p_op_list`` is a list of P2POp instances.
  1037. Also, check that all ops use the same group.
  1038. """
  1039. if not isinstance(p2p_op_list, list) or not all(
  1040. isinstance(p2p_op, P2POp) for p2p_op in p2p_op_list
  1041. ):
  1042. raise ValueError(
  1043. "Invalid ``p2p_op_list``. Each op is expected to "
  1044. "to be of type ``torch.distributed.P2POp``."
  1045. )
  1046. group = p2p_op_list[0].group
  1047. if not all(group == p2p_op.group for p2p_op in p2p_op_list):
  1048. raise ValueError("All ops need to use the same group.")
  1049. def is_mpi_available() -> bool:
  1050. """Check if the MPI backend is available."""
  1051. return _MPI_AVAILABLE
  1052. def is_nccl_available() -> bool:
  1053. """Check if the NCCL backend is available."""
  1054. return _NCCL_AVAILABLE
  1055. def is_gloo_available() -> bool:
  1056. """Check if the Gloo backend is available."""
  1057. return _GLOO_AVAILABLE
  1058. def is_ucc_available() -> bool:
  1059. """Check if the UCC backend is available."""
  1060. return _UCC_AVAILABLE
  1061. def is_xccl_available() -> bool:
  1062. """Check if the XCCL backend is available."""
  1063. return _XCCL_AVAILABLE
  1064. def _check_single_backend_availability(backend_name: str) -> bool:
  1065. """
  1066. Helper function to check if a single backend is available.
  1067. """
  1068. available_func = getattr(
  1069. torch.distributed, f"is_{str(backend_name).lower()}_available", None
  1070. )
  1071. if available_func:
  1072. return available_func()
  1073. return str(backend_name).lower() in Backend.backend_list
  1074. def is_backend_available(backend: str) -> bool:
  1075. """
  1076. Check backend availability.
  1077. Checks if the given backend is available and supports the built-in backends or
  1078. third-party backends through function ``Backend.register_backend``.
  1079. Args:
  1080. backend (str): Backend name.
  1081. Returns:
  1082. bool: Returns true if the backend is available otherwise false.
  1083. """
  1084. # If the backend has an ``is_backend_available`` function, return the result of that function directly
  1085. if ":" in backend.lower(): # composite backend like "cpu:gloo"
  1086. backend_config = BackendConfig(Backend(backend))
  1087. device_backend_map = backend_config.get_device_backend_map()
  1088. return all(
  1089. _check_single_backend_availability(str(backend_name))
  1090. for backend_name in device_backend_map.values()
  1091. )
  1092. else:
  1093. # Handle simple backend strings like "nccl", "gloo"
  1094. return _check_single_backend_availability(backend)
  1095. def is_initialized() -> bool:
  1096. """Check if the default process group has been initialized."""
  1097. return GroupMember.WORLD is not None
  1098. def is_torchelastic_launched() -> bool:
  1099. """
  1100. Check whether this process was launched with ``torch.distributed.elastic`` (aka torchelastic).
  1101. The existence of ``TORCHELASTIC_RUN_ID`` environment
  1102. variable is used as a proxy to determine whether the current process
  1103. was launched with torchelastic. This is a reasonable proxy since
  1104. ``TORCHELASTIC_RUN_ID`` maps to the rendezvous id which is always a
  1105. non-null value indicating the job id for peer discovery purposes..
  1106. """
  1107. return os.getenv("TORCHELASTIC_RUN_ID") is not None
  1108. def _is_barrier_after_init() -> int:
  1109. # Environment variable to control whether process group should perform a
  1110. # barrier after its init. Default value is 0, i.e. no barrier. If you
  1111. # experience issue with this setting, you may set
  1112. # `TORCH_DIST_INIT_BARRIER=1` to add the barrier.
  1113. return int(os.getenv("TORCH_DIST_INIT_BARRIER", "0"))
  1114. def _get_default_group() -> ProcessGroup:
  1115. """Get the default process group created by init_process_group."""
  1116. if not is_initialized():
  1117. raise ValueError(
  1118. "Default process group has not been initialized, "
  1119. "please make sure to call init_process_group."
  1120. )
  1121. if TYPE_CHECKING:
  1122. return not_none(GroupMember.WORLD)
  1123. else:
  1124. return GroupMember.WORLD
  1125. def _get_default_store() -> Store:
  1126. """Get the default store created by init_process_group."""
  1127. if not is_initialized():
  1128. raise ValueError(
  1129. "Default process group has not been initialized, "
  1130. "please make sure to call init_process_group."
  1131. )
  1132. default_pg = _get_default_group()
  1133. _, default_store = _world.pg_map[default_pg]
  1134. return default_store
  1135. def _update_default_pg(pg: ProcessGroup | None) -> None:
  1136. _world.default_pg = pg
  1137. rank = pg.rank() if pg is not None and pg != GroupMember.NON_GROUP_MEMBER else -1
  1138. torch._C._distributed_c10d._set_global_rank(rank)
  1139. def get_backend_config(group: ProcessGroup | None = None) -> str:
  1140. """
  1141. Return the backend configuration of the given process group.
  1142. Args:
  1143. group (ProcessGroup, optional): The process group to work on. The
  1144. default is the general main process group. If another specific group
  1145. is specified, the calling process must be part of :attr:`group`.
  1146. Returns:
  1147. The backend configuration of the given process group as a lower case string.
  1148. """
  1149. pg = group or _get_default_group()
  1150. if _rank_not_in_group(pg):
  1151. raise ValueError("Invalid process group specified")
  1152. backend_config = _world.pg_backend_config.get(pg)
  1153. return str(not_none(backend_config))
  1154. def get_backend(group: ProcessGroup | None = None) -> Backend:
  1155. """
  1156. Return the backend of the given process group.
  1157. Args:
  1158. group (ProcessGroup, optional): The process group to work on. The
  1159. default is the general main process group. If another specific group
  1160. is specified, the calling process must be part of :attr:`group`.
  1161. Returns:
  1162. The backend of the given process group as a lower case string.
  1163. """
  1164. pg = group or _get_default_group()
  1165. if _rank_not_in_group(pg):
  1166. raise ValueError("Invalid process group specified")
  1167. pg_store = _world.pg_map.get(pg, None)
  1168. if pg_store is None:
  1169. raise ValueError(
  1170. f"Process group {pg} is not initialized in the world group map. Please initialize the group first."
  1171. )
  1172. return Backend(not_none(pg_store)[0])
  1173. def get_default_backend_for_device(device: str | torch.device) -> str:
  1174. """
  1175. Return the default backend for the given device.
  1176. Args:
  1177. device (Union[str, torch.device]): The device to get the default backend for.
  1178. Returns:
  1179. The default backend for the given device as a lower case string.
  1180. """
  1181. if isinstance(device, torch.device):
  1182. device_str = device.type
  1183. else:
  1184. device_str = torch.device(device).type
  1185. backend = Backend.default_device_backend_map.get(device_str)
  1186. if backend is None:
  1187. raise ValueError(f"Default backend not registered for device : {device}")
  1188. return backend
  1189. def _get_process_group_uid(pg: ProcessGroup) -> int:
  1190. backend = None
  1191. try:
  1192. backend = pg._get_backend(torch.device("cuda"))
  1193. except RuntimeError:
  1194. pass
  1195. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  1196. return backend.uid
  1197. return -1
  1198. def _get_pg_config(group: ProcessGroup | None = None) -> dict[str, Any]:
  1199. """
  1200. Return the pg configuration of the given process group.
  1201. """
  1202. pg = group or _get_default_group()
  1203. return {
  1204. "pg_name": _get_process_group_name(pg),
  1205. "pg_desc": pg.group_desc,
  1206. "backend_config": get_backend_config(pg),
  1207. "pg_size": _get_group_size(pg),
  1208. "ranks": get_process_group_ranks(pg),
  1209. }
  1210. def _get_all_pg_configs() -> list[dict[str, Any]]:
  1211. """
  1212. Return the pg configuration of all the process groups.
  1213. """
  1214. config_info: list[dict[str, Any]] = [_get_pg_config(pg) for pg in _world.pg_map]
  1215. return config_info
  1216. def get_pg_count() -> int:
  1217. """
  1218. Return the number of process groups.
  1219. """
  1220. return _world.group_count
  1221. def get_node_local_rank(fallback_rank: int | None = None) -> int:
  1222. """
  1223. Return the local rank of the current process relative to the node.
  1224. Semantically, this is a useful concept for mapping processes to devices.
  1225. For example, on a node with 8 accelerator you could use the node local rank to decide
  1226. which accelerator device to bind the process to.
  1227. In practice, the actual assignment of node local ranks is handled by the process launcher outside of pytorch,
  1228. and communicated via the `LOCAL_RANK` environment variable.
  1229. Torchrun will automatically populate `LOCAL_RANK`, but other launchers may not. If `LOCAL_RANK` is unspecified,
  1230. this API will fall back to the provided kwarg 'fallback_rank' if specified, otherwise it will raise an error. The
  1231. intent is to allow writing an application that runs either in single or multi device contexts without error.
  1232. """
  1233. if "LOCAL_RANK" in os.environ:
  1234. return int(os.environ["LOCAL_RANK"])
  1235. elif fallback_rank is not None:
  1236. return int(fallback_rank)
  1237. raise RuntimeError(
  1238. "LOCAL_RANK is not in the environment. Consider passing fallback_rank to allow `get_node_local_rank` to work, "
  1239. "assuming you are not running in a multi-device context and want the code to run locally instead."
  1240. )
  1241. def _add_ephemeral_timeout_for_all_pgs(timeout: timedelta) -> None:
  1242. """
  1243. This API adds an ephemeral timeout extension for all PGs locally
  1244. on one rank. The timeout gets reset when the first collective issued
  1245. after API called finished.
  1246. NOTE: We only support to set timeout for cuda backends for now.
  1247. NOTE: While this feature
  1248. provides flexibility in specific scenarios, it introduces statefulness
  1249. to timeout setting. Therefore, it is advisable to use this API sparingly
  1250. and consider alternative approaches, such as directly setting the timeout
  1251. or utilizing a barrier collective (one can set any timeout to the barrier),
  1252. whenever feasible.
  1253. Args:
  1254. timeout (timedelta): The delta of timeout to extend.
  1255. Returns:
  1256. None.
  1257. """
  1258. for pg in _world.pg_map:
  1259. devices = pg._device_types
  1260. if torch.device("cuda") in devices:
  1261. backend = pg._get_backend(torch.device("cuda"))
  1262. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  1263. backend._add_ephemeral_timeout(timeout)
  1264. def _set_pg_timeout(timeout: timedelta, group: ProcessGroup | None = None) -> None:
  1265. """
  1266. Set the timeout for the given process group when users want to use a different timeout instead of
  1267. default values.
  1268. Args:
  1269. timeout (timedelta): Timeout for operations executed against the process group which
  1270. users want to set. Default value is 10 minutes for NCCL and 30 minutes for other backends.
  1271. This is the duration after which collectives will be aborted asynchronously and the process will crash.
  1272. This is done since CUDA execution is async and it is no longer safe to continue executing user code since
  1273. failed async NCCL operations might result in subsequent CUDA operations running on corrupted data.
  1274. When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.
  1275. group (ProcessGroup, optional): The process group to work on. The
  1276. default is the general main process group. If another specific group
  1277. is specified, the calling process must be part of :attr:`group`.
  1278. Returns:
  1279. None
  1280. """
  1281. if group is None:
  1282. group = _get_default_group()
  1283. if _rank_not_in_group(group):
  1284. raise ValueError("Invalid process group specified")
  1285. if not isinstance(group, ProcessGroup):
  1286. raise AssertionError(f"Expected ProcessGroup, got {type(group)}")
  1287. devices = group._device_types
  1288. backends = set()
  1289. if torch.device("cpu") in devices and is_gloo_available():
  1290. backend = group._get_backend(torch.device("cpu"))
  1291. if isinstance(backend, ProcessGroupGloo):
  1292. backends.add(backend)
  1293. if torch.device("cuda") in devices:
  1294. backend = group._get_backend(torch.device("cuda"))
  1295. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  1296. backends.add(backend) # type: ignore[arg-type]
  1297. elif is_gloo_available() and isinstance(backend, ProcessGroupGloo):
  1298. backends.add(backend) # type: ignore[arg-type]
  1299. elif _use_torchcomms_enabled() and isinstance(backend, _BackendWrapper):
  1300. backends.add(backend) # type: ignore[arg-type]
  1301. if len(backends) == 0:
  1302. warnings.warn(
  1303. "Set timeout is now only supported for either nccl or gloo.", stacklevel=2
  1304. )
  1305. for backend in backends:
  1306. backend._set_default_timeout(timeout)
  1307. @_exception_logger
  1308. @_time_logger
  1309. def init_process_group(
  1310. backend: str | None = None,
  1311. init_method: str | None = None,
  1312. timeout: timedelta | None = None,
  1313. world_size: int = -1,
  1314. rank: int = -1,
  1315. store: Store | None = None,
  1316. group_name: str = "",
  1317. pg_options: Any | None = None,
  1318. device_id: torch.device | int | None = None,
  1319. _ranks: list[int] | None = None,
  1320. ) -> None:
  1321. """
  1322. Initialize the default distributed process group.
  1323. This will also initialize the distributed package.
  1324. There are 2 main ways to initialize a process group:
  1325. 1. Specify ``store``, ``rank``, and ``world_size`` explicitly.
  1326. 2. Specify ``init_method`` (a URL string) which indicates where/how
  1327. to discover peers. Optionally specify ``rank`` and ``world_size``,
  1328. or encode all required parameters in the URL and omit them.
  1329. If neither is specified, ``init_method`` is assumed to be "env://".
  1330. Args:
  1331. backend (str or Backend, optional): The backend to use. Depending on
  1332. build-time configurations, valid values include ``mpi``, ``gloo``,
  1333. ``nccl``, ``ucc``, ``xccl`` or one that is registered by a third-party
  1334. plugin.
  1335. Since 2.6, if ``backend`` is not provided, c10d will use a backend
  1336. registered for the device type indicated by the `device_id` kwarg
  1337. (if provided). The known default registrations today are: ``nccl``
  1338. for ``cuda``, ``gloo`` for ``cpu``, ``xccl`` for ``xpu``.
  1339. If neither ``backend`` nor ``device_id`` is provided, c10d will
  1340. detect the accelerator on the run-time machine and use a backend
  1341. registered for that detected accelerator (or ``cpu``).
  1342. This field can be given as a lowercase string (e.g., ``"gloo"``),
  1343. which can also be accessed via :class:`Backend` attributes (e.g.,
  1344. ``Backend.GLOO``).
  1345. If using multiple processes per machine with ``nccl`` backend, each
  1346. process must have exclusive access to every GPU it uses, as sharing
  1347. GPUs between processes can result in deadlock or NCCL invalid usage.
  1348. ``ucc`` backend is experimental.
  1349. Default backend for the device can be queried with
  1350. :func:`get_default_backend_for_device`.
  1351. init_method (str, optional): URL specifying how to initialize the
  1352. process group. Default is "env://" if no
  1353. ``init_method`` or ``store`` is specified.
  1354. Mutually exclusive with ``store``.
  1355. world_size (int, optional): Number of processes participating in
  1356. the job. Required if ``store`` is specified.
  1357. rank (int, optional): Rank of the current process (it should be a
  1358. number between 0 and ``world_size``-1).
  1359. Required if ``store`` is specified.
  1360. store(Store, optional): Key/value store accessible to all workers, used
  1361. to exchange connection/address information.
  1362. Mutually exclusive with ``init_method``.
  1363. timeout (timedelta, optional): Timeout for operations executed against
  1364. the process group. Default value is 10 minutes for NCCL and 30 minutes for other backends.
  1365. This is the duration after which collectives will be aborted asynchronously and the process will crash.
  1366. This is done since CUDA execution is async and it is no longer safe to continue executing user code since
  1367. failed async NCCL operations might result in subsequent CUDA operations running on corrupted data.
  1368. When TORCH_NCCL_BLOCKING_WAIT is set, the process will block and wait for this timeout.
  1369. group_name (str, optional, deprecated): Group name. This argument is ignored
  1370. pg_options (ProcessGroupOptions, optional): process group options
  1371. specifying what additional options need to be passed in during
  1372. the construction of specific process groups. As of now, the only
  1373. options we support is ``ProcessGroupNCCL.Options`` for the ``nccl``
  1374. backend, ``is_high_priority_stream`` can be specified so that
  1375. the nccl backend can pick up high priority cuda streams when
  1376. there're compute kernels waiting. For other available options to config nccl,
  1377. See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-t
  1378. device_id (torch.device | int, optional): a single, specific device
  1379. this process will work on, allowing for backend-specific
  1380. optimizations. Currently this has two effects, only under
  1381. NCCL: the communicator is immediately formed (calling
  1382. ``ncclCommInit*`` immediately rather than the normal lazy
  1383. call) and sub-groups will use ``ncclCommSplit`` when
  1384. possible to avoid unnecessary overhead of group creation. If you
  1385. want to know NCCL initialization error early, you can also use this
  1386. field. If an `int` is provided, the API assumes that the accelerator
  1387. type at compile time will be used.
  1388. _ranks: The ranks in the process group. If provided, the process
  1389. group name will be the hash of all the ranks in the group.
  1390. .. note:: To enable ``backend == Backend.MPI``, PyTorch needs to be built from source
  1391. on a system that supports MPI.
  1392. .. note:: Support for multiple backends is experimental. Currently when no backend is
  1393. specified, both ``gloo`` and ``nccl`` backends will be created. The ``gloo`` backend
  1394. will be used for collectives with CPU tensors and the ``nccl`` backend will be used
  1395. for collectives with CUDA tensors. A custom backend can be specified by passing in
  1396. a string with format "<device_type>:<backend_name>,<device_type>:<backend_name>", e.g.
  1397. "cpu:gloo,cuda:custom_backend".
  1398. """
  1399. global _world
  1400. global _backend
  1401. global _default_pg_init_method
  1402. if GroupMember.WORLD is not None:
  1403. raise ValueError("trying to initialize the default process group twice!")
  1404. set_pytorch_distributed_envs_from_justknobs()
  1405. # Depending on the import order, some trace_rules functions may be evaluated
  1406. # during the import phase. In such a case, these functions may not correctly
  1407. # add the distributed related rules due to import circular dependency.
  1408. # We need to clear the lru_cache during the runtime to ensure the correctness
  1409. # of these trace_rules.
  1410. #
  1411. # Since this API must be called before all distributed code being compiled,
  1412. # clearing the cache here should be safe.
  1413. if "torch._dynamo" in sys.modules:
  1414. torch._dynamo.trace_rules.clear_lru_cache()
  1415. if not ((store is None) or (init_method is None)):
  1416. raise AssertionError("Cannot specify both init_method and store.")
  1417. if store is not None:
  1418. if not world_size > 0:
  1419. raise AssertionError("world_size must be positive if using store")
  1420. if not rank >= 0:
  1421. raise AssertionError("rank must be non-negative if using store")
  1422. elif init_method is None:
  1423. init_method = "env://"
  1424. # Get the compile-time accelerator type.
  1425. # None indicates no accelerator support.
  1426. acc = torch.accelerator.current_accelerator()
  1427. # Auto complete device id
  1428. if isinstance(device_id, int):
  1429. if acc is None:
  1430. raise ValueError(
  1431. "device_id is an int, but no accelerator support is found from the current compilation. "
  1432. "Please use a different compiled version that supports your accelerator."
  1433. )
  1434. device_id = torch.device(acc.type, device_id)
  1435. # Sanity check device_id
  1436. if device_id is not None and device_id.type != "cpu":
  1437. # Type
  1438. if acc is None or device_id.type != acc.type:
  1439. raise ValueError(
  1440. f"device_id {device_id} does not match the current compilation's accelerator support: {acc}. "
  1441. "Please use a different compiled version that supports your accelerator."
  1442. )
  1443. # Index
  1444. if device_id.index is None:
  1445. raise ValueError("Please use a device_id with index.")
  1446. # Range
  1447. if device_id.index >= torch.accelerator.device_count():
  1448. raise ValueError(
  1449. f"device_id {device_id} is out of range. Please use a device index less than "
  1450. f"the number of accelerators available: {torch.accelerator.device_count()}."
  1451. )
  1452. logger.info("Using device: %s", device_id)
  1453. # If user did not provide a backend string but provided a device id, e.g.
  1454. # >>> init_process_group(device_id=device)
  1455. # we try to figure out the backend name based on the device type.
  1456. if backend is None and device_id is not None:
  1457. # Note: 3rd-party devices can register default backend through the
  1458. # default map below.
  1459. backend = Backend.default_device_backend_map.get(device_id.type)
  1460. # If we still cannot figure it out, e.g.
  1461. # >>> init_process_group()
  1462. # we set it to `undefined` and rely on lazy init.
  1463. if backend is None:
  1464. backend = "undefined"
  1465. # Convert string into `Backend` type
  1466. backend = Backend(backend)
  1467. if timeout is None:
  1468. timeout = _get_default_timeout(backend)
  1469. _check_valid_timeout(timeout)
  1470. """
  1471. Group name is not visible to users unless they access
  1472. internals of c10d. This means we can ignore the value
  1473. they provide as it not exposed in a public way.
  1474. """
  1475. if _ranks is None or len(_ranks) == 0:
  1476. group_name = _process_group_name([], use_hashed_name=False)
  1477. else:
  1478. group_name = _process_group_name(_ranks, use_hashed_name=True)
  1479. if backend == Backend.MPI:
  1480. if world_size != -1 or rank != -1:
  1481. warnings.warn(
  1482. f"For MPI backend, world_size ({world_size}) and rank ({rank}) "
  1483. "are ignored since they are assigned by the "
  1484. "MPI runtime.",
  1485. stacklevel=2,
  1486. )
  1487. default_pg, _ = _new_process_group_helper(
  1488. -1,
  1489. -1,
  1490. [],
  1491. backend,
  1492. Store(), # Placeholder value since store cannot be None
  1493. group_name,
  1494. timeout=timeout,
  1495. group_desc="default_pg",
  1496. )
  1497. else:
  1498. # backward compatible API
  1499. if store is None:
  1500. if backend == Backend.FAKE:
  1501. from torch.testing._internal.distributed.fake_pg import FakeStore
  1502. store = FakeStore()
  1503. else:
  1504. rendezvous_iterator = rendezvous(
  1505. not_none(init_method), rank, world_size, timeout=timeout
  1506. )
  1507. store, rank, world_size = next(rendezvous_iterator)
  1508. store.set_timeout(timeout)
  1509. # Use a PrefixStore to avoid accidental overrides of keys used by
  1510. # different systems (e.g. RPC) in case the store is multi-tenant.
  1511. store = PrefixStore("default_pg", store)
  1512. default_pg, _ = _new_process_group_helper(
  1513. world_size,
  1514. rank,
  1515. [],
  1516. backend,
  1517. store,
  1518. group_name,
  1519. backend_options=pg_options,
  1520. timeout=timeout,
  1521. device_id=device_id,
  1522. group_desc="default_pg",
  1523. )
  1524. _update_default_pg(default_pg)
  1525. _world.pg_group_ranks[GroupMember.WORLD] = { # type: ignore[index]
  1526. i: i
  1527. for i in range(GroupMember.WORLD.size()) # type: ignore[attr-defined]
  1528. }
  1529. _backend = _world.pg_map[not_none(GroupMember.WORLD)][0]
  1530. _default_pg_init_method = init_method
  1531. old_hook = sys.excepthook
  1532. excepthook_prefix = f"[rank{get_rank()}]"
  1533. def _distributed_excepthook(*args):
  1534. old_stderr = sys.stderr
  1535. sys.stderr = buf = io.StringIO()
  1536. try:
  1537. old_hook(*args)
  1538. finally:
  1539. sys.stderr = old_stderr
  1540. msg = buf.getvalue()
  1541. msg = "\n".join(
  1542. f"{excepthook_prefix}: {s}" if s != "" else "" for s in msg.split("\n")
  1543. )
  1544. sys.stderr.write(msg)
  1545. sys.stderr.flush()
  1546. sys.excepthook = _distributed_excepthook
  1547. if _is_barrier_after_init() == 1:
  1548. # barrier at the end to ensure that once we return from this method, all
  1549. # process groups including global variables (if any) are updated
  1550. # correctly on all ranks.
  1551. # Update 04/2023: for large-scale runs, this barrier (esp. store-based
  1552. # barrier) may be costly and/or unscalable. Also, in a lot of cases,
  1553. # these barriers may be unnecessary, as proven by a green CI after
  1554. # removal. An environment variable `TORCH_DIST_INIT_BARRIER` has been
  1555. # added which enables this barrier only when set to 1.
  1556. logger.debug(
  1557. "Performing barrier after ProcessGroup initialization since "
  1558. "TORCH_DIST_INIT_BARRIER = 1"
  1559. )
  1560. if backend == Backend.MPI:
  1561. # MPI backend doesn't use store.
  1562. barrier()
  1563. else:
  1564. # Use store based barrier here since barrier() used a bunch of
  1565. # default devices and messes up NCCL internal state.
  1566. _store_based_barrier(rank, store, group_name, world_size, timeout)
  1567. def _get_split_source(pg: ProcessGroup):
  1568. split_from = None
  1569. if pg.bound_device_id:
  1570. split_from = pg._get_backend(pg.bound_device_id)
  1571. elif pg is _world.default_pg:
  1572. try:
  1573. split_from = pg._get_backend(torch.device("cuda"))
  1574. except RuntimeError:
  1575. # no cuda device associated with this backend
  1576. pass
  1577. if not split_from or not split_from.supports_splitting:
  1578. return None
  1579. # If necessary, find a backend to split from by peeling process
  1580. # group wrappers from our potentially wrapped process group.
  1581. while _GLOO_AVAILABLE and isinstance(split_from, _ProcessGroupWrapper):
  1582. split_from = split_from.wrapped_pg
  1583. return split_from
  1584. def _new_process_group_helper(
  1585. group_size,
  1586. group_rank,
  1587. global_ranks_in_group,
  1588. backend,
  1589. store,
  1590. group_name: GroupName,
  1591. backend_options=None,
  1592. timeout=None,
  1593. pg_tag=None,
  1594. device_id=None,
  1595. group_desc=None,
  1596. ):
  1597. """
  1598. Create a new distributed process group.
  1599. This function must be called by ALL processes in the global group, even if
  1600. the calling process is not part of the newly created group. In that case,
  1601. this function returns GroupMember.NON_GROUP_MEMBER.
  1602. This function is called with ``global_ranks_in_group == []`` for the default group.
  1603. """
  1604. global _world
  1605. if group_name in _world.pg_names.values():
  1606. raise ValueError(
  1607. "The specified group name has already been "
  1608. "created, please use a different group name"
  1609. )
  1610. if device_id is not None and (device_id.index is None or device_id.type == "cpu"):
  1611. raise ValueError(
  1612. "init_process_group device_id parameter must be an accelerator with an index"
  1613. )
  1614. # Note: _new_process_group_helper is only called from init_process_group, which always provides a timeout value
  1615. _check_valid_timeout(timeout)
  1616. if pg_tag not in [None, ""]:
  1617. # creating with the same tag and rank set results in the same underlying PG
  1618. existing_group = _find_pg_by_ranks_and_tag(pg_tag, global_ranks_in_group)
  1619. if existing_group:
  1620. _, prefix_store = _world.pg_map[existing_group]
  1621. return existing_group, prefix_store
  1622. group_desc = "undefined" if group_desc is None else group_desc
  1623. # The list of group ranks is empty if we're creating the default group.
  1624. is_default_group = len(global_ranks_in_group) == 0
  1625. # nccl and potentially other backends allow creation of
  1626. # communicators based on pre-existing ones, which can save
  1627. # initialization time. Due to lazy initialization of
  1628. # communicators in some backends, we have to be careful and only
  1629. # split when we *know* the default PG has already started communicator initialization.
  1630. # We know this if we have bound a device id to the default pg (eager initialized).
  1631. if is_initialized() and _get_default_group().bound_device_id:
  1632. split_from = _get_split_source(_get_default_group())
  1633. else:
  1634. split_from = None
  1635. # If this is a subgroup (which means group_ranks is specified),
  1636. # we check if the current process is a member of the new group.
  1637. if not is_default_group:
  1638. global_rank = _get_default_group().rank()
  1639. if global_rank not in global_ranks_in_group:
  1640. # If we are using `ncclCommSplit` (or similar split from
  1641. # other APIs) to create the communicator, we will need to
  1642. # call `ncclCommSplit` on *all* ranks in this new group's
  1643. # parent group, even those not in the new group. This is
  1644. # a requirement of the NCCL API as otherwise we would get
  1645. # out of sync.
  1646. if split_from:
  1647. split_from.perform_nocolor_split(_get_default_group().bound_device_id)
  1648. return GroupMember.NON_GROUP_MEMBER, None
  1649. prefix_store = PrefixStore(f"{group_name}/", store)
  1650. # The backend for PG will be set later based on what's inside BackendConfig
  1651. # and timeout are set in each backend's option.
  1652. pg: ProcessGroup = ProcessGroup(
  1653. prefix_store,
  1654. group_rank,
  1655. group_size,
  1656. )
  1657. backend_config = BackendConfig(backend)
  1658. # Set the default backend when single backend is passed in.
  1659. if "," not in str(backend) and ":" not in str(backend):
  1660. if backend not in Backend.backend_type_map:
  1661. raise AssertionError(f"Unknown backend type {backend}")
  1662. if backend == Backend.UNDEFINED:
  1663. # Currently when backend is UNDEFINED, only one backend will be initialized
  1664. # we use nccl (if cuda is available) or gloo as default backend
  1665. # so we can correctly call getDefaultBackend which in ProcessGroup.
  1666. if Backend.NCCL in backend_config.get_device_backend_map().values():
  1667. pg._set_default_backend(ProcessGroup.BackendType.NCCL)
  1668. else:
  1669. pg._set_default_backend(ProcessGroup.BackendType.GLOO)
  1670. else:
  1671. pg._set_default_backend(Backend.backend_type_map[backend])
  1672. # In order to correctly call pg._has_hooks(), we should set the default backend
  1673. # when multi backend is passed in
  1674. else:
  1675. if Backend.NCCL in backend_config.device_backend_map.values():
  1676. pg._set_default_backend(ProcessGroup.BackendType.NCCL)
  1677. elif Backend._plugins.keys():
  1678. custom_backend = next(iter(Backend._plugins.keys()))
  1679. if custom_backend in backend_config.device_backend_map.values():
  1680. pg._set_default_backend(ProcessGroup.BackendType.CUSTOM)
  1681. else:
  1682. pg._set_default_backend(ProcessGroup.BackendType.GLOO)
  1683. if device_id:
  1684. pg.bound_device_id = device_id
  1685. backend_class: torch._C._distributed_c10d.Backend
  1686. for device, backend_str in backend_config.get_device_backend_map().items():
  1687. # Use the group name as prefix in the default store, such that
  1688. # a single store can be reused by multiple groups.
  1689. backend_prefix_store = PrefixStore(f"{device}/", prefix_store)
  1690. if _use_torchcomms_enabled() and backend_str not in [Backend.FAKE]:
  1691. torch_device = torch.device(device)
  1692. logger.warning(
  1693. "Using TorchComms backend (enabled via %s) for device %s with backend %s",
  1694. "TORCH_DISTRIBUTED_USE_TORCHCOMMS env var"
  1695. if os.environ.get("TORCH_DISTRIBUTED_USE_TORCHCOMMS")
  1696. else "dist_config.use_torchcomms",
  1697. torch_device,
  1698. backend_str,
  1699. )
  1700. # TODO: figure out pg option conversion for torchComms.
  1701. comm = new_comm(
  1702. backend_str, torch_device, name=group_name, store=backend_prefix_store
  1703. )
  1704. # Keep a reference so the comm outlives this function scope.
  1705. _world.comms.append(comm)
  1706. group_name = GroupName(group_name)
  1707. # pyrefly: ignore [bad-assignment]
  1708. backend_class = _BackendWrapper(comm)
  1709. backend_type = ProcessGroup.BackendType.CUSTOM
  1710. elif backend_str == Backend.MPI:
  1711. if not is_mpi_available():
  1712. raise RuntimeError(
  1713. "Distributed package doesn't have MPI built in."
  1714. " MPI is only included if you build PyTorch from"
  1715. " source on a host that has MPI installed."
  1716. )
  1717. backend_class = ProcessGroupMPI.create(global_ranks_in_group)
  1718. backend_type = ProcessGroup.BackendType.MPI
  1719. if not backend_class:
  1720. return GroupMember.NON_GROUP_MEMBER, None
  1721. # create new process group with accurate rank and size
  1722. if pg.rank() == -1 and pg.size() == -1:
  1723. pg = ProcessGroup(
  1724. backend_prefix_store,
  1725. backend_class.rank(),
  1726. backend_class.size(),
  1727. )
  1728. pg._set_default_backend(backend_type)
  1729. elif backend_str == Backend.GLOO:
  1730. # TODO: remove this check after lazy initialization is supported
  1731. # if pg_options is not None:
  1732. # raise RuntimeError("GLOO options not supported")
  1733. if not is_gloo_available():
  1734. raise RuntimeError("Distributed package doesn't have Gloo built in")
  1735. backend_class = ProcessGroupGloo(
  1736. backend_prefix_store,
  1737. group_rank,
  1738. group_size,
  1739. # pyrefly: ignore [bad-argument-type]
  1740. timeout=timeout,
  1741. )
  1742. backend_class.options.global_ranks_in_group = global_ranks_in_group
  1743. backend_class.options.group_name = group_name
  1744. backend_type = ProcessGroup.BackendType.GLOO
  1745. elif backend_str == Backend.NCCL:
  1746. if not is_nccl_available():
  1747. raise RuntimeError("Distributed package doesn't have NCCL built in")
  1748. if backend_options is not None:
  1749. if not isinstance(backend_options, ProcessGroupNCCL.Options):
  1750. raise AssertionError(
  1751. "Expected backend_options argument to be of type ProcessGroupNCCL.Options"
  1752. )
  1753. if backend_options._timeout != timeout:
  1754. warnings.warn(
  1755. "backend_options._timeout was specified, "
  1756. "but timeout kwarg has a default value that will always override it. ",
  1757. stacklevel=2,
  1758. )
  1759. else:
  1760. # default backend_options for NCCL
  1761. backend_options = ProcessGroupNCCL.Options()
  1762. backend_options.is_high_priority_stream = False
  1763. # pyrefly: ignore [bad-argument-type]
  1764. backend_options._timeout = timeout
  1765. if split_from:
  1766. backend_options.split_from = split_from
  1767. backend_options.split_color = _process_group_color(
  1768. global_ranks_in_group
  1769. )
  1770. backend_options.global_ranks_in_group = global_ranks_in_group
  1771. backend_options.group_name = group_name
  1772. backend_class = ProcessGroupNCCL(
  1773. backend_prefix_store, group_rank, group_size, backend_options
  1774. )
  1775. backend_type = ProcessGroup.BackendType.NCCL
  1776. elif backend_str == Backend.UCC and is_ucc_available():
  1777. # TODO: once UCC plugin is fully deprecated, remove
  1778. # is_ucc_available() from above elif-condition and raise
  1779. # RuntimeError if is_ucc_available() returns false.
  1780. backend_class = ProcessGroupUCC(
  1781. backend_prefix_store,
  1782. group_rank,
  1783. group_size,
  1784. # pyrefly: ignore [bad-argument-type]
  1785. timeout=timeout,
  1786. )
  1787. backend_type = ProcessGroup.BackendType.UCC
  1788. elif backend_str == Backend.XCCL:
  1789. if not is_xccl_available():
  1790. raise RuntimeError("Distributed package doesn't have XCCL built in")
  1791. backend_options = ProcessGroupXCCL.Options()
  1792. backend_options.global_ranks_in_group = global_ranks_in_group
  1793. backend_options.group_name = group_name
  1794. # pyrefly: ignore [bad-argument-type]
  1795. backend_options._timeout = timeout
  1796. backend_class = ProcessGroupXCCL(
  1797. backend_prefix_store, group_rank, group_size, backend_options
  1798. )
  1799. backend_type = ProcessGroup.BackendType.XCCL
  1800. else:
  1801. if backend_str.upper() not in Backend._plugins:
  1802. raise AssertionError(f"Unknown c10d backend type {backend_str.upper()}")
  1803. backend_plugin = Backend._plugins[backend_str.upper()]
  1804. creator_fn = backend_plugin.creator_fn
  1805. extended_api = backend_plugin.extended_api
  1806. backend_type = ProcessGroup.BackendType.CUSTOM
  1807. if not extended_api:
  1808. backend_class = creator_fn(
  1809. backend_prefix_store, group_rank, group_size, timeout
  1810. )
  1811. else:
  1812. dist_backend_opts = _DistributedBackendOptions()
  1813. dist_backend_opts.store = backend_prefix_store
  1814. dist_backend_opts.group_rank = group_rank
  1815. dist_backend_opts.group_size = group_size
  1816. # pyrefly: ignore [bad-argument-type]
  1817. dist_backend_opts.timeout = timeout
  1818. dist_backend_opts.group_id = group_name
  1819. dist_backend_opts.global_ranks_in_group = global_ranks_in_group
  1820. backend_class = creator_fn(dist_backend_opts, backend_options)
  1821. # Set sequence numbers for gloo and nccl backends.
  1822. if backend_str == Backend.GLOO and not _use_torchcomms_enabled():
  1823. if not isinstance(backend_class, ProcessGroupGloo):
  1824. raise AssertionError(
  1825. f"Expected ProcessGroupGloo, got {type(backend_class)}"
  1826. )
  1827. backend_class._set_sequence_number_for_group()
  1828. elif backend_str == Backend.NCCL and not _use_torchcomms_enabled():
  1829. if not isinstance(backend_class, ProcessGroupNCCL):
  1830. raise AssertionError(
  1831. f"Expected ProcessGroupNCCL, got {type(backend_class)}"
  1832. )
  1833. backend_class._set_sequence_number_for_group()
  1834. # If the type is a subclass of ProcessGroup then return this process group immediately
  1835. # TODO: This defaults to the old behavior for PythonProcessGroups which overwrites the
  1836. # ProcessGroup instance
  1837. if issubclass(type(backend_class), ProcessGroup):
  1838. pg = backend_class # type: ignore[assignment]
  1839. break
  1840. # Process group wrapper initialization for supported PGs when TORCH_DISTRIBUTED_DEBUG is set
  1841. if (
  1842. backend_str in [Backend.GLOO, Backend.NCCL, Backend.XCCL, Backend.UCC]
  1843. or backend_str.upper() in Backend._plugins
  1844. ):
  1845. # In debug mode and if GLOO is available, wrap in a wrapper PG that
  1846. # enables enhanced collective checking for debuggability.
  1847. if get_debug_level() == DebugLevel.DETAIL:
  1848. if not _GLOO_AVAILABLE:
  1849. logger.info(
  1850. """TORCH_DISTRIBUTED_DEBUG was set to DETAIL, but
  1851. GLOO is not available. Build with Gloo to
  1852. create a wrapper process group in debug mode
  1853. to aid collective desynchronization debugging."""
  1854. )
  1855. else:
  1856. backend_class = _create_process_group_wrapper(
  1857. wrapped_pg=backend_class,
  1858. store_prefix=group_name,
  1859. store=backend_prefix_store,
  1860. rank=group_rank,
  1861. world_size=group_size,
  1862. # pyrefly: ignore [bad-argument-type]
  1863. timeout=timeout,
  1864. )
  1865. elif (
  1866. get_debug_level() == DebugLevel.DETAIL
  1867. or os.environ.get("TORCH_DISTRIBUTED_DEBUG", "") == "DETAIL"
  1868. ) and _use_torchcomms_enabled():
  1869. logger.warning(
  1870. "(Backend %s) Debug Mode not supported for torchcomms.", backend_str
  1871. )
  1872. # register only a single backend when all get_device_backend_map values are the same
  1873. if len(set(backend_config.get_device_backend_map().values())) == 1:
  1874. for device in backend_config.get_device_backend_map():
  1875. pg._register_backend(torch.device(device), backend_type, backend_class)
  1876. # break out of outer loop to not create any more backends
  1877. break
  1878. pg._register_backend(torch.device(device), backend_type, backend_class)
  1879. # set group_name and group_dsec to backend
  1880. if group_name is None:
  1881. raise AssertionError("group_name must not be None")
  1882. if group_desc is None:
  1883. raise AssertionError("group_desc must not be None")
  1884. pg._set_group_name(group_name)
  1885. pg._set_group_desc(group_desc)
  1886. if device_id and pg._get_backend(device_id).supports_splitting:
  1887. eager_backend = pg._get_backend(device_id)
  1888. eager_backend.eager_connect_single_device(device_id)
  1889. # update global state
  1890. _world.pg_map[pg] = (backend, prefix_store)
  1891. _world.pg_names[pg] = group_name
  1892. _register_process_group(group_name, pg)
  1893. _world.pg_backend_config[pg] = str(backend_config)
  1894. # "" is the default tag for user PGs
  1895. if pg_tag in [None, ""]:
  1896. pg_tag = f"ptd:{group_name}"
  1897. _world.tags_to_pg.setdefault("", []).append(pg)
  1898. else:
  1899. pg_tag = f"user:{pg_tag}"
  1900. _world.tags_to_pg.setdefault(pg_tag, []).append(pg)
  1901. _world.pg_to_tag[pg] = pg_tag
  1902. return pg, prefix_store
  1903. def destroy_process_group(group: ProcessGroup | None = None):
  1904. """
  1905. Destroy a given process group, and deinitialize the distributed package.
  1906. Args:
  1907. group (ProcessGroup, optional): The process group to be destroyed, if
  1908. group.WORLD is given, all process
  1909. groups including the default one will
  1910. be destroyed.
  1911. """
  1912. global _world
  1913. if group == GroupMember.NON_GROUP_MEMBER:
  1914. return
  1915. if group is None:
  1916. pg = GroupMember.WORLD
  1917. else:
  1918. pg = group
  1919. if pg is None:
  1920. raise AssertionError("Process group cannot be None")
  1921. if _world.pg_map.get(pg, None) is None:
  1922. raise ValueError("Invalid process group specified")
  1923. # When users register Python onCompletion hooks, those hooks will run on a
  1924. # different thread than the main thread. Today, the ProcessGroup dtor does
  1925. # wait for that thread. However, the dtor might finish after the Python
  1926. # Interpreter exits. After that grabbing the GIL for the Python hook will crash.
  1927. # We can either revive the interpreter when running hooks or keep the main one
  1928. # alive until all works and hooks are done. The current implementation does the
  1929. # latter. Therefore, we explicitly call _wait_for_pending_works() here to wait
  1930. # for the pending hooks to finish.
  1931. if type(pg) is ProcessGroup and pg._has_hooks():
  1932. pg._wait_for_pending_works()
  1933. if group is None or group == GroupMember.WORLD:
  1934. for comm in _world.comms:
  1935. comm.finalize()
  1936. _world.comms.clear()
  1937. # shutdown all backends in the order of pg names. shutting down in order because
  1938. # ncclCommAbort() was a 'collective' call in some versions of NCCL.
  1939. for pg_to_shutdown in sorted(
  1940. _world.pg_names, key=lambda x: _world.pg_names[x], reverse=True
  1941. ):
  1942. pg_to_shutdown.shutdown()
  1943. _update_default_pg(None)
  1944. _world.pg_map.clear()
  1945. _world.pg_names.clear()
  1946. _world.pg_group_ranks.clear()
  1947. _world.pg_backend_config.clear()
  1948. _world.pg_to_tag.clear()
  1949. _world.tags_to_pg.clear()
  1950. _world.pg_coalesce_state.clear()
  1951. _unregister_all_process_groups()
  1952. # when process group doesn't have an explicit name (only WORLD (default)
  1953. # process group can have an explicit name), we use global _world.group_count
  1954. # to generate the name. We need to reset the counter on destruction to
  1955. # allow consistent value to be generated when we re-create process
  1956. # groups after some trainers recover from failure
  1957. #
  1958. # We only reset this when WORLD is being destroyed because if this
  1959. # process group is in good state, we aren't dealing with failures.
  1960. _world.group_count = 0
  1961. else:
  1962. if _TORCHCOMM_AVAILABLE:
  1963. for device_type in pg._device_types:
  1964. backend = pg._get_backend(device_type)
  1965. if isinstance(backend, _BackendWrapper):
  1966. backend.get_comm().finalize()
  1967. _world.comms.clear()
  1968. pg.shutdown()
  1969. del _world.pg_map[pg]
  1970. del _world.pg_names[pg]
  1971. del _world.pg_group_ranks[pg]
  1972. del _world.pg_backend_config[pg]
  1973. if pg in _world.pg_coalesce_state:
  1974. warnings.warn(
  1975. "Some coalesced collectives haven't been launched when "
  1976. "ProcessGroup is destroyed. They will be cleaned.",
  1977. stacklevel=2,
  1978. )
  1979. del _world.pg_coalesce_state[pg]
  1980. tag = _world.pg_to_tag.get(pg)
  1981. del _world.pg_to_tag[pg]
  1982. if tag is not None:
  1983. try:
  1984. _world.tags_to_pg[tag].remove(pg)
  1985. if tag.startswith("ptd:"):
  1986. _world.tags_to_pg[""].remove(pg)
  1987. except Exception:
  1988. pass
  1989. _unregister_process_group(pg.group_name)
  1990. def _abort_process_group(group: ProcessGroup | None = None):
  1991. """
  1992. Abort a given process group. If group.WORLD (i.e. `None`) is given, all
  1993. process groups including the default one will be aborted.
  1994. Args:
  1995. group (ProcessGroup, optional): The process group to be aborted.
  1996. .. note:: this API is experimental and currently only works with the NCCL
  1997. backend.
  1998. .. note:: this API should be used with `TORCH_NCCL_ASYNC_ERROR_HANDLING`
  1999. turned off (i.e. set to 0). Otherwise, ProcessGroupNCCL's watchdog may
  2000. automatically handle errors or timeouts for you including aborting the
  2001. ProcessGroup.
  2002. """
  2003. global _world
  2004. if group == GroupMember.NON_GROUP_MEMBER:
  2005. return
  2006. pg = group or GroupMember.WORLD
  2007. if pg is None:
  2008. raise AssertionError("Process group cannot be None")
  2009. if _world.pg_map.get(pg, None) is None:
  2010. raise ValueError("Invalid process group specified or has been destroyed.")
  2011. try:
  2012. backend = pg._get_backend(torch.device("cuda"))
  2013. except RuntimeError:
  2014. backend = None
  2015. if group is None or group == GroupMember.WORLD:
  2016. # Abort all backends within a ncclGroupStart|End semantic.
  2017. # This ensures that different NCCL communicators' abort calls won't
  2018. # deadlock each other.
  2019. # For details, please see: https://github.com/pytorch/pytorch/issues/119797
  2020. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  2021. backend._group_start()
  2022. for pg_to_abort in sorted(
  2023. _world.pg_names, key=lambda x: _world.pg_names[x], reverse=True
  2024. ):
  2025. pg_to_abort.abort()
  2026. if is_nccl_available() and isinstance(backend, ProcessGroupNCCL):
  2027. backend._group_end()
  2028. _update_default_pg(None)
  2029. _world.pg_map.clear()
  2030. _world.pg_names.clear()
  2031. _world.pg_group_ranks.clear()
  2032. _world.pg_backend_config.clear()
  2033. _world.pg_to_tag.clear()
  2034. _world.tags_to_pg.clear()
  2035. _world.pg_coalesce_state.clear()
  2036. _unregister_all_process_groups()
  2037. # when process group doesn't have an explicit name (only WORLD (default)
  2038. # process group can have an explicit name), we use global _world.group_count
  2039. # to generate the name. We need to reset the counter on destruction to
  2040. # allow consistent value to be generated when we re-create process
  2041. # groups after some trainers recover from failure
  2042. #
  2043. # We only reset this when WORLD is being destroyed because if this
  2044. # process group is in good state, we aren't dealing with failures.
  2045. _world.group_count = 0
  2046. else:
  2047. pg.abort()
  2048. del _world.pg_map[pg]
  2049. del _world.pg_names[pg]
  2050. del _world.pg_group_ranks[pg]
  2051. del _world.pg_backend_config[pg]
  2052. if pg in _world.pg_coalesce_state:
  2053. warnings.warn(
  2054. "Some coalesced collectives haven't been launched when "
  2055. "ProcessGroup is aborted. They will be cleaned.",
  2056. stacklevel=2,
  2057. )
  2058. del _world.pg_coalesce_state[pg]
  2059. tag = _world.pg_to_tag.get(pg)
  2060. del _world.pg_to_tag[pg]
  2061. if tag is not None:
  2062. try:
  2063. _world.tags_to_pg[tag].remove(pg)
  2064. if tag.startswith("ptd:"):
  2065. _world.tags_to_pg[""].remove(pg)
  2066. except Exception:
  2067. pass
  2068. _unregister_process_group(pg.group_name)
  2069. def get_rank(group: ProcessGroup | None = None) -> int:
  2070. """
  2071. Return the rank of the current process in the provided ``group``, default otherwise.
  2072. Rank is a unique identifier assigned to each process within a distributed
  2073. process group. They are always consecutive integers ranging from 0 to
  2074. ``world_size``.
  2075. Args:
  2076. group (ProcessGroup, optional): The process group to work on. If None,
  2077. the default process group will be used.
  2078. Returns:
  2079. The rank of the process group
  2080. -1, if not part of the group
  2081. """
  2082. if _rank_not_in_group(group):
  2083. return -1
  2084. default_pg = _get_default_group()
  2085. if group is None or group is GroupMember.WORLD:
  2086. return default_pg.rank()
  2087. return get_group_rank(group, default_pg.rank())
  2088. def get_world_size(group: ProcessGroup | None = None) -> int:
  2089. """
  2090. Return the number of processes in the current process group.
  2091. Args:
  2092. group (ProcessGroup, optional): The process group to work on. If None,
  2093. the default process group will be used.
  2094. Returns:
  2095. The world size of the process group
  2096. -1, if not part of the group
  2097. """
  2098. if _rank_not_in_group(group):
  2099. return -1
  2100. return _get_group_size(group)
  2101. def isend(
  2102. tensor: torch.Tensor,
  2103. dst: int | None = None,
  2104. group: ProcessGroup | None = None,
  2105. tag: int = 0,
  2106. group_dst: int | None = None,
  2107. ) -> Work | None:
  2108. """
  2109. Send a tensor asynchronously.
  2110. .. warning::
  2111. Modifying ``tensor`` before the request completes causes undefined
  2112. behavior.
  2113. .. warning::
  2114. ``tag`` is not supported with the NCCL backend.
  2115. Unlike send, which is blocking, isend allows src == dst rank, i.e. send to self.
  2116. Args:
  2117. tensor (Tensor): Tensor to send.
  2118. dst (int): Destination rank on global process group (regardless of ``group`` argument)
  2119. group (ProcessGroup, optional): The process group to work on. If None,
  2120. the default process group will be used.
  2121. tag (int, optional): Tag to match send with remote recv
  2122. group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst``
  2123. Returns:
  2124. A distributed request object.
  2125. None, if not part of the group
  2126. """
  2127. group = _group_or_default_group(group)
  2128. group_dst = _canonicalize_group_rank(group, dst, group_dst)
  2129. _check_single_tensor(tensor, "tensor")
  2130. if _rank_not_in_group(group):
  2131. _warn_not_in_group("isend")
  2132. return None
  2133. if tensor.is_complex():
  2134. tensor = torch.view_as_real(tensor)
  2135. return group.send([tensor], group_dst, tag)
  2136. def irecv(
  2137. tensor: torch.Tensor,
  2138. src: int | None = None,
  2139. group: ProcessGroup | None = None,
  2140. tag: int = 0,
  2141. group_src: int | None = None,
  2142. ) -> Work | None:
  2143. """
  2144. Receives a tensor asynchronously.
  2145. .. warning::
  2146. ``tag`` is not supported with the NCCL backend.
  2147. Unlike recv, which is blocking, irecv allows src == dst rank, i.e. recv from self.
  2148. Args:
  2149. tensor (Tensor): Tensor to fill with received data.
  2150. src (int, optional): Source rank on global process group (regardless of ``group`` argument).
  2151. Will receive from any process if unspecified.
  2152. group (ProcessGroup, optional): The process group to work on. If None,
  2153. the default process group will be used.
  2154. tag (int, optional): Tag to match recv with remote send
  2155. group_src (int, optional): Destination rank on ``group``. Invalid to specify both ``src`` and ``group_src``.
  2156. Returns:
  2157. A distributed request object.
  2158. None, if not part of the group
  2159. """
  2160. _check_single_tensor(tensor, "tensor")
  2161. if _rank_not_in_group(group):
  2162. _warn_not_in_group("irecv")
  2163. return None
  2164. if tensor.is_complex():
  2165. tensor = torch.view_as_real(tensor)
  2166. group = _group_or_default_group(group)
  2167. if src is None and group_src is None:
  2168. return group.recv_anysource([tensor], tag)
  2169. else:
  2170. group_src = _canonicalize_group_rank(group, src, group_src)
  2171. return group.recv([tensor], group_src, tag)
  2172. @_exception_logger
  2173. def send(
  2174. tensor: torch.Tensor,
  2175. dst: int | None = None,
  2176. group: ProcessGroup | None = None,
  2177. tag: int = 0,
  2178. group_dst: int | None = None,
  2179. ) -> None:
  2180. """
  2181. Send a tensor synchronously.
  2182. .. warning::
  2183. ``tag`` is not supported with the NCCL backend.
  2184. Args:
  2185. tensor (Tensor): Tensor to send.
  2186. dst (int): Destination rank on global process group (regardless of ``group`` argument).
  2187. Destination rank should not be the same as the rank of the current process.
  2188. group (ProcessGroup, optional): The process group to work on. If None,
  2189. the default process group will be used.
  2190. tag (int, optional): Tag to match send with remote recv
  2191. group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst``.
  2192. """
  2193. group = _group_or_default_group(group)
  2194. group_dst = _canonicalize_group_rank(group, dst, group_dst)
  2195. _check_not_self_rank(group, group_dst, "destination")
  2196. work = isend(tensor, group=group, tag=tag, group_dst=group_dst)
  2197. if work is not None:
  2198. work.wait()
  2199. @_exception_logger
  2200. def recv(
  2201. tensor: torch.Tensor,
  2202. src: int | None = None,
  2203. group: ProcessGroup | None = None,
  2204. tag: int = 0,
  2205. group_src: int | None = None,
  2206. ) -> int:
  2207. """
  2208. Receives a tensor synchronously.
  2209. .. warning::
  2210. ``tag`` is not supported with the NCCL backend.
  2211. Args:
  2212. tensor (Tensor): Tensor to fill with received data.
  2213. src (int, optional): Source rank on global process group (regardless of ``group`` argument).
  2214. Will receive from any process if unspecified.
  2215. group (ProcessGroup, optional): The process group to work on. If None,
  2216. the default process group will be used.
  2217. tag (int, optional): Tag to match recv with remote send
  2218. group_src (int, optional): Destination rank on ``group``. Invalid to specify both ``src`` and ``group_src``.
  2219. Returns:
  2220. Sender rank
  2221. -1, if not part of the group
  2222. """
  2223. work = irecv(tensor, src=src, group=group, tag=tag, group_src=group_src)
  2224. if work is None:
  2225. return -1
  2226. work.wait()
  2227. if src is None:
  2228. if group_src is None:
  2229. group_src = work._source_rank()
  2230. group = _group_or_default_group(group)
  2231. _check_not_self_rank(group, group_src, "source")
  2232. src = get_global_rank(group, group_src)
  2233. return src
  2234. class _IllegalWork(Work):
  2235. def __getattribute__(self, name):
  2236. if name in [
  2237. "is_success",
  2238. "exception",
  2239. "wait",
  2240. "source_rank",
  2241. "_source_rank",
  2242. "result",
  2243. "synchronize",
  2244. ]:
  2245. raise ValueError(f"Illegal to call {name} on IllegalWork object")
  2246. class _CoalescingManager:
  2247. def __init__(self) -> None:
  2248. self.works: list[Work] = []
  2249. def append(self, work: Work | None = None):
  2250. if work:
  2251. self.works.append(work)
  2252. def wait(self):
  2253. for work in self.works:
  2254. work.wait()
  2255. @contextlib.contextmanager
  2256. def _coalescing_manager(
  2257. group: ProcessGroup | None = None,
  2258. device: torch.device | None = None,
  2259. async_ops: bool = False,
  2260. ):
  2261. """
  2262. Context manager used to coalesce collectives or P2P operations when possible.
  2263. Args:
  2264. group (`ProcessGroup`, optional): The process group to work on. If None,
  2265. the default process group will be used.
  2266. device (`torch.device`, optional): Default is None, set to a device if
  2267. there isn't a `**_coalesced` implementation by the backend.
  2268. async_ops (`bool`, optional): whether the coalesced ops are async ops.
  2269. Examples:
  2270. >>> # xdoctest: +SKIP("no rank")
  2271. >>> # Synchronous ops
  2272. >>> with _coalescing_manager():
  2273. >>> for i in range(num_colls):
  2274. >>> dist.all_reduce(tensors[i])
  2275. >>> # Asynchronous ops
  2276. >>> with _coalescing_manager(async_ops=True) as cm:
  2277. >>> for i in range(num_colls):
  2278. >>> dist.all_reduce(tensors[i])
  2279. >>> cm.wait()
  2280. .. warning::
  2281. :func:`_coalescing_manager` currently do not support coalescing
  2282. all-reduces with different reduce operators, e.g. `ReduceOp.SUM` mixed
  2283. with `ReduceOp.PRODUCT`.
  2284. """
  2285. group = group or _get_default_group()
  2286. op_list = _world.pg_coalesce_state.setdefault(group, [])
  2287. if op_list:
  2288. raise ValueError(
  2289. "ProcessGroup has non-empty op list at the start of coalescing"
  2290. )
  2291. if device:
  2292. group._start_coalescing(device)
  2293. cm = _CoalescingManager()
  2294. yield cm
  2295. work = None
  2296. op_list = _world.pg_coalesce_state.pop(group)
  2297. if op_list:
  2298. # Collectives supporting "Fast Path" coalescing are captured.
  2299. # See implementation in corresponding collective APIs.
  2300. # Currently supported:
  2301. # - coalesced `all_reduce`
  2302. # - coalesced `all_gather_into_tensor`
  2303. # - coalesced `reduce_scatter_tensor`
  2304. op0 = op_list[0].op
  2305. if op0 is all_reduce:
  2306. tensors = [op.tensor for op in op_list]
  2307. all_reduce_opts = AllreduceCoalescedOptions()
  2308. all_reduce_opts.reduceOp = not_none(op_list[0].redop)
  2309. all_reduce_opts.asyncOp = async_ops
  2310. work = group.allreduce_coalesced(tensors, all_reduce_opts)
  2311. elif op0 is all_gather_into_tensor:
  2312. inputs = []
  2313. outputs = []
  2314. for op in op_list:
  2315. inputs.append(op.tensor)
  2316. outputs.append(not_none(op.dst_tensor))
  2317. all_gather_opts = AllgatherOptions()
  2318. all_gather_opts.asyncOp = async_ops
  2319. work = group.allgather_into_tensor_coalesced(outputs, inputs)
  2320. elif op0 is reduce_scatter_tensor:
  2321. inputs = []
  2322. outputs = []
  2323. for op in op_list:
  2324. inputs.append(op.tensor)
  2325. outputs.append(not_none(op.dst_tensor))
  2326. reduce_opts = ReduceScatterOptions()
  2327. reduce_opts.reduceOp = not_none(op_list[0].redop)
  2328. reduce_opts.asyncOp = async_ops
  2329. work = group.reduce_scatter_tensor_coalesced(outputs, inputs, reduce_opts)
  2330. else:
  2331. raise AssertionError(
  2332. f"Coalescing manager does not support fast-path coalescing of {op0}, "
  2333. f"yet {op0} is still recorded in op list. This is an internal error of c10d."
  2334. )
  2335. if device:
  2336. # Old style of letting each coll inside the context manager to call into C++ counterpart via python binding
  2337. work = group._end_coalescing(device)
  2338. if async_ops:
  2339. cm.append(work)
  2340. elif (
  2341. work is not None
  2342. ): # Backward compatible with backends that don't sync at CPP level
  2343. work.wait()
  2344. # Otherwise, the backend has sync'ed at CPP level
  2345. class _TimeEstimator:
  2346. def __init__(self) -> None:
  2347. self.estimated_time: float | None = None
  2348. @contextlib.contextmanager
  2349. def _time_estimator(
  2350. group: ProcessGroup | None = None,
  2351. device: torch.device | None = None,
  2352. ):
  2353. """
  2354. Context manager used to estimate time of collectives.
  2355. Within the context manager, nothing is actually run and the backend just simulates
  2356. the collective time only.
  2357. Args:
  2358. group (`ProcessGroup`, optional): The process group to work on. If None,
  2359. the default process group will be used.
  2360. device (`torch.device`, optional): Default is None, set to a device if
  2361. there isn't a `**_coalesced` implementation by the backend.
  2362. Examples:
  2363. >>> # xdoctest: +SKIP("no rank")
  2364. >>> # Synchronous ops
  2365. >>> with _time_estimator() as cm:
  2366. >>> for i in range(num_colls):
  2367. >>> dist.all_reduce(tensors[i])
  2368. >>> # estimate time is stored in cm.estimated_time
  2369. .. warning::
  2370. :func:`_time_estimator` currently only support NCCL backend but it can
  2371. easily be extended to other backends.
  2372. Also a NCCL communicator needs to be created because only with a real communicator can we do accurate estimation.
  2373. The communicator internally has knowledge about the links it runs on
  2374. (e.g. intra-node or inter-node, whether the links are NVLink or PCI-e or IB).
  2375. """
  2376. # TODO: We need to also support torch inductor for the time estimator.
  2377. group = group or _get_default_group()
  2378. device = device or _get_pg_default_device(group)
  2379. backend = group._get_backend(device)
  2380. if not backend.supports_time_estimate:
  2381. raise NotImplementedError(
  2382. f"collective time estimator is not supported in the current version of backend {backend}"
  2383. )
  2384. backend._start_time_estimate() # type: ignore[attr-defined]
  2385. cm = _TimeEstimator()
  2386. yield cm
  2387. cm.estimated_time = backend._end_time_estimate() # type: ignore[attr-defined]
  2388. def batch_isend_irecv(p2p_op_list: list[P2POp]) -> list[Work]:
  2389. """
  2390. Send or Receive a batch of tensors asynchronously and return a list of requests.
  2391. Process each of the operations in ``p2p_op_list`` and return the corresponding
  2392. requests. NCCL, Gloo, and UCC backend are currently supported.
  2393. Args:
  2394. p2p_op_list: A list of point-to-point operations(type of each operator is
  2395. ``torch.distributed.P2POp``). The order of the isend/irecv in the list
  2396. matters and it needs to match with corresponding isend/irecv on the
  2397. remote end.
  2398. Returns:
  2399. A list of distributed request objects returned by calling the corresponding
  2400. op in the op_list.
  2401. Examples:
  2402. >>> # xdoctest: +SKIP("no rank")
  2403. >>> send_tensor = torch.arange(2, dtype=torch.float32) + 2 * rank
  2404. >>> recv_tensor = torch.randn(2, dtype=torch.float32)
  2405. >>> send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1) % world_size)
  2406. >>> recv_op = dist.P2POp(
  2407. ... dist.irecv, recv_tensor, (rank - 1 + world_size) % world_size
  2408. ... )
  2409. >>> reqs = batch_isend_irecv([send_op, recv_op])
  2410. >>> for req in reqs:
  2411. >>> req.wait()
  2412. >>> recv_tensor
  2413. tensor([2, 3]) # Rank 0
  2414. tensor([0, 1]) # Rank 1
  2415. .. note:: Note that when this API is used with the NCCL PG backend, users must set
  2416. the current GPU device with `torch.cuda.set_device`, otherwise it will
  2417. lead to unexpected hang issues.
  2418. In addition, if this API is the first collective call in the ``group``
  2419. passed to ``dist.P2POp``, all ranks of the ``group`` must participate in
  2420. this API call; otherwise, the behavior is undefined. If this API call is
  2421. not the first collective call in the ``group``, batched P2P operations
  2422. involving only a subset of ranks of the ``group`` are allowed.
  2423. """
  2424. _check_p2p_op_list(p2p_op_list)
  2425. group = p2p_op_list[0].group
  2426. if group is None:
  2427. group = _get_default_group()
  2428. device = p2p_op_list[0].tensor.device
  2429. def peer_kwarg(op: P2POp) -> dict[str, int]:
  2430. key = "group_dst" if op.op is isend else "group_src"
  2431. return {key: op.group_peer}
  2432. if type(group) is ProcessGroup and group._get_backend(device).supports_coalescing:
  2433. # NCCL style coalescing
  2434. with _coalescing_manager(group, device, async_ops=True) as cm:
  2435. for p2p_op in p2p_op_list:
  2436. p2p_op.op(
  2437. p2p_op.tensor,
  2438. group=p2p_op.group,
  2439. tag=p2p_op.tag,
  2440. **peer_kwarg(p2p_op),
  2441. )
  2442. return cm.works
  2443. else:
  2444. # backend not support coalescing
  2445. reqs = []
  2446. for p2p_op in p2p_op_list:
  2447. work = p2p_op.op(
  2448. p2p_op.tensor,
  2449. group=p2p_op.group,
  2450. tag=p2p_op.tag,
  2451. **peer_kwarg(p2p_op),
  2452. )
  2453. if work:
  2454. reqs.append(work)
  2455. return reqs
  2456. @_exception_logger
  2457. def broadcast(
  2458. tensor: torch.Tensor,
  2459. src: int | None = None,
  2460. group: ProcessGroup | None = None,
  2461. async_op: bool = False,
  2462. group_src: int | None = None,
  2463. ):
  2464. """
  2465. Broadcasts the tensor to the whole group.
  2466. ``tensor`` must have the same number of elements in all processes
  2467. participating in the collective.
  2468. Args:
  2469. tensor (Tensor): Data to be sent if ``src`` is the rank of current
  2470. process, and tensor to be used to save received data otherwise.
  2471. src (int): Source rank on global process group (regardless of ``group`` argument).
  2472. group (ProcessGroup, optional): The process group to work on. If None,
  2473. the default process group will be used.
  2474. async_op (bool, optional): Whether this op should be an async op
  2475. group_src (int): Source rank on ``group``. Must specify one of ``group_src``
  2476. and ``src`` but not both.
  2477. Returns:
  2478. Async work handle, if async_op is set to True.
  2479. None, if not async_op or if not part of the group
  2480. """
  2481. group = _group_or_default_group(group)
  2482. group_src = _canonicalize_group_rank(group, src, group_src, return_global=False)
  2483. _check_single_tensor(tensor, "tensor")
  2484. if _rank_not_in_group(group):
  2485. _warn_not_in_group("broadcast")
  2486. return
  2487. opts = BroadcastOptions()
  2488. opts.rootRank = group_src
  2489. opts.rootTensor = 0
  2490. opts.asyncOp = async_op
  2491. if tensor.is_complex():
  2492. tensor = torch.view_as_real(tensor)
  2493. work = group.broadcast([tensor], opts)
  2494. if async_op:
  2495. return work
  2496. elif (
  2497. work is not None
  2498. ): # Backward compatible with backends that don't sync at CPP level
  2499. work.wait()
  2500. # Otherwise, the backend has sync'ed at CPP level
  2501. @_exception_logger
  2502. def all_reduce(tensor, op=ReduceOp.SUM, group=None, async_op: bool = False):
  2503. """
  2504. Reduces the tensor data across all machines in a way that all get the final result.
  2505. After the call ``tensor`` is going to be bitwise identical in all processes.
  2506. Complex tensors are supported.
  2507. Args:
  2508. tensor (Tensor): Input and output of the collective. The function
  2509. operates in-place.
  2510. op (optional): One of the values from
  2511. ``torch.distributed.ReduceOp``
  2512. enum. Specifies an operation used for element-wise reductions.
  2513. group (ProcessGroup, optional): The process group to work on. If None,
  2514. the default process group will be used.
  2515. async_op (bool, optional): Whether this op should be an async op
  2516. Returns:
  2517. Async work handle, if async_op is set to True.
  2518. None, if not async_op or if not part of the group
  2519. Examples:
  2520. >>> # xdoctest: +SKIP("no rank")
  2521. >>> # All tensors below are of torch.int64 type.
  2522. >>> # We have 2 process groups, 2 ranks.
  2523. >>> device = torch.device(f"cuda:{rank}")
  2524. >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  2525. >>> tensor
  2526. tensor([1, 2], device='cuda:0') # Rank 0
  2527. tensor([3, 4], device='cuda:1') # Rank 1
  2528. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  2529. >>> tensor
  2530. tensor([4, 6], device='cuda:0') # Rank 0
  2531. tensor([4, 6], device='cuda:1') # Rank 1
  2532. >>> # All tensors below are of torch.cfloat type.
  2533. >>> # We have 2 process groups, 2 ranks.
  2534. >>> tensor = torch.tensor(
  2535. ... [1 + 1j, 2 + 2j], dtype=torch.cfloat, device=device
  2536. ... ) + 2 * rank * (1 + 1j)
  2537. >>> tensor
  2538. tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
  2539. tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
  2540. >>> dist.all_reduce(tensor, op=ReduceOp.SUM)
  2541. >>> tensor
  2542. tensor([4.+4.j, 6.+6.j], device='cuda:0') # Rank 0
  2543. tensor([4.+4.j, 6.+6.j], device='cuda:1') # Rank 1
  2544. """
  2545. # Dynamo has built-in logic to map legacy distributed ops to functional collectives.
  2546. # Let's redirect to a torch function mode that can mimic this logic outside Dynamo
  2547. # (e.g., non-strict export implements such a torch function mode).
  2548. relevant_args = (tensor,)
  2549. if has_torch_function(relevant_args):
  2550. return handle_torch_function(
  2551. all_reduce,
  2552. relevant_args,
  2553. tensor,
  2554. op=op,
  2555. group=group,
  2556. async_op=async_op,
  2557. )
  2558. _check_single_tensor(tensor, "tensor")
  2559. if _rank_not_in_group(group):
  2560. _warn_not_in_group("all_reduce")
  2561. return
  2562. if tensor.is_complex():
  2563. if not supports_complex(op):
  2564. raise ValueError(f"all_reduce does not support {op} on complex tensors")
  2565. tensor = torch.view_as_real(tensor)
  2566. opts = AllreduceOptions()
  2567. opts.reduceOp = op
  2568. opts.asyncOp = async_op
  2569. if group is None:
  2570. group = _get_default_group()
  2571. if group in _world.pg_coalesce_state:
  2572. # We are in coalescing context, do not issue single operation, just append a collective representation
  2573. coll = _CollOp(all_reduce, tensor, None, op, None)
  2574. _world.pg_coalesce_state[group].append(coll)
  2575. if async_op:
  2576. return _IllegalWork()
  2577. else:
  2578. return None
  2579. work = group.allreduce([tensor], opts)
  2580. if async_op:
  2581. return work
  2582. elif (
  2583. work is not None
  2584. ): # Backward compatible with backends that don't sync at CPP level
  2585. work.wait()
  2586. # Otherwise, the backend has sync'ed at CPP level
  2587. @_exception_logger
  2588. @deprecated(
  2589. "`torch.distributed.all_reduce_coalesced` will be deprecated. If you must "
  2590. "use it, please revisit our documentation later at "
  2591. "https://pytorch.org/docs/main/distributed.html#collective-functions",
  2592. category=FutureWarning,
  2593. )
  2594. def all_reduce_coalesced(tensors, op=ReduceOp.SUM, group=None, async_op: bool = False):
  2595. """
  2596. WARNING: at this time individual shape checking is not implemented across nodes.
  2597. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  2598. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce
  2599. operation will proceed without complaint and return erroneous outputs. This lack
  2600. of shape checking results in significant performance improvements but users of this
  2601. function should take extra care to ensure that each node passes in tensors whose
  2602. shapes match across nodes.
  2603. Reduces each tensor in tensors (residing on the same device) across all machines
  2604. in such a way that all get the final result.
  2605. After the call each tensor in tensors is going to bitwise identical
  2606. in all processes.
  2607. Complex tensors are supported.
  2608. Args:
  2609. tensors (Union[List[Tensor], Tensor]): Input and output of the collective.
  2610. The function operates in-place.
  2611. op (Optional[ReduceOp]): One of the values from
  2612. ``torch.distributed.ReduceOp`` enum. Specifies an operation used for
  2613. element-wise reductions.
  2614. group (ProcessGroup, optional): The process group to work on. If None,
  2615. the default process group will be used.
  2616. async_op (Optional[bool]): Whether this op should be an async op.
  2617. Returns:
  2618. Async work handle, if async_op is set to True.
  2619. None, if not async_op or if not part of the group.
  2620. """
  2621. if isinstance(tensors, torch.Tensor):
  2622. tensors = [tensors]
  2623. _check_tensor_list(tensors, "tensor")
  2624. _ensure_all_tensors_same_dtype(tensors)
  2625. if _rank_not_in_group(group):
  2626. _warn_not_in_group("all_reduce_coalesced")
  2627. return
  2628. if any(t.is_complex() for t in tensors) and not supports_complex(op):
  2629. raise ValueError(f"all_reduce does not support {op} on complex tensors")
  2630. tensors = [t if not t.is_complex() else torch.view_as_real(t) for t in tensors]
  2631. opts = AllreduceCoalescedOptions()
  2632. opts.reduceOp = op
  2633. opts.asyncOp = async_op
  2634. group = group or _get_default_group()
  2635. work = group.allreduce_coalesced(tensors, opts)
  2636. if async_op:
  2637. return work.get_future()
  2638. elif (
  2639. work is not None
  2640. ): # Backward compatible with backends that don't sync at CPP level
  2641. work.wait()
  2642. # Otherwise, the backend has sync'ed at CPP level
  2643. @_exception_logger
  2644. def reduce(
  2645. tensor: torch.Tensor,
  2646. dst: int | None = None,
  2647. op=ReduceOp.SUM,
  2648. group: ProcessGroup | None = None,
  2649. async_op: bool = False,
  2650. group_dst: int | None = None,
  2651. ):
  2652. """
  2653. Reduces the tensor data across all machines.
  2654. Only the process with rank ``dst`` is going to receive the final result.
  2655. Args:
  2656. tensor (Tensor): Input and output of the collective. The function
  2657. operates in-place.
  2658. dst (int): Destination rank on global process group (regardless of ``group`` argument)
  2659. op (optional): One of the values from
  2660. ``torch.distributed.ReduceOp``
  2661. enum. Specifies an operation used for element-wise reductions.
  2662. group (ProcessGroup, optional): The process group to work on. If None,
  2663. the default process group will be used.
  2664. async_op (bool, optional): Whether this op should be an async op
  2665. group_dst (int): Destination rank on ``group``. Must specify one of ``group_dst``
  2666. and ``dst`` but not both.
  2667. Returns:
  2668. Async work handle, if async_op is set to True.
  2669. None, if not async_op or if not part of the group
  2670. """
  2671. group = _group_or_default_group(group)
  2672. group_dst = _canonicalize_group_rank(group, dst, group_dst, return_global=False)
  2673. _check_single_tensor(tensor, "tensor")
  2674. if _rank_not_in_group(group):
  2675. _warn_not_in_group("reduce")
  2676. return
  2677. opts = ReduceOptions()
  2678. opts.reduceOp = op
  2679. opts.rootRank = group_dst
  2680. opts.asyncOp = async_op
  2681. work = group.reduce([tensor], opts)
  2682. if async_op:
  2683. return work
  2684. elif (
  2685. work is not None
  2686. ): # Backward compatible with backends that don't sync at CPP level
  2687. work.wait()
  2688. # Otherwise, the backend has sync'ed at CPP level
  2689. def _object_to_tensor(obj, device, group):
  2690. with _WaitCounter("pytorch.wait_counter.c10d._object_to_tensor").guard():
  2691. f = io.BytesIO()
  2692. _pickler(f).dump(obj)
  2693. byte_storage = torch.ByteStorage._from_buffer(f.getvalue()) # type: ignore[attr-defined]
  2694. # Do not replace `torch.ByteTensor` or `torch.LongTensor` with torch.tensor and specifying dtype.
  2695. # Otherwise, it will cause 100X slowdown.
  2696. # See: https://github.com/pytorch/pytorch/issues/65696
  2697. byte_tensor = torch.ByteTensor(byte_storage).to(device)
  2698. if get_debug_level() == DebugLevel.DETAIL and is_nccl_available():
  2699. backend = get_backend(group)
  2700. if backend == Backend.NCCL:
  2701. hash = torch._C._distributed_c10d._hash_tensors([byte_tensor])
  2702. logger.warning(
  2703. "_object_to_tensor size: %s hash value: %s",
  2704. byte_tensor.numel(),
  2705. hash,
  2706. )
  2707. local_size = torch.LongTensor([byte_tensor.numel()]).to(device)
  2708. return byte_tensor, local_size
  2709. def _tensor_to_object(tensor, tensor_size, group):
  2710. with _WaitCounter("pytorch.wait_counter.c10d._tensor_to_object").guard():
  2711. if get_debug_level() == DebugLevel.DETAIL and is_nccl_available():
  2712. backend = get_backend(group)
  2713. if backend == Backend.NCCL:
  2714. hash = torch._C._distributed_c10d._hash_tensors([tensor])
  2715. logger.warning(
  2716. "_tensor_to_object size: %s hash value: %s", tensor.numel(), hash
  2717. )
  2718. tensor = tensor.cpu()
  2719. buf = tensor.numpy().tobytes()[:tensor_size]
  2720. return _unpickler(io.BytesIO(buf)).load()
  2721. @_exception_logger
  2722. def all_gather_object(object_list, obj, group=None):
  2723. """
  2724. Gathers picklable objects from the whole group into a list.
  2725. Similar to :func:`all_gather`, but Python objects can be passed in.
  2726. Note that the object must be picklable in order to be gathered.
  2727. Args:
  2728. object_list (list[Any]): Output list. It should be correctly sized as the
  2729. size of the group for this collective and will contain the output.
  2730. obj (Any): Pickable Python object to be broadcast from current process.
  2731. group (ProcessGroup, optional): The process group to work on. If None,
  2732. the default process group will be used. Default is ``None``.
  2733. Returns:
  2734. None. If the calling rank is part of this group, the output of the
  2735. collective will be populated into the input ``object_list``. If the
  2736. calling rank is not part of the group, the passed in ``object_list`` will
  2737. be unmodified.
  2738. .. note:: Note that this API differs slightly from the :func:`all_gather`
  2739. collective since it does not provide an ``async_op`` handle and thus
  2740. will be a blocking call.
  2741. .. note:: For NCCL-based processed groups, internal tensor representations
  2742. of objects must be moved to the GPU device before communication takes
  2743. place. In this case, the device used is given by
  2744. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2745. ensure that this is set so that each rank has an individual GPU, via
  2746. ``torch.cuda.set_device()``.
  2747. .. warning::
  2748. Object collectives have a number of serious performance and scalability
  2749. limitations. See :ref:`object_collectives` for details.
  2750. .. warning::
  2751. :func:`all_gather_object` uses ``pickle`` module implicitly, which is
  2752. known to be insecure. It is possible to construct malicious pickle data
  2753. which will execute arbitrary code during unpickling. Only call this
  2754. function with data you trust.
  2755. .. warning::
  2756. Calling :func:`all_gather_object` with GPU tensors is not well supported
  2757. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2758. pickled. Please consider using :func:`all_gather` instead.
  2759. Example::
  2760. >>> # xdoctest: +SKIP("need process group init")
  2761. >>> # Note: Process group initialization omitted on each rank.
  2762. >>> import torch.distributed as dist
  2763. >>> # Assumes world_size of 3.
  2764. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  2765. >>> output = [None for _ in gather_objects]
  2766. >>> dist.all_gather_object(output, gather_objects[dist.get_rank()])
  2767. >>> output
  2768. ['foo', 12, {1: 2}]
  2769. """
  2770. if _rank_not_in_group(group):
  2771. _warn_not_in_group("all_gather_object")
  2772. return
  2773. current_device = _get_object_coll_device(group)
  2774. input_tensor, local_size = _object_to_tensor(obj, current_device, group)
  2775. # Gather all local sizes. This is so that we can find the max size, and index
  2776. # until the correct size when deserializing the tensors.
  2777. group_size = get_world_size(group=group)
  2778. object_sizes_tensor = torch.zeros(
  2779. group_size, dtype=torch.long, device=current_device
  2780. )
  2781. object_size_list = [
  2782. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  2783. ]
  2784. # Allgather tensor sizes
  2785. all_gather(object_size_list, local_size, group=group)
  2786. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  2787. # Resize tensor to max size across all ranks.
  2788. input_tensor.resize_(max_object_size)
  2789. coalesced_output_tensor = torch.empty(
  2790. max_object_size * group_size, dtype=torch.uint8, device=current_device
  2791. )
  2792. # Output tensors are nonoverlapping views of coalesced_output_tensor
  2793. output_tensors = [
  2794. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  2795. for i in range(group_size)
  2796. ]
  2797. all_gather(output_tensors, input_tensor, group=group)
  2798. # Deserialize outputs back to object.
  2799. for i, tensor in enumerate(output_tensors):
  2800. tensor = tensor.type(torch.uint8)
  2801. tensor_size = object_size_list[i]
  2802. object_list[i] = _tensor_to_object(tensor, tensor_size, group)
  2803. @_exception_logger
  2804. def gather_object(
  2805. obj: Any,
  2806. object_gather_list: list[Any] | None = None,
  2807. dst: int | None = None,
  2808. group: ProcessGroup | None = None,
  2809. group_dst: int | None = None,
  2810. ):
  2811. """
  2812. Gathers picklable objects from the whole group in a single process.
  2813. Similar to :func:`gather`, but Python objects can be passed in. Note that the
  2814. object must be picklable in order to be gathered.
  2815. Args:
  2816. obj (Any): Input object. Must be picklable.
  2817. object_gather_list (list[Any]): Output list. On the ``dst`` rank, it
  2818. should be correctly sized as the size of the group for this
  2819. collective and will contain the output. Must be ``None`` on non-dst
  2820. ranks. (default is ``None``)
  2821. dst (int, optional): Destination rank on global process group (regardless of ``group`` argument).
  2822. (If both ``dst`` and ``group_dst`` are None, default is global rank 0)
  2823. group: (ProcessGroup, optional): The process group to work on. If None,
  2824. the default process group will be used. Default is ``None``.
  2825. group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst``
  2826. Returns:
  2827. None. On the ``dst`` rank, ``object_gather_list`` will contain the
  2828. output of the collective.
  2829. .. note:: Note that this API differs slightly from the gather collective
  2830. since it does not provide an async_op handle and thus will be a blocking
  2831. call.
  2832. .. note:: For NCCL-based processed groups, internal tensor representations
  2833. of objects must be moved to the GPU device before communication takes
  2834. place. In this case, the device used is given by
  2835. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2836. ensure that this is set so that each rank has an individual GPU, via
  2837. ``torch.cuda.set_device()``.
  2838. .. warning::
  2839. Object collectives have a number of serious performance and scalability
  2840. limitations. See :ref:`object_collectives` for details.
  2841. .. warning::
  2842. :func:`gather_object` uses ``pickle`` module implicitly, which is
  2843. known to be insecure. It is possible to construct malicious pickle data
  2844. which will execute arbitrary code during unpickling. Only call this
  2845. function with data you trust.
  2846. .. warning::
  2847. Calling :func:`gather_object` with GPU tensors is not well supported
  2848. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2849. pickled. Please consider using :func:`gather` instead.
  2850. Example::
  2851. >>> # xdoctest: +SKIP("need process group init")
  2852. >>> # Note: Process group initialization omitted on each rank.
  2853. >>> import torch.distributed as dist
  2854. >>> # Assumes world_size of 3.
  2855. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
  2856. >>> output = [None for _ in gather_objects]
  2857. >>> dist.gather_object(
  2858. ... gather_objects[dist.get_rank()],
  2859. ... output if dist.get_rank() == 0 else None,
  2860. ... dst=0
  2861. ... )
  2862. >>> # On rank 0
  2863. >>> output
  2864. ['foo', 12, {1: 2}]
  2865. """
  2866. group = _group_or_default_group(group)
  2867. if dst is None and group_dst is None:
  2868. dst = 0
  2869. group_dst = _canonicalize_group_rank(group, dst, group_dst, return_global=False)
  2870. if _rank_not_in_group(group):
  2871. _warn_not_in_group("gather_object")
  2872. return
  2873. # Ensure object_gather_list is specified appropriately.
  2874. my_group_rank = group.rank()
  2875. _validate_output_list_for_rank(my_group_rank, group_dst, object_gather_list)
  2876. current_device = _get_object_coll_device(group)
  2877. input_tensor, local_size = _object_to_tensor(obj, current_device, group)
  2878. # Gather all local sizes. This is so that we can find the max size, and index
  2879. # until the correct size when deserializing the tensors.
  2880. group_size = get_world_size(group=group)
  2881. object_sizes_tensor = torch.zeros(
  2882. group_size, dtype=torch.long, device=current_device
  2883. )
  2884. object_size_list = [
  2885. object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
  2886. ]
  2887. # Allgather tensor sizes. An all-gather is needed here despite this being a
  2888. # gather, since each rank needs to broadcast a tensor of the same (maximal)
  2889. # size.
  2890. all_gather(object_size_list, local_size, group=group)
  2891. max_object_size = int(max(object_size_list).item()) # type: ignore[type-var]
  2892. # Resize tensor to max size across all ranks.
  2893. input_tensor.resize_(max_object_size)
  2894. # Avoid populating output tensors if the result won't be gathered on this rank.
  2895. if my_group_rank == group_dst:
  2896. coalesced_output_tensor = torch.empty(
  2897. max_object_size * group_size, dtype=torch.uint8, device=current_device
  2898. )
  2899. # Output tensors are nonoverlapping views of coalesced_output_tensor
  2900. output_tensors = [
  2901. coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]
  2902. for i in range(group_size)
  2903. ]
  2904. # All ranks call gather with equal-sized tensors.
  2905. gather(
  2906. input_tensor,
  2907. gather_list=output_tensors if my_group_rank == group_dst else None, # type: ignore[possibly-undefined]
  2908. group_dst=group_dst,
  2909. group=group,
  2910. )
  2911. if my_group_rank != group_dst:
  2912. return
  2913. if object_gather_list is None:
  2914. raise AssertionError("Must provide object_gather_list on dst rank")
  2915. # pyrefly: ignore [unbound-name]
  2916. for i, tensor in enumerate(output_tensors):
  2917. tensor = tensor.type(torch.uint8)
  2918. tensor_size = object_size_list[i]
  2919. object_gather_list[i] = _tensor_to_object(tensor, tensor_size, group)
  2920. @_exception_logger
  2921. def send_object_list(
  2922. object_list: list[Any],
  2923. dst: int | None = None,
  2924. group: ProcessGroup | None = None,
  2925. device: torch.device | None = None,
  2926. group_dst: int | None = None,
  2927. use_batch: bool = False,
  2928. ):
  2929. """
  2930. Sends picklable objects in ``object_list`` synchronously.
  2931. Similar to :func:`send`, but Python objects can be passed in.
  2932. Note that all objects in ``object_list`` must be picklable in order to be
  2933. sent.
  2934. Args:
  2935. object_list (List[Any]): List of input objects to sent.
  2936. Each object must be picklable. Receiver must provide lists of equal sizes.
  2937. dst (int): Destination rank to send ``object_list`` to.
  2938. Destination rank is based on global process group (regardless of ``group`` argument)
  2939. group: (ProcessGroup, optional): The process group to work on. If None,
  2940. the default process group will be used. Default is ``None``.
  2941. device (``torch.device``, optional): If not None, the objects are
  2942. serialized and converted to tensors which are moved to the
  2943. ``device`` before sending. Default is ``None``.
  2944. group_dst (int, optional): Destination rank on ``group``.
  2945. Must specify one of ``dst`` and ``group_dst`` but not both
  2946. use_batch (bool, optional): If True, use batch p2p operations instead of
  2947. regular send operations. This avoids initializing 2-rank communicators and
  2948. uses existing entire group communicators. See batch_isend_irecv for usage and
  2949. assumptions. Default is ``False``.
  2950. Returns:
  2951. ``None``.
  2952. .. note:: For NCCL-based process groups, internal tensor representations
  2953. of objects must be moved to the GPU device before communication takes
  2954. place. In this case, the device used is given by
  2955. ``torch.cuda.current_device()`` and it is the user's responsibility to
  2956. ensure that this is set so that each rank has an individual GPU, via
  2957. ``torch.cuda.set_device()``.
  2958. .. warning::
  2959. Object collectives have a number of serious performance and scalability
  2960. limitations. See :ref:`object_collectives` for details.
  2961. .. warning::
  2962. :func:`send_object_list` uses ``pickle`` module implicitly, which
  2963. is known to be insecure. It is possible to construct malicious pickle
  2964. data which will execute arbitrary code during unpickling. Only call this
  2965. function with data you trust.
  2966. .. warning::
  2967. Calling :func:`send_object_list` with GPU tensors is not well supported
  2968. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  2969. pickled. Please consider using :func:`send` instead.
  2970. Example::
  2971. >>> # xdoctest: +SKIP("need process group init")
  2972. >>> # Note: Process group initialization omitted on each rank.
  2973. >>> import torch.distributed as dist
  2974. >>> # Assumes backend is not NCCL
  2975. >>> device = torch.device("cpu")
  2976. >>> if dist.get_rank() == 0:
  2977. >>> # Assumes world_size of 2.
  2978. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  2979. >>> dist.send_object_list(objects, dst=1, device=device)
  2980. >>> else:
  2981. >>> objects = [None, None, None]
  2982. >>> dist.recv_object_list(objects, src=0, device=device)
  2983. >>> objects
  2984. ['foo', 12, {1: 2}]
  2985. """
  2986. group = _group_or_default_group(group)
  2987. group_dst = _canonicalize_group_rank(group, dst, group_dst)
  2988. _check_not_self_rank(group, group_dst, "destination")
  2989. if _rank_not_in_group(group):
  2990. _warn_not_in_group("send_object_list")
  2991. return
  2992. # Current device selection.
  2993. # To preserve backwards compatibility, ``device`` is default to ``None``
  2994. # in which case we run current logic of device selection, i.e.
  2995. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  2996. # case it is not ``None`` we move the size and object tensors to be
  2997. # sent to this device.
  2998. current_device = device or _get_object_coll_device(group)
  2999. # Serialize object_list elements to tensors on src rank.
  3000. tensor_list, size_list = zip(
  3001. *[_object_to_tensor(obj, current_device, group) for obj in object_list]
  3002. )
  3003. object_sizes_tensor = torch.cat(size_list)
  3004. # Send object sizes
  3005. if use_batch:
  3006. batch_isend_irecv(
  3007. [P2POp(isend, object_sizes_tensor, group_peer=group_dst, group=group)]
  3008. ).pop().wait()
  3009. else:
  3010. send(object_sizes_tensor, group_dst=group_dst, group=group)
  3011. # Concatenate and send serialized object tensors
  3012. # Note: torch.cat will do an extra memory copy to the current device, if the tensor_list
  3013. # has only one element, we can skip the copy.
  3014. if len(tensor_list) == 1: # type: ignore[possibly-undefined]
  3015. object_tensor = tensor_list[0]
  3016. else:
  3017. object_tensor = torch.cat(tensor_list)
  3018. if use_batch:
  3019. batch_isend_irecv(
  3020. [P2POp(isend, object_tensor, group_peer=group_dst, group=group)]
  3021. ).pop().wait()
  3022. else:
  3023. send(object_tensor, group_dst=group_dst, group=group)
  3024. @_exception_logger
  3025. def recv_object_list(
  3026. object_list: list[Any],
  3027. src: int | None = None,
  3028. group: ProcessGroup | None = None,
  3029. device: torch.device | None = None,
  3030. group_src: int | None = None,
  3031. use_batch: bool = False,
  3032. ):
  3033. """
  3034. Receives picklable objects in ``object_list`` synchronously.
  3035. Similar to :func:`recv`, but can receive Python objects.
  3036. Args:
  3037. object_list (List[Any]): List of objects to receive into.
  3038. Must provide a list of sizes equal to the size of the list being sent.
  3039. src (int, optional): Source rank from which to recv ``object_list``.
  3040. Source rank is based on global process group (regardless of ``group`` argument)
  3041. Will receive from any rank if set to None. Default is ``None``.
  3042. group: (ProcessGroup, optional): The process group to work on. If None,
  3043. the default process group will be used. Default is ``None``.
  3044. device (``torch.device``, optional): If not None, receives on this device.
  3045. Default is ``None``.
  3046. group_src (int, optional): Destination rank on ``group``. Invalid to specify both ``src`` and ``group_src``.
  3047. use_batch (bool, optional): If True, use batch p2p operations instead of
  3048. regular send operations. This avoids initializing 2-rank communicators and
  3049. uses existing entire group communicators. See batch_isend_irecv for usage and
  3050. assumptions. Default is ``False``.
  3051. Returns:
  3052. Sender rank. -1 if rank is not part of the group. If rank is part of the group,
  3053. ``object_list`` will contain the sent objects from ``src`` rank.
  3054. .. note:: For NCCL-based process groups, internal tensor representations
  3055. of objects must be moved to the GPU device before communication takes
  3056. place. In this case, the device used is given by
  3057. ``torch.cuda.current_device()`` and it is the user's responsibility to
  3058. ensure that this is set so that each rank has an individual GPU, via
  3059. ``torch.cuda.set_device()``.
  3060. .. warning::
  3061. Object collectives have a number of serious performance and scalability
  3062. limitations. See :ref:`object_collectives` for details.
  3063. .. warning::
  3064. :func:`recv_object_list` uses ``pickle`` module implicitly, which
  3065. is known to be insecure. It is possible to construct malicious pickle
  3066. data which will execute arbitrary code during unpickling. Only call this
  3067. function with data you trust.
  3068. .. warning::
  3069. Calling :func:`recv_object_list` with GPU tensors is not well supported
  3070. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  3071. pickled. Please consider using :func:`recv` instead.
  3072. Example::
  3073. >>> # xdoctest: +SKIP("need process group init")
  3074. >>> # Note: Process group initialization omitted on each rank.
  3075. >>> import torch.distributed as dist
  3076. >>> # Assumes backend is not NCCL
  3077. >>> device = torch.device("cpu")
  3078. >>> if dist.get_rank() == 0:
  3079. >>> # Assumes world_size of 2.
  3080. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  3081. >>> dist.send_object_list(objects, dst=1, device=device)
  3082. >>> else:
  3083. >>> objects = [None, None, None]
  3084. >>> dist.recv_object_list(objects, src=0, device=device)
  3085. >>> objects
  3086. ['foo', 12, {1: 2}]
  3087. """
  3088. group = _group_or_default_group(group)
  3089. group_src = _canonicalize_group_rank(group, src, group_src)
  3090. _check_not_self_rank(group, group_src, "source")
  3091. if _rank_not_in_group(group):
  3092. _warn_not_in_group("recv_object_list")
  3093. return -1
  3094. # Current device selection.
  3095. # To preserve backwards compatibility, ``device`` is default to ``None``
  3096. # in which case we run current logic of device selection, i.e.
  3097. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  3098. # case it is not ``None`` we move the size and object tensors to be
  3099. # received to this device.
  3100. current_device = device or _get_object_coll_device(group)
  3101. object_sizes_tensor = torch.empty(
  3102. len(object_list), dtype=torch.long, device=current_device
  3103. )
  3104. # Receive object sizes
  3105. if use_batch:
  3106. work = batch_isend_irecv(
  3107. [
  3108. P2POp(
  3109. irecv,
  3110. object_sizes_tensor,
  3111. group_peer=group_src,
  3112. group=group,
  3113. )
  3114. ]
  3115. ).pop()
  3116. work.wait()
  3117. rank_sizes = get_global_rank(group, group_src)
  3118. else:
  3119. rank_sizes = recv(object_sizes_tensor, group=group, group_src=group_src)
  3120. # Tensor to receive serialized objects into.
  3121. object_tensor = torch.empty( # type: ignore[call-overload]
  3122. torch.sum(object_sizes_tensor).item(), # type: ignore[arg-type]
  3123. dtype=torch.uint8,
  3124. device=current_device,
  3125. )
  3126. if use_batch:
  3127. work = batch_isend_irecv(
  3128. [
  3129. P2POp(
  3130. irecv,
  3131. object_tensor,
  3132. group_peer=group_src,
  3133. group=group,
  3134. )
  3135. ]
  3136. ).pop()
  3137. work.wait()
  3138. rank_objects = get_global_rank(group, group_src)
  3139. else:
  3140. rank_objects = recv(object_tensor, group=group, group_src=group_src)
  3141. if rank_sizes != rank_objects:
  3142. raise AssertionError("Mismatch in return ranks for object sizes and objects.")
  3143. # Deserialize objects using their stored sizes.
  3144. offset = 0
  3145. for i, obj_size in enumerate(object_sizes_tensor):
  3146. obj_view = object_tensor[offset : offset + obj_size]
  3147. obj_view = obj_view.type(torch.uint8)
  3148. offset += obj_size
  3149. object_list[i] = _tensor_to_object(obj_view, obj_size, group)
  3150. return rank_objects
  3151. @_exception_logger
  3152. def broadcast_object_list(
  3153. object_list: list[Any],
  3154. src: int | None = None,
  3155. group: ProcessGroup | None = None,
  3156. device: torch.device | None = None,
  3157. group_src: int | None = None,
  3158. ):
  3159. """
  3160. Broadcasts picklable objects in ``object_list`` to the whole group.
  3161. Similar to :func:`broadcast`, but Python objects can be passed in.
  3162. Note that all objects in ``object_list`` must be picklable in order to be
  3163. broadcasted.
  3164. Args:
  3165. object_list (List[Any]): List of input objects to broadcast.
  3166. Each object must be picklable. Only objects on the ``src`` rank will
  3167. be broadcast, but each rank must provide lists of equal sizes.
  3168. src (int): Source rank from which to broadcast ``object_list``.
  3169. Source rank is based on global process group (regardless of ``group`` argument)
  3170. group: (ProcessGroup, optional): The process group to work on. If None,
  3171. the default process group will be used. Default is ``None``.
  3172. device (``torch.device``, optional): If not None, the objects are
  3173. serialized and converted to tensors which are moved to the
  3174. ``device`` before broadcasting. Default is ``None``.
  3175. group_src (int): Source rank on ``group``. Must not specify one of ``group_src``
  3176. and ``src`` but not both.
  3177. Returns:
  3178. ``None``. If rank is part of the group, ``object_list`` will contain the
  3179. broadcasted objects from ``src`` rank.
  3180. .. note:: For NCCL-based process groups, internal tensor representations
  3181. of objects must be moved to the GPU device before communication takes
  3182. place. In this case, the device used is given by
  3183. ``torch.cuda.current_device()`` and it is the user's responsibility to
  3184. ensure that this is set so that each rank has an individual GPU, via
  3185. ``torch.cuda.set_device()``.
  3186. .. note:: Note that this API differs slightly from the :func:`broadcast`
  3187. collective since it does not provide an ``async_op`` handle and thus
  3188. will be a blocking call.
  3189. .. warning::
  3190. Object collectives have a number of serious performance and scalability
  3191. limitations. See :ref:`object_collectives` for details.
  3192. .. warning::
  3193. :func:`broadcast_object_list` uses ``pickle`` module implicitly, which
  3194. is known to be insecure. It is possible to construct malicious pickle
  3195. data which will execute arbitrary code during unpickling. Only call this
  3196. function with data you trust.
  3197. .. warning::
  3198. Calling :func:`broadcast_object_list` with GPU tensors is not well supported
  3199. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  3200. pickled. Please consider using :func:`broadcast` instead.
  3201. Example::
  3202. >>> # xdoctest: +SKIP("need process group init")
  3203. >>> # Note: Process group initialization omitted on each rank.
  3204. >>> import torch.distributed as dist
  3205. >>> if dist.get_rank() == 0:
  3206. >>> # Assumes world_size of 3.
  3207. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  3208. >>> else:
  3209. >>> objects = [None, None, None]
  3210. >>> # Assumes backend is not NCCL
  3211. >>> device = torch.device("cpu")
  3212. >>> dist.broadcast_object_list(objects, src=0, device=device)
  3213. >>> objects
  3214. ['foo', 12, {1: 2}]
  3215. """
  3216. group = _group_or_default_group(group)
  3217. if src is None and group_src is None:
  3218. src = 0
  3219. group_src = _canonicalize_group_rank(group, src, group_src, return_global=False)
  3220. if _rank_not_in_group(group):
  3221. _warn_not_in_group("broadcast_object_list")
  3222. return
  3223. # Current device selection.
  3224. # To preserve backwards compatibility, ``device`` is default to ``None``
  3225. # in which case we run current logic of device selection, i.e.
  3226. # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In the
  3227. # case it is not ``None`` we move the size and object tensors to be
  3228. # broadcasted to this device.
  3229. current_device = device or _get_object_coll_device(group)
  3230. my_group_rank = group.rank()
  3231. # Serialize object_list elements to tensors on src rank.
  3232. if my_group_rank == group_src:
  3233. tensor_list, size_list = zip(
  3234. *[_object_to_tensor(obj, current_device, group) for obj in object_list]
  3235. )
  3236. object_sizes_tensor = torch.cat(size_list)
  3237. else:
  3238. object_sizes_tensor = torch.empty(
  3239. len(object_list), dtype=torch.long, device=current_device
  3240. )
  3241. # Broadcast object sizes
  3242. broadcast(object_sizes_tensor, group_src=group_src, group=group)
  3243. # Concatenate and broadcast serialized object tensors
  3244. # Note: torch.cat will do an extra memory copy to the current device, if the tensor_list
  3245. # has only one element, we can skip the copy.
  3246. if my_group_rank == group_src:
  3247. if len(tensor_list) == 1: # type: ignore[possibly-undefined]
  3248. # pyrefly: ignore [unbound-name]
  3249. object_tensor = tensor_list[0]
  3250. else:
  3251. # pyrefly: ignore [unbound-name]
  3252. object_tensor = torch.cat(tensor_list)
  3253. else:
  3254. object_tensor = torch.empty( # type: ignore[call-overload]
  3255. torch.sum(object_sizes_tensor).item(), # type: ignore[arg-type]
  3256. dtype=torch.uint8,
  3257. device=current_device,
  3258. )
  3259. broadcast(object_tensor, group_src=group_src, group=group)
  3260. # Deserialize objects using their stored sizes.
  3261. offset = 0
  3262. if my_group_rank != group_src:
  3263. for i, obj_size in enumerate(object_sizes_tensor):
  3264. obj_view = object_tensor[offset : offset + obj_size]
  3265. obj_view = obj_view.type(torch.uint8)
  3266. offset += obj_size
  3267. object_list[i] = _tensor_to_object(obj_view, obj_size, group)
  3268. @_exception_logger
  3269. def scatter_object_list(
  3270. scatter_object_output_list: list[Any],
  3271. scatter_object_input_list: list[Any] | None = None,
  3272. src: int | None = None,
  3273. group: ProcessGroup | None = None,
  3274. group_src: int | None = None,
  3275. ):
  3276. """
  3277. Scatters picklable objects in ``scatter_object_input_list`` to the whole group.
  3278. Similar to :func:`scatter`, but Python objects can be passed in. On
  3279. each rank, the scattered object will be stored as the first element of
  3280. ``scatter_object_output_list``. Note that all objects in
  3281. ``scatter_object_input_list`` must be picklable in order to be scattered.
  3282. Args:
  3283. scatter_object_output_list (List[Any]): Non-empty list whose first
  3284. element will store the object scattered to this rank.
  3285. scatter_object_input_list (List[Any], optional): List of input objects to scatter.
  3286. Each object must be picklable. Only objects on the ``src`` rank will
  3287. be scattered, and the argument can be ``None`` for non-src ranks.
  3288. src (int): Source rank from which to scatter ``scatter_object_input_list``.
  3289. Source rank is based on global process group (regardless of ``group`` argument).
  3290. (If both ``src`` and ``group_src`` are None, default is global rank 0)
  3291. group: (ProcessGroup, optional): The process group to work on. If None,
  3292. the default process group will be used. Default is ``None``.
  3293. group_src (int, optional): Source rank on ``group``. Invalid to specify both ``src`` and ``group_src``
  3294. Returns:
  3295. ``None``. If rank is part of the group, ``scatter_object_output_list``
  3296. will have its first element set to the scattered object for this rank.
  3297. .. note:: Note that this API differs slightly from the scatter collective
  3298. since it does not provide an ``async_op`` handle and thus will be a
  3299. blocking call.
  3300. .. warning::
  3301. Object collectives have a number of serious performance and scalability
  3302. limitations. See :ref:`object_collectives` for details.
  3303. .. warning::
  3304. :func:`scatter_object_list` uses ``pickle`` module implicitly, which
  3305. is known to be insecure. It is possible to construct malicious pickle
  3306. data which will execute arbitrary code during unpickling. Only call this
  3307. function with data you trust.
  3308. .. warning::
  3309. Calling :func:`scatter_object_list` with GPU tensors is not well supported
  3310. and inefficient as it incurs GPU -> CPU transfer since tensors would be
  3311. pickled. Please consider using :func:`scatter` instead.
  3312. Example::
  3313. >>> # xdoctest: +SKIP("need process group init")
  3314. >>> # Note: Process group initialization omitted on each rank.
  3315. >>> import torch.distributed as dist
  3316. >>> if dist.get_rank() == 0:
  3317. >>> # Assumes world_size of 3.
  3318. >>> objects = ["foo", 12, {1: 2}] # any picklable object
  3319. >>> else:
  3320. >>> # Can be any list on non-src ranks, elements are not used.
  3321. >>> objects = [None, None, None]
  3322. >>> output_list = [None]
  3323. >>> dist.scatter_object_list(output_list, objects, src=0)
  3324. >>> # Rank i gets objects[i]. For example, on rank 2:
  3325. >>> output_list
  3326. [{1: 2}]
  3327. """
  3328. group = _group_or_default_group(group)
  3329. if src is None and group_src is None:
  3330. src = 0
  3331. group_src = _canonicalize_group_rank(group, src, group_src, return_global=False)
  3332. if _rank_not_in_group(group):
  3333. _warn_not_in_group("scatter_object_list")
  3334. return
  3335. if (
  3336. not isinstance(scatter_object_output_list, list)
  3337. or len(scatter_object_output_list) < 1
  3338. ):
  3339. raise ValueError(
  3340. "Expected argument scatter_object_output_list to be a list of size at least 1."
  3341. )
  3342. my_group_rank = group.rank()
  3343. pg_device = _get_object_coll_device(group)
  3344. if my_group_rank == group_src:
  3345. if scatter_object_input_list is None:
  3346. raise ValueError(
  3347. "source rank must provide non-None scatter_object_input_list"
  3348. )
  3349. tensor_list, tensor_sizes = zip(
  3350. *[
  3351. _object_to_tensor(obj, pg_device, group)
  3352. for obj in scatter_object_input_list
  3353. ]
  3354. )
  3355. tensor_list, tensor_sizes = list(tensor_list), list(tensor_sizes)
  3356. # Src rank broadcasts the maximum tensor size. This is because all ranks are
  3357. # expected to call into scatter() with equal-sized tensors.
  3358. max_tensor_size = max(tensor_sizes) # type: ignore[possibly-undefined]
  3359. for tensor in tensor_list: # type: ignore[possibly-undefined]
  3360. tensor.resize_(max_tensor_size)
  3361. else:
  3362. max_tensor_size = torch.tensor([0], dtype=torch.long, device=pg_device)
  3363. broadcast(max_tensor_size, group_src=group_src, group=group)
  3364. # Scatter actual serialized objects
  3365. # pyrefly: ignore [no-matching-overload]
  3366. output_tensor = torch.empty(
  3367. max_tensor_size.item(), dtype=torch.uint8, device=pg_device
  3368. )
  3369. scatter(
  3370. output_tensor,
  3371. scatter_list=None if my_group_rank != group_src else tensor_list, # type: ignore[possibly-undefined]
  3372. group_src=group_src,
  3373. group=group,
  3374. )
  3375. # Scatter per-object sizes to trim tensors when deserializing back to object
  3376. obj_tensor_size = torch.tensor([0], dtype=torch.long, device=pg_device)
  3377. scatter(
  3378. obj_tensor_size,
  3379. scatter_list=None if my_group_rank != group_src else tensor_sizes, # type: ignore[possibly-undefined]
  3380. group_src=group_src,
  3381. group=group,
  3382. )
  3383. # Deserialize back to object
  3384. scatter_object_output_list[0] = _tensor_to_object(
  3385. output_tensor, obj_tensor_size, group
  3386. )
  3387. @_exception_logger
  3388. def all_gather(tensor_list, tensor, group=None, async_op=False):
  3389. """
  3390. Gathers tensors from the whole group in a list.
  3391. Complex and uneven sized tensors are supported.
  3392. Args:
  3393. tensor_list (list[Tensor]): Output list. It should contain
  3394. correctly-sized tensors to be used for output of the collective.
  3395. Uneven sized tensors are supported.
  3396. tensor (Tensor): Tensor to be broadcast from current process.
  3397. group (ProcessGroup, optional): The process group to work on. If None,
  3398. the default process group will be used.
  3399. async_op (bool, optional): Whether this op should be an async op
  3400. Returns:
  3401. Async work handle, if async_op is set to True.
  3402. None, if not async_op or if not part of the group
  3403. Examples:
  3404. >>> # xdoctest: +SKIP("need process group init")
  3405. >>> # All tensors below are of torch.int64 dtype.
  3406. >>> # We have 2 process groups, 2 ranks.
  3407. >>> device = torch.device(f"cuda:{rank}")
  3408. >>> tensor_list = [
  3409. ... torch.zeros(2, dtype=torch.int64, device=device) for _ in range(2)
  3410. ... ]
  3411. >>> tensor_list
  3412. [tensor([0, 0], device='cuda:0'), tensor([0, 0], device='cuda:0')] # Rank 0
  3413. [tensor([0, 0], device='cuda:1'), tensor([0, 0], device='cuda:1')] # Rank 1
  3414. >>> tensor = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  3415. >>> tensor
  3416. tensor([1, 2], device='cuda:0') # Rank 0
  3417. tensor([3, 4], device='cuda:1') # Rank 1
  3418. >>> dist.all_gather(tensor_list, tensor)
  3419. >>> tensor_list
  3420. [tensor([1, 2], device='cuda:0'), tensor([3, 4], device='cuda:0')] # Rank 0
  3421. [tensor([1, 2], device='cuda:1'), tensor([3, 4], device='cuda:1')] # Rank 1
  3422. >>> # All tensors below are of torch.cfloat dtype.
  3423. >>> # We have 2 process groups, 2 ranks.
  3424. >>> tensor_list = [
  3425. ... torch.zeros(2, dtype=torch.cfloat, device=device) for _ in range(2)
  3426. ... ]
  3427. >>> tensor_list
  3428. [tensor([0.+0.j, 0.+0.j], device='cuda:0'), tensor([0.+0.j, 0.+0.j], device='cuda:0')] # Rank 0
  3429. [tensor([0.+0.j, 0.+0.j], device='cuda:1'), tensor([0.+0.j, 0.+0.j], device='cuda:1')] # Rank 1
  3430. >>> tensor = torch.tensor(
  3431. ... [1 + 1j, 2 + 2j], dtype=torch.cfloat, device=device
  3432. ... ) + 2 * rank * (1 + 1j)
  3433. >>> tensor
  3434. tensor([1.+1.j, 2.+2.j], device='cuda:0') # Rank 0
  3435. tensor([3.+3.j, 4.+4.j], device='cuda:1') # Rank 1
  3436. >>> dist.all_gather(tensor_list, tensor)
  3437. >>> tensor_list
  3438. [tensor([1.+1.j, 2.+2.j], device='cuda:0'), tensor([3.+3.j, 4.+4.j], device='cuda:0')] # Rank 0
  3439. [tensor([1.+1.j, 2.+2.j], device='cuda:1'), tensor([3.+3.j, 4.+4.j], device='cuda:1')] # Rank 1
  3440. """
  3441. # Dynamo has built-in logic to map legacy distributed ops to functional collectives.
  3442. # Let's redirect to a torch function mode that can mimic this logic outside Dynamo
  3443. # (e.g., non-strict export implements such a torch function mode).
  3444. relevant_args = (tensor,)
  3445. if has_torch_function(relevant_args):
  3446. return handle_torch_function(
  3447. all_gather,
  3448. relevant_args,
  3449. tensor_list,
  3450. tensor,
  3451. group=group,
  3452. async_op=async_op,
  3453. )
  3454. _check_tensor_list(tensor_list, "tensor_list")
  3455. _check_single_tensor(tensor, "tensor")
  3456. _ensure_all_tensors_same_dtype(tensor_list, tensor)
  3457. if _rank_not_in_group(group):
  3458. _warn_not_in_group("all_gather")
  3459. return
  3460. tensor_list = [
  3461. t if not t.is_complex() else torch.view_as_real(t) for t in tensor_list
  3462. ]
  3463. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  3464. group = group or _get_default_group()
  3465. opts = AllgatherOptions()
  3466. opts.asyncOp = async_op
  3467. work = group.allgather([tensor_list], [tensor], opts)
  3468. if async_op:
  3469. return work
  3470. elif (
  3471. work is not None
  3472. ): # Backward compatible with backends that don't sync at CPP level
  3473. work.wait()
  3474. # Otherwise, the backend has sync'ed at CPP level
  3475. @_exception_logger
  3476. def all_gather_into_tensor(output_tensor, input_tensor, group=None, async_op=False):
  3477. """
  3478. Gather tensors from all ranks and put them in a single output tensor.
  3479. This function requires all tensors to be the same size on each process.
  3480. Args:
  3481. output_tensor (Tensor): Output tensor to accommodate tensor elements
  3482. from all ranks. It must be correctly sized to have one of the
  3483. following forms:
  3484. (i) a concatenation of all the input tensors along the primary
  3485. dimension; for definition of "concatenation", see ``torch.cat()``;
  3486. (ii) a stack of all the input tensors along the primary dimension;
  3487. for definition of "stack", see ``torch.stack()``.
  3488. Examples below may better explain the supported output forms.
  3489. input_tensor (Tensor): Tensor to be gathered from current rank.
  3490. Different from the ``all_gather`` API, the input tensors in this
  3491. API must have the same size across all ranks.
  3492. group (ProcessGroup, optional): The process group to work on. If None,
  3493. the default process group will be used.
  3494. async_op (bool, optional): Whether this op should be an async op
  3495. Returns:
  3496. Async work handle, if async_op is set to True.
  3497. None, if not async_op or if not part of the group
  3498. Examples:
  3499. >>> # xdoctest: +SKIP("need process group init")
  3500. >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
  3501. >>> # We have two ranks.
  3502. >>> device = torch.device(f"cuda:{rank}")
  3503. >>> tensor_in = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank
  3504. >>> tensor_in
  3505. tensor([1, 2], device='cuda:0') # Rank 0
  3506. tensor([3, 4], device='cuda:1') # Rank 1
  3507. >>> # Output in concatenation form
  3508. >>> tensor_out = torch.zeros(world_size * 2, dtype=torch.int64, device=device)
  3509. >>> dist.all_gather_into_tensor(tensor_out, tensor_in)
  3510. >>> tensor_out
  3511. tensor([1, 2, 3, 4], device='cuda:0') # Rank 0
  3512. tensor([1, 2, 3, 4], device='cuda:1') # Rank 1
  3513. >>> # Output in stack form
  3514. >>> tensor_out2 = torch.zeros(world_size, 2, dtype=torch.int64, device=device)
  3515. >>> dist.all_gather_into_tensor(tensor_out2, tensor_in)
  3516. >>> tensor_out2
  3517. tensor([[1, 2],
  3518. [3, 4]], device='cuda:0') # Rank 0
  3519. tensor([[1, 2],
  3520. [3, 4]], device='cuda:1') # Rank 1
  3521. """
  3522. # Dynamo has built-in logic to map legacy distributed ops to functional collectives.
  3523. # Let's redirect to a torch function mode that can mimic this logic outside Dynamo
  3524. # (e.g., non-strict export implements such a torch function mode).
  3525. relevant_args = (input_tensor,)
  3526. if has_torch_function(relevant_args):
  3527. return handle_torch_function(
  3528. all_gather_into_tensor,
  3529. relevant_args,
  3530. output_tensor,
  3531. input_tensor,
  3532. group=group,
  3533. async_op=async_op,
  3534. )
  3535. _check_single_tensor(input_tensor, "input_tensor")
  3536. _check_single_tensor(output_tensor, "output_tensor")
  3537. if _rank_not_in_group(group):
  3538. _warn_not_in_group("all_gather_into_tensor")
  3539. return
  3540. output_tensor = (
  3541. output_tensor
  3542. if not output_tensor.is_complex()
  3543. else torch.view_as_real(output_tensor)
  3544. )
  3545. input_tensor = (
  3546. input_tensor
  3547. if not input_tensor.is_complex()
  3548. else torch.view_as_real(input_tensor)
  3549. )
  3550. opts = AllgatherOptions()
  3551. opts.asyncOp = async_op
  3552. group = group or _get_default_group()
  3553. if group in _world.pg_coalesce_state:
  3554. # We are in coalescing context, do not issue single operation, just append a collective representation
  3555. coll = _CollOp(all_gather_into_tensor, input_tensor, output_tensor)
  3556. _world.pg_coalesce_state[group].append(coll)
  3557. if async_op:
  3558. return _IllegalWork()
  3559. else:
  3560. return None
  3561. work = group._allgather_base(output_tensor, input_tensor, opts)
  3562. if async_op:
  3563. return work
  3564. elif (
  3565. work is not None
  3566. ): # Backward compatible with backends that don't sync at CPP level
  3567. work.wait()
  3568. # Otherwise, the backend has sync'ed at CPP level
  3569. @_exception_logger
  3570. @deprecated(
  3571. "`torch.distributed._all_gather_base` is a private function and will be deprecated. "
  3572. "Please use `torch.distributed.all_gather_into_tensor` instead.",
  3573. category=FutureWarning,
  3574. )
  3575. def _all_gather_base(output_tensor, input_tensor, group=None, async_op: bool = False):
  3576. """
  3577. Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
  3578. Args:
  3579. output_tensor (Tensor): Output tensor. It should contain
  3580. correctly-sized tensors to be used for output of the collective.
  3581. input_tensor (Tensor): Tensor to be broadcast from current process.
  3582. group (ProcessGroup, optional): The process group to work on. If None,
  3583. the default process group will be used.
  3584. async_op (bool, optional): Whether this op should be an async op
  3585. Returns:
  3586. Async work handle, if async_op is set to True.
  3587. None, if not async_op or if not part of the group
  3588. .. warning::
  3589. `_all_gather_base` is a private function. Users should use
  3590. `all_gather_into_tensor` instead.
  3591. """
  3592. return all_gather_into_tensor(output_tensor, input_tensor, group, async_op)
  3593. @_exception_logger
  3594. @deprecated(
  3595. "`torch.distributed.all_gather_coalesced` will be deprecated. If you must use it, "
  3596. "please revisit our documentation later at "
  3597. "https://pytorch.org/docs/main/distributed.html#collective-functions",
  3598. category=FutureWarning,
  3599. )
  3600. def all_gather_coalesced(
  3601. output_tensor_lists, input_tensor_list, group=None, async_op: bool = False
  3602. ):
  3603. """
  3604. Gathers input tensors from the whole group in a list in a coalesced manner.
  3605. Complex tensors are supported.
  3606. Args:
  3607. output_tensor_lists (list[list[Tensor]]): Output list. It should contain
  3608. correctly-sized tensors to be used for output of the collective.
  3609. input_tensor_list (list[Tensor]): Tensors to be broadcast from
  3610. current process. At least one tensor has to be non empty.
  3611. group (ProcessGroup, optional): The process group to work on. If None,
  3612. the default process group will be used.
  3613. async_op (bool, optional): Whether this op should be an async op.
  3614. Returns:
  3615. Async work handle, if async_op is set to True.
  3616. None, if not async_op or if not part of the group
  3617. Example:
  3618. we have 2 process groups, 2 ranks.
  3619. rank 0 passes:
  3620. input_tensor_list = [[[1, 1], [1, 1]], [2], [3, 3]]
  3621. output_tensor_lists =
  3622. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  3623. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  3624. rank 1 passes:
  3625. input_tensor_list = [[[3, 3], [3, 3]], [5], [1, 1]]
  3626. output_tensor_lists =
  3627. [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],
  3628. [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]
  3629. both rank 0 and 1 get:
  3630. output_tensor_lists =
  3631. [[[1, 1], [1, 1]], [2], [3, 3]],
  3632. [[3, 3], [3, 3]], [5], [1, 1]]].
  3633. WARNING: at this time individual shape checking is not implemented across nodes.
  3634. For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the
  3635. rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the
  3636. all_gather_coalesced operation will proceed without complaint and return
  3637. erroneous outputs. This lack of shape checking results in significant
  3638. performance improvements but users of this function should take extra care
  3639. to ensure that each node passes in tensors whose shapes match across nodes.
  3640. """
  3641. # We only check basic compatibility with C++ params here, C++ code will
  3642. # do shape and type checking.
  3643. if _rank_not_in_group(group):
  3644. _warn_not_in_group("all_gather_coalesced")
  3645. return
  3646. _check_tensor_list(input_tensor_list, "input_tensor_list")
  3647. _ensure_all_tensors_same_dtype(input_tensor_list)
  3648. if not isinstance(output_tensor_lists, list):
  3649. raise TypeError(
  3650. "Invalid function argument: output_tensor_lists should be a list"
  3651. )
  3652. for output_tensor_list in output_tensor_lists:
  3653. _check_tensor_list(output_tensor_list, "output_tensor_lists")
  3654. _ensure_all_tensors_same_dtype(output_tensor_list)
  3655. output_tensor_lists = [
  3656. [t if not t.is_complex() else torch.view_as_real(t) for t in l]
  3657. for l in output_tensor_lists
  3658. ]
  3659. input_tensor_list = [
  3660. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  3661. ]
  3662. group = group or _get_default_group()
  3663. opts = AllgatherOptions()
  3664. opts.asyncOp = async_op
  3665. work = group.allgather_coalesced(output_tensor_lists, input_tensor_list, opts)
  3666. if async_op:
  3667. return work.get_future()
  3668. elif (
  3669. work is not None
  3670. ): # Backward compatible with backends that don't sync at CPP level
  3671. work.wait()
  3672. # Otherwise, the backend has sync'ed at CPP level
  3673. def _validate_output_list_for_rank(my_rank: int, dst: int, gather_list):
  3674. if dst == my_rank:
  3675. if not gather_list:
  3676. raise ValueError(
  3677. "Argument ``gather_list`` must be specified on destination rank."
  3678. )
  3679. elif gather_list:
  3680. raise ValueError(
  3681. "Argument ``gather_list`` must NOT be specified on non-destination ranks."
  3682. )
  3683. @_exception_logger
  3684. def gather(
  3685. tensor: torch.Tensor,
  3686. gather_list: list[torch.Tensor] | None = None,
  3687. dst: int | None = None,
  3688. group: ProcessGroup | None = None,
  3689. async_op: bool = False,
  3690. group_dst: int | None = None,
  3691. ):
  3692. """
  3693. Gathers a list of tensors in a single process.
  3694. This function requires all tensors to be the same size on each process.
  3695. Args:
  3696. tensor (Tensor): Input tensor.
  3697. gather_list (list[Tensor], optional): List of appropriately,
  3698. same-sized tensors to use for gathered data
  3699. (default is None, must be specified on the destination rank)
  3700. dst (int, optional): Destination rank on global process group (regardless of ``group`` argument).
  3701. (If both ``dst`` and ``group_dst`` are None, default is global rank 0)
  3702. group (ProcessGroup, optional): The process group to work on. If None,
  3703. the default process group will be used.
  3704. async_op (bool, optional): Whether this op should be an async op
  3705. group_dst (int, optional): Destination rank on ``group``. Invalid to specify both ``dst`` and ``group_dst``
  3706. Returns:
  3707. Async work handle, if async_op is set to True.
  3708. None, if not async_op or if not part of the group
  3709. .. note:: Note that all Tensors in gather_list must have the same size.
  3710. Example::
  3711. >>> # xdoctest: +SKIP("no rank")
  3712. >>> # We have 2 process groups, 2 ranks.
  3713. >>> tensor_size = 2
  3714. >>> device = torch.device(f'cuda:{rank}')
  3715. >>> tensor = torch.ones(tensor_size, device=device) + rank
  3716. >>> if dist.get_rank() == 0:
  3717. >>> gather_list = [torch.zeros_like(tensor, device=device) for i in range(2)]
  3718. >>> else:
  3719. >>> gather_list = None
  3720. >>> dist.gather(tensor, gather_list, dst=0)
  3721. >>> # Rank 0 gets gathered data.
  3722. >>> gather_list
  3723. [tensor([1., 1.], device='cuda:0'), tensor([2., 2.], device='cuda:0')] # Rank 0
  3724. None # Rank 1
  3725. """
  3726. _check_single_tensor(tensor, "tensor")
  3727. # Parameter ``gather_list`` may be left unspecified on non-dst ranks.
  3728. if gather_list:
  3729. _check_tensor_list(gather_list, "gather_list")
  3730. else:
  3731. gather_list = []
  3732. _ensure_all_tensors_same_dtype(tensor, gather_list)
  3733. group = _group_or_default_group(group)
  3734. if _rank_not_in_group(group):
  3735. _warn_not_in_group("gather")
  3736. return
  3737. if dst is None and group_dst is None:
  3738. dst = 0
  3739. group_dst = _canonicalize_group_rank(group, dst, group_dst, return_global=False)
  3740. my_group_rank = group.rank()
  3741. _validate_output_list_for_rank(my_group_rank, group_dst, gather_list)
  3742. output_tensors = [gather_list] if group_dst == my_group_rank else []
  3743. input_tensors = [tensor]
  3744. opts = GatherOptions()
  3745. opts.rootRank = group_dst
  3746. opts.asyncOp = async_op
  3747. work = group.gather(output_tensors, input_tensors, opts)
  3748. if async_op:
  3749. return work
  3750. elif (
  3751. work is not None
  3752. ): # Backward compatible with backends that don't sync at CPP level
  3753. work.wait()
  3754. # Otherwise, the backend has sync'ed at CPP level
  3755. @_exception_logger
  3756. def scatter(
  3757. tensor: torch.Tensor,
  3758. scatter_list: list[torch.Tensor] | None = None,
  3759. src: int | None = None,
  3760. group: ProcessGroup | None = None,
  3761. async_op: bool = False,
  3762. group_src: int | None = None,
  3763. ):
  3764. """
  3765. Scatters a list of tensors to all processes in a group.
  3766. Each process will receive exactly one tensor and store its data in the
  3767. ``tensor`` argument.
  3768. Complex tensors are supported.
  3769. Args:
  3770. tensor (Tensor): Output tensor.
  3771. scatter_list (list[Tensor]): List of tensors to scatter (default is
  3772. None, must be specified on the source rank)
  3773. src (int): Source rank on global process group (regardless of ``group`` argument).
  3774. (If both ``src`` and ``group_src`` are None, default is global rank 0)
  3775. group (ProcessGroup, optional): The process group to work on. If None,
  3776. the default process group will be used.
  3777. async_op (bool, optional): Whether this op should be an async op
  3778. group_src (int, optional): Source rank on ``group``. Invalid to specify both ``src`` and ``group_src``
  3779. Returns:
  3780. Async work handle, if async_op is set to True.
  3781. None, if not async_op or if not part of the group
  3782. .. note:: Note that all Tensors in scatter_list must have the same size.
  3783. Example::
  3784. >>> # xdoctest: +SKIP("need process group init")
  3785. >>> # Note: Process group initialization omitted on each rank.
  3786. >>> import torch.distributed as dist
  3787. >>> tensor_size = 2
  3788. >>> device = torch.device(f'cuda:{rank}')
  3789. >>> output_tensor = torch.zeros(tensor_size, device=device)
  3790. >>> if dist.get_rank() == 0:
  3791. >>> # Assumes world_size of 2.
  3792. >>> # Only tensors, all of which must be the same size.
  3793. >>> t_ones = torch.ones(tensor_size, device=device)
  3794. >>> t_fives = torch.ones(tensor_size, device=device) * 5
  3795. >>> scatter_list = [t_ones, t_fives]
  3796. >>> else:
  3797. >>> scatter_list = None
  3798. >>> dist.scatter(output_tensor, scatter_list, src=0)
  3799. >>> # Rank i gets scatter_list[i].
  3800. >>> output_tensor
  3801. tensor([1., 1.], device='cuda:0') # Rank 0
  3802. tensor([5., 5.], device='cuda:1') # Rank 1
  3803. """
  3804. _check_single_tensor(tensor, "tensor")
  3805. # Parameter ``scatter_list`` may be left unspecified on non-src ranks.
  3806. if scatter_list:
  3807. _check_tensor_list(scatter_list, "scatter_list")
  3808. else:
  3809. scatter_list = []
  3810. _ensure_all_tensors_same_dtype(tensor, scatter_list)
  3811. group = _group_or_default_group(group)
  3812. if src is None and group_src is None:
  3813. src = 0
  3814. group_src = _canonicalize_group_rank(group, src, group_src, return_global=False)
  3815. if _rank_not_in_group(group):
  3816. _warn_not_in_group("scatter")
  3817. return
  3818. scatter_list = [
  3819. t if not t.is_complex() else torch.view_as_real(t) for t in scatter_list
  3820. ]
  3821. tensor = tensor if not tensor.is_complex() else torch.view_as_real(tensor)
  3822. my_group_rank = group.rank()
  3823. if group_src == my_group_rank:
  3824. if not scatter_list:
  3825. raise ValueError(
  3826. "Argument ``scatter_list`` must be specified on source rank."
  3827. )
  3828. input_tensors = [scatter_list]
  3829. output_tensors = [tensor]
  3830. else:
  3831. if scatter_list:
  3832. raise ValueError(
  3833. "Argument ``scatter_list`` must NOT be specified on non-source ranks."
  3834. )
  3835. input_tensors = []
  3836. output_tensors = [tensor]
  3837. opts = ScatterOptions()
  3838. opts.rootRank = group_src
  3839. opts.asyncOp = async_op
  3840. work = group.scatter(output_tensors, input_tensors, opts)
  3841. if async_op:
  3842. return work
  3843. elif (
  3844. work is not None
  3845. ): # Backward compatible with backends that don't sync at CPP level
  3846. work.wait()
  3847. # Otherwise, the backend has sync'ed at CPP level
  3848. @_exception_logger
  3849. def reduce_scatter(
  3850. output, input_list, op=ReduceOp.SUM, group=None, async_op: bool = False
  3851. ):
  3852. """
  3853. Reduces, then scatters a list of tensors to all processes in a group.
  3854. Args:
  3855. output (Tensor): Output tensor.
  3856. input_list (list[Tensor]): List of tensors to reduce and scatter.
  3857. op (optional): One of the values from
  3858. ``torch.distributed.ReduceOp``
  3859. enum. Specifies an operation used for element-wise reductions.
  3860. group (ProcessGroup, optional): The process group to work on. If None,
  3861. the default process group will be used.
  3862. async_op (bool, optional): Whether this op should be an async op.
  3863. Returns:
  3864. Async work handle, if async_op is set to True.
  3865. None, if not async_op or if not part of the group.
  3866. """
  3867. _check_single_tensor(output, "output")
  3868. _check_tensor_list(input_list, "input_list")
  3869. _ensure_all_tensors_same_dtype(output, input_list)
  3870. if _rank_not_in_group(group):
  3871. _warn_not_in_group("reduce_scatter")
  3872. return
  3873. opts = ReduceScatterOptions()
  3874. opts.reduceOp = op
  3875. opts.asyncOp = async_op
  3876. group = group or _get_default_group()
  3877. work = group.reduce_scatter([output], [input_list], opts)
  3878. if async_op:
  3879. return work
  3880. elif (
  3881. work is not None
  3882. ): # Backward compatible with backends that don't sync at CPP level
  3883. work.wait()
  3884. # Otherwise, the backend has sync'ed at CPP level
  3885. @_exception_logger
  3886. def reduce_scatter_tensor(output, input, op=ReduceOp.SUM, group=None, async_op=False):
  3887. """
  3888. Reduces, then scatters a tensor to all ranks in a group.
  3889. Args:
  3890. output (Tensor): Output tensor. It should have the same size across all
  3891. ranks.
  3892. input (Tensor): Input tensor to be reduced and scattered. Its size
  3893. should be output tensor size times the world size. The input tensor
  3894. can have one of the following shapes:
  3895. (i) a concatenation of the output tensors along the primary
  3896. dimension, or
  3897. (ii) a stack of the output tensors along the primary dimension.
  3898. For definition of "concatenation", see ``torch.cat()``.
  3899. For definition of "stack", see ``torch.stack()``.
  3900. group (ProcessGroup, optional): The process group to work on. If None,
  3901. the default process group will be used.
  3902. async_op (bool, optional): Whether this op should be an async op.
  3903. Returns:
  3904. Async work handle, if async_op is set to True.
  3905. None, if not async_op or if not part of the group.
  3906. Examples:
  3907. >>> # xdoctest: +SKIP("need process group init")
  3908. >>> # All tensors below are of torch.int64 dtype and on CUDA devices.
  3909. >>> # We have two ranks.
  3910. >>> device = torch.device(f"cuda:{rank}")
  3911. >>> tensor_out = torch.zeros(2, dtype=torch.int64, device=device)
  3912. >>> # Input in concatenation form
  3913. >>> tensor_in = torch.arange(world_size * 2, dtype=torch.int64, device=device)
  3914. >>> tensor_in
  3915. tensor([0, 1, 2, 3], device='cuda:0') # Rank 0
  3916. tensor([0, 1, 2, 3], device='cuda:1') # Rank 1
  3917. >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
  3918. >>> tensor_out
  3919. tensor([0, 2], device='cuda:0') # Rank 0
  3920. tensor([4, 6], device='cuda:1') # Rank 1
  3921. >>> # Input in stack form
  3922. >>> tensor_in = torch.reshape(tensor_in, (world_size, 2))
  3923. >>> tensor_in
  3924. tensor([[0, 1],
  3925. [2, 3]], device='cuda:0') # Rank 0
  3926. tensor([[0, 1],
  3927. [2, 3]], device='cuda:1') # Rank 1
  3928. >>> dist.reduce_scatter_tensor(tensor_out, tensor_in)
  3929. >>> tensor_out
  3930. tensor([0, 2], device='cuda:0') # Rank 0
  3931. tensor([4, 6], device='cuda:1') # Rank 1
  3932. """
  3933. # Dynamo has built-in logic to map legacy distributed ops to functional collectives.
  3934. # Let's redirect to a torch function mode that can mimic this logic outside Dynamo
  3935. # (e.g., non-strict export implements such a torch function mode).
  3936. relevant_args = (input,)
  3937. if has_torch_function(relevant_args):
  3938. return handle_torch_function(
  3939. reduce_scatter_tensor,
  3940. relevant_args,
  3941. output,
  3942. input,
  3943. op=op,
  3944. group=group,
  3945. async_op=async_op,
  3946. )
  3947. _check_single_tensor(output, "output")
  3948. _check_single_tensor(input, "input")
  3949. if _rank_not_in_group(group):
  3950. _warn_not_in_group("reduce_scatter_tensor")
  3951. return
  3952. opts = ReduceScatterOptions()
  3953. opts.reduceOp = op
  3954. opts.asyncOp = async_op
  3955. group = group or _get_default_group()
  3956. # Check if we are in coalescing context
  3957. # If we are, do not issue single operation, just append a collective representation
  3958. if group in _world.pg_coalesce_state:
  3959. coll = _CollOp(reduce_scatter_tensor, input, output, op, None)
  3960. _world.pg_coalesce_state[group].append(coll)
  3961. if async_op:
  3962. return _IllegalWork()
  3963. else:
  3964. return None
  3965. work = group._reduce_scatter_base(output, input, opts)
  3966. if async_op:
  3967. return work
  3968. elif (
  3969. work is not None
  3970. ): # Backward compatible with backends that don't sync at CPP level
  3971. work.wait()
  3972. # Otherwise, the backend has sync'ed at CPP level
  3973. @deprecated(
  3974. "`torch.distributed._reduce_scatter_base` is a private function and will be deprecated. "
  3975. "Please use `torch.distributed.reduce_scatter_tensor` instead.",
  3976. category=FutureWarning,
  3977. )
  3978. def _reduce_scatter_base(
  3979. output, input, op=ReduceOp.SUM, group=None, async_op: bool = False
  3980. ):
  3981. """
  3982. Reduces, then scatters a flattened tensor to all processes in a group.
  3983. Args:
  3984. output (Tensor): Output tensor.
  3985. input (Tensor): Input tensor that is of size output tensor size times world size
  3986. group (ProcessGroup, optional): The process group to work on. If None,
  3987. the default process group will be used.
  3988. async_op (bool, optional): Whether this op should be an async op.
  3989. Returns:
  3990. Async work handle, if async_op is set to True.
  3991. None, if not async_op or if not part of the group.
  3992. .. warning::
  3993. `_reduce_scatter_base` is a private function. Users should use
  3994. `reduce_scatter_tensor` instead.
  3995. """
  3996. return reduce_scatter_tensor(output, input, op, group, async_op)
  3997. @_exception_logger
  3998. def all_to_all_single(
  3999. output,
  4000. input,
  4001. output_split_sizes=None,
  4002. input_split_sizes=None,
  4003. group=None,
  4004. async_op: bool = False,
  4005. ):
  4006. """
  4007. Split input tensor and then scatter the split list to all processes in a group.
  4008. Later the received tensors are concatenated from all the processes in the group
  4009. and returned as a single output tensor.
  4010. Complex tensors are supported.
  4011. Args:
  4012. output (Tensor): Gathered concatenated output tensor.
  4013. input (Tensor): Input tensor to scatter.
  4014. output_split_sizes: (list[Int], optional): Output split sizes for dim 0
  4015. if specified None or empty, dim 0 of ``output`` tensor must divide
  4016. equally by ``world_size``.
  4017. input_split_sizes: (list[Int], optional): Input split sizes for dim 0
  4018. if specified None or empty, dim 0 of ``input`` tensor must divide
  4019. equally by ``world_size``.
  4020. group (ProcessGroup, optional): The process group to work on. If None,
  4021. the default process group will be used.
  4022. async_op (bool, optional): Whether this op should be an async op.
  4023. Returns:
  4024. Async work handle, if async_op is set to True.
  4025. None, if not async_op or if not part of the group.
  4026. .. warning::
  4027. `all_to_all_single` is experimental and subject to change.
  4028. Examples:
  4029. >>> # xdoctest: +SKIP("Undefined rank")
  4030. >>> input = torch.arange(4) + rank * 4
  4031. >>> input
  4032. tensor([0, 1, 2, 3]) # Rank 0
  4033. tensor([4, 5, 6, 7]) # Rank 1
  4034. tensor([8, 9, 10, 11]) # Rank 2
  4035. tensor([12, 13, 14, 15]) # Rank 3
  4036. >>> output = torch.empty([4], dtype=torch.int64)
  4037. >>> dist.all_to_all_single(output, input)
  4038. >>> output
  4039. tensor([0, 4, 8, 12]) # Rank 0
  4040. tensor([1, 5, 9, 13]) # Rank 1
  4041. tensor([2, 6, 10, 14]) # Rank 2
  4042. tensor([3, 7, 11, 15]) # Rank 3
  4043. >>> # Essentially, it is similar to following operation:
  4044. >>> scatter_list = list(input.chunk(world_size))
  4045. >>> gather_list = list(output.chunk(world_size))
  4046. >>> for i in range(world_size):
  4047. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)
  4048. >>> # Another example with uneven split
  4049. >>> input
  4050. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  4051. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  4052. tensor([20, 21, 22, 23, 24]) # Rank 2
  4053. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  4054. >>> input_splits
  4055. [2, 2, 1, 1] # Rank 0
  4056. [3, 2, 2, 2] # Rank 1
  4057. [2, 1, 1, 1] # Rank 2
  4058. [2, 2, 2, 1] # Rank 3
  4059. >>> output_splits
  4060. [2, 3, 2, 2] # Rank 0
  4061. [2, 2, 1, 2] # Rank 1
  4062. [1, 2, 1, 2] # Rank 2
  4063. [1, 2, 1, 1] # Rank 3
  4064. >>> output = ...
  4065. >>> dist.all_to_all_single(output, input, output_splits, input_splits)
  4066. >>> output
  4067. tensor([ 0, 1, 10, 11, 12, 20, 21, 30, 31]) # Rank 0
  4068. tensor([ 2, 3, 13, 14, 22, 32, 33]) # Rank 1
  4069. tensor([ 4, 15, 16, 23, 34, 35]) # Rank 2
  4070. tensor([ 5, 17, 18, 24, 36]) # Rank 3
  4071. >>> # Another example with tensors of torch.cfloat type.
  4072. >>> input = torch.tensor(
  4073. ... [1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j], dtype=torch.cfloat
  4074. ... ) + 4 * rank * (1 + 1j)
  4075. >>> input
  4076. tensor([1+1j, 2+2j, 3+3j, 4+4j]) # Rank 0
  4077. tensor([5+5j, 6+6j, 7+7j, 8+8j]) # Rank 1
  4078. tensor([9+9j, 10+10j, 11+11j, 12+12j]) # Rank 2
  4079. tensor([13+13j, 14+14j, 15+15j, 16+16j]) # Rank 3
  4080. >>> output = torch.empty([4], dtype=torch.int64)
  4081. >>> dist.all_to_all_single(output, input)
  4082. >>> output
  4083. tensor([1+1j, 5+5j, 9+9j, 13+13j]) # Rank 0
  4084. tensor([2+2j, 6+6j, 10+10j, 14+14j]) # Rank 1
  4085. tensor([3+3j, 7+7j, 11+11j, 15+15j]) # Rank 2
  4086. tensor([4+4j, 8+8j, 12+12j, 16+16j]) # Rank 3
  4087. """
  4088. # Dynamo has built-in logic to map legacy distributed ops to functional collectives.
  4089. # Let's redirect to a torch function mode that can mimic this logic outside Dynamo
  4090. # (e.g., non-strict export implements such a torch function mode).
  4091. relevant_args = (input,)
  4092. if has_torch_function(relevant_args):
  4093. return handle_torch_function(
  4094. all_to_all_single,
  4095. relevant_args,
  4096. output,
  4097. input,
  4098. output_split_sizes=output_split_sizes,
  4099. input_split_sizes=input_split_sizes,
  4100. group=group,
  4101. async_op=async_op,
  4102. )
  4103. if _rank_not_in_group(group):
  4104. _warn_not_in_group("all_to_all_single")
  4105. return
  4106. opts = AllToAllOptions()
  4107. opts.asyncOp = async_op
  4108. _check_single_tensor(output, "output")
  4109. _check_single_tensor(input, "input")
  4110. _ensure_all_tensors_same_dtype(output, input)
  4111. if input.is_complex():
  4112. input = torch.view_as_real(input)
  4113. if output.is_complex():
  4114. output = torch.view_as_real(output)
  4115. output_split_sizes = [] if output_split_sizes is None else output_split_sizes
  4116. input_split_sizes = [] if input_split_sizes is None else input_split_sizes
  4117. group = group or _get_default_group()
  4118. work = group.alltoall_base(
  4119. output, input, output_split_sizes, input_split_sizes, opts
  4120. )
  4121. if async_op:
  4122. return work
  4123. elif (
  4124. work is not None
  4125. ): # Backward compatible with backends that don't sync at CPP level
  4126. work.wait()
  4127. # Otherwise, the backend has sync'ed at CPP level
  4128. @_exception_logger
  4129. def all_to_all(
  4130. output_tensor_list, input_tensor_list, group=None, async_op: bool = False
  4131. ):
  4132. """
  4133. Scatters list of input tensors to all processes in a group and return gathered list of tensors in output list.
  4134. Complex tensors are supported.
  4135. Args:
  4136. output_tensor_list (list[Tensor]): List of tensors to be gathered one
  4137. per rank.
  4138. input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
  4139. group (ProcessGroup, optional): The process group to work on. If None,
  4140. the default process group will be used.
  4141. async_op (bool, optional): Whether this op should be an async op.
  4142. Returns:
  4143. Async work handle, if async_op is set to True.
  4144. None, if not async_op or if not part of the group.
  4145. .. warning::
  4146. `all_to_all` is experimental and subject to change.
  4147. Examples:
  4148. >>> # xdoctest: +SKIP("Undefined rank")
  4149. >>> input = torch.arange(4) + rank * 4
  4150. >>> input = list(input.chunk(4))
  4151. >>> input
  4152. [tensor([0]), tensor([1]), tensor([2]), tensor([3])] # Rank 0
  4153. [tensor([4]), tensor([5]), tensor([6]), tensor([7])] # Rank 1
  4154. [tensor([8]), tensor([9]), tensor([10]), tensor([11])] # Rank 2
  4155. [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3
  4156. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  4157. >>> dist.all_to_all(output, input)
  4158. >>> output
  4159. [tensor([0]), tensor([4]), tensor([8]), tensor([12])] # Rank 0
  4160. [tensor([1]), tensor([5]), tensor([9]), tensor([13])] # Rank 1
  4161. [tensor([2]), tensor([6]), tensor([10]), tensor([14])] # Rank 2
  4162. [tensor([3]), tensor([7]), tensor([11]), tensor([15])] # Rank 3
  4163. >>> # Essentially, it is similar to following operation:
  4164. >>> scatter_list = input
  4165. >>> gather_list = output
  4166. >>> for i in range(world_size):
  4167. >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src=i)
  4168. >>> input
  4169. tensor([0, 1, 2, 3, 4, 5]) # Rank 0
  4170. tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1
  4171. tensor([20, 21, 22, 23, 24]) # Rank 2
  4172. tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3
  4173. >>> input_splits
  4174. [2, 2, 1, 1] # Rank 0
  4175. [3, 2, 2, 2] # Rank 1
  4176. [2, 1, 1, 1] # Rank 2
  4177. [2, 2, 2, 1] # Rank 3
  4178. >>> output_splits
  4179. [2, 3, 2, 2] # Rank 0
  4180. [2, 2, 1, 2] # Rank 1
  4181. [1, 2, 1, 2] # Rank 2
  4182. [1, 2, 1, 1] # Rank 3
  4183. >>> input = list(input.split(input_splits))
  4184. >>> input
  4185. [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])] # Rank 0
  4186. [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1
  4187. [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])] # Rank 2
  4188. [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])] # Rank 3
  4189. >>> output = ...
  4190. >>> dist.all_to_all(output, input)
  4191. >>> output
  4192. [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])] # Rank 0
  4193. [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])] # Rank 1
  4194. [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])] # Rank 2
  4195. [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])] # Rank 3
  4196. >>> # Another example with tensors of torch.cfloat type.
  4197. >>> input = torch.tensor(
  4198. ... [1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j], dtype=torch.cfloat
  4199. ... ) + 4 * rank * (1 + 1j)
  4200. >>> input = list(input.chunk(4))
  4201. >>> input
  4202. [tensor([1+1j]), tensor([2+2j]), tensor([3+3j]), tensor([4+4j])] # Rank 0
  4203. [tensor([5+5j]), tensor([6+6j]), tensor([7+7j]), tensor([8+8j])] # Rank 1
  4204. [tensor([9+9j]), tensor([10+10j]), tensor([11+11j]), tensor([12+12j])] # Rank 2
  4205. [tensor([13+13j]), tensor([14+14j]), tensor([15+15j]), tensor([16+16j])] # Rank 3
  4206. >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))
  4207. >>> dist.all_to_all(output, input)
  4208. >>> output
  4209. [tensor([1+1j]), tensor([5+5j]), tensor([9+9j]), tensor([13+13j])] # Rank 0
  4210. [tensor([2+2j]), tensor([6+6j]), tensor([10+10j]), tensor([14+14j])] # Rank 1
  4211. [tensor([3+3j]), tensor([7+7j]), tensor([11+11j]), tensor([15+15j])] # Rank 2
  4212. [tensor([4+4j]), tensor([8+8j]), tensor([12+12j]), tensor([16+16j])] # Rank 3
  4213. """
  4214. if _rank_not_in_group(group):
  4215. _warn_not_in_group("all_to_all")
  4216. return
  4217. opts = AllToAllOptions()
  4218. opts.asyncOp = async_op
  4219. _check_tensor_list(output_tensor_list, "output_tensor_list")
  4220. _check_tensor_list(input_tensor_list, "input_tensor_list")
  4221. _ensure_all_tensors_same_dtype(output_tensor_list, input_tensor_list)
  4222. input_tensor_list = [
  4223. t if not t.is_complex() else torch.view_as_real(t) for t in input_tensor_list
  4224. ]
  4225. output_tensor_list = [
  4226. t if not t.is_complex() else torch.view_as_real(t) for t in output_tensor_list
  4227. ]
  4228. group = group or _get_default_group()
  4229. work = group.alltoall(output_tensor_list, input_tensor_list, opts)
  4230. if async_op:
  4231. return work
  4232. elif (
  4233. work is not None
  4234. ): # Backward compatible with backends that don't sync at CPP level
  4235. work.wait()
  4236. # Otherwise, the backend has sync'ed at CPP level
  4237. @_exception_logger
  4238. def barrier(
  4239. group: ProcessGroup | None = GroupMember.WORLD,
  4240. async_op: bool = False,
  4241. device_ids=None,
  4242. ):
  4243. """
  4244. Synchronize all processes.
  4245. This collective blocks processes until the whole group enters this function,
  4246. if async_op is False, or if async work handle is called on wait().
  4247. Args:
  4248. group (ProcessGroup, optional): The process group to work on. If None,
  4249. the default process group will be used.
  4250. async_op (bool, optional): Whether this op should be an async op
  4251. device_ids ([int], optional): List of device/GPU ids. Only one id is expected.
  4252. Returns:
  4253. Async work handle, if async_op is set to True.
  4254. None, if not async_op or if not part of the group
  4255. .. note:: `ProcessGroupNCCL` now blocks the cpu thread till the completion of the barrier collective.
  4256. .. note:: `ProcessGroupNCCL` implements barrier as an all_reduce of a 1-element tensor. A device must be chosen
  4257. for allocating this tensor. The device choice is made by checking in this order (1) the first device passed to
  4258. `device_ids` arg of barrier if not None, (2) the device passed to init_process_group if not None, (3) the device
  4259. that was first used with this process group, if another collective with tensor inputs has been performed, (4)
  4260. the device index indicated by the global rank mod local device count.
  4261. """
  4262. group = group or _get_default_group()
  4263. if _rank_not_in_group(group):
  4264. _warn_not_in_group("barrier")
  4265. return
  4266. opts = BarrierOptions()
  4267. opts.asyncOp = async_op
  4268. # Detect the accelerator on the machine. If no accelerator is available, it
  4269. # returns CPU.
  4270. device = torch._C._get_accelerator()
  4271. if isinstance(device_ids, list):
  4272. opts.device_ids = device_ids
  4273. # use only the first device id
  4274. # pyrefly: ignore [read-only]
  4275. opts.device = torch.device(device.type, device_ids[0])
  4276. elif getattr(group, "bound_device_id", None) is not None:
  4277. # Use device id from `init_process_group(device_id=...)`
  4278. opts.device = group.bound_device_id # type: ignore[assignment]
  4279. elif device.type == "cpu" or _get_object_coll_device(group) == "cpu":
  4280. # pyrefly: ignore [read-only]
  4281. opts.device = torch.device("cpu")
  4282. else:
  4283. # Use the current device set by the user. If user did not set any, this
  4284. # may use default device 0, causing issues like hang or all processes
  4285. # creating context on device 0.
  4286. # pyrefly: ignore [read-only]
  4287. opts.device = device
  4288. if group.rank() == 0:
  4289. warnings.warn( # warn only once
  4290. "barrier(): using the device under current context. "
  4291. "You can specify `device_id` in `init_process_group` to mute this warning.",
  4292. stacklevel=2,
  4293. )
  4294. work = group.barrier(opts=opts)
  4295. if async_op:
  4296. return work
  4297. elif (
  4298. work is not None
  4299. ): # Backward compatible with backends that don't sync at CPP level
  4300. work.wait()
  4301. # Otherwise, the backend has sync'ed at CPP level
  4302. def monitored_barrier(
  4303. group: ProcessGroup | None = GroupMember.WORLD,
  4304. timeout=None,
  4305. wait_all_ranks: bool = False,
  4306. ):
  4307. """
  4308. Synchronize processes similar to ``torch.distributed.barrier``, but consider a configurable timeout.
  4309. It is able to report ranks that did not pass this barrier within the provided timeout.
  4310. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0.
  4311. Rank 0 will block until all send /recv from other ranks are processed, and will report
  4312. failures for ranks that failed to respond in time. Note that if one rank does not reach the
  4313. monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier.
  4314. This collective will block all processes/ranks in the group, until the
  4315. whole group exits the function successfully, making it useful for debugging
  4316. and synchronizing. However, it can have a performance impact and should only
  4317. be used for debugging or scenarios that require full synchronization points
  4318. on the host-side. For debugging purposes, this barrier can be inserted
  4319. before the application's collective calls to check if any ranks are
  4320. desynchronized.
  4321. .. note:: Note that this collective is only supported with the GLOO backend.
  4322. Args:
  4323. group (ProcessGroup, optional): The process group to work on. If
  4324. ``None``, the default process group will be used.
  4325. timeout (datetime.timedelta, optional): Timeout for monitored_barrier.
  4326. If ``None``, the default process group timeout will be used.
  4327. wait_all_ranks (bool, optional): Whether to collect all failed ranks or
  4328. not. By default, this is ``False`` and ``monitored_barrier`` on rank 0
  4329. will throw on the first failed rank it encounters in order to fail
  4330. fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will
  4331. collect all failed ranks and throw an error containing information
  4332. about all failed ranks.
  4333. Returns:
  4334. ``None``.
  4335. Example::
  4336. >>> # xdoctest: +SKIP("need process group init")
  4337. >>> # Note: Process group initialization omitted on each rank.
  4338. >>> import torch.distributed as dist
  4339. >>> if dist.get_rank() != 1:
  4340. >>> dist.monitored_barrier() # Raises exception indicating that
  4341. >>> # rank 1 did not call into monitored_barrier.
  4342. >>> # Example with wait_all_ranks=True
  4343. >>> if dist.get_rank() == 0:
  4344. >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception
  4345. >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into
  4346. >>> # monitored_barrier.
  4347. """
  4348. # Need to call rank not in group before using the group, otherwise
  4349. # "Invalid process group" error is raised.
  4350. if _rank_not_in_group(group):
  4351. _warn_not_in_group("monitored_barrier")
  4352. return
  4353. if get_backend(group) != Backend.GLOO:
  4354. raise ValueError("monitored_barrier is only implemented for GLOO backend.")
  4355. if timeout is None:
  4356. timeout = _get_default_timeout(get_backend(group))
  4357. elif isinstance(timeout, float):
  4358. # TODO(whc) apparently some existing test case for monitored_barrier passes in a timeout in float format?
  4359. warnings.warn(
  4360. "Please specify timeout arg as a timedelta. "
  4361. f"Converting current value of {timeout} assuming it represents seconds",
  4362. stacklevel=2,
  4363. )
  4364. timeout = timedelta(seconds=timeout)
  4365. _check_valid_timeout(timeout)
  4366. group_to_use = _get_default_group() if group is None else group
  4367. return group_to_use.monitored_barrier( # type:ignore[attr-defined]
  4368. timeout, wait_all_ranks=wait_all_ranks
  4369. )
  4370. def _create_process_group_wrapper(
  4371. wrapped_pg: torch._C._distributed_c10d.Backend,
  4372. store_prefix: str,
  4373. store: Store,
  4374. rank: int,
  4375. world_size: int,
  4376. timeout: timedelta = default_pg_timeout,
  4377. ):
  4378. if not _GLOO_AVAILABLE:
  4379. raise AssertionError("ProcessGroupWrapper unsupported without GLOO backend.")
  4380. # (whc) this appears to be just for the gloo backend? if so, `default_pg_timeout` is appropriate...
  4381. # Create a separate prefix store for the helper process group.
  4382. prefix = f"{PG_WRAPPER_STORE_PREFIX}:{store_prefix}"
  4383. store = PrefixStore(prefix, store)
  4384. helper_pg = ProcessGroupGloo(store, rank, world_size, timeout=timeout)
  4385. # Wrap the underlying pg with ProcessGroupWrapper.
  4386. wrapped_pg = _ProcessGroupWrapper(wrapped_pg, helper_pg)
  4387. return wrapped_pg
  4388. # helper function for deterministically hashing a list of ranks to a unique
  4389. # string
  4390. def _hash_ranks_to_str(ranks: list[int]) -> str:
  4391. rank_join: str = "_".join(map(str, ranks))
  4392. # In case there is already a PG with the same rank composition
  4393. unique_str = "_".join([rank_join, str(len(_world.pg_names))])
  4394. return hashlib.sha1(bytes(unique_str, "utf-8"), usedforsecurity=False).hexdigest()
  4395. # Takes a list of ranks and computes an integer color
  4396. def _process_group_color(ranks: list[int]) -> int:
  4397. # Convert list to tuple to make it hashable
  4398. # pyrefly: ignore [bad-assignment]
  4399. ranks = tuple(ranks)
  4400. hash_value = hash(ranks)
  4401. # Split color must be:
  4402. # - a non-negative integer;
  4403. # - a type compatible with C's int because we are pybinding to the latter.
  4404. # Thus, we limit the hash value within c_int's max value.
  4405. max_c_int = 2 ** (ctypes.sizeof(ctypes.c_int) * 8 - 1)
  4406. color = abs(hash_value) % max_c_int
  4407. return color
  4408. def _process_group_name(ranks, use_hashed_name) -> GroupName:
  4409. # Create name for a process group.
  4410. global _world
  4411. if use_hashed_name:
  4412. pg_name = GroupName(_hash_ranks_to_str(ranks))
  4413. else:
  4414. pg_name = GroupName(str(_world.group_count))
  4415. _world.group_count += 1
  4416. # TODO: why is group count incremented only in the else path?
  4417. return pg_name
  4418. def _get_backend_from_str(backend: str | None = None) -> Backend:
  4419. # Default to the same backend as the global process group
  4420. # if backend is not specified.
  4421. if not backend:
  4422. backend = get_backend(_get_default_group())
  4423. return Backend(backend)
  4424. def _is_safe_to_split() -> bool:
  4425. """
  4426. Checks if it is safe to split the any process group in the world.
  4427. This is only safe if the default pg has a bound device id, otherwise
  4428. users must be aware that a pg is only splittable after the first collective is
  4429. issued.
  4430. """
  4431. return _get_default_group().bound_device_id is not None
  4432. @_time_logger
  4433. def split_group(
  4434. parent_pg: ProcessGroup | None = None,
  4435. split_ranks: list | None = None,
  4436. timeout: timedelta | None = None,
  4437. pg_options: Any | None = None,
  4438. group_desc: str | None = None,
  4439. ) -> ProcessGroup | None:
  4440. """
  4441. Create a new process group split from the given parent process group.
  4442. warning:: This is an experimental API. Only the ``NCCL`` and custom plugin backends
  4443. are supported. Other backends will raise an error.
  4444. Users of this API must guarantee that all ranks in the parent group enter this API call,
  4445. and the split of the sub groups is the same across all ranks in the parent group.
  4446. Args:
  4447. parent_pg (ProcessGroup, optional): The parent process group. If None,
  4448. the default process group will be used. Users need to guarantee that
  4449. the parent group is fully initialized (e.g, communicators are initialized)
  4450. split_ranks (list[list[int]]): the split ranks, which is a list of list of ranks.
  4451. Users need to make sure the validity of the split ranks such that one
  4452. split (represented by one inner list of ints) does not overlap with any other split.
  4453. Note that the ranks in each split is the group rank (instead of global rank)
  4454. in the parent pg. For example, if the parent group has 4 ranks, and split_ranks can be
  4455. [[0, 1], [2, 3]]. Note [[0,1]] is also a valid split, in which case ranks 2, 3 would
  4456. return a non-group member.
  4457. timeout (timedelta, optional): see `init_process_group` for details and default value.
  4458. pg_options (ProcessGroupOptions, optional): Additional options need to be passed in during
  4459. the construction of specific process groups. i.e.``is_high_priority_stream``
  4460. can be specified so that process group can pick up high priority cuda streams.
  4461. group_desc (str, optional): a string to describe the process group.
  4462. Returns:
  4463. ProcessGroup if the current rank is within one split/subgroup given by split_ranks,
  4464. or None if the current rank is not part of any split_ranks`.
  4465. """
  4466. # check inputs
  4467. if split_ranks is None or len(split_ranks) == 0:
  4468. raise ValueError("split_ranks cannot be None or empty")
  4469. global _world
  4470. default_pg = _get_default_group()
  4471. device_id = default_pg.bound_device_id
  4472. if not device_id and not _use_torchcomms_enabled():
  4473. raise RuntimeError(
  4474. "No device associated with the default pg, not safe to split any process groups"
  4475. )
  4476. global_rank = default_pg.rank()
  4477. global_world_size = default_pg.size()
  4478. if not parent_pg:
  4479. parent_pg = default_pg
  4480. if parent_pg not in _world.pg_group_ranks:
  4481. raise ValueError(f"Group {parent_pg} is not registered")
  4482. parent_global_to_group_ranks = _world.pg_group_ranks[parent_pg]
  4483. parent_group_to_global_ranks = {
  4484. group_rank: global_rank
  4485. for global_rank, group_rank in parent_global_to_group_ranks.items()
  4486. }
  4487. if global_rank not in parent_global_to_group_ranks:
  4488. raise ValueError(
  4489. f"Global rank {global_rank} is not part of the parent group {parent_pg}"
  4490. )
  4491. parent_group_rank = parent_global_to_group_ranks[global_rank]
  4492. parent_backend = parent_pg._get_backend(torch.device("cuda"))
  4493. # if the parent backend does not support splitting, raise error
  4494. # currently this API only support NCCL backend
  4495. if (
  4496. not parent_backend or not parent_backend.supports_splitting
  4497. ) and not _use_torchcomms_enabled():
  4498. raise RuntimeError(
  4499. "No backend for the parent process group or its backend does not support splitting"
  4500. )
  4501. # set the group_desc before the color or no_cloor split
  4502. if hasattr(parent_backend, "comm_split_count") and group_desc is None:
  4503. group_desc = f"{parent_pg.group_desc}:split:{parent_backend.comm_split_count()}" # type: ignore[attr-defined]
  4504. parent_backend_str, _ = _world.pg_map[parent_pg]
  4505. # same type of backend as the parent process group
  4506. backend = Backend(parent_backend_str)
  4507. backend_config = BackendConfig(backend)
  4508. # TODO: figure out pg option for torchComms
  4509. if pg_options is None and not _use_torchcomms_enabled():
  4510. # default pg_options same as the parent process group
  4511. # A deep copy is needed because if the option will be modified inside split
  4512. # and if we split parent pg multiple times, we will run into device out of bound error.
  4513. pg_options = copy.deepcopy(parent_backend.options)
  4514. # this timeout defaulting/validation is used for all the new_groups/new_subgroups variants,
  4515. # which may just pass their timeout value (or None)
  4516. if timeout is None:
  4517. timeout = _get_default_timeout(backend)
  4518. _check_valid_timeout(timeout)
  4519. # find my group of ranks and my group local rank in split_ranks
  4520. # for ranks which are not in any split PGs, we just pass in this the first split group
  4521. # and None will be returned.
  4522. my_group = split_ranks[0]
  4523. for split_group in split_ranks:
  4524. if len(split_group) == 0:
  4525. raise ValueError("the split group cannot be empty")
  4526. if len(split_group) > global_world_size:
  4527. raise ValueError(
  4528. "the split group's size should be less or equal to the world_size set by init_process_group"
  4529. )
  4530. if len(split_group) != len(set(split_group)):
  4531. raise ValueError("the split group cannot have duplicate ranks")
  4532. split_group = sorted(split_group)
  4533. if parent_group_rank in split_group:
  4534. my_group = split_group
  4535. break
  4536. # use_hashed_name is True to ensure that subgroups have unique names.
  4537. # This is needed as some backends (e.g. Gloo) use the group name as a
  4538. # PrefixStore prefix for initialization of splits. Thus, names have to be
  4539. # unique to avoid key collisions.
  4540. group_name = _process_group_name(my_group, use_hashed_name=True)
  4541. split_pg = parent_pg.split_group(
  4542. my_group,
  4543. timeout=timeout,
  4544. opts=pg_options,
  4545. group_name=group_name,
  4546. group_desc=group_desc,
  4547. )
  4548. if split_pg is None:
  4549. return None
  4550. global_ranks_in_my_group = [parent_group_to_global_ranks[rank] for rank in my_group]
  4551. split_pg.bound_device_id = device_id # type: ignore[union-attr]
  4552. split_backend_class = split_pg._get_backend(torch.device("cuda"))
  4553. if not _use_torchcomms_enabled():
  4554. split_backend_class._set_sequence_number_for_group()
  4555. if split_pg.group_name != group_name:
  4556. raise AssertionError(
  4557. f"group name should be set to {group_name} but got {split_pg.group_name}"
  4558. )
  4559. # update global state
  4560. _world.pg_map[split_pg] = (backend, split_pg.get_group_store())
  4561. _world.pg_names[split_pg] = group_name
  4562. _register_process_group(group_name, split_pg)
  4563. _world.pg_backend_config[split_pg] = str(backend_config)
  4564. pg_tag = f"ptd:{group_name}"
  4565. _world.tags_to_pg.setdefault(pg_tag, []).append(split_pg)
  4566. _world.pg_to_tag[split_pg] = pg_tag
  4567. # Create the global rank to group rank mapping
  4568. _world.pg_group_ranks[split_pg] = {
  4569. global_rank: group_rank
  4570. for group_rank, global_rank in enumerate(global_ranks_in_my_group)
  4571. }
  4572. if _use_torchcomms_enabled():
  4573. # pyrefly: ignore [missing-attribute]
  4574. _world.comms.append(split_backend_class.get_comm())
  4575. return split_pg
  4576. @_time_logger
  4577. def new_group(
  4578. ranks=None,
  4579. timeout=None,
  4580. backend=None,
  4581. pg_options=None,
  4582. use_local_synchronization: bool = False,
  4583. group_desc=None,
  4584. device_id: torch.device | None = None,
  4585. ):
  4586. """
  4587. Create a new distributed group.
  4588. This function requires that all processes in the main group (i.e. all
  4589. processes that are part of the distributed job) enter this function, even
  4590. if they are not going to be members of the group. Additionally, groups
  4591. should be created in the same order in all processes.
  4592. .. warning::
  4593. Safe concurrent usage:
  4594. When using multiple process groups with the ``NCCL`` backend, the user
  4595. must ensure a globally consistent execution order of collectives across
  4596. ranks.
  4597. If multiple threads within a process issue collectives, explicit
  4598. synchronization is necessary to ensure consistent ordering.
  4599. When using async variants of torch.distributed communication APIs,
  4600. a work object is returned and the communication kernel is
  4601. enqueued on a separate CUDA stream, allowing overlap of communication
  4602. and computation. Once one or more async ops have been issued on one process
  4603. group, they must be synchronized with other cuda streams by calling `work.wait()`
  4604. before using another process group.
  4605. See `Using multiple NCCL communicators concurrently
  4606. <https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html#using-multiple-nccl-communicators-concurrently>`
  4607. for more details.
  4608. Args:
  4609. ranks (list[int]): List of ranks of group members. If ``None``, will be
  4610. set to all ranks. Default is ``None``.
  4611. timeout (timedelta, optional): see `init_process_group` for details and default value.
  4612. backend (str or Backend, optional): The backend to use. Depending on
  4613. build-time configurations, valid values are ``gloo`` and ``nccl``.
  4614. By default uses the same backend as the global group. This field
  4615. should be given as a lowercase string (e.g., ``"gloo"``), which can
  4616. also be accessed via :class:`Backend` attributes (e.g.,
  4617. ``Backend.GLOO``). If ``None`` is passed in, the backend
  4618. corresponding to the default process group will be used. Default is
  4619. ``None``.
  4620. pg_options (ProcessGroupOptions, optional): process group options
  4621. specifying what additional options need to be passed in during
  4622. the construction of specific process groups. i.e. for the ``nccl``
  4623. backend, ``is_high_priority_stream`` can be specified so that
  4624. process group can pick up high priority cuda streams. For other available options to config nccl,
  4625. See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/types.html#ncclconfig-tuse_local_synchronization
  4626. (bool, optional): perform a group-local barrier at the end of the process group creation.
  4627. This is different in that non-member ranks don't need to call into API and don't
  4628. join the barrier.
  4629. group_desc (str, optional): a string to describe the process group.
  4630. device_id (torch.device, optional): a single, specific device
  4631. to "bind" this process to, The `new_group` call will try to initialize
  4632. a communication backend immediately for the device if this field is given.
  4633. Returns:
  4634. A handle of distributed group that can be given to collective calls or
  4635. GroupMember.NON_GROUP_MEMBER if the rank is not part of ``ranks``.
  4636. N.B. use_local_synchronization doesn't work with MPI.
  4637. N.B. While use_local_synchronization=True can be significantly faster with larger
  4638. clusters and small process groups, care must be taken since it changes cluster behavior
  4639. as non-member ranks don't join the group barrier().
  4640. N.B. use_local_synchronization=True can lead to deadlocks when each rank creates
  4641. multiple overlapping process groups. To avoid that, make sure all ranks follow the
  4642. same global creation order.
  4643. """
  4644. return _new_group_with_tag(
  4645. ranks,
  4646. timeout,
  4647. backend,
  4648. pg_options,
  4649. None,
  4650. use_local_synchronization=use_local_synchronization,
  4651. group_desc=group_desc,
  4652. device_id=device_id,
  4653. )
  4654. def _new_group_with_tag(
  4655. ranks=None,
  4656. timeout=None,
  4657. backend=None,
  4658. backend_options=None,
  4659. pg_tag=None,
  4660. use_local_synchronization=False,
  4661. group_desc=None,
  4662. device_id: torch.device | None = None,
  4663. ):
  4664. """
  4665. Variant of ``new_group`` that exposes tag creation.
  4666. :: N.B. The mechanism is experimental and tied to the functional collectives effort, see
  4667. ``torch.distributed._functional_collectives`` for reference on how to use it.
  4668. """
  4669. global _world
  4670. default_pg = _get_default_group()
  4671. if device_id is None:
  4672. device_id = default_pg.bound_device_id
  4673. elif default_pg.bound_device_id is not None:
  4674. if device_id != default_pg.bound_device_id:
  4675. raise AssertionError(
  4676. "Mismatched bound device between new pg and the default pg."
  4677. )
  4678. default_backend, default_store = _world.pg_map[default_pg]
  4679. global_rank = default_pg.rank()
  4680. global_world_size = default_pg.size()
  4681. # Default to the same backend as the global process group
  4682. # if the backend is not specified.
  4683. if not backend:
  4684. backend = default_backend
  4685. backend = Backend(backend)
  4686. # this timeout defaulting/validation is used for all the new_groups/new_subgroups variants,
  4687. # which may just pass their timeout value (or None)
  4688. if timeout is None:
  4689. timeout = _get_default_timeout(backend)
  4690. _check_valid_timeout(timeout)
  4691. if use_local_synchronization:
  4692. # MPI backend doesn't have have a way for us to perform a partial sync
  4693. if backend == Backend.MPI:
  4694. raise ValueError(
  4695. "MPI backend doesn't support use_local_synchronization=True"
  4696. )
  4697. if ranks is not None and get_rank() not in ranks:
  4698. return None
  4699. # checks the input ranks
  4700. if ranks is not None:
  4701. ranks = sorted(ranks)
  4702. group_world_size = len(ranks)
  4703. if group_world_size > global_world_size:
  4704. raise ValueError(
  4705. "the new group's world size should be less or "
  4706. "equal to the world size set by "
  4707. "init_process_group"
  4708. )
  4709. # check ranks' sanity
  4710. for rank in ranks:
  4711. if rank < 0 or rank >= global_world_size:
  4712. raise ValueError(
  4713. "The new group's rank should be within "
  4714. "the world_size set by init_process_group"
  4715. )
  4716. if global_rank in ranks:
  4717. group_rank = ranks.index(global_rank)
  4718. else:
  4719. group_rank = None
  4720. else:
  4721. ranks = list(range(global_world_size))
  4722. group_world_size = global_world_size
  4723. group_rank = global_rank
  4724. group_name = _process_group_name(ranks, use_hashed_name=use_local_synchronization)
  4725. pg, pg_store = _new_process_group_helper(
  4726. group_world_size,
  4727. group_rank,
  4728. ranks,
  4729. backend,
  4730. default_store,
  4731. group_name,
  4732. backend_options=backend_options,
  4733. timeout=timeout,
  4734. pg_tag=pg_tag,
  4735. device_id=device_id,
  4736. group_desc=group_desc,
  4737. )
  4738. # Create the global rank to group rank mapping
  4739. _world.pg_group_ranks[pg] = {
  4740. global_rank: group_rank for group_rank, global_rank in enumerate(ranks)
  4741. }
  4742. if _is_barrier_after_init() == 1:
  4743. # barrier at the end to ensure that once we return from this method, all
  4744. # process groups including global variables (if any) are updated
  4745. # correctly on all ranks.
  4746. # Update 04/2023: for large-scale runs, this barrier (esp. store-based
  4747. # barrier) may be costly and/or unscalable. Also, in a lot of cases,
  4748. # these barriers may be unnecessary, as proven by a green CI after
  4749. # removal. An environment variable `TORCH_DIST_INIT_BARRIER` has been
  4750. # added which enables this barrier only when set to 1.
  4751. logger.info(
  4752. "Performing barrier after ProcessGroup initialization since "
  4753. "TORCH_DIST_INIT_BARRIER = 1"
  4754. )
  4755. if backend == Backend.MPI:
  4756. # MPI doesn't have store.
  4757. barrier()
  4758. else:
  4759. barrier_store = pg_store if use_local_synchronization else default_store
  4760. world_size = len(ranks) if use_local_synchronization else get_world_size()
  4761. # Use store based barrier here since barrier() used a bunch of
  4762. # default devices and messes up NCCL internal state.
  4763. _store_based_barrier(
  4764. global_rank, barrier_store, group_name, world_size, timeout
  4765. )
  4766. return pg
  4767. def new_subgroups(
  4768. group_size=None,
  4769. group=None,
  4770. timeout=None,
  4771. backend=None,
  4772. pg_options=None,
  4773. group_desc=None,
  4774. ):
  4775. """
  4776. Create subgroups of equal size.
  4777. By default, it creates intra-machine subgroups,
  4778. where each of which contains all the ranks of a machine, based on the assumption
  4779. that each machine has the same number of devices.
  4780. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  4781. It requires that all processes in the main group (i.e. all
  4782. processes that are part of the distributed job) enter this function, even
  4783. if they are not going to be members of the group.
  4784. .. warning::
  4785. If ``group_size`` is passed in, the world size must be divisible by ``group_size``.
  4786. If no ``group_size`` is passed in, it believe that you are creating a group based
  4787. on CUDA and determining the group size by number of CUDA devices, and if not all
  4788. the machines have the same number of devices, the subgroup division will be
  4789. different across nodes and can cause unexpected behaviors. Therefore, if you are
  4790. creating a subgroup that does not depend on CUDA (such as Gloo on CPU), please
  4791. pass in ``group_size`` correctly.
  4792. .. warning::
  4793. See warning `Safe concurrent usage` for `new_group` API for important details about
  4794. using multiple process groups concurrently in a safe manner.
  4795. Args:
  4796. group_size (int, optional): The size of each subgroup. If ``None``,
  4797. the default subgroup size is equal to the number of devices on each machine,
  4798. based on the assumption that each machine has exactly the same
  4799. number of devices. Default is ``None``.
  4800. group (ProcessGroup, optional): The process group to work on. If
  4801. ``None``, the default process group will be used. Default is ``None``.
  4802. timeout (timedelta, optional): see `init_process_group` for details and default value.
  4803. backend (str or Backend, optional): The backend to use. Depending on
  4804. build-time configurations, valid values are ``gloo`` and ``nccl``.
  4805. By default uses the same backend as the global group. This field
  4806. should be given as a lowercase string (e.g., ``"gloo"``), which can
  4807. also be accessed via :class:`Backend` attributes (e.g.,
  4808. ``Backend.GLOO``). If ``None`` is passed in, the backend
  4809. corresponding to the default process group will be used. Default is
  4810. ``None``.
  4811. pg_options (ProcessGroupOptions, optional): process group options
  4812. specifying what additional options need to be passed in during
  4813. the construction of specific process groups. i.e. for the ``nccl``
  4814. backend, ``is_high_priority_stream`` can be specified so that
  4815. process group can pick up high priority cuda streams.
  4816. group_desc (str, optional): A string describing the group. Each subgroup will
  4817. inherit its group_desc
  4818. Returns:
  4819. The subgroup containing the current rank, and all the subgroups used for cleanup.
  4820. Examples:
  4821. >>> # Create intra-machine subgroups.
  4822. >>> # xdoctest: +SKIP("need process group init")
  4823. >>> cur_subgroup, subgroups = dist.new_subgroups()
  4824. >>> # Allreduce within the machine.
  4825. >>> rank = dist.get_rank()
  4826. >>> tensor = torch.ones(1, device=rank) * rank
  4827. >>> dist.all_reduce(tensor, group=cur_subgroup)
  4828. >>> tensor
  4829. tensor([28]) # Assume 8 CUDA devices per machine. 28 is sum(range(8)).
  4830. >>> # Cleanup.
  4831. >>> for subgroup in subgroups:
  4832. >>> dist.destroy_process_group(subgroup)
  4833. """
  4834. if group_size is None:
  4835. if not torch.cuda.is_available():
  4836. raise ValueError(
  4837. "Default group size only takes effect when CUDA is available."
  4838. "If your subgroup using a backend that does not depend on CUDA,"
  4839. "please pass in 'group_size' correctly."
  4840. )
  4841. group_size = torch.cuda.device_count()
  4842. if group_size <= 0:
  4843. raise ValueError(f"The arg 'group_size' ({group_size}) must be positive")
  4844. world_size = get_world_size(group=group)
  4845. if world_size < group_size:
  4846. raise ValueError(
  4847. f"The arg 'group_size' ({group_size}) must not exceed the world size ({world_size})"
  4848. )
  4849. if world_size % group_size != 0:
  4850. raise ValueError(
  4851. f"The world size ({world_size}) must be divisible by '{group_size=}'"
  4852. )
  4853. # TODO: Use itertools.batched(get_process_group_ranks(group=group), group_size) instead when Python 3.12 is supported.
  4854. ranks = get_process_group_ranks(group=group)
  4855. ranks_per_subgroup_list = [
  4856. ranks[i : i + group_size] for i in range(0, len(ranks), group_size)
  4857. ]
  4858. return new_subgroups_by_enumeration(
  4859. ranks_per_subgroup_list,
  4860. timeout=timeout,
  4861. backend=backend,
  4862. pg_options=pg_options,
  4863. group_desc=group_desc,
  4864. )
  4865. def new_subgroups_by_enumeration(
  4866. ranks_per_subgroup_list,
  4867. timeout=None,
  4868. backend=None,
  4869. pg_options=None,
  4870. group_desc=None,
  4871. ):
  4872. """
  4873. Create subgroups by dividing the global world.
  4874. The division is specified by a nested list of ranks. The subgroups cannot have
  4875. overlap, and some ranks may not have to be in any subgroup.
  4876. This is a convenience API that calls ``new_group`` to generate multiple subgroups.
  4877. It requires that all processes in the main group (i.e. all
  4878. processes that are part of the distributed job) enter this function, even
  4879. if they are not going to be members of the group.
  4880. .. warning::
  4881. See warning `Safe concurrent usage` for `new_group` API for important details about
  4882. using multiple process groups concurrently in a safe manner.
  4883. Args:
  4884. ranks_per_subgroup_list (list[list[int]]): A nested list of ranks of
  4885. group members.
  4886. timeout (timedelta, optional): see `init_process_group` for details and default value.
  4887. backend (str or Backend, optional): The backend to use. Depending on
  4888. build-time configurations, valid values are ``gloo`` and ``nccl``.
  4889. By default uses the same backend as the global group. This field
  4890. should be given as a lowercase string (e.g., ``"gloo"``), which can
  4891. also be accessed via :class:`Backend` attributes (e.g.,
  4892. ``Backend.GLOO``). If ``None`` is passed in, the backend
  4893. corresponding to the default process group will be used. Default is
  4894. ``None``.
  4895. pg_options (ProcessGroupOptions, optional): process group options
  4896. specifying what additional options need to be passed in during
  4897. the construction of specific process groups. i.e. for the ``nccl``
  4898. backend, ``is_high_priority_stream`` can be specified so that
  4899. process group can pick up high priority cuda streams.
  4900. group_desc (str, optional): A string describing the group. Each subgroup will
  4901. inherit its group_desc.
  4902. Returns:
  4903. The subgroup containing the current rank, and all the subgroups used for cleanup.
  4904. Examples:
  4905. >>> # Create two subgroups, where each has 2 processes.
  4906. >>> # xdoctest: +SKIP("need process group init")
  4907. >>> cur_subgroup, subgroups = dist.new_subgroups(ranks=[[0, 2], [1, 3]])
  4908. >>> rank = dist.get_rank()
  4909. >>> tensor = torch.ones(1, device=rank) * rank
  4910. >>> dist.all_reduce(tensor, group=cur_subgroup)
  4911. >>> tensor
  4912. tensor([2]) # Subgroup 0: ranks 0 and 2
  4913. tensor([4]) # Subgroup 1: ranks 1 and 3
  4914. """
  4915. if ranks_per_subgroup_list is None or len(ranks_per_subgroup_list) == 0:
  4916. raise ValueError("The arg 'ranks_per_subgroup_list' cannot be empty")
  4917. subgroups = []
  4918. cur_subgroup = None
  4919. # Create a mapping from rank to subgroup to check if there is any subgroup overlap.
  4920. rank_to_ranks_dict = {} # type: ignore[var-annotated]
  4921. for ranks in ranks_per_subgroup_list:
  4922. subgroup = new_group(
  4923. ranks=ranks,
  4924. timeout=timeout,
  4925. backend=backend,
  4926. pg_options=pg_options,
  4927. group_desc=group_desc,
  4928. )
  4929. subgroups.append(subgroup)
  4930. my_rank = get_rank()
  4931. for rank in ranks:
  4932. if rank in rank_to_ranks_dict:
  4933. raise ValueError(
  4934. f"Rank {rank} has appeared in both subgroup {rank_to_ranks_dict[rank]} and {ranks}"
  4935. )
  4936. rank_to_ranks_dict[rank] = ranks
  4937. if my_rank == rank:
  4938. cur_subgroup = subgroup
  4939. logger.info("Rank %s is assigned to subgroup %s", rank, ranks)
  4940. return cur_subgroup, subgroups
  4941. def _find_pg_by_ranks_and_tag(tag: str, ranks: list[int]) -> ProcessGroup | None:
  4942. if len(tag) > 0 and not tag.startswith("ptd:") and not tag.startswith("user:"):
  4943. tag = f"user:{tag}"
  4944. for group in _world.tags_to_pg.get(tag, []):
  4945. if group.size() != len(ranks):
  4946. continue
  4947. group_ranks = get_process_group_ranks(group)
  4948. good = all(r in group_ranks for r in ranks)
  4949. if good:
  4950. return group
  4951. return None
  4952. def _find_or_create_pg_by_ranks_and_tag(
  4953. tag: str, ranks: list[int], stride: int
  4954. ) -> ProcessGroup:
  4955. if len(ranks) % stride != 0:
  4956. raise ValueError(
  4957. f"Ranks length ({len(ranks)}) must be divisible by stride ({stride})"
  4958. )
  4959. my_rank = get_rank()
  4960. my_ranks = None
  4961. if stride == len(ranks):
  4962. my_ranks = ranks.copy()
  4963. if my_rank not in my_ranks:
  4964. raise AssertionError("rankset doesn't include the current node")
  4965. else:
  4966. for i in range(0, len(ranks), stride):
  4967. rank_set = ranks[i : i + stride]
  4968. if my_rank in rank_set:
  4969. my_ranks = rank_set
  4970. if my_ranks is None:
  4971. raise AssertionError("rankset doesn't include the current node")
  4972. my_ranks = sorted(my_ranks)
  4973. pg = _find_pg_by_ranks_and_tag(tag, my_ranks)
  4974. if pg is not None:
  4975. return pg
  4976. if tag == "":
  4977. raise ValueError("Cannot automatically create PG with empty tag")
  4978. # TODO copy settings and timeout from default PG
  4979. return _new_group_with_tag(my_ranks, pg_tag=tag)
  4980. def _get_group_tag(pg: ProcessGroup) -> str:
  4981. """Return the tag associated with ``pg``."""
  4982. tag = _world.pg_to_tag[pg]
  4983. tag = tag.removeprefix("user:")
  4984. return tag
  4985. def _get_process_group_name(pg: ProcessGroup) -> str:
  4986. return _world.pg_names.get(pg, "None")
  4987. def _get_process_group_store(pg: ProcessGroup) -> Store:
  4988. return _world.pg_map[pg][1]
  4989. # Shrink flags for process group backends
  4990. SHRINK_DEFAULT = 0x00
  4991. SHRINK_ABORT = 0x01
  4992. @_time_logger
  4993. def shrink_group(
  4994. ranks_to_exclude: list[int],
  4995. group: ProcessGroup | None = None,
  4996. shrink_flags: int = SHRINK_DEFAULT,
  4997. pg_options: Any | None = None,
  4998. ) -> ProcessGroup:
  4999. """
  5000. Shrinks a process group by excluding specified ranks.
  5001. Creates and returns a new, smaller process group comprising only the ranks
  5002. from the original group that were not in the ``ranks_to_exclude`` list.
  5003. Args:
  5004. ranks_to_exclude (List[int]): A list of ranks from the original
  5005. ``group`` to exclude from the new group.
  5006. group (ProcessGroup, optional): The process group to shrink. If ``None``,
  5007. the default process group is used. Defaults to ``None``.
  5008. shrink_flags (int, optional): Flags to control the shrinking behavior.
  5009. Can be ``SHRINK_DEFAULT`` (default) or ``SHRINK_ABORT``.
  5010. ``SHRINK_ABORT`` will attempt to terminate ongoing operations
  5011. in the parent communicator before shrinking.
  5012. Defaults to ``SHRINK_DEFAULT``.
  5013. pg_options (ProcessGroupOptions, optional): Backend-specific options to apply
  5014. to the shrunken process group. If provided, the backend will use
  5015. these options when creating the new group. If omitted, the new group
  5016. inherits defaults from the parent.
  5017. Returns:
  5018. ProcessGroup: a new group comprised of the remaining ranks. If the
  5019. default group was shrunk, the returned group becomes the new default group.
  5020. Raises:
  5021. TypeError: if the group’s backend does not support shrinking.
  5022. ValueError: if ``ranks_to_exclude`` is invalid (empty, out of bounds,
  5023. duplicates, or excludes all ranks).
  5024. RuntimeError: if an excluded rank calls this function or the backend
  5025. fails the operation.
  5026. Notes:
  5027. - Only non-excluded ranks should call this function; excluded ranks
  5028. must not participate in the shrink operation.
  5029. - Shrinking the default group destroys all other process groups since
  5030. rank reassignment makes them inconsistent.
  5031. """
  5032. # Step 1: Validate input parameters with comprehensive error checking
  5033. _validate_shrink_inputs(ranks_to_exclude, shrink_flags)
  5034. # Step 2: Get target group and essential properties
  5035. target_group_info = _prepare_shrink_target_group(group)
  5036. # Step 3: Validate backend requirements and availability
  5037. backend_impl = _validate_shrink_backend_requirements(target_group_info)
  5038. # Step 4: Validate ranks against group and check for duplicates
  5039. excluded_ranks_set = _validate_and_process_excluded_ranks(
  5040. ranks_to_exclude, target_group_info
  5041. )
  5042. # Step 5: Execute the actual shrink operation (backend-specific)
  5043. new_backend = backend_impl.shrink(
  5044. sorted(excluded_ranks_set),
  5045. shrink_flags,
  5046. pg_options if pg_options is not None else None,
  5047. )
  5048. # Step 6: Handle cleanup and creation of new process group
  5049. target_group_info["pg_options_override"] = pg_options
  5050. return _finalize_shrunk_group(target_group_info, excluded_ranks_set, new_backend)
  5051. def _validate_shrink_inputs(ranks_to_exclude: list[int], shrink_flags: int) -> None:
  5052. """Validate input parameters for shrink_group."""
  5053. if not isinstance(ranks_to_exclude, list):
  5054. raise TypeError(
  5055. f"ranks_to_exclude must be a list, but got {type(ranks_to_exclude).__name__}. "
  5056. f"Example: [1, 3, 5] to exclude ranks 1, 3, and 5."
  5057. )
  5058. if not ranks_to_exclude:
  5059. raise ValueError(
  5060. "ranks_to_exclude cannot be empty. To shrink a group, you must specify at least "
  5061. "one rank to exclude. Example: [failed_rank_id]"
  5062. )
  5063. # Validate shrink_flags with clear explanation of valid values
  5064. valid_flags = [SHRINK_DEFAULT, SHRINK_ABORT]
  5065. if not isinstance(shrink_flags, int) or shrink_flags not in valid_flags:
  5066. raise ValueError(
  5067. f"Invalid shrink_flags value: {shrink_flags}. Must be one of: "
  5068. f"SHRINK_DEFAULT ({SHRINK_DEFAULT}) or SHRINK_ABORT ({SHRINK_ABORT}). "
  5069. f"Use SHRINK_ABORT to abort ongoing operations before shrinking."
  5070. )
  5071. def _prepare_shrink_target_group(group: ProcessGroup | None) -> dict:
  5072. """Prepare and validate the target group for shrinking."""
  5073. target_pg = group if group is not None else _get_default_group()
  5074. # Cache frequently accessed properties to avoid repeated calls
  5075. group_size = int(target_pg.size())
  5076. group_info = {
  5077. "process_group": target_pg,
  5078. "is_default_group": (target_pg == _get_default_group()),
  5079. "group_size": group_size,
  5080. "current_rank": target_pg.rank(),
  5081. "group_name": _get_process_group_name(target_pg),
  5082. }
  5083. # Validate that we have a valid process group
  5084. if group_size <= 1:
  5085. raise ValueError(
  5086. f"Cannot shrink a process group with size {group_size}. "
  5087. f"Group must have at least 2 ranks to support shrinking."
  5088. )
  5089. return group_info
  5090. def _validate_shrink_backend_requirements(group_info: dict) -> Any:
  5091. """Return the backend implementation for the target group or raise if unsupported."""
  5092. target_pg = group_info["process_group"]
  5093. group_name = group_info["group_name"]
  5094. # Get the group's backend directly via ProcessGroup API. Prefer a bound device if present,
  5095. # otherwise try CUDA then fall back to CPU.
  5096. try:
  5097. preferred_device = getattr(target_pg, "bound_device_id", None)
  5098. if preferred_device is not None:
  5099. backend_impl = target_pg._get_backend(preferred_device)
  5100. else:
  5101. # Try CUDA first if available, else CPU
  5102. try:
  5103. backend_impl = target_pg._get_backend(torch.device("cuda"))
  5104. except Exception:
  5105. backend_impl = target_pg._get_backend(torch.device("cpu"))
  5106. except RuntimeError as e:
  5107. raise RuntimeError(
  5108. f"Cannot access device backend for process group '{group_name}'. "
  5109. f"Ensure the process group was initialized with a compatible device backend and devices are available."
  5110. ) from e
  5111. try:
  5112. supports = bool(backend_impl.supports_shrinking)
  5113. except Exception:
  5114. supports = False
  5115. if not supports:
  5116. raise TypeError(
  5117. f"Process group backend for '{group_name}' does not support shrinking operations."
  5118. )
  5119. return backend_impl
  5120. def _validate_and_process_excluded_ranks(
  5121. ranks_to_exclude: list[int], group_info: dict
  5122. ) -> set:
  5123. """Validate excluded ranks and convert to set for efficient operations."""
  5124. group_size = group_info["group_size"]
  5125. current_rank = group_info["current_rank"]
  5126. # Use set for O(1) duplicate detection and membership testing
  5127. excluded_ranks_set = set()
  5128. # Validate each rank with detailed error messages
  5129. for i, rank in enumerate(ranks_to_exclude):
  5130. if not isinstance(rank, int):
  5131. raise TypeError(
  5132. f"All elements in ranks_to_exclude must be integers. "
  5133. f"Element at index {i} is {type(rank).__name__}: {rank}"
  5134. )
  5135. if not (0 <= rank < group_size):
  5136. raise ValueError(
  5137. f"Rank {rank} at index {i} is out of bounds for group size {group_size}. "
  5138. f"Valid ranks are in range [0, {group_size - 1}]."
  5139. )
  5140. if rank in excluded_ranks_set:
  5141. raise ValueError(
  5142. f"Duplicate rank {rank} found in ranks_to_exclude at index {i}. "
  5143. f"Each rank can only be excluded once."
  5144. )
  5145. excluded_ranks_set.add(rank)
  5146. # Ensure we don't exclude all ranks
  5147. if len(excluded_ranks_set) >= group_size:
  5148. raise ValueError(
  5149. f"Cannot exclude all {group_size} ranks from process group. "
  5150. f"At least one rank must remain. Excluding {len(excluded_ranks_set)} ranks."
  5151. )
  5152. # Critical check: current rank should not be in excluded list
  5153. if current_rank in excluded_ranks_set:
  5154. raise RuntimeError(
  5155. f"Current rank {current_rank} is in the exclusion list and should not call shrink_group(). "
  5156. f"Only non-excluded ranks should participate in the shrinking operation. "
  5157. f"Excluded ranks should terminate their processes instead."
  5158. )
  5159. return excluded_ranks_set
  5160. def _finalize_shrunk_group(
  5161. group_info: dict, excluded_ranks_set: set, new_backend
  5162. ) -> ProcessGroup:
  5163. """Clean up old group and create new shrunk process group."""
  5164. target_pg = group_info["process_group"]
  5165. is_default_group = group_info["is_default_group"]
  5166. # Handle default group dependencies - destroy other groups first
  5167. if is_default_group:
  5168. _destroy_all_other_groups(exclude_group=target_pg)
  5169. # Gather original group metadata before cleanup
  5170. original_group_metadata = _extract_group_metadata(target_pg)
  5171. # Calculate remaining ranks efficiently
  5172. original_ranks = get_process_group_ranks(target_pg)
  5173. remaining_ranks = [
  5174. rank for rank in original_ranks if rank not in excluded_ranks_set
  5175. ]
  5176. # Clean up the original group
  5177. _cleanup_original_group(target_pg, is_default_group)
  5178. # Create and configure the new process group
  5179. new_pg = _create_shrunk_process_group(
  5180. new_backend, remaining_ranks, original_group_metadata, is_default_group
  5181. )
  5182. # Register the new group in global state
  5183. if is_default_group:
  5184. _update_default_pg(new_pg)
  5185. # Update global state with new group information
  5186. rank_mapping = {
  5187. global_rank: group_rank
  5188. for group_rank, global_rank in enumerate(remaining_ranks)
  5189. }
  5190. _update_process_group_global_state(
  5191. pg=new_pg,
  5192. backend_name=original_group_metadata["backend_name"],
  5193. store=original_group_metadata["store"],
  5194. group_name=original_group_metadata["new_group_name"],
  5195. backend_config=original_group_metadata["backend_config"],
  5196. rank_mapping=rank_mapping,
  5197. )
  5198. return new_pg
  5199. def _extract_group_metadata(target_pg: ProcessGroup) -> dict:
  5200. """Extract metadata from the original group before cleanup."""
  5201. original_backend_name, original_store = _world.pg_map[target_pg]
  5202. original_backend_config = _world.pg_backend_config.get(target_pg, "")
  5203. original_group_name = _get_process_group_name(target_pg)
  5204. # Extract device binding information before cleanup to avoid accessing destroyed group
  5205. bound_device_id = None
  5206. if hasattr(target_pg, "bound_device_id"):
  5207. bound_device_id = target_pg.bound_device_id
  5208. # Generate new group name for the shrunk group; hash for uniqueness across backends
  5209. remaining_ranks = list(get_process_group_ranks(target_pg))
  5210. new_group_name = _process_group_name(remaining_ranks, use_hashed_name=True)
  5211. return {
  5212. "backend_name": original_backend_name,
  5213. "store": original_store,
  5214. "backend_config": original_backend_config,
  5215. "original_group_name": original_group_name,
  5216. "new_group_name": new_group_name,
  5217. "bound_device_id": bound_device_id, # Safe to access after cleanup
  5218. }
  5219. def _cleanup_original_group(target_pg: ProcessGroup, is_default_group: bool) -> None:
  5220. """Clean up the original process group safely."""
  5221. try:
  5222. destroy_process_group(target_pg)
  5223. except Exception:
  5224. group_type = "default" if is_default_group else "non-default"
  5225. logger.warning(
  5226. "Failed to destroy %s group during shrinking", group_type, exc_info=True
  5227. )
  5228. # Ensure global state cleanup even if destroy_process_group fails
  5229. _cleanup_process_group_global_state(target_pg)
  5230. def _create_shrunk_process_group(
  5231. new_backend, remaining_ranks: list[int], metadata: dict, is_default_group: bool
  5232. ) -> ProcessGroup:
  5233. """Create and configure the new shrunk process group."""
  5234. # Create new group properties
  5235. new_group_rank = new_backend.rank()
  5236. new_group_size = new_backend.size()
  5237. group_name = metadata["new_group_name"]
  5238. # Generate descriptive group description
  5239. if is_default_group:
  5240. group_desc = "default:shrunken"
  5241. else:
  5242. group_desc = f"{metadata['original_group_name']}:shrunk"
  5243. # Create process group with new communicator (clone the parent store like split does)
  5244. prefix_store = PrefixStore(f"{group_name}/", metadata["store"].clone())
  5245. new_pg = ProcessGroup(prefix_store, new_group_rank, new_group_size)
  5246. # Configure backend using the device type of the new backend's bound device if available,
  5247. # otherwise derive from the original group's bound device or fall back to CPU.
  5248. backend_device = metadata.get("bound_device_id")
  5249. if backend_device is None:
  5250. # Default to CPU if no bound device is present
  5251. backend_device = torch.device("cpu")
  5252. # Choose backend enum based on device type
  5253. if backend_device.type == "cuda":
  5254. backend_type = ProcessGroup.BackendType.NCCL
  5255. else:
  5256. backend_type = ProcessGroup.BackendType.GLOO
  5257. new_pg._register_backend(backend_device, backend_type, new_backend)
  5258. new_pg._set_default_backend(backend_type)
  5259. # Inherit device binding from original group if it was bound
  5260. bound_device_id = metadata.get("bound_device_id")
  5261. if bound_device_id is not None:
  5262. new_pg.bound_device_id = bound_device_id
  5263. # Set group metadata
  5264. new_pg._set_group_name(group_name)
  5265. new_pg._set_group_desc(group_desc)
  5266. # Persist backend configuration overrides (if provided via shrink_group)
  5267. backend_config_override = metadata.get("backend_config")
  5268. if backend_config_override is not None:
  5269. # Store for introspection/debugging and potential backend hooks
  5270. _world.pg_backend_config[new_pg] = backend_config_override
  5271. return new_pg
  5272. def _destroy_all_other_groups(exclude_group: ProcessGroup | None = None) -> None:
  5273. """
  5274. Destroy all process groups except the excluded group and clean up all global state.
  5275. This is necessary when shrinking the default group because global ranks
  5276. are reassigned by NCCL, making all existing process groups inconsistent.
  5277. Note: Uses abort for non-collective cleanup since excluded ranks may not
  5278. participate in collective operations. Backend cleanup is handled independently per group.
  5279. Args:
  5280. exclude_group (ProcessGroup, optional): Process group to exclude from destruction.
  5281. If None, destroys all process groups.
  5282. """
  5283. # Get list of groups to destroy (avoid modifying dict while iterating)
  5284. groups_to_destroy = []
  5285. for pg in list(_world.pg_group_ranks.keys()):
  5286. if exclude_group is not None and pg == exclude_group:
  5287. continue
  5288. groups_to_destroy.append(pg)
  5289. # Warn user about automatic destruction
  5290. if groups_to_destroy:
  5291. group_names = [_get_process_group_name(pg) for pg in groups_to_destroy]
  5292. logger.warning(
  5293. "Shrinking default group will destroy %d other process groups: %s. "
  5294. "This is necessary because shrinking the default group reassigns global ranks, "
  5295. "making existing groups inconsistent.",
  5296. len(groups_to_destroy),
  5297. ", ".join(group_names),
  5298. )
  5299. # Destroy each group and clean up global state
  5300. for pg in groups_to_destroy:
  5301. try:
  5302. # First call abort_process_group which handles the C++ cleanup non-collectively
  5303. _abort_process_group(pg)
  5304. except Exception:
  5305. # Log but don't fail - some groups might already be destroyed
  5306. logger.warning(
  5307. "Failed to abort process group %s",
  5308. _get_process_group_name(pg),
  5309. exc_info=True,
  5310. )
  5311. # Ensure all global state is cleaned up even if _abort_process_group fails
  5312. # or doesn't clean up everything
  5313. _cleanup_process_group_global_state(pg)
  5314. def _cleanup_process_group_global_state(pg: ProcessGroup) -> None:
  5315. """
  5316. Clean up all global state associated with a process group.
  5317. This function ensures complete cleanup of process group state from all
  5318. global dictionaries and registries, even if destroy_process_group fails
  5319. or doesn't clean up everything. This is critical when destroying multiple
  5320. groups to prevent inconsistent state.
  5321. The cleanup removes the process group from:
  5322. - _world.pg_map (backend and store mapping)
  5323. - _world.pg_names (group name mapping)
  5324. - _world.pg_group_ranks (rank mappings)
  5325. - _world.pg_backend_config (backend configuration)
  5326. - _world.tags_to_pg and _world.pg_to_tag (tag mappings)
  5327. - _world.pg_coalesce_state (coalescing state)
  5328. - C++ internal registries via _unregister_process_group
  5329. Args:
  5330. pg (ProcessGroup): The process group to clean up.
  5331. """
  5332. try:
  5333. # Clean up main process group mappings
  5334. _world.pg_map.pop(pg, None)
  5335. _world.pg_group_ranks.pop(pg, None)
  5336. _world.pg_backend_config.pop(pg, None)
  5337. # Clean up process group name mapping
  5338. group_name = _world.pg_names.pop(pg, None)
  5339. # Clean up tag mappings
  5340. pg_tag = _world.pg_to_tag.pop(pg, None)
  5341. if pg_tag is not None and pg_tag in _world.tags_to_pg:
  5342. try:
  5343. _world.tags_to_pg[pg_tag].remove(pg)
  5344. # Remove the tag entry if list is empty
  5345. if not _world.tags_to_pg[pg_tag]:
  5346. _world.tags_to_pg.pop(pg_tag, None)
  5347. except (ValueError, KeyError):
  5348. # Process group was already removed from the list
  5349. pass
  5350. # Clean up any registered process group names using C++ unregister function
  5351. if group_name is not None:
  5352. try:
  5353. _unregister_process_group(group_name)
  5354. except Exception:
  5355. # Process group name might not be registered or already unregistered
  5356. pass
  5357. # Clean up coalesce state if present
  5358. _world.pg_coalesce_state.pop(pg, None)
  5359. except Exception:
  5360. # Log cleanup failures but don't propagate - we want to continue with other cleanups
  5361. logger.warning(
  5362. "Failed to fully clean up global state for process group", exc_info=True
  5363. )
  5364. def _update_process_group_global_state(
  5365. pg: ProcessGroup,
  5366. backend_name: str,
  5367. store: Store,
  5368. group_name: GroupName,
  5369. backend_config: str,
  5370. rank_mapping: dict[int, int] | None = None,
  5371. pg_tag: str | None = None,
  5372. user_tag: str | None = None,
  5373. ) -> None:
  5374. """
  5375. Update all global state dictionaries for a process group.
  5376. This helper function consolidates the common pattern of updating multiple
  5377. global state dictionaries when creating or modifying process groups.
  5378. Args:
  5379. pg (ProcessGroup): The process group to update state for.
  5380. backend_name (str): Backend name for pg_map.
  5381. store (Store): Store instance for pg_map.
  5382. group_name (str): Group name for pg_names and registration.
  5383. backend_config (str): Backend configuration string.
  5384. rank_mapping (Dict[int, int], optional): Global rank to group rank mapping.
  5385. If None, skips updating pg_group_ranks.
  5386. pg_tag (str, optional): Process group tag. If None, defaults to f"ptd:{group_name}".
  5387. user_tag (str, optional): User-provided tag for special tag handling.
  5388. If provided, creates "user:{user_tag}" tag and also adds to default "".
  5389. """
  5390. # Update main process group mappings
  5391. _world.pg_map[pg] = (backend_name, store)
  5392. _world.pg_names[pg] = group_name
  5393. _world.pg_backend_config[pg] = backend_config
  5394. # Register the process group name
  5395. _register_process_group(group_name, pg)
  5396. # Update rank mapping if provided
  5397. if rank_mapping is not None:
  5398. _world.pg_group_ranks[pg] = rank_mapping
  5399. # Handle tag management
  5400. if pg_tag is None:
  5401. pg_tag = f"ptd:{group_name}"
  5402. if user_tag is not None:
  5403. # Special handling for user-provided tags
  5404. # Add to default "" tag first
  5405. _world.tags_to_pg.setdefault("", []).append(pg)
  5406. # Then create user-specific tag
  5407. user_pg_tag = f"user:{user_tag}"
  5408. _world.tags_to_pg.setdefault(user_pg_tag, []).append(pg)
  5409. _world.pg_to_tag[pg] = user_pg_tag
  5410. else:
  5411. # Standard process group tag
  5412. _world.tags_to_pg.setdefault(pg_tag, []).append(pg)
  5413. _world.pg_to_tag[pg] = pg_tag