Skip to content

Commit b1b99b5

Browse files
some more cleaning
1 parent 606ac57 commit b1b99b5

2 files changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# coding=utf-8
2+
# Copyright 2022 The HuggingFace Inc. team.
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 LDM checkpoints. """
16+
17+
import argparse
18+
import os
19+
import json
20+
import torch
21+
from diffusers import UNet2DModel, UNet2DConditionModel
22+
from transformers.file_utils import has_file
23+
24+
do_only_config = False
25+
do_only_weights = True
26+
do_only_renaming = False
27+
28+
29+
if __name__ == "__main__":
30+
parser = argparse.ArgumentParser()
31+
32+
parser.add_argument(
33+
"--repo_path",
34+
default=None,
35+
type=str,
36+
required=True,
37+
help="The config json file corresponding to the architecture.",
38+
)
39+
40+
parser.add_argument(
41+
"--dump_path", default=None, type=str, required=True, help="Path to the output model."
42+
)
43+
44+
args = parser.parse_args()
45+
46+
config_parameters_to_change = {
47+
"image_size": "sample_size",
48+
"num_res_blocks": "layers_per_block",
49+
"block_channels": "block_out_channels",
50+
"down_blocks": "down_block_types",
51+
"up_blocks": "up_block_types",
52+
"downscale_freq_shift": "freq_shift",
53+
"resnet_num_groups": "norm_num_groups",
54+
"resnet_act_fn": "act_fn",
55+
"resnet_eps": "norm_eps",
56+
"num_head_channels": "attention_head_dim",
57+
}
58+
59+
key_parameters_to_change = {
60+
"time_steps": "time_proj",
61+
"mid": "mid_block",
62+
"downsample_blocks": "down_blocks",
63+
"upsample_blocks": "up_blocks",
64+
}
65+
66+
subfolder = "" if has_file(args.repo_path, "config.json") else "unet"
67+
68+
with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader:
69+
text = reader.read()
70+
config = json.loads(text)
71+
72+
if do_only_config:
73+
for key in config_parameters_to_change.keys():
74+
config.pop(key, None)
75+
76+
if has_file(args.repo_path, "config.json"):
77+
model = UNet2DModel(**config)
78+
else:
79+
class_name = UNet2DConditionModel if "ldm-text2im-large-256" in args.repo_path else UNet2DModel
80+
model = class_name(**config)
81+
82+
if do_only_config:
83+
model.save_config(os.path.join(args.repo_path, subfolder))
84+
85+
config = dict(model.config)
86+
87+
if do_only_renaming:
88+
for key, value in config_parameters_to_change.items():
89+
if key in config:
90+
config[value] = config[key]
91+
del config[key]
92+
93+
config["down_block_types"] = [k.replace("UNetRes", "") for k in config["down_block_types"]]
94+
config["up_block_types"] = [k.replace("UNetRes", "") for k in config["up_block_types"]]
95+
96+
if do_only_weights:
97+
state_dict = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin"))
98+
99+
new_state_dict = {}
100+
for param_key, param_value in state_dict.items():
101+
if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"):
102+
continue
103+
has_changed = False
104+
for key, new_key in key_parameters_to_change.items():
105+
if not has_changed and param_key.split(".")[0] == key:
106+
new_state_dict[".".join([new_key] + param_key.split(".")[1:])] = param_value
107+
has_changed = True
108+
if not has_changed:
109+
new_state_dict[param_key] = param_value
110+
111+
model.load_state_dict(new_state_dict)
112+
model.save_pretrained(os.path.join(args.repo_path, subfolder))

src/diffusers/configuration_utils.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ class ConfigMixin:
4848
4949
"""
5050
config_name = None
51+
ignore_for_config = []
5152

5253
def register_to_config(self, **kwargs):
5354
if self.config_name is None:
@@ -212,6 +213,9 @@ def extract_init_dict(cls, config_dict, **kwargs):
212213
# remove general kwargs if present in dict
213214
if "kwargs" in expected_keys:
214215
expected_keys.remove("kwargs")
216+
# remove keys to be ignored
217+
if len(cls.ignore_for_config) > 0:
218+
expected_keys = expected_keys - set(cls.ignore_for_config)
215219
init_dict = {}
216220
for key in expected_keys:
217221
if key in kwargs:

0 commit comments

Comments
 (0)