setup.py 15 KB

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