devices.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import sys
  2. import contextlib
  3. from functools import lru_cache
  4. import torch
  5. from modules import errors, shared, npu_specific
  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. if npu_specific.has_npu:
  42. return npu_specific.get_npu_device_string()
  43. return "cpu"
  44. def get_optimal_device():
  45. return torch.device(get_optimal_device_name())
  46. def get_device_for(task):
  47. if task in shared.cmd_opts.use_cpu or "all" in shared.cmd_opts.use_cpu:
  48. return cpu
  49. return get_optimal_device()
  50. def torch_gc():
  51. if torch.cuda.is_available():
  52. with torch.cuda.device(get_cuda_device_string()):
  53. torch.cuda.empty_cache()
  54. torch.cuda.ipc_collect()
  55. if has_mps():
  56. mac_specific.torch_mps_gc()
  57. if has_xpu():
  58. xpu_specific.torch_xpu_gc()
  59. if npu_specific.has_npu:
  60. torch_npu_set_device()
  61. npu_specific.torch_npu_gc()
  62. def torch_npu_set_device():
  63. # Work around due to bug in torch_npu, revert me after fixed, @see https://gitee.com/ascend/pytorch/issues/I8KECW?from=project-issue
  64. if npu_specific.has_npu:
  65. torch.npu.set_device(0)
  66. def enable_tf32():
  67. if torch.cuda.is_available():
  68. # enabling benchmark option seems to enable a range of cards to do fp16 when they otherwise can't
  69. # see https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/4407
  70. if cuda_no_autocast():
  71. torch.backends.cudnn.benchmark = True
  72. torch.backends.cuda.matmul.allow_tf32 = True
  73. torch.backends.cudnn.allow_tf32 = True
  74. errors.run(enable_tf32, "Enabling TF32")
  75. cpu: torch.device = torch.device("cpu")
  76. fp8: bool = False
  77. device: torch.device = None
  78. device_interrogate: torch.device = None
  79. device_gfpgan: torch.device = None
  80. device_esrgan: torch.device = None
  81. device_codeformer: torch.device = None
  82. dtype: torch.dtype = torch.float16
  83. dtype_vae: torch.dtype = torch.float16
  84. dtype_unet: torch.dtype = torch.float16
  85. dtype_inference: torch.dtype = torch.float16
  86. unet_needs_upcast = False
  87. def cond_cast_unet(input):
  88. return input.to(dtype_unet) if unet_needs_upcast else input
  89. def cond_cast_float(input):
  90. return input.float() if unet_needs_upcast else input
  91. nv_rng = None
  92. patch_module_list = [
  93. torch.nn.Linear,
  94. torch.nn.Conv2d,
  95. torch.nn.MultiheadAttention,
  96. torch.nn.GroupNorm,
  97. torch.nn.LayerNorm,
  98. ]
  99. def manual_cast_forward(target_dtype):
  100. def forward_wrapper(self, *args, **kwargs):
  101. if any(
  102. isinstance(arg, torch.Tensor) and arg.dtype != target_dtype
  103. for arg in args
  104. ):
  105. args = [arg.to(target_dtype) if isinstance(arg, torch.Tensor) else arg for arg in args]
  106. kwargs = {k: v.to(target_dtype) if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}
  107. org_dtype = target_dtype
  108. for param in self.parameters():
  109. if param.dtype != target_dtype:
  110. org_dtype = param.dtype
  111. break
  112. if org_dtype != target_dtype:
  113. self.to(target_dtype)
  114. result = self.org_forward(*args, **kwargs)
  115. if org_dtype != target_dtype:
  116. self.to(org_dtype)
  117. if target_dtype != dtype_inference:
  118. if isinstance(result, tuple):
  119. result = tuple(
  120. i.to(dtype_inference)
  121. if isinstance(i, torch.Tensor)
  122. else i
  123. for i in result
  124. )
  125. elif isinstance(result, torch.Tensor):
  126. result = result.to(dtype_inference)
  127. return result
  128. return forward_wrapper
  129. @contextlib.contextmanager
  130. def manual_cast(target_dtype):
  131. applied = False
  132. for module_type in patch_module_list:
  133. if hasattr(module_type, "org_forward"):
  134. continue
  135. applied = True
  136. org_forward = module_type.forward
  137. if module_type == torch.nn.MultiheadAttention:
  138. module_type.forward = manual_cast_forward(torch.float32)
  139. else:
  140. module_type.forward = manual_cast_forward(target_dtype)
  141. module_type.org_forward = org_forward
  142. try:
  143. yield None
  144. finally:
  145. if applied:
  146. for module_type in patch_module_list:
  147. if hasattr(module_type, "org_forward"):
  148. module_type.forward = module_type.org_forward
  149. delattr(module_type, "org_forward")
  150. def autocast(disable=False):
  151. if disable:
  152. return contextlib.nullcontext()
  153. if fp8 and device==cpu:
  154. return torch.autocast("cpu", dtype=torch.bfloat16, enabled=True)
  155. if fp8 and dtype_inference == torch.float32:
  156. return manual_cast(dtype)
  157. if dtype == torch.float32 or dtype_inference == torch.float32:
  158. return contextlib.nullcontext()
  159. if has_xpu() or has_mps() or cuda_no_autocast():
  160. return manual_cast(dtype)
  161. return torch.autocast("cuda")
  162. def without_autocast(disable=False):
  163. return torch.autocast("cuda", enabled=False) if torch.is_autocast_enabled() and not disable else contextlib.nullcontext()
  164. class NansException(Exception):
  165. pass
  166. def test_for_nans(x, where):
  167. if shared.cmd_opts.disable_nan_check:
  168. return
  169. if not torch.all(torch.isnan(x)).item():
  170. return
  171. if where == "unet":
  172. message = "A tensor with all NaNs was produced in Unet."
  173. if not shared.cmd_opts.no_half:
  174. 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."
  175. elif where == "vae":
  176. message = "A tensor with all NaNs was produced in VAE."
  177. if not shared.cmd_opts.no_half and not shared.cmd_opts.no_half_vae:
  178. message += " This could be because there's not enough precision to represent the picture. Try adding --no-half-vae commandline argument to fix this."
  179. else:
  180. message = "A tensor with all NaNs was produced."
  181. message += " Use --disable-nan-check commandline argument to disable this check."
  182. raise NansException(message)
  183. @lru_cache
  184. def first_time_calculation():
  185. """
  186. just do any calculation with pytorch layers - the first time this is done it allocaltes about 700MB of memory and
  187. spends about 2.7 seconds doing that, at least wih NVidia.
  188. """
  189. x = torch.zeros((1, 1)).to(device, dtype)
  190. linear = torch.nn.Linear(1, 1).to(device, dtype)
  191. linear(x)
  192. x = torch.zeros((1, 1, 3, 3)).to(device, dtype)
  193. conv2d = torch.nn.Conv2d(1, 1, (3, 3)).to(device, dtype)
  194. conv2d(x)