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