stable-diffusion-webui
138 строк · 5.7 Кб
1from modules import shared2from modules.sd_hijack_utils import CondFunc3
4has_ipex = False5try:6import torch7import intel_extension_for_pytorch as ipex # noqa: F4018has_ipex = True9except Exception:10pass11
12
13def check_for_xpu():14return has_ipex and hasattr(torch, 'xpu') and torch.xpu.is_available()15
16
17def get_xpu_device_string():18if shared.cmd_opts.device_id is not None:19return f"xpu:{shared.cmd_opts.device_id}"20return "xpu"21
22
23def torch_xpu_gc():24with torch.xpu.device(get_xpu_device_string()):25torch.xpu.empty_cache()26
27
28has_xpu = check_for_xpu()29
30
31# Arc GPU cannot allocate a single block larger than 4GB: https://github.com/intel/compute-runtime/issues/627
32# Here we implement a slicing algorithm to split large batch size into smaller chunks,
33# so that SDPA of each chunk wouldn't require any allocation larger than ARC_SINGLE_ALLOCATION_LIMIT.
34# The heuristic limit (TOTAL_VRAM // 8) is tuned for Intel Arc A770 16G and Arc A750 8G,
35# which is the best trade-off between VRAM usage and performance.
36ARC_SINGLE_ALLOCATION_LIMIT = {}37orig_sdp_attn_func = torch.nn.functional.scaled_dot_product_attention38def torch_xpu_scaled_dot_product_attention(39query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *args, **kwargs40):41# cast to same dtype first42key = key.to(query.dtype)43value = value.to(query.dtype)44if attn_mask is not None and attn_mask.dtype != torch.bool:45attn_mask = attn_mask.to(query.dtype)46
47N = query.shape[:-2] # Batch size48L = query.size(-2) # Target sequence length49E = query.size(-1) # Embedding dimension of the query and key50S = key.size(-2) # Source sequence length51Ev = value.size(-1) # Embedding dimension of the value52
53total_batch_size = torch.numel(torch.empty(N))54device_id = query.device.index55if device_id not in ARC_SINGLE_ALLOCATION_LIMIT:56ARC_SINGLE_ALLOCATION_LIMIT[device_id] = min(torch.xpu.get_device_properties(device_id).total_memory // 8, 4 * 1024 * 1024 * 1024)57batch_size_limit = max(1, ARC_SINGLE_ALLOCATION_LIMIT[device_id] // (L * S * query.element_size()))58
59if total_batch_size <= batch_size_limit:60return orig_sdp_attn_func(61query,62key,63value,64attn_mask,65dropout_p,66is_causal,67*args, **kwargs68)69
70query = torch.reshape(query, (-1, L, E))71key = torch.reshape(key, (-1, S, E))72value = torch.reshape(value, (-1, S, Ev))73if attn_mask is not None:74attn_mask = attn_mask.view(-1, L, S)75chunk_count = (total_batch_size + batch_size_limit - 1) // batch_size_limit76outputs = []77for i in range(chunk_count):78attn_mask_chunk = (79None80if attn_mask is None81else attn_mask[i * batch_size_limit : (i + 1) * batch_size_limit, :, :]82)83chunk_output = orig_sdp_attn_func(84query[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],85key[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],86value[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],87attn_mask_chunk,88dropout_p,89is_causal,90*args, **kwargs91)92outputs.append(chunk_output)93result = torch.cat(outputs, dim=0)94return torch.reshape(result, (*N, L, Ev))95
96
97def is_xpu_device(device: str | torch.device = None):98if device is None:99return False100if isinstance(device, str):101return device.startswith("xpu")102return device.type == "xpu"103
104
105if has_xpu:106try:107# torch.Generator supports "xpu" device since 2.1108torch.Generator("xpu")109except RuntimeError:110# W/A for https://github.com/intel/intel-extension-for-pytorch/issues/452: torch.Generator API doesn't support XPU device (for torch < 2.1)111CondFunc('torch.Generator',112lambda orig_func, device=None: torch.xpu.Generator(device),113lambda orig_func, device=None: is_xpu_device(device))114
115# W/A for some OPs that could not handle different input dtypes116CondFunc('torch.nn.functional.layer_norm',117lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:118orig_func(input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs),119lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:120weight is not None and input.dtype != weight.data.dtype)121CondFunc('torch.nn.modules.GroupNorm.forward',122lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),123lambda orig_func, self, input: input.dtype != self.weight.data.dtype)124CondFunc('torch.nn.modules.linear.Linear.forward',125lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),126lambda orig_func, self, input: input.dtype != self.weight.data.dtype)127CondFunc('torch.nn.modules.conv.Conv2d.forward',128lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),129lambda orig_func, self, input: input.dtype != self.weight.data.dtype)130CondFunc('torch.bmm',131lambda orig_func, input, mat2, out=None: orig_func(input.to(mat2.dtype), mat2, out=out),132lambda orig_func, input, mat2, out=None: input.dtype != mat2.dtype)133CondFunc('torch.cat',134lambda orig_func, tensors, dim=0, out=None: orig_func([t.to(tensors[0].dtype) for t in tensors], dim=dim, out=out),135lambda orig_func, tensors, dim=0, out=None: not all(t.dtype == tensors[0].dtype for t in tensors))136CondFunc('torch.nn.functional.scaled_dot_product_attention',137lambda orig_func, *args, **kwargs: torch_xpu_scaled_dot_product_attention(*args, **kwargs),138lambda orig_func, query, *args, **kwargs: query.is_xpu)139