setup.py 17 KB

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