setup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # Copyright (c) 2024, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
  2. import sys
  3. import warnings
  4. import os
  5. import re
  6. import shutil
  7. import ast
  8. from pathlib import Path
  9. from packaging.version import parse, Version
  10. import platform
  11. from setuptools import setup, find_packages
  12. import subprocess
  13. import urllib.request
  14. import urllib.error
  15. from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
  16. import torch
  17. from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
  18. # with open("../README.md", "r", encoding="utf-8") as fh:
  19. with open("../README.md", "r", encoding="utf-8") as fh:
  20. long_description = fh.read()
  21. # ninja build does not work unless include_dirs are abs path
  22. this_dir = os.path.dirname(os.path.abspath(__file__))
  23. PACKAGE_NAME = "flashattn-hopper"
  24. BASE_WHEEL_URL = "https://github.com/Dao-AILab/flash-attention/releases/download/{tag_name}/{wheel_name}"
  25. # FORCE_BUILD: Force a fresh build locally, instead of attempting to find prebuilt wheels
  26. # SKIP_CUDA_BUILD: Intended to allow CI to use a simple `python setup.py sdist` run to copy over raw files, without any cuda compilation
  27. FORCE_BUILD = os.getenv("FAHOPPER_FORCE_BUILD", "FALSE") == "TRUE"
  28. SKIP_CUDA_BUILD = os.getenv("FAHOPPER_SKIP_CUDA_BUILD", "FALSE") == "TRUE"
  29. # For CI, we want the option to build with C++11 ABI since the nvcr images use C++11 ABI
  30. FORCE_CXX11_ABI = os.getenv("FAHOPPER_FORCE_CXX11_ABI", "FALSE") == "TRUE"
  31. def get_platform():
  32. """
  33. Returns the platform name as used in wheel filenames.
  34. """
  35. if sys.platform.startswith("linux"):
  36. return "linux_x86_64"
  37. elif sys.platform == "darwin":
  38. mac_version = ".".join(platform.mac_ver()[0].split(".")[:2])
  39. return f"macosx_{mac_version}_x86_64"
  40. elif sys.platform == "win32":
  41. return "win_amd64"
  42. else:
  43. raise ValueError("Unsupported platform: {}".format(sys.platform))
  44. def get_cuda_bare_metal_version(cuda_dir):
  45. raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
  46. output = raw_output.split()
  47. release_idx = output.index("release") + 1
  48. bare_metal_version = parse(output[release_idx].split(",")[0])
  49. return raw_output, bare_metal_version
  50. def check_if_cuda_home_none(global_option: str) -> None:
  51. if CUDA_HOME is not None:
  52. return
  53. # warn instead of error because user could be downloading prebuilt wheels, so nvcc won't be necessary
  54. # in that case.
  55. warnings.warn(
  56. f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
  57. "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
  58. "only images whose names contain 'devel' will provide nvcc."
  59. )
  60. def append_nvcc_threads(nvcc_extra_args):
  61. return nvcc_extra_args + ["--threads", "4"]
  62. cmdclass = {}
  63. ext_modules = []
  64. # We want this even if SKIP_CUDA_BUILD because when we run python setup.py sdist we want the .hpp
  65. # files included in the source distribution, in case the user compiles from source.
  66. subprocess.run(["git", "submodule", "update", "--init", "../csrc/cutlass"])
  67. if not SKIP_CUDA_BUILD:
  68. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  69. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  70. TORCH_MINOR = int(torch.__version__.split(".")[1])
  71. check_if_cuda_home_none("--fahopper")
  72. cc_flag = []
  73. _, bare_metal_version = get_cuda_bare_metal_version(CUDA_HOME)
  74. if bare_metal_version < Version("12.3"):
  75. raise RuntimeError("FA Hopper is only supported on CUDA 12.3 and above")
  76. cc_flag.append("-gencode")
  77. cc_flag.append("arch=compute_90a,code=sm_90a")
  78. # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
  79. # torch._C._GLIBCXX_USE_CXX11_ABI
  80. # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
  81. if FORCE_CXX11_ABI:
  82. torch._C._GLIBCXX_USE_CXX11_ABI = True
  83. repo_dir = Path(this_dir).parent
  84. cutlass_dir = repo_dir / "csrc" / "cutlass"
  85. sources = [
  86. "flash_api.cpp",
  87. "flash_fwd_hdim64_fp16_sm90.cu",
  88. "flash_fwd_hdim64_bf16_sm90.cu",
  89. "flash_fwd_hdim128_fp16_sm90.cu",
  90. "flash_fwd_hdim128_bf16_sm90.cu",
  91. "flash_fwd_hdim256_fp16_sm90.cu",
  92. "flash_fwd_hdim256_bf16_sm90.cu",
  93. "flash_fwd_hdim64_fp8_sm90.cu",
  94. "flash_fwd_hdim128_fp8_sm90.cu",
  95. "flash_fwd_hdim256_fp8_sm90.cu",
  96. "flash_bwd_hdim64_fp16_sm90.cu",
  97. "flash_bwd_hdim128_fp16_sm90.cu",
  98. "flash_bwd_hdim256_fp16_sm90.cu",
  99. # "flash_fwd_hdim128_e4m3_sm90.cu",
  100. ]
  101. nvcc_flags = [
  102. "-O3",
  103. # "-O0",
  104. "-std=c++17",
  105. "-U__CUDA_NO_HALF_OPERATORS__",
  106. "-U__CUDA_NO_HALF_CONVERSIONS__",
  107. "-U__CUDA_NO_BFLOAT16_OPERATORS__",
  108. "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
  109. "-U__CUDA_NO_BFLOAT162_OPERATORS__",
  110. "-U__CUDA_NO_BFLOAT162_CONVERSIONS__",
  111. "--expt-relaxed-constexpr",
  112. "--expt-extended-lambda",
  113. "--use_fast_math",
  114. # "--ptxas-options=-v", # printing out number of registers
  115. "--ptxas-options=--verbose,--register-usage-level=10,--warn-on-local-memory-usage", # printing out number of registers
  116. "-lineinfo",
  117. "-DCUTLASS_DEBUG_TRACE_LEVEL=0", # Can toggle for debugging
  118. "-DNDEBUG", # Important, otherwise performance is severely impacted
  119. "-DQBLKSIZE=128",
  120. "-DKBLKSIZE=128",
  121. "-DCTA256",
  122. "-DDQINRMEM",
  123. ]
  124. include_dirs = [
  125. # Path(this_dir) / "fmha-pipeline",
  126. # repo_dir / "lib",
  127. # repo_dir / "include",
  128. cutlass_dir / "include",
  129. # cutlass_dir / "examples" / "common",
  130. # cutlass_dir / "tools" / "util" / "include",
  131. ]
  132. ext_modules.append(
  133. CUDAExtension(
  134. name="flashattn_hopper_cuda",
  135. sources=sources,
  136. extra_compile_args={
  137. "cxx": ["-O3", "-std=c++17"],
  138. # "cxx": ["-O0", "-std=c++17"],
  139. "nvcc": append_nvcc_threads(
  140. nvcc_flags + ["-DEXECMODE=0"] + cc_flag
  141. ),
  142. },
  143. include_dirs=include_dirs,
  144. # Without this we get and error about cuTensorMapEncodeTiled not defined
  145. libraries=["cuda"]
  146. )
  147. )
  148. # ext_modules.append(
  149. # CUDAExtension(
  150. # name="flashattn_hopper_cuda_ws",
  151. # sources=sources,
  152. # extra_compile_args={
  153. # "cxx": ["-O3", "-std=c++17"],
  154. # "nvcc": append_nvcc_threads(
  155. # nvcc_flags + ["-DEXECMODE=1"] + cc_flag
  156. # ),
  157. # },
  158. # include_dirs=include_dirs,
  159. # # Without this we get and error about cuTensorMapEncodeTiled not defined
  160. # libraries=["cuda"]
  161. # )
  162. # )
  163. def get_package_version():
  164. with open(Path(this_dir) / "__init__.py", "r") as f:
  165. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  166. public_version = ast.literal_eval(version_match.group(1))
  167. local_version = os.environ.get("FLASHATTN_HOPPER_LOCAL_VERSION")
  168. if local_version:
  169. return f"{public_version}+{local_version}"
  170. else:
  171. return str(public_version)
  172. def get_wheel_url():
  173. # Determine the version numbers that will be used to determine the correct wheel
  174. # We're using the CUDA version used to build torch, not the one currently installed
  175. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  176. torch_cuda_version = parse(torch.version.cuda)
  177. torch_version_raw = parse(torch.__version__)
  178. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
  179. # to save CI time. Minor versions should be compatible.
  180. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
  181. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  182. platform_name = get_platform()
  183. package_version = get_package_version()
  184. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  185. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  186. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  187. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  188. # Determine wheel URL based on CUDA version, torch version, python version and OS
  189. wheel_filename = f"{PACKAGE_NAME}-{package_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  190. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{package_version}", wheel_name=wheel_filename)
  191. return wheel_url, wheel_filename
  192. class CachedWheelsCommand(_bdist_wheel):
  193. """
  194. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  195. find an existing wheel (which is currently the case for all installs). We use
  196. the environment parameters to detect whether there is already a pre-built version of a compatible
  197. wheel available and short-circuits the standard full build pipeline.
  198. """
  199. def run(self):
  200. if FORCE_BUILD:
  201. return super().run()
  202. wheel_url, wheel_filename = get_wheel_url()
  203. print("Guessing wheel URL: ", wheel_url)
  204. try:
  205. urllib.request.urlretrieve(wheel_url, wheel_filename)
  206. # Make the archive
  207. # Lifted from the root wheel processing command
  208. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  209. if not os.path.exists(self.dist_dir):
  210. os.makedirs(self.dist_dir)
  211. impl_tag, abi_tag, plat_tag = self.get_tag()
  212. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  213. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  214. print("Raw wheel path", wheel_path)
  215. shutil.move(wheel_filename, wheel_path)
  216. except urllib.error.HTTPError:
  217. print("Precompiled wheel not found. Building from source...")
  218. # If the wheel could not be downloaded, build from source
  219. super().run()
  220. setup(
  221. name=PACKAGE_NAME,
  222. version=get_package_version(),
  223. packages=find_packages(
  224. exclude=(
  225. "build",
  226. "csrc",
  227. "include",
  228. "tests",
  229. "dist",
  230. "docs",
  231. "benchmarks",
  232. )
  233. ),
  234. py_modules=["flash_attn_interface"],
  235. description="FlashAttention-3",
  236. long_description=long_description,
  237. long_description_content_type="text/markdown",
  238. classifiers=[
  239. "Programming Language :: Python :: 3",
  240. "License :: OSI Approved :: Apache Software License",
  241. "Operating System :: Unix",
  242. ],
  243. ext_modules=ext_modules,
  244. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": BuildExtension}
  245. if ext_modules
  246. else {
  247. "bdist_wheel": CachedWheelsCommand,
  248. },
  249. python_requires=">=3.8",
  250. install_requires=[
  251. "torch",
  252. "einops",
  253. "packaging",
  254. "ninja",
  255. ],
  256. )