cuda_accelerator.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. import os
  5. import pkgutil
  6. import importlib
  7. from .abstract_accelerator import DeepSpeedAccelerator
  8. # During setup stage torch may not be installed, pass on no torch will
  9. # allow op builder related API to be executed.
  10. try:
  11. import torch.cuda
  12. except ImportError:
  13. pass
  14. class CUDA_Accelerator(DeepSpeedAccelerator):
  15. def __init__(self):
  16. self._name = 'cuda'
  17. self._communication_backend_name = 'nccl'
  18. # begin initialize for create_op_builder()
  19. # put all valid class name <--> class type mapping into class_dict
  20. op_builder_dir = self.op_builder_dir()
  21. op_builder_module = importlib.import_module(op_builder_dir)
  22. for _, module_name, _ in pkgutil.iter_modules([os.path.dirname(op_builder_module.__file__)]):
  23. # avoid self references
  24. if module_name != 'all_ops' and module_name != 'builder':
  25. module = importlib.import_module("{}.{}".format(op_builder_dir, module_name))
  26. for member_name in module.__dir__():
  27. if member_name.endswith(
  28. 'Builder'
  29. ) and member_name != "OpBuilder" and member_name != "CUDAOpBuilder" and member_name != "TorchCPUOpBuilder": # avoid abstract classes
  30. if not member_name in self.class_dict:
  31. self.class_dict[member_name] = getattr(module, member_name)
  32. # end initialize for create_op_builder()
  33. # Device APIs
  34. def device_name(self, device_index=None):
  35. if device_index == None:
  36. return 'cuda'
  37. return 'cuda:{}'.format(device_index)
  38. def device(self, device_index=None):
  39. return torch.cuda.device(device_index)
  40. def set_device(self, device_index):
  41. torch.cuda.set_device(device_index)
  42. def current_device(self):
  43. return torch.cuda.current_device()
  44. def current_device_name(self):
  45. return 'cuda:{}'.format(torch.cuda.current_device())
  46. def device_count(self):
  47. return torch.cuda.device_count()
  48. def synchronize(self, device_index=None):
  49. return torch.cuda.synchronize(device_index)
  50. # RNG APIs
  51. def random(self):
  52. return torch.random
  53. def set_rng_state(self, new_state, device_index=None):
  54. if device_index is None:
  55. return torch.cuda.set_rng_state(new_state)
  56. return torch.cuda.set_rng_state(new_state, device_index)
  57. def get_rng_state(self, device_index=None):
  58. if device_index is None:
  59. return torch.cuda.get_rng_state()
  60. return torch.cuda.get_rng_state(device_index)
  61. def manual_seed(self, seed):
  62. return torch.cuda.manual_seed(seed)
  63. def manual_seed_all(self, seed):
  64. return torch.cuda.manual_seed_all(seed)
  65. def initial_seed(self, seed):
  66. return torch.cuda.initial_seed(seed)
  67. def default_generator(self, device_index):
  68. return torch.cuda.default_generators[device_index]
  69. # Streams/Events
  70. @property
  71. def Stream(self):
  72. return torch.cuda.Stream
  73. def stream(self, stream):
  74. return torch.cuda.stream(stream)
  75. def current_stream(self, device_index=None):
  76. return torch.cuda.current_stream(device_index)
  77. def default_stream(self, device_index=None):
  78. return torch.cuda.default_stream(device_index)
  79. @property
  80. def Event(self):
  81. return torch.cuda.Event
  82. # Memory management
  83. def empty_cache(self):
  84. return torch.cuda.empty_cache()
  85. def memory_allocated(self, device_index=None):
  86. return torch.cuda.memory_allocated(device_index)
  87. def max_memory_allocated(self, device_index=None):
  88. return torch.cuda.max_memory_allocated(device_index)
  89. def reset_max_memory_allocated(self, device_index=None):
  90. return torch.cuda.reset_max_memory_allocated(device_index)
  91. def memory_cached(self, device_index=None):
  92. return torch.cuda.memory_cached(device_index)
  93. def max_memory_cached(self, device_index=None):
  94. return torch.cuda.max_memory_cached(device_index)
  95. def reset_max_memory_cached(self, device_index=None):
  96. return torch.cuda.reset_max_memory_cached(device_index)
  97. def memory_stats(self, device_index=None):
  98. if hasattr(torch.cuda, 'memory_stats'):
  99. return torch.cuda.memory_stats(device_index)
  100. def reset_peak_memory_stats(self, device_index=None):
  101. if hasattr(torch.cuda, 'reset_peak_memory_stats'):
  102. return torch.cuda.reset_peak_memory_stats(device_index)
  103. def memory_reserved(self, device_index=None):
  104. if hasattr(torch.cuda, 'memory_reserved'):
  105. return torch.cuda.memory_reserved(device_index)
  106. def max_memory_reserved(self, device_index=None):
  107. if hasattr(torch.cuda, 'max_memory_reserved'):
  108. return torch.cuda.max_memory_reserved(device_index)
  109. def total_memory(self, device_index=None):
  110. return torch.cuda.get_device_properties(device_index).total_memory
  111. # Data types
  112. def is_bf16_supported(self):
  113. return torch.cuda.is_bf16_supported()
  114. def is_fp16_supported(self):
  115. major, _ = torch.cuda.get_device_capability()
  116. if major >= 7:
  117. return True
  118. else:
  119. return False
  120. # Misc
  121. def amp(self):
  122. if hasattr(torch.cuda, 'amp'):
  123. return torch.cuda.amp
  124. return None
  125. def is_available(self):
  126. return torch.cuda.is_available()
  127. def range_push(self, msg):
  128. if hasattr(torch.cuda.nvtx, 'range_push'):
  129. return torch.cuda.nvtx.range_push(msg)
  130. def range_pop(self):
  131. if hasattr(torch.cuda.nvtx, 'range_pop'):
  132. return torch.cuda.nvtx.range_pop()
  133. def lazy_call(self, callback):
  134. return torch.cuda._lazy_call(callback)
  135. def communication_backend_name(self):
  136. return self._communication_backend_name
  137. # Tensor operations
  138. @property
  139. def BFloat16Tensor(self):
  140. return torch.cuda.BFloat16Tensor
  141. @property
  142. def ByteTensor(self):
  143. return torch.cuda.ByteTensor
  144. @property
  145. def DoubleTensor(self):
  146. return torch.cuda.DoubleTensor
  147. @property
  148. def FloatTensor(self):
  149. return torch.cuda.FloatTensor
  150. @property
  151. def HalfTensor(self):
  152. return torch.cuda.HalfTensor
  153. @property
  154. def IntTensor(self):
  155. return torch.cuda.IntTensor
  156. @property
  157. def LongTensor(self):
  158. return torch.cuda.LongTensor
  159. def pin_memory(self, tensor):
  160. return tensor.pin_memory()
  161. def on_accelerator(self, tensor):
  162. device_str = str(tensor.device)
  163. if device_str.startswith('cuda:'):
  164. return True
  165. else:
  166. return False
  167. def op_builder_dir(self):
  168. try:
  169. # is op_builder from deepspeed or a 3p version? this should only succeed if it's deepspeed
  170. # if successful this also means we're doing a local install and not JIT compile path
  171. from op_builder import __deepspeed__ # noqa: F401
  172. return "op_builder"
  173. except ImportError:
  174. return "deepspeed.ops.op_builder"
  175. # dict that holds class name <--> class type mapping i.e.
  176. # 'AsyncIOBuilder': <class 'op_builder.async_io.AsyncIOBuilder'>
  177. # this dict will be filled at init stage
  178. class_dict = {}
  179. # create an instance of op builder and return, name specified by class_name
  180. def create_op_builder(self, class_name):
  181. if class_name in self.class_dict:
  182. return self.class_dict[class_name]()
  183. else:
  184. return None
  185. # return an op builder class, name specified by class_name
  186. def get_op_builder(self, class_name):
  187. if class_name in self.class_dict:
  188. return self.class_dict[class_name]
  189. else:
  190. return None
  191. def build_extension(self):
  192. from torch.utils.cpp_extension import BuildExtension
  193. return BuildExtension