distributed_c10d.py 218 KB

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