Path: blob/main/scripts/convert_original_audioldm_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 AudioLDM checkpoints."""1516import argparse17import re1819import torch20from transformers import (21AutoTokenizer,22ClapTextConfig,23ClapTextModelWithProjection,24SpeechT5HifiGan,25SpeechT5HifiGanConfig,26)2728from diffusers import (29AudioLDMPipeline,30AutoencoderKL,31DDIMScheduler,32DPMSolverMultistepScheduler,33EulerAncestralDiscreteScheduler,34EulerDiscreteScheduler,35HeunDiscreteScheduler,36LMSDiscreteScheduler,37PNDMScheduler,38UNet2DConditionModel,39)40from diffusers.utils import is_omegaconf_available, is_safetensors_available41from diffusers.utils.import_utils import BACKENDS_MAPPING424344# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.shave_segments45def shave_segments(path, n_shave_prefix_segments=1):46"""47Removes segments. Positive values shave the first segments, negative shave the last segments.48"""49if n_shave_prefix_segments >= 0:50return ".".join(path.split(".")[n_shave_prefix_segments:])51else:52return ".".join(path.split(".")[:n_shave_prefix_segments])535455# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.renew_resnet_paths56def renew_resnet_paths(old_list, n_shave_prefix_segments=0):57"""58Updates paths inside resnets to the new naming scheme (local renaming)59"""60mapping = []61for old_item in old_list:62new_item = old_item.replace("in_layers.0", "norm1")63new_item = new_item.replace("in_layers.2", "conv1")6465new_item = new_item.replace("out_layers.0", "norm2")66new_item = new_item.replace("out_layers.3", "conv2")6768new_item = new_item.replace("emb_layers.1", "time_emb_proj")69new_item = new_item.replace("skip_connection", "conv_shortcut")7071new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)7273mapping.append({"old": old_item, "new": new_item})7475return mapping767778# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.renew_vae_resnet_paths79def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0):80"""81Updates paths inside resnets to the new naming scheme (local renaming)82"""83mapping = []84for old_item in old_list:85new_item = old_item8687new_item = new_item.replace("nin_shortcut", "conv_shortcut")88new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)8990mapping.append({"old": old_item, "new": new_item})9192return mapping939495# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.renew_attention_paths96def renew_attention_paths(old_list):97"""98Updates paths inside attentions to the new naming scheme (local renaming)99"""100mapping = []101for old_item in old_list:102new_item = old_item103104# new_item = new_item.replace('norm.weight', 'group_norm.weight')105# new_item = new_item.replace('norm.bias', 'group_norm.bias')106107# new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')108# new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')109110# new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)111112mapping.append({"old": old_item, "new": new_item})113114return mapping115116117# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.renew_vae_attention_paths118def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):119"""120Updates paths inside attentions to the new naming scheme (local renaming)121"""122mapping = []123for old_item in old_list:124new_item = old_item125126new_item = new_item.replace("norm.weight", "group_norm.weight")127new_item = new_item.replace("norm.bias", "group_norm.bias")128129new_item = new_item.replace("q.weight", "query.weight")130new_item = new_item.replace("q.bias", "query.bias")131132new_item = new_item.replace("k.weight", "key.weight")133new_item = new_item.replace("k.bias", "key.bias")134135new_item = new_item.replace("v.weight", "value.weight")136new_item = new_item.replace("v.bias", "value.bias")137138new_item = new_item.replace("proj_out.weight", "proj_attn.weight")139new_item = new_item.replace("proj_out.bias", "proj_attn.bias")140141new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)142143mapping.append({"old": old_item, "new": new_item})144145return mapping146147148# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.assign_to_checkpoint149def assign_to_checkpoint(150paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None151):152"""153This does the final conversion step: take locally converted weights and apply a global renaming to them. It splits154attention layers, and takes into account additional replacements that may arise.155156Assigns the weights to the new checkpoint.157"""158assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."159160# Splits the attention layers into three variables.161if attention_paths_to_split is not None:162for path, path_map in attention_paths_to_split.items():163old_tensor = old_checkpoint[path]164channels = old_tensor.shape[0] // 3165166target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)167168num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3169170old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])171query, key, value = old_tensor.split(channels // num_heads, dim=1)172173checkpoint[path_map["query"]] = query.reshape(target_shape)174checkpoint[path_map["key"]] = key.reshape(target_shape)175checkpoint[path_map["value"]] = value.reshape(target_shape)176177for path in paths:178new_path = path["new"]179180# These have already been assigned181if attention_paths_to_split is not None and new_path in attention_paths_to_split:182continue183184# Global renaming happens here185new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")186new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")187new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")188189if additional_replacements is not None:190for replacement in additional_replacements:191new_path = new_path.replace(replacement["old"], replacement["new"])192193# proj_attn.weight has to be converted from conv 1D to linear194if "proj_attn.weight" in new_path:195checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]196else:197checkpoint[new_path] = old_checkpoint[path["old"]]198199200# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.conv_attn_to_linear201def conv_attn_to_linear(checkpoint):202keys = list(checkpoint.keys())203attn_keys = ["query.weight", "key.weight", "value.weight"]204for key in keys:205if ".".join(key.split(".")[-2:]) in attn_keys:206if checkpoint[key].ndim > 2:207checkpoint[key] = checkpoint[key][:, :, 0, 0]208elif "proj_attn.weight" in key:209if checkpoint[key].ndim > 2:210checkpoint[key] = checkpoint[key][:, :, 0]211212213def create_unet_diffusers_config(original_config, image_size: int):214"""215Creates a UNet config for diffusers based on the config of the original AudioLDM model.216"""217unet_params = original_config.model.params.unet_config.params218vae_params = original_config.model.params.first_stage_config.params.ddconfig219220block_out_channels = [unet_params.model_channels * mult for mult in unet_params.channel_mult]221222down_block_types = []223resolution = 1224for i in range(len(block_out_channels)):225block_type = "CrossAttnDownBlock2D" if resolution in unet_params.attention_resolutions else "DownBlock2D"226down_block_types.append(block_type)227if i != len(block_out_channels) - 1:228resolution *= 2229230up_block_types = []231for i in range(len(block_out_channels)):232block_type = "CrossAttnUpBlock2D" if resolution in unet_params.attention_resolutions else "UpBlock2D"233up_block_types.append(block_type)234resolution //= 2235236vae_scale_factor = 2 ** (len(vae_params.ch_mult) - 1)237238cross_attention_dim = (239unet_params.cross_attention_dim if "cross_attention_dim" in unet_params else block_out_channels240)241242class_embed_type = "simple_projection" if "extra_film_condition_dim" in unet_params else None243projection_class_embeddings_input_dim = (244unet_params.extra_film_condition_dim if "extra_film_condition_dim" in unet_params else None245)246class_embeddings_concat = unet_params.extra_film_use_concat if "extra_film_use_concat" in unet_params else None247248config = dict(249sample_size=image_size // vae_scale_factor,250in_channels=unet_params.in_channels,251out_channels=unet_params.out_channels,252down_block_types=tuple(down_block_types),253up_block_types=tuple(up_block_types),254block_out_channels=tuple(block_out_channels),255layers_per_block=unet_params.num_res_blocks,256cross_attention_dim=cross_attention_dim,257class_embed_type=class_embed_type,258projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,259class_embeddings_concat=class_embeddings_concat,260)261262return config263264265# Adapted from diffusers.pipelines.stable_diffusion.convert_from_ckpt.create_vae_diffusers_config266def create_vae_diffusers_config(original_config, checkpoint, image_size: int):267"""268Creates a VAE config for diffusers based on the config of the original AudioLDM model. Compared to the original269Stable Diffusion conversion, this function passes a *learnt* VAE scaling factor to the diffusers VAE.270"""271vae_params = original_config.model.params.first_stage_config.params.ddconfig272_ = original_config.model.params.first_stage_config.params.embed_dim273274block_out_channels = [vae_params.ch * mult for mult in vae_params.ch_mult]275down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)276up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)277278scaling_factor = checkpoint["scale_factor"] if "scale_by_std" in original_config.model.params else 0.18215279280config = dict(281sample_size=image_size,282in_channels=vae_params.in_channels,283out_channels=vae_params.out_ch,284down_block_types=tuple(down_block_types),285up_block_types=tuple(up_block_types),286block_out_channels=tuple(block_out_channels),287latent_channels=vae_params.z_channels,288layers_per_block=vae_params.num_res_blocks,289scaling_factor=float(scaling_factor),290)291return config292293294# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.create_diffusers_schedular295def create_diffusers_schedular(original_config):296schedular = DDIMScheduler(297num_train_timesteps=original_config.model.params.timesteps,298beta_start=original_config.model.params.linear_start,299beta_end=original_config.model.params.linear_end,300beta_schedule="scaled_linear",301)302return schedular303304305# Adapted from diffusers.pipelines.stable_diffusion.convert_from_ckpt.convert_ldm_unet_checkpoint306def convert_ldm_unet_checkpoint(checkpoint, config, path=None, extract_ema=False):307"""308Takes a state dict and a config, and returns a converted checkpoint. Compared to the original Stable Diffusion309conversion, this function additionally converts the learnt film embedding linear layer.310"""311312# extract state_dict for UNet313unet_state_dict = {}314keys = list(checkpoint.keys())315316unet_key = "model.diffusion_model."317# at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA318if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:319print(f"Checkpoint {path} has both EMA and non-EMA weights.")320print(321"In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"322" weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."323)324for key in keys:325if key.startswith("model.diffusion_model"):326flat_ema_key = "model_ema." + "".join(key.split(".")[1:])327unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)328else:329if sum(k.startswith("model_ema") for k in keys) > 100:330print(331"In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"332" weights (usually better for inference), please make sure to add the `--extract_ema` flag."333)334335for key in keys:336if key.startswith(unet_key):337unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)338339new_checkpoint = {}340341new_checkpoint["time_embedding.linear_1.weight"] = unet_state_dict["time_embed.0.weight"]342new_checkpoint["time_embedding.linear_1.bias"] = unet_state_dict["time_embed.0.bias"]343new_checkpoint["time_embedding.linear_2.weight"] = unet_state_dict["time_embed.2.weight"]344new_checkpoint["time_embedding.linear_2.bias"] = unet_state_dict["time_embed.2.bias"]345346new_checkpoint["class_embedding.weight"] = unet_state_dict["film_emb.weight"]347new_checkpoint["class_embedding.bias"] = unet_state_dict["film_emb.bias"]348349new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]350new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]351352new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]353new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]354new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]355new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]356357# Retrieves the keys for the input blocks only358num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})359input_blocks = {360layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]361for layer_id in range(num_input_blocks)362}363364# Retrieves the keys for the middle blocks only365num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})366middle_blocks = {367layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]368for layer_id in range(num_middle_blocks)369}370371# Retrieves the keys for the output blocks only372num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})373output_blocks = {374layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]375for layer_id in range(num_output_blocks)376}377378for i in range(1, num_input_blocks):379block_id = (i - 1) // (config["layers_per_block"] + 1)380layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)381382resnets = [383key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key384]385attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]386387if f"input_blocks.{i}.0.op.weight" in unet_state_dict:388new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(389f"input_blocks.{i}.0.op.weight"390)391new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(392f"input_blocks.{i}.0.op.bias"393)394395paths = renew_resnet_paths(resnets)396meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"}397assign_to_checkpoint(398paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config399)400401if len(attentions):402paths = renew_attention_paths(attentions)403meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}404assign_to_checkpoint(405paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config406)407408resnet_0 = middle_blocks[0]409attentions = middle_blocks[1]410resnet_1 = middle_blocks[2]411412resnet_0_paths = renew_resnet_paths(resnet_0)413assign_to_checkpoint(resnet_0_paths, new_checkpoint, unet_state_dict, config=config)414415resnet_1_paths = renew_resnet_paths(resnet_1)416assign_to_checkpoint(resnet_1_paths, new_checkpoint, unet_state_dict, config=config)417418attentions_paths = renew_attention_paths(attentions)419meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}420assign_to_checkpoint(421attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config422)423424for i in range(num_output_blocks):425block_id = i // (config["layers_per_block"] + 1)426layer_in_block_id = i % (config["layers_per_block"] + 1)427output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]428output_block_list = {}429430for layer in output_block_layers:431layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)432if layer_id in output_block_list:433output_block_list[layer_id].append(layer_name)434else:435output_block_list[layer_id] = [layer_name]436437if len(output_block_list) > 1:438resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0" in key]439attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key]440441resnet_0_paths = renew_resnet_paths(resnets)442paths = renew_resnet_paths(resnets)443444meta_path = {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"}445assign_to_checkpoint(446paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config447)448449output_block_list = {k: sorted(v) for k, v in output_block_list.items()}450if ["conv.bias", "conv.weight"] in output_block_list.values():451index = list(output_block_list.values()).index(["conv.bias", "conv.weight"])452new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[453f"output_blocks.{i}.{index}.conv.weight"454]455new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[456f"output_blocks.{i}.{index}.conv.bias"457]458459# Clear attentions as they have been attributed above.460if len(attentions) == 2:461attentions = []462463if len(attentions):464paths = renew_attention_paths(attentions)465meta_path = {466"old": f"output_blocks.{i}.1",467"new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",468}469assign_to_checkpoint(470paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config471)472else:473resnet_0_paths = renew_resnet_paths(output_block_layers, n_shave_prefix_segments=1)474for path in resnet_0_paths:475old_path = ".".join(["output_blocks", str(i), path["old"]])476new_path = ".".join(["up_blocks", str(block_id), "resnets", str(layer_in_block_id), path["new"]])477478new_checkpoint[new_path] = unet_state_dict[old_path]479480return new_checkpoint481482483# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.convert_ldm_vae_checkpoint484def convert_ldm_vae_checkpoint(checkpoint, config):485# extract state dict for VAE486vae_state_dict = {}487vae_key = "first_stage_model."488keys = list(checkpoint.keys())489for key in keys:490if key.startswith(vae_key):491vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)492493new_checkpoint = {}494495new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]496new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]497new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]498new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]499new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]500new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]501502new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]503new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]504new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]505new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]506new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]507new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]508509new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]510new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]511new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]512new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]513514# Retrieves the keys for the encoder down blocks only515num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})516down_blocks = {517layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)518}519520# Retrieves the keys for the decoder up blocks only521num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})522up_blocks = {523layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)524}525526for i in range(num_down_blocks):527resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]528529if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:530new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(531f"encoder.down.{i}.downsample.conv.weight"532)533new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(534f"encoder.down.{i}.downsample.conv.bias"535)536537paths = renew_vae_resnet_paths(resnets)538meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}539assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)540541mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]542num_mid_res_blocks = 2543for i in range(1, num_mid_res_blocks + 1):544resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]545546paths = renew_vae_resnet_paths(resnets)547meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}548assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)549550mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]551paths = renew_vae_attention_paths(mid_attentions)552meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}553assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)554conv_attn_to_linear(new_checkpoint)555556for i in range(num_up_blocks):557block_id = num_up_blocks - 1 - i558resnets = [559key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key560]561562if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:563new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[564f"decoder.up.{block_id}.upsample.conv.weight"565]566new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[567f"decoder.up.{block_id}.upsample.conv.bias"568]569570paths = renew_vae_resnet_paths(resnets)571meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}572assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)573574mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]575num_mid_res_blocks = 2576for i in range(1, num_mid_res_blocks + 1):577resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]578579paths = renew_vae_resnet_paths(resnets)580meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}581assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)582583mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]584paths = renew_vae_attention_paths(mid_attentions)585meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}586assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)587conv_attn_to_linear(new_checkpoint)588return new_checkpoint589590591CLAP_KEYS_TO_MODIFY_MAPPING = {592"text_branch": "text_model",593"attn": "attention.self",594"self.proj": "output.dense",595"attention.self_mask": "attn_mask",596"mlp.fc1": "intermediate.dense",597"mlp.fc2": "output.dense",598"norm1": "layernorm_before",599"norm2": "layernorm_after",600"bn0": "batch_norm",601}602603CLAP_KEYS_TO_IGNORE = ["text_transform"]604605CLAP_EXPECTED_MISSING_KEYS = ["text_model.embeddings.token_type_ids"]606607608def convert_open_clap_checkpoint(checkpoint):609"""610Takes a state dict and returns a converted CLAP checkpoint.611"""612# extract state dict for CLAP text embedding model, discarding the audio component613model_state_dict = {}614model_key = "cond_stage_model.model.text_"615keys = list(checkpoint.keys())616for key in keys:617if key.startswith(model_key):618model_state_dict[key.replace(model_key, "text_")] = checkpoint.get(key)619620new_checkpoint = {}621622sequential_layers_pattern = r".*sequential.(\d+).*"623text_projection_pattern = r".*_projection.(\d+).*"624625for key, value in model_state_dict.items():626# check if key should be ignored in mapping627if key.split(".")[0] in CLAP_KEYS_TO_IGNORE:628continue629630# check if any key needs to be modified631for key_to_modify, new_key in CLAP_KEYS_TO_MODIFY_MAPPING.items():632if key_to_modify in key:633key = key.replace(key_to_modify, new_key)634635if re.match(sequential_layers_pattern, key):636# replace sequential layers with list637sequential_layer = re.match(sequential_layers_pattern, key).group(1)638639key = key.replace(f"sequential.{sequential_layer}.", f"layers.{int(sequential_layer)//3}.linear.")640elif re.match(text_projection_pattern, key):641projecton_layer = int(re.match(text_projection_pattern, key).group(1))642643# Because in CLAP they use `nn.Sequential`...644transformers_projection_layer = 1 if projecton_layer == 0 else 2645646key = key.replace(f"_projection.{projecton_layer}.", f"_projection.linear{transformers_projection_layer}.")647648if "audio" and "qkv" in key:649# split qkv into query key and value650mixed_qkv = value651qkv_dim = mixed_qkv.size(0) // 3652653query_layer = mixed_qkv[:qkv_dim]654key_layer = mixed_qkv[qkv_dim : qkv_dim * 2]655value_layer = mixed_qkv[qkv_dim * 2 :]656657new_checkpoint[key.replace("qkv", "query")] = query_layer658new_checkpoint[key.replace("qkv", "key")] = key_layer659new_checkpoint[key.replace("qkv", "value")] = value_layer660else:661new_checkpoint[key] = value662663return new_checkpoint664665666def create_transformers_vocoder_config(original_config):667"""668Creates a config for transformers SpeechT5HifiGan based on the config of the vocoder model.669"""670vocoder_params = original_config.model.params.vocoder_config.params671672config = dict(673model_in_dim=vocoder_params.num_mels,674sampling_rate=vocoder_params.sampling_rate,675upsample_initial_channel=vocoder_params.upsample_initial_channel,676upsample_rates=list(vocoder_params.upsample_rates),677upsample_kernel_sizes=list(vocoder_params.upsample_kernel_sizes),678resblock_kernel_sizes=list(vocoder_params.resblock_kernel_sizes),679resblock_dilation_sizes=[680list(resblock_dilation) for resblock_dilation in vocoder_params.resblock_dilation_sizes681],682normalize_before=False,683)684685return config686687688def convert_hifigan_checkpoint(checkpoint, config):689"""690Takes a state dict and config, and returns a converted HiFiGAN vocoder checkpoint.691"""692# extract state dict for vocoder693vocoder_state_dict = {}694vocoder_key = "first_stage_model.vocoder."695keys = list(checkpoint.keys())696for key in keys:697if key.startswith(vocoder_key):698vocoder_state_dict[key.replace(vocoder_key, "")] = checkpoint.get(key)699700# fix upsampler keys, everything else is correct already701for i in range(len(config.upsample_rates)):702vocoder_state_dict[f"upsampler.{i}.weight"] = vocoder_state_dict.pop(f"ups.{i}.weight")703vocoder_state_dict[f"upsampler.{i}.bias"] = vocoder_state_dict.pop(f"ups.{i}.bias")704705if not config.normalize_before:706# if we don't set normalize_before then these variables are unused, so we set them to their initialised values707vocoder_state_dict["mean"] = torch.zeros(config.model_in_dim)708vocoder_state_dict["scale"] = torch.ones(config.model_in_dim)709710return vocoder_state_dict711712713# Adapted from https://huggingface.co/spaces/haoheliu/audioldm-text-to-audio-generation/blob/84a0384742a22bd80c44e903e241f0623e874f1d/audioldm/utils.py#L72-L73714DEFAULT_CONFIG = {715"model": {716"params": {717"linear_start": 0.0015,718"linear_end": 0.0195,719"timesteps": 1000,720"channels": 8,721"scale_by_std": True,722"unet_config": {723"target": "audioldm.latent_diffusion.openaimodel.UNetModel",724"params": {725"extra_film_condition_dim": 512,726"extra_film_use_concat": True,727"in_channels": 8,728"out_channels": 8,729"model_channels": 128,730"attention_resolutions": [8, 4, 2],731"num_res_blocks": 2,732"channel_mult": [1, 2, 3, 5],733"num_head_channels": 32,734},735},736"first_stage_config": {737"target": "audioldm.variational_autoencoder.autoencoder.AutoencoderKL",738"params": {739"embed_dim": 8,740"ddconfig": {741"z_channels": 8,742"resolution": 256,743"in_channels": 1,744"out_ch": 1,745"ch": 128,746"ch_mult": [1, 2, 4],747"num_res_blocks": 2,748},749},750},751"vocoder_config": {752"target": "audioldm.first_stage_model.vocoder",753"params": {754"upsample_rates": [5, 4, 2, 2, 2],755"upsample_kernel_sizes": [16, 16, 8, 4, 4],756"upsample_initial_channel": 1024,757"resblock_kernel_sizes": [3, 7, 11],758"resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]],759"num_mels": 64,760"sampling_rate": 16000,761},762},763},764},765}766767768def load_pipeline_from_original_audioldm_ckpt(769checkpoint_path: str,770original_config_file: str = None,771image_size: int = 512,772prediction_type: str = None,773extract_ema: bool = False,774scheduler_type: str = "ddim",775num_in_channels: int = None,776device: str = None,777from_safetensors: bool = False,778) -> AudioLDMPipeline:779"""780Load an AudioLDM pipeline object from a `.ckpt`/`.safetensors` file and (ideally) a `.yaml` config file.781782Although many of the arguments can be automatically inferred, some of these rely on brittle checks against the783global step count, which will likely fail for models that have undergone further fine-tuning. Therefore, it is784recommended that you override the default values and/or supply an `original_config_file` wherever possible.785786:param checkpoint_path: Path to `.ckpt` file. :param original_config_file: Path to `.yaml` config file787corresponding to the original architecture.788If `None`, will be automatically instantiated based on default values.789:param image_size: The image size that the model was trained on. Use 512 for original AudioLDM checkpoints. :param790prediction_type: The prediction type that the model was trained on. Use `'epsilon'` for original791AudioLDM checkpoints.792:param num_in_channels: The number of input channels. If `None` number of input channels will be automatically793inferred.794:param scheduler_type: Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler",795"euler-ancestral", "dpm", "ddim"]`.796:param extract_ema: Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract797the EMA weights or not. Defaults to `False`. Pass `True` to extract the EMA weights. EMA weights usually798yield higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.799:param device: The device to use. Pass `None` to determine automatically. :param from_safetensors: If800`checkpoint_path` is in `safetensors` format, load checkpoint with safetensors801instead of PyTorch.802:return: An AudioLDMPipeline object representing the passed-in `.ckpt`/`.safetensors` file.803"""804805if not is_omegaconf_available():806raise ValueError(BACKENDS_MAPPING["omegaconf"][1])807808from omegaconf import OmegaConf809810if from_safetensors:811if not is_safetensors_available():812raise ValueError(BACKENDS_MAPPING["safetensors"][1])813814from safetensors import safe_open815816checkpoint = {}817with safe_open(checkpoint_path, framework="pt", device="cpu") as f:818for key in f.keys():819checkpoint[key] = f.get_tensor(key)820else:821if device is None:822device = "cuda" if torch.cuda.is_available() else "cpu"823checkpoint = torch.load(checkpoint_path, map_location=device)824else:825checkpoint = torch.load(checkpoint_path, map_location=device)826827if "state_dict" in checkpoint:828checkpoint = checkpoint["state_dict"]829830if original_config_file is None:831original_config = DEFAULT_CONFIG832original_config = OmegaConf.create(original_config)833else:834original_config = OmegaConf.load(original_config_file)835836if num_in_channels is not None:837original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels838839if (840"parameterization" in original_config["model"]["params"]841and original_config["model"]["params"]["parameterization"] == "v"842):843if prediction_type is None:844prediction_type = "v_prediction"845else:846if prediction_type is None:847prediction_type = "epsilon"848849if image_size is None:850image_size = 512851852num_train_timesteps = original_config.model.params.timesteps853beta_start = original_config.model.params.linear_start854beta_end = original_config.model.params.linear_end855856scheduler = DDIMScheduler(857beta_end=beta_end,858beta_schedule="scaled_linear",859beta_start=beta_start,860num_train_timesteps=num_train_timesteps,861steps_offset=1,862clip_sample=False,863set_alpha_to_one=False,864prediction_type=prediction_type,865)866# make sure scheduler works correctly with DDIM867scheduler.register_to_config(clip_sample=False)868869if scheduler_type == "pndm":870config = dict(scheduler.config)871config["skip_prk_steps"] = True872scheduler = PNDMScheduler.from_config(config)873elif scheduler_type == "lms":874scheduler = LMSDiscreteScheduler.from_config(scheduler.config)875elif scheduler_type == "heun":876scheduler = HeunDiscreteScheduler.from_config(scheduler.config)877elif scheduler_type == "euler":878scheduler = EulerDiscreteScheduler.from_config(scheduler.config)879elif scheduler_type == "euler-ancestral":880scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler.config)881elif scheduler_type == "dpm":882scheduler = DPMSolverMultistepScheduler.from_config(scheduler.config)883elif scheduler_type == "ddim":884scheduler = scheduler885else:886raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")887888# Convert the UNet2DModel889unet_config = create_unet_diffusers_config(original_config, image_size=image_size)890unet = UNet2DConditionModel(**unet_config)891892converted_unet_checkpoint = convert_ldm_unet_checkpoint(893checkpoint, unet_config, path=checkpoint_path, extract_ema=extract_ema894)895896unet.load_state_dict(converted_unet_checkpoint)897898# Convert the VAE model899vae_config = create_vae_diffusers_config(original_config, checkpoint=checkpoint, image_size=image_size)900converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)901902vae = AutoencoderKL(**vae_config)903vae.load_state_dict(converted_vae_checkpoint)904905# Convert the text model906# AudioLDM uses the same configuration and tokenizer as the original CLAP model907config = ClapTextConfig.from_pretrained("laion/clap-htsat-unfused")908tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")909910converted_text_model = convert_open_clap_checkpoint(checkpoint)911text_model = ClapTextModelWithProjection(config)912913missing_keys, unexpected_keys = text_model.load_state_dict(converted_text_model, strict=False)914# we expect not to have token_type_ids in our original state dict so let's ignore them915missing_keys = list(set(missing_keys) - set(CLAP_EXPECTED_MISSING_KEYS))916917if len(unexpected_keys) > 0:918raise ValueError(f"Unexpected keys when loading CLAP model: {unexpected_keys}")919920if len(missing_keys) > 0:921raise ValueError(f"Missing keys when loading CLAP model: {missing_keys}")922923# Convert the vocoder model924vocoder_config = create_transformers_vocoder_config(original_config)925vocoder_config = SpeechT5HifiGanConfig(**vocoder_config)926converted_vocoder_checkpoint = convert_hifigan_checkpoint(checkpoint, vocoder_config)927928vocoder = SpeechT5HifiGan(vocoder_config)929vocoder.load_state_dict(converted_vocoder_checkpoint)930931# Instantiate the diffusers pipeline932pipe = AudioLDMPipeline(933vae=vae,934text_encoder=text_model,935tokenizer=tokenizer,936unet=unet,937scheduler=scheduler,938vocoder=vocoder,939)940941return pipe942943944if __name__ == "__main__":945parser = argparse.ArgumentParser()946947parser.add_argument(948"--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."949)950parser.add_argument(951"--original_config_file",952default=None,953type=str,954help="The YAML config file corresponding to the original architecture.",955)956parser.add_argument(957"--num_in_channels",958default=None,959type=int,960help="The number of input channels. If `None` number of input channels will be automatically inferred.",961)962parser.add_argument(963"--scheduler_type",964default="ddim",965type=str,966help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']",967)968parser.add_argument(969"--image_size",970default=None,971type=int,972help=("The image size that the model was trained on."),973)974parser.add_argument(975"--prediction_type",976default=None,977type=str,978help=("The prediction type that the model was trained on."),979)980parser.add_argument(981"--extract_ema",982action="store_true",983help=(984"Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"985" or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"986" higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."987),988)989parser.add_argument(990"--from_safetensors",991action="store_true",992help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.",993)994parser.add_argument(995"--to_safetensors",996action="store_true",997help="Whether to store pipeline in safetensors format or not.",998)999parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")1000parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")1001args = parser.parse_args()10021003pipe = load_pipeline_from_original_audioldm_ckpt(1004checkpoint_path=args.checkpoint_path,1005original_config_file=args.original_config_file,1006image_size=args.image_size,1007prediction_type=args.prediction_type,1008extract_ema=args.extract_ema,1009scheduler_type=args.scheduler_type,1010num_in_channels=args.num_in_channels,1011from_safetensors=args.from_safetensors,1012device=args.device,1013)1014pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)101510161017