sd_models.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. import collections
  2. import os
  3. import sys
  4. import threading
  5. import torch
  6. import re
  7. import safetensors.torch
  8. from omegaconf import OmegaConf, ListConfig
  9. from urllib import request
  10. import ldm.modules.midas as midas
  11. from ldm.util import instantiate_from_config
  12. 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, extra_networks, processing, lowvram, sd_hijack, patches
  13. from modules.timer import Timer
  14. from modules.shared import opts
  15. import tomesd
  16. import numpy as np
  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. def replace_key(d, key, new_key, value):
  24. keys = list(d.keys())
  25. d[new_key] = value
  26. if key not in keys:
  27. return d
  28. index = keys.index(key)
  29. keys[index] = new_key
  30. new_d = {k: d[k] for k in keys}
  31. d.clear()
  32. d.update(new_d)
  33. return d
  34. class CheckpointInfo:
  35. def __init__(self, filename):
  36. self.filename = filename
  37. abspath = os.path.abspath(filename)
  38. abs_ckpt_dir = os.path.abspath(shared.cmd_opts.ckpt_dir) if shared.cmd_opts.ckpt_dir is not None else None
  39. self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
  40. if abs_ckpt_dir and abspath.startswith(abs_ckpt_dir):
  41. name = abspath.replace(abs_ckpt_dir, '')
  42. elif abspath.startswith(model_path):
  43. name = abspath.replace(model_path, '')
  44. else:
  45. name = os.path.basename(filename)
  46. if name.startswith("\\") or name.startswith("/"):
  47. name = name[1:]
  48. def read_metadata():
  49. metadata = read_metadata_from_safetensors(filename)
  50. self.modelspec_thumbnail = metadata.pop('modelspec.thumbnail', None)
  51. return metadata
  52. self.metadata = {}
  53. if self.is_safetensors:
  54. try:
  55. self.metadata = cache.cached_data_for_file('safetensors-metadata', "checkpoint/" + name, filename, read_metadata)
  56. except Exception as e:
  57. errors.display(e, f"reading metadata for {filename}")
  58. self.name = name
  59. self.name_for_extra = os.path.splitext(os.path.basename(filename))[0]
  60. self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
  61. self.hash = model_hash(filename)
  62. self.sha256 = hashes.sha256_from_cache(self.filename, f"checkpoint/{name}")
  63. self.shorthash = self.sha256[0:10] if self.sha256 else None
  64. self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]'
  65. self.short_title = self.name_for_extra if self.shorthash is None else f'{self.name_for_extra} [{self.shorthash}]'
  66. self.ids = [self.hash, self.model_name, self.title, name, self.name_for_extra, f'{name} [{self.hash}]']
  67. if self.shorthash:
  68. self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]']
  69. def register(self):
  70. checkpoints_list[self.title] = self
  71. for id in self.ids:
  72. checkpoint_aliases[id] = self
  73. def calculate_shorthash(self):
  74. self.sha256 = hashes.sha256(self.filename, f"checkpoint/{self.name}")
  75. if self.sha256 is None:
  76. return
  77. shorthash = self.sha256[0:10]
  78. if self.shorthash == self.sha256[0:10]:
  79. return self.shorthash
  80. self.shorthash = shorthash
  81. if self.shorthash not in self.ids:
  82. self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]']
  83. old_title = self.title
  84. self.title = f'{self.name} [{self.shorthash}]'
  85. self.short_title = f'{self.name_for_extra} [{self.shorthash}]'
  86. replace_key(checkpoints_list, old_title, self.title, self)
  87. self.register()
  88. return self.shorthash
  89. try:
  90. # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
  91. from transformers import logging, CLIPModel # noqa: F401
  92. logging.set_verbosity_error()
  93. except Exception:
  94. pass
  95. def setup_model():
  96. """called once at startup to do various one-time tasks related to SD models"""
  97. os.makedirs(model_path, exist_ok=True)
  98. enable_midas_autodownload()
  99. patch_given_betas()
  100. def checkpoint_tiles(use_short=False):
  101. return [x.short_title if use_short else x.title for x in checkpoints_list.values()]
  102. def list_models():
  103. checkpoints_list.clear()
  104. checkpoint_aliases.clear()
  105. cmd_ckpt = shared.cmd_opts.ckpt
  106. if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt):
  107. model_url = None
  108. else:
  109. model_url = f"{shared.hf_endpoint}/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors"
  110. 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"])
  111. if os.path.exists(cmd_ckpt):
  112. checkpoint_info = CheckpointInfo(cmd_ckpt)
  113. checkpoint_info.register()
  114. shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title
  115. elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
  116. print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr)
  117. for filename in model_list:
  118. checkpoint_info = CheckpointInfo(filename)
  119. checkpoint_info.register()
  120. re_strip_checksum = re.compile(r"\s*\[[^]]+]\s*$")
  121. def get_closet_checkpoint_match(search_string):
  122. if not search_string:
  123. return None
  124. checkpoint_info = checkpoint_aliases.get(search_string, None)
  125. if checkpoint_info is not None:
  126. return checkpoint_info
  127. found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title))
  128. if found:
  129. return found[0]
  130. search_string_without_checksum = re.sub(re_strip_checksum, '', search_string)
  131. found = sorted([info for info in checkpoints_list.values() if search_string_without_checksum in info.title], key=lambda x: len(x.title))
  132. if found:
  133. return found[0]
  134. return None
  135. def model_hash(filename):
  136. """old hash that only looks at a small part of the file and is prone to collisions"""
  137. try:
  138. with open(filename, "rb") as file:
  139. import hashlib
  140. m = hashlib.sha256()
  141. file.seek(0x100000)
  142. m.update(file.read(0x10000))
  143. return m.hexdigest()[0:8]
  144. except FileNotFoundError:
  145. return 'NOFILE'
  146. def select_checkpoint():
  147. """Raises `FileNotFoundError` if no checkpoints are found."""
  148. model_checkpoint = shared.opts.sd_model_checkpoint
  149. checkpoint_info = checkpoint_aliases.get(model_checkpoint, None)
  150. if checkpoint_info is not None:
  151. return checkpoint_info
  152. if len(checkpoints_list) == 0:
  153. error_message = "No checkpoints found. When searching for checkpoints, looked at:"
  154. if shared.cmd_opts.ckpt is not None:
  155. error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}"
  156. error_message += f"\n - directory {model_path}"
  157. if shared.cmd_opts.ckpt_dir is not None:
  158. error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}"
  159. error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations."
  160. raise FileNotFoundError(error_message)
  161. checkpoint_info = next(iter(checkpoints_list.values()))
  162. if model_checkpoint is not None:
  163. print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr)
  164. return checkpoint_info
  165. checkpoint_dict_replacements_sd1 = {
  166. 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.',
  167. 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.',
  168. 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.',
  169. }
  170. checkpoint_dict_replacements_sd2_turbo = { # Converts SD 2.1 Turbo from SGM to LDM format.
  171. 'conditioner.embedders.0.': 'cond_stage_model.',
  172. }
  173. def transform_checkpoint_dict_key(k, replacements):
  174. for text, replacement in replacements.items():
  175. if k.startswith(text):
  176. k = replacement + k[len(text):]
  177. return k
  178. def get_state_dict_from_checkpoint(pl_sd):
  179. pl_sd = pl_sd.pop("state_dict", pl_sd)
  180. pl_sd.pop("state_dict", None)
  181. is_sd2_turbo = 'conditioner.embedders.0.model.ln_final.weight' in pl_sd and pl_sd['conditioner.embedders.0.model.ln_final.weight'].size()[0] == 1024
  182. sd = {}
  183. for k, v in pl_sd.items():
  184. if is_sd2_turbo:
  185. new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd2_turbo)
  186. else:
  187. new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd1)
  188. if new_key is not None:
  189. sd[new_key] = v
  190. pl_sd.clear()
  191. pl_sd.update(sd)
  192. return pl_sd
  193. def read_metadata_from_safetensors(filename):
  194. import json
  195. with open(filename, mode="rb") as file:
  196. metadata_len = file.read(8)
  197. metadata_len = int.from_bytes(metadata_len, "little")
  198. json_start = file.read(2)
  199. assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file"
  200. json_data = json_start + file.read(metadata_len-2)
  201. json_obj = json.loads(json_data)
  202. res = {}
  203. for k, v in json_obj.get("__metadata__", {}).items():
  204. res[k] = v
  205. if isinstance(v, str) and v[0:1] == '{':
  206. try:
  207. res[k] = json.loads(v)
  208. except Exception:
  209. pass
  210. return res
  211. def read_state_dict(checkpoint_file, print_global_state=False, map_location=None):
  212. _, extension = os.path.splitext(checkpoint_file)
  213. if extension.lower() == ".safetensors":
  214. device = map_location or shared.weight_load_location or devices.get_optimal_device_name()
  215. if not shared.opts.disable_mmap_load_safetensors:
  216. pl_sd = safetensors.torch.load_file(checkpoint_file, device=device)
  217. else:
  218. pl_sd = safetensors.torch.load(open(checkpoint_file, 'rb').read())
  219. pl_sd = {k: v.to(device) for k, v in pl_sd.items()}
  220. else:
  221. pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location)
  222. if print_global_state and "global_step" in pl_sd:
  223. print(f"Global Step: {pl_sd['global_step']}")
  224. sd = get_state_dict_from_checkpoint(pl_sd)
  225. return sd
  226. def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer):
  227. sd_model_hash = checkpoint_info.calculate_shorthash()
  228. timer.record("calculate hash")
  229. if checkpoint_info in checkpoints_loaded:
  230. # use checkpoint cache
  231. print(f"Loading weights [{sd_model_hash}] from cache")
  232. # move to end as latest
  233. checkpoints_loaded.move_to_end(checkpoint_info)
  234. return checkpoints_loaded[checkpoint_info]
  235. print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}")
  236. res = read_state_dict(checkpoint_info.filename)
  237. timer.record("load weights from disk")
  238. return res
  239. class SkipWritingToConfig:
  240. """This context manager prevents load_model_weights from writing checkpoint name to the config when it loads weight."""
  241. skip = False
  242. previous = None
  243. def __enter__(self):
  244. self.previous = SkipWritingToConfig.skip
  245. SkipWritingToConfig.skip = True
  246. return self
  247. def __exit__(self, exc_type, exc_value, exc_traceback):
  248. SkipWritingToConfig.skip = self.previous
  249. def check_fp8(model):
  250. if model is None:
  251. return None
  252. if devices.get_optimal_device_name() == "mps":
  253. enable_fp8 = False
  254. elif shared.opts.fp8_storage == "Enable":
  255. enable_fp8 = True
  256. elif getattr(model, "is_sdxl", False) and shared.opts.fp8_storage == "Enable for SDXL":
  257. enable_fp8 = True
  258. else:
  259. enable_fp8 = False
  260. return enable_fp8
  261. def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer):
  262. sd_model_hash = checkpoint_info.calculate_shorthash()
  263. timer.record("calculate hash")
  264. if devices.fp8:
  265. # prevent model to load state dict in fp8
  266. model.half()
  267. if not SkipWritingToConfig.skip:
  268. shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title
  269. if state_dict is None:
  270. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  271. model.is_sdxl = hasattr(model, 'conditioner')
  272. model.is_sd2 = not model.is_sdxl and hasattr(model.cond_stage_model, 'model')
  273. model.is_sd1 = not model.is_sdxl and not model.is_sd2
  274. model.is_ssd = model.is_sdxl and 'model.diffusion_model.middle_block.1.transformer_blocks.0.attn1.to_q.weight' not in state_dict.keys()
  275. if model.is_sdxl:
  276. sd_models_xl.extend_sdxl(model)
  277. if model.is_ssd:
  278. sd_hijack.model_hijack.convert_sdxl_to_ssd(model)
  279. if shared.opts.sd_checkpoint_cache > 0:
  280. # cache newly loaded model
  281. checkpoints_loaded[checkpoint_info] = state_dict.copy()
  282. model.load_state_dict(state_dict, strict=False)
  283. timer.record("apply weights to model")
  284. del state_dict
  285. if shared.cmd_opts.opt_channelslast:
  286. model.to(memory_format=torch.channels_last)
  287. timer.record("apply channels_last")
  288. if shared.cmd_opts.no_half:
  289. model.float()
  290. model.alphas_cumprod_original = model.alphas_cumprod
  291. devices.dtype_unet = torch.float32
  292. timer.record("apply float()")
  293. else:
  294. vae = model.first_stage_model
  295. depth_model = getattr(model, 'depth_model', None)
  296. # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16
  297. if shared.cmd_opts.no_half_vae:
  298. model.first_stage_model = None
  299. # with --upcast-sampling, don't convert the depth model weights to float16
  300. if shared.cmd_opts.upcast_sampling and depth_model:
  301. model.depth_model = None
  302. alphas_cumprod = model.alphas_cumprod
  303. model.alphas_cumprod = None
  304. model.half()
  305. model.alphas_cumprod = alphas_cumprod
  306. model.alphas_cumprod_original = alphas_cumprod
  307. model.first_stage_model = vae
  308. if depth_model:
  309. model.depth_model = depth_model
  310. devices.dtype_unet = torch.float16
  311. timer.record("apply half()")
  312. apply_alpha_schedule_override(model)
  313. for module in model.modules():
  314. if hasattr(module, 'fp16_weight'):
  315. del module.fp16_weight
  316. if hasattr(module, 'fp16_bias'):
  317. del module.fp16_bias
  318. if check_fp8(model):
  319. devices.fp8 = True
  320. first_stage = model.first_stage_model
  321. model.first_stage_model = None
  322. for module in model.modules():
  323. if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)):
  324. if shared.opts.cache_fp16_weight:
  325. module.fp16_weight = module.weight.data.clone().cpu().half()
  326. if module.bias is not None:
  327. module.fp16_bias = module.bias.data.clone().cpu().half()
  328. module.to(torch.float8_e4m3fn)
  329. model.first_stage_model = first_stage
  330. timer.record("apply fp8")
  331. else:
  332. devices.fp8 = False
  333. devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16
  334. model.first_stage_model.to(devices.dtype_vae)
  335. timer.record("apply dtype to VAE")
  336. # clean up cache if limit is reached
  337. while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache:
  338. checkpoints_loaded.popitem(last=False)
  339. model.sd_model_hash = sd_model_hash
  340. model.sd_model_checkpoint = checkpoint_info.filename
  341. model.sd_checkpoint_info = checkpoint_info
  342. shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256
  343. if hasattr(model, 'logvar'):
  344. model.logvar = model.logvar.to(devices.device) # fix for training
  345. sd_vae.delete_base_vae()
  346. sd_vae.clear_loaded_vae()
  347. vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename).tuple()
  348. sd_vae.load_vae(model, vae_file, vae_source)
  349. timer.record("load VAE")
  350. def enable_midas_autodownload():
  351. """
  352. Gives the ldm.modules.midas.api.load_model function automatic downloading.
  353. When the 512-depth-ema model, and other future models like it, is loaded,
  354. it calls midas.api.load_model to load the associated midas depth model.
  355. This function applies a wrapper to download the model to the correct
  356. location automatically.
  357. """
  358. midas_path = os.path.join(paths.models_path, 'midas')
  359. # stable-diffusion-stability-ai hard-codes the midas model path to
  360. # a location that differs from where other scripts using this model look.
  361. # HACK: Overriding the path here.
  362. for k, v in midas.api.ISL_PATHS.items():
  363. file_name = os.path.basename(v)
  364. midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name)
  365. midas_urls = {
  366. "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
  367. "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt",
  368. "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt",
  369. "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt",
  370. }
  371. midas.api.load_model_inner = midas.api.load_model
  372. def load_model_wrapper(model_type):
  373. path = midas.api.ISL_PATHS[model_type]
  374. if not os.path.exists(path):
  375. if not os.path.exists(midas_path):
  376. os.mkdir(midas_path)
  377. print(f"Downloading midas model weights for {model_type} to {path}")
  378. request.urlretrieve(midas_urls[model_type], path)
  379. print(f"{model_type} downloaded")
  380. return midas.api.load_model_inner(model_type)
  381. midas.api.load_model = load_model_wrapper
  382. def patch_given_betas():
  383. import ldm.models.diffusion.ddpm
  384. def patched_register_schedule(*args, **kwargs):
  385. """a modified version of register_schedule function that converts plain list from Omegaconf into numpy"""
  386. if isinstance(args[1], ListConfig):
  387. args = (args[0], np.array(args[1]), *args[2:])
  388. original_register_schedule(*args, **kwargs)
  389. original_register_schedule = patches.patch(__name__, ldm.models.diffusion.ddpm.DDPM, 'register_schedule', patched_register_schedule)
  390. def repair_config(sd_config):
  391. if not hasattr(sd_config.model.params, "use_ema"):
  392. sd_config.model.params.use_ema = False
  393. if hasattr(sd_config.model.params, 'unet_config'):
  394. if shared.cmd_opts.no_half:
  395. sd_config.model.params.unet_config.params.use_fp16 = False
  396. elif shared.cmd_opts.upcast_sampling:
  397. sd_config.model.params.unet_config.params.use_fp16 = True
  398. if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available:
  399. sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla"
  400. # For UnCLIP-L, override the hardcoded karlo directory
  401. if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"):
  402. karlo_path = os.path.join(paths.models_path, 'karlo')
  403. 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)
  404. def rescale_zero_terminal_snr_abar(alphas_cumprod):
  405. alphas_bar_sqrt = alphas_cumprod.sqrt()
  406. # Store old values.
  407. alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
  408. alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
  409. # Shift so the last timestep is zero.
  410. alphas_bar_sqrt -= (alphas_bar_sqrt_T)
  411. # Scale so the first timestep is back to the old value.
  412. alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
  413. # Convert alphas_bar_sqrt to betas
  414. alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt
  415. alphas_bar[-1] = 4.8973451890853435e-08
  416. return alphas_bar
  417. def apply_alpha_schedule_override(sd_model, p=None):
  418. """
  419. Applies an override to the alpha schedule of the model according to settings.
  420. - downcasts the alpha schedule to half precision
  421. - rescales the alpha schedule to have zero terminal SNR
  422. """
  423. if not hasattr(sd_model, 'alphas_cumprod') or not hasattr(sd_model, 'alphas_cumprod_original'):
  424. return
  425. sd_model.alphas_cumprod = sd_model.alphas_cumprod_original.to(shared.device)
  426. if opts.use_downcasted_alpha_bar:
  427. if p is not None:
  428. p.extra_generation_params['Downcast alphas_cumprod'] = opts.use_downcasted_alpha_bar
  429. sd_model.alphas_cumprod = sd_model.alphas_cumprod.half().to(shared.device)
  430. if opts.sd_noise_schedule == "Zero Terminal SNR":
  431. if p is not None:
  432. p.extra_generation_params['Noise Schedule'] = opts.sd_noise_schedule
  433. sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device)
  434. sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight'
  435. sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight'
  436. sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight'
  437. sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight'
  438. class SdModelData:
  439. def __init__(self):
  440. self.sd_model = None
  441. self.loaded_sd_models = []
  442. self.was_loaded_at_least_once = False
  443. self.lock = threading.Lock()
  444. def get_sd_model(self):
  445. if self.was_loaded_at_least_once:
  446. return self.sd_model
  447. if self.sd_model is None:
  448. with self.lock:
  449. if self.sd_model is not None or self.was_loaded_at_least_once:
  450. return self.sd_model
  451. try:
  452. load_model()
  453. except Exception as e:
  454. errors.display(e, "loading stable diffusion model", full_traceback=True)
  455. print("", file=sys.stderr)
  456. print("Stable diffusion model failed to load", file=sys.stderr)
  457. self.sd_model = None
  458. return self.sd_model
  459. def set_sd_model(self, v, already_loaded=False):
  460. self.sd_model = v
  461. if already_loaded:
  462. sd_vae.base_vae = getattr(v, "base_vae", None)
  463. sd_vae.loaded_vae_file = getattr(v, "loaded_vae_file", None)
  464. sd_vae.checkpoint_info = v.sd_checkpoint_info
  465. try:
  466. self.loaded_sd_models.remove(v)
  467. except ValueError:
  468. pass
  469. if v is not None:
  470. self.loaded_sd_models.insert(0, v)
  471. model_data = SdModelData()
  472. def get_empty_cond(sd_model):
  473. p = processing.StableDiffusionProcessingTxt2Img()
  474. extra_networks.activate(p, {})
  475. if hasattr(sd_model, 'conditioner'):
  476. d = sd_model.get_learned_conditioning([""])
  477. return d['crossattn']
  478. else:
  479. return sd_model.cond_stage_model([""])
  480. def send_model_to_cpu(m):
  481. if m.lowvram:
  482. lowvram.send_everything_to_cpu()
  483. else:
  484. m.to(devices.cpu)
  485. devices.torch_gc()
  486. def model_target_device(m):
  487. if lowvram.is_needed(m):
  488. return devices.cpu
  489. else:
  490. return devices.device
  491. def send_model_to_device(m):
  492. lowvram.apply(m)
  493. if not m.lowvram:
  494. m.to(shared.device)
  495. def send_model_to_trash(m):
  496. m.to(device="meta")
  497. devices.torch_gc()
  498. def load_model(checkpoint_info=None, already_loaded_state_dict=None):
  499. from modules import sd_hijack
  500. checkpoint_info = checkpoint_info or select_checkpoint()
  501. timer = Timer()
  502. if model_data.sd_model:
  503. send_model_to_trash(model_data.sd_model)
  504. model_data.sd_model = None
  505. devices.torch_gc()
  506. timer.record("unload existing model")
  507. if already_loaded_state_dict is not None:
  508. state_dict = already_loaded_state_dict
  509. else:
  510. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  511. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  512. 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)
  513. timer.record("find config")
  514. sd_config = OmegaConf.load(checkpoint_config)
  515. repair_config(sd_config)
  516. timer.record("load config")
  517. print(f"Creating model from config: {checkpoint_config}")
  518. sd_model = None
  519. try:
  520. with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip):
  521. with sd_disable_initialization.InitializeOnMeta():
  522. sd_model = instantiate_from_config(sd_config.model)
  523. except Exception as e:
  524. errors.display(e, "creating model quickly", full_traceback=True)
  525. if sd_model is None:
  526. print('Failed to create model quickly; will retry using slow method.', file=sys.stderr)
  527. with sd_disable_initialization.InitializeOnMeta():
  528. sd_model = instantiate_from_config(sd_config.model)
  529. sd_model.used_config = checkpoint_config
  530. timer.record("create model")
  531. if shared.cmd_opts.no_half:
  532. weight_dtype_conversion = None
  533. else:
  534. weight_dtype_conversion = {
  535. 'first_stage_model': None,
  536. 'alphas_cumprod': None,
  537. '': torch.float16,
  538. }
  539. with sd_disable_initialization.LoadStateDictOnMeta(state_dict, device=model_target_device(sd_model), weight_dtype_conversion=weight_dtype_conversion):
  540. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  541. timer.record("load weights from state dict")
  542. send_model_to_device(sd_model)
  543. timer.record("move model to device")
  544. sd_hijack.model_hijack.hijack(sd_model)
  545. timer.record("hijack")
  546. sd_model.eval()
  547. model_data.set_sd_model(sd_model)
  548. model_data.was_loaded_at_least_once = True
  549. 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
  550. timer.record("load textual inversion embeddings")
  551. script_callbacks.model_loaded_callback(sd_model)
  552. timer.record("scripts callbacks")
  553. with devices.autocast(), torch.no_grad():
  554. sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model)
  555. timer.record("calculate empty prompt")
  556. print(f"Model loaded in {timer.summary()}.")
  557. return sd_model
  558. def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer):
  559. """
  560. Checks if the desired checkpoint from checkpoint_info is not already loaded in model_data.loaded_sd_models.
  561. If it is loaded, returns that (moving it to GPU if necessary, and moving the currently loadded model to CPU if necessary).
  562. If not, returns the model that can be used to load weights from checkpoint_info's file.
  563. If no such model exists, returns None.
  564. Additionally deletes loaded models that are over the limit set in settings (sd_checkpoints_limit).
  565. """
  566. if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  567. return sd_model
  568. if shared.opts.sd_checkpoints_keep_in_cpu:
  569. send_model_to_cpu(sd_model)
  570. timer.record("send model to cpu")
  571. already_loaded = None
  572. for i in reversed(range(len(model_data.loaded_sd_models))):
  573. loaded_model = model_data.loaded_sd_models[i]
  574. if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  575. already_loaded = loaded_model
  576. continue
  577. if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0:
  578. 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}")
  579. del model_data.loaded_sd_models[i]
  580. send_model_to_trash(loaded_model)
  581. timer.record("send model to trash")
  582. if already_loaded is not None:
  583. send_model_to_device(already_loaded)
  584. timer.record("send model to device")
  585. model_data.set_sd_model(already_loaded, already_loaded=True)
  586. if not SkipWritingToConfig.skip:
  587. shared.opts.data["sd_model_checkpoint"] = already_loaded.sd_checkpoint_info.title
  588. shared.opts.data["sd_checkpoint_hash"] = already_loaded.sd_checkpoint_info.sha256
  589. print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}")
  590. sd_vae.reload_vae_weights(already_loaded)
  591. return model_data.sd_model
  592. elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit:
  593. print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})")
  594. model_data.sd_model = None
  595. load_model(checkpoint_info)
  596. return model_data.sd_model
  597. elif len(model_data.loaded_sd_models) > 0:
  598. sd_model = model_data.loaded_sd_models.pop()
  599. model_data.sd_model = sd_model
  600. sd_vae.base_vae = getattr(sd_model, "base_vae", None)
  601. sd_vae.loaded_vae_file = getattr(sd_model, "loaded_vae_file", None)
  602. sd_vae.checkpoint_info = sd_model.sd_checkpoint_info
  603. print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}")
  604. return sd_model
  605. else:
  606. return None
  607. def reload_model_weights(sd_model=None, info=None, forced_reload=False):
  608. checkpoint_info = info or select_checkpoint()
  609. timer = Timer()
  610. if not sd_model:
  611. sd_model = model_data.sd_model
  612. if sd_model is None: # previous model load failed
  613. current_checkpoint_info = None
  614. else:
  615. current_checkpoint_info = sd_model.sd_checkpoint_info
  616. if check_fp8(sd_model) != devices.fp8:
  617. # load from state dict again to prevent extra numerical errors
  618. forced_reload = True
  619. elif sd_model.sd_model_checkpoint == checkpoint_info.filename and not forced_reload:
  620. return sd_model
  621. sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer)
  622. if not forced_reload and sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  623. return sd_model
  624. if sd_model is not None:
  625. sd_unet.apply_unet("None")
  626. send_model_to_cpu(sd_model)
  627. sd_hijack.model_hijack.undo_hijack(sd_model)
  628. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  629. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  630. timer.record("find config")
  631. if sd_model is None or checkpoint_config != sd_model.used_config:
  632. if sd_model is not None:
  633. send_model_to_trash(sd_model)
  634. load_model(checkpoint_info, already_loaded_state_dict=state_dict)
  635. return model_data.sd_model
  636. try:
  637. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  638. except Exception:
  639. print("Failed to load checkpoint, restoring previous")
  640. load_model_weights(sd_model, current_checkpoint_info, None, timer)
  641. raise
  642. finally:
  643. sd_hijack.model_hijack.hijack(sd_model)
  644. timer.record("hijack")
  645. if not sd_model.lowvram:
  646. sd_model.to(devices.device)
  647. timer.record("move model to device")
  648. script_callbacks.model_loaded_callback(sd_model)
  649. timer.record("script callbacks")
  650. print(f"Weights loaded in {timer.summary()}.")
  651. model_data.set_sd_model(sd_model)
  652. sd_unet.apply_unet()
  653. return sd_model
  654. def unload_model_weights(sd_model=None, info=None):
  655. send_model_to_cpu(sd_model or shared.sd_model)
  656. return sd_model
  657. def apply_token_merging(sd_model, token_merging_ratio):
  658. """
  659. Applies speed and memory optimizations from tomesd.
  660. """
  661. current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0)
  662. if current_token_merging_ratio == token_merging_ratio:
  663. return
  664. if current_token_merging_ratio > 0:
  665. tomesd.remove_patch(sd_model)
  666. if token_merging_ratio > 0:
  667. tomesd.apply_patch(
  668. sd_model,
  669. ratio=token_merging_ratio,
  670. use_rand=False, # can cause issues with some samplers
  671. merge_attn=True,
  672. merge_crossattn=False,
  673. merge_mlp=False
  674. )
  675. sd_model.applied_token_merged_ratio = token_merging_ratio