setup.py 17 KB

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