setup.py 17 KB

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