setup.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import io
  2. import os
  3. import re
  4. import subprocess
  5. from typing import List, Set
  6. from packaging.version import parse, Version
  7. import setuptools
  8. import torch
  9. from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CUDA_HOME
  10. ROOT_DIR = os.path.dirname(__file__)
  11. # Compiler flags.
  12. CXX_FLAGS = ["-g", "-O2", "-std=c++17"]
  13. # TODO: Should we use -O3?
  14. NVCC_FLAGS = ["-O2", "-std=c++17"]
  15. ABI = 1 if torch._C._GLIBCXX_USE_CXX11_ABI else 0
  16. CXX_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  17. NVCC_FLAGS += [f"-D_GLIBCXX_USE_CXX11_ABI={ABI}"]
  18. if CUDA_HOME is None:
  19. raise RuntimeError(
  20. f"Cannot find CUDA_HOME. CUDA must be available in order to build the package.")
  21. def get_nvcc_cuda_version(cuda_dir: str) -> Version:
  22. """Get the CUDA version from nvcc.
  23. Adapted from https://github.com/NVIDIA/apex/blob/8b7a1ff183741dd8f9b87e7bafd04cfde99cea28/setup.py
  24. """
  25. nvcc_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"],
  26. universal_newlines=True)
  27. output = nvcc_output.split()
  28. release_idx = output.index("release") + 1
  29. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  30. return nvcc_cuda_version
  31. # Collect the compute capabilities of all available GPUs.
  32. device_count = torch.cuda.device_count()
  33. compute_capabilities: Set[int] = set()
  34. for i in range(device_count):
  35. major, minor = torch.cuda.get_device_capability(i)
  36. if major < 6:
  37. raise RuntimeError(
  38. "GPUs with compute capability less than 6.0 are not supported.")
  39. compute_capabilities.add(major * 10 + minor)
  40. # If no GPU is available, add all supported compute capabilities.
  41. if not compute_capabilities:
  42. compute_capabilities = {60, 61, 65, 70, 75, 80, 86, 89, 90}
  43. # Add target compute capabilities to NVCC flags.
  44. for capability in compute_capabilities:
  45. NVCC_FLAGS += ["-gencode", f"arch=compute_{capability},code=sm_{capability}"]
  46. # Validate the NVCC CUDA version.
  47. nvcc_cuda_version = get_nvcc_cuda_version(CUDA_HOME)
  48. if nvcc_cuda_version < Version("11.0"):
  49. raise RuntimeError("CUDA 11.0 or higher is required to build the package.")
  50. if 86 in compute_capabilities and nvcc_cuda_version < Version("11.1"):
  51. raise RuntimeError(
  52. "CUDA 11.1 or higher is required for GPUs with compute capability 8.6.")
  53. if 89 in compute_capabilities and nvcc_cuda_version < Version("11.8"):
  54. # CUDA 11.8 is required to generate the code targetting compute capability 8.9,
  55. # however, GPUs with compute capability 8.9 can also run the code generated by
  56. # the previous versions of CUDA 11 and targetting compute capability 8.0,
  57. #so if CUDA 11.8 is not available, we target compute capability 8.0 instead.
  58. compute_capabilities.remove(89)
  59. compute_capabilities.add(80)
  60. if 90 in compute_capabilities and nvcc_cuda_version < Version("11.8"):
  61. raise RuntimeError(
  62. "CUDA 11.8 or higher is required for GPUs with compute capability 9.0.")
  63. if not compute_capabilities:
  64. compute_capabilities = {60, 65, 70, 75, 80}
  65. if nvcc_cuda_version >= Version("11.1"):
  66. compute_capabilities.add(86)
  67. if nvcc_cuda_version >= Version("11.8"):
  68. compute_capabilities.add(89)
  69. compute_capabilities.add(90)
  70. for capability in compute_capabilities:
  71. NVCC_FLAGS += ["-gencode", f"arch=compute_{capability},code=sm_{capability}"]
  72. # Use NVCC threads to parallelize the build.
  73. if nvcc_cuda_version >= Version("11.2"):
  74. num_threads = min(os.cpu_count(), 8)
  75. NVCC_FLAGS += ["--threads", str(num_threads)]
  76. ext_modules = []
  77. # Cache operations
  78. cache_extension = CUDAExtension(
  79. name="aphrodite.cache_ops",
  80. sources=["kernels/cache.cpp", "kernels/cache_kernels.cu"],
  81. extra_compile_args={"cxx": CXX_FLAGS, "nvcc": NVCC_FLAGS},
  82. )
  83. ext_modules.append(cache_extension)
  84. # Attention operations
  85. attention_extension = CUDAExtension(
  86. name="aphrodite.attention_ops",
  87. sources=["kernels/attention.cpp", "kernels/attention/attention_kernels.cu"],
  88. extra_compile_args={"cxx": CXX_FLAGS, "nvcc": NVCC_FLAGS},
  89. )
  90. ext_modules.append(attention_extension)
  91. # Positional encoding operations
  92. positional_encoding_extension = CUDAExtension(
  93. name="aphrodite.pos_encoding_ops",
  94. sources=["kernels/pos_encoding.cpp", "kernels/pos_encoding_kernels.cu"],
  95. extra_compile_args={"cxx": CXX_FLAGS, "nvcc": NVCC_FLAGS},
  96. )
  97. ext_modules.append(positional_encoding_extension)
  98. # Layer normalization operations
  99. layernorm_extension = CUDAExtension(
  100. name="aphrodite.layernorm_ops",
  101. sources=["kernels/layernorm.cpp", "kernels/layernorm_kernels.cu"],
  102. extra_compile_args={"cxx": CXX_FLAGS, "nvcc": NVCC_FLAGS},
  103. )
  104. ext_modules.append(layernorm_extension)
  105. # Activation operations
  106. activation_extension = CUDAExtension(
  107. name="aphrodite.activation_ops",
  108. sources=["kernels/activation.cpp", "kernels/activation_kernels.cu"],
  109. extra_compile_args={"cxx": CXX_FLAGS, "nvcc": NVCC_FLAGS},
  110. )
  111. ext_modules.append(activation_extension)
  112. quantization_extension = CUDAExtension(
  113. name="aphrodite.quantization_ops",
  114. sources=[
  115. "kernels/quantization.cpp",
  116. "kernels/quantization/awq/gemm_kernels.cu",
  117. ],
  118. extra_compile_args={
  119. "cxx": CXX_FLAGS,
  120. "nvcc": NVCC_FLAGS,
  121. },
  122. )
  123. ext_modules.append(quantization_extension)
  124. def get_path(*filepath) -> str:
  125. return os.path.join(ROOT_DIR, *filepath)
  126. def find_version(filepath: str):
  127. """Extract version information from the given filepath.
  128. Adapted from https://github.com/ray-project/ray/blob/0b190ee1160eeca9796bc091e07eaebf4c85b511/python/setup.py
  129. """
  130. with open(filepath) as fp:
  131. version_match = re.search(
  132. r"^__version__ = ['\"]([^'\"]*)['\"]", fp.read(), re.M)
  133. if version_match:
  134. return version_match.group(1)
  135. raise RuntimeError("Unable to find version string.")
  136. def read_readme() -> str:
  137. """Read the README file."""
  138. return io.open(get_path("README.md"), "r", encoding="utf-8").read()
  139. def get_requirements() -> List[str]:
  140. """Get Python package dependencies from requirements.txt."""
  141. with open(get_path("requirements.txt")) as f:
  142. requirements = f.read().strip().split("\n")
  143. return requirements
  144. setuptools.setup(
  145. name="aphrodite-engine",
  146. version=find_version(get_path("aphrodite", "__init__.py")),
  147. author="PygmalionAI",
  148. license="AGPL 3.0",
  149. description="The inference engine for PygmalionAI models",
  150. long_description=read_readme(),
  151. long_description_content_type="text/markdown",
  152. url="https://github.com/PygmalionAI/aphrodite-engine",
  153. project_urls={
  154. "Homepage": "https://pygmalion.chat",
  155. "Documentation": "https://docs.pygmalion.chat",
  156. "GitHub": "https://github.com/PygmalionAI",
  157. "Huggingface": "https://huggingface.co/PygmalionAI",
  158. },
  159. classifiers=[
  160. "Programming Language :: Python :: 3.8",
  161. "Programming Language :: Python :: 3.9",
  162. "Programming Language :: Python :: 3.10",
  163. "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
  164. "Topic :: Scientific/Engineering :: Artificial Intelligence",
  165. ],
  166. packages=setuptools.find_packages(
  167. exclude=("assets", "kernels","examples")),
  168. python_requires=">=3.8",
  169. install_requires=get_requirements(),
  170. ext_modules=ext_modules,
  171. cmdclass={"build_ext": BuildExtension},
  172. )