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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from contextlib import nullcontext
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from safetensors.torch import load_file
|
| 7 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 8 |
+
|
| 9 |
+
from diffusers import (
|
| 10 |
+
AutoencoderOobleck,
|
| 11 |
+
CosineDPMSolverMultistepScheduler,
|
| 12 |
+
StableAudioDiTModel,
|
| 13 |
+
StableAudioPipeline,
|
| 14 |
+
StableAudioProjectionModel,
|
| 15 |
+
)
|
| 16 |
+
from diffusers.models.model_loading_utils import load_model_dict_into_meta
|
| 17 |
+
from diffusers.utils import is_accelerate_available
|
| 18 |
+
|
| 19 |
+
if is_accelerate_available():
|
| 20 |
+
from accelerate import init_empty_weights
|
| 21 |
+
|
| 22 |
+
# ==========================================
|
| 23 |
+
# HARDCODED PATHS FOR ENVIRONMENT
|
| 24 |
+
# ==========================================
|
| 25 |
+
CHECKPOINT_PATH = r"\Foundation_1.safetensors" # YOU MUST DOWNLOAD THIS
|
| 26 |
+
CONFIG_PATH = r"\model_config.json" # YOU MUST DOWNLOAD THIS
|
| 27 |
+
SAVE_DIRECTORY = r"\foundation_diffusers"
|
| 28 |
+
|
| 29 |
+
device = "cpu"
|
| 30 |
+
dtype = torch.float32
|
| 31 |
+
|
| 32 |
+
# ==========================================
|
| 33 |
+
|
| 34 |
+
def convert_stable_audio_state_dict_to_diffusers(state_dict, num_autoencoder_layers=5):
|
| 35 |
+
projection_model_state_dict = {
|
| 36 |
+
k.replace("conditioner.conditioners.", "").replace("embedder.embedding", "time_positional_embedding"): v
|
| 37 |
+
for (k, v) in state_dict.items()
|
| 38 |
+
if "conditioner.conditioners" in k
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
for key, value in list(projection_model_state_dict.items()):
|
| 42 |
+
new_key = key.replace("seconds_start", "start_number_conditioner").replace(
|
| 43 |
+
"seconds_total", "end_number_conditioner"
|
| 44 |
+
)
|
| 45 |
+
projection_model_state_dict[new_key] = projection_model_state_dict.pop(key)
|
| 46 |
+
|
| 47 |
+
model_state_dict = {k.replace("model.model.", ""): v for (k, v) in state_dict.items() if "model.model." in k}
|
| 48 |
+
for key, value in list(model_state_dict.items()):
|
| 49 |
+
new_key = (
|
| 50 |
+
key.replace("transformer.", "")
|
| 51 |
+
.replace("layers", "transformer_blocks")
|
| 52 |
+
.replace("self_attn", "attn1")
|
| 53 |
+
.replace("cross_attn", "attn2")
|
| 54 |
+
.replace("ff.ff", "ff.net")
|
| 55 |
+
)
|
| 56 |
+
new_key = (
|
| 57 |
+
new_key.replace("pre_norm", "norm1")
|
| 58 |
+
.replace("cross_attend_norm", "norm2")
|
| 59 |
+
.replace("ff_norm", "norm3")
|
| 60 |
+
.replace("to_out", "to_out.0")
|
| 61 |
+
)
|
| 62 |
+
new_key = new_key.replace("gamma", "weight").replace("beta", "bias")
|
| 63 |
+
|
| 64 |
+
new_key = (
|
| 65 |
+
new_key.replace("project", "proj")
|
| 66 |
+
.replace("to_timestep_embed", "timestep_proj")
|
| 67 |
+
.replace("timestep_features", "time_proj")
|
| 68 |
+
.replace("to_global_embed", "global_proj")
|
| 69 |
+
.replace("to_cond_embed", "cross_attention_proj")
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if new_key == "time_proj.weight":
|
| 73 |
+
model_state_dict[key] = model_state_dict[key].squeeze(1)
|
| 74 |
+
|
| 75 |
+
if "to_qkv" in new_key:
|
| 76 |
+
q, k, v = torch.chunk(model_state_dict.pop(key), 3, dim=0)
|
| 77 |
+
model_state_dict[new_key.replace("qkv", "q")] = q
|
| 78 |
+
model_state_dict[new_key.replace("qkv", "k")] = k
|
| 79 |
+
model_state_dict[new_key.replace("qkv", "v")] = v
|
| 80 |
+
elif "to_kv" in new_key:
|
| 81 |
+
k, v = torch.chunk(model_state_dict.pop(key), 2, dim=0)
|
| 82 |
+
model_state_dict[new_key.replace("kv", "k")] = k
|
| 83 |
+
model_state_dict[new_key.replace("kv", "v")] = v
|
| 84 |
+
else:
|
| 85 |
+
model_state_dict[new_key] = model_state_dict.pop(key)
|
| 86 |
+
|
| 87 |
+
autoencoder_state_dict = {
|
| 88 |
+
k.replace("pretransform.model.", "").replace("coder.layers.0", "coder.conv1"): v
|
| 89 |
+
for (k, v) in state_dict.items()
|
| 90 |
+
if "pretransform.model." in k
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
for key, _ in list(autoencoder_state_dict.items()):
|
| 94 |
+
new_key = key
|
| 95 |
+
if "coder.layers" in new_key:
|
| 96 |
+
idx = int(new_key.split("coder.layers.")[1].split(".")[0])
|
| 97 |
+
new_key = new_key.replace(f"coder.layers.{idx}", f"coder.block.{idx - 1}")
|
| 98 |
+
|
| 99 |
+
if "encoder" in new_key:
|
| 100 |
+
for i in range(3):
|
| 101 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.{i}", f"block.{idx - 1}.res_unit{i + 1}")
|
| 102 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.3", f"block.{idx - 1}.snake1")
|
| 103 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.4", f"block.{idx - 1}.conv1")
|
| 104 |
+
else:
|
| 105 |
+
for i in range(2, 5):
|
| 106 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.{i}", f"block.{idx - 1}.res_unit{i - 1}")
|
| 107 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.0", f"block.{idx - 1}.snake1")
|
| 108 |
+
new_key = new_key.replace(f"block.{idx - 1}.layers.1", f"block.{idx - 1}.conv_t1")
|
| 109 |
+
|
| 110 |
+
new_key = new_key.replace("layers.0.beta", "snake1.beta")
|
| 111 |
+
new_key = new_key.replace("layers.0.alpha", "snake1.alpha")
|
| 112 |
+
new_key = new_key.replace("layers.2.beta", "snake2.beta")
|
| 113 |
+
new_key = new_key.replace("layers.2.alpha", "snake2.alpha")
|
| 114 |
+
new_key = new_key.replace("layers.1.bias", "conv1.bias")
|
| 115 |
+
new_key = new_key.replace("layers.1.weight_", "conv1.weight_")
|
| 116 |
+
new_key = new_key.replace("layers.3.bias", "conv2.bias")
|
| 117 |
+
new_key = new_key.replace("layers.3.weight_", "conv2.weight_")
|
| 118 |
+
|
| 119 |
+
if idx == num_autoencoder_layers + 1:
|
| 120 |
+
new_key = new_key.replace(f"block.{idx - 1}", "snake1")
|
| 121 |
+
elif idx == num_autoencoder_layers + 2:
|
| 122 |
+
new_key = new_key.replace(f"block.{idx - 1}", "conv2")
|
| 123 |
+
|
| 124 |
+
value = autoencoder_state_dict.pop(key)
|
| 125 |
+
if "snake" in new_key:
|
| 126 |
+
value = value.unsqueeze(0).unsqueeze(-1)
|
| 127 |
+
if new_key in autoencoder_state_dict:
|
| 128 |
+
raise ValueError(f"{new_key} already in state dict.")
|
| 129 |
+
autoencoder_state_dict[new_key] = value
|
| 130 |
+
|
| 131 |
+
return model_state_dict, projection_model_state_dict, autoencoder_state_dict
|
| 132 |
+
|
| 133 |
+
print("Reading config...")
|
| 134 |
+
with open(CONFIG_PATH) as f_in:
|
| 135 |
+
config_dict = json.load(f_in)
|
| 136 |
+
|
| 137 |
+
conditioning_dict = {
|
| 138 |
+
conditioning["id"]: conditioning["config"] for conditioning in config_dict["model"]["conditioning"]["configs"]
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
t5_model_config = conditioning_dict["prompt"]
|
| 142 |
+
|
| 143 |
+
print("Downloading/Loading T5 text encoder...")
|
| 144 |
+
text_encoder = T5EncoderModel.from_pretrained(t5_model_config["t5_model_name"])
|
| 145 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 146 |
+
t5_model_config["t5_model_name"], truncation=True, model_max_length=t5_model_config["max_length"]
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
scheduler = CosineDPMSolverMultistepScheduler(
|
| 150 |
+
sigma_min=0.3,
|
| 151 |
+
sigma_max=500,
|
| 152 |
+
solver_order=2,
|
| 153 |
+
prediction_type="v_prediction",
|
| 154 |
+
sigma_data=1.0,
|
| 155 |
+
sigma_schedule="exponential",
|
| 156 |
+
)
|
| 157 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
| 158 |
+
|
| 159 |
+
print("Loading SafeTensors checkpoint...")
|
| 160 |
+
orig_state_dict = load_file(CHECKPOINT_PATH, device=device)
|
| 161 |
+
|
| 162 |
+
model_config = config_dict["model"]["diffusion"]["config"]
|
| 163 |
+
|
| 164 |
+
print("Converting weights (this might take a moment)...")
|
| 165 |
+
model_state_dict, projection_model_state_dict, autoencoder_state_dict = convert_stable_audio_state_dict_to_diffusers(
|
| 166 |
+
orig_state_dict
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
print("Building Models...")
|
| 170 |
+
with ctx():
|
| 171 |
+
projection_model = StableAudioProjectionModel(
|
| 172 |
+
text_encoder_dim=text_encoder.config.d_model,
|
| 173 |
+
conditioning_dim=config_dict["model"]["conditioning"]["cond_dim"],
|
| 174 |
+
min_value=conditioning_dict["seconds_start"]["min_val"],
|
| 175 |
+
max_value=conditioning_dict["seconds_start"]["max_val"],
|
| 176 |
+
)
|
| 177 |
+
if is_accelerate_available():
|
| 178 |
+
load_model_dict_into_meta(projection_model, projection_model_state_dict)
|
| 179 |
+
else:
|
| 180 |
+
projection_model.load_state_dict(projection_model_state_dict)
|
| 181 |
+
|
| 182 |
+
attention_head_dim = model_config["embed_dim"] // model_config["num_heads"]
|
| 183 |
+
with ctx():
|
| 184 |
+
model = StableAudioDiTModel(
|
| 185 |
+
sample_size=int(config_dict["sample_size"])
|
| 186 |
+
/ int(config_dict["model"]["pretransform"]["config"]["downsampling_ratio"]),
|
| 187 |
+
in_channels=model_config["io_channels"],
|
| 188 |
+
num_layers=model_config["depth"],
|
| 189 |
+
attention_head_dim=attention_head_dim,
|
| 190 |
+
num_key_value_attention_heads=model_config["cond_token_dim"] // attention_head_dim,
|
| 191 |
+
num_attention_heads=model_config["num_heads"],
|
| 192 |
+
out_channels=model_config["io_channels"],
|
| 193 |
+
cross_attention_dim=model_config["cond_token_dim"],
|
| 194 |
+
time_proj_dim=256,
|
| 195 |
+
global_states_input_dim=model_config["global_cond_dim"],
|
| 196 |
+
cross_attention_input_dim=model_config["cond_token_dim"],
|
| 197 |
+
)
|
| 198 |
+
if is_accelerate_available():
|
| 199 |
+
load_model_dict_into_meta(model, model_state_dict)
|
| 200 |
+
else:
|
| 201 |
+
model.load_state_dict(model_state_dict)
|
| 202 |
+
|
| 203 |
+
autoencoder_config = config_dict["model"]["pretransform"]["config"]
|
| 204 |
+
with ctx():
|
| 205 |
+
autoencoder = AutoencoderOobleck(
|
| 206 |
+
encoder_hidden_size=autoencoder_config["encoder"]["config"]["channels"],
|
| 207 |
+
downsampling_ratios=autoencoder_config["encoder"]["config"]["strides"],
|
| 208 |
+
decoder_channels=autoencoder_config["decoder"]["config"]["channels"],
|
| 209 |
+
decoder_input_channels=autoencoder_config["decoder"]["config"]["latent_dim"],
|
| 210 |
+
audio_channels=autoencoder_config["io_channels"],
|
| 211 |
+
channel_multiples=autoencoder_config["encoder"]["config"]["c_mults"],
|
| 212 |
+
sampling_rate=config_dict["sample_rate"],
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
if is_accelerate_available():
|
| 216 |
+
load_model_dict_into_meta(autoencoder, autoencoder_state_dict)
|
| 217 |
+
else:
|
| 218 |
+
autoencoder.load_state_dict(autoencoder_state_dict)
|
| 219 |
+
|
| 220 |
+
print("Saving final diffusers pipeline...")
|
| 221 |
+
os.makedirs(SAVE_DIRECTORY, exist_ok=True)
|
| 222 |
+
pipeline = StableAudioPipeline(
|
| 223 |
+
transformer=model,
|
| 224 |
+
tokenizer=tokenizer,
|
| 225 |
+
text_encoder=text_encoder,
|
| 226 |
+
scheduler=scheduler,
|
| 227 |
+
vae=autoencoder,
|
| 228 |
+
projection_model=projection_model,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
pipeline.to(dtype).save_pretrained(SAVE_DIRECTORY)
|
| 232 |
+
|
| 233 |
+
print(f"✅ DONE! Pipeline successfully saved to {SAVE_DIRECTORY}")
|