setup.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 "linux_x86_64"
  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_bwd_hdim32_fp16_sm80.cu",
  128. "csrc/flash_attn/src/flash_bwd_hdim32_bf16_sm80.cu",
  129. "csrc/flash_attn/src/flash_bwd_hdim64_fp16_sm80.cu",
  130. "csrc/flash_attn/src/flash_bwd_hdim64_bf16_sm80.cu",
  131. "csrc/flash_attn/src/flash_bwd_hdim96_fp16_sm80.cu",
  132. "csrc/flash_attn/src/flash_bwd_hdim96_bf16_sm80.cu",
  133. "csrc/flash_attn/src/flash_bwd_hdim128_fp16_sm80.cu",
  134. "csrc/flash_attn/src/flash_bwd_hdim128_bf16_sm80.cu",
  135. "csrc/flash_attn/src/flash_bwd_hdim160_fp16_sm80.cu",
  136. "csrc/flash_attn/src/flash_bwd_hdim160_bf16_sm80.cu",
  137. "csrc/flash_attn/src/flash_bwd_hdim192_fp16_sm80.cu",
  138. "csrc/flash_attn/src/flash_bwd_hdim192_bf16_sm80.cu",
  139. "csrc/flash_attn/src/flash_bwd_hdim224_fp16_sm80.cu",
  140. "csrc/flash_attn/src/flash_bwd_hdim224_bf16_sm80.cu",
  141. "csrc/flash_attn/src/flash_bwd_hdim256_fp16_sm80.cu",
  142. "csrc/flash_attn/src/flash_bwd_hdim256_bf16_sm80.cu",
  143. "csrc/flash_attn/src/flash_fwd_split_hdim32_fp16_sm80.cu",
  144. "csrc/flash_attn/src/flash_fwd_split_hdim32_bf16_sm80.cu",
  145. "csrc/flash_attn/src/flash_fwd_split_hdim64_fp16_sm80.cu",
  146. "csrc/flash_attn/src/flash_fwd_split_hdim64_bf16_sm80.cu",
  147. "csrc/flash_attn/src/flash_fwd_split_hdim96_fp16_sm80.cu",
  148. "csrc/flash_attn/src/flash_fwd_split_hdim96_bf16_sm80.cu",
  149. "csrc/flash_attn/src/flash_fwd_split_hdim128_fp16_sm80.cu",
  150. "csrc/flash_attn/src/flash_fwd_split_hdim128_bf16_sm80.cu",
  151. "csrc/flash_attn/src/flash_fwd_split_hdim160_fp16_sm80.cu",
  152. "csrc/flash_attn/src/flash_fwd_split_hdim160_bf16_sm80.cu",
  153. "csrc/flash_attn/src/flash_fwd_split_hdim192_fp16_sm80.cu",
  154. "csrc/flash_attn/src/flash_fwd_split_hdim192_bf16_sm80.cu",
  155. "csrc/flash_attn/src/flash_fwd_split_hdim224_fp16_sm80.cu",
  156. "csrc/flash_attn/src/flash_fwd_split_hdim224_bf16_sm80.cu",
  157. "csrc/flash_attn/src/flash_fwd_split_hdim256_fp16_sm80.cu",
  158. "csrc/flash_attn/src/flash_fwd_split_hdim256_bf16_sm80.cu",
  159. ],
  160. extra_compile_args={
  161. "cxx": ["-O3", "-std=c++17"] + generator_flag,
  162. "nvcc": append_nvcc_threads(
  163. [
  164. "-O3",
  165. "-std=c++17",
  166. "-U__CUDA_NO_HALF_OPERATORS__",
  167. "-U__CUDA_NO_HALF_CONVERSIONS__",
  168. "-U__CUDA_NO_HALF2_OPERATORS__",
  169. "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
  170. "--expt-relaxed-constexpr",
  171. "--expt-extended-lambda",
  172. "--use_fast_math",
  173. # "--ptxas-options=-v",
  174. # "--ptxas-options=-O2",
  175. # "-lineinfo",
  176. ]
  177. + generator_flag
  178. + cc_flag
  179. ),
  180. },
  181. include_dirs=[
  182. Path(this_dir) / "csrc" / "flash_attn",
  183. Path(this_dir) / "csrc" / "flash_attn" / "src",
  184. Path(this_dir) / "csrc" / "cutlass" / "include",
  185. ],
  186. )
  187. )
  188. def get_package_version():
  189. with open(Path(this_dir) / "flash_attn" / "__init__.py", "r") as f:
  190. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  191. public_version = ast.literal_eval(version_match.group(1))
  192. local_version = os.environ.get("FLASH_ATTN_LOCAL_VERSION")
  193. if local_version:
  194. return f"{public_version}+{local_version}"
  195. else:
  196. return str(public_version)
  197. def get_wheel_url():
  198. # Determine the version numbers that will be used to determine the correct wheel
  199. # We're using the CUDA version used to build torch, not the one currently installed
  200. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  201. torch_cuda_version = parse(torch.version.cuda)
  202. torch_version_raw = parse(torch.__version__)
  203. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
  204. # to save CI time. Minor versions should be compatible.
  205. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
  206. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  207. platform_name = get_platform()
  208. flash_version = get_package_version()
  209. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  210. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  211. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  212. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  213. # Determine wheel URL based on CUDA version, torch version, python version and OS
  214. wheel_filename = f"{PACKAGE_NAME}-{flash_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  215. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{flash_version}", wheel_name=wheel_filename)
  216. return wheel_url, wheel_filename
  217. class CachedWheelsCommand(_bdist_wheel):
  218. """
  219. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  220. find an existing wheel (which is currently the case for all flash attention installs). We use
  221. the environment parameters to detect whether there is already a pre-built version of a compatible
  222. wheel available and short-circuits the standard full build pipeline.
  223. """
  224. def run(self):
  225. if FORCE_BUILD:
  226. return super().run()
  227. wheel_url, wheel_filename = get_wheel_url()
  228. print("Guessing wheel URL: ", wheel_url)
  229. try:
  230. urllib.request.urlretrieve(wheel_url, wheel_filename)
  231. # Make the archive
  232. # Lifted from the root wheel processing command
  233. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  234. if not os.path.exists(self.dist_dir):
  235. os.makedirs(self.dist_dir)
  236. impl_tag, abi_tag, plat_tag = self.get_tag()
  237. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  238. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  239. print("Raw wheel path", wheel_path)
  240. os.rename(wheel_filename, wheel_path)
  241. except urllib.error.HTTPError:
  242. print("Precompiled wheel not found. Building from source...")
  243. # If the wheel could not be downloaded, build from source
  244. super().run()
  245. class NinjaBuildExtension(BuildExtension):
  246. def __init__(self, *args, **kwargs) -> None:
  247. # do not override env MAX_JOBS if already exists
  248. if not os.environ.get("MAX_JOBS"):
  249. import psutil
  250. # calculate the maximum allowed NUM_JOBS based on cores
  251. max_num_jobs_cores = max(1, os.cpu_count() // 2)
  252. # calculate the maximum allowed NUM_JOBS based on free memory
  253. free_memory_gb = psutil.virtual_memory().available / (1024 ** 3) # free memory in GB
  254. max_num_jobs_memory = int(free_memory_gb / 9) # each JOB peak memory cost is ~8-9GB when threads = 4
  255. # pick lower value of jobs based on cores vs memory metric to minimize oom and swap usage during compilation
  256. max_jobs = max(1, min(max_num_jobs_cores, max_num_jobs_memory))
  257. os.environ["MAX_JOBS"] = str(max_jobs)
  258. super().__init__(*args, **kwargs)
  259. setup(
  260. name=PACKAGE_NAME,
  261. version=get_package_version(),
  262. packages=find_packages(
  263. exclude=(
  264. "build",
  265. "csrc",
  266. "include",
  267. "tests",
  268. "dist",
  269. "docs",
  270. "benchmarks",
  271. "flash_attn.egg-info",
  272. )
  273. ),
  274. author="Tri Dao",
  275. author_email="trid@cs.stanford.edu",
  276. description="Flash Attention: Fast and Memory-Efficient Exact Attention",
  277. long_description=long_description,
  278. long_description_content_type="text/markdown",
  279. url="https://github.com/Dao-AILab/flash-attention",
  280. classifiers=[
  281. "Programming Language :: Python :: 3",
  282. "License :: OSI Approved :: BSD License",
  283. "Operating System :: Unix",
  284. ],
  285. ext_modules=ext_modules,
  286. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": NinjaBuildExtension}
  287. if ext_modules
  288. else {
  289. "bdist_wheel": CachedWheelsCommand,
  290. },
  291. python_requires=">=3.7",
  292. install_requires=[
  293. "torch",
  294. "einops",
  295. "packaging",
  296. "ninja",
  297. ],
  298. setup_requires=[
  299. "psutil"
  300. ],
  301. )