sd_models.py 37 KB

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