extras.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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(job="model-merge")
  55. def fail(message):
  56. shared.state.textinfo = message
  57. shared.state.end()
  58. return [*[gr.update() for _ in range(4)], message]
  59. def weighted_sum(theta0, theta1, alpha):
  60. return ((1 - alpha) * theta0) + (alpha * theta1)
  61. def get_difference(theta1, theta2):
  62. return theta1 - theta2
  63. def add_difference(theta0, theta1_2_diff, alpha):
  64. return theta0 + (alpha * theta1_2_diff)
  65. def filename_weighted_sum():
  66. a = primary_model_info.model_name
  67. b = secondary_model_info.model_name
  68. Ma = round(1 - multiplier, 2)
  69. Mb = round(multiplier, 2)
  70. return f"{Ma}({a}) + {Mb}({b})"
  71. def filename_add_difference():
  72. a = primary_model_info.model_name
  73. b = secondary_model_info.model_name
  74. c = tertiary_model_info.model_name
  75. M = round(multiplier, 2)
  76. return f"{a} + {M}({b} - {c})"
  77. def filename_nothing():
  78. return primary_model_info.model_name
  79. theta_funcs = {
  80. "Weighted sum": (filename_weighted_sum, None, weighted_sum),
  81. "Add difference": (filename_add_difference, get_difference, add_difference),
  82. "No interpolation": (filename_nothing, None, None),
  83. }
  84. filename_generator, theta_func1, theta_func2 = theta_funcs[interp_method]
  85. shared.state.job_count = (1 if theta_func1 else 0) + (1 if theta_func2 else 0)
  86. if not primary_model_name:
  87. return fail("Failed: Merging requires a primary model.")
  88. primary_model_info = sd_models.checkpoints_list[primary_model_name]
  89. if theta_func2 and not secondary_model_name:
  90. return fail("Failed: Merging requires a secondary model.")
  91. secondary_model_info = sd_models.checkpoints_list[secondary_model_name] if theta_func2 else None
  92. if theta_func1 and not tertiary_model_name:
  93. return fail(f"Failed: Interpolation method ({interp_method}) requires a tertiary model.")
  94. tertiary_model_info = sd_models.checkpoints_list[tertiary_model_name] if theta_func1 else None
  95. result_is_inpainting_model = False
  96. result_is_instruct_pix2pix_model = False
  97. if theta_func2:
  98. shared.state.textinfo = "Loading B"
  99. print(f"Loading {secondary_model_info.filename}...")
  100. theta_1 = sd_models.read_state_dict(secondary_model_info.filename, map_location='cpu')
  101. else:
  102. theta_1 = None
  103. if theta_func1:
  104. shared.state.textinfo = "Loading C"
  105. print(f"Loading {tertiary_model_info.filename}...")
  106. theta_2 = sd_models.read_state_dict(tertiary_model_info.filename, map_location='cpu')
  107. shared.state.textinfo = 'Merging B and C'
  108. shared.state.sampling_steps = len(theta_1.keys())
  109. for key in tqdm.tqdm(theta_1.keys()):
  110. if key in checkpoint_dict_skip_on_merge:
  111. continue
  112. if 'model' in key:
  113. if key in theta_2:
  114. t2 = theta_2.get(key, torch.zeros_like(theta_1[key]))
  115. theta_1[key] = theta_func1(theta_1[key], t2)
  116. else:
  117. theta_1[key] = torch.zeros_like(theta_1[key])
  118. shared.state.sampling_step += 1
  119. del theta_2
  120. shared.state.nextjob()
  121. shared.state.textinfo = f"Loading {primary_model_info.filename}..."
  122. print(f"Loading {primary_model_info.filename}...")
  123. theta_0 = sd_models.read_state_dict(primary_model_info.filename, map_location='cpu')
  124. print("Merging...")
  125. shared.state.textinfo = 'Merging A and B'
  126. shared.state.sampling_steps = len(theta_0.keys())
  127. for key in tqdm.tqdm(theta_0.keys()):
  128. if theta_1 and 'model' in key and key in theta_1:
  129. if key in checkpoint_dict_skip_on_merge:
  130. continue
  131. a = theta_0[key]
  132. b = theta_1[key]
  133. # this enables merging an inpainting model (A) with another one (B);
  134. # where normal model would have 4 channels, for latenst space, inpainting model would
  135. # have another 4 channels for unmasked picture's latent space, plus one channel for mask, for a total of 9
  136. if a.shape != b.shape and a.shape[0:1] + a.shape[2:] == b.shape[0:1] + b.shape[2:]:
  137. if a.shape[1] == 4 and b.shape[1] == 9:
  138. raise RuntimeError("When merging inpainting model with a normal one, A must be the inpainting model.")
  139. if a.shape[1] == 4 and b.shape[1] == 8:
  140. raise RuntimeError("When merging instruct-pix2pix model with a normal one, A must be the instruct-pix2pix model.")
  141. if a.shape[1] == 8 and b.shape[1] == 4:#If we have an Instruct-Pix2Pix model...
  142. 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.
  143. result_is_instruct_pix2pix_model = True
  144. else:
  145. assert a.shape[1] == 9 and b.shape[1] == 4, f"Bad dimensions for merged layer {key}: A={a.shape}, B={b.shape}"
  146. theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)
  147. result_is_inpainting_model = True
  148. else:
  149. theta_0[key] = theta_func2(a, b, multiplier)
  150. theta_0[key] = to_half(theta_0[key], save_as_half)
  151. shared.state.sampling_step += 1
  152. del theta_1
  153. bake_in_vae_filename = sd_vae.vae_dict.get(bake_in_vae, None)
  154. if bake_in_vae_filename is not None:
  155. print(f"Baking in VAE from {bake_in_vae_filename}")
  156. shared.state.textinfo = 'Baking in VAE'
  157. vae_dict = sd_vae.load_vae_dict(bake_in_vae_filename, map_location='cpu')
  158. for key in vae_dict.keys():
  159. theta_0_key = 'first_stage_model.' + key
  160. if theta_0_key in theta_0:
  161. theta_0[theta_0_key] = to_half(vae_dict[key], save_as_half)
  162. del vae_dict
  163. if save_as_half and not theta_func2:
  164. for key in theta_0.keys():
  165. theta_0[key] = to_half(theta_0[key], save_as_half)
  166. if discard_weights:
  167. regex = re.compile(discard_weights)
  168. for key in list(theta_0):
  169. if re.search(regex, key):
  170. theta_0.pop(key, None)
  171. ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
  172. filename = filename_generator() if custom_name == '' else custom_name
  173. filename += ".inpainting" if result_is_inpainting_model else ""
  174. filename += ".instruct-pix2pix" if result_is_instruct_pix2pix_model else ""
  175. filename += "." + checkpoint_format
  176. output_modelname = os.path.join(ckpt_dir, filename)
  177. shared.state.nextjob()
  178. shared.state.textinfo = "Saving"
  179. print(f"Saving to {output_modelname}...")
  180. metadata = None
  181. if save_metadata:
  182. metadata = {"format": "pt"}
  183. merge_recipe = {
  184. "type": "webui", # indicate this model was merged with webui's built-in merger
  185. "primary_model_hash": primary_model_info.sha256,
  186. "secondary_model_hash": secondary_model_info.sha256 if secondary_model_info else None,
  187. "tertiary_model_hash": tertiary_model_info.sha256 if tertiary_model_info else None,
  188. "interp_method": interp_method,
  189. "multiplier": multiplier,
  190. "save_as_half": save_as_half,
  191. "custom_name": custom_name,
  192. "config_source": config_source,
  193. "bake_in_vae": bake_in_vae,
  194. "discard_weights": discard_weights,
  195. "is_inpainting": result_is_inpainting_model,
  196. "is_instruct_pix2pix": result_is_instruct_pix2pix_model
  197. }
  198. metadata["sd_merge_recipe"] = json.dumps(merge_recipe)
  199. sd_merge_models = {}
  200. def add_model_metadata(checkpoint_info):
  201. checkpoint_info.calculate_shorthash()
  202. sd_merge_models[checkpoint_info.sha256] = {
  203. "name": checkpoint_info.name,
  204. "legacy_hash": checkpoint_info.hash,
  205. "sd_merge_recipe": checkpoint_info.metadata.get("sd_merge_recipe", None)
  206. }
  207. sd_merge_models.update(checkpoint_info.metadata.get("sd_merge_models", {}))
  208. add_model_metadata(primary_model_info)
  209. if secondary_model_info:
  210. add_model_metadata(secondary_model_info)
  211. if tertiary_model_info:
  212. add_model_metadata(tertiary_model_info)
  213. metadata["sd_merge_models"] = json.dumps(sd_merge_models)
  214. _, extension = os.path.splitext(output_modelname)
  215. if extension.lower() == ".safetensors":
  216. safetensors.torch.save_file(theta_0, output_modelname, metadata=metadata)
  217. else:
  218. torch.save(theta_0, output_modelname)
  219. sd_models.list_models()
  220. created_model = next((ckpt for ckpt in sd_models.checkpoints_list.values() if ckpt.name == filename), None)
  221. if created_model:
  222. created_model.calculate_shorthash()
  223. create_config(output_modelname, config_source, primary_model_info, secondary_model_info, tertiary_model_info)
  224. print(f"Checkpoint saved to {output_modelname}.")
  225. shared.state.textinfo = "Checkpoint saved"
  226. shared.state.end()
  227. return [*[gr.Dropdown.update(choices=sd_models.checkpoint_tiles()) for _ in range(4)], "Checkpoint saved to " + output_modelname]