setup.py 18 KB

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