scheduler.py 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719
  1. from __future__ import annotations
  2. import collections
  3. import contextlib
  4. import dataclasses
  5. import functools
  6. import inspect
  7. import itertools
  8. import logging
  9. import math
  10. import operator
  11. import os
  12. import pprint
  13. import textwrap
  14. import traceback
  15. import typing
  16. from collections import Counter, defaultdict
  17. from typing import Any, Callable, Generic, Optional, TYPE_CHECKING, TypeVar, Union
  18. from typing_extensions import ParamSpec, TypeAlias
  19. if TYPE_CHECKING:
  20. from collections.abc import Iterator, Sequence
  21. from types import ModuleType
  22. import sympy
  23. import torch
  24. import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
  25. import torch.utils._pytree as pytree
  26. from torch._dynamo.utils import counters, dynamo_timed
  27. from torch._inductor.codecache import LambdaFuture, PyCodeCache
  28. from torch._inductor.ir import TritonTemplateCallerBase
  29. from torch._inductor.metrics import get_metric_table, is_metric_table_enabled
  30. from torch.fx.experimental.symbolic_shapes import free_symbols
  31. from torch.utils._ordered_set import OrderedSet
  32. from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT
  33. from torch.utils._triton import has_triton
  34. from . import comms, config, config_comms, dependencies, ir, metrics
  35. from .analyze_preserves_zero_mask import can_codegen_without_upcasts
  36. from .codegen.common import BackendFeature, get_scheduling_for_device, Kernel
  37. from .comm_analysis import (
  38. estimate_nccl_collective_runtime,
  39. estimate_nccl_collective_runtime_nccl_estimator,
  40. )
  41. from .dependencies import Dep, MemoryDep, StarDep, WeakDep
  42. from .exc import GPUTooOldForTriton, TritonMissing
  43. from .fx_utils import count_flops_fx
  44. from .ir import (
  45. get_device_type,
  46. GraphPartitionSignature,
  47. MultiOutput,
  48. MultiOutputLayout,
  49. NoneLayout,
  50. )
  51. from .loop_body import LoopBody
  52. from .memory import MemoryPlanningInfoForBuffer, MemoryPlanningInfoForNode
  53. from .runtime.runtime_utils import green_text, red_text
  54. from .sizevars import SimplifyIndexing
  55. from .utils import (
  56. _unstable_customized_partition_wrapper,
  57. cache_on_self,
  58. cmp,
  59. device_need_guard,
  60. get_device_tflops,
  61. get_dtype_size,
  62. get_gpu_dram_gbps,
  63. GraphPartitionMap,
  64. IndentedBuffer,
  65. is_collective,
  66. is_cudagraph_unsafe_op,
  67. is_gpu,
  68. is_multi_outputs_template,
  69. is_output_of_multi_outputs_template,
  70. is_wait,
  71. maybe_log_cudagraph_partition,
  72. sympy_product,
  73. )
  74. from .virtualized import V
  75. log = logging.getLogger(__name__)
  76. fusion_log = torch._logging.getArtifactLogger(__name__, "fusion")
  77. loop_ordering_log = torch._logging.getArtifactLogger(__name__, "loop_ordering")
  78. compute_dependencies_log = torch._logging.getArtifactLogger(
  79. __name__, "compute_dependencies"
  80. )
  81. PartitionType: TypeAlias = list["BaseSchedulerNode"]
  82. _T = TypeVar("_T")
  83. _P = ParamSpec("_P")
  84. @dataclasses.dataclass
  85. class SchedulerBuffer:
  86. scheduler: Scheduler
  87. node: ir.Buffer
  88. defining_op: Optional[BaseSchedulerNode]
  89. users: list[NodeUser] = dataclasses.field(default_factory=list)
  90. mpi_buffer: MemoryPlanningInfoForBuffer = dataclasses.field(
  91. default_factory=MemoryPlanningInfoForBuffer
  92. )
  93. def defining_op_name(self) -> str:
  94. op = self.defining_op
  95. assert op is not None
  96. return op.get_name()
  97. def __hash__(self) -> int:
  98. return hash(self.node.name)
  99. def debug_str(self) -> str:
  100. result = IndentedBuffer()
  101. name = self.get_name()
  102. result.writeline(f"{name}: {type(self.node).__name__}")
  103. result.writeline(f"{name}.layout = {self.node.layout}")
  104. if self.get_aliases():
  105. result.writeline(f"{name}.aliases = {pformat(self.get_aliases())}")
  106. if self.get_mutations():
  107. result.writeline(f"{name}.mutations = {pformat(self.get_mutations())}")
  108. if len(self.users) <= 1:
  109. result.writeline(f"{name}.users = {self.users}")
  110. else:
  111. result.writeline(f"{name}.users = [")
  112. with result.indent(1):
  113. for user in self.users:
  114. result.writeline(f"{user},")
  115. result.writeline("]")
  116. return result.getrawvalue()
  117. def get_name(self) -> str:
  118. return self.node.get_name()
  119. def allocate(self) -> None:
  120. assert self.node is not None
  121. if not self.node.should_allocate():
  122. return
  123. if (
  124. self.node.get_inputs_that_alias_output()
  125. or self.node.get_mutation_names()
  126. or isinstance(self.node.get_output_spec(), ir.CommBufferLayout)
  127. ):
  128. V.graph.wrapper_code.codegen_allocation(self.node)
  129. return
  130. # hacky check for if V.kernel is a real kernel or NullHandler
  131. if (
  132. hasattr(V.kernel, "args")
  133. and self.get_name() in V.kernel.inplace_update_buffers
  134. ):
  135. input_buffer: Union[ir.DonatedBuffer, ir.Buffer]
  136. input_buffer_name = V.kernel.inplace_update_buffers[self.get_name()]
  137. if input_buffer_name in self.scheduler.name_to_donated_buffer:
  138. input_buffer = self.scheduler.name_to_donated_buffer[
  139. input_buffer_name
  140. ].node
  141. else:
  142. input_buffer = self.scheduler.name_to_buf[input_buffer_name].node
  143. V.graph.wrapper_code.codegen_inplace_reuse(
  144. input_buffer,
  145. self.node,
  146. )
  147. else:
  148. V.graph.wrapper_code.codegen_allocation(self.node)
  149. def can_free(self) -> bool:
  150. # There's no real allocated buffer, no need to free it
  151. assert self.node is not None
  152. if isinstance(self.node.layout, ir.NoneLayout) or is_multi_outputs_template(
  153. self.node
  154. ):
  155. return False
  156. for use in self.users:
  157. if isinstance(use.node, OutputNode):
  158. return False
  159. return True
  160. def set_users(self, users: list[NodeUser]) -> None:
  161. # deduplicate
  162. result: dict[int, NodeUser] = {}
  163. for use in users:
  164. if id(use.node) in result:
  165. result[id(use.node)] = use.merge(result[id(use.node)])
  166. else:
  167. result[id(use.node)] = use
  168. self.users = list(result.values())
  169. def get_aliases(self) -> Sequence[str]:
  170. assert self.node is not None
  171. return self.node.get_inputs_that_alias_output()
  172. def get_mutations(self) -> Sequence[str]:
  173. assert self.node is not None
  174. return self.node.get_mutation_names()
  175. def get_device(self) -> Optional[torch.device]:
  176. return self.node.get_output_spec().get_device()
  177. @dataclasses.dataclass
  178. class SchedulerDonatedBuffer(SchedulerBuffer):
  179. defining_op: Optional[BaseSchedulerNode] = None
  180. class BaseSchedulerNode:
  181. group: tuple[torch.device, tuple[tuple[sympy.Expr, ...], ...]]
  182. read_writes: dependencies.ReadWrites
  183. unmet_dependencies: OrderedSet[Dep]
  184. # .min_order and .max_order are only relevant for "grouped" nodes such as FusedSchedulerNode.
  185. # e.g. if the FusedSchedulerNode includes nodes (op_1, op_2, op_3), and op_X is X-th node
  186. # in `self.scheduler.nodes`, then for this FusedSchedulerNode, .min_order is 1 and .max_order is 3.
  187. # For non-"grouped" nodes (i.e. regular SchedulerNode),
  188. # .min_order = .max_order = X if this node is X-th node in `self.scheduler.nodes`.
  189. min_order: int
  190. max_order: int
  191. mpi_node: MemoryPlanningInfoForNode
  192. override_estimated_runtime: Optional[float] = None
  193. def __init__(self, scheduler: Scheduler) -> None:
  194. self.scheduler: Scheduler = scheduler
  195. self.debug_device_str: Callable[[BaseSchedulerNode], list[str]] = (
  196. lambda *args, **kwargs: []
  197. )
  198. def _init_from_node(self, node: ir.Operation) -> None:
  199. self.node: Optional[ir.Operation] = node
  200. self.ancestors: OrderedSet[str] = OrderedSet()
  201. self.last_usage = OrderedSet[
  202. str
  203. ]() # buffers that won't be used after this kernel
  204. self.written = False
  205. self.outputs: list[SchedulerBuffer] = [
  206. SchedulerBuffer(
  207. scheduler=self.scheduler,
  208. node=output,
  209. defining_op=self,
  210. )
  211. for output in node.get_outputs()
  212. ]
  213. self.outputs_by_name: dict[str, SchedulerBuffer] = {
  214. buf.get_name(): buf for buf in self.outputs
  215. }
  216. # mutation_renames for the current node. Due to potential
  217. # more mutations happening later, this can be different
  218. # to Scheduler.mutation_renames. Also this dict should be small
  219. # since only mutation information relevant to the deps for this
  220. # node is stored here.
  221. self.mutation_renames: dict[str, str] = {}
  222. def __repr__(self) -> str:
  223. return f"{type(self).__name__}(name={self.get_name()!r})"
  224. def debug_str(self) -> str:
  225. """Longer form printout for trace logs"""
  226. name = self.get_name()
  227. buf = IndentedBuffer()
  228. buf.splice(
  229. f"""\
  230. {name}: {type(self).__name__}({type(getattr(self, "node", None)).__name__})
  231. {name}.writes = {pformat(self.read_writes.writes)}
  232. {name}.unmet_dependencies = {pformat(self.unmet_dependencies)}
  233. {name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)}
  234. {name}.outputs = [
  235. """
  236. )
  237. with buf.indent():
  238. for out in self.get_outputs():
  239. buf.splice(out.debug_str())
  240. buf.writeline("]")
  241. try:
  242. buf.splice(self.debug_str_extra())
  243. except Exception:
  244. log.warning("Ignoring error in debug_str()", exc_info=True)
  245. return buf.getrawvalue().rstrip()
  246. def debug_str_extra(self) -> str:
  247. return ""
  248. def _debug_str_for_device(self) -> list[str]:
  249. return self.debug_device_str(self)
  250. def debug_str_short(self) -> str:
  251. maybe_data = getattr(self.node, "data", None)
  252. data_str = ""
  253. if isinstance(maybe_data, torch._inductor.ir.Pointwise):
  254. data_str = ", " + maybe_data.str_helper(
  255. [maybe_data.get_size()], shorten=False, multiline=False
  256. )
  257. elif isinstance(maybe_data, torch._inductor.ir.Reduction):
  258. data_str = ", " + maybe_data.str_helper(
  259. [maybe_data.get_reduction_size(), maybe_data.get_reduction_type()],
  260. shorten=False,
  261. multiline=False,
  262. )
  263. return f"{self}{data_str}"
  264. def log_details(self) -> None:
  265. log.info(
  266. "%s: unmet_dependencies = %s, writes = %s",
  267. self,
  268. self.unmet_dependencies,
  269. self.read_writes.writes,
  270. )
  271. def reorder_loops_by_dep_pair(
  272. self, self_dep: MemoryDep, other_dep: MemoryDep
  273. ) -> bool:
  274. return False
  275. def update_mutated_names(self, renames: dict[str, str]) -> None:
  276. self.mutation_renames = {
  277. name: renames[name]
  278. for name in (dep.name for dep in self.read_writes.reads_and_writes())
  279. if name in renames
  280. }
  281. self.set_read_writes(self.read_writes.rename(self.mutation_renames))
  282. def add_fake_dep(self, dep: Dep) -> None:
  283. self.set_read_writes(self.read_writes.with_read(dep))
  284. def has_aliasing_or_mutation(self) -> bool:
  285. return any(
  286. buf.get_aliases() or buf.get_mutations() for buf in self.get_outputs()
  287. )
  288. def set_read_writes(self, rw: dependencies.ReadWrites) -> None:
  289. self.read_writes = rw
  290. self.unmet_dependencies = self.read_writes.reads
  291. self.prune_deps()
  292. def set_last_usage(
  293. self, future_used_buffers: OrderedSet[str], mutation_real_name: dict[str, str]
  294. ) -> None:
  295. used_buffers = self.used_or_aliased_buffer_names()
  296. used_buffers = OrderedSet(mutation_real_name.get(k, k) for k in used_buffers)
  297. self.last_usage = used_buffers - future_used_buffers
  298. def mark_run(self) -> None:
  299. for buf in self.outputs:
  300. buf.allocate()
  301. def used_buffer_names(self) -> OrderedSet[str]:
  302. return OrderedSet(
  303. dep.name
  304. for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes)
  305. )
  306. def used_or_aliased_buffer_names(self) -> OrderedSet[str]:
  307. used_names: OrderedSet[str] = OrderedSet()
  308. deps = [
  309. dep.name
  310. for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes)
  311. ]
  312. while len(deps) > 0:
  313. dep = deps.pop()
  314. used_names.add(dep)
  315. if V.graph.name_to_buffer.get(dep):
  316. deps.extend(
  317. alias
  318. for alias in V.graph.name_to_buffer[
  319. dep
  320. ].get_inputs_that_alias_output()
  321. if alias not in used_names
  322. )
  323. return used_names
  324. def prune_deps(self) -> None:
  325. self.unmet_dependencies = OrderedSet(
  326. dep
  327. for dep in self.unmet_dependencies
  328. if dep.name not in self.scheduler.available_buffer_names
  329. )
  330. def prune_weak_deps(self) -> None:
  331. # Prune weak dependencies on operations that have been removed
  332. def should_prune(dep: Dep) -> bool:
  333. if not isinstance(dep, WeakDep):
  334. return False
  335. op_name = self.scheduler.name_to_buf[dep.name].defining_op_name()
  336. return op_name in V.graph.removed_operations
  337. to_remove = OrderedSet(
  338. dep for dep in self.read_writes.reads if should_prune(dep)
  339. )
  340. self.set_read_writes(self.read_writes.remove_reads(to_remove))
  341. def prune_redundant_deps(
  342. self, name_to_fused_node: dict[str, BaseSchedulerNode]
  343. ) -> None:
  344. _prune_redundant_deps(self, name_to_fused_node, self.scheduler.name_to_buf)
  345. def get_name(self) -> str:
  346. assert self.node is not None
  347. return self.node.get_operation_name()
  348. def get_first_name(self) -> str:
  349. return self.get_name()
  350. @cache_on_self
  351. def get_operation_names(self) -> OrderedSet[str]:
  352. return OrderedSet(node.get_name() for node in self.get_nodes())
  353. @cache_on_self
  354. def get_buffer_names(self) -> OrderedSet[str]:
  355. return OrderedSet(out.get_name() for out in self.outputs)
  356. @cache_on_self
  357. def can_codegen_in_low_precision(self) -> bool:
  358. return all(
  359. isinstance(n, SchedulerNode)
  360. and can_codegen_without_upcasts(n, disallow_fp32_ops=True)
  361. for n in self.get_nodes()
  362. )
  363. @cache_on_self
  364. def can_codegen_without_upcasts(self) -> bool:
  365. return all(
  366. isinstance(n, SchedulerNode) and can_codegen_without_upcasts(n)
  367. for n in self.get_nodes()
  368. )
  369. def get_nodes(self) -> Sequence[BaseSchedulerNode]:
  370. return [self]
  371. def get_outputs(self) -> Sequence[SchedulerBuffer]:
  372. return self.outputs
  373. def get_output(self, buf_name: str) -> SchedulerBuffer:
  374. return self.outputs_by_name[buf_name]
  375. def get_device(self) -> Optional[torch.device]:
  376. assert self.node is not None
  377. return self.node.get_device()
  378. def is_cpu(self) -> bool:
  379. device = self.get_device()
  380. return device is not None and device.type == "cpu"
  381. def is_gpu(self) -> bool:
  382. device = self.get_device()
  383. return device is not None and is_gpu(device.type)
  384. def is_reduction(self) -> bool:
  385. return False
  386. def is_split_scan(self) -> bool:
  387. return False
  388. def is_template(self) -> bool:
  389. return False
  390. def is_extern(self) -> bool:
  391. return False
  392. def is_foreach(self) -> bool:
  393. return False
  394. def can_inplace(self, read_dep: dependencies.Dep) -> bool:
  395. return False
  396. def has_side_effects(self) -> bool:
  397. return False
  398. def decide_inplace_update(self) -> None:
  399. """
  400. Decide if there should be inplace updates for the node
  401. and record the decision in the active kernel.
  402. """
  403. from .codegen.wrapper import can_match_buffer_size
  404. if not (
  405. isinstance(self, SchedulerNode)
  406. and config.inplace_buffers
  407. and V.graph.has_feature(self.get_device(), BackendFeature.INPLACE_BUFFERS)
  408. and (
  409. not isinstance(V.kernel, torch._inductor.codegen.simd.SIMDKernel)
  410. or getattr(V.kernel, "mutations", None) is not None
  411. )
  412. # hacky check for if V.kernel is a real kernel or NullHandler
  413. and hasattr(V.kernel, "args")
  414. ):
  415. return
  416. # NOTE remove V.graph.removed_operations once deps issue is fixed
  417. inconsequential_nodes = (
  418. self.ancestors
  419. | V.graph.removed_operations
  420. | self.scheduler.completed_operations
  421. )
  422. def single_index_in_fused_node(buf_to_be_inplaced: SchedulerBuffer) -> bool:
  423. # Inside of NodeUser, we track that the read and write are equivalent
  424. # before deciding if the use can be inplace.
  425. # But if that use is fused into a larger kernel, we need to check equivalence
  426. # of other accesses in fused scheduler node as well.
  427. fused_node = buf_to_be_inplaced.scheduler.get_fused_node(self)
  428. buf_name = buf_to_be_inplaced.get_name()
  429. # Dedup read/writes with equivalent indices
  430. # TODO - would be nice if we could just cache accesses on ReadWrites,
  431. # and enforce variant that this class & members are functional..
  432. deps: OrderedSet[Dep] = OrderedSet()
  433. for user in buf_to_be_inplaced.users:
  434. user_node = user.node
  435. if not isinstance(user_node, BaseSchedulerNode):
  436. continue
  437. if (
  438. user_node.get_first_name()
  439. not in buf_to_be_inplaced.scheduler.name_to_fused_node
  440. or buf_to_be_inplaced.scheduler.get_fused_node(user_node)
  441. is not fused_node
  442. ):
  443. continue
  444. deps |= (
  445. o
  446. for o in user_node.read_writes.reads_and_writes()
  447. if o.name == buf_name
  448. )
  449. if len(deps) > 1:
  450. return False
  451. return True
  452. for buf in self.get_outputs():
  453. buf_node = buf.node
  454. assert buf_node is not None
  455. if (
  456. not buf_node.should_allocate()
  457. or buf_node.get_inputs_that_alias_output()
  458. or buf_node.get_mutation_names()
  459. or buf.get_name() in V.graph.removed_buffers
  460. ):
  461. continue
  462. for read in self.read_writes.reads:
  463. input_buf: Optional[Union[SchedulerBuffer, SchedulerDonatedBuffer]]
  464. if read.name in self.scheduler.name_to_donated_buffer:
  465. input_buf = self.scheduler.name_to_donated_buffer[read.name]
  466. else:
  467. input_buf = self.scheduler.name_to_buf.get(read.name)
  468. if (
  469. input_buf
  470. and V.graph.wrapper_code.can_reuse(input_buf, self)
  471. and not isinstance(input_buf.defining_op, NopKernelSchedulerNode)
  472. ):
  473. assert input_buf.users is not None
  474. remaining_uses = [
  475. x
  476. for x in input_buf.users
  477. if x.node.get_name() not in inconsequential_nodes
  478. ]
  479. if (
  480. len(remaining_uses) == 1
  481. and remaining_uses[0].can_inplace
  482. and remaining_uses[0].node is self
  483. and input_buf.node is not None
  484. and not isinstance(
  485. input_buf.node.get_output_spec(),
  486. (
  487. ir.NoneLayout,
  488. ir.MultiOutputLayout,
  489. ir.MutationLayoutSHOULDREMOVE,
  490. ),
  491. )
  492. and not (
  493. input_buf.defining_op
  494. and isinstance(
  495. input_buf.defining_op.node,
  496. (ir.FallbackKernel, ir.MultiOutput),
  497. )
  498. and len(input_buf.node.get_inputs_that_alias_output()) > 0
  499. )
  500. and can_match_buffer_size(input_buf.node, buf.node)
  501. and single_index_in_fused_node(input_buf)
  502. ):
  503. # if there isn't a triton kernel, then we don't need to call triton-specific things.
  504. # but TODO this might be a convenient place to signal to the Collective kernels to inplace
  505. # (and, can we make "kernel" less generic of a name?)
  506. V.kernel.args.make_inplace(input_buf.get_name(), buf.get_name())
  507. # mutations not tracked in cpp kernels
  508. if isinstance(
  509. V.kernel, torch._inductor.codegen.simd.SIMDKernel
  510. ):
  511. V.kernel.mutations.add(input_buf.get_name())
  512. V.kernel.mutations.add(buf.get_name())
  513. V.kernel.inplace_update_buffers[buf.get_name()] = (
  514. input_buf.get_name()
  515. )
  516. break
  517. def codegen_originating_info(
  518. self, buffer: IndentedBuffer, only_once: bool = True
  519. ) -> None:
  520. if not config.comment_origin:
  521. return
  522. if only_once and self.written:
  523. return
  524. assert self.node is not None
  525. origins = self.node.get_origins()
  526. out_lines = []
  527. for o in origins:
  528. if o.op == "output":
  529. # These are boring and samey
  530. continue
  531. out_lines.append("")
  532. # TODO(voz): Should the pragma be constant somewhere?
  533. out_lines.append("#pragma CMT ORIGIN:")
  534. op_info_str = f"#pragma CMT {o.op} {o.target}"
  535. if "seq_nr" in o.meta:
  536. op_info_str = op_info_str + f" seq_nr:{o.meta['seq_nr']}"
  537. out_lines.append(op_info_str)
  538. if "stack_trace" in o.meta:
  539. stack_trace = f"{o.meta['stack_trace']}"
  540. stack_trace_last_line = stack_trace.rsplit("|", maxsplit=1)[-1]
  541. out_lines.append(
  542. "#pragma CMT "
  543. + stack_trace_last_line.replace("{", "{{")
  544. .replace("}", "}}")
  545. .replace("\n", "\\")
  546. .replace(
  547. "\\", "\\\\"
  548. ) # For windows safe path, avoid for example \x, \U.
  549. )
  550. out_lines.append("#pragma CMT END ORIGIN")
  551. out_lines.append("")
  552. if len(out_lines) == 0:
  553. return
  554. # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does
  555. # not use BracesBuffer, so we have no good indicator of a C++ buffer atm.
  556. buffer.writelines(out_lines)
  557. self.written = True
  558. @cache_on_self
  559. def get_read_write_buffers_sizes(self) -> int:
  560. return self.get_read_write_buffers_sizes_impl(
  561. include_reads=True, include_writes=True
  562. )
  563. @cache_on_self
  564. def get_read_buffer_sizes(self) -> int:
  565. return self.get_read_write_buffers_sizes_impl(
  566. include_reads=True, include_writes=False
  567. )
  568. @cache_on_self
  569. def get_write_buffer_sizes(self) -> int:
  570. return self.get_read_write_buffers_sizes_impl(
  571. include_reads=False, include_writes=True
  572. )
  573. def get_read_write_buffers_sizes_impl(
  574. self, include_reads: bool, include_writes: bool
  575. ) -> int:
  576. return sum(
  577. self.get_read_write_buffer_accesses(
  578. include_reads=include_reads, include_writes=include_writes
  579. ).values(),
  580. start=0,
  581. )
  582. def get_read_write_buffer_accesses(
  583. self, include_reads: bool, include_writes: bool
  584. ) -> dict[str, int]:
  585. """
  586. Counting the number of bytes accessed for a kernel is
  587. surprisingly tricky. In particular, there is a differentiation
  588. between 'theoretical' memory accesses and practical memory
  589. accesses. For example, a layernorm kernel may actually access an
  590. input 3 times, but in theory, it only needs to access its input
  591. once (and may be optimized to do so through say, persistent
  592. reductions)
  593. Another example is that even though a buffer is passed in, we may
  594. not access the entire buffer. This may occur if we are accessing
  595. a slice of the buffer. Another tricky case is for indirect
  596. indexing, where the amount of bytes accessed depends on the
  597. values of the input.
  598. What this function aims to compute is the memory accesses for
  599. worst-case inputs, best-case optimization. What this means is
  600. that for each buffer we compute the amount of potential accesses in two ways and take the minimum.
  601. 1. Numel in ranges multiplied by number of deps the buffer has
  602. 2. The buffer size
  603. Returns memory accesses per buffer.
  604. """
  605. if isinstance(self, NopKernelSchedulerNode):
  606. return {}
  607. if isinstance(self, ExternKernelSchedulerNode) and isinstance(
  608. self.node, MultiOutput
  609. ):
  610. # todo: Calculate this - it's kinda annoying.
  611. return {}
  612. if (
  613. isinstance(self, ExternKernelSchedulerNode)
  614. and isinstance(self.node, ir.FallbackKernel)
  615. and self.node.op_overload
  616. is torch._prims.rng_prims.graphsafe_run_with_rng_state
  617. ):
  618. return {}
  619. def try_size_hint(s: sympy.Expr) -> int:
  620. return V.graph.sizevars.size_hint(s, fallback=0)
  621. if isinstance(self, SchedulerNode):
  622. node_numel = try_size_hint(
  623. sympy_product(self.get_ranges()[0])
  624. * sympy_product(self.get_ranges()[1]),
  625. )
  626. else:
  627. node_numel = int(1e9)
  628. buf_accesses = collections.defaultdict(list)
  629. if include_reads:
  630. for dep in self.read_writes.reads:
  631. buf_accesses[dep.name].append(dep)
  632. if include_writes:
  633. for dep in self.read_writes.writes:
  634. buf_accesses[dep.name].append(dep)
  635. reads = (
  636. OrderedSet(dep.name for dep in self.read_writes.reads)
  637. if include_reads
  638. else OrderedSet()
  639. )
  640. writes = (
  641. OrderedSet(dep.name for dep in self.read_writes.writes)
  642. if include_writes
  643. else OrderedSet()
  644. )
  645. def is_materialized(buf: str, snodes: Sequence[BaseSchedulerNode]) -> bool:
  646. users = self.scheduler.name_to_buf[buf].users
  647. buf_uses = OrderedSet(user.node for user in users)
  648. return len(buf_uses - OrderedSet(snodes)) > 0
  649. if isinstance(self, FusedSchedulerNode):
  650. removed_buffers = OrderedSet(
  651. dep for dep in writes if not is_materialized(dep, self.snodes)
  652. )
  653. writes = writes - removed_buffers
  654. reads = reads - removed_buffers
  655. buf_byte_accesses: dict[str, int] = {}
  656. for buf_name in reads | writes:
  657. buf_accessed_elems = sum(node_numel for dep in buf_accesses[buf_name])
  658. buf: Union[ir.Buffer, ir.TensorBox, ir.TorchBindObject]
  659. if buf_name in V.graph.name_to_buffer:
  660. buf = V.graph.name_to_buffer[buf_name]
  661. elif buf_name in V.graph.graph_inputs:
  662. buf = V.graph.graph_inputs[buf_name]
  663. else:
  664. continue
  665. def get_buf_bytes(
  666. buf: Optional[Union[ir.Buffer, ir.TensorBox, ir.TorchBindObject]],
  667. ) -> int:
  668. if not buf:
  669. return 0
  670. if isinstance(buf, ir.TorchBindObject):
  671. return buf.get_buf_bytes()
  672. elif isinstance(buf.layout, MultiOutputLayout):
  673. # Kind of a lazy way to get the MultiOutput nodes corresponding to
  674. # a MultiOutputLayout
  675. users = self.scheduler.name_to_buf[buf.get_name()].users
  676. tot = 0
  677. for user in users:
  678. assert isinstance(user.node, BaseSchedulerNode)
  679. if isinstance(user.node.node, MultiOutput):
  680. for sched_buf in user.node.get_outputs():
  681. tot += get_buf_bytes(sched_buf.node)
  682. else:
  683. # Buf is a MultiOutputLayout but not all of its
  684. # users are MultiOutputs...
  685. # TODO: Figure out what's going on
  686. return 0
  687. return tot
  688. elif isinstance(buf.layout, ir.NoneLayout):
  689. return sum(
  690. get_buf_bytes(V.graph.get_buffer(mut_name))
  691. for mut_name in buf.get_mutation_names()
  692. )
  693. else:
  694. buf_elems = try_size_hint(sympy_product(buf.get_size()))
  695. return get_dtype_size(buf.get_dtype()) * min(
  696. buf_accessed_elems, buf_elems
  697. )
  698. buf_bytes = get_buf_bytes(buf)
  699. if buf_name not in buf_byte_accesses:
  700. buf_byte_accesses[buf_name] = buf_bytes
  701. else:
  702. buf_byte_accesses[buf_name] += buf_bytes
  703. return buf_byte_accesses
  704. @cache_on_self
  705. def estimate_flops(self) -> int | None:
  706. if self.node is None:
  707. return None
  708. fx_node = self.node.get_origin_node()
  709. if fx_node is None:
  710. return None
  711. flops = count_flops_fx(fx_node)
  712. if flops is None:
  713. return None
  714. resolved_flops = V.graph.sizevars.size_hint(flops, fallback=0)
  715. counters["inductor"]["flop_count"] += resolved_flops
  716. return resolved_flops
  717. def get_estimated_runtime(self) -> float:
  718. if self.override_estimated_runtime is not None:
  719. return self.override_estimated_runtime
  720. return self._get_estimated_runtime()
  721. @cache_on_self
  722. def _get_estimated_runtime(self) -> float:
  723. """
  724. Returns estimated op runtime in milliseconds (ms)
  725. """
  726. buf = self.get_nodes()[0].get_outputs()[0]
  727. layout = buf.node.get_output_spec()
  728. if not is_gpu(get_device_type(layout)):
  729. # default to no reordering based on runtime
  730. return 0
  731. # Collective kernels
  732. if is_collective(self.node):
  733. assert isinstance(self.node, ir.IRNode)
  734. try:
  735. if config_comms.runtime_estimations_use_nccl_lib_estimations:
  736. cache_key = get_estimate_runtime_cache_key_from_snode(self)
  737. cache = get_estimate_runtime_cache()
  738. cache_val = cache.lookup(cache_key)
  739. if cache_val is not None:
  740. assert isinstance(cache_val, float)
  741. return cache_val
  742. ms = estimate_nccl_collective_runtime_nccl_estimator(self)
  743. if ms is None:
  744. # NCCL estimations fail: fallback to in-tree algorithmic estimation.
  745. ms = estimate_nccl_collective_runtime(self.node)
  746. cache.set_value(cache_key, value=ms)
  747. return ms
  748. return estimate_nccl_collective_runtime(self.node)
  749. except ValueError as e:
  750. # We don't know how to estimate runtime for this collective,
  751. # falling back to 0
  752. log.info(e)
  753. return 0
  754. except TypeError as e:
  755. # this happens when the collective is not of type ir._CollectiveKernel
  756. log.info(e)
  757. return 0
  758. elif is_wait(self.node):
  759. # ir.Wait is only used for collective ops.
  760. # The time needed for the collective op is already estimated and considered
  761. # when we are processing the collective op IR node, so ir.Wait takes 0 time
  762. # since it doesn't take extra time to get the result after the collective is completed.
  763. return 0
  764. ret = maybe_estimate_runtime_benchmark(self)
  765. if ret is not None:
  766. return ret
  767. dtype = buf.node.maybe_get_dtype()
  768. try:
  769. gpu_memory_bandwidth = get_gpu_dram_gbps()
  770. gpu_flops = get_device_tflops(dtype) * 10**12
  771. # If cudaGetDeviceProperties returns 0 for gpu_memory_bandwidth or gpu_flops
  772. # there is a chance to continue execution successfully. Otherwise, it would fail with
  773. # ZeroDivisionError below.
  774. if gpu_memory_bandwidth <= 0:
  775. raise AssertionError(
  776. f"gpu_memory_bandwidth cannot be <= 0, but got {gpu_memory_bandwidth}"
  777. )
  778. if gpu_flops <= 0:
  779. raise AssertionError(f"gpu_flops cannot be <= 0, but got {gpu_flops}")
  780. except Exception:
  781. return 0
  782. flops_est = self.estimate_flops()
  783. if flops_est == 0 or flops_est is None:
  784. # no flops estimate, so fall back to memory estimate
  785. ns = self.get_read_write_buffers_sizes() / gpu_memory_bandwidth
  786. ms = ns / 1e6
  787. return ms
  788. # TODO(xmfan): find a better heuristic to model FLOPS/latency relationship
  789. factor = 1.0
  790. counted_bytes = self.get_read_write_buffers_sizes()
  791. counted_bytes = 0 if counted_bytes is None else counted_bytes
  792. compute_time = (factor * flops_est / gpu_flops) * 1e9
  793. transfer_time = counted_bytes / gpu_memory_bandwidth
  794. # Return estimated runtime in milliseconds
  795. ns = max(compute_time, transfer_time)
  796. ms = ns / 1e6
  797. return ms
  798. def get_template_node(self) -> Optional[ir.TemplateBuffer]:
  799. return None
  800. def get_template_node_or_throw(self) -> ir.TemplateBuffer:
  801. template = self.get_template_node()
  802. assert template is not None
  803. return template
  804. @staticmethod
  805. def get_prologue_template_epilogue(
  806. nodes: list[BaseSchedulerNode],
  807. ) -> tuple[list[BaseSchedulerNode], BaseSchedulerNode, list[BaseSchedulerNode]]:
  808. """
  809. For the list of nodes, get the prologue, template, and epilogue
  810. """
  811. template_index = next(i for i, n in enumerate(nodes) if n.is_template())
  812. prologue = nodes[:template_index]
  813. template_node = nodes[template_index]
  814. epilogue = nodes[template_index + 1 :]
  815. return prologue, template_node, epilogue
  816. @functools.cache
  817. def get_estimate_runtime_cache() -> torch._inductor.codecache.LocalCache:
  818. return torch._inductor.codecache.LocalCache()
  819. def get_estimate_runtime_cache_key_from_snode(snode: BaseSchedulerNode) -> str:
  820. python_kernel_name = getattr(snode.node, "python_kernel_name", "")
  821. args = snode.node.inputs # type: ignore[union-attr]
  822. args = snode.node.fill_non_provided_args( # type: ignore[union-attr]
  823. [*args, *snode.node.constant_args], # type: ignore[union-attr]
  824. snode.node.kwargs, # type: ignore[union-attr]
  825. )
  826. kwargs = snode.node.kwargs # type: ignore[union-attr]
  827. flat_args, flat_args_pytree_spec = pytree.tree_flatten((args, kwargs))
  828. def _is_tensor_ir(x) -> bool: # type: ignore[no-untyped-def]
  829. return isinstance(x, ir.IRNode) and not isinstance(x, ir.GeneratorState)
  830. cache_key = str(
  831. (python_kernel_name,)
  832. + tuple(tuple(a.get_size()) if _is_tensor_ir(a) else None for a in flat_args)
  833. )
  834. return cache_key
  835. def _get_mm_like_fn(snode: BaseSchedulerNode) -> Optional[Callable[[Any], Any]]:
  836. if not isinstance(snode, ExternKernelSchedulerNode):
  837. return None
  838. mms_fns = {
  839. "extern_kernels.mm": torch.ops.aten.mm,
  840. "extern_kernels.bmm": torch.ops.aten.bmm,
  841. "extern_kernels.addmm": torch.ops.aten.addmm,
  842. }
  843. python_kernel_name = getattr(snode.node, "python_kernel_name", "")
  844. if python_kernel_name not in mms_fns:
  845. return None
  846. if not isinstance(snode.node, ir.ExternKernel):
  847. return None
  848. return mms_fns[python_kernel_name]
  849. def maybe_estimate_runtime_benchmark(snode: BaseSchedulerNode) -> Optional[float]:
  850. bench_fn = None
  851. args_kwargs_fn = None
  852. if config.runtime_estimations_mms_benchmark:
  853. mm_fn = _get_mm_like_fn(snode)
  854. if mm_fn is None:
  855. return None
  856. bench_fn = mm_fn
  857. args_kwargs_fn = lambda: snode_args_kwargs(snode) # noqa: E731
  858. else:
  859. return None
  860. cache_key = get_estimate_runtime_cache_key_from_snode(snode)
  861. cache = get_estimate_runtime_cache()
  862. cache_val = cache.lookup(cache_key)
  863. if cache_val is not None:
  864. assert isinstance(cache_val, float)
  865. return cache_val
  866. from .utils import snode_args_kwargs
  867. args, kwargs = args_kwargs_fn()
  868. from triton.testing import do_bench
  869. ms = do_bench(lambda: bench_fn(*args, **kwargs))
  870. cache.set_value(cache_key, value=ms)
  871. return ms
  872. class WhyNoFuse:
  873. # TODO when we drop support for Python < 3.10, we can use
  874. # @dataclass(slots=True) instead of manually specifying __slots__.
  875. __slots__ = ["name1", "name2", "reason", "args"]
  876. reason: str
  877. args: tuple[Any, ...]
  878. def __init__(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> None:
  879. self.name1 = node1.get_name()
  880. self.name2 = node2.get_name()
  881. def __call__(self, reason: str, *args: Any) -> None:
  882. self.reason = reason
  883. self.args = args
  884. fusion_log.debug(self)
  885. def __str__(self) -> str:
  886. return f"cannot fuse {self.name1} with {self.name2}: " + (
  887. self.reason % self.args
  888. )
  889. def pformat(obj: Any) -> str:
  890. if isinstance(obj, (OrderedSet, set)): # noqa: set_linter
  891. # pformat has trouble with sets of sympy exprs
  892. obj = sorted(obj, key=str)
  893. result = pprint.pformat(obj, indent=4)
  894. if "\n" in result:
  895. return f"\n{textwrap.indent(result, ' ' * 4)}"
  896. return result
  897. class OutputNode:
  898. def __init__(self, dep: StarDep) -> None:
  899. self.unmet_dependencies = OrderedSet([dep])
  900. def is_reduction(self) -> bool:
  901. return False
  902. def get_inputs_that_alias_output(self) -> Sequence[str]:
  903. return ()
  904. def get_name(self) -> str:
  905. return "OUTPUT"
  906. __repr__ = get_name
  907. def _prune_redundant_deps(
  908. node: BaseSchedulerNode,
  909. name_to_fused_node: dict[str, BaseSchedulerNode],
  910. name_to_buf: dict[str, SchedulerBuffer],
  911. ) -> None:
  912. """
  913. Prunes weakdeps intended for mutation ordering
  914. on an upstream fused node if after fusion there is another dependency
  915. on the fused upstream node, making the weakdep redundant
  916. In essence this enforces an ordering on fusions. As fusions occur, weakdeps will
  917. be incrementally removed, enabling other fusions, ensuring they are fused in order.
  918. """
  919. name_to_dep_count: Counter[str] = collections.Counter()
  920. for dep in node.unmet_dependencies:
  921. if not isinstance(dep, WeakDep):
  922. op_name = name_to_buf[dep.name].defining_op_name()
  923. name_to_dep_count[name_to_fused_node[op_name].get_name()] += 1
  924. def should_prune(dep: Dep) -> bool:
  925. if isinstance(dep, WeakDep):
  926. op_name = name_to_buf[dep.name].defining_op_name()
  927. is_redundant = name_to_dep_count[name_to_fused_node[op_name].get_name()] > 0
  928. # These can occur because fused nodes always gather deps from their snodes
  929. # If B has a weakdep on A
  930. # B gets fused with C, then any time BC is fused, the weakdep will reappear
  931. is_self_dep = name_to_fused_node[op_name] == node
  932. return is_redundant or is_self_dep
  933. else:
  934. return False
  935. deps_to_prune = OrderedSet(
  936. dep for dep in node.unmet_dependencies if should_prune(dep)
  937. )
  938. if deps_to_prune:
  939. node.unmet_dependencies = node.unmet_dependencies - deps_to_prune
  940. node.set_read_writes(node.read_writes.remove_reads(deps_to_prune))
  941. class ExternKernelSchedulerNode(BaseSchedulerNode):
  942. def __init__(self, scheduler: Scheduler, node: ir.Operation) -> None:
  943. super().__init__(scheduler)
  944. self._init_from_node(node)
  945. self.set_read_writes(node.get_read_writes())
  946. def debug_str_extra(self) -> str:
  947. return f"{self.get_name()}.node.kernel = {getattr(self.node, 'python_kernel_name', None)}"
  948. def is_extern(self) -> bool:
  949. return True
  950. def has_side_effects(self) -> bool:
  951. assert self.node is not None
  952. return hasattr(self.node, "has_side_effects") and self.node.has_side_effects()
  953. class NopKernelSchedulerNode(BaseSchedulerNode):
  954. def __init__(self, scheduler: Scheduler, node: ir.Operation) -> None:
  955. super().__init__(scheduler)
  956. self._init_from_node(node)
  957. self.set_read_writes(node.get_read_writes())
  958. class SchedulerNode(BaseSchedulerNode):
  959. """
  960. A SchedulerNode is a node for scheduling that encapsulates either
  961. a ComputedBuffer or a TemplateBuffer.
  962. """
  963. _sizes: tuple[Sequence[sympy.Expr], ...]
  964. _body: LoopBody
  965. def __init__(
  966. self,
  967. scheduler: Scheduler,
  968. node: Union[ir.ComputedBuffer, ir.TemplateBuffer],
  969. ) -> None:
  970. super().__init__(scheduler)
  971. self._init_from_node(node)
  972. self._compute_attrs()
  973. def _compute_attrs(
  974. self,
  975. extra_indexing_constraints: Optional[tuple[dict[Any, Any], list[Any]]] = None,
  976. recompute_sizes_body_func: Optional[Callable[_P, _T]] = None,
  977. ) -> None:
  978. assert isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer))
  979. self._sizes, body = self.node.simplify_and_reorder(
  980. extra_indexing_constraints=extra_indexing_constraints,
  981. recompute_sizes_body_func=recompute_sizes_body_func,
  982. )
  983. self._body = body # type: ignore[assignment]
  984. device = self.node.get_device_or_error()
  985. group_fn = self.scheduler.get_backend(device).group_fn
  986. self.group = (device, group_fn(self._sizes))
  987. # Don't normalize since normalization will merge loops which
  988. # makes it hard to decide new loop orders.
  989. should_normalize = not config.loop_ordering_after_fusion or not is_gpu(
  990. device.type
  991. )
  992. if isinstance(self.node, ir.TemplateBuffer):
  993. self.set_read_writes(
  994. self.node.extract_read_writes(normalize=should_normalize)
  995. )
  996. else:
  997. self.set_read_writes(
  998. dependencies.extract_read_writes(
  999. self._body, *self._sizes, normalize=should_normalize
  1000. )
  1001. )
  1002. def recompute_size_and_body(
  1003. self,
  1004. extra_indexing_constraints: Optional[tuple[dict[Any, Any], list[Any]]] = None,
  1005. recompute_sizes_body_func: Optional[Callable[..., Any]] = None,
  1006. ) -> None:
  1007. self._compute_attrs(
  1008. extra_indexing_constraints=extra_indexing_constraints,
  1009. recompute_sizes_body_func=recompute_sizes_body_func,
  1010. )
  1011. def refresh_dependencies(
  1012. self, normalize: bool, need_clear_tiling_cache: bool
  1013. ) -> None:
  1014. # Fake dependencies are added manually. They can not be analyzed from
  1015. # extract_read_writes. Find them out and apply manually.
  1016. fake_deps: OrderedSet[Dep] = OrderedSet(
  1017. dep for dep in self.read_writes.reads if isinstance(dep, (WeakDep, StarDep))
  1018. )
  1019. # don't normalize since the loop order may need to be further changed
  1020. # later
  1021. self.set_read_writes(
  1022. dependencies.extract_read_writes(
  1023. self._body, *self._sizes, normalize=normalize
  1024. )
  1025. .with_read(fake_deps)
  1026. .rename(self.mutation_renames)
  1027. )
  1028. self.pointwise_read_writes.clear_cache(self)
  1029. if need_clear_tiling_cache:
  1030. from .codegen.simd import SIMDScheduling
  1031. # TODO(shunting) if this cause compilation time increase when
  1032. # enabling LOAF by default, try just clearing the specific cache
  1033. # entry by using a customized cache implementation rather than
  1034. # lru_cache.
  1035. SIMDScheduling.candidate_tilings.cache_clear()
  1036. def apply_new_loop_order(self, new_order: Sequence[int]) -> None:
  1037. self._body = self._body.reorder_iter_loops(
  1038. new_order,
  1039. )
  1040. self._sizes = self._body.sizes
  1041. self.refresh_dependencies(normalize=False, need_clear_tiling_cache=True)
  1042. def expand_dimension_for_pointwise_node(
  1043. self, dimension: int, new_range: int
  1044. ) -> None:
  1045. assert isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer))
  1046. self._body = self._body.expand_dimension_for_pointwise_node(
  1047. dimension, new_range
  1048. )
  1049. self._sizes = self._body.sizes
  1050. device = self.node.get_device_or_error()
  1051. group_fn = self.scheduler.get_backend(device).group_fn
  1052. self.group = (device, group_fn(self._sizes))
  1053. # Need normalize the prefix name to facilitate finding common dependencies
  1054. self.refresh_dependencies(normalize=True, need_clear_tiling_cache=True)
  1055. def merge_loops(self) -> None:
  1056. self._body = self._body.merge_loops()
  1057. self._sizes = self._body.sizes
  1058. # merge_loops is called after loop reordering.
  1059. # We still need retain fake dependencies since codegen the
  1060. # estimated amount of memory access rely on them.
  1061. #
  1062. # Merge loops does not affect the tiling decision. So we
  1063. # don't need clear the tiling cache.
  1064. self.refresh_dependencies(normalize=True, need_clear_tiling_cache=False)
  1065. def reorder_loops_by_dep_pair(
  1066. self, self_dep: MemoryDep, other_dep: MemoryDep
  1067. ) -> bool:
  1068. new_order = None
  1069. self_sizes = self._sizes[0]
  1070. if len(self_sizes) == self_dep.num_vars == other_dep.num_vars:
  1071. new_order = self_dep.decide_loop_order_to_match(other_dep)
  1072. if new_order:
  1073. metrics.num_loop_reordering += 1
  1074. loop_ordering_log.debug(
  1075. "Reorder loops for %s with order %s", self.get_name(), new_order
  1076. )
  1077. self.apply_new_loop_order(new_order)
  1078. return True
  1079. else:
  1080. loop_ordering_log.debug(
  1081. "Don't reordering %s because we can not decide the suitable loop order",
  1082. self.get_name(),
  1083. )
  1084. return False
  1085. def debug_str_extra(self) -> str:
  1086. name = self.get_name()
  1087. lines = [
  1088. f"{name}.group.device = {self.group[0]}",
  1089. f"{name}.group.iteration = {self.group[1]}",
  1090. f"{name}.sizes = {self._sizes}",
  1091. ]
  1092. for dep in self.read_writes.reads_and_writes():
  1093. if not isinstance(dep, WeakDep):
  1094. buf_name = dep.name
  1095. buf = V.graph.get_buffer(buf_name)
  1096. if not isinstance(buf, ir.TorchBindObject):
  1097. lines.append(f"{buf_name}_layout = {pformat(buf.layout)}")
  1098. if isinstance(self._body, LoopBody):
  1099. lines.append(f"class {name}_loop_body:")
  1100. lines.append(textwrap.indent(self._body.debug_str(), " "))
  1101. assert self.node is not None
  1102. lines.extend(self._debug_str_for_device())
  1103. return "\n".join(lines)
  1104. def get_ranges(self) -> Sequence[Sequence[sympy.Expr]]:
  1105. return self._sizes
  1106. def is_reduction(self) -> bool:
  1107. assert isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)), (
  1108. f"{type(self.node)=}"
  1109. )
  1110. return bool(self.node.get_reduction_type())
  1111. def is_split_scan(self) -> bool:
  1112. assert isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)), (
  1113. f"{type(self.node)=}"
  1114. )
  1115. return isinstance(self.node, ir.ComputedBuffer) and isinstance(
  1116. self.node.data, ir.SplitScan
  1117. )
  1118. def is_template(self) -> bool:
  1119. return isinstance(self.node, ir.TemplateBuffer)
  1120. def get_template_node(self) -> Optional[ir.TemplateBuffer]:
  1121. return self.node if isinstance(self.node, ir.TemplateBuffer) else None
  1122. def run(self, *index_vars: Sequence[sympy.Expr]) -> None:
  1123. self.decide_inplace_update()
  1124. self.mark_run()
  1125. self.codegen(index_vars)
  1126. def ranges_from_index_vars(
  1127. self, index_vars: Sequence[Sequence[sympy.Expr]]
  1128. ) -> dict[sympy.Expr, sympy.Expr]:
  1129. sizes = self._sizes
  1130. assert sum(map(len, sizes)) == sum(map(len, index_vars))
  1131. var_ranges = dict(
  1132. zip(
  1133. itertools.chain.from_iterable(index_vars),
  1134. itertools.chain.from_iterable(sizes),
  1135. )
  1136. )
  1137. return var_ranges
  1138. def codegen(self, index_vars: Sequence[Sequence[sympy.Expr]]) -> None:
  1139. """
  1140. Generate code for this node using the provided index variables.
  1141. This method sets up the appropriate context for code generation, including
  1142. simplifying indexing expressions based on the variable ranges, and then
  1143. calls the node's body function with the index variables.
  1144. Args:
  1145. index_vars: A sequence of sequences of sympy expressions representing
  1146. the index variables for each dimension of the computation.
  1147. """
  1148. var_ranges = self.ranges_from_index_vars(index_vars)
  1149. try:
  1150. with (
  1151. V.set_ops_handler(SimplifyIndexing(V.get_ops_handler(), var_ranges)),
  1152. V.kernel.set_current_node(self),
  1153. ):
  1154. self._body(*index_vars)
  1155. except Exception:
  1156. log.fatal("Error in codegen for %s", self.node)
  1157. raise
  1158. def pointwise_or_reduction_read_writes(
  1159. self, pointwise: bool = True
  1160. ) -> dependencies.ReadWrites:
  1161. """
  1162. Get the memory dependencies in either the pointwise or the reduction axes.
  1163. """
  1164. keep_sizes, ignore_sizes = self._sizes if pointwise else reversed(self._sizes)
  1165. return dependencies.extract_read_writes(
  1166. self._body, keep_sizes, hidden_args=[[sympy.S.Zero] * len(ignore_sizes)]
  1167. )
  1168. @cache_on_self
  1169. def pointwise_read_writes(self) -> dependencies.ReadWrites:
  1170. """
  1171. Get the memory dependencies in the non-reduction axes.
  1172. """
  1173. return self.pointwise_or_reduction_read_writes(pointwise=True)
  1174. @cache_on_self
  1175. def reduction_read_writes(self) -> dependencies.ReadWrites:
  1176. """
  1177. Get the memory dependencies in the reduction axes.
  1178. """
  1179. return self.pointwise_or_reduction_read_writes(pointwise=False)
  1180. def can_inplace(self, read_dep: dependencies.Dep) -> bool:
  1181. if self.is_template():
  1182. return False
  1183. if any(out.get_aliases() for out in self.get_outputs()):
  1184. return False
  1185. if len(self.read_writes.writes) == 1 and isinstance(
  1186. read_dep, dependencies.MemoryDep
  1187. ):
  1188. write_dep = next(iter(self.read_writes.writes))
  1189. assert isinstance(write_dep, dependencies.MemoryDep), f"{type(write_dep)=}"
  1190. return read_dep.index == write_dep.index and read_dep.size == write_dep.size
  1191. return False
  1192. @cache_on_self
  1193. def _get_atomic_add_buffers(self) -> OrderedSet[str]:
  1194. buffers_store_as_atomic_add: OrderedSet[str] = OrderedSet()
  1195. if isinstance(self._body, LoopBody):
  1196. for node in self._body.get_nodes():
  1197. if (
  1198. node.op == "call_method"
  1199. and node.target == "store"
  1200. and (
  1201. ("mode" in node.kwargs and node.kwargs["mode"] == "atomic_add")
  1202. or (len(node.args) == 5 and node.args[4] == "atomic_add")
  1203. )
  1204. ):
  1205. buffers_store_as_atomic_add.add(
  1206. node.kwargs["name"]
  1207. if "name" in node.kwargs
  1208. else (node.args[1] if len(node.args) >= 2 else "")
  1209. )
  1210. return buffers_store_as_atomic_add
  1211. @cache_on_self
  1212. def has_side_effects(self) -> bool:
  1213. # self._body is None sometimes that's why this check was added
  1214. if self._body is not None and self._body.has_op("device_assert_async"):
  1215. return True
  1216. return super().has_side_effects()
  1217. def refresh_group_node_dependencies(
  1218. group_snode: Union[FusedSchedulerNode, GroupedSchedulerNode],
  1219. ) -> None:
  1220. snodes = group_snode.snodes
  1221. group_snode.set_read_writes(
  1222. dependencies.ReadWrites.merge_list([x.read_writes for x in snodes])
  1223. )
  1224. group_snode.unmet_dependencies = (
  1225. OrderedSet(
  1226. dep
  1227. for dep in OrderedSet.union(*[x.unmet_dependencies for x in snodes])
  1228. if dep.name not in group_snode.get_buffer_names()
  1229. )
  1230. - group_snode.read_writes.writes
  1231. )
  1232. def init_group_node(
  1233. group_snode: Union[FusedSchedulerNode, GroupedSchedulerNode],
  1234. scheduler: Scheduler,
  1235. snodes: list[BaseSchedulerNode],
  1236. ) -> None:
  1237. assert isinstance(group_snode, (FusedSchedulerNode, GroupedSchedulerNode))
  1238. group_snode.snodes = snodes
  1239. group_snode.scheduler = scheduler
  1240. group_snode.node = None
  1241. group_snode.ancestors = OrderedSet.union(
  1242. *[x.ancestors for x in snodes if x.ancestors is not None]
  1243. )
  1244. refresh_group_node_dependencies(group_snode)
  1245. group_snode.min_order = min(x.min_order for x in group_snode.snodes)
  1246. group_snode.max_order = max(x.max_order for x in group_snode.snodes)
  1247. group_snode.outputs_by_name = {
  1248. buf.get_name(): buf for buf in group_snode.get_outputs()
  1249. }
  1250. class FusedSchedulerNode(BaseSchedulerNode):
  1251. """
  1252. This is a "fake" scheduler node that represents a group of scheduler nodes
  1253. that are meant to be fused together. The way it does this is by maintaining
  1254. its unmet dependencies as the union of its constituent nodes.
  1255. """
  1256. snodes: list[BaseSchedulerNode]
  1257. @classmethod
  1258. def fuse(
  1259. cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  1260. ) -> FusedSchedulerNode:
  1261. assert node1.scheduler is node2.scheduler
  1262. assert isinstance(node1, (SchedulerNode, FusedSchedulerNode))
  1263. if node1.is_template() and isinstance(node2, ExternKernelSchedulerNode):
  1264. # Fuse multi outputs template and its outputs
  1265. # * Node1 has memorydep of MultiOutput in reads
  1266. # * Node2 has StarDep of MultiOutput in writes
  1267. # Rewrite the Node2' StarDep to MemoryDep, because calculate score_fusion_memory
  1268. # of the template node and its epilogue requires the same type of dependencies
  1269. assert isinstance(node2.node, MultiOutput)
  1270. assert len(node2.read_writes.writes) == 1
  1271. assert isinstance(next(iter(node2.read_writes.writes)), StarDep)
  1272. name = next(iter(node2.read_writes.writes)).name
  1273. template_nodes = [node for node in node1.get_nodes() if node.is_template()]
  1274. assert len(template_nodes) == 1
  1275. template_node = template_nodes[0]
  1276. assert len(template_node.read_writes.writes) == 1
  1277. write = next(iter(template_node.read_writes.writes))
  1278. assert isinstance(write, MemoryDep)
  1279. node2.read_writes.writes = OrderedSet(
  1280. [
  1281. MemoryDep(
  1282. name, write.index, write.var_names, write.size, write.mode
  1283. ),
  1284. ]
  1285. )
  1286. else:
  1287. assert isinstance(node2, (SchedulerNode, FusedSchedulerNode))
  1288. nodes = list(itertools.chain(node1.get_nodes(), node2.get_nodes()))
  1289. return cls(node1.scheduler, nodes)
  1290. @cache_on_self
  1291. def estimate_flops(self) -> int | None:
  1292. # don't increment counters in fused methods so we don't double count
  1293. fps = list(
  1294. filter(
  1295. None,
  1296. (
  1297. node.estimate_flops()
  1298. for node in self.get_nodes()
  1299. if node.is_template() or node.is_extern()
  1300. ),
  1301. )
  1302. )
  1303. if len(fps) == 0:
  1304. return None
  1305. ret = sum(fps)
  1306. return ret
  1307. def reorder_loops_by_dep_pair(
  1308. self, self_dep: MemoryDep, other_dep: MemoryDep
  1309. ) -> bool:
  1310. """
  1311. Return true if a loop reordering is performed.
  1312. """
  1313. if self.is_template():
  1314. # We can not really reorder loops for a triton template
  1315. return False
  1316. self_sizes = None
  1317. for snode in self.snodes:
  1318. assert isinstance(snode, SchedulerNode)
  1319. if self_sizes is not None and tuple(self_sizes) != tuple(snode._sizes[0]):
  1320. loop_ordering_log.debug(
  1321. "Can not reorder fused node due to different sizes"
  1322. )
  1323. return False
  1324. self_sizes = snode._sizes[0]
  1325. new_order = None
  1326. assert self_sizes is not None
  1327. if len(self_sizes) == self_dep.num_vars == other_dep.num_vars:
  1328. new_order = self_dep.decide_loop_order_to_match(other_dep)
  1329. if not new_order:
  1330. loop_ordering_log.debug(
  1331. "Dont reordering fused node %s because we can not decide the suitable loop order",
  1332. self.get_name(),
  1333. )
  1334. return False
  1335. metrics.num_loop_reordering += 1
  1336. loop_ordering_log.debug(
  1337. "Reorder loops for fused node %s with order %s", self.get_name(), new_order
  1338. )
  1339. for snode in self.snodes:
  1340. assert isinstance(snode, SchedulerNode)
  1341. snode.apply_new_loop_order(new_order)
  1342. refresh_group_node_dependencies(self)
  1343. return True
  1344. def __init__(self, scheduler: Scheduler, snodes: list[BaseSchedulerNode]) -> None:
  1345. super().__init__(scheduler)
  1346. init_group_node(self, scheduler, snodes)
  1347. self.users: list[NodeUser] = []
  1348. self.group = max(snodes, key=lambda x: int(x.is_reduction())).group
  1349. @cache_on_self
  1350. def get_name(self) -> str:
  1351. return "_".join([x.get_name() for x in self.snodes])
  1352. def get_first_name(self) -> str:
  1353. return self.snodes[0].get_name()
  1354. @cache_on_self
  1355. def get_buffer_names(self) -> OrderedSet[str]:
  1356. return OrderedSet.union(*[x.get_buffer_names() for x in self.snodes])
  1357. def get_outputs(self) -> list[SchedulerBuffer]:
  1358. result: list[SchedulerBuffer] = []
  1359. for node in self.snodes:
  1360. result.extend(node.get_outputs())
  1361. return result
  1362. def debug_str_extra(self) -> str:
  1363. lines = [
  1364. f"{self.get_name()}.snodes[{i}] =\n{node.debug_str()}"
  1365. for i, node in enumerate(self.snodes)
  1366. ]
  1367. node = self.snodes[0].node
  1368. if node is not None:
  1369. lines.extend(self._debug_str_for_device())
  1370. return textwrap.indent("\n".join(lines).rstrip(), " ")
  1371. def debug_str_short(self) -> str:
  1372. snodes_str = [node.debug_str_short() for node in self.snodes]
  1373. return f"{self}, snodes: {snodes_str}"
  1374. def set_last_usage(
  1375. self, future_used_buffers: OrderedSet[str], mutation_real_name: dict[str, str]
  1376. ) -> None:
  1377. # Set self.last_usage using the global information
  1378. # This will be used for inter-kernel optimisations
  1379. super().set_last_usage(future_used_buffers, mutation_real_name)
  1380. # Set self.last_usage on the snodes
  1381. # This will be used for optimisations within the kernel
  1382. future_used_buffers: OrderedSet[str] = OrderedSet()
  1383. for node in reversed(self.snodes):
  1384. node.set_last_usage(future_used_buffers, mutation_real_name)
  1385. future_used_buffers.update(node.last_usage)
  1386. @cache_on_self
  1387. def used_buffer_names(self) -> OrderedSet[str]:
  1388. return OrderedSet.union(*[x.used_buffer_names() for x in self.snodes])
  1389. @cache_on_self
  1390. def used_or_aliased_buffer_names(self) -> OrderedSet[str]:
  1391. return OrderedSet.union(
  1392. *[x.used_or_aliased_buffer_names() for x in self.snodes]
  1393. )
  1394. def get_nodes(self) -> Sequence[BaseSchedulerNode]:
  1395. return self.snodes
  1396. def __repr__(self) -> str:
  1397. return f"{type(self).__name__}(nodes={self.get_name()})"
  1398. @cache_on_self
  1399. def is_reduction(self) -> bool:
  1400. return any(x.is_reduction() for x in self.snodes)
  1401. @cache_on_self
  1402. def is_split_scan(self) -> bool:
  1403. return any(x.is_split_scan() for x in self.snodes)
  1404. @cache_on_self
  1405. def is_template(self) -> bool:
  1406. return any(x.is_template() for x in self.snodes)
  1407. @cache_on_self
  1408. def get_template_node(self) -> Optional[ir.TemplateBuffer]:
  1409. for node in self.snodes:
  1410. if node.is_template():
  1411. return node.get_template_node()
  1412. return None
  1413. def get_device(self) -> torch.device:
  1414. return self.group[0]
  1415. @cache_on_self
  1416. def has_aliasing_or_mutation(self) -> bool:
  1417. return any(x.has_aliasing_or_mutation() for x in self.snodes)
  1418. # None of these need to be implemented, as a FusedSchedulerNode is just an
  1419. # abstraction for scheduling purposes
  1420. def update_mutated_names(self, renames: dict[str, str]) -> None:
  1421. raise NotImplementedError
  1422. def add_fake_dep(self, name: Dep) -> None:
  1423. raise NotImplementedError
  1424. def can_inplace(self, read_dep: dependencies.Dep) -> bool:
  1425. raise NotImplementedError
  1426. def debug_str(self) -> str:
  1427. """Longer form printout for trace logs"""
  1428. name = self.get_name()
  1429. node_typestr = ",".join(type(n).__name__ for n in self.snodes)
  1430. buf = IndentedBuffer()
  1431. buf.splice(
  1432. f"""\
  1433. {name}: {type(self).__name__}({node_typestr})
  1434. {name}.writes = {pformat(self.read_writes.writes)}
  1435. {name}.unmet_dependencies = {pformat(self.unmet_dependencies)}
  1436. {name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)}
  1437. {name}.outputs = [
  1438. """
  1439. )
  1440. with buf.indent():
  1441. for out in self.get_outputs():
  1442. buf.splice(out.debug_str())
  1443. buf.writeline("]")
  1444. try:
  1445. buf.splice(self.debug_str_extra())
  1446. except Exception:
  1447. log.warning("Ignoring error in debug_str()", exc_info=True)
  1448. return buf.getrawvalue().rstrip()
  1449. @cache_on_self
  1450. def has_side_effects(self) -> bool:
  1451. if self.snodes is not None:
  1452. return any(node.has_side_effects() for node in self.snodes)
  1453. return super().has_side_effects()
  1454. class ForeachKernelSchedulerNode(FusedSchedulerNode):
  1455. """
  1456. This is a schedular node that consists of a set of scheduler nodes that
  1457. has no data dependencies among them and can be executed in parallel.
  1458. """
  1459. def get_consumer_subnode_for(
  1460. self, producer: BaseSchedulerNode
  1461. ) -> Optional[BaseSchedulerNode]:
  1462. for buf in producer.get_outputs():
  1463. if buf.get_name() in self.read_to_node:
  1464. return self.read_to_node[buf.get_name()]
  1465. return None
  1466. def get_producer_subnode_for(
  1467. self, consumer: BaseSchedulerNode
  1468. ) -> Optional[BaseSchedulerNode]:
  1469. producers = OrderedSet[BaseSchedulerNode]()
  1470. for rd in consumer.read_writes.reads:
  1471. if rd.name not in self.scheduler.name_to_buf:
  1472. continue
  1473. node_name = self.scheduler.name_to_buf[rd.name].defining_op_name()
  1474. if node_name in self.name_to_node:
  1475. producers.add(self.name_to_node[node_name])
  1476. # Don't permit fusion if there are multiple subnodes
  1477. # that this consumer reads from
  1478. if len(producers) == 1:
  1479. return next(iter(producers))
  1480. else:
  1481. return None
  1482. @classmethod
  1483. def can_fuse(cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode) -> bool:
  1484. why = WhyNoFuse(producer, consumer)
  1485. if producer.is_foreach() and consumer.is_foreach():
  1486. producer = typing.cast(ForeachKernelSchedulerNode, producer)
  1487. consumer = typing.cast(ForeachKernelSchedulerNode, consumer)
  1488. foreach_match = len(producer.snodes) == len(consumer.snodes)
  1489. if not foreach_match:
  1490. why("foreach do not have same length")
  1491. return foreach_match and all(
  1492. producer.scheduler.can_fuse(l, r)
  1493. for l, r in zip(producer.snodes, consumer.snodes)
  1494. )
  1495. elif consumer.is_foreach():
  1496. if producer.is_reduction():
  1497. why(
  1498. "candidate producer is a reduction, foreach ops cannot be fused with reductions currently"
  1499. )
  1500. return False
  1501. consumer = typing.cast(ForeachKernelSchedulerNode, consumer)
  1502. consumer_subnode = consumer.get_consumer_subnode_for(producer)
  1503. if consumer_subnode is not None:
  1504. return consumer.scheduler.can_fuse(producer, consumer_subnode)
  1505. why("candidate producer is not dep of any foreach consumer")
  1506. return False
  1507. elif producer.is_foreach():
  1508. if consumer.is_reduction():
  1509. why(
  1510. "candidate consumer is a reduction, foreach ops cannot be fused with reductions currently"
  1511. )
  1512. return False
  1513. producer = typing.cast(ForeachKernelSchedulerNode, producer)
  1514. producer_subnode = producer.get_producer_subnode_for(consumer)
  1515. if producer_subnode is not None:
  1516. return producer.scheduler.can_fuse(producer_subnode, consumer)
  1517. why("candidate consumer has no dep in any foreach producer")
  1518. return False
  1519. raise AssertionError(
  1520. "At least one node passed to ForeachKernelSchedulerNode.can_fuse should be a foreach node"
  1521. )
  1522. @classmethod
  1523. def fuse(
  1524. cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode
  1525. ) -> ForeachKernelSchedulerNode:
  1526. assert producer.is_foreach() or consumer.is_foreach()
  1527. if producer.is_foreach():
  1528. producer = typing.cast(ForeachKernelSchedulerNode, producer)
  1529. use_custom_partition_algo = producer.use_custom_partition_algo
  1530. enable_autotune = producer.enable_autotune
  1531. else:
  1532. consumer = typing.cast(ForeachKernelSchedulerNode, consumer)
  1533. use_custom_partition_algo = consumer.use_custom_partition_algo
  1534. enable_autotune = consumer.enable_autotune
  1535. prev_node_1 = None
  1536. prev_node_2 = None
  1537. fused_nodes: list[BaseSchedulerNode]
  1538. if producer.is_foreach() and consumer.is_foreach():
  1539. producer = typing.cast(ForeachKernelSchedulerNode, producer)
  1540. consumer = typing.cast(ForeachKernelSchedulerNode, consumer)
  1541. fused_nodes = [
  1542. FusedSchedulerNode.fuse(l, r)
  1543. for l, r in zip(producer.snodes, consumer.snodes)
  1544. ]
  1545. elif producer.is_foreach():
  1546. producer = typing.cast(ForeachKernelSchedulerNode, producer)
  1547. producer_subnode = producer.get_producer_subnode_for(consumer)
  1548. fused_nodes = []
  1549. prev_node_1 = producer
  1550. prev_node_2 = None
  1551. for node in producer.snodes:
  1552. if node is producer_subnode:
  1553. new_node = FusedSchedulerNode.fuse(node, consumer)
  1554. prev_node_2 = new_node
  1555. fused_nodes.append(new_node)
  1556. else:
  1557. fused_nodes.append(node)
  1558. elif consumer.is_foreach():
  1559. consumer = typing.cast(ForeachKernelSchedulerNode, consumer)
  1560. consumer_subnode = consumer.get_consumer_subnode_for(producer)
  1561. fused_nodes = []
  1562. prev_node_1 = consumer
  1563. prev_node_2 = None
  1564. for node in consumer.snodes:
  1565. if node is consumer_subnode:
  1566. new_node = FusedSchedulerNode.fuse(producer, node)
  1567. prev_node_2 = new_node
  1568. fused_nodes.append(new_node)
  1569. else:
  1570. fused_nodes.append(node)
  1571. else:
  1572. raise AssertionError(
  1573. "At least one node passed to ForeachKernelSchedulerNode.fuse should be a foreach node"
  1574. )
  1575. return cls(
  1576. producer.scheduler,
  1577. fused_nodes,
  1578. use_custom_partition_algo=use_custom_partition_algo,
  1579. prev_node_1=prev_node_1,
  1580. prev_node_2=prev_node_2,
  1581. enable_autotune=enable_autotune,
  1582. )
  1583. def __init__(
  1584. self,
  1585. scheduler: Scheduler,
  1586. snodes: list[BaseSchedulerNode],
  1587. use_custom_partition_algo: bool,
  1588. prev_node_1: Optional[BaseSchedulerNode] = None,
  1589. prev_node_2: Optional[BaseSchedulerNode] = None,
  1590. enable_autotune: bool = False,
  1591. ) -> None:
  1592. self.read_to_node = {}
  1593. self.name_to_node = {}
  1594. if prev_node_1 is None or prev_node_2 is None:
  1595. super().__init__(scheduler, snodes)
  1596. for node in snodes:
  1597. for read in node.read_writes.reads:
  1598. self.read_to_node[read.name] = node
  1599. for name in node.get_operation_names():
  1600. self.name_to_node[name] = node
  1601. else:
  1602. self.scheduler = scheduler
  1603. self.snodes = snodes
  1604. self.node = None
  1605. self.users: list[NodeUser] = []
  1606. self.set_read_writes(
  1607. dependencies.ReadWrites.merge_list(
  1608. [prev_node_1.read_writes, prev_node_2.read_writes]
  1609. )
  1610. )
  1611. self.unmet_dependencies = (
  1612. OrderedSet(
  1613. dep
  1614. for dep in OrderedSet.union(
  1615. prev_node_1.unmet_dependencies, prev_node_2.unmet_dependencies
  1616. )
  1617. if dep.name not in self.get_buffer_names()
  1618. )
  1619. - self.read_writes.writes
  1620. )
  1621. self.min_order = min([prev_node_1.min_order, prev_node_2.min_order])
  1622. self.max_order = max([prev_node_1.max_order, prev_node_2.max_order])
  1623. if prev_node_1.is_foreach():
  1624. assert isinstance(prev_node_1, ForeachKernelSchedulerNode)
  1625. foreach_node, other_node = prev_node_1, prev_node_2
  1626. else:
  1627. assert isinstance(prev_node_2, ForeachKernelSchedulerNode)
  1628. foreach_node, other_node = prev_node_2, prev_node_1
  1629. self.ancestors = foreach_node.ancestors
  1630. self.ancestors.update(other_node.ancestors)
  1631. self.name_to_node = foreach_node.name_to_node
  1632. for name in other_node.get_operation_names():
  1633. self.name_to_node[name] = other_node
  1634. self.outputs_by_name: dict[str, SchedulerBuffer] = {
  1635. k: v for snode in self.snodes for k, v in snode.outputs_by_name.items()
  1636. }
  1637. self.use_custom_partition_algo = use_custom_partition_algo
  1638. device = snodes[0].get_device()
  1639. assert device
  1640. self.group = (device, ((sympy.Expr("combo_kernel"),),))
  1641. self.origins = OrderedSet[torch.fx.Node]()
  1642. self.enable_autotune = enable_autotune
  1643. @classmethod
  1644. def combinable_nodes(
  1645. cls, nodes: list[BaseSchedulerNode]
  1646. ) -> list[BaseSchedulerNode]:
  1647. extern = [x for x in nodes if isinstance(x, ExternKernelSchedulerNode)]
  1648. if extern:
  1649. log.debug(
  1650. "ComboKernels: %d external nodes are filtered %s",
  1651. len(extern),
  1652. [node.node.get_origins() for node in extern if node.node is not None],
  1653. )
  1654. filtered_nodes = [
  1655. x
  1656. for x in nodes
  1657. if not isinstance(x, (NopKernelSchedulerNode, ExternKernelSchedulerNode))
  1658. ]
  1659. foreach_nodes = [
  1660. x for x in filtered_nodes if isinstance(x, ForeachKernelSchedulerNode)
  1661. ]
  1662. if foreach_nodes:
  1663. log.debug("ComboKernels: %d foreach nodes are filtered", len(foreach_nodes))
  1664. filtered_nodes = [
  1665. x for x in filtered_nodes if not isinstance(x, ForeachKernelSchedulerNode)
  1666. ]
  1667. template_nodes = [x for x in filtered_nodes if x.is_template()]
  1668. if template_nodes:
  1669. log.debug(
  1670. "ComboKernels: %d template nodes are filtered: %s",
  1671. len(template_nodes),
  1672. template_nodes,
  1673. )
  1674. filtered_nodes = [x for x in filtered_nodes if x not in template_nodes]
  1675. return filtered_nodes
  1676. @staticmethod
  1677. def _default_group_nodes_for_combo_kernels(
  1678. scheduler: Scheduler,
  1679. ) -> list[list[BaseSchedulerNode]]:
  1680. """
  1681. Returns a list of lists of nodes that are to be grouped together.
  1682. """
  1683. sorted_nodes = scheduler._topological_sort_nodes()
  1684. grouped_nodes = []
  1685. max_num_nodes = 8
  1686. for nodes in sorted_nodes:
  1687. grouped_nodes.extend(
  1688. [
  1689. nodes[i : i + max_num_nodes]
  1690. for i in range(0, len(nodes), max_num_nodes)
  1691. ]
  1692. )
  1693. return grouped_nodes
  1694. group_algorithm_for_combo_kernels: Callable[
  1695. [Scheduler], list[list[BaseSchedulerNode]]
  1696. ] = _default_group_nodes_for_combo_kernels
  1697. @staticmethod
  1698. def set_group_algorithm_for_combo_kernels(
  1699. custom_group_algorithm: Callable[[Scheduler], list[list[BaseSchedulerNode]]],
  1700. ) -> None:
  1701. ForeachKernelSchedulerNode.group_algorithm_for_combo_kernels = (
  1702. custom_group_algorithm
  1703. )
  1704. @staticmethod
  1705. def group_nodes_for_combo_kernels(
  1706. scheduler: Scheduler,
  1707. ) -> list[list[BaseSchedulerNode]]:
  1708. return ForeachKernelSchedulerNode.group_algorithm_for_combo_kernels(scheduler)
  1709. def mark_run(self) -> None:
  1710. raise NotImplementedError
  1711. def codegen(self) -> None:
  1712. raise NotImplementedError
  1713. def is_foreach(self) -> bool:
  1714. return True
  1715. def get_subkernel_nodes(self) -> list[BaseSchedulerNode]:
  1716. """Returns a list of nodes which comprise the combo kernel.
  1717. These nodes may be vertically fused."""
  1718. return list(self.snodes)
  1719. def get_nodes(self) -> Sequence[BaseSchedulerNode]:
  1720. """Returns all nodes contained in this kernel, unpacking fused nodes
  1721. into their constituent scheduler nodes."""
  1722. return list(itertools.chain.from_iterable(x.get_nodes() for x in self.snodes))
  1723. def get_first_name(self) -> str:
  1724. return self.snodes[0].get_first_name()
  1725. def prune_redundant_deps(
  1726. self, name_to_fused_node: dict[str, BaseSchedulerNode]
  1727. ) -> None:
  1728. _prune_redundant_deps(self, name_to_fused_node, self.scheduler.name_to_buf)
  1729. for node in self.snodes:
  1730. node.prune_redundant_deps(name_to_fused_node)
  1731. class GroupedSchedulerNode(BaseSchedulerNode):
  1732. """
  1733. This is a "fake" scheduler node that represents a group of scheduler nodes
  1734. that are meant to be *grouped* together (it does not allow another node to be scheduled
  1735. in between its constituent nodes, nor does it allow another node to fuse into any of its constituent nodes).
  1736. The way it does this is by maintaining its unmet dependencies as the union of its constituent nodes.
  1737. Fusion will still happen among the nodes within each GroupedSchedulerNode.
  1738. At codegen time, this scheduler node will be unpacked and codegen is called on each constituent node.
  1739. """
  1740. snodes: list[BaseSchedulerNode]
  1741. @classmethod
  1742. def create(cls, snodes: list[BaseSchedulerNode]) -> GroupedSchedulerNode:
  1743. scheduler = snodes[0].scheduler
  1744. assert all(node.scheduler is scheduler for node in snodes)
  1745. grouped_snode = cls(scheduler, snodes)
  1746. for snode in snodes:
  1747. scheduler.name_to_fused_node[snode.get_name()] = grouped_snode
  1748. scheduler.name_to_fused_node[grouped_snode.get_name()] = grouped_snode
  1749. return grouped_snode
  1750. def __init__(
  1751. self,
  1752. scheduler: Scheduler,
  1753. snodes: list[BaseSchedulerNode],
  1754. temp_grouping: bool = False,
  1755. ) -> None:
  1756. super().__init__(scheduler)
  1757. init_group_node(self, scheduler, snodes)
  1758. # This flag is introduced for "temporary" grouping during some passes,
  1759. # Where nodes are grouped and moved together.
  1760. # After the pass those nodes are flattened.
  1761. # Reusing calculation of grouped unmed_dependencies etc.
  1762. # No fusion logic in this case.
  1763. self.temp_grouping = temp_grouping
  1764. def unpack(self) -> list[BaseSchedulerNode]:
  1765. """
  1766. Do fusion among nodes within this GroupedSchedulerNode,
  1767. and then unpack this GroupedSchedulerNode into regular nodes.
  1768. """
  1769. if self.temp_grouping:
  1770. return self.snodes
  1771. for snode in self.snodes:
  1772. self.scheduler.name_to_fused_node[snode.get_name()] = snode
  1773. del self.scheduler.name_to_fused_node[self.get_name()]
  1774. return self.scheduler.fuse_nodes(self.snodes)
  1775. def add_fake_dep(self, fake_dep: Dep) -> None:
  1776. self.set_read_writes(self.read_writes.with_read(fake_dep))
  1777. self.unmet_dependencies.add(fake_dep)
  1778. @cache_on_self
  1779. def get_name(self) -> str:
  1780. return "_".join([x.get_name() for x in self.snodes])
  1781. def get_first_name(self) -> str:
  1782. return self.snodes[0].get_name()
  1783. @cache_on_self
  1784. def get_buffer_names(self) -> OrderedSet[str]:
  1785. return OrderedSet.union(*[x.get_buffer_names() for x in self.snodes])
  1786. def get_outputs(self) -> list[SchedulerBuffer]:
  1787. result: list[SchedulerBuffer] = []
  1788. for node in self.snodes:
  1789. result.extend(node.get_outputs())
  1790. return result
  1791. @cache_on_self
  1792. def estimate_flops(self) -> int | None:
  1793. # don't increment counters in fused methods so we don't double count
  1794. fps = list(
  1795. filter(
  1796. None,
  1797. (
  1798. node.estimate_flops()
  1799. for node in self.get_nodes()
  1800. if node.is_template() or node.is_extern()
  1801. ),
  1802. )
  1803. )
  1804. if len(fps) == 0:
  1805. return None
  1806. ret = sum(fps)
  1807. return ret
  1808. def get_nodes(self) -> Sequence[BaseSchedulerNode]:
  1809. return self.snodes
  1810. @classmethod
  1811. def can_fuse(cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode) -> bool:
  1812. # GroupedSchedulerNode cannot be fused with another node
  1813. return False
  1814. def pick_loop_order(
  1815. stride_lengths: list[list[int]],
  1816. sizes: Sequence[sympy.Expr],
  1817. priority_idx: Sequence[int] = (),
  1818. ) -> list[int]:
  1819. """
  1820. A heuristic to decide loop iteration orders. This has not been well
  1821. tuned and may be something we should autotune.
  1822. """
  1823. @functools.cmp_to_key
  1824. def index_cmp(a: int, b: int) -> int:
  1825. if sizes[a] == 1 or sizes[b] == 1:
  1826. # 1-sizes don't matter, just move them to the end
  1827. return cmp(sizes[a] == 1, sizes[b] == 1)
  1828. # Take abs, otherwise flipped dimensions are treated as smaller
  1829. # strides than contiguous dims
  1830. stride_len_a = [abs(sl[a]) for sl in stride_lengths]
  1831. stride_len_b = [abs(sl[b]) for sl in stride_lengths]
  1832. # equivalent to
  1833. # np.logical_or(stride_lengths[:, b] == 0, stride_lengths[:, a] < stride_lengths[:, b]).all()
  1834. a_first = sum(
  1835. sl_b == 0 or sl_a < sl_b for sl_a, sl_b in zip(stride_len_a, stride_len_b)
  1836. )
  1837. b_first = sum(
  1838. sl_a == 0 or sl_b < sl_a for sl_a, sl_b in zip(stride_len_a, stride_len_b)
  1839. )
  1840. if a_first > b_first:
  1841. return -1
  1842. if b_first > a_first:
  1843. return 1
  1844. # otherwise contiguous
  1845. return cmp(b, a)
  1846. order = list(reversed(range(len(stride_lengths[0]))))
  1847. if len(priority_idx) > 0:
  1848. # if we have priority node, only use that node's order
  1849. stride_lengths = [stride_lengths[pi] for pi in priority_idx]
  1850. if config.pick_loop_orders:
  1851. order.sort(key=index_cmp)
  1852. return order
  1853. @dataclasses.dataclass
  1854. class NodeUser:
  1855. node: Union[BaseSchedulerNode, OutputNode]
  1856. can_inplace: bool = False
  1857. # A weak user must be scheduled after a given node, but doesn't actually
  1858. # use the result
  1859. is_weak: bool = False
  1860. def __hash__(self) -> int:
  1861. return hash((self.node.get_name(), self.can_inplace, self.is_weak))
  1862. def __eq__(self, other: object) -> bool:
  1863. return (
  1864. isinstance(other, NodeUser)
  1865. and self.get_name() == other.get_name()
  1866. and self.can_inplace == other.can_inplace
  1867. and self.is_weak == other.is_weak
  1868. )
  1869. def get_name(self) -> str:
  1870. return self.node.get_name()
  1871. def merge(self, other: NodeUser) -> NodeUser:
  1872. assert self.node is other.node
  1873. return NodeUser(
  1874. self.node,
  1875. self.can_inplace and other.can_inplace,
  1876. self.is_weak and other.is_weak,
  1877. )
  1878. _post_grad_graph_counter = itertools.count()
  1879. def used_non_deterministic_runtime_estimations() -> bool:
  1880. return config.runtime_estimations_mms_benchmark
  1881. class Scheduler:
  1882. """
  1883. A Scheduler is a graph of BaseSchedulerNodes. It is responsible for
  1884. optimizations such as fusion, reorder, and graph partition.
  1885. """
  1886. def __init__(self, nodes: list[ir.Operation]) -> None:
  1887. with dynamo_timed("Scheduler.__init__"):
  1888. self._init(nodes)
  1889. def _init(self, nodes: list[ir.Operation]) -> None:
  1890. super().__init__()
  1891. V.graph.scheduler = self
  1892. self.backends: dict[torch.device, BaseScheduling] = {}
  1893. self.post_grad_graph_id = next(_post_grad_graph_counter)
  1894. self._graph_partition_counter = itertools.count()
  1895. self.completed_operations: OrderedSet[str] = OrderedSet()
  1896. self.available_buffer_names = OrderedSet(
  1897. [
  1898. *V.graph.graph_inputs.keys(),
  1899. *V.graph.constants.keys(),
  1900. *V.graph.torchbind_constants.keys(),
  1901. ]
  1902. )
  1903. self.nodes = [self.create_scheduler_node(n) for n in nodes]
  1904. self.current_node: Optional[BaseSchedulerNode] = None
  1905. self.update_zero_dim_cpu_tensor()
  1906. # some new constants could have been created above
  1907. self.available_buffer_names.update(V.graph.constants.keys())
  1908. for node in self.nodes:
  1909. node.prune_deps()
  1910. # See [Note: Graph Partition Device Contexts]
  1911. self.default_device_context: Optional[torch.device] = None
  1912. self.name_to_donated_buffer: dict[str, SchedulerDonatedBuffer] = (
  1913. self.get_donated_buffers()
  1914. )
  1915. self.name_to_node: dict[str, BaseSchedulerNode] = {
  1916. n.get_name(): n for n in self.nodes
  1917. }
  1918. self.name_to_buf: dict[str, SchedulerBuffer] = {
  1919. buf.get_name(): buf for node in self.nodes for buf in node.get_outputs()
  1920. }
  1921. self.name_to_fused_node: dict[str, BaseSchedulerNode] = self.name_to_node.copy()
  1922. # mutation_real_name: Maps back to the original name for codegen
  1923. # Example:
  1924. # If you mutate buf0 inside of buf1's kernel, then:
  1925. # mutation_real_name = {"buf0" : "buf1"}
  1926. # all subsequent uses of buf0 become buf1's usage in dependency graph
  1927. self.mutation_real_name: dict[str, str] = {}
  1928. # We handle mutation by renaming modified versions of the same
  1929. # buffer in the dependency graph to prevent cycles.
  1930. # mutation_renames: tracks the current name for a given buffer
  1931. # (changed once per mutation)
  1932. # Example:
  1933. # If you mutate buf0 inside of buf1's kernel, then:
  1934. # mutation_renames = {"buf1" : "buf0"}
  1935. # in codegen we only use buf0, never buf1
  1936. self.mutation_renames: dict[str, str] = {}
  1937. # Must run first to correctly set dependencies, before all other passes that rely on
  1938. # reading from .read_writes.reads or .unmet_dependencies
  1939. self.nodes = comms.decide_global_ordering_of_comms(
  1940. self.nodes,
  1941. self.name_to_buf,
  1942. self.name_to_fused_node,
  1943. )
  1944. self.compute_dependencies()
  1945. self.nodes = self.topological_sort_schedule(self.nodes)
  1946. self.dead_node_elimination()
  1947. self.name_to_fused_node = {n.get_name(): n for n in self.nodes}
  1948. self.compute_ancestors()
  1949. metrics.ir_nodes_pre_fusion += len(self.nodes)
  1950. from torch._inductor.debug import log_ir_post_fusion, log_ir_pre_fusion
  1951. log_ir_pre_fusion(self.nodes)
  1952. self.num_orig_nodes = len(self.nodes)
  1953. self.create_foreach_nodes()
  1954. self.nodes = self.topological_sort_schedule(self.nodes)
  1955. self.logged_slow_fusion = OrderedSet[tuple[str, str]]()
  1956. if config._pre_fusion_custom_pass is not None:
  1957. self.nodes = config._pre_fusion_custom_pass(self.nodes)
  1958. self.nodes = self.fuse_nodes(self.nodes)
  1959. if config._post_fusion_custom_pass is not None:
  1960. self.nodes = config._post_fusion_custom_pass(self.nodes)
  1961. self.merge_loops()
  1962. self.finalize_multi_template_buffers()
  1963. if config.combo_kernels:
  1964. with dynamo_timed(
  1965. "Scheduler.create_combo_kernel_nodes",
  1966. log_pt2_compile_event=True,
  1967. log_waitcounter=True,
  1968. ):
  1969. self.create_combo_kernel_nodes(num_ck_nodes=None)
  1970. # Peak memory pass and overlap pass must run last, otherwise
  1971. # other reordering passes could undo their effects.
  1972. if config.reorder_for_peak_memory:
  1973. from .memory import reorder_for_peak_memory
  1974. self.nodes = reorder_for_peak_memory(
  1975. self.nodes,
  1976. self.name_to_buf,
  1977. self.name_to_fused_node,
  1978. OrderedSet(V.graph.graph_inputs.keys()),
  1979. OrderedSet(V.graph.get_output_names()),
  1980. )
  1981. if config.reorder_for_compute_comm_overlap:
  1982. if not config.reorder_for_peak_memory:
  1983. from .memory import assign_memory_planning_info_for_scheduler_buffers
  1984. assign_memory_planning_info_for_scheduler_buffers(
  1985. self.nodes, self.name_to_buf
  1986. )
  1987. if (
  1988. used_non_deterministic_runtime_estimations()
  1989. and config_comms.runtime_estimations_align_across_all_distributed_ranks
  1990. ):
  1991. from .comms import (
  1992. align_runtime_estimations_across_all_distributed_ranks,
  1993. )
  1994. align_runtime_estimations_across_all_distributed_ranks(self.nodes)
  1995. from torch._logging import trace_structured
  1996. trace_structured(
  1997. "artifact",
  1998. metadata_fn=lambda: {
  1999. "name": "scheduler_nodes_before_comm_overlap",
  2000. "encoding": "string",
  2001. },
  2002. payload_fn=lambda: "\n\n".join(
  2003. [
  2004. f"snode[{i}]"
  2005. + n.debug_str()
  2006. + f" buffer_names:{n.get_buffer_names()}"
  2007. for i, n in enumerate(self.nodes)
  2008. ]
  2009. ),
  2010. )
  2011. self.nodes = comms.reorder_compute_and_comm_for_overlap(self.nodes)
  2012. self.process_grouped_nodes()
  2013. if (
  2014. torch._inductor.config.graph_partition
  2015. and torch._inductor.config.triton.cudagraphs
  2016. ):
  2017. self.nodes = self.maybe_reorder_for_minimizing_partition(self.nodes)
  2018. self.nodes = self.reorder_for_partition_with_simple_dependency(self.nodes)
  2019. self.compute_last_usage()
  2020. if torch._inductor.config.test_configs.track_memory_lifecycle:
  2021. self.insert_memory_check_nodes()
  2022. log_ir_post_fusion(self.nodes)
  2023. V.debug.graph_diagram(self.nodes)
  2024. self.debug_draw_graph()
  2025. # used during codegen:
  2026. self.buffer_names_to_free: OrderedSet[str] = OrderedSet()
  2027. # fx graph node to the position it appears in the graph
  2028. # for debug attribution
  2029. self.origin_to_index: dict[torch.fx.Node, int] = {}
  2030. get_metric_table("graph_stats").add_row(
  2031. lambda: {
  2032. "graph_id": self.post_grad_graph_id,
  2033. "num_nodes_before_fusion": self.num_orig_nodes,
  2034. "num_nodes_after_fusion": len(self.nodes),
  2035. }
  2036. )
  2037. def get_donated_buffers(self) -> dict[str, SchedulerDonatedBuffer]:
  2038. name_to_donated_buf = {}
  2039. for name in V.graph.graph_inputs_original:
  2040. if isinstance(V.graph.graph_inputs_original[name], ir.DonatedBuffer):
  2041. name_to_donated_buf[name] = SchedulerDonatedBuffer(
  2042. self,
  2043. V.graph.graph_inputs_original[name],
  2044. defining_op=None,
  2045. )
  2046. return name_to_donated_buf
  2047. @property
  2048. def current_device(self) -> Optional[torch.device]:
  2049. return V.graph.current_device
  2050. @current_device.setter
  2051. def current_device(self, device: Optional[torch.device]) -> None:
  2052. V.graph.current_device = device
  2053. def debug_draw_graph(self) -> None:
  2054. """Generate an image of the graph for debugging"""
  2055. if os.environ.get("INDUCTOR_WRITE_SCHEDULER_GRAPH", None) == "1":
  2056. from .debug import draw_buffers
  2057. draw_buffers(self.nodes, print_graph=True)
  2058. def debug_print_nodes(self, label: str) -> None:
  2059. if log.isEnabledFor(logging.INFO):
  2060. log.info("%s:", label)
  2061. for node in self.nodes:
  2062. node.log_details()
  2063. def create_scheduler_node(self, node: ir.Operation) -> BaseSchedulerNode:
  2064. assert node.get_origins() is not None, (
  2065. "All nodes passed to scheduling must have an origin"
  2066. )
  2067. if node.is_no_op():
  2068. return NopKernelSchedulerNode(self, node)
  2069. elif isinstance(node, (ir.ComputedBuffer, ir.TemplateBuffer)):
  2070. return SchedulerNode(self, node)
  2071. elif isinstance(node, ir.ExternKernel):
  2072. return ExternKernelSchedulerNode(self, node)
  2073. else:
  2074. raise NotImplementedError(node)
  2075. def create_foreach_nodes(self) -> None:
  2076. removed_node_names: OrderedSet[str] = OrderedSet()
  2077. fe_nodes = []
  2078. kept_node_names = self.name_to_fused_node.keys()
  2079. for names in V.graph.lists.values():
  2080. names = [
  2081. name
  2082. for name in names
  2083. if name in kept_node_names
  2084. and not isinstance(self.name_to_node[name], NopKernelSchedulerNode)
  2085. ]
  2086. if not names:
  2087. # All nodes eliminated
  2088. continue
  2089. removed_node_names.update(names)
  2090. snodes = [self.name_to_node[name] for name in names]
  2091. enable_autotune = config.combo_kernels_autotune > 1
  2092. fe_node = ForeachKernelSchedulerNode(
  2093. self,
  2094. snodes,
  2095. use_custom_partition_algo=False,
  2096. enable_autotune=enable_autotune,
  2097. )
  2098. fe_nodes.append(fe_node)
  2099. for name in names:
  2100. self.name_to_fused_node[name] = fe_node
  2101. self.nodes = [
  2102. node for node in self.nodes if node.get_name() not in removed_node_names
  2103. ] + list(fe_nodes)
  2104. def compute_dependencies(self) -> None:
  2105. """
  2106. Create dependency edges between nodes, handling aliasing and
  2107. mutation properly.
  2108. """
  2109. class DedupList(Generic[_T]):
  2110. """
  2111. This data structure behaves like a list except it makes sure the
  2112. elements remain unique.
  2113. Normally one could use a OrderedSet/dict for this purpose however
  2114. the list in question gets elements appended as it is being
  2115. iterated over which means that we need to keep the list
  2116. semantics.
  2117. """
  2118. def __init__(
  2119. self,
  2120. items: Optional[list[_T]] = None,
  2121. membership: Optional[OrderedSet[_T]] = None,
  2122. ) -> None:
  2123. self.items = items or []
  2124. self.membership = membership or OrderedSet()
  2125. def append(self, node_user: _T) -> None:
  2126. if node_user in self.membership:
  2127. return
  2128. self.items.append(node_user)
  2129. self.membership.add(node_user)
  2130. def __add__(self, other: DedupList[_T]) -> DedupList[_T]:
  2131. new_membership = OrderedSet.union(self.membership, other.membership)
  2132. new_items = self.items + [
  2133. x for x in other.items if x not in self.membership
  2134. ]
  2135. return DedupList(new_items, new_membership)
  2136. name_to_users: defaultdict[str, DedupList[NodeUser]] = collections.defaultdict(
  2137. DedupList
  2138. )
  2139. # handle aliasing by using python aliasing in name_to_users
  2140. # if foo aliases bar then we will make name_to_users["foo"] point
  2141. # to the same python list as name_to_users["bar"]
  2142. for node in self.nodes:
  2143. for buf1 in node.get_outputs():
  2144. buf1_name = buf1.get_name()
  2145. # This is for handling auto functionized ops which return None
  2146. # and mutate more than 1 inputs, we shouldn't let them all
  2147. # point to the same user list since buffers in the aliases
  2148. # list might not be alias to each other.
  2149. if (
  2150. isinstance(buf1.node.layout, ir.NoneLayout)
  2151. and len(buf1.get_aliases()) > 1
  2152. ):
  2153. continue
  2154. for buf2_name in buf1.get_aliases():
  2155. if buf1_name in name_to_users and buf2_name in name_to_users:
  2156. # merge the two
  2157. list1 = name_to_users[buf1_name]
  2158. list2 = name_to_users[buf2_name]
  2159. combined = list1 + list2
  2160. for key in name_to_users.keys():
  2161. if (
  2162. name_to_users[key] is list1
  2163. or name_to_users[key] is list2
  2164. ):
  2165. name_to_users[key] = combined
  2166. elif buf1_name in name_to_users:
  2167. name_to_users[buf2_name] = name_to_users[buf1_name]
  2168. else:
  2169. name_to_users[buf1_name] = name_to_users[buf2_name]
  2170. def rename(n: str) -> str:
  2171. if n in self.mutation_renames:
  2172. return rename(self.mutation_renames[n])
  2173. return n
  2174. def add_user(
  2175. used_by_name: str,
  2176. user_node: Union[BaseSchedulerNode, OutputNode],
  2177. can_inplace: bool = False,
  2178. is_weak: bool = False,
  2179. ) -> None:
  2180. name_to_users[rename(used_by_name)].append(
  2181. NodeUser(user_node, can_inplace, is_weak)
  2182. )
  2183. unbacked_symbol_to_origin_node: dict[sympy.Symbol, Optional[str]] = {}
  2184. # NB: None means that the dependency is on an input. Don't actually
  2185. # generate a dependency because if we do, Inductor will start trying
  2186. # to free the unbacked int but that's pointless
  2187. for name, val in V.graph.graph_inputs.items():
  2188. if isinstance(val, sympy.Expr):
  2189. for fs in val.free_symbols:
  2190. unbacked_symbol_to_origin_node[fs] = None
  2191. elif isinstance(val, ir.TensorBox):
  2192. # We also need to add symbols from input size as well because
  2193. # AOTI doesn't lift the unbacked symints to inputs
  2194. sym_size = [s for s in val.get_size() if isinstance(s, sympy.Expr)]
  2195. for s in sym_size:
  2196. for fs in s.free_symbols:
  2197. unbacked_symbol_to_origin_node[fs] = None
  2198. has_non_input_unbacked_defs = False
  2199. for node in self.nodes:
  2200. assert node.node is not None
  2201. # unbacked symbols don't follow ordinary buffer dependencies, so
  2202. # we track their def/uses separately
  2203. unbacked_symbol_defs = sorted(
  2204. node.node.get_unbacked_symbol_defs(), key=lambda x: x.name
  2205. )
  2206. for s in unbacked_symbol_defs:
  2207. assert isinstance(s, sympy.Symbol)
  2208. # Pick the first definer as canonical. There may be multiple
  2209. # because if a MultiOutputLayout buffer propagates an unbacked
  2210. # symint to multiple outputs, they will all claim to def it.
  2211. has_non_input_unbacked_defs = True
  2212. if s not in unbacked_symbol_to_origin_node:
  2213. unbacked_symbol_to_origin_node[s] = node.get_name()
  2214. for node in self.nodes:
  2215. log.debug("scheduling %s", node.node)
  2216. if has_non_input_unbacked_defs:
  2217. assert node.node is not None
  2218. unbacked_symbol_uses = sorted(
  2219. node.node.get_free_symbol_uses(unbacked_only=True),
  2220. key=lambda x: x.name,
  2221. )
  2222. # if a kernel takes unbacked symints, register dependencies
  2223. for s in unbacked_symbol_uses:
  2224. assert s in unbacked_symbol_to_origin_node, (
  2225. f"{s} not in {unbacked_symbol_to_origin_node}"
  2226. )
  2227. if (r := unbacked_symbol_to_origin_node[s]) is not None:
  2228. for buf in self.name_to_node[r].get_outputs():
  2229. node.add_fake_dep(StarDep(buf.get_name()))
  2230. if (
  2231. len(node.read_writes.writes) == 1
  2232. and (dep := next(iter(node.read_writes.writes)))
  2233. and isinstance(dep, MemoryDep)
  2234. ):
  2235. node_mode = dep.mode
  2236. else:
  2237. node_mode = None
  2238. # Handle output mutations
  2239. for buf in node.get_outputs():
  2240. # a node will mutate either 0 or 1 buffers
  2241. assert len(buf.get_mutations()) <= 1
  2242. for alt_name in buf.get_mutations():
  2243. alt_name = rename(alt_name)
  2244. # this node must run after the prior writer
  2245. add_user(alt_name, node)
  2246. node.add_fake_dep(StarDep(alt_name, mode=node_mode))
  2247. for user in name_to_users[alt_name].items:
  2248. if user.get_name() == node.get_name():
  2249. continue
  2250. assert isinstance(user.node, BaseSchedulerNode)
  2251. for other_name in user.node.get_buffer_names():
  2252. # this node must run after all prior readers
  2253. other_name = rename(other_name)
  2254. node.add_fake_dep(
  2255. WeakDep(other_name, mutating_buf=buf.get_name())
  2256. )
  2257. add_user(other_name, node, is_weak=True)
  2258. # add normal non-mutation dependencies
  2259. for read in node.read_writes.reads:
  2260. if not isinstance(read, WeakDep):
  2261. add_user(read.name, node, node.can_inplace(read))
  2262. node.update_mutated_names(self.mutation_renames)
  2263. # update our renaming scheme for the next iteration
  2264. for buf in node.get_outputs():
  2265. for alt_name in buf.get_mutations():
  2266. self.mutation_renames[rename(alt_name)] = buf.get_name()
  2267. self.mutation_renames[alt_name] = buf.get_name()
  2268. self.mutation_real_name[buf.get_name()] = (
  2269. self.mutation_real_name.get(alt_name, alt_name)
  2270. )
  2271. # make sure outputs aren't dead-code-eliminated
  2272. for buf_name in V.graph.get_output_names():
  2273. log.debug("scheduling output %s", buf_name)
  2274. add_user(buf_name, OutputNode(StarDep(buf_name)))
  2275. # make sure unbacked symints aren't dead-code-eliminated
  2276. if has_non_input_unbacked_defs:
  2277. for out in V.graph.graph_outputs:
  2278. for s in out.get_free_symbol_uses(unbacked_only=True):
  2279. assert s in unbacked_symbol_to_origin_node, (
  2280. f"{s} not in {unbacked_symbol_to_origin_node.keys()}"
  2281. )
  2282. if r := unbacked_symbol_to_origin_node[s]:
  2283. for buf_name in self.name_to_node[r].get_buffer_names():
  2284. log.debug(
  2285. "scheduling output %s for unbacked symint %s",
  2286. buf_name,
  2287. s,
  2288. )
  2289. add_user(buf_name, OutputNode(StarDep(buf_name)))
  2290. # make sure input mutation isn't dead-code-eliminated
  2291. for name in self.mutation_renames:
  2292. if name in V.graph.graph_inputs:
  2293. add_user(name, OutputNode(StarDep(name)))
  2294. V.graph.mutated_inputs.add(name)
  2295. elif name in V.graph.constants:
  2296. # In AOTI, module parameters and buffers are not lifted as graph inputs
  2297. add_user(name, OutputNode(StarDep(name)))
  2298. inp_names = {
  2299. name: index for index, name in enumerate(V.graph.graph_inputs.keys())
  2300. }
  2301. V.graph.mutated_input_idxs = [
  2302. inp_names[name] for name in V.graph.mutated_inputs
  2303. ]
  2304. # copy users information onto the nodes
  2305. for node in self.nodes:
  2306. for buf in node.get_outputs():
  2307. buf.set_users(name_to_users[buf.get_name()].items)
  2308. for name in self.name_to_donated_buffer:
  2309. self.name_to_donated_buffer[name].set_users(name_to_users[name].items)
  2310. # For debug logging
  2311. logbuf = IndentedBuffer()
  2312. logbuf.splice("{")
  2313. for key, value in name_to_users.items():
  2314. with logbuf.indent():
  2315. users = [v.get_name() for v in value.items]
  2316. logbuf.splice(f"'{key}': {users},")
  2317. logbuf.splice("}")
  2318. str = logbuf.getrawvalue().rstrip()
  2319. compute_dependencies_log.debug("BUFFER USER LIST\n")
  2320. compute_dependencies_log.debug("===== AFTER SCHEDULING =====\n%s", str)
  2321. def insert_memory_check_nodes(self) -> None:
  2322. from .memory import (
  2323. assign_memory_planning_info_for_scheduler_buffers,
  2324. compute_memory_timeline,
  2325. FreeableInputBuffer,
  2326. get_freeable_input_buf,
  2327. )
  2328. graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
  2329. name_to_freeable_input_buf: dict[str, FreeableInputBuffer] = (
  2330. get_freeable_input_buf(self.nodes, graph_inputs)
  2331. )
  2332. if not torch._inductor.config.reorder_for_peak_memory:
  2333. assign_memory_planning_info_for_scheduler_buffers(
  2334. self.nodes, self.name_to_buf
  2335. )
  2336. graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
  2337. buf_info_list, _, _ = compute_memory_timeline(
  2338. self.nodes,
  2339. name_to_freeable_input_buf,
  2340. graph_outputs,
  2341. )
  2342. step_allocs_deallocs: list[tuple[list[str], list[str]]] = [
  2343. ([], []) for _ in range(len(self.nodes))
  2344. ]
  2345. for buf_info in buf_info_list:
  2346. # Skip zero-size buffers
  2347. if buf_info.size_alloc == 0 and buf_info.size_free == 0:
  2348. continue
  2349. buf_name = buf_info.buffer.get_name()
  2350. step_allocs_deallocs[buf_info.start_step][0].append(buf_name)
  2351. step_allocs_deallocs[buf_info.end_step][1].append(buf_name)
  2352. from torch._inductor.runtime.debug_utils import register_check_mem_op
  2353. register_check_mem_op()
  2354. def construct_mem_check_node(
  2355. step_idx: int, is_final_step: bool
  2356. ) -> ExternKernelSchedulerNode:
  2357. expected_newly_alive = step_allocs_deallocs[step_idx][0]
  2358. expected_newly_dead = step_allocs_deallocs[step_idx][1]
  2359. nontensor_args = [expected_newly_alive, expected_newly_dead, is_final_step]
  2360. node = ir.MemoryCheckKernel(
  2361. layout=NoneLayout(device=torch.device("cpu")),
  2362. kernel=torch.ops._inductor_debug.check_memory_step.default,
  2363. tensor_args=[],
  2364. nontensor_args=nontensor_args,
  2365. unflatten_args=lambda tensor_args, constant_args: (
  2366. tensor_args,
  2367. {
  2368. "alive": constant_args[0],
  2369. "dead": constant_args[1],
  2370. "is_final_step": constant_args[2],
  2371. },
  2372. ),
  2373. )
  2374. node.operation_name = f"mem_check_{self.nodes[step_idx].get_name()}"
  2375. return ExternKernelSchedulerNode(self, node)
  2376. new_nodes = []
  2377. for i, node in enumerate(self.nodes):
  2378. new_nodes.append(node)
  2379. new_nodes.append(
  2380. construct_mem_check_node(i, is_final_step=(i == len(self.nodes) - 1))
  2381. )
  2382. self.nodes = new_nodes
  2383. def dead_node_elimination(self) -> None:
  2384. """
  2385. Remove any nodes without users
  2386. """
  2387. # self.nodes is in topological order, so by iterating in reverse order
  2388. # we have visited (and potentially removed) all users before visiting a
  2389. # given node.
  2390. updated_nodes = []
  2391. for node in reversed(self.nodes):
  2392. def can_eliminate_user(user: NodeUser) -> bool:
  2393. return user.is_weak or user.get_name() in V.graph.removed_operations
  2394. active_buffers = False
  2395. for buf in node.get_outputs():
  2396. can_eliminate = all(can_eliminate_user(u) for u in buf.users)
  2397. if can_eliminate:
  2398. log.debug("removed dead buffer: %s", buf.get_name())
  2399. V.graph.removed_buffers.add(buf.get_name())
  2400. else:
  2401. active_buffers = True
  2402. can_eliminate = not node.has_side_effects() and not active_buffers
  2403. if not can_eliminate:
  2404. updated_nodes.append(node)
  2405. else:
  2406. # dead code
  2407. log.debug("removed dead operation: %s", node.get_name())
  2408. V.graph.removed_operations.add(node.get_name())
  2409. for read in node.read_writes.reads:
  2410. if read.name in self.name_to_buf:
  2411. users = self.name_to_buf[read.name].users
  2412. self.name_to_buf[read.name].users = [
  2413. u for u in users if u.node.get_name() != node.get_name()
  2414. ]
  2415. self.nodes = list(reversed(updated_nodes))
  2416. # Prune any WeakDeps no longer needed
  2417. for node in self.nodes:
  2418. node.prune_weak_deps()
  2419. def topological_sort_schedule(
  2420. self, nodes: list[BaseSchedulerNode]
  2421. ) -> list[BaseSchedulerNode]:
  2422. """
  2423. Ensure nodes is in topologically sorted order
  2424. """
  2425. seen = OrderedSet[BaseSchedulerNode]()
  2426. name_to_node: dict[str, BaseSchedulerNode] = dict()
  2427. result: list[BaseSchedulerNode] = []
  2428. def visit(n: BaseSchedulerNode) -> None:
  2429. if n not in seen:
  2430. seen.add(n)
  2431. for dep in sorted(n.unmet_dependencies, key=lambda d: d.name):
  2432. # We only care about doing toposort within `nodes`
  2433. if dep.name not in name_to_node:
  2434. continue
  2435. visit(name_to_node[dep.name])
  2436. result.append(n)
  2437. for node in nodes:
  2438. for name in node.get_buffer_names():
  2439. name_to_node[name] = node
  2440. for node in nodes:
  2441. visit(node)
  2442. return result
  2443. def _get_unmet_dep_nodes(self, snode: BaseSchedulerNode) -> list[BaseSchedulerNode]:
  2444. unmet_deps: OrderedSet[str] = OrderedSet()
  2445. if isinstance(
  2446. snode,
  2447. (
  2448. SchedulerNode,
  2449. ExternKernelSchedulerNode,
  2450. NopKernelSchedulerNode,
  2451. FusedSchedulerNode,
  2452. ),
  2453. ):
  2454. for dep in snode.unmet_dependencies:
  2455. unmet_deps.add(dep.name)
  2456. else:
  2457. raise RuntimeError(
  2458. f"get_unmet_dep_nodes is not implemented for {type(snode)}."
  2459. )
  2460. unmet_dep_ops = (self.name_to_buf[dep].defining_op_name() for dep in unmet_deps)
  2461. return list(OrderedSet(self.name_to_fused_node[n] for n in unmet_dep_ops))
  2462. def _topological_sort_nodes(self) -> list[list[BaseSchedulerNode]]:
  2463. """
  2464. Sort nodes by their topological order, return a list of node lists.
  2465. """
  2466. order = []
  2467. nodes = dict.fromkeys(self.nodes, 0)
  2468. children: dict[Any, Any] = {}
  2469. for node in self.nodes:
  2470. deps = self._get_unmet_dep_nodes(node)
  2471. nodes[node] = len(deps)
  2472. for dep in deps:
  2473. c = children.get(dep, [])
  2474. c.append(node)
  2475. children[dep] = c
  2476. zero_deg_nodes = [n for n, v in nodes.items() if v == 0]
  2477. while zero_deg_nodes:
  2478. order.append(zero_deg_nodes)
  2479. for n in zero_deg_nodes:
  2480. for user in children.get(n, []):
  2481. nodes[user] -= 1
  2482. nodes.pop(n)
  2483. zero_deg_nodes = [n for n, v in nodes.items() if v == 0]
  2484. assert not nodes, "Topological sort failed!"
  2485. return order
  2486. def compute_ancestors(self) -> None:
  2487. """
  2488. Populate each node.ancestors
  2489. """
  2490. # note self.nodes is topologically sorted
  2491. name_to_ancestors: dict[str, OrderedSet[str]] = {}
  2492. for node in self.nodes:
  2493. ancestors: OrderedSet[str] = OrderedSet()
  2494. for dep in node.unmet_dependencies:
  2495. dep_node_name = self.name_to_buf[dep.name].defining_op_name()
  2496. ancestors.add(dep_node_name)
  2497. ancestors |= name_to_ancestors[dep_node_name]
  2498. name_to_ancestors[node.get_name()] = ancestors
  2499. node.ancestors = ancestors
  2500. for order, node in enumerate(self.nodes):
  2501. node.min_order = order
  2502. node.max_order = order
  2503. def merge_loops(self) -> None:
  2504. if not config.loop_ordering_after_fusion:
  2505. return
  2506. for node in self.nodes:
  2507. # Even for CPU, if we are using the halide backend, we still need
  2508. # the merge loops steps below
  2509. if not isinstance(node, (SchedulerNode, FusedSchedulerNode)) or (
  2510. not node.is_gpu() and config.cpu_backend != "halide"
  2511. ):
  2512. continue
  2513. for snode in node.get_nodes():
  2514. # merge loops for the scheduler node
  2515. if not isinstance(snode, SchedulerNode) or snode.is_template():
  2516. continue
  2517. snode.merge_loops()
  2518. # Note that for CPU backend, merging loops will change
  2519. # snode.group. It's fine for Triton backend.
  2520. # But if we simplify update snode.group like this:
  2521. # group_fn = self.get_backend(snode.node.get_device()).group_fn
  2522. # snode.group = (snode.node.get_device(), group_fn(snode._sizes))
  2523. # There is still an issue due to different snode in a
  2524. # FusedSchedulerNode having different merged loops.
  2525. # Skip CPU backend for now.
  2526. def fuse_nodes(self, nodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
  2527. """
  2528. Combine eligible nodes into FusedSchedulerNodes.
  2529. """
  2530. with dynamo_timed(
  2531. "Scheduler.fused_nodes", log_pt2_compile_event=True, log_waitcounter=True
  2532. ):
  2533. for i in range(10):
  2534. old_len = len(nodes)
  2535. fusion_log.debug(
  2536. "===== attempting fusion (%d/10): %d nodes =====",
  2537. i + 1,
  2538. old_len,
  2539. )
  2540. nodes = self.fuse_nodes_once(nodes)
  2541. new_len = len(nodes)
  2542. fusion_log.debug(
  2543. "completed fusion round (%d/10): fused %d nodes into %d nodes\n",
  2544. i + 1,
  2545. old_len,
  2546. new_len,
  2547. )
  2548. if new_len == old_len or new_len == 1:
  2549. fusion_log.debug(
  2550. "===== fusion complete (%d iterations) =====", i + 1
  2551. )
  2552. break
  2553. return nodes
  2554. def process_grouped_nodes(self) -> None:
  2555. """
  2556. Unpack GroupedSchedulerNode into regular nodes.
  2557. """
  2558. new_nodes: list[BaseSchedulerNode] = []
  2559. for node in self.nodes:
  2560. new_nodes.extend(
  2561. node.unpack() if isinstance(node, GroupedSchedulerNode) else [node]
  2562. )
  2563. self.nodes = new_nodes
  2564. def benchmark_fused_nodes(
  2565. self, nodes: Sequence[BaseSchedulerNode]
  2566. ) -> tuple[float, str]:
  2567. """
  2568. Benchmark fused list of nodes and return the execution time
  2569. in milliseconds on randomly generated inputs.
  2570. """
  2571. assert len(nodes) > 0
  2572. device = nodes[0].get_device()
  2573. self.current_device = device
  2574. backend = self.get_backend(device)
  2575. with dynamo_timed(
  2576. "benchmark_fused_nodes",
  2577. log_pt2_compile_event=True,
  2578. dynamo_compile_column_us="compile_time_autotune_time_us",
  2579. ):
  2580. return backend.benchmark_fused_nodes(nodes)
  2581. def generate_kernel_code_from_nodes(
  2582. self,
  2583. nodes: Sequence[BaseSchedulerNode],
  2584. benchmark_kernel: bool,
  2585. hint_override: Optional[int] = None,
  2586. ) -> str:
  2587. """
  2588. Benchmark fused list of nodes and return the execution time
  2589. in milliseconds on randomly generated inputs.
  2590. """
  2591. assert len(nodes) > 0
  2592. device = nodes[0].get_device()
  2593. self.current_device = device
  2594. backend = self.get_backend(device)
  2595. with dynamo_timed("benchmark_fused_nodes"):
  2596. return backend.generate_kernel_code_from_nodes(
  2597. nodes, benchmark_kernel, hint_override=hint_override
  2598. )
  2599. def benchmark_codegened_module(
  2600. self, module: ModuleType, device: torch.device
  2601. ) -> tuple[float, str]:
  2602. """
  2603. Benchmark fused list of nodes and return the execution time
  2604. in milliseconds on randomly generated inputs.
  2605. """
  2606. self.current_device = device
  2607. backend = self.get_backend(device)
  2608. with dynamo_timed("benchmark_fused_nodes"):
  2609. return backend.benchmark_codegened_module(module)
  2610. def finalize_multi_template_buffers(self) -> None:
  2611. """
  2612. Finalize a backing choice for MultiTemplateBuffers which did not already have a
  2613. choice finalized through fusion. In the case of an extern choice, this will result
  2614. in replacing the SchedulerNode.
  2615. If a MultiTemplateBuffer did not have any fusion opportunities, finalizing a choice
  2616. will force completion of compilation and benchmarking.
  2617. """
  2618. def replace_operation_buffer(
  2619. orig_node: ir.MultiTemplateBuffer, new_node: ir.OperationBuffer
  2620. ) -> None:
  2621. replaced_buf_name = new_node.get_name()
  2622. orig_buf_name = orig_node.get_name()
  2623. assert isinstance(orig_buf_name, str) and isinstance(replaced_buf_name, str)
  2624. replaced_op_name = new_node.get_operation_name()
  2625. orig_op_name = orig_node.get_operation_name()
  2626. assert isinstance(orig_op_name, str) and isinstance(replaced_op_name, str)
  2627. del V.graph.name_to_buffer[replaced_buf_name]
  2628. new_node.name = orig_buf_name
  2629. del V.graph.name_to_op[replaced_op_name]
  2630. new_node.operation_name = orig_op_name
  2631. orig = V.graph.buffers.index(orig_node)
  2632. V.graph.buffers.remove(new_node)
  2633. V.graph.buffers[orig] = new_node
  2634. V.graph.name_to_buffer[orig_buf_name] = new_node
  2635. orig = V.graph.operations.index(orig_node)
  2636. V.graph.operations.remove(new_node)
  2637. V.graph.operations[orig] = new_node
  2638. V.graph.name_to_op[orig_op_name] = new_node
  2639. for i, node in enumerate(self.nodes):
  2640. if isinstance(node, SchedulerNode) and isinstance(
  2641. node.node, ir.MultiTemplateBuffer
  2642. ):
  2643. multi_node = node.node
  2644. if not config.test_configs.force_extern_kernel_in_multi_template:
  2645. min_node_unfused, _ = multi_node.get_min_choice()
  2646. else:
  2647. min_node_unfused = next(
  2648. (
  2649. timing
  2650. for timing in multi_node.choice_timings()
  2651. if isinstance(
  2652. timing,
  2653. torch._inductor.select_algorithm.ExternKernelCaller,
  2654. )
  2655. ),
  2656. )
  2657. if isinstance(
  2658. min_node_unfused,
  2659. torch._inductor.ir.TritonTemplateCallerBase,
  2660. ):
  2661. if config.multi_kernel_hints:
  2662. callers: dict[Optional[int], TritonTemplateCallerBase] = {}
  2663. callers[None] = min_node_unfused
  2664. for hint in config.multi_kernel_hints:
  2665. timings = multi_node.choice_timings(hint_override=hint)
  2666. triton_timings = {
  2667. k: v
  2668. for k, v in timings.items()
  2669. if isinstance(k, TritonTemplateCallerBase)
  2670. }
  2671. choice = min(triton_timings.items(), key=lambda x: x[1])[0]
  2672. callers[hint] = choice
  2673. node.node.finalize_as_triton_callers(callers)
  2674. else:
  2675. node.node.finalize_as_triton_caller(min_node_unfused)
  2676. continue
  2677. out_tensorbox = min_node_unfused.output_node()
  2678. out_storage = out_tensorbox.data # type: ignore[union-attr]
  2679. assert isinstance(out_storage, ir.StorageBox)
  2680. out_buffer = out_storage.data
  2681. assert isinstance(out_buffer, ir.OperationBuffer)
  2682. out_buffer.layout = multi_node.layout
  2683. replace_operation_buffer(multi_node, out_buffer)
  2684. new_scheduler_node = self.create_scheduler_node(out_buffer)
  2685. self.nodes[i] = new_scheduler_node
  2686. self.name_to_node[node.get_name()] = new_scheduler_node
  2687. self.name_to_fused_node[node.get_name()] = new_scheduler_node
  2688. # We need to reflect the mutation renames that were recorded in the original node
  2689. mutation_renames = {}
  2690. for dep in itertools.chain(
  2691. node.read_writes.reads, node.unmet_dependencies
  2692. ):
  2693. if real_name := self.mutation_real_name.get(dep.name, None):
  2694. mutation_renames[real_name] = dep.name
  2695. def rename_deps(deps: OrderedSet[Dep]) -> OrderedSet[Dep]:
  2696. return OrderedSet(dep.rename(mutation_renames) for dep in deps)
  2697. new_scheduler_node.unmet_dependencies = rename_deps(
  2698. new_scheduler_node.unmet_dependencies
  2699. )
  2700. new_scheduler_node.read_writes.reads = rename_deps(
  2701. new_scheduler_node.read_writes.reads
  2702. )
  2703. for new_out, old_out in zip(
  2704. new_scheduler_node.get_outputs(), node.get_outputs()
  2705. ):
  2706. self.name_to_buf[old_out.get_name()] = new_out
  2707. new_out.users = old_out.users
  2708. new_scheduler_node.min_order = node.min_order
  2709. new_scheduler_node.max_order = node.max_order
  2710. new_scheduler_node.last_usage = node.last_usage
  2711. def _any_atomic_add(self, node_list: Sequence[BaseSchedulerNode]) -> bool:
  2712. return any(
  2713. hasattr(n.node, "data")
  2714. and n.node is not None
  2715. and hasattr(n.node.data, "scatter_mode")
  2716. and n.node.data.scatter_mode == "atomic_add"
  2717. for n in node_list
  2718. )
  2719. def speedup_by_fusion(
  2720. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  2721. ) -> Union[bool, Callable[[], bool]]:
  2722. """
  2723. If config.benchmark_fusion is False, always return True.
  2724. Otherwise, return True if fusion can brings speedup.
  2725. """
  2726. is_multi_template = any(
  2727. n.is_template()
  2728. and isinstance(n.get_template_node(), ir.MultiTemplateBuffer)
  2729. for n in (node1, node2)
  2730. )
  2731. if not config.benchmark_fusion and not is_multi_template:
  2732. return True
  2733. if (
  2734. node1.is_template()
  2735. and not isinstance(node1.get_template_node(), ir.TritonTemplateBuffer)
  2736. or node1.is_foreach()
  2737. or node2.is_foreach()
  2738. ):
  2739. # TODO support benchmarking epilogue fusion
  2740. return True
  2741. node_list_1 = node1.get_nodes()
  2742. device = node_list_1[0].get_device()
  2743. assert device
  2744. # don't support benchmark fusion for CPU right now.
  2745. if device.type == "cpu":
  2746. return True
  2747. node_list_2 = node2.get_nodes()
  2748. node_list_fused = list(itertools.chain(node_list_1, node_list_2))
  2749. # We can not accurately benchmark kernel using atomic_add
  2750. # due to how we generate random integer inputs.
  2751. # Skip benchmarking them by allowing fusion.
  2752. if self._any_atomic_add(node_list_fused):
  2753. return True
  2754. from triton.compiler.errors import CompilationError
  2755. why = WhyNoFuse(node1, node2)
  2756. device = node_list_fused[0].get_device()
  2757. assert device is not None
  2758. def log_fusion(ms_fused: float, ms1: float, ms2: float) -> None:
  2759. if fusion_log.isEnabledFor(logging.DEBUG):
  2760. if ms_fused < ms1 + ms2:
  2761. fusion_log.debug(
  2762. "can fuse (benchmark): fusing %s with %s cause %sx speedup",
  2763. node1.get_buffer_names(),
  2764. node2.get_buffer_names(),
  2765. green_text(f"{(ms1 + ms2) / ms_fused:.3f}"),
  2766. )
  2767. else:
  2768. fusion_log.debug(
  2769. "cannot fuse (benchmark): fusing %s with %s cause %sx slowdown",
  2770. node1.get_buffer_names(),
  2771. node2.get_buffer_names(),
  2772. red_text(f"{ms_fused / (ms1 + ms2):.3f}"),
  2773. )
  2774. async_compile = torch._inductor.async_compile.AsyncCompile()
  2775. def compile_kernel(
  2776. nodes: Sequence[BaseSchedulerNode], hint_override: Optional[int] = None
  2777. ) -> tuple[Optional[LambdaFuture], ModuleType]:
  2778. src_code = self.generate_kernel_code_from_nodes(
  2779. nodes, benchmark_kernel=True, hint_override=hint_override
  2780. )
  2781. mod = PyCodeCache.load(src_code)
  2782. if not async_compile.use_process_pool():
  2783. fut = None
  2784. else:
  2785. fut = async_compile.triton(kernel_name="triton_", source_code=src_code)
  2786. assert isinstance(fut, LambdaFuture)
  2787. return (fut, mod)
  2788. if is_multi_template and any(
  2789. n.get_template_node() is not None for n in (node1, node2)
  2790. ):
  2791. epilogue_fusion = node1.get_template_node() is not None
  2792. multi_node = (
  2793. node1.get_template_node()
  2794. if epilogue_fusion
  2795. else node2.get_template_node()
  2796. )
  2797. assert isinstance(multi_node, ir.MultiTemplateBuffer)
  2798. hint_override_best_fusion_choice: dict[
  2799. Optional[int], TritonTemplateCallerBase
  2800. ] = {}
  2801. future_choices: list[tuple[Any, Optional[LambdaFuture], ModuleType]] = []
  2802. for hint_override in config.multi_kernel_hints:
  2803. choice_timings = multi_node.choice_timings(hint_override)
  2804. for choice, unfused_time in sorted(
  2805. choice_timings.items(), key=lambda x: x[1]
  2806. ):
  2807. if not isinstance(
  2808. choice, torch._inductor.select_algorithm.TritonTemplateCaller
  2809. ):
  2810. continue
  2811. with multi_node.swap_as_triton_caller(choice):
  2812. future_choices.append(
  2813. (
  2814. choice,
  2815. *compile_kernel(
  2816. node_list_fused, hint_override=choice.hint_override
  2817. ),
  2818. )
  2819. )
  2820. min_ms_fused = float("inf")
  2821. ms_fused_choice: Optional[TritonTemplateCallerBase] = None
  2822. new_timings = {}
  2823. for choice, future, mod_fused in future_choices:
  2824. try:
  2825. if future is not None:
  2826. future.result()
  2827. except Exception as e:
  2828. if fusion_log.isEnabledFor(logging.DEBUG):
  2829. fusion_log.debug(
  2830. "Exception in compiling %s: %s",
  2831. "prologue" if not epilogue_fusion else "epilogue",
  2832. str(e),
  2833. )
  2834. continue
  2835. with multi_node.swap_as_triton_caller(choice):
  2836. ms_fused, path = self.benchmark_codegened_module(
  2837. mod_fused, device
  2838. )
  2839. new_timings[choice] = ms_fused
  2840. if ms_fused < min_ms_fused:
  2841. min_ms_fused = ms_fused
  2842. ms_fused_choice = choice
  2843. multi_node._choice_timings[hint_override] = new_timings
  2844. assert isinstance(ms_fused_choice, TritonTemplateCallerBase)
  2845. hint_override_best_fusion_choice[hint_override] = ms_fused_choice
  2846. # Eagerly compile and benchmark non-template nodes
  2847. choice_timings = multi_node.choice_timings()
  2848. _, ms1 = multi_node.get_min_choice()
  2849. ms2, path2 = (
  2850. self.benchmark_fused_nodes(node_list_2)
  2851. if epilogue_fusion
  2852. else self.benchmark_fused_nodes(node_list_1)
  2853. )
  2854. # Start compiling choices in parallel
  2855. future_choices: list[tuple[Any, Optional[LambdaFuture], ModuleType]] = []
  2856. triton_choices = 0
  2857. for choice, unfused_time in sorted(
  2858. choice_timings.items(), key=operator.itemgetter(1)
  2859. ):
  2860. if not isinstance(choice, torch._inductor.ir.TritonTemplateCallerBase):
  2861. continue
  2862. # For prologue fusion we check if the underlying template of the choice
  2863. # supports all allowed prologue inputs. If not, we skip this choice in
  2864. # the fusion benchmark.
  2865. # TODO: Remove this check after all Triton templates support prologue fusion.
  2866. # Currently, persistent+TMA Triton template does not due to the TMA-based loads.
  2867. if (
  2868. not epilogue_fusion
  2869. and hasattr(choice, "allowed_prologue_inps")
  2870. and choice.allowed_prologue_inps != multi_node.allowed_prologue_inps
  2871. ):
  2872. continue
  2873. if unfused_time >= ms1 + ms2:
  2874. break
  2875. triton_choices += 1
  2876. if triton_choices > config.max_epilogue_benchmarked_choices:
  2877. break
  2878. with multi_node.swap_as_triton_caller(choice):
  2879. future_choices.append((choice, *compile_kernel(node_list_fused)))
  2880. if len(future_choices) == 0:
  2881. return False
  2882. def benchmark_when_ready() -> bool:
  2883. min_ms_fused = float("inf")
  2884. ms_fused_choice = None
  2885. new_timings = {}
  2886. # Benchmark each choice after compilation completes
  2887. for choice, future, mod_fused in future_choices:
  2888. try:
  2889. if future is not None:
  2890. future.result()
  2891. # Ideally we would more narrowly catch Exceptions here but
  2892. # triton will unpredictably error with valid prologue fusions
  2893. except Exception as e:
  2894. if fusion_log.isEnabledFor(logging.DEBUG):
  2895. fusion_log.debug(
  2896. "Exception in compiling %s: %s",
  2897. "prologue" if not epilogue_fusion else "epilogue",
  2898. str(e),
  2899. )
  2900. continue
  2901. with multi_node.swap_as_triton_caller(choice):
  2902. ms_fused, path = self.benchmark_codegened_module(
  2903. mod_fused, device
  2904. )
  2905. new_timings[choice] = ms_fused
  2906. if ms_fused < min_ms_fused:
  2907. min_ms_fused = ms_fused
  2908. ms_fused_choice = choice
  2909. log_fusion(min_ms_fused, ms1, ms2)
  2910. if min_ms_fused < (ms1 + ms2) and ms_fused_choice is not None:
  2911. if config.multi_kernel_hints:
  2912. hint_override_best_fusion_choice[None] = ms_fused_choice
  2913. multi_node.finalize_as_triton_callers(
  2914. hint_override_best_fusion_choice
  2915. )
  2916. else:
  2917. multi_node.finalize_as_triton_caller(ms_fused_choice)
  2918. multi_node._choice_timings[None] = new_timings
  2919. return True
  2920. else:
  2921. return False
  2922. return benchmark_when_ready
  2923. else:
  2924. # Start parallel compilation for all three kernels
  2925. future_and_mod_l1 = compile_kernel(node_list_1)
  2926. future_and_mod_l2 = compile_kernel(node_list_2)
  2927. future_and_mod_l1_fused = compile_kernel(node_list_fused)
  2928. def benchmark_when_ready() -> bool:
  2929. from torch._inductor.runtime.triton_heuristics import (
  2930. NoTritonConfigsError,
  2931. )
  2932. try:
  2933. # Wait for all compilations to complete
  2934. for fut in (
  2935. future_and_mod_l1[0],
  2936. future_and_mod_l2[0],
  2937. future_and_mod_l1_fused[0],
  2938. ):
  2939. if fut is not None:
  2940. fut.result()
  2941. ms1, path1 = self.benchmark_codegened_module(
  2942. future_and_mod_l1[1], device
  2943. )
  2944. if math.isinf(ms1):
  2945. why("register spilling of the first kernel")
  2946. return False
  2947. ms2, path2 = self.benchmark_codegened_module(
  2948. future_and_mod_l2[1], device
  2949. )
  2950. if math.isinf(ms2):
  2951. why("register spilling of the second kernel")
  2952. return False
  2953. ms_fused, path_fused = self.benchmark_codegened_module(
  2954. future_and_mod_l1_fused[1], device
  2955. )
  2956. if math.isinf(ms_fused):
  2957. why("register spilling of the fused kernel")
  2958. return False
  2959. log_fusion(ms_fused, ms1, ms2)
  2960. if (
  2961. is_metric_table_enabled("slow_fusion")
  2962. and ms_fused >= ms1 + ms2
  2963. and (path1, path2) not in self.logged_slow_fusion
  2964. ):
  2965. self.logged_slow_fusion.add((path1, path2))
  2966. get_metric_table("slow_fusion").add_row(
  2967. lambda: {
  2968. "kernel1_path": path1,
  2969. "kernel1_latency": ms1,
  2970. "kernel2_path": path2,
  2971. "kernel2_latency": ms2,
  2972. "fused_kernel_path": path_fused,
  2973. "fused_kernel_latency": ms_fused,
  2974. "slow_down_ratio": ms_fused / (ms1 + ms2),
  2975. }
  2976. )
  2977. return ms_fused < ms1 + ms2
  2978. except NoTritonConfigsError:
  2979. return False
  2980. except CompilationError as e:
  2981. if "Loop-carried variable" in str(e):
  2982. return True
  2983. raise
  2984. return benchmark_when_ready
  2985. def get_fused_node(self, node: BaseSchedulerNode) -> BaseSchedulerNode:
  2986. "Look up the node in Scheduler name_to_fused_node"
  2987. return self.name_to_fused_node[node.get_first_name()]
  2988. def fuse_nodes_once(
  2989. self, nodes: list[BaseSchedulerNode]
  2990. ) -> list[BaseSchedulerNode]:
  2991. """
  2992. Combine eligible nodes into FusedSchedulerNodes.
  2993. This relies on two key functions to control the logic:
  2994. - self.can_fuse(): checks if a fusion is legal
  2995. - self.score_fusion(): assigns priority to a given fusion
  2996. """
  2997. fused_nodes = OrderedSet(nodes)
  2998. if fusion_log.isEnabledFor(logging.DEBUG):
  2999. fusion_log.debug("fuse_nodes_once, candidates:")
  3000. for node in fused_nodes:
  3001. fusion_log.debug(" %s", node.debug_str_short())
  3002. # These are potential fusions which we are async compiling,
  3003. # and which we will benchmark profitability of.
  3004. pending_fusions: dict[
  3005. BaseSchedulerNode,
  3006. tuple[Callable[[], bool], BaseSchedulerNode, BaseSchedulerNode],
  3007. ] = {}
  3008. def fuse_two_nodes(
  3009. node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3010. ) -> BaseSchedulerNode:
  3011. fusion_log.debug("fusing %s with %s", node1.get_name(), node2.get_name())
  3012. device = node1.get_device()
  3013. assert node2.get_device() == device
  3014. node3 = self.get_backend(device).fuse(node1, node2)
  3015. fused_nodes.remove(node1)
  3016. fused_nodes.remove(node2)
  3017. fused_nodes.add(node3)
  3018. self.name_to_fused_node.update(
  3019. {n.get_name(): node3 for n in node3.get_nodes()}
  3020. )
  3021. return node3
  3022. def resolve_pending_fusions(
  3023. node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3024. ) -> None:
  3025. while (
  3026. self.get_fused_node(node1) in pending_fusions
  3027. or self.get_fused_node(node2) in pending_fusions
  3028. ):
  3029. pending_fusion = pending_fusions.get(
  3030. self.get_fused_node(node1),
  3031. pending_fusions.get(self.get_fused_node(node2), None),
  3032. )
  3033. assert pending_fusion is not None
  3034. is_speedup, node_key1, node_key2 = pending_fusion
  3035. pending_fusions.pop(node_key1, None)
  3036. pending_fusions.pop(node_key2, None)
  3037. assert self.get_fused_node(node_key1) is node_key1
  3038. assert self.get_fused_node(node_key2) is node_key2
  3039. if not is_speedup() or self.will_fusion_create_cycle(node1, node2):
  3040. continue
  3041. fuse_two_nodes(node_key1, node_key2)
  3042. for node1, node2 in self.get_possible_fusions(nodes):
  3043. # if either node is in a pending fusion, resolve it.
  3044. # since we iterate on potential fusions based on profitability
  3045. # the first potential fusion should take precedence.
  3046. resolve_pending_fusions(node1, node2)
  3047. node1 = self.get_fused_node(node1)
  3048. node2 = self.get_fused_node(node2)
  3049. if self.can_fuse(node1, node2) and not self.will_fusion_create_cycle(
  3050. node1, node2
  3051. ):
  3052. speedup = self.speedup_by_fusion(node1, node2)
  3053. if callable(speedup):
  3054. pending_fusions[node1] = (speedup, node1, node2)
  3055. pending_fusions[node2] = (speedup, node1, node2)
  3056. continue
  3057. if not speedup:
  3058. continue
  3059. fuse_two_nodes(node1, node2)
  3060. seen_pair_speedup_fn: OrderedSet[Callable[[], bool]] = OrderedSet()
  3061. for is_speedup_fn, node_key1, node_key2 in pending_fusions.values():
  3062. if is_speedup_fn in seen_pair_speedup_fn:
  3063. continue
  3064. seen_pair_speedup_fn.add(is_speedup_fn)
  3065. assert self.get_fused_node(node_key1) is node_key1
  3066. assert self.get_fused_node(node_key2) is node_key2
  3067. if is_speedup_fn() and not self.will_fusion_create_cycle(
  3068. node_key1, node_key2
  3069. ):
  3070. fuse_two_nodes(node_key1, node_key2)
  3071. nodes = sorted(fused_nodes, key=lambda x: x.min_order)
  3072. nodes = self.topological_sort_schedule(nodes)
  3073. self.prune_redundant_deps(nodes)
  3074. return nodes
  3075. def create_combo_kernel_nodes(self, num_ck_nodes: Optional[int] = None) -> None:
  3076. """
  3077. Groups parallel nodes
  3078. """
  3079. fused_nodes = OrderedSet(self.nodes)
  3080. count = 0
  3081. num_nodes_orig = len(self.nodes)
  3082. log.debug("ComboKernels: Generating with num_ck_nodes = %s...", num_ck_nodes)
  3083. for num, node_list in enumerate(
  3084. ForeachKernelSchedulerNode.group_nodes_for_combo_kernels(self)
  3085. ):
  3086. node_list = ForeachKernelSchedulerNode.combinable_nodes(node_list)
  3087. if len(node_list) < 2:
  3088. continue
  3089. if num_ck_nodes is not None and count > num_ck_nodes:
  3090. break
  3091. if not self.speedup_by_combo_kernel(node_list):
  3092. log.debug("ComboKernels: Not speeding up %d-th group", num)
  3093. continue
  3094. count += 1
  3095. enable_autotune = config.combo_kernels_autotune > 0
  3096. group_snode = ForeachKernelSchedulerNode(
  3097. node_list[0].scheduler,
  3098. node_list,
  3099. use_custom_partition_algo=True,
  3100. enable_autotune=enable_autotune,
  3101. )
  3102. log.info(
  3103. "ComboKernels: Combining %d nodes for %d-th group",
  3104. len(node_list),
  3105. num,
  3106. )
  3107. for node in node_list:
  3108. fused_nodes.remove(node)
  3109. fused_nodes.add(group_snode)
  3110. self.name_to_fused_node.update(
  3111. {n.get_name(): group_snode for n in group_snode.get_nodes()}
  3112. )
  3113. self.nodes = sorted(fused_nodes, key=lambda x: x.min_order)
  3114. self.nodes = self.topological_sort_schedule(self.nodes)
  3115. log.info(
  3116. "Generated ComboKernel nodes: %d ComboKernels, totally %d -> %d nodes",
  3117. count,
  3118. num_nodes_orig,
  3119. len(self.nodes),
  3120. )
  3121. self.prune_redundant_deps(self.nodes)
  3122. def prune_redundant_deps(self, nodes: list[BaseSchedulerNode]) -> None:
  3123. for node in nodes:
  3124. node.prune_redundant_deps(self.name_to_fused_node)
  3125. def get_possible_fusions(
  3126. self, nodes: list[BaseSchedulerNode]
  3127. ) -> list[tuple[BaseSchedulerNode, BaseSchedulerNode]]:
  3128. """
  3129. Helper to find all legal fusion opportunities, sorted by self.score_fusion()
  3130. """
  3131. possible_fusions = []
  3132. seen = OrderedSet[tuple[BaseSchedulerNode, BaseSchedulerNode]]()
  3133. def check_all_pairs(nodes: list[BaseSchedulerNode]) -> None:
  3134. for node1_index, node1 in enumerate(nodes):
  3135. for node2 in nodes[
  3136. node1_index + 1 : node1_index
  3137. + 1
  3138. + config.max_fusion_buffer_group_pairwise_attempts
  3139. ]:
  3140. key = (node1, node2)
  3141. if key in seen:
  3142. continue
  3143. seen.add(key)
  3144. if self.can_fuse(node1, node2):
  3145. possible_fusions.append(key)
  3146. elif (node2.is_template() or node2.is_foreach()) and self.can_fuse(
  3147. node2, node1
  3148. ):
  3149. # foreach fusions and epilogue fusions are order dependent
  3150. possible_fusions.append((node2, node1))
  3151. buffer_names_grouping = collections.defaultdict(list)
  3152. for node in nodes:
  3153. if self.unfusable_node(node):
  3154. continue
  3155. for buf in node.used_buffer_names():
  3156. buffer_names_grouping[buf].append(node)
  3157. for node_grouping in buffer_names_grouping.values():
  3158. check_all_pairs(node_grouping)
  3159. if config.aggressive_fusion:
  3160. group_grouping = collections.defaultdict(list)
  3161. for node in nodes:
  3162. group = getattr(node, "group", None)
  3163. if group:
  3164. group_grouping[group].append(node)
  3165. for node_grouping in group_grouping.values():
  3166. check_all_pairs(node_grouping)
  3167. possible_fusions = self.get_possible_fusions_with_highest_priority(
  3168. possible_fusions
  3169. )
  3170. possible_fusions.sort(key=self.score_fusion_key, reverse=True)
  3171. fusion_log.debug("found %d possible fusions", len(possible_fusions))
  3172. return possible_fusions
  3173. def will_fusion_create_cycle(
  3174. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3175. ) -> bool:
  3176. """
  3177. Finds whether there's a path from node1 to node2 (or vice-versa)
  3178. caused indirectly by other fusions.
  3179. """
  3180. # since we are just returning boolean here, use slightly faster, unordered set
  3181. visited = OrderedSet[FusedSchedulerNode]()
  3182. def found_path(node: BaseSchedulerNode) -> bool:
  3183. # only fused nodes can introduce new ancestors.
  3184. if isinstance(node, FusedSchedulerNode) and node not in visited:
  3185. visited.add(node)
  3186. if node.get_operation_names().issubset(combined_ancestors):
  3187. # All fusion outputs are in ancestors of node1 and node2, thus
  3188. # cannot introduce new path:
  3189. #
  3190. # 1. if output is neither descendent of node1 or node2, the
  3191. # output cannot introduce a path
  3192. # 2. due to [can_fuse]: if WLOG output is descendent of node1, it cannot be
  3193. # on path(node1->node2), hence it cannot be ancestor of node2
  3194. # 3. due to [acyclic]: if WLOG output is descendent of node1, it cannot be
  3195. # ancestor of node1
  3196. return False
  3197. else:
  3198. # continue DFS of new ancestors introduced by the fusion
  3199. return bool(combined_names & node.ancestors) or any(
  3200. found_path(self.name_to_fused_node[n])
  3201. for n in node.ancestors - combined_ancestors
  3202. )
  3203. return False
  3204. # as above - use slightly faster, unordered set
  3205. combined_names = (
  3206. node1.get_operation_names()._dict.keys()
  3207. | node2.get_operation_names()._dict.keys()
  3208. )
  3209. combined_ancestors = (
  3210. node1.ancestors._dict.keys() | node2.ancestors._dict.keys()
  3211. ) - combined_names
  3212. cycle = any(found_path(self.name_to_fused_node[n]) for n in combined_ancestors)
  3213. if cycle:
  3214. WhyNoFuse(node1, node2)("will create cycle")
  3215. return cycle
  3216. def can_fusion_increase_peak_memory(
  3217. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3218. ) -> bool:
  3219. """
  3220. Return true if fusing the two nodes can potentially increasing peak memory.
  3221. The implementation is more like a heuristic since we don't really know if we are at peak
  3222. or not when trying to fuse these two nodes. The order of nodes may change later which makes the
  3223. peak memory estimation hard.
  3224. Here is how we decide the LOWER BOUND of extra memory allocation if we fuse these 2 nodes:
  3225. 1. find all buffers read by each node with a single user. These buffers are supposed to
  3226. be reused if we don't fuses these 2 nodes
  3227. 2. find the intersection of these buffers for the two node and sum the total buffer size.
  3228. If we don't fuse these two nodes, we can at lease avoid this much memory allocation.
  3229. Note that the extra memory allocation is not necessarily causing peak memory increase.
  3230. This is just a heuristic.
  3231. We return true only if the saving for fusion can not trade off the extra memory allocation.
  3232. """
  3233. from .codegen.wrapper import buffer_reuse_key
  3234. def _find_single_user_inputs(
  3235. node: BaseSchedulerNode,
  3236. ) -> list[ir.Buffer]:
  3237. output = []
  3238. for rd in node.read_writes.reads:
  3239. buf = self.name_to_buf.get(rd.name)
  3240. if buf and len(buf.users) == 1 and buf.node.has_tensor_output():
  3241. output.append(buf.node)
  3242. return output
  3243. # Check inputs that can be potentially reused
  3244. lhs_dep_nodes = _find_single_user_inputs(node1)
  3245. rhs_dep_nodes = _find_single_user_inputs(node2)
  3246. lhs_reuse_keys = OrderedSet(buffer_reuse_key(buf) for buf in lhs_dep_nodes)
  3247. rhs_reuse_keys = OrderedSet(buffer_reuse_key(buf) for buf in rhs_dep_nodes)
  3248. common_reuse_keys = lhs_reuse_keys.intersection(rhs_reuse_keys)
  3249. memory_overhead = 0
  3250. for key in common_reuse_keys:
  3251. try:
  3252. memory_overhead += int(key[2])
  3253. except ValueError:
  3254. # not an integer. Fallback is to fuse
  3255. return False
  3256. bw_saving = self.score_fusion_memory(node1, node2)
  3257. # The factor 32 here is quite arbitrary.
  3258. if V.graph.sizevars.statically_known_gt(memory_overhead, 32 * bw_saving):
  3259. return True
  3260. return False
  3261. def fusion_accumulate_large_reads(
  3262. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode, threshold: int
  3263. ) -> bool:
  3264. all_reads = (node1.read_writes.reads | node2.read_writes.reads) - (
  3265. node1.read_writes.writes | node2.read_writes.writes
  3266. )
  3267. return sum(self.dep_size_hint(dep) for dep in all_reads) > threshold
  3268. def are_long_distant_nodes(
  3269. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3270. ) -> bool:
  3271. """
  3272. This function prevents fusion for nodes that can increase memory
  3273. footprint. This problem is more common in horizontal fusion, where nodes
  3274. that are far apart in the original order get fused, lengthening the live
  3275. intervals of tensors. This is very evident in models with activation
  3276. checkpointing, where the recomputed nodes from different checkpointed
  3277. regions get fused and significantly increase the memory footprint.
  3278. The current attempt is a quick, possibly hacky, heuristic to prevent the
  3279. fusion of nodes that are far away in the original order.
  3280. A better but difficult to implement heurisitic would be to use live
  3281. intervals of the buffers, find region of peak pressure in the original
  3282. program and prevent fusion that crosses that peak region. We might need
  3283. special care or good approximation in this implementation, as fusion of
  3284. node changes live intervals, and re-computing live intervals and peak
  3285. memory after each fusion can introduce large compilation overhead.
  3286. """
  3287. proximity_score = max(
  3288. abs(node1.min_order - node2.max_order),
  3289. abs(node2.min_order - node1.max_order),
  3290. )
  3291. return proximity_score > 64
  3292. def decide_fusion_fail_reason(
  3293. self,
  3294. node1: BaseSchedulerNode,
  3295. node2: BaseSchedulerNode,
  3296. common_buf_names: Union[tuple[str], OrderedSet[str]],
  3297. ) -> str:
  3298. """
  3299. Try to decide reasons why fusion fail due to no shared memory even though
  3300. there are common buffers.
  3301. """
  3302. reasons = {}
  3303. node1_name2dep = {dep.name: dep for dep in node1.read_writes.reads_and_writes()}
  3304. node2_name2dep = {dep.name: dep for dep in node2.read_writes.reads_and_writes()}
  3305. for buf_name in common_buf_names:
  3306. buf = V.graph.get_buffer(buf_name)
  3307. lhs_dep = node1_name2dep[buf_name]
  3308. rhs_dep = node2_name2dep[buf_name]
  3309. if not isinstance(lhs_dep, MemoryDep) or not isinstance(rhs_dep, MemoryDep):
  3310. reasons[buf_name] = (
  3311. f"not MemoryDep: {type(lhs_dep)} v.s. {type(rhs_dep)}"
  3312. )
  3313. continue
  3314. if lhs_dep.get_numel() != rhs_dep.get_numel():
  3315. reasons[buf_name] = (
  3316. f"different numel: {lhs_dep.get_numel()} v.s. {rhs_dep.get_numel()}"
  3317. )
  3318. continue
  3319. # same numel but different MemoryDep.size. Should be broadcasting
  3320. if sympy_product(lhs_dep.size) != sympy_product(rhs_dep.size):
  3321. reasons[buf_name] = "broadcast"
  3322. continue
  3323. lhs_off = lhs_dep.get_offset()
  3324. rhs_off = rhs_dep.get_offset()
  3325. if lhs_off != rhs_off:
  3326. # One example is in transformer, we use a concatenated linear layer
  3327. # to project Q/K/V and then split the result. The 3 splits will
  3328. # point to the same buffer with different offsets.
  3329. reasons[buf_name] = f"different offset: {lhs_off} v.s. {rhs_off}"
  3330. continue
  3331. if (
  3332. lhs_dep.normalize_with_stride_order()
  3333. == rhs_dep.normalize_with_stride_order()
  3334. ):
  3335. reasons[buf_name] = f"Mismatch loop orders: {lhs_dep} v.s. {rhs_dep}"
  3336. continue
  3337. # Add more rules here
  3338. layout_str = ""
  3339. if not isinstance(buf, ir.TorchBindObject):
  3340. layout_str = f"Layout: {buf.layout}"
  3341. reasons[buf_name] = (
  3342. f"Unknown reason: {lhs_dep} v.s. {rhs_dep}. {layout_str}"
  3343. )
  3344. return str(reasons)
  3345. def shared_data_after_reordering_loop(
  3346. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3347. ) -> int:
  3348. """
  3349. Right now just greedily reorder the loop of node1 to be compatible with node2,
  3350. but ideally we should have some heuristics to reorder the loop for node2
  3351. to be compatible with node1 if that's more efficient.
  3352. Return the amount of shared data re-computed in this method.
  3353. If no such recomputation happens, return -1 (not return 0 since 0 is a valid
  3354. amount of shared data).
  3355. """
  3356. # TODO Don't do loop reordering for CPU for now.
  3357. # Should debug more why it does not work for CPU codegen
  3358. if not config.loop_ordering_after_fusion or any(
  3359. n.is_cpu() for n in [node1, node2]
  3360. ):
  3361. return -1
  3362. # in some rare case, a template can be passed in.
  3363. # Check test_interaction_with_multi_template in test_loop_ordering.py
  3364. # and https://github.com/pytorch/pytorch/issues/165579
  3365. if node1.is_template() or node2.is_template():
  3366. return -1
  3367. node1_buffer_names = node1.read_writes.buffer_names()
  3368. node2_buffer_names = node2.read_writes.buffer_names()
  3369. # Fast path: no common buffers.
  3370. common_buffer_names = node1_buffer_names & node2_buffer_names
  3371. if not common_buffer_names:
  3372. return -1
  3373. node1_name2dep = {dep.name: dep for dep in node1.read_writes.reads_and_writes()}
  3374. node2_name2dep = {dep.name: dep for dep in node2.read_writes.reads_and_writes()}
  3375. # Find the commons buffers that has different loop orders
  3376. candidates = []
  3377. for buffer_name in common_buffer_names:
  3378. lhs_dep = node1_name2dep[buffer_name]
  3379. rhs_dep = node2_name2dep[buffer_name]
  3380. if (
  3381. lhs_dep.normalize_with_stride_order()
  3382. == rhs_dep.normalize_with_stride_order()
  3383. ):
  3384. candidates.append(
  3385. (
  3386. V.graph.sizevars.size_hint(lhs_dep.get_numel(), fallback=0),
  3387. lhs_dep,
  3388. rhs_dep,
  3389. )
  3390. )
  3391. if len(candidates) == 0:
  3392. return -1
  3393. # Pick the largest buffer to guide the loop reordering
  3394. _numel, lhs_dep, rhs_dep = max(candidates, key=operator.itemgetter(0))
  3395. if not isinstance(lhs_dep, MemoryDep) or not isinstance(rhs_dep, MemoryDep):
  3396. return -1
  3397. if lhs_dep.num_vars != rhs_dep.num_vars:
  3398. # this can happen due to we don't merge loops.
  3399. # We can not do loop reordering in this case right now
  3400. # Simply returning true if the two Deps are the same after
  3401. # normalization (merging loops)
  3402. if lhs_dep.normalize() == rhs_dep.normalize():
  3403. return self.dep_size_hint(lhs_dep)
  3404. return -1
  3405. reordered = False
  3406. # Only reorder loops for pointwise for now
  3407. if not node1.is_reduction():
  3408. reordered = node1.reorder_loops_by_dep_pair(lhs_dep, rhs_dep)
  3409. elif not node2.is_reduction():
  3410. reordered = node2.reorder_loops_by_dep_pair(rhs_dep, lhs_dep)
  3411. else:
  3412. loop_ordering_log.debug(
  3413. "Don't reorder loops since both nodes are reductions: %s v.s. %s",
  3414. node1.get_name(),
  3415. node2.get_name(),
  3416. )
  3417. return self.score_fusion_memory(node1, node2) if reordered else -1
  3418. def unfusable_node(self, node: BaseSchedulerNode) -> bool:
  3419. """
  3420. Is this node unfusable under any conditions.
  3421. """
  3422. return (
  3423. isinstance(node, (ExternKernelSchedulerNode, NopKernelSchedulerNode))
  3424. and not node.is_template()
  3425. and not is_output_of_multi_outputs_template(node.node)
  3426. )
  3427. def check_prologue_fusion_heuristics_fusable(
  3428. self,
  3429. prologue_node: BaseSchedulerNode,
  3430. template_node: BaseSchedulerNode,
  3431. why: WhyNoFuse,
  3432. ) -> bool:
  3433. """
  3434. Heuristics to avoid benchmarking predictably slow prologue fusions
  3435. """
  3436. # user opt into more aggressive prologue fusion, dont use heuristics
  3437. if prologue_node.get_operation_names() <= V.graph.invoke_quant_ops:
  3438. return True
  3439. read_bytes = prologue_node.get_read_buffer_sizes()
  3440. write_bytes = prologue_node.get_write_buffer_sizes()
  3441. # Initially, only do fusions which will result in fewer memory accesses inside of the template to avoid
  3442. # potential bad cache behavior and shared memory use.
  3443. # we also want to avoid benchmarking reliably unprofitable fusions like downcasts from fp32 -> fp16 inside kernel.
  3444. # allowing gathers by allowing increasing write_bytes by small factor
  3445. # TODO - make configurable per input, for instance, bias can fuse fp32 -> fp16 profitably
  3446. BYTES_THRESHOLD_MULTIPLIER = 1.1
  3447. if read_bytes > (write_bytes * BYTES_THRESHOLD_MULTIPLIER):
  3448. why("prologue fusion will not increase amount of bytes read in kernel")
  3449. return False
  3450. # we want to avoid attempting to fuse predictably unprofitable prologues
  3451. # such as increasing the unaligned reads or writes.
  3452. # TODO - would be nice to generalize this, however, we would need more explicit
  3453. # knowledge of memory access patterns in the TritonTemplate in order to know
  3454. # the stride order to check alignment.
  3455. origins = tuple(
  3456. e.target
  3457. for n in prologue_node.get_nodes()
  3458. if n.node is not None
  3459. for e in n.node.get_origins()
  3460. if e.op == "call_function"
  3461. )
  3462. if origins == (torch.ops.aten.constant_pad_nd.default,):
  3463. why(
  3464. "prologue fusion will not increase attempt to fuse in padding bc it increases unaligned reads"
  3465. )
  3466. return False
  3467. def low_prec_fp(dtype: torch.dtype) -> bool:
  3468. return dtype.itemsize <= 2 and dtype.is_floating_point
  3469. if (
  3470. low_prec_fp(template_node.get_template_node_or_throw().dtype)
  3471. and not prologue_node.can_codegen_in_low_precision()
  3472. ):
  3473. why(
  3474. "prologue fusion that must be upcast to fp32 not profitable for low precision templates"
  3475. )
  3476. return False
  3477. return True
  3478. def get_expand_dim_for_pointwise_nodes(
  3479. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3480. ) -> Optional[tuple[int, SchedulerNode, sympy.Expr]]:
  3481. """
  3482. Fusing two small pointwise nodes significantly reduces kernel overhead
  3483. and launch overhead. However, slightly different sizes would prevent fusion.
  3484. Here, we decide if expanding sizes of one node is profitible by allowing
  3485. fusion, and returns the dimension to expand, node with smaller sizes,
  3486. and new size after expand.
  3487. """
  3488. # only support scheduler node
  3489. if not isinstance(node1, SchedulerNode) or not isinstance(node2, SchedulerNode):
  3490. return None
  3491. # only support computued buffer
  3492. if not (
  3493. isinstance(node1.node, ir.ComputedBuffer)
  3494. and isinstance(node2.node, ir.ComputedBuffer)
  3495. ):
  3496. return None
  3497. # does not support mutation yet since relying on index mod to handle
  3498. # out-of-boundary access.
  3499. if node1.has_aliasing_or_mutation() or node2.has_aliasing_or_mutation():
  3500. return None
  3501. # skip halide which does not support mod for index
  3502. if config.cpu_backend == "halide":
  3503. return None
  3504. # only support pointwise nodes with the same reduction size
  3505. n1_sizes, n2_sizes = node1._sizes, node2._sizes
  3506. n1_iter_sizes, n1_reduce_sizes = n1_sizes
  3507. n2_iter_sizes, n2_reduce_sizes = n2_sizes
  3508. if (
  3509. node1.is_reduction()
  3510. or node2.is_reduction()
  3511. or n1_reduce_sizes != n2_reduce_sizes
  3512. or len(n1_iter_sizes) != len(n2_iter_sizes)
  3513. ):
  3514. return None
  3515. # only support nodes with 1 write for simplification
  3516. if len(node1.read_writes.writes) > 1 or len(node2.read_writes.writes) > 1:
  3517. return None
  3518. # When memory access is small, reducing gpu kernel overhead is profitable over
  3519. # slightly larger memory access.
  3520. node1_write_memory = self.dep_size_hint(next(iter(node1.read_writes.writes)))
  3521. node2_write_memory = self.dep_size_hint(next(iter(node1.read_writes.writes)))
  3522. if (
  3523. max(node1_write_memory, node2_write_memory)
  3524. > config.small_memory_access_threshold
  3525. ):
  3526. return None
  3527. # does not support reinplace since `index % boundary` may lead to
  3528. # race condition
  3529. def has_reusable_buffer(node: BaseSchedulerNode) -> bool:
  3530. for read in node.read_writes.reads:
  3531. input_buf: Optional[Union[SchedulerBuffer, SchedulerDonatedBuffer]]
  3532. if read.name in self.name_to_donated_buffer:
  3533. input_buf = self.name_to_donated_buffer[read.name]
  3534. else:
  3535. input_buf = self.name_to_buf.get(read.name)
  3536. if (
  3537. input_buf
  3538. and V.graph.wrapper_code.can_reuse(input_buf, node)
  3539. and not isinstance(input_buf.defining_op, NopKernelSchedulerNode)
  3540. ):
  3541. return True
  3542. return False
  3543. if has_reusable_buffer(node1) or has_reusable_buffer(node2):
  3544. return None
  3545. # only support nodes with 1 mismatch dimension
  3546. mismatch_dimensions = []
  3547. for idx, (n1_size, n2_size) in enumerate(zip(n1_iter_sizes, n2_iter_sizes)):
  3548. if n1_size != n2_size:
  3549. mismatch_dimensions.append(idx)
  3550. if len(mismatch_dimensions) != 1:
  3551. return None
  3552. mismatch_dim = mismatch_dimensions[0]
  3553. mismatch_size1, mismatch_size2 = (
  3554. n1_iter_sizes[mismatch_dim],
  3555. n2_iter_sizes[mismatch_dim],
  3556. )
  3557. if V.graph.sizevars.statically_known_lt(mismatch_size1, mismatch_size2):
  3558. return mismatch_dim, node1, mismatch_size2
  3559. elif V.graph.sizevars.statically_known_lt(mismatch_size2, mismatch_size1):
  3560. return mismatch_dim, node2, mismatch_size1
  3561. else:
  3562. return None
  3563. def can_fuse(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> bool:
  3564. """
  3565. Determine if it is possible to combine node1 and node2 into a
  3566. single fused node.
  3567. """
  3568. if node1 is node2:
  3569. return False
  3570. why = WhyNoFuse(node1, node2)
  3571. if node1.is_template() and self.get_backend(
  3572. node1.get_device()
  3573. ).can_fuse_multi_outputs_template(node1, node2):
  3574. return True
  3575. if isinstance(node1, GroupedSchedulerNode) or isinstance(
  3576. node2, GroupedSchedulerNode
  3577. ):
  3578. why("grouped node must not be fused with other nodes")
  3579. return False
  3580. if (
  3581. isinstance(node1, (ExternKernelSchedulerNode, NopKernelSchedulerNode))
  3582. and not node1.is_template()
  3583. ):
  3584. why("node1 is extern or nop")
  3585. return False
  3586. if (
  3587. isinstance(node2, (ExternKernelSchedulerNode, NopKernelSchedulerNode))
  3588. and not node2.is_template()
  3589. ):
  3590. why("node2 is extern or nop")
  3591. return False
  3592. if node2.get_operation_names() & node1.ancestors:
  3593. why("node1 must go before node2")
  3594. return False
  3595. if node2.is_template():
  3596. if not config.prologue_fusion:
  3597. why("prologue fusion turned off")
  3598. return False
  3599. if node1.is_reduction() or node1.is_template():
  3600. why("prologue fusion only supported for pointwise nodes")
  3601. return False
  3602. template = node2.get_template_node_or_throw()
  3603. if not isinstance(template, ir.TritonTemplateBuffer):
  3604. why("prologue fusion only supported for TritonTemplates")
  3605. return False
  3606. allowed_prologue_inps = template.get_allowed_prologue_inps()
  3607. unsupported_prologue_args = (
  3608. OrderedSet(inp.get_name() for inp in template.inputs) # type: ignore[union-attr]
  3609. - allowed_prologue_inps
  3610. )
  3611. if node1.get_buffer_names() & unsupported_prologue_args:
  3612. why("prologue fusion not implemented for kernel for these inputs")
  3613. return False
  3614. if node1.has_aliasing_or_mutation() or node1.has_aliasing_or_mutation():
  3615. why("template prologue can only fuse functional pointwise nodes")
  3616. return False
  3617. prologue_nodes = node1.get_nodes()
  3618. for node in prologue_nodes[:-1]:
  3619. node_outs = node.get_outputs()
  3620. for out in node_outs:
  3621. if not all(user.node in prologue_nodes for user in out.users):
  3622. why("template prologue can only fuse nodes with a single use")
  3623. return False
  3624. template_snodes = (
  3625. [node2]
  3626. if not isinstance(node2, FusedSchedulerNode)
  3627. else [n for n in node2.snodes if n.is_template()]
  3628. )
  3629. assert len(template_snodes) == 1
  3630. template_snode = template_snodes[0]
  3631. if not (
  3632. len(prologue_nodes[-1].outputs) == 1
  3633. and len(prologue_nodes[-1].outputs[0].users) == 1
  3634. and prologue_nodes[-1].outputs[0].users[0].node is template_snode
  3635. ):
  3636. why(
  3637. "template prologue can only fuse nodes with a single use into template"
  3638. )
  3639. return False
  3640. if not self.check_prologue_fusion_heuristics_fusable(node1, node2, why):
  3641. return False
  3642. if node1.is_template() and (
  3643. node2.has_aliasing_or_mutation()
  3644. or node2.is_reduction()
  3645. or not config.epilogue_fusion
  3646. ):
  3647. why("template epilogue not satisfied")
  3648. return False
  3649. if (node1.get_buffer_names() & V.graph.no_fuse_buffer_names) or (
  3650. node2.get_buffer_names() & V.graph.no_fuse_buffer_names
  3651. ):
  3652. why("fusion for buffer explicit disabled")
  3653. return False
  3654. device = node1.get_device()
  3655. device2 = node2.get_device()
  3656. if device != device2:
  3657. why("device mismatch (%s vs %s)", device, device2)
  3658. return False
  3659. del device2
  3660. shared_data_score = self.score_fusion_memory(node1, node2)
  3661. if (
  3662. shared_data_score < config.score_fusion_memory_threshold
  3663. and config.loop_ordering_after_fusion
  3664. ):
  3665. new_shared_data_score = self.shared_data_after_reordering_loop(node1, node2)
  3666. if new_shared_data_score >= 0:
  3667. shared_data_score = new_shared_data_score
  3668. if config.expand_dimension_for_pointwise_nodes and (
  3669. expand_analysis := self.get_expand_dim_for_pointwise_nodes(node1, node2)
  3670. ):
  3671. (expand_dim, smaller_node, expand_size) = expand_analysis
  3672. smaller_node.expand_dimension_for_pointwise_node(expand_dim, expand_size)
  3673. shared_data_score = self.score_fusion_memory(node1, node2)
  3674. if loop_ordering_log.isEnabledFor(logging.DEBUG):
  3675. loop_ordering_log.debug(
  3676. "%s and %s has %s shared data",
  3677. node1.get_name(),
  3678. node2.get_name(),
  3679. shared_data_score,
  3680. )
  3681. if not V.choices.can_fuse(self, node1, node2, shared_data_score):
  3682. return False
  3683. if node1.get_operation_names() & node2.ancestors:
  3684. # node2 depends on node1 outputs
  3685. return (
  3686. self.can_fuse_vertical(node1, node2)
  3687. and V.choices.can_fuse_vertical(self, node1, node2, shared_data_score)
  3688. and self.get_backend(device).can_fuse_vertical(node1, node2)
  3689. )
  3690. else: # nodes don't depend on each other, but may have common reads
  3691. return V.choices.can_fuse_horizontal(
  3692. self, node1, node2, shared_data_score
  3693. ) and self.get_backend(device).can_fuse_horizontal(node1, node2)
  3694. def can_fuse_vertical(
  3695. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3696. ) -> bool:
  3697. """
  3698. Check if it is legal to fuse a consumer (node2) into a producer (node1).
  3699. We can fuse them if all the reads of node2 either match
  3700. corresponding writes in node1, or are written by nodes that can
  3701. be scheduled before the fusion of node1 and node2.
  3702. """
  3703. node1_buf_names = node1.get_buffer_names()
  3704. why = WhyNoFuse(node1, node2)
  3705. remaining_deps_by_name: dict[str, list[Dep]] = defaultdict(list)
  3706. for dep in node2.unmet_dependencies:
  3707. name = self.mutation_renames.get(dep.name, dep.name)
  3708. if isinstance(dep, WeakDep) and self.fusable_weak_dep(dep, node1, node2):
  3709. continue
  3710. remaining_deps_by_name[name].append(dep)
  3711. for cd in node1.read_writes.writes:
  3712. if not isinstance(cd, MemoryDep):
  3713. continue
  3714. remaining = remaining_deps_by_name.get(
  3715. self.mutation_renames.get(cd.name, cd.name)
  3716. )
  3717. if remaining:
  3718. for rd in remaining:
  3719. if self.fusable_read_and_write(rd, cd):
  3720. remaining.remove(rd) # noqa: B909
  3721. remaining_deps = OrderedSet(
  3722. dep.name
  3723. for dep in itertools.chain.from_iterable(remaining_deps_by_name.values())
  3724. )
  3725. if remaining_deps & node1_buf_names:
  3726. # MemoryDeps didn't match and read different locations of the same buffer.
  3727. # Examples here include:
  3728. # - MemoryDep("foo", x) != MemoryDep("foo", x + 1)
  3729. # - MemoryDep("foo", x) != StarDep("foo")
  3730. why("memory deps did not match")
  3731. return False
  3732. node1_op_names = node1.get_operation_names()
  3733. for name in remaining_deps:
  3734. op_name = self.name_to_buf[name].defining_op_name()
  3735. if node1_op_names & self.name_to_fused_node[op_name].ancestors:
  3736. why("intermediate nodes between node1 & node2")
  3737. return False
  3738. return True
  3739. def fusable_weak_dep(
  3740. self, weak_dep: WeakDep, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3741. ) -> bool:
  3742. if weak_dep.name not in node1.get_buffer_names():
  3743. return False
  3744. # A weak dep can be fused if and only if the fused operation acts inplace
  3745. # on the buffer being mutated. i.e. the same index is being read then mutated
  3746. mutating_writes = [
  3747. write
  3748. for write in node2.read_writes.writes
  3749. if write.name == weak_dep.mutating_buf
  3750. ]
  3751. if len(mutating_writes) != 1:
  3752. return False
  3753. write = mutating_writes[0]
  3754. assert isinstance(write, MemoryDep)
  3755. if free_symbol_is_type(write.index, SymT.TMP):
  3756. return False
  3757. real_name = self.mutation_real_name[weak_dep.mutating_buf]
  3758. relevant_reads = [
  3759. read for read in node1.read_writes.reads if read.name == real_name
  3760. ]
  3761. return all(
  3762. isinstance(read, MemoryDep)
  3763. and not free_symbol_is_type(read.index, SymT.TMP)
  3764. and read.index == write.index
  3765. and read.size == write.size
  3766. for read in relevant_reads
  3767. )
  3768. # StarDep doesn't match MemoryDep, different indices don't match
  3769. # However, broadcasting sometimes strips dimensions, and if that's the case
  3770. # we still can match unmet dep
  3771. # if there's indirect indexing, don't match it
  3772. def fusable_read_and_write(self, read: Dep, write: MemoryDep) -> bool:
  3773. if isinstance(read, MemoryDep):
  3774. read_name = self.mutation_renames.get(read.name, read.name)
  3775. if (
  3776. read_name != write.name
  3777. or free_symbol_is_type(read.index, SymT.TMP)
  3778. or free_symbol_is_type(write.index, SymT.TMP)
  3779. ):
  3780. return False
  3781. if config.loop_ordering_after_fusion and read.num_vars != write.num_vars:
  3782. # Need merge loops if we do loop ordering after fusion since
  3783. # we have not merged the loops yet when creating the scheduler
  3784. # nodes.
  3785. read = read.normalize()
  3786. write = write.normalize()
  3787. return (
  3788. read.index == write.index
  3789. and len(read.size) >= len(write.size)
  3790. and read.size[: len(write.size)] == write.size
  3791. )
  3792. elif isinstance(read, StarDep):
  3793. read_name = self.mutation_renames.get(read.name, read.name)
  3794. write_name = self.mutation_renames.get(write.name, write.name)
  3795. if (
  3796. read.mode == write.mode
  3797. and write.mode is not None
  3798. and read_name == write_name
  3799. ):
  3800. return True
  3801. return False
  3802. def dep_size_hint(self, dep: Dep) -> int:
  3803. return V.graph.get_dep_size_hint(dep)
  3804. def score_fusion_memory(
  3805. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  3806. ) -> int:
  3807. """
  3808. The first term in our fusion score that estimates number of saved
  3809. memory operations.
  3810. """
  3811. node1_dep_len = len(node1.read_writes.reads) + len(node1.read_writes.writes)
  3812. node2_dep_len = len(node1.read_writes.reads) + len(node2.read_writes.writes)
  3813. # optimization: iter over smaller set
  3814. if min(node1_dep_len, node2_dep_len) * 4 < max(node1_dep_len, node2_dep_len):
  3815. if node1_dep_len > node2_dep_len:
  3816. tmp = node1
  3817. node1 = node2
  3818. node2 = tmp
  3819. deps = [
  3820. dep
  3821. for dep in node1.read_writes.reads | node1.read_writes.writes
  3822. if dep in node2.read_writes.reads or dep in node2.read_writes.writes
  3823. ]
  3824. return sum(self.dep_size_hint(dep) for dep in deps)
  3825. common_memory_deps = (node1.read_writes.reads | node1.read_writes.writes) & (
  3826. node2.read_writes.reads | node2.read_writes.writes
  3827. )
  3828. return sum(self.dep_size_hint(dep) for dep in common_memory_deps)
  3829. def get_possible_fusions_with_highest_priority(
  3830. self, possible_fusions: list[tuple[BaseSchedulerNode, BaseSchedulerNode]]
  3831. ) -> list[tuple[BaseSchedulerNode, BaseSchedulerNode]]:
  3832. # Group the possible fusions based on their priority from the backend.
  3833. # Only return the group of possible fusions with highest priority.
  3834. if len(possible_fusions) == 0:
  3835. return possible_fusions
  3836. possible_fusions_group_by_priority: dict[
  3837. int, list[tuple[BaseSchedulerNode, BaseSchedulerNode]]
  3838. ] = {}
  3839. for node1, node2 in possible_fusions:
  3840. assert node1.get_device() == node2.get_device()
  3841. device = node1.get_device()
  3842. fusion_pair_priority = int(
  3843. self.get_backend(device).get_fusion_pair_priority(node1, node2)
  3844. )
  3845. if fusion_pair_priority not in possible_fusions_group_by_priority:
  3846. possible_fusions_group_by_priority[fusion_pair_priority] = [
  3847. (node1, node2),
  3848. ]
  3849. else:
  3850. possible_fusions_group_by_priority[fusion_pair_priority].append(
  3851. (node1, node2)
  3852. )
  3853. # return the possible fusions with highest priority
  3854. possible_fusions_with_highest_priority = min(
  3855. possible_fusions_group_by_priority.items(), key=operator.itemgetter(0)
  3856. )[1]
  3857. assert len(possible_fusions_with_highest_priority) > 0
  3858. return possible_fusions_with_highest_priority
  3859. def score_fusion_key(
  3860. self, nodes: tuple[BaseSchedulerNode, BaseSchedulerNode]
  3861. ) -> Any:
  3862. """
  3863. Shim for list.sort(key=...)
  3864. """
  3865. return V.choices.score_fusion(self, *nodes)
  3866. def compute_last_usage(self) -> None:
  3867. """
  3868. Populate node.last_usage recursively (also for the nodes within a FusedSchedulerNode)
  3869. """
  3870. future_used_buffers = OrderedSet(V.graph.get_output_names())
  3871. for node in reversed(self.nodes):
  3872. node.set_last_usage(future_used_buffers, self.mutation_real_name)
  3873. future_used_buffers.update(node.last_usage)
  3874. def free_buffers(self) -> None:
  3875. """Free any buffers that are no longer needed"""
  3876. for name in sorted(
  3877. self.buffer_names_to_free
  3878. - V.graph.removed_buffers
  3879. - V.graph.wrapper_code.freed # type: ignore[has-type]
  3880. ):
  3881. if name in self.name_to_buf:
  3882. buf = self.name_to_buf[name]
  3883. if buf.can_free():
  3884. V.graph.wrapper_code.codegen_free(buf.node)
  3885. elif name in V.graph.graph_inputs:
  3886. inp = V.graph.graph_inputs[name]
  3887. if isinstance(inp, ir.TorchBindObject):
  3888. V.graph.wrapper_code.codegen_free(inp)
  3889. elif isinstance(inp, ir.GeneratorState):
  3890. continue
  3891. else:
  3892. storage = inp.data
  3893. assert (
  3894. isinstance(storage, ir.StorageBox) and storage.is_input_buffer()
  3895. )
  3896. V.graph.wrapper_code.codegen_free(storage.data)
  3897. self.buffer_names_to_free.clear()
  3898. def flush(self) -> None:
  3899. for backend in self.backends.values():
  3900. backend.flush()
  3901. self.free_buffers()
  3902. def codegen_extern_call(self, scheduler_node: ExternKernelSchedulerNode) -> None:
  3903. assert isinstance(scheduler_node, ExternKernelSchedulerNode)
  3904. # 'decide_inplace_update' stores the inplace update decisions in
  3905. # the current kernel from where 'allocate' retrieve those decisions.
  3906. # We have to make sure there is a non-NULL kernel handler to store
  3907. # those inplace update decisions.
  3908. counters["inductor"]["extern_calls"] += 1
  3909. with V.set_kernel_handler(Kernel(increase_kernel_count=False)):
  3910. scheduler_node.decide_inplace_update()
  3911. scheduler_node.mark_run()
  3912. node = scheduler_node.node
  3913. assert isinstance(node, ir.ExternKernel), f"{type(node)=}"
  3914. node.codegen(V.graph.wrapper_code)
  3915. self.free_buffers()
  3916. def create_backend(self, device: torch.device) -> BaseScheduling:
  3917. assert not is_gpu(device.type) or device.index is not None, (
  3918. f"{device} should have been normalized in lowering"
  3919. )
  3920. V.graph.add_device_info(device)
  3921. device_scheduling = get_scheduling_for_device(device.type)
  3922. if device_scheduling is None:
  3923. raise RuntimeError(f"Unsupported device type: {device.type}")
  3924. if not has_triton():
  3925. if (
  3926. device.type == "cuda"
  3927. and (device_props := torch.cuda.get_device_properties(device)).major < 7
  3928. ):
  3929. raise GPUTooOldForTriton(device_props, inspect.currentframe())
  3930. elif is_gpu(device.type) and not device.type == "mps":
  3931. raise TritonMissing(inspect.currentframe())
  3932. return device_scheduling(self)
  3933. def get_backend(self, device: Optional[torch.device]) -> BaseScheduling:
  3934. assert device is not None
  3935. if device not in self.backends:
  3936. self.backends[device] = self.create_backend(device)
  3937. return self.backends[device]
  3938. def enter_context(self, node: BaseSchedulerNode) -> None:
  3939. def get_order(n: torch.fx.Node) -> int:
  3940. if n not in self.origin_to_index:
  3941. self.origin_to_index.update({n: i for i, n in enumerate(n.graph.nodes)})
  3942. return self.origin_to_index[n]
  3943. # Use a dict to have ordering
  3944. origins = {
  3945. (get_order(e), e): None
  3946. for n in node.get_nodes()
  3947. if n.node is not None
  3948. for e in n.node.get_origins()
  3949. }
  3950. origins = list(origins.keys())
  3951. if origins:
  3952. _, last = max(origins, key=operator.itemgetter(0))
  3953. V.graph.wrapper_code.enter_context(last)
  3954. def can_buffer_be_removed_through_fusion(
  3955. self, name: str, fused_node_names: OrderedSet[str]
  3956. ) -> bool:
  3957. try:
  3958. users = self.name_to_buf[name].users
  3959. except KeyError:
  3960. return False
  3961. return (
  3962. all(user.is_weak or user.get_name() in fused_node_names for user in users)
  3963. and name not in self.mutation_renames
  3964. and name not in self.mutation_real_name
  3965. )
  3966. def should_partition(
  3967. self, node: BaseSchedulerNode, should_log: bool = False
  3968. ) -> bool:
  3969. """Return True if we should partition the inductor graph on this node"""
  3970. # Allow users to manually specify if a node should be partitioned
  3971. # Can only do this for FallbackKernels
  3972. ir_node = node.node
  3973. if isinstance(ir_node, torch._inductor.ir.FallbackKernel) and (
  3974. op := ir_node.op_overload
  3975. ):
  3976. op_overload_packet_name = op.name()
  3977. op_overload_name = (
  3978. f"{op_overload_packet_name}.{op._overloadname}"
  3979. if isinstance(op, torch._ops.OpOverload)
  3980. else op_overload_packet_name
  3981. )
  3982. if (
  3983. op_overload_packet_name in config.custom_should_partition_ops
  3984. or op_overload_name in config.custom_should_partition_ops
  3985. ):
  3986. assert isinstance(op, torch._ops.OpOverload)
  3987. return True
  3988. # When not using cudagraphs, keep all kernels in the `call` function
  3989. # instead of graph partition functions, since graph partition only brings
  3990. # benefit to cudagraph
  3991. if (
  3992. not torch._inductor.config.triton.cudagraphs
  3993. and _unstable_customized_partition_wrapper.wrapper is None
  3994. ):
  3995. return True
  3996. # avoid duplicating logs when should_partition is called multiple times
  3997. # on the same node
  3998. def noop_log(msg: str, node: Optional[BaseSchedulerNode]) -> None:
  3999. return
  4000. log_partition_reason = maybe_log_cudagraph_partition if should_log else noop_log
  4001. if isinstance(node, FusedSchedulerNode):
  4002. return any(self.should_partition(snode) for snode in node.snodes)
  4003. assert node.node is not None
  4004. if not node.is_gpu():
  4005. log_partition_reason("non gpu ops", node=node)
  4006. return True
  4007. if isinstance(node.node, ir.DeviceCopy):
  4008. log_partition_reason("DeviceCopy ops", node=node)
  4009. return True
  4010. if isinstance(node.node, ir.Conditional):
  4011. log_partition_reason("Conditional ops", node=node)
  4012. return True
  4013. if getattr(node.node, "unbacked_bindings", None):
  4014. log_partition_reason("unbacked binding ops", node=node)
  4015. return True
  4016. if is_cudagraph_unsafe_op(node.node):
  4017. log_partition_reason("CUDAGraph-unsafe custom ops", node=node)
  4018. return True
  4019. return False
  4020. def get_name_to_nodes(
  4021. self,
  4022. ) -> dict[str, Union[ir.IRNode, ir.TorchBindObject, sympy.Expr]]:
  4023. """
  4024. Return a mapping from name strings to the corresponding graph inputs or
  4025. base scheduler node outputs.
  4026. """
  4027. name_to_node: dict[str, Union[ir.IRNode, ir.TorchBindObject, sympy.Expr]] = {}
  4028. name_to_node.update(V.graph.graph_inputs)
  4029. for node in self.nodes:
  4030. for name, scheduler_buffer in node.outputs_by_name.items():
  4031. name_to_node[name] = scheduler_buffer.node
  4032. return name_to_node
  4033. def compute_graph_partition_maps(
  4034. self,
  4035. signatures: list[GraphPartitionSignature],
  4036. ) -> None:
  4037. """
  4038. computes a mapping from partition input/output indices to graph input/output
  4039. indices for each partition.
  4040. """
  4041. name_to_graph_input_index = {
  4042. name: idx for idx, name in enumerate(V.graph.graph_inputs)
  4043. }
  4044. name_to_graph_output_index = {
  4045. name: idx for idx, name in enumerate(V.graph.get_output_names())
  4046. }
  4047. V.graph.partition_maps = []
  4048. for partition_id, signature in enumerate(signatures):
  4049. if signature.skip_cudagraph:
  4050. # Note: [Graph Partition Map for CUDAGraph]
  4051. # number of partition map should be the same as the number of generated
  4052. # partition functions. This assumption will be used when cudagraphify
  4053. # each partition function.
  4054. continue
  4055. input_mapping = []
  4056. for name in signature.input_nodes:
  4057. input_mapping.append(name_to_graph_input_index.get(name))
  4058. output_mapping = []
  4059. for node in signature.output_nodes:
  4060. output_mapping.append(name_to_graph_output_index.get(node.get_name()))
  4061. V.graph.partition_maps.append(
  4062. GraphPartitionMap(
  4063. partition_id,
  4064. input_mapping,
  4065. output_mapping,
  4066. signature.constant_names,
  4067. )
  4068. )
  4069. def get_graph_partition_symbol_inputs(
  4070. self,
  4071. partition: PartitionType,
  4072. input_nodes: dict[str, Union[ir.IRNode, ir.TorchBindObject, sympy.Expr]],
  4073. ) -> OrderedSet[sympy.Symbol]:
  4074. """
  4075. Returns all symbol inputs which are required to be in scope to successfully
  4076. perform codegen for this graph partition, including:
  4077. - free symbols used in partition nodes
  4078. - free symbols in partition input/node shapes, strides, and offsets. This is needed
  4079. for recording cudagraphs for tensors with dynamic shapes.
  4080. """
  4081. def get_layout_symints(node: ir.IRNode) -> OrderedSet[sympy.Symbol]:
  4082. free_symbol_uses: OrderedSet[sympy.Symbol] = OrderedSet()
  4083. layout = node.maybe_get_layout()
  4084. if isinstance(layout, ir.Layout):
  4085. free_symbol_uses.update(
  4086. free_symbols(layout.size)
  4087. | free_symbols(layout.stride)
  4088. | free_symbols(layout.offset)
  4089. )
  4090. if isinstance(layout, ir.MutationLayoutSHOULDREMOVE):
  4091. # symint may be used as index in layout.target
  4092. free_symbol_uses.update(get_layout_symints(layout.target))
  4093. else:
  4094. assert layout is None, (
  4095. f"Expect layout to be None but found layout={layout}"
  4096. )
  4097. return free_symbol_uses
  4098. def get_scheduler_node_symbol_uses(
  4099. node: BaseSchedulerNode,
  4100. ) -> OrderedSet[sympy.Symbol]:
  4101. """
  4102. Gets symbols used in node.
  4103. """
  4104. if isinstance(node, FusedSchedulerNode):
  4105. return OrderedSet().union(
  4106. *(get_scheduler_node_symbol_uses(snode) for snode in node.snodes)
  4107. )
  4108. assert node.node is not None
  4109. free_symbol_uses = node.node.get_free_symbol_uses()
  4110. free_symbol_uses.update(
  4111. *(get_layout_symints(ir_node) for ir_node in node.node.get_outputs())
  4112. )
  4113. return free_symbol_uses
  4114. def get_input_node_symbols(
  4115. node: Union[ir.IRNode, sympy.Expr, ir.TorchBindObject],
  4116. ) -> OrderedSet[sympy.Symbol]:
  4117. """
  4118. Gets symbols used in input node shapes, strides, and offsets.
  4119. """
  4120. if isinstance(node, ir.TorchBindObject):
  4121. # TorchBindObject does not involve dynamic shapes yet
  4122. return OrderedSet()
  4123. elif isinstance(node, ir.IRNode):
  4124. return get_layout_symints(node)
  4125. else:
  4126. # node cannot be sympy.Expr since node comes from read_writes and
  4127. # read_writes does not contain sympy.Expr
  4128. raise NotImplementedError(f"Unsupported input node type: {type(node)}")
  4129. def filter_symbols(
  4130. symbols: OrderedSet[sympy.Symbol],
  4131. ) -> OrderedSet[sympy.Symbol]:
  4132. """
  4133. Filters a set of symbols that are required for codegen. Skip symbols
  4134. that are always internal to kernels, such as SymT.TMP, SymT.INDEX,
  4135. and SymT.R0_INDEX.
  4136. """
  4137. return OrderedSet(
  4138. s
  4139. for s in symbols
  4140. if symbol_is_type(
  4141. s,
  4142. (
  4143. SymT.SIZE,
  4144. SymT.FLOAT,
  4145. SymT.UNBACKED_INT,
  4146. SymT.UNBACKED_FLOAT,
  4147. ),
  4148. )
  4149. )
  4150. candidate_symbols: OrderedSet[sympy.Symbol] = OrderedSet().union(
  4151. *(get_scheduler_node_symbol_uses(node) for node in partition)
  4152. )
  4153. candidate_symbols.union(
  4154. *(get_input_node_symbols(node) for _, node in input_nodes.items())
  4155. )
  4156. candidate_symbols = filter_symbols(candidate_symbols)
  4157. res: OrderedSet[sympy.Symbol] = OrderedSet()
  4158. for s in candidate_symbols:
  4159. symplified_s = V.graph.sizevars.simplify(s)
  4160. # use free_symbols only when s is simplified to an Integer or expr
  4161. res.update(symplified_s.free_symbols)
  4162. return OrderedSet(sorted(res, key=operator.attrgetter("name")))
  4163. def get_graph_partition_signature(
  4164. self, partitions: list[PartitionType], skip_cudagraphs: list[bool]
  4165. ) -> list[GraphPartitionSignature]:
  4166. """
  4167. Gets signature for each graph partition, including input nodes, output nodes, and
  4168. whether deallocating an input within graph partition.
  4169. """
  4170. signatures = []
  4171. unmet_output_names = OrderedSet(V.graph.get_output_names())
  4172. name_to_node = self.get_name_to_nodes()
  4173. def is_none_layout(buf_name: str) -> bool:
  4174. """
  4175. Checks if buf_name is NoneLayout. Buffers with NoneLayout is not allocated
  4176. so graph partition should not take it as inputs or outputs.
  4177. """
  4178. buf = self.name_to_buf.get(buf_name, None)
  4179. if buf is None:
  4180. return False
  4181. if isinstance(buf.node.layout, NoneLayout):
  4182. if isinstance(buf.node, ir.MutationOutput) and (
  4183. real_name := self.mutation_real_name.get(buf_name, None)
  4184. ):
  4185. return is_none_layout(real_name)
  4186. return True
  4187. return False
  4188. for partition, skip_cudagraph in zip(
  4189. reversed(partitions), reversed(skip_cudagraphs)
  4190. ):
  4191. output_names: OrderedSet[str] = OrderedSet()
  4192. for node in partition:
  4193. output_names.update(node.outputs_by_name.keys())
  4194. returned_output_names = output_names.intersection(unmet_output_names)
  4195. # all reads/writes are partition inputs except those generated
  4196. # within the partition and tensor constants
  4197. read_writes = dependencies.ReadWrites.merge_list(
  4198. [node.read_writes for node in partition]
  4199. )
  4200. # WeakDep is fake dependency on unused buffer. It should not appear
  4201. # in partition_input_names for inputs that are actually read or written.
  4202. partition_input_names = (
  4203. OrderedSet(
  4204. [
  4205. x.name
  4206. for x in read_writes.reads | read_writes.writes
  4207. if not is_none_layout(x.name)
  4208. ]
  4209. )
  4210. - output_names
  4211. )
  4212. partition_input_names = OrderedSet(
  4213. self.mutation_real_name.get(name, name)
  4214. for name in partition_input_names
  4215. )
  4216. buffer_names_to_free: OrderedSet[str] = OrderedSet()
  4217. for node in partition:
  4218. buffer_names_to_free.update(node.last_usage)
  4219. # buffer_names_to_free may contain buffers allocated in previous
  4220. # graph partitions. These buffers should also be a partition
  4221. # input.
  4222. extra_input_names = [
  4223. name
  4224. for name in (buffer_names_to_free - output_names)
  4225. if name in name_to_node
  4226. ]
  4227. partition_input_names.update(extra_input_names)
  4228. input_nodes = {
  4229. name: name_to_node[name]
  4230. for name in partition_input_names
  4231. if name in name_to_node
  4232. }
  4233. input_deallocation = {
  4234. name: True if name in buffer_names_to_free else False
  4235. for name in partition_input_names
  4236. if name in name_to_node
  4237. }
  4238. # if an input tensor is not freed in the partition function, it should
  4239. # also be returned as an output. This brings benefits to cudagraph
  4240. # since the returned output tensor is a cudagraph managed tensor with
  4241. # a static tensor address.
  4242. extra_output_names = [
  4243. name
  4244. for name in partition_input_names
  4245. if name in name_to_node and name not in buffer_names_to_free
  4246. ]
  4247. returned_output_names.update(extra_output_names)
  4248. returned_output_names = OrderedSet(
  4249. self.mutation_real_name.get(name, name)
  4250. for name in returned_output_names
  4251. )
  4252. output_nodes = [
  4253. name_to_node[name]
  4254. for name in returned_output_names
  4255. if not is_none_layout(name)
  4256. ]
  4257. constant_names = [
  4258. name for name in partition_input_names if name in V.graph.constants
  4259. ]
  4260. symbol_inputs = self.get_graph_partition_symbol_inputs(
  4261. partition, input_nodes
  4262. )
  4263. partition_signature = GraphPartitionSignature(
  4264. symbol_inputs,
  4265. input_nodes,
  4266. output_nodes,
  4267. input_deallocation,
  4268. skip_cudagraph,
  4269. constant_names,
  4270. )
  4271. signatures.append(partition_signature)
  4272. unmet_output_names = partition_input_names.union(
  4273. unmet_output_names - returned_output_names
  4274. )
  4275. return signatures[::-1]
  4276. def clean_removed_buffer_from_partition_signatures(
  4277. self, signature: GraphPartitionSignature
  4278. ) -> GraphPartitionSignature:
  4279. """
  4280. Updates the partition signature by removing buffers specified in
  4281. V.graph.removed_buffers. See [Note: Removed Graph Partition Arguments]
  4282. """
  4283. input_nodes = {
  4284. name: buffer
  4285. for name, buffer in signature.input_nodes.items()
  4286. if name not in V.graph.removed_buffers
  4287. }
  4288. input_deallocation = {
  4289. name: val
  4290. for name, val in signature.input_deallocation.items()
  4291. if name not in V.graph.removed_buffers
  4292. }
  4293. output_nodes = [
  4294. node
  4295. for node in signature.output_nodes
  4296. if node.maybe_get_name() not in V.graph.removed_buffers
  4297. ]
  4298. constant_names = [
  4299. name
  4300. for name in signature.constant_names
  4301. if name not in V.graph.removed_buffers
  4302. ]
  4303. return GraphPartitionSignature(
  4304. signature.symbol_inputs,
  4305. input_nodes,
  4306. output_nodes,
  4307. input_deallocation,
  4308. signature.skip_cudagraph,
  4309. constant_names,
  4310. )
  4311. def reorder_for_minimizing_partition(
  4312. self,
  4313. nodes: list[BaseSchedulerNode],
  4314. ) -> list[BaseSchedulerNode]:
  4315. """
  4316. Reorder nodes to minimize the number of partitions via a bfs
  4317. topological sort. This is the optimal reordering such that the
  4318. number of partitions cannot be reduced further. This may be
  4319. sub-optimal for other metrics such as peak memory. This does not
  4320. change relative orders of two cudagraphable nodes, nor the
  4321. relative order of two non_cudagraphable nodes.
  4322. """
  4323. import heapq
  4324. node_to_indegree: dict[BaseSchedulerNode, int] = dict()
  4325. cudagraphable_nodes: list[tuple[int, BaseSchedulerNode]] = []
  4326. non_cudagraphable_nodes: list[tuple[int, BaseSchedulerNode]] = []
  4327. node_to_index = {node: idx for idx, node in enumerate(nodes)}
  4328. def insert_pending_nodes(node: BaseSchedulerNode) -> None:
  4329. node_with_index = (node_to_index[node], node)
  4330. if self.should_partition(node):
  4331. heapq.heappush(non_cudagraphable_nodes, node_with_index)
  4332. else:
  4333. heapq.heappush(cudagraphable_nodes, node_with_index)
  4334. def update_indegree(node: BaseSchedulerNode) -> None:
  4335. for succ_node in node.mpi_node.succ_nodes:
  4336. assert node_to_indegree[succ_node] > 0
  4337. node_to_indegree[succ_node] -= 1
  4338. if node_to_indegree[succ_node] == 0:
  4339. insert_pending_nodes(succ_node)
  4340. for node in nodes:
  4341. node_to_indegree[node] = len(node.mpi_node.pred_nodes)
  4342. if node_to_indegree[node] == 0:
  4343. insert_pending_nodes(node)
  4344. schedule: list[BaseSchedulerNode] = []
  4345. num_iters: int = 0
  4346. while num_iters < len(nodes) and (
  4347. non_cudagraphable_nodes or cudagraphable_nodes
  4348. ):
  4349. while non_cudagraphable_nodes:
  4350. _, node = heapq.heappop(non_cudagraphable_nodes)
  4351. schedule.append(node)
  4352. update_indegree(node)
  4353. while cudagraphable_nodes:
  4354. _, node = heapq.heappop(cudagraphable_nodes)
  4355. schedule.append(node)
  4356. update_indegree(node)
  4357. num_iters += 1
  4358. if num_iters > len(nodes):
  4359. raise RuntimeError(
  4360. """
  4361. Failed to schedule, while loop ran too long when
  4362. reordering for minimizing the num of partitions
  4363. """
  4364. )
  4365. return schedule
  4366. def maybe_reorder_for_minimizing_partition(
  4367. self,
  4368. nodes: list[BaseSchedulerNode],
  4369. ) -> list[BaseSchedulerNode]:
  4370. """
  4371. Reorder nodes to minimize the number of partitions if this only slightly
  4372. increase peak memory.
  4373. """
  4374. from .memory import estimate_peak_memory, prepare_planning_info
  4375. graph_outputs = OrderedSet(V.graph.get_output_names())
  4376. default_peak_memory, name_to_freeable_input_buf = prepare_planning_info(
  4377. nodes,
  4378. self.name_to_buf,
  4379. self.name_to_fused_node,
  4380. OrderedSet(V.graph.graph_inputs.keys()),
  4381. graph_outputs,
  4382. )
  4383. reordered_nodes = self.reorder_for_minimizing_partition(nodes)
  4384. reorder_peak_memory, _ = estimate_peak_memory(
  4385. reordered_nodes, name_to_freeable_input_buf, graph_outputs
  4386. )
  4387. # 1.1 here means 10% extra peak memory budget which is quite arbitrary
  4388. if reorder_peak_memory < default_peak_memory * 1.1:
  4389. return reordered_nodes
  4390. return nodes
  4391. def reorder_for_partition_with_simple_dependency(
  4392. self, nodes: list[BaseSchedulerNode]
  4393. ) -> list[BaseSchedulerNode]:
  4394. """
  4395. Reorder a node if it should be partitioned and has simple dependency:
  4396. 1. move a partitioned node to the front if it has no dependency
  4397. 2. move a partitioned node to the back if it is only used by OutputNode
  4398. 3. otherwise do not reorder
  4399. """
  4400. front: list[BaseSchedulerNode] = []
  4401. middle: list[BaseSchedulerNode] = []
  4402. back: list[BaseSchedulerNode] = []
  4403. def only_output_user(node: BaseSchedulerNode) -> bool:
  4404. for buf in node.get_outputs():
  4405. for use in buf.users:
  4406. if not isinstance(use.node, OutputNode):
  4407. return False
  4408. return True
  4409. for node in nodes:
  4410. should_partition = self.should_partition(node)
  4411. if should_partition and len(node.unmet_dependencies) == 0:
  4412. front.append(node)
  4413. elif should_partition and only_output_user(node):
  4414. back.append(node)
  4415. else:
  4416. middle.append(node)
  4417. return front + middle + back
  4418. def graph_partition(
  4419. self,
  4420. ) -> tuple[list[PartitionType], list[GraphPartitionSignature]]:
  4421. """
  4422. Given a list of BaseSchedulerNodes, split into a list of
  4423. graph partitions and compute partition input/output signatures.
  4424. """
  4425. partitions: list[PartitionType] = []
  4426. skip_cudagraph = True
  4427. cur_partition: PartitionType = []
  4428. skip_cudagraphs = []
  4429. for node in self.nodes:
  4430. should_partition = self.should_partition(node, should_log=True)
  4431. if cur_partition and skip_cudagraph != should_partition:
  4432. partitions.append(cur_partition)
  4433. skip_cudagraphs.append(skip_cudagraph)
  4434. cur_partition = []
  4435. skip_cudagraph = should_partition
  4436. cur_partition.append(node)
  4437. if cur_partition:
  4438. partitions.append(cur_partition)
  4439. skip_cudagraphs.append(skip_cudagraph)
  4440. signatures = self.get_graph_partition_signature(
  4441. partitions=partitions, skip_cudagraphs=skip_cudagraphs
  4442. )
  4443. self.compute_graph_partition_maps(signatures)
  4444. return partitions, signatures
  4445. def codegen(self) -> None:
  4446. with dynamo_timed("Scheduler.codegen"):
  4447. return (
  4448. self._codegen_partitions()
  4449. if torch._inductor.config.graph_partition
  4450. else self._codegen(self.nodes)
  4451. )
  4452. def _codegen_partition_wrapper(
  4453. self,
  4454. partition: PartitionType,
  4455. signature: GraphPartitionSignature,
  4456. ) -> None:
  4457. """Codegen a partition given its inputs/outputs"""
  4458. from .codegen.wrapper import SubgraphPythonWrapperCodegen
  4459. parent_wrapper_code = V.graph.wrapper_code
  4460. graph_partition_id = next(self._graph_partition_counter)
  4461. with V.graph.set_current_wrapper_code():
  4462. V.graph.init_wrapper_code(
  4463. is_subgraph=True,
  4464. subgraph_name=f"partition_{graph_partition_id}",
  4465. parent_wrapper_code=parent_wrapper_code,
  4466. partition_signatures=signature,
  4467. )
  4468. self._codegen(partition)
  4469. # Note: [Removed Graph Partition Arguments]
  4470. # Graph partition relies on node.read_writes to analyze the partition
  4471. # inputs and outputs. However, during codegen, we may decide some buffers
  4472. # are internal to a kernel (e.g., triton kernel) such that these buffers
  4473. # are never actually defined. This information is collected during codegen
  4474. # and recorded in V.graph.removed_buffers. So we cleanup signature and write
  4475. # prefix (i.e., generating call function and return outputs) after we have
  4476. # codegen the partition.
  4477. assert isinstance(V.graph.wrapper_code, SubgraphPythonWrapperCodegen)
  4478. signature = self.clean_removed_buffer_from_partition_signatures(signature)
  4479. V.graph.wrapper_code.partition_signatures = signature
  4480. V.graph.wrapper_code.write_prefix()
  4481. partition_code, _ = V.graph.wrapper_code.generate(V.graph.is_inference)
  4482. V.graph.wrapper_code.define_subgraph_launcher_fn(partition_code.value)
  4483. V.graph.wrapper_code.codegen_partition_call(graph_partition_id, signature)
  4484. V.graph.wrapper_code.allocated.update( # type: ignore[has-type]
  4485. [node.get_name() for node in signature.output_nodes]
  4486. )
  4487. def use_default_device_context(
  4488. self, partitions: list[PartitionType], signatures: list[GraphPartitionSignature]
  4489. ) -> contextlib.AbstractContextManager[None]:
  4490. @contextlib.contextmanager
  4491. def ctx() -> Iterator[None]:
  4492. self.update_graph_partition_default_device(partitions, signatures)
  4493. if self.default_device_context and device_need_guard(
  4494. self.default_device_context.type
  4495. ):
  4496. assert self.default_device_context.index is not None, (
  4497. "device should have an index"
  4498. )
  4499. V.graph.wrapper_code.codegen_device_guard_enter(
  4500. self.default_device_context.index
  4501. )
  4502. try:
  4503. yield
  4504. finally:
  4505. if self.default_device_context and device_need_guard(
  4506. self.default_device_context.type
  4507. ):
  4508. V.graph.wrapper_code.codegen_device_guard_exit()
  4509. self.default_device_context = None
  4510. return ctx()
  4511. def update_graph_partition_default_device(
  4512. self, partitions: list[PartitionType], signatures: list[GraphPartitionSignature]
  4513. ) -> None:
  4514. # Note: [Graph Partition Device Contexts]
  4515. # Entering a device context takes 60 microseconds and exiting a device
  4516. # context takes 20 microseconds. If all graph partitions and
  4517. # cudagraph-unsafe ops happen on the same device, we can share the
  4518. # device context.
  4519. if len(partitions) == 1 and not signatures[0].skip_cudagraph:
  4520. # If there is only 1 cudagraph partition, the device context
  4521. # should happen within the cudagraph partition, which
  4522. # would be removed by cudagraph.
  4523. return
  4524. def get_cudagraph_partition_device(partition: PartitionType) -> torch.device:
  4525. partition_device = partition[0].get_device()
  4526. assert partition_device is not None
  4527. return partition_device
  4528. def all_on_target_device(
  4529. partition: PartitionType, target_device: torch.device
  4530. ) -> bool:
  4531. for node in partition:
  4532. device = node.get_device()
  4533. if device != target_device:
  4534. return False
  4535. return True
  4536. cudagraph_partition_device = None
  4537. for partition, signature in zip(partitions, signatures):
  4538. if not signature.skip_cudagraph:
  4539. cudagraph_partition_device = get_cudagraph_partition_device(partition)
  4540. break
  4541. # all partitions skip cudagraph
  4542. if cudagraph_partition_device is None:
  4543. return
  4544. for partition, signature in zip(partitions, signatures):
  4545. if signature.skip_cudagraph and not all_on_target_device(
  4546. partition, cudagraph_partition_device
  4547. ):
  4548. return
  4549. self.default_device_context = cudagraph_partition_device
  4550. def _codegen_partitions(self) -> None:
  4551. """
  4552. Split nodes into partitions and codegen each partition into separate functions.
  4553. This allows further applying different optimizations (e.g., cudagraph) to
  4554. each function.
  4555. """
  4556. partitions, signatures = self.graph_partition()
  4557. if len(partitions) > 1:
  4558. msg = f"cudagraph partition into {len(partitions)} partitions"
  4559. maybe_log_cudagraph_partition(msg=msg, prefix="")
  4560. with self.use_default_device_context(partitions, signatures):
  4561. for partition, signature in zip(partitions, signatures):
  4562. assert len(partition) >= 1, (
  4563. f"Each partition must have at least one node but found {len(partition)}"
  4564. )
  4565. if signature.skip_cudagraph:
  4566. self._codegen(partition)
  4567. else:
  4568. self._codegen_partition_wrapper(partition, signature)
  4569. num_partitions = next(self._graph_partition_counter)
  4570. V.graph.wrapper_code.set_all_partition_names(num_partitions)
  4571. # See [Note: Graph Partition Map for CUDAGraph]
  4572. if num_partitions > 0:
  4573. assert V.graph.partition_maps is not None
  4574. assert num_partitions == len(V.graph.partition_maps), (
  4575. f"Expect {num_partitions} partition maps but got {len(V.graph.partition_maps)}"
  4576. )
  4577. def _codegen(self, nodes: list[BaseSchedulerNode]) -> None:
  4578. if config.check_stack_no_cycles_TESTING_ONLY:
  4579. import torch._dynamo.convert_frame
  4580. stack = traceback.extract_stack()
  4581. seen: OrderedSet[tuple[str, int | None]] = OrderedSet()
  4582. for frame in reversed(stack):
  4583. # This is where maybe_cprofile is
  4584. if (
  4585. frame.name == "_compile_inner"
  4586. and frame.filename == torch._dynamo.convert_frame.__file__
  4587. ):
  4588. break
  4589. key = (frame.filename, frame.lineno)
  4590. assert key not in seen, (
  4591. f"Duplicate stack frame {frame.filename}:{frame.lineno}; "
  4592. "did you add a decorator to one of the functions in this stack "
  4593. "trace? If so, try using a context manager instead."
  4594. )
  4595. seen.add(key)
  4596. self.current_device = self.default_device_context
  4597. if self.default_device_context and config.triton.autotune_at_compile_time:
  4598. V.graph.wrapper_code.write_get_raw_stream_header()
  4599. for node in nodes:
  4600. if log.isEnabledFor(logging.DEBUG):
  4601. try:
  4602. log.debug(
  4603. "Generating code for node %s with estimated runtime %f",
  4604. node.get_name(),
  4605. node.get_estimated_runtime(),
  4606. )
  4607. except Exception:
  4608. log.debug(
  4609. "Generating code for node %s with estimated runtime 0.0",
  4610. node.get_name(),
  4611. )
  4612. self.enter_context(node)
  4613. if device := node.get_device():
  4614. if (
  4615. device != self.current_device
  4616. or node.is_extern()
  4617. or node.is_template()
  4618. ):
  4619. self.flush()
  4620. if device != self.current_device:
  4621. if self.current_device and device_need_guard(
  4622. self.current_device.type
  4623. ):
  4624. V.graph.wrapper_code.codegen_device_guard_exit()
  4625. self.current_device = device
  4626. if device_need_guard(device.type):
  4627. assert device.index is not None, "device should have an index"
  4628. V.graph.wrapper_code.codegen_device_guard_enter(device.index)
  4629. self.current_node = node
  4630. self.buffer_names_to_free.update(node.last_usage)
  4631. if node.is_template():
  4632. prologue, template_node, epilogue = node.get_prologue_template_epilogue(
  4633. list(node.get_nodes())
  4634. )
  4635. self.get_backend(device).codegen_template(
  4636. template_node, epilogue, prologue
  4637. )
  4638. elif node.is_extern():
  4639. node = typing.cast(ExternKernelSchedulerNode, node)
  4640. self.codegen_extern_call(node)
  4641. elif node.is_foreach():
  4642. node = typing.cast(ForeachKernelSchedulerNode, node)
  4643. backend_ = self.get_backend(device)
  4644. from .codegen.cuda_combined_scheduling import CUDACombinedScheduling
  4645. from .codegen.simd import SIMDScheduling
  4646. if isinstance(backend_, (SIMDScheduling, CUDACombinedScheduling)):
  4647. backend = backend_
  4648. else:
  4649. raise AssertionError(f"{type(self)=}")
  4650. backend.codegen_combo_kernel(node)
  4651. elif isinstance(node, (FusedSchedulerNode, SchedulerNode)):
  4652. self.get_backend(device).codegen_node(node)
  4653. else:
  4654. assert isinstance(node, NopKernelSchedulerNode)
  4655. node.mark_run()
  4656. if config.triton.debug_sync_kernel:
  4657. self.get_backend(device).codegen_sync()
  4658. self.available_buffer_names.update(node.get_buffer_names())
  4659. self.completed_operations.update(node.get_operation_names())
  4660. if not isinstance(node, NopKernelSchedulerNode):
  4661. device = node.get_device()
  4662. if (
  4663. device is not None
  4664. and device.type != "meta"
  4665. and self.get_backend(device).ready_to_flush()
  4666. ):
  4667. self.flush()
  4668. if self.current_device != self.default_device_context:
  4669. # when default_device_context is not None, we are codegen
  4670. # for graph partitions and all nodes must be on
  4671. # the same default device.
  4672. assert self.current_device is not None
  4673. if device_need_guard(self.current_device.type):
  4674. # exit the outermost CUDA device guard. this is
  4675. # important for nested indentation codegen-ing.
  4676. V.graph.wrapper_code.codegen_device_guard_exit()
  4677. self.flush()
  4678. def benchmark_combo_kernel(
  4679. self, node_list: Sequence[BaseSchedulerNode]
  4680. ) -> tuple[float, float, list[Optional[str]]]:
  4681. """
  4682. Benchmark fused list of nodes and return the execution time
  4683. in milliseconds on randomly generated inputs.
  4684. """
  4685. device = node_list[0].get_device()
  4686. V.graph.scheduler = self
  4687. self.current_device = device
  4688. assert device is not None
  4689. backend = self.get_backend(device)
  4690. return backend.benchmark_combo_kernel(node_list)
  4691. def speedup_by_combo_kernel(self, nodes: list[BaseSchedulerNode]) -> bool:
  4692. """
  4693. If config.benchmark_fusion is False, always return True.
  4694. Otherwise, return True if fusion can brings speedup.
  4695. """
  4696. if not config.benchmark_combo_kernel:
  4697. return True
  4698. subkernel_nodes = nodes
  4699. device = subkernel_nodes[0].get_device()
  4700. # don't support benchmark fusion for CPU right now.
  4701. if device is None or device.type == "cpu":
  4702. return True
  4703. from triton.compiler.errors import CompilationError
  4704. ms1, path1_list = 0.0, []
  4705. for i, snode in enumerate(subkernel_nodes):
  4706. node_list = snode.get_nodes()
  4707. # We can not accurately benchmark kernel using atomic_add
  4708. # due to how we generate random integer inputs.
  4709. if self._any_atomic_add(node_list):
  4710. fusion_log.debug(
  4711. "ComboKernel: benchmarking may not accurate due to atomic_add"
  4712. )
  4713. try:
  4714. ms, path = self.benchmark_fused_nodes(node_list)
  4715. if math.isinf(ms):
  4716. fusion_log.debug(
  4717. "ComboKernel benchmark: register spilling of %d-th subkernel",
  4718. i,
  4719. )
  4720. return False
  4721. except CompilationError as e:
  4722. # workaround triton issue: https://github.com/triton-lang/triton/issues/2151
  4723. if "Loop-carried variable" in str(e):
  4724. fusion_log.debug(
  4725. "ComboKernel benchmark: return True because of loop-carried variable"
  4726. )
  4727. return True # allow fusion
  4728. else:
  4729. raise
  4730. ms1 += ms
  4731. path1_list.append(path)
  4732. try:
  4733. ms2, ms2_clone, _path2_list = self.benchmark_combo_kernel(subkernel_nodes)
  4734. except CompilationError as e:
  4735. # workaround triton issue: https://github.com/triton-lang/triton/issues/2151
  4736. if "Loop-carried variable" in str(e):
  4737. fusion_log.debug(
  4738. "ComboKernel benchmark: return True because of loop-carried variable"
  4739. )
  4740. return True # allow fusion
  4741. else:
  4742. raise
  4743. # small kernels are very likely to have speedup but hard to benchmark. So we skip benchmarking.
  4744. small_kernel = ms2 - ms2_clone < 0.3 or ms1 < 0.3
  4745. if fusion_log.isEnabledFor(logging.DEBUG):
  4746. if ms1 > ms2 or small_kernel:
  4747. fusion_log.debug(
  4748. "can fuse (benchmark): fusing causes %sx speedup",
  4749. green_text(f"{ms1 / ms2:.3f}"),
  4750. )
  4751. else:
  4752. fusion_log.debug(
  4753. "cannot fuse (benchmark): fusing causes %sx slowdown",
  4754. red_text(f"{ms1 / ms2:.3f}"),
  4755. )
  4756. # ms1 returned by benchmark_fused_nodes discounted clone time
  4757. return ms2 - ms2_clone < ms1 or small_kernel
  4758. def get_buffer_layout(self, buf_name: str) -> ir.Layout:
  4759. buf = self.name_to_buf[buf_name]
  4760. assert buf.node is not None
  4761. return buf.node.get_layout()
  4762. def update_zero_dim_cpu_tensor(self) -> None:
  4763. for node in self.nodes:
  4764. if node.is_gpu():
  4765. for read in node.read_writes.reads:
  4766. buffer = V.graph.name_to_buffer.get(read.name)
  4767. if (
  4768. buffer
  4769. and get_device_type(buffer) == "cpu"
  4770. and not isinstance(
  4771. buffer.layout, (NoneLayout, MultiOutputLayout)
  4772. )
  4773. and buffer.get_size() == []
  4774. ):
  4775. V.graph.zero_dim_cpu_tensor_list.add(read.name)
  4776. class BaseScheduling:
  4777. def __init__(self, scheduler: Optional[Scheduler]):
  4778. super().__init__()
  4779. self.scheduler = scheduler
  4780. def free_buffers_in_scheduler(self) -> None:
  4781. if self.scheduler:
  4782. self.scheduler.free_buffers()
  4783. def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]:
  4784. """Return a set of .codegen.common.BackendFeature()"""
  4785. return OrderedSet()
  4786. def can_fuse_vertical(
  4787. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  4788. ) -> bool:
  4789. """
  4790. Check whether node1 and node2 can be vertically fused or not.
  4791. """
  4792. raise NotImplementedError
  4793. def can_fuse_horizontal(
  4794. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  4795. ) -> bool:
  4796. """
  4797. Check whether node1 and node2 can be horizontally fused or not.
  4798. """
  4799. raise NotImplementedError
  4800. def can_fuse_multi_outputs_template(
  4801. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  4802. ) -> bool:
  4803. """
  4804. A Multi-Output Template (referenced in #144012) is a template node
  4805. with MultiOutputLayout, and its output buffers are instances of MultiOutput.
  4806. In this context, we verify whether node1 represents the Multi-Output Template
  4807. and node2 corresponds to one of its outputs. If so, we further check if
  4808. backend supports this fusion.
  4809. """
  4810. return False
  4811. def fuse(
  4812. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  4813. ) -> FusedSchedulerNode:
  4814. """
  4815. Fuse two nodes
  4816. """
  4817. if node1.is_foreach() or node2.is_foreach():
  4818. return ForeachKernelSchedulerNode.fuse(node1, node2)
  4819. else:
  4820. return FusedSchedulerNode.fuse(node1, node2)
  4821. def group_fn(
  4822. self, sizes: Sequence[Sequence[sympy.Expr]]
  4823. ) -> tuple[tuple[sympy.Expr, ...], ...]:
  4824. """
  4825. Process the iteration sizes in case a transformation needs to be applied.
  4826. """
  4827. raise NotImplementedError
  4828. def codegen_template(
  4829. self,
  4830. template_node: BaseSchedulerNode,
  4831. epilogue_nodes: Sequence[BaseSchedulerNode],
  4832. prologue_nodes: Sequence[BaseSchedulerNode],
  4833. ) -> Optional[str]:
  4834. """
  4835. Given a template node, generate a kernel.
  4836. This function is only available for triton now. If the third-party backend behaves as a sub-class
  4837. of TritonScheduling, it can override it or reuse it.
  4838. """
  4839. raise NotImplementedError
  4840. def generate_kernel_code_from_nodes(
  4841. self,
  4842. nodes: Sequence[BaseSchedulerNode],
  4843. benchmark_kernel: bool,
  4844. hint_override: Optional[int] = None,
  4845. ) -> str:
  4846. """
  4847. Generate a kernel given a list of pre-fused nodes.
  4848. """
  4849. raise NotImplementedError
  4850. def codegen_node(self, node: Union[FusedSchedulerNode, SchedulerNode]) -> None:
  4851. """
  4852. Generate a kernel given a list of pre-fused nodes.
  4853. """
  4854. raise NotImplementedError
  4855. def codegen_sync(self) -> None:
  4856. """
  4857. Generate synchronization code for the kernel. This method depends on the hardware characteristics.
  4858. """
  4859. raise NotImplementedError
  4860. def ready_to_flush(self) -> bool:
  4861. """
  4862. Check whether the backend is requesting the scheduler to flush the generated kernel.
  4863. If not supported, please return False.
  4864. """
  4865. return False
  4866. def flush(self) -> None:
  4867. """
  4868. Flush the generated kernel and python wrapper code to the source code file.
  4869. """
  4870. raise NotImplementedError
  4871. def benchmark_fused_nodes(
  4872. self, nodes: Sequence[BaseSchedulerNode]
  4873. ) -> tuple[float, str]:
  4874. """
  4875. Benchmark fused list of nodes and return the execution time
  4876. in milliseconds on randomly generated inputs.
  4877. """
  4878. raise NotImplementedError
  4879. def benchmark_codegened_module(self, module: ModuleType) -> tuple[float, str]:
  4880. """
  4881. Benchmark a compiled module and return the execution time
  4882. in milliseconds on randomly generated inputs.
  4883. """
  4884. raise NotImplementedError
  4885. def get_fusion_pair_priority(
  4886. self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
  4887. ) -> int:
  4888. """
  4889. Return an unsigned integer which represents the priority of this fusion pair.
  4890. The smaller is with higher priority.
  4891. """
  4892. return 0
  4893. def benchmark_combo_kernel(
  4894. self, node_list: Sequence[BaseSchedulerNode]
  4895. ) -> tuple[float, float, list[Optional[str]]]:
  4896. """
  4897. Benchmark the list of nodes to combine and return the execution time
  4898. and memory copy time in milliseconds on randomly generated inputs.
  4899. """
  4900. raise NotImplementedError