setup.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 stat
  6. import re
  7. import shutil
  8. import ast
  9. from pathlib import Path
  10. from packaging.version import parse, Version
  11. import platform
  12. import sysconfig
  13. import tarfile
  14. import itertools
  15. from setuptools import setup, find_packages
  16. import subprocess
  17. import urllib.request
  18. import urllib.error
  19. from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
  20. import torch
  21. from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
  22. # with open("../README.md", "r", encoding="utf-8") as fh:
  23. with open("../README.md", "r", encoding="utf-8") as fh:
  24. long_description = fh.read()
  25. # ninja build does not work unless include_dirs are abs path
  26. this_dir = os.path.dirname(os.path.abspath(__file__))
  27. PACKAGE_NAME = "flash_attn"
  28. BASE_WHEEL_URL = "https://github.com/Dao-AILab/flash-attention/releases/download/{tag_name}/{wheel_name}"
  29. # FORCE_BUILD: Force a fresh build locally, instead of attempting to find prebuilt wheels
  30. # 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
  31. FORCE_BUILD = os.getenv("FLASH_ATTENTION_FORCE_BUILD", "FALSE") == "TRUE"
  32. SKIP_CUDA_BUILD = os.getenv("FLASH_ATTENTION_SKIP_CUDA_BUILD", "FALSE") == "TRUE"
  33. # For CI, we want the option to build with C++11 ABI since the nvcr images use C++11 ABI
  34. FORCE_CXX11_ABI = os.getenv("FLASH_ATTENTION_FORCE_CXX11_ABI", "FALSE") == "TRUE"
  35. DISABLE_BACKWARD = os.getenv("FLASH_ATTENTION_DISABLE_BACKWARD", "FALSE") == "TRUE"
  36. DISABLE_SPLIT = os.getenv("FLASH_ATTENTION_DISABLE_SPLIT", "FALSE") == "TRUE"
  37. DISABLE_PAGEDKV = os.getenv("FLASH_ATTENTION_DISABLE_PAGEDKV", "FALSE") == "TRUE"
  38. DISABLE_APPENDKV = os.getenv("FLASH_ATTENTION_DISABLE_APPENDKV", "FALSE") == "TRUE"
  39. DISABLE_LOCAL = os.getenv("FLASH_ATTENTION_DISABLE_LOCAL", "FALSE") == "TRUE"
  40. DISABLE_SOFTCAP = os.getenv("FLASH_ATTENTION_DISABLE_SOFTCAP", "FALSE") == "TRUE"
  41. DISABLE_PACKGQA = os.getenv("FLASH_ATTENTION_DISABLE_PACKGQA", "FALSE") == "TRUE"
  42. DISABLE_FP16 = os.getenv("FLASH_ATTENTION_DISABLE_FP16", "FALSE") == "TRUE"
  43. DISABLE_FP8 = os.getenv("FLASH_ATTENTION_DISABLE_FP8", "FALSE") == "TRUE"
  44. DISABLE_VARLEN = os.getenv("FLASH_ATTENTION_DISABLE_VARLEN", "FALSE") == "TRUE"
  45. DISABLE_CLUSTER = os.getenv("FLASH_ATTENTION_DISABLE_CLUSTER", "FALSE") == "TRUE"
  46. DISABLE_HDIM64 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM64", "FALSE") == "TRUE"
  47. DISABLE_HDIM96 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM96", "FALSE") == "TRUE"
  48. DISABLE_HDIM128 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM128", "FALSE") == "TRUE"
  49. DISABLE_HDIM192 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM192", "FALSE") == "TRUE"
  50. DISABLE_HDIM256 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM256", "FALSE") == "TRUE"
  51. ENABLE_VCOLMAJOR = os.getenv("FLASH_ATTENTION_ENABLE_VCOLMAJOR", "FALSE") == "TRUE"
  52. def get_platform():
  53. """
  54. Returns the platform name as used in wheel filenames.
  55. """
  56. if sys.platform.startswith("linux"):
  57. return "linux_x86_64"
  58. elif sys.platform == "darwin":
  59. mac_version = ".".join(platform.mac_ver()[0].split(".")[:2])
  60. return f"macosx_{mac_version}_x86_64"
  61. elif sys.platform == "win32":
  62. return "win_amd64"
  63. else:
  64. raise ValueError("Unsupported platform: {}".format(sys.platform))
  65. def get_cuda_bare_metal_version(cuda_dir):
  66. raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
  67. output = raw_output.split()
  68. release_idx = output.index("release") + 1
  69. bare_metal_version = parse(output[release_idx].split(",")[0])
  70. return raw_output, bare_metal_version
  71. def check_if_cuda_home_none(global_option: str) -> None:
  72. if CUDA_HOME is not None:
  73. return
  74. # warn instead of error because user could be downloading prebuilt wheels, so nvcc won't be necessary
  75. # in that case.
  76. warnings.warn(
  77. f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
  78. "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
  79. "only images whose names contain 'devel' will provide nvcc."
  80. )
  81. # Taken from https://github.com/pytorch/pytorch/blob/master/tools/setup_helpers/env.py
  82. def check_env_flag(name: str, default: str = "") -> bool:
  83. return os.getenv(name, default).upper() in ["ON", "1", "YES", "TRUE", "Y"]
  84. # Copied from https://github.com/triton-lang/triton/blob/main/python/setup.py
  85. def is_offline_build() -> bool:
  86. """
  87. Downstream projects and distributions which bootstrap their own dependencies from scratch
  88. and run builds in offline sandboxes
  89. may set `FLASH_ATTENTION_OFFLINE_BUILD` in the build environment to prevent any attempts at downloading
  90. pinned dependencies from the internet or at using dependencies vendored in-tree.
  91. Dependencies must be defined using respective search paths (cf. `syspath_var_name` in `Package`).
  92. Missing dependencies lead to an early abortion.
  93. Dependencies' compatibility is not verified.
  94. Note that this flag isn't tested by the CI and does not provide any guarantees.
  95. """
  96. return check_env_flag("FLASH_ATTENTION_OFFLINE_BUILD", "")
  97. # Copied from https://github.com/triton-lang/triton/blob/main/python/setup.py
  98. def get_flashattn_cache_path():
  99. user_home = os.getenv("FLASH_ATTENTION_HOME")
  100. if not user_home:
  101. user_home = os.getenv("HOME") or os.getenv("USERPROFILE") or os.getenv("HOMEPATH") or None
  102. if not user_home:
  103. raise RuntimeError("Could not find user home directory")
  104. return os.path.join(user_home, ".flashattn")
  105. def open_url(url):
  106. user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/119.0'
  107. headers = {
  108. 'User-Agent': user_agent,
  109. }
  110. request = urllib.request.Request(url, None, headers)
  111. # Set timeout to 300 seconds to prevent the request from hanging forever.
  112. return urllib.request.urlopen(request, timeout=300)
  113. def download_and_copy(name, src_path, dst_path, version, url_func):
  114. if is_offline_build():
  115. return
  116. flashattn_cache_path = get_flashattn_cache_path()
  117. base_dir = os.path.dirname(__file__)
  118. system = platform.system()
  119. try:
  120. arch = {"x86_64": "64", "arm64": "aarch64", "aarch64": "aarch64"}[platform.machine()]
  121. except KeyError:
  122. arch = platform.machine()
  123. supported = {"Linux": "linux", "Darwin": "linux"}
  124. url = url_func(supported[system], arch, version)
  125. tmp_path = os.path.join(flashattn_cache_path, "nvidia", name) # path to cache the download
  126. dst_path = os.path.join(base_dir, os.pardir, "third_party", "nvidia", "backend", dst_path) # final binary path
  127. platform_name = "sbsa-linux" if arch == "aarch64" else "x86_64-linux"
  128. src_path = src_path(platform_name, version) if callable(src_path) else src_path
  129. src_path = os.path.join(tmp_path, src_path)
  130. download = not os.path.exists(src_path)
  131. if download:
  132. print(f'downloading and extracting {url} ...')
  133. file = tarfile.open(fileobj=open_url(url), mode="r|*")
  134. file.extractall(path=tmp_path)
  135. os.makedirs(os.path.split(dst_path)[0], exist_ok=True)
  136. print(f'copy {src_path} to {dst_path} ...')
  137. if os.path.isdir(src_path):
  138. shutil.copytree(src_path, dst_path, dirs_exist_ok=True)
  139. else:
  140. shutil.copy(src_path, dst_path)
  141. def nvcc_threads_args():
  142. nvcc_threads = os.getenv("NVCC_THREADS") or "4"
  143. return ["--threads", nvcc_threads]
  144. NVIDIA_TOOLCHAIN_VERSION = {"nvcc": "12.3.107"}
  145. exe_extension = sysconfig.get_config_var("EXE")
  146. cmdclass = {}
  147. ext_modules = []
  148. # We want this even if SKIP_CUDA_BUILD because when we run python setup.py sdist we want the .hpp
  149. # files included in the source distribution, in case the user compiles from source.
  150. subprocess.run(["git", "submodule", "update", "--init", "../csrc/cutlass"])
  151. if not SKIP_CUDA_BUILD:
  152. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  153. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  154. TORCH_MINOR = int(torch.__version__.split(".")[1])
  155. check_if_cuda_home_none("flash_attn")
  156. _, bare_metal_version = get_cuda_bare_metal_version(CUDA_HOME)
  157. if bare_metal_version < Version("12.3"):
  158. raise RuntimeError("FlashAttention-3 is only supported on CUDA 12.3 and above")
  159. if bare_metal_version != Version("12.3"): # nvcc 12.3 gives the best perf currently
  160. download_and_copy(
  161. name="nvcc", src_path=f"bin", dst_path="bin",
  162. version=NVIDIA_TOOLCHAIN_VERSION["nvcc"], url_func=lambda system, arch, version:
  163. ((lambda version_major, version_minor1, version_minor2:
  164. f"https://anaconda.org/nvidia/cuda-nvcc/{version}/download/{system}-{arch}/cuda-nvcc-{version}-0.tar.bz2")
  165. (*version.split('.'))))
  166. download_and_copy(
  167. name="nvcc", src_path=f"nvvm/bin", dst_path="bin",
  168. version=NVIDIA_TOOLCHAIN_VERSION["nvcc"], url_func=lambda system, arch, version:
  169. ((lambda version_major, version_minor1, version_minor2:
  170. f"https://anaconda.org/nvidia/cuda-nvcc/{version}/download/{system}-{arch}/cuda-nvcc-{version}-0.tar.bz2")
  171. (*version.split('.'))))
  172. base_dir = os.path.dirname(__file__)
  173. ctk_path_new = os.path.join(base_dir, os.pardir, "third_party", "nvidia", "backend", "bin")
  174. nvcc_path_new = os.path.join(ctk_path_new, f"nvcc{exe_extension}")
  175. # Need to append to path otherwise nvcc can't find cicc in nvvm/bin/cicc
  176. os.environ["PATH"] = ctk_path_new + os.pathsep + os.environ["PATH"]
  177. os.environ["PYTORCH_NVCC"] = nvcc_path_new
  178. # Make nvcc executable, sometimes after the copy it loses its permissions
  179. os.chmod(nvcc_path_new, os.stat(nvcc_path_new).st_mode | stat.S_IEXEC)
  180. cc_flag = []
  181. cc_flag.append("-gencode")
  182. cc_flag.append("arch=compute_90a,code=sm_90a")
  183. # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
  184. # torch._C._GLIBCXX_USE_CXX11_ABI
  185. # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
  186. if FORCE_CXX11_ABI:
  187. torch._C._GLIBCXX_USE_CXX11_ABI = True
  188. repo_dir = Path(this_dir).parent
  189. cutlass_dir = repo_dir / "csrc" / "cutlass"
  190. feature_args = (
  191. []
  192. + (["-DFLASHATTENTION_DISABLE_BACKWARD"] if DISABLE_BACKWARD else [])
  193. + (["-DFLASHATTENTION_DISABLE_PAGEDKV"] if DISABLE_PAGEDKV else [])
  194. + (["-DFLASHATTENTION_DISABLE_SPLIT"] if DISABLE_SPLIT else [])
  195. + (["-DFLASHATTENTION_DISABLE_APPENDKV"] if DISABLE_APPENDKV else [])
  196. + (["-DFLASHATTENTION_DISABLE_LOCAL"] if DISABLE_LOCAL else [])
  197. + (["-DFLASHATTENTION_DISABLE_SOFTCAP"] if DISABLE_SOFTCAP else [])
  198. + (["-DFLASHATTENTION_DISABLE_PACKGQA"] if DISABLE_PACKGQA else [])
  199. + (["-DFLASHATTENTION_DISABLE_FP16"] if DISABLE_FP16 else [])
  200. + (["-DFLASHATTENTION_DISABLE_FP8"] if DISABLE_FP8 else [])
  201. + (["-DFLASHATTENTION_DISABLE_VARLEN"] if DISABLE_VARLEN else [])
  202. + (["-DFLASHATTENTION_DISABLE_CLUSTER"] if DISABLE_CLUSTER else [])
  203. + (["-DFLASHATTENTION_DISABLE_HDIM64"] if DISABLE_HDIM64 else [])
  204. + (["-DFLASHATTENTION_DISABLE_HDIM96"] if DISABLE_HDIM96 else [])
  205. + (["-DFLASHATTENTION_DISABLE_HDIM128"] if DISABLE_HDIM128 else [])
  206. + (["-DFLASHATTENTION_DISABLE_HDIM192"] if DISABLE_HDIM192 else [])
  207. + (["-DFLASHATTENTION_DISABLE_HDIM256"] if DISABLE_HDIM256 else [])
  208. + (["-DFLASHATTENTION_ENABLE_VCOLMAJOR"] if ENABLE_VCOLMAJOR else [])
  209. )
  210. DTYPE_FWD = ["bf16"] + (["fp16"] if not DISABLE_FP16 else []) + (["e4m3"] if not DISABLE_FP8 else [])
  211. DTYPE_BWD = ["bf16"] + (["fp16"] if not DISABLE_FP16 else [])
  212. HEAD_DIMENSIONS_BWD = (
  213. []
  214. + ([64] if not DISABLE_HDIM64 else [])
  215. + ([96] if not DISABLE_HDIM96 else [])
  216. + ([128] if not DISABLE_HDIM128 else [])
  217. + ([192] if not DISABLE_HDIM192 else [])
  218. + ([256] if not DISABLE_HDIM256 else [])
  219. )
  220. # HEAD_DIMENSIONS_FWD = HEAD_DIMENSIONS_BWD
  221. HEAD_DIMENSIONS_FWD = ["all"]
  222. SPLIT = [""] + (["_split"] if not DISABLE_SPLIT else [])
  223. PAGEDKV = [""] + (["_paged"] if not DISABLE_PAGEDKV else [])
  224. SOFTCAP = [""] + (["_softcap"] if not DISABLE_SOFTCAP else [])
  225. PACKGQA = [""] + (["_packgqa"] if not DISABLE_PACKGQA else [])
  226. sources_fwd = [f"instantiations/flash_fwd_hdim{hdim}_{dtype}{paged}{split}{softcap}{packgqa}_sm90.cu"
  227. for hdim, dtype, split, paged, softcap, packgqa in itertools.product(HEAD_DIMENSIONS_FWD, DTYPE_FWD, SPLIT, PAGEDKV, SOFTCAP, PACKGQA)]
  228. sources_bwd = [f"instantiations/flash_bwd_hdim{hdim}_{dtype}_sm90.cu"
  229. for hdim, dtype in itertools.product(HEAD_DIMENSIONS_BWD, DTYPE_BWD)]
  230. if DISABLE_BACKWARD:
  231. sources_bwd = []
  232. sources = ["flash_api.cpp"] + sources_fwd + sources_bwd
  233. if not DISABLE_SPLIT:
  234. sources += ["flash_fwd_combine_sm80.cu"]
  235. nvcc_flags = [
  236. "-O3",
  237. "-std=c++17",
  238. "--ftemplate-backtrace-limit=0", # To debug template code
  239. "--use_fast_math",
  240. # "--keep",
  241. # "--ptxas-options=--verbose,--register-usage-level=5,--warn-on-local-memory-usage", # printing out number of registers
  242. # f"--split-compile={os.getenv('NVCC_THREADS', '4')}", # split-compile is faster
  243. "--resource-usage", # printing out number of registers
  244. "-lineinfo",
  245. "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", # Necessary for the WGMMA shapes that we use
  246. # "-DCUTLASS_ENABLE_GDC_FOR_SM90", # For PDL
  247. "-DCUTLASS_DEBUG_TRACE_LEVEL=0", # Can toggle for debugging
  248. "-DNDEBUG", # Important, otherwise performance is severely impacted
  249. ]
  250. if get_platform() == "win_amd64":
  251. nvcc_flags.extend(
  252. [
  253. "-D_USE_MATH_DEFINES", # for M_LN2
  254. "-Xcompiler=/Zc:__cplusplus", # sets __cplusplus correctly, CUTLASS_CONSTEXPR_IF_CXX17 needed for cutlass::gcd
  255. ]
  256. )
  257. include_dirs = [
  258. Path(this_dir),
  259. cutlass_dir / "include",
  260. ]
  261. ext_modules.append(
  262. CUDAExtension(
  263. name="flash_attn_3_cuda",
  264. sources=sources,
  265. extra_compile_args={
  266. "cxx": ["-O3", "-std=c++17"] + feature_args,
  267. "nvcc": nvcc_threads_args() + nvcc_flags + cc_flag + feature_args,
  268. },
  269. include_dirs=include_dirs,
  270. )
  271. )
  272. def get_package_version():
  273. with open(Path(this_dir) / "__init__.py", "r") as f:
  274. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  275. public_version = ast.literal_eval(version_match.group(1))
  276. local_version = os.environ.get("FLASH_ATTN_LOCAL_VERSION")
  277. if local_version:
  278. return f"{public_version}+{local_version}"
  279. else:
  280. return str(public_version)
  281. def get_wheel_url():
  282. # Determine the version numbers that will be used to determine the correct wheel
  283. # We're using the CUDA version used to build torch, not the one currently installed
  284. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  285. torch_cuda_version = parse(torch.version.cuda)
  286. torch_version_raw = parse(torch.__version__)
  287. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
  288. # to save CI time. Minor versions should be compatible.
  289. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
  290. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  291. platform_name = get_platform()
  292. package_version = get_package_version()
  293. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  294. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  295. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  296. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  297. # Determine wheel URL based on CUDA version, torch version, python version and OS
  298. wheel_filename = f"{PACKAGE_NAME}-{package_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  299. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{package_version}", wheel_name=wheel_filename)
  300. return wheel_url, wheel_filename
  301. class CachedWheelsCommand(_bdist_wheel):
  302. """
  303. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  304. find an existing wheel (which is currently the case for all installs). We use
  305. the environment parameters to detect whether there is already a pre-built version of a compatible
  306. wheel available and short-circuits the standard full build pipeline.
  307. """
  308. def run(self):
  309. if FORCE_BUILD:
  310. return super().run()
  311. wheel_url, wheel_filename = get_wheel_url()
  312. print("Guessing wheel URL: ", wheel_url)
  313. try:
  314. urllib.request.urlretrieve(wheel_url, wheel_filename)
  315. # Make the archive
  316. # Lifted from the root wheel processing command
  317. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  318. if not os.path.exists(self.dist_dir):
  319. os.makedirs(self.dist_dir)
  320. impl_tag, abi_tag, plat_tag = self.get_tag()
  321. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  322. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  323. print("Raw wheel path", wheel_path)
  324. shutil.move(wheel_filename, wheel_path)
  325. except urllib.error.HTTPError:
  326. print("Precompiled wheel not found. Building from source...")
  327. # If the wheel could not be downloaded, build from source
  328. super().run()
  329. setup(
  330. name=PACKAGE_NAME,
  331. version=get_package_version(),
  332. packages=find_packages(
  333. exclude=(
  334. "build",
  335. "csrc",
  336. "include",
  337. "tests",
  338. "dist",
  339. "docs",
  340. "benchmarks",
  341. )
  342. ),
  343. py_modules=["flash_attn_interface"],
  344. description="FlashAttention-3",
  345. long_description=long_description,
  346. long_description_content_type="text/markdown",
  347. classifiers=[
  348. "Programming Language :: Python :: 3",
  349. "License :: OSI Approved :: Apache Software License",
  350. "Operating System :: Unix",
  351. ],
  352. ext_modules=ext_modules,
  353. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": BuildExtension}
  354. if ext_modules
  355. else {
  356. "bdist_wheel": CachedWheelsCommand,
  357. },
  358. python_requires=">=3.8",
  359. install_requires=[
  360. "torch",
  361. "einops",
  362. "packaging",
  363. "ninja",
  364. ],
  365. )