setup.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import io
  2. import logging
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from shutil import which
  8. from typing import List
  9. import torch
  10. from packaging.version import Version, parse
  11. from setuptools import Extension, find_packages, setup
  12. from setuptools.command.build_ext import build_ext
  13. from torch.utils.cpp_extension import CUDA_HOME
  14. ROOT_DIR = os.path.dirname(__file__)
  15. logger = logging.getLogger(__name__)
  16. # Target device of Aphrodite, supporting [cuda (by default), rocm, neuron, cpu]
  17. APHRODITE_TARGET_DEVICE = os.getenv("APHRODITE_TARGET_DEVICE", "cuda")
  18. # Aphrodite only supports Linux platform
  19. assert sys.platform.startswith(
  20. "linux"), "Aphrodite only supports Linux platform (including WSL)."
  21. MAIN_CUDA_VERSION = "12.1"
  22. def is_sccache_available() -> bool:
  23. return which("sccache") is not None
  24. def is_ccache_available() -> bool:
  25. return which("ccache") is not None
  26. def is_ninja_available() -> bool:
  27. return which("ninja") is not None
  28. def remove_prefix(text, prefix):
  29. if text.startswith(prefix):
  30. return text[len(prefix):]
  31. return text
  32. class CMakeExtension(Extension):
  33. def __init__(self, name: str, cmake_lists_dir: str = '.', **kwa) -> None:
  34. super().__init__(name, sources=[], **kwa)
  35. self.cmake_lists_dir = os.path.abspath(cmake_lists_dir)
  36. class cmake_build_ext(build_ext):
  37. # A dict of extension directories that have been configured.
  38. did_config = {}
  39. #
  40. # Determine number of compilation jobs and optionally nvcc compile threads.
  41. #
  42. def compute_num_jobs(self):
  43. # `num_jobs` is either the value of the MAX_JOBS environment variable
  44. # (if defined) or the number of CPUs available.
  45. num_jobs = os.environ.get("MAX_JOBS", None)
  46. if num_jobs is not None:
  47. num_jobs = int(num_jobs)
  48. logger.info(f"Using MAX_JOBS={num_jobs} as the number of jobs.")
  49. else:
  50. try:
  51. # os.sched_getaffinity() isn't universally available, so fall
  52. # back to os.cpu_count() if we get an error here.
  53. num_jobs = len(os.sched_getaffinity(0))
  54. except AttributeError:
  55. num_jobs = os.cpu_count()
  56. nvcc_threads = None
  57. if _is_cuda() and get_nvcc_cuda_version() >= Version("11.2"):
  58. # `nvcc_threads` is either the value of the NVCC_THREADS
  59. # environment variable (if defined) or 1.
  60. # when it is set, we reduce `num_jobs` to avoid
  61. # overloading the system.
  62. nvcc_threads = os.getenv("NVCC_THREADS", None)
  63. if nvcc_threads is not None:
  64. nvcc_threads = int(nvcc_threads)
  65. logger.info(f"Using NVCC_THREADS={nvcc_threads} as the number"
  66. " of nvcc threads.")
  67. else:
  68. nvcc_threads = 1
  69. num_jobs = max(1, num_jobs // nvcc_threads)
  70. return num_jobs, nvcc_threads
  71. #
  72. # Perform cmake configuration for a single extension.
  73. #
  74. def configure(self, ext: CMakeExtension) -> None:
  75. # If we've already configured using the CMakeLists.txt for
  76. # this extension, exit early.
  77. if ext.cmake_lists_dir in cmake_build_ext.did_config:
  78. return
  79. cmake_build_ext.did_config[ext.cmake_lists_dir] = True
  80. # Select the build type.
  81. # Note: optimization level + debug info are set by the build type
  82. default_cfg = "Debug" if self.debug else "RelWithDebInfo"
  83. cfg = os.getenv("CMAKE_BUILD_TYPE", default_cfg)
  84. # where .so files will be written, should be the same for all extensions
  85. # that use the same CMakeLists.txt.
  86. outdir = os.path.abspath(
  87. os.path.dirname(self.get_ext_fullpath(ext.name)))
  88. cmake_args = [
  89. '-DCMAKE_BUILD_TYPE={}'.format(cfg),
  90. '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={}'.format(outdir),
  91. '-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}'.format(self.build_temp),
  92. '-DAPHRODITE_TARGET_DEVICE={}'.format(APHRODITE_TARGET_DEVICE),
  93. ]
  94. verbose = bool(int(os.getenv('VERBOSE', '0')))
  95. if verbose:
  96. cmake_args += ['-DCMAKE_VERBOSE_MAKEFILE=ON']
  97. if is_sccache_available():
  98. cmake_args += [
  99. '-DCMAKE_CXX_COMPILER_LAUNCHER=sccache',
  100. '-DCMAKE_CUDA_COMPILER_LAUNCHER=sccache',
  101. ]
  102. elif is_ccache_available():
  103. cmake_args += [
  104. '-DCMAKE_CXX_COMPILER_LAUNCHER=ccache',
  105. '-DCMAKE_CUDA_COMPILER_LAUNCHER=ccache',
  106. ]
  107. # Pass the python executable to cmake so it can find an exact
  108. # match.
  109. cmake_args += [
  110. '-DAPHRODITE_PYTHON_EXECUTABLE={}'.format(sys.executable)
  111. ]
  112. if _install_quants():
  113. cmake_args += ['-DAPHRODITE_INSTALL_QUANT_KERNELS=ON']
  114. if _install_punica():
  115. cmake_args += ['-DAPHRODITE_INSTALL_PUNICA_KERNELS=ON']
  116. if _install_hadamard():
  117. cmake_args += ['-DAPHRODITE_INSTALL_HADAMARD_KERNELS=ON']
  118. #
  119. # Setup parallelism and build tool
  120. #
  121. num_jobs, nvcc_threads = self.compute_num_jobs()
  122. if nvcc_threads:
  123. cmake_args += ['-DNVCC_THREADS={}'.format(nvcc_threads)]
  124. if is_ninja_available():
  125. build_tool = ['-G', 'Ninja']
  126. cmake_args += [
  127. '-DCMAKE_JOB_POOL_COMPILE:STRING=compile',
  128. '-DCMAKE_JOB_POOLS:STRING=compile={}'.format(num_jobs),
  129. ]
  130. else:
  131. # Default build tool to whatever cmake picks.
  132. build_tool = []
  133. subprocess.check_call(
  134. ['cmake', ext.cmake_lists_dir, *build_tool, *cmake_args],
  135. cwd=self.build_temp)
  136. def build_extensions(self) -> None:
  137. # Ensure that CMake is present and working
  138. try:
  139. subprocess.check_output(['cmake', '--version'])
  140. except OSError as e:
  141. raise RuntimeError('Cannot find CMake executable') from e
  142. # Create build directory if it does not exist.
  143. if not os.path.exists(self.build_temp):
  144. os.makedirs(self.build_temp)
  145. # Build all the extensions
  146. for ext in self.extensions:
  147. self.configure(ext)
  148. ext_target_name = remove_prefix(ext.name, "aphrodite.")
  149. num_jobs, _ = self.compute_num_jobs()
  150. build_args = [
  151. '--build', '.', '--target', ext_target_name, '-j',
  152. str(num_jobs)
  153. ]
  154. subprocess.check_call(['cmake', *build_args], cwd=self.build_temp)
  155. def _is_cuda() -> bool:
  156. return APHRODITE_TARGET_DEVICE == "cuda" \
  157. and torch.version.cuda is not None \
  158. and not _is_neuron()
  159. def _is_hip() -> bool:
  160. return (APHRODITE_TARGET_DEVICE == "cuda"
  161. or APHRODITE_TARGET_DEVICE == "rocm") \
  162. and torch.version.hip is not None
  163. def _is_neuron() -> bool:
  164. torch_neuronx_installed = True
  165. try:
  166. subprocess.run(["neuron-ls"], capture_output=True, check=True)
  167. except (FileNotFoundError, PermissionError, subprocess.CalledProcessError):
  168. torch_neuronx_installed = False
  169. return torch_neuronx_installed
  170. def _is_cpu() -> bool:
  171. return APHRODITE_TARGET_DEVICE == "cpu"
  172. def _install_quants() -> bool:
  173. install_quants = bool(
  174. int(os.getenv("APHRODITE_INSTALL_QUANT_KERNELS", "1")))
  175. device_count = torch.cuda.device_count()
  176. for i in range(device_count):
  177. major, minor = torch.cuda.get_device_capability(i)
  178. if major < 6:
  179. install_quants = False
  180. break
  181. return install_quants
  182. def _install_punica() -> bool:
  183. install_punica = bool(
  184. int(os.getenv("APHRODITE_INSTALL_PUNICA_KERNELS", "1")))
  185. device_count = torch.cuda.device_count()
  186. for i in range(device_count):
  187. major, minor = torch.cuda.get_device_capability(i)
  188. if major <= 8:
  189. install_punica = False
  190. break
  191. return install_punica
  192. def _install_hadamard() -> bool:
  193. install_hadamard = bool(
  194. int(os.getenv("APHRODITE_INSTALL_HADAMARD_KERNELS", "1")))
  195. device_count = torch.cuda.device_count()
  196. for i in range(device_count):
  197. major, minor = torch.cuda.get_device_capability(i)
  198. if major <= 6:
  199. install_hadamard = False
  200. break
  201. return install_hadamard
  202. def get_hipcc_rocm_version():
  203. # Run the hipcc --version command
  204. result = subprocess.run(['hipcc', '--version'],
  205. stdout=subprocess.PIPE,
  206. stderr=subprocess.STDOUT,
  207. text=True)
  208. # Check if the command was executed successfully
  209. if result.returncode != 0:
  210. print("Error running 'hipcc --version'")
  211. return None
  212. # Extract the version using a regular expression
  213. match = re.search(r'HIP version: (\S+)', result.stdout)
  214. if match:
  215. # Return the version string
  216. return match.group(1)
  217. else:
  218. print("Could not find HIP version in the output")
  219. return None
  220. def get_neuronxcc_version():
  221. import sysconfig
  222. site_dir = sysconfig.get_paths()["purelib"]
  223. version_file = os.path.join(site_dir, "neuronxcc", "version",
  224. "__init__.py")
  225. # Check if the command was executed successfully
  226. with open(version_file, "rt") as fp:
  227. content = fp.read()
  228. # Extract the version using a regular expression
  229. match = re.search(r"__version__ = '(\S+)'", content)
  230. if match:
  231. # Return the version string
  232. return match.group(1)
  233. else:
  234. raise RuntimeError("Could not find HIP version in the output")
  235. def get_nvcc_cuda_version() -> Version:
  236. """Get the CUDA version from nvcc.
  237. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  238. """
  239. nvcc_output = subprocess.check_output([CUDA_HOME + "/bin/nvcc", "-V"],
  240. universal_newlines=True)
  241. output = nvcc_output.split()
  242. release_idx = output.index("release") + 1
  243. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  244. return nvcc_cuda_version
  245. def get_path(*filepath) -> str:
  246. return os.path.join(ROOT_DIR, *filepath)
  247. def find_version(filepath: str) -> str:
  248. """Extract version information from the given filepath.
  249. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  250. """
  251. with open(filepath) as fp:
  252. version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
  253. fp.read(), re.M)
  254. if version_match:
  255. return version_match.group(1)
  256. raise RuntimeError("Unable to find version string.")
  257. def get_aphrodite_version() -> str:
  258. version = find_version(get_path("aphrodite", "__init__.py"))
  259. if _is_cuda():
  260. cuda_version = str(get_nvcc_cuda_version())
  261. if cuda_version != MAIN_CUDA_VERSION:
  262. cuda_version_str = cuda_version.replace(".", "")[:3]
  263. version += f"+cu{cuda_version_str}"
  264. elif _is_hip():
  265. # Get the HIP version
  266. hipcc_version = get_hipcc_rocm_version()
  267. if hipcc_version != MAIN_CUDA_VERSION:
  268. rocm_version_str = hipcc_version.replace(".", "")[:3]
  269. version += f"+rocm{rocm_version_str}"
  270. elif _is_neuron():
  271. # Get the Neuron version
  272. neuron_version = str(get_neuronxcc_version())
  273. if neuron_version != MAIN_CUDA_VERSION:
  274. neuron_version_str = neuron_version.replace(".", "")[:3]
  275. version += f"+neuron{neuron_version_str}"
  276. elif _is_cpu():
  277. version += "+cpu"
  278. else:
  279. raise RuntimeError("Unknown runtime environment, "
  280. "must be either CUDA, ROCm, CPU, or Neuron.")
  281. return version
  282. def read_readme() -> str:
  283. """Read the README file if present."""
  284. p = get_path("README.md")
  285. if os.path.isfile(p):
  286. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  287. else:
  288. return ""
  289. def get_requirements() -> List[str]:
  290. """Get Python package dependencies from requirements.txt."""
  291. def _read_requirements(filename: str) -> List[str]:
  292. with open(get_path(filename)) as f:
  293. requirements = f.read().strip().split("\n")
  294. resolved_requirements = []
  295. for line in requirements:
  296. if line.startswith("-r "):
  297. resolved_requirements += _read_requirements(line.split()[1])
  298. else:
  299. resolved_requirements.append(line)
  300. return resolved_requirements
  301. if _is_cuda():
  302. requirements = _read_requirements("requirements-cuda.txt")
  303. elif _is_hip():
  304. requirements = _read_requirements("requirements-rocm.txt")
  305. elif _is_neuron():
  306. requirements = _read_requirements("requirements-neuron.txt")
  307. elif _is_cpu():
  308. requirements = _read_requirements("requirements-cpu.txt")
  309. else:
  310. raise ValueError(
  311. "Unsupported platform, please use CUDA, ROCm, Neuron, or CPU.")
  312. return requirements
  313. ext_modules = []
  314. if _is_cuda():
  315. ext_modules.append(CMakeExtension(name="aphrodite._moe_C"))
  316. if _install_quants():
  317. ext_modules.append(CMakeExtension(name="aphrodite._quant_C"))
  318. if _install_punica():
  319. ext_modules.append(CMakeExtension(name="aphrodite._punica_C"))
  320. if _install_hadamard():
  321. ext_modules.append(CMakeExtension(name="aphrodite._hadamard_C"))
  322. if not _is_neuron():
  323. ext_modules.append(CMakeExtension(name="aphrodite._C"))
  324. if _install_quants():
  325. ext_modules.append(CMakeExtension(name="aphrodite._quant_C"))
  326. package_data = {
  327. "aphrodite": [
  328. "endpoints/kobold/klite.embd", "quantization/hadamard.safetensors",
  329. "py.typed", "modeling/layers/fused_moe/configs/*.json"
  330. ]
  331. }
  332. if os.environ.get("APHRODITE_USE_PRECOMPILED"):
  333. package_data["aphrodite"].append("*.so")
  334. setup(
  335. name="aphrodite-engine",
  336. version=get_aphrodite_version(),
  337. author="PygmalionAI",
  338. license="AGPL 3.0",
  339. description="The inference engine for PygmalionAI models",
  340. long_description=read_readme(),
  341. long_description_content_type="text/markdown",
  342. url="https://github.com/PygmalionAI/aphrodite-engine",
  343. project_urls={
  344. "Homepage": "https://pygmalion.chat",
  345. "Documentation": "https://docs.pygmalion.chat",
  346. "GitHub": "https://github.com/PygmalionAI",
  347. "Huggingface": "https://huggingface.co/PygmalionAI",
  348. },
  349. classifiers=[
  350. "Programming Language :: Python :: 3.8",
  351. "Programming Language :: Python :: 3.9",
  352. "Programming Language :: Python :: 3.10",
  353. "Programming Language :: Python :: 3.11",
  354. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", # noqa: E501
  355. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  356. ],
  357. packages=find_packages(exclude=("kernels", "examples", "tests")),
  358. python_requires=">=3.8",
  359. install_requires=get_requirements(),
  360. extras_require={"flash-attn": [
  361. "flash-attn==2.5.8",
  362. ]},
  363. ext_modules=ext_modules,
  364. cmdclass={"build_ext": cmake_build_ext} if not _is_neuron() else {},
  365. package_data=package_data,
  366. entry_points={
  367. "console_scripts": [
  368. "aphrodite=aphrodite.endpoints.cli:main",
  369. ],
  370. },
  371. )