setup.py 24 KB

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