cpp_extension.py 103 KB

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