extras.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import os
  2. import re
  3. import shutil
  4. import json
  5. import torch
  6. import tqdm
  7. from modules import shared, images, sd_models, sd_vae, sd_models_config
  8. from modules.ui_common import plaintext_to_html
  9. import gradio as gr
  10. import safetensors.torch
  11. def run_pnginfo(image):
  12. if image is None:
  13. return '', '', ''
  14. geninfo, items = images.read_info_from_image(image)
  15. items = {**{'parameters': geninfo}, **items}
  16. info = ''
  17. for key, text in items.items():
  18. info += f"""
  19. <div>
  20. <p><b>{plaintext_to_html(str(key))}</b></p>
  21. <p>{plaintext_to_html(str(text))}</p>
  22. </div>
  23. """.strip()+"\n"
  24. if len(info) == 0:
  25. message = "Nothing found in the image."
  26. info = f"<div><p>{message}<p></div>"
  27. return '', geninfo, info
  28. def create_config(ckpt_result, config_source, a, b, c):
  29. def config(x):
  30. res = sd_models_config.find_checkpoint_config_near_filename(x) if x else None
  31. return res if res != shared.sd_default_config else None
  32. if config_source == 0:
  33. cfg = config(a) or config(b) or config(c)
  34. elif config_source == 1:
  35. cfg = config(b)
  36. elif config_source == 2:
  37. cfg = config(c)
  38. else:
  39. cfg = None
  40. if cfg is None:
  41. return
  42. filename, _ = os.path.splitext(ckpt_result)
  43. checkpoint_filename = filename + ".yaml"
  44. print("Copying config:")
  45. print(" from:", cfg)
  46. print(" to:", checkpoint_filename)
  47. shutil.copyfile(cfg, checkpoint_filename)
  48. checkpoint_dict_skip_on_merge = ["cond_stage_model.transformer.text_model.embeddings.position_ids"]
  49. def to_half(tensor, enable):
  50. if enable and tensor.dtype == torch.float:
  51. return tensor.half()
  52. return tensor
  53. def run_modelmerger(id_task, primary_model_name, secondary_model_name, tertiary_model_name, interp_method, multiplier, save_as_half, custom_name, checkpoint_format, config_source, bake_in_vae, discard_weights, save_metadata):
  54. shared.state.begin()
  55. shared.state.job = 'model-merge'
  56. def fail(message):
  57. shared.state.textinfo = message
  58. shared.state.end()
  59. return [*[gr.update() for _ in range(4)], message]
  60. def weighted_sum(theta0, theta1, alpha):
  61. return ((1 - alpha) * theta0) + (alpha * theta1)
  62. def get_difference(theta1, theta2):
  63. return theta1 - theta2
  64. def add_difference(theta0, theta1_2_diff, alpha):
  65. return theta0 + (alpha * theta1_2_diff)
  66. def filename_weighted_sum():
  67. a = primary_model_info.model_name
  68. b = secondary_model_info.model_name
  69. Ma = round(1 - multiplier, 2)
  70. Mb = round(multiplier, 2)
  71. return f"{Ma}({a}) + {Mb}({b})"
  72. def filename_add_difference():
  73. a = primary_model_info.model_name
  74. b = secondary_model_info.model_name
  75. c = tertiary_model_info.model_name
  76. M = round(multiplier, 2)
  77. return f"{a} + {M}({b} - {c})"
  78. def filename_nothing():
  79. return primary_model_info.model_name
  80. theta_funcs = {
  81. "Weighted sum": (filename_weighted_sum, None, weighted_sum),
  82. "Add difference": (filename_add_difference, get_difference, add_difference),
  83. "No interpolation": (filename_nothing, None, None),
  84. }
  85. filename_generator, theta_func1, theta_func2 = theta_funcs[interp_method]
  86. shared.state.job_count = (1 if theta_func1 else 0) + (1 if theta_func2 else 0)
  87. if not primary_model_name:
  88. return fail("Failed: Merging requires a primary model.")
  89. primary_model_info = sd_models.checkpoints_list[primary_model_name]
  90. if theta_func2 and not secondary_model_name:
  91. return fail("Failed: Merging requires a secondary model.")
  92. secondary_model_info = sd_models.checkpoints_list[secondary_model_name] if theta_func2 else None
  93. if theta_func1 and not tertiary_model_name:
  94. return fail(f"Failed: Interpolation method ({interp_method}) requires a tertiary model.")
  95. tertiary_model_info = sd_models.checkpoints_list[tertiary_model_name] if theta_func1 else None
  96. result_is_inpainting_model = False
  97. result_is_instruct_pix2pix_model = False
  98. if theta_func2:
  99. shared.state.textinfo = "Loading B"
  100. print(f"Loading {secondary_model_info.filename}...")
  101. theta_1 = sd_models.read_state_dict(secondary_model_info.filename, map_location='cpu')
  102. else:
  103. theta_1 = None
  104. if theta_func1:
  105. shared.state.textinfo = "Loading C"
  106. print(f"Loading {tertiary_model_info.filename}...")
  107. theta_2 = sd_models.read_state_dict(tertiary_model_info.filename, map_location='cpu')
  108. shared.state.textinfo = 'Merging B and C'
  109. shared.state.sampling_steps = len(theta_1.keys())
  110. for key in tqdm.tqdm(theta_1.keys()):
  111. if key in checkpoint_dict_skip_on_merge:
  112. continue
  113. if 'model' in key:
  114. if key in theta_2:
  115. t2 = theta_2.get(key, torch.zeros_like(theta_1[key]))
  116. theta_1[key] = theta_func1(theta_1[key], t2)
  117. else:
  118. theta_1[key] = torch.zeros_like(theta_1[key])
  119. shared.state.sampling_step += 1
  120. del theta_2
  121. shared.state.nextjob()
  122. shared.state.textinfo = f"Loading {primary_model_info.filename}..."
  123. print(f"Loading {primary_model_info.filename}...")
  124. theta_0 = sd_models.read_state_dict(primary_model_info.filename, map_location='cpu')
  125. print("Merging...")
  126. shared.state.textinfo = 'Merging A and B'
  127. shared.state.sampling_steps = len(theta_0.keys())
  128. for key in tqdm.tqdm(theta_0.keys()):
  129. if theta_1 and 'model' in key and key in theta_1:
  130. if key in checkpoint_dict_skip_on_merge:
  131. continue
  132. a = theta_0[key]
  133. b = theta_1[key]
  134. # this enables merging an inpainting model (A) with another one (B);
  135. # where normal model would have 4 channels, for latenst space, inpainting model would
  136. # have another 4 channels for unmasked picture's latent space, plus one channel for mask, for a total of 9
  137. if a.shape != b.shape and a.shape[0:1] + a.shape[2:] == b.shape[0:1] + b.shape[2:]:
  138. if a.shape[1] == 4 and b.shape[1] == 9:
  139. raise RuntimeError("When merging inpainting model with a normal one, A must be the inpainting model.")
  140. if a.shape[1] == 4 and b.shape[1] == 8:
  141. raise RuntimeError("When merging instruct-pix2pix model with a normal one, A must be the instruct-pix2pix model.")
  142. if a.shape[1] == 8 and b.shape[1] == 4:#If we have an Instruct-Pix2Pix model...
  143. theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)#Merge only the vectors the models have in common. Otherwise we get an error due to dimension mismatch.
  144. result_is_instruct_pix2pix_model = True
  145. else:
  146. assert a.shape[1] == 9 and b.shape[1] == 4, f"Bad dimensions for merged layer {key}: A={a.shape}, B={b.shape}"
  147. theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)
  148. result_is_inpainting_model = True
  149. else:
  150. theta_0[key] = theta_func2(a, b, multiplier)
  151. theta_0[key] = to_half(theta_0[key], save_as_half)
  152. shared.state.sampling_step += 1
  153. del theta_1
  154. bake_in_vae_filename = sd_vae.vae_dict.get(bake_in_vae, None)
  155. if bake_in_vae_filename is not None:
  156. print(f"Baking in VAE from {bake_in_vae_filename}")
  157. shared.state.textinfo = 'Baking in VAE'
  158. vae_dict = sd_vae.load_vae_dict(bake_in_vae_filename, map_location='cpu')
  159. for key in vae_dict.keys():
  160. theta_0_key = 'first_stage_model.' + key
  161. if theta_0_key in theta_0:
  162. theta_0[theta_0_key] = to_half(vae_dict[key], save_as_half)
  163. del vae_dict
  164. if save_as_half and not theta_func2:
  165. for key in theta_0.keys():
  166. theta_0[key] = to_half(theta_0[key], save_as_half)
  167. if discard_weights:
  168. regex = re.compile(discard_weights)
  169. for key in list(theta_0):
  170. if re.search(regex, key):
  171. theta_0.pop(key, None)
  172. ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
  173. filename = filename_generator() if custom_name == '' else custom_name
  174. filename += ".inpainting" if result_is_inpainting_model else ""
  175. filename += ".instruct-pix2pix" if result_is_instruct_pix2pix_model else ""
  176. filename += "." + checkpoint_format
  177. output_modelname = os.path.join(ckpt_dir, filename)
  178. shared.state.nextjob()
  179. shared.state.textinfo = "Saving"
  180. print(f"Saving to {output_modelname}...")
  181. metadata = None
  182. if save_metadata:
  183. metadata = {"format": "pt"}
  184. merge_recipe = {
  185. "type": "webui", # indicate this model was merged with webui's built-in merger
  186. "primary_model_hash": primary_model_info.sha256,
  187. "secondary_model_hash": secondary_model_info.sha256 if secondary_model_info else None,
  188. "tertiary_model_hash": tertiary_model_info.sha256 if tertiary_model_info else None,
  189. "interp_method": interp_method,
  190. "multiplier": multiplier,
  191. "save_as_half": save_as_half,
  192. "custom_name": custom_name,
  193. "config_source": config_source,
  194. "bake_in_vae": bake_in_vae,
  195. "discard_weights": discard_weights,
  196. "is_inpainting": result_is_inpainting_model,
  197. "is_instruct_pix2pix": result_is_instruct_pix2pix_model
  198. }
  199. metadata["sd_merge_recipe"] = json.dumps(merge_recipe)
  200. sd_merge_models = {}
  201. def add_model_metadata(checkpoint_info):
  202. checkpoint_info.calculate_shorthash()
  203. sd_merge_models[checkpoint_info.sha256] = {
  204. "name": checkpoint_info.name,
  205. "legacy_hash": checkpoint_info.hash,
  206. "sd_merge_recipe": checkpoint_info.metadata.get("sd_merge_recipe", None)
  207. }
  208. sd_merge_models.update(checkpoint_info.metadata.get("sd_merge_models", {}))
  209. add_model_metadata(primary_model_info)
  210. if secondary_model_info:
  211. add_model_metadata(secondary_model_info)
  212. if tertiary_model_info:
  213. add_model_metadata(tertiary_model_info)
  214. metadata["sd_merge_models"] = json.dumps(sd_merge_models)
  215. _, extension = os.path.splitext(output_modelname)
  216. if extension.lower() == ".safetensors":
  217. safetensors.torch.save_file(theta_0, output_modelname, metadata=metadata)
  218. else:
  219. torch.save(theta_0, output_modelname)
  220. sd_models.list_models()
  221. created_model = next((ckpt for ckpt in sd_models.checkpoints_list.values() if ckpt.name == filename), None)
  222. if created_model:
  223. created_model.calculate_shorthash()
  224. create_config(output_modelname, config_source, primary_model_info, secondary_model_info, tertiary_model_info)
  225. print(f"Checkpoint saved to {output_modelname}.")
  226. shared.state.textinfo = "Checkpoint saved"
  227. shared.state.end()
  228. return [*[gr.Dropdown.update(choices=sd_models.checkpoint_tiles()) for _ in range(4)], "Checkpoint saved to " + output_modelname]