codecache.py 169 KB

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