devices.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import sys
  2. import contextlib
  3. from functools import lru_cache
  4. import torch
  5. from modules import errors, shared
  6. from modules import torch_utils
  7. if sys.platform == "darwin":
  8. from modules import mac_specific
  9. if shared.cmd_opts.use_ipex:
  10. from modules import xpu_specific
  11. def has_xpu() -> bool:
  12. return shared.cmd_opts.use_ipex and xpu_specific.has_xpu
  13. def has_mps() -> bool:
  14. if sys.platform != "darwin":
  15. return False
  16. else:
  17. return mac_specific.has_mps
  18. def cuda_no_autocast(device_id=None) -> bool:
  19. if device_id is None:
  20. device_id = get_cuda_device_id()
  21. return (
  22. torch.cuda.get_device_capability(device_id) == (7, 5)
  23. and torch.cuda.get_device_name(device_id).startswith("NVIDIA GeForce GTX 16")
  24. )
  25. def get_cuda_device_id():
  26. return (
  27. int(shared.cmd_opts.device_id)
  28. if shared.cmd_opts.device_id is not None and shared.cmd_opts.device_id.isdigit()
  29. else 0
  30. ) or torch.cuda.current_device()
  31. def get_cuda_device_string():
  32. if shared.cmd_opts.device_id is not None:
  33. return f"cuda:{shared.cmd_opts.device_id}"
  34. return "cuda"
  35. def get_optimal_device_name():
  36. if torch.cuda.is_available():
  37. return get_cuda_device_string()
  38. if has_mps():
  39. return "mps"
  40. if has_xpu():
  41. return xpu_specific.get_xpu_device_string()
  42. return "cpu"
  43. def get_optimal_device():
  44. return torch.device(get_optimal_device_name())
  45. def get_device_for(task):
  46. if task in shared.cmd_opts.use_cpu or "all" in shared.cmd_opts.use_cpu:
  47. return cpu
  48. return get_optimal_device()
  49. def torch_gc():
  50. if torch.cuda.is_available():
  51. with torch.cuda.device(get_cuda_device_string()):
  52. torch.cuda.empty_cache()
  53. torch.cuda.ipc_collect()
  54. if has_mps():
  55. mac_specific.torch_mps_gc()
  56. if has_xpu():
  57. xpu_specific.torch_xpu_gc()
  58. def enable_tf32():
  59. if torch.cuda.is_available():
  60. # enabling benchmark option seems to enable a range of cards to do fp16 when they otherwise can't
  61. # see https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/4407
  62. if cuda_no_autocast():
  63. torch.backends.cudnn.benchmark = True
  64. torch.backends.cuda.matmul.allow_tf32 = True
  65. torch.backends.cudnn.allow_tf32 = True
  66. errors.run(enable_tf32, "Enabling TF32")
  67. cpu: torch.device = torch.device("cpu")
  68. fp8: bool = False
  69. device: torch.device = None
  70. device_interrogate: torch.device = None
  71. device_gfpgan: torch.device = None
  72. device_esrgan: torch.device = None
  73. device_codeformer: torch.device = None
  74. dtype: torch.dtype = torch.float16
  75. dtype_vae: torch.dtype = torch.float16
  76. dtype_unet: torch.dtype = torch.float16
  77. unet_needs_upcast = False
  78. def cond_cast_unet(input):
  79. return input.to(dtype_unet) if unet_needs_upcast else input
  80. def cond_cast_float(input):
  81. return input.float() if unet_needs_upcast else input
  82. nv_rng = None
  83. patch_module_list = [
  84. torch.nn.Linear,
  85. torch.nn.Conv2d,
  86. torch.nn.MultiheadAttention,
  87. torch.nn.GroupNorm,
  88. torch.nn.LayerNorm,
  89. ]
  90. def manual_cast_forward(self, *args, **kwargs):
  91. org_dtype = torch_utils.get_param(self).dtype
  92. self.to(dtype)
  93. args = [arg.to(dtype) if isinstance(arg, torch.Tensor) else arg for arg in args]
  94. kwargs = {k: v.to(dtype) if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}
  95. result = self.org_forward(*args, **kwargs)
  96. self.to(org_dtype)
  97. return result
  98. @contextlib.contextmanager
  99. def manual_cast():
  100. for module_type in patch_module_list:
  101. org_forward = module_type.forward
  102. module_type.forward = manual_cast_forward
  103. module_type.org_forward = org_forward
  104. try:
  105. yield None
  106. finally:
  107. for module_type in patch_module_list:
  108. module_type.forward = module_type.org_forward
  109. def autocast(disable=False):
  110. if disable:
  111. return contextlib.nullcontext()
  112. if fp8 and device==cpu:
  113. return torch.autocast("cpu", dtype=torch.bfloat16, enabled=True)
  114. if fp8 and (dtype == torch.float32 or shared.cmd_opts.precision == "full" or cuda_no_autocast()):
  115. return manual_cast()
  116. if has_mps() and shared.cmd_opts.precision != "full":
  117. return manual_cast()
  118. if dtype == torch.float32 or shared.cmd_opts.precision == "full":
  119. return contextlib.nullcontext()
  120. return torch.autocast("cuda")
  121. def without_autocast(disable=False):
  122. return torch.autocast("cuda", enabled=False) if torch.is_autocast_enabled() and not disable else contextlib.nullcontext()
  123. class NansException(Exception):
  124. pass
  125. def test_for_nans(x, where):
  126. if shared.cmd_opts.disable_nan_check:
  127. return
  128. if not torch.all(torch.isnan(x)).item():
  129. return
  130. if where == "unet":
  131. message = "A tensor with all NaNs was produced in Unet."
  132. if not shared.cmd_opts.no_half:
  133. message += " This could be either because there's not enough precision to represent the picture, or because your video card does not support half type. Try setting the \"Upcast cross attention layer to float32\" option in Settings > Stable Diffusion or using the --no-half commandline argument to fix this."
  134. elif where == "vae":
  135. message = "A tensor with all NaNs was produced in VAE."
  136. if not shared.cmd_opts.no_half and not shared.cmd_opts.no_half_vae:
  137. message += " This could be because there's not enough precision to represent the picture. Try adding --no-half-vae commandline argument to fix this."
  138. else:
  139. message = "A tensor with all NaNs was produced."
  140. message += " Use --disable-nan-check commandline argument to disable this check."
  141. raise NansException(message)
  142. @lru_cache
  143. def first_time_calculation():
  144. """
  145. just do any calculation with pytorch layers - the first time this is done it allocaltes about 700MB of memory and
  146. spends about 2.7 seconds doing that, at least wih NVidia.
  147. """
  148. x = torch.zeros((1, 1)).to(device, dtype)
  149. linear = torch.nn.Linear(1, 1).to(device, dtype)
  150. linear(x)
  151. x = torch.zeros((1, 1, 3, 3)).to(device, dtype)
  152. conv2d = torch.nn.Conv2d(1, 1, (3, 3)).to(device, dtype)
  153. conv2d(x)