cpp_extension.py 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  1. import copy
  2. import glob
  3. import importlib
  4. import importlib.abc
  5. import os
  6. import re
  7. import shlex
  8. import setuptools
  9. import subprocess
  10. import sys
  11. import sysconfig
  12. import warnings
  13. import collections
  14. import torch
  15. import torch._appdirs
  16. from .file_baton import FileBaton
  17. from ._cpp_extension_versioner import ExtensionVersioner
  18. from .hipify import hipify_python
  19. from .hipify.hipify_python import GeneratedFileCleaner
  20. from typing import Dict, List, Optional, Union, Tuple
  21. from torch.torch_version import TorchVersion
  22. from setuptools.command.build_ext import build_ext
  23. from pkg_resources import packaging # type: ignore[attr-defined]
  24. IS_WINDOWS = sys.platform == 'win32'
  25. IS_MACOS = sys.platform.startswith('darwin')
  26. IS_LINUX = sys.platform.startswith('linux')
  27. LIB_EXT = '.pyd' if IS_WINDOWS else '.so'
  28. EXEC_EXT = '.exe' if IS_WINDOWS else ''
  29. CLIB_PREFIX = '' if IS_WINDOWS else 'lib'
  30. CLIB_EXT = '.dll' if IS_WINDOWS else '.so'
  31. SHARED_FLAG = '/DLL' if IS_WINDOWS else '-shared'
  32. _HERE = os.path.abspath(__file__)
  33. _TORCH_PATH = os.path.dirname(os.path.dirname(_HERE))
  34. TORCH_LIB_PATH = os.path.join(_TORCH_PATH, 'lib')
  35. SUBPROCESS_DECODE_ARGS = ('oem',) if IS_WINDOWS else ()
  36. MINIMUM_GCC_VERSION = (5, 0, 0)
  37. MINIMUM_MSVC_VERSION = (19, 0, 24215)
  38. VersionRange = Tuple[Tuple[int, ...], Tuple[int, ...]]
  39. VersionMap = Dict[str, VersionRange]
  40. # The following values were taken from the following GitHub gist that
  41. # summarizes the minimum valid major versions of g++/clang++ for each supported
  42. # CUDA version: https://gist.github.com/ax3l/9489132
  43. # Or from include/crt/host_config.h in the CUDA SDK
  44. # The second value is the exclusive(!) upper bound, i.e. min <= version < max
  45. CUDA_GCC_VERSIONS: VersionMap = {
  46. '11.0': (MINIMUM_GCC_VERSION, (10, 0)),
  47. '11.1': (MINIMUM_GCC_VERSION, (11, 0)),
  48. '11.2': (MINIMUM_GCC_VERSION, (11, 0)),
  49. '11.3': (MINIMUM_GCC_VERSION, (11, 0)),
  50. '11.4': ((6, 0, 0), (12, 0)),
  51. '11.5': ((6, 0, 0), (12, 0)),
  52. '11.6': ((6, 0, 0), (12, 0)),
  53. '11.7': ((6, 0, 0), (12, 0)),
  54. }
  55. MINIMUM_CLANG_VERSION = (3, 3, 0)
  56. CUDA_CLANG_VERSIONS: VersionMap = {
  57. '11.1': (MINIMUM_CLANG_VERSION, (11, 0)),
  58. '11.2': (MINIMUM_CLANG_VERSION, (12, 0)),
  59. '11.3': (MINIMUM_CLANG_VERSION, (12, 0)),
  60. '11.4': (MINIMUM_CLANG_VERSION, (13, 0)),
  61. '11.5': (MINIMUM_CLANG_VERSION, (13, 0)),
  62. '11.6': (MINIMUM_CLANG_VERSION, (14, 0)),
  63. '11.7': (MINIMUM_CLANG_VERSION, (14, 0)),
  64. }
  65. __all__ = ["get_default_build_root", "check_compiler_ok_for_platform", "get_compiler_abi_compatibility_and_version", "BuildExtension",
  66. "CppExtension", "CUDAExtension", "include_paths", "library_paths", "load", "load_inline", "is_ninja_available",
  67. "verify_ninja_availability"]
  68. # Taken directly from python stdlib < 3.9
  69. # See https://github.com/pytorch/pytorch/issues/48617
  70. def _nt_quote_args(args: Optional[List[str]]) -> List[str]:
  71. """Quote command-line arguments for DOS/Windows conventions.
  72. Just wraps every argument which contains blanks in double quotes, and
  73. returns a new argument list.
  74. """
  75. # Cover None-type
  76. if not args:
  77. return []
  78. return [f'"{arg}"' if ' ' in arg else arg for arg in args]
  79. def _find_cuda_home() -> Optional[str]:
  80. r'''Finds the CUDA install path.'''
  81. # Guess #1
  82. cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')
  83. if cuda_home is None:
  84. # Guess #2
  85. try:
  86. which = 'where' if IS_WINDOWS else 'which'
  87. with open(os.devnull, 'w') as devnull:
  88. nvcc = subprocess.check_output([which, 'nvcc'],
  89. stderr=devnull).decode(*SUBPROCESS_DECODE_ARGS).rstrip('\r\n')
  90. cuda_home = os.path.dirname(os.path.dirname(nvcc))
  91. except Exception:
  92. # Guess #3
  93. if IS_WINDOWS:
  94. cuda_homes = glob.glob(
  95. 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*')
  96. if len(cuda_homes) == 0:
  97. cuda_home = ''
  98. else:
  99. cuda_home = cuda_homes[0]
  100. else:
  101. cuda_home = '/usr/local/cuda'
  102. if not os.path.exists(cuda_home):
  103. cuda_home = None
  104. if cuda_home and not torch.cuda.is_available():
  105. print(f"No CUDA runtime is found, using CUDA_HOME='{cuda_home}'",
  106. file=sys.stderr)
  107. return cuda_home
  108. def _find_rocm_home() -> Optional[str]:
  109. r'''Finds the ROCm install path.'''
  110. # Guess #1
  111. rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH')
  112. if rocm_home is None:
  113. # Guess #2
  114. try:
  115. pipe_hipcc = subprocess.Popen(
  116. ["which hipcc | xargs readlink -f"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  117. hipcc, _ = pipe_hipcc.communicate()
  118. # this will be either <ROCM_HOME>/hip/bin/hipcc or <ROCM_HOME>/bin/hipcc
  119. rocm_home = os.path.dirname(os.path.dirname(hipcc.decode(*SUBPROCESS_DECODE_ARGS).rstrip('\r\n')))
  120. if os.path.basename(rocm_home) == 'hip':
  121. rocm_home = os.path.dirname(rocm_home)
  122. except Exception:
  123. # Guess #3
  124. rocm_home = '/opt/rocm'
  125. if not os.path.exists(rocm_home):
  126. rocm_home = None
  127. if rocm_home and torch.version.hip is None:
  128. print(f"No ROCm runtime is found, using ROCM_HOME='{rocm_home}'",
  129. file=sys.stderr)
  130. return rocm_home
  131. def _join_rocm_home(*paths) -> str:
  132. r'''
  133. Joins paths with ROCM_HOME, or raises an error if it ROCM_HOME is not set.
  134. This is basically a lazy way of raising an error for missing $ROCM_HOME
  135. only once we need to get any ROCm-specific path.
  136. '''
  137. if ROCM_HOME is None:
  138. raise EnvironmentError('ROCM_HOME environment variable is not set. '
  139. 'Please set it to your ROCm install root.')
  140. elif IS_WINDOWS:
  141. raise EnvironmentError('Building PyTorch extensions using '
  142. 'ROCm and Windows is not supported.')
  143. return os.path.join(ROCM_HOME, *paths)
  144. ABI_INCOMPATIBILITY_WARNING = '''
  145. !! WARNING !!
  146. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  147. Your compiler ({}) may be ABI-incompatible with PyTorch!
  148. Please use a compiler that is ABI-compatible with GCC 5.0 and above.
  149. See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html.
  150. See https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6
  151. for instructions on how to install GCC 5 or higher.
  152. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  153. !! WARNING !!
  154. '''
  155. WRONG_COMPILER_WARNING = '''
  156. !! WARNING !!
  157. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  158. Your compiler ({user_compiler}) is not compatible with the compiler Pytorch was
  159. built with for this platform, which is {pytorch_compiler} on {platform}. Please
  160. use {pytorch_compiler} to to compile your extension. Alternatively, you may
  161. compile PyTorch from source using {user_compiler}, and then you can also use
  162. {user_compiler} to compile your extension.
  163. See https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md for help
  164. with compiling PyTorch from source.
  165. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  166. !! WARNING !!
  167. '''
  168. CUDA_MISMATCH_MESSAGE = '''
  169. The detected CUDA version ({0}) mismatches the version that was used to compile
  170. PyTorch ({1}). Please make sure to use the same CUDA versions.
  171. '''
  172. CUDA_MISMATCH_WARN = "The detected CUDA version ({0}) has a minor version mismatch with the version that was used to compile PyTorch ({1}). Most likely this shouldn't be a problem."
  173. CUDA_NOT_FOUND_MESSAGE = '''
  174. CUDA was not found on the system, please set the CUDA_HOME or the CUDA_PATH
  175. environment variable or add NVCC to your system PATH. The extension compilation will fail.
  176. '''
  177. ROCM_HOME = _find_rocm_home()
  178. MIOPEN_HOME = _join_rocm_home('miopen') if ROCM_HOME else None
  179. HIP_HOME = _join_rocm_home('hip') if ROCM_HOME else None
  180. IS_HIP_EXTENSION = True if ((ROCM_HOME is not None) and (torch.version.hip is not None)) else False
  181. ROCM_VERSION = None
  182. if torch.version.hip is not None:
  183. ROCM_VERSION = tuple(int(v) for v in torch.version.hip.split('.')[:2])
  184. CUDA_HOME = _find_cuda_home()
  185. CUDNN_HOME = os.environ.get('CUDNN_HOME') or os.environ.get('CUDNN_PATH')
  186. # PyTorch releases have the version pattern major.minor.patch, whereas when
  187. # PyTorch is built from source, we append the git commit hash, which gives
  188. # it the below pattern.
  189. BUILT_FROM_SOURCE_VERSION_PATTERN = re.compile(r'\d+\.\d+\.\d+\w+\+\w+')
  190. COMMON_MSVC_FLAGS = ['/MD', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018', '/wd4190', '/EHsc']
  191. MSVC_IGNORE_CUDAFE_WARNINGS = [
  192. 'base_class_has_different_dll_interface',
  193. 'field_without_dll_interface',
  194. 'dll_interface_conflict_none_assumed',
  195. 'dll_interface_conflict_dllexport_assumed'
  196. ]
  197. COMMON_NVCC_FLAGS = [
  198. '-D__CUDA_NO_HALF_OPERATORS__',
  199. '-D__CUDA_NO_HALF_CONVERSIONS__',
  200. '-D__CUDA_NO_BFLOAT16_CONVERSIONS__',
  201. '-D__CUDA_NO_HALF2_OPERATORS__',
  202. '--expt-relaxed-constexpr'
  203. ]
  204. COMMON_HIP_FLAGS = [
  205. '-fPIC',
  206. '-D__HIP_PLATFORM_HCC__=1',
  207. '-DUSE_ROCM=1',
  208. ]
  209. COMMON_HIPCC_FLAGS = [
  210. '-DCUDA_HAS_FP16=1',
  211. '-D__HIP_NO_HALF_OPERATORS__=1',
  212. '-D__HIP_NO_HALF_CONVERSIONS__=1',
  213. ]
  214. JIT_EXTENSION_VERSIONER = ExtensionVersioner()
  215. PLAT_TO_VCVARS = {
  216. 'win32' : 'x86',
  217. 'win-amd64' : 'x86_amd64',
  218. }
  219. def _is_binary_build() -> bool:
  220. return not BUILT_FROM_SOURCE_VERSION_PATTERN.match(torch.version.__version__)
  221. def _accepted_compilers_for_platform() -> List[str]:
  222. # gnu-c++ and gnu-cc are the conda gcc compilers
  223. return ['clang++', 'clang'] if IS_MACOS else ['g++', 'gcc', 'gnu-c++', 'gnu-cc']
  224. def get_default_build_root() -> str:
  225. r'''
  226. Returns the path to the root folder under which extensions will built.
  227. For each extension module built, there will be one folder underneath the
  228. folder returned by this function. For example, if ``p`` is the path
  229. returned by this function and ``ext`` the name of an extension, the build
  230. folder for the extension will be ``p/ext``.
  231. This directory is **user-specific** so that multiple users on the same
  232. machine won't meet permission issues.
  233. '''
  234. return os.path.realpath(torch._appdirs.user_cache_dir(appname='torch_extensions'))
  235. def check_compiler_ok_for_platform(compiler: str) -> bool:
  236. r'''
  237. Verifies that the compiler is the expected one for the current platform.
  238. Args:
  239. compiler (str): The compiler executable to check.
  240. Returns:
  241. True if the compiler is gcc/g++ on Linux or clang/clang++ on macOS,
  242. and always True for Windows.
  243. '''
  244. if IS_WINDOWS:
  245. return True
  246. which = subprocess.check_output(['which', compiler], stderr=subprocess.STDOUT)
  247. # Use os.path.realpath to resolve any symlinks, in particular from 'c++' to e.g. 'g++'.
  248. compiler_path = os.path.realpath(which.decode(*SUBPROCESS_DECODE_ARGS).strip())
  249. # Check the compiler name
  250. if any(name in compiler_path for name in _accepted_compilers_for_platform()):
  251. return True
  252. # If compiler wrapper is used try to infer the actual compiler by invoking it with -v flag
  253. env = os.environ.copy()
  254. env['LC_ALL'] = 'C' # Don't localize output
  255. version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS)
  256. if IS_LINUX:
  257. # Check for 'gcc' or 'g++' for sccache warpper
  258. pattern = re.compile("^COLLECT_GCC=(.*)$", re.MULTILINE)
  259. results = re.findall(pattern, version_string)
  260. if len(results) != 1:
  261. return False
  262. compiler_path = os.path.realpath(results[0].strip())
  263. # On RHEL/CentOS c++ is a gcc compiler wrapper
  264. if os.path.basename(compiler_path) == 'c++' and 'gcc version' in version_string:
  265. return True
  266. return any(name in compiler_path for name in _accepted_compilers_for_platform())
  267. if IS_MACOS:
  268. # Check for 'clang' or 'clang++'
  269. return version_string.startswith("Apple clang")
  270. return False
  271. def get_compiler_abi_compatibility_and_version(compiler) -> Tuple[bool, TorchVersion]:
  272. r'''
  273. Determine if the given compiler is ABI-compatible with PyTorch alongside
  274. its version.
  275. Args:
  276. compiler (str): The compiler executable name to check (e.g. ``g++``).
  277. Must be executable in a shell process.
  278. Returns:
  279. A tuple that contains a boolean that defines if the compiler is (likely) ABI-incompatible with PyTorch,
  280. followed by a `TorchVersion` string that contains the compiler version separated by dots.
  281. '''
  282. if not _is_binary_build():
  283. return (True, TorchVersion('0.0.0'))
  284. if os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') in ['ON', '1', 'YES', 'TRUE', 'Y']:
  285. return (True, TorchVersion('0.0.0'))
  286. # First check if the compiler is one of the expected ones for the particular platform.
  287. if not check_compiler_ok_for_platform(compiler):
  288. warnings.warn(WRONG_COMPILER_WARNING.format(
  289. user_compiler=compiler,
  290. pytorch_compiler=_accepted_compilers_for_platform()[0],
  291. platform=sys.platform))
  292. return (False, TorchVersion('0.0.0'))
  293. if IS_MACOS:
  294. # There is no particular minimum version we need for clang, so we're good here.
  295. return (True, TorchVersion('0.0.0'))
  296. try:
  297. if IS_LINUX:
  298. minimum_required_version = MINIMUM_GCC_VERSION
  299. versionstr = subprocess.check_output([compiler, '-dumpfullversion', '-dumpversion'])
  300. version = versionstr.decode(*SUBPROCESS_DECODE_ARGS).strip().split('.')
  301. else:
  302. minimum_required_version = MINIMUM_MSVC_VERSION
  303. compiler_info = subprocess.check_output(compiler, stderr=subprocess.STDOUT)
  304. match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.decode(*SUBPROCESS_DECODE_ARGS).strip())
  305. version = ['0', '0', '0'] if match is None else list(match.groups())
  306. except Exception:
  307. _, error, _ = sys.exc_info()
  308. warnings.warn(f'Error checking compiler version for {compiler}: {error}')
  309. return (False, TorchVersion('0.0.0'))
  310. if tuple(map(int, version)) >= minimum_required_version:
  311. return (True, TorchVersion('.'.join(version)))
  312. compiler = f'{compiler} {".".join(version)}'
  313. warnings.warn(ABI_INCOMPATIBILITY_WARNING.format(compiler))
  314. return (False, TorchVersion('.'.join(version)))
  315. def _check_cuda_version(compiler_name: str, compiler_version: TorchVersion) -> None:
  316. if not CUDA_HOME:
  317. raise RuntimeError(CUDA_NOT_FOUND_MESSAGE)
  318. nvcc = os.path.join(CUDA_HOME, 'bin', 'nvcc')
  319. cuda_version_str = subprocess.check_output([nvcc, '--version']).strip().decode(*SUBPROCESS_DECODE_ARGS)
  320. cuda_version = re.search(r'release (\d+[.]\d+)', cuda_version_str)
  321. if cuda_version is None:
  322. return
  323. cuda_str_version = cuda_version.group(1)
  324. cuda_ver = packaging.version.parse(cuda_str_version)
  325. torch_cuda_version = packaging.version.parse(torch.version.cuda)
  326. if cuda_ver != torch_cuda_version:
  327. # major/minor attributes are only available in setuptools>=49.6.0
  328. if getattr(cuda_ver, "major", float("nan")) != getattr(torch_cuda_version, "major", float("nan")):
  329. raise RuntimeError(CUDA_MISMATCH_MESSAGE.format(cuda_str_version, torch.version.cuda))
  330. warnings.warn(CUDA_MISMATCH_WARN.format(cuda_str_version, torch.version.cuda))
  331. if not (sys.platform.startswith('linux') and
  332. os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') not in ['ON', '1', 'YES', 'TRUE', 'Y'] and
  333. _is_binary_build()):
  334. return
  335. cuda_compiler_bounds: VersionMap = CUDA_CLANG_VERSIONS if compiler_name.startswith('clang') else CUDA_GCC_VERSIONS
  336. if cuda_str_version not in cuda_compiler_bounds:
  337. warnings.warn(f'There are no {compiler_name} version bounds defined for CUDA version {cuda_str_version}')
  338. else:
  339. min_compiler_version, max_excl_compiler_version = cuda_compiler_bounds[cuda_str_version]
  340. # Special case for 11.4.0, which has lower compiler bounds than 11.4.1
  341. if "V11.4.48" in cuda_version_str and cuda_compiler_bounds == CUDA_GCC_VERSIONS:
  342. max_excl_compiler_version = (11, 0)
  343. min_compiler_version_str = '.'.join(map(str, min_compiler_version))
  344. max_excl_compiler_version_str = '.'.join(map(str, max_excl_compiler_version))
  345. version_bound_str = f'>={min_compiler_version_str}, <{max_excl_compiler_version_str}'
  346. if compiler_version < TorchVersion(min_compiler_version_str):
  347. raise RuntimeError(
  348. f'The current installed version of {compiler_name} ({compiler_version}) is less '
  349. f'than the minimum required version by CUDA {cuda_str_version} ({min_compiler_version_str}). '
  350. f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).'
  351. )
  352. if compiler_version >= TorchVersion(max_excl_compiler_version_str):
  353. raise RuntimeError(
  354. f'The current installed version of {compiler_name} ({compiler_version}) is greater '
  355. f'than the maximum required version by CUDA {cuda_str_version}. '
  356. f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).'
  357. )
  358. # See below for why we inherit BuildExtension from object.
  359. # https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj-when
  360. class BuildExtension(build_ext):
  361. r'''
  362. A custom :mod:`setuptools` build extension .
  363. This :class:`setuptools.build_ext` subclass takes care of passing the
  364. minimum required compiler flags (e.g. ``-std=c++17``) as well as mixed
  365. C++/CUDA compilation (and support for CUDA files in general).
  366. When using :class:`BuildExtension`, it is allowed to supply a dictionary
  367. for ``extra_compile_args`` (rather than the usual list) that maps from
  368. languages (``cxx`` or ``nvcc``) to a list of additional compiler flags to
  369. supply to the compiler. This makes it possible to supply different flags to
  370. the C++ and CUDA compiler during mixed compilation.
  371. ``use_ninja`` (bool): If ``use_ninja`` is ``True`` (default), then we
  372. attempt to build using the Ninja backend. Ninja greatly speeds up
  373. compilation compared to the standard ``setuptools.build_ext``.
  374. Fallbacks to the standard distutils backend if Ninja is not available.
  375. .. note::
  376. By default, the Ninja backend uses #CPUS + 2 workers to build the
  377. extension. This may use up too many resources on some systems. One
  378. can control the number of workers by setting the `MAX_JOBS` environment
  379. variable to a non-negative number.
  380. '''
  381. @classmethod
  382. def with_options(cls, **options):
  383. r'''
  384. Returns a subclass with alternative constructor that extends any original keyword
  385. arguments to the original constructor with the given options.
  386. '''
  387. class cls_with_options(cls): # type: ignore[misc, valid-type]
  388. def __init__(self, *args, **kwargs):
  389. kwargs.update(options)
  390. super().__init__(*args, **kwargs)
  391. return cls_with_options
  392. def __init__(self, *args, **kwargs) -> None:
  393. super().__init__(*args, **kwargs)
  394. self.no_python_abi_suffix = kwargs.get("no_python_abi_suffix", False)
  395. self.use_ninja = kwargs.get('use_ninja', True)
  396. if self.use_ninja:
  397. # Test if we can use ninja. Fallback otherwise.
  398. msg = ('Attempted to use ninja as the BuildExtension backend but '
  399. '{}. Falling back to using the slow distutils backend.')
  400. if not is_ninja_available():
  401. warnings.warn(msg.format('we could not find ninja.'))
  402. self.use_ninja = False
  403. def finalize_options(self) -> None:
  404. super().finalize_options()
  405. if self.use_ninja:
  406. self.force = True
  407. def build_extensions(self) -> None:
  408. compiler_name, compiler_version = self._check_abi()
  409. cuda_ext = False
  410. extension_iter = iter(self.extensions)
  411. extension = next(extension_iter, None)
  412. while not cuda_ext and extension:
  413. for source in extension.sources:
  414. _, ext = os.path.splitext(source)
  415. if ext == '.cu':
  416. cuda_ext = True
  417. break
  418. extension = next(extension_iter, None)
  419. if cuda_ext and not IS_HIP_EXTENSION:
  420. _check_cuda_version(compiler_name, compiler_version)
  421. for extension in self.extensions:
  422. # Ensure at least an empty list of flags for 'cxx' and 'nvcc' when
  423. # extra_compile_args is a dict. Otherwise, default torch flags do
  424. # not get passed. Necessary when only one of 'cxx' and 'nvcc' is
  425. # passed to extra_compile_args in CUDAExtension, i.e.
  426. # CUDAExtension(..., extra_compile_args={'cxx': [...]})
  427. # or
  428. # CUDAExtension(..., extra_compile_args={'nvcc': [...]})
  429. if isinstance(extension.extra_compile_args, dict):
  430. for ext in ['cxx', 'nvcc']:
  431. if ext not in extension.extra_compile_args:
  432. extension.extra_compile_args[ext] = []
  433. self._add_compile_flag(extension, '-DTORCH_API_INCLUDE_EXTENSION_H')
  434. # See note [Pybind11 ABI constants]
  435. for name in ["COMPILER_TYPE", "STDLIB", "BUILD_ABI"]:
  436. val = getattr(torch._C, f"_PYBIND11_{name}")
  437. if val is not None and not IS_WINDOWS:
  438. self._add_compile_flag(extension, f'-DPYBIND11_{name}="{val}"')
  439. self._define_torch_extension_name(extension)
  440. self._add_gnu_cpp_abi_flag(extension)
  441. if 'nvcc_dlink' in extension.extra_compile_args:
  442. assert self.use_ninja, f"With dlink=True, ninja is required to build cuda extension {extension.name}."
  443. # Register .cu, .cuh and .hip as valid source extensions.
  444. self.compiler.src_extensions += ['.cu', '.cuh', '.hip']
  445. # Save the original _compile method for later.
  446. if self.compiler.compiler_type == 'msvc':
  447. self.compiler._cpp_extensions += ['.cu', '.cuh']
  448. original_compile = self.compiler.compile
  449. original_spawn = self.compiler.spawn
  450. else:
  451. original_compile = self.compiler._compile
  452. def append_std17_if_no_std_present(cflags) -> None:
  453. # NVCC does not allow multiple -std to be passed, so we avoid
  454. # overriding the option if the user explicitly passed it.
  455. cpp_format_prefix = '/{}:' if self.compiler.compiler_type == 'msvc' else '-{}='
  456. cpp_flag_prefix = cpp_format_prefix.format('std')
  457. cpp_flag = cpp_flag_prefix + 'c++17'
  458. if not any(flag.startswith(cpp_flag_prefix) for flag in cflags):
  459. cflags.append(cpp_flag)
  460. def unix_cuda_flags(cflags):
  461. cflags = (COMMON_NVCC_FLAGS +
  462. ['--compiler-options', "'-fPIC'"] +
  463. cflags + _get_cuda_arch_flags(cflags))
  464. # NVCC does not allow multiple -ccbin/--compiler-bindir to be passed, so we avoid
  465. # overriding the option if the user explicitly passed it.
  466. _ccbin = os.getenv("CC")
  467. if (
  468. _ccbin is not None
  469. and not any([flag.startswith('-ccbin') or flag.startswith('--compiler-bindir') for flag in cflags])
  470. ):
  471. cflags.extend(['-ccbin', _ccbin])
  472. return cflags
  473. def convert_to_absolute_paths_inplace(paths):
  474. # Helper function. See Note [Absolute include_dirs]
  475. if paths is not None:
  476. for i in range(len(paths)):
  477. if not os.path.isabs(paths[i]):
  478. paths[i] = os.path.abspath(paths[i])
  479. def unix_wrap_single_compile(obj, src, ext, cc_args, extra_postargs, pp_opts) -> None:
  480. # Copy before we make any modifications.
  481. cflags = copy.deepcopy(extra_postargs)
  482. try:
  483. original_compiler = self.compiler.compiler_so
  484. if _is_cuda_file(src):
  485. nvcc = [_join_rocm_home('bin', 'hipcc') if IS_HIP_EXTENSION else _join_cuda_home('bin', 'nvcc')]
  486. self.compiler.set_executable('compiler_so', nvcc)
  487. if isinstance(cflags, dict):
  488. cflags = cflags['nvcc']
  489. if IS_HIP_EXTENSION:
  490. cflags = COMMON_HIPCC_FLAGS + cflags + _get_rocm_arch_flags(cflags)
  491. else:
  492. cflags = unix_cuda_flags(cflags)
  493. elif isinstance(cflags, dict):
  494. cflags = cflags['cxx']
  495. if IS_HIP_EXTENSION:
  496. cflags = COMMON_HIP_FLAGS + cflags
  497. append_std17_if_no_std_present(cflags)
  498. original_compile(obj, src, ext, cc_args, cflags, pp_opts)
  499. finally:
  500. # Put the original compiler back in place.
  501. self.compiler.set_executable('compiler_so', original_compiler)
  502. def unix_wrap_ninja_compile(sources,
  503. output_dir=None,
  504. macros=None,
  505. include_dirs=None,
  506. debug=0,
  507. extra_preargs=None,
  508. extra_postargs=None,
  509. depends=None):
  510. r"""Compiles sources by outputting a ninja file and running it."""
  511. # NB: I copied some lines from self.compiler (which is an instance
  512. # of distutils.UnixCCompiler). See the following link.
  513. # https://github.com/python/cpython/blob/f03a8f8d5001963ad5b5b28dbd95497e9cc15596/Lib/distutils/ccompiler.py#L564-L567
  514. # This can be fragile, but a lot of other repos also do this
  515. # (see https://github.com/search?q=_setup_compile&type=Code)
  516. # so it is probably OK; we'll also get CI signal if/when
  517. # we update our python version (which is when distutils can be
  518. # upgraded)
  519. # Use absolute path for output_dir so that the object file paths
  520. # (`objects`) get generated with absolute paths.
  521. output_dir = os.path.abspath(output_dir)
  522. # See Note [Absolute include_dirs]
  523. convert_to_absolute_paths_inplace(self.compiler.include_dirs)
  524. _, objects, extra_postargs, pp_opts, _ = \
  525. self.compiler._setup_compile(output_dir, macros,
  526. include_dirs, sources,
  527. depends, extra_postargs)
  528. common_cflags = self.compiler._get_cc_args(pp_opts, debug, extra_preargs)
  529. extra_cc_cflags = self.compiler.compiler_so[1:]
  530. with_cuda = any(map(_is_cuda_file, sources))
  531. # extra_postargs can be either:
  532. # - a dict mapping cxx/nvcc to extra flags
  533. # - a list of extra flags.
  534. if isinstance(extra_postargs, dict):
  535. post_cflags = extra_postargs['cxx']
  536. else:
  537. post_cflags = list(extra_postargs)
  538. if IS_HIP_EXTENSION:
  539. post_cflags = COMMON_HIP_FLAGS + post_cflags
  540. append_std17_if_no_std_present(post_cflags)
  541. cuda_post_cflags = None
  542. cuda_cflags = None
  543. if with_cuda:
  544. cuda_cflags = common_cflags
  545. if isinstance(extra_postargs, dict):
  546. cuda_post_cflags = extra_postargs['nvcc']
  547. else:
  548. cuda_post_cflags = list(extra_postargs)
  549. if IS_HIP_EXTENSION:
  550. cuda_post_cflags = cuda_post_cflags + _get_rocm_arch_flags(cuda_post_cflags)
  551. cuda_post_cflags = COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS + cuda_post_cflags
  552. else:
  553. cuda_post_cflags = unix_cuda_flags(cuda_post_cflags)
  554. append_std17_if_no_std_present(cuda_post_cflags)
  555. cuda_cflags = [shlex.quote(f) for f in cuda_cflags]
  556. cuda_post_cflags = [shlex.quote(f) for f in cuda_post_cflags]
  557. if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs:
  558. cuda_dlink_post_cflags = unix_cuda_flags(extra_postargs['nvcc_dlink'])
  559. else:
  560. cuda_dlink_post_cflags = None
  561. _write_ninja_file_and_compile_objects(
  562. sources=sources,
  563. objects=objects,
  564. cflags=[shlex.quote(f) for f in extra_cc_cflags + common_cflags],
  565. post_cflags=[shlex.quote(f) for f in post_cflags],
  566. cuda_cflags=cuda_cflags,
  567. cuda_post_cflags=cuda_post_cflags,
  568. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  569. build_directory=output_dir,
  570. verbose=True,
  571. with_cuda=with_cuda)
  572. # Return *all* object filenames, not just the ones we just built.
  573. return objects
  574. def win_cuda_flags(cflags):
  575. return (COMMON_NVCC_FLAGS +
  576. cflags + _get_cuda_arch_flags(cflags))
  577. def win_wrap_single_compile(sources,
  578. output_dir=None,
  579. macros=None,
  580. include_dirs=None,
  581. debug=0,
  582. extra_preargs=None,
  583. extra_postargs=None,
  584. depends=None):
  585. self.cflags = copy.deepcopy(extra_postargs)
  586. extra_postargs = None
  587. def spawn(cmd):
  588. # Using regex to match src, obj and include files
  589. src_regex = re.compile('/T(p|c)(.*)')
  590. src_list = [
  591. m.group(2) for m in (src_regex.match(elem) for elem in cmd)
  592. if m
  593. ]
  594. obj_regex = re.compile('/Fo(.*)')
  595. obj_list = [
  596. m.group(1) for m in (obj_regex.match(elem) for elem in cmd)
  597. if m
  598. ]
  599. include_regex = re.compile(r'((\-|\/)I.*)')
  600. include_list = [
  601. m.group(1)
  602. for m in (include_regex.match(elem) for elem in cmd) if m
  603. ]
  604. if len(src_list) >= 1 and len(obj_list) >= 1:
  605. src = src_list[0]
  606. obj = obj_list[0]
  607. if _is_cuda_file(src):
  608. nvcc = _join_cuda_home('bin', 'nvcc')
  609. if isinstance(self.cflags, dict):
  610. cflags = self.cflags['nvcc']
  611. elif isinstance(self.cflags, list):
  612. cflags = self.cflags
  613. else:
  614. cflags = []
  615. cflags = win_cuda_flags(cflags) + ['--use-local-env']
  616. for flag in COMMON_MSVC_FLAGS:
  617. cflags = ['-Xcompiler', flag] + cflags
  618. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  619. cflags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cflags
  620. cmd = [nvcc, '-c', src, '-o', obj] + include_list + cflags
  621. elif isinstance(self.cflags, dict):
  622. cflags = COMMON_MSVC_FLAGS + self.cflags['cxx']
  623. cmd += cflags
  624. elif isinstance(self.cflags, list):
  625. cflags = COMMON_MSVC_FLAGS + self.cflags
  626. cmd += cflags
  627. return original_spawn(cmd)
  628. try:
  629. self.compiler.spawn = spawn
  630. return original_compile(sources, output_dir, macros,
  631. include_dirs, debug, extra_preargs,
  632. extra_postargs, depends)
  633. finally:
  634. self.compiler.spawn = original_spawn
  635. def win_wrap_ninja_compile(sources,
  636. output_dir=None,
  637. macros=None,
  638. include_dirs=None,
  639. debug=0,
  640. extra_preargs=None,
  641. extra_postargs=None,
  642. depends=None):
  643. if not self.compiler.initialized:
  644. self.compiler.initialize()
  645. output_dir = os.path.abspath(output_dir)
  646. # Note [Absolute include_dirs]
  647. # Convert relative path in self.compiler.include_dirs to absolute path if any,
  648. # For ninja build, the build location is not local, the build happens
  649. # in a in script created build folder, relative path lost their correctness.
  650. # To be consistent with jit extension, we allow user to enter relative include_dirs
  651. # in setuptools.setup, and we convert the relative path to absolute path here
  652. convert_to_absolute_paths_inplace(self.compiler.include_dirs)
  653. _, objects, extra_postargs, pp_opts, _ = \
  654. self.compiler._setup_compile(output_dir, macros,
  655. include_dirs, sources,
  656. depends, extra_postargs)
  657. common_cflags = extra_preargs or []
  658. cflags = []
  659. if debug:
  660. cflags.extend(self.compiler.compile_options_debug)
  661. else:
  662. cflags.extend(self.compiler.compile_options)
  663. common_cflags.extend(COMMON_MSVC_FLAGS)
  664. cflags = cflags + common_cflags + pp_opts
  665. with_cuda = any(map(_is_cuda_file, sources))
  666. # extra_postargs can be either:
  667. # - a dict mapping cxx/nvcc to extra flags
  668. # - a list of extra flags.
  669. if isinstance(extra_postargs, dict):
  670. post_cflags = extra_postargs['cxx']
  671. else:
  672. post_cflags = list(extra_postargs)
  673. append_std17_if_no_std_present(post_cflags)
  674. cuda_post_cflags = None
  675. cuda_cflags = None
  676. if with_cuda:
  677. cuda_cflags = ['--use-local-env']
  678. for common_cflag in common_cflags:
  679. cuda_cflags.append('-Xcompiler')
  680. cuda_cflags.append(common_cflag)
  681. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  682. cuda_cflags.append('-Xcudafe')
  683. cuda_cflags.append('--diag_suppress=' + ignore_warning)
  684. cuda_cflags.extend(pp_opts)
  685. if isinstance(extra_postargs, dict):
  686. cuda_post_cflags = extra_postargs['nvcc']
  687. else:
  688. cuda_post_cflags = list(extra_postargs)
  689. cuda_post_cflags = win_cuda_flags(cuda_post_cflags)
  690. cflags = _nt_quote_args(cflags)
  691. post_cflags = _nt_quote_args(post_cflags)
  692. if with_cuda:
  693. cuda_cflags = _nt_quote_args(cuda_cflags)
  694. cuda_post_cflags = _nt_quote_args(cuda_post_cflags)
  695. if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs:
  696. cuda_dlink_post_cflags = win_cuda_flags(extra_postargs['nvcc_dlink'])
  697. else:
  698. cuda_dlink_post_cflags = None
  699. _write_ninja_file_and_compile_objects(
  700. sources=sources,
  701. objects=objects,
  702. cflags=cflags,
  703. post_cflags=post_cflags,
  704. cuda_cflags=cuda_cflags,
  705. cuda_post_cflags=cuda_post_cflags,
  706. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  707. build_directory=output_dir,
  708. verbose=True,
  709. with_cuda=with_cuda)
  710. # Return *all* object filenames, not just the ones we just built.
  711. return objects
  712. # Monkey-patch the _compile or compile method.
  713. # https://github.com/python/cpython/blob/dc0284ee8f7a270b6005467f26d8e5773d76e959/Lib/distutils/ccompiler.py#L511
  714. if self.compiler.compiler_type == 'msvc':
  715. if self.use_ninja:
  716. self.compiler.compile = win_wrap_ninja_compile
  717. else:
  718. self.compiler.compile = win_wrap_single_compile
  719. else:
  720. if self.use_ninja:
  721. self.compiler.compile = unix_wrap_ninja_compile
  722. else:
  723. self.compiler._compile = unix_wrap_single_compile
  724. build_ext.build_extensions(self)
  725. def get_ext_filename(self, ext_name):
  726. # Get the original shared library name. For Python 3, this name will be
  727. # suffixed with "<SOABI>.so", where <SOABI> will be something like
  728. # cpython-37m-x86_64-linux-gnu.
  729. ext_filename = super().get_ext_filename(ext_name)
  730. # If `no_python_abi_suffix` is `True`, we omit the Python 3 ABI
  731. # component. This makes building shared libraries with setuptools that
  732. # aren't Python modules nicer.
  733. if self.no_python_abi_suffix:
  734. # The parts will be e.g. ["my_extension", "cpython-37m-x86_64-linux-gnu", "so"].
  735. ext_filename_parts = ext_filename.split('.')
  736. # Omit the second to last element.
  737. without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:]
  738. ext_filename = '.'.join(without_abi)
  739. return ext_filename
  740. def _check_abi(self) -> Tuple[str, TorchVersion]:
  741. # On some platforms, like Windows, compiler_cxx is not available.
  742. if hasattr(self.compiler, 'compiler_cxx'):
  743. compiler = self.compiler.compiler_cxx[0]
  744. elif IS_WINDOWS:
  745. compiler = os.environ.get('CXX', 'cl')
  746. else:
  747. compiler = os.environ.get('CXX', 'c++')
  748. _, version = get_compiler_abi_compatibility_and_version(compiler)
  749. # Warn user if VC env is activated but `DISTUILS_USE_SDK` is not set.
  750. if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' in os.environ and 'DISTUTILS_USE_SDK' not in os.environ:
  751. msg = ('It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.'
  752. 'This may lead to multiple activations of the VC env.'
  753. 'Please set `DISTUTILS_USE_SDK=1` and try again.')
  754. raise UserWarning(msg)
  755. return compiler, version
  756. def _add_compile_flag(self, extension, flag):
  757. extension.extra_compile_args = copy.deepcopy(extension.extra_compile_args)
  758. if isinstance(extension.extra_compile_args, dict):
  759. for args in extension.extra_compile_args.values():
  760. args.append(flag)
  761. else:
  762. extension.extra_compile_args.append(flag)
  763. def _define_torch_extension_name(self, extension):
  764. # pybind11 doesn't support dots in the names
  765. # so in order to support extensions in the packages
  766. # like torch._C, we take the last part of the string
  767. # as the library name
  768. names = extension.name.split('.')
  769. name = names[-1]
  770. define = f'-DTORCH_EXTENSION_NAME={name}'
  771. self._add_compile_flag(extension, define)
  772. def _add_gnu_cpp_abi_flag(self, extension):
  773. # use the same CXX ABI as what PyTorch was compiled with
  774. self._add_compile_flag(extension, '-D_GLIBCXX_USE_CXX11_ABI=' + str(int(torch._C._GLIBCXX_USE_CXX11_ABI)))
  775. def CppExtension(name, sources, *args, **kwargs):
  776. r'''
  777. Creates a :class:`setuptools.Extension` for C++.
  778. Convenience method that creates a :class:`setuptools.Extension` with the
  779. bare minimum (but often sufficient) arguments to build a C++ extension.
  780. All arguments are forwarded to the :class:`setuptools.Extension`
  781. constructor.
  782. Example:
  783. >>> # xdoctest: +SKIP
  784. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  785. >>> from setuptools import setup
  786. >>> from torch.utils.cpp_extension import BuildExtension, CppExtension
  787. >>> setup(
  788. ... name='extension',
  789. ... ext_modules=[
  790. ... CppExtension(
  791. ... name='extension',
  792. ... sources=['extension.cpp'],
  793. ... extra_compile_args=['-g']),
  794. ... ],
  795. ... cmdclass={
  796. ... 'build_ext': BuildExtension
  797. ... })
  798. '''
  799. include_dirs = kwargs.get('include_dirs', [])
  800. include_dirs += include_paths()
  801. kwargs['include_dirs'] = include_dirs
  802. library_dirs = kwargs.get('library_dirs', [])
  803. library_dirs += library_paths()
  804. kwargs['library_dirs'] = library_dirs
  805. libraries = kwargs.get('libraries', [])
  806. libraries.append('c10')
  807. libraries.append('torch')
  808. libraries.append('torch_cpu')
  809. libraries.append('torch_python')
  810. kwargs['libraries'] = libraries
  811. kwargs['language'] = 'c++'
  812. return setuptools.Extension(name, sources, *args, **kwargs)
  813. def CUDAExtension(name, sources, *args, **kwargs):
  814. r'''
  815. Creates a :class:`setuptools.Extension` for CUDA/C++.
  816. Convenience method that creates a :class:`setuptools.Extension` with the
  817. bare minimum (but often sufficient) arguments to build a CUDA/C++
  818. extension. This includes the CUDA include path, library path and runtime
  819. library.
  820. All arguments are forwarded to the :class:`setuptools.Extension`
  821. constructor.
  822. Example:
  823. >>> # xdoctest: +SKIP
  824. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  825. >>> from setuptools import setup
  826. >>> from torch.utils.cpp_extension import BuildExtension, CUDAExtension
  827. >>> setup(
  828. ... name='cuda_extension',
  829. ... ext_modules=[
  830. ... CUDAExtension(
  831. ... name='cuda_extension',
  832. ... sources=['extension.cpp', 'extension_kernel.cu'],
  833. ... extra_compile_args={'cxx': ['-g'],
  834. ... 'nvcc': ['-O2']})
  835. ... ],
  836. ... cmdclass={
  837. ... 'build_ext': BuildExtension
  838. ... })
  839. Compute capabilities:
  840. By default the extension will be compiled to run on all archs of the cards visible during the
  841. building process of the extension, plus PTX. If down the road a new card is installed the
  842. extension may need to be recompiled. If a visible card has a compute capability (CC) that's
  843. newer than the newest version for which your nvcc can build fully-compiled binaries, Pytorch
  844. will make nvcc fall back to building kernels with the newest version of PTX your nvcc does
  845. support (see below for details on PTX).
  846. You can override the default behavior using `TORCH_CUDA_ARCH_LIST` to explicitly specify which
  847. CCs you want the extension to support:
  848. TORCH_CUDA_ARCH_LIST="6.1 8.6" python build_my_extension.py
  849. TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python build_my_extension.py
  850. The +PTX option causes extension kernel binaries to include PTX instructions for the specified
  851. CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >=
  852. the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with
  853. CC >= 8.6). This improves your binary's forward compatibility. However, relying on older PTX to
  854. provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on
  855. those newer CCs. If you know exact CC(s) of the GPUs you want to target, you're always better
  856. off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6,
  857. "8.0+PTX" would work functionally because it includes PTX that can runtime-compile for 8.6, but
  858. "8.0 8.6" would be better.
  859. Note that while it's possible to include all supported archs, the more archs get included the
  860. slower the building process will be, as it will build a separate kernel image for each arch.
  861. Note that CUDA-11.5 nvcc will hit internal compiler error while parsing torch/extension.h on Windows.
  862. To workaround the issue, move python binding logic to pure C++ file.
  863. Example use:
  864. #include <ATen/ATen.h>
  865. at::Tensor SigmoidAlphaBlendForwardCuda(....)
  866. Instead of:
  867. #include <torch/extension.h>
  868. torch::Tensor SigmoidAlphaBlendForwardCuda(...)
  869. Currently open issue for nvcc bug: https://github.com/pytorch/pytorch/issues/69460
  870. Complete workaround code example: https://github.com/facebookresearch/pytorch3d/commit/cb170ac024a949f1f9614ffe6af1c38d972f7d48
  871. Relocatable device code linking:
  872. If you want to reference device symbols across compilation units (across object files),
  873. the object files need to be built with `relocatable device code` (-rdc=true or -dc).
  874. An exception to this rule is "dynamic parallelism" (nested kernel launches) which is not used a lot anymore.
  875. `Relocatable device code` is less optimized so it needs to be used only on object files that need it.
  876. Using `-dlto` (Device Link Time Optimization) at the device code compilation step and `dlink` step
  877. help reduce the protentional perf degradation of `-rdc`.
  878. Note that it needs to be used at both steps to be useful.
  879. If you have `rdc` objects you need to have an extra `-dlink` (device linking) step before the CPU symbol linking step.
  880. There is also a case where `-dlink` is used without `-rdc`:
  881. when an extension is linked against a static lib containing rdc-compiled objects
  882. like the [NVSHMEM library](https://developer.nvidia.com/nvshmem).
  883. Note: Ninja is required to build a CUDA Extension with RDC linking.
  884. Example:
  885. >>> # xdoctest: +SKIP
  886. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  887. >>> CUDAExtension(
  888. ... name='cuda_extension',
  889. ... sources=['extension.cpp', 'extension_kernel.cu'],
  890. ... dlink=True,
  891. ... dlink_libraries=["dlink_lib"],
  892. ... extra_compile_args={'cxx': ['-g'],
  893. ... 'nvcc': ['-O2', '-rdc=true']})
  894. '''
  895. library_dirs = kwargs.get('library_dirs', [])
  896. library_dirs += library_paths(cuda=True)
  897. kwargs['library_dirs'] = library_dirs
  898. libraries = kwargs.get('libraries', [])
  899. libraries.append('c10')
  900. libraries.append('torch')
  901. libraries.append('torch_cpu')
  902. libraries.append('torch_python')
  903. if IS_HIP_EXTENSION:
  904. assert ROCM_VERSION is not None
  905. libraries.append('amdhip64' if ROCM_VERSION >= (3, 5) else 'hip_hcc')
  906. libraries.append('c10_hip')
  907. libraries.append('torch_hip')
  908. else:
  909. libraries.append('cudart')
  910. libraries.append('c10_cuda')
  911. libraries.append('torch_cuda')
  912. kwargs['libraries'] = libraries
  913. include_dirs = kwargs.get('include_dirs', [])
  914. if IS_HIP_EXTENSION:
  915. build_dir = os.getcwd()
  916. hipify_result = hipify_python.hipify(
  917. project_directory=build_dir,
  918. output_directory=build_dir,
  919. header_include_dirs=include_dirs,
  920. includes=[os.path.join(build_dir, '*')], # limit scope to build_dir only
  921. extra_files=[os.path.abspath(s) for s in sources],
  922. show_detailed=True,
  923. is_pytorch_extension=True,
  924. hipify_extra_files_only=True, # don't hipify everything in includes path
  925. )
  926. hipified_sources = set()
  927. for source in sources:
  928. s_abs = os.path.abspath(source)
  929. hipified_s_abs = (hipify_result[s_abs]["hipified_path"] if (s_abs in hipify_result and
  930. hipify_result[s_abs]["hipified_path"] is not None) else s_abs)
  931. # setup() arguments must *always* be /-separated paths relative to the setup.py directory,
  932. # *never* absolute paths
  933. hipified_sources.add(os.path.relpath(hipified_s_abs, build_dir))
  934. sources = list(hipified_sources)
  935. include_dirs += include_paths(cuda=True)
  936. kwargs['include_dirs'] = include_dirs
  937. kwargs['language'] = 'c++'
  938. dlink_libraries = kwargs.get('dlink_libraries', [])
  939. dlink = kwargs.get('dlink', False) or dlink_libraries
  940. if dlink:
  941. extra_compile_args = kwargs.get('extra_compile_args', {})
  942. extra_compile_args_dlink = extra_compile_args.get('nvcc_dlink', [])
  943. extra_compile_args_dlink += ['-dlink']
  944. extra_compile_args_dlink += [f'-L{x}' for x in library_dirs]
  945. extra_compile_args_dlink += [f'-l{x}' for x in dlink_libraries]
  946. if (torch.version.cuda is not None) and packaging.version.parse(torch.version.cuda) >= packaging.version.parse('11.2'):
  947. extra_compile_args_dlink += ['-dlto'] # Device Link Time Optimization started from cuda 11.2
  948. extra_compile_args['nvcc_dlink'] = extra_compile_args_dlink
  949. kwargs['extra_compile_args'] = extra_compile_args
  950. return setuptools.Extension(name, sources, *args, **kwargs)
  951. def include_paths(cuda: bool = False) -> List[str]:
  952. '''
  953. Get the include paths required to build a C++ or CUDA extension.
  954. Args:
  955. cuda: If `True`, includes CUDA-specific include paths.
  956. Returns:
  957. A list of include path strings.
  958. '''
  959. lib_include = os.path.join(_TORCH_PATH, 'include')
  960. paths = [
  961. lib_include,
  962. # Remove this once torch/torch.h is officially no longer supported for C++ extensions.
  963. os.path.join(lib_include, 'torch', 'csrc', 'api', 'include'),
  964. # Some internal (old) Torch headers don't properly prefix their includes,
  965. # so we need to pass -Itorch/lib/include/TH as well.
  966. os.path.join(lib_include, 'TH'),
  967. os.path.join(lib_include, 'THC')
  968. ]
  969. if cuda and IS_HIP_EXTENSION:
  970. paths.append(os.path.join(lib_include, 'THH'))
  971. paths.append(_join_rocm_home('include'))
  972. if MIOPEN_HOME is not None:
  973. paths.append(os.path.join(MIOPEN_HOME, 'include'))
  974. if HIP_HOME is not None:
  975. paths.append(os.path.join(HIP_HOME, 'include'))
  976. elif cuda:
  977. cuda_home_include = _join_cuda_home('include')
  978. # if we have the Debian/Ubuntu packages for cuda, we get /usr as cuda home.
  979. # but gcc doesn't like having /usr/include passed explicitly
  980. if cuda_home_include != '/usr/include':
  981. paths.append(cuda_home_include)
  982. if CUDNN_HOME is not None:
  983. paths.append(os.path.join(CUDNN_HOME, 'include'))
  984. return paths
  985. def library_paths(cuda: bool = False) -> List[str]:
  986. r'''
  987. Get the library paths required to build a C++ or CUDA extension.
  988. Args:
  989. cuda: If `True`, includes CUDA-specific library paths.
  990. Returns:
  991. A list of library path strings.
  992. '''
  993. # We need to link against libtorch.so
  994. paths = [TORCH_LIB_PATH]
  995. if cuda and IS_HIP_EXTENSION:
  996. lib_dir = 'lib'
  997. paths.append(_join_rocm_home(lib_dir))
  998. if HIP_HOME is not None:
  999. paths.append(os.path.join(HIP_HOME, 'lib'))
  1000. elif cuda:
  1001. if IS_WINDOWS:
  1002. lib_dir = os.path.join('lib', 'x64')
  1003. else:
  1004. lib_dir = 'lib64'
  1005. if (not os.path.exists(_join_cuda_home(lib_dir)) and
  1006. os.path.exists(_join_cuda_home('lib'))):
  1007. # 64-bit CUDA may be installed in 'lib' (see e.g. gh-16955)
  1008. # Note that it's also possible both don't exist (see
  1009. # _find_cuda_home) - in that case we stay with 'lib64'.
  1010. lib_dir = 'lib'
  1011. paths.append(_join_cuda_home(lib_dir))
  1012. if CUDNN_HOME is not None:
  1013. paths.append(os.path.join(CUDNN_HOME, lib_dir))
  1014. return paths
  1015. def load(name,
  1016. sources: Union[str, List[str]],
  1017. extra_cflags=None,
  1018. extra_cuda_cflags=None,
  1019. extra_ldflags=None,
  1020. extra_include_paths=None,
  1021. build_directory=None,
  1022. verbose=False,
  1023. with_cuda: Optional[bool] = None,
  1024. is_python_module=True,
  1025. is_standalone=False,
  1026. keep_intermediates=True):
  1027. r'''
  1028. Loads a PyTorch C++ extension just-in-time (JIT).
  1029. To load an extension, a Ninja build file is emitted, which is used to
  1030. compile the given sources into a dynamic library. This library is
  1031. subsequently loaded into the current Python process as a module and
  1032. returned from this function, ready for use.
  1033. By default, the directory to which the build file is emitted and the
  1034. resulting library compiled to is ``<tmp>/torch_extensions/<name>``, where
  1035. ``<tmp>`` is the temporary folder on the current platform and ``<name>``
  1036. the name of the extension. This location can be overridden in two ways.
  1037. First, if the ``TORCH_EXTENSIONS_DIR`` environment variable is set, it
  1038. replaces ``<tmp>/torch_extensions`` and all extensions will be compiled
  1039. into subfolders of this directory. Second, if the ``build_directory``
  1040. argument to this function is supplied, it overrides the entire path, i.e.
  1041. the library will be compiled into that folder directly.
  1042. To compile the sources, the default system compiler (``c++``) is used,
  1043. which can be overridden by setting the ``CXX`` environment variable. To pass
  1044. additional arguments to the compilation process, ``extra_cflags`` or
  1045. ``extra_ldflags`` can be provided. For example, to compile your extension
  1046. with optimizations, pass ``extra_cflags=['-O3']``. You can also use
  1047. ``extra_cflags`` to pass further include directories.
  1048. CUDA support with mixed compilation is provided. Simply pass CUDA source
  1049. files (``.cu`` or ``.cuh``) along with other sources. Such files will be
  1050. detected and compiled with nvcc rather than the C++ compiler. This includes
  1051. passing the CUDA lib64 directory as a library directory, and linking
  1052. ``cudart``. You can pass additional flags to nvcc via
  1053. ``extra_cuda_cflags``, just like with ``extra_cflags`` for C++. Various
  1054. heuristics for finding the CUDA install directory are used, which usually
  1055. work fine. If not, setting the ``CUDA_HOME`` environment variable is the
  1056. safest option.
  1057. Args:
  1058. name: The name of the extension to build. This MUST be the same as the
  1059. name of the pybind11 module!
  1060. sources: A list of relative or absolute paths to C++ source files.
  1061. extra_cflags: optional list of compiler flags to forward to the build.
  1062. extra_cuda_cflags: optional list of compiler flags to forward to nvcc
  1063. when building CUDA sources.
  1064. extra_ldflags: optional list of linker flags to forward to the build.
  1065. extra_include_paths: optional list of include directories to forward
  1066. to the build.
  1067. build_directory: optional path to use as build workspace.
  1068. verbose: If ``True``, turns on verbose logging of load steps.
  1069. with_cuda: Determines whether CUDA headers and libraries are added to
  1070. the build. If set to ``None`` (default), this value is
  1071. automatically determined based on the existence of ``.cu`` or
  1072. ``.cuh`` in ``sources``. Set it to `True`` to force CUDA headers
  1073. and libraries to be included.
  1074. is_python_module: If ``True`` (default), imports the produced shared
  1075. library as a Python module. If ``False``, behavior depends on
  1076. ``is_standalone``.
  1077. is_standalone: If ``False`` (default) loads the constructed extension
  1078. into the process as a plain dynamic library. If ``True``, build a
  1079. standalone executable.
  1080. Returns:
  1081. If ``is_python_module`` is ``True``:
  1082. Returns the loaded PyTorch extension as a Python module.
  1083. If ``is_python_module`` is ``False`` and ``is_standalone`` is ``False``:
  1084. Returns nothing. (The shared library is loaded into the process as
  1085. a side effect.)
  1086. If ``is_standalone`` is ``True``.
  1087. Return the path to the executable. (On Windows, TORCH_LIB_PATH is
  1088. added to the PATH environment variable as a side effect.)
  1089. Example:
  1090. >>> # xdoctest: +SKIP
  1091. >>> from torch.utils.cpp_extension import load
  1092. >>> module = load(
  1093. ... name='extension',
  1094. ... sources=['extension.cpp', 'extension_kernel.cu'],
  1095. ... extra_cflags=['-O2'],
  1096. ... verbose=True)
  1097. '''
  1098. return _jit_compile(
  1099. name,
  1100. [sources] if isinstance(sources, str) else sources,
  1101. extra_cflags,
  1102. extra_cuda_cflags,
  1103. extra_ldflags,
  1104. extra_include_paths,
  1105. build_directory or _get_build_directory(name, verbose),
  1106. verbose,
  1107. with_cuda,
  1108. is_python_module,
  1109. is_standalone,
  1110. keep_intermediates=keep_intermediates)
  1111. def load_inline(name,
  1112. cpp_sources,
  1113. cuda_sources=None,
  1114. functions=None,
  1115. extra_cflags=None,
  1116. extra_cuda_cflags=None,
  1117. extra_ldflags=None,
  1118. extra_include_paths=None,
  1119. build_directory=None,
  1120. verbose=False,
  1121. with_cuda=None,
  1122. is_python_module=True,
  1123. with_pytorch_error_handling=True,
  1124. keep_intermediates=True):
  1125. r'''
  1126. Loads a PyTorch C++ extension just-in-time (JIT) from string sources.
  1127. This function behaves exactly like :func:`load`, but takes its sources as
  1128. strings rather than filenames. These strings are stored to files in the
  1129. build directory, after which the behavior of :func:`load_inline` is
  1130. identical to :func:`load`.
  1131. See `the
  1132. tests <https://github.com/pytorch/pytorch/blob/master/test/test_cpp_extensions_jit.py>`_
  1133. for good examples of using this function.
  1134. Sources may omit two required parts of a typical non-inline C++ extension:
  1135. the necessary header includes, as well as the (pybind11) binding code. More
  1136. precisely, strings passed to ``cpp_sources`` are first concatenated into a
  1137. single ``.cpp`` file. This file is then prepended with ``#include
  1138. <torch/extension.h>``.
  1139. Furthermore, if the ``functions`` argument is supplied, bindings will be
  1140. automatically generated for each function specified. ``functions`` can
  1141. either be a list of function names, or a dictionary mapping from function
  1142. names to docstrings. If a list is given, the name of each function is used
  1143. as its docstring.
  1144. The sources in ``cuda_sources`` are concatenated into a separate ``.cu``
  1145. file and prepended with ``torch/types.h``, ``cuda.h`` and
  1146. ``cuda_runtime.h`` includes. The ``.cpp`` and ``.cu`` files are compiled
  1147. separately, but ultimately linked into a single library. Note that no
  1148. bindings are generated for functions in ``cuda_sources`` per se. To bind
  1149. to a CUDA kernel, you must create a C++ function that calls it, and either
  1150. declare or define this C++ function in one of the ``cpp_sources`` (and
  1151. include its name in ``functions``).
  1152. See :func:`load` for a description of arguments omitted below.
  1153. Args:
  1154. cpp_sources: A string, or list of strings, containing C++ source code.
  1155. cuda_sources: A string, or list of strings, containing CUDA source code.
  1156. functions: A list of function names for which to generate function
  1157. bindings. If a dictionary is given, it should map function names to
  1158. docstrings (which are otherwise just the function names).
  1159. with_cuda: Determines whether CUDA headers and libraries are added to
  1160. the build. If set to ``None`` (default), this value is
  1161. automatically determined based on whether ``cuda_sources`` is
  1162. provided. Set it to ``True`` to force CUDA headers
  1163. and libraries to be included.
  1164. with_pytorch_error_handling: Determines whether pytorch error and
  1165. warning macros are handled by pytorch instead of pybind. To do
  1166. this, each function ``foo`` is called via an intermediary ``_safe_foo``
  1167. function. This redirection might cause issues in obscure cases
  1168. of cpp. This flag should be set to ``False`` when this redirect
  1169. causes issues.
  1170. Example:
  1171. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT)
  1172. >>> from torch.utils.cpp_extension import load_inline
  1173. >>> source = """
  1174. at::Tensor sin_add(at::Tensor x, at::Tensor y) {
  1175. return x.sin() + y.sin();
  1176. }
  1177. """
  1178. >>> module = load_inline(name='inline_extension',
  1179. ... cpp_sources=[source],
  1180. ... functions=['sin_add'])
  1181. .. note::
  1182. By default, the Ninja backend uses #CPUS + 2 workers to build the
  1183. extension. This may use up too many resources on some systems. One
  1184. can control the number of workers by setting the `MAX_JOBS` environment
  1185. variable to a non-negative number.
  1186. '''
  1187. build_directory = build_directory or _get_build_directory(name, verbose)
  1188. if isinstance(cpp_sources, str):
  1189. cpp_sources = [cpp_sources]
  1190. cuda_sources = cuda_sources or []
  1191. if isinstance(cuda_sources, str):
  1192. cuda_sources = [cuda_sources]
  1193. cpp_sources.insert(0, '#include <torch/extension.h>')
  1194. # If `functions` is supplied, we create the pybind11 bindings for the user.
  1195. # Here, `functions` is (or becomes, after some processing) a map from
  1196. # function names to function docstrings.
  1197. if functions is not None:
  1198. module_def = []
  1199. module_def.append('PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {')
  1200. if isinstance(functions, str):
  1201. functions = [functions]
  1202. if isinstance(functions, list):
  1203. # Make the function docstring the same as the function name.
  1204. functions = {f: f for f in functions}
  1205. elif not isinstance(functions, dict):
  1206. raise ValueError(f"Expected 'functions' to be a list or dict, but was {type(functions)}")
  1207. for function_name, docstring in functions.items():
  1208. if with_pytorch_error_handling:
  1209. module_def.append(
  1210. 'm.def("{0}", torch::wrap_pybind_function({0}), "{1}");'
  1211. .format(function_name, docstring))
  1212. else:
  1213. module_def.append('m.def("{0}", {0}, "{1}");'.format(function_name, docstring))
  1214. module_def.append('}')
  1215. cpp_sources += module_def
  1216. cpp_source_path = os.path.join(build_directory, 'main.cpp')
  1217. with open(cpp_source_path, 'w') as cpp_source_file:
  1218. cpp_source_file.write('\n'.join(cpp_sources))
  1219. sources = [cpp_source_path]
  1220. if cuda_sources:
  1221. cuda_sources.insert(0, '#include <torch/types.h>')
  1222. cuda_sources.insert(1, '#include <cuda.h>')
  1223. cuda_sources.insert(2, '#include <cuda_runtime.h>')
  1224. cuda_source_path = os.path.join(build_directory, 'cuda.cu')
  1225. with open(cuda_source_path, 'w') as cuda_source_file:
  1226. cuda_source_file.write('\n'.join(cuda_sources))
  1227. sources.append(cuda_source_path)
  1228. return _jit_compile(
  1229. name,
  1230. sources,
  1231. extra_cflags,
  1232. extra_cuda_cflags,
  1233. extra_ldflags,
  1234. extra_include_paths,
  1235. build_directory,
  1236. verbose,
  1237. with_cuda,
  1238. is_python_module,
  1239. is_standalone=False,
  1240. keep_intermediates=keep_intermediates)
  1241. def _jit_compile(name,
  1242. sources,
  1243. extra_cflags,
  1244. extra_cuda_cflags,
  1245. extra_ldflags,
  1246. extra_include_paths,
  1247. build_directory: str,
  1248. verbose: bool,
  1249. with_cuda: Optional[bool],
  1250. is_python_module,
  1251. is_standalone,
  1252. keep_intermediates=True) -> None:
  1253. if is_python_module and is_standalone:
  1254. raise ValueError("`is_python_module` and `is_standalone` are mutually exclusive.")
  1255. if with_cuda is None:
  1256. with_cuda = any(map(_is_cuda_file, sources))
  1257. with_cudnn = any(['cudnn' in f for f in extra_ldflags or []])
  1258. old_version = JIT_EXTENSION_VERSIONER.get_version(name)
  1259. version = JIT_EXTENSION_VERSIONER.bump_version_if_changed(
  1260. name,
  1261. sources,
  1262. build_arguments=[extra_cflags, extra_cuda_cflags, extra_ldflags, extra_include_paths],
  1263. build_directory=build_directory,
  1264. with_cuda=with_cuda,
  1265. is_python_module=is_python_module,
  1266. is_standalone=is_standalone,
  1267. )
  1268. if version > 0:
  1269. if version != old_version and verbose:
  1270. print(f'The input conditions for extension module {name} have changed. ' +
  1271. f'Bumping to version {version} and re-building as {name}_v{version}...',
  1272. file=sys.stderr)
  1273. name = f'{name}_v{version}'
  1274. if version != old_version:
  1275. baton = FileBaton(os.path.join(build_directory, 'lock'))
  1276. if baton.try_acquire():
  1277. try:
  1278. with GeneratedFileCleaner(keep_intermediates=keep_intermediates) as clean_ctx:
  1279. if IS_HIP_EXTENSION and (with_cuda or with_cudnn):
  1280. hipify_result = hipify_python.hipify(
  1281. project_directory=build_directory,
  1282. output_directory=build_directory,
  1283. header_include_dirs=(extra_include_paths if extra_include_paths is not None else []),
  1284. extra_files=[os.path.abspath(s) for s in sources],
  1285. ignores=[_join_rocm_home('*'), os.path.join(_TORCH_PATH, '*')], # no need to hipify ROCm or PyTorch headers
  1286. show_detailed=verbose,
  1287. show_progress=verbose,
  1288. is_pytorch_extension=True,
  1289. clean_ctx=clean_ctx
  1290. )
  1291. hipified_sources = set()
  1292. for source in sources:
  1293. s_abs = os.path.abspath(source)
  1294. hipified_sources.add(hipify_result[s_abs]["hipified_path"] if s_abs in hipify_result else s_abs)
  1295. sources = list(hipified_sources)
  1296. _write_ninja_file_and_build_library(
  1297. name=name,
  1298. sources=sources,
  1299. extra_cflags=extra_cflags or [],
  1300. extra_cuda_cflags=extra_cuda_cflags or [],
  1301. extra_ldflags=extra_ldflags or [],
  1302. extra_include_paths=extra_include_paths or [],
  1303. build_directory=build_directory,
  1304. verbose=verbose,
  1305. with_cuda=with_cuda,
  1306. is_standalone=is_standalone)
  1307. finally:
  1308. baton.release()
  1309. else:
  1310. baton.wait()
  1311. elif verbose:
  1312. print('No modifications detected for re-loaded extension '
  1313. f'module {name}, skipping build step...',
  1314. file=sys.stderr)
  1315. if verbose:
  1316. print(f'Loading extension module {name}...', file=sys.stderr)
  1317. if is_standalone:
  1318. return _get_exec_path(name, build_directory)
  1319. return _import_module_from_library(name, build_directory, is_python_module)
  1320. def _write_ninja_file_and_compile_objects(
  1321. sources: List[str],
  1322. objects,
  1323. cflags,
  1324. post_cflags,
  1325. cuda_cflags,
  1326. cuda_post_cflags,
  1327. cuda_dlink_post_cflags,
  1328. build_directory: str,
  1329. verbose: bool,
  1330. with_cuda: Optional[bool]) -> None:
  1331. verify_ninja_availability()
  1332. if IS_WINDOWS:
  1333. compiler = os.environ.get('CXX', 'cl')
  1334. else:
  1335. compiler = os.environ.get('CXX', 'c++')
  1336. get_compiler_abi_compatibility_and_version(compiler)
  1337. if with_cuda is None:
  1338. with_cuda = any(map(_is_cuda_file, sources))
  1339. build_file_path = os.path.join(build_directory, 'build.ninja')
  1340. if verbose:
  1341. print(f'Emitting ninja build file {build_file_path}...', file=sys.stderr)
  1342. _write_ninja_file(
  1343. path=build_file_path,
  1344. cflags=cflags,
  1345. post_cflags=post_cflags,
  1346. cuda_cflags=cuda_cflags,
  1347. cuda_post_cflags=cuda_post_cflags,
  1348. cuda_dlink_post_cflags=cuda_dlink_post_cflags,
  1349. sources=sources,
  1350. objects=objects,
  1351. ldflags=None,
  1352. library_target=None,
  1353. with_cuda=with_cuda)
  1354. if verbose:
  1355. print('Compiling objects...', file=sys.stderr)
  1356. _run_ninja_build(
  1357. build_directory,
  1358. verbose,
  1359. # It would be better if we could tell users the name of the extension
  1360. # that failed to build but there isn't a good way to get it here.
  1361. error_prefix='Error compiling objects for extension')
  1362. def _write_ninja_file_and_build_library(
  1363. name,
  1364. sources: List[str],
  1365. extra_cflags,
  1366. extra_cuda_cflags,
  1367. extra_ldflags,
  1368. extra_include_paths,
  1369. build_directory: str,
  1370. verbose: bool,
  1371. with_cuda: Optional[bool],
  1372. is_standalone: bool = False) -> None:
  1373. verify_ninja_availability()
  1374. if IS_WINDOWS:
  1375. compiler = os.environ.get('CXX', 'cl')
  1376. else:
  1377. compiler = os.environ.get('CXX', 'c++')
  1378. get_compiler_abi_compatibility_and_version(compiler)
  1379. if with_cuda is None:
  1380. with_cuda = any(map(_is_cuda_file, sources))
  1381. extra_ldflags = _prepare_ldflags(
  1382. extra_ldflags or [],
  1383. with_cuda,
  1384. verbose,
  1385. is_standalone)
  1386. build_file_path = os.path.join(build_directory, 'build.ninja')
  1387. if verbose:
  1388. print(f'Emitting ninja build file {build_file_path}...', file=sys.stderr)
  1389. # NOTE: Emitting a new ninja build file does not cause re-compilation if
  1390. # the sources did not change, so it's ok to re-emit (and it's fast).
  1391. _write_ninja_file_to_build_library(
  1392. path=build_file_path,
  1393. name=name,
  1394. sources=sources,
  1395. extra_cflags=extra_cflags or [],
  1396. extra_cuda_cflags=extra_cuda_cflags or [],
  1397. extra_ldflags=extra_ldflags or [],
  1398. extra_include_paths=extra_include_paths or [],
  1399. with_cuda=with_cuda,
  1400. is_standalone=is_standalone)
  1401. if verbose:
  1402. print(f'Building extension module {name}...', file=sys.stderr)
  1403. _run_ninja_build(
  1404. build_directory,
  1405. verbose,
  1406. error_prefix=f"Error building extension '{name}'")
  1407. def is_ninja_available():
  1408. r'''
  1409. Returns ``True`` if the `ninja <https://ninja-build.org/>`_ build system is
  1410. available on the system, ``False`` otherwise.
  1411. '''
  1412. try:
  1413. subprocess.check_output('ninja --version'.split())
  1414. except Exception:
  1415. return False
  1416. else:
  1417. return True
  1418. def verify_ninja_availability():
  1419. r'''
  1420. Raises ``RuntimeError`` if `ninja <https://ninja-build.org/>`_ build system is not
  1421. available on the system, does nothing otherwise.
  1422. '''
  1423. if not is_ninja_available():
  1424. raise RuntimeError("Ninja is required to load C++ extensions")
  1425. def _prepare_ldflags(extra_ldflags, with_cuda, verbose, is_standalone):
  1426. if IS_WINDOWS:
  1427. python_path = os.path.dirname(sys.executable)
  1428. python_lib_path = os.path.join(python_path, 'libs')
  1429. extra_ldflags.append('c10.lib')
  1430. if with_cuda:
  1431. extra_ldflags.append('c10_cuda.lib')
  1432. extra_ldflags.append('torch_cpu.lib')
  1433. if with_cuda:
  1434. extra_ldflags.append('torch_cuda.lib')
  1435. # /INCLUDE is used to ensure torch_cuda is linked against in a project that relies on it.
  1436. # Related issue: https://github.com/pytorch/pytorch/issues/31611
  1437. extra_ldflags.append('-INCLUDE:?warp_size@cuda@at@@YAHXZ')
  1438. extra_ldflags.append('torch.lib')
  1439. extra_ldflags.append(f'/LIBPATH:{TORCH_LIB_PATH}')
  1440. if not is_standalone:
  1441. extra_ldflags.append('torch_python.lib')
  1442. extra_ldflags.append(f'/LIBPATH:{python_lib_path}')
  1443. else:
  1444. extra_ldflags.append(f'-L{TORCH_LIB_PATH}')
  1445. extra_ldflags.append('-lc10')
  1446. if with_cuda:
  1447. extra_ldflags.append('-lc10_hip' if IS_HIP_EXTENSION else '-lc10_cuda')
  1448. extra_ldflags.append('-ltorch_cpu')
  1449. if with_cuda:
  1450. extra_ldflags.append('-ltorch_hip' if IS_HIP_EXTENSION else '-ltorch_cuda')
  1451. extra_ldflags.append('-ltorch')
  1452. if not is_standalone:
  1453. extra_ldflags.append('-ltorch_python')
  1454. if is_standalone and "TBB" in torch.__config__.parallel_info():
  1455. extra_ldflags.append('-ltbb')
  1456. if is_standalone:
  1457. extra_ldflags.append(f"-Wl,-rpath,{TORCH_LIB_PATH}")
  1458. if with_cuda:
  1459. if verbose:
  1460. print('Detected CUDA files, patching ldflags', file=sys.stderr)
  1461. if IS_WINDOWS:
  1462. extra_ldflags.append(f'/LIBPATH:{_join_cuda_home("lib", "x64")}')
  1463. extra_ldflags.append('cudart.lib')
  1464. if CUDNN_HOME is not None:
  1465. extra_ldflags.append(f'/LIBPATH:{os.path.join(CUDNN_HOME, "lib", "x64")}')
  1466. elif not IS_HIP_EXTENSION:
  1467. extra_ldflags.append(f'-L{_join_cuda_home("lib64")}')
  1468. extra_ldflags.append('-lcudart')
  1469. if CUDNN_HOME is not None:
  1470. extra_ldflags.append(f'-L{os.path.join(CUDNN_HOME, "lib64")}')
  1471. elif IS_HIP_EXTENSION:
  1472. assert ROCM_VERSION is not None
  1473. extra_ldflags.append(f'-L{_join_rocm_home("lib")}')
  1474. extra_ldflags.append('-lamdhip64' if ROCM_VERSION >= (3, 5) else '-lhip_hcc')
  1475. return extra_ldflags
  1476. def _get_cuda_arch_flags(cflags: Optional[List[str]] = None) -> List[str]:
  1477. r'''
  1478. Determine CUDA arch flags to use.
  1479. For an arch, say "6.1", the added compile flag will be
  1480. ``-gencode=arch=compute_61,code=sm_61``.
  1481. For an added "+PTX", an additional
  1482. ``-gencode=arch=compute_xx,code=compute_xx`` is added.
  1483. See select_compute_arch.cmake for corresponding named and supported arches
  1484. when building with CMake.
  1485. '''
  1486. # If cflags is given, there may already be user-provided arch flags in it
  1487. # (from `extra_compile_args`)
  1488. if cflags is not None:
  1489. for flag in cflags:
  1490. if 'arch' in flag:
  1491. return []
  1492. # Note: keep combined names ("arch1+arch2") above single names, otherwise
  1493. # string replacement may not do the right thing
  1494. named_arches = collections.OrderedDict([
  1495. ('Kepler+Tesla', '3.7'),
  1496. ('Kepler', '3.5+PTX'),
  1497. ('Maxwell+Tegra', '5.3'),
  1498. ('Maxwell', '5.0;5.2+PTX'),
  1499. ('Pascal', '6.0;6.1+PTX'),
  1500. ('Volta', '7.0+PTX'),
  1501. ('Turing', '7.5+PTX'),
  1502. ('Ampere', '8.0;8.6+PTX;8.7+PTX'),
  1503. ('Ada', '8.9+PTX'),
  1504. ('Hopper', '9.0+PTX'),
  1505. ])
  1506. supported_arches = ['3.5', '3.7', '5.0', '5.2', '5.3', '6.0', '6.1', '6.2',
  1507. '7.0', '7.2', '7.5', '8.0', '8.6', '8.7', '8.9', '9.0']
  1508. valid_arch_strings = supported_arches + [s + "+PTX" for s in supported_arches]
  1509. # The default is sm_30 for CUDA 9.x and 10.x
  1510. # First check for an env var (same as used by the main setup.py)
  1511. # Can be one or more architectures, e.g. "6.1" or "3.5;5.2;6.0;6.1;7.0+PTX"
  1512. # See cmake/Modules_CUDA_fix/upstream/FindCUDA/select_compute_arch.cmake
  1513. _arch_list = os.environ.get('TORCH_CUDA_ARCH_LIST', None)
  1514. # If not given, determine what's best for the GPU / CUDA version that can be found
  1515. if not _arch_list:
  1516. arch_list = []
  1517. # the assumption is that the extension should run on any of the currently visible cards,
  1518. # which could be of different types - therefore all archs for visible cards should be included
  1519. for i in range(torch.cuda.device_count()):
  1520. capability = torch.cuda.get_device_capability(i)
  1521. supported_sm = [int(arch.split('_')[1])
  1522. for arch in torch.cuda.get_arch_list() if 'sm_' in arch]
  1523. max_supported_sm = max((sm // 10, sm % 10) for sm in supported_sm)
  1524. # Capability of the device may be higher than what's supported by the user's
  1525. # NVCC, causing compilation error. User's NVCC is expected to match the one
  1526. # used to build pytorch, so we use the maximum supported capability of pytorch
  1527. # to clamp the capability.
  1528. capability = min(max_supported_sm, capability)
  1529. arch = f'{capability[0]}.{capability[1]}'
  1530. if arch not in arch_list:
  1531. arch_list.append(arch)
  1532. arch_list = sorted(arch_list)
  1533. arch_list[-1] += '+PTX'
  1534. else:
  1535. # Deal with lists that are ' ' separated (only deal with ';' after)
  1536. _arch_list = _arch_list.replace(' ', ';')
  1537. # Expand named arches
  1538. for named_arch, archval in named_arches.items():
  1539. _arch_list = _arch_list.replace(named_arch, archval)
  1540. arch_list = _arch_list.split(';')
  1541. flags = []
  1542. for arch in arch_list:
  1543. if arch not in valid_arch_strings:
  1544. raise ValueError(f"Unknown CUDA arch ({arch}) or GPU not supported")
  1545. else:
  1546. num = arch[0] + arch[2]
  1547. flags.append(f'-gencode=arch=compute_{num},code=sm_{num}')
  1548. if arch.endswith('+PTX'):
  1549. flags.append(f'-gencode=arch=compute_{num},code=compute_{num}')
  1550. return sorted(set(flags))
  1551. def _get_rocm_arch_flags(cflags: Optional[List[str]] = None) -> List[str]:
  1552. # If cflags is given, there may already be user-provided arch flags in it
  1553. # (from `extra_compile_args`)
  1554. if cflags is not None:
  1555. for flag in cflags:
  1556. if 'amdgpu-target' in flag:
  1557. return ['-fno-gpu-rdc']
  1558. # Use same defaults as used for building PyTorch
  1559. # Allow env var to override, just like during initial cmake build.
  1560. _archs = os.environ.get('PYTORCH_ROCM_ARCH', None)
  1561. if not _archs:
  1562. archFlags = torch._C._cuda_getArchFlags()
  1563. if archFlags:
  1564. archs = archFlags.split()
  1565. else:
  1566. archs = []
  1567. else:
  1568. archs = _archs.replace(' ', ';').split(';')
  1569. flags = ['--amdgpu-target=%s' % arch for arch in archs]
  1570. flags += ['-fno-gpu-rdc']
  1571. return flags
  1572. def _get_build_directory(name: str, verbose: bool) -> str:
  1573. root_extensions_directory = os.environ.get('TORCH_EXTENSIONS_DIR')
  1574. if root_extensions_directory is None:
  1575. root_extensions_directory = get_default_build_root()
  1576. cu_str = ('cpu' if torch.version.cuda is None else
  1577. f'cu{torch.version.cuda.replace(".", "")}') # type: ignore[attr-defined]
  1578. python_version = f'py{sys.version_info.major}{sys.version_info.minor}'
  1579. build_folder = f'{python_version}_{cu_str}'
  1580. root_extensions_directory = os.path.join(
  1581. root_extensions_directory, build_folder)
  1582. if verbose:
  1583. print(f'Using {root_extensions_directory} as PyTorch extensions root...', file=sys.stderr)
  1584. build_directory = os.path.join(root_extensions_directory, name)
  1585. if not os.path.exists(build_directory):
  1586. if verbose:
  1587. print(f'Creating extension directory {build_directory}...', file=sys.stderr)
  1588. # This is like mkdir -p, i.e. will also create parent directories.
  1589. os.makedirs(build_directory, exist_ok=True)
  1590. return build_directory
  1591. def _get_num_workers(verbose: bool) -> Optional[int]:
  1592. max_jobs = os.environ.get('MAX_JOBS')
  1593. if max_jobs is not None and max_jobs.isdigit():
  1594. if verbose:
  1595. print(f'Using envvar MAX_JOBS ({max_jobs}) as the number of workers...',
  1596. file=sys.stderr)
  1597. return int(max_jobs)
  1598. if verbose:
  1599. print('Allowing ninja to set a default number of workers... '
  1600. '(overridable by setting the environment variable MAX_JOBS=N)',
  1601. file=sys.stderr)
  1602. return None
  1603. def _run_ninja_build(build_directory: str, verbose: bool, error_prefix: str) -> None:
  1604. command = ['ninja', '-v']
  1605. num_workers = _get_num_workers(verbose)
  1606. if num_workers is not None:
  1607. command.extend(['-j', str(num_workers)])
  1608. env = os.environ.copy()
  1609. # Try to activate the vc env for the users
  1610. if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' not in env:
  1611. from setuptools import distutils
  1612. plat_name = distutils.util.get_platform()
  1613. plat_spec = PLAT_TO_VCVARS[plat_name]
  1614. vc_env = distutils._msvccompiler._get_vc_env(plat_spec)
  1615. vc_env = {k.upper(): v for k, v in vc_env.items()}
  1616. for k, v in env.items():
  1617. uk = k.upper()
  1618. if uk not in vc_env:
  1619. vc_env[uk] = v
  1620. env = vc_env
  1621. try:
  1622. sys.stdout.flush()
  1623. sys.stderr.flush()
  1624. # Warning: don't pass stdout=None to subprocess.run to get output.
  1625. # subprocess.run assumes that sys.__stdout__ has not been modified and
  1626. # attempts to write to it by default. However, when we call _run_ninja_build
  1627. # from ahead-of-time cpp extensions, the following happens:
  1628. # 1) If the stdout encoding is not utf-8, setuptools detachs __stdout__.
  1629. # https://github.com/pypa/setuptools/blob/7e97def47723303fafabe48b22168bbc11bb4821/setuptools/dist.py#L1110
  1630. # (it probably shouldn't do this)
  1631. # 2) subprocess.run (on POSIX, with no stdout override) relies on
  1632. # __stdout__ not being detached:
  1633. # https://github.com/python/cpython/blob/c352e6c7446c894b13643f538db312092b351789/Lib/subprocess.py#L1214
  1634. # To work around this, we pass in the fileno directly and hope that
  1635. # it is valid.
  1636. stdout_fileno = 1
  1637. subprocess.run(
  1638. command,
  1639. stdout=stdout_fileno if verbose else subprocess.PIPE,
  1640. stderr=subprocess.STDOUT,
  1641. cwd=build_directory,
  1642. check=True,
  1643. env=env)
  1644. except subprocess.CalledProcessError as e:
  1645. # Python 2 and 3 compatible way of getting the error object.
  1646. _, error, _ = sys.exc_info()
  1647. # error.output contains the stdout and stderr of the build attempt.
  1648. message = error_prefix
  1649. # `error` is a CalledProcessError (which has an `ouput`) attribute, but
  1650. # mypy thinks it's Optional[BaseException] and doesn't narrow
  1651. if hasattr(error, 'output') and error.output: # type: ignore[union-attr]
  1652. message += f": {error.output.decode(*SUBPROCESS_DECODE_ARGS)}" # type: ignore[union-attr]
  1653. raise RuntimeError(message) from e
  1654. def _get_exec_path(module_name, path):
  1655. if IS_WINDOWS and TORCH_LIB_PATH not in os.getenv('PATH', '').split(';'):
  1656. torch_lib_in_path = any(
  1657. os.path.exists(p) and os.path.samefile(p, TORCH_LIB_PATH)
  1658. for p in os.getenv('PATH', '').split(';')
  1659. )
  1660. if not torch_lib_in_path:
  1661. os.environ['PATH'] = f"{TORCH_LIB_PATH};{os.getenv('PATH', '')}"
  1662. return os.path.join(path, f'{module_name}{EXEC_EXT}')
  1663. def _import_module_from_library(module_name, path, is_python_module):
  1664. filepath = os.path.join(path, f"{module_name}{LIB_EXT}")
  1665. if is_python_module:
  1666. # https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
  1667. spec = importlib.util.spec_from_file_location(module_name, filepath)
  1668. assert spec is not None
  1669. module = importlib.util.module_from_spec(spec)
  1670. assert isinstance(spec.loader, importlib.abc.Loader)
  1671. spec.loader.exec_module(module)
  1672. return module
  1673. else:
  1674. torch.ops.load_library(filepath)
  1675. def _write_ninja_file_to_build_library(path,
  1676. name,
  1677. sources,
  1678. extra_cflags,
  1679. extra_cuda_cflags,
  1680. extra_ldflags,
  1681. extra_include_paths,
  1682. with_cuda,
  1683. is_standalone) -> None:
  1684. extra_cflags = [flag.strip() for flag in extra_cflags]
  1685. extra_cuda_cflags = [flag.strip() for flag in extra_cuda_cflags]
  1686. extra_ldflags = [flag.strip() for flag in extra_ldflags]
  1687. extra_include_paths = [flag.strip() for flag in extra_include_paths]
  1688. # Turn into absolute paths so we can emit them into the ninja build
  1689. # file wherever it is.
  1690. user_includes = [os.path.abspath(file) for file in extra_include_paths]
  1691. # include_paths() gives us the location of torch/extension.h
  1692. system_includes = include_paths(with_cuda)
  1693. # sysconfig.get_path('include') gives us the location of Python.h
  1694. # Explicitly specify 'posix_prefix' scheme on non-Windows platforms to workaround error on some MacOS
  1695. # installations where default `get_path` points to non-existing `/Library/Python/M.m/include` folder
  1696. python_include_path = sysconfig.get_path('include', scheme='nt' if IS_WINDOWS else 'posix_prefix')
  1697. if python_include_path is not None:
  1698. system_includes.append(python_include_path)
  1699. # Windows does not understand `-isystem`.
  1700. if IS_WINDOWS:
  1701. user_includes += system_includes
  1702. system_includes.clear()
  1703. common_cflags = []
  1704. if not is_standalone:
  1705. common_cflags.append(f'-DTORCH_EXTENSION_NAME={name}')
  1706. common_cflags.append('-DTORCH_API_INCLUDE_EXTENSION_H')
  1707. # Note [Pybind11 ABI constants]
  1708. #
  1709. # Pybind11 before 2.4 used to build an ABI strings using the following pattern:
  1710. # f"__pybind11_internals_v{PYBIND11_INTERNALS_VERSION}{PYBIND11_INTERNALS_KIND}{PYBIND11_BUILD_TYPE}__"
  1711. # Since 2.4 compier type, stdlib and build abi parameters are also encoded like this:
  1712. # f"__pybind11_internals_v{PYBIND11_INTERNALS_VERSION}{PYBIND11_INTERNALS_KIND}{PYBIND11_COMPILER_TYPE}{PYBIND11_STDLIB}{PYBIND11_BUILD_ABI}{PYBIND11_BUILD_TYPE}__"
  1713. #
  1714. # This was done in order to further narrow down the chances of compiler ABI incompatibility
  1715. # that can cause a hard to debug segfaults.
  1716. # For PyTorch extensions we want to relax those restrictions and pass compiler, stdlib and abi properties
  1717. # captured during PyTorch native library compilation in torch/csrc/Module.cpp
  1718. for pname in ["COMPILER_TYPE", "STDLIB", "BUILD_ABI"]:
  1719. pval = getattr(torch._C, f"_PYBIND11_{pname}")
  1720. if pval is not None and not IS_WINDOWS:
  1721. common_cflags.append(f'-DPYBIND11_{pname}=\\"{pval}\\"')
  1722. common_cflags += [f'-I{include}' for include in user_includes]
  1723. common_cflags += [f'-isystem {include}' for include in system_includes]
  1724. common_cflags += ['-D_GLIBCXX_USE_CXX11_ABI=' + str(int(torch._C._GLIBCXX_USE_CXX11_ABI))]
  1725. if IS_WINDOWS:
  1726. cflags = common_cflags + COMMON_MSVC_FLAGS + extra_cflags
  1727. cflags = _nt_quote_args(cflags)
  1728. else:
  1729. cflags = common_cflags + ['-fPIC', '-std=c++17'] + extra_cflags
  1730. if with_cuda and IS_HIP_EXTENSION:
  1731. cuda_flags = ['-DWITH_HIP'] + cflags + COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS
  1732. cuda_flags += extra_cuda_cflags
  1733. cuda_flags += _get_rocm_arch_flags(cuda_flags)
  1734. elif with_cuda:
  1735. cuda_flags = common_cflags + COMMON_NVCC_FLAGS + _get_cuda_arch_flags()
  1736. if IS_WINDOWS:
  1737. for flag in COMMON_MSVC_FLAGS:
  1738. cuda_flags = ['-Xcompiler', flag] + cuda_flags
  1739. for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:
  1740. cuda_flags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cuda_flags
  1741. cuda_flags = _nt_quote_args(cuda_flags)
  1742. cuda_flags += _nt_quote_args(extra_cuda_cflags)
  1743. else:
  1744. cuda_flags += ['--compiler-options', "'-fPIC'"]
  1745. cuda_flags += extra_cuda_cflags
  1746. if not any(flag.startswith('-std=') for flag in cuda_flags):
  1747. cuda_flags.append('-std=c++17')
  1748. if os.getenv("CC") is not None:
  1749. cuda_flags = ['-ccbin', os.getenv("CC")] + cuda_flags
  1750. else:
  1751. cuda_flags = None
  1752. def object_file_path(source_file: str) -> str:
  1753. # '/path/to/file.cpp' -> 'file'
  1754. file_name = os.path.splitext(os.path.basename(source_file))[0]
  1755. if _is_cuda_file(source_file) and with_cuda:
  1756. # Use a different object filename in case a C++ and CUDA file have
  1757. # the same filename but different extension (.cpp vs. .cu).
  1758. target = f'{file_name}.cuda.o'
  1759. else:
  1760. target = f'{file_name}.o'
  1761. return target
  1762. objects = [object_file_path(src) for src in sources]
  1763. ldflags = ([] if is_standalone else [SHARED_FLAG]) + extra_ldflags
  1764. # The darwin linker needs explicit consent to ignore unresolved symbols.
  1765. if IS_MACOS:
  1766. ldflags.append('-undefined dynamic_lookup')
  1767. elif IS_WINDOWS:
  1768. ldflags = _nt_quote_args(ldflags)
  1769. ext = EXEC_EXT if is_standalone else LIB_EXT
  1770. library_target = f'{name}{ext}'
  1771. _write_ninja_file(
  1772. path=path,
  1773. cflags=cflags,
  1774. post_cflags=None,
  1775. cuda_cflags=cuda_flags,
  1776. cuda_post_cflags=None,
  1777. cuda_dlink_post_cflags=None,
  1778. sources=sources,
  1779. objects=objects,
  1780. ldflags=ldflags,
  1781. library_target=library_target,
  1782. with_cuda=with_cuda)
  1783. def _write_ninja_file(path,
  1784. cflags,
  1785. post_cflags,
  1786. cuda_cflags,
  1787. cuda_post_cflags,
  1788. cuda_dlink_post_cflags,
  1789. sources,
  1790. objects,
  1791. ldflags,
  1792. library_target,
  1793. with_cuda) -> None:
  1794. r"""Write a ninja file that does the desired compiling and linking.
  1795. `path`: Where to write this file
  1796. `cflags`: list of flags to pass to $cxx. Can be None.
  1797. `post_cflags`: list of flags to append to the $cxx invocation. Can be None.
  1798. `cuda_cflags`: list of flags to pass to $nvcc. Can be None.
  1799. `cuda_postflags`: list of flags to append to the $nvcc invocation. Can be None.
  1800. `sources`: list of paths to source files
  1801. `objects`: list of desired paths to objects, one per source.
  1802. `ldflags`: list of flags to pass to linker. Can be None.
  1803. `library_target`: Name of the output library. Can be None; in that case,
  1804. we do no linking.
  1805. `with_cuda`: If we should be compiling with CUDA.
  1806. """
  1807. def sanitize_flags(flags):
  1808. if flags is None:
  1809. return []
  1810. else:
  1811. return [flag.strip() for flag in flags]
  1812. cflags = sanitize_flags(cflags)
  1813. post_cflags = sanitize_flags(post_cflags)
  1814. cuda_cflags = sanitize_flags(cuda_cflags)
  1815. cuda_post_cflags = sanitize_flags(cuda_post_cflags)
  1816. cuda_dlink_post_cflags = sanitize_flags(cuda_dlink_post_cflags)
  1817. ldflags = sanitize_flags(ldflags)
  1818. # Sanity checks...
  1819. assert len(sources) == len(objects)
  1820. assert len(sources) > 0
  1821. if IS_WINDOWS:
  1822. compiler = os.environ.get('CXX', 'cl')
  1823. else:
  1824. compiler = os.environ.get('CXX', 'c++')
  1825. # Version 1.3 is required for the `deps` directive.
  1826. config = ['ninja_required_version = 1.3']
  1827. config.append(f'cxx = {compiler}')
  1828. if with_cuda or cuda_dlink_post_cflags:
  1829. if IS_HIP_EXTENSION:
  1830. nvcc = _join_rocm_home('bin', 'hipcc')
  1831. else:
  1832. nvcc = _join_cuda_home('bin', 'nvcc')
  1833. config.append(f'nvcc = {nvcc}')
  1834. if IS_HIP_EXTENSION:
  1835. post_cflags = COMMON_HIP_FLAGS + post_cflags
  1836. flags = [f'cflags = {" ".join(cflags)}']
  1837. flags.append(f'post_cflags = {" ".join(post_cflags)}')
  1838. if with_cuda:
  1839. flags.append(f'cuda_cflags = {" ".join(cuda_cflags)}')
  1840. flags.append(f'cuda_post_cflags = {" ".join(cuda_post_cflags)}')
  1841. flags.append(f'cuda_dlink_post_cflags = {" ".join(cuda_dlink_post_cflags)}')
  1842. flags.append(f'ldflags = {" ".join(ldflags)}')
  1843. # Turn into absolute paths so we can emit them into the ninja build
  1844. # file wherever it is.
  1845. sources = [os.path.abspath(file) for file in sources]
  1846. # See https://ninja-build.org/build.ninja.html for reference.
  1847. compile_rule = ['rule compile']
  1848. if IS_WINDOWS:
  1849. compile_rule.append(
  1850. ' command = cl /showIncludes $cflags -c $in /Fo$out $post_cflags')
  1851. compile_rule.append(' deps = msvc')
  1852. else:
  1853. compile_rule.append(
  1854. ' command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflags')
  1855. compile_rule.append(' depfile = $out.d')
  1856. compile_rule.append(' deps = gcc')
  1857. if with_cuda:
  1858. cuda_compile_rule = ['rule cuda_compile']
  1859. nvcc_gendeps = ''
  1860. # --generate-dependencies-with-compile was added in CUDA 10.2.
  1861. # Compilation will work on earlier CUDA versions but header file
  1862. # dependencies are not correctly computed.
  1863. required_cuda_version = packaging.version.parse('11.0')
  1864. has_cuda_version = torch.version.cuda is not None
  1865. if has_cuda_version and packaging.version.parse(torch.version.cuda) >= required_cuda_version:
  1866. cuda_compile_rule.append(' depfile = $out.d')
  1867. cuda_compile_rule.append(' deps = gcc')
  1868. # Note: non-system deps with nvcc are only supported
  1869. # on Linux so use --generate-dependencies-with-compile
  1870. # to make this work on Windows too.
  1871. if IS_WINDOWS:
  1872. nvcc_gendeps = '--generate-dependencies-with-compile --dependency-output $out.d'
  1873. cuda_compile_rule.append(
  1874. f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags')
  1875. # Emit one build rule per source to enable incremental build.
  1876. build = []
  1877. for source_file, object_file in zip(sources, objects):
  1878. is_cuda_source = _is_cuda_file(source_file) and with_cuda
  1879. rule = 'cuda_compile' if is_cuda_source else 'compile'
  1880. if IS_WINDOWS:
  1881. source_file = source_file.replace(':', '$:')
  1882. object_file = object_file.replace(':', '$:')
  1883. source_file = source_file.replace(" ", "$ ")
  1884. object_file = object_file.replace(" ", "$ ")
  1885. build.append(f'build {object_file}: {rule} {source_file}')
  1886. if cuda_dlink_post_cflags:
  1887. devlink_out = os.path.join(os.path.dirname(objects[0]), 'dlink.o')
  1888. devlink_rule = ['rule cuda_devlink']
  1889. devlink_rule.append(' command = $nvcc $in -o $out $cuda_dlink_post_cflags')
  1890. devlink = [f'build {devlink_out}: cuda_devlink {" ".join(objects)}']
  1891. objects += [devlink_out]
  1892. else:
  1893. devlink_rule, devlink = [], []
  1894. if library_target is not None:
  1895. link_rule = ['rule link']
  1896. if IS_WINDOWS:
  1897. cl_paths = subprocess.check_output(['where',
  1898. 'cl']).decode(*SUBPROCESS_DECODE_ARGS).split('\r\n')
  1899. if len(cl_paths) >= 1:
  1900. cl_path = os.path.dirname(cl_paths[0]).replace(':', '$:')
  1901. else:
  1902. raise RuntimeError("MSVC is required to load C++ extensions")
  1903. link_rule.append(f' command = "{cl_path}/link.exe" $in /nologo $ldflags /out:$out')
  1904. else:
  1905. link_rule.append(' command = $cxx $in $ldflags -o $out')
  1906. link = [f'build {library_target}: link {" ".join(objects)}']
  1907. default = [f'default {library_target}']
  1908. else:
  1909. link_rule, link, default = [], [], []
  1910. # 'Blocks' should be separated by newlines, for visual benefit.
  1911. blocks = [config, flags, compile_rule]
  1912. if with_cuda:
  1913. blocks.append(cuda_compile_rule)
  1914. blocks += [devlink_rule, link_rule, build, devlink, link, default]
  1915. with open(path, 'w') as build_file:
  1916. for block in blocks:
  1917. lines = '\n'.join(block)
  1918. build_file.write(f'{lines}\n\n')
  1919. def _join_cuda_home(*paths) -> str:
  1920. r'''
  1921. Joins paths with CUDA_HOME, or raises an error if it CUDA_HOME is not set.
  1922. This is basically a lazy way of raising an error for missing $CUDA_HOME
  1923. only once we need to get any CUDA-specific path.
  1924. '''
  1925. if CUDA_HOME is None:
  1926. raise EnvironmentError('CUDA_HOME environment variable is not set. '
  1927. 'Please set it to your CUDA install root.')
  1928. return os.path.join(CUDA_HOME, *paths)
  1929. def _is_cuda_file(path: str) -> bool:
  1930. valid_ext = ['.cu', '.cuh']
  1931. if IS_HIP_EXTENSION:
  1932. valid_ext.append('.hip')
  1933. return os.path.splitext(path)[1] in valid_ext