setup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 (
  11. BuildExtension, CUDAExtension, CUDA_HOME, ROCM_HOME)
  12. ROOT_DIR = os.path.dirname(__file__)
  13. MAIN_CUDA_VERSION = "12.1"
  14. # Supported NVIDIA GPU architectures.
  15. NVIDIA_SUPPORTED_ARCHS = {
  16. "6.0", "6.1", "7.0", "7.5", "8.0", "8.6", "8.9", "9.0"
  17. }
  18. ROCM_SUPPORTED_ARCHS = {
  19. "gfx90a", "gfx908", "gfx906", "gfx1030", "gfx1100"
  20. }
  21. def _is_hip() -> bool:
  22. return torch.version.hip is not None
  23. def _is_cuda() -> bool:
  24. return torch.version.cuda is not None
  25. # Compiler flags.
  26. CXX_FLAGS = ["-g", "-O2", "-std=c++17"]
  27. # TODO: Should we use -O3?
  28. NVCC_FLAGS = ["-O2", "-std=c++17"]
  29. if _is_hip():
  30. if ROCM_HOME is None:
  31. raise RuntimeError(
  32. "Cannot find ROCM_HOME. ROCm must be available to build the "
  33. "package.")
  34. NVCC_FLAGS += ["-DUSE_ROCM"]
  35. if _is_cuda() and CUDA_HOME is None:
  36. raise RuntimeError(
  37. "Cannot find CUDA_HOME. CUDA must be available to build the package.")
  38. ABI = 1 if torch._C._GLIBCXX_USE_CXX11_ABI else 0
  39. CXX_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  40. NVCC_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  41. def get_amdgpu_offload_arch():
  42. command = "/opt/rocm/llvm/bin/amdgpu-offload-arch"
  43. try:
  44. output = subprocess.check_output([command])
  45. return output.decode('utf-8').strip()
  46. except subprocess.CalledProcessError as e:
  47. error_message = f"Error: {e}"
  48. raise RuntimeError(error_message) from e
  49. except FileNotFoundError as e:
  50. # If the command is not found, print an error message
  51. error_message = f"The command {command} was not found."
  52. raise RuntimeError(error_message) from e
  53. return None
  54. def get_hipcc_rocm_version():
  55. # Run the hipcc --version command
  56. result = subprocess.run(['hipcc', '--version'],
  57. stdout=subprocess.PIPE,
  58. stderr=subprocess.STDOUT,
  59. text=True)
  60. # Check if the command was executed successfully
  61. if result.returncode != 0:
  62. print("Error running 'hipcc --version'")
  63. return None
  64. # Extract the version using a regular expression
  65. match = re.search(r'HIP version: (\S+)', result.stdout)
  66. if match:
  67. # Return the version string
  68. return match.group(1)
  69. else:
  70. print("Could not find HIP version in the output")
  71. return None
  72. def get_nvcc_cuda_version(cuda_dir: str) -> Version:
  73. """Get the CUDA version from nvcc.
  74. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  75. """
  76. nvcc_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"],
  77. universal_newlines=True)
  78. output = nvcc_output.split()
  79. release_idx = output.index("release") + 1
  80. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  81. return nvcc_cuda_version
  82. def get_torch_arch_list() -> Set[str]:
  83. # TORCH_CUDA_ARCH_LIST can have one or more architectures,
  84. # e.g. "8.0" or "7.5,8.0,8.6+PTX". Here, the "8.6+PTX" option asks the
  85. # compiler to additionally include PTX code that can be runtime-compiled
  86. # and executed on the 8.6 or newer architectures. While the PTX code will
  87. # not give the best performance on the newer architectures, it provides
  88. # forward compatibility.
  89. env_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", None)
  90. if env_arch_list is None:
  91. return set()
  92. # List are separated by ; or space.
  93. torch_arch_list = set(env_arch_list.replace(" ", ";").split(";"))
  94. if not torch_arch_list:
  95. return set()
  96. # Filter out the invalid architectures and print a warning.
  97. valid_archs = NVIDIA_SUPPORTED_ARCHS.union(
  98. {s + "+PTX"
  99. for s in NVIDIA_SUPPORTED_ARCHS})
  100. arch_list = torch_arch_list.intersection(valid_archs)
  101. # If none of the specified architectures are valid, raise an error.
  102. if not arch_list:
  103. raise RuntimeError(
  104. "None of the CUDA/ROCM architectures in `TORCH_CUDA_ARCH_LIST` "
  105. f"env variable ({env_arch_list}) is supported. "
  106. f"Supported CUDA architectures are: {valid_archs}.")
  107. invalid_arch_list = torch_arch_list - valid_archs
  108. if invalid_arch_list:
  109. warnings.warn(
  110. f"Unsupported CUDA/ROCM architectures ({invalid_arch_list}) are "
  111. "excluded from the `TORCH_CUDA_ARCH_LIST` env variable "
  112. f"({env_arch_list}). Supported CUDA/ROCM architectures are: "
  113. f"{valid_archs}.",
  114. stacklevel=2)
  115. return arch_list
  116. # First, check the TORCH_CUDA_ARCH_LIST environment variable.
  117. compute_capabilities = get_torch_arch_list()
  118. if _is_cuda() and not compute_capabilities:
  119. # If TORCH_CUDA_ARCH_LIST is not defined or empty, target all available
  120. # GPUs on the current machine.
  121. device_count = torch.cuda.device_count()
  122. for i in range(device_count):
  123. major, minor = torch.cuda.get_device_capability(i)
  124. if major < 6:
  125. raise RuntimeError(
  126. "GPUs with compute capability below 6.0 are not supported.")
  127. compute_capabilities.add(f"{major}.{minor}")
  128. if _is_cuda():
  129. nvcc_cuda_version = get_nvcc_cuda_version(CUDA_HOME)
  130. if not compute_capabilities:
  131. # If no GPU is specified nor available, add all supported architectures
  132. # based on the NVCC CUDA version.
  133. compute_capabilities = NVIDIA_SUPPORTED_ARCHS.copy()
  134. if nvcc_cuda_version < Version("11.1"):
  135. compute_capabilities.remove("8.6")
  136. if nvcc_cuda_version < Version("11.8"):
  137. compute_capabilities.remove("8.9")
  138. compute_capabilities.remove("9.0")
  139. # Validate the NVCC CUDA version.
  140. if nvcc_cuda_version < Version("11.0"):
  141. raise RuntimeError(
  142. "CUDA 11.0 or higher is required to build the package.")
  143. if (nvcc_cuda_version < Version("11.1")
  144. and any(cc.startswith("8.6") for cc in compute_capabilities)):
  145. raise RuntimeError(
  146. "CUDA 11.1 or higher is required for compute capability 8.6.")
  147. if nvcc_cuda_version < Version("11.8"):
  148. if any(cc.startswith("8.9") for cc in compute_capabilities):
  149. # CUDA 11.8 is required to generate the code targeting compute capability 8.9.
  150. # However, GPUs with compute capability 8.9 can also run the code generated by
  151. # the previous versions of CUDA 11 and targeting compute capability 8.0.
  152. # Therefore, if CUDA 11.8 is not available, we target compute capability 8.0
  153. # instead of 8.9.
  154. warnings.warn(
  155. "CUDA 11.8 or higher is required for compute capability 8.9. "
  156. "Targeting compute capability 8.0 instead.",
  157. stacklevel=2)
  158. compute_capabilities = set(cc for cc in compute_capabilities
  159. if not cc.startswith("8.9"))
  160. compute_capabilities.add("8.0+PTX")
  161. if any(cc.startswith("9.0") for cc in compute_capabilities):
  162. raise RuntimeError(
  163. "CUDA 11.8 or higher is required for compute capability 9.0.")
  164. # Add target compute capabilities to NVCC flags.
  165. for capability in compute_capabilities:
  166. num = capability[0] + capability[2]
  167. NVCC_FLAGS += ["-gencode", f"arch=compute_{num},code=sm_{num}"]
  168. if capability.endswith("+PTX"):
  169. NVCC_FLAGS += [
  170. "-gencode", f"arch=compute_{num},code=compute_{num}"
  171. ]
  172. # Use NVCC threads to parallelize the build.
  173. if nvcc_cuda_version >= Version("11.2"):
  174. num_threads = min(os.cpu_count(), 8)
  175. NVCC_FLAGS += ["--threads", str(num_threads)]
  176. elif _is_hip():
  177. amd_arch = get_amdgpu_offload_arch()
  178. if amd_arch not in ROCM_SUPPORTED_ARCHS:
  179. raise RuntimeError(
  180. f"Only the following arch is supported: {ROCM_SUPPORTED_ARCHS}"
  181. f"amdgpu_arch_found: {amd_arch}")
  182. ext_modules = []
  183. aphrodite_extension_sources = [
  184. "kernels/misc_kernels.cu",
  185. "kernels/cache_kernels.cu",
  186. "kernels/attention/attention_kernels.cu",
  187. "kernels/pos_encoding_kernels.cu",
  188. "kernels/activation_kernels.cu",
  189. "kernels/layernorm_kernels.cu",
  190. "kernels/quantization/squeezellm/quant_cuda_kernel.cu",
  191. "kernels/quantization/gptq/q_gemm.cu",
  192. "kernels/cuda_utils_kernels.cu",
  193. "kernels/pybind.cpp",
  194. ]
  195. if _is_cuda():
  196. aphrodite_extension_sources.append("kernels/quantization/awq/gemm_kernels.cu")
  197. aphrodite_extension = CUDAExtension(
  198. name="aphrodite._C",
  199. sources=aphrodite_extension_sources,
  200. extra_compile_args={
  201. "cxx": CXX_FLAGS,
  202. "nvcc": NVCC_FLAGS,
  203. },
  204. )
  205. ext_modules.append(aphrodite_extension)
  206. def get_path(*filepath) -> str:
  207. return os.path.join(ROOT_DIR, *filepath)
  208. def find_version(filepath: str) -> str:
  209. """Extract version information from the given filepath.
  210. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  211. """
  212. with open(filepath) as fp:
  213. version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
  214. fp.read(), re.M)
  215. if version_match:
  216. return version_match.group(1)
  217. raise RuntimeError("Unable to find version string.")
  218. def get_aphrodite_version() -> str:
  219. version = find_version(get_path("aphrodite-engine", "__init__.py"))
  220. if _is_hip():
  221. # get the HIP version
  222. hipcc_version = get_hipcc_rocm_version()
  223. if hipcc_version != MAIN_CUDA_VERSION:
  224. rocm_version_str = hipcc_version.replace(".", "")[:3]
  225. version += f"+rocm{rocm_version_str}"
  226. else:
  227. cuda_version = str(nvcc_cuda_version)
  228. # Split the version into numerical and suffix parts
  229. version_parts = version.split('-')
  230. version_num = version_parts[0]
  231. version_suffix = version_parts[1] if len(version_parts) > 1 else ''
  232. if cuda_version != MAIN_CUDA_VERSION:
  233. cuda_version_str = cuda_version.replace(".", "")[:3]
  234. version_num += f"+cu{cuda_version_str}"
  235. # Reassemble the version string with the suffix, if any
  236. version = version_num + ('-' + version_suffix if version_suffix else '')
  237. return version
  238. def read_readme() -> str:
  239. """Read the README file if present."""
  240. p = get_path("README.md")
  241. if os.path.isfile(p):
  242. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  243. else:
  244. return ""
  245. def get_requirements() -> List[str]:
  246. """Get Python package dependencies from requirements.txt."""
  247. if _is_hip():
  248. with open(get_path("requirements-rocm.txt")) as f:
  249. requirements = f.read().strip().split("\n")
  250. else:
  251. with open(get_path("requirements.txt")) as f:
  252. requirements = f.read().strip().split("\n")
  253. return requirements
  254. setuptools.setup(
  255. name="aphrodite-engine",
  256. version=find_version(get_path("aphrodite", "__init__.py")),
  257. author="PygmalionAI",
  258. license="AGPL 3.0",
  259. description="The inference engine for PygmalionAI models",
  260. long_description=read_readme(),
  261. long_description_content_type="text/markdown",
  262. url="https://github.com/PygmalionAI/aphrodite-engine",
  263. project_urls={
  264. "Homepage": "https://pygmalion.chat",
  265. "Documentation": "https://docs.pygmalion.chat",
  266. "GitHub": "https://github.com/PygmalionAI",
  267. "Huggingface": "https://huggingface.co/PygmalionAI",
  268. },
  269. classifiers=[
  270. "Programming Language :: Python :: 3.8",
  271. "Programming Language :: Python :: 3.9",
  272. "Programming Language :: Python :: 3.10",
  273. "Programming Language :: Python :: 3.11",
  274. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
  275. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  276. ],
  277. packages=setuptools.find_packages(exclude=("kernels", "examples",
  278. "tests")),
  279. python_requires=">=3.8",
  280. install_requires=get_requirements(),
  281. ext_modules=ext_modules,
  282. cmdclass={"build_ext": BuildExtension},
  283. package_data={"aphrodite-engine": ["aphrodite/endpoints/kobold/klite.embd",
  284. "py.typed"]},
  285. include_package_data=True,
  286. )