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