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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from accelerate import init_empty_weights
|
| 3 |
+
from accelerate.utils.modeling import set_module_tensor_to_device
|
| 4 |
+
from safetensors.torch import load_file, save_file
|
| 5 |
+
from transformers import CLIPTextModel, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer
|
| 6 |
+
from typing import List
|
| 7 |
+
from diffusers import AutoencoderKL, EulerDiscreteScheduler, UNet2DConditionModel
|
| 8 |
+
from library import model_util
|
| 9 |
+
from library import sdxl_original_unet
|
| 10 |
+
from .utils import setup_logging
|
| 11 |
+
setup_logging()
|
| 12 |
+
import logging
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
VAE_SCALE_FACTOR = 0.13025
|
| 16 |
+
MODEL_VERSION_SDXL_BASE_V1_0 = "sdxl_base_v1-0"
|
| 17 |
+
|
| 18 |
+
# Diffusersの設定を読み込むための参照モデル
|
| 19 |
+
DIFFUSERS_REF_MODEL_ID_SDXL = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 20 |
+
|
| 21 |
+
DIFFUSERS_SDXL_UNET_CONFIG = {
|
| 22 |
+
"act_fn": "silu",
|
| 23 |
+
"addition_embed_type": "text_time",
|
| 24 |
+
"addition_embed_type_num_heads": 64,
|
| 25 |
+
"addition_time_embed_dim": 256,
|
| 26 |
+
"attention_head_dim": [5, 10, 20],
|
| 27 |
+
"block_out_channels": [320, 640, 1280],
|
| 28 |
+
"center_input_sample": False,
|
| 29 |
+
"class_embed_type": None,
|
| 30 |
+
"class_embeddings_concat": False,
|
| 31 |
+
"conv_in_kernel": 3,
|
| 32 |
+
"conv_out_kernel": 3,
|
| 33 |
+
"cross_attention_dim": 2048,
|
| 34 |
+
"cross_attention_norm": None,
|
| 35 |
+
"down_block_types": ["DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D"],
|
| 36 |
+
"downsample_padding": 1,
|
| 37 |
+
"dual_cross_attention": False,
|
| 38 |
+
"encoder_hid_dim": None,
|
| 39 |
+
"encoder_hid_dim_type": None,
|
| 40 |
+
"flip_sin_to_cos": True,
|
| 41 |
+
"freq_shift": 0,
|
| 42 |
+
"in_channels": 4,
|
| 43 |
+
"layers_per_block": 2,
|
| 44 |
+
"mid_block_only_cross_attention": None,
|
| 45 |
+
"mid_block_scale_factor": 1,
|
| 46 |
+
"mid_block_type": "UNetMidBlock2DCrossAttn",
|
| 47 |
+
"norm_eps": 1e-05,
|
| 48 |
+
"norm_num_groups": 32,
|
| 49 |
+
"num_attention_heads": None,
|
| 50 |
+
"num_class_embeds": None,
|
| 51 |
+
"only_cross_attention": False,
|
| 52 |
+
"out_channels": 4,
|
| 53 |
+
"projection_class_embeddings_input_dim": 2816,
|
| 54 |
+
"resnet_out_scale_factor": 1.0,
|
| 55 |
+
"resnet_skip_time_act": False,
|
| 56 |
+
"resnet_time_scale_shift": "default",
|
| 57 |
+
"sample_size": 128,
|
| 58 |
+
"time_cond_proj_dim": None,
|
| 59 |
+
"time_embedding_act_fn": None,
|
| 60 |
+
"time_embedding_dim": None,
|
| 61 |
+
"time_embedding_type": "positional",
|
| 62 |
+
"timestep_post_act": None,
|
| 63 |
+
"transformer_layers_per_block": [1, 2, 10],
|
| 64 |
+
"up_block_types": ["CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D"],
|
| 65 |
+
"upcast_attention": False,
|
| 66 |
+
"use_linear_projection": True,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def convert_sdxl_text_encoder_2_checkpoint(checkpoint, max_length):
|
| 71 |
+
SDXL_KEY_PREFIX = "conditioner.embedders.1.model."
|
| 72 |
+
|
| 73 |
+
# SD2のと、基本的には同じ。logit_scaleを後で使うので、それを追加で返す
|
| 74 |
+
# logit_scaleはcheckpointの保存時に使用する
|
| 75 |
+
def convert_key(key):
|
| 76 |
+
# common conversion
|
| 77 |
+
key = key.replace(SDXL_KEY_PREFIX + "transformer.", "text_model.encoder.")
|
| 78 |
+
key = key.replace(SDXL_KEY_PREFIX, "text_model.")
|
| 79 |
+
|
| 80 |
+
if "resblocks" in key:
|
| 81 |
+
# resblocks conversion
|
| 82 |
+
key = key.replace(".resblocks.", ".layers.")
|
| 83 |
+
if ".ln_" in key:
|
| 84 |
+
key = key.replace(".ln_", ".layer_norm")
|
| 85 |
+
elif ".mlp." in key:
|
| 86 |
+
key = key.replace(".c_fc.", ".fc1.")
|
| 87 |
+
key = key.replace(".c_proj.", ".fc2.")
|
| 88 |
+
elif ".attn.out_proj" in key:
|
| 89 |
+
key = key.replace(".attn.out_proj.", ".self_attn.out_proj.")
|
| 90 |
+
elif ".attn.in_proj" in key:
|
| 91 |
+
key = None # 特殊なので後で処理する
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError(f"unexpected key in SD: {key}")
|
| 94 |
+
elif ".positional_embedding" in key:
|
| 95 |
+
key = key.replace(".positional_embedding", ".embeddings.position_embedding.weight")
|
| 96 |
+
elif ".text_projection" in key:
|
| 97 |
+
key = key.replace("text_model.text_projection", "text_projection.weight")
|
| 98 |
+
elif ".logit_scale" in key:
|
| 99 |
+
key = None # 後で処理する
|
| 100 |
+
elif ".token_embedding" in key:
|
| 101 |
+
key = key.replace(".token_embedding.weight", ".embeddings.token_embedding.weight")
|
| 102 |
+
elif ".ln_final" in key:
|
| 103 |
+
key = key.replace(".ln_final", ".final_layer_norm")
|
| 104 |
+
# ckpt from comfy has this key: text_model.encoder.text_model.embeddings.position_ids
|
| 105 |
+
elif ".embeddings.position_ids" in key:
|
| 106 |
+
key = None # remove this key: position_ids is not used in newer transformers
|
| 107 |
+
return key
|
| 108 |
+
|
| 109 |
+
keys = list(checkpoint.keys())
|
| 110 |
+
new_sd = {}
|
| 111 |
+
for key in keys:
|
| 112 |
+
new_key = convert_key(key)
|
| 113 |
+
if new_key is None:
|
| 114 |
+
continue
|
| 115 |
+
new_sd[new_key] = checkpoint[key]
|
| 116 |
+
|
| 117 |
+
# attnの変換
|
| 118 |
+
for key in keys:
|
| 119 |
+
if ".resblocks" in key and ".attn.in_proj_" in key:
|
| 120 |
+
# 三つに分割
|
| 121 |
+
values = torch.chunk(checkpoint[key], 3)
|
| 122 |
+
|
| 123 |
+
key_suffix = ".weight" if "weight" in key else ".bias"
|
| 124 |
+
key_pfx = key.replace(SDXL_KEY_PREFIX + "transformer.resblocks.", "text_model.encoder.layers.")
|
| 125 |
+
key_pfx = key_pfx.replace("_weight", "")
|
| 126 |
+
key_pfx = key_pfx.replace("_bias", "")
|
| 127 |
+
key_pfx = key_pfx.replace(".attn.in_proj", ".self_attn.")
|
| 128 |
+
new_sd[key_pfx + "q_proj" + key_suffix] = values[0]
|
| 129 |
+
new_sd[key_pfx + "k_proj" + key_suffix] = values[1]
|
| 130 |
+
new_sd[key_pfx + "v_proj" + key_suffix] = values[2]
|
| 131 |
+
|
| 132 |
+
# logit_scale はDiffusersには含まれないが、保存時に戻したいので別途返す
|
| 133 |
+
logit_scale = checkpoint.get(SDXL_KEY_PREFIX + "logit_scale", None)
|
| 134 |
+
|
| 135 |
+
# temporary workaround for text_projection.weight.weight for Playground-v2
|
| 136 |
+
if "text_projection.weight.weight" in new_sd:
|
| 137 |
+
logger.info("convert_sdxl_text_encoder_2_checkpoint: convert text_projection.weight.weight to text_projection.weight")
|
| 138 |
+
new_sd["text_projection.weight"] = new_sd["text_projection.weight.weight"]
|
| 139 |
+
del new_sd["text_projection.weight.weight"]
|
| 140 |
+
|
| 141 |
+
return new_sd, logit_scale
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# load state_dict without allocating new tensors
|
| 145 |
+
def _load_state_dict_on_device(model, state_dict, device, dtype=None):
|
| 146 |
+
# dtype will use fp32 as default
|
| 147 |
+
missing_keys = list(model.state_dict().keys() - state_dict.keys())
|
| 148 |
+
unexpected_keys = list(state_dict.keys() - model.state_dict().keys())
|
| 149 |
+
|
| 150 |
+
# similar to model.load_state_dict()
|
| 151 |
+
if not missing_keys and not unexpected_keys:
|
| 152 |
+
for k in list(state_dict.keys()):
|
| 153 |
+
set_module_tensor_to_device(model, k, device, value=state_dict.pop(k), dtype=dtype)
|
| 154 |
+
return "<All keys matched successfully>"
|
| 155 |
+
|
| 156 |
+
# error_msgs
|
| 157 |
+
error_msgs: List[str] = []
|
| 158 |
+
if missing_keys:
|
| 159 |
+
error_msgs.insert(0, "Missing key(s) in state_dict: {}. ".format(", ".join('"{}"'.format(k) for k in missing_keys)))
|
| 160 |
+
if unexpected_keys:
|
| 161 |
+
error_msgs.insert(0, "Unexpected key(s) in state_dict: {}. ".format(", ".join('"{}"'.format(k) for k in unexpected_keys)))
|
| 162 |
+
|
| 163 |
+
raise RuntimeError("Error(s) in loading state_dict for {}:\n\t{}".format(model.__class__.__name__, "\n\t".join(error_msgs)))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def load_models_from_sdxl_checkpoint(model_version, ckpt_path, map_location, dtype=None):
|
| 167 |
+
# model_version is reserved for future use
|
| 168 |
+
# dtype is used for full_fp16/bf16 integration. Text Encoder will remain fp32, because it runs on CPU when caching
|
| 169 |
+
|
| 170 |
+
# Load the state dict
|
| 171 |
+
if model_util.is_safetensors(ckpt_path):
|
| 172 |
+
checkpoint = None
|
| 173 |
+
try:
|
| 174 |
+
state_dict = load_file(ckpt_path, device=map_location)
|
| 175 |
+
except:
|
| 176 |
+
state_dict = load_file(ckpt_path) # prevent device invalid Error
|
| 177 |
+
epoch = None
|
| 178 |
+
global_step = None
|
| 179 |
+
else:
|
| 180 |
+
checkpoint = torch.load(ckpt_path, map_location=map_location)
|
| 181 |
+
if "state_dict" in checkpoint:
|
| 182 |
+
state_dict = checkpoint["state_dict"]
|
| 183 |
+
epoch = checkpoint.get("epoch", 0)
|
| 184 |
+
global_step = checkpoint.get("global_step", 0)
|
| 185 |
+
else:
|
| 186 |
+
state_dict = checkpoint
|
| 187 |
+
epoch = 0
|
| 188 |
+
global_step = 0
|
| 189 |
+
checkpoint = None
|
| 190 |
+
|
| 191 |
+
# U-Net
|
| 192 |
+
logger.info("building U-Net")
|
| 193 |
+
with init_empty_weights():
|
| 194 |
+
unet = sdxl_original_unet.SdxlUNet2DConditionModel()
|
| 195 |
+
|
| 196 |
+
logger.info("loading U-Net from checkpoint")
|
| 197 |
+
unet_sd = {}
|
| 198 |
+
for k in list(state_dict.keys()):
|
| 199 |
+
if k.startswith("model.diffusion_model."):
|
| 200 |
+
unet_sd[k.replace("model.diffusion_model.", "")] = state_dict.pop(k)
|
| 201 |
+
info = _load_state_dict_on_device(unet, unet_sd, device=map_location, dtype=dtype)
|
| 202 |
+
logger.info(f"U-Net: {info}")
|
| 203 |
+
|
| 204 |
+
# Text Encoders
|
| 205 |
+
logger.info("building text encoders")
|
| 206 |
+
|
| 207 |
+
# Text Encoder 1 is same to Stability AI's SDXL
|
| 208 |
+
text_model1_cfg = CLIPTextConfig(
|
| 209 |
+
vocab_size=49408,
|
| 210 |
+
hidden_size=768,
|
| 211 |
+
intermediate_size=3072,
|
| 212 |
+
num_hidden_layers=12,
|
| 213 |
+
num_attention_heads=12,
|
| 214 |
+
max_position_embeddings=77,
|
| 215 |
+
hidden_act="quick_gelu",
|
| 216 |
+
layer_norm_eps=1e-05,
|
| 217 |
+
dropout=0.0,
|
| 218 |
+
attention_dropout=0.0,
|
| 219 |
+
initializer_range=0.02,
|
| 220 |
+
initializer_factor=1.0,
|
| 221 |
+
pad_token_id=1,
|
| 222 |
+
bos_token_id=0,
|
| 223 |
+
eos_token_id=2,
|
| 224 |
+
model_type="clip_text_model",
|
| 225 |
+
projection_dim=768,
|
| 226 |
+
# torch_dtype="float32",
|
| 227 |
+
# transformers_version="4.25.0.dev0",
|
| 228 |
+
)
|
| 229 |
+
with init_empty_weights():
|
| 230 |
+
text_model1 = CLIPTextModel._from_config(text_model1_cfg)
|
| 231 |
+
|
| 232 |
+
# Text Encoder 2 is different from Stability AI's SDXL. SDXL uses open clip, but we use the model from HuggingFace.
|
| 233 |
+
# Note: Tokenizer from HuggingFace is different from SDXL. We must use open clip's tokenizer.
|
| 234 |
+
text_model2_cfg = CLIPTextConfig(
|
| 235 |
+
vocab_size=49408,
|
| 236 |
+
hidden_size=1280,
|
| 237 |
+
intermediate_size=5120,
|
| 238 |
+
num_hidden_layers=32,
|
| 239 |
+
num_attention_heads=20,
|
| 240 |
+
max_position_embeddings=77,
|
| 241 |
+
hidden_act="gelu",
|
| 242 |
+
layer_norm_eps=1e-05,
|
| 243 |
+
dropout=0.0,
|
| 244 |
+
attention_dropout=0.0,
|
| 245 |
+
initializer_range=0.02,
|
| 246 |
+
initializer_factor=1.0,
|
| 247 |
+
pad_token_id=1,
|
| 248 |
+
bos_token_id=0,
|
| 249 |
+
eos_token_id=2,
|
| 250 |
+
model_type="clip_text_model",
|
| 251 |
+
projection_dim=1280,
|
| 252 |
+
# torch_dtype="float32",
|
| 253 |
+
# transformers_version="4.25.0.dev0",
|
| 254 |
+
)
|
| 255 |
+
with init_empty_weights():
|
| 256 |
+
text_model2 = CLIPTextModelWithProjection(text_model2_cfg)
|
| 257 |
+
|
| 258 |
+
logger.info("loading text encoders from checkpoint")
|
| 259 |
+
te1_sd = {}
|
| 260 |
+
te2_sd = {}
|
| 261 |
+
for k in list(state_dict.keys()):
|
| 262 |
+
if k.startswith("conditioner.embedders.0.transformer."):
|
| 263 |
+
te1_sd[k.replace("conditioner.embedders.0.transformer.", "")] = state_dict.pop(k)
|
| 264 |
+
elif k.startswith("conditioner.embedders.1.model."):
|
| 265 |
+
te2_sd[k] = state_dict.pop(k)
|
| 266 |
+
|
| 267 |
+
# 最新の transformers では position_ids を含むとエラーになるので削除 / remove position_ids for latest transformers
|
| 268 |
+
if "text_model.embeddings.position_ids" in te1_sd:
|
| 269 |
+
te1_sd.pop("text_model.embeddings.position_ids")
|
| 270 |
+
|
| 271 |
+
info1 = _load_state_dict_on_device(text_model1, te1_sd, device=map_location) # remain fp32
|
| 272 |
+
logger.info(f"text encoder 1: {info1}")
|
| 273 |
+
|
| 274 |
+
converted_sd, logit_scale = convert_sdxl_text_encoder_2_checkpoint(te2_sd, max_length=77)
|
| 275 |
+
info2 = _load_state_dict_on_device(text_model2, converted_sd, device=map_location) # remain fp32
|
| 276 |
+
logger.info(f"text encoder 2: {info2}")
|
| 277 |
+
|
| 278 |
+
# prepare vae
|
| 279 |
+
logger.info("building VAE")
|
| 280 |
+
vae_config = model_util.create_vae_diffusers_config()
|
| 281 |
+
with init_empty_weights():
|
| 282 |
+
vae = AutoencoderKL(**vae_config)
|
| 283 |
+
|
| 284 |
+
logger.info("loading VAE from checkpoint")
|
| 285 |
+
converted_vae_checkpoint = model_util.convert_ldm_vae_checkpoint(state_dict, vae_config)
|
| 286 |
+
info = _load_state_dict_on_device(vae, converted_vae_checkpoint, device=map_location, dtype=dtype)
|
| 287 |
+
logger.info(f"VAE: {info}")
|
| 288 |
+
|
| 289 |
+
ckpt_info = (epoch, global_step) if epoch is not None else None
|
| 290 |
+
return text_model1, text_model2, vae, unet, logit_scale, ckpt_info
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def make_unet_conversion_map():
|
| 294 |
+
unet_conversion_map_layer = []
|
| 295 |
+
|
| 296 |
+
for i in range(3): # num_blocks is 3 in sdxl
|
| 297 |
+
# loop over downblocks/upblocks
|
| 298 |
+
for j in range(2):
|
| 299 |
+
# loop over resnets/attentions for downblocks
|
| 300 |
+
hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
|
| 301 |
+
sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0."
|
| 302 |
+
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
|
| 303 |
+
|
| 304 |
+
if i < 3:
|
| 305 |
+
# no attention layers in down_blocks.3
|
| 306 |
+
hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
|
| 307 |
+
sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1."
|
| 308 |
+
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
|
| 309 |
+
|
| 310 |
+
for j in range(3):
|
| 311 |
+
# loop over resnets/attentions for upblocks
|
| 312 |
+
hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
|
| 313 |
+
sd_up_res_prefix = f"output_blocks.{3*i + j}.0."
|
| 314 |
+
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
|
| 315 |
+
|
| 316 |
+
# if i > 0: commentout for sdxl
|
| 317 |
+
# no attention layers in up_blocks.0
|
| 318 |
+
hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
|
| 319 |
+
sd_up_atn_prefix = f"output_blocks.{3*i + j}.1."
|
| 320 |
+
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
|
| 321 |
+
|
| 322 |
+
if i < 3:
|
| 323 |
+
# no downsample in down_blocks.3
|
| 324 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
|
| 325 |
+
sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op."
|
| 326 |
+
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
|
| 327 |
+
|
| 328 |
+
# no upsample in up_blocks.3
|
| 329 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
| 330 |
+
sd_upsample_prefix = f"output_blocks.{3*i + 2}.{2}." # change for sdxl
|
| 331 |
+
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
|
| 332 |
+
|
| 333 |
+
hf_mid_atn_prefix = "mid_block.attentions.0."
|
| 334 |
+
sd_mid_atn_prefix = "middle_block.1."
|
| 335 |
+
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
|
| 336 |
+
|
| 337 |
+
for j in range(2):
|
| 338 |
+
hf_mid_res_prefix = f"mid_block.resnets.{j}."
|
| 339 |
+
sd_mid_res_prefix = f"middle_block.{2*j}."
|
| 340 |
+
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
| 341 |
+
|
| 342 |
+
unet_conversion_map_resnet = [
|
| 343 |
+
# (stable-diffusion, HF Diffusers)
|
| 344 |
+
("in_layers.0.", "norm1."),
|
| 345 |
+
("in_layers.2.", "conv1."),
|
| 346 |
+
("out_layers.0.", "norm2."),
|
| 347 |
+
("out_layers.3.", "conv2."),
|
| 348 |
+
("emb_layers.1.", "time_emb_proj."),
|
| 349 |
+
("skip_connection.", "conv_shortcut."),
|
| 350 |
+
]
|
| 351 |
+
|
| 352 |
+
unet_conversion_map = []
|
| 353 |
+
for sd, hf in unet_conversion_map_layer:
|
| 354 |
+
if "resnets" in hf:
|
| 355 |
+
for sd_res, hf_res in unet_conversion_map_resnet:
|
| 356 |
+
unet_conversion_map.append((sd + sd_res, hf + hf_res))
|
| 357 |
+
else:
|
| 358 |
+
unet_conversion_map.append((sd, hf))
|
| 359 |
+
|
| 360 |
+
for j in range(2):
|
| 361 |
+
hf_time_embed_prefix = f"time_embedding.linear_{j+1}."
|
| 362 |
+
sd_time_embed_prefix = f"time_embed.{j*2}."
|
| 363 |
+
unet_conversion_map.append((sd_time_embed_prefix, hf_time_embed_prefix))
|
| 364 |
+
|
| 365 |
+
for j in range(2):
|
| 366 |
+
hf_label_embed_prefix = f"add_embedding.linear_{j+1}."
|
| 367 |
+
sd_label_embed_prefix = f"label_emb.0.{j*2}."
|
| 368 |
+
unet_conversion_map.append((sd_label_embed_prefix, hf_label_embed_prefix))
|
| 369 |
+
|
| 370 |
+
unet_conversion_map.append(("input_blocks.0.0.", "conv_in."))
|
| 371 |
+
unet_conversion_map.append(("out.0.", "conv_norm_out."))
|
| 372 |
+
unet_conversion_map.append(("out.2.", "conv_out."))
|
| 373 |
+
|
| 374 |
+
return unet_conversion_map
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def convert_diffusers_unet_state_dict_to_sdxl(du_sd):
|
| 378 |
+
unet_conversion_map = make_unet_conversion_map()
|
| 379 |
+
|
| 380 |
+
conversion_map = {hf: sd for sd, hf in unet_conversion_map}
|
| 381 |
+
return convert_unet_state_dict(du_sd, conversion_map)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def convert_unet_state_dict(src_sd, conversion_map):
|
| 385 |
+
converted_sd = {}
|
| 386 |
+
for src_key, value in src_sd.items():
|
| 387 |
+
# さすがに全部回すのは時間がかかるので右から要素を削りつつprefixを探す
|
| 388 |
+
src_key_fragments = src_key.split(".")[:-1] # remove weight/bias
|
| 389 |
+
while len(src_key_fragments) > 0:
|
| 390 |
+
src_key_prefix = ".".join(src_key_fragments) + "."
|
| 391 |
+
if src_key_prefix in conversion_map:
|
| 392 |
+
converted_prefix = conversion_map[src_key_prefix]
|
| 393 |
+
converted_key = converted_prefix + src_key[len(src_key_prefix) :]
|
| 394 |
+
converted_sd[converted_key] = value
|
| 395 |
+
break
|
| 396 |
+
src_key_fragments.pop(-1)
|
| 397 |
+
assert len(src_key_fragments) > 0, f"key {src_key} not found in conversion map"
|
| 398 |
+
|
| 399 |
+
return converted_sd
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def convert_sdxl_unet_state_dict_to_diffusers(sd):
|
| 403 |
+
unet_conversion_map = make_unet_conversion_map()
|
| 404 |
+
|
| 405 |
+
conversion_dict = {sd: hf for sd, hf in unet_conversion_map}
|
| 406 |
+
return convert_unet_state_dict(sd, conversion_dict)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def convert_text_encoder_2_state_dict_to_sdxl(checkpoint, logit_scale):
|
| 410 |
+
def convert_key(key):
|
| 411 |
+
# position_idsの除去
|
| 412 |
+
if ".position_ids" in key:
|
| 413 |
+
return None
|
| 414 |
+
|
| 415 |
+
# common
|
| 416 |
+
key = key.replace("text_model.encoder.", "transformer.")
|
| 417 |
+
key = key.replace("text_model.", "")
|
| 418 |
+
if "layers" in key:
|
| 419 |
+
# resblocks conversion
|
| 420 |
+
key = key.replace(".layers.", ".resblocks.")
|
| 421 |
+
if ".layer_norm" in key:
|
| 422 |
+
key = key.replace(".layer_norm", ".ln_")
|
| 423 |
+
elif ".mlp." in key:
|
| 424 |
+
key = key.replace(".fc1.", ".c_fc.")
|
| 425 |
+
key = key.replace(".fc2.", ".c_proj.")
|
| 426 |
+
elif ".self_attn.out_proj" in key:
|
| 427 |
+
key = key.replace(".self_attn.out_proj.", ".attn.out_proj.")
|
| 428 |
+
elif ".self_attn." in key:
|
| 429 |
+
key = None # 特殊なので後で処理する
|
| 430 |
+
else:
|
| 431 |
+
raise ValueError(f"unexpected key in DiffUsers model: {key}")
|
| 432 |
+
elif ".position_embedding" in key:
|
| 433 |
+
key = key.replace("embeddings.position_embedding.weight", "positional_embedding")
|
| 434 |
+
elif ".token_embedding" in key:
|
| 435 |
+
key = key.replace("embeddings.token_embedding.weight", "token_embedding.weight")
|
| 436 |
+
elif "text_projection" in key: # no dot in key
|
| 437 |
+
key = key.replace("text_projection.weight", "text_projection")
|
| 438 |
+
elif "final_layer_norm" in key:
|
| 439 |
+
key = key.replace("final_layer_norm", "ln_final")
|
| 440 |
+
return key
|
| 441 |
+
|
| 442 |
+
keys = list(checkpoint.keys())
|
| 443 |
+
new_sd = {}
|
| 444 |
+
for key in keys:
|
| 445 |
+
new_key = convert_key(key)
|
| 446 |
+
if new_key is None:
|
| 447 |
+
continue
|
| 448 |
+
new_sd[new_key] = checkpoint[key]
|
| 449 |
+
|
| 450 |
+
# attnの変換
|
| 451 |
+
for key in keys:
|
| 452 |
+
if "layers" in key and "q_proj" in key:
|
| 453 |
+
# 三つを結合
|
| 454 |
+
key_q = key
|
| 455 |
+
key_k = key.replace("q_proj", "k_proj")
|
| 456 |
+
key_v = key.replace("q_proj", "v_proj")
|
| 457 |
+
|
| 458 |
+
value_q = checkpoint[key_q]
|
| 459 |
+
value_k = checkpoint[key_k]
|
| 460 |
+
value_v = checkpoint[key_v]
|
| 461 |
+
value = torch.cat([value_q, value_k, value_v])
|
| 462 |
+
|
| 463 |
+
new_key = key.replace("text_model.encoder.layers.", "transformer.resblocks.")
|
| 464 |
+
new_key = new_key.replace(".self_attn.q_proj.", ".attn.in_proj_")
|
| 465 |
+
new_sd[new_key] = value
|
| 466 |
+
|
| 467 |
+
if logit_scale is not None:
|
| 468 |
+
new_sd["logit_scale"] = logit_scale
|
| 469 |
+
|
| 470 |
+
return new_sd
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def save_stable_diffusion_checkpoint(
|
| 474 |
+
output_file,
|
| 475 |
+
text_encoder1,
|
| 476 |
+
text_encoder2,
|
| 477 |
+
unet,
|
| 478 |
+
epochs,
|
| 479 |
+
steps,
|
| 480 |
+
ckpt_info,
|
| 481 |
+
vae,
|
| 482 |
+
logit_scale,
|
| 483 |
+
metadata,
|
| 484 |
+
save_dtype=None,
|
| 485 |
+
):
|
| 486 |
+
state_dict = {}
|
| 487 |
+
|
| 488 |
+
def update_sd(prefix, sd):
|
| 489 |
+
for k, v in sd.items():
|
| 490 |
+
key = prefix + k
|
| 491 |
+
if save_dtype is not None:
|
| 492 |
+
v = v.detach().clone().to("cpu").to(save_dtype)
|
| 493 |
+
state_dict[key] = v
|
| 494 |
+
|
| 495 |
+
# Convert the UNet model
|
| 496 |
+
update_sd("model.diffusion_model.", unet.state_dict())
|
| 497 |
+
|
| 498 |
+
# Convert the text encoders
|
| 499 |
+
update_sd("conditioner.embedders.0.transformer.", text_encoder1.state_dict())
|
| 500 |
+
|
| 501 |
+
text_enc2_dict = convert_text_encoder_2_state_dict_to_sdxl(text_encoder2.state_dict(), logit_scale)
|
| 502 |
+
update_sd("conditioner.embedders.1.model.", text_enc2_dict)
|
| 503 |
+
|
| 504 |
+
# Convert the VAE
|
| 505 |
+
vae_dict = model_util.convert_vae_state_dict(vae.state_dict())
|
| 506 |
+
update_sd("first_stage_model.", vae_dict)
|
| 507 |
+
|
| 508 |
+
# Put together new checkpoint
|
| 509 |
+
key_count = len(state_dict.keys())
|
| 510 |
+
new_ckpt = {"state_dict": state_dict}
|
| 511 |
+
|
| 512 |
+
# epoch and global_step are sometimes not int
|
| 513 |
+
if ckpt_info is not None:
|
| 514 |
+
epochs += ckpt_info[0]
|
| 515 |
+
steps += ckpt_info[1]
|
| 516 |
+
|
| 517 |
+
new_ckpt["epoch"] = epochs
|
| 518 |
+
new_ckpt["global_step"] = steps
|
| 519 |
+
|
| 520 |
+
if model_util.is_safetensors(output_file):
|
| 521 |
+
save_file(state_dict, output_file, metadata)
|
| 522 |
+
else:
|
| 523 |
+
torch.save(new_ckpt, output_file)
|
| 524 |
+
|
| 525 |
+
return key_count
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def save_diffusers_checkpoint(
|
| 529 |
+
output_dir, text_encoder1, text_encoder2, unet, pretrained_model_name_or_path, vae=None, use_safetensors=False, save_dtype=None
|
| 530 |
+
):
|
| 531 |
+
from diffusers import StableDiffusionXLPipeline
|
| 532 |
+
|
| 533 |
+
# convert U-Net
|
| 534 |
+
unet_sd = unet.state_dict()
|
| 535 |
+
du_unet_sd = convert_sdxl_unet_state_dict_to_diffusers(unet_sd)
|
| 536 |
+
|
| 537 |
+
diffusers_unet = UNet2DConditionModel(**DIFFUSERS_SDXL_UNET_CONFIG)
|
| 538 |
+
if save_dtype is not None:
|
| 539 |
+
diffusers_unet.to(save_dtype)
|
| 540 |
+
diffusers_unet.load_state_dict(du_unet_sd)
|
| 541 |
+
|
| 542 |
+
# create pipeline to save
|
| 543 |
+
if pretrained_model_name_or_path is None:
|
| 544 |
+
pretrained_model_name_or_path = DIFFUSERS_REF_MODEL_ID_SDXL
|
| 545 |
+
|
| 546 |
+
scheduler = EulerDiscreteScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
|
| 547 |
+
tokenizer1 = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer")
|
| 548 |
+
tokenizer2 = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer_2")
|
| 549 |
+
if vae is None:
|
| 550 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
|
| 551 |
+
|
| 552 |
+
# prevent local path from being saved
|
| 553 |
+
def remove_name_or_path(model):
|
| 554 |
+
if hasattr(model, "config"):
|
| 555 |
+
model.config._name_or_path = None
|
| 556 |
+
model.config._name_or_path = None
|
| 557 |
+
|
| 558 |
+
remove_name_or_path(diffusers_unet)
|
| 559 |
+
remove_name_or_path(text_encoder1)
|
| 560 |
+
remove_name_or_path(text_encoder2)
|
| 561 |
+
remove_name_or_path(scheduler)
|
| 562 |
+
remove_name_or_path(tokenizer1)
|
| 563 |
+
remove_name_or_path(tokenizer2)
|
| 564 |
+
remove_name_or_path(vae)
|
| 565 |
+
|
| 566 |
+
pipeline = StableDiffusionXLPipeline(
|
| 567 |
+
unet=diffusers_unet,
|
| 568 |
+
text_encoder=text_encoder1,
|
| 569 |
+
text_encoder_2=text_encoder2,
|
| 570 |
+
vae=vae,
|
| 571 |
+
scheduler=scheduler,
|
| 572 |
+
tokenizer=tokenizer1,
|
| 573 |
+
tokenizer_2=tokenizer2,
|
| 574 |
+
)
|
| 575 |
+
if save_dtype is not None:
|
| 576 |
+
pipeline.to(None, save_dtype)
|
| 577 |
+
pipeline.save_pretrained(output_dir, safe_serialization=use_safetensors)
|