cpp_extension.py 129 KB

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