setup.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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_bwd_hdim64_fp16_sm90.cu",
  94. "flash_bwd_hdim96_fp16_sm90.cu",
  95. "flash_bwd_hdim128_fp16_sm90.cu",
  96. # "flash_bwd_hdim256_fp16_sm90.cu",
  97. "flash_bwd_hdim64_bf16_sm90.cu",
  98. "flash_bwd_hdim96_bf16_sm90.cu",
  99. "flash_bwd_hdim128_bf16_sm90.cu",
  100. "flash_fwd_hdim64_e4m3_sm90.cu",
  101. "flash_fwd_hdim128_e4m3_sm90.cu",
  102. "flash_fwd_hdim256_e4m3_sm90.cu",
  103. "flash_fwd_hdim64_fp16_gqa2_sm90.cu",
  104. "flash_fwd_hdim64_fp16_gqa4_sm90.cu",
  105. "flash_fwd_hdim64_fp16_gqa8_sm90.cu",
  106. "flash_fwd_hdim64_fp16_gqa16_sm90.cu",
  107. "flash_fwd_hdim64_fp16_gqa32_sm90.cu",
  108. "flash_fwd_hdim128_fp16_gqa2_sm90.cu",
  109. "flash_fwd_hdim128_fp16_gqa4_sm90.cu",
  110. "flash_fwd_hdim128_fp16_gqa8_sm90.cu",
  111. "flash_fwd_hdim128_fp16_gqa16_sm90.cu",
  112. "flash_fwd_hdim128_fp16_gqa32_sm90.cu",
  113. "flash_fwd_hdim256_fp16_gqa2_sm90.cu",
  114. "flash_fwd_hdim256_fp16_gqa4_sm90.cu",
  115. "flash_fwd_hdim256_fp16_gqa8_sm90.cu",
  116. "flash_fwd_hdim256_fp16_gqa16_sm90.cu",
  117. "flash_fwd_hdim256_fp16_gqa32_sm90.cu",
  118. "flash_fwd_hdim64_bf16_gqa2_sm90.cu",
  119. "flash_fwd_hdim64_bf16_gqa4_sm90.cu",
  120. "flash_fwd_hdim64_bf16_gqa8_sm90.cu",
  121. "flash_fwd_hdim64_bf16_gqa16_sm90.cu",
  122. "flash_fwd_hdim64_bf16_gqa32_sm90.cu",
  123. "flash_fwd_hdim128_bf16_gqa2_sm90.cu",
  124. "flash_fwd_hdim128_bf16_gqa4_sm90.cu",
  125. "flash_fwd_hdim128_bf16_gqa8_sm90.cu",
  126. "flash_fwd_hdim128_bf16_gqa16_sm90.cu",
  127. "flash_fwd_hdim128_bf16_gqa32_sm90.cu",
  128. "flash_fwd_hdim256_bf16_gqa2_sm90.cu",
  129. "flash_fwd_hdim256_bf16_gqa4_sm90.cu",
  130. "flash_fwd_hdim256_bf16_gqa8_sm90.cu",
  131. "flash_fwd_hdim256_bf16_gqa16_sm90.cu",
  132. "flash_fwd_hdim256_bf16_gqa32_sm90.cu",
  133. "flash_fwd_hdim64_e4m3_gqa2_sm90.cu",
  134. "flash_fwd_hdim64_e4m3_gqa4_sm90.cu",
  135. "flash_fwd_hdim64_e4m3_gqa8_sm90.cu",
  136. "flash_fwd_hdim64_e4m3_gqa16_sm90.cu",
  137. "flash_fwd_hdim64_e4m3_gqa32_sm90.cu",
  138. "flash_fwd_hdim128_e4m3_gqa2_sm90.cu",
  139. "flash_fwd_hdim128_e4m3_gqa4_sm90.cu",
  140. "flash_fwd_hdim128_e4m3_gqa8_sm90.cu",
  141. "flash_fwd_hdim128_e4m3_gqa16_sm90.cu",
  142. "flash_fwd_hdim128_e4m3_gqa32_sm90.cu",
  143. "flash_fwd_hdim256_e4m3_gqa2_sm90.cu",
  144. "flash_fwd_hdim256_e4m3_gqa4_sm90.cu",
  145. "flash_fwd_hdim256_e4m3_gqa8_sm90.cu",
  146. "flash_fwd_hdim256_e4m3_gqa16_sm90.cu",
  147. "flash_fwd_hdim256_e4m3_gqa32_sm90.cu",
  148. ]
  149. nvcc_flags = [
  150. "-O3",
  151. # "-O0",
  152. "-std=c++17",
  153. "-U__CUDA_NO_HALF_OPERATORS__",
  154. "-U__CUDA_NO_HALF_CONVERSIONS__",
  155. "-U__CUDA_NO_BFLOAT16_OPERATORS__",
  156. "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
  157. "-U__CUDA_NO_BFLOAT162_OPERATORS__",
  158. "-U__CUDA_NO_BFLOAT162_CONVERSIONS__",
  159. "--expt-relaxed-constexpr",
  160. "--expt-extended-lambda",
  161. "--use_fast_math",
  162. "--ptxas-options=-v", # printing out number of registers
  163. "--ptxas-options=--verbose,--register-usage-level=10,--warn-on-local-memory-usage", # printing out number of registers
  164. "-lineinfo",
  165. "-DCUTLASS_DEBUG_TRACE_LEVEL=0", # Can toggle for debugging
  166. "-DNDEBUG", # Important, otherwise performance is severely impacted
  167. ]
  168. if get_platform() == "win_amd64":
  169. nvcc_flags.extend(
  170. [
  171. "-D_USE_MATH_DEFINES", # for M_LN2
  172. "-Xcompiler=/Zc:__cplusplus", # sets __cplusplus correctly, CUTLASS_CONSTEXPR_IF_CXX17 needed for cutlass::gcd
  173. ]
  174. )
  175. include_dirs = [
  176. # Path(this_dir) / "fmha-pipeline",
  177. # repo_dir / "lib",
  178. # repo_dir / "include",
  179. cutlass_dir / "include",
  180. # cutlass_dir / "examples" / "common",
  181. # cutlass_dir / "tools" / "util" / "include",
  182. ]
  183. ext_modules.append(
  184. CUDAExtension(
  185. name="flashattn_hopper_cuda",
  186. sources=sources,
  187. extra_compile_args={
  188. "cxx": ["-O3", "-std=c++17"],
  189. # "cxx": ["-O0", "-std=c++17"],
  190. "nvcc": append_nvcc_threads(
  191. nvcc_flags + cc_flag
  192. ),
  193. },
  194. include_dirs=include_dirs,
  195. # Without this we get and error about cuTensorMapEncodeTiled not defined
  196. libraries=["cuda"]
  197. )
  198. )
  199. # ext_modules.append(
  200. # CUDAExtension(
  201. # name="flashattn_hopper_cuda_ws",
  202. # sources=sources,
  203. # extra_compile_args={
  204. # "cxx": ["-O3", "-std=c++17"],
  205. # "nvcc": append_nvcc_threads(
  206. # nvcc_flags + ["-DEXECMODE=1"] + cc_flag
  207. # ),
  208. # },
  209. # include_dirs=include_dirs,
  210. # # Without this we get and error about cuTensorMapEncodeTiled not defined
  211. # libraries=["cuda"]
  212. # )
  213. # )
  214. def get_package_version():
  215. with open(Path(this_dir) / "__init__.py", "r") as f:
  216. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  217. public_version = ast.literal_eval(version_match.group(1))
  218. local_version = os.environ.get("FLASHATTN_HOPPER_LOCAL_VERSION")
  219. if local_version:
  220. return f"{public_version}+{local_version}"
  221. else:
  222. return str(public_version)
  223. def get_wheel_url():
  224. # Determine the version numbers that will be used to determine the correct wheel
  225. # We're using the CUDA version used to build torch, not the one currently installed
  226. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  227. torch_cuda_version = parse(torch.version.cuda)
  228. torch_version_raw = parse(torch.__version__)
  229. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
  230. # to save CI time. Minor versions should be compatible.
  231. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
  232. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  233. platform_name = get_platform()
  234. package_version = get_package_version()
  235. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  236. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  237. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  238. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  239. # Determine wheel URL based on CUDA version, torch version, python version and OS
  240. wheel_filename = f"{PACKAGE_NAME}-{package_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  241. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{package_version}", wheel_name=wheel_filename)
  242. return wheel_url, wheel_filename
  243. class CachedWheelsCommand(_bdist_wheel):
  244. """
  245. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  246. find an existing wheel (which is currently the case for all installs). We use
  247. the environment parameters to detect whether there is already a pre-built version of a compatible
  248. wheel available and short-circuits the standard full build pipeline.
  249. """
  250. def run(self):
  251. if FORCE_BUILD:
  252. return super().run()
  253. wheel_url, wheel_filename = get_wheel_url()
  254. print("Guessing wheel URL: ", wheel_url)
  255. try:
  256. urllib.request.urlretrieve(wheel_url, wheel_filename)
  257. # Make the archive
  258. # Lifted from the root wheel processing command
  259. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  260. if not os.path.exists(self.dist_dir):
  261. os.makedirs(self.dist_dir)
  262. impl_tag, abi_tag, plat_tag = self.get_tag()
  263. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  264. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  265. print("Raw wheel path", wheel_path)
  266. shutil.move(wheel_filename, wheel_path)
  267. except urllib.error.HTTPError:
  268. print("Precompiled wheel not found. Building from source...")
  269. # If the wheel could not be downloaded, build from source
  270. super().run()
  271. setup(
  272. name=PACKAGE_NAME,
  273. version=get_package_version(),
  274. packages=find_packages(
  275. exclude=(
  276. "build",
  277. "csrc",
  278. "include",
  279. "tests",
  280. "dist",
  281. "docs",
  282. "benchmarks",
  283. )
  284. ),
  285. py_modules=["flash_attn_interface"],
  286. description="FlashAttention-3",
  287. long_description=long_description,
  288. long_description_content_type="text/markdown",
  289. classifiers=[
  290. "Programming Language :: Python :: 3",
  291. "License :: OSI Approved :: Apache Software License",
  292. "Operating System :: Unix",
  293. ],
  294. ext_modules=ext_modules,
  295. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": BuildExtension}
  296. if ext_modules
  297. else {
  298. "bdist_wheel": CachedWheelsCommand,
  299. },
  300. python_requires=">=3.8",
  301. install_requires=[
  302. "torch",
  303. "einops",
  304. "packaging",
  305. "ninja",
  306. ],
  307. )