setup.py 19 KB

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