setup.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. has_cuda = torch.version.cuda is not None
  163. return (APHRODITE_TARGET_DEVICE == "cuda" and has_cuda
  164. and not (_is_neuron() or _is_tpu()))
  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_tpu() -> bool:
  177. return APHRODITE_TARGET_DEVICE == "tpu"
  178. def _is_cpu() -> bool:
  179. return APHRODITE_TARGET_DEVICE == "cpu"
  180. def _is_openvino() -> bool:
  181. return APHRODITE_TARGET_DEVICE == "openvino"
  182. def _is_xpu() -> bool:
  183. return APHRODITE_TARGET_DEVICE == "xpu"
  184. def _build_custom_ops() -> bool:
  185. return _is_cuda() or _is_hip() or _is_cpu()
  186. def _install_punica() -> bool:
  187. install_punica = bool(
  188. int(os.getenv("APHRODITE_INSTALL_PUNICA_KERNELS", "1")))
  189. device_count = torch.cuda.device_count()
  190. for i in range(device_count):
  191. major, minor = torch.cuda.get_device_capability(i)
  192. if major < 8:
  193. install_punica = False
  194. break
  195. return install_punica
  196. # def _install_hadamard() -> bool:
  197. # install_hadamard = bool(
  198. # int(os.getenv("APHRODITE_INSTALL_HADAMARD_KERNELS", "1")))
  199. # device_count = torch.cuda.device_count()
  200. # for i in range(device_count):
  201. # major, minor = torch.cuda.get_device_capability(i)
  202. # if major <= 6:
  203. # install_hadamard = False
  204. # break
  205. # return install_hadamard
  206. def get_hipcc_rocm_version():
  207. # Run the hipcc --version command
  208. result = subprocess.run(['hipcc', '--version'],
  209. stdout=subprocess.PIPE,
  210. stderr=subprocess.STDOUT,
  211. text=True)
  212. # Check if the command was executed successfully
  213. if result.returncode != 0:
  214. print("Error running 'hipcc --version'")
  215. return None
  216. # Extract the version using a regular expression
  217. match = re.search(r'HIP version: (\S+)', result.stdout)
  218. if match:
  219. # Return the version string
  220. return match.group(1)
  221. else:
  222. print("Could not find HIP version in the output")
  223. return None
  224. def get_neuronxcc_version():
  225. import sysconfig
  226. site_dir = sysconfig.get_paths()["purelib"]
  227. version_file = os.path.join(site_dir, "neuronxcc", "version",
  228. "__init__.py")
  229. # Check if the command was executed successfully
  230. with open(version_file, "rt") as fp:
  231. content = fp.read()
  232. # Extract the version using a regular expression
  233. match = re.search(r"__version__ = '(\S+)'", content)
  234. if match:
  235. # Return the version string
  236. return match.group(1)
  237. else:
  238. raise RuntimeError("Could not find HIP version in the output")
  239. def get_nvcc_cuda_version() -> Version:
  240. """Get the CUDA version from nvcc.
  241. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  242. """
  243. nvcc_output = subprocess.check_output([CUDA_HOME + "/bin/nvcc", "-V"],
  244. universal_newlines=True)
  245. output = nvcc_output.split()
  246. release_idx = output.index("release") + 1
  247. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  248. return nvcc_cuda_version
  249. def get_path(*filepath) -> str:
  250. return os.path.join(ROOT_DIR, *filepath)
  251. def find_version(filepath: str) -> str:
  252. """Extract version information from the given filepath.
  253. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  254. """
  255. with open(filepath) as fp:
  256. version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
  257. fp.read(), re.M)
  258. if version_match:
  259. return version_match.group(1)
  260. raise RuntimeError("Unable to find version string.")
  261. def get_aphrodite_version() -> str:
  262. version = find_version(get_path("aphrodite", "version.py"))
  263. if _is_cuda():
  264. cuda_version = str(get_nvcc_cuda_version())
  265. if cuda_version != MAIN_CUDA_VERSION:
  266. cuda_version_str = cuda_version.replace(".", "")[:3]
  267. version += f"+cu{cuda_version_str}"
  268. elif _is_hip():
  269. # Get the HIP version
  270. hipcc_version = get_hipcc_rocm_version()
  271. if hipcc_version != MAIN_CUDA_VERSION:
  272. rocm_version_str = hipcc_version.replace(".", "")[:3]
  273. version += f"+rocm{rocm_version_str}"
  274. elif _is_neuron():
  275. # Get the Neuron version
  276. neuron_version = str(get_neuronxcc_version())
  277. if neuron_version != MAIN_CUDA_VERSION:
  278. neuron_version_str = neuron_version.replace(".", "")[:3]
  279. version += f"+neuron{neuron_version_str}"
  280. elif _is_openvino():
  281. version += "+openvino"
  282. elif _is_tpu():
  283. version += "+tpu"
  284. elif _is_cpu():
  285. version += "+cpu"
  286. elif _is_xpu():
  287. version += "+xpu"
  288. else:
  289. raise RuntimeError("Unknown runtime environment, "
  290. "must be either CUDA, ROCm, CPU, or Neuron.")
  291. return version
  292. def read_readme() -> str:
  293. """Read the README file if present."""
  294. p = get_path("README.md")
  295. if os.path.isfile(p):
  296. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  297. else:
  298. return ""
  299. def get_requirements() -> List[str]:
  300. """Get Python package dependencies from requirements.txt."""
  301. def _read_requirements(filename: str) -> List[str]:
  302. with open(get_path(filename)) as f:
  303. requirements = f.read().strip().split("\n")
  304. resolved_requirements = []
  305. for line in requirements:
  306. if line.startswith("-r "):
  307. resolved_requirements += _read_requirements(line.split()[1])
  308. else:
  309. resolved_requirements.append(line)
  310. return resolved_requirements
  311. if _is_cuda():
  312. requirements = _read_requirements("requirements-cuda.txt")
  313. cuda_major, cuda_minor = torch.version.cuda.split(".")
  314. modified_requirements = []
  315. for req in requirements:
  316. if ("vllm-flash-attn" in req
  317. and not (cuda_major == "12" and cuda_minor == "1")):
  318. # vllm-flash-attn is built only for CUDA 12.1.
  319. # Skip for other versions.
  320. continue
  321. modified_requirements.append(req)
  322. elif _is_hip():
  323. requirements = _read_requirements("requirements-rocm.txt")
  324. elif _is_neuron():
  325. requirements = _read_requirements("requirements-neuron.txt")
  326. elif _is_openvino():
  327. requirements = _read_requirements("requirements-openvino.txt")
  328. elif _is_tpu():
  329. requirements = _read_requirements("requirements-tpu.txt")
  330. elif _is_cpu():
  331. requirements = _read_requirements("requirements-cpu.txt")
  332. elif _is_xpu():
  333. requirements = _read_requirements("requirements-xpu.txt")
  334. else:
  335. raise ValueError(
  336. "Unsupported platform, please use CUDA, ROCm, Neuron, CPU or "
  337. "OpenVINO.")
  338. return requirements
  339. ext_modules = []
  340. if _is_cuda() or _is_hip():
  341. ext_modules.append(CMakeExtension(name="aphrodite._moe_C"))
  342. if _build_custom_ops():
  343. ext_modules.append(CMakeExtension(name="aphrodite._C"))
  344. if _install_punica() and _is_cuda() or _is_hip():
  345. ext_modules.append(CMakeExtension(name="aphrodite._punica_C"))
  346. # TODO: see if hadamard kernels work with HIP
  347. # if _install_hadamard() and _is_cuda():
  348. # ext_modules.append(CMakeExtension(name="aphrodite._hadamard_C"))
  349. package_data = {
  350. "aphrodite": [
  351. "endpoints/kobold/klite.embd", "quantization/hadamard.safetensors",
  352. "py.typed", "modeling/layers/fused_moe/configs/*.json"
  353. ]
  354. }
  355. if os.environ.get("APHRODITE_USE_PRECOMPILED"):
  356. ext_modules = []
  357. package_data["aphrodite"].append("*.so")
  358. setup(
  359. name="aphrodite-engine",
  360. version=get_aphrodite_version(),
  361. author="PygmalionAI",
  362. license="AGPL 3.0",
  363. description="The inference engine for PygmalionAI models",
  364. long_description=read_readme(),
  365. long_description_content_type="text/markdown",
  366. url="https://github.com/PygmalionAI/aphrodite-engine",
  367. project_urls={
  368. "Homepage": "https://pygmalion.chat",
  369. "Documentation": "https://docs.pygmalion.chat",
  370. "GitHub": "https://github.com/PygmalionAI",
  371. "Huggingface": "https://huggingface.co/PygmalionAI",
  372. },
  373. classifiers=[
  374. "Programming Language :: Python :: 3.8",
  375. "Programming Language :: Python :: 3.9",
  376. "Programming Language :: Python :: 3.10",
  377. "Programming Language :: Python :: 3.11",
  378. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", # noqa: E501
  379. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  380. ],
  381. packages=find_packages(exclude=("kernels", "examples", "tests*")),
  382. python_requires=">=3.8",
  383. install_requires=get_requirements(),
  384. extras_require={
  385. "flash-attn": ["flash-attn==2.5.8"],
  386. "tensorizer": ["tensorizer>=2.9.0"],
  387. "ray": ["ray>=2.9"],
  388. },
  389. ext_modules=ext_modules,
  390. cmdclass={"build_ext": cmake_build_ext} if _build_custom_ops() else {},
  391. package_data=package_data,
  392. entry_points={
  393. "console_scripts": [
  394. "aphrodite=aphrodite.endpoints.cli:main",
  395. ],
  396. },
  397. )