xpu_specific.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from modules import shared
  2. from modules.sd_hijack_utils import CondFunc
  3. has_ipex = False
  4. try:
  5. import torch
  6. import intel_extension_for_pytorch as ipex # noqa: F401
  7. has_ipex = True
  8. except Exception:
  9. pass
  10. def check_for_xpu():
  11. return has_ipex and hasattr(torch, 'xpu') and torch.xpu.is_available()
  12. def get_xpu_device_string():
  13. if shared.cmd_opts.device_id is not None:
  14. return f"xpu:{shared.cmd_opts.device_id}"
  15. return "xpu"
  16. def torch_xpu_gc():
  17. with torch.xpu.device(get_xpu_device_string()):
  18. torch.xpu.empty_cache()
  19. has_xpu = check_for_xpu()
  20. # Arc GPU cannot allocate a single block larger than 4GB: https://github.com/intel/compute-runtime/issues/627
  21. # Here we implement a slicing algorithm to split large batch size into smaller chunks,
  22. # so that SDPA of each chunk wouldn't require any allocation larger than ARC_SINGLE_ALLOCATION_LIMIT.
  23. # The heuristic limit (TOTAL_VRAM // 8) is tuned for Intel Arc A770 16G and Arc A750 8G,
  24. # which is the best trade-off between VRAM usage and performance.
  25. ARC_SINGLE_ALLOCATION_LIMIT = {}
  26. orig_sdp_attn_func = torch.nn.functional.scaled_dot_product_attention
  27. def torch_xpu_scaled_dot_product_attention(
  28. query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *args, **kwargs
  29. ):
  30. # cast to same dtype first
  31. key = key.to(query.dtype)
  32. value = value.to(query.dtype)
  33. if attn_mask is not None and attn_mask.dtype != torch.bool:
  34. attn_mask = attn_mask.to(query.dtype)
  35. N = query.shape[:-2] # Batch size
  36. L = query.size(-2) # Target sequence length
  37. E = query.size(-1) # Embedding dimension of the query and key
  38. S = key.size(-2) # Source sequence length
  39. Ev = value.size(-1) # Embedding dimension of the value
  40. total_batch_size = torch.numel(torch.empty(N))
  41. device_id = query.device.index
  42. if device_id not in ARC_SINGLE_ALLOCATION_LIMIT:
  43. ARC_SINGLE_ALLOCATION_LIMIT[device_id] = min(torch.xpu.get_device_properties(device_id).total_memory // 8, 4 * 1024 * 1024 * 1024)
  44. batch_size_limit = max(1, ARC_SINGLE_ALLOCATION_LIMIT[device_id] // (L * S * query.element_size()))
  45. if total_batch_size <= batch_size_limit:
  46. return orig_sdp_attn_func(
  47. query,
  48. key,
  49. value,
  50. attn_mask,
  51. dropout_p,
  52. is_causal,
  53. *args, **kwargs
  54. )
  55. query = torch.reshape(query, (-1, L, E))
  56. key = torch.reshape(key, (-1, S, E))
  57. value = torch.reshape(value, (-1, S, Ev))
  58. if attn_mask is not None:
  59. attn_mask = attn_mask.view(-1, L, S)
  60. chunk_count = (total_batch_size + batch_size_limit - 1) // batch_size_limit
  61. outputs = []
  62. for i in range(chunk_count):
  63. attn_mask_chunk = (
  64. None
  65. if attn_mask is None
  66. else attn_mask[i * batch_size_limit : (i + 1) * batch_size_limit, :, :]
  67. )
  68. chunk_output = orig_sdp_attn_func(
  69. query[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],
  70. key[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],
  71. value[i * batch_size_limit : (i + 1) * batch_size_limit, :, :],
  72. attn_mask_chunk,
  73. dropout_p,
  74. is_causal,
  75. *args, **kwargs
  76. )
  77. outputs.append(chunk_output)
  78. result = torch.cat(outputs, dim=0)
  79. return torch.reshape(result, (*N, L, Ev))
  80. def is_xpu_device(device: str | torch.device = None):
  81. if device is None:
  82. return False
  83. if isinstance(device, str):
  84. return device.startswith("xpu")
  85. return device.type == "xpu"
  86. if has_xpu:
  87. try:
  88. # torch.Generator supports "xpu" device since 2.1
  89. torch.Generator("xpu")
  90. except RuntimeError:
  91. # 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)
  92. CondFunc('torch.Generator',
  93. lambda orig_func, device=None: torch.xpu.Generator(device),
  94. lambda orig_func, device=None: is_xpu_device(device))
  95. # W/A for some OPs that could not handle different input dtypes
  96. CondFunc('torch.nn.functional.layer_norm',
  97. lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
  98. orig_func(input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs),
  99. lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
  100. weight is not None and input.dtype != weight.data.dtype)
  101. CondFunc('torch.nn.modules.GroupNorm.forward',
  102. lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
  103. lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
  104. CondFunc('torch.nn.modules.linear.Linear.forward',
  105. lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
  106. lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
  107. CondFunc('torch.nn.modules.conv.Conv2d.forward',
  108. lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
  109. lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
  110. CondFunc('torch.bmm',
  111. lambda orig_func, input, mat2, out=None: orig_func(input.to(mat2.dtype), mat2, out=out),
  112. lambda orig_func, input, mat2, out=None: input.dtype != mat2.dtype)
  113. CondFunc('torch.cat',
  114. lambda orig_func, tensors, dim=0, out=None: orig_func([t.to(tensors[0].dtype) for t in tensors], dim=dim, out=out),
  115. lambda orig_func, tensors, dim=0, out=None: not all(t.dtype == tensors[0].dtype for t in tensors))
  116. CondFunc('torch.nn.functional.scaled_dot_product_attention',
  117. lambda orig_func, *args, **kwargs: torch_xpu_scaled_dot_product_attention(*args, **kwargs),
  118. lambda orig_func, query, *args, **kwargs: query.is_xpu)