cpp_builder.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. # This CPP JIT builder is designed to support both Windows and Linux OS.
  2. # The design document please check this RFC: https://github.com/pytorch/pytorch/issues/124245
  3. import copy
  4. import errno
  5. import functools
  6. import logging
  7. import os
  8. import platform
  9. import re
  10. import shlex
  11. import shutil
  12. import subprocess
  13. import sys
  14. import sysconfig
  15. import warnings
  16. from pathlib import Path
  17. from typing import List, Sequence, Tuple, Union
  18. import torch
  19. from torch._inductor import config, exc
  20. from torch._inductor.codecache import (
  21. _get_python_include_dirs,
  22. _LINKER_SCRIPT,
  23. _transform_cuda_paths,
  24. get_lock_dir,
  25. invalid_vec_isa,
  26. LOCK_TIMEOUT,
  27. VecISA,
  28. )
  29. from torch._inductor.runtime.runtime_utils import cache_dir
  30. if config.is_fbcode():
  31. from triton.fb import build_paths # noqa: F401
  32. from torch._inductor.fb.utils import (
  33. log_global_cache_errors,
  34. log_global_cache_stats,
  35. log_global_cache_vals,
  36. use_global_cache,
  37. )
  38. else:
  39. def log_global_cache_errors(*args, **kwargs):
  40. pass
  41. def log_global_cache_stats(*args, **kwargs):
  42. pass
  43. def log_global_cache_vals(*args, **kwargs):
  44. pass
  45. def use_global_cache() -> bool:
  46. return False
  47. # Windows need setup a temp dir to store .obj files.
  48. _BUILD_TEMP_DIR = "CxxBuild"
  49. # initialize variables for compilation
  50. _IS_LINUX = sys.platform.startswith("linux")
  51. _IS_MACOS = sys.platform.startswith("darwin")
  52. _IS_WINDOWS = sys.platform == "win32"
  53. log = logging.getLogger(__name__)
  54. @functools.lru_cache(1)
  55. def cpp_compiler_search(search: str) -> str:
  56. for cxx in search:
  57. try:
  58. if cxx is None:
  59. # gxx package is only available for Linux
  60. # according to https://anaconda.org/conda-forge/gxx/
  61. if sys.platform != "linux":
  62. continue
  63. # Do not install GXX by default
  64. if not os.getenv("TORCH_INDUCTOR_INSTALL_GXX"):
  65. continue
  66. from filelock import FileLock
  67. lock_dir = get_lock_dir()
  68. lock = FileLock(
  69. os.path.join(lock_dir, "g++.lock"), timeout=LOCK_TIMEOUT
  70. )
  71. with lock:
  72. cxx = install_gcc_via_conda()
  73. subprocess.check_output([cxx, "--version"])
  74. return cxx
  75. except (subprocess.SubprocessError, FileNotFoundError, ImportError):
  76. continue
  77. raise exc.InvalidCxxCompiler() # noqa: RSE102
  78. def install_gcc_via_conda() -> str:
  79. """On older systems, this is a quick way to get a modern compiler"""
  80. prefix = os.path.join(cache_dir(), "gcc")
  81. cxx_path = os.path.join(prefix, "bin", "g++")
  82. if not os.path.exists(cxx_path):
  83. log.info("Downloading GCC via conda")
  84. conda = os.environ.get("CONDA_EXE", "conda")
  85. if conda is None:
  86. conda = shutil.which("conda")
  87. if conda is not None:
  88. subprocess.check_call(
  89. [
  90. conda,
  91. "create",
  92. f"--prefix={prefix}",
  93. "--channel=conda-forge",
  94. "--quiet",
  95. "-y",
  96. "python=3.8",
  97. "gxx",
  98. ],
  99. stdout=subprocess.PIPE,
  100. )
  101. return cxx_path
  102. def _get_cpp_compiler() -> str:
  103. if _IS_WINDOWS:
  104. compiler = os.environ.get("CXX", "cl")
  105. else:
  106. if config.is_fbcode():
  107. return build_paths.cc()
  108. if isinstance(config.cpp.cxx, (list, tuple)):
  109. search = tuple(config.cpp.cxx)
  110. else:
  111. search = (config.cpp.cxx,)
  112. compiler = cpp_compiler_search(search)
  113. return compiler
  114. def _is_gcc(cpp_compiler) -> bool:
  115. return bool(re.search(r"(gcc|g\+\+)", cpp_compiler))
  116. def is_gcc() -> bool:
  117. return _is_gcc(_get_cpp_compiler())
  118. def _is_clang(cpp_compiler) -> bool:
  119. # Mac OS apple clang maybe named as gcc, need check compiler info.
  120. if sys.platform == "darwin":
  121. return is_apple_clang(cpp_compiler)
  122. return bool(re.search(r"(clang|clang\+\+)", cpp_compiler))
  123. def is_clang() -> bool:
  124. compiler = _get_cpp_compiler()
  125. return _is_clang(compiler)
  126. @functools.lru_cache(None)
  127. def is_apple_clang(cpp_compiler) -> bool:
  128. version_string = subprocess.check_output([cpp_compiler, "--version"]).decode("utf8")
  129. return "Apple" in version_string.splitlines()[0]
  130. def _append_list(dest_list: List[str], src_list: List[str]):
  131. for item in src_list:
  132. dest_list.append(copy.deepcopy(item))
  133. def _remove_duplication_in_list(orig_list: List[str]) -> List[str]:
  134. new_list: List[str] = []
  135. for item in orig_list:
  136. if item not in new_list:
  137. new_list.append(item)
  138. return new_list
  139. def _create_if_dir_not_exist(path_dir):
  140. if not os.path.exists(path_dir):
  141. try:
  142. Path(path_dir).mkdir(parents=True, exist_ok=True)
  143. except OSError as exc: # Guard against race condition
  144. if exc.errno != errno.EEXIST:
  145. raise RuntimeError( # noqa: TRY200 (Use `raise from`)
  146. f"Fail to create path {path_dir}"
  147. )
  148. def _remove_dir(path_dir):
  149. if os.path.exists(path_dir):
  150. for root, dirs, files in os.walk(path_dir, topdown=False):
  151. for name in files:
  152. file_path = os.path.join(root, name)
  153. os.remove(file_path)
  154. for name in dirs:
  155. dir_path = os.path.join(root, name)
  156. os.rmdir(dir_path)
  157. os.rmdir(path_dir)
  158. def run_command_line(cmd_line, cwd=None):
  159. cmd = shlex.split(cmd_line)
  160. try:
  161. status = subprocess.check_output(args=cmd, cwd=cwd, stderr=subprocess.STDOUT)
  162. except subprocess.CalledProcessError as e:
  163. output = e.output.decode("utf-8")
  164. openmp_problem = "'omp.h' file not found" in output or "libomp" in output
  165. if openmp_problem and sys.platform == "darwin":
  166. instruction = (
  167. "\n\nOpenMP support not found. Please try one of the following solutions:\n"
  168. "(1) Set the `CXX` environment variable to a compiler other than Apple clang++/g++ "
  169. "that has builtin OpenMP support;\n"
  170. "(2) install OpenMP via conda: `conda install llvm-openmp`;\n"
  171. "(3) install libomp via brew: `brew install libomp`;\n"
  172. "(4) manually setup OpenMP and set the `OMP_PREFIX` environment variable to point to a path"
  173. " with `include/omp.h` under it."
  174. )
  175. output += instruction
  176. raise exc.CppCompileError(cmd, output) from e
  177. return status
  178. class BuildOptionsBase:
  179. """
  180. This is the Base class for store cxx build options, as a template.
  181. Acturally, to build a cxx shared library. We just need to select a compiler
  182. and maintains the suitable args.
  183. """
  184. def __init__(self) -> None:
  185. self._compiler = ""
  186. self._definations: List[str] = []
  187. self._include_dirs: List[str] = []
  188. self._cflags: List[str] = []
  189. self._ldflags: List[str] = []
  190. self._libraries_dirs: List[str] = []
  191. self._libraries: List[str] = []
  192. # Some args is hard to abstract to OS compatable, passthough it directly.
  193. self._passthough_args: List[str] = []
  194. self._aot_mode: bool = False
  195. self._use_absolute_path: bool = False
  196. self._compile_only: bool = False
  197. def _remove_duplicate_options(self):
  198. self._definations = _remove_duplication_in_list(self._definations)
  199. self._include_dirs = _remove_duplication_in_list(self._include_dirs)
  200. self._cflags = _remove_duplication_in_list(self._cflags)
  201. self._ldflags = _remove_duplication_in_list(self._ldflags)
  202. self._libraries_dirs = _remove_duplication_in_list(self._libraries_dirs)
  203. self._libraries = _remove_duplication_in_list(self._libraries)
  204. self._passthough_args = _remove_duplication_in_list(self._passthough_args)
  205. def get_compiler(self) -> str:
  206. return self._compiler
  207. def get_definations(self) -> List[str]:
  208. return self._definations
  209. def get_include_dirs(self) -> List[str]:
  210. return self._include_dirs
  211. def get_cflags(self) -> List[str]:
  212. return self._cflags
  213. def get_ldflags(self) -> List[str]:
  214. return self._ldflags
  215. def get_libraries_dirs(self) -> List[str]:
  216. return self._libraries_dirs
  217. def get_libraries(self) -> List[str]:
  218. return self._libraries
  219. def get_passthough_args(self) -> List[str]:
  220. return self._passthough_args
  221. def get_aot_mode(self) -> bool:
  222. return self._aot_mode
  223. def get_use_absolute_path(self) -> bool:
  224. return self._use_absolute_path
  225. def get_compile_only(self) -> bool:
  226. return self._compile_only
  227. def _get_warning_all_cflag(warning_all: bool = True) -> List[str]:
  228. if not _IS_WINDOWS:
  229. return ["Wall"] if warning_all else []
  230. else:
  231. return []
  232. def _get_cpp_std_cflag(std_num: str = "c++17") -> List[str]:
  233. if _IS_WINDOWS:
  234. return [f"std:{std_num}"]
  235. else:
  236. return [f"std={std_num}"]
  237. def _get_linux_cpp_cflags(cpp_compiler) -> List[str]:
  238. if not _IS_WINDOWS:
  239. cflags = ["Wno-unused-variable", "Wno-unknown-pragmas"]
  240. if _is_clang(cpp_compiler):
  241. cflags.append("Werror=ignored-optimization-argument")
  242. return cflags
  243. else:
  244. return []
  245. def _get_optimization_cflags() -> List[str]:
  246. if _IS_WINDOWS:
  247. return ["O2"]
  248. else:
  249. cflags = ["O0", "g"] if config.aot_inductor.debug_compile else ["O3", "DNDEBUG"]
  250. cflags.append("ffast-math")
  251. cflags.append("fno-finite-math-only")
  252. if not config.cpp.enable_unsafe_math_opt_flag:
  253. cflags.append("fno-unsafe-math-optimizations")
  254. if not config.cpp.enable_floating_point_contract_flag:
  255. cflags.append("ffp-contract=off")
  256. if config.is_fbcode():
  257. # FIXME: passing `-fopenmp` adds libgomp.so to the generated shared library's dependencies.
  258. # This causes `ldopen` to fail in fbcode, because libgomp does not exist in the default paths.
  259. # We will fix it later by exposing the lib path.
  260. return cflags
  261. if sys.platform == "darwin":
  262. # Per https://mac.r-project.org/openmp/ right way to pass `openmp` flags to MacOS is via `-Xclang`
  263. # Also, `-march=native` is unrecognized option on M1
  264. cflags.append("Xclang")
  265. else:
  266. if platform.machine() == "ppc64le":
  267. cflags.append("mcpu=native")
  268. else:
  269. cflags.append("march=native")
  270. # Internal cannot find libgomp.so
  271. if not config.is_fbcode():
  272. cflags.append("fopenmp")
  273. return cflags
  274. def _get_shared_cflag(compile_only: bool) -> List[str]:
  275. if _IS_WINDOWS:
  276. SHARED_FLAG = ["DLL"]
  277. else:
  278. if compile_only:
  279. return ["fPIC"]
  280. if platform.system() == "Darwin" and "clang" in _get_cpp_compiler():
  281. # This causes undefined symbols to behave the same as linux
  282. return ["shared", "fPIC", "undefined dynamic_lookup"]
  283. else:
  284. return ["shared", "fPIC"]
  285. return SHARED_FLAG
  286. def get_cpp_options(
  287. cpp_compiler,
  288. compile_only: bool,
  289. warning_all: bool = True,
  290. extra_flags: Sequence[str] = (),
  291. ):
  292. definations: List[str] = []
  293. include_dirs: List[str] = []
  294. cflags: List[str] = []
  295. ldflags: List[str] = []
  296. libraries_dirs: List[str] = []
  297. libraries: List[str] = []
  298. passthough_args: List[str] = []
  299. cflags = (
  300. _get_shared_cflag(compile_only)
  301. + _get_optimization_cflags()
  302. + _get_warning_all_cflag(warning_all)
  303. + _get_cpp_std_cflag()
  304. + _get_linux_cpp_cflags(cpp_compiler)
  305. )
  306. passthough_args.append(" ".join(extra_flags))
  307. return (
  308. definations,
  309. include_dirs,
  310. cflags,
  311. ldflags,
  312. libraries_dirs,
  313. libraries,
  314. passthough_args,
  315. )
  316. class CppOptions(BuildOptionsBase):
  317. """
  318. This class is inherited from BuildOptionsBase, and as cxx build options.
  319. This option need contains basic cxx build option, which contains:
  320. 1. OS related args.
  321. 2. Toolchains related args.
  322. 3. Cxx standard related args.
  323. Note:
  324. 1. This Options is good for assist modules build, such as x86_isa_help.
  325. """
  326. def __init__(
  327. self,
  328. compile_only: bool,
  329. warning_all: bool = True,
  330. extra_flags: Sequence[str] = (),
  331. use_absolute_path: bool = False,
  332. ) -> None:
  333. super().__init__()
  334. self._compiler = _get_cpp_compiler()
  335. self._use_absolute_path = use_absolute_path
  336. self._compile_only = compile_only
  337. (
  338. definations,
  339. include_dirs,
  340. cflags,
  341. ldflags,
  342. libraries_dirs,
  343. libraries,
  344. passthough_args,
  345. ) = get_cpp_options(
  346. cpp_compiler=self._compiler,
  347. compile_only=compile_only,
  348. extra_flags=extra_flags,
  349. warning_all=warning_all,
  350. )
  351. _append_list(self._definations, definations)
  352. _append_list(self._include_dirs, include_dirs)
  353. _append_list(self._cflags, cflags)
  354. _append_list(self._ldflags, ldflags)
  355. _append_list(self._libraries_dirs, libraries_dirs)
  356. _append_list(self._libraries, libraries)
  357. _append_list(self._passthough_args, passthough_args)
  358. self._remove_duplicate_options()
  359. def _get_glibcxx_abi_build_flags() -> List[str]:
  360. if not _IS_WINDOWS:
  361. return ["-D_GLIBCXX_USE_CXX11_ABI=" + str(int(torch._C._GLIBCXX_USE_CXX11_ABI))]
  362. else:
  363. return []
  364. def _get_torch_cpp_wrapper_defination() -> List[str]:
  365. return ["TORCH_INDUCTOR_CPP_WRAPPER"]
  366. def _use_custom_generated_macros() -> List[str]:
  367. return [" C10_USING_CUSTOM_GENERATED_MACROS"]
  368. def _use_fb_internal_macros() -> List[str]:
  369. if not _IS_WINDOWS:
  370. if config.is_fbcode():
  371. fb_internal_macros = [
  372. "C10_USE_GLOG",
  373. "C10_USE_MINIMAL_GLOG",
  374. "C10_DISABLE_TENSORIMPL_EXTENSIBILITY",
  375. ]
  376. # TODO: this is to avoid FC breakage for fbcode. When using newly
  377. # generated model.so on an older verion of PyTorch, need to use
  378. # the v1 version for aoti_torch_create_tensor_from_blob
  379. create_tensor_from_blob_v1 = "AOTI_USE_CREATE_TENSOR_FROM_BLOB_V1"
  380. fb_internal_macros.append(create_tensor_from_blob_v1)
  381. # TODO: remove comments later:
  382. # Moved to _get_openmp_args
  383. # openmp_lib = build_paths.openmp_lib()
  384. # return [f"-Wp,-fopenmp {openmp_lib} {preprocessor_flags}"]
  385. return fb_internal_macros
  386. else:
  387. return []
  388. else:
  389. return []
  390. def _setup_standard_sys_libs(
  391. cpp_compiler,
  392. aot_mode: bool,
  393. use_absolute_path: bool,
  394. ):
  395. cflags: List[str] = []
  396. include_dirs: List[str] = []
  397. passthough_args: List[str] = []
  398. if _IS_WINDOWS:
  399. return cflags, include_dirs, passthough_args
  400. if config.is_fbcode():
  401. cflags.append("nostdinc")
  402. include_dirs.append(build_paths.sleef())
  403. include_dirs.append(build_paths.cc_include())
  404. include_dirs.append(build_paths.libgcc())
  405. include_dirs.append(build_paths.libgcc_arch())
  406. include_dirs.append(build_paths.libgcc_backward())
  407. include_dirs.append(build_paths.glibc())
  408. include_dirs.append(build_paths.linux_kernel())
  409. include_dirs.append("include")
  410. if aot_mode and not use_absolute_path:
  411. linker_script = _LINKER_SCRIPT
  412. else:
  413. linker_script = os.path.basename(_LINKER_SCRIPT)
  414. if _is_clang(cpp_compiler):
  415. passthough_args.append(" --rtlib=compiler-rt")
  416. passthough_args.append(" -fuse-ld=lld")
  417. passthough_args.append(f" -Wl,--script={linker_script}")
  418. passthough_args.append(" -B" + build_paths.glibc_lib())
  419. passthough_args.append(" -L" + build_paths.glibc_lib())
  420. return cflags, include_dirs, passthough_args
  421. @functools.lru_cache
  422. def _cpp_prefix_path() -> str:
  423. from torch._inductor.codecache import write # TODO
  424. path = Path(Path(__file__).parent).parent / "codegen/cpp_prefix.h"
  425. with path.open() as f:
  426. content = f.read()
  427. _, filename = write(
  428. content,
  429. "h",
  430. )
  431. return filename
  432. def _get_build_args_of_chosen_isa(vec_isa: VecISA):
  433. macros = []
  434. build_flags = []
  435. if vec_isa != invalid_vec_isa:
  436. # Add Windows support later.
  437. for x in vec_isa.build_macro():
  438. macros.append(copy.deepcopy(x))
  439. build_flags = [vec_isa.build_arch_flags()]
  440. if config.is_fbcode() and vec_isa != invalid_vec_isa:
  441. cap = str(vec_isa).upper()
  442. macros = [
  443. f"CPU_CAPABILITY={cap}",
  444. f"CPU_CAPABILITY_{cap}",
  445. f"HAVE_{cap}_CPU_DEFINITION",
  446. ]
  447. return macros, build_flags
  448. def _get_torch_related_args(include_pytorch: bool, aot_mode: bool):
  449. from torch.utils.cpp_extension import _TORCH_PATH, TORCH_LIB_PATH
  450. include_dirs = [
  451. os.path.join(_TORCH_PATH, "include"),
  452. os.path.join(_TORCH_PATH, "include", "torch", "csrc", "api", "include"),
  453. # Some internal (old) Torch headers don't properly prefix their includes,
  454. # so we need to pass -Itorch/lib/include/TH as well.
  455. os.path.join(_TORCH_PATH, "include", "TH"),
  456. os.path.join(_TORCH_PATH, "include", "THC"),
  457. ]
  458. libraries_dirs = [TORCH_LIB_PATH]
  459. libraries = []
  460. if sys.platform == "linux" and not config.is_fbcode():
  461. libraries = ["torch", "torch_cpu"]
  462. if not aot_mode:
  463. libraries.append("torch_python")
  464. if _IS_WINDOWS:
  465. libraries.append("sleef")
  466. # Unconditionally import c10 for non-abi-compatible mode to use TORCH_CHECK - See PyTorch #108690
  467. if not config.abi_compatible:
  468. libraries.append("c10")
  469. libraries_dirs.append(TORCH_LIB_PATH)
  470. return include_dirs, libraries_dirs, libraries
  471. def _get_python_related_args():
  472. python_include_dirs = _get_python_include_dirs()
  473. python_include_path = sysconfig.get_path(
  474. "include", scheme="nt" if _IS_WINDOWS else "posix_prefix"
  475. )
  476. if python_include_path is not None:
  477. python_include_dirs.append(python_include_path)
  478. if _IS_WINDOWS:
  479. python_path = os.path.dirname(sys.executable)
  480. python_lib_path = [os.path.join(python_path, "libs")]
  481. else:
  482. python_lib_path = [sysconfig.get_config_var("LIBDIR")]
  483. if config.is_fbcode():
  484. python_include_dirs.append(build_paths.python())
  485. return python_include_dirs, python_lib_path
  486. def _get_openmp_args(cpp_compiler):
  487. cflags: List[str] = []
  488. ldflags: List[str] = []
  489. include_dir_paths: List[str] = []
  490. lib_dir_paths: List[str] = []
  491. libs: List[str] = []
  492. passthough_args: List[str] = []
  493. if _IS_MACOS:
  494. from torch._inductor.codecache import (
  495. homebrew_libomp,
  496. is_conda_llvm_openmp_installed,
  497. )
  498. # only Apple builtin compilers (Apple Clang++) require openmp
  499. omp_available = not is_apple_clang(cpp_compiler)
  500. # check the `OMP_PREFIX` environment first
  501. omp_prefix = os.getenv("OMP_PREFIX")
  502. if omp_prefix is not None:
  503. header_path = os.path.join(omp_prefix, "include", "omp.h")
  504. valid_env = os.path.exists(header_path)
  505. if valid_env:
  506. include_dir_paths.append(os.path.join(omp_prefix, "include"))
  507. lib_dir_paths.append(os.path.join(omp_prefix, "lib"))
  508. else:
  509. warnings.warn("environment variable `OMP_PREFIX` is invalid.")
  510. omp_available = omp_available or valid_env
  511. if not omp_available:
  512. libs.append("omp")
  513. # prefer to use openmp from `conda install llvm-openmp`
  514. conda_prefix = os.getenv("CONDA_PREFIX")
  515. if not omp_available and conda_prefix is not None:
  516. omp_available = is_conda_llvm_openmp_installed()
  517. if omp_available:
  518. conda_lib_path = os.path.join(conda_prefix, "lib")
  519. include_dir_paths.append(os.path.join(conda_prefix, "include"))
  520. lib_dir_paths.append(conda_lib_path)
  521. # Prefer Intel OpenMP on x86 machine
  522. if os.uname().machine == "x86_64" and os.path.exists(
  523. os.path.join(conda_lib_path, "libiomp5.dylib")
  524. ):
  525. libs.append("iomp5")
  526. # next, try to use openmp from `brew install libomp`
  527. if not omp_available:
  528. omp_available, libomp_path = homebrew_libomp()
  529. if omp_available:
  530. include_dir_paths.append(os.path.join(libomp_path, "include"))
  531. lib_dir_paths.append(os.path.join(libomp_path, "lib"))
  532. # if openmp is still not available, we let the compiler to have a try,
  533. # and raise error together with instructions at compilation error later
  534. elif _IS_WINDOWS:
  535. # /openmp, /openmp:llvm
  536. # llvm on Windows, new openmp: https://devblogs.microsoft.com/cppblog/msvc-openmp-update/
  537. # msvc openmp: https://learn.microsoft.com/zh-cn/cpp/build/reference/openmp-enable-openmp-2-0-support?view=msvc-170
  538. cflags.append("openmp")
  539. libs = []
  540. else:
  541. if config.is_fbcode():
  542. include_dir_paths.append(build_paths.openmp())
  543. openmp_lib = build_paths.openmp_lib()
  544. fb_openmp_extra_flags = f"-Wp,-fopenmp {openmp_lib}"
  545. passthough_args.append(fb_openmp_extra_flags)
  546. libs.append("omp")
  547. else:
  548. if _is_clang(cpp_compiler):
  549. # TODO: fix issue, can't find omp.h
  550. cflags.append("fopenmp")
  551. libs.append("gomp")
  552. else:
  553. cflags.append("fopenmp")
  554. libs.append("gomp")
  555. return cflags, ldflags, include_dir_paths, lib_dir_paths, libs, passthough_args
  556. def get_mmap_self_macro(use_mmap_weights: bool) -> List[str]:
  557. macros = []
  558. if use_mmap_weights:
  559. macros.append(" USE_MMAP_SELF")
  560. return macros
  561. def get_cpp_torch_options(
  562. cpp_compiler,
  563. vec_isa: VecISA,
  564. include_pytorch: bool,
  565. aot_mode: bool,
  566. compile_only: bool,
  567. use_absolute_path: bool,
  568. use_mmap_weights: bool,
  569. ):
  570. definations: List[str] = []
  571. include_dirs: List[str] = []
  572. cflags: List[str] = []
  573. ldflags: List[str] = []
  574. libraries_dirs: List[str] = []
  575. libraries: List[str] = []
  576. passthough_args: List[str] = []
  577. torch_cpp_wrapper_definations = _get_torch_cpp_wrapper_defination()
  578. use_custom_generated_macros_definations = _use_custom_generated_macros()
  579. (
  580. sys_libs_cflags,
  581. sys_libs_include_dirs,
  582. sys_libs_passthough_args,
  583. ) = _setup_standard_sys_libs(cpp_compiler, aot_mode, use_absolute_path)
  584. isa_macros, isa_ps_args_build_flags = _get_build_args_of_chosen_isa(vec_isa)
  585. (
  586. torch_include_dirs,
  587. torch_libraries_dirs,
  588. torch_libraries,
  589. ) = _get_torch_related_args(include_pytorch=include_pytorch, aot_mode=aot_mode)
  590. python_include_dirs, python_libraries_dirs = _get_python_related_args()
  591. (
  592. omp_cflags,
  593. omp_ldflags,
  594. omp_include_dir_paths,
  595. omp_lib_dir_paths,
  596. omp_lib,
  597. omp_passthough_args,
  598. ) = _get_openmp_args(cpp_compiler)
  599. cxx_abi_passthough_args = _get_glibcxx_abi_build_flags()
  600. fb_macro_passthough_args = _use_fb_internal_macros()
  601. mmap_self_macros = get_mmap_self_macro(use_mmap_weights)
  602. definations = (
  603. torch_cpp_wrapper_definations
  604. + use_custom_generated_macros_definations
  605. + isa_macros
  606. + fb_macro_passthough_args
  607. + mmap_self_macros
  608. )
  609. include_dirs = (
  610. sys_libs_include_dirs
  611. + python_include_dirs
  612. + torch_include_dirs
  613. + omp_include_dir_paths
  614. )
  615. cflags = sys_libs_cflags + omp_cflags
  616. ldflags = omp_ldflags
  617. libraries_dirs = python_libraries_dirs + torch_libraries_dirs + omp_lib_dir_paths
  618. libraries = torch_libraries + omp_lib
  619. passthough_args = (
  620. sys_libs_passthough_args
  621. + isa_ps_args_build_flags
  622. + cxx_abi_passthough_args
  623. + omp_passthough_args
  624. )
  625. return (
  626. definations,
  627. include_dirs,
  628. cflags,
  629. ldflags,
  630. libraries_dirs,
  631. libraries,
  632. passthough_args,
  633. )
  634. class CppTorchOptions(CppOptions):
  635. """
  636. This class is inherited from CppTorchOptions, which automatic contains
  637. base cxx build options. And then it will maintains torch related build
  638. args.
  639. 1. Torch include_directories, libraries, libraries_directories.
  640. 2. Python include_directories, libraries, libraries_directories.
  641. 3. OpenMP related.
  642. 4. Torch MACROs.
  643. 5. MISC
  644. """
  645. def __init__(
  646. self,
  647. vec_isa: VecISA,
  648. include_pytorch: bool = False,
  649. warning_all: bool = True,
  650. aot_mode: bool = False,
  651. compile_only: bool = False,
  652. use_absolute_path: bool = False,
  653. use_mmap_weights: bool = False,
  654. shared: bool = True,
  655. extra_flags: Sequence[str] = (),
  656. ) -> None:
  657. super().__init__(
  658. compile_only=compile_only,
  659. warning_all=warning_all,
  660. extra_flags=extra_flags,
  661. use_absolute_path=use_absolute_path,
  662. )
  663. self._aot_mode = aot_mode
  664. (
  665. torch_definations,
  666. torch_include_dirs,
  667. torch_cflags,
  668. torch_ldflags,
  669. torch_libraries_dirs,
  670. torch_libraries,
  671. torch_passthough_args,
  672. ) = get_cpp_torch_options(
  673. cpp_compiler=self._compiler,
  674. vec_isa=vec_isa,
  675. include_pytorch=include_pytorch,
  676. aot_mode=aot_mode,
  677. compile_only=compile_only,
  678. use_absolute_path=use_absolute_path,
  679. use_mmap_weights=use_mmap_weights,
  680. )
  681. if compile_only:
  682. torch_libraries_dirs = []
  683. torch_libraries = []
  684. _append_list(self._definations, torch_definations)
  685. _append_list(self._include_dirs, torch_include_dirs)
  686. _append_list(self._cflags, torch_cflags)
  687. _append_list(self._ldflags, torch_ldflags)
  688. _append_list(self._libraries_dirs, torch_libraries_dirs)
  689. _append_list(self._libraries, torch_libraries)
  690. _append_list(self._passthough_args, torch_passthough_args)
  691. self._remove_duplicate_options()
  692. def get_cpp_torch_cuda_options(cuda: bool, aot_mode: bool = False):
  693. definations: List[str] = []
  694. include_dirs: List[str] = []
  695. cflags: List[str] = []
  696. ldflags: List[str] = []
  697. libraries_dirs: List[str] = []
  698. libraries: List[str] = []
  699. passthough_args: List[str] = []
  700. if (
  701. config.is_fbcode()
  702. and "CUDA_HOME" not in os.environ
  703. and "CUDA_PATH" not in os.environ
  704. ):
  705. os.environ["CUDA_HOME"] = build_paths.cuda()
  706. from torch.utils import cpp_extension
  707. include_dirs = cpp_extension.include_paths(cuda)
  708. libraries_dirs = cpp_extension.library_paths(cuda)
  709. if cuda:
  710. definations.append(" USE_ROCM" if torch.version.hip else " USE_CUDA")
  711. if torch.version.hip is not None:
  712. if config.is_fbcode():
  713. libraries += ["amdhip64"]
  714. else:
  715. libraries += ["c10_hip", "torch_hip"]
  716. definations.append(" __HIP_PLATFORM_AMD__")
  717. else:
  718. if config.is_fbcode():
  719. libraries += ["cuda"]
  720. else:
  721. if config.is_fbcode():
  722. libraries += ["cuda"]
  723. else:
  724. libraries += ["c10_cuda", "cuda", "torch_cuda"]
  725. if aot_mode:
  726. cpp_prefix_include_dir = [f"{os.path.dirname(_cpp_prefix_path())}"]
  727. include_dirs += cpp_prefix_include_dir
  728. if cuda and torch.version.hip is None:
  729. _transform_cuda_paths(libraries_dirs)
  730. if config.is_fbcode():
  731. if torch.version.hip is not None:
  732. include_dirs.append(os.path.join(build_paths.rocm(), "include"))
  733. else:
  734. include_dirs.append(os.path.join(build_paths.cuda(), "include"))
  735. if aot_mode and cuda and config.is_fbcode():
  736. if torch.version.hip is None:
  737. # TODO: make static link better on Linux.
  738. passthough_args = ["-Wl,-Bstatic -lcudart_static -Wl,-Bdynamic"]
  739. return (
  740. definations,
  741. include_dirs,
  742. cflags,
  743. ldflags,
  744. libraries_dirs,
  745. libraries,
  746. passthough_args,
  747. )
  748. class CppTorchCudaOptions(CppTorchOptions):
  749. """
  750. This class is inherited from CppTorchOptions, which automatic contains
  751. base cxx build options and torch common build options. And then it will
  752. maintains cuda device related build args.
  753. """
  754. def __init__(
  755. self,
  756. vec_isa: VecISA,
  757. include_pytorch: bool = False,
  758. cuda: bool = True,
  759. aot_mode: bool = False,
  760. compile_only: bool = False,
  761. use_absolute_path: bool = False,
  762. use_mmap_weights: bool = False,
  763. shared: bool = True,
  764. extra_flags: Sequence[str] = (),
  765. ) -> None:
  766. super().__init__(
  767. vec_isa=vec_isa,
  768. include_pytorch=include_pytorch,
  769. aot_mode=aot_mode,
  770. compile_only=compile_only,
  771. use_absolute_path=use_absolute_path,
  772. use_mmap_weights=use_mmap_weights,
  773. extra_flags=extra_flags,
  774. )
  775. cuda_definations: List[str] = []
  776. cuda_include_dirs: List[str] = []
  777. cuda_cflags: List[str] = []
  778. cuda_ldflags: List[str] = []
  779. cuda_libraries_dirs: List[str] = []
  780. cuda_libraries: List[str] = []
  781. cuda_passthough_args: List[str] = []
  782. (
  783. cuda_definations,
  784. cuda_include_dirs,
  785. cuda_cflags,
  786. cuda_ldflags,
  787. cuda_libraries_dirs,
  788. cuda_libraries,
  789. cuda_passthough_args,
  790. ) = get_cpp_torch_cuda_options(cuda=cuda, aot_mode=aot_mode)
  791. if compile_only:
  792. cuda_libraries_dirs = []
  793. cuda_libraries = []
  794. _append_list(self._definations, cuda_definations)
  795. _append_list(self._include_dirs, cuda_include_dirs)
  796. _append_list(self._cflags, cuda_cflags)
  797. _append_list(self._ldflags, cuda_ldflags)
  798. _append_list(self._libraries_dirs, cuda_libraries_dirs)
  799. _append_list(self._libraries, cuda_libraries)
  800. _append_list(self._passthough_args, cuda_passthough_args)
  801. self._remove_duplicate_options()
  802. def get_name_and_dir_from_output_file_path(
  803. aot_mode: bool, use_absolute_path: bool, file_path: str
  804. ):
  805. name_and_ext = os.path.basename(file_path)
  806. name, ext = os.path.splitext(name_and_ext)
  807. dir = os.path.dirname(file_path)
  808. if config.is_fbcode():
  809. if not (aot_mode and not use_absolute_path):
  810. dir = "."
  811. return name, dir
  812. class CppBuilder:
  813. """
  814. CppBuilder is a cpp jit builder, and it supports both Windows, Linux and MacOS.
  815. Args:
  816. name:
  817. 1. Build target name, the final target file will append extension type automatically.
  818. 2. Due to the CppBuilder is supports mutliple OS, it will maintains ext for OS difference.
  819. sources:
  820. Source code file list to be built.
  821. BuildOption:
  822. Build options to the builder.
  823. output_dir:
  824. 1. The output_dir the taget file will output to.
  825. 2. The default value is empty string, and then the use current dir as output dir.
  826. 3. Final target file: output_dir/name.ext
  827. """
  828. def get_shared_lib_ext(self) -> str:
  829. SHARED_LIB_EXT = ".dll" if _IS_WINDOWS else ".so"
  830. return SHARED_LIB_EXT
  831. def get_object_ext(self) -> str:
  832. EXT = ".obj" if _IS_WINDOWS else ".o"
  833. return EXT
  834. def __init__(
  835. self,
  836. name: str,
  837. sources: Union[str, List[str]],
  838. BuildOption: BuildOptionsBase,
  839. output_dir: str = "",
  840. ) -> None:
  841. self._compiler = ""
  842. self._cflags_args = ""
  843. self._definations_args = ""
  844. self._include_dirs_args = ""
  845. self._ldflags_args = ""
  846. self._libraries_dirs_args = ""
  847. self._libraries_args = ""
  848. self._passthough_parameters_args = ""
  849. self._output_dir = ""
  850. self._target_file = ""
  851. self._use_absolute_path: bool = False
  852. self._name = name
  853. # Code start here, initial self internal veriables firstly.
  854. self._compiler = BuildOption.get_compiler()
  855. self._use_absolute_path = BuildOption.get_use_absolute_path()
  856. if len(output_dir) == 0:
  857. self._output_dir = os.path.dirname(os.path.abspath(__file__))
  858. else:
  859. self._output_dir = output_dir
  860. self._compile_only = BuildOption.get_compile_only()
  861. file_ext = (
  862. self.get_object_ext() if self._compile_only else self.get_shared_lib_ext()
  863. )
  864. self._target_file = os.path.join(self._output_dir, f"{self._name}{file_ext}")
  865. if isinstance(sources, str):
  866. sources = [sources]
  867. if config.is_fbcode():
  868. if BuildOption.get_aot_mode() and not self._use_absolute_path:
  869. inp_name = sources
  870. # output process @ get_name_and_dir_from_output_file_path
  871. else:
  872. # We need to copy any absolute-path torch includes
  873. inp_name = [os.path.basename(i) for i in sources]
  874. self._target_file = os.path.basename(self._target_file)
  875. self._sources_args = " ".join(inp_name)
  876. else:
  877. self._sources_args = " ".join(sources)
  878. for cflag in BuildOption.get_cflags():
  879. if _IS_WINDOWS:
  880. self._cflags_args += f"/{cflag} "
  881. else:
  882. self._cflags_args += f"-{cflag} "
  883. for defination in BuildOption.get_definations():
  884. if _IS_WINDOWS:
  885. self._definations_args += f"/D {defination} "
  886. else:
  887. self._definations_args += f"-D {defination} "
  888. for inc_dir in BuildOption.get_include_dirs():
  889. if _IS_WINDOWS:
  890. self._include_dirs_args += f"/I {inc_dir} "
  891. else:
  892. self._include_dirs_args += f"-I{inc_dir} "
  893. for ldflag in BuildOption.get_ldflags():
  894. if _IS_WINDOWS:
  895. self._ldflags_args += f"/{ldflag} "
  896. else:
  897. self._ldflags_args += f"-{ldflag} "
  898. for lib_dir in BuildOption.get_libraries_dirs():
  899. if _IS_WINDOWS:
  900. self._libraries_dirs_args += f'/LIBPATH:"{lib_dir}" '
  901. else:
  902. self._libraries_dirs_args += f"-L{lib_dir} "
  903. for lib in BuildOption.get_libraries():
  904. if _IS_WINDOWS:
  905. self._libraries_args += f'"{lib}.lib" '
  906. else:
  907. self._libraries_args += f"-l{lib} "
  908. for passthough_arg in BuildOption.get_passthough_args():
  909. self._passthough_parameters_args += f"{passthough_arg} "
  910. def get_command_line(self) -> str:
  911. def format_build_command(
  912. compiler,
  913. sources,
  914. include_dirs_args,
  915. definations_args,
  916. cflags_args,
  917. ldflags_args,
  918. libraries_args,
  919. libraries_dirs_args,
  920. passthougn_args,
  921. target_file,
  922. ):
  923. if _IS_WINDOWS:
  924. # https://learn.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line?view=msvc-1704
  925. # https://stackoverflow.com/a/31566153
  926. cmd = (
  927. f"{compiler} {include_dirs_args} {definations_args} {cflags_args} {sources} "
  928. f"{passthougn_args} /LD /Fe{target_file} /link {libraries_dirs_args} {libraries_args} {ldflags_args} "
  929. )
  930. cmd = cmd.replace("\\", "/")
  931. else:
  932. compile_only_arg = "-c" if self._compile_only else ""
  933. cmd = re.sub(
  934. r"[ \n]+",
  935. " ",
  936. f"""
  937. {compiler} {sources} {definations_args} {cflags_args} {include_dirs_args}
  938. {passthougn_args} {ldflags_args} {libraries_args} {libraries_dirs_args} {compile_only_arg} -o {target_file}
  939. """,
  940. ).strip()
  941. return cmd
  942. command_line = format_build_command(
  943. compiler=self._compiler,
  944. sources=self._sources_args,
  945. include_dirs_args=self._include_dirs_args,
  946. definations_args=self._definations_args,
  947. cflags_args=self._cflags_args,
  948. ldflags_args=self._ldflags_args,
  949. libraries_args=self._libraries_args,
  950. libraries_dirs_args=self._libraries_dirs_args,
  951. passthougn_args=self._passthough_parameters_args,
  952. target_file=self._target_file,
  953. )
  954. return command_line
  955. def get_target_file_path(self):
  956. return self._target_file
  957. def convert_to_cpp_extension_args(self):
  958. include_dirs = self._include_dirs_args
  959. cflags = (
  960. self._cflags_args
  961. + self._definations_args
  962. + self._passthough_parameters_args
  963. )
  964. ldflags = self._ldflags_args + self._libraries_args + self._libraries_dirs_args
  965. return include_dirs, cflags, ldflags
  966. def build(self) -> Tuple[int, str]:
  967. """
  968. It is must need a temperary directory to store object files in Windows.
  969. After build completed, delete the temperary directory to save disk space.
  970. """
  971. _create_if_dir_not_exist(self._output_dir)
  972. _build_tmp_dir = os.path.join(
  973. self._output_dir, f"{self._name}_{_BUILD_TEMP_DIR}"
  974. )
  975. _create_if_dir_not_exist(_build_tmp_dir)
  976. build_cmd = self.get_command_line()
  977. status = run_command_line(build_cmd, cwd=_build_tmp_dir)
  978. _remove_dir(_build_tmp_dir)
  979. return status, self._target_file