xpu_accelerator.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. import torch
  5. from deepspeed.accelerator.abstract_accelerator import DeepSpeedAccelerator
  6. import intel_extension_for_pytorch as ipex # noqa: F401 # type: ignore
  7. import oneccl_bindings_for_pytorch # noqa: F401 # type: ignore
  8. import functools
  9. import importlib
  10. import inspect
  11. class XPU_Accelerator(DeepSpeedAccelerator):
  12. def __init__(self):
  13. self._name = 'xpu'
  14. self._communication_backend_name = 'ccl'
  15. self._compile_backend = "inductor"
  16. self.aligned_tensors = []
  17. self.class_dict = None
  18. def is_synchronized_device(self):
  19. return False
  20. def use_host_timers(self):
  21. # WA XPU event will be consolidated in 2.5
  22. if ipex.__version__ < '2.5':
  23. return True
  24. else:
  25. return self.is_synchronized_device()
  26. def resolves_data_dependency(self):
  27. return self.is_synchronized_device()
  28. def handles_memory_backpressure(self):
  29. return self.is_synchronized_device()
  30. # Device APIs
  31. def device_name(self, device_index=None):
  32. if device_index == None:
  33. return 'xpu'
  34. return 'xpu:{}'.format(device_index)
  35. def device(self, device_index=None):
  36. return torch.xpu.device(device_index)
  37. def set_device(self, device_index):
  38. torch.xpu.set_device(device_index)
  39. def current_device(self):
  40. return torch.xpu.current_device()
  41. def current_device_name(self):
  42. return 'xpu:{}'.format(torch.xpu.current_device())
  43. def device_count(self):
  44. return torch.xpu.device_count()
  45. def synchronize(self, device_index=None):
  46. return torch.xpu.synchronize(device_index)
  47. # RNG APIs
  48. def random(self):
  49. return torch.xpu.random
  50. def set_rng_state(self, new_state, device_index=None):
  51. if device_index == None:
  52. return torch.xpu.set_rng_state(new_state)
  53. return torch.xpu.set_rng_state(new_state, device_index)
  54. def get_rng_state(self, device_index=None):
  55. if device_index == None:
  56. return torch.xpu.get_rng_state()
  57. return torch.xpu.get_rng_state(device_index)
  58. def manual_seed(self, seed):
  59. return torch.xpu.manual_seed(seed)
  60. def manual_seed_all(self, seed):
  61. return torch.xpu.manual_seed_all(seed)
  62. def initial_seed(self):
  63. return torch.xpu.initial_seed()
  64. def default_generator(self, device_index):
  65. return torch.xpu.default_generators[device_index]
  66. # Streams/Events
  67. @property
  68. def Stream(self):
  69. return torch.xpu.Stream
  70. def stream(self, stream):
  71. return torch.xpu.stream(stream)
  72. def current_stream(self, device_index=None):
  73. return torch.xpu.current_stream(device_index)
  74. def default_stream(self, device_index=None):
  75. # torch.xpu does not support the sync behavior of default stream as cuda
  76. # use current_stream as workaround
  77. # see https://pytorch.org/docs/stable/notes/cuda.html#cuda-streams
  78. return torch.xpu.current_stream(device_index)
  79. @property
  80. def Event(self):
  81. return torch.xpu.Event
  82. # Memory management
  83. def empty_cache(self):
  84. return torch.xpu.empty_cache()
  85. def memory_allocated(self, device_index=None):
  86. return torch.xpu.memory_allocated(device_index)
  87. def max_memory_allocated(self, device_index=None):
  88. return torch.xpu.max_memory_allocated(device_index)
  89. def reset_max_memory_allocated(self, device_index=None):
  90. return torch.xpu.reset_max_memory_allocated(device_index)
  91. def memory_cached(self, device_index=None):
  92. return torch.xpu.memory_reserved(device_index)
  93. def max_memory_cached(self, device_index=None):
  94. return torch.xpu.max_memory_reserved(device_index)
  95. def reset_max_memory_cached(self, device_index=None):
  96. return torch.xpu.reset_max_memory_reserved(device_index)
  97. def memory_stats(self, device_index=None):
  98. return torch.xpu.memory_stats(device_index)
  99. def reset_peak_memory_stats(self, device_index=None):
  100. return torch.xpu.reset_peak_memory_stats(device_index)
  101. def memory_reserved(self, device_index=None):
  102. return torch.xpu.memory_reserved(device_index)
  103. def max_memory_reserved(self, device_index=None):
  104. return torch.xpu.max_memory_reserved(device_index)
  105. def total_memory(self, device_index=None):
  106. return torch.xpu.get_device_properties(device_index).total_memory
  107. def available_memory(self, device_index=None):
  108. return self.total_memory(device_index) - self.memory_allocated(device_index)
  109. # Misc
  110. def amp(self):
  111. return torch.xpu.amp
  112. def is_available(self):
  113. return torch.xpu.is_available()
  114. def range_push(self, msg):
  115. # TODO itt is currently not supported yet
  116. # return torch.profiler.itt.range_push(msg)
  117. return
  118. def range_pop(self):
  119. # TODO itt is currently not supported yet
  120. # return torch.profiler.itt.range_pop()
  121. return
  122. def lazy_call(self, callback):
  123. if hasattr(torch.xpu, "_lazy_call"):
  124. return torch.xpu._lazy_call(callback)
  125. else:
  126. return torch.xpu.lazy_init._lazy_call(callback)
  127. def communication_backend_name(self):
  128. return self._communication_backend_name
  129. def is_triton_supported(self):
  130. return False
  131. # Graph operations
  132. def create_graph(self):
  133. return None
  134. def capture_to_graph(self, graph, pool=None, stream=None):
  135. from deepspeed.runtime.utils import noop_context
  136. return noop_context()
  137. def replay_graph(self, graph):
  138. return
  139. # Data types
  140. def is_bf16_supported(self):
  141. return True
  142. def is_fp16_supported(self):
  143. return True
  144. def supported_dtypes(self):
  145. return [torch.float, torch.half, torch.bfloat16]
  146. # Tensor operations
  147. @property
  148. def BFloat16Tensor(self):
  149. return functools.partial(torch.tensor, dtype=torch.bfloat16, device=self._name)
  150. @property
  151. def ByteTensor(self):
  152. return functools.partial(torch.tensor, dtype=torch.uint8, device=self._name)
  153. @property
  154. def DoubleTensor(self):
  155. return functools.partial(torch.tensor, dtype=torch.double, device=self._name)
  156. @property
  157. def FloatTensor(self):
  158. return functools.partial(torch.tensor, dtype=torch.float, device=self._name)
  159. @property
  160. def HalfTensor(self):
  161. return functools.partial(torch.tensor, dtype=torch.half, device=self._name)
  162. @property
  163. def IntTensor(self):
  164. return functools.partial(torch.tensor, dtype=torch.int, device=self._name)
  165. @property
  166. def LongTensor(self):
  167. return functools.partial(torch.tensor, dtype=torch.long, device=self._name)
  168. def pin_memory(self, tensor, align_bytes=1):
  169. if align_bytes == 1:
  170. return tensor.pin_memory(device=self.current_device_name())
  171. elif align_bytes == 0:
  172. from deepspeed.ops.op_builder.xpu import AsyncIOBuilder
  173. self.aio_handle = AsyncIOBuilder().load().aio_handle(128 * 1024, 8, False, False, False)
  174. aligned_t = self.aio_handle.new_cpu_locked_tensor(tensor.numel(), tensor)
  175. aligned_t = aligned_t[:tensor.numel()].copy_(tensor)
  176. self.aligned_tensors.append([aligned_t.data_ptr(), aligned_t[-1].data_ptr()])
  177. return aligned_t
  178. def is_pinned(self, tensor):
  179. if tensor.is_pinned(device=self.current_device_name()):
  180. return True
  181. else:
  182. for begin, end in self.aligned_tensors:
  183. if begin <= tensor.data_ptr() and tensor.data_ptr() <= end:
  184. return True
  185. return False
  186. def op_builder_dir(self):
  187. try:
  188. # is op_builder from deepspeed or a 3p version? this should only succeed if it's deepspeed
  189. # if successful this also means we're doing a local install and not JIT compile path
  190. from op_builder import __deepspeed__ # noqa: F401 # type: ignore
  191. return "op_builder.xpu"
  192. except ImportError:
  193. return "deepspeed.ops.op_builder.xpu"
  194. def on_accelerator(self, tensor):
  195. device_str = str(tensor.device)
  196. if device_str.startswith('xpu:'):
  197. return True
  198. else:
  199. return False
  200. def _lazy_init_class_dict(self):
  201. if self.class_dict:
  202. return
  203. op_builder_module = importlib.import_module(self.op_builder_dir())
  204. # get op builder class from op_builder/xpu/__init__.py
  205. self.class_dict = {}
  206. for class_name, class_obj in inspect.getmembers(op_builder_module, inspect.isclass):
  207. self.class_dict[class_name] = class_obj
  208. # create an instance of op builder and return, name specified by class_name
  209. def create_op_builder(self, class_name):
  210. builder_class = self.get_op_builder(class_name)
  211. return builder_class()
  212. # return an op builder class, name specified by class_name
  213. def get_op_builder(self, class_name):
  214. self._lazy_init_class_dict()
  215. if class_name in self.class_dict:
  216. return self.class_dict[class_name]
  217. else:
  218. return self.class_dict['NotImplementedBuilder']
  219. def build_extension(self):
  220. try:
  221. from intel_extension_for_pytorch.xpu.cpp_extension import DpcppBuildExtension
  222. except ImportError:
  223. from intel_extension_for_pytorch.xpu.utils import DpcppBuildExtension
  224. return DpcppBuildExtension
  225. def export_envs(self):
  226. return []
  227. def visible_devices_envs(self):
  228. return ['ZE_AFFINITY_MASK']
  229. def set_visible_devices_envs(self, current_env, local_accelerator_ids):
  230. for env in self.visible_devices_envs():
  231. current_env[env] = ",".join(map(str, local_accelerator_ids))
  232. def get_compile_backend(self):
  233. return self._compile_backend
  234. def set_compile_backend(self, backend):
  235. supported_backends = torch._dynamo.list_backends(exclude_tags=())
  236. if backend in supported_backends:
  237. self._compile_backend = backend
  238. else:
  239. raise ValueError(
  240. f"{backend} not supported by {self.device_name()}. Supported Backends are {supported_backends}")