sd_models.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. import collections
  2. import os.path
  3. import sys
  4. import gc
  5. import threading
  6. import torch
  7. import re
  8. import safetensors.torch
  9. from omegaconf import OmegaConf
  10. from os import mkdir
  11. from urllib import request
  12. import ldm.modules.midas as midas
  13. from ldm.util import instantiate_from_config
  14. from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config, sd_unet, sd_models_xl, cache
  15. from modules.timer import Timer
  16. import tomesd
  17. model_dir = "Stable-diffusion"
  18. model_path = os.path.abspath(os.path.join(paths.models_path, model_dir))
  19. checkpoints_list = {}
  20. checkpoint_aliases = {}
  21. checkpoint_alisases = checkpoint_aliases # for compatibility with old name
  22. checkpoints_loaded = collections.OrderedDict()
  23. class CheckpointInfo:
  24. def __init__(self, filename):
  25. self.filename = filename
  26. abspath = os.path.abspath(filename)
  27. self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
  28. if shared.cmd_opts.ckpt_dir is not None and abspath.startswith(shared.cmd_opts.ckpt_dir):
  29. name = abspath.replace(shared.cmd_opts.ckpt_dir, '')
  30. elif abspath.startswith(model_path):
  31. name = abspath.replace(model_path, '')
  32. else:
  33. name = os.path.basename(filename)
  34. if name.startswith("\\") or name.startswith("/"):
  35. name = name[1:]
  36. def read_metadata():
  37. metadata = read_metadata_from_safetensors(filename)
  38. self.modelspec_thumbnail = metadata.pop('modelspec.thumbnail', None)
  39. return metadata
  40. self.metadata = {}
  41. if self.is_safetensors:
  42. try:
  43. self.metadata = cache.cached_data_for_file('safetensors-metadata', "checkpoint/" + name, filename, read_metadata)
  44. except Exception as e:
  45. errors.display(e, f"reading metadata for {filename}")
  46. self.name = name
  47. self.name_for_extra = os.path.splitext(os.path.basename(filename))[0]
  48. self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
  49. self.hash = model_hash(filename)
  50. self.sha256 = hashes.sha256_from_cache(self.filename, f"checkpoint/{name}")
  51. self.shorthash = self.sha256[0:10] if self.sha256 else None
  52. self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]'
  53. self.short_title = self.name_for_extra if self.shorthash is None else f'{self.name_for_extra} [{self.shorthash}]'
  54. self.ids = [self.hash, self.model_name, self.title, name, self.name_for_extra, f'{name} [{self.hash}]'] + ([self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]'] if self.shorthash else [])
  55. def register(self):
  56. checkpoints_list[self.title] = self
  57. for id in self.ids:
  58. checkpoint_aliases[id] = self
  59. def calculate_shorthash(self):
  60. self.sha256 = hashes.sha256(self.filename, f"checkpoint/{self.name}")
  61. if self.sha256 is None:
  62. return
  63. self.shorthash = self.sha256[0:10]
  64. if self.shorthash not in self.ids:
  65. self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]']
  66. checkpoints_list.pop(self.title, None)
  67. self.title = f'{self.name} [{self.shorthash}]'
  68. self.short_title = f'{self.name_for_extra} [{self.shorthash}]'
  69. self.register()
  70. return self.shorthash
  71. try:
  72. # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
  73. from transformers import logging, CLIPModel # noqa: F401
  74. logging.set_verbosity_error()
  75. except Exception:
  76. pass
  77. def setup_model():
  78. os.makedirs(model_path, exist_ok=True)
  79. enable_midas_autodownload()
  80. def checkpoint_tiles(use_short=False):
  81. return [x.short_title if use_short else x.title for x in checkpoints_list.values()]
  82. def list_models():
  83. checkpoints_list.clear()
  84. checkpoint_aliases.clear()
  85. cmd_ckpt = shared.cmd_opts.ckpt
  86. if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt):
  87. model_url = None
  88. else:
  89. model_url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors"
  90. 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"])
  91. if os.path.exists(cmd_ckpt):
  92. checkpoint_info = CheckpointInfo(cmd_ckpt)
  93. checkpoint_info.register()
  94. shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title
  95. elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
  96. print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr)
  97. for filename in model_list:
  98. checkpoint_info = CheckpointInfo(filename)
  99. checkpoint_info.register()
  100. re_strip_checksum = re.compile(r"\s*\[[^]]+]\s*$")
  101. def get_closet_checkpoint_match(search_string):
  102. checkpoint_info = checkpoint_aliases.get(search_string, None)
  103. if checkpoint_info is not None:
  104. return checkpoint_info
  105. found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title))
  106. if found:
  107. return found[0]
  108. search_string_without_checksum = re.sub(re_strip_checksum, '', search_string)
  109. found = sorted([info for info in checkpoints_list.values() if search_string_without_checksum in info.title], key=lambda x: len(x.title))
  110. if found:
  111. return found[0]
  112. return None
  113. def model_hash(filename):
  114. """old hash that only looks at a small part of the file and is prone to collisions"""
  115. try:
  116. with open(filename, "rb") as file:
  117. import hashlib
  118. m = hashlib.sha256()
  119. file.seek(0x100000)
  120. m.update(file.read(0x10000))
  121. return m.hexdigest()[0:8]
  122. except FileNotFoundError:
  123. return 'NOFILE'
  124. def select_checkpoint():
  125. """Raises `FileNotFoundError` if no checkpoints are found."""
  126. model_checkpoint = shared.opts.sd_model_checkpoint
  127. checkpoint_info = checkpoint_aliases.get(model_checkpoint, None)
  128. if checkpoint_info is not None:
  129. return checkpoint_info
  130. if len(checkpoints_list) == 0:
  131. error_message = "No checkpoints found. When searching for checkpoints, looked at:"
  132. if shared.cmd_opts.ckpt is not None:
  133. error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}"
  134. error_message += f"\n - directory {model_path}"
  135. if shared.cmd_opts.ckpt_dir is not None:
  136. error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}"
  137. error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations."
  138. raise FileNotFoundError(error_message)
  139. checkpoint_info = next(iter(checkpoints_list.values()))
  140. if model_checkpoint is not None:
  141. print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr)
  142. return checkpoint_info
  143. checkpoint_dict_replacements = {
  144. 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.',
  145. 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.',
  146. 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.',
  147. }
  148. def transform_checkpoint_dict_key(k):
  149. for text, replacement in checkpoint_dict_replacements.items():
  150. if k.startswith(text):
  151. k = replacement + k[len(text):]
  152. return k
  153. def get_state_dict_from_checkpoint(pl_sd):
  154. pl_sd = pl_sd.pop("state_dict", pl_sd)
  155. pl_sd.pop("state_dict", None)
  156. sd = {}
  157. for k, v in pl_sd.items():
  158. new_key = transform_checkpoint_dict_key(k)
  159. if new_key is not None:
  160. sd[new_key] = v
  161. pl_sd.clear()
  162. pl_sd.update(sd)
  163. return pl_sd
  164. def read_metadata_from_safetensors(filename):
  165. import json
  166. with open(filename, mode="rb") as file:
  167. metadata_len = file.read(8)
  168. metadata_len = int.from_bytes(metadata_len, "little")
  169. json_start = file.read(2)
  170. assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file"
  171. json_data = json_start + file.read(metadata_len-2)
  172. json_obj = json.loads(json_data)
  173. res = {}
  174. for k, v in json_obj.get("__metadata__", {}).items():
  175. res[k] = v
  176. if isinstance(v, str) and v[0:1] == '{':
  177. try:
  178. res[k] = json.loads(v)
  179. except Exception:
  180. pass
  181. return res
  182. def read_state_dict(checkpoint_file, print_global_state=False, map_location=None):
  183. _, extension = os.path.splitext(checkpoint_file)
  184. if extension.lower() == ".safetensors":
  185. device = map_location or shared.weight_load_location or devices.get_optimal_device_name()
  186. if not shared.opts.disable_mmap_load_safetensors:
  187. pl_sd = safetensors.torch.load_file(checkpoint_file, device=device)
  188. else:
  189. pl_sd = safetensors.torch.load(open(checkpoint_file, 'rb').read())
  190. pl_sd = {k: v.to(device) for k, v in pl_sd.items()}
  191. else:
  192. pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location)
  193. if print_global_state and "global_step" in pl_sd:
  194. print(f"Global Step: {pl_sd['global_step']}")
  195. sd = get_state_dict_from_checkpoint(pl_sd)
  196. return sd
  197. def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer):
  198. sd_model_hash = checkpoint_info.calculate_shorthash()
  199. timer.record("calculate hash")
  200. if checkpoint_info in checkpoints_loaded:
  201. # use checkpoint cache
  202. print(f"Loading weights [{sd_model_hash}] from cache")
  203. return checkpoints_loaded[checkpoint_info]
  204. print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}")
  205. res = read_state_dict(checkpoint_info.filename)
  206. timer.record("load weights from disk")
  207. return res
  208. def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer):
  209. sd_model_hash = checkpoint_info.calculate_shorthash()
  210. timer.record("calculate hash")
  211. shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title
  212. if state_dict is None:
  213. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  214. model.is_sdxl = hasattr(model, 'conditioner')
  215. model.is_sd2 = not model.is_sdxl and hasattr(model.cond_stage_model, 'model')
  216. model.is_sd1 = not model.is_sdxl and not model.is_sd2
  217. if model.is_sdxl:
  218. sd_models_xl.extend_sdxl(model)
  219. model.load_state_dict(state_dict, strict=False)
  220. timer.record("apply weights to model")
  221. if shared.opts.sd_checkpoint_cache > 0:
  222. # cache newly loaded model
  223. checkpoints_loaded[checkpoint_info] = state_dict
  224. del state_dict
  225. if shared.cmd_opts.opt_channelslast:
  226. model.to(memory_format=torch.channels_last)
  227. timer.record("apply channels_last")
  228. if not shared.cmd_opts.no_half:
  229. vae = model.first_stage_model
  230. depth_model = getattr(model, 'depth_model', None)
  231. # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16
  232. if shared.cmd_opts.no_half_vae:
  233. model.first_stage_model = None
  234. # with --upcast-sampling, don't convert the depth model weights to float16
  235. if shared.cmd_opts.upcast_sampling and depth_model:
  236. model.depth_model = None
  237. model.half()
  238. model.first_stage_model = vae
  239. if depth_model:
  240. model.depth_model = depth_model
  241. timer.record("apply half()")
  242. devices.dtype_unet = torch.float16 if model.is_sdxl and not shared.cmd_opts.no_half else model.model.diffusion_model.dtype
  243. devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16
  244. model.first_stage_model.to(devices.dtype_vae)
  245. timer.record("apply dtype to VAE")
  246. # clean up cache if limit is reached
  247. while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache:
  248. checkpoints_loaded.popitem(last=False)
  249. model.sd_model_hash = sd_model_hash
  250. model.sd_model_checkpoint = checkpoint_info.filename
  251. model.sd_checkpoint_info = checkpoint_info
  252. shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256
  253. if hasattr(model, 'logvar'):
  254. model.logvar = model.logvar.to(devices.device) # fix for training
  255. sd_vae.delete_base_vae()
  256. sd_vae.clear_loaded_vae()
  257. vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename)
  258. sd_vae.load_vae(model, vae_file, vae_source)
  259. timer.record("load VAE")
  260. def enable_midas_autodownload():
  261. """
  262. Gives the ldm.modules.midas.api.load_model function automatic downloading.
  263. When the 512-depth-ema model, and other future models like it, is loaded,
  264. it calls midas.api.load_model to load the associated midas depth model.
  265. This function applies a wrapper to download the model to the correct
  266. location automatically.
  267. """
  268. midas_path = os.path.join(paths.models_path, 'midas')
  269. # stable-diffusion-stability-ai hard-codes the midas model path to
  270. # a location that differs from where other scripts using this model look.
  271. # HACK: Overriding the path here.
  272. for k, v in midas.api.ISL_PATHS.items():
  273. file_name = os.path.basename(v)
  274. midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name)
  275. midas_urls = {
  276. "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
  277. "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt",
  278. "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt",
  279. "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt",
  280. }
  281. midas.api.load_model_inner = midas.api.load_model
  282. def load_model_wrapper(model_type):
  283. path = midas.api.ISL_PATHS[model_type]
  284. if not os.path.exists(path):
  285. if not os.path.exists(midas_path):
  286. mkdir(midas_path)
  287. print(f"Downloading midas model weights for {model_type} to {path}")
  288. request.urlretrieve(midas_urls[model_type], path)
  289. print(f"{model_type} downloaded")
  290. return midas.api.load_model_inner(model_type)
  291. midas.api.load_model = load_model_wrapper
  292. def repair_config(sd_config):
  293. if not hasattr(sd_config.model.params, "use_ema"):
  294. sd_config.model.params.use_ema = False
  295. if hasattr(sd_config.model.params, 'unet_config'):
  296. if shared.cmd_opts.no_half:
  297. sd_config.model.params.unet_config.params.use_fp16 = False
  298. elif shared.cmd_opts.upcast_sampling:
  299. sd_config.model.params.unet_config.params.use_fp16 = True
  300. if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available:
  301. sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla"
  302. # For UnCLIP-L, override the hardcoded karlo directory
  303. if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"):
  304. karlo_path = os.path.join(paths.models_path, 'karlo')
  305. 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)
  306. sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight'
  307. sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight'
  308. sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight'
  309. sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight'
  310. class SdModelData:
  311. def __init__(self):
  312. self.sd_model = None
  313. self.loaded_sd_models = []
  314. self.was_loaded_at_least_once = False
  315. self.lock = threading.Lock()
  316. def get_sd_model(self):
  317. if self.was_loaded_at_least_once:
  318. return self.sd_model
  319. if self.sd_model is None:
  320. with self.lock:
  321. if self.sd_model is not None or self.was_loaded_at_least_once:
  322. return self.sd_model
  323. try:
  324. load_model()
  325. except Exception as e:
  326. errors.display(e, "loading stable diffusion model", full_traceback=True)
  327. print("", file=sys.stderr)
  328. print("Stable diffusion model failed to load", file=sys.stderr)
  329. self.sd_model = None
  330. return self.sd_model
  331. def set_sd_model(self, v):
  332. self.sd_model = v
  333. try:
  334. self.loaded_sd_models.remove(v)
  335. except ValueError:
  336. pass
  337. if v is not None:
  338. self.loaded_sd_models.insert(0, v)
  339. model_data = SdModelData()
  340. def get_empty_cond(sd_model):
  341. from modules import extra_networks, processing
  342. p = processing.StableDiffusionProcessingTxt2Img()
  343. extra_networks.activate(p, {})
  344. if hasattr(sd_model, 'conditioner'):
  345. d = sd_model.get_learned_conditioning([""])
  346. return d['crossattn']
  347. else:
  348. return sd_model.cond_stage_model([""])
  349. def send_model_to_cpu(m):
  350. from modules import lowvram
  351. if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
  352. lowvram.send_everything_to_cpu()
  353. else:
  354. m.to(devices.cpu)
  355. devices.torch_gc()
  356. def send_model_to_device(m):
  357. from modules import lowvram
  358. if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
  359. lowvram.setup_for_low_vram(m, shared.cmd_opts.medvram)
  360. else:
  361. m.to(shared.device)
  362. def send_model_to_trash(m):
  363. m.to(device="meta")
  364. devices.torch_gc()
  365. def load_model(checkpoint_info=None, already_loaded_state_dict=None):
  366. from modules import sd_hijack
  367. checkpoint_info = checkpoint_info or select_checkpoint()
  368. timer = Timer()
  369. if model_data.sd_model:
  370. send_model_to_trash(model_data.sd_model)
  371. model_data.sd_model = None
  372. devices.torch_gc()
  373. timer.record("unload existing model")
  374. if already_loaded_state_dict is not None:
  375. state_dict = already_loaded_state_dict
  376. else:
  377. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  378. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  379. clip_is_included_into_sd = any(x for x in [sd1_clip_weight, sd2_clip_weight, sdxl_clip_weight, sdxl_refiner_clip_weight] if x in state_dict)
  380. timer.record("find config")
  381. sd_config = OmegaConf.load(checkpoint_config)
  382. repair_config(sd_config)
  383. timer.record("load config")
  384. print(f"Creating model from config: {checkpoint_config}")
  385. sd_model = None
  386. try:
  387. with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip):
  388. with sd_disable_initialization.InitializeOnMeta():
  389. sd_model = instantiate_from_config(sd_config.model)
  390. except Exception as e:
  391. errors.display(e, "creating model quickly", full_traceback=True)
  392. if sd_model is None:
  393. print('Failed to create model quickly; will retry using slow method.', file=sys.stderr)
  394. with sd_disable_initialization.InitializeOnMeta():
  395. sd_model = instantiate_from_config(sd_config.model)
  396. sd_model.used_config = checkpoint_config
  397. timer.record("create model")
  398. with sd_disable_initialization.LoadStateDictOnMeta(state_dict, devices.cpu):
  399. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  400. timer.record("load weights from state dict")
  401. send_model_to_device(sd_model)
  402. timer.record("move model to device")
  403. sd_hijack.model_hijack.hijack(sd_model)
  404. timer.record("hijack")
  405. sd_model.eval()
  406. model_data.set_sd_model(sd_model)
  407. model_data.was_loaded_at_least_once = True
  408. 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
  409. timer.record("load textual inversion embeddings")
  410. script_callbacks.model_loaded_callback(sd_model)
  411. timer.record("scripts callbacks")
  412. with devices.autocast(), torch.no_grad():
  413. sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model)
  414. timer.record("calculate empty prompt")
  415. print(f"Model loaded in {timer.summary()}.")
  416. return sd_model
  417. def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer):
  418. """
  419. Checks if the desired checkpoint from checkpoint_info is not already loaded in model_data.loaded_sd_models.
  420. If it is loaded, returns that (moving it to GPU if necessary, and moving the currently loadded model to CPU if necessary).
  421. If not, returns the model that can be used to load weights from checkpoint_info's file.
  422. If no such model exists, returns None.
  423. Additionaly deletes loaded models that are over the limit set in settings (sd_checkpoints_limit).
  424. """
  425. already_loaded = None
  426. for i in reversed(range(len(model_data.loaded_sd_models))):
  427. loaded_model = model_data.loaded_sd_models[i]
  428. if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  429. already_loaded = loaded_model
  430. continue
  431. if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0:
  432. print(f"Unloading model {len(model_data.loaded_sd_models)} over the limit of {shared.opts.sd_checkpoints_limit}: {loaded_model.sd_checkpoint_info.title}")
  433. model_data.loaded_sd_models.pop()
  434. send_model_to_trash(loaded_model)
  435. timer.record("send model to trash")
  436. if shared.opts.sd_checkpoints_keep_in_cpu:
  437. send_model_to_cpu(sd_model)
  438. timer.record("send model to cpu")
  439. if already_loaded is not None:
  440. send_model_to_device(already_loaded)
  441. timer.record("send model to device")
  442. model_data.set_sd_model(already_loaded)
  443. print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}")
  444. return model_data.sd_model
  445. elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit:
  446. print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})")
  447. model_data.sd_model = None
  448. load_model(checkpoint_info)
  449. return model_data.sd_model
  450. elif len(model_data.loaded_sd_models) > 0:
  451. sd_model = model_data.loaded_sd_models.pop()
  452. model_data.sd_model = sd_model
  453. print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}")
  454. return sd_model
  455. else:
  456. return None
  457. def reload_model_weights(sd_model=None, info=None):
  458. from modules import devices, sd_hijack
  459. checkpoint_info = info or select_checkpoint()
  460. timer = Timer()
  461. if not sd_model:
  462. sd_model = model_data.sd_model
  463. if sd_model is None: # previous model load failed
  464. current_checkpoint_info = None
  465. else:
  466. current_checkpoint_info = sd_model.sd_checkpoint_info
  467. if sd_model.sd_model_checkpoint == checkpoint_info.filename:
  468. return sd_model
  469. sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer)
  470. if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  471. return sd_model
  472. if sd_model is not None:
  473. sd_unet.apply_unet("None")
  474. send_model_to_cpu(sd_model)
  475. sd_hijack.model_hijack.undo_hijack(sd_model)
  476. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  477. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  478. timer.record("find config")
  479. if sd_model is None or checkpoint_config != sd_model.used_config:
  480. if sd_model is not None:
  481. send_model_to_trash(sd_model)
  482. load_model(checkpoint_info, already_loaded_state_dict=state_dict)
  483. return model_data.sd_model
  484. try:
  485. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  486. except Exception:
  487. print("Failed to load checkpoint, restoring previous")
  488. load_model_weights(sd_model, current_checkpoint_info, None, timer)
  489. raise
  490. finally:
  491. sd_hijack.model_hijack.hijack(sd_model)
  492. timer.record("hijack")
  493. script_callbacks.model_loaded_callback(sd_model)
  494. timer.record("script callbacks")
  495. if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
  496. sd_model.to(devices.device)
  497. timer.record("move model to device")
  498. print(f"Weights loaded in {timer.summary()}.")
  499. model_data.set_sd_model(sd_model)
  500. return sd_model
  501. def unload_model_weights(sd_model=None, info=None):
  502. from modules import devices, sd_hijack
  503. timer = Timer()
  504. if model_data.sd_model:
  505. model_data.sd_model.to(devices.cpu)
  506. sd_hijack.model_hijack.undo_hijack(model_data.sd_model)
  507. model_data.sd_model = None
  508. sd_model = None
  509. gc.collect()
  510. devices.torch_gc()
  511. print(f"Unloaded weights {timer.summary()}.")
  512. return sd_model
  513. def apply_token_merging(sd_model, token_merging_ratio):
  514. """
  515. Applies speed and memory optimizations from tomesd.
  516. """
  517. current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0)
  518. if current_token_merging_ratio == token_merging_ratio:
  519. return
  520. if current_token_merging_ratio > 0:
  521. tomesd.remove_patch(sd_model)
  522. if token_merging_ratio > 0:
  523. tomesd.apply_patch(
  524. sd_model,
  525. ratio=token_merging_ratio,
  526. use_rand=False, # can cause issues with some samplers
  527. merge_attn=True,
  528. merge_crossattn=False,
  529. merge_mlp=False
  530. )
  531. sd_model.applied_token_merged_ratio = token_merging_ratio