convert_lora_safetensor_to_diffusers.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # coding=utf-8
  2. # Copyright 2023, Haofan Wang, Qixun Wang, All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ Conversion script for the LoRA's safetensors checkpoints. """
  16. import argparse
  17. import torch
  18. from safetensors.torch import load_file
  19. from diffusers import StableDiffusionPipeline
  20. import pdb
  21. def convert_motion_lora_ckpt_to_diffusers(pipeline, state_dict, alpha=1.0):
  22. # directly update weight in diffusers model
  23. for key in state_dict:
  24. # only process lora down key
  25. if "up." in key: continue
  26. up_key = key.replace(".down.", ".up.")
  27. model_key = key.replace("processor.", "").replace("_lora", "").replace("down.", "").replace("up.", "")
  28. model_key = model_key.replace("to_out.", "to_out.0.")
  29. layer_infos = model_key.split(".")[:-1]
  30. curr_layer = pipeline.unet
  31. while len(layer_infos) > 0:
  32. temp_name = layer_infos.pop(0)
  33. curr_layer = curr_layer.__getattr__(temp_name)
  34. weight_down = state_dict[key]
  35. weight_up = state_dict[up_key]
  36. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).to(curr_layer.weight.data.device)
  37. return pipeline
  38. def convert_motion_lora_ckpt_to_diffusers_test(pipeline, state_dict, alpha=1.0):
  39. # directly update weight in diffusers model
  40. for key in state_dict:
  41. if "weight" in key:
  42. # only process lora down key
  43. if "up." in key: continue
  44. up_key = key.replace("_down.", "_up.")
  45. model_key = key.replace('-', '.').replace("_lora", "").replace("lora_down.", "").replace("lora_up.", "")
  46. print(up_key)
  47. print(key)
  48. print(model_key)
  49. layer_infos = model_key.split(".")[:-1]
  50. curr_layer = pipeline.unet
  51. while len(layer_infos) > 0:
  52. temp_name = layer_infos.pop(0)
  53. curr_layer = curr_layer.__getattr__(temp_name)
  54. weight_down = state_dict[key]
  55. weight_up = state_dict[up_key]
  56. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).to(curr_layer.weight.data.device)
  57. print(weight_down)
  58. print(weight_up)
  59. print("------")
  60. print(curr_layer)
  61. return pipeline
  62. def convert_lora(pipeline, state_dict, LORA_PREFIX_UNET="lora_unet", LORA_PREFIX_TEXT_ENCODER="lora_te", alpha=0.6):
  63. # load base model
  64. # pipeline = StableDiffusionPipeline.from_pretrained(base_model_path, torch_dtype=torch.float32)
  65. # load LoRA weight from .safetensors
  66. # state_dict = load_file(checkpoint_path)
  67. visited = []
  68. # directly update weight in diffusers model
  69. for key in state_dict:
  70. # it is suggested to print out the key, it usually will be something like below
  71. # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"
  72. # as we have set the alpha beforehand, so just skip
  73. if ".alpha" in key or key in visited:
  74. continue
  75. if "text" in key:
  76. layer_infos = key.split(".")[0].split(LORA_PREFIX_TEXT_ENCODER + "_")[-1].split("_")
  77. curr_layer = pipeline.text_encoder
  78. else:
  79. layer_infos = key.split(".")[0].split(LORA_PREFIX_UNET + "_")[-1].split("_")
  80. curr_layer = pipeline.unet
  81. # find the target layer
  82. temp_name = layer_infos.pop(0)
  83. while len(layer_infos) > -1:
  84. try:
  85. curr_layer = curr_layer.__getattr__(temp_name)
  86. if len(layer_infos) > 0:
  87. temp_name = layer_infos.pop(0)
  88. elif len(layer_infos) == 0:
  89. break
  90. except Exception:
  91. if len(temp_name) > 0:
  92. temp_name += "_" + layer_infos.pop(0)
  93. else:
  94. temp_name = layer_infos.pop(0)
  95. pair_keys = []
  96. if "lora_down" in key:
  97. pair_keys.append(key.replace("lora_down", "lora_up"))
  98. pair_keys.append(key)
  99. else:
  100. pair_keys.append(key)
  101. pair_keys.append(key.replace("lora_up", "lora_down"))
  102. # update weight
  103. if len(state_dict[pair_keys[0]].shape) == 4:
  104. weight_up = state_dict[pair_keys[0]].squeeze(3).squeeze(2).to(torch.float32)
  105. weight_down = state_dict[pair_keys[1]].squeeze(3).squeeze(2).to(torch.float32)
  106. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3).to(curr_layer.weight.data.device)
  107. else:
  108. weight_up = state_dict[pair_keys[0]].to(torch.float32)
  109. weight_down = state_dict[pair_keys[1]].to(torch.float32)
  110. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).to(curr_layer.weight.data.device)
  111. # update visited list
  112. for item in pair_keys:
  113. visited.append(item)
  114. return pipeline
  115. if __name__ == "__main__":
  116. parser = argparse.ArgumentParser()
  117. parser.add_argument(
  118. "--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format."
  119. )
  120. parser.add_argument(
  121. "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
  122. )
  123. parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
  124. parser.add_argument(
  125. "--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors"
  126. )
  127. parser.add_argument(
  128. "--lora_prefix_text_encoder",
  129. default="lora_te",
  130. type=str,
  131. help="The prefix of text encoder weight in safetensors",
  132. )
  133. parser.add_argument("--alpha", default=0.75, type=float, help="The merging ratio in W = W0 + alpha * deltaW")
  134. parser.add_argument(
  135. "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not."
  136. )
  137. parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")
  138. args = parser.parse_args()
  139. base_model_path = args.base_model_path
  140. checkpoint_path = args.checkpoint_path
  141. dump_path = args.dump_path
  142. lora_prefix_unet = args.lora_prefix_unet
  143. lora_prefix_text_encoder = args.lora_prefix_text_encoder
  144. alpha = args.alpha
  145. pipe = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha)
  146. pipe = pipe.to(args.device)
  147. pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)