setup.py 15 KB

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