setup.py 17 KB

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