setup.py 16 KB

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