recoilme commited on
Commit
252b3d1
·
verified ·
1 Parent(s): 82fc634

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ .ipynb_checkpoints/1234567890-checkpoint.png filter=lfs diff=lfs merge=lfs -text
37
+ 123456789.jpg filter=lfs diff=lfs merge=lfs -text
38
+ 1234567890.png filter=lfs diff=lfs merge=lfs -text
.ipynb_checkpoints/1234567890-checkpoint.png ADDED

Git LFS Details

  • SHA256: 8dfe1c0f981015c2ade3cb27e1fe630e2eff32e7b7e5ff8605f85bbaad4f7f7f
  • Pointer size: 131 Bytes
  • Size of remote file: 585 kB
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AsymmetricAutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "asymmetric_vae_empty",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 192,
8
+ 384,
9
+ 768,
10
+ 768
11
+ ],
12
+ "down_block_out_channels": [
13
+ 128,
14
+ 256,
15
+ 512,
16
+ 512
17
+ ],
18
+ "down_block_types": [
19
+ "DownEncoderBlock2D",
20
+ "DownEncoderBlock2D",
21
+ "DownEncoderBlock2D",
22
+ "DownEncoderBlock2D"
23
+ ],
24
+ "force_upcast": false,
25
+ "in_channels": 3,
26
+ "latent_channels": 16,
27
+ "layers_per_down_block": 2,
28
+ "layers_per_up_block": 2,
29
+ "norm_num_groups": 32,
30
+ "out_channels": 3,
31
+ "sample_size": 1024,
32
+ "scaling_factor": 1.0,
33
+ "up_block_out_channels": [
34
+ 192,
35
+ 384,
36
+ 768,
37
+ 768
38
+ ],
39
+ "up_block_types": [
40
+ "UpDecoderBlock2D",
41
+ "UpDecoderBlock2D",
42
+ "UpDecoderBlock2D",
43
+ "UpDecoderBlock2D"
44
+ ]
45
+ }
.ipynb_checkpoints/transfer_simplevae3-checkpoint.ipynb ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 10,
6
+ "id": "c15deb04-94a0-4073-a174-adcd22af10b8",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "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",
14
+ "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"
15
+ ]
16
+ },
17
+ {
18
+ "name": "stdout",
19
+ "output_type": "stream",
20
+ "text": [
21
+ "✅ Создана новая модель: <class 'diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL'>\n",
22
+ "\n",
23
+ "--- Перенос весов ---\n",
24
+ "✅ Готово. Модель сохранена в vae9\n"
25
+ ]
26
+ }
27
+ ],
28
+ "source": [
29
+ "from diffusers.models import AsymmetricAutoencoderKL\n",
30
+ "import torch\n",
31
+ "from tqdm import tqdm\n",
32
+ "\n",
33
+ "# ---- Конфиг новой модели ----\n",
34
+ "config = {\n",
35
+ " \"_class_name\": \"AsymmetricAutoencoderKL\",\n",
36
+ " \"act_fn\": \"silu\",\n",
37
+ " \"in_channels\": 3,\n",
38
+ " \"out_channels\": 3,\n",
39
+ " \"scaling_factor\": 1.0,\n",
40
+ " \"norm_num_groups\": 32,\n",
41
+ " \"down_block_out_channels\": [128, 256, 512, 512],\n",
42
+ " \"down_block_types\": [\n",
43
+ " \"DownEncoderBlock2D\",\n",
44
+ " \"DownEncoderBlock2D\",\n",
45
+ " \"DownEncoderBlock2D\",\n",
46
+ " \"DownEncoderBlock2D\",\n",
47
+ " ],\n",
48
+ " \"latent_channels\": 16,\n",
49
+ " \"up_block_out_channels\": [128,128, 256, 512, 512],\n",
50
+ " \"up_block_types\": [\n",
51
+ " \"UpDecoderBlock2D\",\n",
52
+ " \"UpDecoderBlock2D\",\n",
53
+ " \"UpDecoderBlock2D\",\n",
54
+ " \"UpDecoderBlock2D\",\n",
55
+ " \"UpDecoderBlock2D\",\n",
56
+ " ],\n",
57
+ "}\n",
58
+ "\n",
59
+ "# ---- Создание пустой асимметричной модели ----\n",
60
+ "vae = AsymmetricAutoencoderKL(\n",
61
+ " act_fn=config[\"act_fn\"],\n",
62
+ " down_block_out_channels=config[\"down_block_out_channels\"],\n",
63
+ " down_block_types=config[\"down_block_types\"],\n",
64
+ " latent_channels=config[\"latent_channels\"],\n",
65
+ " up_block_out_channels=config[\"up_block_out_channels\"],\n",
66
+ " up_block_types=config[\"up_block_types\"],\n",
67
+ " in_channels=config[\"in_channels\"],\n",
68
+ " out_channels=config[\"out_channels\"],\n",
69
+ " scaling_factor=config[\"scaling_factor\"],\n",
70
+ " norm_num_groups=config[\"norm_num_groups\"],\n",
71
+ " layers_per_down_block=2,\n",
72
+ " layers_per_up_block=3,\n",
73
+ " sample_size=256\n",
74
+ ")\n",
75
+ "\n",
76
+ "vae.save_pretrained(\"asymmetric_vae_empty\")\n",
77
+ "print(\"✅ Создана новая модель:\", type(vae))\n",
78
+ "\n",
79
+ "def transfer_weights(old_path, new_path, save_path=\"vae_final\", device=\"cuda\", dtype=torch.float32):\n",
80
+ " old_vae = AsymmetricAutoencoderKL.from_pretrained(old_path).to(device, dtype=dtype)\n",
81
+ " new_vae = AsymmetricAutoencoderKL.from_pretrained(new_path).to(device, dtype=dtype)\n",
82
+ "\n",
83
+ " old_sd = old_vae.state_dict()\n",
84
+ " new_sd = new_vae.state_dict()\n",
85
+ "\n",
86
+ " print(\"\\n--- Перенос весов ---\")\n",
87
+ " \n",
88
+ " # 1. Переносим всё, что совпадает по именам и формам (Энкодер, конволоции и т.д.)\n",
89
+ " # Это покроет Encoder полностью, так как там down_blocks не менялись\n",
90
+ " for k, v in old_sd.items():\n",
91
+ " if k in new_sd and v.shape == new_sd[k].shape:\n",
92
+ " new_sd[k] = v.clone()\n",
93
+ "\n",
94
+ " # 2. Переносим блоки декодера (Up-blocks)\n",
95
+ " # Старый: [0, 1, 2, 3, 4] -> Новой: [0, 1, 2, 3]\n",
96
+ " # Нам нужно перенести глубокие слои (0, 1, 2), а последний 3-й взять из 4-го старого\n",
97
+ " \n",
98
+ " # Сопоставление индексов: старый блок -> новый блок\n",
99
+ " # Мы берем 0->0, 1->1, 2->2 и 4->3 (пропуская лишний блок 128->128)\n",
100
+ " mapping = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4} \n",
101
+ " \n",
102
+ " for old_idx, new_idx in mapping.items():\n",
103
+ " old_prefix = f\"decoder.up_blocks.{old_idx}.\"\n",
104
+ " new_prefix = f\"decoder.up_blocks.{new_idx}.\"\n",
105
+ " \n",
106
+ " for k, v in old_sd.items():\n",
107
+ " if k.startswith(old_prefix):\n",
108
+ " new_key = k.replace(old_prefix, new_prefix)\n",
109
+ " if new_key in new_sd and v.shape == new_sd[new_key].shape:\n",
110
+ " new_sd[new_key] = v.clone()\n",
111
+ " else:\n",
112
+ " print(f\"⚠️ Пропущен слой или не совпал размер: {new_key}\")\n",
113
+ "\n",
114
+ " # Загрузка\n",
115
+ " new_vae.load_state_dict(new_sd, strict=False)\n",
116
+ " new_vae.save_pretrained(save_path)\n",
117
+ " print(f\"✅ Готово. Модель сохранена в {save_path}\")\n",
118
+ "\n",
119
+ "# Запуск\n",
120
+ "transfer_weights(\"vae8\", \"asymmetric_vae_empty\", save_path=\"vae9\")\n",
121
+ "\n"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "59fcafb9-6d89-49b4-8362-b4891f591687",
128
+ "metadata": {},
129
+ "outputs": [],
130
+ "source": []
131
+ }
132
+ ],
133
+ "metadata": {
134
+ "kernelspec": {
135
+ "display_name": "Python 3 (ipykernel)",
136
+ "language": "python",
137
+ "name": "python3"
138
+ },
139
+ "language_info": {
140
+ "codemirror_mode": {
141
+ "name": "ipython",
142
+ "version": 3
143
+ },
144
+ "file_extension": ".py",
145
+ "mimetype": "text/x-python",
146
+ "name": "python",
147
+ "nbconvert_exporter": "python",
148
+ "pygments_lexer": "ipython3",
149
+ "version": "3.12.3"
150
+ }
151
+ },
152
+ "nbformat": 4,
153
+ "nbformat_minor": 5
154
+ }
.ipynb_checkpoints/vae_comp-checkpoint.ipynb ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "b3b23a40-8354-4287-bac2-32f9d084fff3",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_validators.py:202: UserWarning: The `local_dir_use_symlinks` argument is deprecated and ignored in `hf_hub_download`. Downloading to a local directory does not use symlinks anymore.\n",
14
+ " warnings.warn(\n"
15
+ ]
16
+ },
17
+ {
18
+ "name": "stdout",
19
+ "output_type": "stream",
20
+ "text": [
21
+ "sdxs_vae log-variance: 1.840\n"
22
+ ]
23
+ },
24
+ {
25
+ "name": "stderr",
26
+ "output_type": "stream",
27
+ "text": [
28
+ "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"
29
+ ]
30
+ },
31
+ {
32
+ "name": "stdout",
33
+ "output_type": "stream",
34
+ "text": [
35
+ "vae8 log-variance: 1.840\n"
36
+ ]
37
+ },
38
+ {
39
+ "name": "stderr",
40
+ "output_type": "stream",
41
+ "text": [
42
+ "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"
43
+ ]
44
+ },
45
+ {
46
+ "name": "stdout",
47
+ "output_type": "stream",
48
+ "text": [
49
+ "vae9 log-variance: 1.840\n",
50
+ "Готово\n"
51
+ ]
52
+ }
53
+ ],
54
+ "source": [
55
+ "import torch\n",
56
+ "from PIL import Image\n",
57
+ "from diffusers import AutoencoderKL,AsymmetricAutoencoderKL\n",
58
+ "from torchvision.transforms.functional import to_pil_image\n",
59
+ "import matplotlib.pyplot as plt\n",
60
+ "import os\n",
61
+ "from torchvision.transforms import ToTensor, Normalize, CenterCrop\n",
62
+ "\n",
63
+ "# путь к вашей картинке\n",
64
+ "IMG_PATH = \"1234567890.png\"\n",
65
+ "OUT_DIR = \"vaetest\"\n",
66
+ "device = \"cuda\"\n",
67
+ "dtype = torch.float32 # ← единый float32\n",
68
+ "os.makedirs(OUT_DIR, exist_ok=True)\n",
69
+ "\n",
70
+ "# список VAE\n",
71
+ "VAES = {\n",
72
+ " #\"sdxl\": \"madebyollin/sdxl-vae-fp16-fix\",\n",
73
+ " \"sdxs_vae\": \"AiArtLab/sdxs-1b\",\n",
74
+ " \"vae8\": \"/workspace/simplevae2x/vae8\",\n",
75
+ " \"vae9\": \"/workspace/simplevae2x/vae9\"\n",
76
+ "}\n",
77
+ "\n",
78
+ "def load_image(path):\n",
79
+ " img = Image.open(path).convert('RGB')\n",
80
+ " # обрезаем до кратности 8\n",
81
+ " w, h = img.size\n",
82
+ " img = CenterCrop((h // 8 * 8, w // 8 * 8))(img)\n",
83
+ " tensor = ToTensor()(img).unsqueeze(0) # [0,1]\n",
84
+ " tensor = Normalize(mean=[0.5]*3, std=[0.5]*3)(tensor) # [-1,1]\n",
85
+ " return img, tensor.to(device, dtype=dtype)\n",
86
+ "\n",
87
+ "# обратно в PIL\n",
88
+ "def tensor_to_img(t):\n",
89
+ " t = (t * 0.5 + 0.5).clamp(0, 1)\n",
90
+ " return to_pil_image(t[0])\n",
91
+ "\n",
92
+ "def logvariance(latents):\n",
93
+ " \"\"\"Возвращает лог-дисперсию по всем элементам.\"\"\"\n",
94
+ " return torch.log(latents.var() + 1e-8).item()\n",
95
+ "\n",
96
+ "def plot_latent_distribution(latents, title, save_path):\n",
97
+ " \"\"\"Гистограмма + QQ-plot.\"\"\"\n",
98
+ " lat = latents.detach().cpu().numpy().flatten()\n",
99
+ " plt.figure(figsize=(10, 4))\n",
100
+ "\n",
101
+ " # гистограмма\n",
102
+ " plt.subplot(1, 2, 1)\n",
103
+ " plt.hist(lat, bins=100, density=True, alpha=0.7, color='steelblue')\n",
104
+ " plt.title(f\"{title} histogram\")\n",
105
+ " plt.xlabel(\"latent value\")\n",
106
+ " plt.ylabel(\"density\")\n",
107
+ "\n",
108
+ " # QQ-plot\n",
109
+ " from scipy.stats import probplot\n",
110
+ " plt.subplot(1, 2, 2)\n",
111
+ " probplot(lat, dist=\"norm\", plot=plt)\n",
112
+ " plt.title(f\"{title} QQ-plot\")\n",
113
+ "\n",
114
+ " plt.tight_layout()\n",
115
+ " plt.savefig(save_path)\n",
116
+ " plt.close()\n",
117
+ "\n",
118
+ "for name, repo in VAES.items():\n",
119
+ " if name==\"sdxs_vae\":\n",
120
+ " vae = AsymmetricAutoencoderKL.from_pretrained(repo, subfolder=\"vae\", torch_dtype=dtype).to(device)\n",
121
+ " else:\n",
122
+ " vae = AsymmetricAutoencoderKL.from_pretrained(repo, torch_dtype=dtype).to(device)#, subfolder=\"vae\", variant=\"fp16\"\n",
123
+ "\n",
124
+ " cfg = vae.config\n",
125
+ " scale = getattr(cfg, \"scaling_factor\", 1.)\n",
126
+ " shift = getattr(cfg, \"shift_factor\", 0.0)\n",
127
+ " mean = getattr(cfg, \"latents_mean\", None)\n",
128
+ " std = getattr(cfg, \"latents_std\", None)\n",
129
+ "\n",
130
+ " C = 4 # 4 для SDXL\n",
131
+ " if mean is not None:\n",
132
+ " mean = torch.tensor(mean, device=device, dtype=dtype).view(1, C, 1, 1)\n",
133
+ " if std is not None:\n",
134
+ " std = torch.tensor(std, device=device, dtype=dtype).view(1, C, 1, 1)\n",
135
+ " if shift is not None:\n",
136
+ " shift = torch.tensor(shift, device=device, dtype=dtype)\n",
137
+ " else:\n",
138
+ " shift = 0.0 \n",
139
+ "\n",
140
+ " scale = torch.tensor(scale, device=device, dtype=dtype)\n",
141
+ "\n",
142
+ " img, x = load_image(IMG_PATH)\n",
143
+ " img.save(os.path.join(OUT_DIR, f\"original.png\"))\n",
144
+ "\n",
145
+ " with torch.no_grad():\n",
146
+ " # encode\n",
147
+ " latents = vae.encode(x).latent_dist.sample().to(dtype)\n",
148
+ " if mean is not None and std is not None:\n",
149
+ " latents = (latents - mean) / std\n",
150
+ " latents = latents * scale + shift\n",
151
+ "\n",
152
+ " lv = logvariance(latents)\n",
153
+ " print(f\"{name} log-variance: {lv:.3f}\")\n",
154
+ "\n",
155
+ " # график\n",
156
+ " plot_latent_distribution(latents, f\"{name}_latents\",\n",
157
+ " os.path.join(OUT_DIR, f\"dist_{name}.png\"))\n",
158
+ "\n",
159
+ " # decode\n",
160
+ " latents = (latents - shift) / scale\n",
161
+ " if mean is not None and std is not None:\n",
162
+ " latents = latents * std + mean\n",
163
+ " rec = vae.decode(latents).sample\n",
164
+ "\n",
165
+ " tensor_to_img(rec).save(os.path.join(OUT_DIR, f\"decoded_{name}.png\"))\n",
166
+ "\n",
167
+ "print(\"Готово\")"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "id": "200b72ab-1978-4d71-9aba-b1ef97cf0b27",
174
+ "metadata": {},
175
+ "outputs": [],
176
+ "source": []
177
+ }
178
+ ],
179
+ "metadata": {
180
+ "kernelspec": {
181
+ "display_name": "Python 3 (ipykernel)",
182
+ "language": "python",
183
+ "name": "python3"
184
+ },
185
+ "language_info": {
186
+ "codemirror_mode": {
187
+ "name": "ipython",
188
+ "version": 3
189
+ },
190
+ "file_extension": ".py",
191
+ "mimetype": "text/x-python",
192
+ "name": "python",
193
+ "nbconvert_exporter": "python",
194
+ "pygments_lexer": "ipython3",
195
+ "version": "3.12.3"
196
+ }
197
+ },
198
+ "nbformat": 4,
199
+ "nbformat_minor": 5
200
+ }
123456789.jpg ADDED

Git LFS Details

  • SHA256: 131522c2f1db361170fb7f8819138893ccec8c1be544509b03aee277c3118e31
  • Pointer size: 131 Bytes
  • Size of remote file: 215 kB
1234567890.png ADDED

Git LFS Details

  • SHA256: 8dfe1c0f981015c2ade3cb27e1fe630e2eff32e7b7e5ff8605f85bbaad4f7f7f
  • Pointer size: 131 Bytes
  • Size of remote file: 585 kB
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AsymmetricAutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "vae9",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 128,
9
+ 256,
10
+ 512,
11
+ 512
12
+ ],
13
+ "down_block_out_channels": [
14
+ 128,
15
+ 256,
16
+ 512,
17
+ 512
18
+ ],
19
+ "down_block_types": [
20
+ "DownEncoderBlock2D",
21
+ "DownEncoderBlock2D",
22
+ "DownEncoderBlock2D",
23
+ "DownEncoderBlock2D"
24
+ ],
25
+ "force_upcast": false,
26
+ "in_channels": 3,
27
+ "latent_channels": 16,
28
+ "layers_per_down_block": 2,
29
+ "layers_per_up_block": 3,
30
+ "norm_num_groups": 32,
31
+ "out_channels": 3,
32
+ "sample_size": 256,
33
+ "scaling_factor": 1.0,
34
+ "up_block_out_channels": [
35
+ 128,
36
+ 128,
37
+ 256,
38
+ 512,
39
+ 512
40
+ ],
41
+ "up_block_types": [
42
+ "UpDecoderBlock2D",
43
+ "UpDecoderBlock2D",
44
+ "UpDecoderBlock2D",
45
+ "UpDecoderBlock2D",
46
+ "UpDecoderBlock2D"
47
+ ]
48
+ }
diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc1c725e6e73d6a1476672544d6e737f07c3882dd5610a8b69084da02c3eae46
3
+ size 427466716
train_vae_fdl.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import math
4
+ import re
5
+ import torch
6
+ import numpy as np
7
+ import random
8
+ import gc
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+
12
+ import torchvision.transforms as transforms
13
+ import torch.nn.functional as F
14
+ from torch.utils.data import DataLoader, Dataset
15
+ from torch.optim.lr_scheduler import LambdaLR
16
+ from diffusers import AutoencoderKL, AsymmetricAutoencoderKL
17
+ # QWEN: импорт класса
18
+ from diffusers import AutoencoderKLQwenImage
19
+ from diffusers import AutoencoderKLWan
20
+
21
+ from accelerate import Accelerator
22
+ from PIL import Image, UnidentifiedImageError
23
+ from tqdm import tqdm
24
+ import bitsandbytes as bnb
25
+ import wandb
26
+ import lpips # pip install lpips
27
+ from FDL_pytorch import FDL_loss # pip install fdl-pytorch
28
+ from collections import deque
29
+
30
+ # --------------------------- Параметры ---------------------------
31
+ ds_path = "/workspace/d23"
32
+ project = "vae9"
33
+ batch_size = 1
34
+ base_learning_rate = 6e-6
35
+ min_learning_rate = 7e-7
36
+ num_epochs = 10
37
+ sample_interval_share = 10
38
+ use_wandb = True
39
+ save_model = True
40
+ use_decay = True
41
+ optimizer_type = "adam8bit"
42
+ dtype = torch.float32
43
+
44
+ model_resolution = 288 #288
45
+ high_resolution = 576 #576
46
+ limit = 0
47
+ save_barrier = 1.3
48
+ warmup_percent = 0.005
49
+ percentile_clipping = 99
50
+ beta2 = 0.997
51
+ eps = 1e-8
52
+ clip_grad_norm = 1.0
53
+ mixed_precision = "no"
54
+ gradient_accumulation_steps = 2
55
+ generated_folder = "samples"
56
+ save_as = "vae9"
57
+ num_workers = 0
58
+ device = None
59
+ torch.backends.cuda.matmul.allow_tf32 = True
60
+ torch.backends.cudnn.allow_tf32 = True
61
+ # Включение Flash Attention 2/SDPA #MAX_JOBS=4 pip install flash-attn --no-build-isolation
62
+ torch.backends.cuda.enable_flash_sdp(True)
63
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
64
+ torch.backends.cuda.enable_math_sdp(False)
65
+
66
+ # --- Режимы обучения ---
67
+ # QWEN: учим только декодер
68
+ train_decoder_only = True
69
+ train_up_only = False
70
+ full_training = False # если True — учим весь VAE и добавляем KL (ниже)
71
+ kl_ratio = 0.00
72
+
73
+ # Доли лоссов
74
+ loss_ratios = {
75
+ "lpips": 0.70,#0.50,
76
+ "fdl" : 0.10,#0.25,
77
+ "edge": 0.05,
78
+ "mse": 0.10,
79
+ "mae": 0.05,
80
+ "kl": 0.00, # активируем при full_training=True
81
+ }
82
+ median_coeff_steps = 250
83
+
84
+ resize_long_side = 1280 # ресайз длинной стороны исходных картинок
85
+
86
+ # QWEN: конфиг загрузки модели
87
+ vae_kind = "kl" # "qwen" или "kl" (обычный)
88
+
89
+ Path(generated_folder).mkdir(parents=True, exist_ok=True)
90
+
91
+ accelerator = Accelerator(
92
+ mixed_precision=mixed_precision,
93
+ gradient_accumulation_steps=gradient_accumulation_steps
94
+ )
95
+ device = accelerator.device
96
+
97
+ # reproducibility
98
+ seed = int(datetime.now().strftime("%Y%m%d")) + 2
99
+ torch.manual_seed(seed); np.random.seed(seed); random.seed(seed)
100
+ torch.backends.cudnn.benchmark = False
101
+
102
+ # --------------------------- WandB ---------------------------
103
+ if use_wandb and accelerator.is_main_process:
104
+ wandb.init(project=project, config={
105
+ "batch_size": batch_size,
106
+ "base_learning_rate": base_learning_rate,
107
+ "num_epochs": num_epochs,
108
+ "optimizer_type": optimizer_type,
109
+ "model_resolution": model_resolution,
110
+ "high_resolution": high_resolution,
111
+ "gradient_accumulation_steps": gradient_accumulation_steps,
112
+ "train_decoder_only": train_decoder_only,
113
+ "full_training": full_training,
114
+ "kl_ratio": kl_ratio,
115
+ "vae_kind": vae_kind,
116
+ })
117
+
118
+ # --------------------------- VAE ---------------------------
119
+ def get_core_model(model):
120
+ m = model
121
+ # если модель уже обёрнута torch.compile
122
+ if hasattr(m, "_orig_mod"):
123
+ m = m._orig_mod
124
+ return m
125
+
126
+ def is_video_vae(model) -> bool:
127
+ # WAN/Qwen — это видео-VAEs
128
+ if vae_kind in ("wan", "qwen"):
129
+ return True
130
+ # fallback по структуре (если понадобится)
131
+ try:
132
+ core = get_core_model(model)
133
+ enc = getattr(core, "encoder", None)
134
+ conv_in = getattr(enc, "conv_in", None)
135
+ w = getattr(conv_in, "weight", None)
136
+ if isinstance(w, torch.nn.Parameter):
137
+ return w.ndim == 5
138
+ except Exception:
139
+ pass
140
+ return False
141
+
142
+ # загрузка
143
+ if vae_kind == "qwen":
144
+ vae = AutoencoderKLQwenImage.from_pretrained("Qwen/Qwen-Image", subfolder="vae")
145
+ else:
146
+ if vae_kind == "wan":
147
+ vae = AutoencoderKLWan.from_pretrained(project)
148
+ else:
149
+ # старое поведение (пример)
150
+ if model_resolution==high_resolution:
151
+ vae = AutoencoderKL.from_pretrained(project)
152
+ else:
153
+ vae = AsymmetricAutoencoderKL.from_pretrained(project)
154
+
155
+ vae = vae.to(dtype)
156
+
157
+ # torch.compile (опционально)
158
+ if hasattr(torch, "compile"):
159
+ try:
160
+ vae = torch.compile(vae)
161
+ except Exception as e:
162
+ print(f"[WARN] torch.compile failed: {e}")
163
+
164
+ # --------------------------- Freeze/Unfreeze ---------------------------
165
+ core = get_core_model(vae)
166
+
167
+ for p in core.parameters():
168
+ p.requires_grad = False
169
+
170
+ unfrozen_param_names = []
171
+
172
+ if full_training and not train_decoder_only:
173
+ for name, p in core.named_parameters():
174
+ p.requires_grad = True
175
+ unfrozen_param_names.append(name)
176
+ loss_ratios["kl"] = float(kl_ratio)
177
+ trainable_module = core
178
+ else:
179
+ # учим только 0-й блок декодера + post_quant_conv
180
+ if hasattr(core, "decoder"):
181
+ if train_up_only:#hasattr(core.decoder, "up_blocks") and len(core.decoder.up_blocks) > 0:
182
+ # --- только 0-й up_block ---
183
+ for name, p in core.decoder.up_blocks[0].named_parameters():
184
+ p.requires_grad = True
185
+ unfrozen_param_names.append(f"{name}")
186
+ else:
187
+ print("Decoder — fallback to full decoder")
188
+ for name, p in core.decoder.named_parameters():
189
+ p.requires_grad = True
190
+ unfrozen_param_names.append(f"decoder.{name}")
191
+ if hasattr(core, "post_quant_conv"):
192
+ for name, p in core.post_quant_conv.named_parameters():
193
+ p.requires_grad = True
194
+ unfrozen_param_names.append(f"post_quant_conv.{name}")
195
+ trainable_module = core.decoder if hasattr(core, "decoder") else core
196
+
197
+
198
+ print(f"[INFO] Разморожено параметров: {len(unfrozen_param_names)}. Первые 200 имён:")
199
+ for nm in unfrozen_param_names[:200]:
200
+ print(" ", nm)
201
+
202
+ # --------------------------- Датасет ---------------------------
203
+ class PngFolderDataset(Dataset):
204
+ def __init__(self, root_dir, min_exts=('.png',), resolution=1024, limit=0):
205
+ self.root_dir = root_dir
206
+ self.resolution = resolution
207
+ self.paths = []
208
+ for root, _, files in os.walk(root_dir):
209
+ for fname in files:
210
+ if fname.lower().endswith(tuple(ext.lower() for ext in min_exts)):
211
+ self.paths.append(os.path.join(root, fname))
212
+ if limit:
213
+ self.paths = self.paths[:limit]
214
+ valid = []
215
+ for p in self.paths:
216
+ try:
217
+ with Image.open(p) as im:
218
+ im.verify()
219
+ valid.append(p)
220
+ except (OSError, UnidentifiedImageError):
221
+ continue
222
+ self.paths = valid
223
+ if len(self.paths) == 0:
224
+ raise RuntimeError(f"No valid PNG images found under {root_dir}")
225
+ random.shuffle(self.paths)
226
+
227
+ def __len__(self):
228
+ return len(self.paths)
229
+
230
+ def __getitem__(self, idx):
231
+ p = self.paths[idx % len(self.paths)]
232
+ with Image.open(p) as img:
233
+ img = img.convert("RGB")
234
+ if not resize_long_side or resize_long_side <= 0:
235
+ return img
236
+ w, h = img.size
237
+ long = max(w, h)
238
+ if long <= resize_long_side:
239
+ return img
240
+ scale = resize_long_side / float(long)
241
+ new_w = int(round(w * scale))
242
+ new_h = int(round(h * scale))
243
+ return img.resize((new_w, new_h), Image.BICUBIC)
244
+
245
+ def random_crop(img, sz):
246
+ w, h = img.size
247
+ if w < sz or h < sz:
248
+ img = img.resize((max(sz, w), max(sz, h)), Image.BICUBIC)
249
+ x = random.randint(0, max(1, img.width - sz))
250
+ y = random.randint(0, max(1, img.height - sz))
251
+ return img.crop((x, y, x + sz, y + sz))
252
+
253
+ tfm = transforms.Compose([
254
+ transforms.ToTensor(),
255
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
256
+ ])
257
+
258
+ dataset = PngFolderDataset(ds_path, min_exts=('.png',), resolution=high_resolution, limit=limit)
259
+ print("len(dataset)",len(dataset))
260
+ if len(dataset) < batch_size:
261
+ raise RuntimeError(f"Not enough valid images ({len(dataset)}) to form a batch of size {batch_size}")
262
+
263
+ def collate_fn(batch):
264
+ imgs = []
265
+ for img in batch:
266
+ img = random_crop(img, high_resolution)
267
+ imgs.append(tfm(img))
268
+ return torch.stack(imgs)
269
+
270
+ dataloader = DataLoader(
271
+ dataset,
272
+ batch_size=batch_size,
273
+ shuffle=True,
274
+ collate_fn=collate_fn,
275
+ num_workers=num_workers,
276
+ pin_memory=True,
277
+ drop_last=True
278
+ )
279
+
280
+ # --------------------------- Оптимизатор ---------------------------
281
+ def get_param_groups(module, weight_decay=0.001):
282
+ no_decay = ["bias", "LayerNorm.weight", "layer_norm.weight", "ln_1.weight", "ln_f.weight"]
283
+ decay_params, no_decay_params = [], []
284
+ for n, p in vae.named_parameters(): # глобально по vae, с фильтром requires_grad
285
+ if not p.requires_grad:
286
+ continue
287
+ if any(nd in n for nd in no_decay):
288
+ no_decay_params.append(p)
289
+ else:
290
+ decay_params.append(p)
291
+ return [
292
+ {"params": decay_params, "weight_decay": weight_decay},
293
+ {"params": no_decay_params, "weight_decay": 0.0},
294
+ ]
295
+
296
+ def get_param_groups(module, weight_decay=0.001):
297
+ no_decay_tokens = ("bias", "norm", "rms", "layernorm")
298
+ decay_params, no_decay_params = [], []
299
+ for n, p in module.named_parameters():
300
+ if not p.requires_grad:
301
+ continue
302
+ n_l = n.lower()
303
+ if any(t in n_l for t in no_decay_tokens):
304
+ no_decay_params.append(p)
305
+ else:
306
+ decay_params.append(p)
307
+ return [
308
+ {"params": decay_params, "weight_decay": weight_decay},
309
+ {"params": no_decay_params, "weight_decay": 0.0},
310
+ ]
311
+
312
+ def create_optimizer(name, param_groups):
313
+ if name == "adam8bit":
314
+ return bnb.optim.AdamW8bit(param_groups, lr=base_learning_rate, betas=(0.9, beta2), eps=eps)
315
+ raise ValueError(name)
316
+
317
+ param_groups = get_param_groups(get_core_model(vae), weight_decay=0.001)
318
+ optimizer = create_optimizer(optimizer_type, param_groups)
319
+
320
+ # --------------------------- LR schedule ---------------------------
321
+ batches_per_epoch = len(dataloader)
322
+ steps_per_epoch = int(math.ceil(batches_per_epoch / float(gradient_accumulation_steps)))
323
+ total_steps = steps_per_epoch * num_epochs
324
+
325
+ def lr_lambda(step):
326
+ if not use_decay:
327
+ return 1.0
328
+ x = float(step) / float(max(1, total_steps))
329
+ warmup = float(warmup_percent)
330
+ min_ratio = float(min_learning_rate) / float(base_learning_rate)
331
+ if x < warmup:
332
+ return min_ratio + (1.0 - min_ratio) * (x / warmup)
333
+ decay_ratio = (x - warmup) / (1.0 - warmup)
334
+ return min_ratio + 0.5 * (1.0 - min_ratio) * (1.0 + math.cos(math.pi * decay_ratio))
335
+
336
+ scheduler = LambdaLR(optimizer, lr_lambda)
337
+
338
+ # Подготовка
339
+ dataloader, vae, optimizer, scheduler = accelerator.prepare(dataloader, vae, optimizer, scheduler)
340
+ trainable_params = [p for p in vae.parameters() if p.requires_grad]
341
+
342
+ # fdl
343
+ fdl_loss = FDL_loss()
344
+ fdl_loss = fdl_loss.to(accelerator.device)
345
+
346
+ # --------------------------- LPIPS и вспомогательные ---------------------------
347
+ _lpips_net = None
348
+ def _get_lpips():
349
+ global _lpips_net
350
+ if _lpips_net is None:
351
+ _lpips_net = lpips.LPIPS(net='vgg', verbose=False).eval().to(accelerator.device).eval()
352
+ return _lpips_net
353
+
354
+ _sobel_kx = torch.tensor([[[[-1,0,1],[-2,0,2],[-1,0,1]]]], dtype=torch.float32)
355
+ _sobel_ky = torch.tensor([[[[-1,-2,-1],[0,0,0],[1,2,1]]]], dtype=torch.float32)
356
+ def sobel_edges(x: torch.Tensor) -> torch.Tensor:
357
+ C = x.shape[1]
358
+ kx = _sobel_kx.to(x.device, x.dtype).repeat(C, 1, 1, 1)
359
+ ky = _sobel_ky.to(x.device, x.dtype).repeat(C, 1, 1, 1)
360
+ gx = F.conv2d(x, kx, padding=1, groups=C)
361
+ gy = F.conv2d(x, ky, padding=1, groups=C)
362
+ return torch.sqrt(gx * gx + gy * gy + 1e-12)
363
+
364
+ class MedianLossNormalizer:
365
+ def __init__(self, desired_ratios: dict, window_steps: int):
366
+ s = sum(desired_ratios.values())
367
+ self.ratios = {k: (v / s) if s > 0 else 0.0 for k, v in desired_ratios.items()}
368
+ self.buffers = {k: deque(maxlen=window_steps) for k in self.ratios.keys()}
369
+ self.window = window_steps
370
+
371
+ def update_and_total(self, abs_losses: dict):
372
+ for k, v in abs_losses.items():
373
+ if k in self.buffers:
374
+ self.buffers[k].append(float(v.detach().abs().cpu()))
375
+ meds = {k: (np.median(self.buffers[k]) if len(self.buffers[k]) > 0 else 1.0) for k in self.buffers}
376
+ coeffs = {k: (self.ratios[k] / max(meds[k], 1e-12)) for k in self.ratios}
377
+ total = sum(coeffs[k] * abs_losses[k] for k in abs_losses if k in coeffs)
378
+ return total, coeffs, meds
379
+
380
+ if full_training and not train_decoder_only:
381
+ loss_ratios["kl"] = float(kl_ratio)
382
+ normalizer = MedianLossNormalizer(loss_ratios, median_coeff_steps)
383
+
384
+ # --------------------------- Сэмплы ---------------------------
385
+ @torch.no_grad()
386
+ def get_fixed_samples(n=3):
387
+ idx = random.sample(range(len(dataset)), min(n, len(dataset)))
388
+ pil_imgs = [dataset[i] for i in idx]
389
+ tensors = []
390
+ for img in pil_imgs:
391
+ img = random_crop(img, high_resolution)
392
+ tensors.append(tfm(img))
393
+ return torch.stack(tensors).to(accelerator.device, dtype)
394
+
395
+ fixed_samples = get_fixed_samples()
396
+
397
+ @torch.no_grad()
398
+ def _to_pil_uint8(img_tensor: torch.Tensor) -> Image.Image:
399
+ arr = ((img_tensor.float().clamp(-1, 1) + 1.0) * 127.5).clamp(0, 255).byte().cpu().numpy().transpose(1, 2, 0)
400
+ return Image.fromarray(arr)
401
+
402
+
403
+ @torch.no_grad()
404
+ def generate_and_save_samples(step=None):
405
+ try:
406
+ temp_vae = accelerator.unwrap_model(vae).eval()
407
+ lpips_net = _get_lpips()
408
+ with torch.no_grad():
409
+ orig_high = fixed_samples
410
+ orig_low = F.interpolate(
411
+ orig_high,
412
+ size=(model_resolution, model_resolution),
413
+ mode="bilinear",
414
+ align_corners=False
415
+ )
416
+ model_dtype = next(temp_vae.parameters()).dtype
417
+ orig_low = orig_low.to(dtype=model_dtype)
418
+
419
+ # Encode/decode с учётом видео-режима
420
+ if is_video_vae(temp_vae):
421
+ x_in = orig_low.unsqueeze(2) # [B,3,1,H,W]
422
+ enc = temp_vae.encode(x_in)
423
+ latents_mean = enc.latent_dist.mean
424
+ dec = temp_vae.decode(latents_mean).sample # [B,3,1,H,W]
425
+ rec = dec.squeeze(2) # [B,3,H,W]
426
+ else:
427
+ enc = temp_vae.encode(orig_low)
428
+ latents_mean = enc.latent_dist.mean
429
+ rec = temp_vae.decode(latents_mean).sample
430
+
431
+ # Подгон размеров, если надо
432
+ #if rec.shape[-2:] != orig_high.shape[-2:]:
433
+ # rec = F.interpolate(rec, size=orig_high.shape[-2:], mode="bilinear", align_corners=False)
434
+
435
+ # Сохраняем все real/decoded
436
+ for i in range(rec.shape[0]):
437
+ real_img = _to_pil_uint8(orig_high[i])
438
+ dec_img = _to_pil_uint8(rec[i])
439
+ real_img.save(f"{generated_folder}/sample_real_{i}.png")
440
+ dec_img.save(f"{generated_folder}/sample_decoded_{i}.png")
441
+
442
+ # LPIPS
443
+ lpips_scores = []
444
+ for i in range(rec.shape[0]):
445
+ orig_full = orig_high[i:i+1].to(torch.float32)
446
+ rec_full = rec[i:i+1].to(torch.float32)
447
+ #if rec_full.shape[-2:] != orig_full.shape[-2:]:
448
+ # rec_full = F.interpolate(rec_full, size=orig_full.shape[-2:], mode="bilinear", align_corners=False)
449
+ lpips_val = lpips_net(orig_full, rec_full).item()
450
+ lpips_scores.append(lpips_val)
451
+ avg_lpips = float(np.mean(lpips_scores))
452
+
453
+ # W&B логирование
454
+ if use_wandb and accelerator.is_main_process:
455
+ log_data = {"lpips_mean": avg_lpips}
456
+ for i in range(rec.shape[0]):
457
+ log_data[f"sample/real_{i}"] = wandb.Image(f"{generated_folder}/sample_real_{i}.png", caption=f"real_{i}")
458
+ log_data[f"sample/decoded_{i}"] = wandb.Image(f"{generated_folder}/sample_decoded_{i}.png", caption=f"decoded_{i}")
459
+ wandb.log(log_data, step=step)
460
+
461
+ finally:
462
+ gc.collect()
463
+ torch.cuda.empty_cache()
464
+
465
+
466
+ if accelerator.is_main_process and save_model:
467
+ print("Генерация сэмплов до старта обучения...")
468
+ generate_and_save_samples(0)
469
+
470
+ accelerator.wait_for_everyone()
471
+
472
+ # --------------------------- Тренировка ---------------------------
473
+ progress = tqdm(total=total_steps, disable=not accelerator.is_local_main_process)
474
+ global_step = 0
475
+ min_loss = float("inf")
476
+ sample_interval = max(1, total_steps // max(1, sample_interval_share * num_epochs))
477
+
478
+ for epoch in range(num_epochs):
479
+ vae.train()
480
+ batch_losses, batch_grads = [], []
481
+ track_losses = {k: [] for k in loss_ratios.keys()}
482
+
483
+ for imgs in dataloader:
484
+ with accelerator.accumulate(vae):
485
+ imgs = imgs.to(accelerator.device)
486
+
487
+ if high_resolution != model_resolution:
488
+ imgs_low = F.interpolate(imgs, size=(model_resolution, model_resolution), mode="bilinear", align_corners=False)
489
+ else:
490
+ imgs_low = imgs
491
+
492
+ model_dtype = next(vae.parameters()).dtype
493
+ imgs_low_model = imgs_low.to(dtype=model_dtype) if imgs_low.dtype != model_dtype else imgs_low
494
+
495
+ # QWEN: encode/decode с T=1
496
+ if is_video_vae(vae):
497
+ x_in = imgs_low_model.unsqueeze(2) # [B,3,1,H,W]
498
+ enc = vae.encode(x_in)
499
+ latents = enc.latent_dist.mean if train_decoder_only else enc.latent_dist.sample()
500
+ dec = vae.decode(latents).sample # [B,3,1,H,W]
501
+ rec = dec.squeeze(2) # [B,3,H,W]
502
+ else:
503
+ enc = vae.encode(imgs_low_model)
504
+ latents = enc.latent_dist.mean if train_decoder_only else enc.latent_dist.sample()
505
+ rec = vae.decode(latents).sample
506
+
507
+ #if rec.shape[-2:] != imgs.shape[-2:]:
508
+ # rec = F.interpolate(rec, size=imgs.shape[-2:], mode="bilinear", align_corners=False)
509
+
510
+ rec_f32 = rec.to(torch.float32)
511
+ imgs_f32 = imgs.to(torch.float32)
512
+
513
+ abs_losses = {
514
+ "mae": F.l1_loss(rec_f32, imgs_f32),
515
+ "mse": F.mse_loss(rec_f32, imgs_f32),
516
+ "lpips": _get_lpips()(rec_f32, imgs_f32).mean(),
517
+ "fdl": fdl_loss(rec_f32, imgs_f32),
518
+ "edge": F.l1_loss(sobel_edges(rec_f32), sobel_edges(imgs_f32)),
519
+ }
520
+
521
+ if full_training and not train_decoder_only:
522
+ mean = enc.latent_dist.mean
523
+ logvar = enc.latent_dist.logvar
524
+ kl = -0.5 * torch.mean(1 + logvar - mean.pow(2) - logvar.exp())
525
+ abs_losses["kl"] = kl
526
+ else:
527
+ abs_losses["kl"] = torch.tensor(0.0, device=accelerator.device, dtype=torch.float32)
528
+
529
+ total_loss, coeffs, meds = normalizer.update_and_total(abs_losses)
530
+
531
+ if torch.isnan(total_loss) or torch.isinf(total_loss):
532
+ raise RuntimeError("NaN/Inf loss")
533
+
534
+ accelerator.backward(total_loss)
535
+
536
+ grad_norm = torch.tensor(0.0, device=accelerator.device)
537
+ if accelerator.sync_gradients:
538
+ grad_norm = accelerator.clip_grad_norm_(trainable_params, clip_grad_norm)
539
+ optimizer.step()
540
+ scheduler.step()
541
+ optimizer.zero_grad(set_to_none=True)
542
+ global_step += 1
543
+ progress.update(1)
544
+
545
+ if accelerator.is_main_process:
546
+ try:
547
+ current_lr = optimizer.param_groups[0]["lr"]
548
+ except Exception:
549
+ current_lr = scheduler.get_last_lr()[0]
550
+
551
+ batch_losses.append(total_loss.detach().item())
552
+ batch_grads.append(float(grad_norm.detach().cpu().item()) if isinstance(grad_norm, torch.Tensor) else float(grad_norm))
553
+ for k, v in abs_losses.items():
554
+ track_losses[k].append(float(v.detach().item()))
555
+
556
+ if use_wandb and accelerator.sync_gradients:
557
+ log_dict = {
558
+ "total_loss": float(total_loss.detach().item()),
559
+ "learning_rate": current_lr,
560
+ "epoch": epoch,
561
+ "grad_norm": batch_grads[-1],
562
+ }
563
+ for k, v in abs_losses.items():
564
+ log_dict[f"loss_{k}"] = float(v.detach().item())
565
+ for k in coeffs:
566
+ log_dict[f"coeff_{k}"] = float(coeffs[k])
567
+ log_dict[f"median_{k}"] = float(meds[k])
568
+ wandb.log(log_dict, step=global_step)
569
+
570
+ if global_step > 0 and global_step % sample_interval == 0:
571
+ if accelerator.is_main_process:
572
+ generate_and_save_samples(global_step)
573
+ accelerator.wait_for_everyone()
574
+
575
+ n_micro = sample_interval * gradient_accumulation_steps
576
+ avg_loss = float(np.mean(batch_losses[-n_micro:])) if len(batch_losses) >= n_micro else float(np.mean(batch_losses)) if batch_losses else float("nan")
577
+ avg_grad = float(np.mean(batch_grads[-n_micro:])) if len(batch_grads) >= 1 else float(np.mean(batch_grads)) if batch_grads else 0.0
578
+
579
+ if accelerator.is_main_process:
580
+ print(f"Epoch {epoch} step {global_step} loss: {avg_loss:.6f}, grad_norm: {avg_grad:.6f}, lr: {current_lr:.9f}")
581
+ if save_model and avg_loss < min_loss * save_barrier:
582
+ min_loss = avg_loss
583
+ accelerator.unwrap_model(vae).save_pretrained(save_as)
584
+ if use_wandb:
585
+ wandb.log({"interm_loss": avg_loss, "interm_grad": avg_grad}, step=global_step)
586
+
587
+ if accelerator.is_main_process:
588
+ epoch_avg = float(np.mean(batch_losses)) if batch_losses else float("nan")
589
+ print(f"Epoch {epoch} done, avg loss {epoch_avg:.6f}")
590
+ if use_wandb:
591
+ wandb.log({"epoch_loss": epoch_avg, "epoch": epoch + 1}, step=global_step)
592
+
593
+ # --------------------------- Финальное сохранение ---------------------------
594
+ if accelerator.is_main_process:
595
+ print("Training finished – saving final model")
596
+ if save_model:
597
+ accelerator.unwrap_model(vae).save_pretrained(save_as)
598
+
599
+ accelerator.free_memory()
600
+ if torch.distributed.is_initialized():
601
+ torch.distributed.destroy_process_group()
602
+ print("Готово!")
transfer_simplevae3.ipynb ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 10,
6
+ "id": "c15deb04-94a0-4073-a174-adcd22af10b8",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "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",
14
+ "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"
15
+ ]
16
+ },
17
+ {
18
+ "name": "stdout",
19
+ "output_type": "stream",
20
+ "text": [
21
+ "✅ Создана новая модель: <class 'diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL'>\n",
22
+ "\n",
23
+ "--- Перенос весов ---\n",
24
+ "✅ Готово. Модель сохранена в vae9\n"
25
+ ]
26
+ }
27
+ ],
28
+ "source": [
29
+ "from diffusers.models import AsymmetricAutoencoderKL\n",
30
+ "import torch\n",
31
+ "from tqdm import tqdm\n",
32
+ "\n",
33
+ "# ---- Конфиг новой модели ----\n",
34
+ "config = {\n",
35
+ " \"_class_name\": \"AsymmetricAutoencoderKL\",\n",
36
+ " \"act_fn\": \"silu\",\n",
37
+ " \"in_channels\": 3,\n",
38
+ " \"out_channels\": 3,\n",
39
+ " \"scaling_factor\": 1.0,\n",
40
+ " \"norm_num_groups\": 32,\n",
41
+ " \"down_block_out_channels\": [128, 256, 512, 512],\n",
42
+ " \"down_block_types\": [\n",
43
+ " \"DownEncoderBlock2D\",\n",
44
+ " \"DownEncoderBlock2D\",\n",
45
+ " \"DownEncoderBlock2D\",\n",
46
+ " \"DownEncoderBlock2D\",\n",
47
+ " ],\n",
48
+ " \"latent_channels\": 16,\n",
49
+ " \"up_block_out_channels\": [128,128, 256, 512, 512],\n",
50
+ " \"up_block_types\": [\n",
51
+ " \"UpDecoderBlock2D\",\n",
52
+ " \"UpDecoderBlock2D\",\n",
53
+ " \"UpDecoderBlock2D\",\n",
54
+ " \"UpDecoderBlock2D\",\n",
55
+ " \"UpDecoderBlock2D\",\n",
56
+ " ],\n",
57
+ "}\n",
58
+ "\n",
59
+ "# ---- Создание пустой асимметричной модели ----\n",
60
+ "vae = AsymmetricAutoencoderKL(\n",
61
+ " act_fn=config[\"act_fn\"],\n",
62
+ " down_block_out_channels=config[\"down_block_out_channels\"],\n",
63
+ " down_block_types=config[\"down_block_types\"],\n",
64
+ " latent_channels=config[\"latent_channels\"],\n",
65
+ " up_block_out_channels=config[\"up_block_out_channels\"],\n",
66
+ " up_block_types=config[\"up_block_types\"],\n",
67
+ " in_channels=config[\"in_channels\"],\n",
68
+ " out_channels=config[\"out_channels\"],\n",
69
+ " scaling_factor=config[\"scaling_factor\"],\n",
70
+ " norm_num_groups=config[\"norm_num_groups\"],\n",
71
+ " layers_per_down_block=2,\n",
72
+ " layers_per_up_block=3,\n",
73
+ " sample_size=256\n",
74
+ ")\n",
75
+ "\n",
76
+ "vae.save_pretrained(\"asymmetric_vae_empty\")\n",
77
+ "print(\"✅ Создана новая модель:\", type(vae))\n",
78
+ "\n",
79
+ "def transfer_weights(old_path, new_path, save_path=\"vae_final\", device=\"cuda\", dtype=torch.float32):\n",
80
+ " old_vae = AsymmetricAutoencoderKL.from_pretrained(old_path).to(device, dtype=dtype)\n",
81
+ " new_vae = AsymmetricAutoencoderKL.from_pretrained(new_path).to(device, dtype=dtype)\n",
82
+ "\n",
83
+ " old_sd = old_vae.state_dict()\n",
84
+ " new_sd = new_vae.state_dict()\n",
85
+ "\n",
86
+ " print(\"\\n--- Перенос весов ---\")\n",
87
+ " \n",
88
+ " # 1. Переносим всё, что совпадает по именам и формам (Энкодер, конволоции и т.д.)\n",
89
+ " # Это покроет Encoder полностью, так как там down_blocks не менялись\n",
90
+ " for k, v in old_sd.items():\n",
91
+ " if k in new_sd and v.shape == new_sd[k].shape:\n",
92
+ " new_sd[k] = v.clone()\n",
93
+ "\n",
94
+ " # 2. Переносим блоки декодера (Up-blocks)\n",
95
+ " # Старый: [0, 1, 2, 3, 4] -> Новой: [0, 1, 2, 3]\n",
96
+ " # Нам нужно перенести глубокие слои (0, 1, 2), а последний 3-й взять из 4-го старого\n",
97
+ " \n",
98
+ " # Сопоставление индексов: старый блок -> новый блок\n",
99
+ " # Мы берем 0->0, 1->1, 2->2 и 4->3 (пропуская лишний блок 128->128)\n",
100
+ " mapping = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4} \n",
101
+ " \n",
102
+ " for old_idx, new_idx in mapping.items():\n",
103
+ " old_prefix = f\"decoder.up_blocks.{old_idx}.\"\n",
104
+ " new_prefix = f\"decoder.up_blocks.{new_idx}.\"\n",
105
+ " \n",
106
+ " for k, v in old_sd.items():\n",
107
+ " if k.startswith(old_prefix):\n",
108
+ " new_key = k.replace(old_prefix, new_prefix)\n",
109
+ " if new_key in new_sd and v.shape == new_sd[new_key].shape:\n",
110
+ " new_sd[new_key] = v.clone()\n",
111
+ " else:\n",
112
+ " print(f\"⚠️ Пропущен слой или не совпал размер: {new_key}\")\n",
113
+ "\n",
114
+ " # Загрузка\n",
115
+ " new_vae.load_state_dict(new_sd, strict=False)\n",
116
+ " new_vae.save_pretrained(save_path)\n",
117
+ " print(f\"✅ Готово. Модель сохранена в {save_path}\")\n",
118
+ "\n",
119
+ "# Запуск\n",
120
+ "transfer_weights(\"vae8\", \"asymmetric_vae_empty\", save_path=\"vae9\")\n",
121
+ "\n"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "59fcafb9-6d89-49b4-8362-b4891f591687",
128
+ "metadata": {},
129
+ "outputs": [],
130
+ "source": []
131
+ }
132
+ ],
133
+ "metadata": {
134
+ "kernelspec": {
135
+ "display_name": "Python 3 (ipykernel)",
136
+ "language": "python",
137
+ "name": "python3"
138
+ },
139
+ "language_info": {
140
+ "codemirror_mode": {
141
+ "name": "ipython",
142
+ "version": 3
143
+ },
144
+ "file_extension": ".py",
145
+ "mimetype": "text/x-python",
146
+ "name": "python",
147
+ "nbconvert_exporter": "python",
148
+ "pygments_lexer": "ipython3",
149
+ "version": "3.12.3"
150
+ }
151
+ },
152
+ "nbformat": 4,
153
+ "nbformat_minor": 5
154
+ }
vae_comp.ipynb ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "b3b23a40-8354-4287-bac2-32f9d084fff3",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_validators.py:202: UserWarning: The `local_dir_use_symlinks` argument is deprecated and ignored in `hf_hub_download`. Downloading to a local directory does not use symlinks anymore.\n",
14
+ " warnings.warn(\n"
15
+ ]
16
+ },
17
+ {
18
+ "name": "stdout",
19
+ "output_type": "stream",
20
+ "text": [
21
+ "sdxs_vae log-variance: 1.840\n"
22
+ ]
23
+ },
24
+ {
25
+ "name": "stderr",
26
+ "output_type": "stream",
27
+ "text": [
28
+ "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"
29
+ ]
30
+ },
31
+ {
32
+ "name": "stdout",
33
+ "output_type": "stream",
34
+ "text": [
35
+ "vae8 log-variance: 1.840\n"
36
+ ]
37
+ },
38
+ {
39
+ "name": "stderr",
40
+ "output_type": "stream",
41
+ "text": [
42
+ "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"
43
+ ]
44
+ },
45
+ {
46
+ "name": "stdout",
47
+ "output_type": "stream",
48
+ "text": [
49
+ "vae9 log-variance: 1.840\n",
50
+ "Готово\n"
51
+ ]
52
+ }
53
+ ],
54
+ "source": [
55
+ "import torch\n",
56
+ "from PIL import Image\n",
57
+ "from diffusers import AutoencoderKL,AsymmetricAutoencoderKL\n",
58
+ "from torchvision.transforms.functional import to_pil_image\n",
59
+ "import matplotlib.pyplot as plt\n",
60
+ "import os\n",
61
+ "from torchvision.transforms import ToTensor, Normalize, CenterCrop\n",
62
+ "\n",
63
+ "# путь к вашей картинке\n",
64
+ "IMG_PATH = \"1234567890.png\"\n",
65
+ "OUT_DIR = \"vaetest\"\n",
66
+ "device = \"cuda\"\n",
67
+ "dtype = torch.float32 # ← единый float32\n",
68
+ "os.makedirs(OUT_DIR, exist_ok=True)\n",
69
+ "\n",
70
+ "# список VAE\n",
71
+ "VAES = {\n",
72
+ " #\"sdxl\": \"madebyollin/sdxl-vae-fp16-fix\",\n",
73
+ " \"sdxs_vae\": \"AiArtLab/sdxs-1b\",\n",
74
+ " \"vae8\": \"/workspace/simplevae2x/vae8\",\n",
75
+ " \"vae9\": \"/workspace/simplevae2x/vae9\"\n",
76
+ "}\n",
77
+ "\n",
78
+ "def load_image(path):\n",
79
+ " img = Image.open(path).convert('RGB')\n",
80
+ " # обрезаем до кратности 8\n",
81
+ " w, h = img.size\n",
82
+ " img = CenterCrop((h // 8 * 8, w // 8 * 8))(img)\n",
83
+ " tensor = ToTensor()(img).unsqueeze(0) # [0,1]\n",
84
+ " tensor = Normalize(mean=[0.5]*3, std=[0.5]*3)(tensor) # [-1,1]\n",
85
+ " return img, tensor.to(device, dtype=dtype)\n",
86
+ "\n",
87
+ "# обратно в PIL\n",
88
+ "def tensor_to_img(t):\n",
89
+ " t = (t * 0.5 + 0.5).clamp(0, 1)\n",
90
+ " return to_pil_image(t[0])\n",
91
+ "\n",
92
+ "def logvariance(latents):\n",
93
+ " \"\"\"Возвращает лог-дисперсию по всем элементам.\"\"\"\n",
94
+ " return torch.log(latents.var() + 1e-8).item()\n",
95
+ "\n",
96
+ "def plot_latent_distribution(latents, title, save_path):\n",
97
+ " \"\"\"Гистограмма + QQ-plot.\"\"\"\n",
98
+ " lat = latents.detach().cpu().numpy().flatten()\n",
99
+ " plt.figure(figsize=(10, 4))\n",
100
+ "\n",
101
+ " # гистограмма\n",
102
+ " plt.subplot(1, 2, 1)\n",
103
+ " plt.hist(lat, bins=100, density=True, alpha=0.7, color='steelblue')\n",
104
+ " plt.title(f\"{title} histogram\")\n",
105
+ " plt.xlabel(\"latent value\")\n",
106
+ " plt.ylabel(\"density\")\n",
107
+ "\n",
108
+ " # QQ-plot\n",
109
+ " from scipy.stats import probplot\n",
110
+ " plt.subplot(1, 2, 2)\n",
111
+ " probplot(lat, dist=\"norm\", plot=plt)\n",
112
+ " plt.title(f\"{title} QQ-plot\")\n",
113
+ "\n",
114
+ " plt.tight_layout()\n",
115
+ " plt.savefig(save_path)\n",
116
+ " plt.close()\n",
117
+ "\n",
118
+ "for name, repo in VAES.items():\n",
119
+ " if name==\"sdxs_vae\":\n",
120
+ " vae = AsymmetricAutoencoderKL.from_pretrained(repo, subfolder=\"vae\", torch_dtype=dtype).to(device)\n",
121
+ " else:\n",
122
+ " vae = AsymmetricAutoencoderKL.from_pretrained(repo, torch_dtype=dtype).to(device)#, subfolder=\"vae\", variant=\"fp16\"\n",
123
+ "\n",
124
+ " cfg = vae.config\n",
125
+ " scale = getattr(cfg, \"scaling_factor\", 1.)\n",
126
+ " shift = getattr(cfg, \"shift_factor\", 0.0)\n",
127
+ " mean = getattr(cfg, \"latents_mean\", None)\n",
128
+ " std = getattr(cfg, \"latents_std\", None)\n",
129
+ "\n",
130
+ " C = 4 # 4 для SDXL\n",
131
+ " if mean is not None:\n",
132
+ " mean = torch.tensor(mean, device=device, dtype=dtype).view(1, C, 1, 1)\n",
133
+ " if std is not None:\n",
134
+ " std = torch.tensor(std, device=device, dtype=dtype).view(1, C, 1, 1)\n",
135
+ " if shift is not None:\n",
136
+ " shift = torch.tensor(shift, device=device, dtype=dtype)\n",
137
+ " else:\n",
138
+ " shift = 0.0 \n",
139
+ "\n",
140
+ " scale = torch.tensor(scale, device=device, dtype=dtype)\n",
141
+ "\n",
142
+ " img, x = load_image(IMG_PATH)\n",
143
+ " img.save(os.path.join(OUT_DIR, f\"original.png\"))\n",
144
+ "\n",
145
+ " with torch.no_grad():\n",
146
+ " # encode\n",
147
+ " latents = vae.encode(x).latent_dist.sample().to(dtype)\n",
148
+ " if mean is not None and std is not None:\n",
149
+ " latents = (latents - mean) / std\n",
150
+ " latents = latents * scale + shift\n",
151
+ "\n",
152
+ " lv = logvariance(latents)\n",
153
+ " print(f\"{name} log-variance: {lv:.3f}\")\n",
154
+ "\n",
155
+ " # график\n",
156
+ " plot_latent_distribution(latents, f\"{name}_latents\",\n",
157
+ " os.path.join(OUT_DIR, f\"dist_{name}.png\"))\n",
158
+ "\n",
159
+ " # decode\n",
160
+ " latents = (latents - shift) / scale\n",
161
+ " if mean is not None and std is not None:\n",
162
+ " latents = latents * std + mean\n",
163
+ " rec = vae.decode(latents).sample\n",
164
+ "\n",
165
+ " tensor_to_img(rec).save(os.path.join(OUT_DIR, f\"decoded_{name}.png\"))\n",
166
+ "\n",
167
+ "print(\"Готово\")"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "id": "200b72ab-1978-4d71-9aba-b1ef97cf0b27",
174
+ "metadata": {},
175
+ "outputs": [],
176
+ "source": []
177
+ }
178
+ ],
179
+ "metadata": {
180
+ "kernelspec": {
181
+ "display_name": "Python 3 (ipykernel)",
182
+ "language": "python",
183
+ "name": "python3"
184
+ },
185
+ "language_info": {
186
+ "codemirror_mode": {
187
+ "name": "ipython",
188
+ "version": 3
189
+ },
190
+ "file_extension": ".py",
191
+ "mimetype": "text/x-python",
192
+ "name": "python",
193
+ "nbconvert_exporter": "python",
194
+ "pygments_lexer": "ipython3",
195
+ "version": "3.12.3"
196
+ }
197
+ },
198
+ "nbformat": 4,
199
+ "nbformat_minor": 5
200
+ }