Path: blob/main/scripts/convert_versatile_diffusion_to_diffusers.py
1440 views
# coding=utf-81# Copyright 2023 The HuggingFace Inc. team.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.14""" Conversion script for the Versatile Stable Diffusion checkpoints. """1516import argparse17from argparse import Namespace1819import torch20from transformers import (21CLIPImageProcessor,22CLIPTextModelWithProjection,23CLIPTokenizer,24CLIPVisionModelWithProjection,25)2627from diffusers import (28AutoencoderKL,29DDIMScheduler,30DPMSolverMultistepScheduler,31EulerAncestralDiscreteScheduler,32EulerDiscreteScheduler,33LMSDiscreteScheduler,34PNDMScheduler,35UNet2DConditionModel,36VersatileDiffusionPipeline,37)38from diffusers.pipelines.versatile_diffusion.modeling_text_unet import UNetFlatConditionModel394041SCHEDULER_CONFIG = Namespace(42**{43"beta_linear_start": 0.00085,44"beta_linear_end": 0.012,45"timesteps": 1000,46"scale_factor": 0.18215,47}48)4950IMAGE_UNET_CONFIG = Namespace(51**{52"input_channels": 4,53"model_channels": 320,54"output_channels": 4,55"num_noattn_blocks": [2, 2, 2, 2],56"channel_mult": [1, 2, 4, 4],57"with_attn": [True, True, True, False],58"num_heads": 8,59"context_dim": 768,60"use_checkpoint": True,61}62)6364TEXT_UNET_CONFIG = Namespace(65**{66"input_channels": 768,67"model_channels": 320,68"output_channels": 768,69"num_noattn_blocks": [2, 2, 2, 2],70"channel_mult": [1, 2, 4, 4],71"second_dim": [4, 4, 4, 4],72"with_attn": [True, True, True, False],73"num_heads": 8,74"context_dim": 768,75"use_checkpoint": True,76}77)7879AUTOENCODER_CONFIG = Namespace(80**{81"double_z": True,82"z_channels": 4,83"resolution": 256,84"in_channels": 3,85"out_ch": 3,86"ch": 128,87"ch_mult": [1, 2, 4, 4],88"num_res_blocks": 2,89"attn_resolutions": [],90"dropout": 0.0,91}92)939495def shave_segments(path, n_shave_prefix_segments=1):96"""97Removes segments. Positive values shave the first segments, negative shave the last segments.98"""99if n_shave_prefix_segments >= 0:100return ".".join(path.split(".")[n_shave_prefix_segments:])101else:102return ".".join(path.split(".")[:n_shave_prefix_segments])103104105def renew_resnet_paths(old_list, n_shave_prefix_segments=0):106"""107Updates paths inside resnets to the new naming scheme (local renaming)108"""109mapping = []110for old_item in old_list:111new_item = old_item.replace("in_layers.0", "norm1")112new_item = new_item.replace("in_layers.2", "conv1")113114new_item = new_item.replace("out_layers.0", "norm2")115new_item = new_item.replace("out_layers.3", "conv2")116117new_item = new_item.replace("emb_layers.1", "time_emb_proj")118new_item = new_item.replace("skip_connection", "conv_shortcut")119120new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)121122mapping.append({"old": old_item, "new": new_item})123124return mapping125126127def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0):128"""129Updates paths inside resnets to the new naming scheme (local renaming)130"""131mapping = []132for old_item in old_list:133new_item = old_item134135new_item = new_item.replace("nin_shortcut", "conv_shortcut")136new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)137138mapping.append({"old": old_item, "new": new_item})139140return mapping141142143def renew_attention_paths(old_list, n_shave_prefix_segments=0):144"""145Updates paths inside attentions to the new naming scheme (local renaming)146"""147mapping = []148for old_item in old_list:149new_item = old_item150151# new_item = new_item.replace('norm.weight', 'group_norm.weight')152# new_item = new_item.replace('norm.bias', 'group_norm.bias')153154# new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')155# new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')156157# new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)158159mapping.append({"old": old_item, "new": new_item})160161return mapping162163164def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):165"""166Updates paths inside attentions to the new naming scheme (local renaming)167"""168mapping = []169for old_item in old_list:170new_item = old_item171172new_item = new_item.replace("norm.weight", "group_norm.weight")173new_item = new_item.replace("norm.bias", "group_norm.bias")174175new_item = new_item.replace("q.weight", "query.weight")176new_item = new_item.replace("q.bias", "query.bias")177178new_item = new_item.replace("k.weight", "key.weight")179new_item = new_item.replace("k.bias", "key.bias")180181new_item = new_item.replace("v.weight", "value.weight")182new_item = new_item.replace("v.bias", "value.bias")183184new_item = new_item.replace("proj_out.weight", "proj_attn.weight")185new_item = new_item.replace("proj_out.bias", "proj_attn.bias")186187new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)188189mapping.append({"old": old_item, "new": new_item})190191return mapping192193194def assign_to_checkpoint(195paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None196):197"""198This does the final conversion step: take locally converted weights and apply a global renaming199to them. It splits attention layers, and takes into account additional replacements200that may arise.201202Assigns the weights to the new checkpoint.203"""204assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."205206# Splits the attention layers into three variables.207if attention_paths_to_split is not None:208for path, path_map in attention_paths_to_split.items():209old_tensor = old_checkpoint[path]210channels = old_tensor.shape[0] // 3211212target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)213214num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3215216old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])217query, key, value = old_tensor.split(channels // num_heads, dim=1)218219checkpoint[path_map["query"]] = query.reshape(target_shape)220checkpoint[path_map["key"]] = key.reshape(target_shape)221checkpoint[path_map["value"]] = value.reshape(target_shape)222223for path in paths:224new_path = path["new"]225226# These have already been assigned227if attention_paths_to_split is not None and new_path in attention_paths_to_split:228continue229230# Global renaming happens here231new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")232new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")233new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")234235if additional_replacements is not None:236for replacement in additional_replacements:237new_path = new_path.replace(replacement["old"], replacement["new"])238239# proj_attn.weight has to be converted from conv 1D to linear240if "proj_attn.weight" in new_path:241checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]242elif path["old"] in old_checkpoint:243checkpoint[new_path] = old_checkpoint[path["old"]]244245246def conv_attn_to_linear(checkpoint):247keys = list(checkpoint.keys())248attn_keys = ["query.weight", "key.weight", "value.weight"]249for key in keys:250if ".".join(key.split(".")[-2:]) in attn_keys:251if checkpoint[key].ndim > 2:252checkpoint[key] = checkpoint[key][:, :, 0, 0]253elif "proj_attn.weight" in key:254if checkpoint[key].ndim > 2:255checkpoint[key] = checkpoint[key][:, :, 0]256257258def create_image_unet_diffusers_config(unet_params):259"""260Creates a config for the diffusers based on the config of the VD model.261"""262263block_out_channels = [unet_params.model_channels * mult for mult in unet_params.channel_mult]264265down_block_types = []266resolution = 1267for i in range(len(block_out_channels)):268block_type = "CrossAttnDownBlock2D" if unet_params.with_attn[i] else "DownBlock2D"269down_block_types.append(block_type)270if i != len(block_out_channels) - 1:271resolution *= 2272273up_block_types = []274for i in range(len(block_out_channels)):275block_type = "CrossAttnUpBlock2D" if unet_params.with_attn[-i - 1] else "UpBlock2D"276up_block_types.append(block_type)277resolution //= 2278279if not all(n == unet_params.num_noattn_blocks[0] for n in unet_params.num_noattn_blocks):280raise ValueError("Not all num_res_blocks are equal, which is not supported in this script.")281282config = dict(283sample_size=None,284in_channels=unet_params.input_channels,285out_channels=unet_params.output_channels,286down_block_types=tuple(down_block_types),287up_block_types=tuple(up_block_types),288block_out_channels=tuple(block_out_channels),289layers_per_block=unet_params.num_noattn_blocks[0],290cross_attention_dim=unet_params.context_dim,291attention_head_dim=unet_params.num_heads,292)293294return config295296297def create_text_unet_diffusers_config(unet_params):298"""299Creates a config for the diffusers based on the config of the VD model.300"""301302block_out_channels = [unet_params.model_channels * mult for mult in unet_params.channel_mult]303304down_block_types = []305resolution = 1306for i in range(len(block_out_channels)):307block_type = "CrossAttnDownBlockFlat" if unet_params.with_attn[i] else "DownBlockFlat"308down_block_types.append(block_type)309if i != len(block_out_channels) - 1:310resolution *= 2311312up_block_types = []313for i in range(len(block_out_channels)):314block_type = "CrossAttnUpBlockFlat" if unet_params.with_attn[-i - 1] else "UpBlockFlat"315up_block_types.append(block_type)316resolution //= 2317318if not all(n == unet_params.num_noattn_blocks[0] for n in unet_params.num_noattn_blocks):319raise ValueError("Not all num_res_blocks are equal, which is not supported in this script.")320321config = dict(322sample_size=None,323in_channels=(unet_params.input_channels, 1, 1),324out_channels=(unet_params.output_channels, 1, 1),325down_block_types=tuple(down_block_types),326up_block_types=tuple(up_block_types),327block_out_channels=tuple(block_out_channels),328layers_per_block=unet_params.num_noattn_blocks[0],329cross_attention_dim=unet_params.context_dim,330attention_head_dim=unet_params.num_heads,331)332333return config334335336def create_vae_diffusers_config(vae_params):337"""338Creates a config for the diffusers based on the config of the VD model.339"""340341block_out_channels = [vae_params.ch * mult for mult in vae_params.ch_mult]342down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)343up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)344345config = dict(346sample_size=vae_params.resolution,347in_channels=vae_params.in_channels,348out_channels=vae_params.out_ch,349down_block_types=tuple(down_block_types),350up_block_types=tuple(up_block_types),351block_out_channels=tuple(block_out_channels),352latent_channels=vae_params.z_channels,353layers_per_block=vae_params.num_res_blocks,354)355return config356357358def create_diffusers_scheduler(original_config):359schedular = DDIMScheduler(360num_train_timesteps=original_config.model.params.timesteps,361beta_start=original_config.model.params.linear_start,362beta_end=original_config.model.params.linear_end,363beta_schedule="scaled_linear",364)365return schedular366367368def convert_vd_unet_checkpoint(checkpoint, config, unet_key, extract_ema=False):369"""370Takes a state dict and a config, and returns a converted checkpoint.371"""372373# extract state_dict for UNet374unet_state_dict = {}375keys = list(checkpoint.keys())376377# at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA378if sum(k.startswith("model_ema") for k in keys) > 100:379print("Checkpoint has both EMA and non-EMA weights.")380if extract_ema:381print(382"In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"383" weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."384)385for key in keys:386if key.startswith("model.diffusion_model"):387flat_ema_key = "model_ema." + "".join(key.split(".")[1:])388unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)389else:390print(391"In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"392" weights (usually better for inference), please make sure to add the `--extract_ema` flag."393)394395for key in keys:396if key.startswith(unet_key):397unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)398399new_checkpoint = {}400401new_checkpoint["time_embedding.linear_1.weight"] = checkpoint["model.diffusion_model.time_embed.0.weight"]402new_checkpoint["time_embedding.linear_1.bias"] = checkpoint["model.diffusion_model.time_embed.0.bias"]403new_checkpoint["time_embedding.linear_2.weight"] = checkpoint["model.diffusion_model.time_embed.2.weight"]404new_checkpoint["time_embedding.linear_2.bias"] = checkpoint["model.diffusion_model.time_embed.2.bias"]405406new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]407new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]408409new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]410new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]411new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]412new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]413414# Retrieves the keys for the input blocks only415num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})416input_blocks = {417layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]418for layer_id in range(num_input_blocks)419}420421# Retrieves the keys for the middle blocks only422num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})423middle_blocks = {424layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]425for layer_id in range(num_middle_blocks)426}427428# Retrieves the keys for the output blocks only429num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})430output_blocks = {431layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]432for layer_id in range(num_output_blocks)433}434435for i in range(1, num_input_blocks):436block_id = (i - 1) // (config["layers_per_block"] + 1)437layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)438439resnets = [440key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key441]442attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]443444if f"input_blocks.{i}.0.op.weight" in unet_state_dict:445new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(446f"input_blocks.{i}.0.op.weight"447)448new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(449f"input_blocks.{i}.0.op.bias"450)451elif f"input_blocks.{i}.0.weight" in unet_state_dict:452# text_unet uses linear layers in place of downsamplers453shape = unet_state_dict[f"input_blocks.{i}.0.weight"].shape454if shape[0] != shape[1]:455continue456new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.weight"] = unet_state_dict.pop(457f"input_blocks.{i}.0.weight"458)459new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.bias"] = unet_state_dict.pop(460f"input_blocks.{i}.0.bias"461)462463paths = renew_resnet_paths(resnets)464meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"}465assign_to_checkpoint(466paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config467)468469if len(attentions):470paths = renew_attention_paths(attentions)471meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}472assign_to_checkpoint(473paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config474)475476resnet_0 = middle_blocks[0]477attentions = middle_blocks[1]478resnet_1 = middle_blocks[2]479480resnet_0_paths = renew_resnet_paths(resnet_0)481assign_to_checkpoint(resnet_0_paths, new_checkpoint, unet_state_dict, config=config)482483resnet_1_paths = renew_resnet_paths(resnet_1)484assign_to_checkpoint(resnet_1_paths, new_checkpoint, unet_state_dict, config=config)485486attentions_paths = renew_attention_paths(attentions)487meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}488assign_to_checkpoint(489attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config490)491492for i in range(num_output_blocks):493block_id = i // (config["layers_per_block"] + 1)494layer_in_block_id = i % (config["layers_per_block"] + 1)495output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]496output_block_list = {}497498for layer in output_block_layers:499layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)500if layer_id in output_block_list:501output_block_list[layer_id].append(layer_name)502else:503output_block_list[layer_id] = [layer_name]504505if len(output_block_list) > 1:506resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0" in key]507attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key]508509paths = renew_resnet_paths(resnets)510511meta_path = {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"}512assign_to_checkpoint(513paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config514)515516if ["conv.weight", "conv.bias"] in output_block_list.values():517index = list(output_block_list.values()).index(["conv.weight", "conv.bias"])518new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[519f"output_blocks.{i}.{index}.conv.weight"520]521new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[522f"output_blocks.{i}.{index}.conv.bias"523]524# Clear attentions as they have been attributed above.525if len(attentions) == 2:526attentions = []527elif f"output_blocks.{i}.1.weight" in unet_state_dict:528# text_unet uses linear layers in place of upsamplers529shape = unet_state_dict[f"output_blocks.{i}.1.weight"].shape530if shape[0] != shape[1]:531continue532new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.weight"] = unet_state_dict.pop(533f"output_blocks.{i}.1.weight"534)535new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.bias"] = unet_state_dict.pop(536f"output_blocks.{i}.1.bias"537)538# Clear attentions as they have been attributed above.539if len(attentions) == 2:540attentions = []541elif f"output_blocks.{i}.2.weight" in unet_state_dict:542# text_unet uses linear layers in place of upsamplers543shape = unet_state_dict[f"output_blocks.{i}.2.weight"].shape544if shape[0] != shape[1]:545continue546new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.weight"] = unet_state_dict.pop(547f"output_blocks.{i}.2.weight"548)549new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.bias"] = unet_state_dict.pop(550f"output_blocks.{i}.2.bias"551)552553if len(attentions):554paths = renew_attention_paths(attentions)555meta_path = {556"old": f"output_blocks.{i}.1",557"new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",558}559assign_to_checkpoint(560paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config561)562else:563resnet_0_paths = renew_resnet_paths(output_block_layers, n_shave_prefix_segments=1)564for path in resnet_0_paths:565old_path = ".".join(["output_blocks", str(i), path["old"]])566new_path = ".".join(["up_blocks", str(block_id), "resnets", str(layer_in_block_id), path["new"]])567568new_checkpoint[new_path] = unet_state_dict[old_path]569570return new_checkpoint571572573def convert_vd_vae_checkpoint(checkpoint, config):574# extract state dict for VAE575vae_state_dict = {}576keys = list(checkpoint.keys())577for key in keys:578vae_state_dict[key] = checkpoint.get(key)579580new_checkpoint = {}581582new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]583new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]584new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]585new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]586new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]587new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]588589new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]590new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]591new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]592new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]593new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]594new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]595596new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]597new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]598new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]599new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]600601# Retrieves the keys for the encoder down blocks only602num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})603down_blocks = {604layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)605}606607# Retrieves the keys for the decoder up blocks only608num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})609up_blocks = {610layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)611}612613for i in range(num_down_blocks):614resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]615616if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:617new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(618f"encoder.down.{i}.downsample.conv.weight"619)620new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(621f"encoder.down.{i}.downsample.conv.bias"622)623624paths = renew_vae_resnet_paths(resnets)625meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}626assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)627628mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]629num_mid_res_blocks = 2630for i in range(1, num_mid_res_blocks + 1):631resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]632633paths = renew_vae_resnet_paths(resnets)634meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}635assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)636637mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]638paths = renew_vae_attention_paths(mid_attentions)639meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}640assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)641conv_attn_to_linear(new_checkpoint)642643for i in range(num_up_blocks):644block_id = num_up_blocks - 1 - i645resnets = [646key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key647]648649if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:650new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[651f"decoder.up.{block_id}.upsample.conv.weight"652]653new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[654f"decoder.up.{block_id}.upsample.conv.bias"655]656657paths = renew_vae_resnet_paths(resnets)658meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}659assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)660661mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]662num_mid_res_blocks = 2663for i in range(1, num_mid_res_blocks + 1):664resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]665666paths = renew_vae_resnet_paths(resnets)667meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}668assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)669670mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]671paths = renew_vae_attention_paths(mid_attentions)672meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}673assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)674conv_attn_to_linear(new_checkpoint)675return new_checkpoint676677678if __name__ == "__main__":679parser = argparse.ArgumentParser()680681parser.add_argument(682"--unet_checkpoint_path", default=None, type=str, required=False, help="Path to the checkpoint to convert."683)684parser.add_argument(685"--vae_checkpoint_path", default=None, type=str, required=False, help="Path to the checkpoint to convert."686)687parser.add_argument(688"--optimus_checkpoint_path", default=None, type=str, required=False, help="Path to the checkpoint to convert."689)690parser.add_argument(691"--scheduler_type",692default="pndm",693type=str,694help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']",695)696parser.add_argument(697"--extract_ema",698action="store_true",699help=(700"Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"701" or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"702" higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."703),704)705parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")706707args = parser.parse_args()708709scheduler_config = SCHEDULER_CONFIG710711num_train_timesteps = scheduler_config.timesteps712beta_start = scheduler_config.beta_linear_start713beta_end = scheduler_config.beta_linear_end714if args.scheduler_type == "pndm":715scheduler = PNDMScheduler(716beta_end=beta_end,717beta_schedule="scaled_linear",718beta_start=beta_start,719num_train_timesteps=num_train_timesteps,720skip_prk_steps=True,721steps_offset=1,722)723elif args.scheduler_type == "lms":724scheduler = LMSDiscreteScheduler(beta_start=beta_start, beta_end=beta_end, beta_schedule="scaled_linear")725elif args.scheduler_type == "euler":726scheduler = EulerDiscreteScheduler(beta_start=beta_start, beta_end=beta_end, beta_schedule="scaled_linear")727elif args.scheduler_type == "euler-ancestral":728scheduler = EulerAncestralDiscreteScheduler(729beta_start=beta_start, beta_end=beta_end, beta_schedule="scaled_linear"730)731elif args.scheduler_type == "dpm":732scheduler = DPMSolverMultistepScheduler(733beta_start=beta_start, beta_end=beta_end, beta_schedule="scaled_linear"734)735elif args.scheduler_type == "ddim":736scheduler = DDIMScheduler(737beta_start=beta_start,738beta_end=beta_end,739beta_schedule="scaled_linear",740clip_sample=False,741set_alpha_to_one=False,742steps_offset=1,743)744else:745raise ValueError(f"Scheduler of type {args.scheduler_type} doesn't exist!")746747# Convert the UNet2DConditionModel models.748if args.unet_checkpoint_path is not None:749# image UNet750image_unet_config = create_image_unet_diffusers_config(IMAGE_UNET_CONFIG)751checkpoint = torch.load(args.unet_checkpoint_path)752converted_image_unet_checkpoint = convert_vd_unet_checkpoint(753checkpoint, image_unet_config, unet_key="model.diffusion_model.unet_image.", extract_ema=args.extract_ema754)755image_unet = UNet2DConditionModel(**image_unet_config)756image_unet.load_state_dict(converted_image_unet_checkpoint)757758# text UNet759text_unet_config = create_text_unet_diffusers_config(TEXT_UNET_CONFIG)760converted_text_unet_checkpoint = convert_vd_unet_checkpoint(761checkpoint, text_unet_config, unet_key="model.diffusion_model.unet_text.", extract_ema=args.extract_ema762)763text_unet = UNetFlatConditionModel(**text_unet_config)764text_unet.load_state_dict(converted_text_unet_checkpoint)765766# Convert the VAE model.767if args.vae_checkpoint_path is not None:768vae_config = create_vae_diffusers_config(AUTOENCODER_CONFIG)769checkpoint = torch.load(args.vae_checkpoint_path)770converted_vae_checkpoint = convert_vd_vae_checkpoint(checkpoint, vae_config)771772vae = AutoencoderKL(**vae_config)773vae.load_state_dict(converted_vae_checkpoint)774775tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")776image_feature_extractor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")777text_encoder = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-large-patch14")778image_encoder = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14")779780pipe = VersatileDiffusionPipeline(781scheduler=scheduler,782tokenizer=tokenizer,783image_feature_extractor=image_feature_extractor,784text_encoder=text_encoder,785image_encoder=image_encoder,786image_unet=image_unet,787text_unet=text_unet,788vae=vae,789)790pipe.save_pretrained(args.dump_path)791792793