codecache.py 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444
  1. # mypy: allow-untyped-defs
  2. from __future__ import annotations
  3. import base64
  4. import copyreg
  5. import dataclasses
  6. import functools
  7. import hashlib
  8. import importlib
  9. import io
  10. import json
  11. import logging
  12. import os
  13. import pickle
  14. import pkgutil
  15. import platform
  16. import re
  17. import shlex
  18. import shutil
  19. import struct
  20. import subprocess
  21. import sys
  22. import sysconfig
  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 functools import partial
  31. from pathlib import Path
  32. from time import time, time_ns
  33. from types import ModuleType
  34. from typing import (
  35. Any,
  36. Callable,
  37. cast,
  38. Dict,
  39. Generator,
  40. List,
  41. Optional,
  42. Sequence,
  43. Set,
  44. Tuple,
  45. TYPE_CHECKING,
  46. Union,
  47. )
  48. import torch
  49. from torch._dynamo.utils import counters, dynamo_timed
  50. from torch._inductor import config, exc, metrics
  51. from torch._inductor.codegen.cuda import cuda_env
  52. from torch._inductor.runtime.compile_tasks import (
  53. _module_to_triton_kernel,
  54. _reload_python_module,
  55. _reload_python_module_in_subproc,
  56. )
  57. from torch._inductor.runtime.runtime_utils import cache_dir
  58. from torch._inductor.utils import ALIGN_BYTES, clear_on_fresh_inductor_cache, is_linux
  59. from torch._logging import trace_structured
  60. from torch._subclasses.fake_tensor import (
  61. extract_tensor_metadata,
  62. FakeTensor,
  63. TensorMetadata,
  64. )
  65. from torch.fx.experimental.symbolic_shapes import has_hint, hint_int, ShapeEnv
  66. if TYPE_CHECKING:
  67. from concurrent.futures import Future
  68. from torch._inductor.graph import GraphLowering
  69. from torch._inductor.ir import ChoiceCaller
  70. from torch._inductor.runtime.hints import HalideMeta
  71. _HERE = os.path.abspath(__file__)
  72. _TORCH_PATH = os.path.dirname(os.path.dirname(_HERE))
  73. _LINKER_SCRIPT = os.path.join(_TORCH_PATH, "_inductor/script.ld")
  74. _IS_WINDOWS = sys.platform == "win32"
  75. if config.is_fbcode():
  76. from triton.fb import build_paths
  77. from triton.fb.build import _run_build_command
  78. from torch._inductor.fb.utils import (
  79. log_global_cache_errors,
  80. log_global_cache_stats,
  81. log_global_cache_vals,
  82. use_global_cache,
  83. )
  84. else:
  85. def log_global_cache_errors(*args, **kwargs):
  86. pass
  87. def log_global_cache_stats(*args, **kwargs):
  88. pass
  89. def log_global_cache_vals(*args, **kwargs):
  90. pass
  91. def use_global_cache() -> bool:
  92. return False
  93. output_code_log = torch._logging.getArtifactLogger(__name__, "output_code")
  94. LOCK_TIMEOUT = 600
  95. _IS_WINDOWS = sys.platform == "win32"
  96. log = logging.getLogger(__name__)
  97. def cpp_wrapper_cache_dir(name: str) -> str:
  98. cu_str = (
  99. "cpu"
  100. if torch.version.cuda is None
  101. else f'cu{torch.version.cuda.replace(".", "")}'
  102. )
  103. python_version = f"py{sys.version_info.major}{sys.version_info.minor}"
  104. build_folder = f"{python_version}_{cu_str}"
  105. cpp_wrapper_dir = os.path.join(cache_dir(), build_folder)
  106. cpp_wrapper_build_directory = os.path.join(cpp_wrapper_dir, name)
  107. os.makedirs(cpp_wrapper_build_directory, exist_ok=True)
  108. return cpp_wrapper_build_directory
  109. def get_cpp_wrapper_cubin_path_name():
  110. return "cubin_path" if torch.version.hip is None else "hsaco_path"
  111. class CacheBase:
  112. @staticmethod
  113. @functools.lru_cache(None)
  114. def get_system() -> Dict[str, Any]:
  115. try:
  116. from triton.compiler.compiler import triton_key
  117. # Use triton_key instead of triton.__version__ as the version
  118. # is not updated with each code change
  119. triton_version = triton_key()
  120. except ModuleNotFoundError:
  121. triton_version = None
  122. try:
  123. system: Dict[str, Any] = {
  124. "device": {
  125. "name": torch.cuda.get_device_properties(
  126. torch.cuda.current_device()
  127. ).name,
  128. },
  129. "version": {
  130. "cuda": torch.version.cuda,
  131. "triton": triton_version,
  132. },
  133. }
  134. except (AssertionError, RuntimeError):
  135. # If cuda is not installed, none of the above config is relevant.
  136. system = {}
  137. system["hash"] = hashlib.sha256(
  138. json.dumps(system, sort_keys=True).encode("utf-8")
  139. ).hexdigest()
  140. return system
  141. @staticmethod
  142. @clear_on_fresh_inductor_cache
  143. @functools.lru_cache(None)
  144. def get_local_cache_path() -> Path:
  145. return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"]))
  146. @staticmethod
  147. @functools.lru_cache(None)
  148. def get_global_cache_path() -> Optional[Path]:
  149. return (
  150. Path(os.path.join(config.global_cache_dir, CacheBase.get_system()["hash"]))
  151. if config.global_cache_dir is not None
  152. else None
  153. )
  154. def __init__(self) -> None:
  155. self.system = CacheBase.get_system()
  156. def get_local_cache(self) -> Dict[str, Any]:
  157. local_cache_path = self.get_local_cache_path()
  158. if not local_cache_path.is_file():
  159. return {}
  160. with open(local_cache_path) as local_cache_fp:
  161. local_cache = json.load(local_cache_fp)
  162. return local_cache["cache"]
  163. def update_local_cache(self, local_cache: Dict[str, Any]) -> None:
  164. local_cache_path = self.get_local_cache_path()
  165. write_atomic(
  166. str(local_cache_path),
  167. json.dumps({"system": self.system, "cache": local_cache}, indent=4),
  168. make_dirs=True,
  169. )
  170. class LocalCache(CacheBase):
  171. def lookup(self, *keys: str) -> Optional[Dict[str, Any]]:
  172. cache = self.get_local_cache()
  173. sub_cache = cache
  174. for key in keys:
  175. if key in cache:
  176. sub_cache = cache[key]
  177. else:
  178. return None
  179. return sub_cache
  180. def set_value(self, *keys: str, value: Any) -> None:
  181. cache = self.get_local_cache()
  182. sub_cache = cache
  183. for key in keys[0:-1]:
  184. sub_cache.setdefault(key, {})
  185. sub_cache = sub_cache[key]
  186. sub_cache[keys[-1]] = value
  187. self.update_local_cache(cache)
  188. class PersistentCache(CacheBase):
  189. @functools.lru_cache(None) # noqa: B019
  190. def get_global_cache(self):
  191. global_cache_path = self.get_global_cache_path()
  192. if global_cache_path is None or not global_cache_path.is_file():
  193. return {}
  194. with open(global_cache_path) as global_cache_fp:
  195. global_cache = json.load(global_cache_fp)
  196. return global_cache["cache"]
  197. def lookup(
  198. self,
  199. choices: List[ChoiceCaller],
  200. op: str,
  201. inputs: str,
  202. benchmark: Optional[Callable[[Any], Dict[ChoiceCaller, float]]],
  203. ) -> Dict[ChoiceCaller, float]:
  204. """
  205. Check to see if we have benchmarked the given choice callers. For each
  206. choice caller:
  207. 1. Check global_cache[op][inputs][choice][precision], return benchmark if cached.
  208. 2. Check local_cache[op][inputs][choice][precision], return benchmark if cached.
  209. 3. If benchmark is not None:
  210. a. `max_autotune_gemm=True`: benchmark the choice, update
  211. local_cache[op][inputs][choice], and return the benchmark.
  212. b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing.
  213. """
  214. precision = torch.get_float32_matmul_precision()
  215. log_stats = partial(log_global_cache_stats, self.system, op, inputs, precision)
  216. log_vals = partial(log_global_cache_vals, self.system, op, inputs, precision)
  217. log_errors = partial(
  218. log_global_cache_errors, self.system, op, inputs, precision
  219. )
  220. timings = {}
  221. def check_cache(cache, callback=None) -> bool:
  222. """Check if `cache` contains data for all the choices"""
  223. hit = True
  224. for choice in choices:
  225. choice_hash = choice.hash_key()
  226. if choice_hash in cache.get(op, {}).get(inputs, {}).get(precision, {}):
  227. # cache hit
  228. timings[choice] = cache[op][inputs][precision][choice_hash]
  229. else:
  230. # cache miss
  231. hit = False
  232. break
  233. if callback:
  234. callback(cached=hit)
  235. return hit
  236. if config.max_autotune or config.max_autotune_gemm:
  237. local_cache = self.get_local_cache() if config.autotune_local_cache else {}
  238. # check local cache first since it is data specific to the current machine
  239. if (
  240. not check_cache(local_cache)
  241. and not (
  242. use_global_cache()
  243. and check_cache(self.get_global_cache(), callback=log_stats)
  244. )
  245. and benchmark is not None
  246. ):
  247. try:
  248. # re-benchmark everything to try to get consistent numbers from the same machine
  249. timings = benchmark(choices)
  250. assert all(choice in timings for choice in choices)
  251. local_cache.setdefault(op, {})
  252. local_cache[op].setdefault(inputs, {}).setdefault(precision, {})
  253. for choice, timing in timings.items():
  254. local_cache[op][inputs][precision][choice.hash_key()] = timing
  255. except RuntimeError as e:
  256. # catch and log autotuning failures
  257. log_errors(e)
  258. raise e
  259. self.update_local_cache(local_cache)
  260. timings_to_log = {
  261. choice.hash_key(): timings[choice] for choice in choices
  262. }
  263. log_vals(timings_to_log)
  264. elif use_global_cache():
  265. # only check global cache, not local one
  266. check_cache(self.get_global_cache(), callback=log_stats)
  267. # may have a partial cache hit, where not everything is benchmarked
  268. return timings
  269. def get_lock_dir() -> str:
  270. lock_dir = os.path.join(cache_dir(), "locks")
  271. if not os.path.exists(lock_dir):
  272. os.makedirs(lock_dir, exist_ok=True)
  273. return lock_dir
  274. def sha256_hash(data: bytes) -> str:
  275. # [:51] to strip off the "Q====" suffix common to every hash value.
  276. return base64.b32encode(hashlib.sha256(data).digest())[:51].decode("utf-8").lower()
  277. def code_hash(code: Union[str, bytes], extra: str = ""):
  278. hashing_str = code if isinstance(code, bytes) else code.encode("utf-8")
  279. if extra != "":
  280. hashing_str = hashing_str + b"||" + extra.encode("utf-8")
  281. return "c" + sha256_hash(hashing_str)
  282. def get_path(
  283. basename: str, extension: str, specified_dir: str = ""
  284. ) -> Tuple[str, str, str]:
  285. if specified_dir:
  286. if os.path.isabs(specified_dir):
  287. subdir = specified_dir
  288. else:
  289. subdir = os.path.join(cache_dir(), specified_dir)
  290. else:
  291. subdir = os.path.join(cache_dir(), basename[1:3])
  292. path = os.path.join(subdir, f"{basename}.{extension}")
  293. return basename, subdir, path
  294. def get_hash(content: Union[str, bytes], extra: str = "", hash_type: str = "code"):
  295. if hash_type == "code":
  296. return code_hash(content, extra)
  297. if hash_type in ["cubin", "hsaco"]:
  298. return code_hash(repr(content))
  299. raise AssertionError(f"Unknown hash type {hash_type}")
  300. def write(
  301. content: Union[str, bytes],
  302. extension: str,
  303. extra: str = "",
  304. hash_type: str = "code",
  305. specified_dir: str = "",
  306. ) -> Tuple[str, str]:
  307. # use striped content to compute hash so we don't end up with different
  308. # hashes just because the content begins/ends with different number of
  309. # spaces.
  310. key: str = get_hash(content.strip(), extra, hash_type)
  311. basename, subdir, path = get_path(key, extension, specified_dir)
  312. if not os.path.exists(path):
  313. write_atomic(path, content, make_dirs=True)
  314. return basename, path
  315. def write_text(text: str) -> str:
  316. """
  317. Write the `text` to a file and return the path computed based on the hash.
  318. """
  319. return write(text, "txt")[1]
  320. def write_atomic(
  321. path: str, content: Union[str, bytes], make_dirs: bool = False
  322. ) -> None:
  323. # Write into temporary file first to avoid conflicts between threads
  324. # Avoid using a named temporary file, as those have restricted permissions
  325. assert isinstance(
  326. content, (str, bytes)
  327. ), "Only strings and byte arrays can be saved in the cache"
  328. path = Path(path)
  329. if make_dirs:
  330. path.parent.mkdir(parents=True, exist_ok=True)
  331. tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp"
  332. write_mode = "w" if isinstance(content, str) else "wb"
  333. with tmp_path.open(write_mode) as f:
  334. f.write(content)
  335. tmp_path.rename(path)
  336. @dataclasses.dataclass
  337. class TensorMetadataAndValues:
  338. """
  339. TensorMetadata plus the elements as a list of raw values.
  340. Used for hashing inlined constants.
  341. """
  342. tensor_metadata: TensorMetadata
  343. values: List[Any]
  344. def _ident(x: Any) -> Any:
  345. return x
  346. def extract_tensor_metadata_for_cache_key(t):
  347. """
  348. Extracts the tensor metadata and removes fields of the TensorMetadata
  349. that are not needed for caching
  350. """
  351. meta = extract_tensor_metadata(t)
  352. if not hasattr(t, "_is_inductor_static"):
  353. meta = dataclasses.replace(meta, storage_offset=0, storage_bytes=None)
  354. return meta
  355. def _reduce_fake_tensor(t):
  356. """
  357. See FxGraphCachePickler. Custom reducer to pickle FakeTensors.
  358. """
  359. metadata = extract_tensor_metadata_for_cache_key(t)
  360. return (_ident, (metadata,))
  361. def _reduce_tensor(t):
  362. """
  363. See FxGraphCachePickler. Custom reducer to pickle Tensors.
  364. If we see tensors, we know they're constants stored as attributes on
  365. the GraphModule. Include the values in the key calculation. Small
  366. tensors will be inlined, so we can't serve the same cache entry for
  367. different values anyway. Large constants are treated as parameters,
  368. so we could conceivably reuse a cache entry. To do that, however,
  369. PyCodeCache would need more complexity to create a new module from its
  370. cache, but with the right constants attached as attributes.
  371. """
  372. if t.is_mkldnn:
  373. # TODO: These tensors don't currently pickle, so we can't cache a
  374. # compiled graph containing them. Just fail now. If mkldnn tensors
  375. # get pickling support, we can remove this.
  376. raise BypassFxGraphCache
  377. # Very large tensors could be expensive to copy to cpu and hash. Let's
  378. # at least report if we find slowness.
  379. start = time()
  380. values = t.tolist()
  381. elapsed = time() - start
  382. if elapsed > 1.0:
  383. warnings.warn(
  384. f"FX graph cache handling of a large constant took {elapsed:.1}s. Please file an issue."
  385. )
  386. metadata = extract_tensor_metadata_for_cache_key(t)
  387. return (_ident, (TensorMetadataAndValues(metadata, values),))
  388. def _reduce_symint(s):
  389. """
  390. See FxGraphCachePickler. Custom reducer to pickle SymInts.
  391. """
  392. # For hashing purposes, we only care about the name of the symbol and
  393. # not the backed value. We evaluate guards stored with a cached graph
  394. # to ensure a cached entity with SymInt args is safe to reuse.
  395. return (_ident, (str(s),))
  396. def _reduce_unsupported(s):
  397. """
  398. See FxGraphCachePickler. Custom reducer to handle any objects that we don't
  399. support and therefore raise to bypass caching.
  400. """
  401. raise BypassFxGraphCache
  402. class FxGraphCachePickler(pickle.Pickler):
  403. """
  404. Custom pickler to customize the pickling of some objects (Tensors), only for the
  405. purpose of computing a hash for keying into the FxGraphCache. Tensors contain
  406. objects that don't pickle and/or vary between runs, and we want to capture the
  407. data that allow us to compute a stable, but safe hash.
  408. """
  409. dispatch_table = copyreg.dispatch_table.copy()
  410. dispatch_table[FakeTensor] = _reduce_fake_tensor
  411. dispatch_table[torch.Tensor] = _reduce_tensor
  412. dispatch_table[torch.SymInt] = _reduce_symint
  413. dispatch_table[
  414. torch.fx.experimental._backward_state.BackwardState
  415. ] = _reduce_unsupported
  416. @classmethod
  417. def dumps(cls, obj) -> bytes:
  418. """
  419. Pickle an object using the FxGraphCachePickler.
  420. """
  421. with io.BytesIO() as stream:
  422. pickler = cls(stream)
  423. try:
  424. pickler.dump(obj)
  425. except (TypeError, AttributeError) as e:
  426. # Some configs options are callables, e.g., post_grad_custom_pre_pass,
  427. # and may not pickle.
  428. log.warning("Can't pickle", exc_info=True)
  429. raise BypassFxGraphCache from e
  430. return stream.getvalue()
  431. @classmethod
  432. def get_hash(cls, obj: Any) -> str:
  433. """
  434. Serialize an object using the FxGraphCachePickler and return a hash
  435. of the pickled object.
  436. """
  437. serialized_data = cls.dumps(obj)
  438. return sha256_hash(serialized_data)
  439. @classmethod
  440. def debug_str(cls, inp: Any) -> str:
  441. """
  442. Get a printable string describing in more detail all the attributes
  443. comprising an object. Useful for debugging when one graph hashes
  444. to a different value than another.
  445. """
  446. def get_str(obj) -> str:
  447. if isinstance(obj, torch.Tensor):
  448. return str(extract_tensor_metadata_for_cache_key(obj))
  449. elif isinstance(obj, bytes):
  450. return "<bytes>"
  451. else:
  452. return str(obj)
  453. lines = []
  454. for attr, obj in vars(inp).items():
  455. if isinstance(obj, list):
  456. for ii in range(len(obj)):
  457. h = cls.get_hash(obj[ii])
  458. lines.append(f"[{h}] {attr}[{ii}]: {get_str(obj[ii])}")
  459. elif isinstance(obj, dict):
  460. for k, v in obj.items():
  461. h = cls.get_hash(v)
  462. lines.append(f"[{h}] {attr}[{k}]: {get_str(v)}")
  463. else:
  464. h = cls.get_hash(obj)
  465. lines.append(f"[{h}] {attr}: {get_str(obj)}")
  466. return "\n".join(lines)
  467. def build_code_hash(roots, prefix, hasher):
  468. for lib in sorted(pkgutil.iter_modules(roots, prefix), key=lambda x: x.name):
  469. spec = lib.module_finder.find_spec(lib.name, None)
  470. assert spec is not None
  471. module = spec.origin
  472. assert module is not None
  473. with open(module, "rb") as f:
  474. hasher.update(spec.name.encode("utf-8"))
  475. hasher.update(f.read())
  476. if lib.ispkg:
  477. # need to also hash submodules
  478. build_code_hash(spec.submodule_search_locations, f"{spec.name}.", hasher)
  479. def get_code_hash(roots, extra_files=()):
  480. hasher = hashlib.sha256()
  481. hasher.update(torch.__version__.encode("utf-8"))
  482. build_code_hash(roots, "", hasher)
  483. for path in extra_files:
  484. if os.path.exists(path):
  485. with open(path, "rb") as f:
  486. hasher.update(f.read())
  487. return hasher.digest()
  488. @functools.lru_cache(None)
  489. def torch_key():
  490. """
  491. Compute a key that contains relevant information about torch source files
  492. """
  493. if not config.is_fbcode():
  494. inductor_root = os.path.dirname(__file__)
  495. extra_files = (
  496. "codegen/aoti_runtime/interface.cpp",
  497. "codegen/aoti_runtime/implementation.cpp",
  498. "codegen/cpp_prefix.h",
  499. "script.ld",
  500. )
  501. return get_code_hash(
  502. [inductor_root], [os.path.join(inductor_root, x) for x in extra_files]
  503. )
  504. from libfb.py import parutil
  505. return parutil.get_file_contents("torch/src_hash.txt").rstrip()
  506. def get_inductor_root():
  507. return os.path.dirname(__file__)
  508. @dataclasses.dataclass
  509. class OrderedSetHolder:
  510. """
  511. See FxGraphHashDetails. Holds a sorted list to support stable hashing
  512. of set kwargs.
  513. """
  514. items: List[Any]
  515. class BypassFxGraphCache(Exception):
  516. """
  517. Exception to indicate that the FxGraphCache should be bypassed.
  518. """
  519. pass
  520. class FxGraphHashDetails:
  521. """
  522. Object to capture all the details for a compiled FX graph relevant to computing
  523. a safe and stable cache key.
  524. """
  525. # Excluded kwargs param that are not stable between runs
  526. EXCLUDED_KWARGS = ["graph_id"]
  527. def __init__(
  528. self,
  529. gm: torch.fx.GraphModule,
  530. example_inputs: List[torch.Tensor],
  531. fx_kwargs: Dict[str, Any],
  532. inputs_to_check: Sequence[int],
  533. ):
  534. self.gm = gm
  535. self.example_inputs = example_inputs
  536. # Order kwargs so hashing is stable to changes in kwarg order.
  537. self.fx_kwargs = {}
  538. for k in sorted(fx_kwargs):
  539. if k not in self.EXCLUDED_KWARGS:
  540. if type(fx_kwargs[k]) is set:
  541. # Special case to handle set params. Python sets can't be
  542. # ordered, so sort the elements and store them in a proxy.
  543. self.fx_kwargs[k] = OrderedSetHolder(sorted(fx_kwargs[k]))
  544. else:
  545. self.fx_kwargs[k] = fx_kwargs[k]
  546. # Alignment checks
  547. self.inputs_to_check = inputs_to_check
  548. # 'Deterministic algorithms' can affect codegen via lowering to cuda kernels.
  549. self.deterministic_algorithms_settings = (
  550. torch.are_deterministic_algorithms_enabled(),
  551. torch.is_deterministic_algorithms_warn_only_enabled(),
  552. torch.utils.deterministic.fill_uninitialized_memory, # type: ignore[attr-defined]
  553. )
  554. # Global settings affecting matmul codegen.
  555. self.cuda_matmul_settings = (
  556. torch.backends.cuda.matmul.allow_tf32,
  557. torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction,
  558. torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction,
  559. )
  560. # Also hash on various system info (including the triton compiler version).
  561. self.torch_version = torch_key()
  562. self.system_info = CacheBase.get_system()
  563. self.inductor_config = config.save_config_portable()
  564. def debug_str(self) -> str:
  565. """
  566. Get a printable string describing in more detail all the attributes
  567. comprising this object. Useful for debugging when one graph hashes
  568. to a different value than another.
  569. """
  570. return FxGraphCachePickler.debug_str(self)
  571. def compiled_fx_graph_hash(
  572. gm: torch.fx.GraphModule,
  573. example_inputs: List[torch.Tensor],
  574. fx_kwargs: Dict[str, Any],
  575. inputs_to_check: Sequence[int],
  576. ) -> str:
  577. """
  578. Generate a unique hash of the FX graph for caching.
  579. """
  580. details = FxGraphHashDetails(gm, example_inputs, fx_kwargs, inputs_to_check)
  581. # The prefix distinguishes among the other kinds of objects we
  582. # cache in this module.
  583. key = "f" + FxGraphCachePickler.get_hash(details)
  584. debug_str = details.debug_str()
  585. log.debug(f"FX graph cache hash details for key {key}:\n{debug_str}") # noqa: G004
  586. torch._logging.trace_structured(
  587. "artifact",
  588. metadata_fn=lambda: {
  589. "name": "fx_graph_cache_hash",
  590. "encoding": "json",
  591. },
  592. payload_fn=lambda: json.dumps(
  593. {"key": key, "components": debug_str.split("\n")}
  594. ),
  595. )
  596. return key
  597. class FxGraphCache:
  598. """
  599. Supports caching and reusing compiled Fx graphs.
  600. The overall strategy is as follows:
  601. - This cache stores entries on disk. When saving an entry, we can't
  602. serialize callables (that could be C++, Triton, etc.), so we serialize
  603. their own disk cache location. We then recreate the compiled artifact
  604. after fetching from disk.
  605. - For indexing the cache, we gather the fields relevant to identifying an
  606. FxGraph (the graph module, graph inputs, system settings etc.) into an
  607. FxGraphCacheDetails object, pickle it, and compute a hash for the key.
  608. See FxGraphCachePickler.
  609. - Among the metadata we store, we also include a guards expression that's
  610. appropriate for validating any symbols for Tensor arguments that have
  611. symbolic bounds. On cache lookup then, we evaluate those guards in the
  612. current context to validate that a cached entry can be served.
  613. - A given graph could have multiple compiled versions, corresponding to
  614. different sets of guards. Therefore, we store cache entries in the form:
  615. <temp dir>/<fx graph hash>/<serialized metatdata>
  616. - On lookup, we compute the key from the graph details, iterate over all
  617. leaf files in the corresponding subdirectory, deserialize the entry, and
  618. evaluate its guards expression. If the evaluation succeeds, we have a
  619. cache hit. If it fails, we compile the graph and store a new entry.
  620. - Finally, on a cache hit, we need to make sure any guards that would
  621. have been created during compilation are added to the current context.
  622. """
  623. # TODO(masnesral): Investigate whether it's beneficial to store compiled graphs
  624. # in an in-memory cache after loading from disk.
  625. @staticmethod
  626. def _get_tmp_dir() -> str:
  627. """
  628. Get the toplevel temporary directory for storing compiled graphs.
  629. """
  630. return os.path.join(cache_dir(), "fxgraph")
  631. @staticmethod
  632. def _get_tmp_dir_for_key(key: str) -> str:
  633. """
  634. Return the disk location for a given cache key.
  635. """
  636. return os.path.join(FxGraphCache._get_tmp_dir(), key[1:3], key)
  637. @staticmethod
  638. def _filter_backed_symints(inputs: List[Any]) -> List[torch.SymInt]:
  639. """
  640. Get the backed SymInt objects from the input list. Note that we can never
  641. have guards that depend on unbacked symint.
  642. """
  643. return [s for s in inputs if isinstance(s, torch.SymInt) and has_hint(s)]
  644. @staticmethod
  645. def _get_shape_env() -> Optional[ShapeEnv]:
  646. """
  647. Helper to get the shape env from the tracing context.
  648. """
  649. ctx = torch._guards.TracingContext.try_get()
  650. if not ctx:
  651. return None
  652. return ctx.fake_mode.shape_env
  653. @staticmethod
  654. def _lookup_graph(
  655. key: str,
  656. example_inputs: List[torch.Tensor],
  657. local,
  658. remote_cache,
  659. ) -> Optional[CompiledFxGraph]:
  660. """
  661. Lookup a compiled graph in the cache by key. On a hit, return the
  662. deserialized CompiledFxGraph object. On a miss, return None.
  663. """
  664. shape_env = FxGraphCache._get_shape_env()
  665. assert shape_env is not None
  666. symints = FxGraphCache._filter_backed_symints(example_inputs)
  667. hints = [hint_int(s) for s in symints]
  668. def iterate_over_candidates() -> Generator[CompiledFxGraph, None, None]:
  669. if local:
  670. subdir = FxGraphCache._get_tmp_dir_for_key(key)
  671. if os.path.exists(subdir):
  672. for path in sorted(os.listdir(subdir)):
  673. try:
  674. with open(os.path.join(subdir, path), "rb") as f:
  675. yield pickle.load(f)
  676. except Exception:
  677. log.warning(
  678. "fx graph cache unable to load compiled graph",
  679. exc_info=True,
  680. )
  681. if remote_cache:
  682. try:
  683. if (data := remote_cache.get(key)) is not None:
  684. yield pickle.loads(data)
  685. except Exception:
  686. log.warning(
  687. "fx graph cache unable to load compiled graph", exc_info=True
  688. )
  689. # Iterate over any entries in the subdir for this key and evaluate
  690. # their guards to determine whether there's a hit.
  691. graph = None
  692. for candidate in iterate_over_candidates():
  693. if not candidate.guards_expr:
  694. # No guards to evaluate, so this is a hit.
  695. graph = candidate
  696. break
  697. # Evaluate the guard expression in the current context.
  698. # If there's not a cache hit, we don't want the evaluation to
  699. # affect the current env, e.g., cause the creation of new guards,
  700. # so we evaluate with the hints instead of the symbols.
  701. hit = bool(
  702. shape_env.evaluate_guards_expression(candidate.guards_expr, hints)
  703. )
  704. log.debug(
  705. "fx graph cache key %s evaluating guards [%s] with values %s => hit=%s",
  706. key,
  707. candidate.guards_expr,
  708. hints,
  709. hit,
  710. )
  711. if hit:
  712. graph = candidate
  713. break
  714. if graph is None:
  715. return None
  716. # See _save_graph(); we don't store the callable in the cache entry so
  717. # recreate it here from the PyCodeCache disk cache.
  718. artifact_path = get_path(graph.cache_key, "py")[2]
  719. if not os.path.exists(artifact_path):
  720. counters["inductor"]["fxgraph_lookup_write_file"] += 1
  721. Path(os.path.dirname(artifact_path)).mkdir(parents=True, exist_ok=True)
  722. code = graph.source_code
  723. cpp_pp = cpp_prefix_path()
  724. if os.path.basename(cpp_pp) in code:
  725. if cpp_pp in code:
  726. # Great the name is correct
  727. pass
  728. else:
  729. # Old dir name is included, replace it
  730. pattern = rf'#include\s*"[^"]+{os.path.basename(cpp_pp)}"'
  731. code = re.sub(pattern, f'#include "{cpp_pp}"', code)
  732. write_atomic(artifact_path, code, make_dirs=True)
  733. try:
  734. graph.current_callable = PyCodeCache.load_by_key_path(
  735. graph.cache_key,
  736. artifact_path,
  737. graph.cache_linemap,
  738. graph.constants,
  739. ).call
  740. except OSError:
  741. # Not expected, but in case the PyCodeCache entry is removed from
  742. # underneath us, treat it as a cache miss and recompile.
  743. log.error("Failed to load cached artifact: %s", artifact_path)
  744. return None
  745. # Now re-evaluate with the symints to add any guards to the current env.
  746. if graph.guards_expr:
  747. check = bool(
  748. shape_env.evaluate_guards_expression(graph.guards_expr, symints)
  749. )
  750. assert check is True
  751. log.debug(
  752. "fx graph cache key %s post-load guards: %s", key, shape_env.guards
  753. )
  754. # Increment the cached metrics by the amounts recorded when the FX
  755. # graph was compiled for this cache entry. Pretending these counters
  756. # were incremented normally is useful for testing with the cache enabled.
  757. metrics.CachedMetricsHelper.apply_deltas(graph.metrics_deltas)
  758. return graph
  759. @staticmethod
  760. def _save_graph(
  761. key: str,
  762. compiled_graph: CompiledFxGraph,
  763. example_inputs: List[torch.Tensor],
  764. time_taken_ns,
  765. local,
  766. remote_cache,
  767. ):
  768. """
  769. Store a serialized CompiledFxGraph on disk.
  770. """
  771. disk_compiled_graph = copy(compiled_graph)
  772. # We can't really serialize callables that may be C++/Triton/etc.,
  773. # so we serialize their PyCodeCache disk cache location instead.
  774. # TODO: This could be better if we're ever able to serialize compiled
  775. # models to disk.
  776. disk_compiled_graph.current_callable = None
  777. # Before serializing, compute the guard expression that will be used to
  778. # ensure that a CompiledFxGraph is valid when loaded from the cache. It's
  779. # sufficient to consider only the SymInt args to the fx graph since the
  780. # Tensor shapes are already captured in the hash for the cache key. Any
  781. # Tensor arg with a symbolic shape will have a SymInt arg for the graph.
  782. shape_env = FxGraphCache._get_shape_env()
  783. assert shape_env is not None
  784. symints = FxGraphCache._filter_backed_symints(example_inputs)
  785. guards = shape_env.get_pruned_guards(symints)
  786. disk_compiled_graph.guards_expr = shape_env.produce_guards_expression(
  787. placeholders=symints, guards=guards
  788. )
  789. try:
  790. content = pickle.dumps(disk_compiled_graph)
  791. except Exception:
  792. log.warning(
  793. "fx graph cache unable to serialize compiled graph", exc_info=True
  794. )
  795. counters["inductor"]["fxgraph_cache_pickle_error"] += 1
  796. return
  797. try:
  798. if local:
  799. subdir = FxGraphCache._get_tmp_dir_for_key(key)
  800. if not os.path.exists(subdir):
  801. os.makedirs(subdir, exist_ok=True)
  802. # Use a hash of the serialized CompiledFxGraph to get a unique file
  803. # name. The specific name doesn't matter since a lookup involves
  804. # iterating over all entries in the parent subdir.
  805. path = os.path.join(subdir, sha256_hash(content))
  806. write_atomic(path, content, make_dirs=True)
  807. if remote_cache:
  808. cache_data = (
  809. {
  810. "data": content,
  811. "time_taken_ms": time_taken_ns
  812. // 1000000, # Convert from NS to MS
  813. }
  814. if config.is_fbcode()
  815. else content
  816. )
  817. remote_cache.put(key, cache_data)
  818. except Exception:
  819. log.warning("fx graph unable to write to cache", exc_info=True)
  820. counters["inductor"]["fxgraph_cache_write_error"] += 1
  821. @staticmethod
  822. def _check_can_cache(gm: torch.fx.GraphModule):
  823. """
  824. Check some conditions that would preclude caching and raise BypassFxGraphCache
  825. to bypass in case caching is not possible.
  826. """
  827. # Freezing can embed constants that wouldn't be static across runs.
  828. if config.freezing or config.aot_inductor.use_runtime_constant_folding:
  829. raise BypassFxGraphCache
  830. # The treatment of guards in the caching implementation requires that
  831. # we have a shape env.
  832. if FxGraphCache._get_shape_env() is None:
  833. log.debug("fx graph cache no shape env")
  834. raise BypassFxGraphCache
  835. # HigherOrderOperators should be handled on a case-by-case basis.
  836. # Currently, we just skip caching if we have any.
  837. # We also skip if there are any torchbind objects.
  838. for node in gm.graph.nodes:
  839. if isinstance(node.target, torch._ops.HigherOrderOperator):
  840. raise BypassFxGraphCache
  841. if node.op == "getattr" and isinstance(
  842. getattr(gm, node.target), torch._C.ScriptObject
  843. ):
  844. raise BypassFxGraphCache
  845. @staticmethod
  846. def load(
  847. compile_fx_fn: Callable[..., Any],
  848. gm: torch.fx.GraphModule,
  849. example_inputs: List[torch.Tensor],
  850. fx_kwargs: Dict[str, Any],
  851. inputs_to_check: Sequence[int],
  852. local: bool,
  853. remote: bool,
  854. ):
  855. """
  856. Load a compiled graph from the cache. If a cached entry does not exist,
  857. compile the graph and save it to the cache.
  858. """
  859. assert local or remote, "at least one of them needs to be enabled"
  860. compiled_graph = None
  861. try:
  862. FxGraphCache._check_can_cache(gm)
  863. key = compiled_fx_graph_hash(gm, example_inputs, fx_kwargs, inputs_to_check)
  864. remote_cache = None
  865. if remote:
  866. cache_id = "fx-graph-v1"
  867. try:
  868. if config.is_fbcode():
  869. from triton.runtime.fb_memcache import (
  870. FbMemcacheRemoteFxGraphCacheBackend,
  871. )
  872. remote_cache = FbMemcacheRemoteFxGraphCacheBackend(cache_id)
  873. else:
  874. from torch._inductor.remote_cache import RedisRemoteCacheBackend
  875. remote_cache = RedisRemoteCacheBackend(cache_id)
  876. except Exception:
  877. remote_cache = None
  878. log.warning("Unable to create a remote cache", exc_info=True)
  879. compiled_graph = FxGraphCache._lookup_graph(
  880. key, example_inputs, local, remote_cache
  881. )
  882. if compiled_graph is None:
  883. log.debug("fx graph cache miss for key %s", key)
  884. counters["inductor"]["fxgraph_cache_miss"] += 1
  885. start_time = time_ns()
  886. compiled_graph = compile_fx_fn(gm, example_inputs, **fx_kwargs)
  887. time_taken_ns = time_ns() - start_time
  888. FxGraphCache._save_graph(
  889. key,
  890. compiled_graph,
  891. example_inputs,
  892. time_taken_ns,
  893. local,
  894. remote_cache,
  895. )
  896. else:
  897. log.debug("fx graph cache hit for key %s", key)
  898. counters["inductor"]["fxgraph_cache_hit"] += 1
  899. except BypassFxGraphCache:
  900. counters["inductor"]["fxgraph_cache_bypass"] += 1
  901. if not compiled_graph:
  902. compiled_graph = compile_fx_fn(gm, example_inputs, **fx_kwargs)
  903. return compiled_graph
  904. @staticmethod
  905. def clear():
  906. """
  907. Clear out the on-disk cache.
  908. """
  909. try:
  910. shutil.rmtree(FxGraphCache._get_tmp_dir())
  911. except FileNotFoundError:
  912. pass
  913. @dataclasses.dataclass
  914. class CompiledFxGraph:
  915. """
  916. Class holding a compiled FX graph. This is the object serialized on disk
  917. to support FxGraph caching.
  918. """
  919. current_callable: Optional[Callable[..., Any]]
  920. cache_key: str
  921. source_code: str = dataclasses.field(repr=False) # Do not display source_code
  922. cache_linemap: Optional[List[Tuple[int, str]]]
  923. device_types: Set[str]
  924. device_idxs: Set[int]
  925. mutated_inputs: Set[str]
  926. mutated_input_idxs: Set[int]
  927. constants: Dict[str, torch.Tensor]
  928. torchbind_constants: Dict[str, torch._C.ScriptObject]
  929. output_strides: Optional[List[Optional[Tuple[int, ...]]]]
  930. disabled_cudagraphs_reason: Optional[str]
  931. metrics_deltas: metrics.CachedMetricsDeltas
  932. # This is a string representation of an expression we serialize
  933. # with the object so the guards can be evaluated in a different
  934. # context in order to verify the validity of serving a cached
  935. # fx graph. The expression must be generated by:
  936. # ShapeEnv.produce_guards_expression()
  937. guards_expr: Optional[str]
  938. _boxed_call: Optional[bool] = None
  939. def __init__(
  940. self,
  941. current_callable: Optional[Callable[..., Any]],
  942. graph: GraphLowering,
  943. output_strides: List[Optional[Tuple[int, ...]]],
  944. disabled_cudagraphs_reason: Optional[str],
  945. metrics_deltas: metrics.CachedMetricsDeltas,
  946. ):
  947. self.current_callable = current_callable
  948. self.cache_key = graph.cache_key
  949. if graph.cache_path:
  950. with open(graph.cache_path) as f:
  951. self.source_code = f.read()
  952. self.cache_linemap = graph.cache_linemap
  953. self.device_types = graph.device_types
  954. self.device_idxs = graph.device_idxs
  955. self.mutated_inputs = graph.mutated_inputs
  956. self.mutated_input_idxs = set(graph.mutated_input_idxs)
  957. self.constants = graph.constants
  958. self.torchbind_constants = graph.torchbind_constants
  959. self.output_strides = output_strides
  960. self.disabled_cudagraphs_reason = disabled_cudagraphs_reason
  961. self.metrics_deltas = metrics_deltas
  962. self.guards_expr = None
  963. def __call__(self, inputs: List[Any]) -> Any:
  964. assert self.current_callable is not None
  965. return self.current_callable(inputs)
  966. def cpp_compiler() -> str:
  967. if config.is_fbcode():
  968. return build_paths.cc() if torch.version.hip is None else build_paths.clang()
  969. if isinstance(config.cpp.cxx, (list, tuple)):
  970. search = tuple(config.cpp.cxx)
  971. else:
  972. search = (config.cpp.cxx,)
  973. return cpp_compiler_search(search)
  974. @functools.lru_cache(1)
  975. def cpp_compiler_search(search: str) -> str:
  976. for cxx in search:
  977. try:
  978. if cxx is None:
  979. # gxx package is only available for Linux
  980. # according to https://anaconda.org/conda-forge/gxx/
  981. if sys.platform != "linux":
  982. continue
  983. # Do not install GXX by default
  984. if not os.getenv("TORCH_INDUCTOR_INSTALL_GXX"):
  985. continue
  986. from filelock import FileLock
  987. lock_dir = get_lock_dir()
  988. lock = FileLock(
  989. os.path.join(lock_dir, "g++.lock"), timeout=LOCK_TIMEOUT
  990. )
  991. with lock:
  992. cxx = install_gcc_via_conda()
  993. subprocess.check_output([cxx, "--version"])
  994. return cxx
  995. except (subprocess.SubprocessError, FileNotFoundError, ImportError):
  996. continue
  997. raise exc.InvalidCxxCompiler
  998. def install_gcc_via_conda() -> str:
  999. """On older systems, this is a quick way to get a modern compiler"""
  1000. prefix = os.path.join(cache_dir(), "gcc")
  1001. cxx_path = os.path.join(prefix, "bin", "g++")
  1002. if not os.path.exists(cxx_path):
  1003. log.info("Downloading GCC via conda")
  1004. conda = os.environ.get("CONDA_EXE", "conda")
  1005. if conda is None:
  1006. conda = shutil.which("conda")
  1007. if conda is not None:
  1008. subprocess.check_call(
  1009. [
  1010. conda,
  1011. "create",
  1012. f"--prefix={prefix}",
  1013. "--channel=conda-forge",
  1014. "--quiet",
  1015. "-y",
  1016. "python=3.8",
  1017. "gxx",
  1018. ],
  1019. stdout=subprocess.PIPE,
  1020. )
  1021. return cxx_path
  1022. def is_gcc() -> bool:
  1023. if sys.platform == "darwin" and is_apple_clang():
  1024. return False
  1025. return bool(re.search(r"(gcc|g\+\+)", cpp_compiler()))
  1026. @functools.lru_cache(None)
  1027. def is_apple_clang() -> bool:
  1028. cxx = cpp_compiler()
  1029. version_string = subprocess.check_output([cxx, "--version"]).decode("utf8")
  1030. return "Apple" in version_string.splitlines()[0]
  1031. def is_clang() -> bool:
  1032. # Mac OS apple clang maybe named as gcc, need check compiler info.
  1033. if sys.platform == "darwin":
  1034. return is_apple_clang()
  1035. return bool(re.search(r"(clang|clang\+\+)", cpp_compiler()))
  1036. def get_compiler_version_info(compiler):
  1037. SUBPROCESS_DECODE_ARGS = ("oem",) if _IS_WINDOWS else ()
  1038. env = os.environ.copy()
  1039. env["LC_ALL"] = "C" # Don't localize output
  1040. try:
  1041. version_string = subprocess.check_output(
  1042. [compiler, "-v"], stderr=subprocess.STDOUT, env=env
  1043. ).decode(*SUBPROCESS_DECODE_ARGS)
  1044. except Exception as e:
  1045. try:
  1046. version_string = subprocess.check_output(
  1047. [compiler, "--version"], stderr=subprocess.STDOUT, env=env
  1048. ).decode(*SUBPROCESS_DECODE_ARGS)
  1049. except Exception as e:
  1050. return ""
  1051. # Mutiple lines to one line string.
  1052. version_string = version_string.replace("\r", "_")
  1053. version_string = version_string.replace("\n", "_")
  1054. return version_string
  1055. def _get_isa_dry_compile_fingerprint(isa_flags: str) -> str:
  1056. # ISA dry compile will cost about 1 sec time each startup time.
  1057. # Please check the issue: https://github.com/pytorch/pytorch/issues/100378
  1058. # Actually, dry compile is checking compile capability for ISA.
  1059. # We just record the compiler version, isa options and pytorch version info,
  1060. # and generated them to output binary hash path.
  1061. # It would optimize and skip compile existing binary.
  1062. compiler_info = get_compiler_version_info(cpp_compiler())
  1063. torch_version = torch.__version__
  1064. fingerprint = f"{compiler_info}={isa_flags}={torch_version}"
  1065. return fingerprint
  1066. class VecISA:
  1067. _bit_width: int
  1068. _macro: List[str]
  1069. _arch_flags: str
  1070. _dtype_nelements: Dict[torch.dtype, int]
  1071. # Note [Checking for Vectorized Support in Inductor]
  1072. # TorchInductor CPU vectorization reuses PyTorch vectorization utility functions
  1073. # Hence, TorchInductor would depend on Sleef* to accelerate mathematical functions
  1074. # like exp, pow, sin, cos and etc.
  1075. # But PyTorch and TorchInductor might use different compilers to build code. If
  1076. # PyTorch uses gcc-7/g++-7 to build the release package, the libtorch_cpu.so
  1077. # will not expose the Sleef* AVX512 symbols since gcc-7/g++-7 cannot pass
  1078. # avx512 check in CMake - FindAVX.cmake. But TorchInductor install the latest
  1079. # gcc/g++ compiler by default while it could support the AVX512 compilation.
  1080. # Therefore, there would be a conflict sleef version between PyTorch and
  1081. # TorchInductor. Hence, we dry-compile the following code to check whether current
  1082. # HW platform and PyTorch both could support AVX512 or AVX2. And suppose ARM
  1083. # also needs the logic
  1084. # In fbcode however, we are using the same compiler for pytorch and for inductor codegen,
  1085. # making the runtime check unnecessary.
  1086. _avx_code = """
  1087. #if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_ZVECTOR) || defined(CPU_CAPABILITY_NEON)
  1088. #include <ATen/cpu/vec/functional.h>
  1089. #include <ATen/cpu/vec/vec.h>
  1090. #endif
  1091. alignas(64) float in_out_ptr0[16] = {0.0};
  1092. extern "C" void __avx_chk_kernel() {
  1093. auto tmp0 = at::vec::Vectorized<float>(1);
  1094. auto tmp1 = tmp0.exp();
  1095. tmp1.store(in_out_ptr0);
  1096. }
  1097. """ # noqa: B950
  1098. _avx_py_load = """
  1099. import torch
  1100. from ctypes import cdll
  1101. cdll.LoadLibrary("__lib_path__")
  1102. """
  1103. def bit_width(self) -> int:
  1104. return self._bit_width
  1105. def nelements(self, dtype: torch.dtype = torch.float) -> int:
  1106. return self._dtype_nelements[dtype]
  1107. def build_macro(self) -> List[str]:
  1108. return self._macro
  1109. def build_arch_flags(self) -> str:
  1110. return self._arch_flags
  1111. def __hash__(self) -> int:
  1112. return hash(str(self))
  1113. @functools.lru_cache(None) # noqa: B019
  1114. def __bool__(self) -> bool:
  1115. from torch._inductor.cpp_builder import CppBuilder, CppTorchOptions
  1116. if config.cpp.vec_isa_ok is not None:
  1117. return config.cpp.vec_isa_ok
  1118. if config.is_fbcode():
  1119. return True
  1120. key, input_path = write(
  1121. VecISA._avx_code,
  1122. "cpp",
  1123. extra=_get_isa_dry_compile_fingerprint(self._arch_flags),
  1124. )
  1125. from filelock import FileLock
  1126. lock_dir = get_lock_dir()
  1127. lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
  1128. with lock:
  1129. output_dir = os.path.dirname(input_path)
  1130. buid_options = CppTorchOptions(vec_isa=self, warning_all=False)
  1131. x86_isa_help_builder = CppBuilder(
  1132. key,
  1133. [input_path],
  1134. buid_options,
  1135. output_dir,
  1136. )
  1137. try:
  1138. # Check if the output file exist, and compile when not.
  1139. output_path = x86_isa_help_builder.get_target_file_path()
  1140. if not os.path.isfile(output_path):
  1141. status, target_file = x86_isa_help_builder.build()
  1142. if status:
  1143. return False
  1144. # Check build result
  1145. subprocess.check_call(
  1146. [
  1147. sys.executable,
  1148. "-c",
  1149. VecISA._avx_py_load.replace("__lib_path__", output_path),
  1150. ],
  1151. stderr=subprocess.DEVNULL,
  1152. env={**os.environ, "PYTHONPATH": ":".join(sys.path)},
  1153. )
  1154. except Exception as e:
  1155. return False
  1156. return True
  1157. @dataclasses.dataclass
  1158. class VecNEON(VecISA):
  1159. _bit_width = 256 # This is required to leverage the compute implemented in aten/src/ATen/cpu/vec/vec256/vec256_float_neon.h
  1160. _macro = ["CPU_CAPABILITY_NEON"]
  1161. if sys.platform == "darwin" and platform.processor() == "arm":
  1162. _macro.append("AT_BUILD_ARM_VEC256_WITH_SLEEF")
  1163. _arch_flags = "" # Unused
  1164. _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16}
  1165. def __str__(self) -> str:
  1166. return "asimd" # detects the presence of advanced SIMD on armv8-a kernels
  1167. __hash__: Callable[[VecISA], Any] = VecISA.__hash__
  1168. @dataclasses.dataclass
  1169. class VecAVX512(VecISA):
  1170. _bit_width = 512
  1171. _macro = ["CPU_CAPABILITY_AVX512"]
  1172. _arch_flags = (
  1173. "-mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma"
  1174. if not _IS_WINDOWS
  1175. else "/arch:AVX512"
  1176. ) # TODO: use cflags
  1177. _dtype_nelements = {torch.float: 16, torch.bfloat16: 32, torch.float16: 32}
  1178. def __str__(self) -> str:
  1179. return "avx512"
  1180. __hash__: Callable[[VecISA], Any] = VecISA.__hash__
  1181. @dataclasses.dataclass
  1182. class VecAVX2(VecISA):
  1183. _bit_width = 256
  1184. _macro = ["CPU_CAPABILITY_AVX2"]
  1185. _arch_flags = (
  1186. "-mavx2 -mfma" if not _IS_WINDOWS else "/arch:AVX2"
  1187. ) # TODO: use cflags
  1188. _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16}
  1189. def __str__(self) -> str:
  1190. return "avx2"
  1191. __hash__: Callable[[VecISA], Any] = VecISA.__hash__
  1192. @dataclasses.dataclass
  1193. class VecZVECTOR(VecISA):
  1194. _bit_width = 256
  1195. _macro = [
  1196. "CPU_CAPABILITY_ZVECTOR",
  1197. "CPU_CAPABILITY=ZVECTOR",
  1198. "HAVE_ZVECTOR_CPU_DEFINITION",
  1199. ]
  1200. _arch_flags = "-mvx -mzvector"
  1201. _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16}
  1202. def __str__(self) -> str:
  1203. return "zvector"
  1204. __hash__: Callable[[VecISA], Any] = VecISA.__hash__
  1205. class InvalidVecISA(VecISA):
  1206. _bit_width = 0
  1207. _macro = [""]
  1208. _arch_flags = ""
  1209. _dtype_nelements = {}
  1210. def __str__(self) -> str:
  1211. return "INVALID_VEC_ISA"
  1212. def __bool__(self) -> bool: # type: ignore[override]
  1213. return False
  1214. __hash__: Callable[[VecISA], Any] = VecISA.__hash__
  1215. def x86_isa_checker() -> List[str]:
  1216. supported_isa: List[str] = []
  1217. def _check_and_append_supported_isa(
  1218. dest: List[str], isa_supported: bool, isa_name: str
  1219. ):
  1220. if isa_supported:
  1221. dest.append(isa_name)
  1222. Arch = platform.machine()
  1223. """
  1224. Arch value is x86_64 on Linux, and the value is AMD64 on Windows.
  1225. """
  1226. if Arch != "x86_64" and Arch != "AMD64":
  1227. return supported_isa
  1228. avx2 = torch.cpu._is_cpu_support_avx2()
  1229. avx512 = torch.cpu._is_cpu_support_avx512()
  1230. _check_and_append_supported_isa(supported_isa, avx2, "avx2")
  1231. _check_and_append_supported_isa(supported_isa, avx512, "avx512")
  1232. return supported_isa
  1233. invalid_vec_isa = InvalidVecISA()
  1234. supported_vec_isa_list = [VecAVX512(), VecAVX2(), VecNEON()]
  1235. # Cache the cpuinfo to avoid I/O overhead. Meanwhile, the cpuinfo content
  1236. # might have too much redundant content that is useless for ISA check. Hence,
  1237. # we only cache some key isa information.
  1238. @functools.lru_cache(None)
  1239. def valid_vec_isa_list() -> List[VecISA]:
  1240. isa_list: List[VecISA] = []
  1241. if sys.platform == "darwin" and platform.processor() == "arm":
  1242. isa_list.append(VecNEON())
  1243. if sys.platform not in ["linux", "win32"]:
  1244. return isa_list
  1245. if platform.machine() == "s390x":
  1246. with open("/proc/cpuinfo") as _cpu_info:
  1247. while True:
  1248. line = _cpu_info.readline()
  1249. if not line:
  1250. break
  1251. # process line
  1252. featuresmatch = re.match(r"^features\s*:\s*(.*)$", line)
  1253. if featuresmatch:
  1254. for group in featuresmatch.groups():
  1255. if re.search(r"[\^ ]+vxe[\$ ]+", group):
  1256. isa_list.append(VecZVECTOR())
  1257. break
  1258. elif platform.machine() == "aarch64":
  1259. isa_list.append(VecNEON())
  1260. elif platform.machine() in ["x86_64", "AMD64"]:
  1261. """
  1262. platform.machine() value is x86_64 on Linux, and the value is AMD64 on Windows.
  1263. """
  1264. _cpu_supported_x86_isa = x86_isa_checker()
  1265. for isa in supported_vec_isa_list:
  1266. if str(isa) in _cpu_supported_x86_isa and isa:
  1267. isa_list.append(isa)
  1268. return isa_list
  1269. def pick_vec_isa() -> VecISA:
  1270. if config.is_fbcode():
  1271. return VecAVX2()
  1272. _valid_vec_isa_list: List[VecISA] = valid_vec_isa_list()
  1273. if not _valid_vec_isa_list:
  1274. return invalid_vec_isa
  1275. # If the simdlen is None, it indicates determine the vectorization length automatically
  1276. if config.cpp.simdlen is None:
  1277. assert _valid_vec_isa_list
  1278. return _valid_vec_isa_list[0]
  1279. for isa in _valid_vec_isa_list:
  1280. if config.cpp.simdlen == isa.bit_width():
  1281. return isa
  1282. return invalid_vec_isa
  1283. def get_compile_only(compile_only: bool = True) -> str:
  1284. return "-c" if compile_only else ""
  1285. def get_shared(shared: bool = True, compile_only: bool = False) -> str:
  1286. if not shared:
  1287. return ""
  1288. if compile_only:
  1289. return "-fPIC"
  1290. if platform.system() == "Darwin" and "clang" in cpp_compiler():
  1291. # This causes undefined symbols to behave the same as linux
  1292. return "-shared -fPIC -undefined dynamic_lookup"
  1293. else:
  1294. return "-shared -fPIC"
  1295. def get_warning_all_flag(warning_all: bool = True) -> str:
  1296. return "-Wall" if warning_all else ""
  1297. def get_glibcxx_abi_build_flags() -> str:
  1298. return "-D_GLIBCXX_USE_CXX11_ABI=" + str(int(torch._C._GLIBCXX_USE_CXX11_ABI))
  1299. def cpp_flags() -> str:
  1300. flags = ["-std=c++17", "-Wno-unused-variable", "-Wno-unknown-pragmas"]
  1301. if is_clang():
  1302. flags.append("-Werror=ignored-optimization-argument")
  1303. return " ".join(flags)
  1304. def cpp_wrapper_flags() -> str:
  1305. return "-D TORCH_INDUCTOR_CPP_WRAPPER"
  1306. def optimization_flags() -> str:
  1307. base_flags = "-O0 -g" if config.aot_inductor.debug_compile else "-O3 -DNDEBUG"
  1308. base_flags += " -ffast-math -fno-finite-math-only"
  1309. if not config.cpp.enable_unsafe_math_opt_flag:
  1310. base_flags += " -fno-unsafe-math-optimizations"
  1311. if not config.cpp.enable_floating_point_contract_flag:
  1312. base_flags += " -ffp-contract=off"
  1313. if config.is_fbcode():
  1314. # FIXME: passing `-fopenmp` adds libgomp.so to the generated shared library's dependencies.
  1315. # This causes `ldopen` to fail in fbcode, because libgomp does not exist in the default paths.
  1316. # We will fix it later by exposing the lib path.
  1317. return base_flags
  1318. if sys.platform == "darwin":
  1319. # Per https://mac.r-project.org/openmp/ right way to pass `openmp` flags to MacOS is via `-Xclang`
  1320. # Also, `-march=native` is unrecognized option on M1
  1321. base_flags += " -Xclang"
  1322. else:
  1323. if platform.machine() == "ppc64le":
  1324. base_flags += " -mcpu=native"
  1325. else:
  1326. base_flags += " -march=native"
  1327. # Internal cannot find libgomp.so
  1328. if not config.is_fbcode():
  1329. base_flags += " -fopenmp"
  1330. return base_flags
  1331. def use_custom_generated_macros() -> str:
  1332. return "-D C10_USING_CUSTOM_GENERATED_MACROS"
  1333. def use_fb_internal_macros() -> str:
  1334. if config.is_fbcode():
  1335. # TODO: this is to avoid FC breakage for fbcode. When using newly
  1336. # generated model.so on an older verion of PyTorch, need to use
  1337. # the v1 version for aoti_torch_create_tensor_from_blob
  1338. create_tensor_from_blob_v1 = "-D AOTI_USE_CREATE_TENSOR_FROM_BLOB_V1"
  1339. openmp_lib = build_paths.openmp_lib()
  1340. preprocessor_flags = " ".join(
  1341. (
  1342. "-D C10_USE_GLOG",
  1343. "-D C10_USE_MINIMAL_GLOG",
  1344. "-D C10_DISABLE_TENSORIMPL_EXTENSIBILITY",
  1345. )
  1346. )
  1347. return f"-Wp,-fopenmp {openmp_lib} {preprocessor_flags} {create_tensor_from_blob_v1}"
  1348. else:
  1349. return ""
  1350. def use_standard_sys_dir_headers() -> str:
  1351. if config.is_fbcode():
  1352. return "-nostdinc"
  1353. else:
  1354. return ""
  1355. @functools.lru_cache(None)
  1356. def is_conda_llvm_openmp_installed() -> bool:
  1357. try:
  1358. command = "conda list llvm-openmp --json"
  1359. output = subprocess.check_output(command.split()).decode("utf8")
  1360. return len(json.loads(output)) > 0
  1361. except subprocess.SubprocessError:
  1362. return False
  1363. @functools.lru_cache(None)
  1364. def homebrew_libomp() -> Tuple[bool, str]:
  1365. try:
  1366. # check if `brew` is installed
  1367. subprocess.check_output(["which", "brew"])
  1368. # get the location of `libomp` if it is installed
  1369. # this is the location that `libomp` **would** be installed
  1370. # see https://github.com/Homebrew/brew/issues/10261#issuecomment-756563567 for details
  1371. libomp_path = (
  1372. subprocess.check_output(["brew", "--prefix", "libomp"])
  1373. .decode("utf8")
  1374. .strip()
  1375. )
  1376. # check if `libomp` is installed
  1377. omp_available = os.path.exists(libomp_path)
  1378. return omp_available, libomp_path
  1379. except subprocess.SubprocessError:
  1380. return False, ""
  1381. def _set_gpu_runtime_env() -> None:
  1382. if (
  1383. config.is_fbcode()
  1384. and torch.version.hip is None
  1385. and "CUDA_HOME" not in os.environ
  1386. and "CUDA_PATH" not in os.environ
  1387. ):
  1388. os.environ["CUDA_HOME"] = build_paths.cuda()
  1389. def _get_python_include_dirs():
  1390. include_dir = Path(sysconfig.get_path("include"))
  1391. # On Darwin Python executable from a framework can return
  1392. # non-existing /Library/Python/... include path, in which case
  1393. # one should use Headers folder from the framework
  1394. if not include_dir.exists() and platform.system() == "Darwin":
  1395. std_lib = Path(sysconfig.get_path("stdlib"))
  1396. include_dir = (std_lib.parent.parent / "Headers").absolute()
  1397. if not (include_dir / "Python.h").exists():
  1398. warnings.warn(f"Can't find Python.h in {str(include_dir)}")
  1399. return [str(include_dir)]
  1400. def _transform_cuda_paths(lpaths):
  1401. # This handles two cases:
  1402. # 1. Meta internal cuda-12 where libs are in lib/cuda-12 and lib/cuda-12/stubs
  1403. # 2. Linux machines may have CUDA installed under either lib64/ or lib/
  1404. for i, path in enumerate(lpaths):
  1405. if (
  1406. "CUDA_HOME" in os.environ
  1407. and path.startswith(os.environ["CUDA_HOME"])
  1408. and not os.path.exists(f"{path}/libcudart_static.a")
  1409. ):
  1410. for root, dirs, files in os.walk(path):
  1411. if "libcudart_static.a" in files:
  1412. lpaths[i] = os.path.join(path, root)
  1413. lpaths.append(os.path.join(lpaths[i], "stubs"))
  1414. break
  1415. def get_include_and_linking_paths(
  1416. include_pytorch: bool = False,
  1417. vec_isa: VecISA = invalid_vec_isa,
  1418. cuda: bool = False,
  1419. aot_mode: bool = False,
  1420. ) -> Tuple[List[str], str, str, str, str]:
  1421. _set_gpu_runtime_env()
  1422. from torch.utils import cpp_extension
  1423. # Remove below in the further
  1424. # macros = "-D {}".format(vec_isa.build_macro()) if vec_isa != invalid_vec_isa else ""
  1425. macros = ""
  1426. if vec_isa != invalid_vec_isa:
  1427. for x in vec_isa.build_macro():
  1428. macros_def = f"-D {x} "
  1429. macros += macros_def
  1430. build_arch_flags = ""
  1431. if sys.platform == "linux" and (
  1432. include_pytorch
  1433. or vec_isa != invalid_vec_isa
  1434. or cuda
  1435. or config.cpp.enable_kernel_profile
  1436. ):
  1437. # Note - We include pytorch only on linux right now. There is more work
  1438. # to do to enable OMP build on darwin where PyTorch is built with IOMP
  1439. # and we need a way to link to what PyTorch links.
  1440. ipaths = cpp_extension.include_paths(cuda) + _get_python_include_dirs()
  1441. lpaths = cpp_extension.library_paths(cuda) + [
  1442. sysconfig.get_config_var("LIBDIR")
  1443. ]
  1444. libs = []
  1445. # No need to manually specify libraries in fbcode.
  1446. if not config.is_fbcode():
  1447. libs += ["torch", "torch_cpu"]
  1448. libs += ["gomp"]
  1449. if not aot_mode:
  1450. libs += ["torch_python"]
  1451. else:
  1452. # internal remote execution is able to find omp, but not gomp
  1453. libs += ["omp"]
  1454. if aot_mode:
  1455. ipaths += [os.path.dirname(cpp_prefix_path())]
  1456. if cuda and torch.version.hip is None:
  1457. _transform_cuda_paths(lpaths)
  1458. if macros:
  1459. if config.is_fbcode() and vec_isa != invalid_vec_isa:
  1460. cap = str(vec_isa).upper()
  1461. macros = " ".join(
  1462. [
  1463. vec_isa.build_arch_flags(),
  1464. f"-D CPU_CAPABILITY={cap}",
  1465. f"-D CPU_CAPABILITY_{cap}",
  1466. f"-D HAVE_{cap}_CPU_DEFINITION",
  1467. ]
  1468. )
  1469. if cuda:
  1470. if macros is None:
  1471. macros = ""
  1472. macros += " -D USE_ROCM" if torch.version.hip else " -D USE_CUDA"
  1473. if cuda:
  1474. if torch.version.hip is not None:
  1475. if config.is_fbcode():
  1476. libs += ["amdhip64"]
  1477. else:
  1478. libs += ["c10_hip", "torch_hip"]
  1479. macros += " -D __HIP_PLATFORM_AMD__"
  1480. else:
  1481. if config.is_fbcode():
  1482. libs += ["cuda"]
  1483. else:
  1484. libs += ["c10_cuda", "cuda", "torch_cuda"]
  1485. build_arch_flags = vec_isa.build_arch_flags()
  1486. else:
  1487. # Note - this is effectively a header only inclusion. Usage of some header files may result in
  1488. # symbol not found, if those header files require a library.
  1489. # For those cases, include the lpath and libs command as we do for pytorch above.
  1490. # This approach allows us to only pay for what we use.
  1491. ipaths = cpp_extension.include_paths(cuda) + _get_python_include_dirs()
  1492. if aot_mode:
  1493. ipaths += [os.path.dirname(cpp_prefix_path())]
  1494. lpaths = []
  1495. if sys.platform == "darwin":
  1496. # only Apple builtin compilers (Apple Clang++) require openmp
  1497. omp_available = not is_apple_clang()
  1498. # check the `OMP_PREFIX` environment first
  1499. if os.getenv("OMP_PREFIX") is not None:
  1500. header_path = os.path.join(os.getenv("OMP_PREFIX"), "include", "omp.h") # type: ignore[arg-type]
  1501. valid_env = os.path.exists(header_path)
  1502. if valid_env:
  1503. ipaths.append(os.path.join(os.getenv("OMP_PREFIX"), "include")) # type: ignore[arg-type]
  1504. lpaths.append(os.path.join(os.getenv("OMP_PREFIX"), "lib")) # type: ignore[arg-type]
  1505. else:
  1506. warnings.warn("environment variable `OMP_PREFIX` is invalid.")
  1507. omp_available = omp_available or valid_env
  1508. libs = [] if omp_available else ["omp"]
  1509. # prefer to use openmp from `conda install llvm-openmp`
  1510. if not omp_available and os.getenv("CONDA_PREFIX") is not None:
  1511. omp_available = is_conda_llvm_openmp_installed()
  1512. if omp_available:
  1513. conda_lib_path = os.path.join(os.getenv("CONDA_PREFIX"), "lib") # type: ignore[arg-type]
  1514. ipaths.append(os.path.join(os.getenv("CONDA_PREFIX"), "include")) # type: ignore[arg-type]
  1515. lpaths.append(conda_lib_path)
  1516. # Prefer Intel OpenMP on x86 machine
  1517. if os.uname().machine == "x86_64" and os.path.exists(
  1518. os.path.join(conda_lib_path, "libiomp5.dylib")
  1519. ):
  1520. libs = ["iomp5"]
  1521. # next, try to use openmp from `brew install libomp`
  1522. if not omp_available:
  1523. omp_available, libomp_path = homebrew_libomp()
  1524. if omp_available:
  1525. ipaths.append(os.path.join(libomp_path, "include"))
  1526. lpaths.append(os.path.join(libomp_path, "lib"))
  1527. # if openmp is still not available, we let the compiler to have a try,
  1528. # and raise error together with instructions at compilation error later
  1529. else:
  1530. libs = ["omp"] if config.is_fbcode() else ["gomp"]
  1531. # For AOT mode, the produced library relies on torch cpu to set grad mode
  1532. # like aoti_torch_grad_mode_set_enabled
  1533. if aot_mode and sys.platform == "linux" and not config.is_fbcode():
  1534. libs += ["torch", "torch_cpu"]
  1535. # Unconditionally import c10 for non-abi-compatible mode to use TORCH_CHECK - See PyTorch #108690
  1536. if not config.abi_compatible:
  1537. libs += ["c10"]
  1538. lpaths += [cpp_extension.TORCH_LIB_PATH]
  1539. # third party libs
  1540. if config.is_fbcode():
  1541. # Note that the order of include paths do matter, as a result
  1542. # we need to have several branches interleaved here
  1543. if torch.version.hip is None:
  1544. ipaths.append(build_paths.sleef())
  1545. ipaths.append(build_paths.openmp())
  1546. ipaths.append(build_paths.python())
  1547. if torch.version.hip is not None:
  1548. ipaths.append(build_paths.clang_include())
  1549. ipaths.append(build_paths.gcc_include())
  1550. ipaths.append(build_paths.gcc_install_tools_include())
  1551. else:
  1552. ipaths.append(build_paths.cc_include())
  1553. ipaths.append(build_paths.libgcc())
  1554. ipaths.append(build_paths.libgcc_arch())
  1555. ipaths.append(build_paths.libgcc_backward())
  1556. ipaths.append(build_paths.glibc())
  1557. ipaths.append(build_paths.linux_kernel())
  1558. if torch.version.hip is not None:
  1559. ipaths.append(build_paths.rocm())
  1560. else:
  1561. ipaths.append(os.path.join(build_paths.cuda(), "include"))
  1562. # We also need to bundle includes with absolute paths into a remote directory
  1563. # (later on, we copy the include paths from cpp_extensions into our remote dir)
  1564. ipaths.append("include")
  1565. static_link_libs = []
  1566. if aot_mode and cuda and config.is_fbcode():
  1567. # For Meta internal cuda-12, it is recommended to static link cudart
  1568. if torch.version.hip is None:
  1569. static_link_libs = ["-Wl,-Bstatic", "-lcudart_static", "-Wl,-Bdynamic"]
  1570. lpaths_str = " ".join(["-L" + p for p in lpaths])
  1571. libs_str = " ".join(static_link_libs + ["-l" + p for p in libs])
  1572. return ipaths, lpaths_str, libs_str, macros, build_arch_flags
  1573. def cpp_compile_command(
  1574. input: Union[str, List[str]],
  1575. output: str,
  1576. warning_all: bool = True,
  1577. shared: bool = True,
  1578. include_pytorch: bool = False,
  1579. vec_isa: VecISA = invalid_vec_isa,
  1580. cuda: bool = False,
  1581. aot_mode: bool = False,
  1582. compile_only: bool = False,
  1583. use_absolute_path: bool = False,
  1584. use_mmap_weights: bool = False,
  1585. extra_flags: Sequence[str] = (),
  1586. ) -> str:
  1587. ipaths, lpaths, libs, macros, build_arch_flags = get_include_and_linking_paths(
  1588. include_pytorch, vec_isa, cuda, aot_mode
  1589. )
  1590. if isinstance(input, str):
  1591. input = [input]
  1592. ipaths_str = " ".join(["-I" + p for p in ipaths])
  1593. clang_flags = ""
  1594. if config.is_fbcode():
  1595. if aot_mode and not use_absolute_path:
  1596. inp_name = input
  1597. out_name = output
  1598. linker_script = _LINKER_SCRIPT
  1599. else:
  1600. # We need to copy any absolute-path torch includes
  1601. inp_name = [os.path.basename(i) for i in input]
  1602. out_name = os.path.basename(output)
  1603. linker_script = os.path.basename(_LINKER_SCRIPT)
  1604. assert is_clang()
  1605. # Use clang runtime instead of libgcc
  1606. clang_flags += " --rtlib=compiler-rt"
  1607. clang_flags += " -fuse-ld=lld"
  1608. clang_flags += f" -Wl,--script={linker_script}"
  1609. linker_paths = "-B" + build_paths.glibc_lib()
  1610. linker_paths += " -L" + build_paths.glibc_lib()
  1611. else:
  1612. inp_name = input
  1613. out_name = output
  1614. linker_paths = "" # let the compiler pick
  1615. if compile_only:
  1616. libs, lpaths = "", ""
  1617. inp_name_str = " ".join(inp_name)
  1618. if use_mmap_weights:
  1619. macros += " -D USE_MMAP_SELF"
  1620. return re.sub(
  1621. r"[ \n]+",
  1622. " ",
  1623. f"""
  1624. {cpp_compiler()} {inp_name_str} {get_shared(shared, compile_only)}
  1625. {get_warning_all_flag(warning_all)} {cpp_flags()}
  1626. {get_glibcxx_abi_build_flags()}
  1627. {ipaths_str} {lpaths} {libs} {build_arch_flags}
  1628. {macros} {linker_paths} {clang_flags}
  1629. {optimization_flags()} {cpp_wrapper_flags()}
  1630. {use_custom_generated_macros()}
  1631. {use_fb_internal_macros()}
  1632. {use_standard_sys_dir_headers()}
  1633. {get_compile_only(compile_only)}
  1634. {' '.join(extra_flags)}
  1635. -o {out_name}
  1636. """,
  1637. ).strip()
  1638. def run_command_and_check(cmd: str):
  1639. cmd = shlex.split(cmd)
  1640. try:
  1641. subprocess.check_call(cmd)
  1642. except subprocess.CalledProcessError as e:
  1643. raise exc.CppCompileError(cmd, e.output) from e
  1644. @functools.lru_cache(None)
  1645. def split_aot_inductor_output_path(path: str) -> Tuple[str, str]:
  1646. """Returns the path where the AOT Inductor compiled kernels are stored."""
  1647. if path.endswith(".so"):
  1648. return os.path.split(path)
  1649. else:
  1650. return path, ""
  1651. @clear_on_fresh_inductor_cache
  1652. class CudaKernelParamCache:
  1653. cache: Dict[str, Dict[str, str]] = dict()
  1654. cache_clear = staticmethod(cache.clear)
  1655. @classmethod
  1656. def set(cls, key: str, params: Dict[str, str], cubin: str) -> None:
  1657. bin_type = "cubin" if torch.version.hip is None else "hsaco"
  1658. _, path = write(
  1659. cubin,
  1660. bin_type,
  1661. hash_type=bin_type,
  1662. specified_dir=split_aot_inductor_output_path(
  1663. config.aot_inductor.output_path
  1664. )[0],
  1665. )
  1666. params[get_cpp_wrapper_cubin_path_name()] = path
  1667. cls.cache[key] = params
  1668. @classmethod
  1669. def get(cls, key: str) -> Optional[Dict[str, str]]:
  1670. return cls.cache.get(key, None)
  1671. @classmethod
  1672. def get_keys(cls):
  1673. return cls.cache.keys()
  1674. class AotCodeCompiler:
  1675. @classmethod
  1676. def compile(
  1677. cls,
  1678. graph: GraphLowering,
  1679. source_code: str,
  1680. serialized_extern_kernel_nodes: Optional[str],
  1681. cuda: bool,
  1682. ) -> str:
  1683. picked_vec_isa = pick_vec_isa()
  1684. cpp_command = repr(
  1685. cpp_compile_command(
  1686. "i",
  1687. "o",
  1688. vec_isa=picked_vec_isa,
  1689. cuda=cuda,
  1690. aot_mode=graph.aot_mode,
  1691. )
  1692. )
  1693. fbcode_aot_cpu_re = False
  1694. use_absolute_path = False
  1695. if config.is_fbcode():
  1696. ld_command = build_paths.ld()
  1697. if not cuda and graph.aot_mode: # Meta internal AOTInductor CPU
  1698. objcopy_command = build_paths.objcopy_fallback()
  1699. fbcode_aot_cpu_re = True
  1700. use_absolute_path = True
  1701. else:
  1702. objcopy_command = build_paths.objcopy()
  1703. else:
  1704. ld_command = "ld"
  1705. objcopy_command = "objcopy"
  1706. (
  1707. specified_output_path,
  1708. specified_so_name,
  1709. ) = split_aot_inductor_output_path(config.aot_inductor.output_path)
  1710. key, input_path = write(
  1711. source_code,
  1712. "cpp",
  1713. extra=cpp_command,
  1714. specified_dir=specified_output_path,
  1715. )
  1716. output_code_log.info("Output code written to: %s", input_path)
  1717. trace_structured(
  1718. "graph_dump",
  1719. lambda: {
  1720. "name": "inductor_aot_code",
  1721. "type": "cpp",
  1722. "filename": input_path,
  1723. },
  1724. payload_fn=lambda: source_code,
  1725. )
  1726. def _compile_consts_linux(consts: bytes) -> str:
  1727. _, consts_path = write(
  1728. consts,
  1729. "bin",
  1730. specified_dir=specified_output_path,
  1731. )
  1732. consts_o = os.path.splitext(consts_path)[0] + ".o"
  1733. if fbcode_aot_cpu_re:
  1734. cmd = f"{ld_command} -r -b binary -o {os.path.basename(consts_o)} {os.path.basename(consts_path)}"
  1735. compile_file(consts_path, consts_o, cmd.split())
  1736. os.chmod(consts_o, 0o644)
  1737. else:
  1738. cmd = f"{ld_command} -r -b binary -o {consts_o} {consts_path}"
  1739. run_command_and_check(cmd)
  1740. log.debug("aot constant binary command: %s", cmd)
  1741. if graph.mutated_buffers & set(graph.constants.keys()):
  1742. # .data section is between .text and .bss. When the size of .data is large,
  1743. # during the linking, the relocation of .text against .bss may overflow.
  1744. # Rename it to .ldata so that it won't be in between the .text and .bss section
  1745. if len(consts) > 2_000_000_000:
  1746. raise ValueError(
  1747. "Models with buffer mutation included doesn't support constants greater than 2GB!"
  1748. )
  1749. rename_data = " .data=.ldata"
  1750. else:
  1751. # if no buffer mutation is needed, we could instead set the data region
  1752. # as read-only (i.e. .lrodata) which could accomodate larger size of data
  1753. # to be linked.
  1754. rename_data = " .data=.lrodata,alloc,load,readonly,data,contents"
  1755. assert (
  1756. ALIGN_BYTES & (ALIGN_BYTES - 1)
  1757. ) == 0 and ALIGN_BYTES >= 64, "must be power of 2 and >= 64"
  1758. cmd = (
  1759. f"{objcopy_command} --rename-section"
  1760. f"{rename_data}"
  1761. f" --set-section-alignment .data={ALIGN_BYTES}" # following the gAlignment of CPU in c10/core/alignment.h
  1762. f" {consts_o} {consts_o}"
  1763. )
  1764. log.debug("aot constant rename section command: %s", cmd)
  1765. run_command_and_check(cmd)
  1766. cmd = f"rm {consts_path}"
  1767. log.debug("aot constant bin removal command: %s", cmd)
  1768. run_command_and_check(cmd)
  1769. if fbcode_aot_cpu_re:
  1770. body = re.sub(r"[\W]", "_", os.path.basename(consts_path))
  1771. else:
  1772. body = re.sub(r"[\W]", "_", consts_path)
  1773. symbol_list = []
  1774. symbol_list.append(
  1775. f"{objcopy_command} --redefine-sym _binary_{body}_start=_binary_constants_bin_start {consts_o}"
  1776. )
  1777. symbol_list.append(
  1778. f"{objcopy_command} --redefine-sym _binary_{body}_size=_binary_constants_bin_size {consts_o}"
  1779. )
  1780. symbol_list.append(
  1781. f"{objcopy_command} --redefine-sym _binary_{body}_end=_binary_constants_bin_end {consts_o}"
  1782. )
  1783. log.debug("aot constant binary redefine symbol: %s", " ".join(symbol_list))
  1784. for cmd in symbol_list:
  1785. run_command_and_check(cmd)
  1786. return consts_o
  1787. def _compile_consts_darwin(consts: bytes) -> str:
  1788. if config.aot_inductor.debug_dump_consts_bin:
  1789. _, _binary_constants_path = write(
  1790. consts,
  1791. "bin",
  1792. specified_dir=specified_output_path,
  1793. )
  1794. log.debug("binary constants path: %s", _binary_constants_path)
  1795. is_large_consts = len(consts) > 1024
  1796. consts_asm = "\t.section\t__DATA,__data\n"
  1797. consts_asm += "\t.globl\t__binary_constants_bin_start\n"
  1798. consts_asm += "__binary_constants_bin_start:\n"
  1799. if not is_large_consts:
  1800. for c in consts:
  1801. consts_asm += f"\t.byte {c}\n"
  1802. # Add one element even if constants are empty
  1803. # Otherwise assembler will not put them in data section
  1804. if not consts:
  1805. consts_asm += "\t.space 1\n"
  1806. else:
  1807. consts_asm += "\t.quad 0x1234567899abcdef\n"
  1808. consts_asm += f"\t.space {len(consts) - 8}\n"
  1809. consts_asm += ".globl\t__binary_constants_bin_end\n"
  1810. consts_asm += "__binary_constants_bin_end:\n"
  1811. _, consts_path = write(
  1812. consts_asm,
  1813. "S",
  1814. specified_dir=specified_output_path,
  1815. )
  1816. consts_o = os.path.splitext(consts_path)[0] + ".o"
  1817. cmd = f"{cpp_compiler()} -c -o {consts_o} {consts_path}"
  1818. run_command_and_check(cmd)
  1819. if is_large_consts:
  1820. with open(consts_o, "r+b") as f:
  1821. f.seek(0)
  1822. hdr = f.read(1024)
  1823. # Search for magic number and write the actual data over it
  1824. start_idx = hdr.find(b"\xef\xcd\xab\x99\x78\x56\x34\x12")
  1825. assert start_idx != -1
  1826. f.seek(start_idx)
  1827. pos = 0
  1828. while pos < len(consts):
  1829. rc = f.write(consts[pos:])
  1830. pos += rc
  1831. return consts_o
  1832. from filelock import FileLock
  1833. lock_dir = get_lock_dir()
  1834. lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
  1835. with lock:
  1836. # Currently, this only support serializing extern nodes in fbcode
  1837. # Eventually, we should also have a serializer for OSS.
  1838. if config.is_fbcode() and serialized_extern_kernel_nodes:
  1839. output_json = os.path.splitext(input_path)[0] + ".json"
  1840. with open(output_json, "w") as f:
  1841. f.write(serialized_extern_kernel_nodes)
  1842. output_so = (
  1843. config.aot_inductor.output_path
  1844. if specified_so_name
  1845. else os.path.splitext(input_path)[0] + ".so"
  1846. )
  1847. output_o = os.path.splitext(input_path)[0] + ".o"
  1848. consts_size = sum(
  1849. torch.ops.mkldnn._nbytes(tensor)
  1850. if tensor.is_mkldnn
  1851. else tensor.untyped_storage().nbytes()
  1852. for (name, tensor) in graph.constants.items()
  1853. if name not in graph.folded_constants
  1854. )
  1855. # TODO: Fix mmap weights with cuda
  1856. use_mmap_weights = not config.is_fbcode() and consts_size > 2_000_000_000
  1857. if config.aot_inductor.force_mmap_weights:
  1858. use_mmap_weights = True
  1859. compile_cmd = cpp_compile_command(
  1860. input=input_path,
  1861. output=output_o,
  1862. vec_isa=picked_vec_isa,
  1863. cuda=cuda,
  1864. aot_mode=graph.aot_mode,
  1865. compile_only=True,
  1866. use_absolute_path=use_absolute_path,
  1867. use_mmap_weights=use_mmap_weights,
  1868. )
  1869. log.debug("aot compilation command: %s", compile_cmd)
  1870. if fbcode_aot_cpu_re:
  1871. compile_file(input_path, output_o, compile_cmd.split())
  1872. os.chmod(output_o, 0o644)
  1873. else:
  1874. run_command_and_check(compile_cmd)
  1875. def _to_bytes(t: torch.Tensor, all_cuda: bool) -> bytes:
  1876. def _pad_to_alignment(raw_bytes):
  1877. padded_bytes = raw_bytes.ljust(
  1878. (len(raw_bytes) + ALIGN_BYTES - 1) // ALIGN_BYTES * ALIGN_BYTES,
  1879. b"\x00",
  1880. )
  1881. return padded_bytes
  1882. # This serializes the tensor's untyped_storage to bytes by accessing
  1883. # the raw data of the underlying structure.
  1884. import ctypes
  1885. if t.numel() == 0:
  1886. return b""
  1887. if t.is_mkldnn:
  1888. data_ptr = torch.ops.mkldnn.data_ptr(t)
  1889. nbytes = torch.ops.mkldnn._nbytes(t)
  1890. else:
  1891. t_cpu = t.untyped_storage().cpu()
  1892. data_ptr = t_cpu.data_ptr()
  1893. nbytes = t_cpu.nbytes()
  1894. raw_array = ctypes.cast(
  1895. data_ptr,
  1896. ctypes.POINTER(ctypes.c_ubyte * nbytes),
  1897. )
  1898. raw_bytes = bytes(raw_array.contents)
  1899. return raw_bytes if all_cuda else _pad_to_alignment(raw_bytes)
  1900. all_cuda = all(
  1901. graph.get_original_value_of_constant(name).is_cuda
  1902. for name in graph.constants.keys()
  1903. if name not in graph.folded_constants
  1904. )
  1905. serialized_weights = b"".join(
  1906. _to_bytes(graph.get_original_value_of_constant(name), all_cuda)
  1907. for name in graph.constants.keys()
  1908. if name not in graph.folded_constants
  1909. )
  1910. if not use_mmap_weights:
  1911. aot_constants = serialized_weights
  1912. magic_number = 0
  1913. else:
  1914. magic_number = cast(
  1915. int, torch.randint(0, torch.iinfo(torch.int64).max, (1,)).item()
  1916. )
  1917. aot_constants = struct.pack("qq", consts_size + 8, magic_number)
  1918. consts_o = {
  1919. "linux": _compile_consts_linux,
  1920. "darwin": _compile_consts_darwin,
  1921. }[sys.platform](aot_constants)
  1922. link_cmd = cpp_compile_command(
  1923. input=[output_o, consts_o],
  1924. output=output_so,
  1925. vec_isa=picked_vec_isa,
  1926. cuda=cuda,
  1927. aot_mode=graph.aot_mode,
  1928. use_absolute_path=use_absolute_path,
  1929. )
  1930. log.debug("aot linkage command: %s", link_cmd)
  1931. if fbcode_aot_cpu_re:
  1932. compile_file([output_o, consts_o], output_so, link_cmd.split())
  1933. os.chmod(output_so, 0o755)
  1934. else:
  1935. run_command_and_check(link_cmd)
  1936. if use_mmap_weights:
  1937. with open(output_so, "a+b") as f_so:
  1938. so_size = f_so.tell()
  1939. # Page align the weights
  1940. f_so.write(b" " * (16384 - so_size % 16384))
  1941. f_so.write(serialized_weights)
  1942. f_so.write(struct.pack("q", magic_number))
  1943. # Append cmds to the end of codegen-ed wrapper file
  1944. with open(input_path, "a") as f:
  1945. f.write("\n")
  1946. f.write(f"// Compile cmd\n// {compile_cmd}\n")
  1947. f.write(f"// Link cmd\n// {link_cmd}\n")
  1948. return output_so
  1949. # Putting this fn in cpp.py (unfortunately) causes a deadlock, which is why it's in codecache.py.
  1950. # Why? importing from cpp.py invokes codecache.pick_vec_isa(), which takes out a lock.
  1951. # Cycle goes:
  1952. # - CppCodeCache.load()
  1953. # - pick_vec_isa()
  1954. # - valid_vec_isa_list()
  1955. # - VecISA.__bool__() <-- takes out a lock
  1956. # - compile_file() <-- imports cpp_prefix_path from cpp, which causes us to try to take out the same lock.
  1957. @clear_on_fresh_inductor_cache
  1958. @functools.lru_cache
  1959. def cpp_prefix_path() -> str:
  1960. path = Path(__file__).parent / "codegen/cpp_prefix.h"
  1961. with path.open() as f:
  1962. content = f.read()
  1963. _, filename = write(
  1964. content,
  1965. "h",
  1966. )
  1967. return filename
  1968. def cpp_prefix() -> str:
  1969. filename = cpp_prefix_path()
  1970. if config.is_fbcode():
  1971. # We need relative paths, since we bundle up
  1972. # everything that we compile into a folder for remote compilation.
  1973. return f'#include "{os.path.basename(filename)}"'
  1974. else:
  1975. return f'#include "{filename}"'
  1976. # Given a path to an input cpp file and an output path,
  1977. # Attempts to compile the file, storing the output in "output_path"
  1978. @dynamo_timed
  1979. def compile_file(
  1980. input_path: Union[str, List[str]], output_path: str, cmd: List[str]
  1981. ) -> None:
  1982. input_paths = [input_path] if isinstance(input_path, str) else input_path
  1983. input_files = [
  1984. os.path.basename(ip) if config.is_fbcode() else ip for ip in input_paths
  1985. ]
  1986. try:
  1987. if config.is_fbcode():
  1988. # Need to copy our header into the same folder as the sourcecode.
  1989. header_path = cpp_prefix_path()
  1990. header_name = os.path.basename(header_path)
  1991. output_name = os.path.basename(output_path)
  1992. # When we build remotely, we need to make sure to carefully copy any files
  1993. # that are required during the compilation process into our build directly.
  1994. # This is where all of the ATen/c10/Torch includes come from.
  1995. torch_includes_path = os.path.join(_TORCH_PATH, "include")
  1996. with tempfile.TemporaryDirectory() as tmp_dir:
  1997. # Copy everything to tmp compilation folder
  1998. shutil.copy(header_path, os.path.join(tmp_dir, header_name))
  1999. shutil.copy(_LINKER_SCRIPT, os.path.join(tmp_dir, "script.ld"))
  2000. for p, f in zip(input_paths, input_files):
  2001. shutil.copy(p, os.path.join(tmp_dir, f))
  2002. dest_include_path = os.path.join(tmp_dir, "include")
  2003. shutil.copytree(torch_includes_path, dest_include_path)
  2004. # Run the build
  2005. output_file_path = _run_build_command(cmd, tmp_dir, output_name)
  2006. # Copy output from the build
  2007. if os.path.exists(output_path):
  2008. os.remove(output_path)
  2009. shutil.copy(output_file_path, output_path)
  2010. else:
  2011. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  2012. except subprocess.CalledProcessError as e:
  2013. output = e.output.decode("utf-8")
  2014. openmp_problem = "'omp.h' file not found" in output or "libomp" in output
  2015. if openmp_problem and sys.platform == "darwin":
  2016. instruction = (
  2017. "\n\nOpenMP support not found. Please try one of the following solutions:\n"
  2018. "(1) Set the `CXX` environment variable to a compiler other than Apple clang++/g++ "
  2019. "that has builtin OpenMP support;\n"
  2020. "(2) install OpenMP via conda: `conda install llvm-openmp`;\n"
  2021. "(3) install libomp via brew: `brew install libomp`;\n"
  2022. "(4) manually setup OpenMP and set the `OMP_PREFIX` environment variable to point to a path"
  2023. " with `include/omp.h` under it."
  2024. )
  2025. output += instruction
  2026. raise exc.CppCompileError(cmd, output) from e
  2027. _libgomp: Optional[CDLL] = None
  2028. def custom_op_wrapper(op: str, *args):
  2029. # This function will be called from generated cpp wrapper code in the JIT mode.
  2030. # Because tensors will be passed in as AtenTensorHandle, we need to explicitly convert them.
  2031. def convert_arg(arg):
  2032. if str(type(arg)) == "<class 'PyCapsule'>":
  2033. # No easy way to do isinstance check on PyCapsule
  2034. return torch._C._aoti.alloc_tensor_by_stealing_from_void_ptr(arg)
  2035. elif isinstance(arg, (list, tuple)):
  2036. return type(arg)(convert_arg(a) for a in arg)
  2037. else:
  2038. return arg
  2039. converted_args = [convert_arg(arg) for arg in args]
  2040. assert op.startswith("torch.ops."), (
  2041. op + " can not be called through custom_op_wrapper"
  2042. )
  2043. func = None
  2044. for i, s in enumerate(op.split(".")):
  2045. if i == 0:
  2046. func = importlib.import_module(s)
  2047. func = getattr(func, s)
  2048. assert callable(func), op + " can not be loaded through custom_op_wrapper"
  2049. result = func(*converted_args)
  2050. if isinstance(result, (list, tuple)):
  2051. for r in result:
  2052. assert isinstance(r, torch.Tensor), op + " returns a list of non-tensors"
  2053. return torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(result) # type: ignore[arg-type]
  2054. else:
  2055. assert isinstance(result, torch.Tensor), op + " returns a non-tensor"
  2056. return torch._C._aoti.unsafe_alloc_void_ptr_from_tensor(result)
  2057. @clear_on_fresh_inductor_cache
  2058. class CppCodeCache:
  2059. cache: Dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2060. cache_clear = staticmethod(cache.clear)
  2061. cpp_compile_command_flags: Dict[str, Any] = {}
  2062. @staticmethod
  2063. def _load_library_inner(path: str, key: str) -> Union[CDLL, ModuleType]:
  2064. return cdll.LoadLibrary(path)
  2065. @classmethod
  2066. def _load_library(cls, path: str, key: str) -> Union[CDLL, ModuleType]:
  2067. try:
  2068. result = cls._load_library_inner(path, key)
  2069. result.key = key # type: ignore[union-attr]
  2070. return result
  2071. except (ImportError, OSError) as e:
  2072. if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"):
  2073. # hacky workaround for fbcode/buck
  2074. global _libgomp
  2075. _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1")
  2076. result = cls._load_library_inner(path, key)
  2077. result.key = key # type: ignore[union-attr]
  2078. return result
  2079. if "failed to map segment from shared object" in str(e):
  2080. raise OSError(
  2081. f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder "
  2082. "is mounted with noexec (e.g., by default Docker mounts tmp file systems "
  2083. f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another "
  2084. "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable."
  2085. ) from e
  2086. raise
  2087. @classmethod
  2088. def load_async(cls, source_code: str, cuda=False, submit_fn=None, extra_flags=()):
  2089. compile_command = {
  2090. **cls.cpp_compile_command_flags,
  2091. "cuda": cuda,
  2092. "vec_isa": pick_vec_isa(),
  2093. "extra_flags": extra_flags,
  2094. }
  2095. _set_gpu_runtime_env() # cpp_extension consults the env
  2096. from torch._inductor.cpp_builder import CppBuilder, CppTorchCudaOptions
  2097. dummy_builder = CppBuilder(
  2098. name="o", sources="i", BuildOption=CppTorchCudaOptions(**compile_command)
  2099. )
  2100. # write function will calc source_code hash, the same source code with different
  2101. # ISA level should be generate different hash.
  2102. # So we need get a command_line which contains isa related parameter as a part of hash key.
  2103. # And then pass the command_line to below write function as extra parameter to
  2104. # guarantee the source code hash contains ISA difference.
  2105. dummy_cmd = repr(dummy_builder.get_command_line())
  2106. key, input_path = write(source_code, "cpp", extra=dummy_cmd)
  2107. if key not in cls.cache:
  2108. from filelock import FileLock
  2109. lock_path = os.path.join(get_lock_dir(), key + ".lock")
  2110. output_path = input_path[:-3] + "so"
  2111. future: Optional[Future[Any]] = None
  2112. lib = None
  2113. worker_fn = functools.partial(
  2114. _worker_compile_cpp,
  2115. lock_path,
  2116. input_path,
  2117. output_path,
  2118. cpp_compile_command(
  2119. input=input_path, output=output_path, **compile_command
  2120. ),
  2121. )
  2122. def load_fn():
  2123. nonlocal lib
  2124. if lib is None:
  2125. if future is not None:
  2126. future.result()
  2127. result = worker_fn()
  2128. assert result is None
  2129. lib = cls._load_library(output_path, key)
  2130. assert lib is not None
  2131. return lib
  2132. if submit_fn is not None:
  2133. with FileLock(lock_path, timeout=LOCK_TIMEOUT):
  2134. if not os.path.exists(output_path):
  2135. future = submit_fn(worker_fn)
  2136. cls.cache[key] = load_fn
  2137. return cls.cache[key]
  2138. @classmethod
  2139. def load(cls, source_code: str, cuda: bool = False):
  2140. return cls.load_async(source_code, cuda)()
  2141. def _worker_compile_cpp(lock_path, input_path, output_path, cmd):
  2142. from filelock import FileLock
  2143. with FileLock(lock_path, timeout=LOCK_TIMEOUT):
  2144. if not os.path.exists(output_path):
  2145. compile_file(input_path, output_path, shlex.split(cmd))
  2146. # Customized Python binding for cpp kernels
  2147. @clear_on_fresh_inductor_cache
  2148. class CppPythonBindingsCodeCache(CppCodeCache):
  2149. cache: Dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2150. cache_clear = staticmethod(cache.clear)
  2151. cpp_compile_command_flags = {
  2152. # kernels have no dependency on libtorch
  2153. "include_pytorch": False,
  2154. "shared": True,
  2155. }
  2156. entry_function = "kernel"
  2157. call_entry_function = "kernel(%s);Py_RETURN_NONE;"
  2158. extra_parse_arg = ""
  2159. suffix_template = textwrap.dedent(
  2160. """
  2161. // Python bindings to call %s():
  2162. #define PY_SSIZE_T_CLEAN
  2163. #include <Python.h>
  2164. #include <sstream>
  2165. #include <cstdlib>
  2166. #ifndef _MSC_VER
  2167. #if __cplusplus < 202002L
  2168. // C++20 earlier code
  2169. // https://en.cppreference.com/w/cpp/language/attributes/likely
  2170. #define likely(x) __builtin_expect(!!(x), 1)
  2171. #define unlikely(x) __builtin_expect(!!(x), 0)
  2172. #endif
  2173. #endif
  2174. // This is defined in guards.cpp so we don't need to import PyTorch headers that are slooow.
  2175. // We manually link it below to workaround issues with fbcode build.
  2176. static void* (*_torchinductor_pyobject_tensor_data_ptr)(PyObject* obj);
  2177. template <typename T> static inline T parse_arg(PyObject* args, size_t n) {
  2178. static_assert(std::is_pointer<T>::value, "arg type must be pointer or long");
  2179. return static_cast<T>(_torchinductor_pyobject_tensor_data_ptr(PyTuple_GET_ITEM(args, n)));
  2180. }
  2181. template <> inline long parse_arg<long>(PyObject* args, size_t n) {
  2182. auto result = PyLong_AsSsize_t(PyTuple_GET_ITEM(args, n));
  2183. if(unlikely(result == -1 && PyErr_Occurred()))
  2184. throw std::runtime_error("expected int arg");
  2185. return result;
  2186. }
  2187. template <> inline uintptr_t parse_arg<uintptr_t>(PyObject* args, size_t n) {
  2188. auto result = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, n));
  2189. if(unlikely(result == reinterpret_cast<void*>(-1) && PyErr_Occurred()))
  2190. throw std::runtime_error("expected int arg");
  2191. return reinterpret_cast<uintptr_t>(result);
  2192. }
  2193. %s
  2194. static PyObject* %s_py(PyObject* self, PyObject* args) {
  2195. try {
  2196. if(unlikely(!PyTuple_CheckExact(args)))
  2197. throw std::runtime_error("tuple args required");
  2198. if(unlikely(PyTuple_GET_SIZE(args) != %s))
  2199. throw std::runtime_error("requires %s args");
  2200. %s
  2201. } catch(std::exception const& e) {
  2202. PyErr_SetString(PyExc_RuntimeError, e.what());
  2203. return nullptr;
  2204. } catch(...) {
  2205. PyErr_SetString(PyExc_RuntimeError, "unhandled error");
  2206. return nullptr;
  2207. }
  2208. }
  2209. static PyMethodDef py_methods[] = {
  2210. {"%s", %s_py, METH_VARARGS, ""},
  2211. {NULL, NULL, 0, NULL}};
  2212. static struct PyModuleDef py_module =
  2213. {PyModuleDef_HEAD_INIT, "%s", NULL, -1, py_methods};
  2214. PyMODINIT_FUNC PyInit_%s(void) {
  2215. const char* str_addr = std::getenv("_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR");
  2216. if(!str_addr) {
  2217. PyErr_SetString(PyExc_RuntimeError, "_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR must be set");
  2218. return nullptr;
  2219. }
  2220. std::istringstream iss(str_addr);
  2221. uintptr_t addr = 0;
  2222. iss >> addr;
  2223. _torchinductor_pyobject_tensor_data_ptr =
  2224. reinterpret_cast<decltype(_torchinductor_pyobject_tensor_data_ptr)>(addr);
  2225. return PyModule_Create(&py_module);
  2226. }
  2227. """
  2228. )
  2229. @classmethod
  2230. def _load_library_inner(cls, path: str, key: str) -> ModuleType:
  2231. os.environ["_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"] = str(
  2232. torch._C._dynamo.guards._torchinductor_pyobject_tensor_data_ptr # type: ignore[attr-defined]
  2233. )
  2234. module_name = f"{key}.{cls.entry_function}"
  2235. try:
  2236. return sys.modules[module_name]
  2237. except KeyError:
  2238. pass
  2239. spec = importlib.util.spec_from_file_location(module_name, path)
  2240. assert spec is not None
  2241. module = importlib.util.module_from_spec(spec)
  2242. sys.modules[module_name] = module
  2243. spec.loader.exec_module(module) # type: ignore[union-attr]
  2244. return module
  2245. @classmethod
  2246. def load_pybinding_async(
  2247. cls,
  2248. argtypes: List[str],
  2249. source_code: str,
  2250. cuda: bool = False,
  2251. num_outputs: int = -1,
  2252. submit_fn=None,
  2253. extra_flags=(),
  2254. ) -> Any:
  2255. """
  2256. Wrap a C++ function in fast Python bindings.
  2257. Args:
  2258. argtypes: The types of args to ENTRY_FUNCTION(), e.g. ["float*", "long"]
  2259. source_code: C++ source code containing a ENTRY_FUNCTION() function
  2260. Returns:
  2261. A python version of ENTRY_FUNCTION()
  2262. """
  2263. parseargs = ", ".join(
  2264. f"parse_arg<{argtype.replace('const ', '')}>(args, {n})"
  2265. for n, argtype in enumerate(argtypes)
  2266. )
  2267. suffix = cls.suffix_template % (
  2268. cls.entry_function,
  2269. cls.extra_parse_arg % num_outputs if cls.extra_parse_arg else "",
  2270. cls.entry_function,
  2271. len(argtypes),
  2272. len(argtypes),
  2273. cls.call_entry_function % parseargs,
  2274. cls.entry_function,
  2275. cls.entry_function,
  2276. cls.entry_function,
  2277. cls.entry_function,
  2278. )
  2279. get_result = cls.load_async(
  2280. source_code + suffix, cuda, submit_fn=submit_fn, extra_flags=extra_flags
  2281. )
  2282. result = None
  2283. def future():
  2284. nonlocal result
  2285. if result is None:
  2286. result = get_result()
  2287. assert isinstance(result, ModuleType)
  2288. return getattr(result, cls.entry_function)
  2289. return future
  2290. @classmethod
  2291. def load_pybinding(cls, *args, **kwargs) -> Any:
  2292. return cls.load_pybinding_async(*args, **kwargs)()
  2293. @clear_on_fresh_inductor_cache
  2294. class CppWrapperCodeCache(CppPythonBindingsCodeCache):
  2295. cache: Dict[str, Callable[[], Union[CDLL, ModuleType]]] = {}
  2296. cache_clear = staticmethod(cache.clear)
  2297. cpp_compile_command_flags = {
  2298. "include_pytorch": True,
  2299. "shared": True,
  2300. }
  2301. entry_function = "inductor_entry_cpp"
  2302. call_entry_function = "return inductor_entry_cpp(%s);"
  2303. extra_parse_arg = textwrap.dedent(
  2304. """
  2305. #include <torch/csrc/inductor/aoti_torch/c/shim.h>
  2306. static inline std::vector<AtenTensorHandle> unpack_tensor_handle_list(PyObject* pyvec) {
  2307. std::vector<AtenTensorHandle> result;
  2308. size_t result_len = PyList_GET_SIZE(pyvec);
  2309. result.reserve(result_len);
  2310. for (size_t i = 0; i < result_len; i++) {
  2311. // AtenTensorHandle is essentially a pointer
  2312. void* elem = PyCapsule_GetPointer(PyList_GET_ITEM(pyvec, i), NULL);
  2313. result.push_back(reinterpret_cast<AtenTensorHandle>(elem));
  2314. }
  2315. return result;
  2316. }
  2317. static inline PyObject* pack_tensor_handle_list(const std::vector<AtenTensorHandle>& cppvec) {
  2318. size_t result_len = cppvec.size();
  2319. PyObject* result = PyList_New(static_cast<Py_ssize_t>(result_len));
  2320. for (size_t i = 0; i < result_len; i++) {
  2321. PyObject *elem =
  2322. cppvec[i] == nullptr
  2323. ? Py_None
  2324. // Store AtenTensorHandle as PyCapsulate
  2325. : PyCapsule_New(reinterpret_cast<void*>(cppvec[i]), NULL, NULL);
  2326. PyList_SET_ITEM(result, i, elem);
  2327. }
  2328. return result;
  2329. }
  2330. template <> inline std::vector<AtenTensorHandle> parse_arg<std::vector<AtenTensorHandle>>(PyObject* args, size_t n) {
  2331. return unpack_tensor_handle_list(PyTuple_GET_ITEM(args, n));
  2332. }
  2333. PyObject* inductor_entry_cpp(std::vector<AtenTensorHandle>&& input_handles) {
  2334. // For outputs, we only allocate a vector to hold returned tensor handles,
  2335. // not allocating the actual output tensor storage here
  2336. std::vector<AtenTensorHandle> output_handles(%s);
  2337. try {
  2338. inductor_entry_impl(input_handles.data(), output_handles.data());
  2339. return pack_tensor_handle_list(output_handles);
  2340. } catch(std::exception const& e) {
  2341. PyErr_SetString(PyExc_RuntimeError, e.what());
  2342. return {};
  2343. } catch(...) {
  2344. PyErr_SetString(PyExc_RuntimeError, "unhandled error");
  2345. return {};
  2346. }
  2347. }
  2348. """
  2349. )
  2350. # TODO: Will remove the temp code after switch to new cpp_builder
  2351. def _temp_validate_new_and_old_command(new_cmd: List[str], old_cmd: List[str]):
  2352. new_diff: List[str] = [x for x in new_cmd if x not in old_cmd]
  2353. old_diff: List[str] = [y for y in old_cmd if y not in new_cmd]
  2354. if new_diff or old_diff:
  2355. print("!!! new_cmd: ", new_cmd)
  2356. print("!!! old_cmd: ", old_cmd)
  2357. print("!!! new_diff: ", new_diff)
  2358. print("!!! old_diff: ", old_diff)
  2359. raise RuntimeError("Error in new and old command different.")
  2360. def _do_validate_cpp_commands(
  2361. include_pytorch: bool,
  2362. cuda: bool,
  2363. compile_only: bool,
  2364. mmap_weights: bool,
  2365. use_absolute_path: bool,
  2366. ):
  2367. # PreCI will failed if test machine can't run cuda.
  2368. temp_dir = tempfile.TemporaryDirectory()
  2369. test_dir_path = temp_dir.name
  2370. test_cuda = torch.cuda.is_available() and cuda
  2371. input_path = os.path.join(test_dir_path, "dummy_input.cpp")
  2372. output_path = os.path.join(test_dir_path, "dummy_output.so")
  2373. extra_flags = ["-D TEST_EXTRA_FLAGS"]
  2374. if compile_only:
  2375. output_path = os.path.join(test_dir_path, "dummy_output.o")
  2376. picked_isa = pick_vec_isa()
  2377. old_cmd = cpp_compile_command(
  2378. input=input_path,
  2379. output=output_path,
  2380. include_pytorch=include_pytorch,
  2381. vec_isa=picked_isa,
  2382. cuda=test_cuda,
  2383. aot_mode=False,
  2384. compile_only=compile_only,
  2385. use_absolute_path=use_absolute_path,
  2386. use_mmap_weights=mmap_weights,
  2387. extra_flags=extra_flags,
  2388. ).split(" ")
  2389. from torch._inductor.cpp_builder import CppBuilder, CppTorchCudaOptions
  2390. dummy_build_option = CppTorchCudaOptions(
  2391. vec_isa=picked_isa,
  2392. include_pytorch=include_pytorch,
  2393. cuda=test_cuda,
  2394. compile_only=compile_only,
  2395. use_absolute_path=use_absolute_path,
  2396. use_mmap_weights=mmap_weights,
  2397. extra_flags=extra_flags,
  2398. )
  2399. dummy_builder = CppBuilder(
  2400. name="dummy_output",
  2401. sources=input_path,
  2402. BuildOption=dummy_build_option,
  2403. output_dir=test_dir_path,
  2404. )
  2405. new_cmd = dummy_builder.get_command_line().split(" ")
  2406. _temp_validate_new_and_old_command(new_cmd, old_cmd)
  2407. temp_dir.cleanup()
  2408. # TODO: Will remove the temp code after switch to new cpp_builder
  2409. # It could help on sync new cpp_builder generate same command line as the old one.
  2410. def validate_new_cpp_commands():
  2411. cuda = [True, False]
  2412. use_mmap_weights = [True, False]
  2413. compile_only = [True, False]
  2414. include_pytorch = [True, False]
  2415. use_absolute_path = [True, False]
  2416. for x in cuda:
  2417. for y in use_mmap_weights:
  2418. for z in compile_only:
  2419. for m in include_pytorch:
  2420. for n in use_absolute_path:
  2421. print(
  2422. f"!!! cuda:{x}, use_mmap_weights:{y}, compile_only:{z}, include_pytorch:{m}, use_absolute_path:{n}"
  2423. )
  2424. _do_validate_cpp_commands(
  2425. include_pytorch=m,
  2426. cuda=x,
  2427. mmap_weights=y,
  2428. compile_only=z,
  2429. use_absolute_path=n,
  2430. )
  2431. @clear_on_fresh_inductor_cache
  2432. class HalideCodeCache(CppPythonBindingsCodeCache):
  2433. cache: Dict[str, Callable[[], Union[ModuleType, CDLL]]] = {}
  2434. cache_clear = staticmethod(cache.clear)
  2435. glue_template = textwrap.dedent(
  2436. """
  2437. #include "{halidebuffer_h}"
  2438. #include "{headerfile}"
  2439. #include <stdexcept>
  2440. #include <cmath>
  2441. void kernel({argdefs}) {{
  2442. {buffers}
  2443. int err = halide_kernel({buffer_names});
  2444. if(err != 0) {{
  2445. throw std::runtime_error("halide_kernel failed");
  2446. }}
  2447. }}
  2448. """
  2449. )
  2450. @classmethod
  2451. def _codegen_glue(cls, argtypes, headerfile):
  2452. buffers = []
  2453. buffer_names = []
  2454. for i, arg in enumerate(argtypes):
  2455. if arg.numel:
  2456. buffer_names.append(f"hl_buf_{i}")
  2457. buffers.append(
  2458. f" Halide::Runtime::Buffer {buffer_names[-1]}({arg.halide_type()}, {arg.name}, {arg.numel});"
  2459. )
  2460. else:
  2461. assert "*" not in arg.ctype
  2462. buffer_names.append(arg.name)
  2463. glue_code = cls.glue_template.format(
  2464. halidebuffer_h=cls.find_header("HalideBuffer.h"),
  2465. headerfile=headerfile,
  2466. argdefs=", ".join(f"{a.bindings_type()} {a.name}" for a in argtypes),
  2467. buffers="\n".join(buffers).lstrip(),
  2468. buffer_names=", ".join(buffer_names),
  2469. )
  2470. return glue_code
  2471. @classmethod
  2472. @functools.lru_cache(None)
  2473. def config_hash(cls):
  2474. return sha256_hash(
  2475. "\n".join(
  2476. [
  2477. cls.glue_template,
  2478. f"{cls.cpu_cache_size()}",
  2479. cpp_compile_command("I", "O"),
  2480. ]
  2481. ).encode("utf-8")
  2482. )
  2483. @staticmethod
  2484. @functools.lru_cache(None)
  2485. def cpu_cache_size():
  2486. try:
  2487. cpuinfo = open("/proc/cpuinfo").read()
  2488. except OSError:
  2489. return 16777216
  2490. m = re.search(r"cache size\s*: (\d+) KB", cpuinfo)
  2491. if m:
  2492. return int(m.group(1)) * 1024
  2493. m = re.search(r"cache size\s*: (\d+) MB", cpuinfo)
  2494. if m:
  2495. return int(m.group(1)) * 1024 * 1024
  2496. raise RuntimeError("failed to find 'cache size: ... KB' in /proc/cpuinfo")
  2497. @staticmethod
  2498. def _search_for_file(suffix, errmsg):
  2499. try:
  2500. search, *_ = importlib.machinery.PathFinder.find_spec( # type: ignore[union-attr,misc]
  2501. "halide"
  2502. ).submodule_search_locations
  2503. for file in os.listdir(search):
  2504. if file.endswith(".so"):
  2505. try:
  2506. out = subprocess.check_output(
  2507. ["ldd", os.path.join(search, file)]
  2508. )
  2509. except subprocess.SubprocessError:
  2510. continue
  2511. m = re.search(r"(/.*)/libHalide.so", out.decode("utf-8"))
  2512. if m:
  2513. path = os.path.join(os.path.abspath(m.group(1)), suffix)
  2514. if os.path.exists(path):
  2515. return os.path.abspath(path)
  2516. except Exception as e:
  2517. raise RuntimeError(errmsg) from e
  2518. raise RuntimeError(errmsg)
  2519. @staticmethod
  2520. @functools.lru_cache(None)
  2521. def find_libautoschedule(name):
  2522. sofile = f"libautoschedule_{name.lower()}.so"
  2523. if "HALIDE_LIB" in os.environ:
  2524. path = os.path.join(os.environ["HALIDE_LIB"], sofile)
  2525. if os.path.exists(path):
  2526. return path
  2527. errmsg = (
  2528. f"Can't find {sofile}, set env HALIDE_LIB to the directory containing it"
  2529. )
  2530. return HalideCodeCache._search_for_file(sofile, errmsg)
  2531. @staticmethod
  2532. @functools.lru_cache(None)
  2533. def find_header(name):
  2534. if "HALIDE_INCLUDE" in os.environ:
  2535. path = os.path.join(os.environ["HALIDE_INCLUDE"], name)
  2536. if os.path.exists(path):
  2537. return path
  2538. if "HALIDE_LIB" in os.environ:
  2539. path = os.path.abspath(
  2540. os.path.join(os.environ["HALIDE_LIB"], f"../include/{name}")
  2541. )
  2542. if os.path.exists(path):
  2543. return path
  2544. errmsg = (
  2545. f"Can't find {name}, set env HALIDE_INCLUDE to the directory containing it"
  2546. )
  2547. return HalideCodeCache._search_for_file(f"../include/{name}", errmsg)
  2548. @classmethod
  2549. def generate_halide_async(cls, meta: HalideMeta, source_code: str, submit_fn=None):
  2550. dirpath = Path(
  2551. get_path(
  2552. code_hash(
  2553. source_code,
  2554. extra=repr((cls.config_hash(), meta)),
  2555. ),
  2556. "halide",
  2557. )[2]
  2558. )
  2559. os.makedirs(dirpath, exist_ok=True)
  2560. wait_for_compile = None
  2561. genfile = str(dirpath / "generate_kernel.py")
  2562. libfile = str(dirpath / "halide_kernel.a")
  2563. headerfile = str(dirpath / "halide_kernel.h")
  2564. donefile = str(dirpath / "done")
  2565. lockfile = str(dirpath / "lock")
  2566. need_compile = not os.path.exists(donefile)
  2567. jobs = []
  2568. if need_compile:
  2569. write_atomic(genfile, source_code)
  2570. jobs.append(
  2571. functools.partial(
  2572. subprocess.check_call,
  2573. [
  2574. sys.executable,
  2575. genfile,
  2576. "-g",
  2577. "kernel",
  2578. "-o",
  2579. f"{dirpath}",
  2580. "-f",
  2581. "halide_kernel",
  2582. "-e",
  2583. "static_library,h,schedule,pytorch_wrapper",
  2584. "-p",
  2585. cls.find_libautoschedule(meta.scheduler),
  2586. *meta.args(),
  2587. ],
  2588. )
  2589. )
  2590. bindings_future = cls.load_pybinding_async(
  2591. [arg.bindings_type() for arg in meta.argtypes],
  2592. cls._codegen_glue(meta.argtypes, headerfile),
  2593. extra_flags=(libfile,),
  2594. submit_fn=jobs.append if need_compile else None,
  2595. )
  2596. if need_compile:
  2597. jobs.append(functools.partial(touch, donefile))
  2598. task = functools.partial(_worker_task_halide, lockfile, jobs)
  2599. if submit_fn:
  2600. wait_for_compile = submit_fn(task).result
  2601. else:
  2602. task()
  2603. def load():
  2604. if wait_for_compile:
  2605. wait_for_compile()
  2606. return bindings_future()
  2607. return load
  2608. @classmethod
  2609. def generate_halide(cls, *args, **kwargs):
  2610. return cls.generate_halide_async(*args, **kwargs)()
  2611. def _worker_task_halide(lockfile, jobs):
  2612. from filelock import FileLock
  2613. with FileLock(lockfile, LOCK_TIMEOUT):
  2614. for job in jobs:
  2615. job()
  2616. def touch(filename):
  2617. open(filename, "a").close()
  2618. @clear_on_fresh_inductor_cache
  2619. class PyCodeCache:
  2620. cache: Dict[str, ModuleType] = dict()
  2621. linemaps: Dict[str, List[Tuple[Any, ...]]] = dict()
  2622. cache_clear = staticmethod(cache.clear)
  2623. @classmethod
  2624. def write(cls, source_code: str, extra: str = "") -> Tuple[str, str]:
  2625. return write(source_code, "py", extra=extra)
  2626. @classmethod
  2627. def load(
  2628. cls,
  2629. source_code: str,
  2630. extra: str = "",
  2631. linemap: Optional[List[Tuple[int, str]]] = None,
  2632. attrs: Optional[Dict[str, Any]] = None,
  2633. ) -> ModuleType:
  2634. key, path = write(source_code, "py", extra=extra)
  2635. return cls.load_by_key_path(key, path, linemap, attrs)
  2636. @classmethod
  2637. def load_by_key_path(
  2638. cls,
  2639. key: str,
  2640. path: str,
  2641. linemap: Optional[List[Tuple[int, str]]] = None,
  2642. attrs: Optional[Dict[str, Any]] = None,
  2643. ) -> ModuleType:
  2644. if linemap is None:
  2645. linemap = []
  2646. if key not in cls.cache:
  2647. mod = _reload_python_module(key, path)
  2648. # another thread might set this first
  2649. cls.cache.setdefault(key, mod)
  2650. # unzip into separate lines/nodes lists
  2651. cls.linemaps[path] = list(zip(*linemap))
  2652. if attrs is not None:
  2653. for k, v in attrs.items():
  2654. setattr(mod, k, v)
  2655. if not (linemap or attrs):
  2656. mod._reload_in_subproc = functools.partial( # type: ignore[attr-defined]
  2657. _reload_python_module_in_subproc, key, path
  2658. )
  2659. return cls.cache[key]
  2660. @classmethod
  2661. @functools.lru_cache(None)
  2662. def stack_frames_for_code(
  2663. cls, path: str, lineno: int
  2664. ) -> Optional[List[Dict[str, Any]]]:
  2665. if path not in cls.linemaps:
  2666. return None
  2667. # [(starting_line, <fx node>), ...]
  2668. lines, nodes = cls.linemaps[path]
  2669. p = bisect_right(lines, lineno)
  2670. if p == 0:
  2671. return None
  2672. entry = nodes[p - 1]
  2673. if not entry:
  2674. return None
  2675. def parse_stack_trace(stack_trace: str) -> List[Dict[str, Any]]:
  2676. # ideally fx stores stack traces as data rather than a string
  2677. # but this is not along a performance critical path
  2678. regex = r'File "(.+)", line (\d+), in (.+)\n'
  2679. matches = re.findall(regex, stack_trace)
  2680. return [
  2681. {"filename": f, "line": int(l), "name": n}
  2682. for f, l, n in reversed(matches)
  2683. ]
  2684. return parse_stack_trace(entry)
  2685. class TritonCodeCache:
  2686. @classmethod
  2687. def load(cls, kernel_name: str, source_code: str) -> ModuleType:
  2688. return _module_to_triton_kernel(PyCodeCache.load(source_code), kernel_name)
  2689. def _cuda_compiler() -> Optional[str]:
  2690. if cuda_env.nvcc_exist(config.cuda.cuda_cxx):
  2691. return config.cuda.cuda_cxx
  2692. if config.is_fbcode():
  2693. return os.path.join(build_paths.cuda(), "bin", "nvcc")
  2694. if cuda_env.nvcc_exist(os.getenv("CUDACXX")):
  2695. return os.getenv("CUDACXX", "")
  2696. if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")):
  2697. return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc"))
  2698. return "nvcc"
  2699. def _cutlass_include_paths() -> List[str]:
  2700. if config.is_fbcode():
  2701. from libfb.py import parutil
  2702. cutlass_path = parutil.get_dir_path("cutlass-3-headers")
  2703. else:
  2704. cutlass_path = config.cuda.cutlass_dir
  2705. return [
  2706. # Use realpath to get canonical absolute paths, in order not to mess up cache keys
  2707. os.path.realpath(os.path.join(cutlass_path, "include")),
  2708. os.path.realpath(os.path.join(cutlass_path, "tools/library/include")),
  2709. os.path.realpath(os.path.join(cutlass_path, "tools/library/src")),
  2710. os.path.realpath(os.path.join(cutlass_path, "tools/util/include")),
  2711. ]
  2712. def _cuda_lib_options() -> List[str]:
  2713. _set_gpu_runtime_env() # cpp_extension consults the env
  2714. from torch.utils import cpp_extension
  2715. lpaths = cpp_extension.library_paths(cuda=True) + [
  2716. sysconfig.get_config_var("LIBDIR")
  2717. ]
  2718. extra_ldflags: List[str] = []
  2719. if is_linux():
  2720. _transform_cuda_paths(lpaths)
  2721. for path in lpaths:
  2722. # -rpath ensures the DLL can find its dependencies when loaded, even
  2723. # if the library path is non-standard.
  2724. extra_ldflags.extend([f"-L{path}", "-Xlinker", f"-rpath={path}"])
  2725. extra_ldflags.append("-lcuda")
  2726. extra_ldflags.append("-lcudart")
  2727. else:
  2728. raise NotImplementedError(
  2729. "Unsupported env, failed to find cuda libs! Currently only Linux is supported."
  2730. )
  2731. return extra_ldflags
  2732. def _nvcc_host_compiler_options() -> List[str]:
  2733. return [
  2734. "-fPIC",
  2735. "-fno-strict-aliasing",
  2736. "-fvisibility=hidden",
  2737. "-Wconversion",
  2738. ]
  2739. def _nvcc_compiler_options() -> List[str]:
  2740. arch = cuda_env.get_cuda_arch()
  2741. if arch == "90":
  2742. # Required by cutlass compilation.
  2743. arch = "90a"
  2744. code = [f"sm_{arch}", f"compute_{arch}"]
  2745. if config.cuda.enable_cuda_lto:
  2746. code += [f"lto_{arch}"]
  2747. options = [
  2748. "-t=0",
  2749. "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
  2750. "-w",
  2751. f"-gencode=arch=compute_{arch},code=[{','.join(code)}]",
  2752. config.cuda.compile_opt_level,
  2753. "-std=c++17",
  2754. "--expt-relaxed-constexpr",
  2755. "-DNDEBUG",
  2756. ]
  2757. if config.is_fbcode():
  2758. options.extend(["-ccbin", os.path.dirname(build_paths.gcc())])
  2759. if config.cuda.enable_debug_info:
  2760. options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"])
  2761. if config.cuda.enable_ptxas_info:
  2762. options.extend(
  2763. [
  2764. "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.)
  2765. "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels
  2766. "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels
  2767. "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.)
  2768. "--source-in-ptx",
  2769. ]
  2770. ) # Annotate the ptx file with source information
  2771. if config.cuda.use_fast_math:
  2772. options.extend(
  2773. [
  2774. "--use_fast_math",
  2775. "-DCUTLASS_USE_TANH_FOR_SIGMOID=1",
  2776. ]
  2777. )
  2778. return options
  2779. def cuda_compile_command(
  2780. src_files: List[str],
  2781. dst_file: str,
  2782. dst_file_ext: str,
  2783. extra_args: Optional[List[str]] = None,
  2784. ) -> str:
  2785. if extra_args is None:
  2786. extra_args = []
  2787. include_paths = _cutlass_include_paths()
  2788. cuda_lib_options = _cuda_lib_options()
  2789. nvcc_host_compiler_options = _nvcc_host_compiler_options()
  2790. nvcc_compiler_options = _nvcc_compiler_options()
  2791. options = (
  2792. nvcc_compiler_options
  2793. + extra_args
  2794. + [
  2795. f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}"
  2796. for opt in nvcc_host_compiler_options
  2797. ]
  2798. + ["-I" + path for path in include_paths]
  2799. + cuda_lib_options
  2800. )
  2801. src_file = " ".join(src_files)
  2802. res = ""
  2803. if dst_file_ext == "o":
  2804. res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}"
  2805. elif dst_file_ext == "so":
  2806. options.append("-shared")
  2807. res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
  2808. elif dst_file_ext == "exe":
  2809. res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
  2810. else:
  2811. raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
  2812. log.debug("CUDA command: %s", res)
  2813. return res
  2814. class DLLWrapper:
  2815. """A wrapper for a dynamic library."""
  2816. def __init__(
  2817. self,
  2818. lib_path: str,
  2819. ):
  2820. self.lib_path = lib_path
  2821. self.is_open = False
  2822. self.DLL = cdll.LoadLibrary(lib_path)
  2823. self.is_open = True
  2824. def close(self):
  2825. if self.is_open:
  2826. self._dlclose()
  2827. self.is_open = False
  2828. def _dlclose(self):
  2829. f_dlclose = None
  2830. if is_linux():
  2831. syms = CDLL(None)
  2832. if not hasattr(syms, "dlclose"):
  2833. # Apline Linux
  2834. syms = CDLL("libc.so")
  2835. if hasattr(syms, "dlclose"):
  2836. f_dlclose = syms.dlclose
  2837. else:
  2838. raise NotImplementedError("Unsupported env, failed to do dlclose!")
  2839. if f_dlclose is not None:
  2840. f_dlclose.argtypes = [c_void_p]
  2841. f_dlclose(self.DLL._handle)
  2842. else:
  2843. log.warning(
  2844. "dll unloading function was not found, library may not be unloaded properly!"
  2845. )
  2846. def __getattr__(self, name):
  2847. if not self.is_open:
  2848. raise RuntimeError(f"Cannot use closed DLL library: {self.lib_path}")
  2849. method = getattr(self.DLL, name)
  2850. def _wrapped_func(*args):
  2851. err = method(*args)
  2852. if err:
  2853. raise RuntimeError(f"Error in function: {method.__name__}")
  2854. return _wrapped_func
  2855. def __enter__(self):
  2856. return self
  2857. def __exit__(self, *args):
  2858. self.close()
  2859. def __del__(self):
  2860. self.close()
  2861. @clear_on_fresh_inductor_cache
  2862. class CUDACodeCache:
  2863. @dataclasses.dataclass
  2864. class CacheEntry:
  2865. input_path: str
  2866. output_path: str
  2867. cache: Dict[str, CacheEntry] = dict()
  2868. cache_clear = staticmethod(cache.clear)
  2869. _SOURCE_CODE_SUFFIX = "cu"
  2870. @classmethod
  2871. def write(cls, source_code, dst_file_ext) -> Tuple[str, str]:
  2872. """
  2873. Writes source code into a file with dst_file_ext as the file extension.
  2874. Returns the hash key of source code, and the path to the file.
  2875. """
  2876. cuda_command = repr(
  2877. cuda_compile_command(["dummy_input"], "dummy_output", dst_file_ext)
  2878. )
  2879. key, input_path = write(
  2880. source_code, cls._SOURCE_CODE_SUFFIX, extra=cuda_command
  2881. )
  2882. return key, input_path
  2883. @classmethod
  2884. def compile(
  2885. cls, source_code, dst_file_ext, extra_args: Optional[List[str]] = None
  2886. ) -> Tuple[str, str, str]:
  2887. """
  2888. Compiles CUDA source_code into a file with dst_file_ext extension.
  2889. Returns a tuple of dst_file_path, hash_key, source_code_path
  2890. """
  2891. key, input_path = cls.write(source_code, dst_file_ext)
  2892. if key not in cls.cache:
  2893. from filelock import FileLock
  2894. lock_dir = get_lock_dir()
  2895. lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
  2896. with lock:
  2897. output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext
  2898. if not os.path.exists(output_path):
  2899. cmd = cuda_compile_command(
  2900. [input_path], output_path, dst_file_ext, extra_args
  2901. )
  2902. start_time = time()
  2903. log.debug("CUDA Compilation: %s", cmd)
  2904. cmd_parts = cmd.split(" ")
  2905. try:
  2906. subprocess.check_output(
  2907. cmd_parts, stderr=subprocess.STDOUT, env=os.environ
  2908. )
  2909. except subprocess.CalledProcessError as error:
  2910. raise exc.CUDACompileError(cmd_parts, error.output) from error
  2911. end_time = time()
  2912. log_duration_msg = f"CUDA Compilation took {end_time-start_time} seconds. Compile command: {cmd}"
  2913. log.info(log_duration_msg)
  2914. else:
  2915. log.debug(
  2916. "CUDA Compilation skipped: %s since output already exists",
  2917. input_path,
  2918. )
  2919. cls.cache[key] = CUDACodeCache.CacheEntry(input_path, output_path)
  2920. return (cls.cache[key].output_path, key, input_path)
  2921. @classmethod
  2922. def load(cls, source_code, dst_file_ext) -> Tuple[DLLWrapper, str, str]:
  2923. """
  2924. Compiles source code and loads the generated .so file.
  2925. Returns a tuple of DLLWrapper, hash_key, source_code_path
  2926. """
  2927. if dst_file_ext != "so":
  2928. raise RuntimeError(
  2929. f"Only support loading a .so file for now. "
  2930. f"Requested file extension: {dst_file_ext}. Source code: {source_code}"
  2931. )
  2932. dst_file_path, hash_key, source_code_path = cls.compile(
  2933. source_code, dst_file_ext
  2934. )
  2935. return (DLLWrapper(dst_file_path), hash_key, source_code_path)
  2936. class CodeCacheFuture:
  2937. def result(self):
  2938. raise NotImplementedError
  2939. class TritonFuture(CodeCacheFuture):
  2940. kernel: ModuleType
  2941. def __init__(
  2942. self,
  2943. kernel: Any,
  2944. future: Optional[Future[Any]],
  2945. ) -> None:
  2946. self.kernel = kernel
  2947. self.future = future
  2948. # @dynamo_utils.dynamo_timed
  2949. def result(self) -> ModuleType:
  2950. if self.future is not None:
  2951. # If the worker failed this will throw an exception.
  2952. result = self.future.result()
  2953. assert result is None
  2954. self.future = None
  2955. self.kernel.precompile()
  2956. return self.kernel
  2957. class LambdaFuture(CodeCacheFuture):
  2958. def __init__(self, result_fn):
  2959. self.result_fn = result_fn
  2960. def result(self):
  2961. return self.result_fn()