utils.cmake 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. #
  2. # Attempt to find the python package that uses the same python executable as
  3. # `EXECUTABLE` and is one of the `SUPPORTED_VERSIONS`.
  4. #
  5. macro (find_python_from_executable EXECUTABLE SUPPORTED_VERSIONS)
  6. file(TO_CMAKE_PATH "${EXECUTABLE}" EXECUTABLE_PATH)
  7. file(REAL_PATH "${EXECUTABLE_PATH}" EXECUTABLE)
  8. set(Python_EXECUTABLE ${EXECUTABLE})
  9. find_package(Python COMPONENTS Interpreter Development.Module Development.SABIModule)
  10. if (NOT Python_FOUND)
  11. message(FATAL_ERROR "Unable to find python matching: ${EXECUTABLE}.")
  12. endif()
  13. set(_VER "${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}")
  14. set(_SUPPORTED_VERSIONS_LIST ${SUPPORTED_VERSIONS} ${ARGN})
  15. if (NOT _VER IN_LIST _SUPPORTED_VERSIONS_LIST)
  16. message(FATAL_ERROR
  17. "Python version (${_VER}) is not one of the supported versions: "
  18. "${_SUPPORTED_VERSIONS_LIST}.")
  19. endif()
  20. message(STATUS "Found python matching: ${EXECUTABLE}.")
  21. endmacro()
  22. #
  23. # Run `EXPR` in python. The standard output of python is stored in `OUT` and
  24. # has trailing whitespace stripped. If an error is encountered when running
  25. # python, a fatal message `ERR_MSG` is issued.
  26. #
  27. function (run_python OUT EXPR ERR_MSG)
  28. execute_process(
  29. COMMAND
  30. "${Python_EXECUTABLE}" "-c" "${EXPR}"
  31. OUTPUT_VARIABLE PYTHON_OUT
  32. RESULT_VARIABLE PYTHON_ERROR_CODE
  33. ERROR_VARIABLE PYTHON_STDERR
  34. OUTPUT_STRIP_TRAILING_WHITESPACE)
  35. if(NOT PYTHON_ERROR_CODE EQUAL 0)
  36. message(FATAL_ERROR "${ERR_MSG}: ${PYTHON_STDERR}")
  37. endif()
  38. set(${OUT} ${PYTHON_OUT} PARENT_SCOPE)
  39. endfunction()
  40. # Run `EXPR` in python after importing `PKG`. Use the result of this to extend
  41. # `CMAKE_PREFIX_PATH` so the torch cmake configuration can be imported.
  42. macro (append_cmake_prefix_path PKG EXPR)
  43. run_python(_PREFIX_PATH
  44. "import ${PKG}; print(${EXPR})" "Failed to locate ${PKG} path")
  45. list(APPEND CMAKE_PREFIX_PATH ${_PREFIX_PATH})
  46. endmacro()
  47. #
  48. # Add a target named `hipify${NAME}` that runs the hipify preprocessor on a set
  49. # of CUDA source files. The names of the corresponding "hipified" sources are
  50. # stored in `OUT_SRCS`.
  51. #
  52. function (hipify_sources_target OUT_SRCS NAME ORIG_SRCS)
  53. #
  54. # Split into C++ and non-C++ (i.e. CUDA) sources.
  55. #
  56. set(SRCS ${ORIG_SRCS})
  57. set(CXX_SRCS ${ORIG_SRCS})
  58. list(FILTER SRCS EXCLUDE REGEX "\.(cc)|(cpp)$")
  59. list(FILTER CXX_SRCS INCLUDE REGEX "\.(cc)|(cpp)$")
  60. #
  61. # Generate ROCm/HIP source file names from CUDA file names.
  62. # Since HIP files are generated code, they will appear in the build area
  63. # `CMAKE_CURRENT_BINARY_DIR` directory rather than the original kernels dir.
  64. #
  65. set(HIP_SRCS)
  66. foreach (SRC ${SRCS})
  67. string(REGEX REPLACE "\.cu$" "\.hip" SRC ${SRC})
  68. string(REGEX REPLACE "cuda" "hip" SRC ${SRC})
  69. list(APPEND HIP_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${SRC}")
  70. endforeach()
  71. set(CSRC_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/kernels)
  72. add_custom_target(
  73. hipify${NAME}
  74. COMMAND ${CMAKE_SOURCE_DIR}/cmake/hipify.py -p ${CMAKE_SOURCE_DIR}/kernels -o ${CSRC_BUILD_DIR} ${SRCS}
  75. DEPENDS ${CMAKE_SOURCE_DIR}/cmake/hipify.py ${SRCS}
  76. BYPRODUCTS ${HIP_SRCS}
  77. COMMENT "Running hipify on ${NAME} extension source files.")
  78. # Swap out original extension sources with hipified sources.
  79. list(APPEND HIP_SRCS ${CXX_SRCS})
  80. set(${OUT_SRCS} ${HIP_SRCS} PARENT_SCOPE)
  81. endfunction()
  82. #
  83. # Get additional GPU compiler flags from torch.
  84. #
  85. function (get_torch_gpu_compiler_flags OUT_GPU_FLAGS GPU_LANG)
  86. if (${GPU_LANG} STREQUAL "CUDA")
  87. #
  88. # Get common NVCC flags from torch.
  89. #
  90. run_python(GPU_FLAGS
  91. "from torch.utils.cpp_extension import COMMON_NVCC_FLAGS; print(';'.join(COMMON_NVCC_FLAGS))"
  92. "Failed to determine torch nvcc compiler flags")
  93. if (CUDA_VERSION VERSION_GREATER_EQUAL 11.8)
  94. list(APPEND GPU_FLAGS "-DENABLE_FP8")
  95. endif()
  96. if (CUDA_VERSION VERSION_GREATER_EQUAL 12.0)
  97. list(REMOVE_ITEM GPU_FLAGS
  98. "-D__CUDA_NO_HALF_OPERATORS__"
  99. "-D__CUDA_NO_HALF_CONVERSIONS__"
  100. "-D__CUDA_NO_BFLOAT16_CONVERSIONS__"
  101. "-D__CUDA_NO_HALF2_OPERATORS__")
  102. endif()
  103. elseif(${GPU_LANG} STREQUAL "HIP")
  104. #
  105. # Get common HIP/HIPCC flags from torch.
  106. #
  107. run_python(GPU_FLAGS
  108. "import torch.utils.cpp_extension as t; print(';'.join(t.COMMON_HIP_FLAGS + t.COMMON_HIPCC_FLAGS))"
  109. "Failed to determine torch nvcc compiler flags")
  110. list(APPEND GPU_FLAGS
  111. "-DUSE_ROCM"
  112. "-DENABLE_FP8"
  113. "-U__HIP_NO_HALF_CONVERSIONS__"
  114. "-U__HIP_NO_HALF_OPERATORS__"
  115. "-fno-gpu-rdc")
  116. endif()
  117. set(${OUT_GPU_FLAGS} ${GPU_FLAGS} PARENT_SCOPE)
  118. endfunction()
  119. # Macro for converting a `gencode` version number to a cmake version number.
  120. macro(string_to_ver OUT_VER IN_STR)
  121. string(REGEX REPLACE "\([0-9]+\)\([0-9]\)" "\\1.\\2" ${OUT_VER} ${IN_STR})
  122. endmacro()
  123. #
  124. # Override the GPU architectures detected by cmake/torch and filter them by
  125. # `GPU_SUPPORTED_ARCHES`. Sets the final set of architectures in
  126. # `GPU_ARCHES`.
  127. #
  128. # Note: this is defined as a macro since it updates `CMAKE_CUDA_FLAGS`.
  129. #
  130. macro(override_gpu_arches GPU_ARCHES GPU_LANG GPU_SUPPORTED_ARCHES)
  131. set(_GPU_SUPPORTED_ARCHES_LIST ${GPU_SUPPORTED_ARCHES} ${ARGN})
  132. message(STATUS "${GPU_LANG} supported arches: ${_GPU_SUPPORTED_ARCHES_LIST}")
  133. if (${GPU_LANG} STREQUAL "HIP")
  134. #
  135. # `GPU_ARCHES` controls the `--offload-arch` flags.
  136. #
  137. # If PYTORCH_ROCM_ARCH env variable exists, then we take it as a list,
  138. # if not, then we use CMAKE_HIP_ARCHITECTURES which was generated by calling
  139. # "rocm_agent_enumerator" in "enable_language(HIP)"
  140. # (in file Modules/CMakeDetermineHIPCompiler.cmake)
  141. #
  142. if(DEFINED ENV{PYTORCH_ROCM_ARCH})
  143. set(HIP_ARCHITECTURES $ENV{PYTORCH_ROCM_ARCH})
  144. else()
  145. set(HIP_ARCHITECTURES ${CMAKE_HIP_ARCHITECTURES})
  146. endif()
  147. #
  148. # Find the intersection of the supported + detected architectures to
  149. # set the module architecture flags.
  150. #
  151. set(${GPU_ARCHES})
  152. foreach (_ARCH ${HIP_ARCHITECTURES})
  153. if (_ARCH IN_LIST _GPU_SUPPORTED_ARCHES_LIST)
  154. list(APPEND ${GPU_ARCHES} ${_ARCH})
  155. endif()
  156. endforeach()
  157. if(NOT ${GPU_ARCHES})
  158. message(FATAL_ERROR
  159. "None of the detected ROCm architectures: ${HIP_ARCHITECTURES} is"
  160. " supported. Supported ROCm architectures are: ${_GPU_SUPPORTED_ARCHES_LIST}.")
  161. endif()
  162. elseif(${GPU_LANG} STREQUAL "CUDA")
  163. #
  164. # Setup/process CUDA arch flags.
  165. #
  166. # The torch cmake setup hardcodes the detected architecture flags in
  167. # `CMAKE_CUDA_FLAGS`. Since `CMAKE_CUDA_FLAGS` is a "global" variable, it
  168. # can't modified on a per-target basis.
  169. # So, all the `-gencode` flags need to be extracted and removed from
  170. # `CMAKE_CUDA_FLAGS` for processing so they can be passed by another method.
  171. # Since it's not possible to use `target_compiler_options` for adding target
  172. # specific `-gencode` arguments, the target's `CUDA_ARCHITECTURES` property
  173. # must be used instead. This requires repackaging the architecture flags
  174. # into a format that cmake expects for `CUDA_ARCHITECTURES`.
  175. #
  176. # This is a bit fragile in that it depends on torch using `-gencode` as opposed
  177. # to one of the other nvcc options to specify architectures.
  178. #
  179. # Note: torch uses the `TORCH_CUDA_ARCH_LIST` environment variable to override
  180. # detected architectures.
  181. #
  182. message(DEBUG "initial CMAKE_CUDA_FLAGS: ${CMAKE_CUDA_FLAGS}")
  183. # Extract all `-gencode` flags from `CMAKE_CUDA_FLAGS`
  184. string(REGEX MATCHALL "-gencode arch=[^ ]+" _CUDA_ARCH_FLAGS
  185. ${CMAKE_CUDA_FLAGS})
  186. # Remove all `-gencode` flags from `CMAKE_CUDA_FLAGS` since they will be modified
  187. # and passed back via the `CUDA_ARCHITECTURES` property.
  188. string(REGEX REPLACE "-gencode arch=[^ ]+ *" "" CMAKE_CUDA_FLAGS
  189. ${CMAKE_CUDA_FLAGS})
  190. # If this error is triggered, it might mean that torch has changed how it sets
  191. # up nvcc architecture code generation flags.
  192. if (NOT _CUDA_ARCH_FLAGS)
  193. message(FATAL_ERROR
  194. "Could not find any architecture related code generation flags in "
  195. "CMAKE_CUDA_FLAGS. (${CMAKE_CUDA_FLAGS})")
  196. endif()
  197. message(DEBUG "final CMAKE_CUDA_FLAGS: ${CMAKE_CUDA_FLAGS}")
  198. message(DEBUG "arch flags: ${_CUDA_ARCH_FLAGS}")
  199. # Initialize the architecture lists to empty.
  200. set(${GPU_ARCHES})
  201. # Process each `gencode` flag.
  202. foreach(_ARCH ${_CUDA_ARCH_FLAGS})
  203. # For each flag, extract the version number and whether it refers to PTX
  204. # or native code.
  205. # Note: if a regex matches then `CMAKE_MATCH_1` holds the binding
  206. # for that match.
  207. string(REGEX MATCH "arch=compute_\([0-9]+a?\)" _COMPUTE ${_ARCH})
  208. if (_COMPUTE)
  209. set(_COMPUTE ${CMAKE_MATCH_1})
  210. endif()
  211. string(REGEX MATCH "code=sm_\([0-9]+a?\)" _SM ${_ARCH})
  212. if (_SM)
  213. set(_SM ${CMAKE_MATCH_1})
  214. endif()
  215. string(REGEX MATCH "code=compute_\([0-9]+a?\)" _CODE ${_ARCH})
  216. if (_CODE)
  217. set(_CODE ${CMAKE_MATCH_1})
  218. endif()
  219. # Make sure the virtual architecture can be matched.
  220. if (NOT _COMPUTE)
  221. message(FATAL_ERROR
  222. "Could not determine virtual architecture from: ${_ARCH}.")
  223. endif()
  224. # One of sm_ or compute_ must exist.
  225. if ((NOT _SM) AND (NOT _CODE))
  226. message(FATAL_ERROR
  227. "Could not determine a codegen architecture from: ${_ARCH}.")
  228. endif()
  229. if (_SM)
  230. # -real suffix let CMake to only generate elf code for the kernels.
  231. # we want this, otherwise the added ptx (default) will increase binary size.
  232. set(_VIRT "-real")
  233. set(_CODE_ARCH ${_SM})
  234. else()
  235. # -virtual suffix let CMake to generate ptx code for the kernels.
  236. set(_VIRT "-virtual")
  237. set(_CODE_ARCH ${_CODE})
  238. endif()
  239. # Check if the current version is in the supported arch list.
  240. string_to_ver(_CODE_VER ${_CODE_ARCH})
  241. if (NOT _CODE_VER IN_LIST _GPU_SUPPORTED_ARCHES_LIST)
  242. message(STATUS "discarding unsupported CUDA arch ${_VER}.")
  243. continue()
  244. endif()
  245. # Add it to the arch list.
  246. list(APPEND ${GPU_ARCHES} "${_CODE_ARCH}${_VIRT}")
  247. endforeach()
  248. endif()
  249. message(STATUS "${GPU_LANG} target arches: ${${GPU_ARCHES}}")
  250. endmacro()
  251. #
  252. # Define a target named `GPU_MOD_NAME` for a single extension. The
  253. # arguments are:
  254. #
  255. # DESTINATION <dest> - Module destination directory.
  256. # LANGUAGE <lang> - The GPU language for this module, e.g CUDA, HIP,
  257. # etc.
  258. # SOURCES <sources> - List of source files relative to CMakeLists.txt
  259. # directory.
  260. #
  261. # Optional arguments:
  262. #
  263. # ARCHITECTURES <arches> - A list of target GPU architectures in cmake
  264. # format.
  265. # Refer `CMAKE_CUDA_ARCHITECTURES` documentation
  266. # and `CMAKE_HIP_ARCHITECTURES` for more info.
  267. # ARCHITECTURES will use cmake's defaults if
  268. # not provided.
  269. # COMPILE_FLAGS <flags> - Extra compiler flags passed to NVCC/hip.
  270. # INCLUDE_DIRECTORIES <dirs> - Extra include directories.
  271. # LIBRARIES <libraries> - Extra link libraries.
  272. # WITH_SOABI - Generate library with python SOABI suffix name.
  273. # USE_SABI <version> - Use python stable api <version>
  274. #
  275. # Note: optimization level/debug info is set via cmake build type.
  276. #
  277. function (define_gpu_extension_target GPU_MOD_NAME)
  278. cmake_parse_arguments(PARSE_ARGV 1
  279. GPU
  280. "WITH_SOABI"
  281. "DESTINATION;LANGUAGE;USE_SABI"
  282. "SOURCES;ARCHITECTURES;COMPILE_FLAGS;INCLUDE_DIRECTORIES;LIBRARIES")
  283. # Add hipify preprocessing step when building with HIP/ROCm.
  284. if (GPU_LANGUAGE STREQUAL "HIP")
  285. hipify_sources_target(GPU_SOURCES ${GPU_MOD_NAME} "${GPU_SOURCES}")
  286. endif()
  287. if (GPU_WITH_SOABI)
  288. set(GPU_WITH_SOABI WITH_SOABI)
  289. else()
  290. set(GPU_WITH_SOABI)
  291. endif()
  292. if (GPU_USE_SABI)
  293. Python_add_library(${GPU_MOD_NAME} MODULE USE_SABI ${GPU_USE_SABI} ${GPU_WITH_SOABI} "${GPU_SOURCES}")
  294. else()
  295. Python_add_library(${GPU_MOD_NAME} MODULE ${GPU_WITH_SOABI} "${GPU_SOURCES}")
  296. endif()
  297. if (GPU_LANGUAGE STREQUAL "HIP")
  298. # Make this target dependent on the hipify preprocessor step.
  299. add_dependencies(${GPU_MOD_NAME} hipify${GPU_MOD_NAME})
  300. endif()
  301. if (GPU_ARCHITECTURES)
  302. set_target_properties(${GPU_MOD_NAME} PROPERTIES
  303. ${GPU_LANGUAGE}_ARCHITECTURES "${GPU_ARCHITECTURES}")
  304. endif()
  305. set_property(TARGET ${GPU_MOD_NAME} PROPERTY CXX_STANDARD 20)
  306. target_compile_options(${GPU_MOD_NAME} PRIVATE
  307. $<$<COMPILE_LANGUAGE:${GPU_LANGUAGE}>:${GPU_COMPILE_FLAGS}>)
  308. target_compile_definitions(${GPU_MOD_NAME} PRIVATE
  309. "-DTORCH_EXTENSION_NAME=${GPU_MOD_NAME}")
  310. target_include_directories(${GPU_MOD_NAME} PRIVATE kernels
  311. ${GPU_INCLUDE_DIRECTORIES})
  312. target_link_libraries(${GPU_MOD_NAME} PRIVATE torch ${GPU_LIBRARIES})
  313. # Don't use `TORCH_LIBRARIES` for CUDA since it pulls in a bunch of
  314. # dependencies that are not necessary and may not be installed.
  315. if (GPU_LANGUAGE STREQUAL "CUDA")
  316. if ("${CUDA_CUDA_LIB}" STREQUAL "")
  317. set(CUDA_CUDA_LIB "${CUDA_CUDA_LIBRARY}")
  318. endif()
  319. target_link_libraries(${GPU_MOD_NAME} PRIVATE ${CUDA_CUDA_LIB}
  320. ${CUDA_LIBRARIES})
  321. else()
  322. target_link_libraries(${GPU_MOD_NAME} PRIVATE ${TORCH_LIBRARIES})
  323. endif()
  324. install(TARGETS ${GPU_MOD_NAME} LIBRARY DESTINATION ${GPU_DESTINATION})
  325. endfunction()