File size: 7,829 Bytes
f8803e6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "c15deb04-94a0-4073-a174-adcd22af10b8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Создана новая модель: <class 'diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL'>\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "e2063f203ab844489f3c02cb9c2ae70b",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"config.json: 0%| | 0.00/801 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d33d67a744ee43b3b9eaeba9228ba976",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"vae/diffusion_pytorch_model.safetensors: 0%| | 0.00/168M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"The config attributes {'block_out_channels': [128, 128, 256, 512, 512], 'force_upcast': False} were passed to AsymmetricAutoencoderKL, but are not expected and will be ignored. Please verify your config.json configuration file.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"--- Перенос весов ---\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 248/248 [00:00<00:00, 87271.36it/s]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"✅ Перенос завершён.\n",
"Статистика:\n",
" перенесено: 216\n",
" дублировано: 26\n",
" пропущено: 0\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\n"
]
}
],
"source": [
"from diffusers.models import AsymmetricAutoencoderKL, AutoencoderKL\n",
"import torch\n",
"from tqdm import tqdm\n",
"\n",
"# ---- Конфиг новой модели ----\n",
"config = {\n",
" \"_class_name\": \"AsymmetricAutoencoderKL\",\n",
" \"act_fn\": \"silu\",\n",
" \"in_channels\": 3,\n",
" \"out_channels\": 3,\n",
" \"scaling_factor\": 1.0,\n",
" \"norm_num_groups\": 32,\n",
" \"down_block_out_channels\": [128, 256, 512, 512],\n",
" \"down_block_types\": [\n",
" \"DownEncoderBlock2D\",\n",
" \"DownEncoderBlock2D\",\n",
" \"DownEncoderBlock2D\",\n",
" \"DownEncoderBlock2D\",\n",
" ],\n",
" \"latent_channels\": 16,\n",
" # Новый UpDecoderBlock добавлен в начало\n",
" \"up_block_out_channels\": [128, 128, 256, 512, 512],\n",
" \"up_block_types\": [\n",
" \"UpDecoderBlock2D\",\n",
" \"UpDecoderBlock2D\",\n",
" \"UpDecoderBlock2D\",\n",
" \"UpDecoderBlock2D\",\n",
" \"UpDecoderBlock2D\",\n",
" ],\n",
"}\n",
"\n",
"# ---- Создание пустой асимметричной модели ----\n",
"vae = AsymmetricAutoencoderKL(\n",
" act_fn=config[\"act_fn\"],\n",
" down_block_out_channels=config[\"down_block_out_channels\"],\n",
" down_block_types=config[\"down_block_types\"],\n",
" latent_channels=config[\"latent_channels\"],\n",
" up_block_out_channels=config[\"up_block_out_channels\"],\n",
" up_block_types=config[\"up_block_types\"],\n",
" in_channels=config[\"in_channels\"],\n",
" out_channels=config[\"out_channels\"],\n",
" scaling_factor=config[\"scaling_factor\"],\n",
" norm_num_groups=config[\"norm_num_groups\"],\n",
" layers_per_down_block=2,\n",
" layers_per_up_block=2,\n",
" sample_size=1024\n",
")\n",
"\n",
"vae.save_pretrained(\"asymmetric_vae_empty\")\n",
"print(\"✅ Создана новая модель:\", type(vae))\n",
"\n",
"# ---- Функция переноса весов старого VAE ----\n",
"def transfer_weights(old_path, new_path, save_path=\"asymmetric_vae\", device=\"cuda\", dtype=torch.float16):\n",
" old_vae = AutoencoderKL.from_pretrained(old_path, subfolder=\"vae\").to(device, dtype=dtype)\n",
" new_vae = AsymmetricAutoencoderKL.from_pretrained(new_path).to(device, dtype=dtype)\n",
"\n",
" old_sd = old_vae.state_dict()\n",
" new_sd = new_vae.state_dict()\n",
"\n",
" transferred_keys = set()\n",
" transfer_stats = {\"перенесено\": 0, \"дублировано\": 0, \"пропущено\": 0}\n",
"\n",
" print(\"\\n--- Перенос весов ---\")\n",
" for k, v in tqdm(old_sd.items()):\n",
" # Копирование энкодера и прочих совпадающих ключей\n",
" if (\"encoder\" in k) or (\"quant_conv\" in k) or (\"post_quant_conv\" in k):\n",
" if k in new_sd and new_sd[k].shape == v.shape:\n",
" new_sd[k] = v.clone()\n",
" transferred_keys.add(k)\n",
" transfer_stats[\"перенесено\"] += 1\n",
" continue\n",
"\n",
" # Копирование декодера (без сдвига)\n",
" if \"decoder.up_blocks\" in k:\n",
" if k in new_sd and new_sd[k].shape == v.shape:\n",
" new_sd[k] = v.clone()\n",
" transferred_keys.add(k)\n",
" transfer_stats[\"перенесено\"] += 1\n",
" continue\n",
"\n",
" # Дублирование весов старого первого 512→512 блока в новый блок 64→128 для апскейла\n",
" ref_prefix = \"decoder.up_blocks.1\"\n",
" new_prefix = \"decoder.up_blocks.0\"\n",
" for k, v in old_sd.items():\n",
" if k.startswith(ref_prefix) and new_prefix + k[len(ref_prefix):] in new_sd:\n",
" new_k = k.replace(ref_prefix, new_prefix)\n",
" if new_sd[new_k].shape == v.shape:\n",
" new_sd[new_k] = v.clone()\n",
" transferred_keys.add(new_k)\n",
" transfer_stats[\"дублировано\"] += 1\n",
"\n",
" # Загрузка и сохранение\n",
" new_vae.load_state_dict(new_sd, strict=False)\n",
" new_vae.save_pretrained(save_path)\n",
"\n",
" print(\"\\n✅ Перенос завершён.\")\n",
" print(\"Статистика:\")\n",
" for k, v in transfer_stats.items():\n",
" print(f\" {k}: {v}\")\n",
"\n",
"# ---- Запуск переноса ----\n",
"transfer_weights(\"AiArtLab/simplevae\", \"asymmetric_vae_empty\", save_path=\"vae3\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "59fcafb9-6d89-49b4-8362-b4891f591687",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|