setup.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import contextlib
  2. import io
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from typing import List, Set
  8. import warnings
  9. from pathlib import Path
  10. from packaging.version import parse, Version
  11. import setuptools
  12. import torch
  13. import torch.utils.cpp_extension as torch_cpp_ext
  14. from torch.utils.cpp_extension import (BuildExtension, CUDAExtension,
  15. CUDA_HOME, ROCM_HOME)
  16. ROOT_DIR = os.path.dirname(__file__)
  17. MAIN_CUDA_VERSION = "12.1"
  18. # Supported NVIDIA GPU architectures.
  19. NVIDIA_SUPPORTED_ARCHS = {"6.1", "7.0", "7.5", "8.0", "8.6", "8.9", "9.0"}
  20. ROCM_SUPPORTED_ARCHS = {"gfx908", "gfx90a", "gfx942", "gfx1100"}
  21. assert sys.platform.startswith(
  22. "linux"), "Aphrodite only supports Linux at the moment (including WSL)."
  23. def _is_cuda() -> bool:
  24. return torch.version.cuda is not None
  25. def _is_hip() -> bool:
  26. return torch.version.hip is not None
  27. def _is_neuron() -> bool:
  28. torch_neuronx_installed = True
  29. try:
  30. subprocess.run(["neuron-ls"], capture_output=True, check=True)
  31. except (FileNotFoundError, PermissionError, subprocess.CalledProcessError):
  32. torch_neuronx_installed = False
  33. return torch_neuronx_installed
  34. # Compiler flags.
  35. CXX_FLAGS = ["-g", "-O2", "-std=c++17"]
  36. # TODO: Should we use -O3?
  37. NVCC_FLAGS = ["-O2", "-std=c++17"]
  38. if _is_hip():
  39. if ROCM_HOME is None:
  40. raise RuntimeError(
  41. "Cannot find ROCM_HOME. ROCm must be available to build the "
  42. "package.")
  43. NVCC_FLAGS += ["-DUSE_ROCM"]
  44. if _is_cuda() and CUDA_HOME is None:
  45. raise RuntimeError(
  46. "Cannot find CUDA_HOME. CUDA must be available to build the package.")
  47. ABI = 1 if torch._C._GLIBCXX_USE_CXX11_ABI else 0
  48. CXX_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  49. NVCC_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  50. def get_hipcc_rocm_version():
  51. # Run the hipcc --version command
  52. result = subprocess.run(['hipcc', '--version'],
  53. stdout=subprocess.PIPE,
  54. stderr=subprocess.STDOUT,
  55. text=True)
  56. # Check if the command was executed successfully
  57. if result.returncode != 0:
  58. print("Error running 'hipcc --version'")
  59. return None
  60. # Extract the version using a regular expression
  61. match = re.search(r'HIP version: (\S+)', result.stdout)
  62. if match:
  63. # Return the version string
  64. return match.group(1)
  65. else:
  66. print("Could not find HIP version in the output")
  67. return None
  68. def glob(pattern: str):
  69. root = Path(__name__).parent
  70. return [str(p) for p in root.glob(pattern)]
  71. def get_neuronxcc_version():
  72. import sysconfig
  73. site_dir = sysconfig.get_paths()["purelib"]
  74. version_file = os.path.join(site_dir, "neuronxcc", "version",
  75. "__init__.py")
  76. # Check if the command was executed successfully
  77. with open(version_file, "rt") as fp:
  78. content = fp.read()
  79. # Extract the version using a regular expression
  80. match = re.search(r"__version__ = '(\S+)'", content)
  81. if match:
  82. # Return the version string
  83. return match.group(1)
  84. else:
  85. raise RuntimeError("Could not find HIP version in the output")
  86. def get_nvcc_cuda_version(cuda_dir: str) -> Version:
  87. """Get the CUDA version from nvcc.
  88. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  89. """
  90. nvcc_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"],
  91. universal_newlines=True)
  92. output = nvcc_output.split()
  93. release_idx = output.index("release") + 1
  94. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  95. return nvcc_cuda_version
  96. def get_pytorch_rocm_arch() -> Set[str]:
  97. """Get the cross section of Pytorch, and aphrodite supported gfx arches
  98. ROCM can get the supported gfx architectures in one of two ways
  99. Either through the PYTORCH_ROCM_ARCH env var, or output from
  100. rocm_agent_enumerator.
  101. In either case we can generate a list of supported arch's and
  102. cross reference with APHRODITE's own ROCM_SUPPORTED_ARCHs.
  103. """
  104. env_arch_list = os.environ.get("PYTORCH_ROCM_ARCH", None)
  105. # If we don't have PYTORCH_ROCM_ARCH specified pull the list from
  106. # rocm_agent_enumerator
  107. if env_arch_list is None:
  108. command = "rocm_agent_enumerator"
  109. env_arch_list = subprocess.check_output([command]).decode('utf-8')\
  110. .strip().replace("\n", ";")
  111. arch_source_str = "rocm_agent_enumerator"
  112. else:
  113. arch_source_str = "PYTORCH_ROCM_ARCH env variable"
  114. # List are separated by ; or space.
  115. pytorch_rocm_arch = set(env_arch_list.replace(" ", ";").split(";"))
  116. # Filter out the invalid architectures and print a warning.
  117. arch_list = pytorch_rocm_arch.intersection(ROCM_SUPPORTED_ARCHS)
  118. # If none of the specified architectures are valid, raise an error.
  119. if not arch_list:
  120. raise RuntimeError(
  121. f"None of the ROCM architectures in {arch_source_str} "
  122. f"({env_arch_list}) is supported. "
  123. f"Supported ROCM architectures are: {ROCM_SUPPORTED_ARCHS}.")
  124. invalid_arch_list = pytorch_rocm_arch - ROCM_SUPPORTED_ARCHS
  125. if invalid_arch_list:
  126. warnings.warn(
  127. f"Unsupported ROCM architectures ({invalid_arch_list}) are "
  128. f"excluded from the {arch_source_str} output "
  129. f"({env_arch_list}). Supported ROCM architectures are: "
  130. f"{ROCM_SUPPORTED_ARCHS}.",
  131. stacklevel=2)
  132. return arch_list
  133. def get_torch_arch_list() -> Set[str]:
  134. # TORCH_CUDA_ARCH_LIST can have one or more architectures,
  135. # e.g. "8.0" or "7.5,8.0,8.6+PTX". Here, the "8.6+PTX" option asks the
  136. # compiler to additionally include PTX code that can be runtime-compiled
  137. # and executed on the 8.6 or newer architectures. While the PTX code will
  138. # not give the best performance on the newer architectures, it provides
  139. # forward compatibility.
  140. env_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", None)
  141. if env_arch_list is None:
  142. return set()
  143. # List are separated by ; or space.
  144. torch_arch_list = set(env_arch_list.replace(" ", ";").split(";"))
  145. if not torch_arch_list:
  146. return set()
  147. # Filter out the invalid architectures and print a warning.
  148. valid_archs = NVIDIA_SUPPORTED_ARCHS.union(
  149. {s + "+PTX"
  150. for s in NVIDIA_SUPPORTED_ARCHS})
  151. arch_list = torch_arch_list.intersection(valid_archs)
  152. # If none of the specified architectures are valid, raise an error.
  153. if not arch_list:
  154. raise RuntimeError(
  155. "None of the CUDA architectures in `TORCH_CUDA_ARCH_LIST` env "
  156. f"variable ({env_arch_list}) is supported. "
  157. f"Supported CUDA architectures are: {valid_archs}.")
  158. invalid_arch_list = torch_arch_list - valid_archs
  159. if invalid_arch_list:
  160. warnings.warn(
  161. f"Unsupported CUDA architectures ({invalid_arch_list}) are "
  162. "excluded from the `TORCH_CUDA_ARCH_LIST` env variable "
  163. f"({env_arch_list}). Supported CUDA architectures are: "
  164. f"{valid_archs}.",
  165. stacklevel=2)
  166. return arch_list
  167. if _is_hip():
  168. rocm_arches = get_pytorch_rocm_arch()
  169. NVCC_FLAGS += ["--offload-arch=" + arch for arch in rocm_arches]
  170. else:
  171. # First, check the TORCH_CUDA_ARCH_LIST environment variable.
  172. compute_capabilities = get_torch_arch_list()
  173. if _is_cuda() and not compute_capabilities:
  174. # If TORCH_CUDA_ARCH_LIST is not defined or empty, target all available
  175. # GPUs on the current machine.
  176. device_count = torch.cuda.device_count()
  177. for i in range(device_count):
  178. major, minor = torch.cuda.get_device_capability(i)
  179. if major < 6 or (major == 6 and minor < 1):
  180. raise RuntimeError(
  181. "GPUs with compute capability below 6.1 are not supported.")
  182. compute_capabilities.add(f"{major}.{minor}")
  183. ext_modules = []
  184. if _is_cuda():
  185. nvcc_cuda_version = get_nvcc_cuda_version(CUDA_HOME)
  186. if not compute_capabilities:
  187. # If no GPU is specified nor available, add all supported architectures
  188. # based on the NVCC CUDA version.
  189. compute_capabilities = NVIDIA_SUPPORTED_ARCHS.copy()
  190. if nvcc_cuda_version < Version("11.1"):
  191. compute_capabilities.remove("8.6")
  192. if nvcc_cuda_version < Version("11.8"):
  193. compute_capabilities.remove("8.9")
  194. compute_capabilities.remove("9.0")
  195. # Validate the NVCC CUDA version.
  196. if nvcc_cuda_version < Version("11.0"):
  197. raise RuntimeError(
  198. "CUDA 11.0 or higher is required to build the package.")
  199. if (nvcc_cuda_version < Version("11.1")
  200. and any(cc.startswith("8.6") for cc in compute_capabilities)):
  201. raise RuntimeError(
  202. "CUDA 11.1 or higher is required for compute capability 8.6.")
  203. if nvcc_cuda_version < Version("11.8"):
  204. if any(cc.startswith("8.9") for cc in compute_capabilities):
  205. # CUDA 11.8 is required to generate the code targeting compute
  206. # capability 8.9. However, GPUs with compute capability 8.9 can
  207. # also run the code generated by the previous versions of CUDA 11
  208. # and targeting compute capability 8.0. Therefore, if CUDA 11.8 is
  209. # not available, we target compute capability 8.0 instead of 8.9.
  210. warnings.warn(
  211. "CUDA 11.8 or higher is required for compute capability 8.9. "
  212. "Targeting compute capability 8.0 instead.",
  213. stacklevel=2)
  214. compute_capabilities = set(cc for cc in compute_capabilities
  215. if not cc.startswith("8.9"))
  216. compute_capabilities.add("8.0+PTX")
  217. if any(cc.startswith("9.0") for cc in compute_capabilities):
  218. raise RuntimeError(
  219. "CUDA 11.8 or higher is required for compute capability 9.0.")
  220. NVCC_FLAGS_PUNICA = NVCC_FLAGS.copy()
  221. # Add target compute capabilities to NVCC flags.
  222. for capability in compute_capabilities:
  223. num = capability[0] + capability[2]
  224. NVCC_FLAGS += ["-gencode", f"arch=compute_{num},code=sm_{num}"]
  225. if capability.endswith("+PTX"):
  226. NVCC_FLAGS += [
  227. "-gencode", f"arch=compute_{num},code=compute_{num}"
  228. ]
  229. if int(capability[0]) >= 8:
  230. NVCC_FLAGS_PUNICA += [
  231. "-gencode", f"arch=compute_{num},code=sm_{num}"
  232. ]
  233. if capability.endswith("+PTX"):
  234. NVCC_FLAGS_PUNICA += [
  235. "-gencode", f"arch=compute_{num},code=compute_{num}"
  236. ]
  237. # Use NVCC threads to parallelize the build.
  238. if nvcc_cuda_version >= Version("11.2"):
  239. nvcc_threads = int(os.getenv("NVCC_THREADS", 8))
  240. num_threads = min(os.cpu_count(), nvcc_threads)
  241. NVCC_FLAGS += ["--threads", str(num_threads)]
  242. if nvcc_cuda_version >= Version("11.8"):
  243. NVCC_FLAGS += ["-DENABLE_FP8_E5M2"]
  244. # changes for punica kernels
  245. NVCC_FLAGS += torch_cpp_ext.COMMON_NVCC_FLAGS
  246. REMOVE_NVCC_FLAGS = [
  247. '-D__CUDA_NO_HALF_OPERATORS__',
  248. '-D__CUDA_NO_HALF_CONVERSIONS__',
  249. '-D__CUDA_NO_BFLOAT16_CONVERSIONS__',
  250. '-D__CUDA_NO_HALF2_OPERATORS__',
  251. ]
  252. for flag in REMOVE_NVCC_FLAGS:
  253. with contextlib.suppress(ValueError):
  254. torch_cpp_ext.COMMON_NVCC_FLAGS.remove(flag)
  255. install_punica = bool(
  256. int(os.getenv("APHRODITE_INSTALL_PUNICA_KERNELS", "1")))
  257. device_count = torch.cuda.device_count()
  258. for i in range(device_count):
  259. major, minor = torch.cuda.get_device_capability(i)
  260. if major < 8:
  261. install_punica = False
  262. break
  263. if install_punica:
  264. ext_modules.append(
  265. CUDAExtension(
  266. name="aphrodite._punica_C",
  267. sources=["kernels/punica/punica_ops.cc"] +
  268. glob("kernels/punica/bgmv/*.cu"),
  269. extra_compile_args={
  270. "cxx": CXX_FLAGS,
  271. "nvcc": NVCC_FLAGS_PUNICA,
  272. },
  273. ))
  274. install_hadamard = bool(
  275. int(os.getenv("APHRODITE_INSTALL_HADAMARD_KERNELS", "1")))
  276. device_count = torch.cuda.device_count()
  277. for i in range(device_count):
  278. major, minor = torch.cuda.get_device_capability(i)
  279. if major < 7:
  280. install_hadamard = False
  281. break
  282. if install_hadamard:
  283. ext_modules.append(
  284. CUDAExtension(
  285. name="aphrodite._hadamard_C",
  286. sources=[
  287. "kernels/hadamard/fast_hadamard_transform.cpp",
  288. "kernels/hadamard/fast_hadamard_transform_cuda.cu"
  289. ],
  290. extra_compile_args={
  291. "cxx": CXX_FLAGS,
  292. "nvcc": NVCC_FLAGS,
  293. },
  294. ))
  295. elif _is_neuron():
  296. neuronxcc_version = get_neuronxcc_version()
  297. aphrodite_extension_sources = [
  298. "kernels/cache_kernels.cu",
  299. "kernels/attention/attention_kernels.cu",
  300. "kernels/pos_encoding_kernels.cu",
  301. "kernels/activation_kernels.cu",
  302. "kernels/layernorm_kernels.cu",
  303. "kernels/quantization/squeezellm/quant_cuda_kernel.cu",
  304. "kernels/quantization/gguf/gguf_kernel.cu",
  305. "kernels/quantization/gptq/q_gemm.cu",
  306. "kernels/quantization/exl2/q_matrix.cu",
  307. "kernels/quantization/exl2/q_gemm_exl2.cu",
  308. "kernels/cuda_utils_kernels.cu",
  309. "kernels/moe/align_block_size_kernel.cu",
  310. "kernels/pybind.cpp",
  311. ]
  312. if _is_cuda():
  313. aphrodite_extension_sources.append(
  314. "kernels/quantization/awq/gemm_kernels.cu")
  315. aphrodite_extension_sources.append(
  316. "kernels/quantization/quip/origin_order.cu")
  317. aphrodite_extension_sources.append(
  318. "kernels/quantization/marlin/marlin_cuda_kernel.cu")
  319. aphrodite_extension_sources.append(
  320. "kernels/all_reduce/custom_all_reduce.cu")
  321. aphrodite_extension_sources.append(
  322. "kernels/quantization/aqlm/aqlm_cuda_entry.cpp")
  323. aphrodite_extension_sources.append(
  324. "kernels/quantization/aqlm/aqlm_cuda_kernel.cu")
  325. aphrodite_extension_sources.append(
  326. "kernels/quantization/bitsandbytes/int4_fp16_gemm_kernels.cu")
  327. aphrodite_extension_sources.append(
  328. "kernels/quantization/bitsandbytes/format.cu")
  329. aphrodite_extension_sources.append(
  330. "kernels/quantization/bitsandbytes/gemm_s4_f16.cu")
  331. ext_modules.append(
  332. CUDAExtension(
  333. name="aphrodite._moe_C",
  334. sources=glob("kernels/moe/*.cu") + glob("kernels/moe/*.cpp"),
  335. extra_compile_args={
  336. "cxx": CXX_FLAGS,
  337. "nvcc": NVCC_FLAGS,
  338. },
  339. ))
  340. if not _is_neuron():
  341. aphrodite_extension = CUDAExtension(
  342. name="aphrodite._C",
  343. sources=aphrodite_extension_sources,
  344. extra_compile_args={
  345. "cxx": CXX_FLAGS,
  346. "nvcc": NVCC_FLAGS,
  347. },
  348. libraries=[
  349. "cuda", "conda/envs/aphrodite-runtime/lib",
  350. "conda/envs/aphrodite-runtime/lib/stubs"
  351. ] if _is_cuda() else [],
  352. library_dirs=[
  353. "conda/envs/aphrodite-runtime/lib",
  354. "conda/envs/aphrodite-runtime/lib/stubs"
  355. ] if _is_cuda() else [],
  356. )
  357. ext_modules.append(aphrodite_extension)
  358. def get_path(*filepath) -> str:
  359. return os.path.join(ROOT_DIR, *filepath)
  360. def find_version(filepath: str) -> str:
  361. """Extract version information from the given filepath.
  362. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  363. """
  364. with open(filepath) as fp:
  365. version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
  366. fp.read(), re.M)
  367. if version_match:
  368. return version_match.group(1)
  369. raise RuntimeError("Unable to find version string.")
  370. def get_aphrodite_version() -> str:
  371. version = find_version(get_path("aphrodite", "__init__.py"))
  372. if _is_cuda():
  373. cuda_version = str(nvcc_cuda_version)
  374. if cuda_version != MAIN_CUDA_VERSION:
  375. cuda_version_str = cuda_version.replace(".", "")[:3]
  376. version += f"+cu{cuda_version_str}"
  377. elif _is_hip():
  378. # Get the HIP version
  379. hipcc_version = get_hipcc_rocm_version()
  380. if hipcc_version != MAIN_CUDA_VERSION:
  381. rocm_version_str = hipcc_version.replace(".", "")[:3]
  382. version += f"+rocm{rocm_version_str}"
  383. elif _is_neuron():
  384. # Get the Neuron version
  385. neuron_version = str(neuronxcc_version)
  386. if neuron_version != MAIN_CUDA_VERSION:
  387. neuron_version_str = neuron_version.replace(".", "")[:3]
  388. version += f"+neuron{neuron_version_str}"
  389. else:
  390. raise RuntimeError("Unknown environment. Only "
  391. "CUDA, HIP, and Neuron are supported.")
  392. return version
  393. def read_readme() -> str:
  394. """Read the README file if present."""
  395. p = get_path("README.md")
  396. if os.path.isfile(p):
  397. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  398. else:
  399. return ""
  400. def get_requirements() -> List[str]:
  401. """Get Python package dependencies from requirements.txt."""
  402. if _is_cuda():
  403. with open(get_path("requirements.txt")) as f:
  404. requirements = f.read().strip().split("\n")
  405. if nvcc_cuda_version <= Version("11.8"):
  406. for i in range(len(requirements)):
  407. if requirements[i].startswith("cupy-cuda12x"):
  408. requirements[i] = "cupy-cuda11x"
  409. break
  410. elif _is_hip():
  411. with open(get_path("requirements-rocm.txt")) as f:
  412. requirements = f.read().strip().split("\n")
  413. elif _is_neuron():
  414. with open(get_path("requirements-neuron.txt")) as f:
  415. requirements = f.read().strip().split("\n")
  416. else:
  417. raise ValueError(
  418. "Unsupported platform, please use CUDA, ROCm or Neuron.")
  419. return requirements
  420. package_data = {
  421. "aphrodite": [
  422. "endpoints/kobold/klite.embd",
  423. "modeling/layers/quantization/hadamard.safetensors", "py.typed",
  424. "modeling/layers/fused_moe/configs/*.json"
  425. ]
  426. }
  427. if os.environ.get("APHRODITE_USE_PRECOMPILED"):
  428. ext_modules = []
  429. package_data["aphrodite"].append("*.so")
  430. setuptools.setup(
  431. name="aphrodite-engine",
  432. version=get_aphrodite_version(),
  433. author="PygmalionAI",
  434. license="AGPL 3.0",
  435. description="The inference engine for PygmalionAI models",
  436. long_description=read_readme(),
  437. long_description_content_type="text/markdown",
  438. url="https://github.com/PygmalionAI/aphrodite-engine",
  439. project_urls={
  440. "Homepage": "https://pygmalion.chat",
  441. "Documentation": "https://docs.pygmalion.chat",
  442. "GitHub": "https://github.com/PygmalionAI",
  443. "Huggingface": "https://huggingface.co/PygmalionAI",
  444. },
  445. classifiers=[
  446. "Programming Language :: Python :: 3.8",
  447. "Programming Language :: Python :: 3.9",
  448. "Programming Language :: Python :: 3.10",
  449. "Programming Language :: Python :: 3.11",
  450. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", # noqa: E501
  451. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  452. ],
  453. packages=setuptools.find_packages(exclude=("kernels", "examples",
  454. "tests")),
  455. python_requires=">=3.8",
  456. install_requires=get_requirements(),
  457. ext_modules=ext_modules,
  458. cmdclass={"build_ext": BuildExtension} if not _is_neuron() else {},
  459. include_package_data=True,
  460. )