setup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. """
  5. DeepSpeed library
  6. To build wheel on Windows:
  7. 1. Install pytorch, such as pytorch 1.12 + cuda 11.6.
  8. 2. Install visual cpp build tool.
  9. 3. Include cuda toolkit.
  10. 4. Launch cmd console with Administrator privilege for creating required symlink folders.
  11. Create a new wheel via the following command:
  12. build_win.bat
  13. The wheel will be located at: dist/*.whl
  14. """
  15. import os
  16. import sys
  17. import subprocess
  18. from setuptools import setup, find_packages
  19. from setuptools.command import egg_info
  20. import time
  21. torch_available = True
  22. try:
  23. import torch
  24. except ImportError:
  25. torch_available = False
  26. print('[WARNING] Unable to import torch, pre-compiling ops will be disabled. ' \
  27. 'Please visit https://pytorch.org/ to see how to properly install torch on your system.')
  28. from op_builder import get_default_compute_capabilities, OpBuilder
  29. from op_builder.all_ops import ALL_OPS
  30. from op_builder.builder import installed_cuda_version
  31. # Fetch rocm state.
  32. is_rocm_pytorch = OpBuilder.is_rocm_pytorch()
  33. rocm_version = OpBuilder.installed_rocm_version()
  34. RED_START = '\033[31m'
  35. RED_END = '\033[0m'
  36. ERROR = f"{RED_START} [ERROR] {RED_END}"
  37. def abort(msg):
  38. print(f"{ERROR} {msg}")
  39. assert False, msg
  40. def fetch_requirements(path):
  41. with open(path, 'r') as fd:
  42. return [r.strip() for r in fd.readlines()]
  43. install_requires = fetch_requirements('requirements/requirements.txt')
  44. extras_require = {
  45. '1bit': [], # add cupy based on cuda/rocm version
  46. '1bit_mpi': fetch_requirements('requirements/requirements-1bit-mpi.txt'),
  47. 'readthedocs': fetch_requirements('requirements/requirements-readthedocs.txt'),
  48. 'dev': fetch_requirements('requirements/requirements-dev.txt'),
  49. 'autotuning': fetch_requirements('requirements/requirements-autotuning.txt'),
  50. 'autotuning_ml': fetch_requirements('requirements/requirements-autotuning-ml.txt'),
  51. 'sparse_attn': fetch_requirements('requirements/requirements-sparse_attn.txt'),
  52. 'sparse': fetch_requirements('requirements/requirements-sparse_pruning.txt'),
  53. 'inf': fetch_requirements('requirements/requirements-inf.txt'),
  54. 'sd': fetch_requirements('requirements/requirements-sd.txt')
  55. }
  56. # Add specific cupy version to both onebit extension variants.
  57. if torch_available and torch.cuda.is_available():
  58. cupy = None
  59. if is_rocm_pytorch:
  60. rocm_major, rocm_minor = rocm_version
  61. # XXX cupy support for rocm 5 is not available yet.
  62. if rocm_major <= 4:
  63. cupy = f"cupy-rocm-{rocm_major}-{rocm_minor}"
  64. else:
  65. cuda_major_ver, cuda_minor_ver = installed_cuda_version()
  66. if (cuda_major_ver < 11) or ((cuda_major_ver == 11) and (cuda_minor_ver < 3)):
  67. cupy = f"cupy-cuda{cuda_major_ver}{cuda_minor_ver}"
  68. else:
  69. cupy = f"cupy-cuda{cuda_major_ver}x"
  70. if cupy:
  71. extras_require['1bit'].append(cupy)
  72. extras_require['1bit_mpi'].append(cupy)
  73. # Make an [all] extra that installs all needed dependencies.
  74. all_extras = set()
  75. for extra in extras_require.items():
  76. for req in extra[1]:
  77. all_extras.add(req)
  78. extras_require['all'] = list(all_extras)
  79. cmdclass = {}
  80. # For any pre-installed ops force disable ninja.
  81. if torch_available:
  82. from accelerator import get_accelerator
  83. cmdclass['build_ext'] = get_accelerator().build_extension().with_options(use_ninja=False)
  84. if torch_available:
  85. TORCH_MAJOR = torch.__version__.split('.')[0]
  86. TORCH_MINOR = torch.__version__.split('.')[1]
  87. else:
  88. TORCH_MAJOR = "0"
  89. TORCH_MINOR = "0"
  90. if torch_available and not torch.cuda.is_available():
  91. # Fix to allow docker builds, similar to https://github.com/NVIDIA/apex/issues/486.
  92. print("[WARNING] Torch did not find cuda available, if cross-compiling or running with cpu only "
  93. "you can ignore this message. Adding compute capability for Pascal, Volta, and Turing "
  94. "(compute capabilities 6.0, 6.1, 6.2)")
  95. if os.environ.get("TORCH_CUDA_ARCH_LIST", None) is None:
  96. os.environ["TORCH_CUDA_ARCH_LIST"] = get_default_compute_capabilities()
  97. ext_modules = []
  98. # Default to pre-install kernels to false so we rely on JIT on Linux, opposite on Windows.
  99. BUILD_OP_PLATFORM = 1 if sys.platform == "win32" else 0
  100. BUILD_OP_DEFAULT = int(os.environ.get('DS_BUILD_OPS', BUILD_OP_PLATFORM))
  101. print(f"DS_BUILD_OPS={BUILD_OP_DEFAULT}")
  102. if BUILD_OP_DEFAULT:
  103. assert torch_available, "Unable to pre-compile ops without torch installed. Please install torch before attempting to pre-compile ops."
  104. def command_exists(cmd):
  105. if sys.platform == "win32":
  106. result = subprocess.Popen(f'{cmd}', stdout=subprocess.PIPE, shell=True)
  107. return result.wait() == 1
  108. else:
  109. result = subprocess.Popen(f'type {cmd}', stdout=subprocess.PIPE, shell=True)
  110. return result.wait() == 0
  111. def op_envvar(op_name):
  112. assert hasattr(ALL_OPS[op_name], 'BUILD_VAR'), \
  113. f"{op_name} is missing BUILD_VAR field"
  114. return ALL_OPS[op_name].BUILD_VAR
  115. def op_enabled(op_name):
  116. env_var = op_envvar(op_name)
  117. return int(os.environ.get(env_var, BUILD_OP_DEFAULT))
  118. compatible_ops = dict.fromkeys(ALL_OPS.keys(), False)
  119. install_ops = dict.fromkeys(ALL_OPS.keys(), False)
  120. for op_name, builder in ALL_OPS.items():
  121. op_compatible = builder.is_compatible()
  122. compatible_ops[op_name] = op_compatible
  123. # If op is requested but not available, throw an error.
  124. if op_enabled(op_name) and not op_compatible:
  125. env_var = op_envvar(op_name)
  126. if env_var not in os.environ:
  127. builder.warning(f"One can disable {op_name} with {env_var}=0")
  128. abort(f"Unable to pre-compile {op_name}")
  129. # If op is compatible but install is not enabled (JIT mode).
  130. if is_rocm_pytorch and op_compatible and not op_enabled(op_name):
  131. builder.hipify_extension()
  132. # If op install enabled, add builder to extensions.
  133. if op_enabled(op_name) and op_compatible:
  134. assert torch_available, f"Unable to pre-compile {op_name}, please first install torch"
  135. install_ops[op_name] = op_enabled(op_name)
  136. ext_modules.append(builder.builder())
  137. print(f'Install Ops={install_ops}')
  138. # Write out version/git info.
  139. git_hash_cmd = "git rev-parse --short HEAD"
  140. git_branch_cmd = "git rev-parse --abbrev-ref HEAD"
  141. if command_exists('git') and 'DS_BUILD_STRING' not in os.environ:
  142. try:
  143. result = subprocess.check_output(git_hash_cmd, shell=True)
  144. git_hash = result.decode('utf-8').strip()
  145. result = subprocess.check_output(git_branch_cmd, shell=True)
  146. git_branch = result.decode('utf-8').strip()
  147. except subprocess.CalledProcessError:
  148. git_hash = "unknown"
  149. git_branch = "unknown"
  150. else:
  151. git_hash = "unknown"
  152. git_branch = "unknown"
  153. def create_dir_symlink(src, dest):
  154. if not os.path.islink(dest):
  155. if os.path.exists(dest):
  156. os.remove(dest)
  157. assert not os.path.exists(dest)
  158. os.symlink(src, dest)
  159. if sys.platform == "win32":
  160. # This creates a symbolic links on Windows.
  161. # It needs Administrator privilege to create symlinks on Windows.
  162. create_dir_symlink('..\\..\\csrc', '.\\deepspeed\\ops\\csrc')
  163. create_dir_symlink('..\\..\\op_builder', '.\\deepspeed\\ops\\op_builder')
  164. create_dir_symlink('..\\accelerator', '.\\deepspeed\\accelerator')
  165. egg_info.manifest_maker.template = 'MANIFEST_win.in'
  166. # Parse the DeepSpeed version string from version.txt.
  167. version_str = open('version.txt', 'r').read().strip()
  168. # Build specifiers like .devX can be added at install time. Otherwise, add the git hash.
  169. # Example: DS_BUILD_STRING=".dev20201022" python setup.py sdist bdist_wheel.
  170. # Building wheel for distribution, update version file.
  171. if 'DS_BUILD_STRING' in os.environ:
  172. # Build string env specified, probably building for distribution.
  173. with open('build.txt', 'w') as fd:
  174. fd.write(os.environ.get('DS_BUILD_STRING'))
  175. version_str += os.environ.get('DS_BUILD_STRING')
  176. elif os.path.isfile('build.txt'):
  177. # build.txt exists, probably installing from distribution.
  178. with open('build.txt', 'r') as fd:
  179. version_str += fd.read().strip()
  180. else:
  181. # None of the above, probably installing from source.
  182. version_str += f'+{git_hash}'
  183. torch_version = ".".join([TORCH_MAJOR, TORCH_MINOR])
  184. bf16_support = False
  185. # Set cuda_version to 0.0 if cpu-only.
  186. cuda_version = "0.0"
  187. nccl_version = "0.0"
  188. # Set hip_version to 0.0 if cpu-only.
  189. hip_version = "0.0"
  190. if torch_available and torch.version.cuda is not None:
  191. cuda_version = ".".join(torch.version.cuda.split('.')[:2])
  192. if sys.platform != "win32":
  193. if isinstance(torch.cuda.nccl.version(), int):
  194. # This will break if minor version > 9.
  195. nccl_version = ".".join(str(torch.cuda.nccl.version())[:2])
  196. else:
  197. nccl_version = ".".join(map(str, torch.cuda.nccl.version()[:2]))
  198. if hasattr(torch.cuda, 'is_bf16_supported') and torch.cuda.is_available():
  199. bf16_support = torch.cuda.is_bf16_supported()
  200. if torch_available and hasattr(torch.version, 'hip') and torch.version.hip is not None:
  201. hip_version = ".".join(torch.version.hip.split('.')[:2])
  202. torch_info = {
  203. "version": torch_version,
  204. "bf16_support": bf16_support,
  205. "cuda_version": cuda_version,
  206. "nccl_version": nccl_version,
  207. "hip_version": hip_version
  208. }
  209. print(f"version={version_str}, git_hash={git_hash}, git_branch={git_branch}")
  210. with open('deepspeed/git_version_info_installed.py', 'w') as fd:
  211. fd.write(f"version='{version_str}'\n")
  212. fd.write(f"git_hash='{git_hash}'\n")
  213. fd.write(f"git_branch='{git_branch}'\n")
  214. fd.write(f"installed_ops={install_ops}\n")
  215. fd.write(f"compatible_ops={compatible_ops}\n")
  216. fd.write(f"torch_info={torch_info}\n")
  217. print(f'install_requires={install_requires}')
  218. print(f'compatible_ops={compatible_ops}')
  219. print(f'ext_modules={ext_modules}')
  220. # Parse README.md to make long_description for PyPI page.
  221. thisdir = os.path.abspath(os.path.dirname(__file__))
  222. with open(os.path.join(thisdir, 'README.md'), encoding='utf-8') as fin:
  223. readme_text = fin.read()
  224. start_time = time.time()
  225. setup(name='deepspeed',
  226. version=version_str,
  227. description='DeepSpeed library',
  228. long_description=readme_text,
  229. long_description_content_type='text/markdown',
  230. author='DeepSpeed Team',
  231. author_email='deepspeed-info@microsoft.com',
  232. url='http://deepspeed.ai',
  233. project_urls={
  234. 'Documentation': 'https://deepspeed.readthedocs.io',
  235. 'Source': 'https://github.com/microsoft/DeepSpeed',
  236. },
  237. install_requires=install_requires,
  238. extras_require=extras_require,
  239. packages=find_packages(include=['deepspeed', 'deepspeed.*']),
  240. include_package_data=True,
  241. scripts=[
  242. 'bin/deepspeed', 'bin/deepspeed.pt', 'bin/ds', 'bin/ds_ssh', 'bin/ds_report', 'bin/ds_bench', 'bin/dsr',
  243. 'bin/ds_elastic'
  244. ],
  245. classifiers=[
  246. 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7',
  247. 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9',
  248. 'Programming Language :: Python :: 3.10'
  249. ],
  250. license='Apache Software License 2.0',
  251. ext_modules=ext_modules,
  252. cmdclass=cmdclass)
  253. end_time = time.time()
  254. print(f'deepspeed build time = {end_time - start_time} secs')