setup.py 9.3 KB

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