setup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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
  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. cmdclass['build_ext'] = get_accelerator().build_extension().with_options(use_ninja=False)
  98. if torch_available:
  99. TORCH_MAJOR = torch.__version__.split('.')[0]
  100. TORCH_MINOR = torch.__version__.split('.')[1]
  101. else:
  102. TORCH_MAJOR = "0"
  103. TORCH_MINOR = "0"
  104. if torch_available and not torch.cuda.is_available():
  105. # Fix to allow docker builds, similar to https://github.com/NVIDIA/apex/issues/486.
  106. print("[WARNING] Torch did not find cuda available, if cross-compiling or running with cpu only "
  107. "you can ignore this message. Adding compute capability for Pascal, Volta, and Turing "
  108. "(compute capabilities 6.0, 6.1, 6.2)")
  109. if not is_env_set("TORCH_CUDA_ARCH_LIST"):
  110. os.environ["TORCH_CUDA_ARCH_LIST"] = get_default_compute_capabilities()
  111. ext_modules = []
  112. # Default to pre-install kernels to false so we rely on JIT on Linux, opposite on Windows.
  113. BUILD_OP_PLATFORM = 1 if sys.platform == "win32" else 0
  114. BUILD_OP_DEFAULT = int(get_env_if_set('DS_BUILD_OPS', BUILD_OP_PLATFORM))
  115. print(f"DS_BUILD_OPS={BUILD_OP_DEFAULT}")
  116. if BUILD_OP_DEFAULT:
  117. assert torch_available, "Unable to pre-compile ops without torch installed. Please install torch before attempting to pre-compile ops."
  118. def command_exists(cmd):
  119. if sys.platform == "win32":
  120. result = subprocess.Popen(f'{cmd}', stdout=subprocess.PIPE, shell=True)
  121. return result.wait() == 1
  122. else:
  123. result = subprocess.Popen(f'type {cmd}', stdout=subprocess.PIPE, shell=True)
  124. return result.wait() == 0
  125. def op_envvar(op_name):
  126. assert hasattr(ALL_OPS[op_name], 'BUILD_VAR'), \
  127. f"{op_name} is missing BUILD_VAR field"
  128. return ALL_OPS[op_name].BUILD_VAR
  129. def op_enabled(op_name):
  130. env_var = op_envvar(op_name)
  131. return int(get_env_if_set(env_var, BUILD_OP_DEFAULT))
  132. compatible_ops = dict.fromkeys(ALL_OPS.keys(), False)
  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. compatible_ops[op_name] = op_compatible
  137. compatible_ops["deepspeed_not_implemented"] = False
  138. # If op is requested but not available, throw an error.
  139. if op_enabled(op_name) and not op_compatible:
  140. env_var = op_envvar(op_name)
  141. if not is_env_set(env_var):
  142. builder.warning(f"One can disable {op_name} with {env_var}=0")
  143. abort(f"Unable to pre-compile {op_name}")
  144. # If op is compatible but install is not enabled (JIT mode).
  145. if is_rocm_pytorch and op_compatible and not op_enabled(op_name):
  146. builder.hipify_extension()
  147. # If op install enabled, add builder to extensions.
  148. if op_enabled(op_name) and op_compatible:
  149. assert torch_available, f"Unable to pre-compile {op_name}, please first install torch"
  150. install_ops[op_name] = op_enabled(op_name)
  151. ext_modules.append(builder.builder())
  152. print(f'Install Ops={install_ops}')
  153. # Write out version/git info.
  154. git_hash_cmd = "git rev-parse --short HEAD"
  155. git_branch_cmd = "git rev-parse --abbrev-ref HEAD"
  156. if command_exists('git') and not is_env_set('DS_BUILD_STRING'):
  157. try:
  158. result = subprocess.check_output(git_hash_cmd, shell=True)
  159. git_hash = result.decode('utf-8').strip()
  160. result = subprocess.check_output(git_branch_cmd, shell=True)
  161. git_branch = result.decode('utf-8').strip()
  162. except subprocess.CalledProcessError:
  163. git_hash = "unknown"
  164. git_branch = "unknown"
  165. else:
  166. git_hash = "unknown"
  167. git_branch = "unknown"
  168. def create_dir_symlink(src, dest):
  169. if not os.path.islink(dest):
  170. if os.path.exists(dest):
  171. os.remove(dest)
  172. assert not os.path.exists(dest)
  173. os.symlink(src, dest)
  174. if sys.platform == "win32":
  175. # This creates a symbolic links on Windows.
  176. # It needs Administrator privilege to create symlinks on Windows.
  177. create_dir_symlink('..\\..\\csrc', '.\\deepspeed\\ops\\csrc')
  178. create_dir_symlink('..\\..\\op_builder', '.\\deepspeed\\ops\\op_builder')
  179. create_dir_symlink('..\\accelerator', '.\\deepspeed\\accelerator')
  180. egg_info.manifest_maker.template = 'MANIFEST_win.in'
  181. # Parse the DeepSpeed version string from version.txt.
  182. version_str = open('version.txt', 'r').read().strip()
  183. # Build specifiers like .devX can be added at install time. Otherwise, add the git hash.
  184. # Example: DS_BUILD_STRING=".dev20201022" python setup.py sdist bdist_wheel.
  185. # Building wheel for distribution, update version file.
  186. if is_env_set('DS_BUILD_STRING'):
  187. # Build string env specified, probably building for distribution.
  188. with open('build.txt', 'w') as fd:
  189. fd.write(os.environ['DS_BUILD_STRING'])
  190. version_str += os.environ['DS_BUILD_STRING']
  191. elif os.path.isfile('build.txt'):
  192. # build.txt exists, probably installing from distribution.
  193. with open('build.txt', 'r') as fd:
  194. version_str += fd.read().strip()
  195. else:
  196. # None of the above, probably installing from source.
  197. version_str += f'+{git_hash}'
  198. torch_version = ".".join([TORCH_MAJOR, TORCH_MINOR])
  199. bf16_support = False
  200. # Set cuda_version to 0.0 if cpu-only.
  201. cuda_version = "0.0"
  202. nccl_version = "0.0"
  203. # Set hip_version to 0.0 if cpu-only.
  204. hip_version = "0.0"
  205. if torch_available and torch.version.cuda is not None:
  206. cuda_version = ".".join(torch.version.cuda.split('.')[:2])
  207. if sys.platform != "win32":
  208. if isinstance(torch.cuda.nccl.version(), int):
  209. # This will break if minor version > 9.
  210. nccl_version = ".".join(str(torch.cuda.nccl.version())[:2])
  211. else:
  212. nccl_version = ".".join(map(str, torch.cuda.nccl.version()[:2]))
  213. if hasattr(torch.cuda, 'is_bf16_supported') and torch.cuda.is_available():
  214. bf16_support = torch.cuda.is_bf16_supported()
  215. if torch_available and hasattr(torch.version, 'hip') and torch.version.hip is not None:
  216. hip_version = ".".join(torch.version.hip.split('.')[:2])
  217. torch_info = {
  218. "version": torch_version,
  219. "bf16_support": bf16_support,
  220. "cuda_version": cuda_version,
  221. "nccl_version": nccl_version,
  222. "hip_version": hip_version
  223. }
  224. print(f"version={version_str}, git_hash={git_hash}, git_branch={git_branch}")
  225. with open('deepspeed/git_version_info_installed.py', 'w') as fd:
  226. fd.write(f"version='{version_str}'\n")
  227. fd.write(f"git_hash='{git_hash}'\n")
  228. fd.write(f"git_branch='{git_branch}'\n")
  229. fd.write(f"installed_ops={install_ops}\n")
  230. fd.write(f"compatible_ops={compatible_ops}\n")
  231. fd.write(f"torch_info={torch_info}\n")
  232. print(f'install_requires={install_requires}')
  233. print(f'compatible_ops={compatible_ops}')
  234. print(f'ext_modules={ext_modules}')
  235. # Parse README.md to make long_description for PyPI page.
  236. thisdir = os.path.abspath(os.path.dirname(__file__))
  237. with open(os.path.join(thisdir, 'README.md'), encoding='utf-8') as fin:
  238. readme_text = fin.read()
  239. start_time = time.time()
  240. setup(name='deepspeed',
  241. version=version_str,
  242. description='DeepSpeed library',
  243. long_description=readme_text,
  244. long_description_content_type='text/markdown',
  245. author='DeepSpeed Team',
  246. author_email='deepspeed-info@microsoft.com',
  247. url='http://deepspeed.ai',
  248. project_urls={
  249. 'Documentation': 'https://deepspeed.readthedocs.io',
  250. 'Source': 'https://github.com/microsoft/DeepSpeed',
  251. },
  252. install_requires=install_requires,
  253. extras_require=extras_require,
  254. packages=find_packages(include=['deepspeed', 'deepspeed.*']),
  255. include_package_data=True,
  256. scripts=[
  257. 'bin/deepspeed', 'bin/deepspeed.pt', 'bin/ds', 'bin/ds_ssh', 'bin/ds_report', 'bin/ds_bench', 'bin/dsr',
  258. 'bin/ds_elastic'
  259. ],
  260. classifiers=[
  261. 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7',
  262. 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9',
  263. 'Programming Language :: Python :: 3.10'
  264. ],
  265. license='Apache Software License 2.0',
  266. ext_modules=ext_modules,
  267. cmdclass=cmdclass)
  268. end_time = time.time()
  269. print(f'deepspeed build time = {end_time - start_time} secs')