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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from functools import wraps
|
3 |
+
from contextlib import nullcontext
|
4 |
+
import torch
|
5 |
+
import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
device_supports_fp64 = torch.xpu.has_fp64_dtype()
|
9 |
+
|
10 |
+
# pylint: disable=protected-access, missing-function-docstring, line-too-long, unnecessary-lambda, no-else-return
|
11 |
+
|
12 |
+
class DummyDataParallel(torch.nn.Module): # pylint: disable=missing-class-docstring, unused-argument, too-few-public-methods
|
13 |
+
def __new__(cls, module, device_ids=None, output_device=None, dim=0): # pylint: disable=unused-argument
|
14 |
+
if isinstance(device_ids, list) and len(device_ids) > 1:
|
15 |
+
print("IPEX backend doesn't support DataParallel on multiple XPU devices")
|
16 |
+
return module.to("xpu")
|
17 |
+
|
18 |
+
def return_null_context(*args, **kwargs): # pylint: disable=unused-argument
|
19 |
+
return nullcontext()
|
20 |
+
|
21 |
+
@property
|
22 |
+
def is_cuda(self):
|
23 |
+
return self.device.type == 'xpu' or self.device.type == 'cuda'
|
24 |
+
|
25 |
+
def check_device(device):
|
26 |
+
return bool((isinstance(device, torch.device) and device.type == "cuda") or (isinstance(device, str) and "cuda" in device) or isinstance(device, int))
|
27 |
+
|
28 |
+
def return_xpu(device):
|
29 |
+
return f"xpu:{device.split(':')[-1]}" if isinstance(device, str) and ":" in device else f"xpu:{device}" if isinstance(device, int) else torch.device("xpu") if isinstance(device, torch.device) else "xpu"
|
30 |
+
|
31 |
+
|
32 |
+
# Autocast
|
33 |
+
original_autocast_init = torch.amp.autocast_mode.autocast.__init__
|
34 |
+
@wraps(torch.amp.autocast_mode.autocast.__init__)
|
35 |
+
def autocast_init(self, device_type, dtype=None, enabled=True, cache_enabled=None):
|
36 |
+
if device_type == "cuda":
|
37 |
+
return original_autocast_init(self, device_type="xpu", dtype=dtype, enabled=enabled, cache_enabled=cache_enabled)
|
38 |
+
else:
|
39 |
+
return original_autocast_init(self, device_type=device_type, dtype=dtype, enabled=enabled, cache_enabled=cache_enabled)
|
40 |
+
|
41 |
+
# Latent Antialias CPU Offload:
|
42 |
+
original_interpolate = torch.nn.functional.interpolate
|
43 |
+
@wraps(torch.nn.functional.interpolate)
|
44 |
+
def interpolate(tensor, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False): # pylint: disable=too-many-arguments
|
45 |
+
if antialias or align_corners is not None or mode == 'bicubic':
|
46 |
+
return_device = tensor.device
|
47 |
+
return_dtype = tensor.dtype
|
48 |
+
return original_interpolate(tensor.to("cpu", dtype=torch.float32), size=size, scale_factor=scale_factor, mode=mode,
|
49 |
+
align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias).to(return_device, dtype=return_dtype)
|
50 |
+
else:
|
51 |
+
return original_interpolate(tensor, size=size, scale_factor=scale_factor, mode=mode,
|
52 |
+
align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias)
|
53 |
+
|
54 |
+
|
55 |
+
# Diffusers Float64 (Alchemist GPUs doesn't support 64 bit):
|
56 |
+
original_from_numpy = torch.from_numpy
|
57 |
+
@wraps(torch.from_numpy)
|
58 |
+
def from_numpy(ndarray):
|
59 |
+
if ndarray.dtype == float:
|
60 |
+
return original_from_numpy(ndarray.astype('float32'))
|
61 |
+
else:
|
62 |
+
return original_from_numpy(ndarray)
|
63 |
+
|
64 |
+
original_as_tensor = torch.as_tensor
|
65 |
+
@wraps(torch.as_tensor)
|
66 |
+
def as_tensor(data, dtype=None, device=None):
|
67 |
+
if check_device(device):
|
68 |
+
device = return_xpu(device)
|
69 |
+
if isinstance(data, np.ndarray) and data.dtype == float and not (
|
70 |
+
(isinstance(device, torch.device) and device.type == "cpu") or (isinstance(device, str) and "cpu" in device)):
|
71 |
+
return original_as_tensor(data, dtype=torch.float32, device=device)
|
72 |
+
else:
|
73 |
+
return original_as_tensor(data, dtype=dtype, device=device)
|
74 |
+
|
75 |
+
|
76 |
+
if device_supports_fp64 and os.environ.get('IPEX_FORCE_ATTENTION_SLICE', None) is None:
|
77 |
+
original_torch_bmm = torch.bmm
|
78 |
+
original_scaled_dot_product_attention = torch.nn.functional.scaled_dot_product_attention
|
79 |
+
else:
|
80 |
+
# 32 bit attention workarounds for Alchemist:
|
81 |
+
try:
|
82 |
+
from .attention import torch_bmm_32_bit as original_torch_bmm
|
83 |
+
from .attention import scaled_dot_product_attention_32_bit as original_scaled_dot_product_attention
|
84 |
+
except Exception: # pylint: disable=broad-exception-caught
|
85 |
+
original_torch_bmm = torch.bmm
|
86 |
+
original_scaled_dot_product_attention = torch.nn.functional.scaled_dot_product_attention
|
87 |
+
|
88 |
+
|
89 |
+
# Data Type Errors:
|
90 |
+
@wraps(torch.bmm)
|
91 |
+
def torch_bmm(input, mat2, *, out=None):
|
92 |
+
if input.dtype != mat2.dtype:
|
93 |
+
mat2 = mat2.to(input.dtype)
|
94 |
+
return original_torch_bmm(input, mat2, out=out)
|
95 |
+
|
96 |
+
@wraps(torch.nn.functional.scaled_dot_product_attention)
|
97 |
+
def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False):
|
98 |
+
if query.dtype != key.dtype:
|
99 |
+
key = key.to(dtype=query.dtype)
|
100 |
+
if query.dtype != value.dtype:
|
101 |
+
value = value.to(dtype=query.dtype)
|
102 |
+
if attn_mask is not None and query.dtype != attn_mask.dtype:
|
103 |
+
attn_mask = attn_mask.to(dtype=query.dtype)
|
104 |
+
return original_scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=dropout_p, is_causal=is_causal)
|
105 |
+
|
106 |
+
# A1111 FP16
|
107 |
+
original_functional_group_norm = torch.nn.functional.group_norm
|
108 |
+
@wraps(torch.nn.functional.group_norm)
|
109 |
+
def functional_group_norm(input, num_groups, weight=None, bias=None, eps=1e-05):
|
110 |
+
if weight is not None and input.dtype != weight.data.dtype:
|
111 |
+
input = input.to(dtype=weight.data.dtype)
|
112 |
+
if bias is not None and weight is not None and bias.data.dtype != weight.data.dtype:
|
113 |
+
bias.data = bias.data.to(dtype=weight.data.dtype)
|
114 |
+
return original_functional_group_norm(input, num_groups, weight=weight, bias=bias, eps=eps)
|
115 |
+
|
116 |
+
# A1111 BF16
|
117 |
+
original_functional_layer_norm = torch.nn.functional.layer_norm
|
118 |
+
@wraps(torch.nn.functional.layer_norm)
|
119 |
+
def functional_layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-05):
|
120 |
+
if weight is not None and input.dtype != weight.data.dtype:
|
121 |
+
input = input.to(dtype=weight.data.dtype)
|
122 |
+
if bias is not None and weight is not None and bias.data.dtype != weight.data.dtype:
|
123 |
+
bias.data = bias.data.to(dtype=weight.data.dtype)
|
124 |
+
return original_functional_layer_norm(input, normalized_shape, weight=weight, bias=bias, eps=eps)
|
125 |
+
|
126 |
+
# Training
|
127 |
+
original_functional_linear = torch.nn.functional.linear
|
128 |
+
@wraps(torch.nn.functional.linear)
|
129 |
+
def functional_linear(input, weight, bias=None):
|
130 |
+
if input.dtype != weight.data.dtype:
|
131 |
+
input = input.to(dtype=weight.data.dtype)
|
132 |
+
if bias is not None and bias.data.dtype != weight.data.dtype:
|
133 |
+
bias.data = bias.data.to(dtype=weight.data.dtype)
|
134 |
+
return original_functional_linear(input, weight, bias=bias)
|
135 |
+
|
136 |
+
original_functional_conv2d = torch.nn.functional.conv2d
|
137 |
+
@wraps(torch.nn.functional.conv2d)
|
138 |
+
def functional_conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
|
139 |
+
if input.dtype != weight.data.dtype:
|
140 |
+
input = input.to(dtype=weight.data.dtype)
|
141 |
+
if bias is not None and bias.data.dtype != weight.data.dtype:
|
142 |
+
bias.data = bias.data.to(dtype=weight.data.dtype)
|
143 |
+
return original_functional_conv2d(input, weight, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
|
144 |
+
|
145 |
+
# A1111 Embedding BF16
|
146 |
+
original_torch_cat = torch.cat
|
147 |
+
@wraps(torch.cat)
|
148 |
+
def torch_cat(tensor, *args, **kwargs):
|
149 |
+
if len(tensor) == 3 and (tensor[0].dtype != tensor[1].dtype or tensor[2].dtype != tensor[1].dtype):
|
150 |
+
return original_torch_cat([tensor[0].to(tensor[1].dtype), tensor[1], tensor[2].to(tensor[1].dtype)], *args, **kwargs)
|
151 |
+
else:
|
152 |
+
return original_torch_cat(tensor, *args, **kwargs)
|
153 |
+
|
154 |
+
# SwinIR BF16:
|
155 |
+
original_functional_pad = torch.nn.functional.pad
|
156 |
+
@wraps(torch.nn.functional.pad)
|
157 |
+
def functional_pad(input, pad, mode='constant', value=None):
|
158 |
+
if mode == 'reflect' and input.dtype == torch.bfloat16:
|
159 |
+
return original_functional_pad(input.to(torch.float32), pad, mode=mode, value=value).to(dtype=torch.bfloat16)
|
160 |
+
else:
|
161 |
+
return original_functional_pad(input, pad, mode=mode, value=value)
|
162 |
+
|
163 |
+
|
164 |
+
original_torch_tensor = torch.tensor
|
165 |
+
@wraps(torch.tensor)
|
166 |
+
def torch_tensor(data, *args, dtype=None, device=None, **kwargs):
|
167 |
+
if check_device(device):
|
168 |
+
device = return_xpu(device)
|
169 |
+
if not device_supports_fp64:
|
170 |
+
if (isinstance(device, torch.device) and device.type == "xpu") or (isinstance(device, str) and "xpu" in device):
|
171 |
+
if dtype == torch.float64:
|
172 |
+
dtype = torch.float32
|
173 |
+
elif dtype is None and (hasattr(data, "dtype") and (data.dtype == torch.float64 or data.dtype == float)):
|
174 |
+
dtype = torch.float32
|
175 |
+
return original_torch_tensor(data, *args, dtype=dtype, device=device, **kwargs)
|
176 |
+
|
177 |
+
original_Tensor_to = torch.Tensor.to
|
178 |
+
@wraps(torch.Tensor.to)
|
179 |
+
def Tensor_to(self, device=None, *args, **kwargs):
|
180 |
+
if check_device(device):
|
181 |
+
return original_Tensor_to(self, return_xpu(device), *args, **kwargs)
|
182 |
+
else:
|
183 |
+
return original_Tensor_to(self, device, *args, **kwargs)
|
184 |
+
|
185 |
+
original_Tensor_cuda = torch.Tensor.cuda
|
186 |
+
@wraps(torch.Tensor.cuda)
|
187 |
+
def Tensor_cuda(self, device=None, *args, **kwargs):
|
188 |
+
if check_device(device):
|
189 |
+
return original_Tensor_cuda(self, return_xpu(device), *args, **kwargs)
|
190 |
+
else:
|
191 |
+
return original_Tensor_cuda(self, device, *args, **kwargs)
|
192 |
+
|
193 |
+
original_Tensor_pin_memory = torch.Tensor.pin_memory
|
194 |
+
@wraps(torch.Tensor.pin_memory)
|
195 |
+
def Tensor_pin_memory(self, device=None, *args, **kwargs):
|
196 |
+
if device is None:
|
197 |
+
device = "xpu"
|
198 |
+
if check_device(device):
|
199 |
+
return original_Tensor_pin_memory(self, return_xpu(device), *args, **kwargs)
|
200 |
+
else:
|
201 |
+
return original_Tensor_pin_memory(self, device, *args, **kwargs)
|
202 |
+
|
203 |
+
original_UntypedStorage_init = torch.UntypedStorage.__init__
|
204 |
+
@wraps(torch.UntypedStorage.__init__)
|
205 |
+
def UntypedStorage_init(*args, device=None, **kwargs):
|
206 |
+
if check_device(device):
|
207 |
+
return original_UntypedStorage_init(*args, device=return_xpu(device), **kwargs)
|
208 |
+
else:
|
209 |
+
return original_UntypedStorage_init(*args, device=device, **kwargs)
|
210 |
+
|
211 |
+
original_UntypedStorage_cuda = torch.UntypedStorage.cuda
|
212 |
+
@wraps(torch.UntypedStorage.cuda)
|
213 |
+
def UntypedStorage_cuda(self, device=None, *args, **kwargs):
|
214 |
+
if check_device(device):
|
215 |
+
return original_UntypedStorage_cuda(self, return_xpu(device), *args, **kwargs)
|
216 |
+
else:
|
217 |
+
return original_UntypedStorage_cuda(self, device, *args, **kwargs)
|
218 |
+
|
219 |
+
original_torch_empty = torch.empty
|
220 |
+
@wraps(torch.empty)
|
221 |
+
def torch_empty(*args, device=None, **kwargs):
|
222 |
+
if check_device(device):
|
223 |
+
return original_torch_empty(*args, device=return_xpu(device), **kwargs)
|
224 |
+
else:
|
225 |
+
return original_torch_empty(*args, device=device, **kwargs)
|
226 |
+
|
227 |
+
original_torch_randn = torch.randn
|
228 |
+
@wraps(torch.randn)
|
229 |
+
def torch_randn(*args, device=None, dtype=None, **kwargs):
|
230 |
+
if dtype == bytes:
|
231 |
+
dtype = None
|
232 |
+
if check_device(device):
|
233 |
+
return original_torch_randn(*args, device=return_xpu(device), **kwargs)
|
234 |
+
else:
|
235 |
+
return original_torch_randn(*args, device=device, **kwargs)
|
236 |
+
|
237 |
+
original_torch_ones = torch.ones
|
238 |
+
@wraps(torch.ones)
|
239 |
+
def torch_ones(*args, device=None, **kwargs):
|
240 |
+
if check_device(device):
|
241 |
+
return original_torch_ones(*args, device=return_xpu(device), **kwargs)
|
242 |
+
else:
|
243 |
+
return original_torch_ones(*args, device=device, **kwargs)
|
244 |
+
|
245 |
+
original_torch_zeros = torch.zeros
|
246 |
+
@wraps(torch.zeros)
|
247 |
+
def torch_zeros(*args, device=None, **kwargs):
|
248 |
+
if check_device(device):
|
249 |
+
return original_torch_zeros(*args, device=return_xpu(device), **kwargs)
|
250 |
+
else:
|
251 |
+
return original_torch_zeros(*args, device=device, **kwargs)
|
252 |
+
|
253 |
+
original_torch_linspace = torch.linspace
|
254 |
+
@wraps(torch.linspace)
|
255 |
+
def torch_linspace(*args, device=None, **kwargs):
|
256 |
+
if check_device(device):
|
257 |
+
return original_torch_linspace(*args, device=return_xpu(device), **kwargs)
|
258 |
+
else:
|
259 |
+
return original_torch_linspace(*args, device=device, **kwargs)
|
260 |
+
|
261 |
+
original_torch_Generator = torch.Generator
|
262 |
+
@wraps(torch.Generator)
|
263 |
+
def torch_Generator(device=None):
|
264 |
+
if check_device(device):
|
265 |
+
return original_torch_Generator(return_xpu(device))
|
266 |
+
else:
|
267 |
+
return original_torch_Generator(device)
|
268 |
+
|
269 |
+
original_torch_load = torch.load
|
270 |
+
@wraps(torch.load)
|
271 |
+
def torch_load(f, map_location=None, *args, **kwargs):
|
272 |
+
if map_location is None:
|
273 |
+
map_location = "xpu"
|
274 |
+
if check_device(map_location):
|
275 |
+
return original_torch_load(f, *args, map_location=return_xpu(map_location), **kwargs)
|
276 |
+
else:
|
277 |
+
return original_torch_load(f, *args, map_location=map_location, **kwargs)
|
278 |
+
|
279 |
+
|
280 |
+
# Hijack Functions:
|
281 |
+
def ipex_hijacks():
|
282 |
+
torch.tensor = torch_tensor
|
283 |
+
torch.Tensor.to = Tensor_to
|
284 |
+
torch.Tensor.cuda = Tensor_cuda
|
285 |
+
torch.Tensor.pin_memory = Tensor_pin_memory
|
286 |
+
torch.UntypedStorage.__init__ = UntypedStorage_init
|
287 |
+
torch.UntypedStorage.cuda = UntypedStorage_cuda
|
288 |
+
torch.empty = torch_empty
|
289 |
+
torch.randn = torch_randn
|
290 |
+
torch.ones = torch_ones
|
291 |
+
torch.zeros = torch_zeros
|
292 |
+
torch.linspace = torch_linspace
|
293 |
+
torch.Generator = torch_Generator
|
294 |
+
torch.load = torch_load
|
295 |
+
|
296 |
+
torch.backends.cuda.sdp_kernel = return_null_context
|
297 |
+
torch.nn.DataParallel = DummyDataParallel
|
298 |
+
torch.UntypedStorage.is_cuda = is_cuda
|
299 |
+
torch.amp.autocast_mode.autocast.__init__ = autocast_init
|
300 |
+
|
301 |
+
torch.nn.functional.scaled_dot_product_attention = scaled_dot_product_attention
|
302 |
+
torch.nn.functional.group_norm = functional_group_norm
|
303 |
+
torch.nn.functional.layer_norm = functional_layer_norm
|
304 |
+
torch.nn.functional.linear = functional_linear
|
305 |
+
torch.nn.functional.conv2d = functional_conv2d
|
306 |
+
torch.nn.functional.interpolate = interpolate
|
307 |
+
torch.nn.functional.pad = functional_pad
|
308 |
+
|
309 |
+
torch.bmm = torch_bmm
|
310 |
+
torch.cat = torch_cat
|
311 |
+
if not device_supports_fp64:
|
312 |
+
torch.from_numpy = from_numpy
|
313 |
+
torch.as_tensor = as_tensor
|