setup.py 17 KB

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