setup.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import io
  2. import os
  3. import re
  4. import subprocess
  5. from typing import List, Set
  6. import warnings
  7. from packaging.version import parse, Version
  8. import setuptools
  9. import torch
  10. from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CUDA_HOME
  11. ROOT_DIR = os.path.dirname(__file__)
  12. # Supported NVIDIA GPU architectures.
  13. SUPPORTED_ARCHS = {"6.0", "6.1", "6.5", "7.0", "7.5", "8.0", "8.6", "8.9", "9.0"}
  14. # Compiler flags.
  15. CXX_FLAGS = ["-g", "-O2", "-std=c++17"]
  16. # TODO: Should we use -O3?
  17. NVCC_FLAGS = ["-O2", "-std=c++17"]
  18. ABI = 1 if torch._C._GLIBCXX_USE_CXX11_ABI else 0
  19. CXX_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  20. NVCC_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  21. if CUDA_HOME is None:
  22. raise RuntimeError(
  23. "Cannot find CUDA_HOME. CUDA must be available to build the package.")
  24. def get_nvcc_cuda_version(cuda_dir: str) -> Version:
  25. """Get the CUDA version from nvcc.
  26. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  27. """
  28. nvcc_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"],
  29. universal_newlines=True)
  30. output = nvcc_output.split()
  31. release_idx = output.index("release") + 1
  32. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  33. return nvcc_cuda_version
  34. def get_torch_arch_list() -> Set[str]:
  35. # TORCH_CUDA_ARCH_LIST can have one or more architectures,
  36. # e.g. "8.0" or "7.5,8.0,8.6+PTX". Here, the "8.6+PTX" option asks the
  37. # compiler to additionally include PTX code that can be runtime-compiled
  38. # and executed on the 8.6 or newer architectures. While the PTX code will
  39. # not give the best performance on the newer architectures, it provides
  40. # forward compatibility.
  41. env_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", None)
  42. if env_arch_list is None:
  43. return set()
  44. # List are separated by ; or space.
  45. torch_arch_list = set(env_arch_list.replace(" ", ";").split(";"))
  46. if not torch_arch_list:
  47. return set()
  48. # Filter out the invalid architectures and print a warning.
  49. valid_archs = SUPPORTED_ARCHS.union({s + "+PTX" for s in SUPPORTED_ARCHS})
  50. arch_list = torch_arch_list.intersection(valid_archs)
  51. # If none of the specified architectures are valid, raise an error.
  52. if not arch_list:
  53. raise RuntimeError(
  54. "None of the CUDA architectures in `TORCH_CUDA_ARCH_LIST` env "
  55. f"variable ({env_arch_list}) is supported. "
  56. f"Supported CUDA architectures are: {valid_archs}.")
  57. invalid_arch_list = torch_arch_list - valid_archs
  58. if invalid_arch_list:
  59. warnings.warn(
  60. f"Unsupported CUDA architectures ({invalid_arch_list}) are "
  61. "excluded from the `TORCH_CUDA_ARCH_LIST` env variable "
  62. f"({env_arch_list}). Supported CUDA architectures are: "
  63. f"{valid_archs}.")
  64. return arch_list
  65. # First, check the TORCH_CUDA_ARCH_LIST environment variable.
  66. compute_capabilities = get_torch_arch_list()
  67. if not compute_capabilities:
  68. # If TORCH_CUDA_ARCH_LIST is not defined or empty, target all available
  69. # GPUs on the current machine.
  70. device_count = torch.cuda.device_count()
  71. for i in range(device_count):
  72. major, minor = torch.cuda.get_device_capability(i)
  73. if major < 6:
  74. raise RuntimeError(
  75. "GPUs with compute capability below 6.0 are not supported.")
  76. compute_capabilities.add(f"{major}.{minor}")
  77. nvcc_cuda_version = get_nvcc_cuda_version(CUDA_HOME)
  78. if not compute_capabilities:
  79. # If no GPU is specified nor available, add all supported architectures
  80. # based on the NVCC CUDA version.
  81. compute_capabilities = SUPPORTED_ARCHS.copy()
  82. if nvcc_cuda_version < Version("11.1"):
  83. compute_capabilities.remove("8.6")
  84. if nvcc_cuda_version < Version("11.8"):
  85. compute_capabilities.remove("8.9")
  86. compute_capabilities.remove("9.0")
  87. # Validate the NVCC CUDA version.
  88. if nvcc_cuda_version < Version("11.0"):
  89. raise RuntimeError("CUDA 11.0 or higher is required to build the package.")
  90. if nvcc_cuda_version < Version("11.1"):
  91. if any(cc.startswith("8.6") for cc in compute_capabilities):
  92. raise RuntimeError(
  93. "CUDA 11.1 or higher is required for compute capability 8.6.")
  94. if nvcc_cuda_version < Version("11.8"):
  95. if any(cc.startswith("8.9") for cc in compute_capabilities):
  96. # CUDA 11.8 is required to generate the code targeting compute capability 8.9.
  97. # However, GPUs with compute capability 8.9 can also run the code generated by
  98. # the previous versions of CUDA 11 and targeting compute capability 8.0.
  99. # Therefore, if CUDA 11.8 is not available, we target compute capability 8.0
  100. # instead of 8.9.
  101. warnings.warn(
  102. "CUDA 11.8 or higher is required for compute capability 8.9. "
  103. "Targeting compute capability 8.0 instead.")
  104. compute_capabilities = set(cc for cc in compute_capabilities
  105. if not cc.startswith("8.9"))
  106. compute_capabilities.add("8.0+PTX")
  107. if any(cc.startswith("9.0") for cc in compute_capabilities):
  108. raise RuntimeError(
  109. "CUDA 11.8 or higher is required for compute capability 9.0.")
  110. # Add target compute capabilities to NVCC flags.
  111. for capability in compute_capabilities:
  112. num = capability[0] + capability[2]
  113. NVCC_FLAGS += ["-gencode", f"arch=compute_{num},code=sm_{num}"]
  114. if capability.endswith("+PTX"):
  115. NVCC_FLAGS += ["-gencode", f"arch=compute_{num},code=compute_{num}"]
  116. # Use NVCC threads to parallelize the build.
  117. if nvcc_cuda_version >= Version("11.2"):
  118. num_threads = min(os.cpu_count(), 8)
  119. NVCC_FLAGS += ["--threads", str(num_threads)]
  120. ext_modules = []
  121. # Cache operations.
  122. cache_extension = CUDAExtension(
  123. name="aphrodite.cache_ops",
  124. sources=["kernels/cache.cpp", "kernels/cache_kernels.cu"],
  125. extra_compile_args={
  126. "cxx": CXX_FLAGS,
  127. "nvcc": NVCC_FLAGS,
  128. },
  129. )
  130. ext_modules.append(cache_extension)
  131. # Attention kernels.
  132. attention_extension = CUDAExtension(
  133. name="aphrodite.attention_ops",
  134. sources=["kernels/attention.cpp", "kernels/attention/attention_kernels.cu"],
  135. extra_compile_args={
  136. "cxx": CXX_FLAGS,
  137. "nvcc": NVCC_FLAGS,
  138. },
  139. )
  140. ext_modules.append(attention_extension)
  141. # Positional encoding kernels.
  142. positional_encoding_extension = CUDAExtension(
  143. name="aphrodite.pos_encoding_ops",
  144. sources=["kernels/pos_encoding.cpp", "kernels/pos_encoding_kernels.cu"],
  145. extra_compile_args={
  146. "cxx": CXX_FLAGS,
  147. "nvcc": NVCC_FLAGS,
  148. },
  149. )
  150. ext_modules.append(positional_encoding_extension)
  151. # Layer normalization kernels.
  152. layernorm_extension = CUDAExtension(
  153. name="aphrodite.layernorm_ops",
  154. sources=["kernels/layernorm.cpp", "kernels/layernorm_kernels.cu"],
  155. extra_compile_args={
  156. "cxx": CXX_FLAGS,
  157. "nvcc": NVCC_FLAGS,
  158. },
  159. )
  160. ext_modules.append(layernorm_extension)
  161. # Activation kernels.
  162. activation_extension = CUDAExtension(
  163. name="aphrodite.activation_ops",
  164. sources=["kernels/activation.cpp", "kernels/activation_kernels.cu"],
  165. extra_compile_args={
  166. "cxx": CXX_FLAGS,
  167. "nvcc": NVCC_FLAGS,
  168. },
  169. )
  170. ext_modules.append(activation_extension)
  171. # Quantization kernels.
  172. quantization_extension = CUDAExtension(
  173. name="aphrodite.quantization_ops",
  174. sources=[
  175. "kernels/quantization.cpp", "kernels/quantization/awq/gemm_kernels.cu",
  176. "kernels/quantization/gptq/exllama_ext.cpp",
  177. "kernels/quantization/gptq/cuda_buffers.cu",
  178. "kernels/quantization/gptq/cuda_func/column_remap.cu",
  179. "kernels/quantization/gptq/cuda_func/q4_matmul.cu",
  180. "kernels/quantization/gptq/cuda_func/q4_matrix.cu",
  181. "kernels/quantization/gptq/alt_matmul_kernel.cu",
  182. "kernels/quantization/gptq/alt_matmul.cpp"
  183. ],
  184. extra_compile_args={
  185. "cxx": CXX_FLAGS,
  186. "nvcc": NVCC_FLAGS,
  187. },
  188. )
  189. ext_modules.append(quantization_extension)
  190. # Misc. CUDA utils.
  191. cuda_utils_extension = CUDAExtension(
  192. name="aphrodite.cuda_utils",
  193. sources=["kernels/cuda_utils.cpp", "kernels/cuda_utils_kernels.cu"],
  194. extra_compile_args={
  195. "cxx": CXX_FLAGS,
  196. "nvcc": NVCC_FLAGS,
  197. },
  198. )
  199. ext_modules.append(cuda_utils_extension)
  200. def get_path(*filepath) -> str:
  201. return os.path.join(ROOT_DIR, *filepath)
  202. def find_version(filepath: str):
  203. """Extract version information from the given filepath.
  204. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  205. """
  206. with open(filepath) as fp:
  207. version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
  208. fp.read(), re.M)
  209. if version_match:
  210. return version_match.group(1)
  211. raise RuntimeError("Unable to find version string.")
  212. def read_readme() -> str:
  213. """Read the README file."""
  214. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  215. def get_requirements() -> List[str]:
  216. """Get Python package dependencies from requirements.txt."""
  217. with open(get_path("requirements.txt")) as f:
  218. requirements = f.read().strip().split("\n")
  219. return requirements
  220. setuptools.setup(
  221. name="aphrodite-engine",
  222. version=find_version(get_path("aphrodite", "__init__.py")),
  223. author="PygmalionAI",
  224. license="AGPL 3.0",
  225. description="The inference engine for PygmalionAI models",
  226. long_description=read_readme(),
  227. long_description_content_type="text/markdown",
  228. url="https://github.com/PygmalionAI/aphrodite-engine",
  229. project_urls={
  230. "Homepage": "https://pygmalion.chat",
  231. "Documentation": "https://docs.pygmalion.chat",
  232. "GitHub": "https://github.com/PygmalionAI",
  233. "Huggingface": "https://huggingface.co/PygmalionAI",
  234. },
  235. classifiers=[
  236. "Programming Language :: Python :: 3.8",
  237. "Programming Language :: Python :: 3.9",
  238. "Programming Language :: Python :: 3.10",
  239. "Programming Language :: Python :: 3.11",
  240. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
  241. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  242. ],
  243. packages=setuptools.find_packages(
  244. exclude=("kernels","examples", "tests")),
  245. python_requires=">=3.8",
  246. install_requires=get_requirements(),
  247. ext_modules=ext_modules,
  248. cmdclass={"build_ext": BuildExtension},
  249. )