devices.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. # Force fp16 for all models in inference. No casting during inference.
  78. # This flag is controlled by "--precision half" command line arg.
  79. force_fp16: bool = False
  80. device: torch.device = None
  81. device_interrogate: torch.device = None
  82. device_gfpgan: torch.device = None
  83. device_esrgan: torch.device = None
  84. device_codeformer: torch.device = None
  85. dtype: torch.dtype = torch.float16
  86. dtype_vae: torch.dtype = torch.float16
  87. dtype_unet: torch.dtype = torch.float16
  88. dtype_inference: torch.dtype = torch.float16
  89. unet_needs_upcast = False
  90. def cond_cast_unet(input):
  91. if force_fp16:
  92. return input.to(torch.float16)
  93. return input.to(dtype_unet) if unet_needs_upcast else input
  94. def cond_cast_float(input):
  95. return input.float() if unet_needs_upcast else input
  96. nv_rng = None
  97. patch_module_list = [
  98. torch.nn.Linear,
  99. torch.nn.Conv2d,
  100. torch.nn.MultiheadAttention,
  101. torch.nn.GroupNorm,
  102. torch.nn.LayerNorm,
  103. ]
  104. def manual_cast_forward(target_dtype):
  105. def forward_wrapper(self, *args, **kwargs):
  106. if any(
  107. isinstance(arg, torch.Tensor) and arg.dtype != target_dtype
  108. for arg in args
  109. ):
  110. args = [arg.to(target_dtype) if isinstance(arg, torch.Tensor) else arg for arg in args]
  111. kwargs = {k: v.to(target_dtype) if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}
  112. org_dtype = target_dtype
  113. for param in self.parameters():
  114. if param.dtype != target_dtype:
  115. org_dtype = param.dtype
  116. break
  117. if org_dtype != target_dtype:
  118. self.to(target_dtype)
  119. result = self.org_forward(*args, **kwargs)
  120. if org_dtype != target_dtype:
  121. self.to(org_dtype)
  122. if target_dtype != dtype_inference:
  123. if isinstance(result, tuple):
  124. result = tuple(
  125. i.to(dtype_inference)
  126. if isinstance(i, torch.Tensor)
  127. else i
  128. for i in result
  129. )
  130. elif isinstance(result, torch.Tensor):
  131. result = result.to(dtype_inference)
  132. return result
  133. return forward_wrapper
  134. @contextlib.contextmanager
  135. def manual_cast(target_dtype):
  136. applied = False
  137. for module_type in patch_module_list:
  138. if hasattr(module_type, "org_forward"):
  139. continue
  140. applied = True
  141. org_forward = module_type.forward
  142. if module_type == torch.nn.MultiheadAttention:
  143. module_type.forward = manual_cast_forward(torch.float32)
  144. else:
  145. module_type.forward = manual_cast_forward(target_dtype)
  146. module_type.org_forward = org_forward
  147. try:
  148. yield None
  149. finally:
  150. if applied:
  151. for module_type in patch_module_list:
  152. if hasattr(module_type, "org_forward"):
  153. module_type.forward = module_type.org_forward
  154. delattr(module_type, "org_forward")
  155. def autocast(disable=False):
  156. if disable:
  157. return contextlib.nullcontext()
  158. if force_fp16:
  159. # No casting during inference if force_fp16 is enabled.
  160. # All tensor dtype conversion happens before inference.
  161. return contextlib.nullcontext()
  162. if fp8 and device==cpu:
  163. return torch.autocast("cpu", dtype=torch.bfloat16, enabled=True)
  164. if fp8 and dtype_inference == torch.float32:
  165. return manual_cast(dtype)
  166. if dtype == torch.float32 or dtype_inference == torch.float32:
  167. return contextlib.nullcontext()
  168. if has_xpu() or has_mps() or cuda_no_autocast():
  169. return manual_cast(dtype)
  170. return torch.autocast("cuda")
  171. def without_autocast(disable=False):
  172. return torch.autocast("cuda", enabled=False) if torch.is_autocast_enabled() and not disable else contextlib.nullcontext()
  173. class NansException(Exception):
  174. pass
  175. def test_for_nans(x, where):
  176. if shared.cmd_opts.disable_nan_check:
  177. return
  178. if not torch.isnan(x[(0, ) * len(x.shape)]):
  179. return
  180. if where == "unet":
  181. message = "A tensor with NaNs was produced in Unet."
  182. if not shared.cmd_opts.no_half:
  183. 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."
  184. elif where == "vae":
  185. message = "A tensor with NaNs was produced in VAE."
  186. if not shared.cmd_opts.no_half and not shared.cmd_opts.no_half_vae:
  187. message += " This could be because there's not enough precision to represent the picture. Try adding --no-half-vae commandline argument to fix this."
  188. else:
  189. message = "A tensor with NaNs was produced."
  190. message += " Use --disable-nan-check commandline argument to disable this check."
  191. raise NansException(message)
  192. @lru_cache
  193. def first_time_calculation():
  194. """
  195. just do any calculation with pytorch layers - the first time this is done it allocates about 700MB of memory and
  196. spends about 2.7 seconds doing that, at least with NVidia.
  197. """
  198. x = torch.zeros((1, 1)).to(device, dtype)
  199. linear = torch.nn.Linear(1, 1).to(device, dtype)
  200. linear(x)
  201. x = torch.zeros((1, 1, 3, 3)).to(device, dtype)
  202. conv2d = torch.nn.Conv2d(1, 1, (3, 3)).to(device, dtype)
  203. conv2d(x)
  204. def force_model_fp16():
  205. """
  206. ldm and sgm has modules.diffusionmodules.util.GroupNorm32.forward, which
  207. force conversion of input to float32. If force_fp16 is enabled, we need to
  208. prevent this casting.
  209. """
  210. assert force_fp16
  211. import sgm.modules.diffusionmodules.util as sgm_util
  212. import ldm.modules.diffusionmodules.util as ldm_util
  213. sgm_util.GroupNorm32 = torch.nn.GroupNorm
  214. ldm_util.GroupNorm32 = torch.nn.GroupNorm
  215. print("ldm/sgm GroupNorm32 replaced with normal torch.nn.GroupNorm due to `--precision half`.")