setup.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. DISABLE_SM8x = os.getenv("FLASH_ATTENTION_DISABLE_SM80", "FALSE") == "TRUE"
  52. ENABLE_VCOLMAJOR = os.getenv("FLASH_ATTENTION_ENABLE_VCOLMAJOR", "FALSE") == "TRUE"
  53. # HACK: we monkey patch pytorch's _write_ninja_file to pass
  54. # "-gencode arch=compute_sm90a,code=sm_90a" to files ending in '_sm90.cu',
  55. # and pass "-gencode arch=compute_sm80,code=sm_80" to files ending in '_sm80.cu'
  56. from torch.utils.cpp_extension import (
  57. IS_HIP_EXTENSION,
  58. COMMON_HIP_FLAGS,
  59. SUBPROCESS_DECODE_ARGS,
  60. IS_WINDOWS,
  61. get_cxx_compiler,
  62. _join_rocm_home,
  63. _join_cuda_home,
  64. _is_cuda_file,
  65. _maybe_write,
  66. )
  67. def _write_ninja_file(path,
  68. cflags,
  69. post_cflags,
  70. cuda_cflags,
  71. cuda_post_cflags,
  72. cuda_dlink_post_cflags,
  73. sources,
  74. objects,
  75. ldflags,
  76. library_target,
  77. with_cuda) -> None:
  78. r"""Write a ninja file that does the desired compiling and linking.
  79. `path`: Where to write this file
  80. `cflags`: list of flags to pass to $cxx. Can be None.
  81. `post_cflags`: list of flags to append to the $cxx invocation. Can be None.
  82. `cuda_cflags`: list of flags to pass to $nvcc. Can be None.
  83. `cuda_postflags`: list of flags to append to the $nvcc invocation. Can be None.
  84. `sources`: list of paths to source files
  85. `objects`: list of desired paths to objects, one per source.
  86. `ldflags`: list of flags to pass to linker. Can be None.
  87. `library_target`: Name of the output library. Can be None; in that case,
  88. we do no linking.
  89. `with_cuda`: If we should be compiling with CUDA.
  90. """
  91. def sanitize_flags(flags):
  92. if flags is None:
  93. return []
  94. else:
  95. return [flag.strip() for flag in flags]
  96. cflags = sanitize_flags(cflags)
  97. post_cflags = sanitize_flags(post_cflags)
  98. cuda_cflags = sanitize_flags(cuda_cflags)
  99. cuda_post_cflags = sanitize_flags(cuda_post_cflags)
  100. cuda_dlink_post_cflags = sanitize_flags(cuda_dlink_post_cflags)
  101. ldflags = sanitize_flags(ldflags)
  102. # Sanity checks...
  103. assert len(sources) == len(objects)
  104. assert len(sources) > 0
  105. compiler = get_cxx_compiler()
  106. # Version 1.3 is required for the `deps` directive.
  107. config = ['ninja_required_version = 1.3']
  108. config.append(f'cxx = {compiler}')
  109. if with_cuda or cuda_dlink_post_cflags:
  110. if IS_HIP_EXTENSION:
  111. nvcc = _join_rocm_home('bin', 'hipcc')
  112. else:
  113. nvcc = _join_cuda_home('bin', 'nvcc')
  114. if "PYTORCH_NVCC" in os.environ:
  115. nvcc_from_env = os.getenv("PYTORCH_NVCC") # user can set nvcc compiler with ccache using the environment variable here
  116. else:
  117. nvcc_from_env = nvcc
  118. config.append(f'nvcc_from_env = {nvcc_from_env}')
  119. config.append(f'nvcc = {nvcc}')
  120. if IS_HIP_EXTENSION:
  121. post_cflags = COMMON_HIP_FLAGS + post_cflags
  122. flags = [f'cflags = {" ".join(cflags)}']
  123. flags.append(f'post_cflags = {" ".join(post_cflags)}')
  124. if with_cuda:
  125. flags.append(f'cuda_cflags = {" ".join(cuda_cflags)}')
  126. flags.append(f'cuda_post_cflags = {" ".join(cuda_post_cflags)}')
  127. cuda_post_cflags_sm80 = [s if s != 'arch=compute_90a,code=sm_90a' else 'arch=compute_80,code=sm_80' for s in cuda_post_cflags]
  128. flags.append(f'cuda_post_cflags_sm80 = {" ".join(cuda_post_cflags_sm80)}')
  129. cuda_post_cflags_sm80_sm90 = cuda_post_cflags + ['-gencode', 'arch=compute_80,code=sm_80']
  130. flags.append(f'cuda_post_cflags_sm80_sm90 = {" ".join(cuda_post_cflags_sm80_sm90)}')
  131. flags.append(f'cuda_dlink_post_cflags = {" ".join(cuda_dlink_post_cflags)}')
  132. flags.append(f'ldflags = {" ".join(ldflags)}')
  133. # Turn into absolute paths so we can emit them into the ninja build
  134. # file wherever it is.
  135. sources = [os.path.abspath(file) for file in sources]
  136. # See https://ninja-build.org/build.ninja.html for reference.
  137. compile_rule = ['rule compile']
  138. if IS_WINDOWS:
  139. compile_rule.append(
  140. ' command = cl /showIncludes $cflags -c $in /Fo$out $post_cflags')
  141. compile_rule.append(' deps = msvc')
  142. else:
  143. compile_rule.append(
  144. ' command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflags')
  145. compile_rule.append(' depfile = $out.d')
  146. compile_rule.append(' deps = gcc')
  147. if with_cuda:
  148. cuda_compile_rule = ['rule cuda_compile']
  149. nvcc_gendeps = ''
  150. # --generate-dependencies-with-compile is not supported by ROCm
  151. # Nvcc flag `--generate-dependencies-with-compile` is not supported by sccache, which may increase build time.
  152. if torch.version.cuda is not None and os.getenv('TORCH_EXTENSION_SKIP_NVCC_GEN_DEPENDENCIES', '0') != '1':
  153. cuda_compile_rule.append(' depfile = $out.d')
  154. cuda_compile_rule.append(' deps = gcc')
  155. # Note: non-system deps with nvcc are only supported
  156. # on Linux so use --generate-dependencies-with-compile
  157. # to make this work on Windows too.
  158. nvcc_gendeps = '--generate-dependencies-with-compile --dependency-output $out.d'
  159. cuda_compile_rule_sm80 = ['rule cuda_compile_sm80'] + cuda_compile_rule[1:] + [
  160. f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags_sm80'
  161. ]
  162. cuda_compile_rule_sm80_sm90 = ['rule cuda_compile_sm80_sm90'] + cuda_compile_rule[1:] + [
  163. f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags_sm80_sm90'
  164. ]
  165. cuda_compile_rule.append(
  166. f' command = $nvcc_from_env {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags')
  167. # Emit one build rule per source to enable incremental build.
  168. build = []
  169. for source_file, object_file in zip(sources, objects):
  170. is_cuda_source = _is_cuda_file(source_file) and with_cuda
  171. if is_cuda_source:
  172. if source_file.endswith('_sm90.cu'):
  173. rule = 'cuda_compile'
  174. elif source_file.endswith('_sm80.cu'):
  175. rule = 'cuda_compile_sm80'
  176. else:
  177. rule = 'cuda_compile_sm80_sm90'
  178. else:
  179. rule = 'compile'
  180. if IS_WINDOWS:
  181. source_file = source_file.replace(':', '$:')
  182. object_file = object_file.replace(':', '$:')
  183. source_file = source_file.replace(" ", "$ ")
  184. object_file = object_file.replace(" ", "$ ")
  185. build.append(f'build {object_file}: {rule} {source_file}')
  186. if cuda_dlink_post_cflags:
  187. devlink_out = os.path.join(os.path.dirname(objects[0]), 'dlink.o')
  188. devlink_rule = ['rule cuda_devlink']
  189. devlink_rule.append(' command = $nvcc $in -o $out $cuda_dlink_post_cflags')
  190. devlink = [f'build {devlink_out}: cuda_devlink {" ".join(objects)}']
  191. objects += [devlink_out]
  192. else:
  193. devlink_rule, devlink = [], []
  194. if library_target is not None:
  195. link_rule = ['rule link']
  196. if IS_WINDOWS:
  197. cl_paths = subprocess.check_output(['where',
  198. 'cl']).decode(*SUBPROCESS_DECODE_ARGS).split('\r\n')
  199. if len(cl_paths) >= 1:
  200. cl_path = os.path.dirname(cl_paths[0]).replace(':', '$:')
  201. else:
  202. raise RuntimeError("MSVC is required to load C++ extensions")
  203. link_rule.append(f' command = "{cl_path}/link.exe" $in /nologo $ldflags /out:$out')
  204. else:
  205. link_rule.append(' command = $cxx $in $ldflags -o $out')
  206. link = [f'build {library_target}: link {" ".join(objects)}']
  207. default = [f'default {library_target}']
  208. else:
  209. link_rule, link, default = [], [], []
  210. # 'Blocks' should be separated by newlines, for visual benefit.
  211. blocks = [config, flags, compile_rule]
  212. if with_cuda:
  213. blocks.append(cuda_compile_rule) # type: ignore[possibly-undefined]
  214. blocks.append(cuda_compile_rule_sm80) # type: ignore[possibly-undefined]
  215. blocks.append(cuda_compile_rule_sm80_sm90) # type: ignore[possibly-undefined]
  216. blocks += [devlink_rule, link_rule, build, devlink, link, default]
  217. content = "\n\n".join("\n".join(b) for b in blocks)
  218. # Ninja requires a new lines at the end of the .ninja file
  219. content += "\n"
  220. _maybe_write(path, content)
  221. # Monkey patching
  222. torch.utils.cpp_extension._write_ninja_file = _write_ninja_file
  223. def get_platform():
  224. """
  225. Returns the platform name as used in wheel filenames.
  226. """
  227. if sys.platform.startswith("linux"):
  228. return "linux_x86_64"
  229. elif sys.platform == "darwin":
  230. mac_version = ".".join(platform.mac_ver()[0].split(".")[:2])
  231. return f"macosx_{mac_version}_x86_64"
  232. elif sys.platform == "win32":
  233. return "win_amd64"
  234. else:
  235. raise ValueError("Unsupported platform: {}".format(sys.platform))
  236. def get_cuda_bare_metal_version(cuda_dir):
  237. raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
  238. output = raw_output.split()
  239. release_idx = output.index("release") + 1
  240. bare_metal_version = parse(output[release_idx].split(",")[0])
  241. return raw_output, bare_metal_version
  242. def check_if_cuda_home_none(global_option: str) -> None:
  243. if CUDA_HOME is not None:
  244. return
  245. # warn instead of error because user could be downloading prebuilt wheels, so nvcc won't be necessary
  246. # in that case.
  247. warnings.warn(
  248. f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
  249. "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
  250. "only images whose names contain 'devel' will provide nvcc."
  251. )
  252. # Taken from https://github.com/pytorch/pytorch/blob/master/tools/setup_helpers/env.py
  253. def check_env_flag(name: str, default: str = "") -> bool:
  254. return os.getenv(name, default).upper() in ["ON", "1", "YES", "TRUE", "Y"]
  255. # Copied from https://github.com/triton-lang/triton/blob/main/python/setup.py
  256. def is_offline_build() -> bool:
  257. """
  258. Downstream projects and distributions which bootstrap their own dependencies from scratch
  259. and run builds in offline sandboxes
  260. may set `FLASH_ATTENTION_OFFLINE_BUILD` in the build environment to prevent any attempts at downloading
  261. pinned dependencies from the internet or at using dependencies vendored in-tree.
  262. Dependencies must be defined using respective search paths (cf. `syspath_var_name` in `Package`).
  263. Missing dependencies lead to an early abortion.
  264. Dependencies' compatibility is not verified.
  265. Note that this flag isn't tested by the CI and does not provide any guarantees.
  266. """
  267. return check_env_flag("FLASH_ATTENTION_OFFLINE_BUILD", "")
  268. # Copied from https://github.com/triton-lang/triton/blob/main/python/setup.py
  269. def get_flashattn_cache_path():
  270. user_home = os.getenv("FLASH_ATTENTION_HOME")
  271. if not user_home:
  272. user_home = os.getenv("HOME") or os.getenv("USERPROFILE") or os.getenv("HOMEPATH") or None
  273. if not user_home:
  274. raise RuntimeError("Could not find user home directory")
  275. return os.path.join(user_home, ".flashattn")
  276. def open_url(url):
  277. user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/119.0'
  278. headers = {
  279. 'User-Agent': user_agent,
  280. }
  281. request = urllib.request.Request(url, None, headers)
  282. # Set timeout to 300 seconds to prevent the request from hanging forever.
  283. return urllib.request.urlopen(request, timeout=300)
  284. def download_and_copy(name, src_path, dst_path, version, url_func):
  285. if is_offline_build():
  286. return
  287. flashattn_cache_path = get_flashattn_cache_path()
  288. base_dir = os.path.dirname(__file__)
  289. system = platform.system()
  290. try:
  291. arch = {"x86_64": "64", "arm64": "aarch64", "aarch64": "aarch64"}[platform.machine()]
  292. except KeyError:
  293. arch = platform.machine()
  294. supported = {"Linux": "linux", "Darwin": "linux"}
  295. url = url_func(supported[system], arch, version)
  296. tmp_path = os.path.join(flashattn_cache_path, "nvidia", name) # path to cache the download
  297. dst_path = os.path.join(base_dir, os.pardir, "third_party", "nvidia", "backend", dst_path) # final binary path
  298. platform_name = "sbsa-linux" if arch == "aarch64" else "x86_64-linux"
  299. src_path = src_path(platform_name, version) if callable(src_path) else src_path
  300. src_path = os.path.join(tmp_path, src_path)
  301. download = not os.path.exists(src_path)
  302. if download:
  303. print(f'downloading and extracting {url} ...')
  304. file = tarfile.open(fileobj=open_url(url), mode="r|*")
  305. file.extractall(path=tmp_path)
  306. os.makedirs(os.path.split(dst_path)[0], exist_ok=True)
  307. print(f'copy {src_path} to {dst_path} ...')
  308. if os.path.isdir(src_path):
  309. shutil.copytree(src_path, dst_path, dirs_exist_ok=True)
  310. else:
  311. shutil.copy(src_path, dst_path)
  312. def nvcc_threads_args():
  313. nvcc_threads = os.getenv("NVCC_THREADS") or "4"
  314. return ["--threads", nvcc_threads]
  315. NVIDIA_TOOLCHAIN_VERSION = {"nvcc": "12.3.107"}
  316. exe_extension = sysconfig.get_config_var("EXE")
  317. cmdclass = {}
  318. ext_modules = []
  319. # We want this even if SKIP_CUDA_BUILD because when we run python setup.py sdist we want the .hpp
  320. # files included in the source distribution, in case the user compiles from source.
  321. subprocess.run(["git", "submodule", "update", "--init", "../csrc/cutlass"])
  322. if not SKIP_CUDA_BUILD:
  323. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  324. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  325. TORCH_MINOR = int(torch.__version__.split(".")[1])
  326. check_if_cuda_home_none("flash_attn")
  327. _, bare_metal_version = get_cuda_bare_metal_version(CUDA_HOME)
  328. if bare_metal_version < Version("12.3"):
  329. raise RuntimeError("FlashAttention-3 is only supported on CUDA 12.3 and above")
  330. if bare_metal_version != Version("12.3"): # nvcc 12.3 gives the best perf currently
  331. download_and_copy(
  332. name="nvcc", src_path=f"bin", dst_path="bin",
  333. version=NVIDIA_TOOLCHAIN_VERSION["nvcc"], url_func=lambda system, arch, version:
  334. ((lambda version_major, version_minor1, version_minor2:
  335. f"https://anaconda.org/nvidia/cuda-nvcc/{version}/download/{system}-{arch}/cuda-nvcc-{version}-0.tar.bz2")
  336. (*version.split('.'))))
  337. download_and_copy(
  338. name="nvcc", src_path=f"nvvm/bin", dst_path="bin",
  339. version=NVIDIA_TOOLCHAIN_VERSION["nvcc"], url_func=lambda system, arch, version:
  340. ((lambda version_major, version_minor1, version_minor2:
  341. f"https://anaconda.org/nvidia/cuda-nvcc/{version}/download/{system}-{arch}/cuda-nvcc-{version}-0.tar.bz2")
  342. (*version.split('.'))))
  343. base_dir = os.path.dirname(__file__)
  344. ctk_path_new = os.path.join(base_dir, os.pardir, "third_party", "nvidia", "backend", "bin")
  345. nvcc_path_new = os.path.join(ctk_path_new, f"nvcc{exe_extension}")
  346. # Need to append to path otherwise nvcc can't find cicc in nvvm/bin/cicc
  347. os.environ["PATH"] = ctk_path_new + os.pathsep + os.environ["PATH"]
  348. os.environ["PYTORCH_NVCC"] = nvcc_path_new
  349. # Make nvcc executable, sometimes after the copy it loses its permissions
  350. os.chmod(nvcc_path_new, os.stat(nvcc_path_new).st_mode | stat.S_IEXEC)
  351. cc_flag = []
  352. cc_flag.append("-gencode")
  353. cc_flag.append("arch=compute_90a,code=sm_90a")
  354. # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
  355. # torch._C._GLIBCXX_USE_CXX11_ABI
  356. # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
  357. if FORCE_CXX11_ABI:
  358. torch._C._GLIBCXX_USE_CXX11_ABI = True
  359. repo_dir = Path(this_dir).parent
  360. cutlass_dir = repo_dir / "csrc" / "cutlass"
  361. feature_args = (
  362. []
  363. + (["-DFLASHATTENTION_DISABLE_BACKWARD"] if DISABLE_BACKWARD else [])
  364. + (["-DFLASHATTENTION_DISABLE_PAGEDKV"] if DISABLE_PAGEDKV else [])
  365. + (["-DFLASHATTENTION_DISABLE_SPLIT"] if DISABLE_SPLIT else [])
  366. + (["-DFLASHATTENTION_DISABLE_APPENDKV"] if DISABLE_APPENDKV else [])
  367. + (["-DFLASHATTENTION_DISABLE_LOCAL"] if DISABLE_LOCAL else [])
  368. + (["-DFLASHATTENTION_DISABLE_SOFTCAP"] if DISABLE_SOFTCAP else [])
  369. + (["-DFLASHATTENTION_DISABLE_PACKGQA"] if DISABLE_PACKGQA else [])
  370. + (["-DFLASHATTENTION_DISABLE_FP16"] if DISABLE_FP16 else [])
  371. + (["-DFLASHATTENTION_DISABLE_FP8"] if DISABLE_FP8 else [])
  372. + (["-DFLASHATTENTION_DISABLE_VARLEN"] if DISABLE_VARLEN else [])
  373. + (["-DFLASHATTENTION_DISABLE_CLUSTER"] if DISABLE_CLUSTER else [])
  374. + (["-DFLASHATTENTION_DISABLE_HDIM64"] if DISABLE_HDIM64 else [])
  375. + (["-DFLASHATTENTION_DISABLE_HDIM96"] if DISABLE_HDIM96 else [])
  376. + (["-DFLASHATTENTION_DISABLE_HDIM128"] if DISABLE_HDIM128 else [])
  377. + (["-DFLASHATTENTION_DISABLE_HDIM192"] if DISABLE_HDIM192 else [])
  378. + (["-DFLASHATTENTION_DISABLE_HDIM256"] if DISABLE_HDIM256 else [])
  379. + (["-DFLASHATTENTION_DISABLE_SM8x"] if DISABLE_SM8x else [])
  380. + (["-DFLASHATTENTION_ENABLE_VCOLMAJOR"] if ENABLE_VCOLMAJOR else [])
  381. )
  382. DTYPE_FWD_SM80 = ["bf16"] + (["fp16"] if not DISABLE_FP16 else [])
  383. DTYPE_FWD_SM90 = ["bf16"] + (["fp16"] if not DISABLE_FP16 else []) + (["e4m3"] if not DISABLE_FP8 else [])
  384. DTYPE_BWD = ["bf16"] + (["fp16"] if not DISABLE_FP16 else [])
  385. HEAD_DIMENSIONS_BWD = (
  386. []
  387. + ([64] if not DISABLE_HDIM64 else [])
  388. + ([96] if not DISABLE_HDIM96 else [])
  389. + ([128] if not DISABLE_HDIM128 else [])
  390. + ([192] if not DISABLE_HDIM192 else [])
  391. + ([256] if not DISABLE_HDIM256 else [])
  392. )
  393. HEAD_DIMENSIONS_FWD = ["all"]
  394. HEAD_DIMENSIONS_FWD_SM80 = HEAD_DIMENSIONS_BWD
  395. SPLIT = [""] + (["_split"] if not DISABLE_SPLIT else [])
  396. PAGEDKV = [""] + (["_paged"] if not DISABLE_PAGEDKV else [])
  397. SOFTCAP = [""] + (["_softcap"] if not DISABLE_SOFTCAP else [])
  398. SOFTCAP_ALL = [""] if DISABLE_SOFTCAP else ["_softcapall"]
  399. PACKGQA = [""] + (["_packgqa"] if not DISABLE_PACKGQA else [])
  400. # We already always hard-code PackGQA=true for Sm8x
  401. sources_fwd_sm80 = [f"instantiations/flash_fwd_hdim{hdim}_{dtype}{paged}{split}{softcap}_sm80.cu"
  402. for hdim, dtype, split, paged, softcap in itertools.product(HEAD_DIMENSIONS_FWD_SM80, DTYPE_FWD_SM80, SPLIT, PAGEDKV, SOFTCAP_ALL)]
  403. # We already always hard-code PackGQA=true for Sm9x if PagedKV or Split
  404. sources_fwd_sm90 = [f"instantiations/flash_fwd_hdim{hdim}_{dtype}{paged}{split}{softcap}{packgqa}_sm90.cu"
  405. for hdim, dtype, split, paged, softcap, packgqa in itertools.product(HEAD_DIMENSIONS_FWD, DTYPE_FWD_SM90, SPLIT, PAGEDKV, SOFTCAP, PACKGQA)
  406. if not (packgqa and (paged or split))]
  407. sources_bwd_sm80 = [f"instantiations/flash_bwd_hdim{hdim}_{dtype}{softcap}_sm80.cu"
  408. for hdim, dtype, softcap in itertools.product(HEAD_DIMENSIONS_BWD, DTYPE_BWD, SOFTCAP)]
  409. sources_bwd_sm90 = [f"instantiations/flash_bwd_hdim{hdim}_{dtype}{softcap}_sm90.cu"
  410. for hdim, dtype, softcap in itertools.product(HEAD_DIMENSIONS_BWD, DTYPE_BWD, SOFTCAP_ALL)]
  411. if DISABLE_BACKWARD:
  412. sources_bwd_sm90 = []
  413. sources_bwd_sm80 = []
  414. sources = (
  415. ["flash_api.cpp"]
  416. + (sources_fwd_sm80 if not DISABLE_SM8x else []) + sources_fwd_sm90
  417. + (sources_bwd_sm80 if not DISABLE_SM8x else []) + sources_bwd_sm90
  418. )
  419. if not DISABLE_SPLIT:
  420. sources += ["flash_fwd_combine.cu"]
  421. nvcc_flags = [
  422. "-O3",
  423. "-std=c++17",
  424. "--ftemplate-backtrace-limit=0", # To debug template code
  425. "--use_fast_math",
  426. # "--keep",
  427. # "--ptxas-options=--verbose,--register-usage-level=5,--warn-on-local-memory-usage", # printing out number of registers
  428. "--resource-usage", # printing out number of registers
  429. # f"--split-compile={os.getenv('NVCC_THREADS', '4')}", # split-compile is faster
  430. "-lineinfo",
  431. "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", # Necessary for the WGMMA shapes that we use
  432. # "-DCUTLASS_ENABLE_GDC_FOR_SM90", # For PDL
  433. "-DCUTLASS_DEBUG_TRACE_LEVEL=0", # Can toggle for debugging
  434. "-DNDEBUG", # Important, otherwise performance is severely impacted
  435. ]
  436. if get_platform() == "win_amd64":
  437. nvcc_flags.extend(
  438. [
  439. "-D_USE_MATH_DEFINES", # for M_LN2
  440. "-Xcompiler=/Zc:__cplusplus", # sets __cplusplus correctly, CUTLASS_CONSTEXPR_IF_CXX17 needed for cutlass::gcd
  441. ]
  442. )
  443. include_dirs = [
  444. Path(this_dir),
  445. cutlass_dir / "include",
  446. ]
  447. ext_modules.append(
  448. CUDAExtension(
  449. name="flash_attn_3_cuda",
  450. sources=sources,
  451. extra_compile_args={
  452. "cxx": ["-O3", "-std=c++17"] + feature_args,
  453. "nvcc": nvcc_threads_args() + nvcc_flags + cc_flag + feature_args,
  454. },
  455. include_dirs=include_dirs,
  456. )
  457. )
  458. def get_package_version():
  459. with open(Path(this_dir) / "__init__.py", "r") as f:
  460. version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
  461. public_version = ast.literal_eval(version_match.group(1))
  462. local_version = os.environ.get("FLASH_ATTN_LOCAL_VERSION")
  463. if local_version:
  464. return f"{public_version}+{local_version}"
  465. else:
  466. return str(public_version)
  467. def get_wheel_url():
  468. # Determine the version numbers that will be used to determine the correct wheel
  469. # We're using the CUDA version used to build torch, not the one currently installed
  470. # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
  471. torch_cuda_version = parse(torch.version.cuda)
  472. torch_version_raw = parse(torch.__version__)
  473. # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
  474. # to save CI time. Minor versions should be compatible.
  475. torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
  476. python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
  477. platform_name = get_platform()
  478. package_version = get_package_version()
  479. # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
  480. cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
  481. torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
  482. cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
  483. # Determine wheel URL based on CUDA version, torch version, python version and OS
  484. wheel_filename = f"{PACKAGE_NAME}-{package_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
  485. wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{package_version}", wheel_name=wheel_filename)
  486. return wheel_url, wheel_filename
  487. class CachedWheelsCommand(_bdist_wheel):
  488. """
  489. The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
  490. find an existing wheel (which is currently the case for all installs). We use
  491. the environment parameters to detect whether there is already a pre-built version of a compatible
  492. wheel available and short-circuits the standard full build pipeline.
  493. """
  494. def run(self):
  495. if FORCE_BUILD:
  496. return super().run()
  497. wheel_url, wheel_filename = get_wheel_url()
  498. print("Guessing wheel URL: ", wheel_url)
  499. try:
  500. urllib.request.urlretrieve(wheel_url, wheel_filename)
  501. # Make the archive
  502. # Lifted from the root wheel processing command
  503. # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
  504. if not os.path.exists(self.dist_dir):
  505. os.makedirs(self.dist_dir)
  506. impl_tag, abi_tag, plat_tag = self.get_tag()
  507. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  508. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  509. print("Raw wheel path", wheel_path)
  510. shutil.move(wheel_filename, wheel_path)
  511. except urllib.error.HTTPError:
  512. print("Precompiled wheel not found. Building from source...")
  513. # If the wheel could not be downloaded, build from source
  514. super().run()
  515. setup(
  516. name=PACKAGE_NAME,
  517. version=get_package_version(),
  518. packages=find_packages(
  519. exclude=(
  520. "build",
  521. "csrc",
  522. "include",
  523. "tests",
  524. "dist",
  525. "docs",
  526. "benchmarks",
  527. )
  528. ),
  529. py_modules=["flash_attn_interface"],
  530. description="FlashAttention-3",
  531. long_description=long_description,
  532. long_description_content_type="text/markdown",
  533. classifiers=[
  534. "Programming Language :: Python :: 3",
  535. "License :: OSI Approved :: Apache Software License",
  536. "Operating System :: Unix",
  537. ],
  538. ext_modules=ext_modules,
  539. cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": BuildExtension}
  540. if ext_modules
  541. else {
  542. "bdist_wheel": CachedWheelsCommand,
  543. },
  544. python_requires=">=3.8",
  545. install_requires=[
  546. "torch",
  547. "einops",
  548. "packaging",
  549. "ninja",
  550. ],
  551. )