devices.py 7.3 KB

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