Path: blob/main/scripts/convert_ms_text_to_video_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 LDM checkpoints. """1516import argparse1718import torch1920from diffusers import UNet3DConditionModel212223def assign_to_checkpoint(24paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None25):26"""27This does the final conversion step: take locally converted weights and apply a global renaming to them. It splits28attention layers, and takes into account additional replacements that may arise.2930Assigns the weights to the new checkpoint.31"""32assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."3334# Splits the attention layers into three variables.35if attention_paths_to_split is not None:36for path, path_map in attention_paths_to_split.items():37old_tensor = old_checkpoint[path]38channels = old_tensor.shape[0] // 33940target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)4142num_heads = old_tensor.shape[0] // config["num_head_channels"] // 34344old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])45query, key, value = old_tensor.split(channels // num_heads, dim=1)4647checkpoint[path_map["query"]] = query.reshape(target_shape)48checkpoint[path_map["key"]] = key.reshape(target_shape)49checkpoint[path_map["value"]] = value.reshape(target_shape)5051for path in paths:52new_path = path["new"]5354# These have already been assigned55if attention_paths_to_split is not None and new_path in attention_paths_to_split:56continue5758if additional_replacements is not None:59for replacement in additional_replacements:60new_path = new_path.replace(replacement["old"], replacement["new"])6162# proj_attn.weight has to be converted from conv 1D to linear63weight = old_checkpoint[path["old"]]64names = ["proj_attn.weight"]65names_2 = ["proj_out.weight", "proj_in.weight"]66if any(k in new_path for k in names):67checkpoint[new_path] = weight[:, :, 0]68elif any(k in new_path for k in names_2) and len(weight.shape) > 2 and ".attentions." not in new_path:69checkpoint[new_path] = weight[:, :, 0]70else:71checkpoint[new_path] = weight727374def renew_attention_paths(old_list, n_shave_prefix_segments=0):75"""76Updates paths inside attentions to the new naming scheme (local renaming)77"""78mapping = []79for old_item in old_list:80new_item = old_item8182# new_item = new_item.replace('norm.weight', 'group_norm.weight')83# new_item = new_item.replace('norm.bias', 'group_norm.bias')8485# new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')86# new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')8788# new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)8990mapping.append({"old": old_item, "new": new_item})9192return mapping939495def 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_temp_conv_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:111mapping.append({"old": old_item, "new": old_item})112113return mapping114115116def renew_resnet_paths(old_list, n_shave_prefix_segments=0):117"""118Updates paths inside resnets to the new naming scheme (local renaming)119"""120mapping = []121for old_item in old_list:122new_item = old_item.replace("in_layers.0", "norm1")123new_item = new_item.replace("in_layers.2", "conv1")124125new_item = new_item.replace("out_layers.0", "norm2")126new_item = new_item.replace("out_layers.3", "conv2")127128new_item = new_item.replace("emb_layers.1", "time_emb_proj")129new_item = new_item.replace("skip_connection", "conv_shortcut")130131new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)132133if "temopral_conv" not in old_item:134mapping.append({"old": old_item, "new": new_item})135136return mapping137138139def convert_ldm_unet_checkpoint(checkpoint, config, path=None, extract_ema=False):140"""141Takes a state dict and a config, and returns a converted checkpoint.142"""143144# extract state_dict for UNet145unet_state_dict = {}146keys = list(checkpoint.keys())147148unet_key = "model.diffusion_model."149150# at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA151if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:152print(f"Checkpoint {path} has both EMA and non-EMA weights.")153print(154"In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"155" weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."156)157for key in keys:158if key.startswith("model.diffusion_model"):159flat_ema_key = "model_ema." + "".join(key.split(".")[1:])160unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)161else:162if sum(k.startswith("model_ema") for k in keys) > 100:163print(164"In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"165" weights (usually better for inference), please make sure to add the `--extract_ema` flag."166)167168for key in keys:169unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)170171new_checkpoint = {}172173new_checkpoint["time_embedding.linear_1.weight"] = unet_state_dict["time_embed.0.weight"]174new_checkpoint["time_embedding.linear_1.bias"] = unet_state_dict["time_embed.0.bias"]175new_checkpoint["time_embedding.linear_2.weight"] = unet_state_dict["time_embed.2.weight"]176new_checkpoint["time_embedding.linear_2.bias"] = unet_state_dict["time_embed.2.bias"]177178if config["class_embed_type"] is None:179# No parameters to port180...181elif config["class_embed_type"] == "timestep" or config["class_embed_type"] == "projection":182new_checkpoint["class_embedding.linear_1.weight"] = unet_state_dict["label_emb.0.0.weight"]183new_checkpoint["class_embedding.linear_1.bias"] = unet_state_dict["label_emb.0.0.bias"]184new_checkpoint["class_embedding.linear_2.weight"] = unet_state_dict["label_emb.0.2.weight"]185new_checkpoint["class_embedding.linear_2.bias"] = unet_state_dict["label_emb.0.2.bias"]186else:187raise NotImplementedError(f"Not implemented `class_embed_type`: {config['class_embed_type']}")188189new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]190new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]191192first_temp_attention = [v for v in unet_state_dict if v.startswith("input_blocks.0.1")]193paths = renew_attention_paths(first_temp_attention)194meta_path = {"old": "input_blocks.0.1", "new": "transformer_in"}195assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config)196197new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]198new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]199new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]200new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]201202# Retrieves the keys for the input blocks only203num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})204input_blocks = {205layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]206for layer_id in range(num_input_blocks)207}208209# Retrieves the keys for the middle blocks only210num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})211middle_blocks = {212layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]213for layer_id in range(num_middle_blocks)214}215216# Retrieves the keys for the output blocks only217num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})218output_blocks = {219layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]220for layer_id in range(num_output_blocks)221}222223for i in range(1, num_input_blocks):224block_id = (i - 1) // (config["layers_per_block"] + 1)225layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)226227resnets = [228key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key229]230attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]231temp_attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.2" in key]232233if f"input_blocks.{i}.op.weight" in unet_state_dict:234new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(235f"input_blocks.{i}.op.weight"236)237new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(238f"input_blocks.{i}.op.bias"239)240241paths = renew_resnet_paths(resnets)242meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"}243assign_to_checkpoint(244paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config245)246247temporal_convs = [key for key in resnets if "temopral_conv" in key]248paths = renew_temp_conv_paths(temporal_convs)249meta_path = {250"old": f"input_blocks.{i}.0.temopral_conv",251"new": f"down_blocks.{block_id}.temp_convs.{layer_in_block_id}",252}253assign_to_checkpoint(254paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config255)256257if len(attentions):258paths = renew_attention_paths(attentions)259meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}260assign_to_checkpoint(261paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config262)263264if len(temp_attentions):265paths = renew_attention_paths(temp_attentions)266meta_path = {267"old": f"input_blocks.{i}.2",268"new": f"down_blocks.{block_id}.temp_attentions.{layer_in_block_id}",269}270assign_to_checkpoint(271paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config272)273274resnet_0 = middle_blocks[0]275temporal_convs_0 = [key for key in resnet_0 if "temopral_conv" in key]276attentions = middle_blocks[1]277temp_attentions = middle_blocks[2]278resnet_1 = middle_blocks[3]279temporal_convs_1 = [key for key in resnet_1 if "temopral_conv" in key]280281resnet_0_paths = renew_resnet_paths(resnet_0)282meta_path = {"old": "middle_block.0", "new": "mid_block.resnets.0"}283assign_to_checkpoint(284resnet_0_paths, new_checkpoint, unet_state_dict, config=config, additional_replacements=[meta_path]285)286287temp_conv_0_paths = renew_temp_conv_paths(temporal_convs_0)288meta_path = {"old": "middle_block.0.temopral_conv", "new": "mid_block.temp_convs.0"}289assign_to_checkpoint(290temp_conv_0_paths, new_checkpoint, unet_state_dict, config=config, additional_replacements=[meta_path]291)292293resnet_1_paths = renew_resnet_paths(resnet_1)294meta_path = {"old": "middle_block.3", "new": "mid_block.resnets.1"}295assign_to_checkpoint(296resnet_1_paths, new_checkpoint, unet_state_dict, config=config, additional_replacements=[meta_path]297)298299temp_conv_1_paths = renew_temp_conv_paths(temporal_convs_1)300meta_path = {"old": "middle_block.3.temopral_conv", "new": "mid_block.temp_convs.1"}301assign_to_checkpoint(302temp_conv_1_paths, new_checkpoint, unet_state_dict, config=config, additional_replacements=[meta_path]303)304305attentions_paths = renew_attention_paths(attentions)306meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}307assign_to_checkpoint(308attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config309)310311temp_attentions_paths = renew_attention_paths(temp_attentions)312meta_path = {"old": "middle_block.2", "new": "mid_block.temp_attentions.0"}313assign_to_checkpoint(314temp_attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config315)316317for i in range(num_output_blocks):318block_id = i // (config["layers_per_block"] + 1)319layer_in_block_id = i % (config["layers_per_block"] + 1)320output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]321output_block_list = {}322323for layer in output_block_layers:324layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)325if layer_id in output_block_list:326output_block_list[layer_id].append(layer_name)327else:328output_block_list[layer_id] = [layer_name]329330if len(output_block_list) > 1:331resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0" in key]332attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key]333temp_attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.2" in key]334335resnet_0_paths = renew_resnet_paths(resnets)336paths = renew_resnet_paths(resnets)337338meta_path = {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"}339assign_to_checkpoint(340paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config341)342343temporal_convs = [key for key in resnets if "temopral_conv" in key]344paths = renew_temp_conv_paths(temporal_convs)345meta_path = {346"old": f"output_blocks.{i}.0.temopral_conv",347"new": f"up_blocks.{block_id}.temp_convs.{layer_in_block_id}",348}349assign_to_checkpoint(350paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config351)352353output_block_list = {k: sorted(v) for k, v in output_block_list.items()}354if ["conv.bias", "conv.weight"] in output_block_list.values():355index = list(output_block_list.values()).index(["conv.bias", "conv.weight"])356new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[357f"output_blocks.{i}.{index}.conv.weight"358]359new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[360f"output_blocks.{i}.{index}.conv.bias"361]362363# Clear attentions as they have been attributed above.364if len(attentions) == 2:365attentions = []366367if len(attentions):368paths = renew_attention_paths(attentions)369meta_path = {370"old": f"output_blocks.{i}.1",371"new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",372}373assign_to_checkpoint(374paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config375)376377if len(temp_attentions):378paths = renew_attention_paths(temp_attentions)379meta_path = {380"old": f"output_blocks.{i}.2",381"new": f"up_blocks.{block_id}.temp_attentions.{layer_in_block_id}",382}383assign_to_checkpoint(384paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config385)386else:387resnet_0_paths = renew_resnet_paths(output_block_layers, n_shave_prefix_segments=1)388for path in resnet_0_paths:389old_path = ".".join(["output_blocks", str(i), path["old"]])390new_path = ".".join(["up_blocks", str(block_id), "resnets", str(layer_in_block_id), path["new"]])391new_checkpoint[new_path] = unet_state_dict[old_path]392393temopral_conv_paths = [l for l in output_block_layers if "temopral_conv" in l]394for path in temopral_conv_paths:395pruned_path = path.split("temopral_conv.")[-1]396old_path = ".".join(["output_blocks", str(i), str(block_id), "temopral_conv", pruned_path])397new_path = ".".join(["up_blocks", str(block_id), "temp_convs", str(layer_in_block_id), pruned_path])398new_checkpoint[new_path] = unet_state_dict[old_path]399400return new_checkpoint401402403if __name__ == "__main__":404parser = argparse.ArgumentParser()405406parser.add_argument(407"--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."408)409parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")410args = parser.parse_args()411412unet_checkpoint = torch.load(args.checkpoint_path, map_location="cpu")413unet = UNet3DConditionModel()414415converted_ckpt = convert_ldm_unet_checkpoint(unet_checkpoint, unet.config)416417diff_0 = set(unet.state_dict().keys()) - set(converted_ckpt.keys())418diff_1 = set(converted_ckpt.keys()) - set(unet.state_dict().keys())419420assert len(diff_0) == len(diff_1) == 0, "Converted weights don't match"421422# load state_dict423unet.load_state_dict(converted_ckpt)424425unet.save_pretrained(args.dump_path)426427# -- finish converting the unet --428429430