Path: blob/main/scripts/convert_lora_safetensor_to_diffusers.py
1440 views
# coding=utf-81# Copyright 2023, Haofan Wang, Qixun Wang, All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.1415""" Conversion script for the LoRA's safetensors checkpoints. """1617import argparse1819import torch20from safetensors.torch import load_file2122from diffusers import StableDiffusionPipeline232425def convert(base_model_path, checkpoint_path, LORA_PREFIX_UNET, LORA_PREFIX_TEXT_ENCODER, alpha):26# load base model27pipeline = StableDiffusionPipeline.from_pretrained(base_model_path, torch_dtype=torch.float32)2829# load LoRA weight from .safetensors30state_dict = load_file(checkpoint_path)3132visited = []3334# directly update weight in diffusers model35for key in state_dict:36# it is suggested to print out the key, it usually will be something like below37# "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"3839# as we have set the alpha beforehand, so just skip40if ".alpha" in key or key in visited:41continue4243if "text" in key:44layer_infos = key.split(".")[0].split(LORA_PREFIX_TEXT_ENCODER + "_")[-1].split("_")45curr_layer = pipeline.text_encoder46else:47layer_infos = key.split(".")[0].split(LORA_PREFIX_UNET + "_")[-1].split("_")48curr_layer = pipeline.unet4950# find the target layer51temp_name = layer_infos.pop(0)52while len(layer_infos) > -1:53try:54curr_layer = curr_layer.__getattr__(temp_name)55if len(layer_infos) > 0:56temp_name = layer_infos.pop(0)57elif len(layer_infos) == 0:58break59except Exception:60if len(temp_name) > 0:61temp_name += "_" + layer_infos.pop(0)62else:63temp_name = layer_infos.pop(0)6465pair_keys = []66if "lora_down" in key:67pair_keys.append(key.replace("lora_down", "lora_up"))68pair_keys.append(key)69else:70pair_keys.append(key)71pair_keys.append(key.replace("lora_up", "lora_down"))7273# update weight74if len(state_dict[pair_keys[0]].shape) == 4:75weight_up = state_dict[pair_keys[0]].squeeze(3).squeeze(2).to(torch.float32)76weight_down = state_dict[pair_keys[1]].squeeze(3).squeeze(2).to(torch.float32)77curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)78else:79weight_up = state_dict[pair_keys[0]].to(torch.float32)80weight_down = state_dict[pair_keys[1]].to(torch.float32)81curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down)8283# update visited list84for item in pair_keys:85visited.append(item)8687return pipeline888990if __name__ == "__main__":91parser = argparse.ArgumentParser()9293parser.add_argument(94"--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format."95)96parser.add_argument(97"--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."98)99parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")100parser.add_argument(101"--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors"102)103parser.add_argument(104"--lora_prefix_text_encoder",105default="lora_te",106type=str,107help="The prefix of text encoder weight in safetensors",108)109parser.add_argument("--alpha", default=0.75, type=float, help="The merging ratio in W = W0 + alpha * deltaW")110parser.add_argument(111"--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not."112)113parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")114115args = parser.parse_args()116117base_model_path = args.base_model_path118checkpoint_path = args.checkpoint_path119dump_path = args.dump_path120lora_prefix_unet = args.lora_prefix_unet121lora_prefix_text_encoder = args.lora_prefix_text_encoder122alpha = args.alpha123124pipe = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha)125126pipe = pipe.to(args.device)127pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)128129130