cpp_extension.py 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195
  1. # mypy: allow-untyped-defs
  2. import copy
  3. import glob
  4. import importlib
  5. import importlib.abc
  6. import os
  7. import re
  8. import shlex
  9. import shutil
  10. import setuptools
  11. import subprocess
  12. import sys
  13. import sysconfig
  14. import types
  15. import collections
  16. from pathlib import Path
  17. import errno
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. import torch
  21. import torch._appdirs
  22. from .file_baton import FileBaton
  23. from ._cpp_extension_versioner import ExtensionVersioner
  24. from typing_extensions import deprecated
  25. from torch.torch_version import TorchVersion, Version
  26. from setuptools.command.build_ext import build_ext
  27. IS_WINDOWS = sys.platform == 'win32'
  28. IS_MACOS = sys.platform.startswith('darwin')
  29. IS_LINUX = sys.platform.startswith('linux')
  30. LIB_EXT = '.pyd' if IS_WINDOWS else '.so'
  31. EXEC_EXT = '.exe' if IS_WINDOWS else ''
  32. CLIB_PREFIX = '' if IS_WINDOWS else 'lib'
  33. CLIB_EXT = '.dll' if IS_WINDOWS else '.so'
  34. SHARED_FLAG = '/DLL' if IS_WINDOWS else '-shared'
  35. _HERE = os.path.abspath(__file__)
  36. _TORCH_PATH = os.path.dirname(os.path.dirname(_HERE))
  37. TORCH_LIB_PATH = os.path.join(_TORCH_PATH, 'lib')
  38. SUBPROCESS_DECODE_ARGS = ('oem',) if IS_WINDOWS else ()
  39. MINIMUM_GCC_VERSION = (5, 0, 0)
  40. MINIMUM_MSVC_VERSION = (19, 0, 24215)
  41. VersionRange = tuple[tuple[int, ...], tuple[int, ...]]
  42. VersionMap = dict[str, VersionRange]
  43. # The following values were taken from the following GitHub gist that
  44. # summarizes the minimum valid major versions of g++/clang++ for each supported
  45. # CUDA version: https://gist.github.com/ax3l/9489132
  46. # Or from include/crt/host_config.h in the CUDA SDK
  47. # The second value is the exclusive(!) upper bound, i.e. min <= version < max
  48. CUDA_GCC_VERSIONS: VersionMap = {
  49. '11.0': (MINIMUM_GCC_VERSION, (10, 0)),
  50. '11.1': (MINIMUM_GCC_VERSION, (11, 0)),
  51. '11.2': (MINIMUM_GCC_VERSION, (11, 0)),
  52. '11.3': (MINIMUM_GCC_VERSION, (11, 0)),
  53. '11.4': ((6, 0, 0), (12, 0)),
  54. '11.5': ((6, 0, 0), (12, 0)),
  55. '11.6': ((6, 0, 0), (12, 0)),
  56. '11.7': ((6, 0, 0), (12, 0)),
  57. '12.0': ((6, 0, 0), (13, 0)),
  58. '12.1': ((6, 0, 0), (13, 0)),
  59. '12.2': ((6, 0, 0), (13, 0)),
  60. '12.3': ((6, 0, 0), (14, 0)),
  61. '12.4': ((6, 0, 0), (14, 0)),
  62. '12.5': ((6, 0, 0), (14, 0)),
  63. '12.6': ((6, 0, 0), (14, 0)),
  64. '12.7': ((6, 0, 0), (14, 0)),
  65. '12.8': ((6, 0, 0), (14, 0)),
  66. '12.9': ((6, 0, 0), (14, 0)),
  67. '13.0': ((6, 0, 0), (16, 0)),
  68. }
  69. MINIMUM_CLANG_VERSION = (3, 3, 0)
  70. CUDA_CLANG_VERSIONS: VersionMap = {
  71. '11.1': (MINIMUM_CLANG_VERSION, (11, 0)),
  72. '11.2': (MINIMUM_CLANG_VERSION, (12, 0)),
  73. '11.3': (MINIMUM_CLANG_VERSION, (12, 0)),
  74. '11.4': (MINIMUM_CLANG_VERSION, (13, 0)),
  75. '11.5': (MINIMUM_CLANG_VERSION, (13, 0)),
  76. '11.6': (MINIMUM_CLANG_VERSION, (14, 0)),
  77. '11.7': (MINIMUM_CLANG_VERSION, (14, 0)),
  78. '12.0': ((7, 0), (15, 0)),
  79. '12.1': ((7, 0), (15, 0)),
  80. '12.2': ((7, 0), (16, 0)),
  81. '12.3': ((7, 0), (16, 0)),
  82. '12.4': ((7, 0), (17, 0)),
  83. '12.5': ((7, 0), (18, 0)),
  84. '12.6': ((7, 0), (18, 0)),
  85. '12.7': ((7, 0), (19, 0)),
  86. '12.8': ((7, 0), (19, 0)),
  87. '12.9': ((7, 0), (19, 0)),
  88. '13.0': ((7, 0), (21, 0)),
  89. }
  90. __all__ = ["get_default_build_root", "check_compiler_ok_for_platform", "get_compiler_abi_compatibility_and_version", "BuildExtension",
  91. "CppExtension", "CUDAExtension", "SyclExtension", "include_paths", "library_paths", "load", "load_inline", "is_ninja_available",
  92. "verify_ninja_availability", "remove_extension_h_precompiler_headers", "get_cxx_compiler", "check_compiler_is_gcc"]
  93. # Taken directly from python stdlib < 3.9
  94. # See https://github.com/pytorch/pytorch/issues/48617
  95. def _nt_quote_args(args: list[str] | None) -> list[str]:
  96. """Quote command-line arguments for DOS/Windows conventions.
  97. Just wraps every argument which contains blanks in double quotes, and
  98. returns a new argument list.
  99. """
  100. # Cover None-type
  101. if not args:
  102. return []
  103. return [f'"{arg}"' if ' ' in arg else arg for arg in args]
  104. def _find_cuda_home() -> str | None:
  105. """Find the CUDA install path."""
  106. # Guess #1
  107. cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')
  108. if cuda_home is None:
  109. # Guess #2
  110. nvcc_path = shutil.which("nvcc")
  111. if nvcc_path is not None:
  112. cuda_home = os.path.dirname(os.path.dirname(nvcc_path))
  113. else:
  114. # Guess #3
  115. if IS_WINDOWS:
  116. cuda_homes = glob.glob(
  117. 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*')
  118. if len(cuda_homes) == 0:
  119. cuda_home = ''
  120. else:
  121. cuda_home = cuda_homes[0]
  122. else:
  123. cuda_home = '/usr/local/cuda'
  124. if not os.path.exists(cuda_home):
  125. cuda_home = None
  126. if cuda_home and not torch.cuda.is_available():
  127. logger.warning("No CUDA runtime is found, using CUDA_HOME='%s'", cuda_home)
  128. return cuda_home
  129. def _find_rocm_home() -> str | None:
  130. """Find the ROCm install path."""
  131. # Guess #1
  132. rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH')
  133. if rocm_home is None:
  134. # Guess #2
  135. hipcc_path = shutil.which('hipcc')
  136. if hipcc_path is not None:
  137. rocm_home = os.path.dirname(os.path.dirname(
  138. os.path.realpath(hipcc_path)))
  139. # can be either <ROCM_HOME>/hip/bin/hipcc or <ROCM_HOME>/bin/hipcc
  140. if os.path.basename(rocm_home) == 'hip':
  141. rocm_home = os.path.dirname(rocm_home)
  142. else:
  143. # Guess #3
  144. fallback_path = '/opt/rocm'
  145. if os.path.exists(fallback_path):
  146. rocm_home = fallback_path
  147. if rocm_home and torch.version.hip is None:
  148. logger.warning("No ROCm runtime is found, using ROCM_HOME='%s'", rocm_home)
  149. return rocm_home
  150. def _find_sycl_home() -> str | None:
  151. sycl_home = None
  152. icpx_path = shutil.which('icpx')
  153. # Guess 1: for source code build developer/user, we'll have icpx in PATH,
  154. # which will tell us the SYCL_HOME location.
  155. if icpx_path is not None:
  156. sycl_home = os.path.dirname(os.path.dirname(
  157. os.path.realpath(icpx_path)))
  158. # Guess 2: for users install Pytorch with XPU support, the sycl runtime is
  159. # inside intel-sycl-rt, which is automatically installed via pip dependency.
  160. else:
  161. try:
  162. files = importlib.metadata.files('intel-sycl-rt') or []
  163. for f in files:
  164. if f.name == "libsycl.so":
  165. sycl_home = os.path.dirname(Path(f.locate()).parent.resolve())
  166. break
  167. except importlib.metadata.PackageNotFoundError:
  168. logger.warning("Trying to find SYCL_HOME from intel-sycl-rt package, but it is not installed.")
  169. return sycl_home
  170. def _join_rocm_home(*paths) -> str:
  171. """
  172. Join paths with ROCM_HOME, or raises an error if it ROCM_HOME is not set.
  173. This is basically a lazy way of raising an error for missing $ROCM_HOME
  174. only once we need to get any ROCm-specific path.
  175. """
  176. if ROCM_HOME is None:
  177. raise OSError('ROCM_HOME environment variable is not set. '
  178. 'Please set it to your ROCm install root.')
  179. return os.path.join(ROCM_HOME, *paths)
  180. def _join_sycl_home(*paths) -> str:
  181. """
  182. Join paths with SYCL_HOME, or raises an error if it SYCL_HOME is not found.
  183. This is basically a lazy way of raising an error for missing SYCL_HOME
  184. only once we need to get any SYCL-specific path.
  185. """
  186. if SYCL_HOME is None:
  187. raise OSError('SYCL runtime is not dected. Please setup the pytorch '
  188. 'prerequisites for Intel GPU following the instruction in '
  189. 'https://github.com/pytorch/pytorch?tab=readme-ov-file#intel-gpu-support '
  190. 'or install intel-sycl-rt via pip.')
  191. return os.path.join(SYCL_HOME, *paths)
  192. ABI_INCOMPATIBILITY_WARNING = (
  193. " !! WARNING !!"
  194. "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  195. "Your compiler (%s) may be ABI-incompatible with PyTorch!"
  196. "Please use a compiler that is ABI-compatible with GCC 5.0 and above."
  197. "See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html."
  198. "See https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6"
  199. "for instructions on how to install GCC 5 or higher."
  200. "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  201. " !! WARNING !!"
  202. )
  203. WRONG_COMPILER_WARNING = (
  204. " !! WARNING !!"
  205. "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  206. "Your compiler (%s) is not compatible with the compiler Pytorch was"
  207. "built with for this platform, which is %s on %s. Please"
  208. "use %s to compile your extension. Alternatively, you may"
  209. "compile PyTorch from source using %s, and then you can also use"
  210. "%s to compile your extension."
  211. "See https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md for help"
  212. "with compiling PyTorch from source."
  213. "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  214. " !! WARNING !!"
  215. )
  216. CUDA_MISMATCH_MESSAGE = (
  217. "The detected CUDA version (%s) mismatches the version that was used to compile"
  218. "PyTorch (%s). Please make sure to use the same CUDA versions."
  219. )
  220. CUDA_MISMATCH_WARN = (
  221. "The detected CUDA version (%s) has a minor version mismatch with the version that was used to compile PyTorch (%s). Most likely this shouldn't be a problem."
  222. )
  223. CUDA_NOT_FOUND_MESSAGE = (
  224. "CUDA was not found on the system, please set the CUDA_HOME or the CUDA_PATH"
  225. "environment variable or add NVCC to your system PATH. The extension compilation will fail."
  226. )
  227. ROCM_HOME = _find_rocm_home() if (torch.cuda._is_compiled() and torch.version.hip) else None
  228. HIP_HOME = _join_rocm_home('hip') if ROCM_HOME else None
  229. IS_HIP_EXTENSION = bool(ROCM_HOME is not None and torch.version.hip is not None)
  230. ROCM_VERSION = None
  231. if torch.version.hip is not None:
  232. ROCM_VERSION = tuple(int(v) for v in torch.version.hip.split('.')[:2])
  233. CUDA_HOME = _find_cuda_home() if (torch.cuda._is_compiled() and torch.version.cuda) else None
  234. CUDNN_HOME = os.environ.get('CUDNN_HOME') or os.environ.get('CUDNN_PATH')
  235. SYCL_HOME = _find_sycl_home() if torch.xpu._is_compiled() else None
  236. WINDOWS_CUDA_HOME = os.environ.get('WINDOWS_CUDA_HOME') # used for AOTI cross-compilation
  237. # PyTorch releases have the version pattern major.minor.patch, whereas when
  238. # PyTorch is built from source, we append the git commit hash, which gives
  239. # it the below pattern.
  240. BUILT_FROM_SOURCE_VERSION_PATTERN = re.compile(r'\d+\.\d+\.\d+\w+\+\w+')
  241. COMMON_MSVC_FLAGS = ['/MD', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018', '/wd4190', '/wd4624', '/wd4067', '/wd4068', '/EHsc']
  242. MSVC_IGNORE_CUDAFE_WARNINGS = [
  243. 'base_class_has_different_dll_interface',
  244. 'field_without_dll_interface',
  245. 'dll_interface_conflict_none_assumed',
  246. 'dll_interface_conflict_dllexport_assumed'
  247. ]
  248. COMMON_NVCC_FLAGS = [
  249. '-D__CUDA_NO_HALF_OPERATORS__',
  250. '-D__CUDA_NO_HALF_CONVERSIONS__',
  251. '-D__CUDA_NO_BFLOAT16_CONVERSIONS__',
  252. '-D__CUDA_NO_HALF2_OPERATORS__',
  253. '--expt-relaxed-constexpr'
  254. ]
  255. COMMON_HIP_FLAGS = [
  256. '-D__HIP_PLATFORM_AMD__=1',
  257. '-DUSE_ROCM=1',
  258. '-DHIPBLAS_V2',
  259. ]
  260. if not IS_WINDOWS:
  261. COMMON_HIP_FLAGS.append('-fPIC')
  262. COMMON_HIPCC_FLAGS = [
  263. '-DCUDA_HAS_FP16=1',
  264. '-D__HIP_NO_HALF_OPERATORS__=1',
  265. '-D__HIP_NO_HALF_CONVERSIONS__=1',
  266. '-DHIP_ENABLE_WARP_SYNC_BUILTINS=1'
  267. ]
  268. if IS_WINDOWS:
  269. # Compatibility flags, similar to those set in cmake/Dependencies.cmake.
  270. COMMON_HIPCC_FLAGS.append('-fms-extensions')
  271. # Suppress warnings about dllexport.
  272. COMMON_HIPCC_FLAGS.append('-Wno-ignored-attributes')
  273. def _get_icpx_version() -> str:
  274. icpx = 'icx' if IS_WINDOWS else 'icpx'
  275. compiler_info = subprocess.check_output([icpx, '--version'])
  276. match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.decode().strip())
  277. version = ['0', '0', '0'] if match is None else list(match.groups())
  278. version = list(map(int, version))
  279. if len(version) != 3:
  280. raise AssertionError("Failed to parse DPC++ compiler version")
  281. # Aligning version format with what torch.version.xpu() returns
  282. return f"{version[0]}{version[1]:02}{version[2]:02}"
  283. def _get_sycl_arch_list():
  284. if 'TORCH_XPU_ARCH_LIST' in os.environ:
  285. return os.environ.get('TORCH_XPU_ARCH_LIST')
  286. arch_list = torch.xpu.get_arch_list()
  287. # Dropping dg2* archs since they lack hardware support for fp64 and require
  288. # special consideration from the user. If needed these platforms can
  289. # be requested thru TORCH_XPU_ARCH_LIST environment variable.
  290. arch_list = [x for x in arch_list if not x.startswith('dg2')]
  291. return ','.join(arch_list)
  292. # If arch list returned by _get_sycl_arch_list() is empty, then sycl kernels will be compiled
  293. # for default spir64 target and avoid device specific compilations entirely. Further, kernels
  294. # will be JIT compiled at runtime.
  295. def _append_sycl_targets_if_missing(cflags) -> None:
  296. if any(flag.startswith('-fsycl-targets=') for flag in cflags):
  297. # do nothing: user has manually specified sycl targets
  298. return
  299. if _get_sycl_arch_list() != '':
  300. # AOT (spir64_gen) + JIT (spir64)
  301. cflags.append('-fsycl-targets=spir64_gen,spir64')
  302. else:
  303. # JIT (spir64)
  304. cflags.append('-fsycl-targets=spir64')
  305. def _get_sycl_device_flags(cflags):
  306. # We need last occurrence of -fsycl-targets as it will be the one taking effect.
  307. # So searching in reversed list.
  308. flags = [f for f in reversed(cflags) if f.startswith('-fsycl-targets=')]
  309. if not flags:
  310. raise AssertionError("bug: -fsycl-targets should have been amended to cflags")
  311. arch_list = _get_sycl_arch_list()
  312. if arch_list != '':
  313. flags += [f'-Xs "-device {arch_list}"']
  314. return flags
  315. _COMMON_SYCL_FLAGS = [
  316. '-fsycl',
  317. ]
  318. _SYCL_DLINK_FLAGS = [
  319. *_COMMON_SYCL_FLAGS,
  320. '-fsycl-link',
  321. '--offload-compress',
  322. ]
  323. JIT_EXTENSION_VERSIONER = ExtensionVersioner()
  324. PLAT_TO_VCVARS = {
  325. 'win32' : 'x86',
  326. 'win-amd64' : 'x86_amd64',
  327. }
  328. min_supported_cpython = "0x030A0000" # Python 3.10 hexcode
  329. def get_cxx_compiler():
  330. if IS_WINDOWS:
  331. compiler = os.environ.get('CXX', 'cl')
  332. else:
  333. compiler = os.environ.get('CXX', 'c++')
  334. return compiler
  335. def _is_binary_build() -> bool:
  336. return not BUILT_FROM_SOURCE_VERSION_PATTERN.match(torch.version.__version__)
  337. def _accepted_compilers_for_platform() -> list[str]:
  338. # gnu-c++ and gnu-cc are the conda gcc compilers
  339. return ['clang++', 'clang'] if IS_MACOS else ['g++', 'gcc', 'gnu-c++', 'gnu-cc', 'clang++', 'clang']
  340. def _maybe_write(filename, new_content) -> None:
  341. r'''
  342. Equivalent to writing the content into the file but will not touch the file
  343. if it already had the right content (to avoid triggering recompile).
  344. '''
  345. if os.path.exists(filename):
  346. with open(filename) as f:
  347. content = f.read()
  348. if content == new_content:
  349. # The file already contains the right thing!
  350. return
  351. with open(filename, 'w') as source_file:
  352. source_file.write(new_content)
  353. def get_default_build_root() -> str:
  354. """
  355. Return the path to the root folder under which extensions will built.
  356. For each extension module built, there will be one folder underneath the
  357. folder returned by this function. For example, if ``p`` is the path
  358. returned by this function and ``ext`` the name of an extension, the build
  359. folder for the extension will be ``p/ext``.
  360. This directory is **user-specific** so that multiple users on the same
  361. machine won't meet permission issues.
  362. """
  363. return os.path.realpath(torch._appdirs.user_cache_dir(appname='torch_extensions'))
  364. def check_compiler_ok_for_platform(compiler: str) -> bool:
  365. """
  366. Verify that the compiler is the expected one for the current platform.
  367. Args:
  368. compiler (str): The compiler executable to check.
  369. Returns:
  370. True if the compiler is gcc/g++ on Linux or clang/clang++ on macOS,
  371. and always True for Windows.
  372. """
  373. if IS_WINDOWS:
  374. return True
  375. compiler_path = shutil.which(compiler)
  376. if compiler_path is None:
  377. return False
  378. # Use os.path.realpath to resolve any symlinks, in particular from 'c++' to e.g. 'g++'.
  379. compiler_path = os.path.realpath(compiler_path)
  380. # Check the compiler name
  381. if any(name in compiler_path for name in _accepted_compilers_for_platform()):
  382. return True
  383. # If compiler wrapper is used try to infer the actual compiler by invoking it with -v flag
  384. env = os.environ.copy()
  385. env['LC_ALL'] = 'C' # Don't localize output
  386. try:
  387. version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS)
  388. except subprocess.CalledProcessError:
  389. # If '-v' fails, try '--version'
  390. version_string = subprocess.check_output([compiler, '--version'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS)
  391. if IS_LINUX:
  392. # Check for 'gcc' or 'g++' for sccache wrapper
  393. pattern = re.compile("^COLLECT_GCC=(.*)$", re.MULTILINE)
  394. results = re.findall(pattern, version_string)
  395. if len(results) != 1:
  396. # Clang is also a supported compiler on Linux
  397. # Though on Ubuntu it's sometimes called "Ubuntu clang version"
  398. return 'clang version' in version_string
  399. compiler_path = os.path.realpath(results[0].strip())
  400. # On RHEL/CentOS c++ is a gcc compiler wrapper
  401. if os.path.basename(compiler_path) == 'c++' and 'gcc version' in version_string:
  402. return True
  403. return any(name in compiler_path for name in _accepted_compilers_for_platform())
  404. if IS_MACOS:
  405. # Check for 'clang' or 'clang++'
  406. return version_string.startswith("Apple clang")
  407. return False
  408. def get_compiler_abi_compatibility_and_version(compiler) -> tuple[bool, TorchVersion]:
  409. """
  410. Determine if the given compiler is ABI-compatible with PyTorch alongside its version.
  411. Args:
  412. compiler (str): The compiler executable name to check (e.g. ``g++``).
  413. Must be executable in a shell process.
  414. Returns:
  415. A tuple that contains a boolean that defines if the compiler is (likely) ABI-incompatible with PyTorch,
  416. followed by a `TorchVersion` string that contains the compiler version separated by dots.
  417. """
  418. if not _is_binary_build():
  419. return (True, TorchVersion('0.0.0'))
  420. if os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') in ['ON', '1', 'YES', 'TRUE', 'Y']:
  421. return (True, TorchVersion('0.0.0'))
  422. # First check if the compiler is one of the expected ones for the particular platform.
  423. if not check_compiler_ok_for_platform(compiler):
  424. logger.warning(WRONG_COMPILER_WARNING, compiler, _accepted_compilers_for_platform()[0], sys.platform, _accepted_compilers_for_platform()[0], compiler, compiler)
  425. return (False, TorchVersion('0.0.0'))
  426. if IS_MACOS:
  427. # There is no particular minimum version we need for clang, so we're good here.
  428. return (True, TorchVersion('0.0.0'))
  429. try:
  430. if IS_LINUX:
  431. minimum_required_version = MINIMUM_GCC_VERSION
  432. compiler_info = subprocess.check_output([compiler, '-dumpfullversion', '-dumpversion'])
  433. else:
  434. minimum_required_version = MINIMUM_MSVC_VERSION
  435. compiler_info = subprocess.check_output(compiler, stderr=subprocess.STDOUT)
  436. match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.decode(*SUBPROCESS_DECODE_ARGS).strip())
  437. version = ['0', '0', '0'] if match is None else list(match.groups())
  438. except (subprocess.CalledProcessError, OSError):
  439. logger.warning('Error checking compiler version for %s', compiler, exc_info=True)
  440. return (False, TorchVersion('0.0.0'))
  441. # convert alphanumeric string to numeric string
  442. # amdclang++ returns str like 0.0.0git, others return 0.0.0
  443. numeric_version = [re.sub(r'\D', '', v) for v in version]
  444. if tuple(map(int, numeric_version)) >= minimum_required_version:
  445. return (True, TorchVersion('.'.join(numeric_version)))
  446. compiler = f'{compiler} {".".join(numeric_version)}'
  447. logger.warning(ABI_INCOMPATIBILITY_WARNING, compiler)
  448. return (False, TorchVersion('.'.join(numeric_version)))
  449. def _check_cuda_version(compiler_name: str, compiler_version: TorchVersion) -> None:
  450. if not CUDA_HOME:
  451. raise RuntimeError(CUDA_NOT_FOUND_MESSAGE)
  452. nvcc = os.path.join(CUDA_HOME, 'bin', 'nvcc.exe' if IS_WINDOWS else 'nvcc')
  453. if not os.path.exists(nvcc):
  454. raise FileNotFoundError(f"nvcc not found at '{nvcc}'. Ensure CUDA path '{CUDA_HOME}' is correct.")
  455. cuda_version_str = subprocess.check_output([nvcc, '--version']).strip().decode(*SUBPROCESS_DECODE_ARGS)
  456. cuda_version = re.search(r'release (\d+[.]\d+)', cuda_version_str)
  457. if cuda_version is None:
  458. return
  459. cuda_str_version = cuda_version.group(1)
  460. cuda_ver = Version(cuda_str_version)
  461. if torch.version.cuda is None:
  462. return
  463. torch_cuda_version = Version(torch.version.cuda)
  464. if cuda_ver != torch_cuda_version:
  465. # major/minor attributes are only available in setuptools>=49.4.0
  466. if getattr(cuda_ver, "major", None) is None:
  467. raise ValueError("setuptools>=49.4.0 is required")
  468. if cuda_ver.major != torch_cuda_version.major:
  469. raise RuntimeError(CUDA_MISMATCH_MESSAGE, cuda_str_version, torch.version.cuda)
  470. logger.warning(CUDA_MISMATCH_WARN, cuda_str_version, torch.version.cuda)
  471. if not (sys.platform.startswith('linux') and
  472. os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') not in ['ON', '1', 'YES', 'TRUE', 'Y'] and
  473. _is_binary_build()):
  474. return
  475. cuda_compiler_bounds: VersionMap = CUDA_CLANG_VERSIONS if compiler_name.startswith('clang') else CUDA_GCC_VERSIONS
  476. if cuda_str_version not in cuda_compiler_bounds:
  477. logger.warning('There are no %s version bounds defined for CUDA version %s', compiler_name, cuda_str_version)
  478. else:
  479. min_compiler_version, max_excl_compiler_version = cuda_compiler_bounds[cuda_str_version]
  480. # Special case for 11.4.0, which has lower compiler bounds than 11.4.1
  481. if "V11.4.48" in cuda_version_str and cuda_compiler_bounds == CUDA_GCC_VERSIONS:
  482. max_excl_compiler_version = (11, 0)
  483. min_compiler_version_str = '.'.join(map(str, min_compiler_version))
  484. max_excl_compiler_version_str = '.'.join(map(str, max_excl_compiler_version))
  485. version_bound_str = f'>={min_compiler_version_str}, <{max_excl_compiler_version_str}'
  486. if compiler_version < TorchVersion(min_compiler_version_str):
  487. raise RuntimeError(
  488. f'The current installed version of {compiler_name} ({compiler_version}) is less '
  489. f'than the minimum required version by CUDA {cuda_str_version} ({min_compiler_version_str}). '
  490. f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).'
  491. )
  492. if compiler_version >= TorchVersion(max_excl_compiler_version_str):
  493. raise RuntimeError(
  494. f'The current installed version of {compiler_name} ({compiler_version}) is greater '
  495. f'than the maximum required version by CUDA {cuda_str_version}. '
  496. f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).'
  497. )
  498. # Specify Visual Studio C runtime library for hipcc
  499. def _set_hipcc_runtime_lib(is_standalone, debug) -> None:
  500. if is_standalone:
  501. if debug:
  502. COMMON_HIP_FLAGS.append('-fms-runtime-lib=static_dbg')
  503. else:
  504. COMMON_HIP_FLAGS.append('-fms-runtime-lib=static')
  505. else:
  506. if debug:
  507. COMMON_HIP_FLAGS.append('-fms-runtime-lib=dll_dbg')
  508. else:
  509. COMMON_HIP_FLAGS.append('-fms-runtime-lib=dll')
  510. def _append_sycl_std_if_no_std_present(cflags) -> None:
  511. if not any(flag.startswith('-sycl-std=') for flag in cflags):
  512. cflags.append('-sycl-std=2020')
  513. def _wrap_sycl_host_flags(cflags):
  514. host_cflags = []
  515. host_cxx = get_cxx_compiler()
  516. if IS_WINDOWS:
  517. for flag in cflags:
  518. if flag.startswith("-I"):
  519. flag = flag.replace("\\", "\\\\").replace("-I", "/I")
  520. else:
  521. flag = flag.replace("-D", "/D")
  522. flag = flag.replace('"', '\\"')
  523. host_cflags.append(flag)
  524. joined_host_cflags = ' '.join(host_cflags)
  525. external_include = _join_sycl_home("include").replace("\\", "\\\\")
  526. # Some versions of DPC++ compiler pass paths to SYCL headers as user include paths (`-I`) rather
  527. # than system paths (`-isystem`). This makes host compiler to report warnings encountered in the
  528. # SYCL headers, such as deprecated warnings, even if warmed API is not actually used in the program.
  529. # We expect that this issue will be addressed in the later version of DPC++ compiler. To workaround the
  530. # issue now we wrap paths to SYCL headers in `/external:I`. Warning free compilation is especially important
  531. # for Windows build as `/sdl` compilation flag assumes that and we will fail compilation otherwise.
  532. wrapped_host_cflags = [
  533. f"-fsycl-host-compiler={host_cxx}",
  534. f'-fsycl-host-compiler-options="\\"/external:I{external_include}\\" /external:W0 {joined_host_cflags}"',
  535. ]
  536. else:
  537. joined_host_cflags = ' '.join(cflags)
  538. wrapped_host_cflags = [
  539. f"-fsycl-host-compiler={host_cxx}",
  540. shlex.quote(f"-fsycl-host-compiler-options={joined_host_cflags}"),
  541. ]
  542. return wrapped_host_cflags
  543. class BuildExtension(build_ext):
  544. """
  545. A custom :mod:`setuptools` build extension .
  546. This :class:`setuptools.build_ext` subclass takes care of passing the
  547. minimum required compiler flags (e.g. ``-std=c++17``) as well as mixed
  548. C++/CUDA/SYCL compilation (and support for CUDA/SYCL files in general).
  549. When using :class:`BuildExtension`, it is allowed to supply a dictionary
  550. for ``extra_compile_args`` (rather than the usual list) that maps from
  551. languages/compilers (the only expected values are ``cxx``, ``nvcc`` or
  552. ``sycl``) to a list of additional compiler flags to supply to the compiler.
  553. This makes it possible to supply different flags to the C++, CUDA and SYCL
  554. compiler during mixed compilation.
  555. ``use_ninja`` (bool): If ``use_ninja`` is ``True`` (default), then we
  556. attempt to build using the Ninja backend. Ninja greatly speeds up
  557. compilation compared to the standard ``setuptools.build_ext``.
  558. Fallbacks to the standard distutils backend if Ninja is not available.
  559. .. note::
  560. By default, the Ninja backend uses #CPUS + 2 workers to build the
  561. extension. This may use up too many resources on some systems. One
  562. can control the number of workers by setting the `MAX_JOBS` environment
  563. variable to a non-negative number.
  564. """
  565. @classmethod
  566. def with_options(cls, **options):
  567. """Return a subclass with alternative constructor that extends any original keyword arguments to the original constructor with the given options."""
  568. class cls_with_options(cls): # type: ignore[misc, valid-type]
  569. def __init__(self, *args, **kwargs) -> None:
  570. kwargs.update(options)
  571. super().__init__(*args, **kwargs)
  572. return cls_with_options
  573. def __init__(self, *args, **kwargs) -> None:
  574. super().__init__(*args, **kwargs)
  575. self.no_python_abi_suffix = kwargs.get("no_python_abi_suffix", False)
  576. self.use_ninja = kwargs.get('use_ninja', True)
  577. if self.use_ninja:
  578. # Test if we can use ninja. Fallback otherwise.
  579. msg = ('Attempted to use ninja as the BuildExtension backend but '
  580. '%s. Falling back to using the slow distutils backend.')
  581. if not is_ninja_available():
  582. logger.warning(msg, 'we could not find ninja.')
  583. self.use_ninja = False
  584. def finalize_options(self) -> None:
  585. super().finalize_options()
  586. if self.use_ninja:
  587. self.force = True
  588. def build_extensions(self) -> None:
  589. compiler_name, compiler_version = self._check_abi()
  590. cuda_ext = False
  591. sycl_ext = False
  592. extension_iter = iter(self.extensions)
  593. extension = next(extension_iter, None)
  594. while not (cuda_ext and sycl_ext) and extension:
  595. for source in extension.sources:
  596. _, ext = os.path.splitext(source)
  597. if ext == '.cu':
  598. cuda_ext = True
  599. elif ext == '.sycl':
  600. sycl_ext = True
  601. # This check accounts on a case when cuda and sycl sources
  602. # are mixed in the same extension. We can stop checking
  603. # sources if both are found or there is no more sources.
  604. if cuda_ext and sycl_ext:
  605. break
  606. extension = next(extension_iter, None)
  607. if sycl_ext:
  608. if not self.use_ninja:
  609. raise AssertionError("ninja is required to build sycl extensions.")
  610. if cuda_ext and not IS_HIP_EXTENSION:
  611. _check_cuda_version(compiler_name, compiler_version)
  612. for extension in self.extensions:
  613. # Ensure at least an empty list of flags for 'cxx', 'nvcc' and 'sycl' when
  614. # extra_compile_args is a dict. Otherwise, default torch flags do
  615. # not get passed. Necessary when only one of 'cxx', 'nvcc' or 'sycl' is
  616. # passed to extra_compile_args in CUDAExtension or SyclExtension, i.e.
  617. # CUDAExtension(..., extra_compile_args={'cxx': [...]})
  618. # or
  619. # CUDAExtension(..., extra_compile_args={'nvcc': [...]})
  620. if isinstance(extension.extra_compile_args, dict):
  621. for ext in ['cxx', 'nvcc', 'sycl']:
  622. if ext not in extension.extra_compile_args:
  623. extension.extra_compile_args[ext] = []
  624. self._add_compile_flag(extension, '-DTORCH_API_INCLUDE_EXTENSION_H')
  625. if IS_HIP_EXTENSION:
  626. self._hipify_compile_flags(extension)
  627. if extension.py_limited_api:
  628. # compile any extension that has passed in py_limited_api to the
  629. # Extension constructor with the Py_LIMITED_API flag set to our
  630. # min supported CPython version.
  631. # See https://docs.python.org/3/c-api/stable.html#c.Py_LIMITED_API
  632. self._add_compile_flag(extension, f'-DPy_LIMITED_API={min_supported_cpython}')
  633. self._define_torch_extension_name(extension)
  634. if 'nvcc_dlink' in extension.extra_compile_args:
  635. if not self.use_ninja:
  636. raise AssertionError(
  637. f"With dlink=True, ninja is required to build cuda extension {extension.name}."
  638. )
  639. # Register .cu, .cuh, .hip, .mm and .sycl as valid source extensions.
  640. # NOTE: At the moment .sycl is not a standard extension for SYCL supported
  641. # by compiler. Here we introduce a torch level convention that SYCL sources
  642. # should have .sycl file extension.
  643. self.compiler.src_extensions += ['.cu', '.cuh', '.hip', '.sycl']
  644. if torch.backends.mps.is_built():
  645. self.compiler.src_extensions += ['.mm']
  646. # Save the original _compile method for later.
  647. if self.compiler.compiler_type == 'msvc':
  648. self.compiler._cpp_extensions += ['.cu', '.cuh']
  649. original_compile = self.compiler.compile
  650. original_spawn = self.compiler.spawn
  651. else:
  652. original_compile = self.compiler._compile
  653. def append_std17_if_no_std_present(cflags) -> None:
  654. # NVCC does not allow multiple -std to be passed, so we avoid
  655. # overriding the option if the user explicitly passed it.
  656. cpp_format_prefix = '/{}:' if self.compiler.compiler_type == 'msvc' else '-{}='
  657. cpp_flag_prefix = cpp_format_prefix.format('std')
  658. cpp_flag = cpp_flag_prefix + 'c++17'
  659. if not any(flag.startswith(cpp_flag_prefix) for flag in cflags):
  660. cflags.append(cpp_flag)
  661. def unix_cuda_flags(cflags):
  662. cflags = (COMMON_NVCC_FLAGS +
  663. ['--compiler-options', "'-fPIC'"] +
  664. cflags + _get_cuda_arch_flags(cflags))
  665. # NVCC does not allow multiple -ccbin/--compiler-bindir to be passed, so we avoid
  666. # overriding the option if the user explicitly passed it.
  667. _ccbin = os.getenv("CC")
  668. if (
  669. _ccbin is not None
  670. and not any(flag.startswith(('-ccbin', '--compiler-bindir')) for flag in cflags)
  671. ):
  672. cflags.extend(['-ccbin', _ccbin])
  673. return cflags
  674. def convert_to_absolute_paths_inplace(paths) -> None:
  675. # Helper function. See Note [Absolute include_dirs]
  676. if paths is not None:
  677. for i in range(len(paths)):
  678. if not os.path.isabs(paths[i]):
  679. paths[i] = os.path.abspath(paths[i])
  680. def unix_wrap_single_compile(obj, src, ext, cc_args, extra_postargs, pp_opts) -> None:
  681. # Copy before we make any modifications.
  682. cflags = copy.deepcopy(extra_postargs)
  683. try:
  684. original_compiler = self.compiler.compiler_so
  685. if _is_cuda_file(src):
  686. nvcc = [_join_rocm_home('bin', 'hipcc') if IS_HIP_EXTENSION else _join_cuda_home('bin', 'nvcc')]
  687. self.compiler.set_executable('compiler_so', nvcc)
  688. if isinstance(cflags, dict):
  689. cflags = cflags['nvcc']
  690. if IS_HIP_EXTENSION:
  691. cflags = COMMON_HIPCC_FLAGS + cflags + _get_rocm_arch_flags(cflags)
  692. else:
  693. cflags = unix_cuda_flags(cflags)
  694. elif isinstance(cflags, dict):
  695. cflags = cflags['cxx']
  696. if IS_HIP_EXTENSION:
  697. cflags = COMMON_HIP_FLAGS + cflags
  698. append_std17_if_no_std_present(cflags)
  699. original_compile(obj, src, ext, cc_args, cflags, pp_opts)
  700. finally:
  701. # Put the original compiler back in place.
  702. self.compiler.set_executable('compiler_so', original_compiler)
  703. def unix_wrap_ninja_compile(sources,
  704. output_dir=None,
  705. macros=None,
  706. include_dirs=None,
  707. debug=0,
  708. extra_preargs=None,
  709. extra_postargs=None,
  710. depends=None):
  711. r"""Compiles sources by outputting a ninja file and running it."""
  712. # NB: I copied some lines from self.compiler (which is an instance
  713. # of distutils.UnixCCompiler). See the following link.
  714. # https://github.com/python/cpython/blob/f03a8f8d5001963ad5b5b28dbd95497e9cc15596/Lib/distutils/ccompiler.py#L564-L567 # codespell:ignore
  715. # This can be fragile, but a lot of other repos also do this
  716. # (see https://github.com/search?q=_setup_compile&type=Code)
  717. # so it is probably OK; we'll also get CI signal if/when
  718. # we update our python version (which is when distutils can be
  719. # upgraded)
  720. # Use absolute path for output_dir so that the object file paths
  721. # (`objects`) get generated with absolute paths.
  722. # pyrefly: ignore [no-matching-overload]
  723. output_dir = os.path.abspath(output_dir)
  724. # See Note [Absolute include_dirs]
  725. convert_to_absolute_paths_inplace(self.compiler.include_dirs)
  726. _, objects, extra_postargs, pp_opts, _ = \
  727. self.compiler._setup_compile(output_dir, macros,
  728. include_dirs, sources,
  729. depends, extra_postargs)
  730. common_cflags = self.compiler._get_cc_args(pp_opts, debug, extra_preargs)
  731. extra_cc_cflags = self.compiler.compiler_so[1:]
  732. with_cuda = any(map(_is_cuda_file, sources))
  733. with_sycl = any(map(_is_sycl_file, sources))
  734. if with_sycl and with_cuda:
  735. raise AssertionError(
  736. "cannot have both SYCL and CUDA files in the same extension"
  737. )
  738. # extra_postargs can be either:
  739. # - a dict mapping cxx/nvcc/sycl to extra flags
  740. # - a list of extra flags.
  741. if isinstance(extra_postargs, dict):
  742. post_cflags = extra_postargs['cxx']
  743. else:
  744. post_cflags = list(extra_postargs)
  745. if IS_HIP_EXTENSION:
  746. post_cflags = COMMON_HIP_FLAGS + post_cflags
  747. append_std17_if_no_std_present(post_cflags)
  748. cuda_post_cflags = None
  749. cuda_cflags = None
  750. if with_cuda:
  751. cuda_cflags = common_cflags
  752. if isinstance(extra_postargs, dict):
  753. cuda_post_cflags = extra_postargs['nvcc']
  754. else:
  755. cuda_post_cflags = list(extra_postargs)
  756. if IS_HIP_EXTENSION:
  757. cuda_post_cflags = cuda_post_cflags + _get_rocm_arch_flags(cuda_post_cflags)
  758. cuda_post_cflags = COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS + cuda_post_cflags
  759. else:
  760. cuda_post_cflags = unix_cuda_flags(cuda_post_cflags)
  761. append_std17_if_no_std_present(cuda_post_cflags)
  762. cuda_cflags = [shlex.quote(f) for f in cuda_cflags]
  763. cuda_post_cflags = [shlex.quote(f) for f in cuda_post_cflags]
  764. if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs:
  765. cuda_dlink_post_cflags = unix_cuda_flags(extra_postargs['nvcc_dlink'])
  766. cuda_dlink_post_cflags = [shlex.quote(f) for f in cuda_dlink_post_cflags]
  767. else:
  768. cuda_dlink_post_cflags = None
  769. sycl_post_cflags = None
  770. sycl_cflags = None
  771. sycl_dlink_post_cflags = None
  772. if with_sycl:
  773. sycl_cflags = extra_cc_cflags + common_cflags + _COMMON_SYCL_FLAGS
  774. if isinstance(extra_postargs, dict):
  775. sycl_post_cflags = extra_postargs['sycl']
  776. else:
  777. sycl_post_cflags = list(extra_postargs)
  778. _append_sycl_targets_if_missing(sycl_post_cflags)
  779. append_std17_if_no_std_present(sycl_cflags)
  780. _append_sycl_std_if_no_std_present(sycl_cflags)
  781. host_cflags = extra_cc_cflags + common_cflags + post_cflags
  782. append_std17_if_no_std_present(host_cflags)
  783. # escaping quoted arguments to pass them thru SYCL compiler
  784. icpx_version = _get_icpx_version()
  785. if int(icpx_version) >= 20250200:
  786. host_cflags = [item.replace('"', '\\"') for item in host_cflags]
  787. else:
  788. host_cflags = [item.replace('"', '\\\\"') for item in host_cflags]
  789. # Note the order: shlex.quote sycl_flags first, _wrap_sycl_host_flags
  790. # second. Reason is that sycl host flags are quoted, space containing
  791. # strings passed to SYCL compiler.
  792. sycl_cflags = [shlex.quote(f) for f in sycl_cflags]
  793. sycl_cflags += _wrap_sycl_host_flags(host_cflags)
  794. sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy()
  795. sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_post_cflags)
  796. sycl_post_cflags = [shlex.quote(f) for f in sycl_post_cflags]
  797. _write_ninja_file_and_compile_objects(
  798. sources=sources,
  799. objects=objects,
  800. cflags=[shlex.quote(f) for f in extra_cc_cflags + common_cflags],
  801. post_cflags=[shlex.quote(f) for f in post_cflags],
  802. cuda_cflags=cuda_cflags,
  803. cuda_post_cflags=cuda_post_cflags,
  804. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  805. sycl_cflags=sycl_cflags,
  806. sycl_post_cflags=sycl_post_cflags,
  807. sycl_dlink_post_cflags=sycl_dlink_post_cflags,
  808. build_directory=output_dir,
  809. verbose=True,
  810. with_cuda=with_cuda,
  811. with_sycl=with_sycl)
  812. # Return *all* object filenames, not just the ones we just built.
  813. return objects
  814. def win_cuda_flags(cflags):
  815. return (COMMON_NVCC_FLAGS +
  816. cflags + _get_cuda_arch_flags(cflags))
  817. def win_hip_flags(cflags):
  818. return (COMMON_HIPCC_FLAGS + COMMON_HIP_FLAGS + cflags + _get_rocm_arch_flags(cflags))
  819. def win_filter_msvc_include_dirs(pp_opts) -> list[str]:
  820. """Filter out MSVC include dirs from pp_opts for oneAPI 2025.3+."""
  821. # oneAPI 2025.3+ changed include path ordering to match MSVC behavior.
  822. # Filter out MSVC headers to avoid conflicting declarations with oneAPI's std headers.
  823. icpx_version = int(_get_icpx_version())
  824. if icpx_version >= 20250300:
  825. vc_tools_dir = os.path.normcase(os.environ.get('VCToolsInstallDir', ''))
  826. if vc_tools_dir:
  827. pp_opts = [
  828. path for path in pp_opts
  829. if vc_tools_dir not in os.path.normcase(path)
  830. ]
  831. return pp_opts
  832. def win_wrap_single_compile(sources,
  833. output_dir=None,
  834. macros=None,
  835. include_dirs=None,
  836. debug=0,
  837. extra_preargs=None,
  838. extra_postargs=None,
  839. depends=None):
  840. self.cflags = copy.deepcopy(extra_postargs)
  841. extra_postargs = None
  842. def spawn(cmd):
  843. # Using regex to match src, obj and include files
  844. src_regex = re.compile('/T(p|c)(.*)')
  845. src_list = [
  846. m.group(2) for m in (src_regex.match(elem) for elem in cmd)
  847. if m
  848. ]
  849. obj_regex = re.compile('/Fo(.*)') # codespell:ignore
  850. obj_list = [
  851. m.group(1) for m in (obj_regex.match(elem) for elem in cmd)
  852. if m
  853. ]
  854. include_regex = re.compile(r'((\-|\/)I.*)')
  855. include_list = [
  856. m.group(1)
  857. for m in (include_regex.match(elem) for elem in cmd) if m
  858. ]
  859. if len(src_list) >= 1 and len(obj_list) >= 1:
  860. src = src_list[0]
  861. obj = obj_list[0]
  862. if _is_cuda_file(src):
  863. if IS_HIP_EXTENSION:
  864. nvcc = _get_hipcc_path()
  865. else:
  866. nvcc = _join_cuda_home('bin', 'nvcc')
  867. if isinstance(self.cflags, dict):
  868. cflags = self.cflags['nvcc']
  869. elif isinstance(self.cflags, list):
  870. cflags = self.cflags
  871. else:
  872. cflags = []
  873. if IS_HIP_EXTENSION:
  874. cflags = win_hip_flags(cflags)
  875. else:
  876. cflags = win_cuda_flags(cflags) + ['-std=c++17', '--use-local-env']
  877. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  878. cflags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cflags
  879. for flag in COMMON_MSVC_FLAGS:
  880. cflags = ['-Xcompiler', flag] + cflags
  881. cmd = [nvcc, '-c', src, '-o', obj] + include_list + cflags
  882. elif isinstance(self.cflags, dict):
  883. cflags = COMMON_MSVC_FLAGS + self.cflags['cxx']
  884. append_std17_if_no_std_present(cflags)
  885. cmd += cflags
  886. elif isinstance(self.cflags, list):
  887. cflags = COMMON_MSVC_FLAGS + self.cflags
  888. append_std17_if_no_std_present(cflags)
  889. cmd += cflags
  890. return original_spawn(cmd)
  891. try:
  892. self.compiler.spawn = spawn
  893. return original_compile(sources, output_dir, macros,
  894. include_dirs, debug, extra_preargs,
  895. extra_postargs, depends)
  896. finally:
  897. self.compiler.spawn = original_spawn
  898. def win_wrap_ninja_compile(sources,
  899. output_dir=None,
  900. macros=None,
  901. include_dirs=None,
  902. debug=0,
  903. extra_preargs=None,
  904. extra_postargs=None,
  905. depends=None,
  906. is_standalone=False):
  907. if not self.compiler.initialized:
  908. self.compiler.initialize()
  909. # pyrefly: ignore [no-matching-overload]
  910. output_dir = os.path.abspath(output_dir)
  911. # Note [Absolute include_dirs]
  912. # Convert relative path in self.compiler.include_dirs to absolute path if any.
  913. # For ninja build, the build location is not local, but instead, the build happens
  914. # in a script-created build folder. Thus, relative paths lose their correctness.
  915. # To be consistent with jit extension, we allow user to enter relative include_dirs
  916. # in setuptools.setup, and we convert the relative path to absolute path here.
  917. convert_to_absolute_paths_inplace(self.compiler.include_dirs)
  918. _, objects, extra_postargs, pp_opts, _ = \
  919. self.compiler._setup_compile(output_dir, macros,
  920. include_dirs, sources,
  921. depends, extra_postargs)
  922. # Replace space with \ when using hipcc (hipcc passes includes to clang without ""s so clang sees space in include paths as new argument)
  923. if IS_HIP_EXTENSION:
  924. pp_opts = ["-I{}".format(s[2:].replace(" ", "\\")) if s.startswith('-I') else s for s in pp_opts]
  925. common_cflags = extra_preargs or []
  926. cflags = []
  927. if debug:
  928. cflags.extend(self.compiler.compile_options_debug)
  929. else:
  930. cflags.extend(self.compiler.compile_options)
  931. cflags = cflags + common_cflags + pp_opts + COMMON_MSVC_FLAGS
  932. if IS_HIP_EXTENSION:
  933. _set_hipcc_runtime_lib(is_standalone, debug)
  934. common_cflags.extend(COMMON_HIP_FLAGS)
  935. else:
  936. common_cflags.extend(COMMON_MSVC_FLAGS)
  937. with_cuda = any(map(_is_cuda_file, sources))
  938. with_sycl = any(map(_is_sycl_file, sources))
  939. if with_sycl and with_cuda:
  940. raise AssertionError(
  941. "cannot have both SYCL and CUDA files in the same extension"
  942. )
  943. # extra_postargs can be either:
  944. # - a dict mapping cxx/nvcc to extra flags
  945. # - a list of extra flags.
  946. if isinstance(extra_postargs, dict):
  947. post_cflags = extra_postargs['cxx']
  948. else:
  949. post_cflags = list(extra_postargs)
  950. if IS_HIP_EXTENSION:
  951. post_cflags = COMMON_HIP_FLAGS + post_cflags
  952. append_std17_if_no_std_present(post_cflags)
  953. cuda_post_cflags = None
  954. cuda_cflags = None
  955. if with_cuda:
  956. cuda_cflags = ['-std=c++17']
  957. for common_cflag in common_cflags:
  958. cuda_cflags.append('-Xcompiler')
  959. cuda_cflags.append(common_cflag)
  960. if not IS_HIP_EXTENSION:
  961. cuda_cflags.append('--use-local-env')
  962. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  963. cuda_cflags.append('-Xcudafe')
  964. cuda_cflags.append('--diag_suppress=' + ignore_warning)
  965. cuda_cflags.extend(pp_opts)
  966. if isinstance(extra_postargs, dict):
  967. cuda_post_cflags = extra_postargs['nvcc']
  968. else:
  969. cuda_post_cflags = list(extra_postargs)
  970. if IS_HIP_EXTENSION:
  971. cuda_post_cflags = win_hip_flags(cuda_post_cflags)
  972. else:
  973. cuda_post_cflags = win_cuda_flags(cuda_post_cflags)
  974. cflags = _nt_quote_args(cflags)
  975. post_cflags = _nt_quote_args(post_cflags)
  976. if with_cuda:
  977. cuda_cflags = _nt_quote_args(cuda_cflags)
  978. cuda_post_cflags = _nt_quote_args(cuda_post_cflags)
  979. if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs:
  980. cuda_dlink_post_cflags = win_cuda_flags(extra_postargs['nvcc_dlink'])
  981. else:
  982. cuda_dlink_post_cflags = None
  983. sycl_cflags = None
  984. sycl_post_cflags = None
  985. sycl_dlink_post_cflags = None
  986. if with_sycl:
  987. sycl_cflags = common_cflags + win_filter_msvc_include_dirs(pp_opts) + _COMMON_SYCL_FLAGS
  988. if isinstance(extra_postargs, dict):
  989. sycl_post_cflags = extra_postargs['sycl']
  990. else:
  991. sycl_post_cflags = list(extra_postargs)
  992. _append_sycl_targets_if_missing(sycl_post_cflags)
  993. append_std17_if_no_std_present(sycl_cflags)
  994. _append_sycl_std_if_no_std_present(sycl_cflags)
  995. host_cflags = common_cflags + pp_opts + post_cflags
  996. append_std17_if_no_std_present(host_cflags)
  997. sycl_cflags = _nt_quote_args(sycl_cflags)
  998. host_cflags = _nt_quote_args(host_cflags)
  999. sycl_cflags += _wrap_sycl_host_flags(host_cflags)
  1000. sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy()
  1001. sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_post_cflags)
  1002. sycl_post_cflags = _nt_quote_args(sycl_post_cflags)
  1003. _write_ninja_file_and_compile_objects(
  1004. sources=sources,
  1005. objects=objects,
  1006. cflags=cflags,
  1007. post_cflags=post_cflags,
  1008. cuda_cflags=cuda_cflags,
  1009. cuda_post_cflags=cuda_post_cflags,
  1010. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  1011. sycl_cflags=sycl_cflags,
  1012. sycl_post_cflags=sycl_post_cflags,
  1013. sycl_dlink_post_cflags=sycl_dlink_post_cflags,
  1014. build_directory=output_dir,
  1015. verbose=True,
  1016. with_cuda=with_cuda,
  1017. with_sycl=with_sycl)
  1018. # Return *all* object filenames, not just the ones we just built.
  1019. return objects
  1020. # Monkey-patch the _compile or compile method.
  1021. # https://github.com/python/cpython/blob/dc0284ee8f7a270b6005467f26d8e5773d76e959/Lib/distutils/ccompiler.py#L511 # codespell:ignore
  1022. if self.compiler.compiler_type == 'msvc':
  1023. if self.use_ninja:
  1024. self.compiler.compile = win_wrap_ninja_compile
  1025. else:
  1026. self.compiler.compile = win_wrap_single_compile
  1027. else:
  1028. if self.use_ninja:
  1029. self.compiler.compile = unix_wrap_ninja_compile
  1030. else:
  1031. self.compiler._compile = unix_wrap_single_compile
  1032. build_ext.build_extensions(self)
  1033. def get_ext_filename(self, ext_name):
  1034. # Get the original shared library name. For Python 3, this name will be
  1035. # suffixed with "<SOABI>.so", where <SOABI> will be something like
  1036. # cpython-37m-x86_64-linux-gnu.
  1037. ext_filename = super().get_ext_filename(ext_name)
  1038. # If `no_python_abi_suffix` is `True`, we omit the Python 3 ABI
  1039. # component. This makes building shared libraries with setuptools that
  1040. # aren't Python modules nicer.
  1041. if self.no_python_abi_suffix:
  1042. # The parts will be e.g. ["my_extension", "cpython-37m-x86_64-linux-gnu", "so"].
  1043. ext_filename_parts = ext_filename.split('.')
  1044. # Remove ABI component only if it actually exists in a file name, see gh-170542.
  1045. if len(ext_filename_parts) > 2:
  1046. # Omit the second to last element.
  1047. without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:]
  1048. ext_filename = '.'.join(without_abi)
  1049. return ext_filename
  1050. def get_export_symbols(self, ext):
  1051. if IS_WINDOWS:
  1052. # Skips exporting the module "PyInit_" function that the
  1053. # distutils Extension.get_export_symbols would add to
  1054. # ext.export_symbols. Only relevant for Windows builds.
  1055. return ext.export_symbols
  1056. return super().get_export_symbols(ext)
  1057. def _check_abi(self) -> tuple[str, TorchVersion]:
  1058. # On some platforms, like Windows, compiler_cxx is not available.
  1059. if hasattr(self.compiler, 'compiler_cxx'):
  1060. compiler = self.compiler.compiler_cxx[0]
  1061. else:
  1062. compiler = get_cxx_compiler()
  1063. _, version = get_compiler_abi_compatibility_and_version(compiler)
  1064. # Warn user if VC env is activated but `DISTUILS_USE_SDK` is not set.
  1065. if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' in os.environ and 'DISTUTILS_USE_SDK' not in os.environ:
  1066. msg = ('It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.'
  1067. 'This may lead to multiple activations of the VC env.'
  1068. 'Please set `DISTUTILS_USE_SDK=1` and try again.')
  1069. raise UserWarning(msg)
  1070. return compiler, version
  1071. def _add_compile_flag(self, extension, flag) -> None:
  1072. extension.extra_compile_args = copy.deepcopy(extension.extra_compile_args)
  1073. if isinstance(extension.extra_compile_args, dict):
  1074. for args in extension.extra_compile_args.values():
  1075. args.append(flag)
  1076. else:
  1077. extension.extra_compile_args.append(flag)
  1078. # Simple hipify, replace the first occurrence of CUDA with HIP
  1079. # in flags starting with "-" and containing "CUDA", but exclude -I flags
  1080. def _hipify_compile_flags(self, extension) -> None:
  1081. if isinstance(extension.extra_compile_args, dict) and 'nvcc' in extension.extra_compile_args:
  1082. modified_flags = []
  1083. for flag in extension.extra_compile_args['nvcc']:
  1084. if flag.startswith("-") and "CUDA" in flag and not flag.startswith("-I"):
  1085. # check/split flag into flag and value
  1086. parts = flag.split("=", 1)
  1087. if len(parts) == 2:
  1088. flag_part, value_part = parts
  1089. # replace fist instance of "CUDA" with "HIP" only in the flag and not flag value
  1090. modified_flag_part = flag_part.replace("CUDA", "HIP", 1)
  1091. modified_flag = f"{modified_flag_part}={value_part}"
  1092. else:
  1093. # replace fist instance of "CUDA" with "HIP" in flag
  1094. modified_flag = flag.replace("CUDA", "HIP", 1)
  1095. modified_flags.append(modified_flag)
  1096. logger.info('Modified flag: %s -> %s', flag, modified_flag)
  1097. else:
  1098. modified_flags.append(flag)
  1099. extension.extra_compile_args['nvcc'] = modified_flags
  1100. def _define_torch_extension_name(self, extension) -> None:
  1101. # pybind11 doesn't support dots in the names
  1102. # so in order to support extensions in the packages
  1103. # like torch._C, we take the last part of the string
  1104. # as the library name
  1105. names = extension.name.split('.')
  1106. name = names[-1]
  1107. define = f'-DTORCH_EXTENSION_NAME={name}'
  1108. self._add_compile_flag(extension, define)
  1109. def CppExtension(name, sources, *args, **kwargs):
  1110. """
  1111. Create a :class:`setuptools.Extension` for C++.
  1112. Convenience method that creates a :class:`setuptools.Extension` with the
  1113. bare minimum (but often sufficient) arguments to build a C++ extension.
  1114. All arguments are forwarded to the :class:`setuptools.Extension`
  1115. constructor. Full list arguments can be found at
  1116. https://setuptools.pypa.io/en/latest/userguide/ext_modules.html#extension-api-reference
  1117. .. warning::
  1118. The PyTorch python API (as provided in libtorch_python) cannot be built
  1119. with the flag ``py_limited_api=True``. When this flag is passed, it is
  1120. the user's responsibility in their library to not use APIs from
  1121. libtorch_python (in particular pytorch/python bindings) and to only use
  1122. APIs from libtorch (aten objects, operators and the dispatcher). For
  1123. example, to give access to custom ops from python, the library should
  1124. register the ops through the dispatcher.
  1125. Contrary to CPython setuptools, who does not define -DPy_LIMITED_API
  1126. as a compile flag when py_limited_api is specified as an option for
  1127. the "bdist_wheel" command in ``setup``, PyTorch does! We will specify
  1128. -DPy_LIMITED_API=min_supported_cpython to best enforce consistency,
  1129. safety, and sanity in order to encourage best practices. To target a
  1130. different version, set min_supported_cpython to the hexcode of the
  1131. CPython version of choice.
  1132. Example:
  1133. >>> # xdoctest: +SKIP
  1134. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1135. >>> from setuptools import setup
  1136. >>> from torch.utils.cpp_extension import BuildExtension, CppExtension
  1137. >>> setup(
  1138. ... name='extension',
  1139. ... ext_modules=[
  1140. ... CppExtension(
  1141. ... name='extension',
  1142. ... sources=['extension.cpp'],
  1143. ... extra_compile_args=['-g'],
  1144. ... extra_link_args=['-Wl,--no-as-needed', '-lm'])
  1145. ... ],
  1146. ... cmdclass={
  1147. ... 'build_ext': BuildExtension
  1148. ... })
  1149. """
  1150. include_dirs = kwargs.get('include_dirs', [])
  1151. include_dirs += include_paths()
  1152. kwargs['include_dirs'] = include_dirs
  1153. library_dirs = kwargs.get('library_dirs', [])
  1154. library_dirs += library_paths()
  1155. kwargs['library_dirs'] = library_dirs
  1156. libraries = kwargs.get('libraries', [])
  1157. libraries.append('c10')
  1158. libraries.append('torch')
  1159. libraries.append('torch_cpu')
  1160. if not kwargs.get('py_limited_api', False):
  1161. # torch_python uses more than the python limited api
  1162. libraries.append('torch_python')
  1163. if IS_WINDOWS:
  1164. libraries.append("sleef")
  1165. kwargs['libraries'] = libraries
  1166. kwargs['language'] = 'c++'
  1167. return setuptools.Extension(name, sources, *args, **kwargs)
  1168. def CUDAExtension(name, sources, *args, **kwargs):
  1169. """
  1170. Create a :class:`setuptools.Extension` for CUDA/C++.
  1171. Convenience method that creates a :class:`setuptools.Extension` with the
  1172. bare minimum (but often sufficient) arguments to build a CUDA/C++
  1173. extension. This includes the CUDA include path, library path and runtime
  1174. library.
  1175. All arguments are forwarded to the :class:`setuptools.Extension`
  1176. constructor. Full list arguments can be found at
  1177. https://setuptools.pypa.io/en/latest/userguide/ext_modules.html#extension-api-reference
  1178. .. warning::
  1179. The PyTorch python API (as provided in libtorch_python) cannot be built
  1180. with the flag ``py_limited_api=True``. When this flag is passed, it is
  1181. the user's responsibility in their library to not use APIs from
  1182. libtorch_python (in particular pytorch/python bindings) and to only use
  1183. APIs from libtorch (aten objects, operators and the dispatcher). For
  1184. example, to give access to custom ops from python, the library should
  1185. register the ops through the dispatcher.
  1186. Contrary to CPython setuptools, who does not define -DPy_LIMITED_API
  1187. as a compile flag when py_limited_api is specified as an option for
  1188. the "bdist_wheel" command in ``setup``, PyTorch does! We will specify
  1189. -DPy_LIMITED_API=min_supported_cpython to best enforce consistency,
  1190. safety, and sanity in order to encourage best practices. To target a
  1191. different version, set min_supported_cpython to the hexcode of the
  1192. CPython version of choice.
  1193. Example:
  1194. >>> # xdoctest: +SKIP
  1195. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1196. >>> from setuptools import setup
  1197. >>> from torch.utils.cpp_extension import BuildExtension, CUDAExtension
  1198. >>> setup(
  1199. ... name='cuda_extension',
  1200. ... ext_modules=[
  1201. ... CUDAExtension(
  1202. ... name='cuda_extension',
  1203. ... sources=['extension.cpp', 'extension_kernel.cu'],
  1204. ... extra_compile_args={'cxx': ['-g'],
  1205. ... 'nvcc': ['-O2']},
  1206. ... extra_link_args=['-Wl,--no-as-needed', '-lcuda'])
  1207. ... ],
  1208. ... cmdclass={
  1209. ... 'build_ext': BuildExtension
  1210. ... })
  1211. Compute capabilities:
  1212. By default the extension will be compiled to run on all archs of the cards visible during the
  1213. building process of the extension, plus PTX. If down the road a new card is installed the
  1214. extension may need to be recompiled. If a visible card has a compute capability (CC) that's
  1215. newer than the newest version for which your nvcc can build fully-compiled binaries, PyTorch
  1216. will make nvcc fall back to building kernels with the newest version of PTX your nvcc does
  1217. support (see below for details on PTX).
  1218. You can override the default behavior using `TORCH_CUDA_ARCH_LIST` to explicitly specify which
  1219. CCs you want the extension to support:
  1220. ``TORCH_CUDA_ARCH_LIST="6.1 8.6" python build_my_extension.py``
  1221. ``TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python build_my_extension.py``
  1222. The +PTX option causes extension kernel binaries to include PTX instructions for the specified
  1223. CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >=
  1224. the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with
  1225. CC >= 8.6). This improves your binary's forward compatibility. However, relying on older PTX to
  1226. provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on
  1227. those newer CCs. If you know exact CC(s) of the GPUs you want to target, you're always better
  1228. off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6,
  1229. "8.0+PTX" would work functionally because it includes PTX that can runtime-compile for 8.6, but
  1230. "8.0 8.6" would be better.
  1231. Note that while it's possible to include all supported archs, the more archs get included the
  1232. slower the building process will be, as it will build a separate kernel image for each arch.
  1233. Note that CUDA-11.5 nvcc will hit internal compiler error while parsing torch/extension.h on Windows.
  1234. To workaround the issue, move python binding logic to pure C++ file.
  1235. Example use:
  1236. #include <ATen/ATen.h>
  1237. at::Tensor SigmoidAlphaBlendForwardCuda(....)
  1238. Instead of:
  1239. #include <torch/extension.h>
  1240. torch::Tensor SigmoidAlphaBlendForwardCuda(...)
  1241. Currently open issue for nvcc bug: https://github.com/pytorch/pytorch/issues/69460
  1242. Complete workaround code example: https://github.com/facebookresearch/pytorch3d/commit/cb170ac024a949f1f9614ffe6af1c38d972f7d48
  1243. Relocatable device code linking:
  1244. If you want to reference device symbols across compilation units (across object files),
  1245. the object files need to be built with `relocatable device code` (-rdc=true or -dc).
  1246. An exception to this rule is "dynamic parallelism" (nested kernel launches) which is not used a lot anymore.
  1247. `Relocatable device code` is less optimized so it needs to be used only on object files that need it.
  1248. Using `-dlto` (Device Link Time Optimization) at the device code compilation step and `dlink` step
  1249. helps reduce the protentional perf degradation of `-rdc`.
  1250. Note that it needs to be used at both steps to be useful.
  1251. If you have `rdc` objects you need to have an extra `-dlink` (device linking) step before the CPU symbol linking step.
  1252. There is also a case where `-dlink` is used without `-rdc`:
  1253. when an extension is linked against a static lib containing rdc-compiled objects
  1254. like the [NVSHMEM library](https://developer.nvidia.com/nvshmem).
  1255. Note: Ninja is required to build a CUDA Extension with RDC linking.
  1256. Example:
  1257. >>> # xdoctest: +SKIP
  1258. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1259. >>> CUDAExtension(
  1260. ... name='cuda_extension',
  1261. ... sources=['extension.cpp', 'extension_kernel.cu'],
  1262. ... dlink=True,
  1263. ... dlink_libraries=["dlink_lib"],
  1264. ... extra_compile_args={'cxx': ['-g'],
  1265. ... 'nvcc': ['-O2', '-rdc=true']})
  1266. """
  1267. library_dirs = kwargs.get('library_dirs', [])
  1268. library_dirs += library_paths(device_type="cuda")
  1269. kwargs['library_dirs'] = library_dirs
  1270. libraries = kwargs.get('libraries', [])
  1271. libraries.append('c10')
  1272. libraries.append('torch')
  1273. libraries.append('torch_cpu')
  1274. if not kwargs.get('py_limited_api', False):
  1275. # torch_python uses more than the python limited api
  1276. libraries.append('torch_python')
  1277. if IS_HIP_EXTENSION:
  1278. libraries.append('amdhip64')
  1279. libraries.append('c10_hip')
  1280. libraries.append('torch_hip')
  1281. else:
  1282. libraries.append('cudart')
  1283. libraries.append('c10_cuda')
  1284. libraries.append('torch_cuda')
  1285. kwargs['libraries'] = libraries
  1286. include_dirs = kwargs.get('include_dirs', [])
  1287. if IS_HIP_EXTENSION:
  1288. from .hipify import hipify_python
  1289. build_dir = os.getcwd()
  1290. hipify_result = hipify_python.hipify(
  1291. project_directory=build_dir,
  1292. output_directory=build_dir,
  1293. header_include_dirs=include_dirs,
  1294. includes=[os.path.join(build_dir, '*')], # limit scope to build_dir only
  1295. extra_files=[os.path.abspath(s) for s in sources],
  1296. show_detailed=True,
  1297. is_pytorch_extension=True,
  1298. hipify_extra_files_only=True, # don't hipify everything in includes path
  1299. )
  1300. hipified_sources = set()
  1301. for source in sources:
  1302. s_abs = os.path.abspath(source)
  1303. hipified_s_abs = (hipify_result[s_abs].hipified_path if (s_abs in hipify_result and
  1304. hipify_result[s_abs].hipified_path is not None) else s_abs)
  1305. # setup() arguments must *always* be /-separated paths relative to the setup.py directory,
  1306. # *never* absolute paths
  1307. hipified_sources.add(os.path.relpath(hipified_s_abs, build_dir))
  1308. sources = list(hipified_sources)
  1309. include_dirs += include_paths(device_type="cuda")
  1310. kwargs['include_dirs'] = include_dirs
  1311. kwargs['language'] = 'c++'
  1312. dlink_libraries = kwargs.get('dlink_libraries', [])
  1313. dlink = kwargs.get('dlink', False) or dlink_libraries
  1314. if dlink:
  1315. extra_compile_args = kwargs.get('extra_compile_args', {})
  1316. extra_compile_args_dlink = extra_compile_args.get('nvcc_dlink', [])
  1317. extra_compile_args_dlink += ['-dlink']
  1318. extra_compile_args_dlink += [f'-L{x}' for x in library_dirs]
  1319. extra_compile_args_dlink += [f'-l{x}' for x in dlink_libraries]
  1320. if (torch.version.cuda is not None) and TorchVersion(torch.version.cuda) >= '11.2':
  1321. extra_compile_args_dlink += ['-dlto'] # Device Link Time Optimization started from cuda 11.2
  1322. extra_compile_args['nvcc_dlink'] = extra_compile_args_dlink
  1323. kwargs['extra_compile_args'] = extra_compile_args
  1324. return setuptools.Extension(name, sources, *args, **kwargs)
  1325. def SyclExtension(name, sources, *args, **kwargs):
  1326. r"""
  1327. Creates a :class:`setuptools.Extension` for SYCL/C++.
  1328. Convenience method that creates a :class:`setuptools.Extension` with the
  1329. bare minimum (but often sufficient) arguments to build a SYCL/C++
  1330. extension.
  1331. All arguments are forwarded to the :class:`setuptools.Extension`
  1332. constructor.
  1333. .. warning::
  1334. The PyTorch python API (as provided in libtorch_python) cannot be built
  1335. with the flag ``py_limited_api=True``. When this flag is passed, it is
  1336. the user's responsibility in their library to not use APIs from
  1337. libtorch_python (in particular pytorch/python bindings) and to only use
  1338. APIs from libtorch (aten objects, operators and the dispatcher). For
  1339. example, to give access to custom ops from python, the library should
  1340. register the ops through the dispatcher.
  1341. Contrary to CPython setuptools, who does not define -DPy_LIMITED_API
  1342. as a compile flag when py_limited_api is specified as an option for
  1343. the "bdist_wheel" command in ``setup``, PyTorch does! We will specify
  1344. -DPy_LIMITED_API=min_supported_cpython to best enforce consistency,
  1345. safety, and sanity in order to encourage best practices. To target a
  1346. different version, set min_supported_cpython to the hexcode of the
  1347. CPython version of choice.
  1348. Example:
  1349. >>> # xdoctest: +SKIP
  1350. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1351. >>> from torch.utils.cpp_extension import BuildExtension, SyclExtension
  1352. >>> setup(
  1353. ... name='xpu_extension',
  1354. ... ext_modules=[
  1355. ... SyclExtension(
  1356. ... name='xpu_extension',
  1357. ... sources=['extension.cpp', 'extension_kernel.cpp'],
  1358. ... extra_compile_args={'cxx': ['-g', '-std=c++20', '-fPIC']})
  1359. ... ],
  1360. ... cmdclass={
  1361. ... 'build_ext': BuildExtension
  1362. ... })
  1363. By default the extension will be compiled to run on all archs of the cards visible during the
  1364. building process of the extension. If down the road a new card is installed the
  1365. extension may need to be recompiled. You can override the default behavior using
  1366. `TORCH_XPU_ARCH_LIST` to explicitly specify which device architectures you want the extension
  1367. to support:
  1368. ``TORCH_XPU_ARCH_LIST="pvc,xe-lpg" python build_my_extension.py``
  1369. Note that while it's possible to include all supported archs, the more archs get included the
  1370. slower the building process will be, as it will build a separate kernel image for each arch.
  1371. Note: Ninja is required to build SyclExtension.
  1372. """
  1373. library_dirs = kwargs.get("library_dirs", [])
  1374. library_dirs += library_paths()
  1375. kwargs["library_dirs"] = library_dirs
  1376. libraries = kwargs.get("libraries", [])
  1377. libraries.append("c10")
  1378. libraries.append("c10_xpu")
  1379. libraries.append("torch")
  1380. libraries.append("torch_cpu")
  1381. libraries.append("sycl")
  1382. if not kwargs.get('py_limited_api', False):
  1383. # torch_python uses more than the python limited api
  1384. libraries.append("torch_python")
  1385. libraries.append("torch_xpu")
  1386. kwargs["libraries"] = libraries
  1387. include_dirs = kwargs.get("include_dirs", [])
  1388. include_dirs += include_paths(device_type="xpu")
  1389. kwargs["include_dirs"] = include_dirs
  1390. kwargs["language"] = "c++"
  1391. return setuptools.Extension(name, sources, *args, **kwargs)
  1392. def include_paths(device_type: str = "cpu", torch_include_dirs=True) -> list[str]:
  1393. """
  1394. Get the include paths required to build a C++ or CUDA or SYCL extension.
  1395. Args:
  1396. device_type: Defaults to "cpu".
  1397. Returns:
  1398. A list of include path strings.
  1399. """
  1400. paths = []
  1401. lib_include = os.path.join(_TORCH_PATH, 'include')
  1402. if torch_include_dirs:
  1403. paths.extend([
  1404. lib_include,
  1405. # Remove this once torch/torch.h is officially no longer supported for C++ extensions.
  1406. os.path.join(lib_include, 'torch', 'csrc', 'api', 'include'),
  1407. ])
  1408. if device_type == "cuda" and IS_HIP_EXTENSION:
  1409. paths.append(os.path.join(lib_include, 'THH'))
  1410. paths.append(_join_rocm_home('include'))
  1411. elif device_type == "cuda":
  1412. cuda_home_include = _join_cuda_home('include')
  1413. # if we have the Debian/Ubuntu packages for cuda, we get /usr as cuda home.
  1414. # but gcc doesn't like having /usr/include passed explicitly
  1415. if cuda_home_include != '/usr/include':
  1416. paths.append(cuda_home_include)
  1417. # Support CUDA_INC_PATH env variable supported by CMake files
  1418. if (cuda_inc_path := os.environ.get("CUDA_INC_PATH", None)) and \
  1419. cuda_inc_path != '/usr/include':
  1420. paths.append(cuda_inc_path)
  1421. if CUDNN_HOME is not None:
  1422. paths.append(os.path.join(CUDNN_HOME, 'include'))
  1423. elif device_type == "xpu":
  1424. paths.append(_join_sycl_home('include'))
  1425. paths.append(_join_sycl_home('include', 'sycl'))
  1426. return paths
  1427. def library_paths(device_type: str = "cpu", torch_include_dirs: bool = True, cross_target_platform: str | None = None) -> list[str]:
  1428. """
  1429. Get the library paths required to build a C++ or CUDA extension.
  1430. Args:
  1431. device_type: Defaults to "cpu".
  1432. Returns:
  1433. A list of library path strings.
  1434. """
  1435. paths = []
  1436. if torch_include_dirs:
  1437. # We need to link against libtorch.so
  1438. paths.extend([TORCH_LIB_PATH])
  1439. if device_type == "cuda" and IS_HIP_EXTENSION:
  1440. lib_dir = 'lib'
  1441. paths.append(_join_rocm_home(lib_dir))
  1442. if HIP_HOME is not None:
  1443. paths.append(os.path.join(HIP_HOME, 'lib'))
  1444. elif device_type == "cuda":
  1445. if cross_target_platform == "windows":
  1446. lib_dir = os.path.join('lib', 'x64')
  1447. if WINDOWS_CUDA_HOME is None:
  1448. raise RuntimeError("Need to set WINDOWS_CUDA_HOME for windows cross-compilation")
  1449. paths.append(os.path.join(WINDOWS_CUDA_HOME, lib_dir))
  1450. else:
  1451. if IS_WINDOWS:
  1452. lib_dir = os.path.join('lib', 'x64')
  1453. else:
  1454. lib_dir = 'lib64'
  1455. if (not os.path.exists(_join_cuda_home(lib_dir)) and
  1456. os.path.exists(_join_cuda_home('lib'))):
  1457. # 64-bit CUDA may be installed in 'lib' (see e.g. gh-16955)
  1458. # Note that it's also possible both don't exist (see
  1459. # _find_cuda_home) - in that case we stay with 'lib64'.
  1460. lib_dir = 'lib'
  1461. paths.append(_join_cuda_home(lib_dir))
  1462. if CUDNN_HOME is not None:
  1463. paths.append(os.path.join(CUDNN_HOME, lib_dir))
  1464. elif device_type == "xpu":
  1465. if IS_WINDOWS:
  1466. lib_dir = os.path.join('lib', 'x64')
  1467. else:
  1468. lib_dir = 'lib64'
  1469. if (not os.path.exists(_join_sycl_home(lib_dir)) and
  1470. os.path.exists(_join_sycl_home('lib'))):
  1471. lib_dir = 'lib'
  1472. paths.append(_join_sycl_home(lib_dir))
  1473. return paths
  1474. def load(name,
  1475. sources: str | list[str],
  1476. extra_cflags=None,
  1477. extra_cuda_cflags=None,
  1478. extra_sycl_cflags=None,
  1479. extra_ldflags=None,
  1480. extra_include_paths=None,
  1481. build_directory=None,
  1482. verbose=False,
  1483. with_cuda: bool | None = None,
  1484. with_sycl: bool | None = None,
  1485. is_python_module=True,
  1486. is_standalone=False,
  1487. keep_intermediates=True):
  1488. """
  1489. Load a PyTorch C++ extension just-in-time (JIT).
  1490. To load an extension, a Ninja build file is emitted, which is used to
  1491. compile the given sources into a dynamic library. This library is
  1492. subsequently loaded into the current Python process as a module and
  1493. returned from this function, ready for use.
  1494. By default, the directory to which the build file is emitted and the
  1495. resulting library compiled to is ``<tmp>/torch_extensions/<name>``, where
  1496. ``<tmp>`` is the temporary folder on the current platform and ``<name>``
  1497. the name of the extension. This location can be overridden in two ways.
  1498. First, if the ``TORCH_EXTENSIONS_DIR`` environment variable is set, it
  1499. replaces ``<tmp>/torch_extensions`` and all extensions will be compiled
  1500. into subfolders of this directory. Second, if the ``build_directory``
  1501. argument to this function is supplied, it overrides the entire path, i.e.
  1502. the library will be compiled into that folder directly.
  1503. To compile the sources, the default system compiler (``c++``) is used,
  1504. which can be overridden by setting the ``CXX`` environment variable. To pass
  1505. additional arguments to the compilation process, ``extra_cflags`` or
  1506. ``extra_ldflags`` can be provided. For example, to compile your extension
  1507. with optimizations, pass ``extra_cflags=['-O3']``. You can also use
  1508. ``extra_cflags`` to pass further include directories.
  1509. CUDA support with mixed compilation is provided. Simply pass CUDA source
  1510. files (``.cu`` or ``.cuh``) along with other sources. Such files will be
  1511. detected and compiled with nvcc rather than the C++ compiler. This includes
  1512. passing the CUDA lib64 directory as a library directory, and linking
  1513. ``cudart``. You can pass additional flags to nvcc via
  1514. ``extra_cuda_cflags``, just like with ``extra_cflags`` for C++. Various
  1515. heuristics for finding the CUDA install directory are used, which usually
  1516. work fine. If not, setting the ``CUDA_HOME`` environment variable is the
  1517. safest option.
  1518. SYCL support with mixed compilation is provided. Simply pass SYCL source
  1519. files (``.sycl``) along with other sources. Such files will be detected
  1520. and compiled with SYCL compiler (such as Intel DPC++ Compiler) rather
  1521. than the C++ compiler. You can pass additional flags to SYCL compiler
  1522. via ``extra_sycl_cflags``, just like with ``extra_cflags`` for C++.
  1523. SYCL compiler is expected to be found via system PATH environment
  1524. variable.
  1525. Args:
  1526. name: The name of the extension to build. This MUST be the same as the
  1527. name of the pybind11 module!
  1528. sources: A list of relative or absolute paths to C++ source files.
  1529. extra_cflags: optional list of compiler flags to forward to the build.
  1530. extra_cuda_cflags: optional list of compiler flags to forward to nvcc
  1531. when building CUDA sources.
  1532. extra_sycl_cflags: optional list of compiler flags to forward to SYCL
  1533. compiler when building SYCL sources.
  1534. extra_ldflags: optional list of linker flags to forward to the build.
  1535. extra_include_paths: optional list of include directories to forward
  1536. to the build.
  1537. build_directory: optional path to use as build workspace.
  1538. verbose: If ``True``, turns on verbose logging of load steps.
  1539. with_cuda: Determines whether CUDA headers and libraries are added to
  1540. the build. If set to ``None`` (default), this value is
  1541. automatically determined based on the existence of ``.cu`` or
  1542. ``.cuh`` in ``sources``. Set it to `True`` to force CUDA headers
  1543. and libraries to be included.
  1544. with_sycl: Determines whether SYCL headers and libraries are added to
  1545. the build. If set to ``None`` (default), this value is
  1546. automatically determined based on the existence of ``.sycl`` in
  1547. ``sources``. Set it to `True`` to force SYCL headers and
  1548. libraries to be included.
  1549. is_python_module: If ``True`` (default), imports the produced shared
  1550. library as a Python module. If ``False``, behavior depends on
  1551. ``is_standalone``.
  1552. is_standalone: If ``False`` (default) loads the constructed extension
  1553. into the process as a plain dynamic library. If ``True``, build a
  1554. standalone executable.
  1555. Returns:
  1556. If ``is_python_module`` is ``True``:
  1557. Returns the loaded PyTorch extension as a Python module.
  1558. If ``is_python_module`` is ``False`` and ``is_standalone`` is ``False``:
  1559. Returns nothing. (The shared library is loaded into the process as
  1560. a side effect.)
  1561. If ``is_standalone`` is ``True``.
  1562. Return the path to the executable. (On Windows, TORCH_LIB_PATH is
  1563. added to the PATH environment variable as a side effect.)
  1564. Example:
  1565. >>> # xdoctest: +SKIP
  1566. >>> from torch.utils.cpp_extension import load
  1567. >>> module = load(
  1568. ... name='extension',
  1569. ... sources=['extension.cpp', 'extension_kernel.cu'],
  1570. ... extra_cflags=['-O2'],
  1571. ... verbose=True)
  1572. """
  1573. return _jit_compile(
  1574. name,
  1575. [sources] if isinstance(sources, str) else sources,
  1576. extra_cflags,
  1577. extra_cuda_cflags,
  1578. extra_sycl_cflags,
  1579. extra_ldflags,
  1580. extra_include_paths,
  1581. build_directory or _get_build_directory(name, verbose),
  1582. verbose,
  1583. with_cuda,
  1584. with_sycl,
  1585. is_python_module,
  1586. is_standalone,
  1587. keep_intermediates=keep_intermediates)
  1588. @deprecated("PyBind11 ABI handling is internal to PyBind11; this will be removed after PyTorch 2.9.0")
  1589. def _get_pybind11_abi_build_flags() -> list[str]:
  1590. return []
  1591. def check_compiler_is_gcc(compiler) -> bool:
  1592. if not IS_LINUX:
  1593. return False
  1594. env = os.environ.copy()
  1595. env['LC_ALL'] = 'C' # Don't localize output
  1596. try:
  1597. version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS)
  1598. except (subprocess.CalledProcessError, OSError):
  1599. try:
  1600. version_string = subprocess.check_output([compiler, '--version'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS)
  1601. except (subprocess.CalledProcessError, OSError):
  1602. return False
  1603. # Check for GCC by verifying both COLLECT_GCC and gcc version string are present
  1604. # This works for c++, g++, gcc, and versioned variants like g++-13
  1605. pattern = re.compile("^COLLECT_GCC=(.*)$", re.MULTILINE)
  1606. has_collect_gcc = pattern.search(version_string) is not None
  1607. if has_collect_gcc and 'gcc version' in version_string:
  1608. return True
  1609. return False
  1610. def _check_and_build_extension_h_precompiler_headers(
  1611. extra_cflags,
  1612. extra_include_paths,
  1613. is_standalone=False) -> None:
  1614. r'''
  1615. Precompiled Headers(PCH) can pre-build the same headers and reduce build time for pytorch load_inline modules.
  1616. GCC official manual: https://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Precompiled-Headers.html
  1617. PCH only works when built pch file(header.h.gch) and build target have the same build parameters. So, We need
  1618. add a signature file to record PCH file parameters. If the build parameters(signature) changed, it should rebuild
  1619. PCH file.
  1620. Note:
  1621. 1. Windows and MacOS have different PCH mechanism. We only support Linux currently.
  1622. 2. It only works on GCC/G++.
  1623. '''
  1624. if not IS_LINUX:
  1625. return
  1626. compiler = get_cxx_compiler()
  1627. b_is_gcc = check_compiler_is_gcc(compiler)
  1628. if b_is_gcc is False:
  1629. return
  1630. head_file = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h')
  1631. head_file_pch = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.gch')
  1632. head_file_signature = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.sign')
  1633. def listToString(s):
  1634. # initialize an empty string
  1635. string = ""
  1636. if s is None:
  1637. return string
  1638. # traverse in the string
  1639. for element in s:
  1640. string += (element + ' ')
  1641. # return string
  1642. return string
  1643. def format_precompiler_header_cmd(compiler, head_file, head_file_pch, common_cflags, torch_include_dirs, extra_cflags, extra_include_paths):
  1644. return re.sub(
  1645. r"[ \n]+",
  1646. " ",
  1647. f"""
  1648. {compiler} -x c++-header {head_file} -o {head_file_pch} {torch_include_dirs} {extra_include_paths} {extra_cflags} {common_cflags}
  1649. """,
  1650. ).strip()
  1651. def command_to_signature(cmd):
  1652. signature = cmd.replace(' ', '_')
  1653. return signature
  1654. def check_pch_signature_in_file(file_path, signature):
  1655. b_exist = os.path.isfile(file_path)
  1656. if b_exist is False:
  1657. return False
  1658. with open(file_path) as file:
  1659. # read all content of a file
  1660. content = file.read()
  1661. # check if string present in a file
  1662. return signature == content
  1663. def _create_if_not_exist(path_dir) -> None:
  1664. if not os.path.exists(path_dir):
  1665. try:
  1666. Path(path_dir).mkdir(parents=True, exist_ok=True)
  1667. except OSError as exc: # Guard against race condition
  1668. if exc.errno != errno.EEXIST:
  1669. raise RuntimeError(f"Fail to create path {path_dir}") from exc
  1670. def write_pch_signature_to_file(file_path, pch_sign) -> None:
  1671. _create_if_not_exist(os.path.dirname(file_path))
  1672. with open(file_path, "w") as f:
  1673. f.write(pch_sign)
  1674. f.close()
  1675. def build_precompile_header(pch_cmd) -> None:
  1676. try:
  1677. subprocess.check_output(shlex.split(pch_cmd), stderr=subprocess.STDOUT)
  1678. except subprocess.CalledProcessError as e:
  1679. raise RuntimeError(f"Compile PreCompile Header fail, command: {pch_cmd}") from e
  1680. extra_cflags_str = listToString(extra_cflags)
  1681. extra_include_paths_str = " ".join(
  1682. [f"-I{include}" for include in extra_include_paths] if extra_include_paths else []
  1683. )
  1684. lib_include = os.path.join(_TORCH_PATH, 'include')
  1685. torch_include_dirs = [
  1686. f"-I {lib_include}",
  1687. # Python.h
  1688. "-I {}".format(sysconfig.get_path("include")),
  1689. # torch/all.h
  1690. "-I {}".format(os.path.join(lib_include, 'torch', 'csrc', 'api', 'include')),
  1691. ]
  1692. torch_include_dirs_str = listToString(torch_include_dirs)
  1693. common_cflags = []
  1694. if not is_standalone:
  1695. common_cflags += ['-DTORCH_API_INCLUDE_EXTENSION_H']
  1696. common_cflags += ['-std=c++17', '-fPIC']
  1697. common_cflags_str = listToString(common_cflags)
  1698. pch_cmd = format_precompiler_header_cmd(compiler, head_file, head_file_pch, common_cflags_str, torch_include_dirs_str, extra_cflags_str, extra_include_paths_str)
  1699. pch_sign = command_to_signature(pch_cmd)
  1700. if os.path.isfile(head_file_pch) is not True:
  1701. build_precompile_header(pch_cmd)
  1702. write_pch_signature_to_file(head_file_signature, pch_sign)
  1703. else:
  1704. b_same_sign = check_pch_signature_in_file(head_file_signature, pch_sign)
  1705. if b_same_sign is False:
  1706. build_precompile_header(pch_cmd)
  1707. write_pch_signature_to_file(head_file_signature, pch_sign)
  1708. def remove_extension_h_precompiler_headers() -> None:
  1709. def _remove_if_file_exists(path_file) -> None:
  1710. if os.path.exists(path_file):
  1711. os.remove(path_file)
  1712. head_file_pch = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.gch')
  1713. head_file_signature = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.sign')
  1714. _remove_if_file_exists(head_file_pch)
  1715. _remove_if_file_exists(head_file_signature)
  1716. def load_inline(name,
  1717. cpp_sources,
  1718. cuda_sources=None,
  1719. sycl_sources=None,
  1720. functions=None,
  1721. extra_cflags=None,
  1722. extra_cuda_cflags=None,
  1723. extra_sycl_cflags=None,
  1724. extra_ldflags=None,
  1725. extra_include_paths=None,
  1726. build_directory=None,
  1727. verbose=False,
  1728. with_cuda=None,
  1729. with_sycl=None,
  1730. is_python_module=True,
  1731. with_pytorch_error_handling=True,
  1732. keep_intermediates=True,
  1733. use_pch=False,
  1734. no_implicit_headers=False):
  1735. r'''
  1736. Load a PyTorch C++ extension just-in-time (JIT) from string sources.
  1737. This function behaves exactly like :func:`load`, but takes its sources as
  1738. strings rather than filenames. These strings are stored to files in the
  1739. build directory, after which the behavior of :func:`load_inline` is
  1740. identical to :func:`load`.
  1741. See `the
  1742. tests <https://github.com/pytorch/pytorch/blob/master/test/test_cpp_extensions_jit.py>`_
  1743. for good examples of using this function.
  1744. Sources may omit two required parts of a typical non-inline C++ extension:
  1745. the necessary header includes, as well as the (pybind11) binding code. More
  1746. precisely, strings passed to ``cpp_sources`` are first concatenated into a
  1747. single ``.cpp`` file. This file is then prepended with ``#include
  1748. <torch/extension.h>``
  1749. Furthermore, if the ``functions`` argument is supplied, bindings will be
  1750. automatically generated for each function specified. ``functions`` can
  1751. either be a list of function names, or a dictionary mapping from function
  1752. names to docstrings. If a list is given, the name of each function is used
  1753. as its docstring.
  1754. The sources in ``cuda_sources`` are concatenated into a separate ``.cu``
  1755. file and prepended with ``torch/types.h``, ``cuda.h`` and
  1756. ``cuda_runtime.h`` includes. The ``.cpp`` and ``.cu`` files are compiled
  1757. separately, but ultimately linked into a single library. Note that no
  1758. bindings are generated for functions in ``cuda_sources`` per se. To bind
  1759. to a CUDA kernel, you must create a C++ function that calls it, and either
  1760. declare or define this C++ function in one of the ``cpp_sources`` (and
  1761. include its name in ``functions``).
  1762. The sources in ``sycl_sources`` are concatenated into a separate ``.sycl``
  1763. file and prepended with ``torch/types.h``, ``sycl/sycl.hpp`` includes.
  1764. The ``.cpp`` and ``.sycl`` files are compiled separately, but ultimately
  1765. linked into a single library. Note that no bindings are generated for
  1766. functions in ``sycl_sources`` per se. To bind to a SYCL kernel, you must
  1767. create a C++ function that calls it, and either declare or define this
  1768. C++ function in one of the ``cpp_sources`` (and include its name
  1769. in ``functions``).
  1770. See :func:`load` for a description of arguments omitted below.
  1771. Args:
  1772. cpp_sources: A string, or list of strings, containing C++ source code.
  1773. cuda_sources: A string, or list of strings, containing CUDA source code.
  1774. sycl_sources: A string, or list of strings, containing SYCL source code.
  1775. functions: A list of function names for which to generate function
  1776. bindings. If a dictionary is given, it should map function names to
  1777. docstrings (which are otherwise just the function names).
  1778. with_cuda: Determines whether CUDA headers and libraries are added to
  1779. the build. If set to ``None`` (default), this value is
  1780. automatically determined based on whether ``cuda_sources`` is
  1781. provided. Set it to ``True`` to force CUDA headers
  1782. and libraries to be included.
  1783. with_sycl: Determines whether SYCL headers and libraries are added to
  1784. the build. If set to ``None`` (default), this value is
  1785. automatically determined based on whether ``sycl_sources`` is
  1786. provided. Set it to ``True`` to force SYCL headers
  1787. and libraries to be included.
  1788. with_pytorch_error_handling: Determines whether pytorch error and
  1789. warning macros are handled by pytorch instead of pybind. To do
  1790. this, each function ``foo`` is called via an intermediary ``_safe_foo``
  1791. function. This redirection might cause issues in obscure cases
  1792. of cpp. This flag should be set to ``False`` when this redirect
  1793. causes issues.
  1794. no_implicit_headers: If ``True``, skips automatically adding headers, most notably
  1795. ``#include <torch/extension.h>`` and ``#include <torch/types.h>`` lines.
  1796. Use this option to improve cold start times when you
  1797. already include the necessary headers in your source code. Default: ``False``.
  1798. Example:
  1799. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1800. >>> from torch.utils.cpp_extension import load_inline
  1801. >>> source = """
  1802. at::Tensor sin_add(at::Tensor x, at::Tensor y) {
  1803. return x.sin() + y.sin();
  1804. }
  1805. """
  1806. >>> module = load_inline(name='inline_extension',
  1807. ... cpp_sources=[source],
  1808. ... functions=['sin_add'])
  1809. .. note::
  1810. Since load_inline will just-in-time compile the source code, please ensure
  1811. that you have the right toolchains installed in the runtime. For example,
  1812. when loading C++, make sure a C++ compiler is available. If you're loading
  1813. a CUDA extension, you will need to additionally install the corresponding CUDA
  1814. toolkit (nvcc and any other dependencies your code has). Compiling toolchains
  1815. are not included when you install torch and must be additionally installed.
  1816. During compiling, by default, the Ninja backend uses #CPUS + 2 workers to build
  1817. the extension. This may use up too many resources on some systems. One
  1818. can control the number of workers by setting the `MAX_JOBS` environment
  1819. variable to a non-negative number.
  1820. '''
  1821. build_directory = build_directory or _get_build_directory(name, verbose)
  1822. if isinstance(cpp_sources, str):
  1823. cpp_sources = [cpp_sources]
  1824. cuda_sources = cuda_sources or []
  1825. if isinstance(cuda_sources, str):
  1826. cuda_sources = [cuda_sources]
  1827. sycl_sources = sycl_sources or []
  1828. if isinstance(sycl_sources, str):
  1829. sycl_sources = [sycl_sources]
  1830. if not no_implicit_headers:
  1831. cpp_sources.insert(0, '#include <torch/extension.h>')
  1832. if use_pch is True:
  1833. # Using PreCompile Header('torch/extension.h') to reduce compile time.
  1834. _check_and_build_extension_h_precompiler_headers(extra_cflags, extra_include_paths)
  1835. else:
  1836. remove_extension_h_precompiler_headers()
  1837. # If `functions` is supplied, we create the pybind11 bindings for the user.
  1838. # Here, `functions` is (or becomes, after some processing) a map from
  1839. # function names to function docstrings.
  1840. if functions is not None:
  1841. module_def = []
  1842. module_def.append('PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {')
  1843. if isinstance(functions, str):
  1844. functions = [functions]
  1845. if isinstance(functions, list):
  1846. # Make the function docstring the same as the function name.
  1847. functions = {f: f for f in functions}
  1848. elif not isinstance(functions, dict):
  1849. raise ValueError(f"Expected 'functions' to be a list or dict, but was {type(functions)}")
  1850. for function_name, docstring in functions.items():
  1851. if with_pytorch_error_handling:
  1852. module_def.append(f'm.def("{function_name}", torch::wrap_pybind_function({function_name}), "{docstring}");')
  1853. else:
  1854. module_def.append(f'm.def("{function_name}", {function_name}, "{docstring}");')
  1855. module_def.append('}')
  1856. cpp_sources += module_def
  1857. cpp_source_path = os.path.join(build_directory, 'main.cpp')
  1858. _maybe_write(cpp_source_path, "\n".join(cpp_sources))
  1859. sources = [cpp_source_path]
  1860. if cuda_sources:
  1861. if not no_implicit_headers:
  1862. cuda_sources.insert(0, '#include <torch/types.h>')
  1863. cuda_sources.insert(1, '#include <cuda.h>')
  1864. cuda_sources.insert(2, '#include <cuda_runtime.h>')
  1865. cuda_source_path = os.path.join(build_directory, 'cuda.cu')
  1866. _maybe_write(cuda_source_path, "\n".join(cuda_sources))
  1867. sources.append(cuda_source_path)
  1868. if sycl_sources:
  1869. if not no_implicit_headers:
  1870. sycl_sources.insert(0, '#include <torch/types.h>')
  1871. sycl_sources.insert(1, '#include <sycl/sycl.hpp>')
  1872. sycl_source_path = os.path.join(build_directory, 'sycl.sycl')
  1873. _maybe_write(sycl_source_path, "\n".join(sycl_sources))
  1874. sources.append(sycl_source_path)
  1875. return _jit_compile(
  1876. name,
  1877. sources,
  1878. extra_cflags,
  1879. extra_cuda_cflags,
  1880. extra_sycl_cflags,
  1881. extra_ldflags,
  1882. extra_include_paths,
  1883. build_directory,
  1884. verbose,
  1885. with_cuda,
  1886. with_sycl,
  1887. is_python_module,
  1888. is_standalone=False,
  1889. keep_intermediates=keep_intermediates)
  1890. def _jit_compile(name,
  1891. sources,
  1892. extra_cflags,
  1893. extra_cuda_cflags,
  1894. extra_sycl_cflags,
  1895. extra_ldflags,
  1896. extra_include_paths,
  1897. build_directory: str,
  1898. verbose: bool,
  1899. with_cuda: bool | None,
  1900. with_sycl: bool | None,
  1901. is_python_module,
  1902. is_standalone,
  1903. keep_intermediates=True) -> types.ModuleType | str:
  1904. if is_python_module and is_standalone:
  1905. raise ValueError("`is_python_module` and `is_standalone` are mutually exclusive.")
  1906. if with_cuda is None:
  1907. with_cuda = any(map(_is_cuda_file, sources))
  1908. with_cudnn = any('cudnn' in f for f in extra_ldflags or [])
  1909. if with_sycl is None:
  1910. with_sycl = any(map(_is_sycl_file, sources))
  1911. if with_sycl and with_cuda:
  1912. raise AssertionError(
  1913. "cannot have both SYCL and CUDA files in the same extension"
  1914. )
  1915. old_version = JIT_EXTENSION_VERSIONER.get_version(name)
  1916. version = JIT_EXTENSION_VERSIONER.bump_version_if_changed(
  1917. name,
  1918. sources,
  1919. build_arguments=[extra_cflags, extra_cuda_cflags, extra_ldflags, extra_include_paths],
  1920. build_directory=build_directory,
  1921. with_cuda=with_cuda,
  1922. with_sycl=with_sycl,
  1923. is_python_module=is_python_module,
  1924. is_standalone=is_standalone,
  1925. )
  1926. if version > 0:
  1927. if version != old_version and verbose:
  1928. logger.info('The input conditions for extension module %s have changed.', name)
  1929. logger.info('Bumping to version %s and re-building as %s_v%s...', version, name, version)
  1930. name = f'{name}_v{version}'
  1931. baton = FileBaton(os.path.join(build_directory, 'lock'))
  1932. if baton.try_acquire():
  1933. try:
  1934. if version != old_version:
  1935. if IS_HIP_EXTENSION and (with_cuda or with_cudnn):
  1936. from .hipify import hipify_python
  1937. from .hipify.hipify_python import GeneratedFileCleaner
  1938. clean_ctx_mgr = GeneratedFileCleaner(keep_intermediates=keep_intermediates)
  1939. else:
  1940. import contextlib
  1941. hipify_python = None # type: ignore[assignment]
  1942. clean_ctx_mgr = contextlib.nullcontext()
  1943. with clean_ctx_mgr as clean_ctx:
  1944. if IS_HIP_EXTENSION and (with_cuda or with_cudnn):
  1945. assert hipify_python is not None # noqa: S101
  1946. hipify_result = hipify_python.hipify(
  1947. project_directory=build_directory,
  1948. output_directory=build_directory,
  1949. header_include_dirs=(extra_include_paths if extra_include_paths is not None else []),
  1950. extra_files=[os.path.abspath(s) for s in sources],
  1951. ignores=[_join_rocm_home('*'), os.path.join(_TORCH_PATH, '*')], # no need to hipify ROCm or PyTorch headers
  1952. show_detailed=verbose,
  1953. show_progress=verbose,
  1954. is_pytorch_extension=True,
  1955. clean_ctx=clean_ctx
  1956. )
  1957. hipified_sources = set()
  1958. for source in sources:
  1959. s_abs = os.path.abspath(source)
  1960. hipified_sources.add(hipify_result[s_abs].hipified_path if s_abs in hipify_result else s_abs)
  1961. sources = list(hipified_sources)
  1962. _write_ninja_file_and_build_library(
  1963. name=name,
  1964. sources=sources,
  1965. extra_cflags=extra_cflags or [],
  1966. extra_cuda_cflags=extra_cuda_cflags or [],
  1967. extra_sycl_cflags=extra_sycl_cflags or [],
  1968. extra_ldflags=extra_ldflags or [],
  1969. extra_include_paths=extra_include_paths or [],
  1970. build_directory=build_directory,
  1971. verbose=verbose,
  1972. with_cuda=with_cuda,
  1973. with_sycl=with_sycl,
  1974. is_standalone=is_standalone)
  1975. elif verbose:
  1976. logger.debug('No modifications detected for re-loaded extension module %s, skipping build step...', name)
  1977. finally:
  1978. baton.release()
  1979. else:
  1980. baton.wait()
  1981. if verbose:
  1982. logger.info('Loading extension module %s...', name)
  1983. if is_standalone:
  1984. return _get_exec_path(name, build_directory)
  1985. return _import_module_from_library(name, build_directory, is_python_module)
  1986. def _get_hipcc_path():
  1987. if IS_WINDOWS:
  1988. # mypy thinks ROCM_VERSION is None but it will never be None here
  1989. hipcc_exe = 'hipcc.exe' if ROCM_VERSION >= (6, 4) else 'hipcc.bat' # type: ignore[operator]
  1990. return _join_rocm_home('bin', hipcc_exe)
  1991. else:
  1992. return _join_rocm_home('bin', 'hipcc')
  1993. def _write_ninja_file_and_compile_objects(
  1994. sources: list[str],
  1995. objects,
  1996. cflags,
  1997. post_cflags,
  1998. cuda_cflags,
  1999. cuda_post_cflags,
  2000. cuda_dlink_post_cflags,
  2001. sycl_cflags,
  2002. sycl_post_cflags,
  2003. sycl_dlink_post_cflags,
  2004. build_directory: str,
  2005. verbose: bool,
  2006. with_cuda: bool | None,
  2007. with_sycl: bool | None) -> None:
  2008. verify_ninja_availability()
  2009. compiler = get_cxx_compiler()
  2010. get_compiler_abi_compatibility_and_version(compiler)
  2011. if with_cuda is None:
  2012. with_cuda = any(map(_is_cuda_file, sources))
  2013. if with_sycl is None:
  2014. with_sycl = any(map(_is_sycl_file, sources))
  2015. if with_sycl and with_cuda:
  2016. raise AssertionError(
  2017. "cannot have both SYCL and CUDA files in the same extension"
  2018. )
  2019. build_file_path = os.path.join(build_directory, 'build.ninja')
  2020. if verbose:
  2021. logger.debug('Emitting ninja build file %s...', build_file_path)
  2022. # Create build_directory if it does not exist
  2023. if not os.path.exists(build_directory):
  2024. if verbose:
  2025. logger.debug('Creating directory %s...', build_directory)
  2026. # This is like mkdir -p, i.e. will also create parent directories.
  2027. os.makedirs(build_directory, exist_ok=True)
  2028. _write_ninja_file(
  2029. path=build_file_path,
  2030. cflags=cflags,
  2031. post_cflags=post_cflags,
  2032. cuda_cflags=cuda_cflags,
  2033. cuda_post_cflags=cuda_post_cflags,
  2034. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  2035. sycl_cflags=sycl_cflags,
  2036. sycl_post_cflags=sycl_post_cflags,
  2037. sycl_dlink_post_cflags=sycl_dlink_post_cflags,
  2038. sources=sources,
  2039. objects=objects,
  2040. ldflags=None,
  2041. library_target=None,
  2042. with_cuda=with_cuda,
  2043. with_sycl=with_sycl)
  2044. if verbose:
  2045. logger.info('Compiling objects...')
  2046. _run_ninja_build(
  2047. build_directory,
  2048. verbose,
  2049. # It would be better if we could tell users the name of the extension
  2050. # that failed to build but there isn't a good way to get it here.
  2051. error_prefix='Error compiling objects for extension')
  2052. def _write_ninja_file_and_build_library(
  2053. name,
  2054. sources: list[str],
  2055. extra_cflags,
  2056. extra_cuda_cflags,
  2057. extra_sycl_cflags,
  2058. extra_ldflags,
  2059. extra_include_paths,
  2060. build_directory: str,
  2061. verbose: bool,
  2062. with_cuda: bool | None,
  2063. with_sycl: bool | None,
  2064. is_standalone: bool = False) -> None:
  2065. verify_ninja_availability()
  2066. compiler = get_cxx_compiler()
  2067. get_compiler_abi_compatibility_and_version(compiler)
  2068. if with_cuda is None:
  2069. with_cuda = any(map(_is_cuda_file, sources))
  2070. if with_sycl is None:
  2071. with_sycl = any(map(_is_sycl_file, sources))
  2072. if with_sycl and with_cuda:
  2073. raise AssertionError(
  2074. "cannot have both SYCL and CUDA files in the same extension"
  2075. )
  2076. extra_ldflags = _prepare_ldflags(
  2077. extra_ldflags or [],
  2078. with_cuda,
  2079. with_sycl,
  2080. verbose,
  2081. is_standalone)
  2082. build_file_path = os.path.join(build_directory, 'build.ninja')
  2083. if verbose:
  2084. logger.debug('Emitting ninja build file %s...', build_file_path)
  2085. # Create build_directory if it does not exist
  2086. if not os.path.exists(build_directory):
  2087. if verbose:
  2088. logger.debug('Creating directory %s...', build_directory)
  2089. # This is like mkdir -p, i.e. will also create parent directories.
  2090. os.makedirs(build_directory, exist_ok=True)
  2091. # NOTE: Emitting a new ninja build file does not cause re-compilation if
  2092. # the sources did not change, so it's ok to re-emit (and it's fast).
  2093. _write_ninja_file_to_build_library(
  2094. path=build_file_path,
  2095. name=name,
  2096. sources=sources,
  2097. extra_cflags=extra_cflags or [],
  2098. extra_cuda_cflags=extra_cuda_cflags or [],
  2099. extra_sycl_cflags=extra_sycl_cflags or [],
  2100. extra_ldflags=extra_ldflags or [],
  2101. extra_include_paths=extra_include_paths or [],
  2102. with_cuda=with_cuda,
  2103. with_sycl=with_sycl,
  2104. is_standalone=is_standalone)
  2105. if verbose:
  2106. logger.info('Building extension module %s...', name)
  2107. _run_ninja_build(
  2108. build_directory,
  2109. verbose,
  2110. error_prefix=f"Error building extension '{name}'")
  2111. def is_ninja_available() -> bool:
  2112. """Return ``True`` if the `ninja <https://ninja-build.org/>`_ build system is available on the system, ``False`` otherwise."""
  2113. try:
  2114. subprocess.check_output(['ninja', '--version'])
  2115. except Exception:
  2116. return False
  2117. else:
  2118. return True
  2119. def verify_ninja_availability() -> None:
  2120. """Raise ``RuntimeError`` if `ninja <https://ninja-build.org/>`_ build system is not available on the system, does nothing otherwise."""
  2121. if not is_ninja_available():
  2122. raise RuntimeError("Ninja is required to load C++ extensions (pip install ninja to get it)")
  2123. def _prepare_ldflags(extra_ldflags, with_cuda, with_sycl, verbose, is_standalone):
  2124. if IS_WINDOWS:
  2125. python_lib_path = os.path.join(sys.base_exec_prefix, 'libs')
  2126. extra_ldflags.append('c10.lib')
  2127. if with_cuda:
  2128. extra_ldflags.append('c10_hip.lib' if IS_HIP_EXTENSION else 'c10_cuda.lib')
  2129. if with_sycl:
  2130. extra_ldflags.append('c10_xpu.lib')
  2131. extra_ldflags.append('torch_cpu.lib')
  2132. if with_cuda:
  2133. extra_ldflags.append('torch_hip.lib' if IS_HIP_EXTENSION else 'torch_cuda.lib')
  2134. # /INCLUDE is used to ensure torch_cuda is linked against in a project that relies on it.
  2135. # Related issue: https://github.com/pytorch/pytorch/issues/31611
  2136. extra_ldflags.append('-INCLUDE:?warp_size@cuda@at@@YAHXZ')
  2137. if with_sycl:
  2138. extra_ldflags.append('torch_xpu.lib')
  2139. extra_ldflags.append('torch.lib')
  2140. extra_ldflags.append(f'/LIBPATH:{TORCH_LIB_PATH}')
  2141. if not is_standalone:
  2142. extra_ldflags.append('torch_python.lib')
  2143. extra_ldflags.append(f'/LIBPATH:{python_lib_path}')
  2144. else:
  2145. extra_ldflags.append(f'-L{TORCH_LIB_PATH}')
  2146. extra_ldflags.append('-lc10')
  2147. if with_cuda:
  2148. extra_ldflags.append('-lc10_hip' if IS_HIP_EXTENSION else '-lc10_cuda')
  2149. if with_sycl:
  2150. extra_ldflags.append('-lc10_xpu')
  2151. extra_ldflags.append('-ltorch_cpu')
  2152. if with_cuda:
  2153. extra_ldflags.append('-ltorch_hip' if IS_HIP_EXTENSION else '-ltorch_cuda')
  2154. if with_sycl:
  2155. extra_ldflags.append('-ltorch_xpu')
  2156. extra_ldflags.append('-ltorch')
  2157. if not is_standalone:
  2158. extra_ldflags.append('-ltorch_python')
  2159. if is_standalone:
  2160. extra_ldflags.append(f"-Wl,-rpath,{TORCH_LIB_PATH}")
  2161. if with_cuda:
  2162. if verbose:
  2163. logger.info('Detected CUDA files, patching ldflags')
  2164. if IS_WINDOWS and not IS_HIP_EXTENSION:
  2165. extra_ldflags.append(f'/LIBPATH:{_join_cuda_home("lib", "x64")}')
  2166. extra_ldflags.append('cudart.lib')
  2167. if CUDNN_HOME is not None:
  2168. extra_ldflags.append(f'/LIBPATH:{os.path.join(CUDNN_HOME, "lib", "x64")}')
  2169. elif not IS_HIP_EXTENSION:
  2170. extra_lib_dir = "lib64"
  2171. if (not os.path.exists(_join_cuda_home(extra_lib_dir)) and
  2172. os.path.exists(_join_cuda_home("lib"))):
  2173. # 64-bit CUDA may be installed in "lib"
  2174. # Note that it's also possible both don't exist (see _find_cuda_home) - in that case we stay with "lib64"
  2175. extra_lib_dir = "lib"
  2176. extra_ldflags.append(f'-L{_join_cuda_home(extra_lib_dir)}')
  2177. extra_ldflags.append('-lcudart')
  2178. if CUDNN_HOME is not None:
  2179. extra_ldflags.append(f'-L{os.path.join(CUDNN_HOME, "lib64")}')
  2180. elif IS_HIP_EXTENSION:
  2181. if IS_WINDOWS:
  2182. extra_ldflags.append(f'/LIBPATH:{_join_rocm_home("lib")}')
  2183. extra_ldflags.append('amdhip64.lib')
  2184. else:
  2185. extra_ldflags.append(f'-L{_join_rocm_home("lib")}')
  2186. extra_ldflags.append('-lamdhip64')
  2187. if with_sycl:
  2188. if IS_WINDOWS:
  2189. extra_ldflags.append(f'/LIBPATH:{_join_sycl_home("lib")}')
  2190. extra_ldflags.append('sycl.lib')
  2191. else:
  2192. extra_ldflags.append(f'-L{_join_sycl_home("lib")}')
  2193. extra_ldflags.append('-lsycl')
  2194. return extra_ldflags
  2195. def _get_cuda_arch_flags(cflags: list[str] | None = None) -> list[str]:
  2196. """
  2197. Determine CUDA arch flags to use.
  2198. For an arch, say "6.1", the added compile flag will be
  2199. ``-gencode=arch=compute_61,code=sm_61``.
  2200. For an added "+PTX", an additional
  2201. ``-gencode=arch=compute_xx,code=compute_xx`` is added.
  2202. See select_compute_arch.cmake for corresponding named and supported arches
  2203. when building with CMake.
  2204. """
  2205. # If cflags is given, there may already be user-provided arch flags in it
  2206. # (from `extra_compile_args`)
  2207. if cflags is not None:
  2208. for flag in cflags:
  2209. if 'TORCH_EXTENSION_NAME' in flag:
  2210. continue
  2211. if 'arch' in flag:
  2212. return []
  2213. # Note: keep combined names ("arch1+arch2") above single names, otherwise
  2214. # string replacement may not do the right thing
  2215. named_arches = collections.OrderedDict([
  2216. ('Kepler+Tesla', '3.7'),
  2217. ('Kepler', '3.5+PTX'),
  2218. ('Maxwell+Tegra', '5.3'),
  2219. ('Maxwell', '5.0;5.2+PTX'),
  2220. ('Pascal', '6.0;6.1+PTX'),
  2221. ('Volta+Tegra', '7.2'),
  2222. ('Volta', '7.0+PTX'),
  2223. ('Turing', '7.5+PTX'),
  2224. ('Ampere+Tegra', '8.7'),
  2225. ('Ampere', '8.0;8.6+PTX'),
  2226. ('Ada', '8.9+PTX'),
  2227. ('Hopper', '9.0+PTX'),
  2228. ('Blackwell+Tegra', '11.0'),
  2229. ('Blackwell', '10.0;10.3;12.0;12.1+PTX'),
  2230. ])
  2231. supported_arches = ['3.5', '3.7', '5.0', '5.2', '5.3', '6.0', '6.1', '6.2',
  2232. '7.0', '7.2', '7.5', '8.0', '8.6', '8.7', '8.9', '9.0', '9.0a',
  2233. '10.0', '10.0a', '11.0', '11.0a', '10.3', '10.3a', '12.0',
  2234. '12.0a', '12.1', '12.1a']
  2235. valid_arch_strings = supported_arches + [s + "+PTX" for s in supported_arches]
  2236. # The default is sm_30 for CUDA 9.x and 10.x
  2237. # First check for an env var (same as used by the main setup.py)
  2238. # Can be one or more architectures, e.g. "6.1" or "3.5;5.2;6.0;6.1;7.0+PTX"
  2239. # See cmake/Modules_CUDA_fix/upstream/FindCUDA/select_compute_arch.cmake
  2240. _arch_list = os.environ.get('TORCH_CUDA_ARCH_LIST', None)
  2241. # If not given or set as native, determine what's best for the GPU / CUDA version that can be found
  2242. if not _arch_list or _arch_list == "native":
  2243. arch_list = []
  2244. # the assumption is that the extension should run on any of the currently visible cards,
  2245. # which could be of different types - therefore all archs for visible cards should be included
  2246. for i in range(torch.cuda.device_count()):
  2247. capability = torch.cuda.get_device_capability(i)
  2248. supported_sm = [int("".join(re.findall(r"\d+", arch.split('_')[1])))
  2249. for arch in torch.cuda.get_arch_list() if 'sm_' in arch]
  2250. max_supported_sm = max((sm // 10, sm % 10) for sm in supported_sm)
  2251. # Capability of the device may be higher than what's supported by the user's
  2252. # NVCC, causing compilation error. User's NVCC is expected to match the one
  2253. # used to build pytorch, so we use the maximum supported capability of pytorch
  2254. # to clamp the capability.
  2255. capability = min(max_supported_sm, capability)
  2256. arch = f'{capability[0]}.{capability[1]}'
  2257. if arch not in arch_list:
  2258. arch_list.append(arch)
  2259. arch_list = sorted(arch_list)
  2260. arch_list[-1] += '+PTX'
  2261. if not _arch_list:
  2262. # Only log on rank 0 in distributed settings to avoid spam
  2263. if not torch.distributed.is_available() or not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:
  2264. arch_list_str = ';'.join(arch_list)
  2265. logger.debug(
  2266. "TORCH_CUDA_ARCH_LIST is not set, using TORCH_CUDA_ARCH_LIST='%s' "
  2267. "for visible GPU architectures. Set os.environ['TORCH_CUDA_ARCH_LIST'] to override.",
  2268. arch_list_str)
  2269. else:
  2270. # Deal with lists that are ' ' separated (only deal with ';' after)
  2271. _arch_list = _arch_list.replace(' ', ';')
  2272. # Expand named arches
  2273. for named_arch, archival in named_arches.items():
  2274. _arch_list = _arch_list.replace(named_arch, archival)
  2275. arch_list = _arch_list.split(';')
  2276. flags = []
  2277. for arch in arch_list:
  2278. if arch not in valid_arch_strings:
  2279. raise ValueError(f"Unknown CUDA arch ({arch}) or GPU not supported")
  2280. else:
  2281. # Handle both single and double-digit architecture versions
  2282. version = arch.split('+')[0] # Remove "+PTX" if present
  2283. major, minor = version.split('.')
  2284. num = f"{major}{minor}"
  2285. flags.append(f'-gencode=arch=compute_{num},code=sm_{num}')
  2286. if arch.endswith('+PTX'):
  2287. flags.append(f'-gencode=arch=compute_{num},code=compute_{num}')
  2288. return sorted(set(flags))
  2289. def _get_rocm_arch_flags(cflags: list[str] | None = None) -> list[str]:
  2290. # If cflags is given, there may already be user-provided arch flags in it
  2291. # (from `extra_compile_args`). If user also specified -fgpu-rdc or -fno-gpu-rdc, we
  2292. # assume they know what they're doing. Otherwise, we force -fno-gpu-rdc default.
  2293. has_gpu_rdc_flag = False
  2294. if cflags is not None:
  2295. has_custom_flags = False
  2296. for flag in cflags:
  2297. if 'amdgpu-target' in flag or 'offload-arch' in flag:
  2298. has_custom_flags = True
  2299. elif 'gpu-rdc' in flag:
  2300. has_gpu_rdc_flag = True
  2301. if has_custom_flags:
  2302. return [] if has_gpu_rdc_flag else ['-fno-gpu-rdc']
  2303. # Use same defaults as used for building PyTorch
  2304. # Allow env var to override, just like during initial cmake build.
  2305. _archs = os.environ.get('PYTORCH_ROCM_ARCH', None)
  2306. if not _archs:
  2307. archFlags = torch._C._cuda_getArchFlags()
  2308. if archFlags:
  2309. archs = archFlags.split()
  2310. else:
  2311. archs = []
  2312. logger.warning(
  2313. "Failed to auto-detect ROCm architecture. Extensions will be compiled "
  2314. "without architecture-specific optimizations. Set PYTORCH_ROCM_ARCH "
  2315. "environment variable to specify target architectures "
  2316. "(e.g., export PYTORCH_ROCM_ARCH='gfx90a;gfx942')."
  2317. )
  2318. else:
  2319. archs = _archs.replace(' ', ';').split(';')
  2320. flags = [f'--offload-arch={arch}' for arch in archs]
  2321. flags += [] if has_gpu_rdc_flag else ['-fno-gpu-rdc']
  2322. return flags
  2323. def _get_build_directory(name: str, verbose: bool) -> str:
  2324. """
  2325. Get the build directory for an extension.
  2326. Args:
  2327. name: The name of the extension
  2328. verbose: Whether to print verbose information
  2329. Returns:
  2330. The path to the build directory
  2331. """
  2332. root_extensions_directory = os.environ.get('TORCH_EXTENSIONS_DIR')
  2333. if root_extensions_directory is None:
  2334. root_extensions_directory = get_default_build_root()
  2335. # Determine GPU accelerator prefix based on available accelerators. Fallback to CPU.
  2336. # Priority: ROCm/HIP > CUDA > CPU
  2337. # Note: torch.backends.cuda.is_built() returns True for both CUDA and ROCm,
  2338. # so we need to check torch.version.hip to distinguish them
  2339. if torch.version.hip is not None:
  2340. accelerator_str = f'rocm{torch.version.hip.replace(".", "")}'
  2341. elif torch.version.cuda is not None:
  2342. accelerator_str = f'cu{torch.version.cuda.replace(".", "")}'
  2343. else:
  2344. accelerator_str = 'cpu'
  2345. python_version = f'py{sys.version_info.major}{sys.version_info.minor}{getattr(sys, "abiflags", "")}'
  2346. build_folder = f'{python_version}_{accelerator_str}'
  2347. root_extensions_directory = os.path.join(
  2348. root_extensions_directory, build_folder)
  2349. if verbose:
  2350. logger.info('Using %s as PyTorch extensions root...', root_extensions_directory)
  2351. build_directory = os.path.join(root_extensions_directory, name)
  2352. if not os.path.exists(build_directory):
  2353. if verbose:
  2354. logger.debug('Creating extension directory %s...', build_directory)
  2355. # This is like mkdir -p, i.e. will also create parent directories.
  2356. os.makedirs(build_directory, exist_ok=True)
  2357. return build_directory
  2358. def _get_num_workers(verbose: bool) -> int | None:
  2359. max_jobs = os.environ.get('MAX_JOBS')
  2360. if max_jobs is not None and max_jobs.isdigit():
  2361. if verbose:
  2362. logger.debug('Using envvar MAX_JOBS (%s) as the number of workers...', max_jobs)
  2363. return int(max_jobs)
  2364. if verbose:
  2365. logger.info(
  2366. 'Allowing ninja to set a default number of workers... '
  2367. '(overridable by setting the environment variable MAX_JOBS=N)'
  2368. )
  2369. return None
  2370. def _get_vc_env(vc_arch: str) -> dict[str, str]:
  2371. try:
  2372. from setuptools import distutils # type: ignore[attr-defined]
  2373. return distutils._msvccompiler._get_vc_env(vc_arch)
  2374. except AttributeError:
  2375. try:
  2376. from setuptools._distutils import _msvccompiler
  2377. return _msvccompiler._get_vc_env(vc_arch) # type: ignore[attr-defined]
  2378. except AttributeError:
  2379. from setuptools._distutils.compilers.C import msvc
  2380. return msvc._get_vc_env(vc_arch) # type: ignore[attr-defined]
  2381. def _run_ninja_build(build_directory: str, verbose: bool, error_prefix: str) -> None:
  2382. command = ['ninja', '-v']
  2383. num_workers = _get_num_workers(verbose)
  2384. if num_workers is not None:
  2385. command.extend(['-j', str(num_workers)])
  2386. env = os.environ.copy()
  2387. # Try to activate the vc env for the users
  2388. if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' not in env:
  2389. from setuptools import distutils # type: ignore[attr-defined]
  2390. plat_name = distutils.util.get_platform()
  2391. plat_spec = PLAT_TO_VCVARS[plat_name]
  2392. vc_env = {k.upper(): v for k, v in _get_vc_env(plat_spec).items()}
  2393. for k, v in env.items():
  2394. uk = k.upper()
  2395. if uk not in vc_env:
  2396. vc_env[uk] = v
  2397. env = vc_env
  2398. try:
  2399. sys.stdout.flush()
  2400. sys.stderr.flush()
  2401. # Warning: don't pass stdout=None to subprocess.run to get output.
  2402. # subprocess.run assumes that sys.__stdout__ has not been modified and
  2403. # attempts to write to it by default. However, when we call _run_ninja_build
  2404. # from ahead-of-time cpp extensions, the following happens:
  2405. # 1) If the stdout encoding is not utf-8, setuptools detaches __stdout__.
  2406. # https://github.com/pypa/setuptools/blob/7e97def47723303fafabe48b22168bbc11bb4821/setuptools/dist.py#L1110
  2407. # (it probably shouldn't do this)
  2408. # 2) subprocess.run (on POSIX, with no stdout override) relies on
  2409. # __stdout__ not being detached:
  2410. # https://github.com/python/cpython/blob/c352e6c7446c894b13643f538db312092b351789/Lib/subprocess.py#L1214
  2411. # To work around this, we pass in the fileno directly and hope that
  2412. # it is valid.
  2413. stdout_fileno = 1
  2414. subprocess.run(
  2415. command,
  2416. shell=IS_WINDOWS and IS_HIP_EXTENSION,
  2417. stdout=stdout_fileno if verbose else subprocess.PIPE,
  2418. stderr=subprocess.STDOUT,
  2419. cwd=build_directory,
  2420. check=True,
  2421. env=env)
  2422. except subprocess.CalledProcessError as e:
  2423. # Python 2 and 3 compatible way of getting the error object.
  2424. _, error, _ = sys.exc_info()
  2425. # error.output contains the stdout and stderr of the build attempt.
  2426. message = error_prefix
  2427. # `error` is a CalledProcessError (which has an `output`) attribute, but
  2428. # mypy thinks it's Optional[BaseException] and doesn't narrow
  2429. if hasattr(error, 'output') and error.output: # type: ignore[union-attr]
  2430. message += f": {error.output.decode(*SUBPROCESS_DECODE_ARGS)}" # type: ignore[union-attr]
  2431. raise RuntimeError(message) from e
  2432. def _get_exec_path(module_name, path):
  2433. if IS_WINDOWS and TORCH_LIB_PATH not in os.getenv('PATH', '').split(';'):
  2434. torch_lib_in_path = any(
  2435. os.path.exists(p) and os.path.samefile(p, TORCH_LIB_PATH)
  2436. for p in os.getenv('PATH', '').split(';')
  2437. )
  2438. if not torch_lib_in_path:
  2439. os.environ['PATH'] = f"{TORCH_LIB_PATH};{os.getenv('PATH', '')}"
  2440. return os.path.join(path, f'{module_name}{EXEC_EXT}')
  2441. def _import_module_from_library(module_name, path, is_python_module):
  2442. filepath = os.path.join(path, f"{module_name}{LIB_EXT}")
  2443. if is_python_module:
  2444. # https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
  2445. spec = importlib.util.spec_from_file_location(module_name, filepath)
  2446. if spec is None:
  2447. raise AssertionError(f"Failed to create spec for module {module_name} at {filepath}")
  2448. module = importlib.util.module_from_spec(spec)
  2449. if not isinstance(spec.loader, importlib.abc.Loader):
  2450. raise AssertionError("spec.loader is not a valid importlib Loader")
  2451. spec.loader.exec_module(module)
  2452. return module
  2453. else:
  2454. torch.ops.load_library(filepath)
  2455. return filepath
  2456. def _write_ninja_file_to_build_library(path,
  2457. name,
  2458. sources,
  2459. extra_cflags,
  2460. extra_cuda_cflags,
  2461. extra_sycl_cflags,
  2462. extra_ldflags,
  2463. extra_include_paths,
  2464. with_cuda,
  2465. with_sycl,
  2466. is_standalone) -> None:
  2467. extra_cflags = [flag.strip() for flag in extra_cflags]
  2468. extra_cuda_cflags = [flag.strip() for flag in extra_cuda_cflags]
  2469. extra_sycl_cflags = [flag.strip() for flag in extra_sycl_cflags]
  2470. extra_ldflags = [flag.strip() for flag in extra_ldflags]
  2471. extra_include_paths = [flag.strip() for flag in extra_include_paths]
  2472. # Turn into absolute paths so we can emit them into the ninja build
  2473. # file wherever it is.
  2474. user_includes = [os.path.abspath(file) for file in extra_include_paths]
  2475. # include_paths() gives us the location of torch/extension.h
  2476. # TODO generalize with_cuda as specific device type.
  2477. if with_cuda:
  2478. system_includes = include_paths("cuda")
  2479. elif with_sycl:
  2480. system_includes = include_paths("xpu")
  2481. else:
  2482. system_includes = include_paths("cpu")
  2483. # sysconfig.get_path('include') gives us the location of Python.h
  2484. # Explicitly specify 'posix_prefix' scheme on non-Windows platforms to workaround error on some MacOS
  2485. # installations where default `get_path` points to non-existing `/Library/Python/M.m/include` folder
  2486. python_include_path = sysconfig.get_path('include', scheme='nt' if IS_WINDOWS else 'posix_prefix')
  2487. if python_include_path is not None:
  2488. system_includes.append(python_include_path)
  2489. common_cflags = []
  2490. if not is_standalone:
  2491. common_cflags.append(f'-DTORCH_EXTENSION_NAME={name}')
  2492. common_cflags.append('-DTORCH_API_INCLUDE_EXTENSION_H')
  2493. # Windows does not understand `-isystem` and quotes flags later.
  2494. if IS_WINDOWS:
  2495. common_cflags += [f'-I{include}' for include in user_includes + system_includes]
  2496. else:
  2497. common_cflags += [f'-I{shlex.quote(include)}' for include in user_includes]
  2498. common_cflags += [f'-isystem {shlex.quote(include)}' for include in system_includes]
  2499. if IS_WINDOWS:
  2500. COMMON_HIP_FLAGS.extend(['-fms-runtime-lib=dll'])
  2501. cflags = common_cflags + ['/std:c++17'] + extra_cflags
  2502. cflags += COMMON_MSVC_FLAGS + (COMMON_HIP_FLAGS if IS_HIP_EXTENSION else [])
  2503. cflags = _nt_quote_args(cflags)
  2504. else:
  2505. cflags = common_cflags + ['-fPIC', '-std=c++17'] + extra_cflags
  2506. if with_cuda and IS_HIP_EXTENSION:
  2507. cuda_flags = ['-DWITH_HIP'] + common_cflags + extra_cflags + COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS
  2508. cuda_flags = cuda_flags + ['-std=c++17']
  2509. cuda_flags += _get_rocm_arch_flags(cuda_flags)
  2510. cuda_flags += extra_cuda_cflags
  2511. if IS_WINDOWS:
  2512. cuda_flags = _nt_quote_args(cuda_flags)
  2513. elif with_cuda:
  2514. cuda_flags = common_cflags + COMMON_NVCC_FLAGS + _get_cuda_arch_flags(extra_cuda_cflags)
  2515. if IS_WINDOWS:
  2516. for flag in COMMON_MSVC_FLAGS:
  2517. cuda_flags = ['-Xcompiler', flag] + cuda_flags
  2518. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  2519. cuda_flags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cuda_flags
  2520. cuda_flags = cuda_flags + ['-std=c++17']
  2521. cuda_flags = _nt_quote_args(cuda_flags)
  2522. cuda_flags += _nt_quote_args(extra_cuda_cflags)
  2523. else:
  2524. cuda_flags += ['--compiler-options', "'-fPIC'"]
  2525. cuda_flags += extra_cuda_cflags
  2526. if not any(flag.startswith('-std=') for flag in cuda_flags):
  2527. cuda_flags.append('-std=c++17')
  2528. cc_env = os.getenv("CC")
  2529. if cc_env is not None:
  2530. cuda_flags = ['-ccbin', cc_env] + cuda_flags
  2531. else:
  2532. cuda_flags = None
  2533. if with_sycl:
  2534. sycl_cflags = cflags + _COMMON_SYCL_FLAGS
  2535. sycl_cflags += extra_sycl_cflags
  2536. _append_sycl_targets_if_missing(sycl_cflags)
  2537. _append_sycl_std_if_no_std_present(sycl_cflags)
  2538. host_cflags = cflags
  2539. # escaping quoted arguments to pass them thru SYCL compiler
  2540. icpx_version = _get_icpx_version()
  2541. if int(icpx_version) < 20250200:
  2542. host_cflags = [item.replace('\\"', '\\\\"') for item in host_cflags]
  2543. sycl_cflags += _wrap_sycl_host_flags(host_cflags)
  2544. sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy()
  2545. sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_cflags)
  2546. else:
  2547. sycl_cflags = None
  2548. sycl_dlink_post_cflags = None
  2549. def object_file_path(source_file: str) -> str:
  2550. # '/path/to/file.cpp' -> 'file'
  2551. file_name = os.path.splitext(os.path.basename(source_file))[0]
  2552. if _is_cuda_file(source_file) and with_cuda:
  2553. # Use a different object filename in case a C++ and CUDA file have
  2554. # the same filename but different extension (.cpp vs. .cu).
  2555. target = f'{file_name}.cuda.o'
  2556. elif _is_sycl_file(source_file) and with_sycl:
  2557. target = f'{file_name}.sycl.o'
  2558. else:
  2559. target = f'{file_name}.o'
  2560. return target
  2561. objects = [object_file_path(src) for src in sources]
  2562. ldflags = ([] if is_standalone else [SHARED_FLAG]) + extra_ldflags
  2563. # The darwin linker needs explicit consent to ignore unresolved symbols.
  2564. if IS_MACOS:
  2565. ldflags.append('-undefined dynamic_lookup')
  2566. elif IS_WINDOWS:
  2567. ldflags = _nt_quote_args(ldflags)
  2568. ext = EXEC_EXT if is_standalone else LIB_EXT
  2569. library_target = f'{name}{ext}'
  2570. _write_ninja_file(
  2571. path=path,
  2572. cflags=cflags,
  2573. post_cflags=None,
  2574. cuda_cflags=cuda_flags,
  2575. cuda_post_cflags=None,
  2576. cuda_dlink_post_cflags=None,
  2577. sycl_cflags=sycl_cflags,
  2578. sycl_post_cflags=[],
  2579. sycl_dlink_post_cflags=sycl_dlink_post_cflags,
  2580. sources=sources,
  2581. objects=objects,
  2582. ldflags=ldflags,
  2583. library_target=library_target,
  2584. with_cuda=with_cuda,
  2585. with_sycl=with_sycl)
  2586. def _write_ninja_file(path,
  2587. cflags,
  2588. post_cflags,
  2589. cuda_cflags,
  2590. cuda_post_cflags,
  2591. cuda_dlink_post_cflags,
  2592. sycl_cflags,
  2593. sycl_post_cflags,
  2594. sycl_dlink_post_cflags,
  2595. sources,
  2596. objects,
  2597. ldflags,
  2598. library_target,
  2599. with_cuda,
  2600. with_sycl) -> None:
  2601. r"""Write a ninja file that does the desired compiling and linking.
  2602. `path`: Where to write this file
  2603. `cflags`: list of flags to pass to $cxx. Can be None.
  2604. `post_cflags`: list of flags to append to the $cxx invocation. Can be None.
  2605. `cuda_cflags`: list of flags to pass to $nvcc. Can be None.
  2606. `cuda_post_cflags`: list of flags to append to the $nvcc invocation. Can be None.
  2607. `cuda_dlink_post_cflags`: list of flags to append to the $nvcc device code link invocation. Can be None.
  2608. `sycl_cflags`: list of flags to pass to SYCL compiler. Can be None.
  2609. `sycl_post_cflags`: list of flags to append to the SYCL compiler invocation. Can be None.
  2610. `sycl_dlink_post_cflags`: list of flags to append to the SYCL compiler device code link invocation. Can be None.
  2611. e.
  2612. `sources`: list of paths to source files
  2613. `objects`: list of desired paths to objects, one per source.
  2614. `ldflags`: list of flags to pass to linker. Can be None.
  2615. `library_target`: Name of the output library. Can be None; in that case,
  2616. we do no linking.
  2617. `with_cuda`: If we should be compiling with CUDA.
  2618. """
  2619. def sanitize_flags(flags):
  2620. if flags is None:
  2621. return []
  2622. else:
  2623. return [flag.strip() for flag in flags]
  2624. cflags = sanitize_flags(cflags)
  2625. post_cflags = sanitize_flags(post_cflags)
  2626. cuda_cflags = sanitize_flags(cuda_cflags)
  2627. cuda_post_cflags = sanitize_flags(cuda_post_cflags)
  2628. cuda_dlink_post_cflags = sanitize_flags(cuda_dlink_post_cflags)
  2629. sycl_cflags = sanitize_flags(sycl_cflags)
  2630. sycl_post_cflags = sanitize_flags(sycl_post_cflags)
  2631. sycl_dlink_post_cflags = sanitize_flags(sycl_dlink_post_cflags)
  2632. ldflags = sanitize_flags(ldflags)
  2633. # Sanity checks...
  2634. if len(sources) != len(objects):
  2635. raise AssertionError("sources and objects lists must be the same length")
  2636. if len(sources) == 0:
  2637. raise AssertionError("At least one source is required to build a library")
  2638. compiler = get_cxx_compiler()
  2639. # Version 1.3 is required for the `deps` directive.
  2640. config = ['ninja_required_version = 1.3']
  2641. config.append(f'cxx = {compiler}')
  2642. if with_cuda or cuda_dlink_post_cflags:
  2643. if "PYTORCH_NVCC" in os.environ:
  2644. nvcc = os.getenv("PYTORCH_NVCC") # user can set nvcc compiler with ccache using the environment variable here
  2645. else:
  2646. if IS_HIP_EXTENSION:
  2647. nvcc = _get_hipcc_path()
  2648. else:
  2649. nvcc = _join_cuda_home('bin', 'nvcc')
  2650. config.append(f'nvcc = {nvcc}')
  2651. if with_sycl or sycl_dlink_post_cflags:
  2652. sycl = 'icx' if IS_WINDOWS else 'icpx'
  2653. config.append(f'sycl = {sycl}')
  2654. if IS_HIP_EXTENSION:
  2655. post_cflags = COMMON_HIP_FLAGS + post_cflags
  2656. flags = [f'cflags = {" ".join(cflags)}']
  2657. flags.append(f'post_cflags = {" ".join(post_cflags)}')
  2658. if with_cuda:
  2659. flags.append(f'cuda_cflags = {" ".join(cuda_cflags)}')
  2660. flags.append(f'cuda_post_cflags = {" ".join(cuda_post_cflags)}')
  2661. flags.append(f'cuda_dlink_post_cflags = {" ".join(cuda_dlink_post_cflags)}')
  2662. if with_sycl:
  2663. flags.append(f'sycl_cflags = {" ".join(sycl_cflags)}')
  2664. flags.append(f'sycl_post_cflags = {" ".join(sycl_post_cflags)}')
  2665. flags.append(f'sycl_dlink_post_cflags = {" ".join(sycl_dlink_post_cflags)}')
  2666. flags.append(f'ldflags = {" ".join(ldflags)}')
  2667. # Turn into absolute paths so we can emit them into the ninja build
  2668. # file wherever it is.
  2669. sources = [os.path.abspath(file) for file in sources]
  2670. # See https://ninja-build.org/build.ninja.html for reference.
  2671. compile_rule = ['rule compile']
  2672. if IS_WINDOWS:
  2673. compiler_name = "$cxx" if IS_HIP_EXTENSION else "cl"
  2674. compile_rule.append(
  2675. f' command = {compiler_name} '
  2676. '/showIncludes $cflags -c $in /Fo$out $post_cflags' # codespell:ignore
  2677. )
  2678. if not IS_HIP_EXTENSION:
  2679. compile_rule.append(' deps = msvc')
  2680. else:
  2681. compile_rule.append(
  2682. ' command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflags')
  2683. compile_rule.append(' depfile = $out.d')
  2684. compile_rule.append(' deps = gcc')
  2685. if with_cuda:
  2686. cuda_compile_rule = ['rule cuda_compile']
  2687. nvcc_gendeps = ''
  2688. # -MD is not supported by ROCm
  2689. # Nvcc flag `-MD` is not supported by sccache, which may increase build time.
  2690. if torch.version.cuda is not None and os.getenv('TORCH_EXTENSION_SKIP_NVCC_GEN_DEPENDENCIES', '0') != '1':
  2691. cuda_compile_rule.append(' depfile = $out.d')
  2692. cuda_compile_rule.append(' deps = gcc')
  2693. # Note: non-system deps with nvcc are only supported
  2694. # on Linux so use -MD to make this work on Windows too.
  2695. nvcc_gendeps = '-MD -MF $out.d'
  2696. cuda_compile_rule.append(
  2697. f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags')
  2698. if with_sycl:
  2699. sycl_compile_rule = ['rule sycl_compile']
  2700. # SYCL compiler does not recognize .sycl extension automatically,
  2701. # so we pass '-x c++' explicitly notifying compiler of file format
  2702. sycl_compile_rule.append(
  2703. ' command = $sycl $sycl_cflags -c -x c++ $in -o $out $sycl_post_cflags')
  2704. # Emit one build rule per source to enable incremental build.
  2705. build = []
  2706. for source_file, object_file in zip(sources, objects, strict=True):
  2707. is_cuda_source = _is_cuda_file(source_file) and with_cuda
  2708. is_sycl_source = _is_sycl_file(source_file) and with_sycl
  2709. if is_cuda_source:
  2710. rule = 'cuda_compile'
  2711. elif is_sycl_source:
  2712. rule = 'sycl_compile'
  2713. else:
  2714. rule = 'compile'
  2715. if IS_WINDOWS:
  2716. source_file = source_file.replace(':', '$:')
  2717. object_file = object_file.replace(':', '$:')
  2718. source_file = source_file.replace(" ", "$ ")
  2719. object_file = object_file.replace(" ", "$ ")
  2720. build.append(f'build {object_file}: {rule} {source_file}')
  2721. if cuda_dlink_post_cflags:
  2722. cuda_devlink_out = os.path.join(os.path.dirname(objects[0]), 'dlink.o')
  2723. cuda_devlink_rule = ['rule cuda_devlink']
  2724. cuda_devlink_rule.append(' command = $nvcc $in -o $out $cuda_dlink_post_cflags')
  2725. cuda_devlink = [f'build {cuda_devlink_out}: cuda_devlink {" ".join(objects)}']
  2726. objects += [cuda_devlink_out]
  2727. else:
  2728. cuda_devlink_rule, cuda_devlink = [], []
  2729. if sycl_dlink_post_cflags:
  2730. sycl_devlink_out = os.path.join(os.path.dirname(objects[0]), "sycl_dlink.o")
  2731. if IS_WINDOWS:
  2732. sycl_devlink_objects = [obj.replace(":", "$:") for obj in objects]
  2733. objects += [sycl_devlink_out]
  2734. sycl_devlink_out = sycl_devlink_out.replace(":", "$:")
  2735. else:
  2736. sycl_devlink_objects = list(objects)
  2737. objects += [sycl_devlink_out]
  2738. sycl_devlink_rule = ["rule sycl_devlink"]
  2739. sycl_devlink_rule.append(
  2740. " command = $sycl $in -o $out $sycl_dlink_post_cflags"
  2741. )
  2742. sycl_devlink = [
  2743. f"build {sycl_devlink_out}: sycl_devlink {' '.join(sycl_devlink_objects)}"
  2744. ]
  2745. else:
  2746. sycl_devlink_rule, sycl_devlink = [], []
  2747. if library_target is not None:
  2748. link_rule = ['rule link']
  2749. if IS_WINDOWS:
  2750. cl_paths = subprocess.check_output(['where',
  2751. 'cl']).decode(*SUBPROCESS_DECODE_ARGS).split('\r\n')
  2752. if len(cl_paths) >= 1:
  2753. cl_path = os.path.dirname(cl_paths[0]).replace(':', '$:')
  2754. else:
  2755. raise RuntimeError("MSVC is required to load C++ extensions")
  2756. link_rule.append(f' command = "{cl_path}/link.exe" $in /nologo $ldflags /out:$out')
  2757. else:
  2758. link_rule.append(' command = $cxx $in $ldflags -o $out')
  2759. link = [f'build {library_target}: link {" ".join(objects)}']
  2760. default = [f'default {library_target}']
  2761. else:
  2762. link_rule, link, default = [], [], []
  2763. # 'Blocks' should be separated by newlines, for visual benefit.
  2764. blocks = [config, flags, compile_rule]
  2765. if with_cuda:
  2766. blocks.append(cuda_compile_rule) # type: ignore[possibly-undefined]
  2767. if with_sycl:
  2768. blocks.append(sycl_compile_rule) # type: ignore[possibly-undefined]
  2769. blocks += [cuda_devlink_rule, sycl_devlink_rule, link_rule, build, cuda_devlink, sycl_devlink, link, default]
  2770. content = "\n\n".join("\n".join(b) for b in blocks)
  2771. # Ninja requires a new lines at the end of the .ninja file
  2772. content += "\n"
  2773. _maybe_write(path, content)
  2774. def _join_cuda_home(*paths) -> str:
  2775. """
  2776. Join paths with CUDA_HOME, or raises an error if it CUDA_HOME is not set.
  2777. This is basically a lazy way of raising an error for missing $CUDA_HOME
  2778. only once we need to get any CUDA-specific path.
  2779. """
  2780. if CUDA_HOME is None:
  2781. raise OSError('CUDA_HOME environment variable is not set. '
  2782. 'Please set it to your CUDA install root.')
  2783. return os.path.join(CUDA_HOME, *paths)
  2784. def _is_cuda_file(path: str) -> bool:
  2785. valid_ext = ['.cu', '.cuh']
  2786. if IS_HIP_EXTENSION:
  2787. valid_ext.append('.hip')
  2788. return os.path.splitext(path)[1] in valid_ext
  2789. def _is_sycl_file(path: str) -> bool:
  2790. valid_ext = ['.sycl']
  2791. return os.path.splitext(path)[1] in valid_ext