Path: blob/master/modules/mac_specific.py
3055 views
import logging12import torch3from torch import Tensor4import platform5from modules.sd_hijack_utils import CondFunc6from packaging import version7from modules import shared89log = logging.getLogger(__name__)101112# before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,13# use check `getattr` and try it for compatibility.14# in torch version 1.13, backends.mps.is_available() and backends.mps.is_built() are introduced in to check mps availability,15# since torch 2.0.1+ nightly build, getattr(torch, 'has_mps', False) was deprecated, see https://github.com/pytorch/pytorch/pull/10327916def check_for_mps() -> bool:17if version.parse(torch.__version__) <= version.parse("2.0.1"):18if not getattr(torch, 'has_mps', False):19return False20try:21torch.zeros(1).to(torch.device("mps"))22return True23except Exception:24return False25else:26return torch.backends.mps.is_available() and torch.backends.mps.is_built()272829has_mps = check_for_mps()303132def torch_mps_gc() -> None:33try:34if shared.state.current_latent is not None:35log.debug("`current_latent` is set, skipping MPS garbage collection")36return37from torch.mps import empty_cache38empty_cache()39except Exception:40log.warning("MPS garbage collection failed", exc_info=True)414243# MPS workaround for https://github.com/pytorch/pytorch/issues/8978444def cumsum_fix(input, cumsum_func, *args, **kwargs):45if input.device.type == 'mps':46output_dtype = kwargs.get('dtype', input.dtype)47if output_dtype == torch.int64:48return cumsum_func(input.cpu(), *args, **kwargs).to(input.device)49elif output_dtype == torch.bool or cumsum_needs_int_fix and (output_dtype == torch.int8 or output_dtype == torch.int16):50return cumsum_func(input.to(torch.int32), *args, **kwargs).to(torch.int64)51return cumsum_func(input, *args, **kwargs)525354# MPS workaround for https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/1404655def interpolate_with_fp32_fallback(orig_func, *args, **kwargs) -> Tensor:56try:57return orig_func(*args, **kwargs)58except RuntimeError as e:59if "not implemented for" in str(e) and "Half" in str(e):60input_tensor = args[0]61return orig_func(input_tensor.to(torch.float32), *args[1:], **kwargs).to(input_tensor.dtype)62else:63print(f"An unexpected RuntimeError occurred: {str(e)}")6465if has_mps:66if platform.mac_ver()[0].startswith("13.2."):67# MPS workaround for https://github.com/pytorch/pytorch/issues/95188, thanks to danieldk (https://github.com/explosion/curated-transformers/pull/124)68CondFunc('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)6970if version.parse(torch.__version__) < version.parse("1.13"):71# PyTorch 1.13 doesn't need these fixes but unfortunately is slower and has regressions that prevent training from working7273# MPS workaround for https://github.com/pytorch/pytorch/issues/7938374CondFunc('torch.Tensor.to', lambda orig_func, self, *args, **kwargs: orig_func(self.contiguous(), *args, **kwargs),75lambda _, 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'))76# MPS workaround for https://github.com/pytorch/pytorch/issues/8080077CondFunc('torch.nn.functional.layer_norm', lambda orig_func, *args, **kwargs: orig_func(*([args[0].contiguous()] + list(args[1:])), **kwargs),78lambda _, *args, **kwargs: args and isinstance(args[0], torch.Tensor) and args[0].device.type == 'mps')79# MPS workaround for https://github.com/pytorch/pytorch/issues/9053280CondFunc('torch.Tensor.numpy', lambda orig_func, self, *args, **kwargs: orig_func(self.detach(), *args, **kwargs), lambda _, self, *args, **kwargs: self.requires_grad)81elif version.parse(torch.__version__) > version.parse("1.13.1"):82cumsum_needs_int_fix = not torch.Tensor([1,2]).to(torch.device("mps")).equal(torch.ShortTensor([1,1]).to(torch.device("mps")).cumsum(0))83cumsum_fix_func = lambda orig_func, input, *args, **kwargs: cumsum_fix(input, orig_func, *args, **kwargs)84CondFunc('torch.cumsum', cumsum_fix_func, None)85CondFunc('torch.Tensor.cumsum', cumsum_fix_func, None)86CondFunc('torch.narrow', lambda orig_func, *args, **kwargs: orig_func(*args, **kwargs).clone(), None)8788# MPS workaround for https://github.com/pytorch/pytorch/issues/9611389CondFunc('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')9091# MPS workaround for https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/1404692CondFunc('torch.nn.functional.interpolate', interpolate_with_fp32_fallback, None)9394# MPS workaround for https://github.com/pytorch/pytorch/issues/9231195if platform.processor() == 'i386':96for funcName in ['torch.argmax', 'torch.Tensor.argmax']:97CondFunc(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')9899100