setup.py 12 KB

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