sd_models.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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}/runwayml/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 model.is_sdxl:
  311. sd_models_xl.extend_sdxl(model)
  312. if model.is_ssd:
  313. sd_hijack.model_hijack.convert_sdxl_to_ssd(model)
  314. if shared.opts.sd_checkpoint_cache > 0:
  315. # cache newly loaded model
  316. checkpoints_loaded[checkpoint_info] = state_dict.copy()
  317. if hasattr(model, "before_load_weights"):
  318. model.before_load_weights(state_dict)
  319. model.load_state_dict(state_dict, strict=False)
  320. timer.record("apply weights to model")
  321. if hasattr(model, "after_load_weights"):
  322. model.after_load_weights(state_dict)
  323. del state_dict
  324. # Set is_sdxl_inpaint flag.
  325. # Checks Unet structure to detect inpaint model. The inpaint model's
  326. # checkpoint state_dict does not contain the key
  327. # 'diffusion_model.input_blocks.0.0.weight'.
  328. diffusion_model_input = model.model.state_dict().get(
  329. 'diffusion_model.input_blocks.0.0.weight'
  330. )
  331. model.is_sdxl_inpaint = (
  332. model.is_sdxl and
  333. diffusion_model_input is not None and
  334. diffusion_model_input.shape[1] == 9
  335. )
  336. if shared.cmd_opts.opt_channelslast:
  337. model.to(memory_format=torch.channels_last)
  338. timer.record("apply channels_last")
  339. if shared.cmd_opts.no_half:
  340. model.float()
  341. model.alphas_cumprod_original = model.alphas_cumprod
  342. devices.dtype_unet = torch.float32
  343. assert shared.cmd_opts.precision != "half", "Cannot use --precision half with --no-half"
  344. timer.record("apply float()")
  345. else:
  346. vae = model.first_stage_model
  347. depth_model = getattr(model, 'depth_model', None)
  348. # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16
  349. if shared.cmd_opts.no_half_vae:
  350. model.first_stage_model = None
  351. # with --upcast-sampling, don't convert the depth model weights to float16
  352. if shared.cmd_opts.upcast_sampling and depth_model:
  353. model.depth_model = None
  354. alphas_cumprod = model.alphas_cumprod
  355. model.alphas_cumprod = None
  356. model.half()
  357. model.alphas_cumprod = alphas_cumprod
  358. model.alphas_cumprod_original = alphas_cumprod
  359. model.first_stage_model = vae
  360. if depth_model:
  361. model.depth_model = depth_model
  362. devices.dtype_unet = torch.float16
  363. timer.record("apply half()")
  364. apply_alpha_schedule_override(model)
  365. for module in model.modules():
  366. if hasattr(module, 'fp16_weight'):
  367. del module.fp16_weight
  368. if hasattr(module, 'fp16_bias'):
  369. del module.fp16_bias
  370. if check_fp8(model):
  371. devices.fp8 = True
  372. first_stage = model.first_stage_model
  373. model.first_stage_model = None
  374. for module in model.modules():
  375. if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)):
  376. if shared.opts.cache_fp16_weight:
  377. module.fp16_weight = module.weight.data.clone().cpu().half()
  378. if module.bias is not None:
  379. module.fp16_bias = module.bias.data.clone().cpu().half()
  380. module.to(torch.float8_e4m3fn)
  381. model.first_stage_model = first_stage
  382. timer.record("apply fp8")
  383. else:
  384. devices.fp8 = False
  385. devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16
  386. model.first_stage_model.to(devices.dtype_vae)
  387. timer.record("apply dtype to VAE")
  388. # clean up cache if limit is reached
  389. while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache:
  390. checkpoints_loaded.popitem(last=False)
  391. model.sd_model_hash = sd_model_hash
  392. model.sd_model_checkpoint = checkpoint_info.filename
  393. model.sd_checkpoint_info = checkpoint_info
  394. shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256
  395. if hasattr(model, 'logvar'):
  396. model.logvar = model.logvar.to(devices.device) # fix for training
  397. sd_vae.delete_base_vae()
  398. sd_vae.clear_loaded_vae()
  399. vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename).tuple()
  400. sd_vae.load_vae(model, vae_file, vae_source)
  401. timer.record("load VAE")
  402. def enable_midas_autodownload():
  403. """
  404. Gives the ldm.modules.midas.api.load_model function automatic downloading.
  405. When the 512-depth-ema model, and other future models like it, is loaded,
  406. it calls midas.api.load_model to load the associated midas depth model.
  407. This function applies a wrapper to download the model to the correct
  408. location automatically.
  409. """
  410. midas_path = os.path.join(paths.models_path, 'midas')
  411. # stable-diffusion-stability-ai hard-codes the midas model path to
  412. # a location that differs from where other scripts using this model look.
  413. # HACK: Overriding the path here.
  414. for k, v in midas.api.ISL_PATHS.items():
  415. file_name = os.path.basename(v)
  416. midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name)
  417. midas_urls = {
  418. "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
  419. "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt",
  420. "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt",
  421. "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt",
  422. }
  423. midas.api.load_model_inner = midas.api.load_model
  424. def load_model_wrapper(model_type):
  425. path = midas.api.ISL_PATHS[model_type]
  426. if not os.path.exists(path):
  427. if not os.path.exists(midas_path):
  428. os.mkdir(midas_path)
  429. print(f"Downloading midas model weights for {model_type} to {path}")
  430. request.urlretrieve(midas_urls[model_type], path)
  431. print(f"{model_type} downloaded")
  432. return midas.api.load_model_inner(model_type)
  433. midas.api.load_model = load_model_wrapper
  434. def patch_given_betas():
  435. import ldm.models.diffusion.ddpm
  436. def patched_register_schedule(*args, **kwargs):
  437. """a modified version of register_schedule function that converts plain list from Omegaconf into numpy"""
  438. if isinstance(args[1], ListConfig):
  439. args = (args[0], np.array(args[1]), *args[2:])
  440. original_register_schedule(*args, **kwargs)
  441. original_register_schedule = patches.patch(__name__, ldm.models.diffusion.ddpm.DDPM, 'register_schedule', patched_register_schedule)
  442. def repair_config(sd_config, state_dict=None):
  443. if not hasattr(sd_config.model.params, "use_ema"):
  444. sd_config.model.params.use_ema = False
  445. if hasattr(sd_config.model.params, 'unet_config'):
  446. if shared.cmd_opts.no_half:
  447. sd_config.model.params.unet_config.params.use_fp16 = False
  448. elif shared.cmd_opts.upcast_sampling or shared.cmd_opts.precision == "half":
  449. sd_config.model.params.unet_config.params.use_fp16 = True
  450. if hasattr(sd_config.model.params, 'first_stage_config'):
  451. if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available:
  452. sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla"
  453. # For UnCLIP-L, override the hardcoded karlo directory
  454. if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"):
  455. karlo_path = os.path.join(paths.models_path, 'karlo')
  456. 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)
  457. # Do not use checkpoint for inference.
  458. # This helps prevent extra performance overhead on checking parameters.
  459. # The perf overhead is about 100ms/it on 4090 for SDXL.
  460. if hasattr(sd_config.model.params, "network_config"):
  461. sd_config.model.params.network_config.params.use_checkpoint = False
  462. if hasattr(sd_config.model.params, "unet_config"):
  463. sd_config.model.params.unet_config.params.use_checkpoint = False
  464. def rescale_zero_terminal_snr_abar(alphas_cumprod):
  465. alphas_bar_sqrt = alphas_cumprod.sqrt()
  466. # Store old values.
  467. alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
  468. alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
  469. # Shift so the last timestep is zero.
  470. alphas_bar_sqrt -= (alphas_bar_sqrt_T)
  471. # Scale so the first timestep is back to the old value.
  472. alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
  473. # Convert alphas_bar_sqrt to betas
  474. alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt
  475. alphas_bar[-1] = 4.8973451890853435e-08
  476. return alphas_bar
  477. def apply_alpha_schedule_override(sd_model, p=None):
  478. """
  479. Applies an override to the alpha schedule of the model according to settings.
  480. - downcasts the alpha schedule to half precision
  481. - rescales the alpha schedule to have zero terminal SNR
  482. """
  483. if not hasattr(sd_model, 'alphas_cumprod') or not hasattr(sd_model, 'alphas_cumprod_original'):
  484. return
  485. sd_model.alphas_cumprod = sd_model.alphas_cumprod_original.to(shared.device)
  486. if opts.use_downcasted_alpha_bar:
  487. if p is not None:
  488. p.extra_generation_params['Downcast alphas_cumprod'] = opts.use_downcasted_alpha_bar
  489. sd_model.alphas_cumprod = sd_model.alphas_cumprod.half().to(shared.device)
  490. if opts.sd_noise_schedule == "Zero Terminal SNR":
  491. if p is not None:
  492. p.extra_generation_params['Noise Schedule'] = opts.sd_noise_schedule
  493. sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device)
  494. sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight'
  495. sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight'
  496. sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight'
  497. sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight'
  498. class SdModelData:
  499. def __init__(self):
  500. self.sd_model = None
  501. self.loaded_sd_models = []
  502. self.was_loaded_at_least_once = False
  503. self.lock = threading.Lock()
  504. def get_sd_model(self):
  505. if self.was_loaded_at_least_once:
  506. return self.sd_model
  507. if self.sd_model is None:
  508. with self.lock:
  509. if self.sd_model is not None or self.was_loaded_at_least_once:
  510. return self.sd_model
  511. try:
  512. load_model()
  513. except Exception as e:
  514. errors.display(e, "loading stable diffusion model", full_traceback=True)
  515. print("", file=sys.stderr)
  516. print("Stable diffusion model failed to load", file=sys.stderr)
  517. self.sd_model = None
  518. return self.sd_model
  519. def set_sd_model(self, v, already_loaded=False):
  520. self.sd_model = v
  521. if already_loaded:
  522. sd_vae.base_vae = getattr(v, "base_vae", None)
  523. sd_vae.loaded_vae_file = getattr(v, "loaded_vae_file", None)
  524. sd_vae.checkpoint_info = v.sd_checkpoint_info
  525. try:
  526. self.loaded_sd_models.remove(v)
  527. except ValueError:
  528. pass
  529. if v is not None:
  530. self.loaded_sd_models.insert(0, v)
  531. model_data = SdModelData()
  532. def get_empty_cond(sd_model):
  533. p = processing.StableDiffusionProcessingTxt2Img()
  534. extra_networks.activate(p, {})
  535. if hasattr(sd_model, 'get_learned_conditioning'):
  536. d = sd_model.get_learned_conditioning([""])
  537. else:
  538. d = sd_model.cond_stage_model([""])
  539. if isinstance(d, dict):
  540. d = d['crossattn']
  541. return d
  542. def send_model_to_cpu(m):
  543. if m is not None:
  544. if m.lowvram:
  545. lowvram.send_everything_to_cpu()
  546. else:
  547. m.to(devices.cpu)
  548. devices.torch_gc()
  549. def model_target_device(m):
  550. if lowvram.is_needed(m):
  551. return devices.cpu
  552. else:
  553. return devices.device
  554. def send_model_to_device(m):
  555. lowvram.apply(m)
  556. if not m.lowvram:
  557. m.to(shared.device)
  558. def send_model_to_trash(m):
  559. m.to(device="meta")
  560. devices.torch_gc()
  561. def instantiate_from_config(config, state_dict=None):
  562. constructor = get_obj_from_str(config["target"])
  563. params = {**config.get("params", {})}
  564. if state_dict and "state_dict" in params and params["state_dict"] is None:
  565. params["state_dict"] = state_dict
  566. return constructor(**params)
  567. def get_obj_from_str(string, reload=False):
  568. module, cls = string.rsplit(".", 1)
  569. if reload:
  570. module_imp = importlib.import_module(module)
  571. importlib.reload(module_imp)
  572. return getattr(importlib.import_module(module, package=None), cls)
  573. def load_model(checkpoint_info=None, already_loaded_state_dict=None):
  574. from modules import sd_hijack
  575. checkpoint_info = checkpoint_info or select_checkpoint()
  576. timer = Timer()
  577. if model_data.sd_model:
  578. send_model_to_trash(model_data.sd_model)
  579. model_data.sd_model = None
  580. devices.torch_gc()
  581. timer.record("unload existing model")
  582. if already_loaded_state_dict is not None:
  583. state_dict = already_loaded_state_dict
  584. else:
  585. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  586. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  587. 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)
  588. timer.record("find config")
  589. sd_config = OmegaConf.load(checkpoint_config)
  590. repair_config(sd_config, state_dict)
  591. timer.record("load config")
  592. print(f"Creating model from config: {checkpoint_config}")
  593. sd_model = None
  594. try:
  595. with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip):
  596. with sd_disable_initialization.InitializeOnMeta():
  597. sd_model = instantiate_from_config(sd_config.model, state_dict)
  598. except Exception as e:
  599. errors.display(e, "creating model quickly", full_traceback=True)
  600. if sd_model is None:
  601. print('Failed to create model quickly; will retry using slow method.', file=sys.stderr)
  602. with sd_disable_initialization.InitializeOnMeta():
  603. sd_model = instantiate_from_config(sd_config.model, state_dict)
  604. sd_model.used_config = checkpoint_config
  605. timer.record("create model")
  606. if shared.cmd_opts.no_half:
  607. weight_dtype_conversion = None
  608. else:
  609. weight_dtype_conversion = {
  610. 'first_stage_model': None,
  611. 'alphas_cumprod': None,
  612. '': torch.float16,
  613. }
  614. with sd_disable_initialization.LoadStateDictOnMeta(state_dict, device=model_target_device(sd_model), weight_dtype_conversion=weight_dtype_conversion):
  615. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  616. timer.record("load weights from state dict")
  617. send_model_to_device(sd_model)
  618. timer.record("move model to device")
  619. sd_hijack.model_hijack.hijack(sd_model)
  620. timer.record("hijack")
  621. sd_model.eval()
  622. model_data.set_sd_model(sd_model)
  623. model_data.was_loaded_at_least_once = True
  624. 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
  625. timer.record("load textual inversion embeddings")
  626. script_callbacks.model_loaded_callback(sd_model)
  627. timer.record("scripts callbacks")
  628. with devices.autocast(), torch.no_grad():
  629. sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model)
  630. timer.record("calculate empty prompt")
  631. print(f"Model loaded in {timer.summary()}.")
  632. return sd_model
  633. def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer):
  634. """
  635. Checks if the desired checkpoint from checkpoint_info is not already loaded in model_data.loaded_sd_models.
  636. If it is loaded, returns that (moving it to GPU if necessary, and moving the currently loadded model to CPU if necessary).
  637. If not, returns the model that can be used to load weights from checkpoint_info's file.
  638. If no such model exists, returns None.
  639. Additionally deletes loaded models that are over the limit set in settings (sd_checkpoints_limit).
  640. """
  641. if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  642. return sd_model
  643. if shared.opts.sd_checkpoints_keep_in_cpu:
  644. send_model_to_cpu(sd_model)
  645. timer.record("send model to cpu")
  646. already_loaded = None
  647. for i in reversed(range(len(model_data.loaded_sd_models))):
  648. loaded_model = model_data.loaded_sd_models[i]
  649. if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  650. already_loaded = loaded_model
  651. continue
  652. if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0:
  653. 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}")
  654. del model_data.loaded_sd_models[i]
  655. send_model_to_trash(loaded_model)
  656. timer.record("send model to trash")
  657. if already_loaded is not None:
  658. send_model_to_device(already_loaded)
  659. timer.record("send model to device")
  660. model_data.set_sd_model(already_loaded, already_loaded=True)
  661. if not SkipWritingToConfig.skip:
  662. shared.opts.data["sd_model_checkpoint"] = already_loaded.sd_checkpoint_info.title
  663. shared.opts.data["sd_checkpoint_hash"] = already_loaded.sd_checkpoint_info.sha256
  664. print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}")
  665. sd_vae.reload_vae_weights(already_loaded)
  666. return model_data.sd_model
  667. elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit:
  668. print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})")
  669. model_data.sd_model = None
  670. load_model(checkpoint_info)
  671. return model_data.sd_model
  672. elif len(model_data.loaded_sd_models) > 0:
  673. sd_model = model_data.loaded_sd_models.pop()
  674. model_data.sd_model = sd_model
  675. sd_vae.base_vae = getattr(sd_model, "base_vae", None)
  676. sd_vae.loaded_vae_file = getattr(sd_model, "loaded_vae_file", None)
  677. sd_vae.checkpoint_info = sd_model.sd_checkpoint_info
  678. print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}")
  679. return sd_model
  680. else:
  681. return None
  682. def reload_model_weights(sd_model=None, info=None, forced_reload=False):
  683. checkpoint_info = info or select_checkpoint()
  684. timer = Timer()
  685. if not sd_model:
  686. sd_model = model_data.sd_model
  687. if sd_model is None: # previous model load failed
  688. current_checkpoint_info = None
  689. else:
  690. current_checkpoint_info = sd_model.sd_checkpoint_info
  691. if check_fp8(sd_model) != devices.fp8:
  692. # load from state dict again to prevent extra numerical errors
  693. forced_reload = True
  694. elif sd_model.sd_model_checkpoint == checkpoint_info.filename and not forced_reload:
  695. return sd_model
  696. sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer)
  697. if not forced_reload and sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename:
  698. return sd_model
  699. if sd_model is not None:
  700. sd_unet.apply_unet("None")
  701. send_model_to_cpu(sd_model)
  702. sd_hijack.model_hijack.undo_hijack(sd_model)
  703. state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
  704. checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
  705. timer.record("find config")
  706. if sd_model is None or checkpoint_config != sd_model.used_config:
  707. if sd_model is not None:
  708. send_model_to_trash(sd_model)
  709. load_model(checkpoint_info, already_loaded_state_dict=state_dict)
  710. return model_data.sd_model
  711. try:
  712. load_model_weights(sd_model, checkpoint_info, state_dict, timer)
  713. except Exception:
  714. print("Failed to load checkpoint, restoring previous")
  715. load_model_weights(sd_model, current_checkpoint_info, None, timer)
  716. raise
  717. finally:
  718. sd_hijack.model_hijack.hijack(sd_model)
  719. timer.record("hijack")
  720. if not sd_model.lowvram:
  721. sd_model.to(devices.device)
  722. timer.record("move model to device")
  723. script_callbacks.model_loaded_callback(sd_model)
  724. timer.record("script callbacks")
  725. print(f"Weights loaded in {timer.summary()}.")
  726. model_data.set_sd_model(sd_model)
  727. sd_unet.apply_unet()
  728. return sd_model
  729. def unload_model_weights(sd_model=None, info=None):
  730. send_model_to_cpu(sd_model or shared.sd_model)
  731. return sd_model
  732. def apply_token_merging(sd_model, token_merging_ratio):
  733. """
  734. Applies speed and memory optimizations from tomesd.
  735. """
  736. current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0)
  737. if current_token_merging_ratio == token_merging_ratio:
  738. return
  739. if current_token_merging_ratio > 0:
  740. tomesd.remove_patch(sd_model)
  741. if token_merging_ratio > 0:
  742. tomesd.apply_patch(
  743. sd_model,
  744. ratio=token_merging_ratio,
  745. use_rand=False, # can cause issues with some samplers
  746. merge_attn=True,
  747. merge_crossattn=False,
  748. merge_mlp=False
  749. )
  750. sd_model.applied_token_merged_ratio = token_merging_ratio