1
0

setup.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. # Copyright (c) 2023, Tri Dao.
  2. import sys
  3. import warnings
  4. import os
  5. import re
  6. import ast
  7. import glob
  8. import shutil
  9. from pathlib import Path
  10. from packaging.version import parse, Version
  11. import platform
  12. from setuptools import setup, find_packages
  13. import subprocess
  14. import urllib.request
  15. import urllib.error
  16. from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
  17. import torch
  18. from torch.utils.cpp_extension import (
  19. BuildExtension,
  20. CppExtension,
  21. CUDAExtension,
  22. CUDA_HOME,
  23. ROCM_HOME,
  24. IS_HIP_EXTENSION,
  25. )
  26. with open("README.md", "r", encoding="utf-8") as fh:
  27. long_description = fh.read()
  28. # ninja build does not work unless include_dirs are abs path
  29. this_dir = os.path.dirname(os.path.abspath(__file__))
  30. BUILD_TARGET = os.environ.get("BUILD_TARGET", "auto")
  31. if BUILD_TARGET == "auto":
  32. if IS_HIP_EXTENSION:
  33. IS_ROCM = True
  34. else:
  35. IS_ROCM = False
  36. else:
  37. if BUILD_TARGET == "cuda":
  38. IS_ROCM = False
  39. elif BUILD_TARGET == "rocm":
  40. IS_ROCM = True
  41. PACKAGE_NAME = "flash_attn"
  42. BASE_WHEEL_URL = (
  43. "https://github.com/Dao-AILab/flash-attention/releases/download/{tag_name}/{wheel_name}"
  44. )
  45. # FORCE_BUILD: Force a fresh build locally, instead of attempting to find prebuilt wheels
  46. # 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
  47. FORCE_BUILD = os.getenv("FLASH_ATTENTION_FORCE_BUILD", "FALSE") == "TRUE"
  48. SKIP_CUDA_BUILD = os.getenv("FLASH_ATTENTION_SKIP_CUDA_BUILD", "FALSE") == "TRUE"
  49. # For CI, we want the option to build with C++11 ABI since the nvcr images use C++11 ABI
  50. FORCE_CXX11_ABI = os.getenv("FLASH_ATTENTION_FORCE_CXX11_ABI", "FALSE") == "TRUE"
  51. def get_platform():
  52. """
  53. Returns the platform name as used in wheel filenames.
  54. """
  55. if sys.platform.startswith("linux"):
  56. return f'linux_{platform.uname().machine}'
  57. elif sys.platform == "darwin":
  58. mac_version = ".".join(platform.mac_ver()[0].split(".")[:2])
  59. return f"macosx_{mac_version}_x86_64"
  60. elif sys.platform == "win32":
  61. return "win_amd64"
  62. else:
  63. raise ValueError("Unsupported platform: {}".format(sys.platform))
  64. def get_cuda_bare_metal_version(cuda_dir):
  65. raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
  66. output = raw_output.split()
  67. release_idx = output.index("release") + 1
  68. bare_metal_version = parse(output[release_idx].split(",")[0])
  69. return raw_output, bare_metal_version
  70. def check_if_cuda_home_none(global_option: str) -> None:
  71. if CUDA_HOME is not None:
  72. return
  73. # warn instead of error because user could be downloading prebuilt wheels, so nvcc won't be necessary
  74. # in that case.
  75. warnings.warn(
  76. f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
  77. "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
  78. "only images whose names contain 'devel' will provide nvcc."
  79. )
  80. def check_if_rocm_home_none(global_option: str) -> None:
  81. if ROCM_HOME is not None:
  82. return
  83. # warn instead of error because user could be downloading prebuilt wheels, so hipcc won't be necessary
  84. # in that case.
  85. warnings.warn(
  86. f"{global_option} was requested, but hipcc was not found."
  87. )
  88. def append_nvcc_threads(nvcc_extra_args):
  89. nvcc_threads = os.getenv("NVCC_THREADS") or "4"
  90. return nvcc_extra_args + ["--threads", nvcc_threads]
  91. def rename_cpp_to_cu(cpp_files):
  92. for entry in cpp_files:
  93. shutil.copy(entry, os.path.splitext(entry)[0] + ".cu")
  94. def validate_and_update_archs(archs):
  95. # List of allowed architectures
  96. allowed_archs = ["native", "gfx90a", "gfx940", "gfx941", "gfx942"]
  97. # Validate if each element in archs is in allowed_archs
  98. assert all(
  99. arch in allowed_archs for arch in archs
  100. ), f"One of GPU archs of {archs} is invalid or not supported by Flash-Attention"
  101. cmdclass = {}
  102. ext_modules = []
  103. # We want this even if SKIP_CUDA_BUILD because when we run python setup.py sdist we want the .hpp
  104. # files included in the source distribution, in case the user compiles from source.
  105. if IS_ROCM:
  106. subprocess.run(["git", "submodule", "update", "--init", "csrc/composable_kernel"])
  107. else:
  108. subprocess.run(["git", "submodule", "update", "--init", "csrc/cutlass"])
  109. if not SKIP_CUDA_BUILD and not IS_ROCM:
  110. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  111. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  112. TORCH_MINOR = int(torch.__version__.split(".")[1])
  113. # Check, if ATen/CUDAGeneratorImpl.h is found, otherwise use ATen/cuda/CUDAGeneratorImpl.h
  114. # See https://github.com/pytorch/pytorch/pull/70650
  115. generator_flag = []
  116. torch_dir = torch.__path__[0]
  117. if os.path.exists(os.path.join(torch_dir, "include", "ATen", "CUDAGeneratorImpl.h")):
  118. generator_flag = ["-DOLD_GENERATOR_PATH"]
  119. check_if_cuda_home_none("flash_attn")
  120. # Check, if CUDA11 is installed for compute capability 8.0
  121. cc_flag = []
  122. if CUDA_HOME is not None:
  123. _, bare_metal_version = get_cuda_bare_metal_version(CUDA_HOME)
  124. if bare_metal_version < Version("11.6"):
  125. raise RuntimeError(
  126. "FlashAttention is only supported on CUDA 11.6 and above. "
  127. "Note: make sure nvcc has a supported version by running nvcc -V."
  128. )
  129. # cc_flag.append("-gencode")
  130. # cc_flag.append("arch=compute_75,code=sm_75")
  131. cc_flag.append("-gencode")
  132. cc_flag.append("arch=compute_80,code=sm_80")
  133. if CUDA_HOME is not None:
  134. if bare_metal_version >= Version("11.8"):
  135. cc_flag.append("-gencode")
  136. cc_flag.append("arch=compute_90,code=sm_90")
  137. # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
  138. # torch._C._GLIBCXX_USE_CXX11_ABI
  139. # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
  140. if FORCE_CXX11_ABI:
  141. torch._C._GLIBCXX_USE_CXX11_ABI = True
  142. ext_modules.append(
  143. CUDAExtension(
  144. name="flash_attn_2_cuda",
  145. sources=[
  146. "csrc/flash_attn/flash_api.cpp",
  147. "csrc/flash_attn/src/flash_fwd_hdim32_fp16_sm80.cu",
  148. "csrc/flash_attn/src/flash_fwd_hdim32_bf16_sm80.cu",
  149. "csrc/flash_attn/src/flash_fwd_hdim64_fp16_sm80.cu",
  150. "csrc/flash_attn/src/flash_fwd_hdim64_bf16_sm80.cu",
  151. "csrc/flash_attn/src/flash_fwd_hdim96_fp16_sm80.cu",
  152. "csrc/flash_attn/src/flash_fwd_hdim96_bf16_sm80.cu",
  153. "csrc/flash_attn/src/flash_fwd_hdim128_fp16_sm80.cu",
  154. "csrc/flash_attn/src/flash_fwd_hdim128_bf16_sm80.cu",
  155. "csrc/flash_attn/src/flash_fwd_hdim160_fp16_sm80.cu",
  156. "csrc/flash_attn/src/flash_fwd_hdim160_bf16_sm80.cu",
  157. "csrc/flash_attn/src/flash_fwd_hdim192_fp16_sm80.cu",
  158. "csrc/flash_attn/src/flash_fwd_hdim192_bf16_sm80.cu",
  159. "csrc/flash_attn/src/flash_fwd_hdim256_fp16_sm80.cu",
  160. "csrc/flash_attn/src/flash_fwd_hdim256_bf16_sm80.cu",
  161. "csrc/flash_attn/src/flash_fwd_hdim32_fp16_causal_sm80.cu",
  162. "csrc/flash_attn/src/flash_fwd_hdim32_bf16_causal_sm80.cu",
  163. "csrc/flash_attn/src/flash_fwd_hdim64_fp16_causal_sm80.cu",
  164. "csrc/flash_attn/src/flash_fwd_hdim64_bf16_causal_sm80.cu",
  165. "csrc/flash_attn/src/flash_fwd_hdim96_fp16_causal_sm80.cu",
  166. "csrc/flash_attn/src/flash_fwd_hdim96_bf16_causal_sm80.cu",
  167. "csrc/flash_attn/src/flash_fwd_hdim128_fp16_causal_sm80.cu",
  168. "csrc/flash_attn/src/flash_fwd_hdim128_bf16_causal_sm80.cu",
  169. "csrc/flash_attn/src/flash_fwd_hdim160_fp16_causal_sm80.cu",
  170. "csrc/flash_attn/src/flash_fwd_hdim160_bf16_causal_sm80.cu",
  171. "csrc/flash_attn/src/flash_fwd_hdim192_fp16_causal_sm80.cu",
  172. "csrc/flash_attn/src/flash_fwd_hdim192_bf16_causal_sm80.cu",
  173. "csrc/flash_attn/src/flash_fwd_hdim256_fp16_causal_sm80.cu",
  174. "csrc/flash_attn/src/flash_fwd_hdim256_bf16_causal_sm80.cu",
  175. "csrc/flash_attn/src/flash_bwd_hdim32_fp16_sm80.cu",
  176. "csrc/flash_attn/src/flash_bwd_hdim32_bf16_sm80.cu",
  177. "csrc/flash_attn/src/flash_bwd_hdim64_fp16_sm80.cu",
  178. "csrc/flash_attn/src/flash_bwd_hdim64_bf16_sm80.cu",
  179. "csrc/flash_attn/src/flash_bwd_hdim96_fp16_sm80.cu",
  180. "csrc/flash_attn/src/flash_bwd_hdim96_bf16_sm80.cu",
  181. "csrc/flash_attn/src/flash_bwd_hdim128_fp16_sm80.cu",
  182. "csrc/flash_attn/src/flash_bwd_hdim128_bf16_sm80.cu",
  183. "csrc/flash_attn/src/flash_bwd_hdim160_fp16_sm80.cu",
  184. "csrc/flash_attn/src/flash_bwd_hdim160_bf16_sm80.cu",
  185. "csrc/flash_attn/src/flash_bwd_hdim192_fp16_sm80.cu",
  186. "csrc/flash_attn/src/flash_bwd_hdim192_bf16_sm80.cu",
  187. "csrc/flash_attn/src/flash_bwd_hdim256_fp16_sm80.cu",
  188. "csrc/flash_attn/src/flash_bwd_hdim256_bf16_sm80.cu",
  189. "csrc/flash_attn/src/flash_bwd_hdim32_fp16_causal_sm80.cu",
  190. "csrc/flash_attn/src/flash_bwd_hdim32_bf16_causal_sm80.cu",
  191. "csrc/flash_attn/src/flash_bwd_hdim64_fp16_causal_sm80.cu",
  192. "csrc/flash_attn/src/flash_bwd_hdim64_bf16_causal_sm80.cu",
  193. "csrc/flash_attn/src/flash_bwd_hdim96_fp16_causal_sm80.cu",
  194. "csrc/flash_attn/src/flash_bwd_hdim96_bf16_causal_sm80.cu",
  195. "csrc/flash_attn/src/flash_bwd_hdim128_fp16_causal_sm80.cu",
  196. "csrc/flash_attn/src/flash_bwd_hdim128_bf16_causal_sm80.cu",
  197. "csrc/flash_attn/src/flash_bwd_hdim160_fp16_causal_sm80.cu",
  198. "csrc/flash_attn/src/flash_bwd_hdim160_bf16_causal_sm80.cu",
  199. "csrc/flash_attn/src/flash_bwd_hdim192_fp16_causal_sm80.cu",
  200. "csrc/flash_attn/src/flash_bwd_hdim192_bf16_causal_sm80.cu",
  201. "csrc/flash_attn/src/flash_bwd_hdim256_fp16_causal_sm80.cu",
  202. "csrc/flash_attn/src/flash_bwd_hdim256_bf16_causal_sm80.cu",
  203. "csrc/flash_attn/src/flash_fwd_split_hdim32_fp16_sm80.cu",
  204. "csrc/flash_attn/src/flash_fwd_split_hdim32_bf16_sm80.cu",
  205. "csrc/flash_attn/src/flash_fwd_split_hdim64_fp16_sm80.cu",
  206. "csrc/flash_attn/src/flash_fwd_split_hdim64_bf16_sm80.cu",
  207. "csrc/flash_attn/src/flash_fwd_split_hdim96_fp16_sm80.cu",
  208. "csrc/flash_attn/src/flash_fwd_split_hdim96_bf16_sm80.cu",
  209. "csrc/flash_attn/src/flash_fwd_split_hdim128_fp16_sm80.cu",
  210. "csrc/flash_attn/src/flash_fwd_split_hdim128_bf16_sm80.cu",
  211. "csrc/flash_attn/src/flash_fwd_split_hdim160_fp16_sm80.cu",
  212. "csrc/flash_attn/src/flash_fwd_split_hdim160_bf16_sm80.cu",
  213. "csrc/flash_attn/src/flash_fwd_split_hdim192_fp16_sm80.cu",
  214. "csrc/flash_attn/src/flash_fwd_split_hdim192_bf16_sm80.cu",
  215. "csrc/flash_attn/src/flash_fwd_split_hdim256_fp16_sm80.cu",
  216. "csrc/flash_attn/src/flash_fwd_split_hdim256_bf16_sm80.cu",
  217. "csrc/flash_attn/src/flash_fwd_split_hdim32_fp16_causal_sm80.cu",
  218. "csrc/flash_attn/src/flash_fwd_split_hdim32_bf16_causal_sm80.cu",
  219. "csrc/flash_attn/src/flash_fwd_split_hdim64_fp16_causal_sm80.cu",
  220. "csrc/flash_attn/src/flash_fwd_split_hdim64_bf16_causal_sm80.cu",
  221. "csrc/flash_attn/src/flash_fwd_split_hdim96_fp16_causal_sm80.cu",
  222. "csrc/flash_attn/src/flash_fwd_split_hdim96_bf16_causal_sm80.cu",
  223. "csrc/flash_attn/src/flash_fwd_split_hdim128_fp16_causal_sm80.cu",
  224. "csrc/flash_attn/src/flash_fwd_split_hdim128_bf16_causal_sm80.cu",
  225. "csrc/flash_attn/src/flash_fwd_split_hdim160_fp16_causal_sm80.cu",
  226. "csrc/flash_attn/src/flash_fwd_split_hdim160_bf16_causal_sm80.cu",
  227. "csrc/flash_attn/src/flash_fwd_split_hdim192_fp16_causal_sm80.cu",
  228. "csrc/flash_attn/src/flash_fwd_split_hdim192_bf16_causal_sm80.cu",
  229. "csrc/flash_attn/src/flash_fwd_split_hdim256_fp16_causal_sm80.cu",
  230. "csrc/flash_attn/src/flash_fwd_split_hdim256_bf16_causal_sm80.cu",
  231. ],
  232. extra_compile_args={
  233. "cxx": ["-O3", "-std=c++17"] + generator_flag,
  234. "nvcc": append_nvcc_threads(
  235. [
  236. "-O3",
  237. "-std=c++17",
  238. "-U__CUDA_NO_HALF_OPERATORS__",
  239. "-U__CUDA_NO_HALF_CONVERSIONS__",
  240. "-U__CUDA_NO_HALF2_OPERATORS__",
  241. "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
  242. "--expt-relaxed-constexpr",
  243. "--expt-extended-lambda",
  244. "--use_fast_math",
  245. # "--ptxas-options=-v",
  246. # "--ptxas-options=-O2",
  247. # "-lineinfo",
  248. # "-DFLASHATTENTION_DISABLE_BACKWARD",
  249. # "-DFLASHATTENTION_DISABLE_DROPOUT",
  250. # "-DFLASHATTENTION_DISABLE_ALIBI",
  251. # "-DFLASHATTENTION_DISABLE_SOFTCAP",
  252. # "-DFLASHATTENTION_DISABLE_UNEVEN_K",
  253. # "-DFLASHATTENTION_DISABLE_LOCAL",
  254. ]
  255. + generator_flag
  256. + cc_flag
  257. ),
  258. },
  259. include_dirs=[
  260. Path(this_dir) / "csrc" / "flash_attn",
  261. Path(this_dir) / "csrc" / "flash_attn" / "src",
  262. Path(this_dir) / "csrc" / "cutlass" / "include",
  263. ],
  264. )
  265. )
  266. elif not SKIP_CUDA_BUILD and IS_ROCM:
  267. ck_dir = "csrc/composable_kernel"
  268. #use codegen get code dispatch
  269. if not os.path.exists("./build"):
  270. os.makedirs("build")
  271. os.system(f"{sys.executable} {ck_dir}/example/ck_tile/01_fmha/generate.py -d fwd --output_dir build --receipt 2")
  272. os.system(f"{sys.executable} {ck_dir}/example/ck_tile/01_fmha/generate.py -d bwd --output_dir build --receipt 2")
  273. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  274. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  275. TORCH_MINOR = int(torch.__version__.split(".")[1])
  276. # Check, if ATen/CUDAGeneratorImpl.h is found, otherwise use ATen/cuda/CUDAGeneratorImpl.h
  277. # See https://github.com/pytorch/pytorch/pull/70650
  278. generator_flag = []
  279. torch_dir = torch.__path__[0]
  280. if os.path.exists(os.path.join(torch_dir, "include", "ATen", "CUDAGeneratorImpl.h")):
  281. generator_flag = ["-DOLD_GENERATOR_PATH"]
  282. check_if_rocm_home_none("flash_attn")
  283. cc_flag = []
  284. archs = os.getenv("GPU_ARCHS", "native").split(";")
  285. validate_and_update_archs(archs)
  286. cc_flag = [f"--offload-arch={arch}" for arch in archs]
  287. # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
  288. # torch._C._GLIBCXX_USE_CXX11_ABI
  289. # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
  290. if FORCE_CXX11_ABI:
  291. torch._C._GLIBCXX_USE_CXX11_ABI = True
  292. sources = ["csrc/flash_attn_ck/flash_api.cpp",
  293. "csrc/flash_attn_ck/mha_bwd.cpp",
  294. "csrc/flash_attn_ck/mha_fwd.cpp",
  295. "csrc/flash_attn_ck/mha_varlen_bwd.cpp",
  296. "csrc/flash_attn_ck/mha_varlen_fwd.cpp"] + glob.glob(
  297. f"build/fmha_*wd*.cpp"
  298. )
  299. rename_cpp_to_cu(sources)
  300. renamed_sources = ["csrc/flash_attn_ck/flash_api.cu",
  301. "csrc/flash_attn_ck/mha_bwd.cu",
  302. "csrc/flash_attn_ck/mha_fwd.cu",
  303. "csrc/flash_attn_ck/mha_varlen_bwd.cu",
  304. "csrc/flash_attn_ck/mha_varlen_fwd.cu"] + glob.glob(f"build/fmha_*wd*.cu")
  305. extra_compile_args = {
  306. "cxx": ["-O3", "-std=c++17"] + generator_flag,
  307. "nvcc":
  308. [
  309. "-O3","-std=c++17",
  310. "-mllvm", "-enable-post-misched=0",
  311. "-DCK_TILE_FMHA_FWD_FAST_EXP2=1",
  312. "-fgpu-flush-denormals-to-zero",
  313. "-DCK_ENABLE_BF16",
  314. "-DCK_ENABLE_BF8",
  315. "-DCK_ENABLE_FP16",
  316. "-DCK_ENABLE_FP32",
  317. "-DCK_ENABLE_FP64",
  318. "-DCK_ENABLE_FP8",
  319. "-DCK_ENABLE_INT8",
  320. "-DCK_USE_XDL",
  321. "-DUSE_PROF_API=1",
  322. "-D__HIP_PLATFORM_HCC__=1",
  323. # "-DFLASHATTENTION_DISABLE_BACKWARD",
  324. ]
  325. + generator_flag
  326. + cc_flag
  327. ,
  328. }
  329. include_dirs = [
  330. Path(this_dir) / "csrc" / "composable_kernel" / "include",
  331. Path(this_dir) / "csrc" / "composable_kernel" / "library" / "include",
  332. Path(this_dir) / "csrc" / "composable_kernel" / "example" / "ck_tile" / "01_fmha",
  333. ]
  334. ext_modules.append(
  335. CUDAExtension(
  336. name="flash_attn_2_cuda",
  337. sources=renamed_sources,
  338. extra_compile_args=extra_compile_args,
  339. include_dirs=include_dirs,
  340. )
  341. )
  342. def get_package_version():
  343. with open(Path(this_dir) / "flash_attn" / "__init__.py", "r") as f:
  344. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  345. public_version = ast.literal_eval(version_match.group(1))
  346. local_version = os.environ.get("FLASH_ATTN_LOCAL_VERSION")
  347. if local_version:
  348. return f"{public_version}+{local_version}"
  349. else:
  350. return str(public_version)
  351. def get_wheel_url():
  352. torch_version_raw = parse(torch.__version__)
  353. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  354. platform_name = get_platform()
  355. flash_version = get_package_version()
  356. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  357. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  358. if IS_ROCM:
  359. torch_hip_version = parse(torch.version.hip.split()[-1].rstrip('-').replace('-', '+'))
  360. hip_version = f"{torch_hip_version.major}{torch_hip_version.minor}"
  361. wheel_filename = f"{PACKAGE_NAME}-{flash_version}+rocm{hip_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  362. else:
  363. # Determine the version numbers that will be used to determine the correct wheel
  364. # We're using the CUDA version used to build torch, not the one currently installed
  365. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  366. torch_cuda_version = parse(torch.version.cuda)
  367. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.3
  368. # to save CI time. Minor versions should be compatible.
  369. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.3")
  370. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  371. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  372. # Determine wheel URL based on CUDA version, torch version, python version and OS
  373. wheel_filename = f"{PACKAGE_NAME}-{flash_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  374. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{flash_version}", wheel_name=wheel_filename)
  375. return wheel_url, wheel_filename
  376. class CachedWheelsCommand(_bdist_wheel):
  377. """
  378. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  379. find an existing wheel (which is currently the case for all flash attention installs). We use
  380. the environment parameters to detect whether there is already a pre-built version of a compatible
  381. wheel available and short-circuits the standard full build pipeline.
  382. """
  383. def run(self):
  384. if FORCE_BUILD:
  385. return super().run()
  386. wheel_url, wheel_filename = get_wheel_url()
  387. print("Guessing wheel URL: ", wheel_url)
  388. try:
  389. urllib.request.urlretrieve(wheel_url, wheel_filename)
  390. # Make the archive
  391. # Lifted from the root wheel processing command
  392. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  393. if not os.path.exists(self.dist_dir):
  394. os.makedirs(self.dist_dir)
  395. impl_tag, abi_tag, plat_tag = self.get_tag()
  396. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  397. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  398. print("Raw wheel path", wheel_path)
  399. os.rename(wheel_filename, wheel_path)
  400. except (urllib.error.HTTPError, urllib.error.URLError):
  401. print("Precompiled wheel not found. Building from source...")
  402. # If the wheel could not be downloaded, build from source
  403. super().run()
  404. class NinjaBuildExtension(BuildExtension):
  405. def __init__(self, *args, **kwargs) -> None:
  406. # do not override env MAX_JOBS if already exists
  407. if not os.environ.get("MAX_JOBS"):
  408. import psutil
  409. # calculate the maximum allowed NUM_JOBS based on cores
  410. max_num_jobs_cores = max(1, os.cpu_count() // 2)
  411. # calculate the maximum allowed NUM_JOBS based on free memory
  412. free_memory_gb = psutil.virtual_memory().available / (1024 ** 3) # free memory in GB
  413. max_num_jobs_memory = int(free_memory_gb / 9) # each JOB peak memory cost is ~8-9GB when threads = 4
  414. # pick lower value of jobs based on cores vs memory metric to minimize oom and swap usage during compilation
  415. max_jobs = max(1, min(max_num_jobs_cores, max_num_jobs_memory))
  416. os.environ["MAX_JOBS"] = str(max_jobs)
  417. super().__init__(*args, **kwargs)
  418. setup(
  419. name=PACKAGE_NAME,
  420. version=get_package_version(),
  421. packages=find_packages(
  422. exclude=(
  423. "build",
  424. "csrc",
  425. "include",
  426. "tests",
  427. "dist",
  428. "docs",
  429. "benchmarks",
  430. "flash_attn.egg-info",
  431. )
  432. ),
  433. author="Tri Dao",
  434. author_email="tri@tridao.me",
  435. description="Flash Attention: Fast and Memory-Efficient Exact Attention",
  436. long_description=long_description,
  437. long_description_content_type="text/markdown",
  438. url="https://github.com/Dao-AILab/flash-attention",
  439. classifiers=[
  440. "Programming Language :: Python :: 3",
  441. "License :: OSI Approved :: BSD License",
  442. "Operating System :: Unix",
  443. ],
  444. ext_modules=ext_modules,
  445. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": NinjaBuildExtension}
  446. if ext_modules
  447. else {
  448. "bdist_wheel": CachedWheelsCommand,
  449. },
  450. python_requires=">=3.8",
  451. install_requires=[
  452. "torch",
  453. "einops",
  454. ],
  455. setup_requires=[
  456. "packaging",
  457. "psutil",
  458. "ninja",
  459. ],
  460. )