convert_lora_safetensor_to_diffusers.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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_lora(pipeline, state_dict, LORA_PREFIX_UNET="lora_unet", LORA_PREFIX_TEXT_ENCODER="lora_te", alpha=0.6):
  39. # load base model
  40. # pipeline = StableDiffusionPipeline.from_pretrained(base_model_path, torch_dtype=torch.float32)
  41. # load LoRA weight from .safetensors
  42. # state_dict = load_file(checkpoint_path)
  43. visited = []
  44. # directly update weight in diffusers model
  45. for key in state_dict:
  46. # it is suggested to print out the key, it usually will be something like below
  47. # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"
  48. # as we have set the alpha beforehand, so just skip
  49. if ".alpha" in key or key in visited:
  50. continue
  51. if "text" in key:
  52. layer_infos = key.split(".")[0].split(LORA_PREFIX_TEXT_ENCODER + "_")[-1].split("_")
  53. curr_layer = pipeline.text_encoder
  54. else:
  55. layer_infos = key.split(".")[0].split(LORA_PREFIX_UNET + "_")[-1].split("_")
  56. curr_layer = pipeline.unet
  57. # find the target layer
  58. temp_name = layer_infos.pop(0)
  59. while len(layer_infos) > -1:
  60. try:
  61. curr_layer = curr_layer.__getattr__(temp_name)
  62. if len(layer_infos) > 0:
  63. temp_name = layer_infos.pop(0)
  64. elif len(layer_infos) == 0:
  65. break
  66. except Exception:
  67. if len(temp_name) > 0:
  68. temp_name += "_" + layer_infos.pop(0)
  69. else:
  70. temp_name = layer_infos.pop(0)
  71. pair_keys = []
  72. if "lora_down" in key:
  73. pair_keys.append(key.replace("lora_down", "lora_up"))
  74. pair_keys.append(key)
  75. else:
  76. pair_keys.append(key)
  77. pair_keys.append(key.replace("lora_up", "lora_down"))
  78. # update weight
  79. if len(state_dict[pair_keys[0]].shape) == 4:
  80. weight_up = state_dict[pair_keys[0]].squeeze(3).squeeze(2).to(torch.float32)
  81. weight_down = state_dict[pair_keys[1]].squeeze(3).squeeze(2).to(torch.float32)
  82. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3).to(curr_layer.weight.data.device)
  83. else:
  84. weight_up = state_dict[pair_keys[0]].to(torch.float32)
  85. weight_down = state_dict[pair_keys[1]].to(torch.float32)
  86. curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).to(curr_layer.weight.data.device)
  87. # update visited list
  88. for item in pair_keys:
  89. visited.append(item)
  90. return pipeline
  91. if __name__ == "__main__":
  92. parser = argparse.ArgumentParser()
  93. parser.add_argument(
  94. "--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format."
  95. )
  96. parser.add_argument(
  97. "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
  98. )
  99. parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
  100. parser.add_argument(
  101. "--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors"
  102. )
  103. parser.add_argument(
  104. "--lora_prefix_text_encoder",
  105. default="lora_te",
  106. type=str,
  107. help="The prefix of text encoder weight in safetensors",
  108. )
  109. parser.add_argument("--alpha", default=0.75, type=float, help="The merging ratio in W = W0 + alpha * deltaW")
  110. parser.add_argument(
  111. "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not."
  112. )
  113. parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")
  114. args = parser.parse_args()
  115. base_model_path = args.base_model_path
  116. checkpoint_path = args.checkpoint_path
  117. dump_path = args.dump_path
  118. lora_prefix_unet = args.lora_prefix_unet
  119. lora_prefix_text_encoder = args.lora_prefix_text_encoder
  120. alpha = args.alpha
  121. pipe = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha)
  122. pipe = pipe.to(args.device)
  123. pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)