mac_specific.py 5.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import logging
  2. import torch
  3. from torch import Tensor
  4. import platform
  5. from modules.sd_hijack_utils import CondFunc
  6. from packaging import version
  7. from modules import shared
  8. log = logging.getLogger(__name__)
  9. # before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,
  10. # use check `getattr` and try it for compatibility.
  11. # in torch version 1.13, backends.mps.is_available() and backends.mps.is_built() are introduced in to check mps availabilty,
  12. # since torch 2.0.1+ nightly build, getattr(torch, 'has_mps', False) was deprecated, see https://github.com/pytorch/pytorch/pull/103279
  13. def check_for_mps() -> bool:
  14. if version.parse(torch.__version__) <= version.parse("2.0.1"):
  15. if not getattr(torch, 'has_mps', False):
  16. return False
  17. try:
  18. torch.zeros(1).to(torch.device("mps"))
  19. return True
  20. except Exception:
  21. return False
  22. else:
  23. return torch.backends.mps.is_available() and torch.backends.mps.is_built()
  24. has_mps = check_for_mps()
  25. def torch_mps_gc() -> None:
  26. try:
  27. if shared.state.current_latent is not None:
  28. log.debug("`current_latent` is set, skipping MPS garbage collection")
  29. return
  30. from torch.mps import empty_cache
  31. empty_cache()
  32. except Exception:
  33. log.warning("MPS garbage collection failed", exc_info=True)
  34. # MPS workaround for https://github.com/pytorch/pytorch/issues/89784
  35. def cumsum_fix(input, cumsum_func, *args, **kwargs):
  36. if input.device.type == 'mps':
  37. output_dtype = kwargs.get('dtype', input.dtype)
  38. if output_dtype == torch.int64:
  39. return cumsum_func(input.cpu(), *args, **kwargs).to(input.device)
  40. elif output_dtype == torch.bool or cumsum_needs_int_fix and (output_dtype == torch.int8 or output_dtype == torch.int16):
  41. return cumsum_func(input.to(torch.int32), *args, **kwargs).to(torch.int64)
  42. return cumsum_func(input, *args, **kwargs)
  43. # MPS workaround for https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14046
  44. def interpolate_with_fp32_fallback(orig_func, *args, **kwargs) -> Tensor:
  45. try:
  46. return orig_func(*args, **kwargs)
  47. except RuntimeError as e:
  48. if "not implemented for" in str(e) and "Half" in str(e):
  49. input_tensor = args[0]
  50. return orig_func(input_tensor.to(torch.float32), *args[1:], **kwargs).to(input_tensor.dtype)
  51. else:
  52. print(f"An unexpected RuntimeError occurred: {str(e)}")
  53. if has_mps:
  54. if platform.mac_ver()[0].startswith("13.2."):
  55. # MPS workaround for https://github.com/pytorch/pytorch/issues/95188, thanks to danieldk (https://github.com/explosion/curated-transformers/pull/124)
  56. CondFunc('torch.nn.functional.linear', lambda _, input, weight, bias: (torch.matmul(input, weight.t()) + bias) if bias is not None else torch.matmul(input, weight.t()), lambda _, input, weight, bias: input.numel() > 10485760)
  57. if version.parse(torch.__version__) < version.parse("1.13"):
  58. # PyTorch 1.13 doesn't need these fixes but unfortunately is slower and has regressions that prevent training from working
  59. # MPS workaround for https://github.com/pytorch/pytorch/issues/79383
  60. CondFunc('torch.Tensor.to', lambda orig_func, self, *args, **kwargs: orig_func(self.contiguous(), *args, **kwargs),
  61. lambda _, self, *args, **kwargs: self.device.type != 'mps' and (args and isinstance(args[0], torch.device) and args[0].type == 'mps' or isinstance(kwargs.get('device'), torch.device) and kwargs['device'].type == 'mps'))
  62. # MPS workaround for https://github.com/pytorch/pytorch/issues/80800
  63. CondFunc('torch.nn.functional.layer_norm', lambda orig_func, *args, **kwargs: orig_func(*([args[0].contiguous()] + list(args[1:])), **kwargs),
  64. lambda _, *args, **kwargs: args and isinstance(args[0], torch.Tensor) and args[0].device.type == 'mps')
  65. # MPS workaround for https://github.com/pytorch/pytorch/issues/90532
  66. CondFunc('torch.Tensor.numpy', lambda orig_func, self, *args, **kwargs: orig_func(self.detach(), *args, **kwargs), lambda _, self, *args, **kwargs: self.requires_grad)
  67. elif version.parse(torch.__version__) > version.parse("1.13.1"):
  68. cumsum_needs_int_fix = not torch.Tensor([1,2]).to(torch.device("mps")).equal(torch.ShortTensor([1,1]).to(torch.device("mps")).cumsum(0))
  69. cumsum_fix_func = lambda orig_func, input, *args, **kwargs: cumsum_fix(input, orig_func, *args, **kwargs)
  70. CondFunc('torch.cumsum', cumsum_fix_func, None)
  71. CondFunc('torch.Tensor.cumsum', cumsum_fix_func, None)
  72. CondFunc('torch.narrow', lambda orig_func, *args, **kwargs: orig_func(*args, **kwargs).clone(), None)
  73. # MPS workaround for https://github.com/pytorch/pytorch/issues/96113
  74. CondFunc('torch.nn.functional.layer_norm', lambda orig_func, x, normalized_shape, weight, bias, eps, **kwargs: orig_func(x.float(), normalized_shape, weight.float() if weight is not None else None, bias.float() if bias is not None else bias, eps).to(x.dtype), lambda _, input, *args, **kwargs: len(args) == 4 and input.device.type == 'mps')
  75. # MPS workaround for https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14046
  76. CondFunc('torch.nn.functional.interpolate', interpolate_with_fp32_fallback, None)
  77. # MPS workaround for https://github.com/pytorch/pytorch/issues/92311
  78. if platform.processor() == 'i386':
  79. for funcName in ['torch.argmax', 'torch.Tensor.argmax']:
  80. CondFunc(funcName, lambda _, input, *args, **kwargs: torch.max(input.float() if input.dtype == torch.int64 else input, *args, **kwargs)[1], lambda _, input, *args, **kwargs: input.device.type == 'mps')