convert_lora_safetensor_to_diffusers.py 5.0 KB

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