sd_models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import collections
  2. import os.path
  3. import sys
  4. import gc
  5. import torch
  6. import re
  7. import safetensors.torch
  8. from omegaconf import OmegaConf
  9. from os import mkdir
  10. from urllib import request
  11. import ldm.modules.midas as midas
  12. from ldm.util import instantiate_from_config
  13. from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config
  14. from modules.paths import models_path
  15. from modules.sd_hijack_inpainting import do_inpainting_hijack
  16. from modules.timer import Timer
  17. model_dir = "Stable-diffusion"
  18. model_path = os.path.abspath(os.path.join(paths.models_path, model_dir))
  19. checkpoints_list = {}
  20. checkpoint_alisases = {}
  21. checkpoints_loaded = collections.OrderedDict()
  22. class CheckpointInfo:
  23. def __init__(self, filename):
  24. self.filename = filename
  25. abspath = os.path.abspath(filename)
  26. if shared.cmd_opts.ckpt_dir is not None and abspath.startswith(shared.cmd_opts.ckpt_dir):
  27. name = abspath.replace(shared.cmd_opts.ckpt_dir, '')
  28. elif abspath.startswith(model_path):
  29. name = abspath.replace(model_path, '')
  30. else:
  31. name = os.path.basename(filename)
  32. if name.startswith("\\") or name.startswith("/"):
  33. name = name[1:]
  34. self.name = name
  35. self.name_for_extra = os.path.splitext(os.path.basename(filename))[0]
  36. self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
  37. self.hash = model_hash(filename)
  38. self.sha256 = hashes.sha256_from_cache(self.filename, "checkpoint/" + name)
  39. self.shorthash = self.sha256[0:10] if self.sha256 else None
  40. self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]'
  41. self.ids = [self.hash, self.model_name, self.title, name, f'{name} [{self.hash}]'] + ([self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]'] if self.shorthash else [])
  42. def register(self):
  43. checkpoints_list[self.title] = self
  44. for id in self.ids:
  45. checkpoint_alisases[id] = self
  46. def calculate_shorthash(self):
  47. self.sha256 = hashes.sha256(self.filename, "checkpoint/" + self.name)
  48. if self.sha256 is None:
  49. return
  50. self.shorthash = self.sha256[0:10]
  51. if self.shorthash not in self.ids:
  52. self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]']
  53. checkpoints_list.pop(self.title)
  54. self.title = f'{self.name} [{self.shorthash}]'
  55. self.register()
  56. return self.shorthash
  57. try:
  58. # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
  59. from transformers import logging, CLIPModel
  60. logging.set_verbosity_error()
  61. except Exception:
  62. pass
  63. def setup_model():
  64. if not os.path.exists(model_path):
  65. os.makedirs(model_path)
  66. list_models()
  67. enable_midas_autodownload()
  68. def checkpoint_tiles():
  69. def convert(name):
  70. return int(name) if name.isdigit() else name.lower()
  71. def alphanumeric_key(key):
  72. return [convert(c) for c in re.split('([0-9]+)', key)]
  73. return sorted([x.title for x in checkpoints_list.values()], key=alphanumeric_key)
  74. def list_models():
  75. checkpoints_list.clear()
  76. checkpoint_alisases.clear()
  77. cmd_ckpt = shared.cmd_opts.ckpt
  78. if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt):
  79. model_url = None
  80. else:
  81. model_url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors"
  82. model_list = modelloader.load_models(model_path=model_path, model_url=model_url, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt", ".safetensors"], download_name="v1-5-pruned-emaonly.safetensors", ext_blacklist=[".vae.ckpt", ".vae.safetensors"])
  83. if os.path.exists(cmd_ckpt):
  84. checkpoint_info = CheckpointInfo(cmd_ckpt)
  85. checkpoint_info.register()
  86. shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title
  87. elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
  88. print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr)
  89. for filename in model_list:
  90. checkpoint_info = CheckpointInfo(filename)
  91. checkpoint_info.register()
  92. def get_closet_checkpoint_match(search_string):
  93. checkpoint_info = checkpoint_alisases.get(search_string, None)
  94. if checkpoint_info is not None:
  95. return checkpoint_info
  96. found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title))
  97. if found:
  98. return found[0]
  99. return None
  100. def model_hash(filename):
  101. """old hash that only looks at a small part of the file and is prone to collisions"""
  102. try:
  103. with open(filename, "rb") as file:
  104. import hashlib
  105. m = hashlib.sha256()
  106. file.seek(0x100000)
  107. m.update(file.read(0x10000))
  108. return m.hexdigest()[0:8]
  109. except FileNotFoundError:
  110. return 'NOFILE'
  111. def select_checkpoint():
  112. model_checkpoint = shared.opts.sd_model_checkpoint
  113. checkpoint_info = checkpoint_alisases.get(model_checkpoint, None)
  114. if checkpoint_info is not None:
  115. return checkpoint_info
  116. if len(checkpoints_list) == 0:
  117. print("No checkpoints found. When searching for checkpoints, looked at:", file=sys.stderr)
  118. if shared.cmd_opts.ckpt is not None:
  119. print(f" - file {os.path.abspath(shared.cmd_opts.ckpt)}", file=sys.stderr)
  120. print(f" - directory {model_path}", file=sys.stderr)
  121. if shared.cmd_opts.ckpt_dir is not None:
  122. print(f" - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}", file=sys.stderr)
  123. print("Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations. The program will exit.", file=sys.stderr)
  124. exit(1)
  125. checkpoint_info = next(iter(checkpoints_list.values()))
  126. if model_checkpoint is not None:
  127. print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr)
  128. return checkpoint_info
  129. chckpoint_dict_replacements = {
  130. 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.',
  131. 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.',
  132. 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.',
  133. }
  134. def transform_checkpoint_dict_key(k):
  135. for text, replacement in chckpoint_dict_replacements.items():
  136. if k.startswith(text):
  137. k = replacement + k[len(text):]
  138. return k
  139. def get_state_dict_from_checkpoint(pl_sd):
  140. pl_sd = pl_sd.pop("state_dict", pl_sd)
  141. pl_sd.pop("state_dict", None)
  142. sd = {}
  143. for k, v in pl_sd.items():
  144. new_key = transform_checkpoint_dict_key(k)
  145. if new_key is not None:
  146. sd[new_key] = v
  147. pl_sd.clear()
  148. pl_sd.update(sd)
  149. return pl_sd
  150. def read_metadata_from_safetensors(filename):
  151. import json
  152. with open(filename, mode="rb") as file:
  153. metadata_len = file.read(8)
  154. metadata_len = int.from_bytes(metadata_len, "little")
  155. json_start = file.read(2)
  156. assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file"
  157. json_data = json_start + file.read(metadata_len-2)
  158. json_obj = json.loads(json_data)
  159. res = {}
  160. for k, v in json_obj.get("__metadata__", {}).items():
  161. res[k] = v
  162. if isinstance(v, str) and v[0:1] == '{':
  163. try:
  164. res[k] = json.loads(v)
  165. except Exception as e:
  166. pass
  167. return res
  168. def read_state_dict(checkpoint_file, print_global_state=False, map_location=None):
  169. _, extension = os.path.splitext(checkpoint_file)
  170. if extension.lower() == ".safetensors":
  171. device = map_location or shared.weight_load_location or devices.get_optimal_device_name()
  172. pl_sd = safetensors.torch.load_file(checkpoint_file, device=device)
  173. else:
  174. pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location)
  175. if print_global_state and "global_step" in pl_sd:
  176. print(f"Global Step: {pl_sd['global_step']}")
  177. sd = get_state_dict_from_checkpoint(pl_sd)
  178. return sd
  179. def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer):
  180. sd_model_hash = checkpoint_info.calculate_shorthash()
  181. timer.record("calculate hash")
  182. if checkpoint_info in checkpoints_loaded:
  183. # use checkpoint cache
  184. print(f"Loading weights [{sd_model_hash}] from cache")
  185. return checkpoints_loaded[checkpoint_info]
  186. print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}")
  187. res = read_state_dict(checkpoint_info.filename)
  188. timer.record("load weights from disk")
  189. return res
  190. def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer):
  191. sd_model_hash = checkpoint_info.calculate_shorthash()
  192. timer.record("calculate hash")
  193. shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title
  194. if state_dict is None:
  195. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  196. model.load_state_dict(state_dict, strict=False)
  197. del state_dict
  198. timer.record("apply weights to model")
  199. if shared.opts.sd_checkpoint_cache > 0:
  200. # cache newly loaded model
  201. checkpoints_loaded[checkpoint_info] = model.state_dict().copy()
  202. if shared.cmd_opts.opt_channelslast:
  203. model.to(memory_format=torch.channels_last)
  204. timer.record("apply channels_last")
  205. if not shared.cmd_opts.no_half:
  206. vae = model.first_stage_model
  207. depth_model = getattr(model, 'depth_model', None)
  208. # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16
  209. if shared.cmd_opts.no_half_vae:
  210. model.first_stage_model = None
  211. # with --upcast-sampling, don't convert the depth model weights to float16
  212. if shared.cmd_opts.upcast_sampling and depth_model:
  213. model.depth_model = None
  214. model.half()
  215. model.first_stage_model = vae
  216. if depth_model:
  217. model.depth_model = depth_model
  218. timer.record("apply half()")
  219. devices.dtype = torch.float32 if shared.cmd_opts.no_half else torch.float16
  220. devices.dtype_vae = torch.float32 if shared.cmd_opts.no_half or shared.cmd_opts.no_half_vae else torch.float16
  221. devices.dtype_unet = model.model.diffusion_model.dtype
  222. devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16
  223. model.first_stage_model.to(devices.dtype_vae)
  224. timer.record("apply dtype to VAE")
  225. # clean up cache if limit is reached
  226. while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache:
  227. checkpoints_loaded.popitem(last=False)
  228. model.sd_model_hash = sd_model_hash
  229. model.sd_model_checkpoint = checkpoint_info.filename
  230. model.sd_checkpoint_info = checkpoint_info
  231. shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256
  232. model.logvar = model.logvar.to(devices.device) # fix for training
  233. sd_vae.delete_base_vae()
  234. sd_vae.clear_loaded_vae()
  235. vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename)
  236. sd_vae.load_vae(model, vae_file, vae_source)
  237. timer.record("load VAE")
  238. def enable_midas_autodownload():
  239. """
  240. Gives the ldm.modules.midas.api.load_model function automatic downloading.
  241. When the 512-depth-ema model, and other future models like it, is loaded,
  242. it calls midas.api.load_model to load the associated midas depth model.
  243. This function applies a wrapper to download the model to the correct
  244. location automatically.
  245. """
  246. midas_path = os.path.join(paths.models_path, 'midas')
  247. # stable-diffusion-stability-ai hard-codes the midas model path to
  248. # a location that differs from where other scripts using this model look.
  249. # HACK: Overriding the path here.
  250. for k, v in midas.api.ISL_PATHS.items():
  251. file_name = os.path.basename(v)
  252. midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name)
  253. midas_urls = {
  254. "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
  255. "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt",
  256. "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt",
  257. "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt",
  258. }
  259. midas.api.load_model_inner = midas.api.load_model
  260. def load_model_wrapper(model_type):
  261. path = midas.api.ISL_PATHS[model_type]
  262. if not os.path.exists(path):
  263. if not os.path.exists(midas_path):
  264. mkdir(midas_path)
  265. print(f"Downloading midas model weights for {model_type} to {path}")
  266. request.urlretrieve(midas_urls[model_type], path)
  267. print(f"{model_type} downloaded")
  268. return midas.api.load_model_inner(model_type)
  269. midas.api.load_model = load_model_wrapper
  270. def repair_config(sd_config):
  271. if not hasattr(sd_config.model.params, "use_ema"):
  272. sd_config.model.params.use_ema = False
  273. if shared.cmd_opts.no_half:
  274. sd_config.model.params.unet_config.params.use_fp16 = False
  275. elif shared.cmd_opts.upcast_sampling:
  276. sd_config.model.params.unet_config.params.use_fp16 = True
  277. # For UnCLIP-L, override the hardcoded karlo directory
  278. if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"):
  279. karlo_path = os.path.join(paths.models_path, 'karlo')
  280. sd_config.model.params.noise_aug_config.params.clip_stats_path = sd_config.model.params.noise_aug_config.params.clip_stats_path.replace("checkpoints/karlo_models", karlo_path)
  281. sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight'
  282. sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight'
  283. def load_model(checkpoint_info=None, already_loaded_state_dict=None, time_taken_to_load_state_dict=None):
  284. from modules import lowvram, sd_hijack
  285. checkpoint_info = checkpoint_info or select_checkpoint()
  286. if shared.sd_model:
  287. sd_hijack.model_hijack.undo_hijack(shared.sd_model)
  288. shared.sd_model = None
  289. gc.collect()
  290. devices.torch_gc()
  291. do_inpainting_hijack()
  292. timer = Timer()
  293. if already_loaded_state_dict is not None:
  294. state_dict = already_loaded_state_dict
  295. else:
  296. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  297. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  298. clip_is_included_into_sd = sd1_clip_weight in state_dict or sd2_clip_weight in state_dict
  299. timer.record("find config")
  300. sd_config = OmegaConf.load(checkpoint_config)
  301. repair_config(sd_config)
  302. timer.record("load config")
  303. print(f"Creating model from config: {checkpoint_config}")
  304. sd_model = None
  305. try:
  306. with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd):
  307. sd_model = instantiate_from_config(sd_config.model)
  308. except Exception as e:
  309. pass
  310. if sd_model is None:
  311. print('Failed to create model quickly; will retry using slow method.', file=sys.stderr)
  312. sd_model = instantiate_from_config(sd_config.model)
  313. sd_model.used_config = checkpoint_config
  314. timer.record("create model")
  315. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  316. if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
  317. lowvram.setup_for_low_vram(sd_model, shared.cmd_opts.medvram)
  318. else:
  319. sd_model.to(shared.device)
  320. timer.record("move model to device")
  321. sd_hijack.model_hijack.hijack(sd_model)
  322. timer.record("hijack")
  323. sd_model.eval()
  324. shared.sd_model = sd_model
  325. sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True) # Reload embeddings after model load as they may or may not fit the model
  326. timer.record("load textual inversion embeddings")
  327. script_callbacks.model_loaded_callback(sd_model)
  328. timer.record("scripts callbacks")
  329. print(f"Model loaded in {timer.summary()}.")
  330. return sd_model
  331. def reload_model_weights(sd_model=None, info=None):
  332. from modules import lowvram, devices, sd_hijack
  333. checkpoint_info = info or select_checkpoint()
  334. if not sd_model:
  335. sd_model = shared.sd_model
  336. if sd_model is None: # previous model load failed
  337. current_checkpoint_info = None
  338. else:
  339. current_checkpoint_info = sd_model.sd_checkpoint_info
  340. if sd_model.sd_model_checkpoint == checkpoint_info.filename:
  341. return
  342. if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
  343. lowvram.send_everything_to_cpu()
  344. else:
  345. sd_model.to(devices.cpu)
  346. sd_hijack.model_hijack.undo_hijack(sd_model)
  347. timer = Timer()
  348. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  349. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  350. timer.record("find config")
  351. if sd_model is None or checkpoint_config != sd_model.used_config:
  352. del sd_model
  353. checkpoints_loaded.clear()
  354. load_model(checkpoint_info, already_loaded_state_dict=state_dict, time_taken_to_load_state_dict=timer.records["load weights from disk"])
  355. return shared.sd_model
  356. try:
  357. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  358. except Exception as e:
  359. print("Failed to load checkpoint, restoring previous")
  360. load_model_weights(sd_model, current_checkpoint_info, None, timer)
  361. raise
  362. finally:
  363. sd_hijack.model_hijack.hijack(sd_model)
  364. timer.record("hijack")
  365. script_callbacks.model_loaded_callback(sd_model)
  366. timer.record("script callbacks")
  367. if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
  368. sd_model.to(devices.device)
  369. timer.record("move model to device")
  370. print(f"Weights loaded in {timer.summary()}.")
  371. return sd_model