cpp_extension.py 91 KB

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