distributed_c10d.py 242 KB

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