sd_vae.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import os
  2. import collections
  3. from modules import paths, shared, devices, script_callbacks, sd_models
  4. import glob
  5. from copy import deepcopy
  6. vae_path = os.path.abspath(os.path.join(paths.models_path, "VAE"))
  7. vae_ignore_keys = {"model_ema.decay", "model_ema.num_updates"}
  8. vae_dict = {}
  9. base_vae = None
  10. loaded_vae_file = None
  11. checkpoint_info = None
  12. checkpoints_loaded = collections.OrderedDict()
  13. def get_base_vae(model):
  14. if base_vae is not None and checkpoint_info == model.sd_checkpoint_info and model:
  15. return base_vae
  16. return None
  17. def store_base_vae(model):
  18. global base_vae, checkpoint_info
  19. if checkpoint_info != model.sd_checkpoint_info:
  20. assert not loaded_vae_file, "Trying to store non-base VAE!"
  21. base_vae = deepcopy(model.first_stage_model.state_dict())
  22. checkpoint_info = model.sd_checkpoint_info
  23. def delete_base_vae():
  24. global base_vae, checkpoint_info
  25. base_vae = None
  26. checkpoint_info = None
  27. def restore_base_vae(model):
  28. global loaded_vae_file
  29. if base_vae is not None and checkpoint_info == model.sd_checkpoint_info:
  30. print("Restoring base VAE")
  31. _load_vae_dict(model, base_vae)
  32. loaded_vae_file = None
  33. delete_base_vae()
  34. def get_filename(filepath):
  35. return os.path.basename(filepath)
  36. def refresh_vae_list():
  37. vae_dict.clear()
  38. paths = [
  39. os.path.join(sd_models.model_path, '**/*.vae.ckpt'),
  40. os.path.join(sd_models.model_path, '**/*.vae.pt'),
  41. os.path.join(sd_models.model_path, '**/*.vae.safetensors'),
  42. os.path.join(vae_path, '**/*.ckpt'),
  43. os.path.join(vae_path, '**/*.pt'),
  44. os.path.join(vae_path, '**/*.safetensors'),
  45. ]
  46. if shared.cmd_opts.ckpt_dir is not None and os.path.isdir(shared.cmd_opts.ckpt_dir):
  47. paths += [
  48. os.path.join(shared.cmd_opts.ckpt_dir, '**/*.vae.ckpt'),
  49. os.path.join(shared.cmd_opts.ckpt_dir, '**/*.vae.pt'),
  50. os.path.join(shared.cmd_opts.ckpt_dir, '**/*.vae.safetensors'),
  51. ]
  52. if shared.cmd_opts.vae_dir is not None and os.path.isdir(shared.cmd_opts.vae_dir):
  53. paths += [
  54. os.path.join(shared.cmd_opts.vae_dir, '**/*.ckpt'),
  55. os.path.join(shared.cmd_opts.vae_dir, '**/*.pt'),
  56. os.path.join(shared.cmd_opts.vae_dir, '**/*.safetensors'),
  57. ]
  58. candidates = []
  59. for path in paths:
  60. candidates += glob.iglob(path, recursive=True)
  61. for filepath in candidates:
  62. name = get_filename(filepath)
  63. vae_dict[name] = filepath
  64. def find_vae_near_checkpoint(checkpoint_file):
  65. checkpoint_path = os.path.basename(checkpoint_file).rsplit('.', 1)[0]
  66. for vae_file in vae_dict.values():
  67. if os.path.basename(vae_file).startswith(checkpoint_path):
  68. return vae_file
  69. return None
  70. def resolve_vae(checkpoint_file):
  71. if shared.cmd_opts.vae_path is not None:
  72. return shared.cmd_opts.vae_path, 'from commandline argument'
  73. is_automatic = shared.opts.sd_vae in {"Automatic", "auto"} # "auto" for people with old config
  74. vae_near_checkpoint = find_vae_near_checkpoint(checkpoint_file)
  75. if vae_near_checkpoint is not None and (shared.opts.sd_vae_as_default or is_automatic):
  76. return vae_near_checkpoint, 'found near the checkpoint'
  77. if shared.opts.sd_vae == "None":
  78. return None, None
  79. vae_from_options = vae_dict.get(shared.opts.sd_vae, None)
  80. if vae_from_options is not None:
  81. return vae_from_options, 'specified in settings'
  82. if not is_automatic:
  83. print(f"Couldn't find VAE named {shared.opts.sd_vae}; using None instead")
  84. return None, None
  85. def load_vae_dict(filename, map_location):
  86. vae_ckpt = sd_models.read_state_dict(filename, map_location=map_location)
  87. vae_dict_1 = {k: v for k, v in vae_ckpt.items() if k[0:4] != "loss" and k not in vae_ignore_keys}
  88. return vae_dict_1
  89. def load_vae(model, vae_file=None, vae_source="from unknown source"):
  90. global vae_dict, loaded_vae_file
  91. # save_settings = False
  92. cache_enabled = shared.opts.sd_vae_checkpoint_cache > 0
  93. if vae_file:
  94. if cache_enabled and vae_file in checkpoints_loaded:
  95. # use vae checkpoint cache
  96. print(f"Loading VAE weights {vae_source}: cached {get_filename(vae_file)}")
  97. store_base_vae(model)
  98. _load_vae_dict(model, checkpoints_loaded[vae_file])
  99. else:
  100. assert os.path.isfile(vae_file), f"VAE {vae_source} doesn't exist: {vae_file}"
  101. print(f"Loading VAE weights {vae_source}: {vae_file}")
  102. store_base_vae(model)
  103. vae_dict_1 = load_vae_dict(vae_file, map_location=shared.weight_load_location)
  104. _load_vae_dict(model, vae_dict_1)
  105. if cache_enabled:
  106. # cache newly loaded vae
  107. checkpoints_loaded[vae_file] = vae_dict_1.copy()
  108. # clean up cache if limit is reached
  109. if cache_enabled:
  110. while len(checkpoints_loaded) > shared.opts.sd_vae_checkpoint_cache + 1: # we need to count the current model
  111. checkpoints_loaded.popitem(last=False) # LRU
  112. # If vae used is not in dict, update it
  113. # It will be removed on refresh though
  114. vae_opt = get_filename(vae_file)
  115. if vae_opt not in vae_dict:
  116. vae_dict[vae_opt] = vae_file
  117. elif loaded_vae_file:
  118. restore_base_vae(model)
  119. loaded_vae_file = vae_file
  120. # don't call this from outside
  121. def _load_vae_dict(model, vae_dict_1):
  122. model.first_stage_model.load_state_dict(vae_dict_1)
  123. model.first_stage_model.to(devices.dtype_vae)
  124. def clear_loaded_vae():
  125. global loaded_vae_file
  126. loaded_vae_file = None
  127. unspecified = object()
  128. def reload_vae_weights(sd_model=None, vae_file=unspecified):
  129. from modules import lowvram, devices, sd_hijack
  130. if not sd_model:
  131. sd_model = shared.sd_model
  132. checkpoint_info = sd_model.sd_checkpoint_info
  133. checkpoint_file = checkpoint_info.filename
  134. if vae_file == unspecified:
  135. vae_file, vae_source = resolve_vae(checkpoint_file)
  136. else:
  137. vae_source = "from function argument"
  138. if loaded_vae_file == vae_file:
  139. return
  140. if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
  141. lowvram.send_everything_to_cpu()
  142. else:
  143. sd_model.to(devices.cpu)
  144. sd_hijack.model_hijack.undo_hijack(sd_model)
  145. load_vae(sd_model, vae_file, vae_source)
  146. sd_hijack.model_hijack.hijack(sd_model)
  147. script_callbacks.model_loaded_callback(sd_model)
  148. if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
  149. sd_model.to(devices.device)
  150. print("VAE weights loaded.")
  151. return sd_model