setup.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # Adapted from https://github.com/NVIDIA/apex/blob/master/setup.py
  2. import sys
  3. import warnings
  4. import os
  5. from pathlib import Path
  6. from setuptools import setup, find_packages
  7. import subprocess
  8. import torch
  9. from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
  10. with open("README.md", "r", encoding="utf-8") as fh:
  11. long_description = fh.read()
  12. # ninja build does not work unless include_dirs are abs path
  13. this_dir = os.path.dirname(os.path.abspath(__file__))
  14. def get_cuda_bare_metal_version(cuda_dir):
  15. raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
  16. output = raw_output.split()
  17. release_idx = output.index("release") + 1
  18. release = output[release_idx].split(".")
  19. bare_metal_major = release[0]
  20. bare_metal_minor = release[1][0]
  21. return raw_output, bare_metal_major, bare_metal_minor
  22. def check_cuda_torch_binary_vs_bare_metal(cuda_dir):
  23. raw_output, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(cuda_dir)
  24. torch_binary_major = torch.version.cuda.split(".")[0]
  25. torch_binary_minor = torch.version.cuda.split(".")[1]
  26. print("\nCompiling cuda extensions with")
  27. print(raw_output + "from " + cuda_dir + "/bin\n")
  28. if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor):
  29. raise RuntimeError(
  30. "Cuda extensions are being compiled with a version of Cuda that does "
  31. "not match the version used to compile Pytorch binaries. "
  32. "Pytorch binaries were compiled with Cuda {}.\n".format(torch.version.cuda)
  33. + "In some cases, a minor-version mismatch will not cause later errors: "
  34. "https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. "
  35. "You can try commenting out this check (at your own risk)."
  36. )
  37. def raise_if_cuda_home_none(global_option: str) -> None:
  38. if CUDA_HOME is not None:
  39. return
  40. raise RuntimeError(
  41. f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
  42. "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
  43. "only images whose names contain 'devel' will provide nvcc."
  44. )
  45. def append_nvcc_threads(nvcc_extra_args):
  46. _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME)
  47. if int(bare_metal_major) >= 11 and int(bare_metal_minor) >= 2:
  48. return nvcc_extra_args + ["--threads", "4"]
  49. return nvcc_extra_args
  50. if not torch.cuda.is_available():
  51. # https://github.com/NVIDIA/apex/issues/486
  52. # Extension builds after https://github.com/pytorch/pytorch/pull/23408 attempt to query torch.cuda.get_device_capability(),
  53. # which will fail if you are compiling in an environment without visible GPUs (e.g. during an nvidia-docker build command).
  54. print(
  55. "\nWarning: Torch did not find available GPUs on this system.\n",
  56. "If your intention is to cross-compile, this is not an error.\n"
  57. "By default, We cross-compile for Volta (compute capability 7.0), "
  58. "Turing (compute capability 7.5),\n"
  59. "and, if the CUDA version is >= 11.0, Ampere (compute capability 8.0).\n"
  60. "If you wish to cross-compile for a single specific architecture,\n"
  61. 'export TORCH_CUDA_ARCH_LIST="compute capability" before running setup.py.\n',
  62. )
  63. if os.environ.get("TORCH_CUDA_ARCH_LIST", None) is None:
  64. _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME)
  65. if int(bare_metal_major) == 11:
  66. os.environ["TORCH_CUDA_ARCH_LIST"] = "7.0;7.5;8.0"
  67. if int(bare_metal_minor) > 0:
  68. os.environ["TORCH_CUDA_ARCH_LIST"] = "7.0;7.5;8.0;8.6"
  69. else:
  70. os.environ["TORCH_CUDA_ARCH_LIST"] = "7.0;7.5"
  71. print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
  72. TORCH_MAJOR = int(torch.__version__.split(".")[0])
  73. TORCH_MINOR = int(torch.__version__.split(".")[1])
  74. cmdclass = {}
  75. ext_modules = []
  76. # Check, if ATen/CUDAGeneratorImpl.h is found, otherwise use ATen/cuda/CUDAGeneratorImpl.h
  77. # See https://github.com/pytorch/pytorch/pull/70650
  78. generator_flag = []
  79. torch_dir = torch.__path__[0]
  80. if os.path.exists(os.path.join(torch_dir, "include", "ATen", "CUDAGeneratorImpl.h")):
  81. generator_flag = ["-DOLD_GENERATOR_PATH"]
  82. raise_if_cuda_home_none("flash_attn")
  83. # Check, if CUDA11 is installed for compute capability 8.0
  84. cc_flag = []
  85. _, bare_metal_major, _ = get_cuda_bare_metal_version(CUDA_HOME)
  86. if int(bare_metal_major) < 11:
  87. raise RuntimeError("FlashAttention is only supported on CUDA 11")
  88. cc_flag.append("-gencode")
  89. cc_flag.append("arch=compute_75,code=sm_75")
  90. cc_flag.append("-gencode")
  91. cc_flag.append("arch=compute_80,code=sm_80")
  92. subprocess.run(["git", "submodule", "update", "--init", "csrc/flash_attn/cutlass"])
  93. ext_modules.append(
  94. CUDAExtension(
  95. name="flash_attn_cuda",
  96. sources=[
  97. "csrc/flash_attn/fmha_api.cpp",
  98. "csrc/flash_attn/src/fmha_fprop_fp16_kernel.sm80.cu",
  99. "csrc/flash_attn/src/fmha_dgrad_fp16_kernel_loop.sm80.cu",
  100. "csrc/flash_attn/src/fmha_block_fprop_fp16_kernel.sm80.cu",
  101. "csrc/flash_attn/src/fmha_block_dgrad_fp16_kernel_loop.sm80.cu",
  102. ],
  103. extra_compile_args={
  104. "cxx": ["-O3", "-std=c++17"] + generator_flag,
  105. "nvcc": append_nvcc_threads(
  106. [
  107. "-O3",
  108. "-std=c++17",
  109. "-U__CUDA_NO_HALF_OPERATORS__",
  110. "-U__CUDA_NO_HALF_CONVERSIONS__",
  111. "--expt-relaxed-constexpr",
  112. "--expt-extended-lambda",
  113. "--use_fast_math",
  114. "--ptxas-options=-v",
  115. "-lineinfo"
  116. ]
  117. + generator_flag
  118. + cc_flag
  119. ),
  120. },
  121. include_dirs=[
  122. Path(this_dir) / 'csrc' / 'flash_attn',
  123. Path(this_dir) / 'csrc' / 'flash_attn' / 'src',
  124. Path(this_dir) / 'csrc' / 'flash_attn' / 'cutlass' / 'include',
  125. ],
  126. )
  127. )
  128. setup(
  129. name="flash_attn",
  130. version="0.1",
  131. packages=find_packages(
  132. exclude=("build", "csrc", "include", "tests", "dist", "docs", "benchmarks", "flash_attn.egg-info",)
  133. ),
  134. author="Tri Dao",
  135. author_email="trid@stanford.edu",
  136. description="Flash Attention: Fast and Memory-Efficient Exact Attention",
  137. long_description=long_description,
  138. long_description_content_type="text/markdown",
  139. url="https://github.com/HazyResearch/flash-attention",
  140. classifiers=[
  141. "Programming Language :: Python :: 3",
  142. "License :: OSI Approved :: Apache Software License",
  143. "Operating System :: Unix",
  144. ],
  145. ext_modules=ext_modules,
  146. cmdclass={"build_ext": BuildExtension} if ext_modules else {},
  147. python_requires=">=3.7",
  148. install_requires=[
  149. "torch",
  150. "einops",
  151. ],
  152. )