codecache.py 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317
  1. from __future__ import annotations
  2. import base64
  3. import copyreg
  4. import dataclasses
  5. import functools
  6. import hashlib
  7. import importlib
  8. import importlib.resources
  9. import io
  10. import itertools
  11. import json
  12. import logging
  13. import os
  14. import pickle
  15. import pkgutil
  16. import re
  17. import shlex
  18. import shutil
  19. import struct
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import textwrap
  24. import threading
  25. import warnings
  26. from bisect import bisect_right
  27. from copy import copy
  28. from ctypes import c_void_p, CDLL, cdll
  29. from datetime import timedelta
  30. from functools import lru_cache, partial
  31. from pathlib import Path
  32. from tempfile import _TemporaryFileWrapper
  33. from time import time, time_ns
  34. from types import ModuleType
  35. from typing import (
  36. Any,
  37. Callable,
  38. cast,
  39. Generic,
  40. NoReturn,
  41. Optional,
  42. TYPE_CHECKING,
  43. TypeVar,
  44. Union,
  45. )
  46. from typing_extensions import override, Self
  47. import torch
  48. import torch.distributed as dist
  49. from torch import SymInt, Tensor
  50. from torch._dynamo.exc import SkipFrame
  51. from torch._dynamo.utils import CompileEventLogger, counters, dynamo_timed
  52. from torch._inductor import config, exc, metrics
  53. from torch._inductor.codegen.common import (
  54. custom_backend_codegen_configs,
  55. custom_backend_passes,
  56. init_backend_registration,
  57. )
  58. from torch._inductor.codegen.cuda import cuda_env
  59. from torch._inductor.codegen.rocm.compile_command import (
  60. rocm_compile_command,
  61. rocm_compiler,
  62. )
  63. from torch._inductor.compile_worker.utils import in_toplevel_process
  64. from torch._inductor.cpp_builder import (
  65. _LINKER_SCRIPT,
  66. _set_gpu_runtime_env,
  67. _TORCH_PATH,
  68. _transform_cuda_paths,
  69. convert_cubin_to_obj,
  70. CppBuilder,
  71. CppOptions,
  72. CppTorchDeviceOptions,
  73. get_compiler_version_info,
  74. get_ld_and_objcopy,
  75. get_name_and_dir_from_output_file_path,
  76. normalize_path_separator,
  77. run_asm_build_object,
  78. )
  79. from torch._inductor.cpu_vec_isa import pick_vec_isa
  80. from torch._inductor.custom_graph_pass import (
  81. CustomGraphModulePass,
  82. CustomGraphPass,
  83. CustomGraphPassType,
  84. CustomPartitionerFn,
  85. CustomPartitionerFnType,
  86. )
  87. from torch._inductor.freezing_utils import has_frozen_params, is_frozen_param
  88. from torch._inductor.runtime.compile_tasks import _reload_python_module
  89. from torch._inductor.runtime.runtime_utils import cache_dir, default_cache_dir
  90. from torch._inductor.utils import (
  91. ALIGN_BYTES,
  92. clear_on_fresh_cache,
  93. is_linux,
  94. is_windows,
  95. )
  96. from torch._logging import trace_structured
  97. from torch._subclasses.fake_tensor import (
  98. extract_tensor_metadata,
  99. FakeTensor,
  100. TensorMetadata,
  101. )
  102. from torch._utils_internal import log_cache_bypass
  103. from torch.compiler import config as cconfig
  104. from torch.compiler._cache import (
  105. CacheArtifact,
  106. CacheArtifactFactory,
  107. CacheArtifactManager,
  108. )
  109. from torch.export.pt2_archive._package_weights import TensorProperties, Weights
  110. from torch.export.pt2_archive.constants import CUSTOM_OBJ_FILENAME_PREFIX
  111. from torch.fx.experimental.symbolic_shapes import has_hint, hint_int, ShapeEnv
  112. from torch.utils._ordered_set import OrderedSet
  113. from .output_code import CompiledFxGraph
  114. from .remote_cache import create_cache
  115. from .runtime import autotune_cache
  116. from .runtime.autotune_cache import AutotuneCacheBundler
  117. from .triton_bundler import TritonBundler
  118. from .virtualized import V
  119. if config.is_fbcode():
  120. from triton.fb.build import build_paths
  121. T = TypeVar("T")
  122. if TYPE_CHECKING:
  123. from collections.abc import Generator, KeysView, Sequence
  124. from concurrent.futures import Future
  125. from .compile_fx import _CompileFxKwargs
  126. from .cpp_builder import BuildOptionsBase
  127. from .graph import GraphLowering
  128. from .ir import ChoiceCaller
  129. from .output_code import CompiledFxGraphConstants, OutputCode
  130. from .remote_cache import JsonDataTy, RemoteCache
  131. from .runtime.hints import HalideInputSpec, HalideMeta
  132. from .runtime.triton_heuristics import CachingAutotuner
  133. from .utils import InputType
  134. _IS_WINDOWS = sys.platform == "win32"
  135. LOCK_TIMEOUT = 600
  136. output_code_log = torch._logging.getArtifactLogger(__name__, "output_code")
  137. autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning")
  138. log = logging.getLogger(__name__)
  139. def use_re_build() -> bool:
  140. """
  141. Use for CUTLASS compilation only right now.
  142. """
  143. if config.is_fbcode() and not cuda_env.nvcc_exist(_cuda_compiler()):
  144. from triton.fb.re_build_helper import should_build_locally
  145. return not should_build_locally()
  146. return False
  147. def get_cpp_wrapper_cubin_path_name() -> str:
  148. return "cubin_path" if torch.version.hip is None else "hsaco_path"
  149. def get_kernel_bin_format(device: str) -> str:
  150. if device == "cuda":
  151. return "cubin" if torch.version.hip is None else "hsaco"
  152. elif device == "xpu":
  153. return "spv"
  154. else:
  155. return ""
  156. class CacheBase:
  157. @staticmethod
  158. @functools.cache
  159. def get_system() -> dict[str, Any]:
  160. from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key
  161. if HAS_TRITON:
  162. # Use triton_key instead of triton.__version__ as the version
  163. # is not updated with each code change
  164. triton_version = triton_key()
  165. else:
  166. triton_version = None
  167. try:
  168. system: dict[str, Any] = {
  169. "device": {"name": None},
  170. "version": {
  171. "triton": triton_version,
  172. },
  173. }
  174. device_properties = torch.cuda.get_device_properties(
  175. torch.cuda.current_device()
  176. )
  177. if torch.version.cuda is not None:
  178. system["device"]["name"] = device_properties.name
  179. system["version"]["cuda"] = torch.version.cuda
  180. else:
  181. system["device"]["name"] = device_properties.gcnArchName
  182. system["version"]["hip"] = torch.version.hip
  183. except (AssertionError, RuntimeError):
  184. # If cuda is not installed, none of the above config is relevant.
  185. system = {}
  186. system["hash"] = hashlib.sha256(
  187. json.dumps(system, sort_keys=True).encode("utf-8")
  188. ).hexdigest()
  189. return system
  190. @staticmethod
  191. @clear_on_fresh_cache
  192. @functools.cache
  193. def get_local_cache_path() -> Path:
  194. return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"]))
  195. def __init__(self) -> None:
  196. self.system = CacheBase.get_system()
  197. def get_local_cache(self) -> dict[str, Any]:
  198. local_cache_path = self.get_local_cache_path()
  199. if not local_cache_path.is_file():
  200. return {}
  201. with open(local_cache_path) as local_cache_fp:
  202. local_cache = json.load(local_cache_fp)
  203. return local_cache["cache"]
  204. def update_local_cache(self, local_cache: dict[str, Any]) -> None:
  205. local_cache_path = self.get_local_cache_path()
  206. write_atomic(
  207. str(local_cache_path),
  208. json.dumps({"system": self.system, "cache": local_cache}, indent=4),
  209. make_dirs=True,
  210. )
  211. class LocalCache(CacheBase):
  212. def lookup(self, *keys: str) -> Optional[dict[str, Any]]:
  213. cache = self.get_local_cache()
  214. sub_cache = cache
  215. for key in keys:
  216. if key in cache:
  217. sub_cache = cache[key]
  218. else:
  219. return None
  220. return sub_cache
  221. def set_value(self, *keys: str, value: Any) -> None:
  222. cache = self.get_local_cache()
  223. sub_cache = cache
  224. for key in keys[0:-1]:
  225. sub_cache.setdefault(key, {})
  226. sub_cache = sub_cache[key]
  227. sub_cache[keys[-1]] = value
  228. self.update_local_cache(cache)
  229. class PersistentCache(CacheBase):
  230. def lookup(
  231. self,
  232. choices: list[ChoiceCaller],
  233. op: str,
  234. inputs: str,
  235. benchmark: Optional[Callable[[Any], dict[ChoiceCaller, float]]],
  236. hint_override: Optional[int] = None,
  237. ) -> dict[ChoiceCaller, float]:
  238. """
  239. Check to see if we have benchmarked the given choice callers. For each
  240. choice caller:
  241. 1. Check local_cache[op][inputs][choice][precision], return benchmark if cached.
  242. 2. If benchmark is not None:
  243. a. `max_autotune_gemm=True`: benchmark the choice, update
  244. local_cache[op][inputs][choice], and return the benchmark.
  245. b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing.
  246. """
  247. precision = torch.get_float32_matmul_precision()
  248. cache_key = f"{inputs}_{hint_override}" if hint_override is not None else inputs
  249. timings = {}
  250. def check_cache(cache: dict[str, Any]) -> bool:
  251. """Check if `cache` contains data for all the choices"""
  252. hit = True
  253. for choice in choices:
  254. choice_hash = choice.hash_key()
  255. if choice_hash in cache.get(op, {}).get(cache_key, {}).get(
  256. precision, {}
  257. ):
  258. # cache hit
  259. timings[choice] = cache[op][cache_key][precision][choice_hash]
  260. else:
  261. # cache miss
  262. hit = False
  263. break
  264. return hit
  265. local_cache = self.get_local_cache() if config.autotune_local_cache else {}
  266. if (not check_cache(local_cache)) and (benchmark is not None):
  267. # re-benchmark everything to try to get consistent numbers from the same machine
  268. timings = benchmark(choices)
  269. assert all(choice in timings for choice in choices)
  270. local_cache.setdefault(op, {})
  271. local_cache[op].setdefault(cache_key, {}).setdefault(precision, {})
  272. for choice, timing in timings.items():
  273. local_cache[op][cache_key][precision][choice.hash_key()] = timing
  274. self.update_local_cache(local_cache)
  275. return timings
  276. def get_lock_dir() -> str:
  277. lock_dir = os.path.join(cache_dir(), "locks")
  278. if not os.path.exists(lock_dir):
  279. os.makedirs(lock_dir, exist_ok=True)
  280. return lock_dir
  281. def sha256_hash(data: bytes) -> str:
  282. # [:51] to strip off the "Q====" suffix common to every hash value.
  283. return base64.b32encode(hashlib.sha256(data).digest())[:51].decode("utf-8").lower()
  284. def code_hash(code: Union[str, bytes], extra: Union[str, bytes] = "") -> str:
  285. hashing_str = code if isinstance(code, bytes) else code.encode("utf-8")
  286. if extra:
  287. extra_b = extra if isinstance(extra, bytes) else extra.encode("utf-8")
  288. hashing_str = hashing_str + b"||" + extra_b
  289. return "c" + sha256_hash(hashing_str)
  290. def get_path(
  291. basename: str, extension: str, specified_dir: str = ""
  292. ) -> tuple[str, str, str]:
  293. if specified_dir:
  294. if os.path.isabs(specified_dir):
  295. subdir = specified_dir
  296. else:
  297. subdir = os.path.join(cache_dir(), specified_dir)
  298. else:
  299. subdir = os.path.join(cache_dir(), basename[1:3])
  300. path = os.path.join(subdir, f"{basename}.{extension}")
  301. return basename, subdir, path
  302. def get_hash(
  303. content: Union[str, bytes], extra: str = "", hash_type: str = "code"
  304. ) -> str:
  305. if hash_type in {"amdgcn", "code", "ptx", "spv"}:
  306. return code_hash(content, extra)
  307. if hash_type in {"cubin", "hsaco", "spv"}:
  308. return code_hash(repr(content))
  309. raise AssertionError(f"Unknown hash type {hash_type}")
  310. class WritableTempFile:
  311. """
  312. Avoid "Permission denied error" on Windows:
  313. with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file:
  314. # Not writable on Windows:
  315. # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
  316. Example:
  317. with WritableTempFile("w", suffix=".gv") as temp_file:
  318. tree.to_dotfile(temp_file.name)
  319. """
  320. def __init__(
  321. self, mode: str = "w", *, encoding: Any = None, suffix: Any = None
  322. ) -> None:
  323. self.mode = mode
  324. self.encoding = encoding
  325. self.suffix = suffix
  326. def __enter__(self) -> _TemporaryFileWrapper[Any]:
  327. self.temp_file = tempfile.NamedTemporaryFile(
  328. self.mode, encoding=self.encoding, suffix=self.suffix, delete=False
  329. )
  330. return self.temp_file
  331. def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
  332. self.temp_file.close()
  333. os.unlink(self.temp_file.name)
  334. def write(
  335. content: Union[str, bytes],
  336. extension: str,
  337. extra: str = "",
  338. hash_type: str = "code",
  339. specified_dir: str = "",
  340. key: Optional[str] = None,
  341. ) -> tuple[str, str]:
  342. if key is None:
  343. # use striped content to compute hash so we don't end up with different
  344. # hashes just because the content begins/ends with different number of
  345. # spaces.
  346. key = get_hash(content.strip(), extra, hash_type)
  347. basename, _subdir, path = get_path(key, extension, specified_dir)
  348. if not os.path.exists(path):
  349. write_atomic(path, content, make_dirs=True)
  350. return basename, path
  351. def write_text(text: str) -> str:
  352. """
  353. Write the `text` to a file and return the path computed based on the hash.
  354. """
  355. return write(text, "txt")[1]
  356. def write_atomic(
  357. path_: str,
  358. content: Union[str, bytes],
  359. make_dirs: bool = False,
  360. encode_utf_8: bool = False,
  361. ) -> None:
  362. # Write into temporary file first to avoid conflicts between threads
  363. # Avoid using a named temporary file, as those have restricted permissions
  364. assert isinstance(content, (str, bytes)), (
  365. "Only strings and byte arrays can be saved in the cache"
  366. )
  367. path = Path(path_)
  368. if make_dirs:
  369. path.parent.mkdir(parents=True, exist_ok=True)
  370. tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp"
  371. write_mode = "w" if isinstance(content, str) else "wb"
  372. with tmp_path.open(write_mode, encoding="utf-8" if encode_utf_8 else None) as f:
  373. f.write(content)
  374. try:
  375. tmp_path.rename(target=path)
  376. except FileExistsError:
  377. if not _IS_WINDOWS:
  378. raise
  379. # On Windows file exist is expected: https://docs.python.org/3/library/pathlib.html#pathlib.Path.rename
  380. # Below two lines code is equal to `tmp_path.rename(path)` on non-Windows OS.
  381. # 1. Copy tmp_file to Target(Dst) file.
  382. shutil.copy2(src=tmp_path, dst=path)
  383. # 2. Delete tmp_file.
  384. os.remove(tmp_path)
  385. @dataclasses.dataclass
  386. class TensorMetadataAndValues:
  387. """
  388. TensorMetadata plus the elements as a list of raw values.
  389. Used for hashing inlined constants.
  390. """
  391. tensor_metadata: TensorMetadata
  392. values: list[Any]
  393. def _ident(x: T) -> T:
  394. return x
  395. def extract_tensor_metadata_for_cache_key(t: Tensor) -> TensorMetadata:
  396. """
  397. Extracts the tensor metadata and removes fields of the TensorMetadata
  398. that are not needed for caching
  399. """
  400. meta = extract_tensor_metadata(t)
  401. if not hasattr(t, "_is_inductor_static"):
  402. meta = dataclasses.replace(meta, storage_offset=0, storage_bytes=None)
  403. return meta
  404. class FxGraphCachePickler(pickle.Pickler):
  405. """
  406. Custom pickler to customize the pickling of some objects (Tensors), only for the
  407. purpose of computing a hash for keying into the FxGraphCache. Tensors contain
  408. objects that don't pickle and/or vary between runs, and we want to capture the
  409. data that allow us to compute a stable, but safe hash.
  410. """
  411. def __init__(
  412. self,
  413. gm: torch.fx.GraphModule,
  414. has_user_defined_triton_kernels: bool = False,
  415. ) -> None:
  416. """
  417. Create an FX graph pickler. If include_non_inlined=True, then pickling will
  418. include the _values_ for all Tensors. (Note that any tensors are constants
  419. attached as attributes to the GraphModule). Otherwise, pickling will include
  420. only the metadata for these tensors.
  421. """
  422. self._stream = io.BytesIO()
  423. super().__init__(self._stream)
  424. self.dispatch_table = copyreg.dispatch_table.copy()
  425. self.dispatch_table.update(
  426. {
  427. FakeTensor: functools.partial(self._reduce_fake_tensor),
  428. torch.Tensor: functools.partial(self._reduce_tensor),
  429. torch.nn.parameter.Parameter: functools.partial(self._reduce_tensor),
  430. torch.SymInt: functools.partial(self._reduce_symint),
  431. torch.fx.experimental._backward_state.BackwardState: functools.partial(
  432. self._reduce_unsupported
  433. ),
  434. }
  435. )
  436. if has_user_defined_triton_kernels:
  437. # Need to use runtime type as GraphModule generates a singleton in __new__ function
  438. self.dispatch_table[gm.__class__] = functools.partial(
  439. self._reduce_graph_module
  440. )
  441. # Run with pickler.fast so it doesn't intern strings, making the hash result more predictable
  442. # TODO: pickler.fast is technically deprecated. Will this work on new python versions?
  443. self.fast = True
  444. def _reduce_fake_tensor(
  445. self, t: Tensor
  446. ) -> tuple[Callable[[T], T], tuple[TensorMetadata]]:
  447. """
  448. Custom reducer to pickle FakeTensors.
  449. """
  450. metadata = extract_tensor_metadata_for_cache_key(t)
  451. return (_ident, (metadata,))
  452. def _reduce_tensor(
  453. self, t: Tensor
  454. ) -> tuple[Callable[[T], T], tuple[Union[TensorMetadata, TensorMetadataAndValues]]]:
  455. """
  456. Custom reducer to pickle Tensors. If we see tensors, we know they're constants
  457. stored as attributes on the GraphModule.
  458. """
  459. from .graph import GraphLowering
  460. if t.is_mkldnn:
  461. # TODO: These tensors don't currently pickle, so we can't cache a compiled
  462. # graph containing them. Just fail now. If mkldnn tensors get pickling
  463. # support, we can remove this.
  464. raise BypassFxGraphCache("mkldnn tensors unpickleable")
  465. metadata = extract_tensor_metadata_for_cache_key(t)
  466. # If this is a non-inlined frozen parameter, we consider the metadata only.
  467. if is_frozen_param(t) and not GraphLowering.can_inline_constant(t):
  468. return (_ident, (metadata,))
  469. # Very large tensors will be expensive to copy to cpu and hash. Let's at least
  470. # report any slowness.
  471. start = time()
  472. values = t.tolist()
  473. elapsed = time() - start
  474. if elapsed > 1.0:
  475. warnings.warn(
  476. f"FX graph cache copying of a large constant took {elapsed:.1}s. "
  477. "Please file an issue."
  478. )
  479. return (_ident, (TensorMetadataAndValues(metadata, values),))
  480. def _reduce_symint(self, s: SymInt) -> tuple[Callable[[T], T], tuple[str]]:
  481. """
  482. Custom reducer to pickle SymInts.
  483. """
  484. # For hashing purposes, we only care about the name of the symbol and not the
  485. # backed value. We evaluate guards stored with a cached graph to ensure a cached
  486. # entity with SymInt args is safe to reuse.
  487. return (_ident, (str(s),))
  488. def _reduce_unsupported(self, s: Any) -> NoReturn:
  489. """
  490. Custom reducer to handle any objects that we don't support and therefore
  491. raise to bypass caching.
  492. """
  493. raise BypassFxGraphCache("Reduce unsupported")
  494. def _reduce_graph_module(
  495. self, gm: torch.fx.GraphModule
  496. ) -> tuple[Any, tuple[dict[str, Any], str]]:
  497. """
  498. Custom reducer for graph module to handle irrelevant data for user
  499. defined triton kernels
  500. Essentially what we are doing here is a huge hack where user defined
  501. triton kernel contain a dynamo time side table and the arguments to the
  502. call_function are indices into this side table. These arguments are not
  503. for hashing purposes since we included the source code into the cache
  504. key and the numbers are prone to give false negatives due to ordering.
  505. """
  506. fn, (data, imports) = gm.__reduce__()
  507. code = data["_code"]
  508. code = re.sub(r"kernel_idx = \d+", "", code)
  509. code = re.sub(r"constant_args_idx = \d+", "", code)
  510. data["_code"] = code
  511. return fn, (data, imports)
  512. def dumps(self, obj: Any) -> bytes:
  513. """
  514. Pickle an object and return a byte string.
  515. """
  516. try:
  517. self.dump(obj)
  518. return self._stream.getvalue()
  519. except (TypeError, AttributeError) as e:
  520. # Some configs options may not pickle.
  521. log.warning("Failed to pickle cache key", exc_info=True)
  522. raise BypassFxGraphCache("Failed to pickle cache key") from e
  523. finally:
  524. # Reset our stream for the next dump.
  525. self._stream.seek(0)
  526. self._stream.truncate(0)
  527. def get_hash(self, obj: Any) -> str:
  528. """
  529. Serialize an object and return a hash of the bytes.
  530. """
  531. serialized_data = self.dumps(obj)
  532. return sha256_hash(serialized_data)
  533. def debug_lines(self, inp: FxGraphHashDetails) -> list[str]:
  534. """
  535. Get a printable string describing in more detail all the attributes
  536. comprising an object. Useful for debugging when one graph hashes
  537. to a different value than another.
  538. """
  539. def get_str(obj: Any) -> str:
  540. if isinstance(obj, torch.Tensor):
  541. return str(extract_tensor_metadata_for_cache_key(obj))
  542. elif isinstance(obj, bytes):
  543. return "<bytes>"
  544. elif type(obj) in self.dispatch_table:
  545. # Run the reducer on the object
  546. return str(self.dispatch_table[type(obj)](obj)[1])
  547. else:
  548. return str(obj)
  549. lines = []
  550. for attr, obj in vars(inp).items():
  551. if isinstance(obj, list):
  552. for ii in range(len(obj)):
  553. h = self.get_hash(obj[ii])
  554. lines.append(f"[{h}] {attr}[{ii}]: {get_str(obj[ii])}")
  555. elif isinstance(obj, dict):
  556. for k, v in obj.items():
  557. h = self.get_hash(v)
  558. lines.append(f"[{h}] {attr}[{k}]: {get_str(v)}")
  559. else:
  560. h = self.get_hash(obj)
  561. lines.append(f"[{h}] {attr}: {get_str(obj)}")
  562. return lines
  563. def build_code_hash(
  564. roots: list[str] | None, prefix: str, hasher: hashlib._Hash
  565. ) -> None:
  566. for lib in sorted(pkgutil.iter_modules(roots, prefix), key=lambda x: x.name):
  567. spec = lib.module_finder.find_spec(lib.name, None)
  568. assert spec is not None
  569. module = spec.origin
  570. assert module is not None
  571. with open(module, "rb") as f:
  572. hasher.update(spec.name.encode("utf-8"))
  573. hasher.update(f.read())
  574. if lib.ispkg:
  575. # need to also hash submodules
  576. build_code_hash(spec.submodule_search_locations, f"{spec.name}.", hasher)
  577. def torch_key_cache(func: Callable[[], bytes]) -> Callable[[], bytes]:
  578. """
  579. This function is a reimplementation of functools.lru_cache with a
  580. set function that allows prepopulating the cache.
  581. """
  582. # Use list for reference semantics
  583. _cache: list[bytes] = []
  584. def wrapper() -> bytes:
  585. if len(_cache) == 0:
  586. _cache.append(func())
  587. return _cache[0]
  588. def set_val(val: bytes) -> None:
  589. assert len(_cache) == 0
  590. _cache.append(val)
  591. def clear() -> None:
  592. _cache.clear()
  593. wrapper.set = set_val # type: ignore[attr-defined]
  594. wrapper.clear = clear # type: ignore[attr-defined]
  595. return wrapper
  596. @torch_key_cache
  597. def torch_key() -> bytes:
  598. """
  599. Compute a key that contains relevant information about torch source files
  600. """
  601. with dynamo_timed("inductor_codecache_torch_key", log_pt2_compile_event=False):
  602. if not config.is_fbcode():
  603. def get_code_hash(root: str) -> bytes:
  604. # This function isn't meant to be used outside of torch_key, just a
  605. # helper for clarity. Instead, use torch_key() directly when you need
  606. # a hash representing the state of the source code.
  607. extra_files = (
  608. "codegen/aoti_runtime/interface.cpp",
  609. "script.ld",
  610. )
  611. inductor_root = os.path.dirname(__file__)
  612. extra_files = [os.path.join(inductor_root, x) for x in extra_files]
  613. hasher = hashlib.sha256()
  614. hasher.update(torch.__version__.encode("utf-8"))
  615. build_code_hash([root], "", hasher)
  616. for path in extra_files:
  617. if os.path.exists(path):
  618. with open(path, "rb") as f:
  619. hasher.update(f.read())
  620. return hasher.digest()
  621. return get_code_hash(_TORCH_PATH)
  622. from libfb.py import parutil
  623. return parutil.get_file_contents("torch/src_hash.txt").rstrip().encode("ascii")
  624. def get_inductor_root() -> str:
  625. return os.path.dirname(__file__)
  626. @dataclasses.dataclass
  627. class OrderedSetHolder:
  628. """
  629. See FxGraphHashDetails. Holds a sorted list to support stable hashing
  630. of set kwargs.
  631. """
  632. items: list[Any]
  633. class BypassFxGraphCache(Exception):
  634. """
  635. Exception to indicate that the FxGraphCache should be bypassed.
  636. """
  637. class FxGraphHashDetails:
  638. """
  639. Object to capture all the details for a compiled FX graph relevant to computing
  640. a safe and stable cache key.
  641. """
  642. # Excluded kwargs param that are not stable between runs
  643. EXCLUDED_KWARGS = ["graph_id"]
  644. def __init__(
  645. self,
  646. gm: torch.fx.GraphModule,
  647. example_inputs: Sequence[InputType],
  648. fx_kwargs: _CompileFxKwargs,
  649. inputs_to_check: Sequence[int],
  650. ) -> None:
  651. self.gm = gm
  652. self.example_inputs = example_inputs
  653. self.cache_key_tag = cconfig.cache_key_tag
  654. # Order kwargs so hashing is stable to changes in kwarg order. Although
  655. # it's technically a _CompileFxKwargs we don't actually need it typed as
  656. # such since we're just using it to generate a hash.
  657. self.fx_kwargs: dict[str, object] = {}
  658. for k, v in sorted(fx_kwargs.items()):
  659. if k not in self.EXCLUDED_KWARGS:
  660. if type(v) in (set, OrderedSet): # noqa: set_linter
  661. # Special case to handle set params. Python sets can't be
  662. # ordered, so sort the elements and store them in a proxy.
  663. self.fx_kwargs[k] = OrderedSetHolder(sorted(v)) # type: ignore[call-overload]
  664. else:
  665. self.fx_kwargs[k] = v
  666. from torch._higher_order_ops.triton_kernel_wrap import (
  667. kernel_side_table,
  668. triton_kernel_wrapper_functional,
  669. triton_kernel_wrapper_mutation,
  670. )
  671. from torch._inductor.codegen.wrapper import (
  672. user_defined_triton_kernel_transitive_closure_source_code,
  673. )
  674. # Node meta will not be part of gm's reduce function, so lets remember
  675. # the kernel source code separately
  676. self.user_defined_triton_source: list[Any] = []
  677. if gm is not None:
  678. for module in gm.modules():
  679. if not isinstance(module, torch.fx.GraphModule):
  680. continue
  681. for node in itertools.chain(
  682. module.graph.find_nodes(
  683. op="call_function", target=triton_kernel_wrapper_functional
  684. ),
  685. module.graph.find_nodes(
  686. op="call_function", target=triton_kernel_wrapper_mutation
  687. ),
  688. ):
  689. from triton.runtime.autotuner import Autotuner
  690. kernel = kernel_side_table.get_kernel(node.kwargs["kernel_idx"])
  691. configs = None
  692. if isinstance(kernel, Autotuner):
  693. if kernel.configs:
  694. configs = str(
  695. sorted(
  696. sorted(str(kv) for kv in c.all_kwargs().items())
  697. for c in kernel.configs
  698. )
  699. )
  700. kernel = kernel.fn
  701. kernel_source = (
  702. user_defined_triton_kernel_transitive_closure_source_code(
  703. kernel
  704. )
  705. )
  706. constant_args = kernel_side_table.get_constant_args(
  707. node.kwargs["constant_args_idx"]
  708. )
  709. self.user_defined_triton_source.append(
  710. (kernel_source, constant_args, configs)
  711. )
  712. # Alignment checks
  713. self.inputs_to_check = inputs_to_check
  714. no_tensor_inputs = not any(isinstance(x, torch.Tensor) for x in example_inputs)
  715. # This device index is usually already encoded by the device of the inputs
  716. # but fx graphs don't necessarily have tensor inputs. If there aren't any,
  717. # we need to guard on the device index in case we allocate cuda tensors
  718. if no_tensor_inputs and torch.accelerator.is_available():
  719. self.default_cuda_device_index = torch.accelerator.current_device_index()
  720. # 'Deterministic algorithms' can affect codegen via lowering to cuda kernels.
  721. self.deterministic_algorithms_settings = (
  722. torch.are_deterministic_algorithms_enabled(),
  723. torch.is_deterministic_algorithms_warn_only_enabled(),
  724. torch.utils.deterministic.fill_uninitialized_memory, # type: ignore[attr-defined]
  725. )
  726. # Global settings affecting matmul codegen.
  727. self.cuda_matmul_settings = (
  728. torch.backends.cuda.matmul.fp32_precision,
  729. torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction,
  730. torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction,
  731. )
  732. # Also hash on various system info (including the triton compiler version).
  733. self.torch_version = torch_key()
  734. self.system_info = CacheBase.get_system()
  735. self.inductor_config = config.save_config_portable(ignore_private_configs=False)
  736. # Custom post grad passes should provide an ID to hash.
  737. self.post_grad_custom_pre_pass = self._get_custom_pass_detail(
  738. config.post_grad_custom_pre_pass
  739. )
  740. # TODO: change to more holistic config rather than bundled_autograd_cache
  741. self.precompile_enabled = torch._functorch.config.bundled_autograd_cache
  742. self.post_grad_custom_post_pass = self._get_custom_pass_detail(
  743. config.post_grad_custom_post_pass
  744. )
  745. self.joint_custom_pre_pass = self._get_custom_pass_detail(
  746. config.joint_custom_pre_pass
  747. )
  748. self.joint_custom_post_pass = self._get_custom_pass_detail(
  749. config.joint_custom_post_pass
  750. )
  751. self._pre_fusion_custom_pass = self._get_custom_pass_detail_unsafe(
  752. config._pre_fusion_custom_pass
  753. )
  754. self._fuse_ddp_communication_passes = self._get_custom_pass_detail_unsafe(
  755. config._fuse_ddp_communication_passes
  756. )
  757. # Register indcutor backends and custom passes and get their UUIDs.
  758. init_backend_registration()
  759. self.custom_backend_passes = tuple(
  760. map(self._get_custom_pass_detail, custom_backend_passes.values())
  761. )
  762. # Save custom inductor codegen configs
  763. self.custom_backend_codegen_configs = {
  764. device: custom_config.save_config_portable(ignore_private_configs=False)
  765. for device, custom_config in custom_backend_codegen_configs.items()
  766. if custom_config is not None
  767. }
  768. # Register the custom partitioner function
  769. self._custom_partitioner_fn = self._get_custom_partitioner_fn_detail(
  770. config.custom_partitioner_fn
  771. )
  772. # This is mainly added to handle these two inductor configs, which are (unfortunately)
  773. # sometimes cache safe:
  774. # - _pre_fusion_custom_pass
  775. # - _fuse_ddp_communication_passes
  776. # Their types can be found in `torch/_inductor/config.py`, but:
  777. # - if they are string names, we can cache them safely (one is by default)
  778. # - if any of them are set to custom callables, we will need to cache miss
  779. # Future work is for someone to find any places where these functions are used
  780. # and force them to be of type CustomGraphPass, so we can guarantee serialization.
  781. def _get_custom_pass_detail_unsafe(self, custom_pass: Any) -> Optional[Any]:
  782. if not custom_pass:
  783. return None
  784. if isinstance(custom_pass, list):
  785. return [self._get_custom_pass_detail_unsafe(x) for x in custom_pass]
  786. if isinstance(custom_pass, str):
  787. return custom_pass
  788. if isinstance(custom_pass, CustomGraphPass):
  789. return custom_pass.uuid()
  790. if callable(custom_pass):
  791. # Returning None is safe here because we raise an explicit bypass error
  792. # later if we detect these passes are set to callables
  793. return None
  794. raise AssertionError(f"unknown config type: {str(type(custom_pass))}")
  795. def _get_custom_pass_detail(
  796. self, custom_pass: Union[CustomGraphPassType, CustomGraphModulePass]
  797. ) -> Optional[Any]:
  798. if not custom_pass:
  799. return None
  800. assert isinstance(custom_pass, (CustomGraphPass, CustomGraphModulePass))
  801. return custom_pass.uuid()
  802. def _get_custom_partitioner_fn_detail(
  803. self, custom_partitioner_fn: CustomPartitionerFnType
  804. ) -> Optional[Any]:
  805. if not custom_partitioner_fn:
  806. return None
  807. assert isinstance(custom_partitioner_fn, CustomPartitionerFn)
  808. return custom_partitioner_fn.uuid()
  809. def compiled_fx_graph_hash(
  810. gm: torch.fx.GraphModule,
  811. example_inputs: Sequence[InputType],
  812. fx_kwargs: _CompileFxKwargs,
  813. inputs_to_check: Sequence[int],
  814. ) -> tuple[str, list[str]]:
  815. """
  816. Generate a unique hash of the FX graph for caching.
  817. """
  818. details = FxGraphHashDetails(gm, example_inputs, fx_kwargs, inputs_to_check)
  819. has_user_defined_triton_kernels = len(details.user_defined_triton_source) != 0
  820. pickler = FxGraphCachePickler(gm, has_user_defined_triton_kernels)
  821. # The prefix distinguishes among the other kinds of objects we
  822. # cache in this module.
  823. key = "f" + pickler.get_hash(details)
  824. debug_lines = pickler.debug_lines(details)
  825. debug_str = "\n".join(debug_lines)
  826. log.debug(f"FX graph cache hash details for key {key}:\n{debug_str}") # noqa: G004
  827. return key, debug_lines
  828. def add_ephemeral_timeout_increase_for_distributed(time_saved_ns: int) -> int:
  829. """
  830. Ephemerally increases the NCCL timeout when compiling for a distributed job
  831. Returns amount of seconds increased
  832. """
  833. if not torch.distributed.is_available() or not torch.distributed.is_initialized():
  834. return 0
  835. increased_timeout_sec = int(time_saved_ns // 1e9) # convert to seconds
  836. if config.is_fbcode():
  837. fudge_factor = torch._utils_internal.justknobs_getval_int(
  838. "pytorch/remote_cache:ephemeral_timeout_fudge_factor_percentage"
  839. )
  840. log.info(
  841. "Ephemeral NCCL timeout increase fudge factor %d and original increase value %d",
  842. fudge_factor,
  843. increased_timeout_sec,
  844. )
  845. increased_timeout_sec += int(increased_timeout_sec * fudge_factor / 100)
  846. log.info("Increasing NCCL timeout by %d", increased_timeout_sec)
  847. dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs(
  848. timedelta(seconds=increased_timeout_sec)
  849. )
  850. return increased_timeout_sec
  851. class GuardedCache(Generic[T]):
  852. """
  853. Mixin for caches that have guards associated with their entries.
  854. """
  855. @classmethod
  856. def _get_tmp_dir_for_key(cls: type[GuardedCache[T]], _key: str) -> str:
  857. raise NotImplementedError("Implement _get_tmp_dir_for_key on parent class")
  858. @classmethod
  859. def iterate_over_candidates(
  860. cls: type[GuardedCache[T]],
  861. local: bool,
  862. remote_cache: Optional[RemoteCache[JsonDataTy]],
  863. key: str,
  864. ) -> Generator[tuple[T, bytes], None, None]:
  865. if local:
  866. subdir = cls._get_tmp_dir_for_key(key)
  867. if os.path.exists(subdir):
  868. for path in sorted(os.listdir(subdir)):
  869. try:
  870. with open(os.path.join(subdir, path), "rb") as f:
  871. content = f.read()
  872. yield pickle.loads(content), content
  873. except Exception:
  874. log.warning(
  875. "fx graph cache unable to load compiled graph",
  876. exc_info=True,
  877. )
  878. if remote_cache:
  879. try:
  880. if (cache_data := remote_cache.get(key)) is not None:
  881. assert isinstance(cache_data, dict)
  882. data = cache_data["data"]
  883. assert isinstance(data, (str, bytes))
  884. content = base64.b64decode(data)
  885. yield pickle.loads(content), content
  886. except Exception:
  887. log.warning(
  888. "%s unable to load compiled graph", cls.__name__, exc_info=True
  889. )
  890. @classmethod
  891. def find_guarded_entry(
  892. cls: type[GuardedCache[T]],
  893. key: str,
  894. local: bool,
  895. remote_cache: Optional[RemoteCache[JsonDataTy]],
  896. evaluate_guards: Callable[[str, Union[list[int], list[torch.SymInt]]], bool],
  897. hints: list[int],
  898. ) -> tuple[Optional[T], Optional[bytes], dict[str, str]]:
  899. """
  900. Find the first cache entry in iterate_over_candidates that passes `evaluate_guards`.
  901. Args:
  902. key: The cache key to look up
  903. local: Whether to check the local cache
  904. remote_cache: The remote cache to check, if any
  905. evaluate_guards: Function that evaluates whether a guard passes the check,
  906. given a list of hint values and the guard expression.
  907. hints: List of symint hints paired with evaluate_guards
  908. Returns:
  909. A tuple of (graph, pickled_content) if found, or (None, None) if not found
  910. """
  911. graph = None
  912. pickled_content = None
  913. result_status = "full_miss"
  914. sample_guards_expr = None
  915. # Iterate over any entries in the subdir for this key and evaluate
  916. # guards to determine whether there's a hit.
  917. for candidate, content in cls.iterate_over_candidates(local, remote_cache, key):
  918. assert hasattr(candidate, "guards_expr")
  919. if not candidate.guards_expr: # type: ignore[attr-defined]
  920. # No guards to evaluate, so this is a hit.
  921. graph = candidate
  922. pickled_content = content
  923. result_status = "hit"
  924. break
  925. # Evaluate the guard expression in the current context.
  926. # If there's not a cache hit, we don't want the evaluation to
  927. # affect the current env, e.g., cause the creation of new guards,
  928. # so we evaluate with the hints instead of the symbols.
  929. hit = bool(evaluate_guards(candidate.guards_expr, hints)) # type: ignore[attr-defined]
  930. if hit:
  931. graph = candidate
  932. pickled_content = content
  933. result_status = "hit"
  934. sample_guards_expr = candidate.guards_expr
  935. break
  936. else:
  937. # At least one guard missed, log this
  938. result_status = "guard_miss"
  939. sample_guards_expr = candidate.guards_expr
  940. info = {"cache_status_detailed": result_status}
  941. if sample_guards_expr is not None:
  942. info["cache_status_guard_expr"] = sample_guards_expr
  943. return graph, pickled_content, info
  944. @classmethod
  945. def _filter_backed_symints(
  946. cls: type[GuardedCache[T]], inputs: Sequence[InputType]
  947. ) -> list[torch.SymInt]:
  948. """
  949. Get the backed SymInt objects from the input list. Note that we can never
  950. have guards that depend on unbacked symint.
  951. """
  952. return [s for s in inputs if isinstance(s, torch.SymInt) and has_hint(s)]
  953. @classmethod
  954. def _get_shape_env(cls: type[GuardedCache[T]]) -> Optional[ShapeEnv]:
  955. """
  956. Helper to get the shape env from the tracing context.
  957. """
  958. ctx = torch._guards.TracingContext.try_get()
  959. if not ctx or not ctx.fake_mode:
  960. return None
  961. return ctx.fake_mode.shape_env
  962. @CacheArtifactFactory.register
  963. class InductorCacheArtifact(CacheArtifact):
  964. @override
  965. def populate_cache(self) -> None:
  966. FxGraphCache._write_to_local_cache(self.key, self.content)
  967. @override
  968. @staticmethod
  969. def type() -> str:
  970. return "inductor"
  971. class FxGraphCache(GuardedCache[CompiledFxGraph]):
  972. """
  973. Supports caching and reusing compiled Fx graphs.
  974. The overall strategy is as follows:
  975. - This cache stores entries on disk. When saving an entry, we can't
  976. serialize callables (that could be C++, Triton, etc.), so we serialize
  977. their own disk cache location. We then recreate the compiled artifact
  978. after fetching from disk.
  979. - For indexing the cache, we gather the fields relevant to identifying an
  980. FxGraph (the graph module, graph inputs, system settings etc.) into an
  981. FxGraphCacheDetails object, pickle it, and compute a hash for the key.
  982. See FxGraphCachePickler.
  983. - Among the metadata we store, we also include a guards expression that's
  984. appropriate for validating any symbols for Tensor arguments that have
  985. symbolic bounds. On cache lookup then, we evaluate those guards in the
  986. current context to validate that a cached entry can be served.
  987. - A given graph could have multiple compiled versions, corresponding to
  988. different sets of guards. Therefore, we store cache entries in the form:
  989. <temp dir>/<fx graph hash>/<serialized metadata>
  990. - On lookup, we compute the key from the graph details, iterate over all
  991. leaf files in the corresponding subdirectory, deserialize the entry, and
  992. evaluate its guards expression. If the evaluation succeeds, we have a
  993. cache hit. If it fails, we compile the graph and store a new entry.
  994. - Finally, on a cache hit, we need to make sure any guards that would
  995. have been created during compilation are added to the current context.
  996. """
  997. # TODO(masnesral): Investigate whether it's beneficial to store compiled graphs
  998. # in an in-memory cache after loading from disk.
  999. @staticmethod
  1000. def _get_tmp_dir() -> str:
  1001. """
  1002. Get the toplevel temporary directory for storing compiled graphs.
  1003. """
  1004. return os.path.join(cache_dir(), "fxgraph")
  1005. @classmethod
  1006. def _get_tmp_dir_for_key(cls: type[FxGraphCache], key: str) -> str:
  1007. """
  1008. Return the disk location for a given cache key.
  1009. """
  1010. return os.path.join(FxGraphCache._get_tmp_dir(), key[1:3], key)
  1011. @staticmethod
  1012. def cache_hit_post_compile(
  1013. graph: CompiledFxGraph,
  1014. cache_info: dict[str, Any],
  1015. constants: CompiledFxGraphConstants,
  1016. ) -> tuple[Optional[CompiledFxGraph], dict[str, Any]]:
  1017. """
  1018. Cache specific post compile steps that need to run if we find a graph in the cache
  1019. This includes putting bundled triton artifacts in the right place,
  1020. reloading the PyCodeCache artifact, etc.
  1021. These don't always happen (i.e. on a cache miss, so they are in a separate function from
  1022. CompiledFxGraph.post_compile)
  1023. """
  1024. if bundle := graph._triton_bundle:
  1025. triton_bundler_meta = TritonBundler.read_and_emit(bundle)
  1026. if (meta := triton_bundler_meta) is not None:
  1027. cache_info["triton_bundler_meta"] = str(meta)
  1028. CompileEventLogger.try_add_pt2_compile(
  1029. "inductor_compile", cached_kernel_names=meta.cached_kernel_names
  1030. )
  1031. CompileEventLogger.try_add_pt2_compile(
  1032. "AOTAutogradCache.inductor_load",
  1033. cached_kernel_names=meta.cached_kernel_names,
  1034. )
  1035. if len(meta.cached_kernel_names) > 0:
  1036. CompileEventLogger.try_(
  1037. CompileEventLogger.increment_toplevel, "num_triton_bundles"
  1038. )
  1039. try:
  1040. artifact_path = graph.after_deserialization(constants)
  1041. from .graph import GraphLowering
  1042. # This is used by tests to check the output for specific details.
  1043. if GraphLowering.save_output_code is not None:
  1044. GraphLowering.save_output_code(graph.source_code)
  1045. except OSError:
  1046. # Not expected, but in case the PyCodeCache entry is removed from
  1047. # underneath us, treat it as a cache miss and recompile.
  1048. return None, cache_info
  1049. inductor_meta = autotune_cache.inductor_meta_from_config()
  1050. code = graph.source_code
  1051. AutotuneCacheBundler.begin_compile(inductor_meta, code=code)
  1052. # Increment the cached metrics/counters by the amounts recorded when the FX
  1053. # graph was compiled for this cache entry. Pretending these counters
  1054. # were incremented normally is useful for testing with the cache enabled.
  1055. metrics.CachedMetricsHelper.apply_deltas(graph.metrics_deltas)
  1056. counters["inductor"] += graph.counter_deltas
  1057. output_code_log.debug("Output code: \n%s", code)
  1058. output_code_log.debug("Output code written to: %s", artifact_path)
  1059. # On cache hit, use artifact path as filename
  1060. trace_structured(
  1061. "artifact",
  1062. metadata_fn=lambda: {
  1063. "name": "fx_graph_runnable",
  1064. "encoding": "string",
  1065. },
  1066. payload_fn=lambda: graph.runnable_graph_str,
  1067. )
  1068. trace_structured(
  1069. "inductor_post_grad_graph",
  1070. payload_fn=lambda: graph.inductor_post_grad_graph_str,
  1071. )
  1072. trace_structured(
  1073. "inductor_output_code",
  1074. lambda: {"filename": artifact_path},
  1075. payload_fn=lambda: code,
  1076. )
  1077. trace_structured(
  1078. "artifact",
  1079. metadata_fn=lambda: {
  1080. "name": "inductor_provenance_tracking_node_mappings",
  1081. "encoding": "json",
  1082. },
  1083. payload_fn=lambda: graph.inductor_provenance_mapping_str,
  1084. )
  1085. trace_structured(
  1086. "artifact",
  1087. metadata_fn=lambda: {
  1088. "name": "inductor_provenance_tracking_kernel_stack_traces",
  1089. "encoding": "json",
  1090. },
  1091. payload_fn=lambda: graph.inductor_provenance_stack_traces_str,
  1092. )
  1093. return graph, cache_info
  1094. @staticmethod
  1095. def _lookup_graph(
  1096. key: str,
  1097. example_inputs: Sequence[InputType],
  1098. local: bool,
  1099. remote_cache: Optional[RemoteCache[JsonDataTy]],
  1100. constants: CompiledFxGraphConstants,
  1101. evaluate_guards: Optional[
  1102. Callable[[str, Union[list[int], list[torch.SymInt]]], bool]
  1103. ] = None,
  1104. ) -> tuple[Optional[CompiledFxGraph], dict[str, Any]]:
  1105. """
  1106. Lookup a compiled graph in the cache by key. On a hit, return the
  1107. deserialized CompiledFxGraph object. On a miss, return None.
  1108. `constants` tracks a list of constants, or a way to obtain the list of constants
  1109. associated with a given cache entry
  1110. `evaluate_guards` allows AOTAutogradCache and other callers to customize
  1111. what constitutes a guard success. Normally, a guard hit happens if
  1112. `shape_env.evaluate_guards_expression` returns True.
  1113. """
  1114. shape_env = FxGraphCache._get_shape_env()
  1115. assert shape_env is not None
  1116. symints = FxGraphCache._filter_backed_symints(example_inputs)
  1117. hints = [hint_int(s) for s in symints]
  1118. # If this config is turned on, everything is a guard hit and we check nothing
  1119. if config.unsafe_skip_cache_dynamic_shape_guards:
  1120. # This also makes it so we don't add anything to the dynamic
  1121. # shape environment
  1122. evaluate_guards = lambda x, y: True # noqa: E731
  1123. if evaluate_guards is None:
  1124. evaluate_guards = shape_env.evaluate_guards_expression
  1125. cache_info: dict[str, Any] = dict()
  1126. # Use the find_graph_for_key method to find a graph for the given key
  1127. graph, pickled_content, guard_info = FxGraphCache.find_guarded_entry(
  1128. key, local, remote_cache, evaluate_guards, hints
  1129. )
  1130. cache_info.update(guard_info)
  1131. if graph is None:
  1132. return None, cache_info
  1133. if pickled_content is not None:
  1134. CacheArtifactManager.record_artifact(
  1135. InductorCacheArtifact.type(), key, pickled_content
  1136. )
  1137. # Now re-evaluate with the symints to add any guards to the current env.
  1138. if graph.guards_expr:
  1139. check = bool(evaluate_guards(graph.guards_expr, symints))
  1140. assert check is True
  1141. log.debug(
  1142. "fx graph cache key %s post-load guards: %s", key, shape_env.guards
  1143. )
  1144. return FxGraphCache.cache_hit_post_compile(graph, cache_info, constants)
  1145. @staticmethod
  1146. def _write_to_local_cache(key: str, content: bytes) -> None:
  1147. subdir = FxGraphCache._get_tmp_dir_for_key(key)
  1148. if not os.path.exists(subdir):
  1149. os.makedirs(subdir, exist_ok=True)
  1150. # Use a hash of the serialized CompiledFxGraph to get a unique file
  1151. # name. The specific name doesn't matter since a lookup involves
  1152. # iterating over all entries in the parent subdir.
  1153. path = os.path.join(subdir, sha256_hash(content))
  1154. write_atomic(path, content, make_dirs=True)
  1155. @staticmethod
  1156. def _save_graph(
  1157. key: str,
  1158. compiled_graph: OutputCode,
  1159. example_inputs: Sequence[InputType],
  1160. local: bool,
  1161. remote_cache: Optional[RemoteCache[JsonDataTy]],
  1162. ) -> None:
  1163. """
  1164. Store a serialized CompiledFxGraph on disk.
  1165. """
  1166. from .compile_fx import CompiledFxGraph
  1167. assert isinstance(compiled_graph, CompiledFxGraph), (
  1168. f"serialization for {type(compiled_graph)} NYI"
  1169. )
  1170. # Before serializing, compute the guard expression that will be used to
  1171. # ensure that a CompiledFxGraph is valid when loaded from the cache. It's
  1172. # sufficient to consider only the SymInt args to the fx graph since the
  1173. # Tensor shapes are already captured in the hash for the cache key. Any
  1174. # Tensor arg with a symbolic shape will have a SymInt arg for the graph.
  1175. shape_env = FxGraphCache._get_shape_env()
  1176. assert shape_env is not None
  1177. symints = FxGraphCache._filter_backed_symints(example_inputs)
  1178. guards = shape_env.get_pruned_guards(symints)
  1179. compiled_graph.guards_expr = shape_env.produce_guards_expression(
  1180. placeholders=symints, guards=guards
  1181. )
  1182. disk_compiled_graph = copy(compiled_graph)
  1183. disk_compiled_graph.prepare_for_serialization()
  1184. try:
  1185. content = pickle.dumps(disk_compiled_graph)
  1186. except Exception:
  1187. log.warning(
  1188. "fx graph cache unable to serialize compiled graph", exc_info=True
  1189. )
  1190. counters["inductor"]["fxgraph_cache_pickle_error"] += 1
  1191. return
  1192. try:
  1193. CacheArtifactManager.record_artifact(
  1194. InductorCacheArtifact.type(), key, content
  1195. )
  1196. if local:
  1197. FxGraphCache._write_to_local_cache(key, content)
  1198. if remote_cache:
  1199. time_taken_ms = int((disk_compiled_graph._time_taken_ns or 0) // 1e6)
  1200. cache_data: JsonDataTy = {
  1201. "data": base64.b64encode(content).decode("ascii"),
  1202. "time_taken_ms": time_taken_ms,
  1203. }
  1204. remote_cache.put(key, cache_data)
  1205. except Exception:
  1206. log.warning("fx graph unable to write to cache", exc_info=True)
  1207. counters["inductor"]["fxgraph_cache_write_error"] += 1
  1208. @staticmethod
  1209. def _check_for_hop(gm: torch.fx.GraphModule) -> None:
  1210. for module in gm.modules():
  1211. if not isinstance(module, torch.fx.GraphModule):
  1212. continue
  1213. for node in module.graph.nodes:
  1214. if (
  1215. isinstance(node.target, torch._ops.HigherOrderOperator)
  1216. and not node.target.cacheable()
  1217. ):
  1218. raise BypassFxGraphCache(
  1219. f"Can't cache HigherOrderOperator: {node.target.name()}"
  1220. )
  1221. if node.op == "getattr" and isinstance(
  1222. getattr(gm, node.target), torch._C.ScriptObject
  1223. ):
  1224. raise BypassFxGraphCache("Can't cache torchbind objects")
  1225. @staticmethod
  1226. def _check_can_cache(gm: torch.fx.GraphModule) -> None:
  1227. """
  1228. Check some conditions that would preclude caching and raise BypassFxGraphCache
  1229. to bypass in case caching is not possible.
  1230. """
  1231. # Post grad custom passes must implement the CustomGraphPass or we don't
  1232. # know how to include them in the cache key calculation.
  1233. for p in (config.post_grad_custom_pre_pass, config.post_grad_custom_post_pass):
  1234. if p and (not isinstance(p, CustomGraphPass) or not p.uuid()):
  1235. raise BypassFxGraphCache("Unsupported post grad custom pass")
  1236. # Same with the joint custom passes
  1237. for p in (config.joint_custom_pre_pass, config.joint_custom_post_pass):
  1238. if p and (not isinstance(p, CustomGraphPass) or not p.uuid()):
  1239. raise BypassFxGraphCache("Unsupported joint custom pass")
  1240. # We should find any users of _pre_fusion_custom_pass and _fuse_ddp_communication_passes
  1241. # and ensure they are not passing us raw callables
  1242. if config._pre_fusion_custom_pass is not None:
  1243. if not isinstance(config._pre_fusion_custom_pass, CustomGraphPass):
  1244. raise BypassFxGraphCache("Unsupported _pre_fusion_custom_pass")
  1245. for p in config._fuse_ddp_communication_passes:
  1246. if callable(p) and not isinstance(p, CustomGraphPass):
  1247. raise BypassFxGraphCache("Unsupported _fuse_ddp_communication_pass")
  1248. # Freezing can embed constants that wouldn't be static across runs.
  1249. if has_frozen_params(gm) and not torch._utils_internal.justknobs_check(
  1250. "pytorch/inductor:allow_freezing_with_caching"
  1251. ):
  1252. raise BypassFxGraphCache("Skipping graph with frozen constants")
  1253. if config.aot_inductor.use_runtime_constant_folding:
  1254. raise BypassFxGraphCache(
  1255. "Runtime constant folding can introduce constants that aren't "
  1256. "static across runs"
  1257. )
  1258. from torch._inductor.compiler_bisector import CompilerBisector
  1259. if CompilerBisector.bisection_enabled:
  1260. log.debug("dont cache graph when bisect enabled")
  1261. raise BypassFxGraphCache
  1262. # The treatment of guards in the caching implementation requires that
  1263. # we have a shape env.
  1264. if FxGraphCache._get_shape_env() is None:
  1265. log.debug("fx graph cache no shape env")
  1266. raise BypassFxGraphCache("No shape env")
  1267. # We skip caching if there are any HOPs or torchbind objects.
  1268. FxGraphCache._check_for_hop(gm)
  1269. @staticmethod
  1270. def prepare_key(
  1271. gm: torch.fx.GraphModule,
  1272. example_inputs: Sequence[InputType],
  1273. fx_kwargs: _CompileFxKwargs,
  1274. inputs_to_check: Sequence[int],
  1275. remote: bool,
  1276. ) -> tuple[Optional[tuple[str, list[str]]], dict[str, Any]]:
  1277. """
  1278. Checks that the inductor input is cacheable, then computes
  1279. and returns the cache key for the input.
  1280. Returns (key_info, cache_info) where:
  1281. - key_info is (hash_key, debug_lines), and
  1282. - cache_info will contain debug info in the event of BypassFxGraphCache.
  1283. NB: It is possible to have this function return a union instead. But
  1284. I personally believe it is more annoying/difficult to read in that format.
  1285. """
  1286. try:
  1287. FxGraphCache._check_can_cache(gm)
  1288. key, debug_lines = compiled_fx_graph_hash(
  1289. gm, example_inputs, fx_kwargs, inputs_to_check
  1290. )
  1291. except BypassFxGraphCache as e:
  1292. counters["inductor"]["fxgraph_cache_bypass"] += 1
  1293. log.info("Bypassing FX Graph Cache because '%s'", e)
  1294. if remote:
  1295. log_cache_bypass("bypass_fx_graph", str(e))
  1296. cache_info = {
  1297. "cache_state": "bypass",
  1298. "cache_bypass_reason": str(e),
  1299. "cache_event_time": time_ns(),
  1300. }
  1301. return None, cache_info
  1302. # If key exists, then cache_info will come from load_with_key
  1303. return (key, debug_lines), {}
  1304. @staticmethod
  1305. def get_remote_cache() -> Optional[RemoteCache[JsonDataTy]]:
  1306. """
  1307. Attempts to load the remote cache, returns None on error.
  1308. """
  1309. cache_id = "fx-graph-v1"
  1310. return create_cache(
  1311. cache_id,
  1312. config.is_fbcode(),
  1313. "FbRemoteFxGraphCache",
  1314. "RemoteFxGraphCache",
  1315. )
  1316. @staticmethod
  1317. def load_with_key(
  1318. key: str,
  1319. debug_lines: list[str],
  1320. example_inputs: Sequence[InputType],
  1321. local: bool,
  1322. remote_cache: Optional[RemoteCache[JsonDataTy]],
  1323. is_backward: bool,
  1324. constants: CompiledFxGraphConstants,
  1325. evaluate_guards: Optional[
  1326. Callable[[str, Union[list[int], list[torch.SymInt]]], bool]
  1327. ] = None,
  1328. ) -> tuple[Optional[CompiledFxGraph], dict[str, Any]]:
  1329. """
  1330. Lookup the graph with the given key, and return results and metadata.
  1331. Doesn't do any logging on its own, because AOTAutograd handles a cache miss
  1332. differently from FXGraphCache.
  1333. """
  1334. compiled_graph, cache_info = FxGraphCache._lookup_graph(
  1335. key, example_inputs, local, remote_cache, constants, evaluate_guards
  1336. )
  1337. cache_info = {
  1338. **cache_info,
  1339. "key": key,
  1340. "components": debug_lines,
  1341. "cache_event_time": time_ns(),
  1342. }
  1343. if compiled_graph is not None:
  1344. log.info("fx graph cache hit for key %s", key)
  1345. counters["inductor"]["fxgraph_cache_hit"] += 1
  1346. cache_info["cache_state"] = "hit"
  1347. if remote_cache:
  1348. # Count remote cache hit stats
  1349. CompileEventLogger.try_(
  1350. CompileEventLogger.increment_toplevel,
  1351. "inductor_fx_remote_cache_hit_count",
  1352. )
  1353. CompileEventLogger.try_(
  1354. CompileEventLogger.add_to_set_toplevel,
  1355. "inductor_fx_remote_cache_hit_keys",
  1356. key,
  1357. )
  1358. if (time_saved_ns := compiled_graph._time_taken_ns) is not None:
  1359. cache_info["time_saved_ns"] = time_saved_ns
  1360. CompileEventLogger.try_(
  1361. CompileEventLogger.increment_toplevel,
  1362. "distributed_ephemeral_timeout_us",
  1363. time_saved_ns // 1000,
  1364. )
  1365. if (
  1366. ephemeral_increase
  1367. := add_ephemeral_timeout_increase_for_distributed(time_saved_ns)
  1368. ) != 0:
  1369. cache_info["ephemeral_timeout_increase"] = ephemeral_increase
  1370. else:
  1371. if remote_cache:
  1372. # Count remote cache miss stats
  1373. CompileEventLogger.try_(
  1374. CompileEventLogger.increment_toplevel,
  1375. "inductor_fx_remote_cache_miss_count",
  1376. )
  1377. CompileEventLogger.try_(
  1378. CompileEventLogger.add_to_set_toplevel,
  1379. "inductor_fx_remote_cache_miss_keys",
  1380. key,
  1381. )
  1382. log.info("fx graph cache miss for key %s", key)
  1383. counters["inductor"]["fxgraph_cache_miss"] += 1
  1384. cache_info["cache_state"] = "miss"
  1385. return compiled_graph, cache_info
  1386. @staticmethod
  1387. def clear() -> None:
  1388. """
  1389. Clear out the on-disk cache.
  1390. """
  1391. try:
  1392. shutil.rmtree(FxGraphCache._get_tmp_dir())
  1393. except FileNotFoundError:
  1394. pass
  1395. @functools.cache
  1396. def split_aot_inductor_output_path(path: str) -> tuple[str, str]:
  1397. def get_module_ext_type() -> str:
  1398. if _IS_WINDOWS:
  1399. return ".pyd"
  1400. else:
  1401. return ".so"
  1402. """Returns the path where the AOT Inductor compiled kernels are stored."""
  1403. if path.endswith(get_module_ext_type()):
  1404. return os.path.split(path)
  1405. elif path.endswith(".pt2"):
  1406. return os.path.split(path)
  1407. else:
  1408. return path, ""
  1409. @clear_on_fresh_cache
  1410. class CudaKernelParamCache:
  1411. cache: dict[str, dict[str, Any]] = {}
  1412. cache_clear = staticmethod(cache.clear)
  1413. @classmethod
  1414. def set(
  1415. cls,
  1416. key: str,
  1417. params: dict[str, Optional[str]],
  1418. cubin: str,
  1419. bin_type: str,
  1420. asm: Optional[str] = None,
  1421. asm_type: Optional[str] = None,
  1422. ) -> None:
  1423. basename = None
  1424. if config.aot_inductor.package_cpp_only:
  1425. assert config.triton.unique_kernel_names, (
  1426. "package_cpp_only requires triton kernel names to be unique"
  1427. )
  1428. assert params["mangled_name"], "Missing kernel name"
  1429. basename = params["mangled_name"]
  1430. _, bin_path = write(
  1431. cubin,
  1432. bin_type,
  1433. hash_type=bin_type,
  1434. specified_dir=split_aot_inductor_output_path(
  1435. config.aot_inductor.output_path
  1436. )[0],
  1437. key=basename,
  1438. )
  1439. # Retrieve the basename again in case it is a generated hashcode
  1440. basename, _ = get_name_and_dir_from_output_file_path(bin_path)
  1441. if config.aot_inductor.emit_multi_arch_kernel:
  1442. bin_type_to_ext = {"cubin": ".fatbin", "spv": ".spv"}
  1443. assert bin_type in bin_type_to_ext.keys(), (
  1444. "multi_arch_kernel_binary only supported in CUDA/XPU"
  1445. )
  1446. base_path, _ = os.path.splitext(bin_path)
  1447. bin_path = base_path + bin_type_to_ext[bin_type]
  1448. asm_path: str = ""
  1449. if (
  1450. config.aot_inductor.emit_multi_arch_kernel
  1451. or config.aot_inductor.package_cpp_only
  1452. ):
  1453. assert asm, "Missing kernel assembly code"
  1454. assert asm_type, "Missing kernel assembly type"
  1455. _, asm_path = write(
  1456. asm,
  1457. asm_type,
  1458. hash_type=asm_type,
  1459. specified_dir=split_aot_inductor_output_path(
  1460. config.aot_inductor.output_path
  1461. )[0],
  1462. # make sure asm file has the same basename
  1463. key=basename,
  1464. )
  1465. params[get_cpp_wrapper_cubin_path_name()] = bin_path
  1466. params["asm"] = asm_path
  1467. cls.cache[key] = params
  1468. @classmethod
  1469. def get(cls, key: str) -> Optional[dict[str, Any]]:
  1470. return cls.cache.get(key, None)
  1471. @classmethod
  1472. def get_keys(cls) -> KeysView[str]:
  1473. return cls.cache.keys()
  1474. class AotCodeCompiler:
  1475. """
  1476. Compile AOT Inductor generated code.
  1477. """
  1478. @classmethod
  1479. def compile(
  1480. cls,
  1481. graph: GraphLowering,
  1482. wrapper_code: str,
  1483. kernel_code: str,
  1484. serialized_extern_kernel_nodes: Optional[str],
  1485. *,
  1486. device_type: str,
  1487. additional_files: list[str],
  1488. ) -> Union[list[Union[str, Weights]], str]:
  1489. """
  1490. Returns the .so path, or returns a list of files that were generated if
  1491. config.aot_inductor.package=True.
  1492. """
  1493. generated_files: list[Union[str, Weights]] = additional_files # type: ignore[assignment]
  1494. _set_gpu_runtime_env() # cpp_extension consults the env
  1495. picked_vec_isa = pick_vec_isa()
  1496. vec_isa_cmd_gen = CppBuilder(
  1497. name="o",
  1498. sources="i",
  1499. BuildOption=CppTorchDeviceOptions(
  1500. vec_isa=picked_vec_isa,
  1501. device_type=device_type,
  1502. aot_mode=graph.aot_mode,
  1503. ),
  1504. )
  1505. # write function will calc source_code hash, the same source code with different
  1506. # ISA level should be generate different hash.
  1507. # So we need get a command_line which contains isa related parameter as a part of hash key.
  1508. # And then pass the command_line to below write function as extra parameter to
  1509. # guarantee the source code hash contains ISA difference.
  1510. cpp_command = repr(vec_isa_cmd_gen.get_command_line())
  1511. # Meta internal AOTInductor CPU
  1512. use_relative_path = (
  1513. config.is_fbcode() and device_type == "cpu" and graph.aot_mode
  1514. )
  1515. (
  1516. specified_output_path,
  1517. specified_artifact_name,
  1518. ) = split_aot_inductor_output_path(config.aot_inductor.output_path)
  1519. # TODO (benjaminglass1): the CMake packaging path doesn't support linking files
  1520. # built with different flags. Until that's implemented, append the kernel code
  1521. # to the wrapper and build everything at max optimization.
  1522. if config.aot_inductor.package_cpp_only:
  1523. wrapper_code = "\n".join((wrapper_code, kernel_code))
  1524. kernel_code = ""
  1525. wrapper_key, wrapper_path = write(
  1526. wrapper_code,
  1527. "wrapper.cpp",
  1528. extra=cpp_command,
  1529. specified_dir=specified_output_path,
  1530. key=config.aot_inductor.model_name_for_generated_files,
  1531. )
  1532. kernel_code = (
  1533. f"// Triton kernels are embedded as comments in {wrapper_path}\n"
  1534. + kernel_code
  1535. )
  1536. _, kernel_path = write(
  1537. kernel_code,
  1538. "kernel.cpp",
  1539. extra=cpp_command,
  1540. specified_dir=specified_output_path,
  1541. key=config.aot_inductor.model_name_for_generated_files,
  1542. )
  1543. header_code = ""
  1544. header_path = ""
  1545. if config.aot_inductor.compile_standalone:
  1546. # to link statically, we also need a header file
  1547. with open(
  1548. os.path.join(
  1549. os.path.dirname(os.path.dirname(__file__)),
  1550. "csrc",
  1551. "inductor",
  1552. "aoti_runtime",
  1553. "model.h",
  1554. )
  1555. ) as f:
  1556. # model_name_for_generated_files is guaranteed to be non-empty when compile_standalone
  1557. model_class_name = config.aot_inductor.model_name_for_generated_files
  1558. class_name = f"AOTInductorModel{model_class_name}"
  1559. header_code = f.read()
  1560. # we replace like this to avoid replacing
  1561. # AOTInductorModelBase and AOTInductorModelKernelsBase
  1562. header_code = (
  1563. header_code.replace("<AOTInductorModel>", f"<{class_name}>")
  1564. .replace("AOTInductorModel(", f"{class_name}(")
  1565. .replace("AOTInductorModel :", f"{class_name} :")
  1566. )
  1567. _, header_path = write(
  1568. header_code,
  1569. "h",
  1570. specified_dir=specified_output_path,
  1571. key=model_class_name,
  1572. )
  1573. # Log the AOTInductor wrapper and kernel code, if needed.
  1574. with WritableTempFile("w+") as t:
  1575. """
  1576. Avoid "Permission denied error" on Windows:
  1577. with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file:
  1578. # Not writable on Windows:
  1579. # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
  1580. Example:
  1581. with WritableTempFile("w", suffix=".gv") as temp_file:
  1582. tree.to_dotfile(temp_file.name)
  1583. """
  1584. t.writelines((wrapper_code, "\n", kernel_code, "\n"))
  1585. t.flush()
  1586. V.debug.output_code(t.name, extension="cpp")
  1587. if config.aot_inductor.package:
  1588. generated_files.append(wrapper_path)
  1589. if not config.aot_inductor.package_cpp_only:
  1590. generated_files.append(kernel_path)
  1591. if config.aot_inductor.compile_standalone:
  1592. generated_files.append(header_path)
  1593. output_code_log.info("Wrapper code written to: %s", wrapper_path)
  1594. output_code_log.info("Kernel code written to: %s", kernel_path)
  1595. trace_structured(
  1596. "graph_dump",
  1597. lambda: {
  1598. "name": "inductor_aot_wrapper_code",
  1599. "type": "cpp",
  1600. "filename": wrapper_path,
  1601. },
  1602. payload_fn=lambda: wrapper_code,
  1603. )
  1604. trace_structured(
  1605. "graph_dump",
  1606. lambda: {
  1607. "name": "inductor_aot_kernel_code",
  1608. "type": "cpp",
  1609. "filename": kernel_path,
  1610. },
  1611. payload_fn=lambda: kernel_code,
  1612. )
  1613. if config.aot_inductor.compile_standalone:
  1614. output_code_log.info("Header code written to: %s", header_path)
  1615. trace_structured(
  1616. "graph_dump",
  1617. lambda: {
  1618. "name": "inductor_aot_header_code",
  1619. "type": "cpp",
  1620. "filename": header_path,
  1621. },
  1622. payload_fn=lambda: header_code,
  1623. )
  1624. # We use a file lock below to protect FS operations. The lock file
  1625. # is scoped to the 'key', so make sure the consts_s is protected
  1626. # by the same lock:
  1627. wrapper_path_operator = Path(wrapper_path)
  1628. kernel_path_operator = Path(kernel_path)
  1629. specified_sub_dir = wrapper_path_operator.parent / wrapper_key
  1630. if not specified_sub_dir.exists():
  1631. specified_sub_dir.mkdir(exist_ok=True)
  1632. cmake_path = str(Path(specified_sub_dir) / "CMakeLists.txt")
  1633. def _compile_consts(consts: bytes, platform: str) -> str:
  1634. # Load from aot_inductor, and update the value on demand.
  1635. use_asm_build: bool = config.aot_inductor.use_consts_asm_build
  1636. if platform == "linux":
  1637. if graph.mutated_buffers & OrderedSet(graph.constants.keys()):
  1638. # .data section is between .text and .bss. When the size of .data is large,
  1639. # during the linking, the relocation of .text against .bss may overflow.
  1640. # Rename it to .ldata so that it won't be in between the .text and .bss section
  1641. if len(consts) > 2_000_000_000:
  1642. raise ValueError(
  1643. "Models with buffer mutation included doesn't support constants greater than 2GB!"
  1644. )
  1645. section_attr = '.ldata, "aw"'
  1646. else:
  1647. section_attr = '.lrodata, "a"'
  1648. symbol_prefix = ""
  1649. elif platform == "darwin":
  1650. section_attr = "__DATA,__data"
  1651. symbol_prefix = "_"
  1652. elif platform == "win32":
  1653. symbol_prefix = ""
  1654. # ASM build is not supported on Windows, force use CPP build.
  1655. use_asm_build = False
  1656. else:
  1657. raise RuntimeError(f"Unsupported platform: {platform}")
  1658. # Intel compiler failed to compile this manually constructed assembly file.
  1659. # Switch XPU to use consts cpp build.
  1660. if device_type == "xpu":
  1661. use_asm_build = False
  1662. is_large_consts = len(consts) > 1024
  1663. is_zero_size_consts = len(consts) == 0
  1664. def format_consts_to_gnu_asm(
  1665. consts: bytes,
  1666. align_bytes: int,
  1667. symbol_prefix: str,
  1668. is_large_consts: bool,
  1669. ) -> tuple[str, str]:
  1670. consts_asm = f"\t.section\t{section_attr}\n"
  1671. consts_asm += f"\t.balign {align_bytes}\n"
  1672. consts_asm += f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n"
  1673. consts_asm += f"{symbol_prefix}_binary_constants_bin_start:\n"
  1674. if not is_large_consts:
  1675. for c in consts:
  1676. consts_asm += f"\t.byte {c}\n"
  1677. # Add one element even if constants are empty
  1678. # Otherwise assembler will not put them in data section
  1679. if not consts:
  1680. consts_asm += "\t.space 1\n"
  1681. else:
  1682. consts_asm += "\t.quad 0x1234567899abcdef\n"
  1683. consts_asm += f"\t.space {len(consts) - 8}\n"
  1684. consts_asm += f".globl\t{symbol_prefix}_binary_constants_bin_end\n"
  1685. consts_asm += f"{symbol_prefix}_binary_constants_bin_end:\n"
  1686. return consts_asm, "weights.S"
  1687. # Use c++ to convert consts to object file can support more compilers, such as msvc and icx.
  1688. def format_consts_to_cpp(
  1689. consts: bytes, align_bytes: int, symbol_prefix: str
  1690. ) -> tuple[str, str]:
  1691. consts_size = len(consts)
  1692. asan_attr = """#if defined(__clang__) || defined (__GNUC__)\t\n\
  1693. #define ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address")))\t\n\
  1694. #else\t\n\
  1695. #define ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n\
  1696. #endif\t\n\
  1697. \t\n\
  1698. ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n"""
  1699. const_cpp = asan_attr
  1700. const_cpp += f"alignas({align_bytes}) extern "
  1701. const_cpp += f"unsigned char {symbol_prefix}_binary_constants_bin_start[{consts_size}] = {{\t\n"
  1702. count_bytes = 0
  1703. for c in consts:
  1704. const_cpp += f"{c}, "
  1705. count_bytes = count_bytes + 1
  1706. if count_bytes % 16 == 0:
  1707. const_cpp += "\t\n"
  1708. const_cpp += "};\t\n"
  1709. const_cpp += f"alignas({align_bytes}) extern unsigned char * {symbol_prefix}_binary_constants_bin_end;\t\n"
  1710. return const_cpp, "weights.cpp"
  1711. def get_zero_consts_asm_code(
  1712. align_bytes: int,
  1713. symbol_prefix: str,
  1714. ) -> tuple[str, str]:
  1715. """
  1716. This function handles zero-sized constants because the C++ standard prohibits zero-length arrays:
  1717. https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c
  1718. On Windows (MSVC):
  1719. The compiler reports error C2466 for zero-sized arrays:
  1720. https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2466
  1721. Solution: Use assembly compilation to handle this case.
  1722. Why not use Win32 assembly for all paths?
  1723. ml64 only supports alignment up to 16 bytes, which isn't optimal for performance.
  1724. Cross-platform implementation:
  1725. Linux: Added '-pedantic' to disable zero-sized arrays in C++ compiler
  1726. Windows: MSVC naturally rejects zero-sized arrays by default
  1727. """
  1728. if _IS_WINDOWS:
  1729. # Windows ml64 is max support align to 16, but it is no effect to zero size data.
  1730. asm_code = """
  1731. option casemap:none
  1732. .data
  1733. ?_binary_constants_bin_start@@3PAEA:
  1734. align 16
  1735. ?_binary_constants_bin_end@@3PAEA:
  1736. align 16
  1737. public ?_binary_constants_bin_start@@3PAEA
  1738. public ?_binary_constants_bin_end@@3PAEA
  1739. end
  1740. """
  1741. asm_ext = "asm"
  1742. else:
  1743. asm_code = f"\t.section\t{section_attr}\n"
  1744. asm_code += f"\t.balign {align_bytes}\n"
  1745. asm_code += (
  1746. f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n"
  1747. )
  1748. asm_code += f"{symbol_prefix}_binary_constants_bin_start:\n"
  1749. asm_code += f".globl\t{symbol_prefix}_binary_constants_bin_end\n"
  1750. asm_code += f"{symbol_prefix}_binary_constants_bin_end:\n"
  1751. asm_ext = "S"
  1752. return asm_code, asm_ext
  1753. if use_asm_build:
  1754. consts_code, code_ext = format_consts_to_gnu_asm(
  1755. consts, ALIGN_BYTES, symbol_prefix, is_large_consts
  1756. )
  1757. else:
  1758. if is_zero_size_consts:
  1759. consts_code, code_ext = get_zero_consts_asm_code(
  1760. ALIGN_BYTES, symbol_prefix
  1761. )
  1762. else:
  1763. consts_code, code_ext = format_consts_to_cpp(
  1764. consts, ALIGN_BYTES, symbol_prefix
  1765. )
  1766. _, consts_s = write(
  1767. consts_code,
  1768. code_ext,
  1769. specified_dir=str(specified_sub_dir),
  1770. key=config.aot_inductor.model_name_for_generated_files,
  1771. )
  1772. consts_s = Path(consts_s)
  1773. object_build_options = CppTorchDeviceOptions(
  1774. device_type=device_type,
  1775. aot_mode=graph.aot_mode,
  1776. compile_only=True,
  1777. use_relative_path=use_relative_path,
  1778. )
  1779. object_builder = CppBuilder(
  1780. name=str(consts_s.stem),
  1781. sources=str(consts_s),
  1782. output_dir=str(consts_s.parent),
  1783. BuildOption=object_build_options,
  1784. )
  1785. consts_o = object_builder.get_target_file_path()
  1786. if use_asm_build is False and is_zero_size_consts:
  1787. run_asm_build_object(str(consts_s), consts_o, str(consts_s.parent))
  1788. else:
  1789. object_builder.build()
  1790. if is_large_consts and use_asm_build:
  1791. with open(consts_o, "r+b") as f:
  1792. f.seek(0)
  1793. hdr = f.read(1024)
  1794. # Search for magic number and write the actual data over it
  1795. start_idx = (
  1796. hdr.find(b"\xef\xcd\xab\x99\x78\x56\x34\x12")
  1797. if sys.byteorder == "little"
  1798. else hdr.find(b"\x12\x34\x56\x78\x99\xab\xcd\xef")
  1799. )
  1800. assert start_idx != -1
  1801. f.seek(start_idx)
  1802. pos = 0
  1803. while pos < len(consts):
  1804. rc = f.write(consts[pos:])
  1805. pos += rc
  1806. # Remove the .S file to save space
  1807. os.remove(consts_s)
  1808. return consts_o
  1809. from torch.utils._filelock import FileLock
  1810. lock_dir = get_lock_dir()
  1811. lock = FileLock(
  1812. os.path.join(lock_dir, wrapper_key + ".lock"), timeout=LOCK_TIMEOUT
  1813. )
  1814. with lock:
  1815. if serialized_extern_kernel_nodes:
  1816. extern_kernel_nodes_json = str(
  1817. wrapper_path_operator.with_suffix(".json")
  1818. )
  1819. with open(extern_kernel_nodes_json, "w") as f:
  1820. f.write(serialized_extern_kernel_nodes)
  1821. if config.aot_inductor.package:
  1822. generated_files.append(extern_kernel_nodes_json)
  1823. metadata = config.aot_inductor.metadata
  1824. metadata["AOTI_DEVICE_KEY"] = device_type
  1825. # Save user provided metadata
  1826. meta_json = str(
  1827. wrapper_path_operator.with_name(
  1828. f"{wrapper_path_operator.stem}_metadata.json"
  1829. )
  1830. )
  1831. for k, v in config.aot_inductor.metadata.items():
  1832. assert isinstance(k, str) and isinstance(v, (str)), (
  1833. "Metadata must only contain strings"
  1834. )
  1835. with open(meta_json, "w") as f:
  1836. f.write(json.dumps(config.aot_inductor.metadata))
  1837. kernel_meta_json = str(
  1838. kernel_path_operator.with_name(
  1839. f"{kernel_path_operator.stem}_metadata.json"
  1840. )
  1841. )
  1842. shutil.copy(meta_json, kernel_meta_json)
  1843. if config.aot_inductor.package:
  1844. generated_files.append(meta_json)
  1845. if not config.aot_inductor.package_cpp_only:
  1846. generated_files.append(kernel_meta_json)
  1847. output_so = (
  1848. config.aot_inductor.output_path
  1849. if specified_artifact_name
  1850. else str(wrapper_path_operator.with_suffix(".so"))
  1851. )
  1852. all_cuda = all(
  1853. graph.get_original_value_of_constant(name).is_cuda
  1854. for name in graph.constants.keys()
  1855. if name not in graph.folded_constants
  1856. )
  1857. def _to_bytes(t: torch.Tensor, all_cuda: bool) -> bytes:
  1858. def _pad_to_alignment(raw_bytes: bytes) -> bytes:
  1859. padded_bytes = raw_bytes.ljust(
  1860. (len(raw_bytes) + ALIGN_BYTES - 1) // ALIGN_BYTES * ALIGN_BYTES,
  1861. b"\x00",
  1862. )
  1863. return padded_bytes
  1864. # This serializes the tensor's untyped_storage to bytes by accessing
  1865. # the raw data of the underlying structure.
  1866. import ctypes
  1867. if t.numel() == 0:
  1868. return b""
  1869. if t.is_mkldnn:
  1870. data_ptr = torch.ops.mkldnn.data_ptr(t)
  1871. nbytes = torch.ops.mkldnn._nbytes(t)
  1872. else:
  1873. t_cpu = t.untyped_storage().cpu()
  1874. data_ptr = t_cpu.data_ptr()
  1875. nbytes = t_cpu.nbytes()
  1876. raw_array = ctypes.cast(
  1877. data_ptr,
  1878. ctypes.POINTER(ctypes.c_ubyte * nbytes),
  1879. )
  1880. raw_bytes = bytes(raw_array.contents)
  1881. return raw_bytes if all_cuda else _pad_to_alignment(raw_bytes)
  1882. if config.aot_inductor.package_constants_in_so:
  1883. serialized_weights = b"".join(
  1884. _to_bytes(graph.get_original_value_of_constant(name), all_cuda)
  1885. for name in graph.constants.keys()
  1886. if name not in graph.folded_constants
  1887. )
  1888. else:
  1889. serialized_weights = b""
  1890. if config.aot_inductor.package_constants_on_disk:
  1891. # We need to return a storage key here because the original value tensor might be a clone
  1892. weights_dict = Weights(
  1893. {
  1894. graph.allocated_constant_name[name]: (
  1895. graph.get_original_value_of_constant(name),
  1896. TensorProperties(graph.constants[name]),
  1897. )
  1898. for name in graph.constants.keys()
  1899. if name not in graph.folded_constants
  1900. }
  1901. )
  1902. generated_files.append(weights_dict)
  1903. consts_size = len(serialized_weights)
  1904. # TODO: Fix mmap weights with cuda
  1905. use_mmap_weights = not config.is_fbcode() and consts_size > 2_000_000_000
  1906. if config.aot_inductor.force_mmap_weights:
  1907. use_mmap_weights = True
  1908. compile_command: dict[str, Any] = {
  1909. "aot_mode": graph.aot_mode,
  1910. "device_type": device_type,
  1911. "use_mmap_weights": use_mmap_weights,
  1912. "use_relative_path": use_relative_path,
  1913. "vec_isa": picked_vec_isa,
  1914. }
  1915. # If we're packaging via CMake, we build the whole code at max optimization.
  1916. wrapper_build_options = CppTorchDeviceOptions(
  1917. compile_only=True,
  1918. min_optimize=not config.aot_inductor.package_cpp_only,
  1919. **compile_command,
  1920. )
  1921. kernel_build_options = CppTorchDeviceOptions(
  1922. compile_only=True,
  1923. **compile_command,
  1924. )
  1925. # potentially, precompile the AOT header for this device
  1926. if config.aot_inductor.precompile_headers and not _IS_WINDOWS:
  1927. header_file = _get_cpp_wrapper_header(
  1928. device_type, aot_mode=graph.aot_mode
  1929. )
  1930. wrapper_build_options.precompiled_header = _precompile_header(
  1931. header_file,
  1932. cpp_command,
  1933. min_optimize=not config.aot_inductor.package_cpp_only,
  1934. **compile_command,
  1935. )
  1936. if cpp_prefix := _get_cpp_prefix_header(device_type):
  1937. kernel_build_options.precompiled_header = _precompile_header(
  1938. cpp_prefix,
  1939. cpp_command,
  1940. **compile_command,
  1941. )
  1942. wrapper_builder = CppBuilder(
  1943. name=str(wrapper_path_operator.stem),
  1944. sources=wrapper_path,
  1945. output_dir=str(wrapper_path_operator.parent),
  1946. BuildOption=wrapper_build_options,
  1947. )
  1948. wrapper_compile_cmd = wrapper_builder.get_command_line()
  1949. wrapper_o = wrapper_builder.get_target_file_path()
  1950. kernel_builder = CppBuilder(
  1951. name=str(kernel_path_operator.stem),
  1952. sources=kernel_path,
  1953. output_dir=str(wrapper_path_operator.parent),
  1954. BuildOption=kernel_build_options,
  1955. )
  1956. kernel_compile_cmd = kernel_builder.get_command_line()
  1957. kernel_o = kernel_builder.get_target_file_path()
  1958. log.debug("aot wrapper compilation command: %s", wrapper_compile_cmd)
  1959. log.debug("aot kernel compilation command: %s", kernel_compile_cmd)
  1960. if config.aot_inductor.package_cpp_only:
  1961. # Not doing the actual compilation here
  1962. compile_flags = str(
  1963. wrapper_path_operator.with_name(
  1964. f"{wrapper_path_operator.stem}_compile_flags.json"
  1965. )
  1966. )
  1967. wrapper_build_options.save_flags_to_json(compile_flags)
  1968. generated_files.append(compile_flags)
  1969. wrapper_builder.save_compile_cmd_to_cmake(cmake_path, device_type)
  1970. wrapper_builder.save_src_to_cmake(cmake_path, wrapper_path)
  1971. generated_files.append(cmake_path)
  1972. else:
  1973. try:
  1974. wrapper_builder.build()
  1975. except (exc.CppCompileError, SkipFrame) as e:
  1976. if " is too big to optimize" in str(e):
  1977. raise RuntimeError(
  1978. "Please use torch._inductor.config.aot_inductor.compile_wrapper_opt_level = 'O0' flag."
  1979. ) from e
  1980. raise e
  1981. kernel_builder.build()
  1982. if not use_mmap_weights:
  1983. aot_constants = serialized_weights
  1984. magic_number = 0
  1985. else:
  1986. magic_number = cast(
  1987. int, torch.randint(0, torch.iinfo(torch.int64).max, (1,)).item()
  1988. )
  1989. aot_constants = struct.pack("qq", consts_size + 8, magic_number)
  1990. consts_o = _compile_consts(aot_constants, sys.platform)
  1991. custom_obj_idx = 0
  1992. # Note that custom_objs_config.json file is different from the model_constants_config.json file produced
  1993. # in package_sigmoid(). The keys in custom_objs_config.json directly correspond to the arg name in extern
  1994. # nodes json. The key in model_constants_config.json produced by package_sigmoid is the attribute name in the
  1995. # user model code.
  1996. qual_name_to_id = {} # Map from constant name to its name in constants folder
  1997. for custom_obj_idx, (name, constant) in enumerate(
  1998. graph.torchbind_constants.items()
  1999. ):
  2000. if isinstance(
  2001. constant, torch._library.fake_class_registry.FakeScriptObject
  2002. ):
  2003. constant = constant.real_obj
  2004. assert isinstance(constant, torch._C.ScriptObject)
  2005. custom_obj_name = f"{CUSTOM_OBJ_FILENAME_PREFIX}{custom_obj_idx}"
  2006. log.debug("saving script object %s as %s", name, custom_obj_name)
  2007. qual_name_to_id[name] = custom_obj_name
  2008. custom_obj_bytes = torch._C._pickle_save(constant)
  2009. custom_obj_path = os.path.join(
  2010. wrapper_path_operator.parent, custom_obj_name
  2011. )
  2012. write_atomic(custom_obj_path, custom_obj_bytes, True)
  2013. generated_files.append(custom_obj_path)
  2014. if qual_name_to_id:
  2015. constants_config_json = os.path.join(
  2016. wrapper_path_operator.parent, "custom_objs_config.json"
  2017. )
  2018. with open(constants_config_json, "w") as f:
  2019. f.write(json.dumps(qual_name_to_id))
  2020. generated_files.append(constants_config_json)
  2021. gpu_codecache: Union[ROCmCodeCache, CUDACodeCache] = (
  2022. ROCmCodeCache() if torch.version.hip else CUDACodeCache()
  2023. )
  2024. gpu_kernels_o = gpu_codecache.aot_kernels_o.copy()
  2025. # clear the list of aot kernels after each linking
  2026. gpu_codecache.aot_kernels_o.clear()
  2027. if gpu_kernels_o:
  2028. assert not config.aot_inductor.emit_multi_arch_kernel, (
  2029. "TODO: add emit_multi_arch_kernel support for cutlass kernels"
  2030. )
  2031. cubins_o = []
  2032. asm_files = []
  2033. if not _IS_WINDOWS:
  2034. ld, objcopy = get_ld_and_objcopy(use_relative_path)
  2035. kernels = getattr(V.graph.wrapper_code, "_kernel_name_to_body", {})
  2036. for kernel_name, value in CudaKernelParamCache.cache.items():
  2037. if kernel_name not in kernels:
  2038. # It is possible that CudaKernelParamCache contains more Triton kernels
  2039. # than what the current graph uses
  2040. continue
  2041. if asm_file := value["asm"]:
  2042. asm_files.append(asm_file)
  2043. cubin_file = value[get_cpp_wrapper_cubin_path_name()]
  2044. if (
  2045. config.aot_inductor.emit_multi_arch_kernel
  2046. and device_type == "cuda"
  2047. ):
  2048. current_arch = _nvcc_arch_as_compile_option()
  2049. cmd = (
  2050. f"{_cuda_compiler()} -fatbin {asm_file} -o {cubin_file} "
  2051. # Triton only allows generating PTX version as same as the current arch
  2052. f"-gencode arch=compute_{current_arch},code=compute_{current_arch} "
  2053. # Include SASS for the current specific arch
  2054. f"-gencode arch=compute_{current_arch},code=sm_{current_arch} "
  2055. )
  2056. try:
  2057. subprocess.run(
  2058. cmd.split(),
  2059. capture_output=True,
  2060. text=True,
  2061. check=True,
  2062. )
  2063. except subprocess.CalledProcessError as e:
  2064. print(
  2065. f"{cmd} failed with:\nstdout:\n{e.stdout}\nstderr:\n{e.stderr}",
  2066. file=sys.stderr,
  2067. )
  2068. raise
  2069. if config.aot_inductor.embed_kernel_binary:
  2070. # Embed cubin files into model.so using objcopy
  2071. cubins_o.append(
  2072. convert_cubin_to_obj(cubin_file, kernel_name, ld, objcopy)
  2073. )
  2074. output_name, output_dir = get_name_and_dir_from_output_file_path(output_so)
  2075. so_build_options = CppTorchDeviceOptions(
  2076. vec_isa=picked_vec_isa,
  2077. device_type=device_type,
  2078. aot_mode=graph.aot_mode,
  2079. use_relative_path=use_relative_path,
  2080. )
  2081. obj_srcs = [wrapper_o, kernel_o, consts_o, *gpu_kernels_o, *cubins_o]
  2082. so_builder = CppBuilder(
  2083. name=output_name,
  2084. sources=obj_srcs,
  2085. output_dir=output_dir,
  2086. BuildOption=so_build_options,
  2087. )
  2088. link_cmd = so_builder.get_command_line()
  2089. output_so = so_builder.get_target_file_path()
  2090. log.debug("aot linkage command: %s", link_cmd)
  2091. # Append cmds to the end of codegen-ed wrapper file
  2092. with open(wrapper_path, "a") as f:
  2093. f.write("\n")
  2094. f.write(f"// Compile cmd\n// {wrapper_compile_cmd}\n")
  2095. f.write(f"// Link cmd\n// {link_cmd}\n")
  2096. with open(kernel_path, "a") as f:
  2097. f.write("\n")
  2098. f.write(f"// Compile cmd\n// {kernel_compile_cmd}\n")
  2099. f.write(f"// Link cmd\n// {link_cmd}\n")
  2100. if config.aot_inductor.package_cpp_only:
  2101. linker_flags = str(
  2102. wrapper_path_operator.with_name(
  2103. f"{wrapper_path_operator.stem}_linker_flags.json"
  2104. )
  2105. )
  2106. so_build_options.save_flags_to_json(linker_flags)
  2107. generated_files.append(linker_flags)
  2108. generated_files.append(_LINKER_SCRIPT)
  2109. # If we only want to package the cpp, then we need to save the
  2110. # weights separately into a bin, and we also need to prevent compiling the so
  2111. if use_mmap_weights:
  2112. weight_file = str(
  2113. wrapper_path_operator.with_name(
  2114. f"{wrapper_path_operator.stem}_serialized_weights.bin"
  2115. )
  2116. )
  2117. with open(weight_file, "wb") as f_weights:
  2118. f_weights.write(serialized_weights)
  2119. f_weights.write(struct.pack("q", magic_number))
  2120. generated_files.append(weight_file)
  2121. else:
  2122. # TODO: unify to always use mmap_weights
  2123. generated_files.append(consts_o)
  2124. so_builder.save_src_to_cmake(cmake_path, consts_o)
  2125. if config.aot_inductor.emit_multi_arch_kernel:
  2126. so_builder.save_kernel_asm_to_cmake(cmake_path, asm_files)
  2127. generated_files.extend(asm_files)
  2128. else:
  2129. obj_srcs = [*gpu_kernels_o, *cubins_o]
  2130. generated_files.extend(obj_srcs)
  2131. for obj in obj_srcs:
  2132. so_builder.save_src_to_cmake(cmake_path, obj)
  2133. so_builder.save_link_cmd_to_cmake(cmake_path)
  2134. else:
  2135. so_builder.build()
  2136. for o_file in obj_srcs:
  2137. if o_file in gpu_kernels_o:
  2138. continue
  2139. # Remove these as they are not needed anymore
  2140. os.remove(o_file)
  2141. if use_mmap_weights:
  2142. def get_page_size() -> int:
  2143. # Don't use resource.getpagesize() on Windows, as it is a Unix specific package
  2144. # as seen in https://docs.python.org/2/library/resource.html
  2145. if _IS_WINDOWS:
  2146. from ctypes import ( # type: ignore[attr-defined]
  2147. byref,
  2148. Structure,
  2149. windll,
  2150. )
  2151. from ctypes.wintypes import DWORD, LPVOID, WORD
  2152. class SYSTEM_INFO(Structure):
  2153. _fields_ = [
  2154. ("wProcessorArchitecture", WORD),
  2155. ("wReserved", WORD),
  2156. ("dwPageSize", DWORD),
  2157. ("lpMinimumApplicationAddress", LPVOID),
  2158. ("lpMaximumApplicationAddress", LPVOID),
  2159. ("dwActiveProcessorMask", DWORD),
  2160. ("dwNumberOfProcessors", DWORD),
  2161. ("dwProcessorType", DWORD),
  2162. ("dwAllocationGranularity", DWORD),
  2163. ("wProcessorLevel", WORD),
  2164. ("wProcessorRevision", WORD),
  2165. ]
  2166. si = SYSTEM_INFO()
  2167. windll.kernel32.GetSystemInfo(byref(si))
  2168. sys_page_size = si.dwPageSize
  2169. else:
  2170. import resource
  2171. sys_page_size = resource.getpagesize()
  2172. return sys_page_size
  2173. page_size_ = get_page_size()
  2174. page_size = max(16384, page_size_)
  2175. with open(output_so, "a+b") as f_so:
  2176. so_size = f_so.tell()
  2177. # Page align the weights
  2178. f_so.write(b" " * (page_size - so_size % page_size))
  2179. f_so.write(serialized_weights)
  2180. f_so.write(struct.pack("q", magic_number))
  2181. if config.aot_inductor.package:
  2182. generated_files.append(output_so)
  2183. if config.aot_inductor.package:
  2184. if config.trace.provenance_tracking_level != 0:
  2185. kernel_info = torch._inductor.debug.create_kernel_information_json()
  2186. kernel_info_json = os.path.join(
  2187. wrapper_path_operator.parent, "kernel_information.json"
  2188. )
  2189. with open(kernel_info_json, "w") as f:
  2190. f.write(json.dumps(kernel_info, indent=4))
  2191. generated_files.append(kernel_info_json)
  2192. # We want to return the directory that contains all the AOTI
  2193. # generated files, not just the so
  2194. # return os.path.split(output_so)[0]
  2195. return generated_files
  2196. return output_so
  2197. _libgomp: Optional[CDLL] = None
  2198. def custom_op_wrapper(op: str, *args: Any) -> Union[list[c_void_p], c_void_p, None]:
  2199. # This function will be called from generated cpp wrapper code in the JIT mode.
  2200. # Because tensors will be passed in as AtenTensorHandle, we need to explicitly convert them.
  2201. def convert_arg(arg: Any) -> Any:
  2202. if str(type(arg)) == "<class 'PyCapsule'>":
  2203. # No easy way to do isinstance check on PyCapsule
  2204. return torch._C._aoti.alloc_tensor_by_stealing_from_void_ptr(arg)
  2205. elif isinstance(arg, (list, tuple)):
  2206. return type(arg)(convert_arg(a) for a in arg)
  2207. else:
  2208. return arg
  2209. converted_args = [convert_arg(arg) for arg in args]
  2210. assert op.startswith("torch.ops."), (
  2211. op + " can not be called through custom_op_wrapper"
  2212. )
  2213. func = None
  2214. for i, s in enumerate(op.split(".")):
  2215. if i == 0:
  2216. func = importlib.import_module(s)
  2217. func = getattr(func, s)
  2218. assert callable(func), op + " can not be loaded through custom_op_wrapper"
  2219. # convert any kwarg-only arguments to kwargs
  2220. kwargs = dict()
  2221. for func_arg, conv_arg in zip(func._schema.arguments, converted_args):
  2222. if func_arg.kwarg_only:
  2223. kwargs[func_arg.name] = conv_arg
  2224. if kwargs:
  2225. del converted_args[-len(kwargs) :]
  2226. result = func(*converted_args, **kwargs)
  2227. if result is None:
  2228. return None
  2229. if isinstance(result, (list, tuple)):
  2230. # unsafe_alloc_void_ptrs_from_tensors expects result contains tensor only
  2231. result = [torch.tensor([]) if r is None else r for r in result]
  2232. for i, r in enumerate(result):
  2233. assert isinstance(r, torch.Tensor), op + " returns a list of non-tensors"
  2234. return torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(result) # type: ignore[arg-type]
  2235. assert isinstance(result, torch.Tensor), op + " returns a non-tensor"
  2236. return torch._C._aoti.unsafe_alloc_void_ptr_from_tensor(result)
  2237. # Precompiled headers are persistent past program runtime, but associated with one
  2238. # specific compiler version and set of flags. We explicitly use default_cache_dir here
  2239. # because these headers need to be global, rather than ignored by fresh_cache.
  2240. _HEADER_DIR = os.path.join(default_cache_dir(), "precompiled_headers")
  2241. _HEADER_LOCK_DIR = os.path.join(_HEADER_DIR, "locks")
  2242. @functools.cache
  2243. def _precompile_header(
  2244. header: str,
  2245. hashable_cmd_line: str,
  2246. **compile_command: Any,
  2247. ) -> str:
  2248. assert not _IS_WINDOWS, (
  2249. "CppBuilder does not currently support precompiling on Windows!"
  2250. )
  2251. # Get the preprocessed output from the header file to be precompiled. This allows
  2252. # us to properly invalidate the file cache when any header dependency changes. This
  2253. # is thread-safe, as each thread will get its own temporary directory.
  2254. #
  2255. # N.B. we can't use NamedTemporaryFile here because Windows errors out on attempts
  2256. # to read from a file with an open write handle.
  2257. with tempfile.TemporaryDirectory() as preprocessing_dir:
  2258. preprocessing_header = Path(preprocessing_dir) / "header.hpp"
  2259. preprocessing_header.write_text(f"#include <{header}>\n")
  2260. preprocessor = CppBuilder(
  2261. name=str(preprocessing_header)[:-4], # strip off the .hpp extension
  2262. sources=str(preprocessing_header),
  2263. BuildOption=CppTorchDeviceOptions(**compile_command, preprocessing=True),
  2264. )
  2265. preprocessor.build()
  2266. def _get_file_checksum(filename: str) -> str:
  2267. """Reading the whole preprocessed header in for hashing is very expensive,
  2268. but calling a fast hashing utility in a subprocess is cheap."""
  2269. # If Windows support needs to be added here, use certutil -hashfile.
  2270. cmd_output = subprocess.run(
  2271. ("openssl", "sha512", filename), capture_output=True, text=True
  2272. )
  2273. return cmd_output.stdout.split()[-1]
  2274. preprocessor_hash = _get_file_checksum(preprocessor.get_target_file_path())
  2275. header_build_option = CppTorchDeviceOptions(**compile_command, precompiling=True)
  2276. header_hash, header_full_path = write(
  2277. content=f"#include <{header}>\n",
  2278. extension="h",
  2279. extra=(
  2280. hashable_cmd_line
  2281. + preprocessor_hash
  2282. + get_compiler_version_info(header_build_option.get_compiler())
  2283. ),
  2284. specified_dir=_HEADER_DIR,
  2285. )
  2286. cpp_builder = CppBuilder(
  2287. name=header_full_path,
  2288. sources=header_full_path,
  2289. BuildOption=header_build_option,
  2290. )
  2291. # _worker_compile_cpp will automatically ignore any compilation whose result already
  2292. # exists, so this is always safe.
  2293. os.makedirs(_HEADER_LOCK_DIR, exist_ok=True)
  2294. _worker_compile_cpp(
  2295. os.path.join(_HEADER_LOCK_DIR, f"{header_hash}.lock"),
  2296. (cpp_builder,),
  2297. )
  2298. return header_full_path
  2299. def _get_cpp_prefix_header(device: str) -> Optional[str]:
  2300. if device.startswith("cpu"):
  2301. return "torch/csrc/inductor/cpp_prefix.h"
  2302. return None
  2303. def _get_cpp_wrapper_header(device: str, aot_mode: bool = False) -> str:
  2304. """Given a device type (and optionally whether we're in AOT Inductor mode), returns
  2305. the path to the cpp_wrapper header file to be precompiled."""
  2306. base_device = device.split(":", maxsplit=1)[0]
  2307. is_array_ref = config.aot_inductor.allow_stack_allocation and base_device == "cpu"
  2308. return (
  2309. "torch/csrc/inductor/"
  2310. f"{'aoti_include' if aot_mode else 'cpp_wrapper'}/"
  2311. f"{'array_ref' if is_array_ref else base_device}.h"
  2312. )
  2313. @clear_on_fresh_cache
  2314. class CppCodeCache:
  2315. """Compiles and caches C++ libraries. Users of this class supply the source code to
  2316. be compiled, while compilation flags are set by CppBuilder."""
  2317. cache: dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2318. cache_clear = staticmethod(cache.clear)
  2319. cpp_compile_command_flags: dict[str, Any] = {}
  2320. @staticmethod
  2321. def _load_library_inner(path: str, key: str) -> Union[CDLL, ModuleType]:
  2322. return cdll.LoadLibrary(path)
  2323. @classmethod
  2324. def _load_library(cls, path: str, key: str) -> Union[CDLL, ModuleType]:
  2325. try:
  2326. result = cls._load_library_inner(path, key)
  2327. result.key = key # type: ignore[union-attr]
  2328. return result
  2329. except (ImportError, OSError) as e:
  2330. if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"):
  2331. # hacky workaround for fbcode/buck
  2332. global _libgomp
  2333. _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1")
  2334. result = cls._load_library_inner(path, key)
  2335. result.key = key # type: ignore[union-attr]
  2336. return result
  2337. if "failed to map segment from shared object" in str(e):
  2338. raise OSError(
  2339. f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder "
  2340. "is mounted with noexec (e.g., by default Docker mounts tmp file systems "
  2341. f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another "
  2342. "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable."
  2343. ) from e
  2344. raise
  2345. @classmethod
  2346. def _get_uncompiled_header(cls, device: str) -> str | None:
  2347. """
  2348. Given a device type, returns the path to a CPP header file to be precompiled.
  2349. """
  2350. return None
  2351. @classmethod
  2352. def load_async(
  2353. cls,
  2354. main_code: str,
  2355. device_type: str = "cpu",
  2356. submit_fn: Any = None,
  2357. extra_flags: Sequence[str] = (),
  2358. optimized_code: Optional[str] = None,
  2359. ) -> Any:
  2360. """Compile and load a C++ library. Returns a callable that returns the loaded
  2361. library."""
  2362. compile_command = {
  2363. **cls.cpp_compile_command_flags,
  2364. "device_type": device_type,
  2365. "extra_flags": extra_flags,
  2366. "use_relative_path": config.is_fbcode(),
  2367. "vec_isa": pick_vec_isa(),
  2368. }
  2369. _set_gpu_runtime_env() # cpp_extension consults the env
  2370. # Note the distinction between the two booleans. We do minimal optimization if
  2371. # the optimized_code argument is present at all, since that's how the user of
  2372. # this function opts in, but we do compilation and linking in one step if the
  2373. # optimized_code argument is empty (as a micro-optimization).
  2374. main_build_option = CppTorchDeviceOptions(
  2375. compile_only=bool(optimized_code),
  2376. min_optimize=optimized_code is not None,
  2377. **compile_command,
  2378. )
  2379. optimized_build_option = CppTorchDeviceOptions(
  2380. compile_only=True, **compile_command
  2381. )
  2382. def get_hashable_command_line(build_option: BuildOptionsBase) -> str:
  2383. """Writing the code to file will calculate a hash, which we need to vary if
  2384. the command line flags change. This implements a mostly-generic way of
  2385. validating that."""
  2386. return CppBuilder(
  2387. name="o", sources="i", BuildOption=build_option
  2388. ).get_command_line()
  2389. main_cmd_line = get_hashable_command_line(main_build_option)
  2390. optimized_cmd_line = get_hashable_command_line(optimized_build_option)
  2391. key, main_path = write(
  2392. main_code, "main.cpp", extra=f"{optimized_code} {main_cmd_line}"
  2393. )
  2394. # Don't bother writing if the argument is empty.
  2395. if optimized_code:
  2396. _, optimized_path = write(
  2397. optimized_code, "optimized.cpp", extra=optimized_cmd_line
  2398. )
  2399. else:
  2400. # Unused, but makes type checkers happy.
  2401. optimized_path = os.devnull
  2402. if key not in cls.cache:
  2403. from torch.utils._filelock import FileLock
  2404. lock_path = os.path.join(get_lock_dir(), key + ".lock")
  2405. future: Optional[Future[Any]] = None
  2406. lib = None
  2407. # if requested, pre-compile any headers
  2408. if config.cpp_cache_precompile_headers and not _IS_WINDOWS:
  2409. if header := cls._get_uncompiled_header(device_type):
  2410. main_build_option.precompiled_header = _precompile_header(
  2411. header,
  2412. main_cmd_line,
  2413. min_optimize=optimized_code is not None,
  2414. **compile_command,
  2415. )
  2416. # Currently, the optimized_code field is only used for cpp kernel code,
  2417. # so go ahead and precompile the relevant header here. Revisit this
  2418. # decision if that ever changes.
  2419. if optimized_code and (header := _get_cpp_prefix_header(device_type)):
  2420. optimized_build_option.precompiled_header = _precompile_header(
  2421. header,
  2422. optimized_cmd_line,
  2423. **compile_command,
  2424. )
  2425. main_name, output_dir = get_name_and_dir_from_output_file_path(main_path)
  2426. main_builder = CppBuilder(
  2427. name=main_name,
  2428. sources=main_path,
  2429. BuildOption=main_build_option,
  2430. output_dir=output_dir,
  2431. )
  2432. if optimized_code:
  2433. optimized_name, _ = get_name_and_dir_from_output_file_path(
  2434. optimized_path
  2435. )
  2436. optimized_builder = CppBuilder(
  2437. name=optimized_name,
  2438. sources=optimized_path,
  2439. BuildOption=optimized_build_option,
  2440. output_dir=output_dir,
  2441. )
  2442. linker = CppBuilder(
  2443. name=main_name,
  2444. sources=[
  2445. main_builder.get_target_file_path(),
  2446. optimized_builder.get_target_file_path(),
  2447. ],
  2448. BuildOption=CppTorchDeviceOptions(**compile_command),
  2449. output_dir=output_dir,
  2450. )
  2451. worker_fn = functools.partial(
  2452. _worker_compile_cpp,
  2453. lock_path,
  2454. (main_builder, optimized_builder, linker),
  2455. )
  2456. binary_path = normalize_path_separator(linker.get_target_file_path())
  2457. else:
  2458. worker_fn = functools.partial(
  2459. _worker_compile_cpp, lock_path, (main_builder,)
  2460. )
  2461. binary_path = normalize_path_separator(
  2462. main_builder.get_target_file_path()
  2463. )
  2464. def load_fn() -> Any:
  2465. nonlocal lib
  2466. if lib is None:
  2467. if future is not None:
  2468. future.result()
  2469. result = worker_fn()
  2470. assert result is None
  2471. lib = cls._load_library(binary_path, key)
  2472. assert lib is not None
  2473. return lib
  2474. if submit_fn is not None:
  2475. with FileLock(lock_path, timeout=LOCK_TIMEOUT):
  2476. if not os.path.exists(binary_path):
  2477. future = submit_fn(worker_fn)
  2478. cls.cache[key] = load_fn
  2479. return cls.cache[key]
  2480. @classmethod
  2481. def load(cls, *args: Any, **kwargs: Any) -> Any:
  2482. return cls.load_async(*args, **kwargs)()
  2483. def _worker_compile_cpp(
  2484. lock_path: str,
  2485. cpp_builders: Sequence[CppBuilder],
  2486. ) -> None:
  2487. from torch.utils._filelock import FileLock
  2488. with FileLock(lock_path, timeout=LOCK_TIMEOUT):
  2489. for builder in cpp_builders:
  2490. if not os.path.exists(builder.get_target_file_path()):
  2491. builder.build()
  2492. # Customized Python binding for cpp kernels
  2493. @clear_on_fresh_cache
  2494. class CppPythonBindingsCodeCache(CppCodeCache):
  2495. cache: dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2496. cache_clear = staticmethod(cache.clear)
  2497. cpp_compile_command_flags = {
  2498. # kernels have no dependency on libtorch
  2499. "include_pytorch": False,
  2500. "shared": True,
  2501. }
  2502. entry_function = "kernel"
  2503. call_entry_function = "kernel({}); Py_RETURN_NONE;"
  2504. extra_parse_arg = ""
  2505. suffix_template = textwrap.dedent(
  2506. """
  2507. // Python bindings to call {entry_func}():
  2508. #define PY_SSIZE_T_CLEAN
  2509. #include <Python.h>
  2510. #include <sstream>
  2511. #include <cstdlib>
  2512. #ifndef _MSC_VER
  2513. #if __cplusplus < 202002L
  2514. // C++20 (earlier) code
  2515. // https://en.cppreference.com/w/cpp/language/attributes/likely
  2516. #define likely(x) __builtin_expect(!!(x), 1)
  2517. #define unlikely(x) __builtin_expect(!!(x), 0)
  2518. #endif
  2519. #else
  2520. #define likely(x) (x)
  2521. #define unlikely(x) (x)
  2522. #endif
  2523. // This is defined in guards.cpp so we don't need to import PyTorch headers that are slooow.
  2524. // We manually link it below to workaround issues with fbcode build.
  2525. static void* (*_torchinductor_pyobject_tensor_data_ptr)(PyObject* obj);
  2526. template <typename T> static inline T parse_arg(PyObject* args, size_t n) {{
  2527. static_assert(std::is_pointer_v<T>, "arg type must be pointer or long");
  2528. return static_cast<T>(_torchinductor_pyobject_tensor_data_ptr(PyTuple_GET_ITEM(args, n)));
  2529. }}
  2530. template <> inline int64_t parse_arg<int64_t>(PyObject* args, size_t n) {{
  2531. auto result = PyLong_AsSsize_t(PyTuple_GET_ITEM(args, n));
  2532. if(unlikely(result == -1 && PyErr_Occurred()))
  2533. throw std::runtime_error("expected int arg");
  2534. return result;
  2535. }}
  2536. template <> inline uintptr_t parse_arg<uintptr_t>(PyObject* args, size_t n) {{
  2537. auto result = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, n));
  2538. if(unlikely(result == reinterpret_cast<void*>(-1) && PyErr_Occurred()))
  2539. throw std::runtime_error("expected int arg");
  2540. return reinterpret_cast<uintptr_t>(result);
  2541. }}
  2542. {extra_parse_arg}
  2543. static PyObject* {entry_func}_py(PyObject* self, PyObject* args) {{
  2544. try {{
  2545. if(unlikely(!PyTuple_CheckExact(args)))
  2546. throw std::runtime_error("tuple args required");
  2547. if(unlikely(PyTuple_GET_SIZE(args) != {arg_len}))
  2548. throw std::runtime_error("requires {arg_len} args");
  2549. {call_entry_func}
  2550. }} catch(std::exception const& e) {{
  2551. PyErr_SetString(PyExc_RuntimeError, e.what());
  2552. return nullptr;
  2553. }} catch(...) {{
  2554. PyErr_SetString(PyExc_RuntimeError, "unhandled error");
  2555. return nullptr;
  2556. }}
  2557. }}
  2558. static PyMethodDef py_methods[] = {{
  2559. {{"{entry_func}", {entry_func}_py, METH_VARARGS, ""}},
  2560. {{NULL, NULL, 0, NULL}}}};
  2561. static struct PyModuleDef py_module =
  2562. {{PyModuleDef_HEAD_INIT, "{entry_func}", NULL, -1, py_methods}};
  2563. PyMODINIT_FUNC PyInit_{entry_func}(void) {{
  2564. const char* str_addr = std::getenv("_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR");
  2565. if(!str_addr) {{
  2566. PyErr_SetString(PyExc_RuntimeError, "_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR must be set");
  2567. return nullptr;
  2568. }}
  2569. std::istringstream iss(str_addr);
  2570. uintptr_t addr = 0;
  2571. iss >> addr;
  2572. _torchinductor_pyobject_tensor_data_ptr =
  2573. reinterpret_cast<decltype(_torchinductor_pyobject_tensor_data_ptr)>(addr);
  2574. PyObject* module = PyModule_Create(&py_module);
  2575. if (module == NULL) {{
  2576. return NULL;
  2577. }}
  2578. #ifdef Py_GIL_DISABLED
  2579. PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED);
  2580. #endif
  2581. return module;
  2582. }}
  2583. """
  2584. )
  2585. @classmethod
  2586. def _load_library_inner(cls, path: str, key: str) -> ModuleType:
  2587. os.environ["_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"] = str(
  2588. torch._C._dynamo.guards._torchinductor_pyobject_tensor_data_ptr # type: ignore[attr-defined]
  2589. )
  2590. module_name = f"{key}.{cls.entry_function}"
  2591. try:
  2592. return sys.modules[module_name]
  2593. except KeyError:
  2594. pass
  2595. spec = importlib.util.spec_from_file_location(module_name, path)
  2596. assert spec is not None
  2597. module = importlib.util.module_from_spec(spec)
  2598. sys.modules[module_name] = module
  2599. assert spec.loader is not None
  2600. spec.loader.exec_module(module)
  2601. return module
  2602. @classmethod
  2603. def _get_uncompiled_header(cls, device: str) -> str | None:
  2604. return _get_cpp_prefix_header(device)
  2605. @classmethod
  2606. def load_pybinding_async(
  2607. cls,
  2608. argtypes: Sequence[str],
  2609. main_code: str,
  2610. device_type: str = "cpu",
  2611. num_outputs: int = -1,
  2612. submit_fn: Any = None,
  2613. extra_flags: Sequence[str] = (),
  2614. kernel_code: Optional[str] = None,
  2615. ) -> Any:
  2616. """
  2617. Wrap a C++ function in fast Python bindings.
  2618. Args:
  2619. argtypes: The types of args to ENTRY_FUNCTION(), e.g. ["float*", "long"]
  2620. main_code: C++ source code containing ENTRY_FUNCTION(). Will be built at
  2621. -O3 if kernel_code is None (to maximize performance in any kernels that
  2622. are present), or -O1 otherwise (to minimize compile time).
  2623. kernel_code: If present, C++ source code that will be built at -O3 and
  2624. linked to main_code.
  2625. Returns:
  2626. A python version of ENTRY_FUNCTION()
  2627. """
  2628. parseargs = ", ".join(
  2629. f"parse_arg<{argtype.replace('const ', '')}>(args, {n})"
  2630. for n, argtype in enumerate(argtypes)
  2631. )
  2632. suffix = cls.suffix_template.format(
  2633. arg_len=len(argtypes),
  2634. call_entry_func=cls.call_entry_function.format(parseargs),
  2635. entry_func=cls.entry_function,
  2636. extra_parse_arg=cls.extra_parse_arg.format(array_len=num_outputs),
  2637. )
  2638. get_result = cls.load_async(
  2639. main_code + suffix,
  2640. device_type,
  2641. submit_fn=submit_fn,
  2642. extra_flags=extra_flags,
  2643. optimized_code=kernel_code,
  2644. )
  2645. result = None
  2646. def future() -> Any:
  2647. nonlocal result
  2648. if result is None:
  2649. result = get_result()
  2650. assert isinstance(result, ModuleType)
  2651. return getattr(result, cls.entry_function)
  2652. return future
  2653. @classmethod
  2654. def load_pybinding(cls, *args: Any, **kwargs: Any) -> Any:
  2655. return cls.load_pybinding_async(*args, **kwargs)()
  2656. @clear_on_fresh_cache
  2657. class CppWrapperCodeCache(CppPythonBindingsCodeCache):
  2658. cache: dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2659. cache_clear = staticmethod(cache.clear)
  2660. cpp_compile_command_flags = {
  2661. "include_pytorch": True,
  2662. "shared": True,
  2663. }
  2664. entry_function = "inductor_entry_cpp"
  2665. call_entry_function = "return inductor_entry_cpp({});"
  2666. extra_parse_arg = textwrap.dedent(
  2667. """
  2668. #include <torch/csrc/inductor/aoti_torch/c/shim.h>
  2669. static inline std::vector<AtenTensorHandle> unpack_tensor_handle_list(PyObject* pyvec) {{
  2670. std::vector<AtenTensorHandle> result;
  2671. size_t result_len = PyList_GET_SIZE(pyvec);
  2672. result.reserve(result_len);
  2673. for (size_t i = 0; i < result_len; i++) {{
  2674. // AtenTensorHandle is essentially a pointer
  2675. void* elem = PyCapsule_GetPointer(PyList_GET_ITEM(pyvec, i), NULL);
  2676. result.push_back(reinterpret_cast<AtenTensorHandle>(elem));
  2677. }}
  2678. return result;
  2679. }}
  2680. static inline PyObject* pack_tensor_handle_list(const std::array<AtenTensorHandle, {array_len}>& arr) {{
  2681. PyObject* result = PyList_New({array_len});
  2682. for (size_t i = 0; i < {array_len}; i++) {{
  2683. PyObject *elem =
  2684. arr[i] == nullptr
  2685. ? Py_None
  2686. // Store AtenTensorHandle as PyCapsulate
  2687. : PyCapsule_New(reinterpret_cast<void*>(arr[i]), NULL, NULL);
  2688. PyList_SET_ITEM(result, i, elem);
  2689. }}
  2690. return result;
  2691. }}
  2692. template <> inline std::vector<AtenTensorHandle> parse_arg<std::vector<AtenTensorHandle>>(PyObject* args, size_t n) {{
  2693. return unpack_tensor_handle_list(PyTuple_GET_ITEM(args, n));
  2694. }}
  2695. PyObject* inductor_entry_cpp(std::vector<AtenTensorHandle>&& input_handles) {{
  2696. // For outputs, we only allocate an array to hold returned tensor handles,
  2697. // not the actual output tensor storage.
  2698. std::array<AtenTensorHandle, {array_len}> output_handles{{}};
  2699. try {{
  2700. inductor_entry_impl(input_handles.data(), output_handles.data());
  2701. if (PyErr_Occurred()) {{
  2702. return nullptr;
  2703. }}
  2704. return pack_tensor_handle_list(output_handles);
  2705. }} catch(std::exception const& e) {{
  2706. PyErr_SetString(PyExc_RuntimeError, e.what());
  2707. return nullptr;
  2708. }} catch(...) {{
  2709. PyErr_SetString(PyExc_RuntimeError, "unhandled error");
  2710. return nullptr;
  2711. }}
  2712. }}
  2713. """
  2714. )
  2715. @classmethod
  2716. def _get_uncompiled_header(cls, device: str) -> str | None:
  2717. return _get_cpp_wrapper_header(device)
  2718. @clear_on_fresh_cache
  2719. class HalideCodeCache(CppPythonBindingsCodeCache):
  2720. cache: dict[str, Callable[[], Union[ModuleType, CDLL]]] = {}
  2721. cache_clear = staticmethod(cache.clear)
  2722. _standalone_runtime_path: Optional[str] = None
  2723. prefix = textwrap.dedent(
  2724. """
  2725. #include "{halideruntime_h}"
  2726. #include "{headerfile}"
  2727. #include <stdexcept>
  2728. #include <cmath>
  2729. namespace c10 {{
  2730. inline long div_floor_integer(long a, long b) {{
  2731. if ((a<0) != (b<0)) {{
  2732. const auto quot = a / b;
  2733. const auto rem = a % b;
  2734. return rem ? quot - 1 : quot;
  2735. }}
  2736. return a / b;
  2737. }}
  2738. }}
  2739. """
  2740. )
  2741. glue_template_cpp = prefix + textwrap.dedent(
  2742. """
  2743. void kernel({argdefs}) {{
  2744. {buffers}
  2745. int err = halide_kernel({buffer_names});
  2746. if(err != 0) throw std::runtime_error("halide_kernel failed");
  2747. }}
  2748. """
  2749. )
  2750. glue_template_cuda = prefix + textwrap.dedent(
  2751. """
  2752. #include <cuda.h>
  2753. static const halide_device_interface_t* cuda_interface = halide_cuda_device_interface();
  2754. void kernel({argdefs}, uintptr_t stream) {{
  2755. {buffers}
  2756. int err = halide_kernel(reinterpret_cast<void*>(stream), {buffer_names});
  2757. if(err != 0) throw std::runtime_error("halide_kernel failed");
  2758. }}
  2759. """
  2760. )
  2761. standalone_runtime_cuda_init = textwrap.dedent(
  2762. """
  2763. #include "{}"
  2764. #include <cuda.h>
  2765. static int acquire_context(void* user_context,
  2766. void** cuda_context_out,
  2767. bool create) {{
  2768. return cuCtxGetCurrent(reinterpret_cast<CUcontext*>(cuda_context_out));
  2769. }}
  2770. static int release_context(void* user_context) {{
  2771. return 0;
  2772. }}
  2773. static int get_stream(void* user_context,
  2774. void* cuda_context,
  2775. void** stream_out) {{
  2776. *stream_out = user_context;
  2777. return 0;
  2778. }}
  2779. static int register_halide_hooks() {{
  2780. halide_set_cuda_acquire_context(&acquire_context);
  2781. halide_set_cuda_release_context(&release_context);
  2782. halide_set_cuda_get_stream(&get_stream);
  2783. return 0;
  2784. }}
  2785. int inductor_register_halide_hooks_result = register_halide_hooks();
  2786. """
  2787. )
  2788. @classmethod
  2789. def _codegen_buffer(cls, name: str, arg: HalideInputSpec, cuda: bool) -> list[str]:
  2790. assert arg.shape is not None
  2791. assert arg.stride is not None and len(arg.shape) == len(arg.stride)
  2792. assert arg.offset is not None
  2793. data_ptr = f"{arg.alias_of or arg.name} + {arg.offset}"
  2794. if cuda:
  2795. device = f"reinterpret_cast<uint64_t>({data_ptr})"
  2796. device_interface = "cuda_interface"
  2797. host = "nullptr"
  2798. flags = "halide_buffer_flag_device_dirty"
  2799. else:
  2800. device = "0"
  2801. device_interface = "nullptr"
  2802. host = f"reinterpret_cast<uint8_t*>({data_ptr})"
  2803. flags = "halide_buffer_flag_host_dirty"
  2804. dims = []
  2805. for size, stride in zip(arg.shape, arg.stride):
  2806. dims.append(f"halide_dimension_t(0, {size}, {stride})")
  2807. return [
  2808. f"halide_buffer_t {name};",
  2809. f"halide_dimension_t {name}_dims[] = {{{', '.join(dims)}}};"
  2810. if len(dims) > 0
  2811. else f"halide_dimension_t * {name}_dims = nullptr;",
  2812. f"{name}.device = {device};",
  2813. f"{name}.device_interface = {device_interface};",
  2814. f"{name}.host = {host};",
  2815. f"{name}.flags = {flags};",
  2816. f"{name}.type = {arg.halide_type()};",
  2817. f"{name}.dimensions = {len(dims)};",
  2818. f"{name}.dim = {name}_dims;",
  2819. f"{name}.padding = nullptr;",
  2820. ]
  2821. @classmethod
  2822. def _codegen_glue(cls, meta: HalideMeta, headerfile: object) -> str:
  2823. is_cuda = meta.is_cuda()
  2824. assert is_cuda is ("user_context" in meta.target)
  2825. assert "no_runtime" in meta.target
  2826. buffers = []
  2827. buffer_names = []
  2828. for i, arg in enumerate(meta.argtypes):
  2829. if arg.is_buffer():
  2830. buffer_names.append(f"&hl_buf_{i}")
  2831. buffers.extend(cls._codegen_buffer(f"hl_buf_{i}", arg, is_cuda))
  2832. else:
  2833. assert "*" not in arg.ctype
  2834. buffer_names.append(arg.name)
  2835. buffers = "\n".join([f" {line}" for line in buffers]).lstrip()
  2836. glue_template = cls.glue_template_cuda if is_cuda else cls.glue_template_cpp
  2837. glue_code = glue_template.format(
  2838. halideruntime_h=cls.find_header(
  2839. "HalideRuntimeCuda.h" if is_cuda else "HalideRuntime.h"
  2840. ),
  2841. headerfile=headerfile,
  2842. argdefs=", ".join(
  2843. f"{a.bindings_type()} {a.name}"
  2844. for a in meta.argtypes
  2845. if a.alias_of is None
  2846. ),
  2847. buffers=buffers,
  2848. buffer_names=", ".join(buffer_names),
  2849. )
  2850. return glue_code
  2851. @classmethod
  2852. @functools.cache
  2853. def config_hash(cls) -> str:
  2854. command_gen = CppBuilder(
  2855. name="O",
  2856. sources="I",
  2857. BuildOption=CppOptions(),
  2858. )
  2859. command_line = command_gen.get_command_line()
  2860. return sha256_hash(
  2861. "\n".join(
  2862. [
  2863. cls.glue_template_cpp,
  2864. cls.glue_template_cuda,
  2865. cls.standalone_runtime_cuda_init,
  2866. command_line,
  2867. ]
  2868. ).encode("utf-8")
  2869. )
  2870. @staticmethod
  2871. def _search_for_file(suffix: str, errmsg: str) -> str:
  2872. spec = importlib.machinery.PathFinder.find_spec("halide")
  2873. if spec is None or not spec.submodule_search_locations:
  2874. raise RuntimeError("halide python bindings not installed")
  2875. try:
  2876. search = spec.submodule_search_locations[0]
  2877. for file in os.listdir(search):
  2878. if file.endswith(".so"):
  2879. try:
  2880. out = subprocess.check_output(
  2881. ["ldd", os.path.join(search, file)]
  2882. )
  2883. except subprocess.SubprocessError:
  2884. continue
  2885. m = re.search(r"(/.*)/libHalide.so", out.decode("utf-8"))
  2886. if m:
  2887. path = os.path.join(os.path.abspath(m.group(1)), suffix)
  2888. if os.path.exists(path):
  2889. return os.path.abspath(path)
  2890. except Exception as e:
  2891. raise RuntimeError(errmsg) from e
  2892. raise RuntimeError(errmsg)
  2893. @staticmethod
  2894. @functools.cache
  2895. def find_libautoschedule(name: str) -> str:
  2896. sofile = f"libautoschedule_{name.lower()}.so"
  2897. if "HALIDE_LIB" in os.environ:
  2898. path = os.path.join(os.environ["HALIDE_LIB"], sofile)
  2899. if os.path.exists(path):
  2900. return path
  2901. errmsg = (
  2902. f"Can't find {sofile}, set env HALIDE_LIB to the directory containing it"
  2903. )
  2904. return HalideCodeCache._search_for_file(sofile, errmsg)
  2905. @staticmethod
  2906. @functools.cache
  2907. def find_header(name: str) -> str:
  2908. if "HALIDE_INCLUDE" in os.environ:
  2909. path = os.path.join(os.environ["HALIDE_INCLUDE"], name)
  2910. if os.path.exists(path):
  2911. return path
  2912. if "HALIDE_LIB" in os.environ:
  2913. path = os.path.abspath(
  2914. os.path.join(os.environ["HALIDE_LIB"], f"../include/{name}")
  2915. )
  2916. if os.path.exists(path):
  2917. return path
  2918. errmsg = (
  2919. f"Can't find {name}, set env HALIDE_INCLUDE to the directory containing it"
  2920. )
  2921. return HalideCodeCache._search_for_file(f"../include/{name}", errmsg)
  2922. @classmethod
  2923. def generate_halide_async(
  2924. cls, meta: HalideMeta, source_code: str, submit_fn: Any = None
  2925. ) -> Callable[[], Any]:
  2926. dirpath = Path(
  2927. get_path(
  2928. code_hash(
  2929. source_code,
  2930. extra=repr((cls.config_hash(), meta)),
  2931. ),
  2932. "halide",
  2933. )[2]
  2934. )
  2935. os.makedirs(dirpath, exist_ok=True)
  2936. wait_for_compile = None
  2937. genfile = str(dirpath / "generate_kernel.py")
  2938. libfile = str(dirpath / "halide_kernel.a")
  2939. headerfile = str(dirpath / "halide_kernel.h")
  2940. donefile = str(dirpath / "done")
  2941. lockfile = str(dirpath / "lock")
  2942. need_compile = not os.path.exists(donefile)
  2943. jobs: list[Any] = []
  2944. if need_compile:
  2945. write_atomic(genfile, source_code)
  2946. cmd = [
  2947. sys.executable,
  2948. genfile,
  2949. "-g",
  2950. "kernel",
  2951. "-o",
  2952. f"{dirpath}",
  2953. "-f",
  2954. "halide_kernel",
  2955. "-e",
  2956. "static_library,h,schedule",
  2957. ]
  2958. if meta.scheduler:
  2959. cmd.extend(["-p", cls.find_libautoschedule(meta.scheduler)])
  2960. cmd.extend(meta.args())
  2961. jobs.append(functools.partial(subprocess.check_call, cmd))
  2962. binding_types = [
  2963. arg.bindings_type() for arg in meta.argtypes if arg.alias_of is None
  2964. ]
  2965. if meta.is_cuda():
  2966. binding_types.append("uintptr_t") # stream
  2967. bindings_future = cls.load_pybinding_async(
  2968. binding_types,
  2969. cls._codegen_glue(meta, headerfile),
  2970. extra_flags=(libfile, cls.build_standalone_runtime()),
  2971. submit_fn=jobs.append if need_compile else None,
  2972. device_type="cuda" if meta.is_cuda() else "cpu",
  2973. )
  2974. if need_compile:
  2975. jobs.append(functools.partial(touch, donefile))
  2976. task = functools.partial(_worker_task_halide, lockfile, jobs)
  2977. if submit_fn:
  2978. wait_for_compile = submit_fn(task).result
  2979. else:
  2980. task()
  2981. def load() -> Callable[[], Any]:
  2982. if wait_for_compile:
  2983. wait_for_compile()
  2984. return bindings_future()
  2985. return load
  2986. @classmethod
  2987. def generate_halide(cls, *args: Any, **kwargs: Any) -> Callable[[], Any]:
  2988. return cls.generate_halide_async(*args, **kwargs)()
  2989. @classmethod
  2990. def build_standalone_runtime(cls) -> str:
  2991. if cls._standalone_runtime_path and os.path.exists(
  2992. cls._standalone_runtime_path
  2993. ):
  2994. return cls._standalone_runtime_path
  2995. device_type = "cuda" if torch.cuda.is_available() else "cpu"
  2996. libname = "libStandaloneHalideRuntime.so"
  2997. target = "host-cuda" if device_type == "cuda" else "host"
  2998. if cls._standalone_runtime_path:
  2999. assert not os.path.exists(cls._standalone_runtime_path)
  3000. # We hit this case in unittests when we run with fresh_cache()
  3001. # Generating a fresh runtime over and over causes errors because we initialize
  3002. # cuda hundreds of times in the same process and run out of file descriptors.
  3003. # Workaround by jail breaking the current fresh_cache().
  3004. base = default_cache_dir()
  3005. else:
  3006. base = cache_dir()
  3007. dirpath = Path(base) / f"halide-runtime-{target}-{cls.config_hash()}"
  3008. os.makedirs(dirpath, exist_ok=True)
  3009. done_file = str(dirpath / "done")
  3010. lock_file = str(dirpath / "lock")
  3011. hook_file = str(dirpath / "hooks.cpp")
  3012. a_file = str(dirpath / "standalone_halide_runtime.a")
  3013. so_file = str(dirpath / libname)
  3014. if not os.path.exists(done_file):
  3015. import halide as hl # type: ignore[import-untyped,import-not-found]
  3016. from torch.utils._filelock import FileLock
  3017. with FileLock(lock_file, LOCK_TIMEOUT):
  3018. if not os.path.exists(done_file):
  3019. with open(hook_file, "w") as f:
  3020. if device_type == "cuda":
  3021. f.write(
  3022. cls.standalone_runtime_cuda_init.format(
  3023. cls.find_header("HalideRuntimeCuda.h")
  3024. )
  3025. )
  3026. hl.compile_standalone_runtime(a_file, hl.Target(target))
  3027. name, output_dir = get_name_and_dir_from_output_file_path(so_file)
  3028. halide_cmd_gen = CppBuilder(
  3029. name=name,
  3030. sources=[hook_file, a_file],
  3031. output_dir=output_dir,
  3032. BuildOption=CppTorchDeviceOptions(
  3033. device_type=device_type,
  3034. ),
  3035. )
  3036. subprocess.check_call(
  3037. shlex.split(halide_cmd_gen.get_command_line())
  3038. )
  3039. touch(done_file)
  3040. assert os.path.exists(so_file)
  3041. cls._standalone_runtime_path = so_file
  3042. return so_file
  3043. @classmethod
  3044. def _get_uncompiled_header(cls, device: str) -> str | None:
  3045. """Header precompiling is currently disabled for halide."""
  3046. return None
  3047. def _worker_task_halide(lockfile: str, jobs: list[partial[Any]]) -> None:
  3048. from torch.utils._filelock import FileLock
  3049. try:
  3050. with FileLock(lockfile, LOCK_TIMEOUT):
  3051. for job in jobs:
  3052. job()
  3053. except subprocess.SubprocessError as e:
  3054. if os.environ.get("HALIDE_REPRO") == "1":
  3055. cmd: list[Any]
  3056. python, script, *cmd = getattr(e, "cmd", ("", "", ""))
  3057. if os.path.basename(python).startswith("python"):
  3058. code = open(script).read()
  3059. main = " hl.main()"
  3060. assert code.count(main) == 1
  3061. class Out:
  3062. def __repr__(self) -> str:
  3063. return "out"
  3064. ci = cmd.index("-o")
  3065. assert isinstance(ci, int)
  3066. cmd[ci + 1] = Out()
  3067. repl = textwrap.indent(
  3068. textwrap.dedent(
  3069. f"""\
  3070. import sys, tempfile
  3071. with tempfile.TemporaryDirectory() as out:
  3072. sys.argv = {["repro.py", *cmd]!r}
  3073. hl.main()
  3074. """
  3075. ),
  3076. " ",
  3077. )
  3078. code = code.replace(main, repl)
  3079. with open("repro.py", "w") as fd:
  3080. fd.write(code.lstrip())
  3081. raise RuntimeError(f"wrote repro.py: {e}") from e
  3082. raise
  3083. def touch(filename: str) -> None:
  3084. open(filename, "a").close()
  3085. @clear_on_fresh_cache
  3086. class PyCodeCache:
  3087. # Track the loaded modules so we can remove the on-disk artifacts when
  3088. # clearing the cache. Note also that we may load the same path more
  3089. # than once, but attach different attributes, i.e., due to different
  3090. # constant values.
  3091. modules: list[ModuleType] = []
  3092. # Modules loaded without extra attributes are stored here, those do not
  3093. # need to be re-loaded.
  3094. modules_no_attr: dict[str, ModuleType] = {}
  3095. linemaps: dict[str, list[tuple[Any, ...]]] = {}
  3096. @classmethod
  3097. def write(cls, source_code: str, extra: str = "") -> tuple[str, str]:
  3098. return write(source_code, "py", extra=extra)
  3099. @classmethod
  3100. def load(cls, source_code: str, extra: str = "") -> ModuleType:
  3101. key, path = write(source_code, "py", extra=extra)
  3102. return cls.load_by_key_path(key, path)
  3103. @classmethod
  3104. def load_by_key_path(
  3105. cls,
  3106. key: str,
  3107. path: str,
  3108. linemap: Optional[list[tuple[int, str]]] = None,
  3109. attrs: Optional[dict[str, Any]] = None,
  3110. ) -> ModuleType:
  3111. if linemap is None:
  3112. linemap = []
  3113. # we only cache when attrs is None
  3114. if attrs is None and path in cls.modules_no_attr:
  3115. return cls.modules_no_attr[path]
  3116. in_toplevel = in_toplevel_process()
  3117. mod = _reload_python_module(key, path, set_sys_modules=in_toplevel)
  3118. # unzip into separate lines/nodes lists
  3119. if in_toplevel:
  3120. cls.linemaps[path] = list(zip(*linemap))
  3121. if attrs is not None:
  3122. for k, v in attrs.items():
  3123. setattr(mod, k, v)
  3124. if in_toplevel:
  3125. # we only cache when attrs is None
  3126. if attrs is None:
  3127. cls.modules_no_attr[path] = mod
  3128. cls.modules.append(mod)
  3129. return mod
  3130. @classmethod
  3131. def cache_clear(cls, purge: bool = False) -> None:
  3132. """
  3133. Clear the in-memory module cache. If purge=True, also delete all the
  3134. corresponding on-disk source files.
  3135. """
  3136. if purge:
  3137. for mod in cls.modules:
  3138. try:
  3139. assert mod.__file__
  3140. os.remove(mod.__file__)
  3141. except FileNotFoundError:
  3142. pass
  3143. cls.modules.clear()
  3144. cls.modules_no_attr.clear()
  3145. @classmethod
  3146. @functools.cache
  3147. def stack_frames_for_code(
  3148. cls, path: str, lineno: int
  3149. ) -> Optional[list[dict[str, Any]]]:
  3150. if path not in cls.linemaps:
  3151. return None
  3152. if len(cls.linemaps[path]) == 0:
  3153. return None
  3154. # [(starting_line, <fx node>), ...]
  3155. lines, nodes = cls.linemaps[path]
  3156. p = bisect_right(lines, lineno)
  3157. if p == 0:
  3158. return None
  3159. entry = nodes[p - 1]
  3160. if not entry:
  3161. return None
  3162. def parse_stack_trace(stack_trace: str) -> list[dict[str, Any]]:
  3163. # ideally fx stores stack traces as data rather than a string
  3164. # but this is not along a performance critical path
  3165. regex = r'File "(.+)", line (\d+), in (.+)\n'
  3166. matches = re.findall(regex, stack_trace)
  3167. return [
  3168. {"filename": f, "line": int(l), "name": n}
  3169. for f, l, n in reversed(matches)
  3170. ]
  3171. return parse_stack_trace(entry)
  3172. def _load_triton_kernel_from_source(
  3173. kernel_name: str, source_code: str
  3174. ) -> CachingAutotuner:
  3175. return getattr(PyCodeCache.load(source_code), kernel_name)
  3176. def _cuda_compiler() -> Optional[str]:
  3177. if cuda_env.nvcc_exist(config.cuda.cuda_cxx):
  3178. return config.cuda.cuda_cxx
  3179. if config.is_fbcode():
  3180. return os.path.join(build_paths.sdk_home, "bin", "nvcc")
  3181. if cuda_env.nvcc_exist(os.getenv("CUDACXX")):
  3182. return os.getenv("CUDACXX", "")
  3183. if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")):
  3184. return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc"))
  3185. return "nvcc"
  3186. def _cutlass_path() -> str:
  3187. if config.is_fbcode():
  3188. from libfb.py import parutil
  3189. return parutil.get_dir_path("cutlass-4-headers")
  3190. else:
  3191. return config.cuda.cutlass_dir
  3192. def _cutlass_paths() -> list[str]:
  3193. return [
  3194. "include",
  3195. "tools/library/include",
  3196. "tools/library/src",
  3197. "tools/util/include",
  3198. ]
  3199. def _clone_cutlass_paths(build_root: str) -> list[str]:
  3200. paths = _cutlass_paths()
  3201. cutlass_root = _cutlass_path()
  3202. for path in _cutlass_paths():
  3203. old_path = os.path.join(cutlass_root, path)
  3204. new_path = os.path.join(build_root, path)
  3205. shutil.copytree(old_path, new_path, dirs_exist_ok=True)
  3206. return paths
  3207. def _cutlass_include_paths() -> list[str]:
  3208. cutlass_path = _cutlass_path()
  3209. return [
  3210. # Use realpath to get canonical absolute paths, in order not to mess up cache keys
  3211. os.path.realpath(os.path.join(cutlass_path, path))
  3212. for path in _cutlass_paths()
  3213. ]
  3214. @torch_key_cache
  3215. def cutlass_key() -> bytes:
  3216. """
  3217. Compute a key representing the state of the CUTLASS library.
  3218. Note: OSS and fbcode will have different keys.
  3219. """
  3220. if config.is_fbcode():
  3221. with importlib.resources.path(
  3222. "cutlass_library", "src_hash.txt"
  3223. ) as resource_path:
  3224. with open(resource_path) as resource_file:
  3225. return resource_file.read().encode()
  3226. combined_hash = hashlib.sha256()
  3227. build_code_hash([config.cuda.cutlass_dir], "", combined_hash)
  3228. return combined_hash.digest()
  3229. def _cuda_lib_options() -> list[str]:
  3230. """
  3231. Util function for CUTLASS backend to find the correct CUDA libraries.
  3232. """
  3233. _set_gpu_runtime_env() # cpp_extension consults the env
  3234. from torch.utils import cpp_extension
  3235. lpaths = cpp_extension.library_paths(device_type="cuda")
  3236. if use_re_build():
  3237. lpaths += [
  3238. build_paths.sdk_lib,
  3239. os.path.join(build_paths.sdk_lib, "stubs"),
  3240. ]
  3241. extra_ldflags: list[str] = []
  3242. if is_linux():
  3243. _transform_cuda_paths(lpaths)
  3244. for path in lpaths:
  3245. if "torch/lib" in path:
  3246. # don't want to depend on pytorch
  3247. continue
  3248. extra_ldflags.append(f"-L{path}")
  3249. # -rpath ensures the DLL can find its dependencies when loaded, even
  3250. # if the library path is non-standard.
  3251. # But do not add the stubs folder to rpath as the driver is expected to be found at runtime
  3252. if os.path.basename(path) != "stubs":
  3253. extra_ldflags.extend(["-Xlinker", f"-rpath={path}"])
  3254. extra_ldflags.append("-lcuda")
  3255. extra_ldflags.append("-lcudart")
  3256. else:
  3257. raise NotImplementedError(
  3258. "Unsupported env, failed to find cuda libs! Currently only Linux is supported."
  3259. )
  3260. return extra_ldflags
  3261. def _nvcc_host_compiler_options() -> list[str]:
  3262. return [
  3263. "-fPIC",
  3264. "-fno-strict-aliasing",
  3265. "-fvisibility=hidden",
  3266. "-Wconversion",
  3267. ]
  3268. def _nvcc_arch_as_compile_option() -> str:
  3269. arch = cuda_env.get_cuda_arch()
  3270. if arch == "90":
  3271. # Required by cutlass compilation.
  3272. return "90a"
  3273. if arch == "100":
  3274. return "100a"
  3275. return arch
  3276. def _nvcc_compiler_options() -> list[str]:
  3277. arch = _nvcc_arch_as_compile_option()
  3278. code = [f"sm_{arch}", f"compute_{arch}"]
  3279. if config.cuda.enable_cuda_lto:
  3280. code += [f"lto_{arch}"]
  3281. options = [
  3282. "-t=0",
  3283. "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
  3284. "-DCUTLASS_ENABLE_SM90_EXTENDED_MMA_SHAPES=1",
  3285. "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED",
  3286. "-w",
  3287. f"-gencode=arch=compute_{arch},code=[{','.join(code)}]",
  3288. config.cuda.compile_opt_level,
  3289. "-std=c++17",
  3290. "--expt-relaxed-constexpr",
  3291. "-DNDEBUG",
  3292. ]
  3293. if config.is_fbcode():
  3294. options.extend(["-ccbin", os.path.dirname(build_paths.gcc)])
  3295. if config.cuda.enable_debug_info:
  3296. options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"])
  3297. if config.cuda.enable_ptxas_info:
  3298. options.extend(
  3299. [
  3300. "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.)
  3301. "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels
  3302. "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels
  3303. "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.)
  3304. "--source-in-ptx",
  3305. ]
  3306. ) # Annotate the ptx file with source information
  3307. if config.cuda.use_fast_math:
  3308. options.extend(
  3309. [
  3310. "--use_fast_math",
  3311. "-DCUTLASS_USE_TANH_FOR_SIGMOID=1",
  3312. ]
  3313. )
  3314. return options
  3315. def cuda_compile_command(
  3316. src_files: list[str],
  3317. dst_file: str,
  3318. dst_file_ext: str,
  3319. extra_args: Optional[list[str]] = None,
  3320. ) -> str:
  3321. if extra_args is None:
  3322. extra_args = []
  3323. if use_re_build():
  3324. build_path = os.path.dirname(dst_file)
  3325. include_paths = _clone_cutlass_paths(build_path)
  3326. src_files = [os.path.basename(src_file) for src_file in src_files]
  3327. dst_file = os.path.basename(dst_file)
  3328. else:
  3329. include_paths = _cutlass_include_paths()
  3330. cuda_lib_options = _cuda_lib_options()
  3331. nvcc_host_compiler_options = _nvcc_host_compiler_options()
  3332. nvcc_compiler_options = _nvcc_compiler_options()
  3333. options = (
  3334. nvcc_compiler_options
  3335. + extra_args
  3336. + [
  3337. f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}"
  3338. for opt in nvcc_host_compiler_options
  3339. ]
  3340. + ["-I" + path for path in include_paths]
  3341. + cuda_lib_options
  3342. )
  3343. src_file = " ".join(src_files)
  3344. res = ""
  3345. if dst_file_ext == "o":
  3346. res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}"
  3347. elif dst_file_ext == "so":
  3348. options.append("-shared")
  3349. res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
  3350. elif dst_file_ext == "exe":
  3351. res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
  3352. else:
  3353. raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
  3354. if log.isEnabledFor(logging.DEBUG):
  3355. log.debug("CUDA command: %s", res)
  3356. else:
  3357. autotuning_log.debug("CUDA command: %s", res)
  3358. return res
  3359. class DLLWrapper:
  3360. """A wrapper for a dynamic library."""
  3361. def __init__(
  3362. self,
  3363. lib_path: str,
  3364. ) -> None:
  3365. self.lib_path = lib_path
  3366. self.is_open = False
  3367. self.DLL = cdll.LoadLibrary(lib_path)
  3368. self.is_open = True
  3369. def close(self) -> None:
  3370. if self.is_open:
  3371. self._dlclose()
  3372. self.is_open = False
  3373. def _dlclose(self) -> None:
  3374. f_dlclose = None
  3375. if is_linux():
  3376. syms = CDLL(None)
  3377. if not hasattr(syms, "dlclose"):
  3378. # Apline Linux
  3379. syms = CDLL("libc.so")
  3380. if hasattr(syms, "dlclose"):
  3381. f_dlclose = syms.dlclose
  3382. elif is_windows():
  3383. import ctypes
  3384. kernel32 = ctypes.CDLL("kernel32", use_last_error=True)
  3385. f_dlclose = kernel32.FreeLibrary
  3386. else:
  3387. raise NotImplementedError("Unsupported env, failed to do dlclose!")
  3388. if f_dlclose is not None:
  3389. if is_linux():
  3390. f_dlclose.argtypes = [c_void_p]
  3391. f_dlclose(self.DLL._handle)
  3392. elif is_windows():
  3393. import ctypes
  3394. from ctypes import wintypes
  3395. f_dlclose.argtypes = [wintypes.HMODULE]
  3396. f_dlclose(self.DLL._handle)
  3397. else:
  3398. log.warning(
  3399. "dll unloading function was not found, library may not be unloaded properly!"
  3400. )
  3401. def __getattr__(self, name: str) -> Callable[..., None]:
  3402. if not self.is_open:
  3403. raise RuntimeError(f"Cannot use closed DLL library: {self.lib_path}")
  3404. method = getattr(self.DLL, name)
  3405. def _wrapped_func(*args: Any) -> None:
  3406. err = method(*args)
  3407. if err:
  3408. raise RuntimeError(f"Error in function: {method.__name__}")
  3409. return _wrapped_func
  3410. def __enter__(self) -> Self:
  3411. return self
  3412. def __exit__(self, *args: Any) -> None:
  3413. self.close()
  3414. def __del__(self) -> None:
  3415. self.close()
  3416. @lru_cache
  3417. def binary_error_path(output_path: str) -> str:
  3418. """
  3419. standard format for the error path
  3420. """
  3421. return output_path + ".error"
  3422. @clear_on_fresh_cache
  3423. class CUDACodeCache:
  3424. """
  3425. A cache for managing the compilation and loading of CUDA source code specifically for CUTLASS.
  3426. This class handles writing source code to files, compiling them into shared objects, and caching
  3427. the results to avoid redundant compilations. It also manages error handling and logging for the
  3428. compilation process.
  3429. """
  3430. @dataclasses.dataclass
  3431. class CacheEntry:
  3432. input_path: str
  3433. output_path: str
  3434. error_json: Optional[str] = None
  3435. cache: dict[str, CacheEntry] = {}
  3436. aot_kernels_o: list[str] = []
  3437. _SOURCE_CODE_SUFFIX = "cu"
  3438. @staticmethod
  3439. def cache_clear() -> None:
  3440. CUDACodeCache.cache.clear()
  3441. CUDACodeCache.aot_kernels_o.clear()
  3442. @staticmethod
  3443. @lru_cache(maxsize=4)
  3444. def get_kernel_binary_remote_cache(
  3445. caching_enabled: bool, caching_available: bool
  3446. ) -> Optional[Any]:
  3447. """
  3448. Get or create the class instance of the CUTLASSKernelBinaryRemoteCache.
  3449. Args:
  3450. caching_enabled: Whether binary remote caching is enabled
  3451. caching_available: Whether we're in fbcode environment
  3452. Returns:
  3453. CUTLASSKernelBinaryRemoteCache: The class instance of the kernel binary remote cache
  3454. """
  3455. if not caching_enabled:
  3456. log.debug("CUTLASSKernelBinaryRemoteCache not requested, skipping")
  3457. return None
  3458. if not caching_available:
  3459. return None
  3460. try:
  3461. from torch._inductor.fb.kernel_binary_remote_cache import (
  3462. CUTLASSKernelBinaryRemoteCache,
  3463. )
  3464. return CUTLASSKernelBinaryRemoteCache()
  3465. except ImportError:
  3466. log.debug(
  3467. "CUTLASSKernelBinaryRemoteCache not available, remote caching disabled"
  3468. )
  3469. return None
  3470. @classmethod
  3471. @lru_cache(None)
  3472. def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]:
  3473. """
  3474. Writes source code into a file with dst_file_ext as the file extension.
  3475. Returns the hash key of source code, and the path to the file.
  3476. """
  3477. if config.cuda.cutlass_hash_with_compile_cmd:
  3478. cuda_command = repr(
  3479. cuda_compile_command(["dummy_input"], "dummy_output", dst_file_ext)
  3480. )
  3481. extra = cuda_command
  3482. else:
  3483. extra = repr(
  3484. [
  3485. # nvcc and cuda hash
  3486. _cuda_compiler(),
  3487. # cutlass flags and gcc hash
  3488. _nvcc_compiler_options(),
  3489. # flags
  3490. _nvcc_host_compiler_options(),
  3491. # cutlass key
  3492. cutlass_key(),
  3493. # hack to deal with AOTI .o compilation
  3494. ]
  3495. )
  3496. key, input_path = write(source_code, cls._SOURCE_CODE_SUFFIX, extra=extra)
  3497. return key, input_path
  3498. @classmethod
  3499. def compile(
  3500. cls, source_code: str, dst_file_ext: str, extra_args: Optional[list[str]] = None
  3501. ) -> tuple[str, str, str]:
  3502. """
  3503. Compiles CUDA source_code into a file with dst_file_ext extension.
  3504. If dst_file_ext is "so", first compiles to ".o" and then links to ".so".
  3505. Returns a tuple of dst_file_path, hash_key, source_code_path
  3506. """
  3507. if dst_file_ext == "so":
  3508. # Two-step compilation: first compile to .o, then link to .so
  3509. obj_path, _, _ = cls.compile(source_code, "o", extra_args)
  3510. key, input_path = cls.write(source_code, dst_file_ext)
  3511. src_files, operation_name = [obj_path], "Linking"
  3512. else:
  3513. # Regular compilation for non-.so files
  3514. key, input_path = cls.write(source_code, dst_file_ext)
  3515. src_files, operation_name = [input_path], "Compilation"
  3516. key_with_ext = key + dst_file_ext
  3517. if key_with_ext not in cls.cache:
  3518. from torch.utils._filelock import FileLock
  3519. lock_dir = get_lock_dir()
  3520. lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
  3521. with lock:
  3522. output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext
  3523. error_path = binary_error_path(output_path)
  3524. binary_remote_cache = cls.get_kernel_binary_remote_cache(
  3525. caching_enabled=config.cuda.use_binary_remote_cache
  3526. and not config.force_disable_caches,
  3527. caching_available=config.is_fbcode(),
  3528. )
  3529. if binary_remote_cache is not None:
  3530. # The remote cache implementation will only download if the file does
  3531. # not already exist locally
  3532. binary_remote_cache.get(output_path, error_path)
  3533. if os.path.exists(error_path):
  3534. with open(error_path, encoding="utf-8") as fh:
  3535. error_json = fh.read()
  3536. cmd_parts, error_output = json.loads(error_json)
  3537. if (
  3538. binary_remote_cache is not None
  3539. and config.cuda.upload_to_binary_remote_cache
  3540. ):
  3541. # This ensures that a local error is uploaded to the remote cache,
  3542. # as we make no assumptions about the remote cache having the same
  3543. # information as the local cache
  3544. binary_remote_cache.put(
  3545. error_path, config.cuda.binary_remote_cache_force_write
  3546. )
  3547. cls.cache[key_with_ext] = CUDACodeCache.CacheEntry(
  3548. input_path, output_path, error_json
  3549. )
  3550. raise exc.CUDACompileError(cmd_parts, error_output)
  3551. if not os.path.exists(output_path):
  3552. cmd = cuda_compile_command(
  3553. src_files, output_path, dst_file_ext, extra_args
  3554. )
  3555. with open(input_path, "a") as f:
  3556. f.write("\n")
  3557. f.write(f"// CUDA {operation_name} cmd\n// {cmd}\n")
  3558. start_time = time()
  3559. log.debug("CUDA %s: %s", operation_name, cmd)
  3560. cmd_parts = cmd.split(" ")
  3561. try:
  3562. if use_re_build():
  3563. from triton.fb.re_build_helper import run_build_command
  3564. run_build_command(
  3565. cmd_parts,
  3566. os.path.dirname(input_path),
  3567. os.path.basename(output_path),
  3568. )
  3569. else:
  3570. subprocess.check_output(
  3571. cmd_parts, stderr=subprocess.STDOUT, env=os.environ
  3572. )
  3573. except subprocess.CalledProcessError as error:
  3574. cls._record_cuda_compile_error(
  3575. error.output.decode("utf-8"),
  3576. key_with_ext,
  3577. cmd_parts,
  3578. input_path,
  3579. output_path,
  3580. binary_remote_cache,
  3581. )
  3582. raise exc.CUDACompileError(cmd_parts, error.output) from error
  3583. except Exception as error:
  3584. if "COMPILE FAILED WITH" in str(error):
  3585. cls._record_cuda_compile_error(
  3586. str(error),
  3587. key_with_ext,
  3588. cmd_parts,
  3589. input_path,
  3590. output_path,
  3591. binary_remote_cache,
  3592. )
  3593. raise exc.CUDACompileError(cmd_parts, str(error)) from error
  3594. raise error
  3595. end_time = time()
  3596. log_duration_msg = f"CUDA {operation_name} took {end_time - start_time} seconds. Command: {cmd}"
  3597. log.info(log_duration_msg)
  3598. else:
  3599. log.debug(
  3600. "CUDA %s skipped: %s since output already exists",
  3601. operation_name,
  3602. output_path,
  3603. )
  3604. # Upload to remote cache if enabled
  3605. if (
  3606. binary_remote_cache is not None
  3607. and config.cuda.upload_to_binary_remote_cache
  3608. ):
  3609. # will log on errors, but not fail out
  3610. binary_remote_cache.put(
  3611. output_path, config.cuda.binary_remote_cache_force_write
  3612. )
  3613. cls.cache[key_with_ext] = CUDACodeCache.CacheEntry(
  3614. input_path, output_path, None
  3615. )
  3616. cache_entry: CUDACodeCache.CacheEntry = cls.cache[key_with_ext]
  3617. if cache_entry.error_json is not None:
  3618. # Restore cached Exception and raise it as if we had compiled
  3619. cmd_parts, error_output = json.loads(cache_entry.error_json)
  3620. raise exc.CUDACompileError(cmd_parts, error_output.encode("utf-8"))
  3621. return (cls.cache[key_with_ext].output_path, key, input_path)
  3622. @classmethod
  3623. def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]:
  3624. """
  3625. Compiles source code and loads the generated .so file.
  3626. Returns a tuple of DLLWrapper, hash_key, source_code_path
  3627. """
  3628. if dst_file_ext != "so":
  3629. raise RuntimeError(
  3630. f"Only support loading a .so file for now. "
  3631. f"Requested file extension: {dst_file_ext}. Source code: {source_code}"
  3632. )
  3633. dst_file_path, hash_key, source_code_path = cls.compile(
  3634. source_code, dst_file_ext
  3635. )
  3636. return (DLLWrapper(dst_file_path), hash_key, source_code_path)
  3637. @classmethod
  3638. def _record_cuda_compile_error(
  3639. cls,
  3640. error_str: str,
  3641. key_with_ext: str,
  3642. cmd_parts: list[str],
  3643. input_path: str,
  3644. output_path: str,
  3645. # Any here, as the import and type will only work in fbcode
  3646. # TODO: Make the typing hint strong here
  3647. binary_remote_cache: Any = None,
  3648. ) -> None:
  3649. error_json = json.dumps([cmd_parts, error_str])
  3650. cls.cache[key_with_ext] = CUDACodeCache.CacheEntry(
  3651. input_path, output_path, error_json
  3652. )
  3653. error_path = binary_error_path(output_path)
  3654. with open(error_path, "w", encoding="utf-8") as fh:
  3655. fh.write(error_json)
  3656. # Upload to remote cache directly from memory if enabled
  3657. if (
  3658. binary_remote_cache is not None
  3659. and config.cuda.upload_to_binary_remote_cache
  3660. ):
  3661. binary_remote_cache.put(
  3662. error_path, config.cuda.binary_remote_cache_force_write
  3663. )
  3664. @clear_on_fresh_cache
  3665. class ROCmCodeCache:
  3666. @dataclasses.dataclass
  3667. class CacheEntry:
  3668. input_path: str
  3669. output_path: str
  3670. cache: dict[str, CacheEntry] = {}
  3671. aot_kernels_o: list[str] = []
  3672. _SOURCE_CODE_SUFFIX = "cpp"
  3673. _logged_compiler_version = False
  3674. @staticmethod
  3675. def cache_clear() -> None:
  3676. ROCmCodeCache.cache.clear()
  3677. ROCmCodeCache.aot_kernels_o.clear()
  3678. @classmethod
  3679. def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]:
  3680. """
  3681. Writes source code into a file with dst_file_ext as the file extension.
  3682. Returns the hash key of source code, and the path to the file.
  3683. """
  3684. cuda_command = repr(
  3685. rocm_compile_command(["dummy_input"], "dummy_output", dst_file_ext)
  3686. )
  3687. key, input_path = write(
  3688. source_code, cls._SOURCE_CODE_SUFFIX, extra=cuda_command
  3689. )
  3690. return key, input_path
  3691. @classmethod
  3692. def compile(
  3693. cls, source_code: str, dst_file_ext: str, extra_args: Optional[list[str]] = None
  3694. ) -> tuple[str, str, str]:
  3695. """
  3696. Compiles source_code into a file with dst_file_ext extension,
  3697. using the compile command specific for the ROCm platform.
  3698. Returns a tuple of dst_file_path, hash_key, source_code_path
  3699. """
  3700. if not cls._logged_compiler_version:
  3701. cls._logged_compiler_version = True
  3702. log.debug(get_compiler_version_info(str(rocm_compiler())))
  3703. key, input_path = cls.write(source_code, dst_file_ext)
  3704. if key not in cls.cache:
  3705. from torch.utils._filelock import FileLock
  3706. lock_dir = get_lock_dir()
  3707. lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
  3708. with lock:
  3709. output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext
  3710. if not os.path.exists(output_path):
  3711. cmd = rocm_compile_command(
  3712. [input_path], output_path, dst_file_ext, extra_args
  3713. )
  3714. start_time = time()
  3715. cmd_parts = cmd.split(" ")
  3716. try:
  3717. output = subprocess.check_output(
  3718. cmd_parts,
  3719. stderr=subprocess.STDOUT,
  3720. text=True,
  3721. env=os.environ,
  3722. )
  3723. log.debug("Compilation output: %s", output)
  3724. except subprocess.CalledProcessError as error:
  3725. raise exc.CUDACompileError(cmd_parts, error.output) from error
  3726. end_time = time()
  3727. log_duration_msg = f"Compilation took {end_time - start_time} seconds. Compile command: {cmd}"
  3728. log.info(log_duration_msg)
  3729. else:
  3730. log.debug(
  3731. "Skip compiling %s: output %s already exists",
  3732. input_path,
  3733. output_path,
  3734. )
  3735. cls.cache[key] = ROCmCodeCache.CacheEntry(input_path, output_path)
  3736. return (cls.cache[key].output_path, key, input_path)
  3737. @classmethod
  3738. def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]:
  3739. """
  3740. Compiles source code and loads the generated .so file.
  3741. Returns a tuple of DLLWrapper, hash_key, source_code_path
  3742. """
  3743. if dst_file_ext != "so":
  3744. raise RuntimeError(
  3745. f"Only support loading a .so file for now. "
  3746. f"Requested file extension: {dst_file_ext}. Source code: {source_code}"
  3747. )
  3748. dst_file_path, hash_key, source_code_path = cls.compile(
  3749. source_code, dst_file_ext
  3750. )
  3751. return (DLLWrapper(dst_file_path), hash_key, source_code_path)
  3752. class CodeCacheFuture:
  3753. def result(self) -> Callable[..., Any]:
  3754. raise NotImplementedError
  3755. class LambdaFuture(CodeCacheFuture):
  3756. def __init__(
  3757. self, result_fn: Callable[..., Any], future: Optional[Future[Any]] = None
  3758. ) -> None:
  3759. self.result_fn = result_fn
  3760. self.future = future
  3761. def result(self) -> Callable[..., Any]:
  3762. return self.result_fn()
  3763. class StaticAutotunerFuture(CodeCacheFuture):
  3764. """
  3765. A statically launchable CachingAutotuner, loaded from TritonBundler
  3766. """
  3767. def __init__(self, static_autotuner: CachingAutotuner) -> None:
  3768. # Pickled version of CachingAutotuner
  3769. self.static_autotuner = static_autotuner
  3770. # This needs to be set in AsyncCompile.triton, in case
  3771. # we need to reload the CachingAutotuner from its source code
  3772. # We don't store the source code on the CachingAutotuner itself
  3773. # since it can be very large.
  3774. self.reload_kernel_from_src: Optional[Callable[[], Any]] = None
  3775. def result(self) -> CachingAutotuner:
  3776. assert self.reload_kernel_from_src is not None
  3777. with dynamo_timed("StaticAutotunerFuture.warm_precompile"):
  3778. self.static_autotuner.recheck_autotune_cache(
  3779. reload_kernel_from_src=self.reload_kernel_from_src
  3780. )
  3781. self.static_autotuner.precompile( # type: ignore[union-attr]
  3782. warm_cache_only=False,
  3783. reload_kernel=self.reload_kernel_from_src,
  3784. static_triton_bundle_key=None, # no need to save again
  3785. )
  3786. return self.static_autotuner