Aero-Ex commited on
Commit
ed17f1e
·
verified ·
1 Parent(s): 8311b5f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .vscode/launch.json +56 -0
  2. __pycache__/info.cpython-312.pyc +0 -0
  3. assets/glif.svg +40 -0
  4. config/examples/train_lora_flux_24gb.yaml +96 -0
  5. docker/start.sh +70 -0
  6. notebooks/FLUX_1_dev_LoRA_Training.ipynb +291 -0
  7. notebooks/FLUX_1_schnell_LoRA_Training.ipynb +296 -0
  8. notebooks/SliderTraining.ipynb +339 -0
  9. scripts/caption_audio_dataset.py +309 -0
  10. scripts/convert_cog.py +128 -0
  11. scripts/convert_lora_to_peft_format.py +91 -0
  12. scripts/generate_sampler_step_scales.py +20 -0
  13. scripts/make_diffusers_model.py +61 -0
  14. scripts/patch_te_adapter.py +42 -0
  15. scripts/repair_dataset_folder.py +65 -0
  16. scripts/update_sponsors.py +309 -0
  17. toolkit/__init__.py +0 -0
  18. toolkit/accelerator.py +20 -0
  19. toolkit/advanced_prompt_embeds.py +195 -0
  20. toolkit/assistant_lora.py +55 -0
  21. toolkit/basic.py +70 -0
  22. toolkit/buckets.py +129 -0
  23. toolkit/clip_vision_adapter.py +406 -0
  24. toolkit/config.py +110 -0
  25. toolkit/config_modules.py +1403 -0
  26. toolkit/control_generator.py +291 -0
  27. toolkit/cuda_malloc.py +93 -0
  28. toolkit/custom_adapter.py +1359 -0
  29. toolkit/data_loader.py +758 -0
  30. toolkit/dataloader_mixins.py +0 -0
  31. toolkit/dequantize.py +88 -0
  32. toolkit/ema.py +347 -0
  33. toolkit/embedding.py +284 -0
  34. toolkit/esrgan_utils.py +51 -0
  35. toolkit/extension.py +57 -0
  36. toolkit/guidance.py +831 -0
  37. toolkit/image_utils.py +547 -0
  38. toolkit/inversion_utils.py +410 -0
  39. toolkit/ip_adapter.py +1302 -0
  40. toolkit/job.py +44 -0
  41. toolkit/kohya_lora.py +1221 -0
  42. toolkit/kohya_model_util.py +1533 -0
  43. toolkit/layers.py +44 -0
  44. toolkit/logging_aitk.py +344 -0
  45. toolkit/lora_special.py +595 -0
  46. toolkit/lorm.py +461 -0
  47. toolkit/losses.py +113 -0
  48. toolkit/lycoris_special.py +373 -0
  49. toolkit/lycoris_utils.py +536 -0
  50. toolkit/metadata.py +88 -0
.vscode/launch.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "Run current config",
6
+ "type": "python",
7
+ "request": "launch",
8
+ "program": "${workspaceFolder}/run.py",
9
+ "args": [
10
+ "${file}"
11
+ ],
12
+ "env": {
13
+ "CUDA_LAUNCH_BLOCKING": "1",
14
+ "DEBUG_TOOLKIT": "1"
15
+ },
16
+ "console": "integratedTerminal",
17
+ "justMyCode": false
18
+ },
19
+ {
20
+ "name": "Run current config (cuda:1)",
21
+ "type": "python",
22
+ "request": "launch",
23
+ "program": "${workspaceFolder}/run.py",
24
+ "args": [
25
+ "${file}"
26
+ ],
27
+ "env": {
28
+ "CUDA_LAUNCH_BLOCKING": "1",
29
+ "DEBUG_TOOLKIT": "1",
30
+ "CUDA_VISIBLE_DEVICES": "1"
31
+ },
32
+ "console": "integratedTerminal",
33
+ "justMyCode": false
34
+ },
35
+ {
36
+ "name": "Python: Debug Current File",
37
+ "type": "python",
38
+ "request": "launch",
39
+ "program": "${file}",
40
+ "console": "integratedTerminal",
41
+ "justMyCode": false
42
+ },
43
+ {
44
+ "name": "Python: Debug Current File (cuda:1)",
45
+ "type": "python",
46
+ "request": "launch",
47
+ "program": "${file}",
48
+ "console": "integratedTerminal",
49
+ "env": {
50
+ "CUDA_LAUNCH_BLOCKING": "1",
51
+ "CUDA_VISIBLE_DEVICES": "1"
52
+ },
53
+ "justMyCode": false
54
+ },
55
+ ]
56
+ }
__pycache__/info.cpython-312.pyc ADDED
Binary file (408 Bytes). View file
 
assets/glif.svg ADDED
config/examples/train_lora_flux_24gb.yaml ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ job: extension
3
+ config:
4
+ # this name will be the folder and filename name
5
+ name: "my_first_flux_lora_v1"
6
+ process:
7
+ - type: 'sd_trainer'
8
+ # root folder to save training sessions/samples/weights
9
+ training_folder: "output"
10
+ # uncomment to see performance stats in the terminal every N steps
11
+ # performance_log_every: 1000
12
+ device: cuda:0
13
+ # if a trigger word is specified, it will be added to captions of training data if it does not already exist
14
+ # alternatively, in your captions you can add [trigger] and it will be replaced with the trigger word
15
+ # trigger_word: "p3r5on"
16
+ network:
17
+ type: "lora"
18
+ linear: 16
19
+ linear_alpha: 16
20
+ save:
21
+ dtype: float16 # precision to save
22
+ save_every: 250 # save every this many steps
23
+ max_step_saves_to_keep: 4 # how many intermittent saves to keep
24
+ push_to_hub: false #change this to True to push your trained model to Hugging Face.
25
+ # You can either set up a HF_TOKEN env variable or you'll be prompted to log-in
26
+ # hf_repo_id: your-username/your-model-slug
27
+ # hf_private: true #whether the repo is private or public
28
+ datasets:
29
+ # datasets are a folder of images. captions need to be txt files with the same name as the image
30
+ # for instance image2.jpg and image2.txt. Only jpg, jpeg, and png are supported currently
31
+ # images will automatically be resized and bucketed into the resolution specified
32
+ # on windows, escape back slashes with another backslash so
33
+ # "C:\\path\\to\\images\\folder"
34
+ - folder_path: "/path/to/images/folder"
35
+ caption_ext: "txt"
36
+ caption_dropout_rate: 0.05 # will drop out the caption 5% of time
37
+ shuffle_tokens: false # shuffle caption order, split by commas
38
+ cache_latents_to_disk: true # leave this true unless you know what you're doing
39
+ resolution: [ 512, 768, 1024 ] # flux enjoys multiple resolutions
40
+ train:
41
+ batch_size: 1
42
+ steps: 2000 # total number of steps to train 500 - 4000 is a good range
43
+ gradient_accumulation_steps: 1
44
+ train_unet: true
45
+ train_text_encoder: false # probably won't work with flux
46
+ gradient_checkpointing: true # need the on unless you have a ton of vram
47
+ noise_scheduler: "flowmatch" # for training only
48
+ optimizer: "adamw8bit"
49
+ lr: 1e-4
50
+ # uncomment this to skip the pre training sample
51
+ # skip_first_sample: true
52
+ # uncomment to completely disable sampling
53
+ # disable_sampling: true
54
+ # uncomment to use new vell curved weighting. Experimental but may produce better results
55
+ # linear_timesteps: true
56
+
57
+ # ema will smooth out learning, but could slow it down. Recommended to leave on.
58
+ ema_config:
59
+ use_ema: true
60
+ ema_decay: 0.99
61
+
62
+ # will probably need this if gpu supports it for flux, other dtypes may not work correctly
63
+ dtype: bf16
64
+ model:
65
+ # huggingface model name or path
66
+ name_or_path: "black-forest-labs/FLUX.1-dev"
67
+ is_flux: true
68
+ quantize: true # run 8bit mixed precision
69
+ # low_vram: true # uncomment this if the GPU is connected to your monitors. It will use less vram to quantize, but is slower.
70
+ sample:
71
+ sampler: "flowmatch" # must match train.noise_scheduler
72
+ sample_every: 250 # sample every this many steps
73
+ width: 1024
74
+ height: 1024
75
+ prompts:
76
+ # you can add [trigger] to the prompts here and it will be replaced with the trigger word
77
+ # - "[trigger] holding a sign that says 'I LOVE PROMPTS!'"\
78
+ - "woman with red hair, playing chess at the park, bomb going off in the background"
79
+ - "a woman holding a coffee cup, in a beanie, sitting at a cafe"
80
+ - "a horse is a DJ at a night club, fish eye lens, smoke machine, lazer lights, holding a martini"
81
+ - "a man showing off his cool new t shirt at the beach, a shark is jumping out of the water in the background"
82
+ - "a bear building a log cabin in the snow covered mountains"
83
+ - "woman playing the guitar, on stage, singing a song, laser lights, punk rocker"
84
+ - "hipster man with a beard, building a chair, in a wood shop"
85
+ - "photo of a man, white background, medium shot, modeling clothing, studio lighting, white backdrop"
86
+ - "a man holding a sign that says, 'this is a sign'"
87
+ - "a bulldog, in a post apocalyptic world, with a shotgun, in a leather jacket, in a desert, with a motorcycle"
88
+ neg: "" # not used on flux
89
+ seed: 42
90
+ walk_seed: true
91
+ guidance_scale: 4
92
+ sample_steps: 20
93
+ # you can add any additional meta info here. [name] is replaced with config name at top
94
+ meta:
95
+ name: "[name]"
96
+ version: '1.0'
docker/start.sh ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e # Exit the script if any statement returns a non-true return value
3
+
4
+ # ref https://github.com/runpod/containers/blob/main/container-template/start.sh
5
+
6
+ # ---------------------------------------------------------------------------- #
7
+ # Function Definitions #
8
+ # ---------------------------------------------------------------------------- #
9
+
10
+
11
+ # Setup ssh
12
+ setup_ssh() {
13
+ if [[ $PUBLIC_KEY ]]; then
14
+ echo "Setting up SSH..."
15
+ mkdir -p ~/.ssh
16
+ echo "$PUBLIC_KEY" >> ~/.ssh/authorized_keys
17
+ chmod 700 -R ~/.ssh
18
+
19
+ if [ ! -f /etc/ssh/ssh_host_rsa_key ]; then
20
+ ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -q -N ''
21
+ echo "RSA key fingerprint:"
22
+ ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub
23
+ fi
24
+
25
+ if [ ! -f /etc/ssh/ssh_host_dsa_key ]; then
26
+ ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -q -N ''
27
+ echo "DSA key fingerprint:"
28
+ ssh-keygen -lf /etc/ssh/ssh_host_dsa_key.pub
29
+ fi
30
+
31
+ if [ ! -f /etc/ssh/ssh_host_ecdsa_key ]; then
32
+ ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -q -N ''
33
+ echo "ECDSA key fingerprint:"
34
+ ssh-keygen -lf /etc/ssh/ssh_host_ecdsa_key.pub
35
+ fi
36
+
37
+ if [ ! -f /etc/ssh/ssh_host_ed25519_key ]; then
38
+ ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -q -N ''
39
+ echo "ED25519 key fingerprint:"
40
+ ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
41
+ fi
42
+
43
+ service ssh start
44
+
45
+ echo "SSH host keys:"
46
+ for key in /etc/ssh/*.pub; do
47
+ echo "Key: $key"
48
+ ssh-keygen -lf $key
49
+ done
50
+ fi
51
+ }
52
+
53
+ # Export env vars
54
+ export_env_vars() {
55
+ echo "Exporting environment variables..."
56
+ printenv | grep -E '^RUNPOD_|^PATH=|^_=' | awk -F = '{ print "export " $1 "=\"" $2 "\"" }' >> /etc/rp_environment
57
+ echo 'source /etc/rp_environment' >> ~/.bashrc
58
+ }
59
+
60
+ # ---------------------------------------------------------------------------- #
61
+ # Main Program #
62
+ # ---------------------------------------------------------------------------- #
63
+
64
+
65
+ echo "Pod Started"
66
+
67
+ setup_ssh
68
+ export_env_vars
69
+ echo "Starting AI Toolkit UI..."
70
+ cd /app/ai-toolkit/ui && npm run start
notebooks/FLUX_1_dev_LoRA_Training.ipynb ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "collapsed": false,
7
+ "id": "zl-S0m3pkQC5"
8
+ },
9
+ "source": [
10
+ "# AI Toolkit by Ostris\n",
11
+ "## FLUX.1-dev Training\n"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "!nvidia-smi"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "metadata": {
27
+ "id": "BvAG0GKAh59G"
28
+ },
29
+ "outputs": [],
30
+ "source": [
31
+ "!git clone https://github.com/ostris/ai-toolkit\n",
32
+ "!mkdir -p /content/dataset"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "markdown",
37
+ "metadata": {
38
+ "id": "UFUW4ZMmnp1V"
39
+ },
40
+ "source": [
41
+ "Put your image dataset in the `/content/dataset` folder"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "execution_count": null,
47
+ "metadata": {
48
+ "id": "XGZqVER_aQJW"
49
+ },
50
+ "outputs": [],
51
+ "source": [
52
+ "!cd ai-toolkit && git submodule update --init --recursive && pip install -r requirements.txt\n"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "markdown",
57
+ "metadata": {
58
+ "id": "OV0HnOI6o8V6"
59
+ },
60
+ "source": [
61
+ "## Model License\n",
62
+ "Training currently only works with FLUX.1-dev. Which means anything you train will inherit the non-commercial license. It is also a gated model, so you need to accept the license on HF before using it. Otherwise, this will fail. Here are the required steps to setup a license.\n",
63
+ "\n",
64
+ "Sign into HF and accept the model access here [black-forest-labs/FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)\n",
65
+ "\n",
66
+ "[Get a READ key from huggingface](https://huggingface.co/settings/tokens/new?) and place it in the next cell after running it."
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": null,
72
+ "metadata": {
73
+ "id": "3yZZdhFRoj2m"
74
+ },
75
+ "outputs": [],
76
+ "source": [
77
+ "import getpass\n",
78
+ "import os\n",
79
+ "\n",
80
+ "# Prompt for the token\n",
81
+ "hf_token = getpass.getpass('Enter your HF access token and press enter: ')\n",
82
+ "\n",
83
+ "# Set the environment variable\n",
84
+ "os.environ['HF_TOKEN'] = hf_token\n",
85
+ "\n",
86
+ "print(\"HF_TOKEN environment variable has been set.\")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": null,
92
+ "metadata": {
93
+ "id": "9gO2EzQ1kQC8"
94
+ },
95
+ "outputs": [],
96
+ "source": [
97
+ "import os\n",
98
+ "import sys\n",
99
+ "sys.path.append('/content/ai-toolkit')\n",
100
+ "from toolkit.job import run_job\n",
101
+ "from collections import OrderedDict\n",
102
+ "from PIL import Image\n",
103
+ "import os\n",
104
+ "os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\""
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "markdown",
109
+ "metadata": {
110
+ "id": "N8UUFzVRigbC"
111
+ },
112
+ "source": [
113
+ "## Setup\n",
114
+ "\n",
115
+ "This is your config. It is documented pretty well. Normally you would do this as a yaml file, but for colab, this will work. This will run as is without modification, but feel free to edit as you want."
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "metadata": {
122
+ "id": "_t28QURYjRQO"
123
+ },
124
+ "outputs": [],
125
+ "source": [
126
+ "from collections import OrderedDict\n",
127
+ "\n",
128
+ "job_to_run = OrderedDict([\n",
129
+ " ('job', 'extension'),\n",
130
+ " ('config', OrderedDict([\n",
131
+ " # this name will be the folder and filename name\n",
132
+ " ('name', 'my_first_flux_lora_v1'),\n",
133
+ " ('process', [\n",
134
+ " OrderedDict([\n",
135
+ " ('type', 'sd_trainer'),\n",
136
+ " # root folder to save training sessions/samples/weights\n",
137
+ " ('training_folder', '/content/output'),\n",
138
+ " # uncomment to see performance stats in the terminal every N steps\n",
139
+ " #('performance_log_every', 1000),\n",
140
+ " ('device', 'cuda:0'),\n",
141
+ " # if a trigger word is specified, it will be added to captions of training data if it does not already exist\n",
142
+ " # alternatively, in your captions you can add [trigger] and it will be replaced with the trigger word\n",
143
+ " # ('trigger_word', 'image'),\n",
144
+ " ('network', OrderedDict([\n",
145
+ " ('type', 'lora'),\n",
146
+ " ('linear', 16),\n",
147
+ " ('linear_alpha', 16)\n",
148
+ " ])),\n",
149
+ " ('save', OrderedDict([\n",
150
+ " ('dtype', 'float16'), # precision to save\n",
151
+ " ('save_every', 250), # save every this many steps\n",
152
+ " ('max_step_saves_to_keep', 4) # how many intermittent saves to keep\n",
153
+ " ])),\n",
154
+ " ('datasets', [\n",
155
+ " # datasets are a folder of images. captions need to be txt files with the same name as the image\n",
156
+ " # for instance image2.jpg and image2.txt. Only jpg, jpeg, and png are supported currently\n",
157
+ " # images will automatically be resized and bucketed into the resolution specified\n",
158
+ " OrderedDict([\n",
159
+ " ('folder_path', '/content/dataset'),\n",
160
+ " ('caption_ext', 'txt'),\n",
161
+ " ('caption_dropout_rate', 0.05), # will drop out the caption 5% of time\n",
162
+ " ('shuffle_tokens', False), # shuffle caption order, split by commas\n",
163
+ " ('cache_latents_to_disk', True), # leave this true unless you know what you're doing\n",
164
+ " ('resolution', [512, 768, 1024]) # flux enjoys multiple resolutions\n",
165
+ " ])\n",
166
+ " ]),\n",
167
+ " ('train', OrderedDict([\n",
168
+ " ('batch_size', 1),\n",
169
+ " ('steps', 2000), # total number of steps to train 500 - 4000 is a good range\n",
170
+ " ('gradient_accumulation_steps', 1),\n",
171
+ " ('train_unet', True),\n",
172
+ " ('train_text_encoder', False), # probably won't work with flux\n",
173
+ " ('content_or_style', 'balanced'), # content, style, balanced\n",
174
+ " ('gradient_checkpointing', True), # need the on unless you have a ton of vram\n",
175
+ " ('noise_scheduler', 'flowmatch'), # for training only\n",
176
+ " ('optimizer', 'adamw8bit'),\n",
177
+ " ('lr', 1e-4),\n",
178
+ "\n",
179
+ " # uncomment this to skip the pre training sample\n",
180
+ " # ('skip_first_sample', True),\n",
181
+ "\n",
182
+ " # uncomment to completely disable sampling\n",
183
+ " # ('disable_sampling', True),\n",
184
+ "\n",
185
+ " # uncomment to use new vell curved weighting. Experimental but may produce better results\n",
186
+ " # ('linear_timesteps', True),\n",
187
+ "\n",
188
+ " # ema will smooth out learning, but could slow it down. Recommended to leave on.\n",
189
+ " ('ema_config', OrderedDict([\n",
190
+ " ('use_ema', True),\n",
191
+ " ('ema_decay', 0.99)\n",
192
+ " ])),\n",
193
+ "\n",
194
+ " # will probably need this if gpu supports it for flux, other dtypes may not work correctly\n",
195
+ " ('dtype', 'bf16')\n",
196
+ " ])),\n",
197
+ " ('model', OrderedDict([\n",
198
+ " # huggingface model name or path\n",
199
+ " ('name_or_path', 'black-forest-labs/FLUX.1-dev'),\n",
200
+ " ('is_flux', True),\n",
201
+ " ('quantize', True), # run 8bit mixed precision\n",
202
+ " #('low_vram', True), # uncomment this if the GPU is connected to your monitors. It will use less vram to quantize, but is slower.\n",
203
+ " ])),\n",
204
+ " ('sample', OrderedDict([\n",
205
+ " ('sampler', 'flowmatch'), # must match train.noise_scheduler\n",
206
+ " ('sample_every', 250), # sample every this many steps\n",
207
+ " ('width', 1024),\n",
208
+ " ('height', 1024),\n",
209
+ " ('prompts', [\n",
210
+ " # you can add [trigger] to the prompts here and it will be replaced with the trigger word\n",
211
+ " #'[trigger] holding a sign that says \\'I LOVE PROMPTS!\\'',\n",
212
+ " 'woman with red hair, playing chess at the park, bomb going off in the background',\n",
213
+ " 'a woman holding a coffee cup, in a beanie, sitting at a cafe',\n",
214
+ " 'a horse is a DJ at a night club, fish eye lens, smoke machine, lazer lights, holding a martini',\n",
215
+ " 'a man showing off his cool new t shirt at the beach, a shark is jumping out of the water in the background',\n",
216
+ " 'a bear building a log cabin in the snow covered mountains',\n",
217
+ " 'woman playing the guitar, on stage, singing a song, laser lights, punk rocker',\n",
218
+ " 'hipster man with a beard, building a chair, in a wood shop',\n",
219
+ " 'photo of a man, white background, medium shot, modeling clothing, studio lighting, white backdrop',\n",
220
+ " 'a man holding a sign that says, \\'this is a sign\\'',\n",
221
+ " 'a bulldog, in a post apocalyptic world, with a shotgun, in a leather jacket, in a desert, with a motorcycle'\n",
222
+ " ]),\n",
223
+ " ('neg', ''), # not used on flux\n",
224
+ " ('seed', 42),\n",
225
+ " ('walk_seed', True),\n",
226
+ " ('guidance_scale', 4),\n",
227
+ " ('sample_steps', 20)\n",
228
+ " ]))\n",
229
+ " ])\n",
230
+ " ])\n",
231
+ " ])),\n",
232
+ " # you can add any additional meta info here. [name] is replaced with config name at top\n",
233
+ " ('meta', OrderedDict([\n",
234
+ " ('name', '[name]'),\n",
235
+ " ('version', '1.0')\n",
236
+ " ]))\n",
237
+ "])\n"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "markdown",
242
+ "metadata": {
243
+ "id": "h6F1FlM2Wb3l"
244
+ },
245
+ "source": [
246
+ "## Run it\n",
247
+ "\n",
248
+ "Below does all the magic. Check your folders to the left. Items will be in output/LoRA/your_name_v1 In the samples folder, there are preiodic sampled. This doesnt work great with colab. They will be in /content/output"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": null,
254
+ "metadata": {
255
+ "id": "HkajwI8gteOh"
256
+ },
257
+ "outputs": [],
258
+ "source": [
259
+ "run_job(job_to_run)\n"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "markdown",
264
+ "metadata": {
265
+ "id": "Hblgb5uwW5SD"
266
+ },
267
+ "source": [
268
+ "## Done\n",
269
+ "\n",
270
+ "Check your ourput dir and get your slider\n"
271
+ ]
272
+ }
273
+ ],
274
+ "metadata": {
275
+ "accelerator": "GPU",
276
+ "colab": {
277
+ "gpuType": "A100",
278
+ "machine_shape": "hm",
279
+ "provenance": []
280
+ },
281
+ "kernelspec": {
282
+ "display_name": "Python 3",
283
+ "name": "python3"
284
+ },
285
+ "language_info": {
286
+ "name": "python"
287
+ }
288
+ },
289
+ "nbformat": 4,
290
+ "nbformat_minor": 0
291
+ }
notebooks/FLUX_1_schnell_LoRA_Training.ipynb ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "collapsed": false,
7
+ "id": "zl-S0m3pkQC5"
8
+ },
9
+ "source": [
10
+ "# AI Toolkit by Ostris\n",
11
+ "## FLUX.1-schnell Training\n"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {
18
+ "id": "3cokMT-WC6rG"
19
+ },
20
+ "outputs": [],
21
+ "source": [
22
+ "!nvidia-smi"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "metadata": {
29
+ "collapsed": true,
30
+ "id": "BvAG0GKAh59G"
31
+ },
32
+ "outputs": [],
33
+ "source": [
34
+ "!git clone https://github.com/ostris/ai-toolkit\n",
35
+ "!mkdir -p /content/dataset"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "metadata": {
41
+ "id": "UFUW4ZMmnp1V"
42
+ },
43
+ "source": [
44
+ "Put your image dataset in the `/content/dataset` folder"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "metadata": {
51
+ "collapsed": true,
52
+ "id": "XGZqVER_aQJW"
53
+ },
54
+ "outputs": [],
55
+ "source": [
56
+ "!cd ai-toolkit && git submodule update --init --recursive && pip install -r requirements.txt\n"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "markdown",
61
+ "metadata": {
62
+ "id": "OV0HnOI6o8V6"
63
+ },
64
+ "source": [
65
+ "## Model License\n",
66
+ "Training currently only works with FLUX.1-dev. Which means anything you train will inherit the non-commercial license. It is also a gated model, so you need to accept the license on HF before using it. Otherwise, this will fail. Here are the required steps to setup a license.\n",
67
+ "\n",
68
+ "Sign into HF and accept the model access here [black-forest-labs/FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)\n",
69
+ "\n",
70
+ "[Get a READ key from huggingface](https://huggingface.co/settings/tokens/new?) and place it in the next cell after running it."
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "metadata": {
77
+ "id": "3yZZdhFRoj2m"
78
+ },
79
+ "outputs": [],
80
+ "source": [
81
+ "import getpass\n",
82
+ "import os\n",
83
+ "\n",
84
+ "# Prompt for the token\n",
85
+ "hf_token = getpass.getpass('Enter your HF access token and press enter: ')\n",
86
+ "\n",
87
+ "# Set the environment variable\n",
88
+ "os.environ['HF_TOKEN'] = hf_token\n",
89
+ "\n",
90
+ "print(\"HF_TOKEN environment variable has been set.\")"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "execution_count": 5,
96
+ "metadata": {
97
+ "id": "9gO2EzQ1kQC8"
98
+ },
99
+ "outputs": [],
100
+ "source": [
101
+ "import os\n",
102
+ "import sys\n",
103
+ "sys.path.append('/content/ai-toolkit')\n",
104
+ "from toolkit.job import run_job\n",
105
+ "from collections import OrderedDict\n",
106
+ "from PIL import Image\n",
107
+ "import os\n",
108
+ "os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\""
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "markdown",
113
+ "metadata": {
114
+ "id": "N8UUFzVRigbC"
115
+ },
116
+ "source": [
117
+ "## Setup\n",
118
+ "\n",
119
+ "This is your config. It is documented pretty well. Normally you would do this as a yaml file, but for colab, this will work. This will run as is without modification, but feel free to edit as you want."
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": 6,
125
+ "metadata": {
126
+ "id": "_t28QURYjRQO"
127
+ },
128
+ "outputs": [],
129
+ "source": [
130
+ "from collections import OrderedDict\n",
131
+ "\n",
132
+ "job_to_run = OrderedDict([\n",
133
+ " ('job', 'extension'),\n",
134
+ " ('config', OrderedDict([\n",
135
+ " # this name will be the folder and filename name\n",
136
+ " ('name', 'my_first_flux_lora_v1'),\n",
137
+ " ('process', [\n",
138
+ " OrderedDict([\n",
139
+ " ('type', 'sd_trainer'),\n",
140
+ " # root folder to save training sessions/samples/weights\n",
141
+ " ('training_folder', '/content/output'),\n",
142
+ " # uncomment to see performance stats in the terminal every N steps\n",
143
+ " #('performance_log_every', 1000),\n",
144
+ " ('device', 'cuda:0'),\n",
145
+ " # if a trigger word is specified, it will be added to captions of training data if it does not already exist\n",
146
+ " # alternatively, in your captions you can add [trigger] and it will be replaced with the trigger word\n",
147
+ " # ('trigger_word', 'image'),\n",
148
+ " ('network', OrderedDict([\n",
149
+ " ('type', 'lora'),\n",
150
+ " ('linear', 16),\n",
151
+ " ('linear_alpha', 16)\n",
152
+ " ])),\n",
153
+ " ('save', OrderedDict([\n",
154
+ " ('dtype', 'float16'), # precision to save\n",
155
+ " ('save_every', 250), # save every this many steps\n",
156
+ " ('max_step_saves_to_keep', 4) # how many intermittent saves to keep\n",
157
+ " ])),\n",
158
+ " ('datasets', [\n",
159
+ " # datasets are a folder of images. captions need to be txt files with the same name as the image\n",
160
+ " # for instance image2.jpg and image2.txt. Only jpg, jpeg, and png are supported currently\n",
161
+ " # images will automatically be resized and bucketed into the resolution specified\n",
162
+ " OrderedDict([\n",
163
+ " ('folder_path', '/content/dataset'),\n",
164
+ " ('caption_ext', 'txt'),\n",
165
+ " ('caption_dropout_rate', 0.05), # will drop out the caption 5% of time\n",
166
+ " ('shuffle_tokens', False), # shuffle caption order, split by commas\n",
167
+ " ('cache_latents_to_disk', True), # leave this true unless you know what you're doing\n",
168
+ " ('resolution', [512, 768, 1024]) # flux enjoys multiple resolutions\n",
169
+ " ])\n",
170
+ " ]),\n",
171
+ " ('train', OrderedDict([\n",
172
+ " ('batch_size', 1),\n",
173
+ " ('steps', 2000), # total number of steps to train 500 - 4000 is a good range\n",
174
+ " ('gradient_accumulation_steps', 1),\n",
175
+ " ('train_unet', True),\n",
176
+ " ('train_text_encoder', False), # probably won't work with flux\n",
177
+ " ('gradient_checkpointing', True), # need the on unless you have a ton of vram\n",
178
+ " ('noise_scheduler', 'flowmatch'), # for training only\n",
179
+ " ('optimizer', 'adamw8bit'),\n",
180
+ " ('lr', 1e-4),\n",
181
+ "\n",
182
+ " # uncomment this to skip the pre training sample\n",
183
+ " # ('skip_first_sample', True),\n",
184
+ "\n",
185
+ " # uncomment to completely disable sampling\n",
186
+ " # ('disable_sampling', True),\n",
187
+ "\n",
188
+ " # uncomment to use new vell curved weighting. Experimental but may produce better results\n",
189
+ " # ('linear_timesteps', True),\n",
190
+ "\n",
191
+ " # ema will smooth out learning, but could slow it down. Recommended to leave on.\n",
192
+ " ('ema_config', OrderedDict([\n",
193
+ " ('use_ema', True),\n",
194
+ " ('ema_decay', 0.99)\n",
195
+ " ])),\n",
196
+ "\n",
197
+ " # will probably need this if gpu supports it for flux, other dtypes may not work correctly\n",
198
+ " ('dtype', 'bf16')\n",
199
+ " ])),\n",
200
+ " ('model', OrderedDict([\n",
201
+ " # huggingface model name or path\n",
202
+ " ('name_or_path', 'black-forest-labs/FLUX.1-schnell'),\n",
203
+ " ('assistant_lora_path', 'ostris/FLUX.1-schnell-training-adapter'), # Required for flux schnell training\n",
204
+ " ('is_flux', True),\n",
205
+ " ('quantize', True), # run 8bit mixed precision\n",
206
+ " # low_vram is painfully slow to fuse in the adapter avoid it unless absolutely necessary\n",
207
+ " #('low_vram', True), # uncomment this if the GPU is connected to your monitors. It will use less vram to quantize, but is slower.\n",
208
+ " ])),\n",
209
+ " ('sample', OrderedDict([\n",
210
+ " ('sampler', 'flowmatch'), # must match train.noise_scheduler\n",
211
+ " ('sample_every', 250), # sample every this many steps\n",
212
+ " ('width', 1024),\n",
213
+ " ('height', 1024),\n",
214
+ " ('prompts', [\n",
215
+ " # you can add [trigger] to the prompts here and it will be replaced with the trigger word\n",
216
+ " #'[trigger] holding a sign that says \\'I LOVE PROMPTS!\\'',\n",
217
+ " 'woman with red hair, playing chess at the park, bomb going off in the background',\n",
218
+ " 'a woman holding a coffee cup, in a beanie, sitting at a cafe',\n",
219
+ " 'a horse is a DJ at a night club, fish eye lens, smoke machine, lazer lights, holding a martini',\n",
220
+ " 'a man showing off his cool new t shirt at the beach, a shark is jumping out of the water in the background',\n",
221
+ " 'a bear building a log cabin in the snow covered mountains',\n",
222
+ " 'woman playing the guitar, on stage, singing a song, laser lights, punk rocker',\n",
223
+ " 'hipster man with a beard, building a chair, in a wood shop',\n",
224
+ " 'photo of a man, white background, medium shot, modeling clothing, studio lighting, white backdrop',\n",
225
+ " 'a man holding a sign that says, \\'this is a sign\\'',\n",
226
+ " 'a bulldog, in a post apocalyptic world, with a shotgun, in a leather jacket, in a desert, with a motorcycle'\n",
227
+ " ]),\n",
228
+ " ('neg', ''), # not used on flux\n",
229
+ " ('seed', 42),\n",
230
+ " ('walk_seed', True),\n",
231
+ " ('guidance_scale', 1), # schnell does not do guidance\n",
232
+ " ('sample_steps', 4) # 1 - 4 works well\n",
233
+ " ]))\n",
234
+ " ])\n",
235
+ " ])\n",
236
+ " ])),\n",
237
+ " # you can add any additional meta info here. [name] is replaced with config name at top\n",
238
+ " ('meta', OrderedDict([\n",
239
+ " ('name', '[name]'),\n",
240
+ " ('version', '1.0')\n",
241
+ " ]))\n",
242
+ "])\n"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "markdown",
247
+ "metadata": {
248
+ "id": "h6F1FlM2Wb3l"
249
+ },
250
+ "source": [
251
+ "## Run it\n",
252
+ "\n",
253
+ "Below does all the magic. Check your folders to the left. Items will be in output/LoRA/your_name_v1 In the samples folder, there are preiodic sampled. This doesnt work great with colab. They will be in /content/output"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "metadata": {
260
+ "id": "HkajwI8gteOh"
261
+ },
262
+ "outputs": [],
263
+ "source": [
264
+ "run_job(job_to_run)\n"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "markdown",
269
+ "metadata": {
270
+ "id": "Hblgb5uwW5SD"
271
+ },
272
+ "source": [
273
+ "## Done\n",
274
+ "\n",
275
+ "Check your ourput dir and get your slider\n"
276
+ ]
277
+ }
278
+ ],
279
+ "metadata": {
280
+ "accelerator": "GPU",
281
+ "colab": {
282
+ "gpuType": "A100",
283
+ "machine_shape": "hm",
284
+ "provenance": []
285
+ },
286
+ "kernelspec": {
287
+ "display_name": "Python 3",
288
+ "name": "python3"
289
+ },
290
+ "language_info": {
291
+ "name": "python"
292
+ }
293
+ },
294
+ "nbformat": 4,
295
+ "nbformat_minor": 0
296
+ }
notebooks/SliderTraining.ipynb ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "machine_shape": "hm",
8
+ "gpuType": "V100"
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "source": [
23
+ "# AI Toolkit by Ostris\n",
24
+ "## Slider Training\n",
25
+ "\n",
26
+ "This is a quick colab demo for training sliders like can be found in my CivitAI profile https://civitai.com/user/Ostris/models . I will work on making it more user friendly, but for now, it will get you started."
27
+ ],
28
+ "metadata": {
29
+ "collapsed": false
30
+ }
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "source": [
35
+ "!git clone https://github.com/ostris/ai-toolkit"
36
+ ],
37
+ "metadata": {
38
+ "id": "BvAG0GKAh59G"
39
+ },
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": null,
46
+ "metadata": {
47
+ "id": "XGZqVER_aQJW"
48
+ },
49
+ "outputs": [],
50
+ "source": [
51
+ "!cd ai-toolkit && git submodule update --init --recursive && pip install -r requirements.txt\n"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "source": [
57
+ "import os\n",
58
+ "import sys\n",
59
+ "sys.path.append('/content/ai-toolkit')\n",
60
+ "from toolkit.job import run_job\n",
61
+ "from collections import OrderedDict\n",
62
+ "from PIL import Image"
63
+ ],
64
+ "metadata": {
65
+ "collapsed": false
66
+ },
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "markdown",
71
+ "source": [
72
+ "## Setup\n",
73
+ "\n",
74
+ "This is your config. It is documented pretty well. Normally you would do this as a yaml file, but for colab, this will work. This will run as is without modification, but feel free to edit as you want."
75
+ ],
76
+ "metadata": {
77
+ "id": "N8UUFzVRigbC"
78
+ }
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "source": [
83
+ "from collections import OrderedDict\n",
84
+ "\n",
85
+ "job_to_run = OrderedDict({\n",
86
+ " # This is the config I use on my sliders, It is solid and tested\n",
87
+ " 'job': 'train',\n",
88
+ " 'config': {\n",
89
+ " # the name will be used to create a folder in the output folder\n",
90
+ " # it will also replace any [name] token in the rest of this config\n",
91
+ " 'name': 'detail_slider_v1',\n",
92
+ " # folder will be created with name above in folder below\n",
93
+ " # it can be relative to the project root or absolute\n",
94
+ " 'training_folder': \"output/LoRA\",\n",
95
+ " 'device': 'cuda', # cpu, cuda:0, etc\n",
96
+ " # for tensorboard logging, we will make a subfolder for this job\n",
97
+ " 'log_dir': \"output/.tensorboard\",\n",
98
+ " # you can stack processes for other jobs, It is not tested with sliders though\n",
99
+ " # just use one for now\n",
100
+ " 'process': [\n",
101
+ " {\n",
102
+ " 'type': 'slider', # tells runner to run the slider process\n",
103
+ " # network is the LoRA network for a slider, I recommend to leave this be\n",
104
+ " 'network': {\n",
105
+ " 'type': \"lora\",\n",
106
+ " # rank / dim of the network. Bigger is not always better. Especially for sliders. 8 is good\n",
107
+ " 'linear': 8, # \"rank\" or \"dim\"\n",
108
+ " 'linear_alpha': 4, # Do about half of rank \"alpha\"\n",
109
+ " # 'conv': 4, # for convolutional layers \"locon\"\n",
110
+ " # 'conv_alpha': 4, # Do about half of conv \"alpha\"\n",
111
+ " },\n",
112
+ " # training config\n",
113
+ " 'train': {\n",
114
+ " # this is also used in sampling. Stick with ddpm unless you know what you are doing\n",
115
+ " 'noise_scheduler': \"ddpm\", # or \"ddpm\", \"lms\", \"euler_a\"\n",
116
+ " # how many steps to train. More is not always better. I rarely go over 1000\n",
117
+ " 'steps': 100,\n",
118
+ " # I have had good results with 4e-4 to 1e-4 at 500 steps\n",
119
+ " 'lr': 2e-4,\n",
120
+ " # enables gradient checkpoint, saves vram, leave it on\n",
121
+ " 'gradient_checkpointing': True,\n",
122
+ " # train the unet. I recommend leaving this true\n",
123
+ " 'train_unet': True,\n",
124
+ " # train the text encoder. I don't recommend this unless you have a special use case\n",
125
+ " # for sliders we are adjusting representation of the concept (unet),\n",
126
+ " # not the description of it (text encoder)\n",
127
+ " 'train_text_encoder': False,\n",
128
+ "\n",
129
+ " # just leave unless you know what you are doing\n",
130
+ " # also supports \"dadaptation\" but set lr to 1 if you use that,\n",
131
+ " # but it learns too fast and I don't recommend it\n",
132
+ " 'optimizer': \"adamw\",\n",
133
+ " # only constant for now\n",
134
+ " 'lr_scheduler': \"constant\",\n",
135
+ " # we randomly denoise random num of steps form 1 to this number\n",
136
+ " # while training. Just leave it\n",
137
+ " 'max_denoising_steps': 40,\n",
138
+ " # works great at 1. I do 1 even with my 4090.\n",
139
+ " # higher may not work right with newer single batch stacking code anyway\n",
140
+ " 'batch_size': 1,\n",
141
+ " # bf16 works best if your GPU supports it (modern)\n",
142
+ " 'dtype': 'bf16', # fp32, bf16, fp16\n",
143
+ " # I don't recommend using unless you are trying to make a darker lora. Then do 0.1 MAX\n",
144
+ " # although, the way we train sliders is comparative, so it probably won't work anyway\n",
145
+ " 'noise_offset': 0.0,\n",
146
+ " },\n",
147
+ "\n",
148
+ " # the model to train the LoRA network on\n",
149
+ " 'model': {\n",
150
+ " # name_or_path can be a hugging face name, local path or url to model\n",
151
+ " # on civit ai with or without modelVersionId. They will be cached in /model folder\n",
152
+ " # epicRealisim v5\n",
153
+ " 'name_or_path': \"https://civitai.com/models/25694?modelVersionId=134065\",\n",
154
+ " 'is_v2': False, # for v2 models\n",
155
+ " 'is_v_pred': False, # for v-prediction models (most v2 models)\n",
156
+ " # has some issues with the dual text encoder and the way we train sliders\n",
157
+ " # it works bit weights need to probably be higher to see it.\n",
158
+ " 'is_xl': False, # for SDXL models\n",
159
+ " },\n",
160
+ "\n",
161
+ " # saving config\n",
162
+ " 'save': {\n",
163
+ " 'dtype': 'float16', # precision to save. I recommend float16\n",
164
+ " 'save_every': 50, # save every this many steps\n",
165
+ " # this will remove step counts more than this number\n",
166
+ " # allows you to save more often in case of a crash without filling up your drive\n",
167
+ " 'max_step_saves_to_keep': 2,\n",
168
+ " },\n",
169
+ "\n",
170
+ " # sampling config\n",
171
+ " 'sample': {\n",
172
+ " # must match train.noise_scheduler, this is not used here\n",
173
+ " # but may be in future and in other processes\n",
174
+ " 'sampler': \"ddpm\",\n",
175
+ " # sample every this many steps\n",
176
+ " 'sample_every': 20,\n",
177
+ " # image size\n",
178
+ " 'width': 512,\n",
179
+ " 'height': 512,\n",
180
+ " # prompts to use for sampling. Do as many as you want, but it slows down training\n",
181
+ " # pick ones that will best represent the concept you are trying to adjust\n",
182
+ " # allows some flags after the prompt\n",
183
+ " # --m [number] # network multiplier. LoRA weight. -3 for the negative slide, 3 for the positive\n",
184
+ " # slide are good tests. will inherit sample.network_multiplier if not set\n",
185
+ " # --n [string] # negative prompt, will inherit sample.neg if not set\n",
186
+ " # Only 75 tokens allowed currently\n",
187
+ " # I like to do a wide positive and negative spread so I can see a good range and stop\n",
188
+ " # early if the network is braking down\n",
189
+ " 'prompts': [\n",
190
+ " \"a woman in a coffee shop, black hat, blonde hair, blue jacket --m -5\",\n",
191
+ " \"a woman in a coffee shop, black hat, blonde hair, blue jacket --m -3\",\n",
192
+ " \"a woman in a coffee shop, black hat, blonde hair, blue jacket --m 3\",\n",
193
+ " \"a woman in a coffee shop, black hat, blonde hair, blue jacket --m 5\",\n",
194
+ " \"a golden retriever sitting on a leather couch, --m -5\",\n",
195
+ " \"a golden retriever sitting on a leather couch --m -3\",\n",
196
+ " \"a golden retriever sitting on a leather couch --m 3\",\n",
197
+ " \"a golden retriever sitting on a leather couch --m 5\",\n",
198
+ " \"a man with a beard and red flannel shirt, wearing vr goggles, walking into traffic --m -5\",\n",
199
+ " \"a man with a beard and red flannel shirt, wearing vr goggles, walking into traffic --m -3\",\n",
200
+ " \"a man with a beard and red flannel shirt, wearing vr goggles, walking into traffic --m 3\",\n",
201
+ " \"a man with a beard and red flannel shirt, wearing vr goggles, walking into traffic --m 5\",\n",
202
+ " ],\n",
203
+ " # negative prompt used on all prompts above as default if they don't have one\n",
204
+ " 'neg': \"cartoon, fake, drawing, illustration, cgi, animated, anime, monochrome\",\n",
205
+ " # seed for sampling. 42 is the answer for everything\n",
206
+ " 'seed': 42,\n",
207
+ " # walks the seed so s1 is 42, s2 is 43, s3 is 44, etc\n",
208
+ " # will start over on next sample_every so s1 is always seed\n",
209
+ " # works well if you use same prompt but want different results\n",
210
+ " 'walk_seed': False,\n",
211
+ " # cfg scale (4 to 10 is good)\n",
212
+ " 'guidance_scale': 7,\n",
213
+ " # sampler steps (20 to 30 is good)\n",
214
+ " 'sample_steps': 20,\n",
215
+ " # default network multiplier for all prompts\n",
216
+ " # since we are training a slider, I recommend overriding this with --m [number]\n",
217
+ " # in the prompts above to get both sides of the slider\n",
218
+ " 'network_multiplier': 1.0,\n",
219
+ " },\n",
220
+ "\n",
221
+ " # logging information\n",
222
+ " 'logging': {\n",
223
+ " 'log_every': 10, # log every this many steps\n",
224
+ " 'use_wandb': False, # not supported yet\n",
225
+ " 'verbose': False, # probably done need unless you are debugging\n",
226
+ " },\n",
227
+ "\n",
228
+ " # slider training config, best for last\n",
229
+ " 'slider': {\n",
230
+ " # resolutions to train on. [ width, height ]. This is less important for sliders\n",
231
+ " # as we are not teaching the model anything it doesn't already know\n",
232
+ " # but must be a size it understands [ 512, 512 ] for sd_v1.5 and [ 768, 768 ] for sd_v2.1\n",
233
+ " # and [ 1024, 1024 ] for sd_xl\n",
234
+ " # you can do as many as you want here\n",
235
+ " 'resolutions': [\n",
236
+ " [512, 512],\n",
237
+ " # [ 512, 768 ]\n",
238
+ " # [ 768, 768 ]\n",
239
+ " ],\n",
240
+ " # slider training uses 4 combined steps for a single round. This will do it in one gradient\n",
241
+ " # step. It is highly optimized and shouldn't take anymore vram than doing without it,\n",
242
+ " # since we break down batches for gradient accumulation now. so just leave it on.\n",
243
+ " 'batch_full_slide': True,\n",
244
+ " # These are the concepts to train on. You can do as many as you want here,\n",
245
+ " # but they can conflict outweigh each other. Other than experimenting, I recommend\n",
246
+ " # just doing one for good results\n",
247
+ " 'targets': [\n",
248
+ " # target_class is the base concept we are adjusting the representation of\n",
249
+ " # for example, if we are adjusting the representation of a person, we would use \"person\"\n",
250
+ " # if we are adjusting the representation of a cat, we would use \"cat\" It is not\n",
251
+ " # a keyword necessarily but what the model understands the concept to represent.\n",
252
+ " # \"person\" will affect men, women, children, etc but will not affect cats, dogs, etc\n",
253
+ " # it is the models base general understanding of the concept and everything it represents\n",
254
+ " # you can leave it blank to affect everything. In this example, we are adjusting\n",
255
+ " # detail, so we will leave it blank to affect everything\n",
256
+ " {\n",
257
+ " 'target_class': \"\",\n",
258
+ " # positive is the prompt for the positive side of the slider.\n",
259
+ " # It is the concept that will be excited and amplified in the model when we slide the slider\n",
260
+ " # to the positive side and forgotten / inverted when we slide\n",
261
+ " # the slider to the negative side. It is generally best to include the target_class in\n",
262
+ " # the prompt. You want it to be the extreme of what you want to train on. For example,\n",
263
+ " # if you want to train on fat people, you would use \"an extremely fat, morbidly obese person\"\n",
264
+ " # as the prompt. Not just \"fat person\"\n",
265
+ " # max 75 tokens for now\n",
266
+ " 'positive': \"high detail, 8k, intricate, detailed, high resolution, high res, high quality\",\n",
267
+ " # negative is the prompt for the negative side of the slider and works the same as positive\n",
268
+ " # it does not necessarily work the same as a negative prompt when generating images\n",
269
+ " # these need to be polar opposites.\n",
270
+ " # max 76 tokens for now\n",
271
+ " 'negative': \"blurry, boring, fuzzy, low detail, low resolution, low res, low quality\",\n",
272
+ " # the loss for this target is multiplied by this number.\n",
273
+ " # if you are doing more than one target it may be good to set less important ones\n",
274
+ " # to a lower number like 0.1 so they don't outweigh the primary target\n",
275
+ " 'weight': 1.0,\n",
276
+ " },\n",
277
+ " ],\n",
278
+ " },\n",
279
+ " },\n",
280
+ " ]\n",
281
+ " },\n",
282
+ "\n",
283
+ " # You can put any information you want here, and it will be saved in the model.\n",
284
+ " # The below is an example, but you can put your grocery list in it if you want.\n",
285
+ " # It is saved in the model so be aware of that. The software will include this\n",
286
+ " # plus some other information for you automatically\n",
287
+ " 'meta': {\n",
288
+ " # [name] gets replaced with the name above\n",
289
+ " 'name': \"[name]\",\n",
290
+ " 'version': '1.0',\n",
291
+ " # 'creator': {\n",
292
+ " # 'name': 'your name',\n",
293
+ " # 'email': 'your@gmail.com',\n",
294
+ " # 'website': 'https://your.website'\n",
295
+ " # }\n",
296
+ " }\n",
297
+ "})\n"
298
+ ],
299
+ "metadata": {
300
+ "id": "_t28QURYjRQO"
301
+ },
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "markdown",
307
+ "source": [
308
+ "## Run it\n",
309
+ "\n",
310
+ "Below does all the magic. Check your folders to the left. Items will be in output/LoRA/your_name_v1 In the samples folder, there are preiodic sampled. This doesnt work great with colab. Ill update soon."
311
+ ],
312
+ "metadata": {
313
+ "id": "h6F1FlM2Wb3l"
314
+ }
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "source": [
319
+ "run_job(job_to_run)\n"
320
+ ],
321
+ "metadata": {
322
+ "id": "HkajwI8gteOh"
323
+ },
324
+ "execution_count": null,
325
+ "outputs": []
326
+ },
327
+ {
328
+ "cell_type": "markdown",
329
+ "source": [
330
+ "## Done\n",
331
+ "\n",
332
+ "Check your ourput dir and get your slider\n"
333
+ ],
334
+ "metadata": {
335
+ "id": "Hblgb5uwW5SD"
336
+ }
337
+ }
338
+ ]
339
+ }
scripts/caption_audio_dataset.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Caption audio files for ACE-Step v1.5 training.
4
+
5
+ Produces .txt files containing all training metadata:
6
+ - caption (from acestep-captioner)
7
+ - lyrics (from acestep-transcriber)
8
+ - bpm, keyscale, timesignature (from librosa)
9
+ - duration, language
10
+
11
+ Requirements:
12
+ pip install torch torchaudio transformers librosa numpy
13
+
14
+ Usage:
15
+ python caption_dir.py input_dir/
16
+ python caption_dir.py input_dir/ --low_vram --skip_existing
17
+ """
18
+
19
+ import argparse
20
+ import gc
21
+ import os
22
+ import glob
23
+ import logging
24
+ import warnings
25
+
26
+ import librosa
27
+ import numpy as np
28
+ import torch
29
+ import torchaudio
30
+ from tqdm import tqdm
31
+ from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
32
+
33
+ warnings.filterwarnings("ignore")
34
+ logging.disable(logging.WARNING)
35
+
36
+ TARGET_SAMPLE_RATE = 16000
37
+ CAPTIONER_ID = "ACE-Step/acestep-captioner"
38
+ TRANSCRIBER_ID = "ACE-Step/acestep-transcriber"
39
+
40
+ # Key profiles for Krumhansl-Schmuckler key detection
41
+ MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
42
+ MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
43
+ KEY_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
44
+
45
+
46
+ def get_audio_files(input_dir):
47
+ extensions = ["*.wav", "*.mp3", "*.flac", "*.ogg", "*.WAV", "*.MP3", "*.FLAC"]
48
+ files = []
49
+ for ext in extensions:
50
+ files.extend(glob.glob(os.path.join(input_dir, ext)))
51
+ return sorted(set(files))
52
+
53
+
54
+ def load_audio_mono_16k(audio_path):
55
+ waveform, sr = torchaudio.load(audio_path)
56
+ if waveform.shape[0] > 1:
57
+ waveform = waveform.mean(dim=0, keepdim=True)
58
+ if sr != TARGET_SAMPLE_RATE:
59
+ waveform = torchaudio.functional.resample(waveform, sr, TARGET_SAMPLE_RATE)
60
+ return waveform.squeeze(0).numpy(), TARGET_SAMPLE_RATE
61
+
62
+
63
+ # ═══════════════════════════════════════════════════════════════════════════════
64
+ # Audio analysis (BPM, key, time signature) via librosa
65
+ # ═══════════════════════════════════════════════════════════════════════════════
66
+
67
+ def analyze_audio(audio_path):
68
+ """Extract BPM, key, and time signature from audio using librosa."""
69
+ y, sr = librosa.load(audio_path, sr=22050, mono=True)
70
+ duration = librosa.get_duration(y=y, sr=sr)
71
+
72
+ # BPM
73
+ tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
74
+ if hasattr(tempo, '__len__'):
75
+ tempo = tempo[0]
76
+ bpm = int(round(float(tempo)))
77
+
78
+ # Key detection via chroma correlation with key profiles
79
+ chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
80
+ chroma_avg = chroma.mean(axis=1)
81
+ major_corrs = np.array([np.corrcoef(np.roll(MAJOR_PROFILE, i), chroma_avg)[0, 1] for i in range(12)])
82
+ minor_corrs = np.array([np.corrcoef(np.roll(MINOR_PROFILE, i), chroma_avg)[0, 1] for i in range(12)])
83
+
84
+ best_major_idx = major_corrs.argmax()
85
+ best_minor_idx = minor_corrs.argmax()
86
+ if major_corrs[best_major_idx] >= minor_corrs[best_minor_idx]:
87
+ keyscale = f"{KEY_NAMES[best_major_idx]} major"
88
+ else:
89
+ keyscale = f"{KEY_NAMES[best_minor_idx]} minor"
90
+
91
+ # Time signature estimation from beat strength pattern
92
+ onset_env = librosa.onset.onset_strength(y=y, sr=sr)
93
+ tempo_est, beats = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr)
94
+ if len(beats) >= 8:
95
+ beat_strengths = onset_env[beats]
96
+ # Check 3/4 vs 4/4 by looking at periodicity of strong beats
97
+ acf = np.correlate(beat_strengths - beat_strengths.mean(),
98
+ beat_strengths - beat_strengths.mean(), mode='full')
99
+ acf = acf[len(acf) // 2:]
100
+ if len(acf) > 6:
101
+ # Look at autocorrelation peaks at lag 3 vs lag 4
102
+ score_3 = acf[3] if len(acf) > 3 else 0
103
+ score_4 = acf[4] if len(acf) > 4 else 0
104
+ timesig = "3" if score_3 > score_4 * 1.2 else "4"
105
+ else:
106
+ timesig = "4"
107
+ else:
108
+ timesig = "4"
109
+
110
+ return {
111
+ "bpm": bpm,
112
+ "keyscale": keyscale,
113
+ "timesignature": timesig,
114
+ "duration": int(round(duration)),
115
+ }
116
+
117
+
118
+ # ═══════════════════════════════════════════════════════════════════════════════
119
+ # Model management
120
+ # ═══════════════════════════════════════════════════════════════════════════════
121
+
122
+ def offload_to_cpu(model):
123
+ """Move model to CPU and free GPU memory."""
124
+ if model is not None:
125
+ model.to("cpu")
126
+ gc.collect()
127
+ if torch.cuda.is_available():
128
+ torch.cuda.empty_cache()
129
+
130
+
131
+ def load_qwen_model(model_id, device="cuda", dtype=torch.bfloat16):
132
+ """Load a Qwen2.5-Omni model."""
133
+ model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
134
+ model_id, torch_dtype=dtype, device_map=device,
135
+ )
136
+ model.disable_talker()
137
+ processor = Qwen2_5OmniProcessor.from_pretrained(model_id)
138
+ return model, processor
139
+
140
+
141
+ def run_qwen_audio(model, processor, audio_data, sr, prompt_text):
142
+ """Run a Qwen2.5-Omni model on audio with a text prompt."""
143
+ conversation = [
144
+ {
145
+ "role": "user",
146
+ "content": [
147
+ {"type": "audio", "audio": "<|audio_bos|><|AUDIO|><|audio_eos|>"},
148
+ {"type": "text", "text": prompt_text},
149
+ ],
150
+ }
151
+ ]
152
+ text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
153
+ inputs = processor(
154
+ text=text, audio=[audio_data], images=None, videos=None,
155
+ return_tensors="pt", padding=True, sampling_rate=sr,
156
+ )
157
+ inputs = inputs.to(model.device).to(model.dtype)
158
+ text_ids = model.generate(**inputs, return_audio=False)
159
+ output = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
160
+ result = output[0]
161
+ marker = "assistant\n"
162
+ if marker in result:
163
+ result = result[result.rfind(marker) + len(marker):]
164
+ return result.strip()
165
+
166
+
167
+ # ═══════════════════════════════════════════════════════════════════════════════
168
+ # Output formatting
169
+ # ═══════════════════════════════════════════════════════════════════════════════
170
+
171
+ def format_output(caption, lyrics, analysis, language="en"):
172
+ """Format all metadata into tagged format for easy parsing."""
173
+ return (
174
+ f"<CAPTION>\n{caption}\n</CAPTION>\n"
175
+ f"<LYRICS>\n{lyrics}\n</LYRICS>\n"
176
+ f"<BPM>{analysis['bpm']}</BPM>\n"
177
+ f"<KEYSCALE>{analysis['keyscale']}</KEYSCALE>\n"
178
+ f"<TIMESIGNATURE>{analysis['timesignature']}</TIMESIGNATURE>\n"
179
+ f"<DURATION>{analysis['duration']}</DURATION>\n"
180
+ f"<LANGUAGE>{language}</LANGUAGE>"
181
+ )
182
+
183
+
184
+ def parse_caption_file(path):
185
+ """Parse a tagged caption file back into a dict."""
186
+ import re
187
+ text = open(path, "r", encoding="utf-8").read()
188
+ def tag(name):
189
+ m = re.search(rf"<{name}>(.*?)</{name}>", text, re.DOTALL)
190
+ return m.group(1).strip() if m else ""
191
+ return {
192
+ "caption": tag("CAPTION"),
193
+ "lyrics": tag("LYRICS"),
194
+ "bpm": tag("BPM"),
195
+ "keyscale": tag("KEYSCALE"),
196
+ "timesignature": tag("TIMESIGNATURE"),
197
+ "duration": tag("DURATION"),
198
+ "language": tag("LANGUAGE"),
199
+ }
200
+
201
+
202
+ # ═══════════════════════════════════════════════════════════════════════════════
203
+ # Main
204
+ # ═══════════════════════════════════════════════════════════════════════════════
205
+
206
+ def main():
207
+ parser = argparse.ArgumentParser(description="Caption audio files for ACE-Step training")
208
+ parser.add_argument("input_dir", type=str, help="Directory containing audio files")
209
+ parser.add_argument("--skip_existing", action="store_true", help="Skip files that already have captions")
210
+ parser.add_argument("--low_vram", action="store_true", help="Offload models to CPU between stages")
211
+ parser.add_argument("--language", default="en", help="Default language code (default: en)")
212
+ args = parser.parse_args()
213
+
214
+ if not os.path.isdir(args.input_dir):
215
+ print(f"Error: {args.input_dir} is not a valid directory")
216
+ return
217
+
218
+ audio_files = get_audio_files(args.input_dir)
219
+ if not audio_files:
220
+ print("No audio files found in the directory")
221
+ return
222
+
223
+ print(f"Found {len(audio_files)} audio files")
224
+
225
+ # ── Stage 1: Audio analysis (BPM, key, time sig) — no GPU needed ─────
226
+ print("\n[Stage 1/3] Analyzing audio (BPM, key, time signature)...")
227
+ analyses = {}
228
+ for audio_path in tqdm(audio_files, desc="Analyzing"):
229
+ base_name = os.path.splitext(audio_path)[0]
230
+ if args.skip_existing and os.path.exists(base_name + ".txt"):
231
+ continue
232
+ try:
233
+ analyses[audio_path] = analyze_audio(audio_path)
234
+ except Exception as e:
235
+ print(f"\n Error analyzing {os.path.basename(audio_path)}: {e}")
236
+ analyses[audio_path] = {"bpm": 120, "keyscale": "C major", "timesignature": "4",
237
+ "duration": 30}
238
+
239
+ # Filter to only files that need processing
240
+ files_to_process = [f for f in audio_files if f in analyses]
241
+ if not files_to_process:
242
+ print("All files already captioned (use without --skip_existing to overwrite)")
243
+ return
244
+
245
+ # ── Stage 2: Captioning ──────────────────────────────────────────────
246
+ print(f"\n[Stage 2/3] Captioning {len(files_to_process)} files...")
247
+ print(" Loading captioner model...")
248
+ captioner, cap_processor = load_qwen_model(CAPTIONER_ID)
249
+
250
+ captions = {}
251
+ for audio_path in tqdm(files_to_process, desc="Captioning"):
252
+ try:
253
+ audio_data, sr = load_audio_mono_16k(audio_path)
254
+ caption = run_qwen_audio(
255
+ captioner, cap_processor, audio_data, sr,
256
+ "*Task* Describe this music in detail. Include genre, mood, instrumentation, tempo feel, and vocal style if present."
257
+ )
258
+ captions[audio_path] = caption
259
+ except Exception as e:
260
+ print(f"\n Error captioning {os.path.basename(audio_path)}: {e}")
261
+ captions[audio_path] = ""
262
+
263
+ if args.low_vram:
264
+ print(" Offloading captioner to CPU...")
265
+ offload_to_cpu(captioner)
266
+ del captioner, cap_processor
267
+
268
+ # ── Stage 3: Lyrics transcription ────────────────────────────────────
269
+ print(f"\n[Stage 3/3] Transcribing lyrics for {len(files_to_process)} files...")
270
+ print(" Loading transcriber model...")
271
+ transcriber, trans_processor = load_qwen_model(TRANSCRIBER_ID)
272
+
273
+ lyrics_map = {}
274
+ for audio_path in tqdm(files_to_process, desc="Transcribing"):
275
+ try:
276
+ audio_data, sr = load_audio_mono_16k(audio_path)
277
+ lyrics = run_qwen_audio(
278
+ transcriber, trans_processor, audio_data, sr,
279
+ "*Task* Transcribe this audio in detail"
280
+ )
281
+ lyrics_map[audio_path] = lyrics
282
+ except Exception as e:
283
+ print(f"\n Error transcribing {os.path.basename(audio_path)}: {e}")
284
+ lyrics_map[audio_path] = "[Instrumental]"
285
+
286
+ if args.low_vram:
287
+ print(" Offloading transcriber to CPU...")
288
+ offload_to_cpu(transcriber)
289
+ del transcriber, trans_processor
290
+
291
+ # ── Write output files ───────────────────────────────────────────────
292
+ print("\nWriting output files...")
293
+ for audio_path in files_to_process:
294
+ base_name = os.path.splitext(audio_path)[0]
295
+ output_path = base_name + ".txt"
296
+
297
+ caption = captions.get(audio_path, "")
298
+ lyrics = lyrics_map.get(audio_path, "[Instrumental]")
299
+ analysis = analyses[audio_path]
300
+
301
+ output = format_output(caption, lyrics, analysis, args.language)
302
+ with open(output_path, "w", encoding="utf-8") as f:
303
+ f.write(output)
304
+
305
+ print(f"Done! Processed {len(files_to_process)} files.")
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
scripts/convert_cog.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections import OrderedDict
3
+ import os
4
+ import torch
5
+ from safetensors import safe_open
6
+ from safetensors.torch import save_file
7
+
8
+ device = torch.device('cpu')
9
+
10
+ # [diffusers] -> kohya
11
+ embedding_mapping = {
12
+ 'text_encoders_0': 'clip_l',
13
+ 'text_encoders_1': 'clip_g'
14
+ }
15
+
16
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ KEYMAP_ROOT = os.path.join(PROJECT_ROOT, 'toolkit', 'keymaps')
18
+ sdxl_keymap_path = os.path.join(KEYMAP_ROOT, 'stable_diffusion_locon_sdxl.json')
19
+
20
+ # load keymap
21
+ with open(sdxl_keymap_path, 'r') as f:
22
+ ldm_diffusers_keymap = json.load(f)['ldm_diffusers_keymap']
23
+
24
+ # invert the item / key pairs
25
+ diffusers_ldm_keymap = {v: k for k, v in ldm_diffusers_keymap.items()}
26
+
27
+
28
+ def get_ldm_key(diffuser_key):
29
+ diffuser_key = f"lora_unet_{diffuser_key.replace('.', '_')}"
30
+ diffuser_key = diffuser_key.replace('_lora_down_weight', '.lora_down.weight')
31
+ diffuser_key = diffuser_key.replace('_lora_up_weight', '.lora_up.weight')
32
+ diffuser_key = diffuser_key.replace('_alpha', '.alpha')
33
+ diffuser_key = diffuser_key.replace('_processor_to_', '_to_')
34
+ diffuser_key = diffuser_key.replace('_to_out.', '_to_out_0.')
35
+ if diffuser_key in diffusers_ldm_keymap:
36
+ return diffusers_ldm_keymap[diffuser_key]
37
+ else:
38
+ raise KeyError(f"Key {diffuser_key} not found in keymap")
39
+
40
+
41
+ def convert_cog(lora_path, embedding_path):
42
+ embedding_state_dict = OrderedDict()
43
+ lora_state_dict = OrderedDict()
44
+
45
+ # # normal dict
46
+ # normal_dict = OrderedDict()
47
+ # example_path = "/mnt/Models/stable-diffusion/models/LoRA/sdxl/LogoRedmond_LogoRedAF.safetensors"
48
+ # with safe_open(example_path, framework="pt", device='cpu') as f:
49
+ # keys = list(f.keys())
50
+ # for key in keys:
51
+ # normal_dict[key] = f.get_tensor(key)
52
+
53
+ with safe_open(embedding_path, framework="pt", device='cpu') as f:
54
+ keys = list(f.keys())
55
+ for key in keys:
56
+ new_key = embedding_mapping[key]
57
+ embedding_state_dict[new_key] = f.get_tensor(key)
58
+
59
+ with safe_open(lora_path, framework="pt", device='cpu') as f:
60
+ keys = list(f.keys())
61
+ lora_rank = None
62
+
63
+ # get the lora dim first. Check first 3 linear layers just to be safe
64
+ for key in keys:
65
+ new_key = get_ldm_key(key)
66
+ tensor = f.get_tensor(key)
67
+ num_checked = 0
68
+ if len(tensor.shape) == 2:
69
+ this_dim = min(tensor.shape)
70
+ if lora_rank is None:
71
+ lora_rank = this_dim
72
+ elif lora_rank != this_dim:
73
+ raise ValueError(f"lora rank is not consistent, got {tensor.shape}")
74
+ else:
75
+ num_checked += 1
76
+ if num_checked >= 3:
77
+ break
78
+
79
+ for key in keys:
80
+ new_key = get_ldm_key(key)
81
+ tensor = f.get_tensor(key)
82
+ if new_key.endswith('.lora_down.weight'):
83
+ alpha_key = new_key.replace('.lora_down.weight', '.alpha')
84
+ # diffusers does not have alpha, they usa an alpha multiplier of 1 which is a tensor weight of the dims
85
+ # assume first smallest dim is the lora rank if shape is 2
86
+ lora_state_dict[alpha_key] = torch.ones(1).to(tensor.device, tensor.dtype) * lora_rank
87
+
88
+ lora_state_dict[new_key] = tensor
89
+
90
+ return lora_state_dict, embedding_state_dict
91
+
92
+
93
+ if __name__ == "__main__":
94
+ import argparse
95
+
96
+ parser = argparse.ArgumentParser()
97
+ parser.add_argument(
98
+ 'lora_path',
99
+ type=str,
100
+ help='Path to lora file'
101
+ )
102
+ parser.add_argument(
103
+ 'embedding_path',
104
+ type=str,
105
+ help='Path to embedding file'
106
+ )
107
+
108
+ parser.add_argument(
109
+ '--lora_output',
110
+ type=str,
111
+ default="lora_output",
112
+ )
113
+
114
+ parser.add_argument(
115
+ '--embedding_output',
116
+ type=str,
117
+ default="embedding_output",
118
+ )
119
+
120
+ args = parser.parse_args()
121
+
122
+ lora_state_dict, embedding_state_dict = convert_cog(args.lora_path, args.embedding_path)
123
+
124
+ # save them
125
+ save_file(lora_state_dict, args.lora_output)
126
+ save_file(embedding_state_dict, args.embedding_output)
127
+ print(f"Saved lora to {args.lora_output}")
128
+ print(f"Saved embedding to {args.embedding_output}")
scripts/convert_lora_to_peft_format.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # currently only works with flux as support is not quite there yet
2
+
3
+ import argparse
4
+ import os.path
5
+ from collections import OrderedDict
6
+
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument(
9
+ 'input_path',
10
+ type=str,
11
+ help='Path to original sdxl model'
12
+ )
13
+ parser.add_argument(
14
+ 'output_path',
15
+ type=str,
16
+ help='output path'
17
+ )
18
+ args = parser.parse_args()
19
+ args.input_path = os.path.abspath(args.input_path)
20
+ args.output_path = os.path.abspath(args.output_path)
21
+
22
+ from safetensors.torch import load_file, save_file
23
+
24
+ meta = OrderedDict()
25
+ meta['format'] = 'pt'
26
+
27
+ state_dict = load_file(args.input_path)
28
+
29
+ # peft doesnt have an alpha so we need to scale the weights
30
+ alpha_keys = [
31
+ 'lora_transformer_single_transformer_blocks_0_attn_to_q.alpha' # flux
32
+ ]
33
+
34
+ # keys where the rank is in the first dimension
35
+ rank_idx0_keys = [
36
+ 'lora_transformer_single_transformer_blocks_0_attn_to_q.lora_down.weight'
37
+ # 'transformer.single_transformer_blocks.0.attn.to_q.lora_A.weight'
38
+ ]
39
+
40
+ alpha = None
41
+ rank = None
42
+
43
+ for key in rank_idx0_keys:
44
+ if key in state_dict:
45
+ rank = int(state_dict[key].shape[0])
46
+ break
47
+
48
+ if rank is None:
49
+ raise ValueError(f'Could not find rank in state dict')
50
+
51
+ for key in alpha_keys:
52
+ if key in state_dict:
53
+ alpha = int(state_dict[key])
54
+ break
55
+
56
+ if alpha is None:
57
+ # set to rank if not found
58
+ alpha = rank
59
+
60
+
61
+ up_multiplier = alpha / rank
62
+
63
+ new_state_dict = {}
64
+
65
+ for key, value in state_dict.items():
66
+ if key.endswith('.alpha'):
67
+ continue
68
+
69
+ orig_dtype = value.dtype
70
+
71
+ new_val = value.float() * up_multiplier
72
+
73
+ new_key = key
74
+ new_key = new_key.replace('lora_transformer_', 'transformer.')
75
+ for i in range(100):
76
+ new_key = new_key.replace(f'transformer_blocks_{i}_', f'transformer_blocks.{i}.')
77
+ new_key = new_key.replace('lora_down', 'lora_A')
78
+ new_key = new_key.replace('lora_up', 'lora_B')
79
+ new_key = new_key.replace('_lora', '.lora')
80
+ new_key = new_key.replace('attn_', 'attn.')
81
+ new_key = new_key.replace('ff_', 'ff.')
82
+ new_key = new_key.replace('context_net_', 'context.net.')
83
+ new_key = new_key.replace('0_proj', '0.proj')
84
+ new_key = new_key.replace('norm_linear', 'norm.linear')
85
+ new_key = new_key.replace('norm_out_linear', 'norm_out.linear')
86
+ new_key = new_key.replace('to_out_', 'to_out.')
87
+
88
+ new_state_dict[new_key] = new_val.to(orig_dtype)
89
+
90
+ save_file(new_state_dict, args.output_path, meta)
91
+ print(f'Saved to {args.output_path}')
scripts/generate_sampler_step_scales.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import os
4
+ from diffusers import StableDiffusionPipeline
5
+ import sys
6
+
7
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8
+ # add project root to path
9
+ sys.path.append(PROJECT_ROOT)
10
+
11
+ SAMPLER_SCALES_ROOT = os.path.join(PROJECT_ROOT, 'toolkit', 'samplers_scales')
12
+
13
+
14
+ parser = argparse.ArgumentParser(description='Process some images.')
15
+ add_arg = parser.add_argument
16
+ add_arg('--model', type=str, required=True, help='Path to model')
17
+ add_arg('--sampler', type=str, required=True, help='Name of sampler')
18
+
19
+ args = parser.parse_args()
20
+
scripts/make_diffusers_model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from collections import OrderedDict
3
+ import sys
4
+ import os
5
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
6
+ sys.path.append(ROOT_DIR)
7
+
8
+ import torch
9
+
10
+ from toolkit.config_modules import ModelConfig
11
+ from toolkit.stable_diffusion_model import StableDiffusion
12
+
13
+
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument(
16
+ 'input_path',
17
+ type=str,
18
+ help='Path to original sdxl model'
19
+ )
20
+ parser.add_argument(
21
+ 'output_path',
22
+ type=str,
23
+ help='output path'
24
+ )
25
+ parser.add_argument('--sdxl', action='store_true', help='is sdxl model')
26
+ parser.add_argument('--refiner', action='store_true', help='is refiner model')
27
+ parser.add_argument('--ssd', action='store_true', help='is ssd model')
28
+ parser.add_argument('--sd2', action='store_true', help='is sd 2 model')
29
+
30
+ args = parser.parse_args()
31
+ device = torch.device('cpu')
32
+ dtype = torch.float32
33
+
34
+ print(f"Loading model from {args.input_path}")
35
+
36
+
37
+ diffusers_model_config = ModelConfig(
38
+ name_or_path=args.input_path,
39
+ is_xl=args.sdxl,
40
+ is_v2=args.sd2,
41
+ is_ssd=args.ssd,
42
+ dtype=dtype,
43
+ )
44
+ diffusers_sd = StableDiffusion(
45
+ model_config=diffusers_model_config,
46
+ device=device,
47
+ dtype=dtype,
48
+ )
49
+ diffusers_sd.load_model()
50
+
51
+
52
+ print(f"Loaded model from {args.input_path}")
53
+
54
+ diffusers_sd.pipeline.fuse_lora()
55
+
56
+ meta = OrderedDict()
57
+
58
+ diffusers_sd.save(args.output_path, meta=meta)
59
+
60
+
61
+ print(f"Saved to {args.output_path}")
scripts/patch_te_adapter.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from safetensors.torch import save_file, load_file
3
+ from collections import OrderedDict
4
+ meta = OrderedDict()
5
+ meta["format"] ="pt"
6
+
7
+ attn_dict = load_file("/mnt/Train/out/ip_adapter/sd15_bigG/sd15_bigG_000266000.safetensors")
8
+ state_dict = load_file("/home/jaret/Dev/models/hf/OstrisDiffusionV1/unet/diffusion_pytorch_model.safetensors")
9
+
10
+ attn_list = []
11
+ for key, value in state_dict.items():
12
+ if "attn1" in key:
13
+ attn_list.append(key)
14
+
15
+ attn_names = ['down_blocks.0.attentions.0.transformer_blocks.0.attn2.processor', 'down_blocks.0.attentions.1.transformer_blocks.0.attn2.processor', 'down_blocks.1.attentions.0.transformer_blocks.0.attn2.processor', 'down_blocks.1.attentions.1.transformer_blocks.0.attn2.processor', 'down_blocks.2.attentions.0.transformer_blocks.0.attn2.processor', 'down_blocks.2.attentions.1.transformer_blocks.0.attn2.processor', 'up_blocks.1.attentions.0.transformer_blocks.0.attn2.processor', 'up_blocks.1.attentions.1.transformer_blocks.0.attn2.processor', 'up_blocks.1.attentions.2.transformer_blocks.0.attn2.processor', 'up_blocks.2.attentions.0.transformer_blocks.0.attn2.processor', 'up_blocks.2.attentions.1.transformer_blocks.0.attn2.processor', 'up_blocks.2.attentions.2.transformer_blocks.0.attn2.processor', 'up_blocks.3.attentions.0.transformer_blocks.0.attn2.processor', 'up_blocks.3.attentions.1.transformer_blocks.0.attn2.processor', 'up_blocks.3.attentions.2.transformer_blocks.0.attn2.processor', 'mid_block.attentions.0.transformer_blocks.0.attn2.processor']
16
+
17
+ adapter_names = []
18
+ for i in range(100):
19
+ if f'te_adapter.adapter_modules.{i}.to_k_adapter.weight' in attn_dict:
20
+ adapter_names.append(f"te_adapter.adapter_modules.{i}.adapter")
21
+
22
+
23
+ for i in range(len(adapter_names)):
24
+ adapter_name = adapter_names[i]
25
+ attn_name = attn_names[i]
26
+ adapter_k_name = adapter_name[:-8] + '.to_k_adapter.weight'
27
+ adapter_v_name = adapter_name[:-8] + '.to_v_adapter.weight'
28
+ state_k_name = attn_name.replace(".processor", ".to_k.weight")
29
+ state_v_name = attn_name.replace(".processor", ".to_v.weight")
30
+ if adapter_k_name in attn_dict:
31
+ state_dict[state_k_name] = attn_dict[adapter_k_name]
32
+ state_dict[state_v_name] = attn_dict[adapter_v_name]
33
+ else:
34
+ print("adapter_k_name", adapter_k_name)
35
+ print("state_k_name", state_k_name)
36
+
37
+ for key, value in state_dict.items():
38
+ state_dict[key] = value.cpu().to(torch.float16)
39
+
40
+ save_file(state_dict, "/home/jaret/Dev/models/hf/OstrisDiffusionV1/unet/diffusion_pytorch_model.safetensors", metadata=meta)
41
+
42
+ print("Done")
scripts/repair_dataset_folder.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from PIL import Image
3
+ from PIL.ImageOps import exif_transpose
4
+ from tqdm import tqdm
5
+ import os
6
+
7
+ parser = argparse.ArgumentParser(description='Process some images.')
8
+ parser.add_argument("input_folder", type=str, help="Path to folder containing images")
9
+
10
+ args = parser.parse_args()
11
+
12
+ img_types = ['.jpg', '.jpeg', '.png', '.webp']
13
+
14
+ # find all images in the input folder
15
+ images = []
16
+ for root, _, files in os.walk(args.input_folder):
17
+ for file in files:
18
+ if file.lower().endswith(tuple(img_types)):
19
+ images.append(os.path.join(root, file))
20
+ print(f"Found {len(images)} images")
21
+
22
+ num_skipped = 0
23
+ num_repaired = 0
24
+ num_deleted = 0
25
+
26
+ pbar = tqdm(total=len(images), desc=f"Repaired {num_repaired} images", unit="image")
27
+ for img_path in images:
28
+ filename = os.path.basename(img_path)
29
+ filename_no_ext, file_extension = os.path.splitext(filename)
30
+ # if it is jpg, ignore
31
+ if file_extension.lower() == '.jpg':
32
+ num_skipped += 1
33
+ pbar.update(1)
34
+
35
+ continue
36
+
37
+ try:
38
+ img = Image.open(img_path)
39
+ except Exception as e:
40
+ print(f"Error opening {img_path}: {e}")
41
+ # delete it
42
+ os.remove(img_path)
43
+ num_deleted += 1
44
+ pbar.update(1)
45
+ pbar.set_description(f"Repaired {num_repaired} images, Skipped {num_skipped}, Deleted {num_deleted}")
46
+ continue
47
+
48
+
49
+ try:
50
+ img = exif_transpose(img)
51
+ except Exception as e:
52
+ print(f"Error rotating {img_path}: {e}")
53
+
54
+ new_path = os.path.join(os.path.dirname(img_path), filename_no_ext + '.jpg')
55
+
56
+ img = img.convert("RGB")
57
+ img.save(new_path, quality=95)
58
+ # remove the old file
59
+ os.remove(img_path)
60
+ num_repaired += 1
61
+ pbar.update(1)
62
+ # update pbar
63
+ pbar.set_description(f"Repaired {num_repaired} images, Skipped {num_skipped}, Deleted {num_deleted}")
64
+
65
+ print("Done")
scripts/update_sponsors.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+ from datetime import datetime
5
+ from dotenv import load_dotenv
6
+
7
+ # Load environment variables from .env file
8
+ env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env")
9
+ load_dotenv(dotenv_path=env_path)
10
+
11
+ # API credentials
12
+ PATREON_TOKEN = os.getenv("PATREON_ACCESS_TOKEN")
13
+ GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
14
+ GITHUB_USERNAME = os.getenv("GITHUB_USERNAME")
15
+ GITHUB_ORG = os.getenv("GITHUB_ORG") # Organization name (optional)
16
+
17
+ # Output file
18
+ README_PATH = "SUPPORTERS.md"
19
+
20
+ def fetch_patreon_supporters():
21
+ """Fetch current Patreon supporters"""
22
+ print("Fetching Patreon supporters...")
23
+
24
+ headers = {
25
+ "Authorization": f"Bearer {PATREON_TOKEN}",
26
+ "Content-Type": "application/json"
27
+ }
28
+
29
+ url = "https://www.patreon.com/api/oauth2/v2/campaigns"
30
+
31
+ try:
32
+ # First get the campaign ID
33
+ campaign_response = requests.get(url, headers=headers)
34
+ campaign_response.raise_for_status()
35
+ campaign_data = campaign_response.json()
36
+
37
+ if not campaign_data.get('data'):
38
+ print("No campaigns found for this Patreon account")
39
+ return []
40
+
41
+ campaign_id = campaign_data['data'][0]['id']
42
+
43
+ # Now get the supporters for this campaign
44
+ members_url = f"https://www.patreon.com/api/oauth2/v2/campaigns/{campaign_id}/members"
45
+ params = {
46
+ "include": "user",
47
+ "fields[member]": "full_name,is_follower,patron_status", # Removed profile_url
48
+ "fields[user]": "image_url"
49
+ }
50
+
51
+ supporters = []
52
+ while members_url:
53
+ members_response = requests.get(members_url, headers=headers, params=params)
54
+ members_response.raise_for_status()
55
+ members_data = members_response.json()
56
+
57
+ # Process the response to extract active patrons
58
+ for member in members_data.get('data', []):
59
+ attributes = member.get('attributes', {})
60
+
61
+ # Only include active patrons
62
+ if attributes.get('patron_status') == 'active_patron':
63
+ name = attributes.get('full_name', 'Anonymous Supporter')
64
+
65
+ # Get user data which contains the profile image
66
+ user_id = member.get('relationships', {}).get('user', {}).get('data', {}).get('id')
67
+ profile_image = None
68
+ profile_url = None # Removed profile_url since it's not supported
69
+
70
+ if user_id:
71
+ for included in members_data.get('included', []):
72
+ if included.get('id') == user_id and included.get('type') == 'user':
73
+ profile_image = included.get('attributes', {}).get('image_url')
74
+ break
75
+
76
+ supporters.append({
77
+ 'name': name,
78
+ 'profile_image': profile_image,
79
+ 'profile_url': profile_url, # This will be None
80
+ 'platform': 'Patreon',
81
+ 'amount': 0 # Placeholder, as Patreon API doesn't provide this in the current response
82
+ })
83
+
84
+ # Handle pagination
85
+ members_url = members_data.get('links', {}).get('next')
86
+
87
+ print(f"Found {len(supporters)} active Patreon supporters")
88
+ return supporters
89
+
90
+ except requests.exceptions.RequestException as e:
91
+ print(f"Error fetching Patreon data: {e}")
92
+ print(f"Response content: {e.response.content if hasattr(e, 'response') else 'No response content'}")
93
+ return []
94
+
95
+ def fetch_github_sponsors():
96
+ """Fetch current GitHub sponsors for a user or organization"""
97
+ print("Fetching GitHub sponsors...")
98
+
99
+ headers = {
100
+ "Authorization": f"Bearer {GITHUB_TOKEN}",
101
+ "Accept": "application/vnd.github.v3+json"
102
+ }
103
+
104
+ # Determine if we're fetching for a user or an organization
105
+ entity_type = "organization" if GITHUB_ORG else "user"
106
+ entity_name = GITHUB_ORG if GITHUB_ORG else GITHUB_USERNAME
107
+
108
+ if not entity_name:
109
+ print("Error: Neither GITHUB_USERNAME nor GITHUB_ORG is set")
110
+ return []
111
+
112
+ # Different GraphQL query structure based on entity type
113
+ if entity_type == "user":
114
+ query = """
115
+ query {
116
+ user(login: "%s") {
117
+ sponsorshipsAsMaintainer(first: 100) {
118
+ nodes {
119
+ sponsorEntity {
120
+ ... on User {
121
+ login
122
+ name
123
+ avatarUrl
124
+ url
125
+ }
126
+ ... on Organization {
127
+ login
128
+ name
129
+ avatarUrl
130
+ url
131
+ }
132
+ }
133
+ tier {
134
+ monthlyPriceInDollars
135
+ }
136
+ isOneTimePayment
137
+ isActive
138
+ }
139
+ }
140
+ }
141
+ }
142
+ """ % entity_name
143
+ else: # organization
144
+ query = """
145
+ query {
146
+ organization(login: "%s") {
147
+ sponsorshipsAsMaintainer(first: 100) {
148
+ nodes {
149
+ sponsorEntity {
150
+ ... on User {
151
+ login
152
+ name
153
+ avatarUrl
154
+ url
155
+ }
156
+ ... on Organization {
157
+ login
158
+ name
159
+ avatarUrl
160
+ url
161
+ }
162
+ }
163
+ tier {
164
+ monthlyPriceInDollars
165
+ }
166
+ isOneTimePayment
167
+ isActive
168
+ }
169
+ }
170
+ }
171
+ }
172
+ """ % entity_name
173
+
174
+ try:
175
+ response = requests.post(
176
+ "https://api.github.com/graphql",
177
+ headers=headers,
178
+ json={"query": query}
179
+ )
180
+ response.raise_for_status()
181
+ data = response.json()
182
+
183
+ # Process the response - the path to the data differs based on entity type
184
+ if entity_type == "user":
185
+ sponsors_data = data.get('data', {}).get('user', {}).get('sponsorshipsAsMaintainer', {}).get('nodes', [])
186
+ else:
187
+ sponsors_data = data.get('data', {}).get('organization', {}).get('sponsorshipsAsMaintainer', {}).get('nodes', [])
188
+
189
+ sponsors = []
190
+ for sponsor in sponsors_data:
191
+ # Only include active sponsors
192
+ if sponsor.get('isActive'):
193
+ entity = sponsor.get('sponsorEntity', {})
194
+ name = entity.get('name') or entity.get('login', 'Anonymous Sponsor')
195
+ profile_image = entity.get('avatarUrl')
196
+ profile_url = entity.get('url')
197
+ amount = sponsor.get('tier', {}).get('monthlyPriceInDollars', 0)
198
+
199
+ sponsors.append({
200
+ 'name': name,
201
+ 'profile_image': profile_image,
202
+ 'profile_url': profile_url,
203
+ 'platform': 'GitHub Sponsors',
204
+ 'amount': amount
205
+ })
206
+
207
+ print(f"Found {len(sponsors)} active GitHub sponsors for {entity_type} '{entity_name}'")
208
+ return sponsors
209
+
210
+ except requests.exceptions.RequestException as e:
211
+ print(f"Error fetching GitHub sponsors data: {e}")
212
+ return []
213
+
214
+ def generate_readme(supporters):
215
+ """Generate a README.md file with supporter information"""
216
+ print(f"Generating {README_PATH}...")
217
+
218
+ # Sort supporters by amount (descending) and then by name
219
+ supporters.sort(key=lambda x: (-x['amount'], x['name'].lower()))
220
+
221
+ # Determine the proper footer links based on what's configured
222
+ github_entity = GITHUB_ORG if GITHUB_ORG else GITHUB_USERNAME
223
+ github_entity_type = "orgs" if GITHUB_ORG else "sponsors"
224
+ github_sponsor_url = f"https://github.com/{github_entity_type}/{github_entity}"
225
+
226
+ with open(README_PATH, "w", encoding="utf-8") as f:
227
+ f.write("## Support My Work\n\n")
228
+ f.write("If you enjoy my work, or use it for commercial purposes, please consider sponsoring me so I can continue to maintain it. Every bit helps! \n\n")
229
+ # Create appropriate call-to-action based on what's configured
230
+ cta_parts = []
231
+ if github_entity:
232
+ cta_parts.append(f"[Become a sponsor on GitHub]({github_sponsor_url})")
233
+ if PATREON_TOKEN:
234
+ cta_parts.append("[support me on Patreon](https://www.patreon.com/ostris)")
235
+
236
+ if cta_parts:
237
+ if GITHUB_ORG:
238
+ f.write(f"{' or '.join(cta_parts)}.\n\n")
239
+ f.write("Thank you to all my current supporters!\n\n")
240
+
241
+ f.write(f"_Last updated: {datetime.now().strftime('%Y-%m-%d')}_\n\n")
242
+
243
+ # Write GitHub Sponsors section
244
+ github_sponsors = [s for s in supporters if s['platform'] == 'GitHub Sponsors']
245
+ if github_sponsors:
246
+ f.write("### GitHub Sponsors\n\n")
247
+ for sponsor in github_sponsors:
248
+ if sponsor['profile_image']:
249
+ f.write(f"<a href=\"{sponsor['profile_url']}\" title=\"{sponsor['name']}\"><img src=\"{sponsor['profile_image']}\" width=\"50\" height=\"50\" alt=\"{sponsor['name']}\" style=\"border-radius:50%;display:inline-block;\"></a> ")
250
+ else:
251
+ f.write(f"[{sponsor['name']}]({sponsor['profile_url']}) ")
252
+ f.write("\n\n")
253
+
254
+ # Write Patreon section
255
+ patreon_supporters = [s for s in supporters if s['platform'] == 'Patreon']
256
+ if patreon_supporters:
257
+ f.write("### Patreon Supporters\n\n")
258
+ for supporter in patreon_supporters:
259
+ if supporter['profile_image']:
260
+ f.write(f"<a href=\"{supporter['profile_url']}\" title=\"{supporter['name']}\"><img src=\"{supporter['profile_image']}\" width=\"50\" height=\"50\" alt=\"{supporter['name']}\" style=\"border-radius:50%;display:inline-block;\"></a> ")
261
+ else:
262
+ f.write(f"[{supporter['name']}]({supporter['profile_url']}) ")
263
+ f.write("\n\n")
264
+
265
+ f.write("\n---\n\n")
266
+
267
+
268
+ print(f"Successfully generated {README_PATH} with {len(supporters)} supporters!")
269
+
270
+ def main():
271
+ """Main function"""
272
+ print("Starting supporter data collection...")
273
+
274
+ # Check if required environment variables are set
275
+ missing_vars = []
276
+ if not GITHUB_TOKEN:
277
+ missing_vars.append("GITHUB_TOKEN")
278
+
279
+ # Either username or org is required for GitHub
280
+ if not GITHUB_USERNAME and not GITHUB_ORG:
281
+ missing_vars.append("GITHUB_USERNAME or GITHUB_ORG")
282
+
283
+ # Patreon token is optional but warn if missing
284
+ patreon_enabled = bool(PATREON_TOKEN)
285
+
286
+ if missing_vars:
287
+ print(f"Error: Missing required environment variables: {', '.join(missing_vars)}")
288
+ print("Please add them to your .env file")
289
+ return
290
+
291
+ if not patreon_enabled:
292
+ print("Warning: PATREON_ACCESS_TOKEN not set. Will only fetch GitHub sponsors.")
293
+
294
+ # Fetch data from both platforms
295
+ patreon_supporters = fetch_patreon_supporters() if PATREON_TOKEN else []
296
+ github_sponsors = fetch_github_sponsors()
297
+
298
+ # Combine supporters from both platforms
299
+ all_supporters = patreon_supporters + github_sponsors
300
+
301
+ if not all_supporters:
302
+ print("No supporters found on either platform")
303
+ return
304
+
305
+ # Generate README
306
+ generate_readme(all_supporters)
307
+
308
+ if __name__ == "__main__":
309
+ main()
toolkit/__init__.py ADDED
File without changes
toolkit/accelerator.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from accelerate import Accelerator
2
+ from diffusers.utils.torch_utils import is_compiled_module
3
+
4
+ global_accelerator = None
5
+
6
+
7
+ def get_accelerator() -> Accelerator:
8
+ global global_accelerator
9
+ if global_accelerator is None:
10
+ global_accelerator = Accelerator()
11
+ return global_accelerator
12
+
13
+ def unwrap_model(model):
14
+ try:
15
+ accelerator = get_accelerator()
16
+ model = accelerator.unwrap_model(model)
17
+ model = model._orig_mod if is_compiled_module(model) else model
18
+ except Exception as e:
19
+ pass
20
+ return model
toolkit/advanced_prompt_embeds.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from safetensors.torch import load_file, save_file
4
+
5
+
6
+ class AdvancedPromptEmbeds:
7
+ """
8
+ Flexible container for prompt embedding tensors.
9
+
10
+ Each value passed in must be a list of tensors, where each item in the
11
+ list corresponds to a single item in the batch (list length == batch size).
12
+ Do not store more than one tensor per batch item under the same key — if
13
+ you need multiple tensors per batch item, give them different key names.
14
+
15
+ Usage:
16
+ pe = AdvancedPromptEmbeds(
17
+ prompt_embeds=[t0, t1, t2], # one tensor per batch item
18
+ pooled_embeds=[p0, p1, p2],
19
+ )
20
+
21
+ pe.prompt_embeds # -> [t0, t1, t2]
22
+ pe['prompt_embeds'] # -> [t0, t1, t2]
23
+ pe.keys() # -> ['prompt_embeds', 'pooled_embeds']
24
+
25
+ # add more after init
26
+ pe.extra = [e0, e1, e2]
27
+ pe['extra2'] = [e0, e1, e2]
28
+ pe.set('extra3', [e0, e1, e2])
29
+ pe.update(extra4=[e0, e1, e2])
30
+ """
31
+
32
+ def __init__(self, **kwargs):
33
+ self._store = {}
34
+ self._frozen_dtype_keys = []
35
+ for key, value in kwargs.items():
36
+ if not isinstance(value, list):
37
+ value = [value]
38
+ self._store[key] = value
39
+
40
+ @property
41
+ def frozen_dtype_keys(self):
42
+ return self._frozen_dtype_keys
43
+
44
+ @frozen_dtype_keys.setter
45
+ def frozen_dtype_keys(self, keys):
46
+ self._frozen_dtype_keys = list(keys) if keys else []
47
+
48
+ def __getattr__(self, name):
49
+ if name.startswith("_"):
50
+ raise AttributeError(name)
51
+ store = self.__dict__.get("_store", {})
52
+ if name in store:
53
+ return store[name]
54
+ raise AttributeError(f"{type(self).__name__!s} has no attribute {name!r}")
55
+
56
+ def __setattr__(self, name, value):
57
+ if name.startswith("_"):
58
+ super().__setattr__(name, value)
59
+ return
60
+ cls_attr = getattr(type(self), name, None)
61
+ if isinstance(cls_attr, property):
62
+ super().__setattr__(name, value)
63
+ return
64
+ if not isinstance(value, list):
65
+ value = [value]
66
+ self._store[name] = value
67
+
68
+ def set(self, key, value):
69
+ if not isinstance(value, list):
70
+ value = [value]
71
+ self._store[key] = value
72
+
73
+ def update(self, **kwargs):
74
+ for key, value in kwargs.items():
75
+ if not isinstance(value, list):
76
+ value = [value]
77
+ self._store[key] = value
78
+
79
+ def keys(self):
80
+ return list(self._store.keys())
81
+
82
+ def __getitem__(self, key):
83
+ return self._store[key]
84
+
85
+ def __setitem__(self, key, value):
86
+ if not isinstance(value, list):
87
+ value = [value]
88
+ self._store[key] = value
89
+
90
+ def __contains__(self, key):
91
+ return key in self._store
92
+
93
+ def to(self, *args, **kwargs):
94
+ frozen = set(self._frozen_dtype_keys)
95
+ if frozen:
96
+ no_dtype_args = [a for a in args if not isinstance(a, torch.dtype)]
97
+ no_dtype_kwargs = {k: v for k, v in kwargs.items() if k != "dtype"}
98
+ new_pe = AdvancedPromptEmbeds()
99
+ new_pe._frozen_dtype_keys = list(self._frozen_dtype_keys)
100
+ for key, value in self._store.items():
101
+ if key in frozen:
102
+ new_pe._store[key] = [
103
+ v.to(*no_dtype_args, **no_dtype_kwargs) for v in value
104
+ ]
105
+ else:
106
+ new_pe._store[key] = [v.to(*args, **kwargs) for v in value]
107
+ return new_pe
108
+
109
+ def detach(self):
110
+ new_pe = AdvancedPromptEmbeds()
111
+ new_pe._frozen_dtype_keys = list(self._frozen_dtype_keys)
112
+ for key, value in self._store.items():
113
+ new_pe._store[key] = [v.detach() for v in value]
114
+ return new_pe
115
+
116
+ def clone(self):
117
+ new_pe = AdvancedPromptEmbeds()
118
+ new_pe._frozen_dtype_keys = list(self._frozen_dtype_keys)
119
+ for key, value in self._store.items():
120
+ new_pe._store[key] = [v.clone() for v in value]
121
+ return new_pe
122
+
123
+ def expand_to_batch(self, batch_size):
124
+ new_pe = AdvancedPromptEmbeds()
125
+ new_pe._frozen_dtype_keys = list(self._frozen_dtype_keys)
126
+ for key, value in self._store.items():
127
+ if len(value) == 1:
128
+ new_pe._store[key] = value * batch_size
129
+ elif len(value) == batch_size:
130
+ new_pe._store[key] = value
131
+ else:
132
+ raise ValueError(
133
+ f"Cannot expand key {key!r}: expected list of length 1 or {batch_size}, got {len(value)}"
134
+ )
135
+ return new_pe
136
+
137
+ def save(self, path):
138
+ data = {}
139
+ metadata = {"class_name": self.__class__.__name__}
140
+ for key, value in self._store.items():
141
+ if len(value) != 1:
142
+ raise ValueError(
143
+ f"Cannot save key {key!r}: expected list of length 1, got {len(value)}"
144
+ )
145
+ data[key] = value[0]
146
+ os.makedirs(os.path.dirname(path), exist_ok=True)
147
+ save_file(data, path, metadata=metadata)
148
+
149
+ @classmethod
150
+ def load(cls, path=None):
151
+ if path is not None:
152
+ loaded = load_file(path)
153
+ else:
154
+ raise ValueError("Must provide a path")
155
+
156
+ data = {}
157
+ for key in loaded.keys():
158
+ data[key] = loaded[key]
159
+
160
+ return cls(**data)
161
+
162
+ @classmethod
163
+ def concat_prompt_embeds(
164
+ cls, prompt_embeds: list["AdvancedPromptEmbeds"], padding_side: str = "right"
165
+ ):
166
+ embeds = {}
167
+ frozen = []
168
+ for pe in prompt_embeds:
169
+ for key in pe.keys():
170
+ if key not in embeds:
171
+ embeds[key] = []
172
+ embeds[key].extend(pe[key])
173
+ for k in pe.frozen_dtype_keys:
174
+ if k not in frozen:
175
+ frozen.append(k)
176
+ out = cls(**embeds)
177
+ out.frozen_dtype_keys = frozen
178
+ return out
179
+
180
+ @classmethod
181
+ def split_prompt_embeds(cls, concatenated: "AdvancedPromptEmbeds", num_parts=None):
182
+ if num_parts is None:
183
+ # use length of first item as num_parts
184
+ num_parts = len(concatenated[concatenated.keys()[0]])
185
+ split_embeds = [cls() for _ in range(num_parts)]
186
+ for pe in split_embeds:
187
+ pe.frozen_dtype_keys = list(concatenated.frozen_dtype_keys)
188
+ for key in concatenated.keys():
189
+ values = concatenated[key]
190
+ if len(values) != num_parts:
191
+ raise ValueError(
192
+ f"Cannot split key {key!r}: expected list of length {num_parts}, got {len(values)}"
193
+ )
194
+ for i in range(num_parts):
195
+ split_embeds[i]._store[key] = [values[i]]
toolkit/assistant_lora.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+ from toolkit.config_modules import NetworkConfig
3
+ from toolkit.lora_special import LoRASpecialNetwork
4
+ from safetensors.torch import load_file
5
+
6
+ if TYPE_CHECKING:
7
+ from toolkit.stable_diffusion_model import StableDiffusion
8
+
9
+
10
+ def load_assistant_lora_from_path(adapter_path, sd: 'StableDiffusion') -> LoRASpecialNetwork:
11
+ if not sd.is_flux:
12
+ raise ValueError("Only Flux models can load assistant adapters currently.")
13
+ pipe = sd.pipeline
14
+ print(f"Loading assistant adapter from {adapter_path}")
15
+ adapter_name = adapter_path.split("/")[-1].split(".")[0]
16
+ lora_state_dict = load_file(adapter_path)
17
+
18
+ linear_dim = int(lora_state_dict['transformer.single_transformer_blocks.0.attn.to_k.lora_A.weight'].shape[0])
19
+ # linear_alpha = int(lora_state_dict['lora_transformer_single_transformer_blocks_0_attn_to_k.alpha'].item())
20
+ linear_alpha = linear_dim
21
+ transformer_only = 'transformer.proj_out.alpha' not in lora_state_dict
22
+ # get dim and scale
23
+ network_config = NetworkConfig(
24
+ linear=linear_dim,
25
+ linear_alpha=linear_alpha,
26
+ transformer_only=transformer_only,
27
+ )
28
+
29
+ network = LoRASpecialNetwork(
30
+ text_encoder=pipe.text_encoder,
31
+ unet=pipe.transformer,
32
+ lora_dim=network_config.linear,
33
+ multiplier=1.0,
34
+ alpha=network_config.linear_alpha,
35
+ train_unet=True,
36
+ train_text_encoder=False,
37
+ is_flux=True,
38
+ network_config=network_config,
39
+ network_type=network_config.type,
40
+ transformer_only=network_config.transformer_only,
41
+ is_assistant_adapter=True
42
+ )
43
+ network.apply_to(
44
+ pipe.text_encoder,
45
+ pipe.transformer,
46
+ apply_text_encoder=False,
47
+ apply_unet=True
48
+ )
49
+ network.force_to(sd.device_torch, dtype=sd.torch_dtype)
50
+ network.eval()
51
+ network._update_torch_multiplier()
52
+ network.load_weights(lora_state_dict)
53
+ network.is_active = True
54
+
55
+ return network
toolkit/basic.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import os
3
+
4
+ import torch
5
+
6
+
7
+ def value_map(inputs, min_in, max_in, min_out, max_out):
8
+ return (inputs - min_in) * (max_out - min_out) / (max_in - min_in) + min_out
9
+
10
+
11
+ def flush(garbage_collect=True):
12
+ if torch.cuda.is_available():
13
+ torch.cuda.empty_cache()
14
+ # if is mps, also clear the mps cache
15
+ if torch.backends.mps.is_available():
16
+ torch.mps.empty_cache()
17
+ if garbage_collect:
18
+ gc.collect()
19
+
20
+
21
+ def get_mean_std(tensor):
22
+ if len(tensor.shape) == 3:
23
+ tensor = tensor.unsqueeze(0)
24
+ elif len(tensor.shape) != 4:
25
+ raise Exception("Expected tensor of shape (batch_size, channels, width, height)")
26
+ mean, variance = torch.mean(
27
+ tensor, dim=[2, 3], keepdim=True
28
+ ), torch.var(
29
+ tensor, dim=[2, 3],
30
+ keepdim=True
31
+ )
32
+ std = torch.sqrt(variance + 1e-5)
33
+ return mean, std
34
+
35
+
36
+ def adain(content_features, style_features):
37
+ # Assumes that the content and style features are of shape (batch_size, channels, width, height)
38
+
39
+ dims = [2, 3]
40
+ if len(content_features.shape) == 3:
41
+ # content_features = content_features.unsqueeze(0)
42
+ # style_features = style_features.unsqueeze(0)
43
+ dims = [1]
44
+
45
+ # Step 1: Calculate mean and variance of content features
46
+ content_mean, content_var = torch.mean(content_features, dim=dims, keepdim=True), torch.var(content_features,
47
+ dim=dims,
48
+ keepdim=True)
49
+ # Step 2: Calculate mean and variance of style features
50
+ style_mean, style_var = torch.mean(style_features, dim=dims, keepdim=True), torch.var(style_features, dim=dims,
51
+ keepdim=True)
52
+
53
+ # Step 3: Normalize content features
54
+ content_std = torch.sqrt(content_var + 1e-5)
55
+ normalized_content = (content_features - content_mean) / content_std
56
+
57
+ # Step 4: Scale and shift normalized content with style's statistics
58
+ style_std = torch.sqrt(style_var + 1e-5)
59
+ stylized_content = normalized_content * style_std + style_mean
60
+
61
+ return stylized_content
62
+
63
+ def get_quick_signature_string(file_path):
64
+ try:
65
+ file_stats = os.stat(file_path)
66
+ # Combine size and mtime into a single string
67
+ return f"{file_stats.st_size}:{int(file_stats.st_mtime)}"
68
+ except Exception as e:
69
+ print(f"Error accessing file {file_path}: {e}")
70
+ return None
toolkit/buckets.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Type, List, Union, TypedDict
2
+
3
+
4
+ class BucketResolution(TypedDict):
5
+ width: int
6
+ height: int
7
+
8
+
9
+ # resolutions SDXL was trained on with a 1024x1024 base resolution
10
+ resolutions_1024: List[BucketResolution] = [
11
+ # SDXL Base resolution
12
+ {"width": 1024, "height": 1024},
13
+ # SDXL Resolutions, widescreen
14
+ {"width": 2048, "height": 512},
15
+ {"width": 1984, "height": 512},
16
+ {"width": 1920, "height": 512},
17
+ {"width": 1856, "height": 512},
18
+ {"width": 1792, "height": 576},
19
+ {"width": 1728, "height": 576},
20
+ {"width": 1664, "height": 576},
21
+ {"width": 1600, "height": 640},
22
+ {"width": 1536, "height": 640},
23
+ {"width": 1472, "height": 704},
24
+ {"width": 1408, "height": 704},
25
+ {"width": 1344, "height": 704},
26
+ {"width": 1344, "height": 768},
27
+ {"width": 1280, "height": 768},
28
+ {"width": 1216, "height": 832},
29
+ {"width": 1152, "height": 832},
30
+ {"width": 1152, "height": 896},
31
+ {"width": 1088, "height": 896},
32
+ {"width": 1088, "height": 960},
33
+ {"width": 1024, "height": 960},
34
+ # SDXL Resolutions, portrait
35
+ {"width": 960, "height": 1024},
36
+ {"width": 960, "height": 1088},
37
+ {"width": 896, "height": 1088},
38
+ {"width": 896, "height": 1152}, # 2:3
39
+ {"width": 832, "height": 1152},
40
+ {"width": 832, "height": 1216},
41
+ {"width": 768, "height": 1280},
42
+ {"width": 768, "height": 1344},
43
+ {"width": 704, "height": 1408},
44
+ {"width": 704, "height": 1472},
45
+ {"width": 640, "height": 1536},
46
+ {"width": 640, "height": 1600},
47
+ {"width": 576, "height": 1664},
48
+ {"width": 576, "height": 1728},
49
+ {"width": 576, "height": 1792},
50
+ {"width": 512, "height": 1856},
51
+ {"width": 512, "height": 1920},
52
+ {"width": 512, "height": 1984},
53
+ {"width": 512, "height": 2048},
54
+ # extra wides
55
+ {"width": 8192, "height": 128},
56
+ {"width": 128, "height": 8192},
57
+ ]
58
+
59
+ def get_bucket_sizes(resolution: int = 512, divisibility: int = 8) -> List[BucketResolution]:
60
+ # determine scaler form 1024 to resolution
61
+ scaler = resolution / 1024
62
+
63
+ bucket_size_list = []
64
+ for bucket in resolutions_1024:
65
+ # must be divisible by 8
66
+ width = int(bucket["width"] * scaler)
67
+ height = int(bucket["height"] * scaler)
68
+ if width % divisibility != 0:
69
+ width = width - (width % divisibility)
70
+ if height % divisibility != 0:
71
+ height = height - (height % divisibility)
72
+ bucket_size_list.append({"width": width, "height": height})
73
+
74
+ return bucket_size_list
75
+
76
+
77
+ def get_resolution(width, height):
78
+ num_pixels = width * height
79
+ # determine same number of pixels for square image
80
+ square_resolution = int(num_pixels ** 0.5)
81
+ return square_resolution
82
+
83
+
84
+ def get_bucket_for_image_size(
85
+ width: int,
86
+ height: int,
87
+ bucket_size_list: List[BucketResolution] = None,
88
+ resolution: Union[int, None] = None,
89
+ divisibility: int = 8
90
+ ) -> BucketResolution:
91
+
92
+ if bucket_size_list is None and resolution is None:
93
+ # get resolution from width and height
94
+ resolution = get_resolution(width, height)
95
+ if bucket_size_list is None:
96
+ # if real resolution is smaller, use that instead
97
+ real_resolution = get_resolution(width, height)
98
+ resolution = min(resolution, real_resolution)
99
+ bucket_size_list = get_bucket_sizes(resolution=resolution, divisibility=divisibility)
100
+
101
+ # Check for exact match first
102
+ for bucket in bucket_size_list:
103
+ if bucket["width"] == width and bucket["height"] == height:
104
+ return bucket
105
+
106
+ # If exact match not found, find the closest bucket
107
+ closest_bucket = None
108
+ min_removed_pixels = float("inf")
109
+
110
+ for bucket in bucket_size_list:
111
+ scale_w = bucket["width"] / width
112
+ scale_h = bucket["height"] / height
113
+
114
+ # To minimize pixels, we use the larger scale factor to minimize the amount that has to be cropped.
115
+ scale = max(scale_w, scale_h)
116
+
117
+ new_width = int(width * scale)
118
+ new_height = int(height * scale)
119
+
120
+ removed_pixels = (new_width - bucket["width"]) * new_height + (new_height - bucket["height"]) * new_width
121
+
122
+ if removed_pixels < min_removed_pixels:
123
+ min_removed_pixels = removed_pixels
124
+ closest_bucket = bucket
125
+
126
+ if closest_bucket is None:
127
+ raise ValueError("No suitable bucket found")
128
+
129
+ return closest_bucket
toolkit/clip_vision_adapter.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Mapping, Any
2
+
3
+ import torch
4
+ import weakref
5
+
6
+ from toolkit.config_modules import AdapterConfig
7
+ from toolkit.models.clip_fusion import ZipperBlock
8
+ from toolkit.models.zipper_resampler import ZipperModule
9
+ from toolkit.prompt_utils import PromptEmbeds
10
+ from toolkit.train_tools import get_torch_dtype
11
+
12
+ if TYPE_CHECKING:
13
+ from toolkit.stable_diffusion_model import StableDiffusion
14
+
15
+ from transformers import (
16
+ CLIPImageProcessor,
17
+ CLIPVisionModelWithProjection,
18
+ CLIPVisionModel
19
+ )
20
+
21
+ from toolkit.resampler import Resampler
22
+
23
+ import torch.nn as nn
24
+
25
+
26
+ class Embedder(nn.Module):
27
+ def __init__(
28
+ self,
29
+ num_input_tokens: int = 1,
30
+ input_dim: int = 1024,
31
+ num_output_tokens: int = 8,
32
+ output_dim: int = 768,
33
+ mid_dim: int = 1024
34
+ ):
35
+ super(Embedder, self).__init__()
36
+ self.num_output_tokens = num_output_tokens
37
+ self.num_input_tokens = num_input_tokens
38
+ self.input_dim = input_dim
39
+ self.output_dim = output_dim
40
+
41
+ self.layer_norm = nn.LayerNorm(input_dim)
42
+ self.fc1 = nn.Linear(input_dim, mid_dim)
43
+ self.gelu = nn.GELU()
44
+ # self.fc2 = nn.Linear(mid_dim, mid_dim)
45
+ self.fc2 = nn.Linear(mid_dim, mid_dim)
46
+
47
+ self.fc2.weight.data.zero_()
48
+
49
+ self.layer_norm2 = nn.LayerNorm(mid_dim)
50
+ self.fc3 = nn.Linear(mid_dim, mid_dim)
51
+ self.gelu2 = nn.GELU()
52
+ self.fc4 = nn.Linear(mid_dim, output_dim * num_output_tokens)
53
+
54
+ # set the weights to 0
55
+ self.fc3.weight.data.zero_()
56
+ self.fc4.weight.data.zero_()
57
+
58
+
59
+ # self.static_tokens = nn.Parameter(torch.zeros(num_output_tokens, output_dim))
60
+ # self.scaler = nn.Parameter(torch.zeros(num_output_tokens, output_dim))
61
+
62
+ def forward(self, x):
63
+ if len(x.shape) == 2:
64
+ x = x.unsqueeze(1)
65
+ x = self.layer_norm(x)
66
+ x = self.fc1(x)
67
+ x = self.gelu(x)
68
+ x = self.fc2(x)
69
+ x = self.layer_norm2(x)
70
+ x = self.fc3(x)
71
+ x = self.gelu2(x)
72
+ x = self.fc4(x)
73
+
74
+ x = x.view(-1, self.num_output_tokens, self.output_dim)
75
+
76
+ return x
77
+
78
+
79
+ class ClipVisionAdapter(torch.nn.Module):
80
+ def __init__(self, sd: 'StableDiffusion', adapter_config: AdapterConfig):
81
+ super().__init__()
82
+ self.config = adapter_config
83
+ self.trigger = adapter_config.trigger
84
+ self.trigger_class_name = adapter_config.trigger_class_name
85
+ self.sd_ref: weakref.ref = weakref.ref(sd)
86
+ # embedding stuff
87
+ self.text_encoder_list = sd.text_encoder if isinstance(sd.text_encoder, list) else [sd.text_encoder]
88
+ self.tokenizer_list = sd.tokenizer if isinstance(sd.tokenizer, list) else [sd.tokenizer]
89
+ placeholder_tokens = [self.trigger]
90
+
91
+ # add dummy tokens for multi-vector
92
+ additional_tokens = []
93
+ for i in range(1, self.config.num_tokens):
94
+ additional_tokens.append(f"{self.trigger}_{i}")
95
+ placeholder_tokens += additional_tokens
96
+
97
+ # handle dual tokenizer
98
+ self.tokenizer_list = self.sd_ref().tokenizer if isinstance(self.sd_ref().tokenizer, list) else [
99
+ self.sd_ref().tokenizer]
100
+ self.text_encoder_list = self.sd_ref().text_encoder if isinstance(self.sd_ref().text_encoder, list) else [
101
+ self.sd_ref().text_encoder]
102
+
103
+ self.placeholder_token_ids = []
104
+ self.embedding_tokens = []
105
+
106
+ print(f"Adding {placeholder_tokens} tokens to tokenizer")
107
+ print(f"Adding {self.config.num_tokens} tokens to tokenizer")
108
+
109
+
110
+ for text_encoder, tokenizer in zip(self.text_encoder_list, self.tokenizer_list):
111
+ num_added_tokens = tokenizer.add_tokens(placeholder_tokens)
112
+ if num_added_tokens != self.config.num_tokens:
113
+ raise ValueError(
114
+ f"The tokenizer already contains the token {self.trigger}. Please pass a different"
115
+ f" `placeholder_token` that is not already in the tokenizer. Only added {num_added_tokens}"
116
+ )
117
+
118
+ # Convert the initializer_token, placeholder_token to ids
119
+ init_token_ids = tokenizer.encode(self.config.trigger_class_name, add_special_tokens=False)
120
+ # if length of token ids is more than number of orm embedding tokens fill with *
121
+ if len(init_token_ids) > self.config.num_tokens:
122
+ init_token_ids = init_token_ids[:self.config.num_tokens]
123
+ elif len(init_token_ids) < self.config.num_tokens:
124
+ pad_token_id = tokenizer.encode(["*"], add_special_tokens=False)
125
+ init_token_ids += pad_token_id * (self.config.num_tokens - len(init_token_ids))
126
+
127
+ placeholder_token_ids = tokenizer.encode(placeholder_tokens, add_special_tokens=False)
128
+ self.placeholder_token_ids.append(placeholder_token_ids)
129
+
130
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
131
+ text_encoder.resize_token_embeddings(len(tokenizer))
132
+
133
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
134
+ token_embeds = text_encoder.get_input_embeddings().weight.data
135
+ with torch.no_grad():
136
+ for initializer_token_id, token_id in zip(init_token_ids, placeholder_token_ids):
137
+ token_embeds[token_id] = token_embeds[initializer_token_id].clone()
138
+
139
+ # replace "[name] with this. on training. This is automatically generated in pipeline on inference
140
+ self.embedding_tokens.append(" ".join(tokenizer.convert_ids_to_tokens(placeholder_token_ids)))
141
+
142
+ # backup text encoder embeddings
143
+ self.orig_embeds_params = [x.get_input_embeddings().weight.data.clone() for x in self.text_encoder_list]
144
+
145
+ try:
146
+ self.clip_image_processor = CLIPImageProcessor.from_pretrained(self.config.image_encoder_path)
147
+ except EnvironmentError:
148
+ self.clip_image_processor = CLIPImageProcessor()
149
+ self.device = self.sd_ref().unet.device
150
+ self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(
151
+ self.config.image_encoder_path,
152
+ ignore_mismatched_sizes=True
153
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
154
+ if self.config.train_image_encoder:
155
+ self.image_encoder.train()
156
+ else:
157
+ self.image_encoder.eval()
158
+
159
+ # max_seq_len = CLIP tokens + CLS token
160
+ image_encoder_state_dict = self.image_encoder.state_dict()
161
+ in_tokens = 257
162
+ if "vision_model.embeddings.position_embedding.weight" in image_encoder_state_dict:
163
+ # clip
164
+ in_tokens = int(image_encoder_state_dict["vision_model.embeddings.position_embedding.weight"].shape[0])
165
+
166
+ if hasattr(self.image_encoder.config, 'hidden_sizes'):
167
+ embedding_dim = self.image_encoder.config.hidden_sizes[-1]
168
+ else:
169
+ embedding_dim = self.image_encoder.config.target_hidden_size
170
+
171
+ if self.config.clip_layer == 'image_embeds':
172
+ in_tokens = 1
173
+ embedding_dim = self.image_encoder.config.projection_dim
174
+
175
+ self.embedder = Embedder(
176
+ num_output_tokens=self.config.num_tokens,
177
+ num_input_tokens=in_tokens,
178
+ input_dim=embedding_dim,
179
+ output_dim=self.sd_ref().unet.config['cross_attention_dim'],
180
+ mid_dim=embedding_dim * self.config.num_tokens,
181
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
182
+
183
+ self.embedder.train()
184
+
185
+ def state_dict(self, *args, destination=None, prefix='', keep_vars=False):
186
+ state_dict = {
187
+ 'embedder': self.embedder.state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
188
+ }
189
+ if self.config.train_image_encoder:
190
+ state_dict['image_encoder'] = self.image_encoder.state_dict(
191
+ *args, destination=destination, prefix=prefix,
192
+ keep_vars=keep_vars)
193
+
194
+ return state_dict
195
+
196
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
197
+ self.embedder.load_state_dict(state_dict["embedder"], strict=strict)
198
+ if self.config.train_image_encoder and 'image_encoder' in state_dict:
199
+ self.image_encoder.load_state_dict(state_dict["image_encoder"], strict=strict)
200
+
201
+ def parameters(self, *args, **kwargs):
202
+ yield from self.embedder.parameters(*args, **kwargs)
203
+
204
+ def named_parameters(self, *args, **kwargs):
205
+ yield from self.embedder.named_parameters(*args, **kwargs)
206
+
207
+ def get_clip_image_embeds_from_tensors(
208
+ self, tensors_0_1: torch.Tensor, drop=False,
209
+ is_training=False,
210
+ has_been_preprocessed=False
211
+ ) -> torch.Tensor:
212
+ with torch.no_grad():
213
+ if not has_been_preprocessed:
214
+ # tensors should be 0-1
215
+ if tensors_0_1.ndim == 3:
216
+ tensors_0_1 = tensors_0_1.unsqueeze(0)
217
+ # training tensors are 0 - 1
218
+ tensors_0_1 = tensors_0_1.to(self.device, dtype=torch.float16)
219
+
220
+ # if images are out of this range throw error
221
+ if tensors_0_1.min() < -0.3 or tensors_0_1.max() > 1.3:
222
+ raise ValueError("image tensor values must be between 0 and 1. Got min: {}, max: {}".format(
223
+ tensors_0_1.min(), tensors_0_1.max()
224
+ ))
225
+ # unconditional
226
+ if drop:
227
+ if self.clip_noise_zero:
228
+ tensors_0_1 = torch.rand_like(tensors_0_1).detach()
229
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
230
+ dtype=get_torch_dtype(self.sd_ref().dtype))
231
+ tensors_0_1 = tensors_0_1 * noise_scale
232
+ else:
233
+ tensors_0_1 = torch.zeros_like(tensors_0_1).detach()
234
+ # tensors_0_1 = tensors_0_1 * 0
235
+ clip_image = self.clip_image_processor(
236
+ images=tensors_0_1,
237
+ return_tensors="pt",
238
+ do_resize=True,
239
+ do_rescale=False,
240
+ ).pixel_values
241
+ else:
242
+ if drop:
243
+ # scale the noise down
244
+ if self.clip_noise_zero:
245
+ tensors_0_1 = torch.rand_like(tensors_0_1).detach()
246
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
247
+ dtype=get_torch_dtype(self.sd_ref().dtype))
248
+ tensors_0_1 = tensors_0_1 * noise_scale
249
+ else:
250
+ tensors_0_1 = torch.zeros_like(tensors_0_1).detach()
251
+ # tensors_0_1 = tensors_0_1 * 0
252
+ mean = torch.tensor(self.clip_image_processor.image_mean).to(
253
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
254
+ ).detach()
255
+ std = torch.tensor(self.clip_image_processor.image_std).to(
256
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
257
+ ).detach()
258
+ tensors_0_1 = torch.clip((255. * tensors_0_1), 0, 255).round() / 255.0
259
+ clip_image = (tensors_0_1 - mean.view([1, 3, 1, 1])) / std.view([1, 3, 1, 1])
260
+
261
+ else:
262
+ clip_image = tensors_0_1
263
+ clip_image = clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype)).detach()
264
+ with torch.set_grad_enabled(is_training):
265
+ if is_training:
266
+ self.image_encoder.train()
267
+ else:
268
+ self.image_encoder.eval()
269
+ clip_output = self.image_encoder(clip_image, output_hidden_states=True)
270
+
271
+ if self.config.clip_layer == 'penultimate_hidden_states':
272
+ # they skip last layer for ip+
273
+ # https://github.com/tencent-ailab/IP-Adapter/blob/f4b6742db35ea6d81c7b829a55b0a312c7f5a677/tutorial_train_plus.py#L403C26-L403C26
274
+ clip_image_embeds = clip_output.hidden_states[-2]
275
+ elif self.config.clip_layer == 'last_hidden_state':
276
+ clip_image_embeds = clip_output.hidden_states[-1]
277
+ else:
278
+ clip_image_embeds = clip_output.image_embeds
279
+ return clip_image_embeds
280
+
281
+ import torch
282
+
283
+ def set_vec(self, new_vector, text_encoder_idx=0):
284
+ # Get the embedding layer
285
+ embedding_layer = self.text_encoder_list[text_encoder_idx].get_input_embeddings()
286
+
287
+ # Indices to replace in the embeddings
288
+ indices_to_replace = self.placeholder_token_ids[text_encoder_idx]
289
+
290
+ # Replace the specified embeddings with new_vector
291
+ for idx in indices_to_replace:
292
+ vector_idx = idx - indices_to_replace[0]
293
+ embedding_layer.weight[idx] = new_vector[vector_idx]
294
+
295
+ # adds it to the tokenizer
296
+ def forward(self, clip_image_embeds: torch.Tensor) -> PromptEmbeds:
297
+ clip_image_embeds = clip_image_embeds.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
298
+ if clip_image_embeds.ndim == 2:
299
+ # expand the token dimension
300
+ clip_image_embeds = clip_image_embeds.unsqueeze(1)
301
+ image_prompt_embeds = self.embedder(clip_image_embeds)
302
+ # todo add support for multiple batch sizes
303
+ if image_prompt_embeds.shape[0] != 1:
304
+ raise ValueError("Batch size must be 1 for embedder for now")
305
+
306
+ # output on sd1.5 is bs, num_tokens, 768
307
+ if len(self.text_encoder_list) == 1:
308
+ # add it to the text encoder
309
+ self.set_vec(image_prompt_embeds[0], text_encoder_idx=0)
310
+ elif len(self.text_encoder_list) == 2:
311
+ if self.text_encoder_list[0].config.target_hidden_size + self.text_encoder_list[1].config.target_hidden_size != \
312
+ image_prompt_embeds.shape[2]:
313
+ raise ValueError("Something went wrong. The embeddings do not match the text encoder sizes")
314
+ # sdxl variants
315
+ # image_prompt_embeds = 2048
316
+ # te1 = 768
317
+ # te2 = 1280
318
+ te1_embeds = image_prompt_embeds[:, :, :self.text_encoder_list[0].config.target_hidden_size]
319
+ te2_embeds = image_prompt_embeds[:, :, self.text_encoder_list[0].config.target_hidden_size:]
320
+ self.set_vec(te1_embeds[0], text_encoder_idx=0)
321
+ self.set_vec(te2_embeds[0], text_encoder_idx=1)
322
+ else:
323
+
324
+ raise ValueError("Unsupported number of text encoders")
325
+ # just a place to put a breakpoint
326
+ pass
327
+
328
+ def restore_embeddings(self):
329
+ # Let's make sure we don't update any embedding weights besides the newly added token
330
+ for text_encoder, tokenizer, orig_embeds, placeholder_token_ids in zip(
331
+ self.text_encoder_list,
332
+ self.tokenizer_list,
333
+ self.orig_embeds_params,
334
+ self.placeholder_token_ids
335
+ ):
336
+ index_no_updates = torch.ones((len(tokenizer),), dtype=torch.bool)
337
+ index_no_updates[
338
+ min(placeholder_token_ids): max(placeholder_token_ids) + 1] = False
339
+ with torch.no_grad():
340
+ text_encoder.get_input_embeddings().weight[
341
+ index_no_updates
342
+ ] = orig_embeds[index_no_updates]
343
+ # detach it all
344
+ text_encoder.get_input_embeddings().weight.detach_()
345
+
346
+ def enable_gradient_checkpointing(self):
347
+ self.image_encoder.gradient_checkpointing = True
348
+
349
+ def inject_trigger_into_prompt(self, prompt, expand_token=False, to_replace_list=None, add_if_not_present=True):
350
+ output_prompt = prompt
351
+ embedding_tokens = self.embedding_tokens[0] # shoudl be the same
352
+ default_replacements = ["[name]", "[trigger]"]
353
+
354
+ replace_with = embedding_tokens if expand_token else self.trigger
355
+ if to_replace_list is None:
356
+ to_replace_list = default_replacements
357
+ else:
358
+ to_replace_list += default_replacements
359
+
360
+ # remove duplicates
361
+ to_replace_list = list(set(to_replace_list))
362
+
363
+ # replace them all
364
+ for to_replace in to_replace_list:
365
+ # replace it
366
+ output_prompt = output_prompt.replace(to_replace, replace_with)
367
+
368
+ # see how many times replace_with is in the prompt
369
+ num_instances = output_prompt.count(replace_with)
370
+
371
+ if num_instances == 0 and add_if_not_present:
372
+ # add it to the beginning of the prompt
373
+ output_prompt = replace_with + " " + output_prompt
374
+
375
+ if num_instances > 1:
376
+ print(
377
+ f"Warning: {replace_with} token appears {num_instances} times in prompt {output_prompt}. This may cause issues.")
378
+
379
+ return output_prompt
380
+
381
+ # reverses injection with class name. useful for normalizations
382
+ def inject_trigger_class_name_into_prompt(self, prompt):
383
+ output_prompt = prompt
384
+ embedding_tokens = self.embedding_tokens[0] # shoudl be the same
385
+
386
+ default_replacements = ["[name]", "[trigger]", embedding_tokens, self.trigger]
387
+
388
+ replace_with = self.config.trigger_class_name
389
+ to_replace_list = default_replacements
390
+
391
+ # remove duplicates
392
+ to_replace_list = list(set(to_replace_list))
393
+
394
+ # replace them all
395
+ for to_replace in to_replace_list:
396
+ # replace it
397
+ output_prompt = output_prompt.replace(to_replace, replace_with)
398
+
399
+ # see how many times replace_with is in the prompt
400
+ num_instances = output_prompt.count(replace_with)
401
+
402
+ if num_instances > 1:
403
+ print(
404
+ f"Warning: {replace_with} token appears {num_instances} times in prompt {output_prompt}. This may cause issues.")
405
+
406
+ return output_prompt
toolkit/config.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from typing import Union
4
+
5
+ import oyaml as yaml
6
+ import re
7
+ from collections import OrderedDict
8
+
9
+ from toolkit.paths import TOOLKIT_ROOT
10
+
11
+ possible_extensions = ['.json', '.jsonc', '.yaml', '.yml']
12
+
13
+
14
+ def get_cwd_abs_path(path):
15
+ if not os.path.isabs(path):
16
+ path = os.path.join(os.getcwd(), path)
17
+ return path
18
+
19
+
20
+ def replace_env_vars_in_string(s: str) -> str:
21
+ """
22
+ Replace placeholders like ${VAR_NAME} with the value of the corresponding environment variable.
23
+ If the environment variable is not set, raise an error.
24
+ """
25
+
26
+ def replacer(match):
27
+ var_name = match.group(1)
28
+ value = os.environ.get(var_name)
29
+
30
+ if value is None:
31
+ raise ValueError(f"Environment variable {var_name} not set. Please ensure it's defined before proceeding.")
32
+
33
+ return value
34
+
35
+ return re.sub(r'\$\{([^}]+)\}', replacer, s)
36
+
37
+
38
+ def preprocess_config(config: OrderedDict, name: str = None):
39
+ if "job" not in config:
40
+ raise ValueError("config file must have a job key")
41
+ if "config" not in config:
42
+ raise ValueError("config file must have a config section")
43
+ if "name" not in config["config"] and name is None:
44
+ raise ValueError("config file must have a config.name key")
45
+ # we need to replace tags. For now just [name]
46
+ if name is None:
47
+ name = config["config"]["name"]
48
+ config_string = json.dumps(config)
49
+ config_string = config_string.replace("[name]", name)
50
+ config = json.loads(config_string, object_pairs_hook=OrderedDict)
51
+ return config
52
+
53
+
54
+ # Fixes issue where yaml doesnt load exponents correctly
55
+ fixed_loader = yaml.SafeLoader
56
+ fixed_loader.add_implicit_resolver(
57
+ u'tag:yaml.org,2002:float',
58
+ re.compile(u'''^(?:
59
+ [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
60
+ |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
61
+ |\\.[0-9_]+(?:[eE][-+][0-9]+)?
62
+ |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
63
+ |[-+]?\\.(?:inf|Inf|INF)
64
+ |\\.(?:nan|NaN|NAN))$''', re.X),
65
+ list(u'-+0123456789.'))
66
+
67
+
68
+ def get_config(
69
+ config_file_path_or_dict: Union[str, dict, OrderedDict],
70
+ name=None
71
+ ):
72
+ # if we got a dict, process it and return it
73
+ if isinstance(config_file_path_or_dict, dict) or isinstance(config_file_path_or_dict, OrderedDict):
74
+ config = config_file_path_or_dict
75
+ return preprocess_config(config, name)
76
+
77
+ config_file_path = config_file_path_or_dict
78
+
79
+ # first check if it is in the config folder
80
+ config_path = os.path.join(TOOLKIT_ROOT, 'config', config_file_path)
81
+ # see if it is in the config folder with any of the possible extensions if it doesnt have one
82
+ real_config_path = None
83
+ if not os.path.exists(config_path):
84
+ for ext in possible_extensions:
85
+ if os.path.exists(config_path + ext):
86
+ real_config_path = config_path + ext
87
+ break
88
+
89
+ # if we didn't find it there, check if it is a full path
90
+ if not real_config_path:
91
+ if os.path.exists(config_file_path):
92
+ real_config_path = config_file_path
93
+ elif os.path.exists(get_cwd_abs_path(config_file_path)):
94
+ real_config_path = get_cwd_abs_path(config_file_path)
95
+
96
+ if not real_config_path:
97
+ raise ValueError(f"Could not find config file {config_file_path}")
98
+
99
+ # if we found it, check if it is a json or yaml file
100
+ with open(real_config_path, 'r', encoding='utf-8') as f:
101
+ content = f.read()
102
+ content_with_env_replaced = replace_env_vars_in_string(content)
103
+ if real_config_path.endswith('.json') or real_config_path.endswith('.jsonc'):
104
+ config = json.loads(content_with_env_replaced, object_pairs_hook=OrderedDict)
105
+ elif real_config_path.endswith('.yaml') or real_config_path.endswith('.yml'):
106
+ config = yaml.load(content_with_env_replaced, Loader=fixed_loader)
107
+ else:
108
+ raise ValueError(f"Config file {config_file_path} must be a json or yaml file")
109
+
110
+ return preprocess_config(config, name)
toolkit/config_modules.py ADDED
@@ -0,0 +1,1403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from typing import List, Optional, Literal, Tuple, Union, TYPE_CHECKING, Dict
4
+ import random
5
+
6
+ import torch
7
+ import torchaudio
8
+
9
+ from toolkit.audio.album_artwork import add_album_artwork
10
+ from toolkit.prompt_utils import PromptEmbeds
11
+ from torchao.quantization.quant_primitives import _DTYPE_TO_BIT_WIDTH
12
+
13
+ ImgExt = Literal['jpg', 'png', 'webp']
14
+
15
+ SaveFormat = Literal['safetensors', 'diffusers']
16
+
17
+ if TYPE_CHECKING:
18
+ from toolkit.guidance import GuidanceType
19
+ from toolkit.logging_aitk import EmptyLogger
20
+ else:
21
+ EmptyLogger = None
22
+
23
+ class SaveConfig:
24
+ def __init__(self, **kwargs):
25
+ self.save_every: int = kwargs.get('save_every', 1000)
26
+ self.dtype: str = kwargs.get('dtype', 'float16')
27
+ self.max_step_saves_to_keep: int = kwargs.get('max_step_saves_to_keep', 5)
28
+ self.save_format: SaveFormat = kwargs.get('save_format', 'safetensors')
29
+ if self.save_format not in ['safetensors', 'diffusers']:
30
+ raise ValueError(f"save_format must be safetensors or diffusers, got {self.save_format}")
31
+ self.push_to_hub: bool = kwargs.get("push_to_hub", False)
32
+ self.hf_repo_id: Optional[str] = kwargs.get("hf_repo_id", None)
33
+ self.hf_private: Optional[str] = kwargs.get("hf_private", False)
34
+
35
+ class LoggingConfig:
36
+ def __init__(self, **kwargs):
37
+ self.log_every: int = kwargs.get('log_every', 100)
38
+ self.verbose: bool = kwargs.get('verbose', False)
39
+ self.use_wandb: bool = kwargs.get('use_wandb', False)
40
+ self.use_ui_logger: bool = kwargs.get('use_ui_logger', False)
41
+ self.project_name: str = kwargs.get('project_name', 'ai-toolkit')
42
+ self.run_name: str = kwargs.get('run_name', None)
43
+
44
+ class SampleItem:
45
+ def __init__(
46
+ self,
47
+ sample_config: 'SampleConfig',
48
+ **kwargs
49
+ ):
50
+ # prompt should always be in the kwargs
51
+ self.prompt = kwargs.get('prompt', None)
52
+ self.width: int = kwargs.get('width', sample_config.width)
53
+ self.height: int = kwargs.get('height', sample_config.height)
54
+ self.neg: str = kwargs.get('neg', sample_config.neg)
55
+ self.seed: Optional[int] = kwargs.get('seed', None) # if none, default to autogen seed
56
+ self.guidance_scale: float = kwargs.get('guidance_scale', sample_config.guidance_scale)
57
+ self.sample_steps: int = kwargs.get('sample_steps', sample_config.sample_steps)
58
+ self.fps: int = kwargs.get('fps', sample_config.fps)
59
+ self.num_frames: int = kwargs.get('num_frames', sample_config.num_frames)
60
+ self.ctrl_img: Optional[str] = kwargs.get('ctrl_img', None)
61
+ self.ctrl_idx: int = kwargs.get('ctrl_idx', 0)
62
+ # for multi control image models
63
+ self.ctrl_img_1: Optional[str] = kwargs.get('ctrl_img_1', self.ctrl_img)
64
+ self.ctrl_img_2: Optional[str] = kwargs.get('ctrl_img_2', None)
65
+ self.ctrl_img_3: Optional[str] = kwargs.get('ctrl_img_3', None)
66
+
67
+ self.network_multiplier: float = kwargs.get('network_multiplier', sample_config.network_multiplier)
68
+ # convert to a number if it is a string
69
+ if isinstance(self.network_multiplier, str):
70
+ try:
71
+ self.network_multiplier = float(self.network_multiplier)
72
+ except:
73
+ print(f"Invalid network_multiplier {self.network_multiplier}, defaulting to 1.0")
74
+ self.network_multiplier = 1.0
75
+
76
+ # only for models that support it, (qwen image edit 2509 for now)
77
+ self.do_cfg_norm: bool = kwargs.get('do_cfg_norm', False)
78
+
79
+ class SampleConfig:
80
+ def __init__(self, **kwargs):
81
+ self.sampler: str = kwargs.get('sampler', 'ddpm')
82
+ self.sample_every: int = kwargs.get('sample_every', 100)
83
+ self.width: int = kwargs.get('width', 512)
84
+ self.height: int = kwargs.get('height', 512)
85
+ self.neg = kwargs.get('neg', False)
86
+ self.seed = kwargs.get('seed', 0)
87
+ self.walk_seed = kwargs.get('walk_seed', False)
88
+ self.guidance_scale = kwargs.get('guidance_scale', 7)
89
+ self.sample_steps = kwargs.get('sample_steps', 20)
90
+ self.network_multiplier = kwargs.get('network_multiplier', 1)
91
+ self.guidance_rescale = kwargs.get('guidance_rescale', 0.0)
92
+ self.ext: ImgExt = kwargs.get('format', 'jpg')
93
+ self.adapter_conditioning_scale = kwargs.get('adapter_conditioning_scale', 1.0)
94
+ self.refiner_start_at = kwargs.get('refiner_start_at',
95
+ 0.5) # step to start using refiner on sample if it exists
96
+ self.extra_values = kwargs.get('extra_values', [])
97
+ self.num_frames = kwargs.get('num_frames', 1)
98
+ self.fps: int = kwargs.get('fps', 16)
99
+ if self.num_frames > 1 and self.ext not in ['webp']:
100
+ print("Changing sample extention to animated webp")
101
+ self.ext = 'webp'
102
+
103
+ prompts: list[str] = kwargs.get('prompts', [])
104
+
105
+ self.samples: Optional[List[SampleItem]] = None
106
+ # use the legacy prompts if it is passed that way to get samples object
107
+ default_samples_kwargs = [
108
+ {"prompt": x} for x in prompts
109
+ ]
110
+ raw_samples = kwargs.get('samples', default_samples_kwargs)
111
+ self.samples = [SampleItem(self, **item) for item in raw_samples]
112
+ # only for models that support it, (qwen image edit 2509 for now)
113
+ self.do_cfg_norm: bool = kwargs.get('do_cfg_norm', False)
114
+
115
+ @property
116
+ def prompts(self):
117
+ # for backwards compatibility as this is checked for length frequently
118
+ return [sample.prompt for sample in self.samples if sample.prompt is not None]
119
+
120
+
121
+
122
+
123
+ class LormModuleSettingsConfig:
124
+ def __init__(self, **kwargs):
125
+ self.contains: str = kwargs.get('contains', '4nt$3')
126
+ self.extract_mode: str = kwargs.get('extract_mode', 'ratio')
127
+ # min num parameters to attach to
128
+ self.parameter_threshold: int = kwargs.get('parameter_threshold', 0)
129
+ self.extract_mode_param: dict = kwargs.get('extract_mode_param', 0.25)
130
+
131
+
132
+ class LoRMConfig:
133
+ def __init__(self, **kwargs):
134
+ self.extract_mode: str = kwargs.get('extract_mode', 'ratio')
135
+ self.do_conv: bool = kwargs.get('do_conv', False)
136
+ self.extract_mode_param: dict = kwargs.get('extract_mode_param', 0.25)
137
+ self.parameter_threshold: int = kwargs.get('parameter_threshold', 0)
138
+ module_settings = kwargs.get('module_settings', [])
139
+ default_module_settings = {
140
+ 'extract_mode': self.extract_mode,
141
+ 'extract_mode_param': self.extract_mode_param,
142
+ 'parameter_threshold': self.parameter_threshold,
143
+ }
144
+ module_settings = [{**default_module_settings, **module_setting, } for module_setting in module_settings]
145
+ self.module_settings: List[LormModuleSettingsConfig] = [LormModuleSettingsConfig(**module_setting) for
146
+ module_setting in module_settings]
147
+
148
+ def get_config_for_module(self, block_name):
149
+ for setting in self.module_settings:
150
+ contain_pieces = setting.contains.split('|')
151
+ if all(contain_piece in block_name for contain_piece in contain_pieces):
152
+ return setting
153
+ # try replacing the . with _
154
+ contain_pieces = setting.contains.replace('.', '_').split('|')
155
+ if all(contain_piece in block_name for contain_piece in contain_pieces):
156
+ return setting
157
+ # do default
158
+ return LormModuleSettingsConfig(**{
159
+ 'extract_mode': self.extract_mode,
160
+ 'extract_mode_param': self.extract_mode_param,
161
+ 'parameter_threshold': self.parameter_threshold,
162
+ })
163
+
164
+
165
+ NetworkType = Literal['lora', 'locon', 'lorm', 'lokr']
166
+
167
+
168
+ class NetworkConfig:
169
+ def __init__(self, **kwargs):
170
+ self.type: NetworkType = kwargs.get('type', 'lora')
171
+ rank = kwargs.get('rank', None)
172
+ linear = kwargs.get('linear', None)
173
+ if rank is not None:
174
+ self.rank: int = rank # rank for backward compatibility
175
+ self.linear: int = rank
176
+ elif linear is not None:
177
+ self.rank: int = linear
178
+ self.linear: int = linear
179
+ else:
180
+ self.rank: int = 4
181
+ self.linear: int = 4
182
+ self.conv: int = kwargs.get('conv', None)
183
+ self.alpha: float = kwargs.get('alpha', 1.0)
184
+ self.linear_alpha: float = kwargs.get('linear_alpha', self.alpha)
185
+ self.conv_alpha: float = kwargs.get('conv_alpha', self.conv)
186
+ self.dropout: Union[float, None] = kwargs.get('dropout', None)
187
+ self.network_kwargs: dict = kwargs.get('network_kwargs', {})
188
+
189
+ self.lorm_config: Union[LoRMConfig, None] = None
190
+ lorm = kwargs.get('lorm', None)
191
+ if lorm is not None:
192
+ self.lorm_config: LoRMConfig = LoRMConfig(**lorm)
193
+
194
+ if self.type == 'lorm':
195
+ # set linear to arbitrary values so it makes them
196
+ self.linear = 4
197
+ self.rank = 4
198
+ if self.lorm_config.do_conv:
199
+ self.conv = 4
200
+
201
+ self.transformer_only = kwargs.get('transformer_only', True)
202
+
203
+ self.lokr_full_rank = kwargs.get('lokr_full_rank', False)
204
+ if self.lokr_full_rank and self.type.lower() == 'lokr':
205
+ self.linear = 9999999999
206
+ self.linear_alpha = 9999999999
207
+ self.conv = 9999999999
208
+ self.conv_alpha = 9999999999
209
+ # -1 automatically finds the largest factor
210
+ self.lokr_factor = kwargs.get('lokr_factor', -1)
211
+
212
+ # Use the old lokr format
213
+ self.old_lokr_format = kwargs.get('old_lokr_format', False)
214
+
215
+ # for multi stage models
216
+ self.split_multistage_loras = kwargs.get('split_multistage_loras', True)
217
+
218
+ # ramtorch, doesn't work yet
219
+ self.layer_offloading = kwargs.get('layer_offloading', False)
220
+
221
+ # start from a pretrained lora
222
+ self.pretrained_lora_path = kwargs.get('pretrained_lora_path', None)
223
+
224
+
225
+ AdapterTypes = Literal['t2i', 'ip', 'ip+', 'clip', 'ilora', 'photo_maker', 'control_net', 'control_lora', 'i2v']
226
+
227
+ CLIPLayer = Literal['penultimate_hidden_states', 'image_embeds', 'last_hidden_state']
228
+
229
+
230
+ class AdapterConfig:
231
+ def __init__(self, **kwargs):
232
+ self.type: AdapterTypes = kwargs.get('type', 't2i') # t2i, ip, clip, control_net, i2v
233
+ self.in_channels: int = kwargs.get('in_channels', 3)
234
+ self.channels: List[int] = kwargs.get('channels', [320, 640, 1280, 1280])
235
+ self.num_res_blocks: int = kwargs.get('num_res_blocks', 2)
236
+ self.downscale_factor: int = kwargs.get('downscale_factor', 8)
237
+ self.adapter_type: str = kwargs.get('adapter_type', 'full_adapter')
238
+ self.image_dir: str = kwargs.get('image_dir', None)
239
+ self.test_img_path: List[str] = kwargs.get('test_img_path', None)
240
+ if self.test_img_path is not None:
241
+ if isinstance(self.test_img_path, str):
242
+ self.test_img_path = self.test_img_path.split(',')
243
+ self.test_img_path = [p.strip() for p in self.test_img_path]
244
+ self.test_img_path = [p for p in self.test_img_path if p != '']
245
+
246
+ self.train: str = kwargs.get('train', False)
247
+ self.image_encoder_path: str = kwargs.get('image_encoder_path', None)
248
+ self.name_or_path = kwargs.get('name_or_path', None)
249
+
250
+ num_tokens = kwargs.get('num_tokens', None)
251
+ if num_tokens is None and self.type.startswith('ip'):
252
+ if self.type == 'ip+':
253
+ num_tokens = 16
254
+ num_tokens = 16
255
+ elif self.type == 'ip':
256
+ num_tokens = 4
257
+
258
+ self.num_tokens: int = num_tokens
259
+ self.train_image_encoder: bool = kwargs.get('train_image_encoder', False)
260
+ self.train_only_image_encoder: bool = kwargs.get('train_only_image_encoder', False)
261
+ if self.train_only_image_encoder:
262
+ self.train_image_encoder = True
263
+ self.train_only_image_encoder_positional_embedding: bool = kwargs.get(
264
+ 'train_only_image_encoder_positional_embedding', False)
265
+ self.image_encoder_arch: str = kwargs.get('image_encoder_arch', 'clip') # clip vit vit_hybrid, safe
266
+ self.safe_reducer_channels: int = kwargs.get('safe_reducer_channels', 512)
267
+ self.safe_channels: int = kwargs.get('safe_channels', 2048)
268
+ self.safe_tokens: int = kwargs.get('safe_tokens', 8)
269
+ self.quad_image: bool = kwargs.get('quad_image', False)
270
+
271
+ # clip vision
272
+ self.trigger = kwargs.get('trigger', 'tri993r')
273
+ self.trigger_class_name = kwargs.get('trigger_class_name', None)
274
+
275
+ self.class_names = kwargs.get('class_names', [])
276
+
277
+ self.clip_layer: CLIPLayer = kwargs.get('clip_layer', None)
278
+ if self.clip_layer is None:
279
+ if self.type.startswith('ip+'):
280
+ self.clip_layer = 'penultimate_hidden_states'
281
+ else:
282
+ self.clip_layer = 'last_hidden_state'
283
+
284
+ # text encoder
285
+ self.text_encoder_path: str = kwargs.get('text_encoder_path', None)
286
+ self.text_encoder_arch: str = kwargs.get('text_encoder_arch', 'clip') # clip t5
287
+
288
+ self.train_scaler: bool = kwargs.get('train_scaler', False)
289
+ self.scaler_lr: Optional[float] = kwargs.get('scaler_lr', None)
290
+
291
+ # trains with a scaler to easy channel bias but merges it in on save
292
+ self.merge_scaler: bool = kwargs.get('merge_scaler', False)
293
+
294
+ # for ilora
295
+ self.head_dim: int = kwargs.get('head_dim', 1024)
296
+ self.num_heads: int = kwargs.get('num_heads', 1)
297
+ self.ilora_down: bool = kwargs.get('ilora_down', True)
298
+ self.ilora_mid: bool = kwargs.get('ilora_mid', True)
299
+ self.ilora_up: bool = kwargs.get('ilora_up', True)
300
+
301
+ self.pixtral_max_image_size: int = kwargs.get('pixtral_max_image_size', 512)
302
+ self.pixtral_random_image_size: int = kwargs.get('pixtral_random_image_size', False)
303
+
304
+ self.flux_only_double: bool = kwargs.get('flux_only_double', False)
305
+
306
+ # train and use a conv layer to pool the embedding
307
+ self.conv_pooling: bool = kwargs.get('conv_pooling', False)
308
+ self.conv_pooling_stacks: int = kwargs.get('conv_pooling_stacks', 1)
309
+ self.sparse_autoencoder_dim: Optional[int] = kwargs.get('sparse_autoencoder_dim', None)
310
+
311
+ # for llm adapter
312
+ self.num_cloned_blocks: int = kwargs.get('num_cloned_blocks', 0)
313
+ self.quantize_llm: bool = kwargs.get('quantize_llm', False)
314
+
315
+ # for control lora only
316
+ lora_config: dict = kwargs.get('lora_config', None)
317
+ if lora_config is not None:
318
+ self.lora_config: NetworkConfig = NetworkConfig(**lora_config)
319
+ else:
320
+ self.lora_config = None
321
+ self.num_control_images: int = kwargs.get('num_control_images', 1)
322
+ # decimal for how often the control is dropped out and replaced with noise 1.0 is 100%
323
+ self.control_image_dropout: float = kwargs.get('control_image_dropout', 0.0)
324
+ self.has_inpainting_input: bool = kwargs.get('has_inpainting_input', False)
325
+ self.invert_inpaint_mask_chance: float = kwargs.get('invert_inpaint_mask_chance', 0.0)
326
+
327
+ # for subpixel adapter
328
+ self.subpixel_downscale_factor: int = kwargs.get('subpixel_downscale_factor', 8)
329
+
330
+ # for i2v adapter
331
+ # append the masked start frame. During pretraining we will only do the vision encoder
332
+ self.i2v_do_start_frame: bool = kwargs.get('i2v_do_start_frame', False)
333
+
334
+
335
+ class EmbeddingConfig:
336
+ def __init__(self, **kwargs):
337
+ self.trigger = kwargs.get('trigger', 'custom_embedding')
338
+ self.tokens = kwargs.get('tokens', 4)
339
+ self.init_words = kwargs.get('init_words', '*')
340
+ self.save_format = kwargs.get('save_format', 'safetensors')
341
+ self.trigger_class_name = kwargs.get('trigger_class_name', None) # used for inverted masked prior
342
+
343
+
344
+ class DecoratorConfig:
345
+ def __init__(self, **kwargs):
346
+ self.num_tokens: str = kwargs.get('num_tokens', 4)
347
+
348
+
349
+ ContentOrStyleType = Literal['balanced', 'style', 'content']
350
+ LossTarget = Literal['noise', 'source', 'unaugmented', 'differential_noise']
351
+
352
+
353
+ class TrainConfig:
354
+ def __init__(self, **kwargs):
355
+ self.noise_scheduler = kwargs.get('noise_scheduler', 'ddpm')
356
+ self.content_or_style: ContentOrStyleType = kwargs.get('content_or_style', 'balanced')
357
+ self.content_or_style_reg: ContentOrStyleType = kwargs.get('content_or_style', 'balanced')
358
+ self.steps: int = kwargs.get('steps', 1000)
359
+ self.lr = kwargs.get('lr', 1e-6)
360
+ self.unet_lr = kwargs.get('unet_lr', self.lr)
361
+ self.text_encoder_lr = kwargs.get('text_encoder_lr', self.lr)
362
+ self.refiner_lr = kwargs.get('refiner_lr', self.lr)
363
+ self.embedding_lr = kwargs.get('embedding_lr', self.lr)
364
+ self.adapter_lr = kwargs.get('adapter_lr', self.lr)
365
+ self.optimizer = kwargs.get('optimizer', 'adamw')
366
+ self.optimizer_params = kwargs.get('optimizer_params', {})
367
+ self.lr_scheduler = kwargs.get('lr_scheduler', 'constant')
368
+ self.lr_scheduler_params = kwargs.get('lr_scheduler_params', {})
369
+ self.min_denoising_steps: int = kwargs.get('min_denoising_steps', 0)
370
+ self.max_denoising_steps: int = kwargs.get('max_denoising_steps', 999)
371
+ self.batch_size: int = kwargs.get('batch_size', 1)
372
+ self.orig_batch_size: int = self.batch_size
373
+ self.dtype: str = kwargs.get('dtype', 'fp32')
374
+ self.xformers = kwargs.get('xformers', False)
375
+ self.sdp = kwargs.get('sdp', False)
376
+ # see https://huggingface.co/docs/diffusers/main/optimization/attention_backends#available-backends for options
377
+ self.attention_backend: str = kwargs.get('attention_backend', 'native') # native, flash, _flash_3_hub, _flash_3,
378
+ self.train_unet = kwargs.get('train_unet', True)
379
+ self.train_text_encoder = kwargs.get('train_text_encoder', False)
380
+ self.train_refiner = kwargs.get('train_refiner', True)
381
+ self.train_turbo = kwargs.get('train_turbo', False)
382
+ self.show_turbo_outputs = kwargs.get('show_turbo_outputs', False)
383
+ self.min_snr_gamma = kwargs.get('min_snr_gamma', None)
384
+ self.snr_gamma = kwargs.get('snr_gamma', None)
385
+ # trains a gamma, offset, and scale to adjust loss to adapt to timestep differentials
386
+ # this should balance the learning rate across all timesteps over time
387
+ self.learnable_snr_gos = kwargs.get('learnable_snr_gos', False)
388
+ self.noise_offset = kwargs.get('noise_offset', 0.0)
389
+ self.skip_first_sample = kwargs.get('skip_first_sample', False)
390
+ self.force_first_sample = kwargs.get('force_first_sample', False)
391
+ self.gradient_checkpointing = kwargs.get('gradient_checkpointing', True)
392
+ self.weight_jitter = kwargs.get('weight_jitter', 0.0)
393
+ self.merge_network_on_save = kwargs.get('merge_network_on_save', False)
394
+ self.merge_network_on_save_strength = kwargs.get('merge_network_on_save_strength', 1.0)
395
+ self.max_grad_norm = kwargs.get('max_grad_norm', 1.0)
396
+ self.start_step = kwargs.get('start_step', None)
397
+ self.free_u = kwargs.get('free_u', False)
398
+ self.adapter_assist_name_or_path: Optional[str] = kwargs.get('adapter_assist_name_or_path', None)
399
+ self.adapter_assist_type: Optional[str] = kwargs.get('adapter_assist_type', 't2i') # t2i, control_net
400
+ self.noise_multiplier = kwargs.get('noise_multiplier', 1.0)
401
+ self.target_noise_multiplier = kwargs.get('target_noise_multiplier', 1.0)
402
+ self.random_noise_multiplier = kwargs.get('random_noise_multiplier', 0.0)
403
+ self.do_signal_correction_noise = kwargs.get('do_signal_correction_noise', False)
404
+ # batch noise correction adds other images in the batch as noise to correct away from other images
405
+ self.do_batch_noise_correction = kwargs.get('do_batch_noise_correction', False)
406
+ self.batch_noise_correction_scale = kwargs.get('batch_noise_correction_scale', 0.1)
407
+ self.do_signal_amplification = kwargs.get('do_signal_amplification', False)
408
+ self.signal_amplification_strength = kwargs.get('signal_amplification_strength', 0.5)
409
+
410
+ self.signal_correction_noise_scale = kwargs.get('signal_correction_noise_scale', 1.0)
411
+ self.random_noise_shift = kwargs.get('random_noise_shift', 0.0)
412
+ self.img_multiplier = kwargs.get('img_multiplier', 1.0)
413
+ self.noisy_latent_multiplier = kwargs.get('noisy_latent_multiplier', 1.0)
414
+ self.latent_multiplier = kwargs.get('latent_multiplier', 1.0)
415
+ self.negative_prompt = kwargs.get('negative_prompt', None)
416
+ self.max_negative_prompts = kwargs.get('max_negative_prompts', 1)
417
+ # multiplier applied to loos on regularization images
418
+ self.reg_weight = kwargs.get('reg_weight', 1.0)
419
+ self.num_train_timesteps = kwargs.get('num_train_timesteps', 1000)
420
+ # automatically adapte the vae scaling based on the image norm
421
+ self.adaptive_scaling_factor = kwargs.get('adaptive_scaling_factor', False)
422
+
423
+ # dropout that happens before encoding. It functions independently per text encoder
424
+ self.prompt_dropout_prob = kwargs.get('prompt_dropout_prob', 0.0)
425
+
426
+ # match the norm of the noise before computing loss. This will help the model maintain its
427
+ # current understandin of the brightness of images.
428
+
429
+ self.match_noise_norm = kwargs.get('match_noise_norm', False)
430
+
431
+ # set to -1 to accumulate gradients for entire epoch
432
+ # warning, only do this with a small dataset or you will run out of memory
433
+ # This is legacy but left in for backwards compatibility
434
+ self.gradient_accumulation_steps = kwargs.get('gradient_accumulation_steps', 1)
435
+
436
+ # this will do proper gradient accumulation where you will not see a step until the end of the accumulation
437
+ # the method above will show a step every accumulation
438
+ self.gradient_accumulation = kwargs.get('gradient_accumulation', 1)
439
+ if self.gradient_accumulation > 1:
440
+ if self.gradient_accumulation_steps != 1:
441
+ raise ValueError("gradient_accumulation and gradient_accumulation_steps are mutually exclusive")
442
+
443
+ # short long captions will double your batch size. This only works when a dataset is
444
+ # prepared with a json caption file that has both short and long captions in it. It will
445
+ # Double up every image and run it through with both short and long captions. The idea
446
+ # is that the network will learn how to generate good images with both short and long captions
447
+ self.short_and_long_captions = kwargs.get('short_and_long_captions', False)
448
+ # if above is NOT true, this will make it so the long caption foes to te2 and the short caption goes to te1 for sdxl only
449
+ self.short_and_long_captions_encoder_split = kwargs.get('short_and_long_captions_encoder_split', False)
450
+
451
+ # basically gradient accumulation but we run just 1 item through the network
452
+ # and accumulate gradients. This can be used as basic gradient accumulation but is very helpful
453
+ # for training tricks that increase batch size but need a single gradient step
454
+ self.single_item_batching = kwargs.get('single_item_batching', False)
455
+
456
+ match_adapter_assist = kwargs.get('match_adapter_assist', False)
457
+ self.match_adapter_chance = kwargs.get('match_adapter_chance', 0.0)
458
+ self.loss_target: LossTarget = kwargs.get('loss_target',
459
+ 'noise') # noise, source, unaugmented, differential_noise
460
+
461
+ # When a mask is passed in a dataset, and this is true,
462
+ # we will predict noise without a the LoRa network and use the prediction as a target for
463
+ # unmasked reign. It is unmasked regularization basically
464
+ self.inverted_mask_prior = kwargs.get('inverted_mask_prior', False)
465
+ self.inverted_mask_prior_multiplier = kwargs.get('inverted_mask_prior_multiplier', 0.5)
466
+
467
+ # DOP will will run the same image and prompt through the network without the trigger word blank and use it as a target
468
+ self.diff_output_preservation = kwargs.get('diff_output_preservation', False)
469
+ self.diff_output_preservation_multiplier = kwargs.get('diff_output_preservation_multiplier', 1.0)
470
+ # If the trigger word is in the prompt, we will use this class name to replace it eg. "sks woman" -> "woman"
471
+ self.diff_output_preservation_class = kwargs.get('diff_output_preservation_class', '')
472
+
473
+ # blank prompt preservation will preserve the model's knowledge of a blank prompt
474
+ self.blank_prompt_preservation = kwargs.get('blank_prompt_preservation', False)
475
+ self.blank_prompt_preservation_multiplier = kwargs.get('blank_prompt_preservation_multiplier', 1.0)
476
+
477
+ # legacy
478
+ if match_adapter_assist and self.match_adapter_chance == 0.0:
479
+ self.match_adapter_chance = 1.0
480
+
481
+ # standardize inputs to the meand std of the model knowledge
482
+ self.standardize_images = kwargs.get('standardize_images', False)
483
+ self.standardize_latents = kwargs.get('standardize_latents', False)
484
+
485
+ # if self.train_turbo and not self.noise_scheduler.startswith("euler"):
486
+ # raise ValueError(f"train_turbo is only supported with euler and wuler_a noise schedulers")
487
+
488
+ self.dynamic_noise_offset = kwargs.get('dynamic_noise_offset', False)
489
+ self.do_cfg = kwargs.get('do_cfg', False)
490
+ self.do_random_cfg = kwargs.get('do_random_cfg', False)
491
+ self.cfg_scale = kwargs.get('cfg_scale', 1.0)
492
+ self.max_cfg_scale = kwargs.get('max_cfg_scale', self.cfg_scale)
493
+ self.cfg_rescale = kwargs.get('cfg_rescale', None)
494
+ if self.cfg_rescale is None:
495
+ self.cfg_rescale = self.cfg_scale
496
+
497
+ # applies the inverse of the prediction mean and std to the target to correct
498
+ # for norm drift
499
+ self.correct_pred_norm = kwargs.get('correct_pred_norm', False)
500
+ self.correct_pred_norm_multiplier = kwargs.get('correct_pred_norm_multiplier', 1.0)
501
+
502
+ self.loss_type = kwargs.get('loss_type', 'mse') # mse, mae, wavelet, pixelspace, mean_flow, pseudo_huber
503
+
504
+ # do the loss on a timestep to 0 prediction
505
+ self.t0_loss_target = kwargs.get('t0_loss_target', False)
506
+ self.t0_velocity_equiv_weight = kwargs.get('t0_velocity_equiv_weight', False)
507
+
508
+ # do additional fft loss
509
+ self.do_fft_loss = kwargs.get('do_fft_loss', False)
510
+ self.do_fft_velocity_equiv_weight = kwargs.get('do_fft_velocity_equiv_weight', False)
511
+
512
+ # scale the prediction by this. Increase for more detail, decrease for less
513
+ self.pred_scaler = kwargs.get('pred_scaler', 1.0)
514
+
515
+ # repeats the prompt a few times to saturate the encoder
516
+ self.prompt_saturation_chance = kwargs.get('prompt_saturation_chance', 0.0)
517
+
518
+ # applies negative loss on the prior to encourage network to diverge from it
519
+ self.do_prior_divergence = kwargs.get('do_prior_divergence', False)
520
+
521
+ ema_config: Union[Dict, None] = kwargs.get('ema_config', None)
522
+ # if it is set explicitly to false, leave it false.
523
+ if ema_config is not None and ema_config.get('use_ema', False):
524
+ ema_config['use_ema'] = True
525
+ print(f"Using EMA")
526
+ else:
527
+ ema_config = {'use_ema': False}
528
+
529
+ self.ema_config: EMAConfig = EMAConfig(**ema_config)
530
+
531
+ # adds an additional loss to the network to encourage it output a normalized standard deviation
532
+ self.target_norm_std = kwargs.get('target_norm_std', None)
533
+ self.target_norm_std_value = kwargs.get('target_norm_std_value', 1.0)
534
+ self.timestep_type = kwargs.get('timestep_type', 'sigmoid') # sigmoid, linear, lognorm_blend, next_sample, weighted, one_step
535
+ self.next_sample_timesteps = kwargs.get('next_sample_timesteps', 8)
536
+ self.linear_timesteps = kwargs.get('linear_timesteps', False)
537
+ self.linear_timesteps2 = kwargs.get('linear_timesteps2', False)
538
+ self.disable_sampling = kwargs.get('disable_sampling', False)
539
+
540
+ # will cache a blank prompt or the trigger word, and unload the text encoder to cpu
541
+ # will make training faster and use less vram
542
+ self.unload_text_encoder = kwargs.get('unload_text_encoder', False)
543
+ # will toggle all datasets to cache text embeddings
544
+ self.cache_text_embeddings: bool = kwargs.get('cache_text_embeddings', False)
545
+ # for swapping which parameters are trained during training
546
+ self.do_paramiter_swapping = kwargs.get('do_paramiter_swapping', False)
547
+ # 0.1 is 10% of the parameters active at a time lower is less vram, higher is more
548
+ self.paramiter_swapping_factor = kwargs.get('paramiter_swapping_factor', 0.1)
549
+ # bypass the guidance embedding for training. For open flux with guidance embedding
550
+ self.bypass_guidance_embedding = kwargs.get('bypass_guidance_embedding', False)
551
+
552
+ # diffusion feature extractor
553
+ self.latent_feature_extractor_path = kwargs.get('latent_feature_extractor_path', None)
554
+ self.latent_feature_loss_weight = kwargs.get('latent_feature_loss_weight', 1.0)
555
+
556
+ # we use this in the code, but it really needs to be called latent_feature_extractor as that makes more sense with new architecture
557
+ self.diffusion_feature_extractor_path = kwargs.get('diffusion_feature_extractor_path', self.latent_feature_extractor_path)
558
+ self.diffusion_feature_extractor_weight = kwargs.get('diffusion_feature_extractor_weight', self.latent_feature_loss_weight)
559
+
560
+ # optimal noise pairing
561
+ self.optimal_noise_pairing_samples = kwargs.get('optimal_noise_pairing_samples', 1)
562
+
563
+ # forces same noise for the same image at a given size.
564
+ self.force_consistent_noise = kwargs.get('force_consistent_noise', False)
565
+ self.blended_blur_noise = kwargs.get('blended_blur_noise', False)
566
+
567
+ # contrastive loss
568
+ self.do_guidance_loss = kwargs.get('do_guidance_loss', False)
569
+ self.guidance_loss_target: Union[int, List[int, int]] = kwargs.get('guidance_loss_target', 3.0)
570
+ self.do_guidance_loss_cfg_zero: bool = kwargs.get('do_guidance_loss_cfg_zero', False)
571
+ self.unconditional_prompt: str = kwargs.get('unconditional_prompt', '')
572
+ if isinstance(self.guidance_loss_target, tuple):
573
+ self.guidance_loss_target = list(self.guidance_loss_target)
574
+
575
+ self.do_differential_guidance = kwargs.get('do_differential_guidance', False)
576
+ self.differential_guidance_scale = kwargs.get('differential_guidance_scale', 3.0)
577
+
578
+ # for multi stage models, how often to switch the boundary
579
+ self.switch_boundary_every: int = kwargs.get('switch_boundary_every', 1)
580
+
581
+ # stabilizes empty prompts to be zeroed predictions
582
+ self.do_blank_stabilization = kwargs.get('do_blank_stabilization', False)
583
+
584
+ self.audio_loss_multiplier = kwargs.get("audio_loss_multiplier", 1.0)
585
+
586
+ # will throw detailed error when it goes over
587
+ self.max_loss_debug: bool = kwargs.get("max_loss_debug", False)
588
+ # will clip the loss to this amount to prevent wild outliers
589
+ self.max_loss: Optional[float] = kwargs.get("max_loss", None)
590
+
591
+
592
+ ModelArch = Literal['sd1', 'sd2', 'sd3', 'sdxl', 'pixart', 'pixart_sigma', 'auraflow', 'flux', 'flex1', 'flex2', 'lumina2', 'vega', 'ssd', 'wan21']
593
+
594
+
595
+ class ModelConfig:
596
+ def __init__(self, **kwargs):
597
+ self.name_or_path: str = kwargs.get('name_or_path', None)
598
+ # name or path is updated on fine tuning. Keep a copy of the original
599
+ self.name_or_path_original: str = self.name_or_path
600
+ self.is_v2: bool = kwargs.get('is_v2', False)
601
+ self.is_xl: bool = kwargs.get('is_xl', False)
602
+ self.is_pixart: bool = kwargs.get('is_pixart', False)
603
+ self.is_pixart_sigma: bool = kwargs.get('is_pixart_sigma', False)
604
+ self.is_auraflow: bool = kwargs.get('is_auraflow', False)
605
+ self.is_v3: bool = kwargs.get('is_v3', False)
606
+ self.is_flux: bool = kwargs.get('is_flux', False)
607
+ self.is_lumina2: bool = kwargs.get('is_lumina2', False)
608
+ if self.is_pixart_sigma:
609
+ self.is_pixart = True
610
+ self.use_flux_cfg = kwargs.get('use_flux_cfg', False)
611
+ self.is_ssd: bool = kwargs.get('is_ssd', False)
612
+ self.is_vega: bool = kwargs.get('is_vega', False)
613
+ self.is_v_pred: bool = kwargs.get('is_v_pred', False)
614
+ self.dtype: str = kwargs.get('dtype', 'float16')
615
+ self.vae_path = kwargs.get('vae_path', None)
616
+ self.refiner_name_or_path = kwargs.get('refiner_name_or_path', None)
617
+ self._original_refiner_name_or_path = self.refiner_name_or_path
618
+ self.refiner_start_at = kwargs.get('refiner_start_at', 0.5)
619
+ self.lora_path = kwargs.get('lora_path', None)
620
+ # mainly for decompression loras for distilled models
621
+ self.assistant_lora_path = kwargs.get('assistant_lora_path', None)
622
+ self.inference_lora_path = kwargs.get('inference_lora_path', None)
623
+ self.latent_space_version = kwargs.get('latent_space_version', None)
624
+
625
+ # only for SDXL models for now
626
+ self.use_text_encoder_1: bool = kwargs.get('use_text_encoder_1', True)
627
+ self.use_text_encoder_2: bool = kwargs.get('use_text_encoder_2', True)
628
+
629
+ self.experimental_xl: bool = kwargs.get('experimental_xl', False)
630
+
631
+ if self.name_or_path is None:
632
+ raise ValueError('name_or_path must be specified')
633
+
634
+ if self.is_ssd:
635
+ # sed sdxl as true since it is mostly the same architecture
636
+ self.is_xl = True
637
+
638
+ if self.is_vega:
639
+ self.is_xl = True
640
+
641
+ # for text encoder quant. Only works with pixart currently
642
+ self.text_encoder_bits = kwargs.get('text_encoder_bits', 16) # 16, 8, 4
643
+ self.unet_path = kwargs.get("unet_path", None)
644
+ self.unet_sample_size = kwargs.get("unet_sample_size", None)
645
+ self.vae_device = kwargs.get("vae_device", None)
646
+ self.vae_dtype = kwargs.get("vae_dtype", self.dtype)
647
+ self.te_device = kwargs.get("te_device", None)
648
+ self.te_dtype = kwargs.get("te_dtype", self.dtype)
649
+
650
+ # only for flux for now
651
+ self.quantize = kwargs.get("quantize", False)
652
+ self.quantize_te = kwargs.get("quantize_te", self.quantize)
653
+ self.qtype = kwargs.get("qtype", "qfloat8")
654
+ self.qtype_te = kwargs.get("qtype_te", "qfloat8")
655
+ self.low_vram = kwargs.get("low_vram", False)
656
+ self.attn_masking = kwargs.get("attn_masking", False)
657
+ if self.attn_masking and not self.is_flux:
658
+ raise ValueError("attn_masking is only supported with flux models currently")
659
+ # for targeting a specific layers
660
+ self.ignore_if_contains: Optional[List[str]] = kwargs.get("ignore_if_contains", None)
661
+ self.only_if_contains: Optional[List[str]] = kwargs.get("only_if_contains", None)
662
+ self.quantize_kwargs = kwargs.get("quantize_kwargs", {})
663
+
664
+ # splits the model over the available gpus WIP
665
+ self.split_model_over_gpus = kwargs.get("split_model_over_gpus", False)
666
+ if self.split_model_over_gpus and not self.is_flux:
667
+ raise ValueError("split_model_over_gpus is only supported with flux models currently")
668
+ self.split_model_other_module_param_count_scale = kwargs.get("split_model_other_module_param_count_scale", 0.3)
669
+
670
+ self.te_name_or_path = kwargs.get("te_name_or_path", None)
671
+
672
+ self.arch: ModelArch = kwargs.get("arch", None)
673
+
674
+ # auto memory management, only for some models
675
+ self.auto_memory = kwargs.get("auto_memory", False)
676
+ # auto memory is deprecated, use layer offloading instead
677
+ if self.auto_memory:
678
+ print("auto_memory is deprecated, use layer_offloading instead")
679
+ self.layer_offloading = kwargs.get("layer_offloading", self.auto_memory )
680
+ if self.layer_offloading and self.qtype == "qfloat8":
681
+ self.qtype = "float8"
682
+ if self.layer_offloading and self.qtype_te == "qfloat8":
683
+ self.qtype_te = "float8"
684
+
685
+ # Mac mps only works with torachao uint
686
+ if torch.backends.mps.is_available() and self.qtype == "qfloat8":
687
+ self.qtype = "int8"
688
+ if torch.backends.mps.is_available() and self.qtype_te == "qfloat8":
689
+ self.qtype_te = "int8"
690
+
691
+ # 0 is off and 1.0 is 100% of the layers
692
+ self.layer_offloading_transformer_percent = kwargs.get("layer_offloading_transformer_percent", 1.0)
693
+ self.layer_offloading_text_encoder_percent = kwargs.get("layer_offloading_text_encoder_percent", 1.0)
694
+
695
+ # can be used to load the extras like text encoder or vae from here
696
+ # only setup for some models but will prevent having to download the te for
697
+ # 20 different model variants
698
+ self.extras_name_or_path = kwargs.get("extras_name_or_path", self.name_or_path)
699
+
700
+ # path to an accuracy recovery adapter, either local or remote
701
+ self.accuracy_recovery_adapter = kwargs.get("accuracy_recovery_adapter", None)
702
+
703
+ # parse ARA from qtype
704
+ if self.qtype is not None and "|" in self.qtype:
705
+ self.qtype, self.accuracy_recovery_adapter = self.qtype.split('|')
706
+
707
+ # compile the model with torch compile
708
+ self.compile = kwargs.get("compile", False)
709
+
710
+ if self.compile and self.quantize:
711
+ print("Warning: You cannot compile a quantized model. Disabling compile.")
712
+ self.compile = False
713
+
714
+ # kwargs to pass to the model
715
+ self.model_kwargs = kwargs.get("model_kwargs", {})
716
+
717
+ # model paths for models that support it
718
+ self.model_paths = kwargs.get("model_paths", {})
719
+
720
+ self.in_context = kwargs.get("in_context", False)
721
+
722
+ # allow frontend to pass arch with a color like arch:tag
723
+ # but remove the tag
724
+ if self.arch is not None:
725
+ if ':' in self.arch:
726
+ self.arch = self.arch.split(':')[0]
727
+
728
+ if self.arch == "flex1":
729
+ self.arch = "flux"
730
+
731
+
732
+ # handle migrating to new model arch
733
+ if self.arch is not None:
734
+ # reverse the arch to the old style
735
+ if self.arch == 'sd2':
736
+ self.is_v2 = True
737
+ elif self.arch == 'sd3':
738
+ self.is_v3 = True
739
+ elif self.arch == 'sdxl':
740
+ self.is_xl = True
741
+ elif self.arch == 'pixart':
742
+ self.is_pixart = True
743
+ elif self.arch == 'pixart_sigma':
744
+ self.is_pixart_sigma = True
745
+ elif self.arch == 'auraflow':
746
+ self.is_auraflow = True
747
+ elif self.arch == 'flux':
748
+ self.is_flux = True
749
+ elif self.arch == 'lumina2':
750
+ self.is_lumina2 = True
751
+ elif self.arch == 'vega':
752
+ self.is_vega = True
753
+ elif self.arch == 'ssd':
754
+ self.is_ssd = True
755
+ else:
756
+ pass
757
+ if self.arch is None:
758
+ if kwargs.get('is_v2', False):
759
+ self.arch = 'sd2'
760
+ elif kwargs.get('is_v3', False):
761
+ self.arch = 'sd3'
762
+ elif kwargs.get('is_xl', False):
763
+ self.arch = 'sdxl'
764
+ elif kwargs.get('is_pixart', False):
765
+ self.arch = 'pixart'
766
+ elif kwargs.get('is_pixart_sigma', False):
767
+ self.arch = 'pixart_sigma'
768
+ elif kwargs.get('is_auraflow', False):
769
+ self.arch = 'auraflow'
770
+ elif kwargs.get('is_flux', False):
771
+ self.arch = 'flux'
772
+ elif kwargs.get('is_lumina2', False):
773
+ self.arch = 'lumina2'
774
+ elif kwargs.get('is_vega', False):
775
+ self.arch = 'vega'
776
+ elif kwargs.get('is_ssd', False):
777
+ self.arch = 'ssd'
778
+ else:
779
+ self.arch = 'sd1'
780
+
781
+
782
+
783
+ class EMAConfig:
784
+ def __init__(self, **kwargs):
785
+ self.use_ema: bool = kwargs.get('use_ema', False)
786
+ self.ema_decay: float = kwargs.get('ema_decay', 0.999)
787
+ # feeds back the decay difference into the parameter
788
+ self.use_feedback: bool = kwargs.get('use_feedback', False)
789
+
790
+ # every update, the params are multiplied by this amount
791
+ # only use for things without a bias like lora
792
+ # similar to a decay in an optimizer but the opposite
793
+ self.param_multiplier: float = kwargs.get('param_multiplier', 1.0)
794
+
795
+
796
+ class ReferenceDatasetConfig:
797
+ def __init__(self, **kwargs):
798
+ # can pass with a side by side pait or a folder with pos and neg folder
799
+ self.pair_folder: str = kwargs.get('pair_folder', None)
800
+ self.pos_folder: str = kwargs.get('pos_folder', None)
801
+ self.neg_folder: str = kwargs.get('neg_folder', None)
802
+
803
+ self.network_weight: float = float(kwargs.get('network_weight', 1.0))
804
+ self.pos_weight: float = float(kwargs.get('pos_weight', self.network_weight))
805
+ self.neg_weight: float = float(kwargs.get('neg_weight', self.network_weight))
806
+ # make sure they are all absolute values no negatives
807
+ self.pos_weight = abs(self.pos_weight)
808
+ self.neg_weight = abs(self.neg_weight)
809
+
810
+ self.target_class: str = kwargs.get('target_class', '')
811
+ self.size: int = kwargs.get('size', 512)
812
+
813
+
814
+ class SliderTargetConfig:
815
+ def __init__(self, **kwargs):
816
+ self.target_class: str = kwargs.get('target_class', '')
817
+ self.positive: str = kwargs.get('positive', '')
818
+ self.negative: str = kwargs.get('negative', '')
819
+ self.multiplier: float = kwargs.get('multiplier', 1.0)
820
+ self.weight: float = kwargs.get('weight', 1.0)
821
+ self.shuffle: bool = kwargs.get('shuffle', False)
822
+
823
+
824
+ class GuidanceConfig:
825
+ def __init__(self, **kwargs):
826
+ self.target_class: str = kwargs.get('target_class', '')
827
+ self.guidance_scale: float = kwargs.get('guidance_scale', 1.0)
828
+ self.positive_prompt: str = kwargs.get('positive_prompt', '')
829
+ self.negative_prompt: str = kwargs.get('negative_prompt', '')
830
+
831
+
832
+ class SliderConfigAnchors:
833
+ def __init__(self, **kwargs):
834
+ self.prompt = kwargs.get('prompt', '')
835
+ self.neg_prompt = kwargs.get('neg_prompt', '')
836
+ self.multiplier = kwargs.get('multiplier', 1.0)
837
+
838
+
839
+ class SliderConfig:
840
+ def __init__(self, **kwargs):
841
+ targets = kwargs.get('targets', [])
842
+ anchors = kwargs.get('anchors', [])
843
+ anchors = [SliderConfigAnchors(**anchor) for anchor in anchors]
844
+ self.anchors: List[SliderConfigAnchors] = anchors
845
+ self.resolutions: List[List[int]] = kwargs.get('resolutions', [[512, 512]])
846
+ self.prompt_file: str = kwargs.get('prompt_file', None)
847
+ self.prompt_tensors: str = kwargs.get('prompt_tensors', None)
848
+ self.batch_full_slide: bool = kwargs.get('batch_full_slide', True)
849
+ self.use_adapter: bool = kwargs.get('use_adapter', None) # depth
850
+ self.adapter_img_dir = kwargs.get('adapter_img_dir', None)
851
+ self.low_ram = kwargs.get('low_ram', False)
852
+
853
+ # expand targets if shuffling
854
+ from toolkit.prompt_utils import get_slider_target_permutations
855
+ self.targets: List[SliderTargetConfig] = []
856
+ targets = [SliderTargetConfig(**target) for target in targets]
857
+ # do permutations if shuffle is true
858
+ print(f"Building slider targets")
859
+ for target in targets:
860
+ if target.shuffle:
861
+ target_permutations = get_slider_target_permutations(target, max_permutations=8)
862
+ self.targets = self.targets + target_permutations
863
+ else:
864
+ self.targets.append(target)
865
+ print(f"Built {len(self.targets)} slider targets (with permutations)")
866
+
867
+ ControlTypes = Literal['depth', 'line', 'pose', 'inpaint', 'mask', 'sapiens2_mask']
868
+
869
+ class DatasetConfig:
870
+ """
871
+ Dataset config for sd-datasets
872
+
873
+ """
874
+
875
+ def __init__(self, **kwargs):
876
+ self.type = kwargs.get('type', 'image') # sd, slider, reference
877
+ # will be legacy
878
+ self.folder_path: str = kwargs.get('folder_path', None)
879
+ # can be json or folder path
880
+ self.dataset_path: str = kwargs.get('dataset_path', None)
881
+
882
+ self.default_caption: str = kwargs.get('default_caption', None)
883
+ # trigger word for just this dataset
884
+ self.trigger_word: str = kwargs.get('trigger_word', None)
885
+ random_triggers = kwargs.get('random_triggers', [])
886
+ # if they are a string, load them from a file
887
+ if isinstance(random_triggers, str) and os.path.exists(random_triggers):
888
+ with open(random_triggers, 'r') as f:
889
+ random_triggers = f.read().splitlines()
890
+ # remove empty lines
891
+ random_triggers = [line for line in random_triggers if line.strip() != '']
892
+ self.random_triggers: List[str] = random_triggers
893
+ self.random_triggers_max: int = kwargs.get('random_triggers_max', 1)
894
+ self.caption_ext: str = kwargs.get('caption_ext', '.txt')
895
+ # if caption_ext doesnt start with a dot, add it
896
+ if self.caption_ext and not self.caption_ext.startswith('.'):
897
+ self.caption_ext = '.' + self.caption_ext
898
+ self.random_scale: bool = kwargs.get('random_scale', False)
899
+ self.random_crop: bool = kwargs.get('random_crop', False)
900
+ self.resolution: int = kwargs.get('resolution', 512)
901
+ self.scale: float = kwargs.get('scale', 1.0)
902
+ self.buckets: bool = kwargs.get('buckets', True)
903
+ self.bucket_tolerance: int = kwargs.get('bucket_tolerance', 64)
904
+ self.is_reg: bool = kwargs.get('is_reg', False)
905
+ self.prior_reg: bool = kwargs.get('prior_reg', False)
906
+ self.network_weight: float = float(kwargs.get('network_weight', 1.0))
907
+ self.token_dropout_rate: float = float(kwargs.get('token_dropout_rate', 0.0))
908
+ self.shuffle_tokens: bool = kwargs.get('shuffle_tokens', False)
909
+ self.caption_dropout_rate: float = float(kwargs.get('caption_dropout_rate', 0.0))
910
+ self.keep_tokens: int = kwargs.get('keep_tokens', 0) # #of first tokens to always keep unless caption dropped
911
+ self.flip_x: bool = kwargs.get('flip_x', False)
912
+ self.flip_y: bool = kwargs.get('flip_y', False)
913
+ self.augments: List[str] = kwargs.get('augments', [])
914
+ self.control_path: Union[str,List[str]] = kwargs.get('control_path', None) # depth maps, etc
915
+ if self.control_path == '':
916
+ self.control_path = None
917
+
918
+ # handle multi control inputs from the ui. It is just easier to handle it here for a cleaner ui experience
919
+ control_path_1 = kwargs.get('control_path_1', None)
920
+ control_path_2 = kwargs.get('control_path_2', None)
921
+ control_path_3 = kwargs.get('control_path_3', None)
922
+
923
+ if any([control_path_1, control_path_2, control_path_3]):
924
+ control_paths = []
925
+ if control_path_1:
926
+ control_paths.append(control_path_1)
927
+ if control_path_2:
928
+ control_paths.append(control_path_2)
929
+ if control_path_3:
930
+ control_paths.append(control_path_3)
931
+ self.control_path = control_paths
932
+
933
+ # color for transparent reigon of control images with transparency
934
+ self.control_transparent_color: List[int] = kwargs.get('control_transparent_color', [0, 0, 0])
935
+ # inpaint images should be webp/png images with alpha channel. The alpha 0 (invisible) section will
936
+ # be the part conditioned to be inpainted. The alpha 1 (visible) section will be the part that is ignored
937
+ self.inpaint_path: Union[str,List[str]] = kwargs.get('inpaint_path', None)
938
+ # instead of cropping ot match image, it will serve the full size control image (clip images ie for ip adapters)
939
+ self.full_size_control_images: bool = kwargs.get('full_size_control_images', True)
940
+ self.alpha_mask: bool = kwargs.get('alpha_mask', False) # if true, will use alpha channel as mask
941
+ self.mask_path: str = kwargs.get('mask_path',
942
+ None) # focus mask (black and white. White has higher loss than black)
943
+ self.unconditional_path: str = kwargs.get('unconditional_path',
944
+ None) # path where matching unconditional images are located
945
+ self.invert_mask: bool = kwargs.get('invert_mask', False) # invert mask
946
+ self.mask_min_value: float = kwargs.get('mask_min_value', 0.0) # min value for . 0 - 1
947
+ self.poi: Union[str, None] = kwargs.get('poi',
948
+ None) # if one is set and in json data, will be used as auto crop scale point of interes
949
+ self.use_short_captions: bool = kwargs.get('use_short_captions', False) # if true, will use 'caption_short' from json
950
+ self.num_repeats: int = kwargs.get('num_repeats', 1) # number of times to repeat dataset
951
+ # cache latents will store them in memory
952
+ self.cache_latents: bool = kwargs.get('cache_latents', False)
953
+ # cache latents to disk will store them on disk. If both are true, it will save to disk, but keep in memory
954
+ self.cache_latents_to_disk: bool = kwargs.get('cache_latents_to_disk', False)
955
+ self.cache_clip_vision_to_disk: bool = kwargs.get('cache_clip_vision_to_disk', False)
956
+ self.cache_text_embeddings: bool = kwargs.get('cache_text_embeddings', False)
957
+
958
+ self.standardize_images: bool = kwargs.get('standardize_images', False)
959
+
960
+ # https://albumentations.ai/docs/api_reference/augmentations/transforms
961
+ # augmentations are returned as a separate image and cannot currently be cached
962
+ self.augmentations: List[dict] = kwargs.get('augmentations', None)
963
+ self.shuffle_augmentations: bool = kwargs.get('shuffle_augmentations', False)
964
+
965
+ has_augmentations = self.augmentations is not None and len(self.augmentations) > 0
966
+
967
+ if (len(self.augments) > 0 or has_augmentations) and (self.cache_latents or self.cache_latents_to_disk):
968
+ print(f"WARNING: Augments are not supported with caching latents. Setting cache_latents to False")
969
+ self.cache_latents = False
970
+ self.cache_latents_to_disk = False
971
+
972
+ # legacy compatability
973
+ legacy_caption_type = kwargs.get('caption_type', None)
974
+ if legacy_caption_type:
975
+ self.caption_ext = legacy_caption_type
976
+ self.caption_type = self.caption_ext
977
+ self.guidance_type: GuidanceType = kwargs.get('guidance_type', 'targeted')
978
+
979
+ # ip adapter / reference dataset
980
+ self.clip_image_path: str = kwargs.get('clip_image_path', None) # depth maps, etc
981
+ # get the clip image randomly from the same folder as the image. Useful for folder grouped pairs.
982
+ self.clip_image_from_same_folder: bool = kwargs.get('clip_image_from_same_folder', False)
983
+ self.clip_image_augmentations: List[dict] = kwargs.get('clip_image_augmentations', None)
984
+ self.clip_image_shuffle_augmentations: bool = kwargs.get('clip_image_shuffle_augmentations', False)
985
+ self.replacements: List[str] = kwargs.get('replacements', [])
986
+ self.loss_multiplier: float = kwargs.get('loss_multiplier', 1.0)
987
+
988
+ self.num_workers: int = kwargs.get('num_workers', 2)
989
+ self.prefetch_factor: int = kwargs.get('prefetch_factor', 2)
990
+ self.extra_values: List[float] = kwargs.get('extra_values', [])
991
+ self.square_crop: bool = kwargs.get('square_crop', False)
992
+ # apply same augmentations to control images. Usually want this true unless special case
993
+ self.replay_transforms: bool = kwargs.get('replay_transforms', True)
994
+
995
+ # for video
996
+ # if num_frames is greater than 1, the dataloader will look for video files.
997
+ # num_frames will be the number of frames in the training batch. If num_frames is 1, it will look for images
998
+ self.num_frames: int = kwargs.get('num_frames', 1)
999
+ # if true, will shrink video to our frames. For instance, if we have a video with 100 frames and num_frames is 10,
1000
+ # we would pull frame 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 so they are evenly spaced
1001
+ self.shrink_video_to_frames: bool = kwargs.get('shrink_video_to_frames', True)
1002
+ # fps is only used if shrink_video_to_frames is false. This will attempt to pull the num_frames at the given fps
1003
+ # it will select a random start frame and pull the frames at the given fps
1004
+ # this could have various issues with shorter videos and videos with variable fps
1005
+ # I recommend trimming your videos to the desired length and using shrink_video_to_frames(default)
1006
+ self.fps: int = kwargs.get('fps', 24)
1007
+
1008
+ # auto_frame_count pull as many frames as in the video at given fps
1009
+ # Important, make sure fps for dataset is set correctly.
1010
+ # this wont work with bucketing for now until I can handle this before bucketing.
1011
+ self.auto_frame_count: bool = kwargs.get('auto_frame_count', False)
1012
+
1013
+ # debug the frame count and frame selection. You dont need this. It is for debugging.
1014
+ self.debug: bool = kwargs.get('debug', False)
1015
+
1016
+ # automatic controls
1017
+ self.controls: List[ControlTypes] = kwargs.get('controls', [])
1018
+ if isinstance(self.controls, str):
1019
+ self.controls = [self.controls]
1020
+ # remove empty strings
1021
+ self.controls = [control for control in self.controls if control.strip() != '']
1022
+
1023
+ # if true, will use a fask method to get image sizes. This can result in errors. Do not use unless you know what you are doing
1024
+ self.fast_image_size: bool = kwargs.get('fast_image_size', False)
1025
+
1026
+ self.do_i2v: bool = kwargs.get('do_i2v', True) # do image to video on models that are both t2i and i2v capable
1027
+ self.do_audio: bool = kwargs.get('do_audio', False) # load audio from video files for models that support it
1028
+ self.audio_preserve_pitch: bool = kwargs.get('audio_preserve_pitch', False) # preserve pitch when stretching audio to fit num_frames
1029
+ self.audio_normalize: bool = kwargs.get('audio_normalize', False) # normalize audio volume levels when loading
1030
+
1031
+
1032
+ def preprocess_dataset_raw_config(raw_config: List[dict]) -> List[dict]:
1033
+ """
1034
+ This just splits up the datasets by resolutions so you dont have to do it manually
1035
+ :param raw_config:
1036
+ :return:
1037
+ """
1038
+ # split up datasets by resolutions
1039
+ new_config = []
1040
+ for dataset in raw_config:
1041
+ resolution = dataset.get('resolution', 512)
1042
+ if isinstance(resolution, list):
1043
+ resolution_list = resolution
1044
+ else:
1045
+ resolution_list = [resolution]
1046
+ for res in resolution_list:
1047
+ dataset_copy = dataset.copy()
1048
+ dataset_copy['resolution'] = res
1049
+ new_config.append(dataset_copy)
1050
+ return new_config
1051
+
1052
+
1053
+ class GenerateImageConfig:
1054
+ def __init__(
1055
+ self,
1056
+ prompt: str = '',
1057
+ prompt_2: Optional[str] = None,
1058
+ width: int = 512,
1059
+ height: int = 512,
1060
+ num_inference_steps: int = 50,
1061
+ guidance_scale: float = 7.5,
1062
+ negative_prompt: str = '',
1063
+ negative_prompt_2: Optional[str] = None,
1064
+ seed: int = -1,
1065
+ network_multiplier: float = 1.0,
1066
+ guidance_rescale: float = 0.0,
1067
+ # the tag [time] will be replaced with milliseconds since epoch
1068
+ output_path: str = None, # full image path
1069
+ output_folder: str = None, # folder to save image in if output_path is not specified
1070
+ output_ext: str = ImgExt, # extension to save image as if output_path is not specified
1071
+ output_tail: str = '', # tail to add to output filename
1072
+ add_prompt_file: bool = False, # add a prompt file with generated image
1073
+ adapter_image_path: str = None, # path to adapter image
1074
+ adapter_conditioning_scale: float = 1.0, # scale for adapter conditioning
1075
+ latents: Union[torch.Tensor | None] = None, # input latent to start with,
1076
+ extra_kwargs: dict = None, # extra data to save with prompt file
1077
+ refiner_start_at: float = 0.5, # start at this percentage of a step. 0.0 to 1.0 . 1.0 is the end
1078
+ extra_values: List[float] = None, # extra values to save with prompt file
1079
+ logger: Optional[EmptyLogger] = None,
1080
+ ctrl_img: Optional[str] = None, # control image for controlnet
1081
+ ctrl_img_1: Optional[str] = None, # first control image for multi control model
1082
+ ctrl_img_2: Optional[str] = None, # second control image for multi control model
1083
+ ctrl_img_3: Optional[str] = None, # third control image for multi control model
1084
+ num_frames: int = 1,
1085
+ fps: int = 15,
1086
+ ctrl_idx: int = 0,
1087
+ do_cfg_norm: bool = False,
1088
+ ):
1089
+ self.width: int = width
1090
+ self.height: int = height
1091
+ self.num_inference_steps: int = num_inference_steps
1092
+ self.guidance_scale: float = guidance_scale
1093
+ self.guidance_rescale: float = guidance_rescale
1094
+ self.prompt: str = prompt
1095
+ self.prompt_2: str = prompt_2
1096
+ self.negative_prompt: str = negative_prompt
1097
+ self.negative_prompt_2: str = negative_prompt_2
1098
+ self.latents: Union[torch.Tensor | None] = latents
1099
+
1100
+ self.output_path: str = output_path
1101
+ self.seed: int = seed
1102
+ if self.seed == -1:
1103
+ # generate random one
1104
+ self.seed = random.randint(0, 2 ** 32 - 1)
1105
+ self.network_multiplier: float = network_multiplier
1106
+ self.output_folder: str = output_folder
1107
+ self.output_ext: str = output_ext
1108
+ self.add_prompt_file: bool = add_prompt_file
1109
+ self.output_tail: str = output_tail
1110
+ self.gen_time: int = int(time.time() * 1000)
1111
+ self.adapter_image_path: str = adapter_image_path
1112
+ self.adapter_conditioning_scale: float = adapter_conditioning_scale
1113
+ self.extra_kwargs = extra_kwargs if extra_kwargs is not None else {}
1114
+ self.refiner_start_at = refiner_start_at
1115
+ self.extra_values = extra_values if extra_values is not None else []
1116
+ self.num_frames = num_frames
1117
+ self.fps = fps
1118
+ self.ctrl_img = ctrl_img
1119
+ self.ctrl_idx = ctrl_idx
1120
+
1121
+ if ctrl_img_1 is None and ctrl_img is not None:
1122
+ ctrl_img_1 = ctrl_img
1123
+
1124
+ self.ctrl_img_1 = ctrl_img_1
1125
+ self.ctrl_img_2 = ctrl_img_2
1126
+ self.ctrl_img_3 = ctrl_img_3
1127
+
1128
+ # prompt string will override any settings above
1129
+ self._process_prompt_string()
1130
+
1131
+ # handle dual text encoder prompts if nothing passed
1132
+ if negative_prompt_2 is None:
1133
+ self.negative_prompt_2 = negative_prompt
1134
+
1135
+ if prompt_2 is None:
1136
+ self.prompt_2 = self.prompt
1137
+
1138
+ # parse prompt paths
1139
+ if self.output_path is None and self.output_folder is None:
1140
+ raise ValueError('output_path or output_folder must be specified')
1141
+ elif self.output_path is not None:
1142
+ self.output_folder = os.path.dirname(self.output_path)
1143
+ self.output_ext = os.path.splitext(self.output_path)[1][1:]
1144
+ self.output_filename_no_ext = os.path.splitext(os.path.basename(self.output_path))[0]
1145
+
1146
+ else:
1147
+ self.output_filename_no_ext = '[time]_[count]'
1148
+ if len(self.output_tail) > 0:
1149
+ self.output_filename_no_ext += '_' + self.output_tail
1150
+ self.output_path = os.path.join(self.output_folder, self.output_filename_no_ext + '.' + self.output_ext)
1151
+
1152
+ # adjust height
1153
+ self.height = max(64, self.height - self.height % 8) # round to divisible by 8
1154
+ self.width = max(64, self.width - self.width % 8) # round to divisible by 8
1155
+
1156
+ self.logger = logger
1157
+
1158
+ self.do_cfg_norm: bool = do_cfg_norm
1159
+
1160
+ def set_gen_time(self, gen_time: int = None):
1161
+ if gen_time is not None:
1162
+ self.gen_time = gen_time
1163
+ else:
1164
+ self.gen_time = int(time.time() * 1000)
1165
+
1166
+ def _get_path_no_ext(self, count: int = 0, max_count=0):
1167
+ # zero pad count
1168
+ count_str = str(count).zfill(len(str(max_count)))
1169
+ # replace [time] with gen time
1170
+ filename = self.output_filename_no_ext.replace('[time]', str(self.gen_time))
1171
+ # replace [count] with count
1172
+ filename = filename.replace('[count]', count_str)
1173
+ return filename
1174
+
1175
+ def get_image_path(self, count: int = 0, max_count=0):
1176
+ filename = self._get_path_no_ext(count, max_count)
1177
+ ext = self.output_ext
1178
+ # if it does not start with a dot add one
1179
+ if ext[0] != '.':
1180
+ ext = '.' + ext
1181
+ filename += ext
1182
+ # join with folder
1183
+ return os.path.join(self.output_folder, filename)
1184
+
1185
+ def get_prompt_path(self, count: int = 0, max_count=0):
1186
+ filename = self._get_path_no_ext(count, max_count)
1187
+ filename += '.txt'
1188
+ # join with folder
1189
+ return os.path.join(self.output_folder, filename)
1190
+
1191
+ def save_image(self, image, count: int = 0, max_count=0):
1192
+ # make parent dirs
1193
+ os.makedirs(self.output_folder, exist_ok=True)
1194
+ self.set_gen_time()
1195
+ if isinstance(image, list):
1196
+ # video
1197
+ if self.num_frames == 1:
1198
+ raise ValueError(f"Expected 1 img but got a list {len(image)}")
1199
+ if self.num_frames > 1 and self.output_ext not in ['webp']:
1200
+ self.output_ext = 'webp'
1201
+ if self.output_ext == 'webp':
1202
+ # save as animated webp
1203
+ duration = 1000 // self.fps # Convert fps to milliseconds per frame
1204
+ image[0].save(
1205
+ self.get_image_path(count, max_count),
1206
+ format='WEBP',
1207
+ append_images=image[1:],
1208
+ save_all=True,
1209
+ duration=duration, # Duration per frame in milliseconds
1210
+ loop=0, # 0 means loop forever
1211
+ quality=80 # Quality setting (0-100)
1212
+ )
1213
+ else:
1214
+ raise ValueError(f"Unsupported video format {self.output_ext}")
1215
+ elif self.output_ext in ['wav', 'mp3', 'flac', 'ogg']:
1216
+ # save audio file
1217
+ audio_path = self.get_image_path(count, max_count)
1218
+ torchaudio.save(
1219
+ audio_path,
1220
+ image[0].to('cpu'),
1221
+ sample_rate=48000,
1222
+ format=None,
1223
+ backend=None
1224
+ )
1225
+ if self.output_ext == 'mp3':
1226
+ add_album_artwork(audio_path)
1227
+ else:
1228
+ # TODO save image gen header info for A1111 and us, our seeds probably wont match
1229
+ image.save(self.get_image_path(count, max_count))
1230
+ # do prompt file
1231
+ if self.add_prompt_file:
1232
+ self.save_prompt_file(count, max_count)
1233
+
1234
+ def save_prompt_file(self, count: int = 0, max_count=0):
1235
+ # save prompt file
1236
+ with open(self.get_prompt_path(count, max_count), 'w') as f:
1237
+ prompt = self.prompt
1238
+ if self.prompt_2 is not None:
1239
+ prompt += ' --p2 ' + self.prompt_2
1240
+ if self.negative_prompt is not None:
1241
+ prompt += ' --n ' + self.negative_prompt
1242
+ if self.negative_prompt_2 is not None:
1243
+ prompt += ' --n2 ' + self.negative_prompt_2
1244
+ prompt += ' --w ' + str(self.width)
1245
+ prompt += ' --h ' + str(self.height)
1246
+ prompt += ' --seed ' + str(self.seed)
1247
+ prompt += ' --cfg ' + str(self.guidance_scale)
1248
+ prompt += ' --steps ' + str(self.num_inference_steps)
1249
+ prompt += ' --m ' + str(self.network_multiplier)
1250
+ prompt += ' --gr ' + str(self.guidance_rescale)
1251
+
1252
+ # get gen info
1253
+ try:
1254
+ f.write(self.prompt)
1255
+ except Exception as e:
1256
+ print(f"Error writing prompt file. Prompt contains non-unicode characters. {e}")
1257
+
1258
+ def _process_prompt_string(self):
1259
+ # we will try to support all sd-scripts where we can
1260
+
1261
+ # FROM SD-SCRIPTS
1262
+ # --n Treat everything until the next option as a negative prompt.
1263
+ # --w Specify the width of the generated image.
1264
+ # --h Specify the height of the generated image.
1265
+ # --d Specify the seed for the generated image.
1266
+ # --l Specify the CFG scale for the generated image.
1267
+ # --s Specify the number of steps during generation.
1268
+
1269
+ # OURS and some QOL additions
1270
+ # --m Specify the network multiplier for the generated image.
1271
+ # --p2 Prompt for the second text encoder (SDXL only)
1272
+ # --n2 Negative prompt for the second text encoder (SDXL only)
1273
+ # --gr Specify the guidance rescale for the generated image (SDXL only)
1274
+
1275
+ # --seed Specify the seed for the generated image same as --d
1276
+ # --cfg Specify the CFG scale for the generated image same as --l
1277
+ # --steps Specify the number of steps during generation same as --s
1278
+ # --network_multiplier Specify the network multiplier for the generated image same as --m
1279
+
1280
+ # process prompt string and update values if it has some
1281
+ if self.prompt is not None and len(self.prompt) > 0:
1282
+ # process prompt string
1283
+ prompt = self.prompt
1284
+ prompt = prompt.strip()
1285
+ p_split = prompt.split('--')
1286
+ self.prompt = p_split[0].strip()
1287
+
1288
+ if len(p_split) > 1:
1289
+ for split in p_split[1:]:
1290
+ # allows multi char flags
1291
+ flag = split.split(' ')[0].strip()
1292
+ content = split[len(flag):].strip()
1293
+ if flag == 'p2':
1294
+ self.prompt_2 = content
1295
+ elif flag == 'n':
1296
+ self.negative_prompt = content
1297
+ elif flag == 'n2':
1298
+ self.negative_prompt_2 = content
1299
+ elif flag == 'w':
1300
+ self.width = int(content)
1301
+ elif flag == 'h':
1302
+ self.height = int(content)
1303
+ elif flag == 'd':
1304
+ self.seed = int(content)
1305
+ elif flag == 'seed':
1306
+ self.seed = int(content)
1307
+ elif flag == 'l':
1308
+ self.guidance_scale = float(content)
1309
+ elif flag == 'cfg':
1310
+ self.guidance_scale = float(content)
1311
+ elif flag == 's':
1312
+ self.num_inference_steps = int(content)
1313
+ elif flag == 'steps':
1314
+ self.num_inference_steps = int(content)
1315
+ elif flag == 'm':
1316
+ self.network_multiplier = float(content)
1317
+ elif flag == 'network_multiplier':
1318
+ self.network_multiplier = float(content)
1319
+ elif flag == 'gr':
1320
+ self.guidance_rescale = float(content)
1321
+ elif flag == 'a':
1322
+ self.adapter_conditioning_scale = float(content)
1323
+ elif flag == 'ref':
1324
+ self.refiner_start_at = float(content)
1325
+ elif flag == 'ev':
1326
+ # split by comma
1327
+ self.extra_values = [float(val) for val in content.split(',')]
1328
+ elif flag == 'extra_values':
1329
+ # split by comma
1330
+ self.extra_values = [float(val) for val in content.split(',')]
1331
+ elif flag == 'frames':
1332
+ self.num_frames = int(content)
1333
+ elif flag == 'num_frames':
1334
+ self.num_frames = int(content)
1335
+ elif flag == 'fps':
1336
+ self.fps = int(content)
1337
+ elif flag == 'ctrl_img':
1338
+ self.ctrl_img = content
1339
+ elif flag == 'ctrl_idx':
1340
+ self.ctrl_idx = int(content)
1341
+
1342
+ def post_process_embeddings(
1343
+ self,
1344
+ conditional_prompt_embeds: PromptEmbeds,
1345
+ unconditional_prompt_embeds: Optional[PromptEmbeds] = None,
1346
+ ):
1347
+ # this is called after prompt embeds are encoded. We can override them in the future here
1348
+ pass
1349
+
1350
+ def log_image(self, image, count: int = 0, max_count=0):
1351
+ if self.logger is None:
1352
+ return
1353
+
1354
+ self.logger.log_image(image, count, self.prompt)
1355
+
1356
+
1357
+ def validate_configs(
1358
+ train_config: TrainConfig,
1359
+ model_config: ModelConfig,
1360
+ save_config: SaveConfig,
1361
+ dataset_configs: List[DatasetConfig]
1362
+ ):
1363
+ if model_config.is_flux:
1364
+ if save_config.save_format != 'diffusers':
1365
+ # make it diffusers
1366
+ save_config.save_format = 'diffusers'
1367
+ if model_config.use_flux_cfg:
1368
+ # bypass the embedding
1369
+ train_config.bypass_guidance_embedding = True
1370
+ if train_config.bypass_guidance_embedding and train_config.do_guidance_loss:
1371
+ raise ValueError("Cannot bypass guidance embedding and do guidance loss at the same time. "
1372
+ "Please set bypass_guidance_embedding to False or do_guidance_loss to False.")
1373
+
1374
+ if model_config.accuracy_recovery_adapter is not None:
1375
+ if model_config.assistant_lora_path is not None:
1376
+ raise ValueError("Cannot use accuracy recovery adapter and assistant lora at the same time. "
1377
+ "Please set one of them to None.")
1378
+
1379
+ # see if any datasets are caching text embeddings
1380
+ is_caching_text_embeddings = any(dataset.cache_text_embeddings for dataset in dataset_configs)
1381
+ if is_caching_text_embeddings:
1382
+
1383
+ # check if they are doing differential output preservation
1384
+ if train_config.diff_output_preservation:
1385
+ raise ValueError("Cannot use differential output preservation with caching text embeddings. Please set diff_output_preservation to False.")
1386
+
1387
+ # make sure they are all cached
1388
+ for dataset in dataset_configs:
1389
+ if not dataset.cache_text_embeddings:
1390
+ raise ValueError("All datasets must have cache_text_embeddings set to True when caching text embeddings is enabled.")
1391
+
1392
+ # qwen image edit cannot cache text embeddings
1393
+ if model_config.arch == 'qwen_image_edit':
1394
+ if train_config.unload_text_encoder:
1395
+ raise ValueError("Cannot cache unload text encoder with qwen_image_edit model. Control images are encoded with text embeddings. You can cache the text embeddings though")
1396
+
1397
+ if train_config.diff_output_preservation and train_config.blank_prompt_preservation:
1398
+ raise ValueError("Cannot use both differential output preservation and blank prompt preservation at the same time. Please set one of them to False.")
1399
+
1400
+ if train_config.batch_size > 1 and any(dataset_config.auto_frame_count for dataset_config in dataset_configs):
1401
+ raise ValueError("Cannot use batch size greater than 1 with auto_frame_count. Please set batch_size to 1 or auto_frame_count to False.")
1402
+
1403
+
toolkit/control_generator.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import math
3
+ import os
4
+ import torch
5
+ from typing import Literal
6
+ from PIL import Image, ImageFilter, ImageOps
7
+ from PIL.ImageOps import exif_transpose
8
+ from tqdm import tqdm
9
+
10
+ from torchvision import transforms
11
+
12
+ # supress all warnings
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore", category=UserWarning)
16
+ warnings.filterwarnings("ignore", category=FutureWarning)
17
+
18
+
19
+ def flush(garbage_collect=True):
20
+ torch.cuda.empty_cache()
21
+ if garbage_collect:
22
+ gc.collect()
23
+
24
+
25
+ ControlTypes = Literal['depth', 'pose', 'line', 'inpaint', 'mask']
26
+
27
+ img_ext_list = ['.jpg', '.jpeg', '.png', '.webp']
28
+
29
+
30
+ class ControlGenerator:
31
+ def __init__(self, device, sd=None):
32
+ self.device = device
33
+ self.sd = sd # optional. It will unload the model if not None
34
+ self.has_unloaded = False
35
+ self.control_depth_model = None
36
+ self.control_pose_model = None
37
+ self.control_line_model = None
38
+ self.control_bg_remover = None
39
+ self.debug = False
40
+ self.regen = False
41
+
42
+ def get_control_path(self, img_path, control_type: ControlTypes):
43
+ if self.regen:
44
+ return self._generate_control(img_path, control_type)
45
+ coltrols_folder = os.path.join(os.path.dirname(img_path), '_controls')
46
+ file_name_no_ext = os.path.splitext(os.path.basename(img_path))[0]
47
+ file_name_no_ext_control = f"{file_name_no_ext}.{control_type}"
48
+ for ext in img_ext_list:
49
+ possible_path = os.path.join(
50
+ coltrols_folder, file_name_no_ext_control + ext)
51
+ if os.path.exists(possible_path):
52
+ return possible_path
53
+ # if we get here, we need to generate the control
54
+ return self._generate_control(img_path, control_type)
55
+
56
+ def debug_print(self, *args, **kwargs):
57
+ if self.debug:
58
+ print(*args, **kwargs)
59
+
60
+ def _generate_control(self, img_path, control_type):
61
+ device = self.device
62
+ image: Image = None
63
+
64
+ coltrols_folder = os.path.join(os.path.dirname(img_path), '_controls')
65
+ file_name_no_ext = os.path.splitext(os.path.basename(img_path))[0]
66
+
67
+ # we need to generate the control. Unload model if not unloaded
68
+ if not self.has_unloaded:
69
+ if self.sd is not None:
70
+ print("Unloading model to generate controls")
71
+ self.sd.set_device_state_preset('unload')
72
+ self.has_unloaded = True
73
+
74
+ if image is None:
75
+ # make sure image is loaded if we havent loaded it with another control
76
+ image = Image.open(img_path).convert('RGB')
77
+ image = exif_transpose(image)
78
+
79
+ # resize to a max of 1mp
80
+ max_size = 1024 * 1024
81
+
82
+ w, h = image.size
83
+ if w * h > max_size:
84
+ scale = math.sqrt(max_size / (w * h))
85
+ w = int(w * scale)
86
+ h = int(h * scale)
87
+ image = image.resize((w, h), Image.BICUBIC)
88
+
89
+ save_path = os.path.join(
90
+ coltrols_folder, f"{file_name_no_ext}.{control_type}.jpg")
91
+ os.makedirs(coltrols_folder, exist_ok=True)
92
+ if control_type == 'depth':
93
+ self.debug_print("Generating depth control")
94
+ if self.control_depth_model is None:
95
+ from transformers import pipeline
96
+ self.control_depth_model = pipeline(
97
+ task="depth-estimation",
98
+ model="depth-anything/Depth-Anything-V2-Large-hf",
99
+ device=device,
100
+ torch_dtype=torch.float16
101
+ )
102
+ img = image.copy()
103
+ in_size = img.size
104
+ output = self.control_depth_model(img)
105
+ out_tensor = output["predicted_depth"] # shape (1, H, W) 0 - 255
106
+ out_tensor = out_tensor.clamp(0, 255)
107
+ out_tensor = out_tensor.squeeze(0).cpu().numpy()
108
+ img = Image.fromarray(out_tensor.astype('uint8'))
109
+ img = img.resize(in_size, Image.LANCZOS)
110
+ img.save(save_path)
111
+ return save_path
112
+ elif control_type == 'pose':
113
+ self.debug_print("Generating pose control")
114
+ if self.control_pose_model is None:
115
+ try:
116
+ import onnxruntime
117
+ onnxruntime.set_default_logger_severity(3)
118
+ except ImportError:
119
+ raise ImportError(
120
+ "onnxruntime is not installed. Please install it with pip install onnxruntime or onnxruntime-gpu")
121
+ try:
122
+ from easy_dwpose import DWposeDetector
123
+ self.control_pose_model = DWposeDetector(
124
+ device=str(device))
125
+ except ImportError:
126
+ raise ImportError(
127
+ "easy-dwpose is not installed. Please install it with pip install git+https://github.com/jaretburkett/easy_dwpose.git")
128
+ img = image.copy()
129
+
130
+ detect_res = int(math.sqrt(img.size[0] * img.size[1]))
131
+ img = self.control_pose_model(
132
+ img, output_type="pil", include_hands=True, include_face=True, detect_resolution=detect_res)
133
+ img = img.convert('RGB')
134
+ img.save(save_path)
135
+ return save_path
136
+
137
+ elif control_type == 'line':
138
+ self.debug_print("Generating line control")
139
+ if self.control_line_model is None:
140
+ from controlnet_aux import TEEDdetector
141
+ self.control_line_model = TEEDdetector.from_pretrained(
142
+ "fal-ai/teed", filename="5_model.pth").to(device)
143
+ img = image.copy()
144
+ img = self.control_line_model(img, detect_resolution=1024)
145
+ # apply threshold
146
+ # img = img.filter(ImageFilter.GaussianBlur(radius=1))
147
+ img = img.point(lambda p: p > 128 and 255)
148
+ img = img.convert('RGB')
149
+ img.save(save_path)
150
+ return save_path
151
+ elif control_type in ['inpaint', 'mask']:
152
+ self.debug_print("Generating inpaint/mask control")
153
+ img = image.copy()
154
+ if self.control_bg_remover is None:
155
+ from transformers import AutoModelForImageSegmentation
156
+ self.control_bg_remover = AutoModelForImageSegmentation.from_pretrained(
157
+ 'ZhengPeng7/BiRefNet_HR',
158
+ trust_remote_code=True,
159
+ revision="595e212b3eaa6a1beaad56cee49749b1e00b1596",
160
+ torch_dtype=torch.float16
161
+ ).to(device)
162
+ self.control_bg_remover.eval()
163
+
164
+ image_size = (1024, 1024)
165
+ transform_image = transforms.Compose([
166
+ transforms.Resize(image_size),
167
+ transforms.ToTensor(),
168
+ transforms.Normalize([0.485, 0.456, 0.406], [
169
+ 0.229, 0.224, 0.225])
170
+ ])
171
+
172
+ input_images = transform_image(img).unsqueeze(
173
+ 0).to('cuda').to(torch.float16)
174
+
175
+ # Prediction
176
+ preds = self.control_bg_remover(input_images)[-1].sigmoid().cpu()
177
+ pred = preds[0].squeeze()
178
+ pred_pil = transforms.ToPILImage()(pred)
179
+ mask = pred_pil.resize(img.size)
180
+ if control_type == 'inpaint':
181
+ # inpainting feature currently only supports "erased" section desired to inpaint
182
+ mask = ImageOps.invert(mask)
183
+ img.putalpha(mask)
184
+ save_path = os.path.join(
185
+ coltrols_folder, f"{file_name_no_ext}.{control_type}.webp")
186
+ else:
187
+ img = mask
188
+ img = img.convert('RGB')
189
+ img.save(save_path)
190
+ return save_path
191
+ elif control_type in ['sapiens2_mask']:
192
+ self.debug_print("Generating sapiens2_mask control")
193
+ if self.control_bg_remover is None:
194
+ from toolkit.models.sapiens2 import Sapiens2Matting
195
+ self.control_bg_remover = Sapiens2Matting.from_pretrained(
196
+ device=device,
197
+ dtype=torch.float16
198
+ )
199
+ img = image.copy()
200
+ img = self.control_bg_remover(img)
201
+ img.save(save_path)
202
+ return save_path
203
+ else:
204
+ raise Exception(f"Error: unknown control type {control_type}")
205
+
206
+ def cleanup(self):
207
+ if self.control_depth_model is not None:
208
+ self.control_depth_model = None
209
+ if self.control_pose_model is not None:
210
+ self.control_pose_model = None
211
+ if self.control_line_model is not None:
212
+ self.control_line_model = None
213
+ if self.control_bg_remover is not None:
214
+ self.control_bg_remover = None
215
+ if self.sd is not None and self.has_unloaded:
216
+ self.sd.restore_device_state()
217
+ self.has_unloaded = False
218
+
219
+ flush()
220
+
221
+
222
+ if __name__ == "__main__":
223
+ import sys
224
+ import argparse
225
+ import time
226
+ import transformers
227
+ transformers.logging.set_verbosity_error()
228
+
229
+ control_times = {
230
+ 'depth': 0,
231
+ 'pose': 0,
232
+ 'line': 0,
233
+ 'inpaint': 0,
234
+ 'mask': 0
235
+ }
236
+
237
+ controls = control_times.keys()
238
+
239
+ parser = argparse.ArgumentParser(description="Generate control images")
240
+ parser.add_argument("img_dir", type=str, help="Path to image directory")
241
+ parser.add_argument('--debug', action='store_true',
242
+ help="Enable debug mode")
243
+ parser.add_argument('--regen', action='store_true',
244
+ help="Regenerate all controls")
245
+
246
+ args = parser.parse_args()
247
+ img_dir = args.img_dir
248
+ if not os.path.exists(img_dir):
249
+ print(f"Error: {img_dir} does not exist")
250
+ exit()
251
+ if not os.path.isdir(img_dir):
252
+ print(f"Error: {img_dir} is not a directory")
253
+ exit()
254
+
255
+ # find images
256
+ img_list = []
257
+ for root, dirs, files in os.walk(img_dir):
258
+ for file in files:
259
+ if "_controls" in root:
260
+ continue
261
+ if file.startswith('.'):
262
+ continue
263
+ if file.lower().endswith(tuple(img_ext_list)):
264
+ img_list.append(os.path.join(root, file))
265
+ if len(img_list) == 0:
266
+ print(f"Error: no images found in {img_dir}")
267
+ exit()
268
+
269
+ # load model
270
+ idx = 0
271
+ for img_path in tqdm(img_list):
272
+ for control in controls:
273
+ start = time.time()
274
+ control_gen = ControlGenerator(torch.device('cuda'))
275
+ control_gen.debug = args.debug
276
+ control_gen.regen = args.regen
277
+ control_path = control_gen.get_control_path(img_path, control)
278
+ end = time.time()
279
+ # dont track for first 2 images
280
+ if idx < 2:
281
+ continue
282
+ control_times[control] += end - start
283
+ idx += 1
284
+
285
+ # determine avgt time
286
+ for control in controls:
287
+ control_times[control] /= (idx - 2)
288
+ print(
289
+ f"Avg time for {control} control: {control_times[control]:.2f} seconds")
290
+
291
+ print("Done")
toolkit/cuda_malloc.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref comfy ui
2
+ import os
3
+ import importlib.util
4
+
5
+
6
+ # Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
7
+ def get_gpu_names():
8
+ if os.name == 'nt':
9
+ import ctypes
10
+
11
+ # Define necessary C structures and types
12
+ class DISPLAY_DEVICEA(ctypes.Structure):
13
+ _fields_ = [
14
+ ('cb', ctypes.c_ulong),
15
+ ('DeviceName', ctypes.c_char * 32),
16
+ ('DeviceString', ctypes.c_char * 128),
17
+ ('StateFlags', ctypes.c_ulong),
18
+ ('DeviceID', ctypes.c_char * 128),
19
+ ('DeviceKey', ctypes.c_char * 128)
20
+ ]
21
+
22
+ # Load user32.dll
23
+ user32 = ctypes.windll.user32
24
+
25
+ # Call EnumDisplayDevicesA
26
+ def enum_display_devices():
27
+ device_info = DISPLAY_DEVICEA()
28
+ device_info.cb = ctypes.sizeof(device_info)
29
+ device_index = 0
30
+ gpu_names = set()
31
+
32
+ while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
33
+ device_index += 1
34
+ gpu_names.add(device_info.DeviceString.decode('utf-8'))
35
+ return gpu_names
36
+
37
+ return enum_display_devices()
38
+ else:
39
+ return set()
40
+
41
+
42
+ blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950",
43
+ "GeForce 945M",
44
+ "GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745",
45
+ "Quadro K620",
46
+ "Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
47
+ "Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000",
48
+ "Quadro M5500", "Quadro M6000",
49
+ "GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
50
+ "GeForce GTX 1650", "GeForce GTX 1630"
51
+ }
52
+
53
+
54
+ def cuda_malloc_supported():
55
+ try:
56
+ names = get_gpu_names()
57
+ except:
58
+ names = set()
59
+ for x in names:
60
+ if "NVIDIA" in x:
61
+ for b in blacklist:
62
+ if b in x:
63
+ return False
64
+ return True
65
+
66
+
67
+ cuda_malloc = False
68
+
69
+ if not cuda_malloc:
70
+ try:
71
+ version = ""
72
+ torch_spec = importlib.util.find_spec("torch")
73
+ for folder in torch_spec.submodule_search_locations:
74
+ ver_file = os.path.join(folder, "version.py")
75
+ if os.path.isfile(ver_file):
76
+ spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
77
+ module = importlib.util.module_from_spec(spec)
78
+ spec.loader.exec_module(module)
79
+ version = module.__version__
80
+ if int(version[0]) >= 2: # enable by default for torch version 2.0 and up
81
+ cuda_malloc = cuda_malloc_supported()
82
+ except:
83
+ pass
84
+
85
+ if cuda_malloc:
86
+ env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
87
+ if env_var is None:
88
+ env_var = "backend:cudaMallocAsync"
89
+ else:
90
+ env_var += ",backend:cudaMallocAsync"
91
+
92
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
93
+ print("CUDA Malloc Async Enabled")
toolkit/custom_adapter.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import sys
4
+
5
+ from PIL import Image
6
+ from torch.nn import Parameter
7
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, T5EncoderModel, CLIPTextModel, \
8
+ CLIPTokenizer, T5Tokenizer
9
+
10
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
11
+ from toolkit.models.clip_fusion import CLIPFusionModule
12
+ from toolkit.models.clip_pre_processor import CLIPImagePreProcessor
13
+ from toolkit.models.control_lora_adapter import ControlLoraAdapter
14
+ from toolkit.models.mean_flow_adapter import MeanFlowAdapter
15
+ from toolkit.models.i2v_adapter import I2VAdapter
16
+ from toolkit.models.subpixel_adapter import SubpixelAdapter
17
+ from toolkit.models.ilora import InstantLoRAModule
18
+ from toolkit.models.single_value_adapter import SingleValueAdapter
19
+ from toolkit.models.te_adapter import TEAdapter
20
+ from toolkit.models.te_aug_adapter import TEAugAdapter
21
+ from toolkit.models.vd_adapter import VisionDirectAdapter
22
+ from toolkit.models.redux import ReduxImageEncoder
23
+ from toolkit.photomaker import PhotoMakerIDEncoder, FuseModule, PhotoMakerCLIPEncoder
24
+ from toolkit.saving import load_ip_adapter_model, load_custom_adapter_model
25
+ from toolkit.train_tools import get_torch_dtype
26
+ from toolkit.models.pixtral_vision import PixtralVisionEncoderCompatible, PixtralVisionImagePreprocessorCompatible
27
+ import random
28
+ from toolkit.util.mask import generate_random_mask
29
+ from typing import TYPE_CHECKING, Union, Iterator, Mapping, Any, Tuple, List, Optional, Dict
30
+ from collections import OrderedDict
31
+ from toolkit.config_modules import AdapterConfig, AdapterTypes, TrainConfig
32
+ from toolkit.prompt_utils import PromptEmbeds
33
+ import weakref
34
+
35
+ if TYPE_CHECKING:
36
+ from toolkit.stable_diffusion_model import StableDiffusion
37
+
38
+ from transformers import (
39
+ ConvNextForImageClassification,
40
+ ConvNextImageProcessor,
41
+ UMT5EncoderModel, LlamaTokenizerFast, AutoModel, AutoTokenizer, BitsAndBytesConfig
42
+ )
43
+ from toolkit.models.size_agnostic_feature_encoder import SAFEImageProcessor, SAFEVisionModel
44
+
45
+ from toolkit.models.llm_adapter import LLMAdapter
46
+
47
+ import torch.nn.functional as F
48
+
49
+
50
+ class CustomAdapter(torch.nn.Module):
51
+ def __init__(self, sd: 'StableDiffusion', adapter_config: 'AdapterConfig', train_config: 'TrainConfig'):
52
+ super().__init__()
53
+ self.config = adapter_config
54
+ self.sd_ref: weakref.ref = weakref.ref(sd)
55
+ self.train_config = train_config
56
+ self.device = self.sd_ref().unet.device
57
+ self.image_processor: CLIPImageProcessor = None
58
+ self.input_size = 224
59
+ self.adapter_type: AdapterTypes = self.config.type
60
+ self.current_scale = 1.0
61
+ self.is_active = True
62
+ self.flag_word = "fla9wor0"
63
+ self.is_unconditional_run = False
64
+ self.is_sampling = False
65
+
66
+ self.vision_encoder: Union[PhotoMakerCLIPEncoder, CLIPVisionModelWithProjection] = None
67
+
68
+ self.fuse_module: FuseModule = None
69
+
70
+ self.lora: None = None
71
+
72
+ self.position_ids: Optional[List[int]] = None
73
+
74
+ self.num_control_images = self.config.num_control_images
75
+ self.token_mask: Optional[torch.Tensor] = None
76
+
77
+ # setup clip
78
+ self.setup_clip()
79
+ # add for dataloader
80
+ self.clip_image_processor = self.image_processor
81
+
82
+ self.clip_fusion_module: CLIPFusionModule = None
83
+ self.ilora_module: InstantLoRAModule = None
84
+
85
+ self.te: Union[T5EncoderModel, CLIPTextModel] = None
86
+ self.tokenizer: CLIPTokenizer = None
87
+ self.te_adapter: TEAdapter = None
88
+ self.te_augmenter: TEAugAdapter = None
89
+ self.vd_adapter: VisionDirectAdapter = None
90
+ self.single_value_adapter: SingleValueAdapter = None
91
+ self.redux_adapter: ReduxImageEncoder = None
92
+ self.control_lora: ControlLoraAdapter = None
93
+ self.mean_flow_adapter: MeanFlowAdapter = None
94
+ self.subpixel_adapter: SubpixelAdapter = None
95
+ self.i2v_adapter: I2VAdapter = None
96
+
97
+ self.conditional_embeds: Optional[torch.Tensor] = None
98
+ self.unconditional_embeds: Optional[torch.Tensor] = None
99
+
100
+ self.cached_control_image_0_1: Optional[torch.Tensor] = None
101
+
102
+ self.setup_adapter()
103
+
104
+ if self.adapter_type == 'photo_maker':
105
+ # try to load from our name_or_path
106
+ if self.config.name_or_path is not None and self.config.name_or_path.endswith('.bin'):
107
+ self.load_state_dict(torch.load(self.config.name_or_path, map_location=self.device), strict=False)
108
+ # add the trigger word to the tokenizer
109
+ if isinstance(self.sd_ref().tokenizer, list):
110
+ for tokenizer in self.sd_ref().tokenizer:
111
+ tokenizer.add_tokens([self.flag_word], special_tokens=True)
112
+ else:
113
+ self.sd_ref().tokenizer.add_tokens([self.flag_word], special_tokens=True)
114
+ elif self.config.name_or_path is not None:
115
+ loaded_state_dict = load_custom_adapter_model(
116
+ self.config.name_or_path,
117
+ self.sd_ref().device,
118
+ dtype=self.sd_ref().dtype,
119
+ )
120
+ self.load_state_dict(loaded_state_dict, strict=False)
121
+
122
+ @property
123
+ def do_direct_save(self):
124
+ # some adapters save their weights directly, others like ip adapters split the state dict
125
+ if self.config.train_only_image_encoder:
126
+ return True
127
+ if self.config.type in ['control_lora', 'subpixel', 'i2v', 'redux', 'mean_flow']:
128
+ return True
129
+ return False
130
+
131
+
132
+ def setup_adapter(self):
133
+ torch_dtype = get_torch_dtype(self.sd_ref().dtype)
134
+ if self.adapter_type == 'photo_maker':
135
+ sd = self.sd_ref()
136
+ embed_dim = sd.unet_unwrapped.config['cross_attention_dim']
137
+ self.fuse_module = FuseModule(embed_dim)
138
+ elif self.adapter_type == 'clip_fusion':
139
+ sd = self.sd_ref()
140
+ embed_dim = sd.unet_unwrapped.config['cross_attention_dim']
141
+
142
+ vision_tokens = ((self.vision_encoder.config.image_size // self.vision_encoder.config.patch_size) ** 2)
143
+ if self.config.image_encoder_arch == 'clip':
144
+ vision_tokens = vision_tokens + 1
145
+ self.clip_fusion_module = CLIPFusionModule(
146
+ text_hidden_size=embed_dim,
147
+ text_tokens=77,
148
+ vision_hidden_size=self.vision_encoder.config.hidden_size,
149
+ vision_tokens=vision_tokens
150
+ )
151
+ elif self.adapter_type == 'ilora':
152
+ vision_tokens = ((self.vision_encoder.config.image_size // self.vision_encoder.config.patch_size) ** 2)
153
+ if self.config.image_encoder_arch == 'clip':
154
+ vision_tokens = vision_tokens + 1
155
+
156
+ vision_hidden_size = self.vision_encoder.config.hidden_size
157
+
158
+ if self.config.clip_layer == 'image_embeds':
159
+ vision_tokens = 1
160
+ vision_hidden_size = self.vision_encoder.config.projection_dim
161
+
162
+ self.ilora_module = InstantLoRAModule(
163
+ vision_tokens=vision_tokens,
164
+ vision_hidden_size=vision_hidden_size,
165
+ head_dim=self.config.head_dim,
166
+ num_heads=self.config.num_heads,
167
+ sd=self.sd_ref(),
168
+ config=self.config
169
+ )
170
+ elif self.adapter_type == 'text_encoder':
171
+ if self.config.text_encoder_arch == 't5':
172
+ te_kwargs = {}
173
+ # te_kwargs['load_in_4bit'] = True
174
+ # te_kwargs['load_in_8bit'] = True
175
+ te_kwargs['device_map'] = "auto"
176
+ te_is_quantized = True
177
+
178
+ self.te = T5EncoderModel.from_pretrained(
179
+ self.config.text_encoder_path,
180
+ torch_dtype=torch_dtype,
181
+ **te_kwargs
182
+ )
183
+
184
+ # self.te.to = lambda *args, **kwargs: None
185
+ self.tokenizer = T5Tokenizer.from_pretrained(self.config.text_encoder_path)
186
+ elif self.config.text_encoder_arch == 'pile-t5':
187
+ te_kwargs = {}
188
+ # te_kwargs['load_in_4bit'] = True
189
+ # te_kwargs['load_in_8bit'] = True
190
+ te_kwargs['device_map'] = "auto"
191
+ te_is_quantized = True
192
+
193
+ self.te = UMT5EncoderModel.from_pretrained(
194
+ self.config.text_encoder_path,
195
+ torch_dtype=torch_dtype,
196
+ **te_kwargs
197
+ )
198
+
199
+ # self.te.to = lambda *args, **kwargs: None
200
+ self.tokenizer = LlamaTokenizerFast.from_pretrained(self.config.text_encoder_path)
201
+ if self.tokenizer.pad_token is None:
202
+ self.tokenizer.add_special_tokens({'pad_token': '[PAD]'})
203
+ elif self.config.text_encoder_arch == 'clip':
204
+ self.te = CLIPTextModel.from_pretrained(self.config.text_encoder_path).to(self.sd_ref().unet.device,
205
+ dtype=torch_dtype)
206
+ self.tokenizer = CLIPTokenizer.from_pretrained(self.config.text_encoder_path)
207
+ else:
208
+ raise ValueError(f"unknown text encoder arch: {self.config.text_encoder_arch}")
209
+
210
+ self.te_adapter = TEAdapter(self, self.sd_ref(), self.te, self.tokenizer)
211
+ elif self.adapter_type == 'llm_adapter':
212
+ kwargs = {}
213
+ if self.config.quantize_llm:
214
+ bnb_kwargs = {
215
+ 'load_in_4bit': True,
216
+ 'bnb_4bit_quant_type': "nf4",
217
+ 'bnb_4bit_compute_dtype': torch.bfloat16
218
+ }
219
+ quantization_config = BitsAndBytesConfig(**bnb_kwargs)
220
+ kwargs['quantization_config'] = quantization_config
221
+ kwargs['torch_dtype'] = torch_dtype
222
+ self.te = AutoModel.from_pretrained(
223
+ self.config.text_encoder_path,
224
+ **kwargs
225
+ )
226
+ else:
227
+ self.te = AutoModel.from_pretrained(self.config.text_encoder_path).to(
228
+ self.sd_ref().unet.device,
229
+ dtype=torch_dtype,
230
+ )
231
+ self.te.to = lambda *args, **kwargs: None
232
+ self.te.eval()
233
+ self.tokenizer = AutoTokenizer.from_pretrained(self.config.text_encoder_path)
234
+ self.llm_adapter = LLMAdapter(
235
+ adapter=self,
236
+ sd=self.sd_ref(),
237
+ llm=self.te,
238
+ tokenizer=self.tokenizer,
239
+ num_cloned_blocks=self.config.num_cloned_blocks,
240
+ )
241
+ self.llm_adapter.to(self.device, torch_dtype)
242
+ elif self.adapter_type == 'te_augmenter':
243
+ self.te_augmenter = TEAugAdapter(self, self.sd_ref())
244
+ elif self.adapter_type == 'vision_direct':
245
+ self.vd_adapter = VisionDirectAdapter(self, self.sd_ref(), self.vision_encoder)
246
+ elif self.adapter_type == 'single_value':
247
+ self.single_value_adapter = SingleValueAdapter(self, self.sd_ref(), num_values=self.config.num_tokens)
248
+ elif self.adapter_type == 'redux':
249
+ vision_hidden_size = self.vision_encoder.config.hidden_size
250
+ self.redux_adapter = ReduxImageEncoder(vision_hidden_size, 4096, self.device, torch_dtype)
251
+ elif self.adapter_type == 'mean_flow':
252
+ self.mean_flow_adapter = MeanFlowAdapter(
253
+ self,
254
+ sd=self.sd_ref(),
255
+ config=self.config,
256
+ train_config=self.train_config
257
+ )
258
+ elif self.adapter_type == 'control_lora':
259
+ self.control_lora = ControlLoraAdapter(
260
+ self,
261
+ sd=self.sd_ref(),
262
+ config=self.config,
263
+ train_config=self.train_config
264
+ )
265
+ elif self.adapter_type == 'i2v':
266
+ self.i2v_adapter = I2VAdapter(
267
+ self,
268
+ sd=self.sd_ref(),
269
+ config=self.config,
270
+ train_config=self.train_config,
271
+ image_processor=self.image_processor,
272
+ vision_encoder=self.vision_encoder,
273
+ )
274
+ elif self.adapter_type == 'subpixel':
275
+ self.subpixel_adapter = SubpixelAdapter(
276
+ self,
277
+ sd=self.sd_ref(),
278
+ config=self.config,
279
+ train_config=self.train_config
280
+ )
281
+ else:
282
+ raise ValueError(f"unknown adapter type: {self.adapter_type}")
283
+
284
+ def forward(self, *args, **kwargs):
285
+ # dont think this is used
286
+ # if self.adapter_type == 'photo_maker':
287
+ # id_pixel_values = args[0]
288
+ # prompt_embeds: PromptEmbeds = args[1]
289
+ # class_tokens_mask = args[2]
290
+ #
291
+ # grads_on_image_encoder = self.config.train_image_encoder and torch.is_grad_enabled()
292
+ #
293
+ # with torch.set_grad_enabled(grads_on_image_encoder):
294
+ # id_embeds = self.vision_encoder(self, id_pixel_values, do_projection2=False)
295
+ #
296
+ # if not grads_on_image_encoder:
297
+ # id_embeds = id_embeds.detach()
298
+ #
299
+ # prompt_embeds = prompt_embeds.detach()
300
+ #
301
+ # updated_prompt_embeds = self.fuse_module(
302
+ # prompt_embeds, id_embeds, class_tokens_mask
303
+ # )
304
+ #
305
+ # return updated_prompt_embeds
306
+ # else:
307
+ raise NotImplementedError
308
+
309
+ def edit_batch_raw(self, batch: DataLoaderBatchDTO):
310
+ # happens on a raw batch before latents are created
311
+ return batch
312
+
313
+ def edit_batch_processed(self, batch: DataLoaderBatchDTO):
314
+ # happens after the latents are processed
315
+ if self.adapter_type == "i2v":
316
+ return self.i2v_adapter.edit_batch_processed(batch)
317
+ return batch
318
+
319
+ def setup_clip(self):
320
+ adapter_config = self.config
321
+ sd = self.sd_ref()
322
+ if self.config.type in ["text_encoder", "llm_adapter", "single_value", "control_lora", "subpixel", "mean_flow"]:
323
+ return
324
+ if self.config.type == 'photo_maker':
325
+ try:
326
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.config.image_encoder_path)
327
+ except EnvironmentError:
328
+ self.image_processor = CLIPImageProcessor()
329
+ if self.config.image_encoder_path is None:
330
+ self.vision_encoder = PhotoMakerCLIPEncoder()
331
+ else:
332
+ self.vision_encoder = PhotoMakerCLIPEncoder.from_pretrained(self.config.image_encoder_path)
333
+ elif self.config.image_encoder_arch == 'clip' or self.config.image_encoder_arch == 'clip+':
334
+ try:
335
+ self.image_processor = CLIPImageProcessor.from_pretrained(adapter_config.image_encoder_path)
336
+ except EnvironmentError:
337
+ self.image_processor = CLIPImageProcessor()
338
+ self.vision_encoder = CLIPVisionModelWithProjection.from_pretrained(
339
+ adapter_config.image_encoder_path,
340
+ ignore_mismatched_sizes=True).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
341
+ elif self.config.image_encoder_arch == 'siglip':
342
+ from transformers import SiglipImageProcessor, SiglipVisionModel
343
+ try:
344
+ self.image_processor = SiglipImageProcessor.from_pretrained(adapter_config.image_encoder_path)
345
+ except EnvironmentError:
346
+ self.image_processor = SiglipImageProcessor()
347
+ self.vision_encoder = SiglipVisionModel.from_pretrained(
348
+ adapter_config.image_encoder_path,
349
+ ignore_mismatched_sizes=True).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
350
+ elif self.config.image_encoder_arch == 'siglip2':
351
+ from transformers import SiglipImageProcessor, SiglipVisionModel
352
+ try:
353
+ self.image_processor = SiglipImageProcessor.from_pretrained(adapter_config.image_encoder_path)
354
+ except EnvironmentError:
355
+ self.image_processor = SiglipImageProcessor()
356
+ self.vision_encoder = SiglipVisionModel.from_pretrained(
357
+ adapter_config.image_encoder_path,
358
+ ignore_mismatched_sizes=True).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
359
+ elif self.config.image_encoder_arch == 'pixtral':
360
+ self.image_processor = PixtralVisionImagePreprocessorCompatible(
361
+ max_image_size=self.config.pixtral_max_image_size,
362
+ )
363
+ self.vision_encoder = PixtralVisionEncoderCompatible.from_pretrained(
364
+ adapter_config.image_encoder_path,
365
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
366
+ elif self.config.image_encoder_arch == 'safe':
367
+ try:
368
+ self.image_processor = SAFEImageProcessor.from_pretrained(adapter_config.image_encoder_path)
369
+ except EnvironmentError:
370
+ self.image_processor = SAFEImageProcessor()
371
+ self.vision_encoder = SAFEVisionModel(
372
+ in_channels=3,
373
+ num_tokens=self.config.safe_tokens,
374
+ num_vectors=sd.unet_unwrapped.config['cross_attention_dim'],
375
+ reducer_channels=self.config.safe_reducer_channels,
376
+ channels=self.config.safe_channels,
377
+ downscale_factor=8
378
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
379
+ elif self.config.image_encoder_arch == 'convnext':
380
+ try:
381
+ self.image_processor = ConvNextImageProcessor.from_pretrained(adapter_config.image_encoder_path)
382
+ except EnvironmentError:
383
+ print(f"could not load image processor from {adapter_config.image_encoder_path}")
384
+ self.image_processor = ConvNextImageProcessor(
385
+ size=320,
386
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
387
+ image_std=[0.26862954, 0.26130258, 0.27577711],
388
+ )
389
+ self.vision_encoder = ConvNextForImageClassification.from_pretrained(
390
+ adapter_config.image_encoder_path,
391
+ use_safetensors=True,
392
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
393
+ else:
394
+ raise ValueError(f"unknown image encoder arch: {adapter_config.image_encoder_arch}")
395
+
396
+ self.input_size = self.vision_encoder.config.image_size
397
+
398
+ if self.config.quad_image: # 4x4 image
399
+ # self.clip_image_processor.config
400
+ # We do a 3x downscale of the image, so we need to adjust the input size
401
+ preprocessor_input_size = self.vision_encoder.config.image_size * 2
402
+
403
+ # update the preprocessor so images come in at the right size
404
+ if 'height' in self.image_processor.size:
405
+ self.image_processor.size['height'] = preprocessor_input_size
406
+ self.image_processor.size['width'] = preprocessor_input_size
407
+ elif hasattr(self.image_processor, 'crop_size'):
408
+ self.image_processor.size['shortest_edge'] = preprocessor_input_size
409
+ self.image_processor.crop_size['height'] = preprocessor_input_size
410
+ self.image_processor.crop_size['width'] = preprocessor_input_size
411
+
412
+ if self.config.image_encoder_arch == 'clip+':
413
+ # self.image_processor.config
414
+ # We do a 3x downscale of the image, so we need to adjust the input size
415
+ preprocessor_input_size = self.vision_encoder.config.image_size * 4
416
+
417
+ # update the preprocessor so images come in at the right size
418
+ self.image_processor.size['shortest_edge'] = preprocessor_input_size
419
+ self.image_processor.crop_size['height'] = preprocessor_input_size
420
+ self.image_processor.crop_size['width'] = preprocessor_input_size
421
+
422
+ self.preprocessor = CLIPImagePreProcessor(
423
+ input_size=preprocessor_input_size,
424
+ clip_input_size=self.vision_encoder.config.image_size,
425
+ )
426
+ if 'height' in self.image_processor.size:
427
+ self.input_size = self.image_processor.size['height']
428
+ else:
429
+ self.input_size = self.image_processor.crop_size['height']
430
+
431
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
432
+ strict = False
433
+ if self.config.train_only_image_encoder and 'vd_adapter' not in state_dict and 'dvadapter' not in state_dict:
434
+ # we are loading pure clip weights.
435
+ self.vision_encoder.load_state_dict(state_dict, strict=strict)
436
+
437
+ if 'lora_weights' in state_dict:
438
+ # todo add LoRA
439
+ # self.sd_ref().pipeline.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
440
+ # self.sd_ref().pipeline.fuse_lora()
441
+ pass
442
+ if 'clip_fusion' in state_dict:
443
+ self.clip_fusion_module.load_state_dict(state_dict['clip_fusion'], strict=strict)
444
+ if 'id_encoder' in state_dict and (self.adapter_type == 'photo_maker' or self.adapter_type == 'clip_fusion'):
445
+ self.vision_encoder.load_state_dict(state_dict['id_encoder'], strict=strict)
446
+ # check to see if the fuse weights are there
447
+ fuse_weights = {}
448
+ for k, v in state_dict['id_encoder'].items():
449
+ if k.startswith('fuse_module'):
450
+ k = k.replace('fuse_module.', '')
451
+ fuse_weights[k] = v
452
+ if len(fuse_weights) > 0:
453
+ try:
454
+ self.fuse_module.load_state_dict(fuse_weights, strict=strict)
455
+ except Exception as e:
456
+
457
+ print(e)
458
+ # force load it
459
+ print(f"force loading fuse module as it did not match")
460
+ current_state_dict = self.fuse_module.state_dict()
461
+ for k, v in fuse_weights.items():
462
+ if len(v.shape) == 1:
463
+ current_state_dict[k] = v[:current_state_dict[k].shape[0]]
464
+ elif len(v.shape) == 2:
465
+ current_state_dict[k] = v[:current_state_dict[k].shape[0], :current_state_dict[k].shape[1]]
466
+ elif len(v.shape) == 3:
467
+ current_state_dict[k] = v[:current_state_dict[k].shape[0], :current_state_dict[k].shape[1],
468
+ :current_state_dict[k].shape[2]]
469
+ elif len(v.shape) == 4:
470
+ current_state_dict[k] = v[:current_state_dict[k].shape[0], :current_state_dict[k].shape[1],
471
+ :current_state_dict[k].shape[2], :current_state_dict[k].shape[3]]
472
+ else:
473
+ raise ValueError(f"unknown shape: {v.shape}")
474
+ self.fuse_module.load_state_dict(current_state_dict, strict=strict)
475
+
476
+ if 'te_adapter' in state_dict:
477
+ self.te_adapter.load_state_dict(state_dict['te_adapter'], strict=strict)
478
+
479
+ if 'llm_adapter' in state_dict:
480
+ self.llm_adapter.load_state_dict(state_dict['llm_adapter'], strict=strict)
481
+
482
+ if 'te_augmenter' in state_dict:
483
+ self.te_augmenter.load_state_dict(state_dict['te_augmenter'], strict=strict)
484
+
485
+ if 'vd_adapter' in state_dict:
486
+ self.vd_adapter.load_state_dict(state_dict['vd_adapter'], strict=strict)
487
+ if 'dvadapter' in state_dict:
488
+ self.vd_adapter.load_state_dict(state_dict['dvadapter'], strict=False)
489
+
490
+ if 'sv_adapter' in state_dict:
491
+ self.single_value_adapter.load_state_dict(state_dict['sv_adapter'], strict=strict)
492
+
493
+ if 'vision_encoder' in state_dict:
494
+ self.vision_encoder.load_state_dict(state_dict['vision_encoder'], strict=strict)
495
+
496
+ if 'fuse_module' in state_dict:
497
+ self.fuse_module.load_state_dict(state_dict['fuse_module'], strict=strict)
498
+
499
+ if 'ilora' in state_dict:
500
+ try:
501
+ self.ilora_module.load_state_dict(state_dict['ilora'], strict=strict)
502
+ except Exception as e:
503
+ print(e)
504
+ if 'redux_up' in state_dict:
505
+ # state dict is seperated. so recombine it
506
+ new_dict = {}
507
+ for k, v in state_dict.items():
508
+ for k2, v2 in v.items():
509
+ new_dict[k + '.' + k2] = v2
510
+ self.redux_adapter.load_state_dict(new_dict, strict=True)
511
+
512
+ if self.adapter_type == 'control_lora':
513
+ # state dict is seperated. so recombine it
514
+ new_dict = {}
515
+ for k, v in state_dict.items():
516
+ for k2, v2 in v.items():
517
+ new_dict[k + '.' + k2] = v2
518
+ self.control_lora.load_weights(new_dict, strict=strict)
519
+
520
+ if self.adapter_type == 'mean_flow':
521
+ # state dict is seperated. so recombine it
522
+ new_dict = {}
523
+ for k, v in state_dict.items():
524
+ for k2, v2 in v.items():
525
+ new_dict[k + '.' + k2] = v2
526
+ self.mean_flow_adapter.load_weights(new_dict, strict=strict)
527
+
528
+ if self.adapter_type == 'i2v':
529
+ # state dict is seperated. so recombine it
530
+ new_dict = {}
531
+ for k, v in state_dict.items():
532
+ for k2, v2 in v.items():
533
+ new_dict[k + '.' + k2] = v2
534
+ self.i2v_adapter.load_weights(new_dict, strict=strict)
535
+
536
+ if self.adapter_type == 'subpixel':
537
+ # state dict is seperated. so recombine it
538
+ new_dict = {}
539
+ for k, v in state_dict.items():
540
+ for k2, v2 in v.items():
541
+ new_dict[k + '.' + k2] = v2
542
+ self.subpixel_adapter.load_weights(new_dict, strict=strict)
543
+
544
+ pass
545
+
546
+ def state_dict(self) -> OrderedDict:
547
+ state_dict = OrderedDict()
548
+ if self.config.train_only_image_encoder:
549
+ return self.vision_encoder.state_dict()
550
+
551
+ if self.adapter_type == 'photo_maker':
552
+ if self.config.train_image_encoder:
553
+ state_dict["id_encoder"] = self.vision_encoder.state_dict()
554
+
555
+ state_dict["fuse_module"] = self.fuse_module.state_dict()
556
+
557
+ # todo save LoRA
558
+ return state_dict
559
+
560
+ elif self.adapter_type == 'clip_fusion':
561
+ if self.config.train_image_encoder:
562
+ state_dict["vision_encoder"] = self.vision_encoder.state_dict()
563
+ state_dict["clip_fusion"] = self.clip_fusion_module.state_dict()
564
+ return state_dict
565
+ elif self.adapter_type == 'text_encoder':
566
+ state_dict["te_adapter"] = self.te_adapter.state_dict()
567
+ return state_dict
568
+ elif self.adapter_type == 'llm_adapter':
569
+ state_dict["llm_adapter"] = self.llm_adapter.state_dict()
570
+ return state_dict
571
+ elif self.adapter_type == 'te_augmenter':
572
+ if self.config.train_image_encoder:
573
+ state_dict["vision_encoder"] = self.vision_encoder.state_dict()
574
+ state_dict["te_augmenter"] = self.te_augmenter.state_dict()
575
+ return state_dict
576
+ elif self.adapter_type == 'vision_direct':
577
+ state_dict["dvadapter"] = self.vd_adapter.state_dict()
578
+ # if self.config.train_image_encoder: # always return vision encoder
579
+ state_dict["vision_encoder"] = self.vision_encoder.state_dict()
580
+ return state_dict
581
+ elif self.adapter_type == 'single_value':
582
+ state_dict["sv_adapter"] = self.single_value_adapter.state_dict()
583
+ return state_dict
584
+ elif self.adapter_type == 'ilora':
585
+ if self.config.train_image_encoder:
586
+ state_dict["vision_encoder"] = self.vision_encoder.state_dict()
587
+ state_dict["ilora"] = self.ilora_module.state_dict()
588
+ return state_dict
589
+ elif self.adapter_type == 'redux':
590
+ d = self.redux_adapter.state_dict()
591
+ for k, v in d.items():
592
+ state_dict[k] = v
593
+ return state_dict
594
+ elif self.adapter_type == 'control_lora':
595
+ d = self.control_lora.get_state_dict()
596
+ for k, v in d.items():
597
+ state_dict[k] = v
598
+ return state_dict
599
+ elif self.adapter_type == 'mean_flow':
600
+ d = self.mean_flow_adapter.get_state_dict()
601
+ for k, v in d.items():
602
+ state_dict[k] = v
603
+ return state_dict
604
+ elif self.adapter_type == 'i2v':
605
+ d = self.i2v_adapter.get_state_dict()
606
+ for k, v in d.items():
607
+ state_dict[k] = v
608
+ return state_dict
609
+ elif self.adapter_type == 'subpixel':
610
+ d = self.subpixel_adapter.get_state_dict()
611
+ for k, v in d.items():
612
+ state_dict[k] = v
613
+ return state_dict
614
+ else:
615
+ raise NotImplementedError
616
+
617
+ def add_extra_values(self, extra_values: torch.Tensor, is_unconditional=False):
618
+ if self.adapter_type == 'single_value':
619
+ if is_unconditional:
620
+ self.unconditional_embeds = extra_values.to(self.device, get_torch_dtype(self.sd_ref().dtype))
621
+ else:
622
+ self.conditional_embeds = extra_values.to(self.device, get_torch_dtype(self.sd_ref().dtype))
623
+
624
+ def condition_noisy_latents(self, latents: torch.Tensor, batch:DataLoaderBatchDTO):
625
+ with torch.no_grad():
626
+ # todo add i2v start frame conditioning here
627
+
628
+ if self.adapter_type in ['i2v']:
629
+ return self.i2v_adapter.condition_noisy_latents(latents, batch)
630
+ elif self.adapter_type in ['control_lora']:
631
+ # inpainting input is 0-1 (bs, 4, h, w) on batch.inpaint_tensor
632
+ # 4th channel is the mask with 1 being keep area and 0 being area to inpaint.
633
+ sd: StableDiffusion = self.sd_ref()
634
+ inpainting_latent = None
635
+ if self.config.has_inpainting_input:
636
+ do_dropout = random.random() < self.config.control_image_dropout
637
+ # do random mask if we dont have one
638
+ inpaint_tensor = batch.inpaint_tensor
639
+ if inpaint_tensor is None and not do_dropout:
640
+ # generate a random one since we dont have one
641
+ # this will make random blobs, invert the blobs for now as we normanlly inpaint the alpha
642
+ inpaint_tensor = 1 - generate_random_mask(
643
+ batch_size=latents.shape[0],
644
+ height=latents.shape[2],
645
+ width=latents.shape[3],
646
+ device=latents.device,
647
+ ).to(latents.device, latents.dtype)
648
+ if inpaint_tensor is not None and not do_dropout:
649
+
650
+ if inpaint_tensor.shape[1] == 4:
651
+ # get just the mask
652
+ inpainting_tensor_mask = inpaint_tensor[:, 3:4, :, :].to(latents.device, dtype=latents.dtype)
653
+ elif inpaint_tensor.shape[1] == 3:
654
+ # rgb mask. Just get one channel
655
+ inpainting_tensor_mask = inpaint_tensor[:, 0:1, :, :].to(latents.device, dtype=latents.dtype)
656
+ else:
657
+ inpainting_tensor_mask = inpaint_tensor
658
+
659
+ # # use our batch latents so we cna avoid ancoding again
660
+ inpainting_latent = batch.latents
661
+
662
+ # resize the mask to match the new encoded size
663
+ inpainting_tensor_mask = F.interpolate(inpainting_tensor_mask, size=(inpainting_latent.shape[2], inpainting_latent.shape[3]), mode='bilinear')
664
+ inpainting_tensor_mask = inpainting_tensor_mask.to(latents.device, latents.dtype)
665
+
666
+ do_mask_invert = False
667
+ if self.config.invert_inpaint_mask_chance > 0.0:
668
+ do_mask_invert = random.random() < self.config.invert_inpaint_mask_chance
669
+ if do_mask_invert:
670
+ # invert the mask
671
+ inpainting_tensor_mask = 1 - inpainting_tensor_mask
672
+
673
+ # mask out the inpainting area, it is currently 0 for inpaint area, and 1 for keep area
674
+ # we are zeroing our the latents in the inpaint area not on the pixel space.
675
+ inpainting_latent = inpainting_latent * inpainting_tensor_mask
676
+
677
+ # mask needs to be 1 for inpaint area and 0 for area to leave alone. So flip it.
678
+ inpainting_tensor_mask = 1 - inpainting_tensor_mask
679
+ # leave the mask as 0-1 and concat on channel of latents
680
+ inpainting_latent = torch.cat((inpainting_latent, inpainting_tensor_mask), dim=1)
681
+ else:
682
+ # we have iinpainting but didnt get a control. or we are doing a dropout
683
+ # the input needs to be all zeros for the latents and all 1s for the mask
684
+ inpainting_latent = torch.zeros_like(latents)
685
+ # add ones for the mask since we are technically inpainting everything
686
+ inpainting_latent = torch.cat((inpainting_latent, torch.ones_like(inpainting_latent[:, :1, :, :])), dim=1)
687
+
688
+ if self.config.num_control_images == 1:
689
+ # this is our only control
690
+ control_latent = inpainting_latent.to(latents.device, latents.dtype)
691
+ latents = torch.cat((latents, control_latent), dim=1)
692
+ return latents.detach()
693
+
694
+ if control_tensor is None:
695
+ # concat zeros onto the latents
696
+ ctrl = torch.zeros(
697
+ latents.shape[0], # bs
698
+ latents.shape[1] * self.num_control_images, # ch
699
+ latents.shape[2],
700
+ latents.shape[3],
701
+ device=latents.device,
702
+ dtype=latents.dtype
703
+ )
704
+ if inpainting_latent is not None:
705
+ # inpainting always comes first
706
+ ctrl = torch.cat((inpainting_latent, ctrl), dim=1)
707
+ latents = torch.cat((latents, ctrl), dim=1)
708
+ return latents.detach()
709
+ # if we have multiple control tensors, they come in like [bs, num_control_images, ch, h, w]
710
+ # if we have 1, it comes in like [bs, ch, h, w]
711
+ # stack out control tensors to be [bs, ch * num_control_images, h, w]
712
+
713
+ control_tensor = batch.control_tensor.to(latents.device, dtype=latents.dtype)
714
+
715
+ control_tensor_list = []
716
+ if len(control_tensor.shape) == 4:
717
+ control_tensor_list.append(control_tensor)
718
+ else:
719
+ # reshape
720
+ control_tensor = control_tensor.view(
721
+ control_tensor.shape[0],
722
+ control_tensor.shape[1] * control_tensor.shape[2],
723
+ control_tensor.shape[3],
724
+ control_tensor.shape[4]
725
+ )
726
+ control_tensor_list = control_tensor.chunk(self.num_control_images, dim=1)
727
+ control_latent_list = []
728
+ for control_tensor in control_tensor_list:
729
+ do_dropout = random.random() < self.config.control_image_dropout
730
+ if do_dropout:
731
+ # dropout with noise
732
+ control_latent_list.append(torch.zeros_like(batch.latents))
733
+ else:
734
+ # it is 0-1 need to convert to -1 to 1
735
+ control_tensor = control_tensor * 2 - 1
736
+
737
+ control_tensor = control_tensor.to(sd.vae_device_torch, dtype=sd.torch_dtype)
738
+
739
+ # if it is not the size of batch.tensor, (bs,ch,h,w) then we need to resize it
740
+ if control_tensor.shape[2] != batch.tensor.shape[2] or control_tensor.shape[3] != batch.tensor.shape[3]:
741
+ control_tensor = F.interpolate(control_tensor, size=(batch.tensor.shape[2], batch.tensor.shape[3]), mode='bicubic')
742
+
743
+ # encode it
744
+ control_latent = sd.encode_images(control_tensor).to(latents.device, latents.dtype)
745
+ control_latent_list.append(control_latent)
746
+ # stack them on the channel dimension
747
+ control_latent = torch.cat(control_latent_list, dim=1)
748
+ if inpainting_latent is not None:
749
+ # inpainting always comes first
750
+ control_latent = torch.cat((inpainting_latent, control_latent), dim=1)
751
+ # concat it onto the latents
752
+ latents = torch.cat((latents, control_latent), dim=1)
753
+ return latents.detach()
754
+ return latents
755
+
756
+
757
+ def condition_prompt(
758
+ self,
759
+ prompt: Union[List[str], str],
760
+ is_unconditional: bool = False,
761
+ ):
762
+ if self.adapter_type in ['clip_fusion', 'ilora', 'vision_direct', 'redux', 'control_lora', 'subpixel', 'i2v', 'mean_flow']:
763
+ return prompt
764
+ elif self.adapter_type == 'text_encoder':
765
+ # todo allow for training
766
+ with torch.no_grad():
767
+ # encode and save the embeds
768
+ if is_unconditional:
769
+ self.unconditional_embeds = self.te_adapter.encode_text(prompt).detach()
770
+ else:
771
+ self.conditional_embeds = self.te_adapter.encode_text(prompt).detach()
772
+ elif self.adapter_type == 'llm_adapter':
773
+ # todo allow for training
774
+ with torch.no_grad():
775
+ # encode and save the embeds
776
+ if is_unconditional:
777
+ self.unconditional_embeds = self.llm_adapter.encode_text(prompt).detach()
778
+ else:
779
+ self.conditional_embeds = self.llm_adapter.encode_text(prompt).detach()
780
+ return prompt
781
+ elif self.adapter_type == 'photo_maker':
782
+ if is_unconditional:
783
+ return prompt
784
+ else:
785
+
786
+ with torch.no_grad():
787
+ was_list = isinstance(prompt, list)
788
+ if not was_list:
789
+ prompt_list = [prompt]
790
+ else:
791
+ prompt_list = prompt
792
+
793
+ new_prompt_list = []
794
+ token_mask_list = []
795
+
796
+ for prompt in prompt_list:
797
+
798
+ our_class = None
799
+ # find a class in the prompt
800
+ prompt_parts = prompt.split(' ')
801
+ prompt_parts = [p.strip().lower() for p in prompt_parts if len(p) > 0]
802
+
803
+ new_prompt_parts = []
804
+ tokened_prompt_parts = []
805
+ for idx, prompt_part in enumerate(prompt_parts):
806
+ new_prompt_parts.append(prompt_part)
807
+ tokened_prompt_parts.append(prompt_part)
808
+ if prompt_part in self.config.class_names:
809
+ our_class = prompt_part
810
+ # add the flag word
811
+ tokened_prompt_parts.append(self.flag_word)
812
+
813
+ if self.num_control_images > 1:
814
+ # add the rest
815
+ for _ in range(self.num_control_images - 1):
816
+ new_prompt_parts.extend(prompt_parts[idx + 1:])
817
+
818
+ # add the rest
819
+ tokened_prompt_parts.extend(prompt_parts[idx + 1:])
820
+ new_prompt_parts.extend(prompt_parts[idx + 1:])
821
+
822
+ break
823
+
824
+ prompt = " ".join(new_prompt_parts)
825
+ tokened_prompt = " ".join(tokened_prompt_parts)
826
+
827
+ if our_class is None:
828
+ # add the first one to the front of the prompt
829
+ tokened_prompt = self.config.class_names[0] + ' ' + self.flag_word + ' ' + prompt
830
+ our_class = self.config.class_names[0]
831
+ prompt = " ".join(
832
+ [self.config.class_names[0] for _ in range(self.num_control_images)]) + ' ' + prompt
833
+
834
+ # add the prompt to the list
835
+ new_prompt_list.append(prompt)
836
+
837
+ # tokenize them with just the first tokenizer
838
+ tokenizer = self.sd_ref().tokenizer
839
+ if isinstance(tokenizer, list):
840
+ tokenizer = tokenizer[0]
841
+
842
+ flag_token = tokenizer.convert_tokens_to_ids(self.flag_word)
843
+
844
+ tokenized_prompt = tokenizer.encode(prompt)
845
+ tokenized_tokened_prompt = tokenizer.encode(tokened_prompt)
846
+
847
+ flag_idx = tokenized_tokened_prompt.index(flag_token)
848
+
849
+ class_token = tokenized_prompt[flag_idx - 1]
850
+
851
+ boolean_mask = torch.zeros(flag_idx - 1, dtype=torch.bool)
852
+ boolean_mask = torch.cat((boolean_mask, torch.ones(self.num_control_images, dtype=torch.bool)))
853
+ boolean_mask = boolean_mask.to(self.device)
854
+ # zero pad it to 77
855
+ boolean_mask = F.pad(boolean_mask, (0, 77 - boolean_mask.shape[0]), value=False)
856
+
857
+ token_mask_list.append(boolean_mask)
858
+
859
+ self.token_mask = torch.cat(token_mask_list, dim=0).to(self.device)
860
+
861
+ prompt_list = new_prompt_list
862
+
863
+ if not was_list:
864
+ prompt = prompt_list[0]
865
+ else:
866
+ prompt = prompt_list
867
+
868
+ return prompt
869
+
870
+ else:
871
+ return prompt
872
+
873
+ def condition_encoded_embeds(
874
+ self,
875
+ tensors_0_1: torch.Tensor,
876
+ prompt_embeds: PromptEmbeds,
877
+ is_training=False,
878
+ has_been_preprocessed=False,
879
+ is_unconditional=False,
880
+ quad_count=4,
881
+ is_generating_samples=False,
882
+ ) -> PromptEmbeds:
883
+ if self.adapter_type == 'text_encoder':
884
+ # replace the prompt embed with ours
885
+ if is_unconditional:
886
+ return self.unconditional_embeds.clone()
887
+ return self.conditional_embeds.clone()
888
+ if self.adapter_type == 'llm_adapter':
889
+ # replace the prompt embed with ours
890
+ if is_unconditional:
891
+ prompt_embeds.text_embeds = self.unconditional_embeds.text_embeds.clone()
892
+ prompt_embeds.attention_mask = self.unconditional_embeds.attention_mask.clone()
893
+ return prompt_embeds
894
+ prompt_embeds.text_embeds = self.conditional_embeds.text_embeds.clone()
895
+ prompt_embeds.attention_mask = self.conditional_embeds.attention_mask.clone()
896
+ return prompt_embeds
897
+
898
+ if self.adapter_type == 'ilora':
899
+ return prompt_embeds
900
+
901
+ if self.adapter_type == 'photo_maker' or self.adapter_type == 'clip_fusion' or self.adapter_type == 'redux':
902
+ if is_unconditional:
903
+ # we dont condition the negative embeds for photo maker
904
+ return prompt_embeds.clone()
905
+ with torch.no_grad():
906
+ # on training the clip image is created in the dataloader
907
+ if not has_been_preprocessed:
908
+ # tensors should be 0-1
909
+ if tensors_0_1.ndim == 3:
910
+ tensors_0_1 = tensors_0_1.unsqueeze(0)
911
+ # training tensors are 0 - 1
912
+ tensors_0_1 = tensors_0_1.to(self.device, dtype=torch.float16)
913
+ # if images are out of this range throw error
914
+ if tensors_0_1.min() < -0.3 or tensors_0_1.max() > 1.3:
915
+ raise ValueError("image tensor values must be between 0 and 1. Got min: {}, max: {}".format(
916
+ tensors_0_1.min(), tensors_0_1.max()
917
+ ))
918
+ clip_image = self.image_processor(
919
+ images=tensors_0_1,
920
+ return_tensors="pt",
921
+ do_resize=True,
922
+ do_rescale=False,
923
+ do_convert_rgb=True
924
+ ).pixel_values
925
+ else:
926
+ clip_image = tensors_0_1
927
+ clip_image = clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype)).detach()
928
+
929
+ if self.config.quad_image:
930
+ # split the 4x4 grid and stack on batch
931
+ ci1, ci2 = clip_image.chunk(2, dim=2)
932
+ ci1, ci3 = ci1.chunk(2, dim=3)
933
+ ci2, ci4 = ci2.chunk(2, dim=3)
934
+ to_cat = []
935
+ for i, ci in enumerate([ci1, ci2, ci3, ci4]):
936
+ if i < quad_count:
937
+ to_cat.append(ci)
938
+ else:
939
+ break
940
+
941
+ clip_image = torch.cat(to_cat, dim=0).detach()
942
+
943
+ if self.adapter_type == 'photo_maker':
944
+ # Embeddings need to be (b, num_inputs, c, h, w) for now, just put 1 input image
945
+ clip_image = clip_image.unsqueeze(1)
946
+ with torch.set_grad_enabled(is_training):
947
+ if is_training and self.config.train_image_encoder:
948
+ self.vision_encoder.train()
949
+ clip_image = clip_image.requires_grad_(True)
950
+ id_embeds = self.vision_encoder(
951
+ clip_image,
952
+ do_projection2=isinstance(self.sd_ref().text_encoder, list),
953
+ )
954
+ else:
955
+ with torch.no_grad():
956
+ self.vision_encoder.eval()
957
+ id_embeds = self.vision_encoder(
958
+ clip_image, do_projection2=isinstance(self.sd_ref().text_encoder, list)
959
+ ).detach()
960
+
961
+ prompt_embeds.text_embeds = self.fuse_module(
962
+ prompt_embeds.text_embeds,
963
+ id_embeds,
964
+ self.token_mask
965
+ )
966
+ return prompt_embeds
967
+ elif self.adapter_type == 'clip_fusion':
968
+ with torch.set_grad_enabled(is_training):
969
+ if is_training and self.config.train_image_encoder:
970
+ self.vision_encoder.train()
971
+ clip_image = clip_image.requires_grad_(True)
972
+ id_embeds = self.vision_encoder(
973
+ clip_image,
974
+ output_hidden_states=True,
975
+ )
976
+ else:
977
+ with torch.no_grad():
978
+ self.vision_encoder.eval()
979
+ id_embeds = self.vision_encoder(
980
+ clip_image, output_hidden_states=True
981
+ )
982
+
983
+ img_embeds = id_embeds['last_hidden_state']
984
+
985
+ if self.config.quad_image:
986
+ # get the outputs of the quat
987
+ chunks = img_embeds.chunk(quad_count, dim=0)
988
+ chunk_sum = torch.zeros_like(chunks[0])
989
+ for chunk in chunks:
990
+ chunk_sum = chunk_sum + chunk
991
+ # get the mean of them
992
+
993
+ img_embeds = chunk_sum / quad_count
994
+
995
+ if not is_training or not self.config.train_image_encoder:
996
+ img_embeds = img_embeds.detach()
997
+
998
+ prompt_embeds.text_embeds = self.clip_fusion_module(
999
+ prompt_embeds.text_embeds,
1000
+ img_embeds
1001
+ )
1002
+ return prompt_embeds
1003
+
1004
+ elif self.adapter_type == 'redux':
1005
+ with torch.set_grad_enabled(is_training):
1006
+ if is_training and self.config.train_image_encoder:
1007
+ self.vision_encoder.train()
1008
+ clip_image = clip_image.requires_grad_(True)
1009
+ id_embeds = self.vision_encoder(
1010
+ clip_image,
1011
+ output_hidden_states=True,
1012
+ )
1013
+ else:
1014
+ with torch.no_grad():
1015
+ self.vision_encoder.eval()
1016
+ id_embeds = self.vision_encoder(
1017
+ clip_image, output_hidden_states=True
1018
+ )
1019
+
1020
+ img_embeds = id_embeds['last_hidden_state']
1021
+
1022
+ if self.config.quad_image:
1023
+ # get the outputs of the quat
1024
+ chunks = img_embeds.chunk(quad_count, dim=0)
1025
+ chunk_sum = torch.zeros_like(chunks[0])
1026
+ for chunk in chunks:
1027
+ chunk_sum = chunk_sum + chunk
1028
+ # get the mean of them
1029
+
1030
+ img_embeds = chunk_sum / quad_count
1031
+
1032
+ if not is_training or not self.config.train_image_encoder:
1033
+ img_embeds = img_embeds.detach()
1034
+
1035
+ img_embeds = self.redux_adapter(img_embeds.to(self.device, get_torch_dtype(self.sd_ref().dtype)))
1036
+
1037
+ prompt_embeds.text_embeds = torch.cat((prompt_embeds.text_embeds, img_embeds), dim=-2)
1038
+ return prompt_embeds
1039
+ else:
1040
+ return prompt_embeds
1041
+
1042
+ def get_empty_clip_image(self, batch_size: int, shape=None) -> torch.Tensor:
1043
+ with torch.no_grad():
1044
+ if shape is None:
1045
+ shape = [batch_size, 3, self.input_size, self.input_size]
1046
+ tensors_0_1 = torch.rand(shape, device=self.device)
1047
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
1048
+ dtype=get_torch_dtype(self.sd_ref().dtype))
1049
+ tensors_0_1 = tensors_0_1 * noise_scale
1050
+ # tensors_0_1 = tensors_0_1 * 0
1051
+ mean = torch.tensor(self.clip_image_processor.image_mean).to(
1052
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
1053
+ ).detach()
1054
+ std = torch.tensor(self.clip_image_processor.image_std).to(
1055
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
1056
+ ).detach()
1057
+ tensors_0_1 = torch.clip((255. * tensors_0_1), 0, 255).round() / 255.0
1058
+ clip_image = (tensors_0_1 - mean.view([1, 3, 1, 1])) / std.view([1, 3, 1, 1])
1059
+ return clip_image.detach()
1060
+
1061
+ def train(self, mode: bool = True):
1062
+ if self.config.train_image_encoder:
1063
+ self.vision_encoder.train(mode)
1064
+ super().train(mode)
1065
+
1066
+ def trigger_pre_te(
1067
+ self,
1068
+ tensors_0_1: Optional[torch.Tensor]=None,
1069
+ tensors_preprocessed: Optional[torch.Tensor]=None, # preprocessed by the dataloader
1070
+ is_training=False,
1071
+ has_been_preprocessed=False,
1072
+ batch_tensor: Optional[torch.Tensor]=None,
1073
+ quad_count=4,
1074
+ batch_size=1,
1075
+ ) -> PromptEmbeds:
1076
+ if tensors_0_1 is not None:
1077
+ # actual 0 - 1 image
1078
+ self.cached_control_image_0_1 = tensors_0_1
1079
+ else:
1080
+ # image has been processed through the dataloader and is prepped for vision encoder
1081
+ self.cached_control_image_0_1 = None
1082
+ if batch_tensor is not None and self.cached_control_image_0_1 is None:
1083
+ # convert it to 0 - 1
1084
+ to_cache = batch_tensor / 2 + 0.5
1085
+ # videos come in (bs, num_frames, channels, height, width)
1086
+ # images come in (bs, channels, height, width)
1087
+ # if it is a video, just grad first frame
1088
+ if len(to_cache.shape) == 5:
1089
+ to_cache = to_cache[:, 0:1, :, :, :]
1090
+ to_cache = to_cache.squeeze(1)
1091
+ self.cached_control_image_0_1 = to_cache
1092
+
1093
+ if tensors_preprocessed is not None and has_been_preprocessed:
1094
+ tensors_0_1 = tensors_preprocessed
1095
+ # if self.adapter_type == 'ilora' or self.adapter_type == 'vision_direct' or self.adapter_type == 'te_augmenter':
1096
+ if self.adapter_type in ['ilora', 'vision_direct', 'te_augmenter', 'i2v']:
1097
+ skip_unconditional = self.sd_ref().is_flux
1098
+ if tensors_0_1 is None:
1099
+ tensors_0_1 = self.get_empty_clip_image(batch_size)
1100
+ has_been_preprocessed = True
1101
+
1102
+ with torch.no_grad():
1103
+ # on training the clip image is created in the dataloader
1104
+ if not has_been_preprocessed:
1105
+ # tensors should be 0-1
1106
+ if tensors_0_1.ndim == 3:
1107
+ tensors_0_1 = tensors_0_1.unsqueeze(0)
1108
+ # training tensors are 0 - 1
1109
+ tensors_0_1 = tensors_0_1.to(self.device, dtype=torch.float16)
1110
+ # if images are out of this range throw error
1111
+ if tensors_0_1.min() < -0.3 or tensors_0_1.max() > 1.3:
1112
+ raise ValueError("image tensor values must be between 0 and 1. Got min: {}, max: {}".format(
1113
+ tensors_0_1.min(), tensors_0_1.max()
1114
+ ))
1115
+ clip_image = self.image_processor(
1116
+ images=tensors_0_1,
1117
+ return_tensors="pt",
1118
+ do_resize=True,
1119
+ do_rescale=False,
1120
+ ).pixel_values
1121
+ else:
1122
+ clip_image = tensors_0_1
1123
+
1124
+ # if is pixtral
1125
+ if self.config.image_encoder_arch == 'pixtral' and self.config.pixtral_random_image_size:
1126
+ # get the random size
1127
+ random_size = random.randint(256, self.config.pixtral_max_image_size)
1128
+ # images are already sized for max size, we have to fit them to the pixtral patch size to reduce / enlarge it farther.
1129
+ h, w = clip_image.shape[2], clip_image.shape[3]
1130
+ current_base_size = int(math.sqrt(w * h))
1131
+ ratio = current_base_size / random_size
1132
+ if ratio > 1:
1133
+ w = round(w / ratio)
1134
+ h = round(h / ratio)
1135
+
1136
+ width_tokens = (w - 1) // self.image_processor.image_patch_size + 1
1137
+ height_tokens = (h - 1) // self.image_processor.image_patch_size + 1
1138
+ assert width_tokens > 0
1139
+ assert height_tokens > 0
1140
+
1141
+ new_image_size = (
1142
+ width_tokens * self.image_processor.image_patch_size,
1143
+ height_tokens * self.image_processor.image_patch_size,
1144
+ )
1145
+
1146
+ # resize the image
1147
+ clip_image = F.interpolate(clip_image, size=new_image_size, mode='bicubic', align_corners=False)
1148
+
1149
+
1150
+ batch_size = clip_image.shape[0]
1151
+ if self.config.control_image_dropout > 0 and is_training:
1152
+ clip_batch = torch.chunk(clip_image, batch_size, dim=0)
1153
+ unconditional_batch = torch.chunk(self.get_empty_clip_image(batch_size, shape=clip_image.shape).to(
1154
+ clip_image.device, dtype=clip_image.dtype
1155
+ ), batch_size, dim=0)
1156
+ combine_list = []
1157
+ for i in range(batch_size):
1158
+ do_dropout = random.random() < self.config.control_image_dropout
1159
+ if do_dropout:
1160
+ # dropout with noise
1161
+ combine_list.append(unconditional_batch[i])
1162
+ else:
1163
+ combine_list.append(clip_batch[i])
1164
+ clip_image = torch.cat(combine_list, dim=0)
1165
+
1166
+ if self.adapter_type in ['vision_direct', 'te_augmenter', 'i2v'] and not skip_unconditional:
1167
+ # add an unconditional so we can save it
1168
+ unconditional = self.get_empty_clip_image(batch_size, shape=clip_image.shape).to(
1169
+ clip_image.device, dtype=clip_image.dtype
1170
+ )
1171
+ clip_image = torch.cat([unconditional, clip_image], dim=0)
1172
+
1173
+ clip_image = clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype)).detach()
1174
+
1175
+ if self.config.quad_image:
1176
+ # split the 4x4 grid and stack on batch
1177
+ ci1, ci2 = clip_image.chunk(2, dim=2)
1178
+ ci1, ci3 = ci1.chunk(2, dim=3)
1179
+ ci2, ci4 = ci2.chunk(2, dim=3)
1180
+ to_cat = []
1181
+ for i, ci in enumerate([ci1, ci2, ci3, ci4]):
1182
+ if i < quad_count:
1183
+ to_cat.append(ci)
1184
+ else:
1185
+ break
1186
+
1187
+ clip_image = torch.cat(to_cat, dim=0).detach()
1188
+
1189
+ if self.adapter_type == 'ilora':
1190
+ with torch.set_grad_enabled(is_training):
1191
+ if is_training and self.config.train_image_encoder:
1192
+ self.vision_encoder.train()
1193
+ clip_image = clip_image.requires_grad_(True)
1194
+ id_embeds = self.vision_encoder(
1195
+ clip_image,
1196
+ output_hidden_states=True,
1197
+ )
1198
+ else:
1199
+ with torch.no_grad():
1200
+ self.vision_encoder.eval()
1201
+ id_embeds = self.vision_encoder(
1202
+ clip_image, output_hidden_states=True
1203
+ )
1204
+
1205
+ if self.config.clip_layer == 'penultimate_hidden_states':
1206
+ img_embeds = id_embeds.hidden_states[-2]
1207
+ elif self.config.clip_layer == 'last_hidden_state':
1208
+ img_embeds = id_embeds.hidden_states[-1]
1209
+ elif self.config.clip_layer == 'image_embeds':
1210
+ img_embeds = id_embeds.image_embeds
1211
+ else:
1212
+ raise ValueError(f"unknown clip layer: {self.config.clip_layer}")
1213
+
1214
+ if self.config.quad_image:
1215
+ # get the outputs of the quat
1216
+ chunks = img_embeds.chunk(quad_count, dim=0)
1217
+ chunk_sum = torch.zeros_like(chunks[0])
1218
+ for chunk in chunks:
1219
+ chunk_sum = chunk_sum + chunk
1220
+ # get the mean of them
1221
+
1222
+ img_embeds = chunk_sum / quad_count
1223
+
1224
+ if not is_training or not self.config.train_image_encoder:
1225
+ img_embeds = img_embeds.detach()
1226
+
1227
+ self.ilora_module(img_embeds)
1228
+ # if self.adapter_type == 'vision_direct' or self.adapter_type == 'te_augmenter':
1229
+ if self.adapter_type in ['vision_direct', 'te_augmenter', 'i2v']:
1230
+ with torch.set_grad_enabled(is_training):
1231
+ if is_training and self.config.train_image_encoder:
1232
+ self.vision_encoder.train()
1233
+ clip_image = clip_image.requires_grad_(True)
1234
+ else:
1235
+ with torch.no_grad():
1236
+ self.vision_encoder.eval()
1237
+ self.vision_encoder.to(self.device)
1238
+ clip_output = self.vision_encoder(
1239
+ clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype)),
1240
+ output_hidden_states=True,
1241
+ )
1242
+ if self.config.clip_layer == 'penultimate_hidden_states':
1243
+ # they skip last layer for ip+
1244
+ # https://github.com/tencent-ailab/IP-Adapter/blob/f4b6742db35ea6d81c7b829a55b0a312c7f5a677/tutorial_train_plus.py#L403C26-L403C26
1245
+ clip_image_embeds = clip_output.hidden_states[-2]
1246
+ elif self.config.clip_layer == 'last_hidden_state':
1247
+ clip_image_embeds = clip_output.hidden_states[-1]
1248
+ else:
1249
+ if hasattr(clip_output, 'image_embeds'):
1250
+ clip_image_embeds = clip_output.image_embeds
1251
+ elif hasattr(clip_output, 'pooler_output'):
1252
+ clip_image_embeds = clip_output.pooler_output
1253
+ # TODO should we always norm image embeds?
1254
+ # get norm embeddings
1255
+ # l2_norm = torch.norm(clip_image_embeds, p=2)
1256
+ # clip_image_embeds = clip_image_embeds / l2_norm
1257
+
1258
+ if not is_training or not self.config.train_image_encoder:
1259
+ clip_image_embeds = clip_image_embeds.detach()
1260
+
1261
+ if self.adapter_type == 'te_augmenter':
1262
+ clip_image_embeds = self.te_augmenter(clip_image_embeds)
1263
+
1264
+ if self.adapter_type == 'vision_direct':
1265
+ clip_image_embeds = self.vd_adapter(clip_image_embeds)
1266
+
1267
+ # save them to the conditional and unconditional
1268
+ try:
1269
+ if skip_unconditional:
1270
+ self.unconditional_embeds, self.conditional_embeds = None, clip_image_embeds
1271
+ else:
1272
+ self.unconditional_embeds, self.conditional_embeds = clip_image_embeds.chunk(2, dim=0)
1273
+ except ValueError:
1274
+ raise ValueError(f"could not split the clip image embeds into 2. Got shape: {clip_image_embeds.shape}")
1275
+
1276
+ def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
1277
+ if self.config.train_only_image_encoder:
1278
+ yield from self.vision_encoder.parameters(recurse)
1279
+ return
1280
+ if self.config.type == 'photo_maker':
1281
+ yield from self.fuse_module.parameters(recurse)
1282
+ if self.config.train_image_encoder:
1283
+ yield from self.vision_encoder.parameters(recurse)
1284
+ elif self.config.type == 'clip_fusion':
1285
+ yield from self.clip_fusion_module.parameters(recurse)
1286
+ if self.config.train_image_encoder:
1287
+ yield from self.vision_encoder.parameters(recurse)
1288
+ elif self.config.type == 'ilora':
1289
+ yield from self.ilora_module.parameters(recurse)
1290
+ if self.config.train_image_encoder:
1291
+ yield from self.vision_encoder.parameters(recurse)
1292
+ elif self.config.type == 'text_encoder':
1293
+ for attn_processor in self.te_adapter.adapter_modules:
1294
+ yield from attn_processor.parameters(recurse)
1295
+ elif self.config.type == 'llm_adapter':
1296
+ yield from self.llm_adapter.parameters(recurse)
1297
+ elif self.config.type == 'vision_direct':
1298
+ if self.config.train_scaler:
1299
+ # only yield the self.block_scaler = torch.nn.Parameter(torch.tensor([1.0] * num_modules)
1300
+ yield self.vd_adapter.block_scaler
1301
+ else:
1302
+ for attn_processor in self.vd_adapter.adapter_modules:
1303
+ yield from attn_processor.parameters(recurse)
1304
+ if self.config.train_image_encoder:
1305
+ yield from self.vision_encoder.parameters(recurse)
1306
+ if self.vd_adapter.resampler is not None:
1307
+ yield from self.vd_adapter.resampler.parameters(recurse)
1308
+ if self.vd_adapter.pool is not None:
1309
+ yield from self.vd_adapter.pool.parameters(recurse)
1310
+ if self.vd_adapter.sparse_autoencoder is not None:
1311
+ yield from self.vd_adapter.sparse_autoencoder.parameters(recurse)
1312
+ elif self.config.type == 'te_augmenter':
1313
+ yield from self.te_augmenter.parameters(recurse)
1314
+ if self.config.train_image_encoder:
1315
+ yield from self.vision_encoder.parameters(recurse)
1316
+ elif self.config.type == 'single_value':
1317
+ yield from self.single_value_adapter.parameters(recurse)
1318
+ elif self.config.type == 'redux':
1319
+ yield from self.redux_adapter.parameters(recurse)
1320
+ elif self.config.type == 'control_lora':
1321
+ param_list = self.control_lora.get_params()
1322
+ for param in param_list:
1323
+ yield param
1324
+ elif self.config.type == 'mean_flow':
1325
+ param_list = self.mean_flow_adapter.get_params()
1326
+ for param in param_list:
1327
+ yield param
1328
+ elif self.config.type == 'i2v':
1329
+ param_list = self.i2v_adapter.get_params()
1330
+ for param in param_list:
1331
+ yield param
1332
+ elif self.config.type == 'subpixel':
1333
+ param_list = self.subpixel_adapter.get_params()
1334
+ for param in param_list:
1335
+ yield param
1336
+ else:
1337
+ raise NotImplementedError
1338
+
1339
+ def enable_gradient_checkpointing(self):
1340
+ if hasattr(self.vision_encoder, "enable_gradient_checkpointing"):
1341
+ self.vision_encoder.enable_gradient_checkpointing()
1342
+ elif hasattr(self.vision_encoder, 'gradient_checkpointing'):
1343
+ self.vision_encoder.gradient_checkpointing = True
1344
+
1345
+ def get_additional_save_metadata(self) -> Dict[str, Any]:
1346
+ additional = {}
1347
+ if self.config.type == 'ilora':
1348
+ extra = self.ilora_module.get_additional_save_metadata()
1349
+ for k, v in extra.items():
1350
+ additional[k] = v
1351
+ additional['clip_layer'] = self.config.clip_layer
1352
+ additional['image_encoder_arch'] = self.config.head_dim
1353
+ return additional
1354
+
1355
+ def post_weight_update(self):
1356
+ # do any kind of updates after the weight update
1357
+ if self.config.type == 'vision_direct':
1358
+ self.vd_adapter.post_weight_update()
1359
+ pass
toolkit/data_loader.py ADDED
@@ -0,0 +1,758 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import os
4
+ import random
5
+ import traceback
6
+ from functools import lru_cache
7
+ from typing import List, TYPE_CHECKING
8
+
9
+ import cv2
10
+ import numpy as np
11
+ import torch
12
+ from PIL import Image
13
+ from PIL.ImageOps import exif_transpose
14
+ from torchvision import transforms
15
+ from torch.utils.data import Dataset, DataLoader, ConcatDataset
16
+ from tqdm import tqdm
17
+ import albumentations as A
18
+
19
+ from toolkit import image_utils
20
+ from toolkit.buckets import get_bucket_for_image_size, BucketResolution
21
+ from toolkit.config_modules import DatasetConfig, preprocess_dataset_raw_config
22
+ from toolkit.dataloader_mixins import CaptionMixin, BucketsMixin, LatentCachingMixin, Augments, CLIPCachingMixin, ControlCachingMixin, TextEmbeddingCachingMixin
23
+ from toolkit.data_transfer_object.data_loader import FileItemDTO, DataLoaderBatchDTO
24
+ from toolkit.print import print_acc
25
+ from toolkit.accelerator import get_accelerator
26
+
27
+ import platform
28
+
29
+ def is_native_windows():
30
+ return platform.system() == "Windows" and platform.release() != "2"
31
+
32
+ def is_macos():
33
+ return platform.system() == "Darwin"
34
+
35
+ if TYPE_CHECKING:
36
+ from toolkit.stable_diffusion_model import StableDiffusion
37
+
38
+
39
+ image_extensions = ['.jpg', '.jpeg', '.png', '.webp']
40
+ video_extensions = ['.mp4', '.avi', '.mov', '.webm', '.mkv', '.wmv', '.m4v', '.flv']
41
+ audio_extensions = ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a']
42
+
43
+
44
+ class RescaleTransform:
45
+ """Transform to rescale images to the range [-1, 1]."""
46
+
47
+ def __call__(self, image):
48
+ return image * 2 - 1
49
+
50
+
51
+ class NormalizeSDXLTransform:
52
+ """
53
+ Transforms the range from 0 to 1 to SDXL mean and std per channel based on avgs over thousands of images
54
+
55
+ Mean: tensor([ 0.0002, -0.1034, -0.1879])
56
+ Standard Deviation: tensor([0.5436, 0.5116, 0.5033])
57
+ """
58
+
59
+ def __call__(self, image):
60
+ return transforms.Normalize(
61
+ mean=[0.0002, -0.1034, -0.1879],
62
+ std=[0.5436, 0.5116, 0.5033],
63
+ )(image)
64
+
65
+
66
+ class NormalizeSD15Transform:
67
+ """
68
+ Transforms the range from 0 to 1 to SDXL mean and std per channel based on avgs over thousands of images
69
+
70
+ Mean: tensor([-0.1600, -0.2450, -0.3227])
71
+ Standard Deviation: tensor([0.5319, 0.4997, 0.5139])
72
+
73
+ """
74
+
75
+ def __call__(self, image):
76
+ return transforms.Normalize(
77
+ mean=[-0.1600, -0.2450, -0.3227],
78
+ std=[0.5319, 0.4997, 0.5139],
79
+ )(image)
80
+
81
+
82
+
83
+ class ImageDataset(Dataset, CaptionMixin):
84
+ def __init__(self, config):
85
+ self.config = config
86
+ self.name = self.get_config('name', 'dataset')
87
+ self.path = self.get_config('path', required=True)
88
+ self.scale = self.get_config('scale', 1)
89
+ self.random_scale = self.get_config('random_scale', False)
90
+ self.include_prompt = self.get_config('include_prompt', False)
91
+ self.default_prompt = self.get_config('default_prompt', '')
92
+ if self.include_prompt:
93
+ self.caption_type = self.get_config('caption_ext', 'txt')
94
+ else:
95
+ self.caption_type = None
96
+ # we always random crop if random scale is enabled
97
+ self.random_crop = self.random_scale if self.random_scale else self.get_config('random_crop', False)
98
+
99
+ self.resolution = self.get_config('resolution', 256)
100
+ self.file_list = [os.path.join(self.path, file) for file in os.listdir(self.path) if
101
+ file.lower().endswith(('.jpg', '.jpeg', '.png', '.webp'))]
102
+
103
+ # this might take a while
104
+ print_acc(f" - Preprocessing image dimensions")
105
+ new_file_list = []
106
+ bad_count = 0
107
+ for file in tqdm(self.file_list):
108
+ try:
109
+ w, h = image_utils.get_image_size(file)
110
+ except image_utils.UnknownImageFormat:
111
+ img = exif_transpose(Image.open(file))
112
+ w, h = img.size
113
+ # img = Image.open(file)
114
+ if int(min([w, h]) * self.scale) >= self.resolution:
115
+ new_file_list.append(file)
116
+ else:
117
+ bad_count += 1
118
+
119
+ self.file_list = new_file_list
120
+
121
+ print_acc(f" - Found {len(self.file_list)} images")
122
+ print_acc(f" - Found {bad_count} images that are too small")
123
+ assert len(self.file_list) > 0, f"no images found in {self.path}"
124
+
125
+ self.transform = transforms.Compose([
126
+ transforms.ToTensor(),
127
+ RescaleTransform(),
128
+ ])
129
+
130
+ def get_config(self, key, default=None, required=False):
131
+ if key in self.config:
132
+ value = self.config[key]
133
+ return value
134
+ elif required:
135
+ raise ValueError(f'config file error. Missing "config.dataset.{key}" key')
136
+ else:
137
+ return default
138
+
139
+ def __len__(self):
140
+ return len(self.file_list)
141
+
142
+ def __getitem__(self, index):
143
+ img_path = self.file_list[index]
144
+ try:
145
+ img = exif_transpose(Image.open(img_path)).convert('RGB')
146
+ except Exception as e:
147
+ print_acc(f"Error opening image: {img_path}")
148
+ print_acc(e)
149
+ # make a noise image if we can't open it
150
+ img = Image.fromarray(np.random.randint(0, 255, (1024, 1024, 3), dtype=np.uint8))
151
+
152
+ # Downscale the source image first
153
+ img = img.resize((int(img.size[0] * self.scale), int(img.size[1] * self.scale)), Image.BICUBIC)
154
+ min_img_size = min(img.size)
155
+
156
+ if self.random_crop:
157
+ if self.random_scale and min_img_size > self.resolution:
158
+ if min_img_size < self.resolution:
159
+ print_acc(
160
+ f"Unexpected values: min_img_size={min_img_size}, self.resolution={self.resolution}, image file={img_path}")
161
+ scale_size = self.resolution
162
+ else:
163
+ scale_size = random.randint(self.resolution, int(min_img_size))
164
+ scaler = scale_size / min_img_size
165
+ scale_width = int((img.width + 5) * scaler)
166
+ scale_height = int((img.height + 5) * scaler)
167
+ img = img.resize((scale_width, scale_height), Image.BICUBIC)
168
+ img = transforms.RandomCrop(self.resolution)(img)
169
+ else:
170
+ img = transforms.CenterCrop(min_img_size)(img)
171
+ img = img.resize((self.resolution, self.resolution), Image.BICUBIC)
172
+
173
+ img = self.transform(img)
174
+
175
+ if self.include_prompt:
176
+ prompt = self.get_caption_item(index)
177
+ return img, prompt
178
+ else:
179
+ return img
180
+
181
+
182
+
183
+
184
+
185
+ class AugmentedImageDataset(ImageDataset):
186
+ def __init__(self, config):
187
+ super().__init__(config)
188
+ self.augmentations = self.get_config('augmentations', [])
189
+ self.augmentations = [Augments(**aug) for aug in self.augmentations]
190
+
191
+ augmentation_list = []
192
+ for aug in self.augmentations:
193
+ # make sure method name is valid
194
+ assert hasattr(A, aug.method_name), f"invalid augmentation method: {aug.method_name}"
195
+ # get the method
196
+ method = getattr(A, aug.method_name)
197
+ # add the method to the list
198
+ augmentation_list.append(method(**aug.params))
199
+
200
+ self.aug_transform = A.Compose(augmentation_list)
201
+ self.original_transform = self.transform
202
+ # replace transform so we get raw pil image
203
+ self.transform = transforms.Compose([])
204
+
205
+ def __getitem__(self, index):
206
+ # get the original image
207
+ # image is a PIL image, convert to bgr
208
+ pil_image = super().__getitem__(index)
209
+ open_cv_image = np.array(pil_image)
210
+ # Convert RGB to BGR
211
+ open_cv_image = open_cv_image[:, :, ::-1].copy()
212
+
213
+ # apply augmentations
214
+ augmented = self.aug_transform(image=open_cv_image)["image"]
215
+
216
+ # convert back to RGB tensor
217
+ augmented = cv2.cvtColor(augmented, cv2.COLOR_BGR2RGB)
218
+
219
+ # convert to PIL image
220
+ augmented = Image.fromarray(augmented)
221
+
222
+ # return both # return image as 0 - 1 tensor
223
+ return transforms.ToTensor()(pil_image), transforms.ToTensor()(augmented)
224
+
225
+
226
+ class PairedImageDataset(Dataset):
227
+ def __init__(self, config):
228
+ super().__init__()
229
+ self.config = config
230
+ self.size = self.get_config('size', 512)
231
+ self.path = self.get_config('path', None)
232
+ self.pos_folder = self.get_config('pos_folder', None)
233
+ self.neg_folder = self.get_config('neg_folder', None)
234
+
235
+ self.default_prompt = self.get_config('default_prompt', '')
236
+ self.network_weight = self.get_config('network_weight', 1.0)
237
+ self.pos_weight = self.get_config('pos_weight', self.network_weight)
238
+ self.neg_weight = self.get_config('neg_weight', self.network_weight)
239
+
240
+ supported_exts = ('.jpg', '.jpeg', '.png', '.webp', '.JPEG', '.JPG', '.PNG', '.WEBP')
241
+
242
+ if self.pos_folder is not None and self.neg_folder is not None:
243
+ # find matching files
244
+ self.pos_file_list = [os.path.join(self.pos_folder, file) for file in os.listdir(self.pos_folder) if
245
+ file.lower().endswith(supported_exts)]
246
+ self.neg_file_list = [os.path.join(self.neg_folder, file) for file in os.listdir(self.neg_folder) if
247
+ file.lower().endswith(supported_exts)]
248
+
249
+ matched_files = []
250
+ for pos_file in self.pos_file_list:
251
+ pos_file_no_ext = os.path.splitext(pos_file)[0]
252
+ for neg_file in self.neg_file_list:
253
+ neg_file_no_ext = os.path.splitext(neg_file)[0]
254
+ if os.path.basename(pos_file_no_ext) == os.path.basename(neg_file_no_ext):
255
+ matched_files.append((neg_file, pos_file))
256
+ break
257
+
258
+ # remove duplicates
259
+ matched_files = [t for t in (set(tuple(i) for i in matched_files))]
260
+
261
+ self.file_list = matched_files
262
+ print_acc(f" - Found {len(self.file_list)} matching pairs")
263
+ else:
264
+ self.file_list = [os.path.join(self.path, file) for file in os.listdir(self.path) if
265
+ file.lower().endswith(supported_exts)]
266
+ print_acc(f" - Found {len(self.file_list)} images")
267
+
268
+ self.transform = transforms.Compose([
269
+ transforms.ToTensor(),
270
+ RescaleTransform(),
271
+ ])
272
+
273
+ def get_all_prompts(self):
274
+ prompts = []
275
+ for index in range(len(self.file_list)):
276
+ prompts.append(self.get_prompt_item(index))
277
+
278
+ # remove duplicates
279
+ prompts = list(set(prompts))
280
+ return prompts
281
+
282
+ def __len__(self):
283
+ return len(self.file_list)
284
+
285
+ def get_config(self, key, default=None, required=False):
286
+ if key in self.config:
287
+ value = self.config[key]
288
+ return value
289
+ elif required:
290
+ raise ValueError(f'config file error. Missing "config.dataset.{key}" key')
291
+ else:
292
+ return default
293
+
294
+ def get_prompt_item(self, index):
295
+ img_path_or_tuple = self.file_list[index]
296
+ if isinstance(img_path_or_tuple, tuple):
297
+ # check if either has a prompt file
298
+ path_no_ext = os.path.splitext(img_path_or_tuple[0])[0]
299
+ prompt_path = path_no_ext + '.txt'
300
+ if not os.path.exists(prompt_path):
301
+ path_no_ext = os.path.splitext(img_path_or_tuple[1])[0]
302
+ prompt_path = path_no_ext + '.txt'
303
+ else:
304
+ img_path = img_path_or_tuple
305
+ # see if prompt file exists
306
+ path_no_ext = os.path.splitext(img_path)[0]
307
+ prompt_path = path_no_ext + '.txt'
308
+
309
+ if os.path.exists(prompt_path):
310
+ with open(prompt_path, 'r', encoding='utf-8') as f:
311
+ prompt = f.read()
312
+ # remove any newlines
313
+ prompt = prompt.replace('\n', ', ')
314
+ # remove new lines for all operating systems
315
+ prompt = prompt.replace('\r', ', ')
316
+ prompt_split = prompt.split(',')
317
+ # remove empty strings
318
+ prompt_split = [p.strip() for p in prompt_split if p.strip()]
319
+ # join back together
320
+ prompt = ', '.join(prompt_split)
321
+ else:
322
+ prompt = self.default_prompt
323
+ return prompt
324
+
325
+ def __getitem__(self, index):
326
+ img_path_or_tuple = self.file_list[index]
327
+ if isinstance(img_path_or_tuple, tuple):
328
+ # load both images
329
+ img_path = img_path_or_tuple[0]
330
+ img1 = exif_transpose(Image.open(img_path)).convert('RGB')
331
+ img_path = img_path_or_tuple[1]
332
+ img2 = exif_transpose(Image.open(img_path)).convert('RGB')
333
+
334
+ # always use # 2 (pos)
335
+ bucket_resolution = get_bucket_for_image_size(
336
+ width=img2.width,
337
+ height=img2.height,
338
+ resolution=self.size,
339
+ # divisibility=self.
340
+ )
341
+
342
+ # images will be same base dimension, but may be trimmed. We need to shrink and then central crop
343
+ if bucket_resolution['width'] > bucket_resolution['height']:
344
+ img1_scale_to_height = bucket_resolution["height"]
345
+ img1_scale_to_width = int(img1.width * (bucket_resolution["height"] / img1.height))
346
+ img2_scale_to_height = bucket_resolution["height"]
347
+ img2_scale_to_width = int(img2.width * (bucket_resolution["height"] / img2.height))
348
+ else:
349
+ img1_scale_to_width = bucket_resolution["width"]
350
+ img1_scale_to_height = int(img1.height * (bucket_resolution["width"] / img1.width))
351
+ img2_scale_to_width = bucket_resolution["width"]
352
+ img2_scale_to_height = int(img2.height * (bucket_resolution["width"] / img2.width))
353
+
354
+ img1_crop_height = bucket_resolution["height"]
355
+ img1_crop_width = bucket_resolution["width"]
356
+ img2_crop_height = bucket_resolution["height"]
357
+ img2_crop_width = bucket_resolution["width"]
358
+
359
+ # scale then center crop images
360
+ img1 = img1.resize((img1_scale_to_width, img1_scale_to_height), Image.BICUBIC)
361
+ img1 = transforms.CenterCrop((img1_crop_height, img1_crop_width))(img1)
362
+ img2 = img2.resize((img2_scale_to_width, img2_scale_to_height), Image.BICUBIC)
363
+ img2 = transforms.CenterCrop((img2_crop_height, img2_crop_width))(img2)
364
+
365
+ # combine them side by side
366
+ img = Image.new('RGB', (img1.width + img2.width, max(img1.height, img2.height)))
367
+ img.paste(img1, (0, 0))
368
+ img.paste(img2, (img1.width, 0))
369
+ else:
370
+ img_path = img_path_or_tuple
371
+ img = exif_transpose(Image.open(img_path)).convert('RGB')
372
+ height = self.size
373
+ # determine width to keep aspect ratio
374
+ width = int(img.size[0] * height / img.size[1])
375
+
376
+ # Downscale the source image first
377
+ img = img.resize((width, height), Image.BICUBIC)
378
+
379
+ prompt = self.get_prompt_item(index)
380
+ img = self.transform(img)
381
+
382
+ return img, prompt, (self.neg_weight, self.pos_weight)
383
+
384
+
385
+ class AiToolkitDataset(LatentCachingMixin, ControlCachingMixin, CLIPCachingMixin, TextEmbeddingCachingMixin, BucketsMixin, CaptionMixin, Dataset):
386
+
387
+ def __init__(
388
+ self,
389
+ dataset_config: 'DatasetConfig',
390
+ batch_size=1,
391
+ sd: 'StableDiffusion' = None,
392
+ ):
393
+ self.dataset_config = dataset_config
394
+ # update bucket divisibility
395
+ self.dataset_config.bucket_tolerance = sd.get_bucket_divisibility()
396
+ self.is_video = dataset_config.num_frames > 1 or dataset_config.auto_frame_count
397
+ self.is_audio_model = hasattr(sd, 'is_audio_model') and sd.is_audio_model if sd is not None else False
398
+ super().__init__()
399
+ folder_path = dataset_config.folder_path
400
+ self.dataset_path = dataset_config.dataset_path
401
+ if self.dataset_path is None:
402
+ self.dataset_path = folder_path
403
+
404
+ self.is_caching_latents = dataset_config.cache_latents or dataset_config.cache_latents_to_disk
405
+ self.is_caching_latents_to_memory = dataset_config.cache_latents
406
+ self.is_caching_latents_to_disk = dataset_config.cache_latents_to_disk
407
+ self.is_caching_clip_vision_to_disk = dataset_config.cache_clip_vision_to_disk
408
+ self.is_generating_controls = len(dataset_config.controls) > 0
409
+ self.epoch_num = 0
410
+
411
+ self.sd = sd
412
+
413
+ if self.sd is None and self.is_caching_latents:
414
+ raise ValueError(f"sd is required for caching latents")
415
+
416
+ self.caption_type = dataset_config.caption_ext
417
+ self.default_caption = dataset_config.default_caption
418
+ self.random_scale = dataset_config.random_scale
419
+ self.scale = dataset_config.scale
420
+ self.batch_size = batch_size
421
+ # we always random crop if random scale is enabled
422
+ self.random_crop = self.random_scale if self.random_scale else dataset_config.random_crop
423
+ self.resolution = dataset_config.resolution
424
+ self.caption_dict = None
425
+ self.file_list: List['FileItemDTO'] = []
426
+
427
+ # check if dataset_path is a folder or json
428
+ if os.path.isdir(self.dataset_path):
429
+ extensions = image_extensions
430
+ if self.is_audio_model:
431
+ # only look for audio files
432
+ extensions = audio_extensions
433
+ elif self.is_video:
434
+ # only look for videos
435
+ extensions = video_extensions
436
+ file_list = [os.path.join(root, file) for root, _, files in os.walk(self.dataset_path) for file in files if file.lower().endswith(tuple(extensions)) and not file.startswith('.')]
437
+ else:
438
+ # assume json
439
+ with open(self.dataset_path, 'r') as f:
440
+ self.caption_dict = json.load(f)
441
+ # keys are file paths
442
+ file_list = list(self.caption_dict.keys())
443
+
444
+ # remove items in the _controls_ folder
445
+ file_list = [x for x in file_list if not os.path.basename(os.path.dirname(x)) == "_controls"]
446
+
447
+ if self.dataset_config.num_repeats > 1:
448
+ # repeat the list
449
+ file_list = file_list * self.dataset_config.num_repeats
450
+
451
+ if self.dataset_config.standardize_images:
452
+ if self.sd.is_xl or self.sd.is_vega or self.sd.is_ssd:
453
+ NormalizeMethod = NormalizeSDXLTransform
454
+ else:
455
+ NormalizeMethod = NormalizeSD15Transform
456
+
457
+ self.transform = transforms.Compose([
458
+ transforms.ToTensor(),
459
+ RescaleTransform(),
460
+ NormalizeMethod(),
461
+ ])
462
+ else:
463
+ self.transform = transforms.Compose([
464
+ transforms.ToTensor(),
465
+ RescaleTransform(),
466
+ ])
467
+
468
+ # this might take a while
469
+ print_acc(f"Dataset: {self.dataset_path}")
470
+ if self.is_video:
471
+ print_acc(f" - Preprocessing video dimensions")
472
+ else:
473
+ print_acc(f" - Preprocessing image dimensions")
474
+ dataset_folder = self.dataset_path
475
+ if not os.path.isdir(self.dataset_path):
476
+ dataset_folder = os.path.dirname(dataset_folder)
477
+
478
+ dataset_size_file = os.path.join(dataset_folder, '.aitk_size.json')
479
+ dataloader_version = "0.1.2"
480
+ if os.path.exists(dataset_size_file):
481
+ try:
482
+ with open(dataset_size_file, 'r') as f:
483
+ self.size_database = json.load(f)
484
+
485
+ if "__version__" not in self.size_database or self.size_database["__version__"] != dataloader_version:
486
+ print_acc("Upgrading size database to new version")
487
+ # old version, delete and recreate
488
+ self.size_database = {}
489
+ except Exception as e:
490
+ print_acc(f"Error loading size database: {dataset_size_file}")
491
+ print_acc(e)
492
+ self.size_database = {}
493
+ else:
494
+ self.size_database = {}
495
+
496
+ self.size_database["__version__"] = dataloader_version
497
+
498
+ # set latent space version
499
+ latent_space_version = "sd1"
500
+ if self.sd is not None and self.sd.model_config.latent_space_version is not None:
501
+ latent_space_version = self.sd.model_config.latent_space_version
502
+ elif self.sd is not None and self.sd.latent_space_version is not None:
503
+ latent_space_version = self.sd.latent_space_version
504
+ elif self.sd.is_xl:
505
+ latent_space_version = 'sdxl'
506
+ elif self.sd.is_v3:
507
+ latent_space_version = 'sd3'
508
+ elif self.sd.is_auraflow:
509
+ latent_space_version = 'sdxl'
510
+ elif self.sd.is_flux:
511
+ latent_space_version = 'flux1'
512
+ elif self.sd.model_config.is_pixart_sigma:
513
+ latent_space_version = 'sdxl'
514
+ else:
515
+ latent_space_version = self.sd.model_config.arch if self.sd is not None else "sd1"
516
+
517
+ temporal_compression = 8
518
+ if self.sd is not None:
519
+ if hasattr(self.sd.vae, 'config') and hasattr(self.sd.vae.config, 'scale_factor_temporal'):
520
+ temporal_compression = self.sd.vae.config.scale_factor_temporal
521
+ if hasattr(self.sd.unet, 'config') and hasattr(self.sd.unet.config, 'temporal_compression_ratio'):
522
+ temporal_compression = self.sd.unet.config.temporal_compression_ratio
523
+
524
+ bad_count = 0
525
+ for file in tqdm(file_list):
526
+ try:
527
+ file_item = FileItemDTO(
528
+ sd=self.sd,
529
+ path=file,
530
+ is_audio_model=self.is_audio_model,
531
+ dataset_config=dataset_config,
532
+ dataloader_transforms=self.transform,
533
+ size_database=self.size_database,
534
+ dataset_root=dataset_folder,
535
+ encode_control_in_text_embeddings=self.sd.encode_control_in_text_embeddings if self.sd else False,
536
+ text_embedding_space_version=self.sd.model_config.arch if self.sd else "sd1",
537
+ te_padding_side=self.sd.te_padding_side if self.sd else "right",
538
+ latent_space_version=latent_space_version,
539
+ temporal_compression=temporal_compression,
540
+ sample_rate=self.sd.sample_rate if self.is_audio_model and self.sd is not None else 48000,
541
+ )
542
+ self.file_list.append(file_item)
543
+ except Exception as e:
544
+ print_acc(traceback.format_exc())
545
+ if self.is_video:
546
+ print_acc(f"Error processing video: {file}")
547
+ else:
548
+ print_acc(f"Error processing image: {file}")
549
+ print_acc(e)
550
+ bad_count += 1
551
+
552
+ # save the size database
553
+ with open(dataset_size_file, 'w') as f:
554
+ json.dump(self.size_database, f)
555
+
556
+ if self.is_video:
557
+ print_acc(f" - Found {len(self.file_list)} videos")
558
+ assert len(self.file_list) > 0, f"no videos found in {self.dataset_path}"
559
+ else:
560
+ print_acc(f" - Found {len(self.file_list)} images")
561
+ assert len(self.file_list) > 0, f"no images found in {self.dataset_path}"
562
+
563
+ # handle x axis flips
564
+ if self.dataset_config.flip_x:
565
+ print_acc(" - adding x axis flips")
566
+ current_file_list = [x for x in self.file_list]
567
+ for file_item in current_file_list:
568
+ # create a copy that is flipped on the x axis
569
+ new_file_item = copy.deepcopy(file_item)
570
+ new_file_item.flip_x = True
571
+ self.file_list.append(new_file_item)
572
+
573
+ # handle y axis flips
574
+ if self.dataset_config.flip_y:
575
+ print_acc(" - adding y axis flips")
576
+ current_file_list = [x for x in self.file_list]
577
+ for file_item in current_file_list:
578
+ # create a copy that is flipped on the y axis
579
+ new_file_item = copy.deepcopy(file_item)
580
+ new_file_item.flip_y = True
581
+ self.file_list.append(new_file_item)
582
+
583
+ if self.dataset_config.flip_x or self.dataset_config.flip_y:
584
+ if self.is_video:
585
+ print_acc(f" - Found {len(self.file_list)} videos after adding flips")
586
+ else:
587
+ print_acc(f" - Found {len(self.file_list)} images after adding flips")
588
+
589
+ self.setup_epoch()
590
+
591
+ def setup_epoch(self):
592
+ if self.epoch_num == 0:
593
+ # initial setup
594
+ # do not call for now
595
+ if self.dataset_config.buckets:
596
+ # setup buckets
597
+ self.setup_buckets()
598
+ if self.is_caching_latents:
599
+ self.cache_latents_all_latents()
600
+ if self.is_caching_clip_vision_to_disk:
601
+ self.cache_clip_vision_to_disk()
602
+ if self.is_caching_text_embeddings:
603
+ self.cache_text_embeddings()
604
+ if self.is_generating_controls:
605
+ # always do this last
606
+ self.setup_controls()
607
+ else:
608
+ if self.dataset_config.poi is not None:
609
+ # handle cropping to a specific point of interest
610
+ # setup buckets every epoch
611
+ self.setup_buckets(quiet=True)
612
+ self.epoch_num += 1
613
+
614
+ def __len__(self):
615
+ if self.dataset_config.buckets:
616
+ return len(self.batch_indices)
617
+ return len(self.file_list)
618
+
619
+ def _get_single_item(self, index) -> 'FileItemDTO':
620
+ file_item: 'FileItemDTO' = copy.deepcopy(self.file_list[index])
621
+ file_item.load_and_process_image(self.transform)
622
+ file_item.load_caption(self.caption_dict)
623
+ return file_item
624
+
625
+ def __getitem__(self, item):
626
+ if self.dataset_config.buckets:
627
+ # for buckets we collate ourselves for now
628
+ # todo allow a scheduler to dynamically make buckets
629
+ # we collate ourselves
630
+ if len(self.batch_indices) - 1 < item:
631
+ # tried everything to solve this. No way to reset length when redoing things. Pick another index
632
+ item = random.randint(0, len(self.batch_indices) - 1)
633
+ idx_list = self.batch_indices[item]
634
+ return [self._get_single_item(idx) for idx in idx_list]
635
+ else:
636
+ # Dataloader is batching
637
+ return self._get_single_item(item)
638
+
639
+
640
+ def get_dataloader_from_datasets(
641
+ dataset_options,
642
+ batch_size=1,
643
+ sd: 'StableDiffusion' = None,
644
+ ) -> DataLoader:
645
+ if dataset_options is None or len(dataset_options) == 0:
646
+ return None
647
+
648
+ datasets = []
649
+ has_buckets = False
650
+ is_caching_latents = False
651
+
652
+ dataset_config_list = []
653
+ # preprocess them all
654
+ for dataset_option in dataset_options:
655
+ if isinstance(dataset_option, DatasetConfig):
656
+ dataset_config_list.append(dataset_option)
657
+ else:
658
+ # preprocess raw data
659
+ split_configs = preprocess_dataset_raw_config([dataset_option])
660
+ for x in split_configs:
661
+ dataset_config_list.append(DatasetConfig(**x))
662
+
663
+ for config in dataset_config_list:
664
+
665
+ if config.type == 'image':
666
+ dataset = AiToolkitDataset(config, batch_size=batch_size, sd=sd)
667
+ datasets.append(dataset)
668
+ if config.buckets:
669
+ has_buckets = True
670
+ if config.cache_latents or config.cache_latents_to_disk:
671
+ is_caching_latents = True
672
+ else:
673
+ raise ValueError(f"invalid dataset type: {config.type}")
674
+
675
+ concatenated_dataset = ConcatDataset(datasets)
676
+
677
+ # todo build scheduler that can get buckets from all datasets that match
678
+ # todo and evenly distribute reg images
679
+
680
+ def dto_collation(batch: List['FileItemDTO']):
681
+ # create DTO batch
682
+ batch = DataLoaderBatchDTO(
683
+ file_items=batch
684
+ )
685
+ return batch
686
+
687
+ # check if is caching latents
688
+
689
+ dataloader_kwargs = {}
690
+
691
+ if is_native_windows() or is_macos():
692
+ dataloader_kwargs['num_workers'] = 0
693
+ else:
694
+ dataloader_kwargs['num_workers'] = dataset_config_list[0].num_workers
695
+ dataloader_kwargs['prefetch_factor'] = dataset_config_list[0].prefetch_factor
696
+
697
+ if has_buckets:
698
+ # make sure they all have buckets
699
+ for dataset in datasets:
700
+ assert dataset.dataset_config.buckets, f"buckets not found on dataset {dataset.dataset_config.folder_path}, you either need all buckets or none"
701
+
702
+ data_loader = DataLoader(
703
+ concatenated_dataset,
704
+ batch_size=None, # we batch in the datasets for now
705
+ drop_last=False,
706
+ shuffle=True,
707
+ collate_fn=dto_collation, # Use the custom collate function
708
+ **dataloader_kwargs
709
+ )
710
+ else:
711
+ data_loader = DataLoader(
712
+ concatenated_dataset,
713
+ batch_size=batch_size,
714
+ shuffle=True,
715
+ collate_fn=dto_collation,
716
+ **dataloader_kwargs
717
+ )
718
+ return data_loader
719
+
720
+
721
+ def trigger_dataloader_setup_epoch(dataloader: DataLoader):
722
+ # hacky but needed because of different types of datasets and dataloaders
723
+ dataloader.len = None
724
+ if isinstance(dataloader.dataset, list):
725
+ for dataset in dataloader.dataset:
726
+ if hasattr(dataset, 'datasets'):
727
+ for sub_dataset in dataset.datasets:
728
+ if hasattr(sub_dataset, 'setup_epoch'):
729
+ sub_dataset.setup_epoch()
730
+ sub_dataset.len = None
731
+ elif hasattr(dataset, 'setup_epoch'):
732
+ dataset.setup_epoch()
733
+ dataset.len = None
734
+ elif hasattr(dataloader.dataset, 'setup_epoch'):
735
+ dataloader.dataset.setup_epoch()
736
+ dataloader.dataset.len = None
737
+ elif hasattr(dataloader.dataset, 'datasets'):
738
+ dataloader.dataset.len = None
739
+ for sub_dataset in dataloader.dataset.datasets:
740
+ if hasattr(sub_dataset, 'setup_epoch'):
741
+ sub_dataset.setup_epoch()
742
+ sub_dataset.len = None
743
+
744
+ def get_dataloader_datasets(dataloader: DataLoader):
745
+ # hacky but needed because of different types of datasets and dataloaders
746
+ if isinstance(dataloader.dataset, list):
747
+ datasets = []
748
+ for dataset in dataloader.dataset:
749
+ if hasattr(dataset, 'datasets'):
750
+ for sub_dataset in dataset.datasets:
751
+ datasets.append(sub_dataset)
752
+ else:
753
+ datasets.append(dataset)
754
+ return datasets
755
+ elif hasattr(dataloader.dataset, 'datasets'):
756
+ return dataloader.dataset.datasets
757
+ else:
758
+ return [dataloader.dataset]
toolkit/dataloader_mixins.py ADDED
The diff for this file is too large to render. See raw diff
 
toolkit/dequantize.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from functools import partial
4
+ from optimum.quanto.tensor import QTensor
5
+ import torch
6
+
7
+
8
+ def hacked_state_dict(self, *args, **kwargs):
9
+ orig_state_dict = self.orig_state_dict(*args, **kwargs)
10
+ new_state_dict = {}
11
+ for key, value in orig_state_dict.items():
12
+ if key.endswith("._scale"):
13
+ continue
14
+ if key.endswith(".input_scale"):
15
+ continue
16
+ if key.endswith(".output_scale"):
17
+ continue
18
+ if key.endswith("._data"):
19
+ key = key[:-6]
20
+ scale = orig_state_dict[key + "._scale"]
21
+ # scale is the original dtype
22
+ dtype = scale.dtype
23
+ scale = scale.float()
24
+ value = value.float()
25
+ dequantized = value * scale
26
+
27
+ # handle input and output scaling if they exist
28
+ input_scale = orig_state_dict.get(key + ".input_scale")
29
+
30
+ if input_scale is not None:
31
+ # make sure the tensor is 1.0
32
+ if input_scale.item() != 1.0:
33
+ raise ValueError("Input scale is not 1.0, cannot dequantize")
34
+
35
+ output_scale = orig_state_dict.get(key + ".output_scale")
36
+
37
+ if output_scale is not None:
38
+ # make sure the tensor is 1.0
39
+ if output_scale.item() != 1.0:
40
+ raise ValueError("Output scale is not 1.0, cannot dequantize")
41
+
42
+ new_state_dict[key] = dequantized.to('cpu', dtype=dtype)
43
+ else:
44
+ new_state_dict[key] = value
45
+ return new_state_dict
46
+
47
+ # hacks the state dict so we can dequantize before saving
48
+ def patch_dequantization_on_save(model):
49
+ model.orig_state_dict = model.state_dict
50
+ model.state_dict = partial(hacked_state_dict, model)
51
+
52
+
53
+ def dequantize_parameter(module: torch.nn.Module, param_name: str) -> bool:
54
+ """
55
+ Convert a quantized parameter back to a regular Parameter with floating point values.
56
+
57
+ Args:
58
+ module: The module containing the parameter to unquantize
59
+ param_name: Name of the parameter to unquantize (e.g., 'weight', 'bias')
60
+
61
+ Returns:
62
+ bool: True if parameter was unquantized, False if it was already unquantized
63
+ """
64
+
65
+ # Check if the parameter exists
66
+ if not hasattr(module, param_name):
67
+ raise AttributeError(f"Module has no parameter named '{param_name}'")
68
+
69
+ param = getattr(module, param_name)
70
+
71
+ # If it's not a parameter or not quantized, nothing to do
72
+ if not isinstance(param, torch.nn.Parameter):
73
+ raise TypeError(f"'{param_name}' is not a Parameter")
74
+ if not isinstance(param, QTensor):
75
+ return False
76
+
77
+ # Convert to float tensor while preserving device and requires_grad
78
+ with torch.no_grad():
79
+ float_tensor = param.float()
80
+ new_param = torch.nn.Parameter(
81
+ float_tensor,
82
+ requires_grad=param.requires_grad
83
+ )
84
+
85
+ # Replace the parameter
86
+ setattr(module, param_name, new_param)
87
+
88
+ return True
toolkit/ema.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import division
2
+ from __future__ import unicode_literals
3
+
4
+ from typing import Iterable, Optional
5
+ import weakref
6
+ import copy
7
+ import contextlib
8
+ from toolkit.optimizers.optimizer_utils import copy_stochastic
9
+
10
+ import torch
11
+
12
+
13
+ # Partially based on:
14
+ # https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py
15
+ class ExponentialMovingAverage:
16
+ """
17
+ Maintains (exponential) moving average of a set of parameters.
18
+
19
+ Args:
20
+ parameters: Iterable of `torch.nn.Parameter` (typically from
21
+ `model.parameters()`).
22
+ Note that EMA is computed on *all* provided parameters,
23
+ regardless of whether or not they have `requires_grad = True`;
24
+ this allows a single EMA object to be consistantly used even
25
+ if which parameters are trainable changes step to step.
26
+
27
+ If you want to some parameters in the EMA, do not pass them
28
+ to the object in the first place. For example:
29
+
30
+ ExponentialMovingAverage(
31
+ parameters=[p for p in model.parameters() if p.requires_grad],
32
+ decay=0.9
33
+ )
34
+
35
+ will ignore parameters that do not require grad.
36
+
37
+ decay: The exponential decay.
38
+
39
+ use_num_updates: Whether to use number of updates when computing
40
+ averages.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ parameters: Iterable[torch.nn.Parameter] = None,
46
+ decay: float = 0.995,
47
+ use_num_updates: bool = False,
48
+ # feeds back the decat to the parameter
49
+ use_feedback: bool = False,
50
+ param_multiplier: float = 1.0
51
+ ):
52
+ if parameters is None:
53
+ raise ValueError("parameters must be provided")
54
+ if decay < 0.0 or decay > 1.0:
55
+ raise ValueError('Decay must be between 0 and 1')
56
+ self.decay = decay
57
+ self.num_updates = 0 if use_num_updates else None
58
+ self.use_feedback = use_feedback
59
+ self.param_multiplier = param_multiplier
60
+ parameters = list(parameters)
61
+ self.shadow_params = [
62
+ p.clone().detach()
63
+ for p in parameters
64
+ ]
65
+ self.collected_params = None
66
+ self._is_train_mode = True
67
+ # By maintaining only a weakref to each parameter,
68
+ # we maintain the old GC behaviour of ExponentialMovingAverage:
69
+ # if the model goes out of scope but the ExponentialMovingAverage
70
+ # is kept, no references to the model or its parameters will be
71
+ # maintained, and the model will be cleaned up.
72
+ self._params_refs = [weakref.ref(p) for p in parameters]
73
+
74
+ def _get_parameters(
75
+ self,
76
+ parameters: Optional[Iterable[torch.nn.Parameter]]
77
+ ) -> Iterable[torch.nn.Parameter]:
78
+ if parameters is None:
79
+ parameters = [p() for p in self._params_refs]
80
+ if any(p is None for p in parameters):
81
+ raise ValueError(
82
+ "(One of) the parameters with which this "
83
+ "ExponentialMovingAverage "
84
+ "was initialized no longer exists (was garbage collected);"
85
+ " please either provide `parameters` explicitly or keep "
86
+ "the model to which they belong from being garbage "
87
+ "collected."
88
+ )
89
+ return parameters
90
+ else:
91
+ parameters = list(parameters)
92
+ if len(parameters) != len(self.shadow_params):
93
+ raise ValueError(
94
+ "Number of parameters passed as argument is different "
95
+ "from number of shadow parameters maintained by this "
96
+ "ExponentialMovingAverage"
97
+ )
98
+ return parameters
99
+
100
+ def update(
101
+ self,
102
+ parameters: Optional[Iterable[torch.nn.Parameter]] = None
103
+ ) -> None:
104
+ """
105
+ Update currently maintained parameters.
106
+
107
+ Call this every time the parameters are updated, such as the result of
108
+ the `optimizer.step()` call.
109
+
110
+ Args:
111
+ parameters: Iterable of `torch.nn.Parameter`; usually the same set of
112
+ parameters used to initialize this object. If `None`, the
113
+ parameters with which this `ExponentialMovingAverage` was
114
+ initialized will be used.
115
+ """
116
+ parameters = self._get_parameters(parameters)
117
+ decay = self.decay
118
+ if self.num_updates is not None:
119
+ self.num_updates += 1
120
+ decay = min(
121
+ decay,
122
+ (1 + self.num_updates) / (10 + self.num_updates)
123
+ )
124
+ one_minus_decay = 1.0 - decay
125
+ with torch.no_grad():
126
+ for s_param, param in zip(self.shadow_params, parameters):
127
+ s_param_float = s_param.float()
128
+ if s_param.dtype != torch.float32:
129
+ s_param_float = s_param_float.to(torch.float32)
130
+ param_float = param
131
+ if param.dtype != torch.float32:
132
+ param_float = param_float.to(torch.float32)
133
+ tmp = (s_param_float - param_float)
134
+ # tmp will be a new tensor so we can do in-place
135
+ tmp.mul_(one_minus_decay)
136
+ s_param_float.sub_(tmp)
137
+
138
+ update_param = False
139
+ if self.use_feedback:
140
+ # make feedback 10x decay
141
+ param_float.add_(tmp * 10)
142
+ update_param = True
143
+
144
+ if self.param_multiplier != 1.0:
145
+ param_float.mul_(self.param_multiplier)
146
+ update_param = True
147
+
148
+ if s_param.dtype != torch.float32:
149
+ copy_stochastic(s_param, s_param_float)
150
+
151
+ if update_param and param.dtype != torch.float32:
152
+ copy_stochastic(param, param_float)
153
+
154
+
155
+ def copy_to(
156
+ self,
157
+ parameters: Optional[Iterable[torch.nn.Parameter]] = None
158
+ ) -> None:
159
+ """
160
+ Copy current averaged parameters into given collection of parameters.
161
+
162
+ Args:
163
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
164
+ updated with the stored moving averages. If `None`, the
165
+ parameters with which this `ExponentialMovingAverage` was
166
+ initialized will be used.
167
+ """
168
+ parameters = self._get_parameters(parameters)
169
+ for s_param, param in zip(self.shadow_params, parameters):
170
+ param.data.copy_(s_param.data)
171
+
172
+ def store(
173
+ self,
174
+ parameters: Optional[Iterable[torch.nn.Parameter]] = None
175
+ ) -> None:
176
+ """
177
+ Save the current parameters for restoring later.
178
+
179
+ Args:
180
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
181
+ temporarily stored. If `None`, the parameters of with which this
182
+ `ExponentialMovingAverage` was initialized will be used.
183
+ """
184
+ parameters = self._get_parameters(parameters)
185
+ self.collected_params = [
186
+ param.clone()
187
+ for param in parameters
188
+ ]
189
+
190
+ def restore(
191
+ self,
192
+ parameters: Optional[Iterable[torch.nn.Parameter]] = None
193
+ ) -> None:
194
+ """
195
+ Restore the parameters stored with the `store` method.
196
+ Useful to validate the model with EMA parameters without affecting the
197
+ original optimization process. Store the parameters before the
198
+ `copy_to` method. After validation (or model saving), use this to
199
+ restore the former parameters.
200
+
201
+ Args:
202
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
203
+ updated with the stored parameters. If `None`, the
204
+ parameters with which this `ExponentialMovingAverage` was
205
+ initialized will be used.
206
+ """
207
+ if self.collected_params is None:
208
+ raise RuntimeError(
209
+ "This ExponentialMovingAverage has no `store()`ed weights "
210
+ "to `restore()`"
211
+ )
212
+ parameters = self._get_parameters(parameters)
213
+ for c_param, param in zip(self.collected_params, parameters):
214
+ param.data.copy_(c_param.data)
215
+
216
+ @contextlib.contextmanager
217
+ def average_parameters(
218
+ self,
219
+ parameters: Optional[Iterable[torch.nn.Parameter]] = None
220
+ ):
221
+ r"""
222
+ Context manager for validation/inference with averaged parameters.
223
+
224
+ Equivalent to:
225
+
226
+ ema.store()
227
+ ema.copy_to()
228
+ try:
229
+ ...
230
+ finally:
231
+ ema.restore()
232
+
233
+ Args:
234
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
235
+ updated with the stored parameters. If `None`, the
236
+ parameters with which this `ExponentialMovingAverage` was
237
+ initialized will be used.
238
+ """
239
+ parameters = self._get_parameters(parameters)
240
+ self.store(parameters)
241
+ self.copy_to(parameters)
242
+ try:
243
+ yield
244
+ finally:
245
+ self.restore(parameters)
246
+
247
+ def to(self, device=None, dtype=None) -> None:
248
+ r"""Move internal buffers of the ExponentialMovingAverage to `device`.
249
+
250
+ Args:
251
+ device: like `device` argument to `torch.Tensor.to`
252
+ """
253
+ # .to() on the tensors handles None correctly
254
+ self.shadow_params = [
255
+ p.to(device=device, dtype=dtype)
256
+ if p.is_floating_point()
257
+ else p.to(device=device)
258
+ for p in self.shadow_params
259
+ ]
260
+ if self.collected_params is not None:
261
+ self.collected_params = [
262
+ p.to(device=device, dtype=dtype)
263
+ if p.is_floating_point()
264
+ else p.to(device=device)
265
+ for p in self.collected_params
266
+ ]
267
+ return
268
+
269
+ def state_dict(self) -> dict:
270
+ r"""Returns the state of the ExponentialMovingAverage as a dict."""
271
+ # Following PyTorch conventions, references to tensors are returned:
272
+ # "returns a reference to the state and not its copy!" -
273
+ # https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict
274
+ return {
275
+ "decay": self.decay,
276
+ "num_updates": self.num_updates,
277
+ "shadow_params": self.shadow_params,
278
+ "collected_params": self.collected_params
279
+ }
280
+
281
+ def load_state_dict(self, state_dict: dict) -> None:
282
+ r"""Loads the ExponentialMovingAverage state.
283
+
284
+ Args:
285
+ state_dict (dict): EMA state. Should be an object returned
286
+ from a call to :meth:`state_dict`.
287
+ """
288
+ # deepcopy, to be consistent with module API
289
+ state_dict = copy.deepcopy(state_dict)
290
+ self.decay = state_dict["decay"]
291
+ if self.decay < 0.0 or self.decay > 1.0:
292
+ raise ValueError('Decay must be between 0 and 1')
293
+ self.num_updates = state_dict["num_updates"]
294
+ assert self.num_updates is None or isinstance(self.num_updates, int), \
295
+ "Invalid num_updates"
296
+
297
+ self.shadow_params = state_dict["shadow_params"]
298
+ assert isinstance(self.shadow_params, list), \
299
+ "shadow_params must be a list"
300
+ assert all(
301
+ isinstance(p, torch.Tensor) for p in self.shadow_params
302
+ ), "shadow_params must all be Tensors"
303
+
304
+ self.collected_params = state_dict["collected_params"]
305
+ if self.collected_params is not None:
306
+ assert isinstance(self.collected_params, list), \
307
+ "collected_params must be a list"
308
+ assert all(
309
+ isinstance(p, torch.Tensor) for p in self.collected_params
310
+ ), "collected_params must all be Tensors"
311
+ assert len(self.collected_params) == len(self.shadow_params), \
312
+ "collected_params and shadow_params had different lengths"
313
+
314
+ if len(self.shadow_params) == len(self._params_refs):
315
+ # Consistant with torch.optim.Optimizer, cast things to consistant
316
+ # device and dtype with the parameters
317
+ params = [p() for p in self._params_refs]
318
+ # If parameters have been garbage collected, just load the state
319
+ # we were given without change.
320
+ if not any(p is None for p in params):
321
+ # ^ parameter references are still good
322
+ for i, p in enumerate(params):
323
+ self.shadow_params[i] = self.shadow_params[i].to(
324
+ device=p.device, dtype=p.dtype
325
+ )
326
+ if self.collected_params is not None:
327
+ self.collected_params[i] = self.collected_params[i].to(
328
+ device=p.device, dtype=p.dtype
329
+ )
330
+ else:
331
+ raise ValueError(
332
+ "Tried to `load_state_dict()` with the wrong number of "
333
+ "parameters in the saved state."
334
+ )
335
+
336
+ def eval(self):
337
+ if self._is_train_mode:
338
+ with torch.no_grad():
339
+ self.store()
340
+ self.copy_to()
341
+ self._is_train_mode = False
342
+
343
+ def train(self):
344
+ if not self._is_train_mode:
345
+ with torch.no_grad():
346
+ self.restore()
347
+ self._is_train_mode = True
toolkit/embedding.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from collections import OrderedDict
4
+
5
+ import safetensors
6
+ import torch
7
+ from typing import TYPE_CHECKING
8
+
9
+ from safetensors.torch import save_file
10
+
11
+ from toolkit.metadata import get_meta_for_safetensors
12
+
13
+ if TYPE_CHECKING:
14
+ from toolkit.stable_diffusion_model import StableDiffusion
15
+ from toolkit.config_modules import EmbeddingConfig
16
+
17
+
18
+ # this is a frankenstein mix of automatic1111 and my own code
19
+
20
+ class Embedding:
21
+ def __init__(
22
+ self,
23
+ sd: 'StableDiffusion',
24
+ embed_config: 'EmbeddingConfig',
25
+ state_dict: OrderedDict = None,
26
+ ):
27
+ self.name = embed_config.trigger
28
+ self.sd = sd
29
+ self.trigger = embed_config.trigger
30
+ self.embed_config = embed_config
31
+ self.step = 0
32
+ # setup our embedding
33
+ # Add the placeholder token in tokenizer
34
+ placeholder_tokens = [self.embed_config.trigger]
35
+
36
+ # add dummy tokens for multi-vector
37
+ additional_tokens = []
38
+ for i in range(1, self.embed_config.tokens):
39
+ additional_tokens.append(f"{self.embed_config.trigger}_{i}")
40
+ placeholder_tokens += additional_tokens
41
+
42
+ # handle dual tokenizer
43
+ self.tokenizer_list = self.sd.tokenizer if isinstance(self.sd.tokenizer, list) else [self.sd.tokenizer]
44
+ self.text_encoder_list = self.sd.text_encoder if isinstance(self.sd.text_encoder, list) else [
45
+ self.sd.text_encoder]
46
+
47
+ self.placeholder_token_ids = []
48
+ self.embedding_tokens = []
49
+
50
+ print(f"Adding {placeholder_tokens} tokens to tokenizer")
51
+ print(f"Adding {self.embed_config.tokens} tokens to tokenizer")
52
+
53
+ for text_encoder, tokenizer in zip(self.text_encoder_list, self.tokenizer_list):
54
+ num_added_tokens = tokenizer.add_tokens(placeholder_tokens)
55
+ if num_added_tokens != self.embed_config.tokens:
56
+ raise ValueError(
57
+ f"The tokenizer already contains the token {self.embed_config.trigger}. Please pass a different"
58
+ f" `placeholder_token` that is not already in the tokenizer. Only added {num_added_tokens}"
59
+ )
60
+
61
+ # Convert the initializer_token, placeholder_token to ids
62
+ init_token_ids = tokenizer.encode(self.embed_config.init_words, add_special_tokens=False)
63
+ # if length of token ids is more than number of orm embedding tokens fill with *
64
+ if len(init_token_ids) > self.embed_config.tokens:
65
+ init_token_ids = init_token_ids[:self.embed_config.tokens]
66
+ elif len(init_token_ids) < self.embed_config.tokens:
67
+ pad_token_id = tokenizer.encode(["*"], add_special_tokens=False)
68
+ init_token_ids += pad_token_id * (self.embed_config.tokens - len(init_token_ids))
69
+
70
+ placeholder_token_ids = tokenizer.encode(placeholder_tokens, add_special_tokens=False)
71
+ self.placeholder_token_ids.append(placeholder_token_ids)
72
+
73
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
74
+ text_encoder.resize_token_embeddings(len(tokenizer))
75
+
76
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
77
+ token_embeds = text_encoder.get_input_embeddings().weight.data
78
+ with torch.no_grad():
79
+ for initializer_token_id, token_id in zip(init_token_ids, placeholder_token_ids):
80
+ token_embeds[token_id] = token_embeds[initializer_token_id].clone()
81
+
82
+ # replace "[name] with this. on training. This is automatically generated in pipeline on inference
83
+ self.embedding_tokens.append(" ".join(tokenizer.convert_ids_to_tokens(placeholder_token_ids)))
84
+
85
+ # backup text encoder embeddings
86
+ self.orig_embeds_params = [x.get_input_embeddings().weight.data.clone() for x in self.text_encoder_list]
87
+
88
+ def restore_embeddings(self):
89
+ with torch.no_grad():
90
+ # Let's make sure we don't update any embedding weights besides the newly added token
91
+ for text_encoder, tokenizer, orig_embeds, placeholder_token_ids in zip(self.text_encoder_list,
92
+ self.tokenizer_list,
93
+ self.orig_embeds_params,
94
+ self.placeholder_token_ids):
95
+ index_no_updates = torch.ones((len(tokenizer),), dtype=torch.bool)
96
+ index_no_updates[ min(placeholder_token_ids): max(placeholder_token_ids) + 1] = False
97
+ text_encoder.get_input_embeddings().weight[
98
+ index_no_updates
99
+ ] = orig_embeds[index_no_updates]
100
+ weight = text_encoder.get_input_embeddings().weight
101
+ pass
102
+
103
+ def get_trainable_params(self):
104
+ params = []
105
+ for text_encoder in self.text_encoder_list:
106
+ params += text_encoder.get_input_embeddings().parameters()
107
+ return params
108
+
109
+ def _get_vec(self, text_encoder_idx=0):
110
+ # should we get params instead
111
+ # create vector from token embeds
112
+ token_embeds = self.text_encoder_list[text_encoder_idx].get_input_embeddings().weight.data
113
+ # stack the tokens along batch axis adding that axis
114
+ new_vector = torch.stack(
115
+ [token_embeds[token_id] for token_id in self.placeholder_token_ids[text_encoder_idx]],
116
+ dim=0
117
+ )
118
+ return new_vector
119
+
120
+ def _set_vec(self, new_vector, text_encoder_idx=0):
121
+ # shape is (1, 768) for SD 1.5 for 1 token
122
+ token_embeds = self.text_encoder_list[text_encoder_idx].get_input_embeddings().weight.data
123
+ for i in range(new_vector.shape[0]):
124
+ # apply the weights to the placeholder tokens while preserving gradient
125
+ token_embeds[self.placeholder_token_ids[text_encoder_idx][i]] = new_vector[i].clone()
126
+
127
+ # make setter and getter for vec
128
+ @property
129
+ def vec(self):
130
+ return self._get_vec(0)
131
+
132
+ @vec.setter
133
+ def vec(self, new_vector):
134
+ self._set_vec(new_vector, 0)
135
+
136
+ @property
137
+ def vec2(self):
138
+ return self._get_vec(1)
139
+
140
+ @vec2.setter
141
+ def vec2(self, new_vector):
142
+ self._set_vec(new_vector, 1)
143
+
144
+ # diffusers automatically expands the token meaning test123 becomes test123 test123_1 test123_2 etc
145
+ # however, on training we don't use that pipeline, so we have to do it ourselves
146
+ def inject_embedding_to_prompt(self, prompt, expand_token=False, to_replace_list=None, add_if_not_present=True):
147
+ output_prompt = prompt
148
+ embedding_tokens = self.embedding_tokens[0] # shoudl be the same
149
+ default_replacements = ["[name]", "[trigger]"]
150
+
151
+ replace_with = embedding_tokens if expand_token else self.trigger
152
+ if to_replace_list is None:
153
+ to_replace_list = default_replacements
154
+ else:
155
+ to_replace_list += default_replacements
156
+
157
+ # remove duplicates
158
+ to_replace_list = list(set(to_replace_list))
159
+
160
+ # replace them all
161
+ for to_replace in to_replace_list:
162
+ # replace it
163
+ output_prompt = output_prompt.replace(to_replace, replace_with)
164
+
165
+ # see how many times replace_with is in the prompt
166
+ num_instances = output_prompt.count(replace_with)
167
+
168
+ if num_instances == 0 and add_if_not_present:
169
+ # add it to the beginning of the prompt
170
+ output_prompt = replace_with + " " + output_prompt
171
+
172
+ if num_instances > 1:
173
+ print(
174
+ f"Warning: {replace_with} token appears {num_instances} times in prompt {output_prompt}. This may cause issues.")
175
+
176
+ return output_prompt
177
+
178
+ def state_dict(self):
179
+ if self.sd.is_xl:
180
+ state_dict = OrderedDict()
181
+ state_dict['clip_l'] = self.vec
182
+ state_dict['clip_g'] = self.vec2
183
+ else:
184
+ state_dict = OrderedDict()
185
+ state_dict['emb_params'] = self.vec
186
+
187
+ return state_dict
188
+
189
+ def save(self, filename):
190
+ # todo check to see how to get the vector out of the embedding
191
+
192
+ embedding_data = {
193
+ "string_to_token": {"*": 265},
194
+ "string_to_param": {"*": self.vec},
195
+ "name": self.name,
196
+ "step": self.step,
197
+ # todo get these
198
+ "sd_checkpoint": None,
199
+ "sd_checkpoint_name": None,
200
+ "notes": None,
201
+ }
202
+ # TODO we do not currently support this. Check how auto is doing it. Only safetensors supported sor sdxl
203
+ if filename.endswith('.pt'):
204
+ torch.save(embedding_data, filename)
205
+ elif filename.endswith('.bin'):
206
+ torch.save(embedding_data, filename)
207
+ elif filename.endswith('.safetensors'):
208
+ # save the embedding as a safetensors file
209
+ state_dict = self.state_dict()
210
+ # add all embedding data (except string_to_param), to metadata
211
+ metadata = OrderedDict({k: json.dumps(v) for k, v in embedding_data.items() if k != "string_to_param"})
212
+ metadata["string_to_param"] = {"*": "emb_params"}
213
+ save_meta = get_meta_for_safetensors(metadata, name=self.name)
214
+ save_file(state_dict, filename, metadata=save_meta)
215
+
216
+ def load_embedding_from_file(self, file_path, device):
217
+ # full path
218
+ path = os.path.realpath(file_path)
219
+ filename = os.path.basename(path)
220
+ name, ext = os.path.splitext(filename)
221
+ tensors = {}
222
+ ext = ext.upper()
223
+ if ext in ['.PNG', '.WEBP', '.JXL', '.AVIF']:
224
+ _, second_ext = os.path.splitext(name)
225
+ if second_ext.upper() == '.PREVIEW':
226
+ return
227
+
228
+ if ext in ['.BIN', '.PT']:
229
+ # todo check this
230
+ if self.sd.is_xl:
231
+ raise Exception("XL not supported yet for bin, pt")
232
+ data = torch.load(path, map_location="cpu")
233
+ elif ext in ['.SAFETENSORS']:
234
+ # rebuild the embedding from the safetensors file if it has it
235
+ with safetensors.torch.safe_open(path, framework="pt", device="cpu") as f:
236
+ metadata = f.metadata()
237
+ for k in f.keys():
238
+ tensors[k] = f.get_tensor(k)
239
+ # data = safetensors.torch.load_file(path, device="cpu")
240
+ if metadata and 'string_to_param' in metadata and 'emb_params' in tensors:
241
+ # our format
242
+ def try_json(v):
243
+ try:
244
+ return json.loads(v)
245
+ except:
246
+ return v
247
+
248
+ data = {k: try_json(v) for k, v in metadata.items()}
249
+ data['string_to_param'] = {'*': tensors['emb_params']}
250
+ else:
251
+ # old format
252
+ data = tensors
253
+ else:
254
+ return
255
+
256
+ if self.sd.is_xl:
257
+ self.vec = tensors['clip_l'].detach().to(device, dtype=torch.float32)
258
+ self.vec2 = tensors['clip_g'].detach().to(device, dtype=torch.float32)
259
+ if 'step' in data:
260
+ self.step = int(data['step'])
261
+ else:
262
+ # textual inversion embeddings
263
+ if 'string_to_param' in data:
264
+ param_dict = data['string_to_param']
265
+ if hasattr(param_dict, '_parameters'):
266
+ param_dict = getattr(param_dict,
267
+ '_parameters') # fix for torch 1.12.1 loading saved file from torch 1.11
268
+ assert len(param_dict) == 1, 'embedding file has multiple terms in it'
269
+ emb = next(iter(param_dict.items()))[1]
270
+ # diffuser concepts
271
+ elif type(data) == dict and type(next(iter(data.values()))) == torch.Tensor:
272
+ assert len(data.keys()) == 1, 'embedding file has multiple terms in it'
273
+
274
+ emb = next(iter(data.values()))
275
+ if len(emb.shape) == 1:
276
+ emb = emb.unsqueeze(0)
277
+ else:
278
+ raise Exception(
279
+ f"Couldn't identify {filename} as neither textual inversion embedding nor diffuser concept.")
280
+
281
+ if 'step' in data:
282
+ self.step = int(data['step'])
283
+
284
+ self.vec = emb.detach().to(device, dtype=torch.float32)
toolkit/esrgan_utils.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ to_basicsr_dict = {
3
+ 'model.0.weight': 'conv_first.weight',
4
+ 'model.0.bias': 'conv_first.bias',
5
+ 'model.1.sub.23.weight': 'conv_body.weight',
6
+ 'model.1.sub.23.bias': 'conv_body.bias',
7
+ 'model.3.weight': 'conv_up1.weight',
8
+ 'model.3.bias': 'conv_up1.bias',
9
+ 'model.6.weight': 'conv_up2.weight',
10
+ 'model.6.bias': 'conv_up2.bias',
11
+ 'model.8.weight': 'conv_hr.weight',
12
+ 'model.8.bias': 'conv_hr.bias',
13
+ 'model.10.bias': 'conv_last.bias',
14
+ 'model.10.weight': 'conv_last.weight',
15
+ # 'model.1.sub.0.RDB1.conv1.0.weight': 'body.0.rdb1.conv1.weight'
16
+ }
17
+
18
+ def convert_state_dict_to_basicsr(state_dict):
19
+ new_state_dict = {}
20
+ for k, v in state_dict.items():
21
+ if k in to_basicsr_dict:
22
+ new_state_dict[to_basicsr_dict[k]] = v
23
+ elif k.startswith('model.1.sub.'):
24
+ bsr_name = k.replace('model.1.sub.', 'body.').lower()
25
+ bsr_name = bsr_name.replace('.0.weight', '.weight')
26
+ bsr_name = bsr_name.replace('.0.bias', '.bias')
27
+ new_state_dict[bsr_name] = v
28
+ else:
29
+ new_state_dict[k] = v
30
+ return new_state_dict
31
+
32
+
33
+ # just matching a commonly used format
34
+ def convert_basicsr_state_dict_to_save_format(state_dict):
35
+ new_state_dict = {}
36
+ to_basicsr_dict_values = list(to_basicsr_dict.values())
37
+ for k, v in state_dict.items():
38
+ if k in to_basicsr_dict_values:
39
+ for key, value in to_basicsr_dict.items():
40
+ if value == k:
41
+ new_state_dict[key] = v
42
+
43
+ elif k.startswith('body.'):
44
+ bsr_name = k.replace('body.', 'model.1.sub.').lower()
45
+ bsr_name = bsr_name.replace('rdb', 'RDB')
46
+ bsr_name = bsr_name.replace('.weight', '.0.weight')
47
+ bsr_name = bsr_name.replace('.bias', '.0.bias')
48
+ new_state_dict[bsr_name] = v
49
+ else:
50
+ new_state_dict[k] = v
51
+ return new_state_dict
toolkit/extension.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib
3
+ import pkgutil
4
+ from typing import List
5
+
6
+ from toolkit.paths import TOOLKIT_ROOT
7
+
8
+
9
+ class Extension(object):
10
+ """Base class for extensions.
11
+
12
+ Extensions are registered with the ExtensionManager, which is
13
+ responsible for calling the extension's load() and unload()
14
+ methods at the appropriate times.
15
+
16
+ """
17
+
18
+ name: str = None
19
+ uid: str = None
20
+
21
+ @classmethod
22
+ def get_process(cls):
23
+ # extend in subclass
24
+ pass
25
+
26
+
27
+ def get_all_extensions() -> List[Extension]:
28
+ extension_folders = ['extensions', 'extensions_built_in']
29
+
30
+ # This will hold the classes from all extension modules
31
+ all_extension_classes: List[Extension] = []
32
+
33
+ # Iterate over all directories (i.e., packages) in the "extensions" directory
34
+ for sub_dir in extension_folders:
35
+ extensions_dir = os.path.join(TOOLKIT_ROOT, sub_dir)
36
+ for (_, name, _) in pkgutil.iter_modules([extensions_dir]):
37
+ # try:
38
+ # Import the module
39
+ module = importlib.import_module(f"{sub_dir}.{name}")
40
+ # Get the value of the AI_TOOLKIT_EXTENSIONS variable
41
+ extensions = getattr(module, "AI_TOOLKIT_EXTENSIONS", None)
42
+ # Check if the value is a list
43
+ if isinstance(extensions, list):
44
+ # Iterate over the list and add the classes to the main list
45
+ all_extension_classes.extend(extensions)
46
+ # except ImportError as e:
47
+ # print(f"Failed to import the {name} module. Error: {str(e)}")
48
+
49
+ return all_extension_classes
50
+
51
+
52
+ def get_all_extensions_process_dict():
53
+ all_extensions = get_all_extensions()
54
+ process_dict = {}
55
+ for extension in all_extensions:
56
+ process_dict[extension.uid] = extension.get_process()
57
+ return process_dict
toolkit/guidance.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Literal, Optional
3
+
4
+ from toolkit.basic import value_map
5
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
6
+ from toolkit.prompt_utils import PromptEmbeds, concat_prompt_embeds
7
+ from toolkit.stable_diffusion_model import StableDiffusion
8
+ from toolkit.train_tools import get_torch_dtype
9
+ from toolkit.config_modules import TrainConfig
10
+
11
+ GuidanceType = Literal["targeted", "polarity", "targeted_polarity", "direct"]
12
+
13
+ DIFFERENTIAL_SCALER = 0.2
14
+
15
+
16
+ # DIFFERENTIAL_SCALER = 0.25
17
+
18
+
19
+ def get_differential_mask(
20
+ conditional_latents: torch.Tensor,
21
+ unconditional_latents: torch.Tensor,
22
+ threshold: float = 0.2,
23
+ gradient: bool = False,
24
+ ):
25
+ # make a differential mask
26
+ differential_mask = torch.abs(conditional_latents - unconditional_latents)
27
+ if len(differential_mask.shape) == 4:
28
+ max_differential = \
29
+ differential_mask.max(dim=1, keepdim=True)[0].max(dim=2, keepdim=True)[0].max(dim=3, keepdim=True)[0]
30
+ elif len(differential_mask.shape) == 5:
31
+ max_differential = \
32
+ differential_mask.max(dim=1, keepdim=True)[0].max(dim=2, keepdim=True)[0].max(dim=3, keepdim=True)[0].max(dim=4, keepdim=True)[0]
33
+ differential_scaler = 1.0 / max_differential
34
+ differential_mask = differential_mask * differential_scaler
35
+
36
+ if gradient:
37
+ # wew need to scale it to 0-1
38
+ # differential_mask = differential_mask - differential_mask.min()
39
+ # differential_mask = differential_mask / differential_mask.max()
40
+ # add 0.2 threshold to both sides and clip
41
+ differential_mask = value_map(
42
+ differential_mask,
43
+ differential_mask.min(),
44
+ differential_mask.max(),
45
+ 0 - threshold,
46
+ 1 + threshold
47
+ )
48
+ differential_mask = torch.clamp(differential_mask, 0.0, 1.0)
49
+ else:
50
+
51
+ # make everything less than 0.2 be 0.0 and everything else be 1.0
52
+ differential_mask = torch.where(
53
+ differential_mask < threshold,
54
+ torch.zeros_like(differential_mask),
55
+ torch.ones_like(differential_mask)
56
+ )
57
+ return differential_mask
58
+
59
+
60
+ def get_targeted_polarity_loss(
61
+ noisy_latents: torch.Tensor,
62
+ conditional_embeds: PromptEmbeds,
63
+ match_adapter_assist: bool,
64
+ network_weight_list: list,
65
+ timesteps: torch.Tensor,
66
+ pred_kwargs: dict,
67
+ batch: 'DataLoaderBatchDTO',
68
+ noise: torch.Tensor,
69
+ sd: 'StableDiffusion',
70
+ **kwargs
71
+ ):
72
+ dtype = get_torch_dtype(sd.torch_dtype)
73
+ device = sd.device_torch
74
+ with torch.no_grad():
75
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
76
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
77
+
78
+ # inputs_abs_mean = torch.abs(conditional_latents).mean(dim=[1, 2, 3], keepdim=True)
79
+ # noise_abs_mean = torch.abs(noise).mean(dim=[1, 2, 3], keepdim=True)
80
+ differential_scaler = DIFFERENTIAL_SCALER
81
+
82
+ unconditional_diff = (unconditional_latents - conditional_latents)
83
+ unconditional_diff_noise = unconditional_diff * differential_scaler
84
+ conditional_diff = (conditional_latents - unconditional_latents)
85
+ conditional_diff_noise = conditional_diff * differential_scaler
86
+ conditional_diff_noise = conditional_diff_noise.detach().requires_grad_(False)
87
+ unconditional_diff_noise = unconditional_diff_noise.detach().requires_grad_(False)
88
+ #
89
+ baseline_conditional_noisy_latents = sd.add_noise(
90
+ conditional_latents,
91
+ noise,
92
+ timesteps
93
+ ).detach()
94
+
95
+ baseline_unconditional_noisy_latents = sd.add_noise(
96
+ unconditional_latents,
97
+ noise,
98
+ timesteps
99
+ ).detach()
100
+
101
+ conditional_noise = noise + unconditional_diff_noise
102
+ unconditional_noise = noise + conditional_diff_noise
103
+
104
+ conditional_noisy_latents = sd.add_noise(
105
+ conditional_latents,
106
+ conditional_noise,
107
+ timesteps
108
+ ).detach()
109
+
110
+ unconditional_noisy_latents = sd.add_noise(
111
+ unconditional_latents,
112
+ unconditional_noise,
113
+ timesteps
114
+ ).detach()
115
+
116
+ # double up everything to run it through all at once
117
+ cat_embeds = concat_prompt_embeds([conditional_embeds, conditional_embeds])
118
+ cat_latents = torch.cat([conditional_noisy_latents, unconditional_noisy_latents], dim=0)
119
+ cat_timesteps = torch.cat([timesteps, timesteps], dim=0)
120
+ # cat_baseline_noisy_latents = torch.cat(
121
+ # [baseline_conditional_noisy_latents, baseline_unconditional_noisy_latents],
122
+ # dim=0
123
+ # )
124
+
125
+ # Disable the LoRA network so we can predict parent network knowledge without it
126
+ # sd.network.is_active = False
127
+ # sd.unet.eval()
128
+
129
+ # Predict noise to get a baseline of what the parent network wants to do with the latents + noise.
130
+ # This acts as our control to preserve the unaltered parts of the image.
131
+ # baseline_prediction = sd.predict_noise(
132
+ # latents=cat_baseline_noisy_latents.to(device, dtype=dtype).detach(),
133
+ # conditional_embeddings=cat_embeds.to(device, dtype=dtype).detach(),
134
+ # timestep=cat_timesteps,
135
+ # guidance_scale=1.0,
136
+ # **pred_kwargs # adapter residuals in here
137
+ # ).detach()
138
+
139
+ # conditional_baseline_prediction, unconditional_baseline_prediction = torch.chunk(baseline_prediction, 2, dim=0)
140
+
141
+ # negative_network_weights = [weight * -1.0 for weight in network_weight_list]
142
+ # positive_network_weights = [weight * 1.0 for weight in network_weight_list]
143
+ # cat_network_weight_list = positive_network_weights + negative_network_weights
144
+
145
+ # turn the LoRA network back on.
146
+ sd.unet.train()
147
+ # sd.network.is_active = True
148
+
149
+ # sd.network.multiplier = cat_network_weight_list
150
+
151
+ # do our prediction with LoRA active on the scaled guidance latents
152
+ prediction = sd.predict_noise(
153
+ latents=cat_latents.to(device, dtype=dtype).detach(),
154
+ conditional_embeddings=cat_embeds.to(device, dtype=dtype).detach(),
155
+ timestep=cat_timesteps,
156
+ guidance_scale=1.0,
157
+ **pred_kwargs # adapter residuals in here
158
+ )
159
+
160
+ # prediction = prediction - baseline_prediction
161
+
162
+ pred_pos, pred_neg = torch.chunk(prediction, 2, dim=0)
163
+ # pred_pos = pred_pos - conditional_baseline_prediction
164
+ # pred_neg = pred_neg - unconditional_baseline_prediction
165
+
166
+ pred_loss = torch.nn.functional.mse_loss(
167
+ pred_pos.float(),
168
+ conditional_noise.float(),
169
+ reduction="none"
170
+ )
171
+ pred_loss = pred_loss.mean([1, 2, 3])
172
+
173
+ pred_neg_loss = torch.nn.functional.mse_loss(
174
+ pred_neg.float(),
175
+ unconditional_noise.float(),
176
+ reduction="none"
177
+ )
178
+ pred_neg_loss = pred_neg_loss.mean([1, 2, 3])
179
+
180
+ loss = pred_loss + pred_neg_loss
181
+
182
+ loss = loss.mean()
183
+ loss.backward()
184
+
185
+ # detach it so parent class can run backward on no grads without throwing error
186
+ loss = loss.detach()
187
+ loss.requires_grad_(True)
188
+
189
+ return loss
190
+
191
+ def get_direct_guidance_loss(
192
+ noisy_latents: torch.Tensor,
193
+ conditional_embeds: 'PromptEmbeds',
194
+ match_adapter_assist: bool,
195
+ network_weight_list: list,
196
+ timesteps: torch.Tensor,
197
+ pred_kwargs: dict,
198
+ batch: 'DataLoaderBatchDTO',
199
+ noise: torch.Tensor,
200
+ sd: 'StableDiffusion',
201
+ unconditional_embeds: Optional[PromptEmbeds] = None,
202
+ mask_multiplier=None,
203
+ prior_pred=None,
204
+ **kwargs
205
+ ):
206
+ with torch.no_grad():
207
+ # Perform targeted guidance (working title)
208
+ dtype = get_torch_dtype(sd.torch_dtype)
209
+ device = sd.device_torch
210
+
211
+
212
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
213
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
214
+
215
+ conditional_noisy_latents = sd.add_noise(
216
+ conditional_latents,
217
+ # target_noise,
218
+ noise,
219
+ timesteps
220
+ ).detach()
221
+
222
+ unconditional_noisy_latents = sd.add_noise(
223
+ unconditional_latents,
224
+ noise,
225
+ timesteps
226
+ ).detach()
227
+ # turn the LoRA network back on.
228
+ sd.unet.train()
229
+ # sd.network.is_active = True
230
+
231
+ # sd.network.multiplier = network_weight_list
232
+ # do our prediction with LoRA active on the scaled guidance latents
233
+ if unconditional_embeds is not None:
234
+ unconditional_embeds = unconditional_embeds.to(device, dtype=dtype).detach()
235
+ unconditional_embeds = concat_prompt_embeds([unconditional_embeds, unconditional_embeds])
236
+
237
+ prediction = sd.predict_noise(
238
+ latents=torch.cat([unconditional_noisy_latents, conditional_noisy_latents]).to(device, dtype=dtype).detach(),
239
+ conditional_embeddings=concat_prompt_embeds([conditional_embeds,conditional_embeds]).to(device, dtype=dtype).detach(),
240
+ unconditional_embeddings=unconditional_embeds,
241
+ timestep=torch.cat([timesteps, timesteps]),
242
+ guidance_scale=1.0,
243
+ **pred_kwargs # adapter residuals in here
244
+ )
245
+
246
+ noise_pred_uncond, noise_pred_cond = torch.chunk(prediction, 2, dim=0)
247
+
248
+ guidance_scale = 1.1
249
+ guidance_pred = noise_pred_uncond + guidance_scale * (
250
+ noise_pred_cond - noise_pred_uncond
251
+ )
252
+
253
+ guidance_loss = torch.nn.functional.mse_loss(
254
+ guidance_pred.float(),
255
+ noise.detach().float(),
256
+ reduction="none"
257
+ )
258
+ if mask_multiplier is not None:
259
+ guidance_loss = guidance_loss * mask_multiplier
260
+
261
+ guidance_loss = guidance_loss.mean([1, 2, 3])
262
+
263
+ guidance_loss = guidance_loss.mean()
264
+
265
+ # loss = guidance_loss + masked_noise_loss
266
+ loss = guidance_loss
267
+
268
+ loss.backward()
269
+
270
+ # detach it so parent class can run backward on no grads without throwing error
271
+ loss = loss.detach()
272
+ loss.requires_grad_(True)
273
+
274
+ return loss
275
+
276
+
277
+ # targeted
278
+ def get_targeted_guidance_loss(
279
+ noisy_latents: torch.Tensor,
280
+ conditional_embeds: 'PromptEmbeds',
281
+ match_adapter_assist: bool,
282
+ network_weight_list: list,
283
+ timesteps: torch.Tensor,
284
+ pred_kwargs: dict,
285
+ batch: 'DataLoaderBatchDTO',
286
+ noise: torch.Tensor,
287
+ sd: 'StableDiffusion',
288
+ **kwargs
289
+ ):
290
+ with torch.no_grad():
291
+ dtype = get_torch_dtype(sd.torch_dtype)
292
+ device = sd.device_torch
293
+
294
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
295
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
296
+
297
+ # Encode the unconditional image into latents
298
+ unconditional_noisy_latents = sd.noise_scheduler.add_noise(
299
+ unconditional_latents,
300
+ noise,
301
+ timesteps
302
+ )
303
+ conditional_noisy_latents = sd.noise_scheduler.add_noise(
304
+ conditional_latents,
305
+ noise,
306
+ timesteps
307
+ )
308
+
309
+ # was_network_active = self.network.is_active
310
+ sd.network.is_active = False
311
+ sd.unet.eval()
312
+
313
+ target_differential = unconditional_latents - conditional_latents
314
+ # scale our loss by the differential scaler
315
+ target_differential_abs = target_differential.abs()
316
+ target_differential_abs_min = \
317
+ target_differential_abs.min(dim=1, keepdim=True)[0].max(dim=2, keepdim=True)[0].max(dim=3, keepdim=True)[0]
318
+ target_differential_abs_max = \
319
+ target_differential_abs.max(dim=1, keepdim=True)[0].max(dim=2, keepdim=True)[0].max(dim=3, keepdim=True)[0]
320
+
321
+ min_guidance = 1.0
322
+ max_guidance = 2.0
323
+
324
+ differential_scaler = value_map(
325
+ target_differential_abs,
326
+ target_differential_abs_min,
327
+ target_differential_abs_max,
328
+ min_guidance,
329
+ max_guidance
330
+ ).detach()
331
+
332
+
333
+ # With LoRA network bypassed, predict noise to get a baseline of what the network
334
+ # wants to do with the latents + noise. Pass our target latents here for the input.
335
+ target_unconditional = sd.predict_noise(
336
+ latents=unconditional_noisy_latents.to(device, dtype=dtype).detach(),
337
+ conditional_embeddings=conditional_embeds.to(device, dtype=dtype).detach(),
338
+ timestep=timesteps,
339
+ guidance_scale=1.0,
340
+ **pred_kwargs # adapter residuals in here
341
+ ).detach()
342
+ prior_prediction_loss = torch.nn.functional.mse_loss(
343
+ target_unconditional.float(),
344
+ noise.float(),
345
+ reduction="none"
346
+ ).detach().clone()
347
+
348
+ # turn the LoRA network back on.
349
+ sd.unet.train()
350
+ sd.network.is_active = True
351
+ sd.network.multiplier = network_weight_list + [x + -1.0 for x in network_weight_list]
352
+
353
+ # with LoRA active, predict the noise with the scaled differential latents added. This will allow us
354
+ # the opportunity to predict the differential + noise that was added to the latents.
355
+ prediction = sd.predict_noise(
356
+ latents=torch.cat([conditional_noisy_latents, unconditional_noisy_latents], dim=0).to(device, dtype=dtype).detach(),
357
+ conditional_embeddings=concat_prompt_embeds([conditional_embeds, conditional_embeds]).to(device, dtype=dtype).detach(),
358
+ timestep=torch.cat([timesteps, timesteps], dim=0),
359
+ guidance_scale=1.0,
360
+ **pred_kwargs # adapter residuals in here
361
+ )
362
+
363
+ prediction_conditional, prediction_unconditional = torch.chunk(prediction, 2, dim=0)
364
+
365
+ conditional_loss = torch.nn.functional.mse_loss(
366
+ prediction_conditional.float(),
367
+ noise.float(),
368
+ reduction="none"
369
+ )
370
+
371
+ unconditional_loss = torch.nn.functional.mse_loss(
372
+ prediction_unconditional.float(),
373
+ noise.float(),
374
+ reduction="none"
375
+ )
376
+
377
+ positive_loss = torch.abs(
378
+ conditional_loss.float() - prior_prediction_loss.float(),
379
+ )
380
+ # scale our loss by the differential scaler
381
+ positive_loss = positive_loss * differential_scaler
382
+
383
+ positive_loss = positive_loss.mean([1, 2, 3])
384
+
385
+ polar_loss = torch.abs(
386
+ conditional_loss.float() - unconditional_loss.float(),
387
+ ).mean([1, 2, 3])
388
+
389
+
390
+ positive_loss = positive_loss.mean() + polar_loss.mean()
391
+
392
+
393
+ positive_loss.backward()
394
+ # loss = positive_loss.detach() + negative_loss.detach()
395
+ loss = positive_loss.detach()
396
+
397
+ # add a grad so other backward does not fail
398
+ loss.requires_grad_(True)
399
+
400
+ # restore network
401
+ sd.network.multiplier = network_weight_list
402
+
403
+ return loss
404
+
405
+ def get_guided_loss_polarity(
406
+ noisy_latents: torch.Tensor,
407
+ conditional_embeds: PromptEmbeds,
408
+ match_adapter_assist: bool,
409
+ network_weight_list: list,
410
+ timesteps: torch.Tensor,
411
+ pred_kwargs: dict,
412
+ batch: 'DataLoaderBatchDTO',
413
+ noise: torch.Tensor,
414
+ sd: 'StableDiffusion',
415
+ train_config: 'TrainConfig',
416
+ scaler=None,
417
+ **kwargs
418
+ ):
419
+ dtype = get_torch_dtype(sd.torch_dtype)
420
+ device = sd.device_torch
421
+ with torch.no_grad():
422
+ dtype = get_torch_dtype(dtype)
423
+ noise = noise.to(device, dtype=dtype).detach()
424
+
425
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
426
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
427
+
428
+ target_pos = noise
429
+ target_neg = noise
430
+
431
+ if sd.is_flow_matching:
432
+ linear_timesteps = any([
433
+ train_config.linear_timesteps,
434
+ train_config.linear_timesteps2,
435
+ train_config.timestep_type == 'linear',
436
+ ])
437
+
438
+ timestep_type = 'linear' if linear_timesteps else None
439
+ if timestep_type is None:
440
+ timestep_type = train_config.timestep_type
441
+
442
+ sd.noise_scheduler.set_train_timesteps(
443
+ 1000,
444
+ device=device,
445
+ timestep_type=timestep_type,
446
+ latents=conditional_latents
447
+ )
448
+ target_pos = (noise - conditional_latents).detach()
449
+ target_neg = (noise - unconditional_latents).detach()
450
+
451
+ conditional_noisy_latents = sd.add_noise(
452
+ conditional_latents,
453
+ noise,
454
+ timesteps
455
+ ).detach()
456
+ conditional_noisy_latents = sd.condition_noisy_latents(conditional_noisy_latents, batch)
457
+
458
+ unconditional_noisy_latents = sd.add_noise(
459
+ unconditional_latents,
460
+ noise,
461
+ timesteps
462
+ ).detach()
463
+ unconditional_noisy_latents = sd.condition_noisy_latents(unconditional_noisy_latents, batch)
464
+
465
+ # double up everything to run it through all at once
466
+ cat_embeds = concat_prompt_embeds([conditional_embeds, conditional_embeds])
467
+ cat_latents = torch.cat([conditional_noisy_latents, unconditional_noisy_latents], dim=0)
468
+ cat_timesteps = torch.cat([timesteps, timesteps], dim=0)
469
+
470
+ negative_network_weights = [weight * -1.0 for weight in network_weight_list]
471
+ positive_network_weights = [weight * 1.0 for weight in network_weight_list]
472
+ cat_network_weight_list = positive_network_weights + negative_network_weights
473
+
474
+ # turn the LoRA network back on.
475
+ sd.unet.train()
476
+ sd.network.is_active = True
477
+
478
+ sd.network.multiplier = cat_network_weight_list
479
+
480
+ # do our prediction with LoRA active on the scaled guidance latents
481
+ prediction = sd.predict_noise(
482
+ latents=cat_latents.to(device, dtype=dtype).detach(),
483
+ conditional_embeddings=cat_embeds.to(device, dtype=dtype).detach(),
484
+ timestep=cat_timesteps,
485
+ guidance_scale=1.0,
486
+ **pred_kwargs # adapter residuals in here
487
+ )
488
+
489
+ pred_pos, pred_neg = torch.chunk(prediction, 2, dim=0)
490
+
491
+ pred_loss = torch.nn.functional.mse_loss(
492
+ pred_pos.float(),
493
+ target_pos.float(),
494
+ reduction="none"
495
+ )
496
+ # pred_loss = pred_loss.mean([1, 2, 3])
497
+
498
+ pred_neg_loss = torch.nn.functional.mse_loss(
499
+ pred_neg.float(),
500
+ target_neg.float(),
501
+ reduction="none"
502
+ )
503
+
504
+ loss = pred_loss + pred_neg_loss
505
+
506
+ loss = loss.mean([1, 2, 3])
507
+ loss = loss.mean()
508
+ if scaler is not None:
509
+ scaler.scale(loss).backward()
510
+ else:
511
+ loss.backward()
512
+
513
+ # detach it so parent class can run backward on no grads without throwing error
514
+ loss = loss.detach()
515
+ loss.requires_grad_(True)
516
+
517
+ return loss
518
+
519
+
520
+
521
+ def get_guided_tnt(
522
+ noisy_latents: torch.Tensor,
523
+ conditional_embeds: PromptEmbeds,
524
+ match_adapter_assist: bool,
525
+ network_weight_list: list,
526
+ timesteps: torch.Tensor,
527
+ pred_kwargs: dict,
528
+ batch: 'DataLoaderBatchDTO',
529
+ noise: torch.Tensor,
530
+ sd: 'StableDiffusion',
531
+ prior_pred: torch.Tensor = None,
532
+ **kwargs
533
+ ):
534
+ dtype = get_torch_dtype(sd.torch_dtype)
535
+ device = sd.device_torch
536
+ with torch.no_grad():
537
+ dtype = get_torch_dtype(dtype)
538
+ noise = noise.to(device, dtype=dtype).detach()
539
+
540
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
541
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
542
+
543
+ conditional_noisy_latents = sd.add_noise(
544
+ conditional_latents,
545
+ noise,
546
+ timesteps
547
+ ).detach()
548
+
549
+ unconditional_noisy_latents = sd.add_noise(
550
+ unconditional_latents,
551
+ noise,
552
+ timesteps
553
+ ).detach()
554
+
555
+ # double up everything to run it through all at once
556
+ cat_embeds = concat_prompt_embeds([conditional_embeds, conditional_embeds])
557
+ cat_latents = torch.cat([conditional_noisy_latents, unconditional_noisy_latents], dim=0)
558
+ cat_timesteps = torch.cat([timesteps, timesteps], dim=0)
559
+
560
+
561
+ # turn the LoRA network back on.
562
+ sd.unet.train()
563
+ if sd.network is not None:
564
+ cat_network_weight_list = [weight for weight in network_weight_list * 2]
565
+ sd.network.multiplier = cat_network_weight_list
566
+ sd.network.is_active = True
567
+
568
+
569
+ prediction = sd.predict_noise(
570
+ latents=cat_latents.to(device, dtype=dtype).detach(),
571
+ conditional_embeddings=cat_embeds.to(device, dtype=dtype).detach(),
572
+ timestep=cat_timesteps,
573
+ guidance_scale=1.0,
574
+ **pred_kwargs # adapter residuals in here
575
+ )
576
+ this_prediction, that_prediction = torch.chunk(prediction, 2, dim=0)
577
+
578
+ this_loss = torch.nn.functional.mse_loss(
579
+ this_prediction.float(),
580
+ noise.float(),
581
+ reduction="none"
582
+ )
583
+
584
+ that_loss = torch.nn.functional.mse_loss(
585
+ that_prediction.float(),
586
+ noise.float(),
587
+ reduction="none"
588
+ )
589
+
590
+ this_loss = this_loss.mean([1, 2, 3])
591
+ # negative loss on that
592
+ that_loss = -that_loss.mean([1, 2, 3])
593
+
594
+ with torch.no_grad():
595
+ # match that loss with this loss so it is not a negative value and same scale
596
+ that_loss_scaler = torch.abs(this_loss) / torch.abs(that_loss)
597
+
598
+ that_loss = that_loss * that_loss_scaler * 0.01
599
+
600
+ loss = this_loss + that_loss
601
+
602
+ loss = loss.mean()
603
+
604
+ loss.backward()
605
+
606
+ # detach it so parent class can run backward on no grads without throwing error
607
+ loss = loss.detach()
608
+ loss.requires_grad_(True)
609
+
610
+ return loss
611
+
612
+ def targeted_flow_guidance(
613
+ noisy_latents: torch.Tensor,
614
+ conditional_embeds: 'PromptEmbeds',
615
+ match_adapter_assist: bool,
616
+ network_weight_list: list,
617
+ timesteps: torch.Tensor,
618
+ pred_kwargs: dict,
619
+ batch: 'DataLoaderBatchDTO',
620
+ noise: torch.Tensor,
621
+ sd: 'StableDiffusion',
622
+ unconditional_embeds: Optional[PromptEmbeds] = None,
623
+ mask_multiplier=None,
624
+ prior_pred=None,
625
+ scaler=None,
626
+ train_config=None,
627
+ **kwargs
628
+ ):
629
+ if not sd.is_flow_matching:
630
+ raise ValueError("targeted_flow only works on flow matching models")
631
+ dtype = get_torch_dtype(sd.torch_dtype)
632
+ device = sd.device_torch
633
+ with torch.no_grad():
634
+ dtype = get_torch_dtype(dtype)
635
+ noise = noise.to(device, dtype=dtype).detach()
636
+
637
+ conditional_latents = batch.latents.to(device, dtype=dtype).detach()
638
+ unconditional_latents = batch.unconditional_latents.to(device, dtype=dtype).detach()
639
+
640
+ # get a mask on the differential of the latents
641
+ # this will be scaled from 0.0-1.0 with 1.0 being the largest differential
642
+ abs_differential_mask = get_differential_mask(
643
+ conditional_latents,
644
+ unconditional_latents,
645
+ gradient=True
646
+ )
647
+
648
+ # get noisy latents for both conditional and unconditional predictions
649
+ unconditional_noisy_latents = sd.add_noise(
650
+ unconditional_latents,
651
+ noise,
652
+ timesteps
653
+ ).detach()
654
+ unconditional_noisy_latents = sd.condition_noisy_latents(unconditional_noisy_latents, batch)
655
+ conditional_noisy_latents = sd.add_noise(
656
+ conditional_latents,
657
+ noise,
658
+ timesteps
659
+ ).detach()
660
+ conditional_noisy_latents = sd.condition_noisy_latents(conditional_noisy_latents, batch)
661
+
662
+ # disable the lora to get a baseline prediction
663
+ sd.network.is_active = False
664
+ sd.unet.eval()
665
+
666
+ # get a baseline prediction of the model knowledge without the lora network
667
+ # we do this with the unconditional noisy latents
668
+ baseline_prediction = sd.predict_noise(
669
+ latents=unconditional_noisy_latents.to(device, dtype=dtype).detach(),
670
+ conditional_embeddings=conditional_embeds.to(device, dtype=dtype).detach(),
671
+ timestep=timesteps,
672
+ guidance_scale=1.0,
673
+ **pred_kwargs
674
+ ).detach()
675
+
676
+ # This is our normal flowmatching target
677
+ # target = noise - latents
678
+ # we need to target the baseline noise but with our conditional latents
679
+ # to do this we first have to determine the baseline_prediction noise by reversing the flowmatching target
680
+ baseline_predicted_noise = baseline_prediction + unconditional_latents
681
+
682
+ # baseline_predicted_noise is now the noise prediction our model would make with a the unconditional image.
683
+ # we use this as our new noise target to preserve the existing knowledge of the image.
684
+ # we apply a mask to this noise to only allow the differential of the conditional latents to be learned
685
+ baseline_predicted_noise = (1 - abs_differential_mask) * baseline_predicted_noise
686
+ masked_noise = abs_differential_mask * noise
687
+ target_noise = masked_noise + baseline_predicted_noise
688
+
689
+ # compute our new target prediction using our current knowledge noise with our conditional latents
690
+ # this makes it so the only new information is the differential of our conditional and unconditional latents
691
+ # forcing the network to preserve existing knowledge, but learn only our changes
692
+ target_pred = (target_noise - conditional_latents).detach()
693
+
694
+ # make a prediction with the lora network active
695
+ sd.unet.train()
696
+ sd.network.is_active = True
697
+ sd.network.multiplier = network_weight_list
698
+ prediction = sd.predict_noise(
699
+ latents=conditional_noisy_latents.to(device, dtype=dtype).detach(),
700
+ conditional_embeddings=conditional_embeds.to(device, dtype=dtype).detach(),
701
+ timestep=timesteps,
702
+ guidance_scale=1.0,
703
+ **pred_kwargs
704
+ )
705
+
706
+ # target our baseline + diffirential noise target
707
+ pred_loss = torch.nn.functional.mse_loss(
708
+ prediction.float(),
709
+ target_pred.float()
710
+ )
711
+
712
+ return pred_loss
713
+
714
+
715
+ # this processes all guidance losses based on the batch information
716
+ def get_guidance_loss(
717
+ noisy_latents: torch.Tensor,
718
+ conditional_embeds: 'PromptEmbeds',
719
+ match_adapter_assist: bool,
720
+ network_weight_list: list,
721
+ timesteps: torch.Tensor,
722
+ pred_kwargs: dict,
723
+ batch: 'DataLoaderBatchDTO',
724
+ noise: torch.Tensor,
725
+ sd: 'StableDiffusion',
726
+ unconditional_embeds: Optional[PromptEmbeds] = None,
727
+ mask_multiplier=None,
728
+ prior_pred=None,
729
+ scaler=None,
730
+ train_config=None,
731
+ **kwargs
732
+ ):
733
+ # TODO add others and process individual batch items separately
734
+ guidance_type: GuidanceType = batch.file_items[0].dataset_config.guidance_type
735
+
736
+ if guidance_type == "targeted":
737
+ assert unconditional_embeds is None, "Unconditional embeds are not supported for targeted guidance"
738
+ return get_targeted_guidance_loss(
739
+ noisy_latents,
740
+ conditional_embeds,
741
+ match_adapter_assist,
742
+ network_weight_list,
743
+ timesteps,
744
+ pred_kwargs,
745
+ batch,
746
+ noise,
747
+ sd,
748
+ **kwargs
749
+ )
750
+ elif guidance_type == "polarity":
751
+ assert unconditional_embeds is None, "Unconditional embeds are not supported for polarity guidance"
752
+ return get_guided_loss_polarity(
753
+ noisy_latents,
754
+ conditional_embeds,
755
+ match_adapter_assist,
756
+ network_weight_list,
757
+ timesteps,
758
+ pred_kwargs,
759
+ batch,
760
+ noise,
761
+ sd,
762
+ scaler=scaler,
763
+ train_config=train_config,
764
+ **kwargs
765
+ )
766
+ elif guidance_type == "tnt":
767
+ assert unconditional_embeds is None, "Unconditional embeds are not supported for polarity guidance"
768
+ return get_guided_tnt(
769
+ noisy_latents,
770
+ conditional_embeds,
771
+ match_adapter_assist,
772
+ network_weight_list,
773
+ timesteps,
774
+ pred_kwargs,
775
+ batch,
776
+ noise,
777
+ sd,
778
+ prior_pred=prior_pred,
779
+ **kwargs
780
+ )
781
+
782
+ elif guidance_type == "targeted_polarity":
783
+ assert unconditional_embeds is None, "Unconditional embeds are not supported for targeted polarity guidance"
784
+ return get_targeted_polarity_loss(
785
+ noisy_latents,
786
+ conditional_embeds,
787
+ match_adapter_assist,
788
+ network_weight_list,
789
+ timesteps,
790
+ pred_kwargs,
791
+ batch,
792
+ noise,
793
+ sd,
794
+ **kwargs
795
+ )
796
+ elif guidance_type == "direct":
797
+ return get_direct_guidance_loss(
798
+ noisy_latents,
799
+ conditional_embeds,
800
+ match_adapter_assist,
801
+ network_weight_list,
802
+ timesteps,
803
+ pred_kwargs,
804
+ batch,
805
+ noise,
806
+ sd,
807
+ unconditional_embeds=unconditional_embeds,
808
+ mask_multiplier=mask_multiplier,
809
+ prior_pred=prior_pred,
810
+ **kwargs
811
+ )
812
+ elif guidance_type == "targeted_flow":
813
+ return targeted_flow_guidance(
814
+ noisy_latents,
815
+ conditional_embeds,
816
+ match_adapter_assist,
817
+ network_weight_list,
818
+ timesteps,
819
+ pred_kwargs,
820
+ batch,
821
+ noise,
822
+ sd,
823
+ unconditional_embeds=unconditional_embeds,
824
+ mask_multiplier=mask_multiplier,
825
+ prior_pred=prior_pred,
826
+ scaler=scaler,
827
+ train_config=train_config,
828
+ **kwargs
829
+ )
830
+ else:
831
+ raise NotImplementedError(f"Guidance type {guidance_type} is not implemented")
toolkit/image_utils.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref https://github.com/scardine/image_size/blob/master/get_image_size.py
2
+ import atexit
3
+ import collections
4
+ import json
5
+ import os
6
+ import io
7
+ import struct
8
+ import threading
9
+ from typing import TYPE_CHECKING
10
+
11
+ import cv2
12
+ import numpy as np
13
+ import torch
14
+ from diffusers import AutoencoderTiny
15
+ from PIL import Image as PILImage
16
+
17
+ FILE_UNKNOWN = "Sorry, don't know how to get size for this file."
18
+
19
+
20
+ class UnknownImageFormat(Exception):
21
+ pass
22
+
23
+
24
+ types = collections.OrderedDict()
25
+ BMP = types['BMP'] = 'BMP'
26
+ GIF = types['GIF'] = 'GIF'
27
+ ICO = types['ICO'] = 'ICO'
28
+ JPEG = types['JPEG'] = 'JPEG'
29
+ PNG = types['PNG'] = 'PNG'
30
+ TIFF = types['TIFF'] = 'TIFF'
31
+
32
+ image_fields = ['path', 'type', 'file_size', 'width', 'height']
33
+
34
+
35
+ class Image(collections.namedtuple('Image', image_fields)):
36
+
37
+ def to_str_row(self):
38
+ return ("%d\t%d\t%d\t%s\t%s" % (
39
+ self.width,
40
+ self.height,
41
+ self.file_size,
42
+ self.type,
43
+ self.path.replace('\t', '\\t'),
44
+ ))
45
+
46
+ def to_str_row_verbose(self):
47
+ return ("%d\t%d\t%d\t%s\t%s\t##%s" % (
48
+ self.width,
49
+ self.height,
50
+ self.file_size,
51
+ self.type,
52
+ self.path.replace('\t', '\\t'),
53
+ self))
54
+
55
+ def to_str_json(self, indent=None):
56
+ return json.dumps(self._asdict(), indent=indent)
57
+
58
+
59
+ def get_image_size(file_path):
60
+ """
61
+ Return (width, height) for a given img file content - no external
62
+ dependencies except the os and struct builtin modules
63
+ """
64
+ img = get_image_metadata(file_path)
65
+ return (img.width, img.height)
66
+
67
+
68
+ def get_image_size_from_bytesio(input, size):
69
+ """
70
+ Return (width, height) for a given img file content - no external
71
+ dependencies except the os and struct builtin modules
72
+
73
+ Args:
74
+ input (io.IOBase): io object support read & seek
75
+ size (int): size of buffer in byte
76
+ """
77
+ img = get_image_metadata_from_bytesio(input, size)
78
+ return (img.width, img.height)
79
+
80
+
81
+ def get_image_metadata(file_path):
82
+ """
83
+ Return an `Image` object for a given img file content - no external
84
+ dependencies except the os and struct builtin modules
85
+
86
+ Args:
87
+ file_path (str): path to an image file
88
+
89
+ Returns:
90
+ Image: (path, type, file_size, width, height)
91
+ """
92
+ size = os.path.getsize(file_path)
93
+
94
+ # be explicit with open arguments - we need binary mode
95
+ with io.open(file_path, "rb") as input:
96
+ return get_image_metadata_from_bytesio(input, size, file_path)
97
+
98
+
99
+ def get_image_metadata_from_bytesio(input, size, file_path=None):
100
+ """
101
+ Return an `Image` object for a given img file content - no external
102
+ dependencies except the os and struct builtin modules
103
+
104
+ Args:
105
+ input (io.IOBase): io object support read & seek
106
+ size (int): size of buffer in byte
107
+ file_path (str): path to an image file
108
+
109
+ Returns:
110
+ Image: (path, type, file_size, width, height)
111
+ """
112
+ height = -1
113
+ width = -1
114
+ data = input.read(26)
115
+ msg = " raised while trying to decode as JPEG."
116
+
117
+ if (size >= 10) and data[:6] in (b'GIF87a', b'GIF89a'):
118
+ # GIFs
119
+ imgtype = GIF
120
+ w, h = struct.unpack("<HH", data[6:10])
121
+ width = int(w)
122
+ height = int(h)
123
+ elif ((size >= 24) and data.startswith(b'\211PNG\r\n\032\n')
124
+ and (data[12:16] == b'IHDR')):
125
+ # PNGs
126
+ imgtype = PNG
127
+ w, h = struct.unpack(">LL", data[16:24])
128
+ width = int(w)
129
+ height = int(h)
130
+ elif (size >= 16) and data.startswith(b'\211PNG\r\n\032\n'):
131
+ # older PNGs
132
+ imgtype = PNG
133
+ w, h = struct.unpack(">LL", data[8:16])
134
+ width = int(w)
135
+ height = int(h)
136
+ elif (size >= 2) and data.startswith(b'\377\330'):
137
+ # JPEG
138
+ imgtype = JPEG
139
+ input.seek(0)
140
+ input.read(2)
141
+ b = input.read(1)
142
+ try:
143
+ while (b and ord(b) != 0xDA):
144
+ while (ord(b) != 0xFF):
145
+ b = input.read(1)
146
+ while (ord(b) == 0xFF):
147
+ b = input.read(1)
148
+ if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
149
+ input.read(3)
150
+ h, w = struct.unpack(">HH", input.read(4))
151
+ break
152
+ else:
153
+ input.read(
154
+ int(struct.unpack(">H", input.read(2))[0]) - 2)
155
+ b = input.read(1)
156
+ width = int(w)
157
+ height = int(h)
158
+ except struct.error:
159
+ raise UnknownImageFormat("StructError" + msg)
160
+ except ValueError:
161
+ raise UnknownImageFormat("ValueError" + msg)
162
+ except Exception as e:
163
+ raise UnknownImageFormat(e.__class__.__name__ + msg)
164
+ elif (size >= 26) and data.startswith(b'BM'):
165
+ # BMP
166
+ imgtype = 'BMP'
167
+ headersize = struct.unpack("<I", data[14:18])[0]
168
+ if headersize == 12:
169
+ w, h = struct.unpack("<HH", data[18:22])
170
+ width = int(w)
171
+ height = int(h)
172
+ elif headersize >= 40:
173
+ w, h = struct.unpack("<ii", data[18:26])
174
+ width = int(w)
175
+ # as h is negative when stored upside down
176
+ height = abs(int(h))
177
+ else:
178
+ raise UnknownImageFormat(
179
+ "Unkown DIB header size:" +
180
+ str(headersize))
181
+ elif (size >= 8) and data[:4] in (b"II\052\000", b"MM\000\052"):
182
+ # Standard TIFF, big- or little-endian
183
+ # BigTIFF and other different but TIFF-like formats are not
184
+ # supported currently
185
+ imgtype = TIFF
186
+ byteOrder = data[:2]
187
+ boChar = ">" if byteOrder == "MM" else "<"
188
+ # maps TIFF type id to size (in bytes)
189
+ # and python format char for struct
190
+ tiffTypes = {
191
+ 1: (1, boChar + "B"), # BYTE
192
+ 2: (1, boChar + "c"), # ASCII
193
+ 3: (2, boChar + "H"), # SHORT
194
+ 4: (4, boChar + "L"), # LONG
195
+ 5: (8, boChar + "LL"), # RATIONAL
196
+ 6: (1, boChar + "b"), # SBYTE
197
+ 7: (1, boChar + "c"), # UNDEFINED
198
+ 8: (2, boChar + "h"), # SSHORT
199
+ 9: (4, boChar + "l"), # SLONG
200
+ 10: (8, boChar + "ll"), # SRATIONAL
201
+ 11: (4, boChar + "f"), # FLOAT
202
+ 12: (8, boChar + "d") # DOUBLE
203
+ }
204
+ ifdOffset = struct.unpack(boChar + "L", data[4:8])[0]
205
+ try:
206
+ countSize = 2
207
+ input.seek(ifdOffset)
208
+ ec = input.read(countSize)
209
+ ifdEntryCount = struct.unpack(boChar + "H", ec)[0]
210
+ # 2 bytes: TagId + 2 bytes: type + 4 bytes: count of values + 4
211
+ # bytes: value offset
212
+ ifdEntrySize = 12
213
+ for i in range(ifdEntryCount):
214
+ entryOffset = ifdOffset + countSize + i * ifdEntrySize
215
+ input.seek(entryOffset)
216
+ tag = input.read(2)
217
+ tag = struct.unpack(boChar + "H", tag)[0]
218
+ if (tag == 256 or tag == 257):
219
+ # if type indicates that value fits into 4 bytes, value
220
+ # offset is not an offset but value itself
221
+ type = input.read(2)
222
+ type = struct.unpack(boChar + "H", type)[0]
223
+ if type not in tiffTypes:
224
+ raise UnknownImageFormat(
225
+ "Unkown TIFF field type:" +
226
+ str(type))
227
+ typeSize = tiffTypes[type][0]
228
+ typeChar = tiffTypes[type][1]
229
+ input.seek(entryOffset + 8)
230
+ value = input.read(typeSize)
231
+ value = int(struct.unpack(typeChar, value)[0])
232
+ if tag == 256:
233
+ width = value
234
+ else:
235
+ height = value
236
+ if width > -1 and height > -1:
237
+ break
238
+ except Exception as e:
239
+ raise UnknownImageFormat(str(e))
240
+ elif size >= 2:
241
+ # see http://en.wikipedia.org/wiki/ICO_(file_format)
242
+ imgtype = 'ICO'
243
+ input.seek(0)
244
+ reserved = input.read(2)
245
+ if 0 != struct.unpack("<H", reserved)[0]:
246
+ raise UnknownImageFormat(FILE_UNKNOWN)
247
+ format = input.read(2)
248
+ assert 1 == struct.unpack("<H", format)[0]
249
+ num = input.read(2)
250
+ num = struct.unpack("<H", num)[0]
251
+ if num > 1:
252
+ import warnings
253
+ warnings.warn("ICO File contains more than one image")
254
+ # http://msdn.microsoft.com/en-us/library/ms997538.aspx
255
+ w = input.read(1)
256
+ h = input.read(1)
257
+ width = ord(w)
258
+ height = ord(h)
259
+ else:
260
+ raise UnknownImageFormat(FILE_UNKNOWN)
261
+
262
+ return Image(path=file_path,
263
+ type=imgtype,
264
+ file_size=size,
265
+ width=width,
266
+ height=height)
267
+
268
+
269
+ import unittest
270
+
271
+
272
+ class Test_get_image_size(unittest.TestCase):
273
+ data = [{
274
+ 'path': 'lookmanodeps.png',
275
+ 'width': 251,
276
+ 'height': 208,
277
+ 'file_size': 22228,
278
+ 'type': 'PNG'}]
279
+
280
+ def setUp(self):
281
+ pass
282
+
283
+ def test_get_image_size_from_bytesio(self):
284
+ img = self.data[0]
285
+ p = img['path']
286
+ with io.open(p, 'rb') as fp:
287
+ b = fp.read()
288
+ fp = io.BytesIO(b)
289
+ sz = len(b)
290
+ output = get_image_size_from_bytesio(fp, sz)
291
+ self.assertTrue(output)
292
+ self.assertEqual(output,
293
+ (img['width'],
294
+ img['height']))
295
+
296
+ def test_get_image_metadata_from_bytesio(self):
297
+ img = self.data[0]
298
+ p = img['path']
299
+ with io.open(p, 'rb') as fp:
300
+ b = fp.read()
301
+ fp = io.BytesIO(b)
302
+ sz = len(b)
303
+ output = get_image_metadata_from_bytesio(fp, sz)
304
+ self.assertTrue(output)
305
+ for field in image_fields:
306
+ self.assertEqual(getattr(output, field), None if field == 'path' else img[field])
307
+
308
+ def test_get_image_metadata(self):
309
+ img = self.data[0]
310
+ output = get_image_metadata(img['path'])
311
+ self.assertTrue(output)
312
+ for field in image_fields:
313
+ self.assertEqual(getattr(output, field), img[field])
314
+
315
+ def test_get_image_metadata__ENOENT_OSError(self):
316
+ with self.assertRaises(OSError):
317
+ get_image_metadata('THIS_DOES_NOT_EXIST')
318
+
319
+ def test_get_image_metadata__not_an_image_UnknownImageFormat(self):
320
+ with self.assertRaises(UnknownImageFormat):
321
+ get_image_metadata('README.rst')
322
+
323
+ def test_get_image_size(self):
324
+ img = self.data[0]
325
+ output = get_image_size(img['path'])
326
+ self.assertTrue(output)
327
+ self.assertEqual(output,
328
+ (img['width'],
329
+ img['height']))
330
+
331
+ def tearDown(self):
332
+ pass
333
+
334
+
335
+ def main(argv=None):
336
+ """
337
+ Print image metadata fields for the given file path.
338
+
339
+ Keyword Arguments:
340
+ argv (list): commandline arguments (e.g. sys.argv[1:])
341
+ Returns:
342
+ int: zero for OK
343
+ """
344
+ import logging
345
+ import optparse
346
+ import sys
347
+
348
+ prs = optparse.OptionParser(
349
+ usage="%prog [-v|--verbose] [--json|--json-indent] <path0> [<pathN>]",
350
+ description="Print metadata for the given image paths "
351
+ "(without image library bindings).")
352
+
353
+ prs.add_option('--json',
354
+ dest='json',
355
+ action='store_true')
356
+ prs.add_option('--json-indent',
357
+ dest='json_indent',
358
+ action='store_true')
359
+
360
+ prs.add_option('-v', '--verbose',
361
+ dest='verbose',
362
+ action='store_true', )
363
+ prs.add_option('-q', '--quiet',
364
+ dest='quiet',
365
+ action='store_true', )
366
+ prs.add_option('-t', '--test',
367
+ dest='run_tests',
368
+ action='store_true', )
369
+
370
+ argv = list(argv) if argv is not None else sys.argv[1:]
371
+ (opts, args) = prs.parse_args(args=argv)
372
+ loglevel = logging.INFO
373
+ if opts.verbose:
374
+ loglevel = logging.DEBUG
375
+ elif opts.quiet:
376
+ loglevel = logging.ERROR
377
+ logging.basicConfig(level=loglevel)
378
+ log = logging.getLogger()
379
+ log.debug('argv: %r', argv)
380
+ log.debug('opts: %r', opts)
381
+ log.debug('args: %r', args)
382
+
383
+ if opts.run_tests:
384
+ import sys
385
+ sys.argv = [sys.argv[0]] + args
386
+ import unittest
387
+ return unittest.main()
388
+
389
+ output_func = Image.to_str_row
390
+ if opts.json_indent:
391
+ import functools
392
+ output_func = functools.partial(Image.to_str_json, indent=2)
393
+ elif opts.json:
394
+ output_func = Image.to_str_json
395
+ elif opts.verbose:
396
+ output_func = Image.to_str_row_verbose
397
+
398
+ EX_OK = 0
399
+ EX_NOT_OK = 2
400
+
401
+ if len(args) < 1:
402
+ prs.print_help()
403
+ print('')
404
+ prs.error("You must specify one or more paths to image files")
405
+
406
+ errors = []
407
+ for path_arg in args:
408
+ try:
409
+ img = get_image_metadata(path_arg)
410
+ print(output_func(img))
411
+ except KeyboardInterrupt:
412
+ raise
413
+ except OSError as e:
414
+ log.error((path_arg, e))
415
+ errors.append((path_arg, e))
416
+ except Exception as e:
417
+ log.exception(e)
418
+ errors.append((path_arg, e))
419
+ pass
420
+ if len(errors):
421
+ import pprint
422
+ print("ERRORS", file=sys.stderr)
423
+ print("======", file=sys.stderr)
424
+ print(pprint.pformat(errors, indent=2), file=sys.stderr)
425
+ return EX_NOT_OK
426
+ return EX_OK
427
+
428
+
429
+ is_window_shown = False
430
+ display_lock = threading.Lock()
431
+ current_img = None
432
+ update_event = threading.Event()
433
+
434
+ def update_image(img, name):
435
+ global current_img
436
+ with display_lock:
437
+ current_img = (img, name)
438
+ update_event.set()
439
+
440
+ def display_image_in_thread():
441
+ global is_window_shown
442
+
443
+ def display_img():
444
+ global current_img
445
+ while True:
446
+ update_event.wait()
447
+ with display_lock:
448
+ if current_img:
449
+ img, name = current_img
450
+ cv2.imshow(name, img)
451
+ current_img = None
452
+ update_event.clear()
453
+ if cv2.waitKey(1) & 0xFF == 27: # Esc key to stop
454
+ cv2.destroyAllWindows()
455
+ print('\nESC pressed, stopping')
456
+ break
457
+
458
+ if not is_window_shown:
459
+ is_window_shown = True
460
+ threading.Thread(target=display_img, daemon=True).start()
461
+
462
+
463
+ def show_img(img, name='AI Toolkit'):
464
+ img = np.clip(img, 0, 255).astype(np.uint8)
465
+ update_image(img[:, :, ::-1], name)
466
+ if not is_window_shown:
467
+ display_image_in_thread()
468
+
469
+
470
+ def show_tensors(imgs: torch.Tensor, name='AI Toolkit'):
471
+ if len(imgs.shape) == 4:
472
+ img_list = torch.chunk(imgs, imgs.shape[0], dim=0)
473
+ else:
474
+ img_list = [imgs]
475
+
476
+ img = torch.cat(img_list, dim=3)
477
+ img = img / 2 + 0.5
478
+ img_numpy = img.to(torch.float32).detach().cpu().numpy()
479
+ img_numpy = np.clip(img_numpy, 0, 1) * 255
480
+ img_numpy = img_numpy.transpose(0, 2, 3, 1)
481
+ img_numpy = img_numpy.astype(np.uint8)
482
+
483
+ show_img(img_numpy[0], name=name)
484
+
485
+ def save_tensors(imgs: torch.Tensor, path='output.png', fps=None):
486
+ if len(imgs.shape) == 5 and imgs.shape[0] == 1:
487
+ imgs = imgs.squeeze(0)
488
+ if len(imgs.shape) == 4:
489
+ img_list = torch.chunk(imgs, imgs.shape[0], dim=0)
490
+ else:
491
+ img_list = [imgs]
492
+
493
+ num_frames = len(img_list)
494
+ print(f"Saving {num_frames} frames to {path} at {fps} fps")
495
+ if fps is not None and num_frames > 1:
496
+ img = torch.cat(img_list, dim=0)
497
+ else:
498
+ img = torch.cat(img_list, dim=3)
499
+ img = img / 2 + 0.5
500
+ img_numpy = img.to(torch.float32).detach().cpu().numpy()
501
+ img_numpy = np.clip(img_numpy, 0, 1) * 255
502
+ img_numpy = img_numpy.transpose(0, 2, 3, 1)
503
+ img_numpy = img_numpy.astype(np.uint8)
504
+
505
+ if fps is not None and num_frames > 1:
506
+ img_list = [PILImage.fromarray(img_numpy[i]) for i in range(num_frames)]
507
+ duration = int(1000 / fps)
508
+ img_list[0].save(path, save_all=True, append_images=img_list[1:], duration=duration, loop=0, quality=95)
509
+ else:
510
+ # concat images to one
511
+ img_numpy = np.concatenate(img_numpy, axis=1)
512
+ # conver to pil
513
+ img_pil = PILImage.fromarray(img_numpy)
514
+ img_pil.save(path)
515
+
516
+ def show_latents(latents: torch.Tensor, vae: 'AutoencoderTiny', name='AI Toolkit'):
517
+ if vae.device == 'cpu':
518
+ vae.to(latents.device)
519
+ latents = latents / vae.config['scaling_factor']
520
+ imgs = vae.decode(latents).sample
521
+ show_tensors(imgs, name=name)
522
+
523
+
524
+ def on_exit():
525
+ if is_window_shown:
526
+ cv2.destroyAllWindows()
527
+
528
+
529
+ def reduce_contrast(tensor, factor):
530
+ # Ensure factor is between 0 and 1
531
+ factor = max(0, min(factor, 1))
532
+
533
+ # Calculate the mean of the tensor
534
+ mean = torch.mean(tensor)
535
+
536
+ # Reduce contrast
537
+ adjusted_tensor = (tensor - mean) * factor + mean
538
+
539
+ # Clip values to ensure they stay within -1 to 1 range
540
+ return torch.clamp(adjusted_tensor, -1.0, 1.0)
541
+
542
+ atexit.register(on_exit)
543
+
544
+ if __name__ == "__main__":
545
+ import sys
546
+
547
+ sys.exit(main(argv=sys.argv[1:]))
toolkit/inversion_utils.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref https://huggingface.co/spaces/editing-images/ledits/blob/main/inversion_utils.py
2
+
3
+ import torch
4
+ import os
5
+ from tqdm import tqdm
6
+
7
+ from toolkit import train_tools
8
+ from toolkit.prompt_utils import PromptEmbeds
9
+ from toolkit.stable_diffusion_model import StableDiffusion
10
+
11
+
12
+ def mu_tilde(model, xt, x0, timestep):
13
+ "mu_tilde(x_t, x_0) DDPM paper eq. 7"
14
+ prev_timestep = timestep - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
15
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[
16
+ prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
17
+ alpha_t = model.scheduler.alphas[timestep]
18
+ beta_t = 1 - alpha_t
19
+ alpha_bar = model.scheduler.alphas_cumprod[timestep]
20
+ return ((alpha_prod_t_prev ** 0.5 * beta_t) / (1 - alpha_bar)) * x0 + (
21
+ (alpha_t ** 0.5 * (1 - alpha_prod_t_prev)) / (1 - alpha_bar)) * xt
22
+
23
+
24
+ def sample_xts_from_x0(sd: StableDiffusion, sample: torch.Tensor, num_inference_steps=50):
25
+ """
26
+ Samples from P(x_1:T|x_0)
27
+ """
28
+ # torch.manual_seed(43256465436)
29
+ alpha_bar = sd.noise_scheduler.alphas_cumprod
30
+ sqrt_one_minus_alpha_bar = (1 - alpha_bar) ** 0.5
31
+ alphas = sd.noise_scheduler.alphas
32
+ betas = 1 - alphas
33
+ # variance_noise_shape = (
34
+ # num_inference_steps,
35
+ # sd.unet.in_channels,
36
+ # sd.unet.sample_size,
37
+ # sd.unet.sample_size)
38
+ variance_noise_shape = list(sample.shape)
39
+ variance_noise_shape[0] = num_inference_steps
40
+
41
+ timesteps = sd.noise_scheduler.timesteps.to(sd.device)
42
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
43
+ xts = torch.zeros(variance_noise_shape).to(sample.device, dtype=torch.float16)
44
+ for t in reversed(timesteps):
45
+ idx = t_to_idx[int(t)]
46
+ xts[idx] = sample * (alpha_bar[t] ** 0.5) + torch.randn_like(sample, dtype=torch.float16) * sqrt_one_minus_alpha_bar[t]
47
+ xts = torch.cat([xts, sample], dim=0)
48
+
49
+ return xts
50
+
51
+
52
+ def encode_text(model, prompts):
53
+ text_input = model.tokenizer(
54
+ prompts,
55
+ padding="max_length",
56
+ max_length=model.tokenizer.model_max_length,
57
+ truncation=True,
58
+ return_tensors="pt",
59
+ )
60
+ with torch.no_grad():
61
+ text_encoding = model.text_encoder(text_input.input_ids.to(model.device))[0]
62
+ return text_encoding
63
+
64
+
65
+ def forward_step(sd: StableDiffusion, model_output, timestep, sample):
66
+ next_timestep = min(
67
+ sd.noise_scheduler.config['num_train_timesteps'] - 2,
68
+ timestep + sd.noise_scheduler.config['num_train_timesteps'] // sd.noise_scheduler.num_inference_steps
69
+ )
70
+
71
+ # 2. compute alphas, betas
72
+ alpha_prod_t = sd.noise_scheduler.alphas_cumprod[timestep]
73
+ # alpha_prod_t_next = self.scheduler.alphas_cumprod[next_timestep] if next_ltimestep >= 0 else self.scheduler.final_alpha_cumprod
74
+
75
+ beta_prod_t = 1 - alpha_prod_t
76
+
77
+ # 3. compute predicted original sample from predicted noise also called
78
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
79
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
80
+
81
+ # 5. TODO: simple noising implementation
82
+ next_sample = sd.noise_scheduler.add_noise(
83
+ pred_original_sample,
84
+ model_output,
85
+ torch.LongTensor([next_timestep]))
86
+ return next_sample
87
+
88
+
89
+ def get_variance(sd: StableDiffusion, timestep): # , prev_timestep):
90
+ prev_timestep = timestep - sd.noise_scheduler.config['num_train_timesteps'] // sd.noise_scheduler.num_inference_steps
91
+ alpha_prod_t = sd.noise_scheduler.alphas_cumprod[timestep]
92
+ alpha_prod_t_prev = sd.noise_scheduler.alphas_cumprod[
93
+ prev_timestep] if prev_timestep >= 0 else sd.noise_scheduler.final_alpha_cumprod
94
+ beta_prod_t = 1 - alpha_prod_t
95
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
96
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
97
+ return variance
98
+
99
+
100
+ def get_time_ids_from_latents(sd: StableDiffusion, latents: torch.Tensor):
101
+ VAE_SCALE_FACTOR = 2 ** (len(sd.vae.config['block_out_channels']) - 1)
102
+ if sd.is_xl:
103
+ bs, ch, h, w = list(latents.shape)
104
+
105
+ height = h * VAE_SCALE_FACTOR
106
+ width = w * VAE_SCALE_FACTOR
107
+
108
+ dtype = latents.dtype
109
+ # just do it without any cropping nonsense
110
+ target_size = (height, width)
111
+ original_size = (height, width)
112
+ crops_coords_top_left = (0, 0)
113
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
114
+ add_time_ids = torch.tensor([add_time_ids])
115
+ add_time_ids = add_time_ids.to(latents.device, dtype=dtype)
116
+
117
+ batch_time_ids = torch.cat(
118
+ [add_time_ids for _ in range(bs)]
119
+ )
120
+ return batch_time_ids
121
+ else:
122
+ return None
123
+
124
+
125
+ def inversion_forward_process(
126
+ sd: StableDiffusion,
127
+ sample: torch.Tensor,
128
+ conditional_embeddings: PromptEmbeds,
129
+ unconditional_embeddings: PromptEmbeds,
130
+ etas=None,
131
+ prog_bar=False,
132
+ cfg_scale=3.5,
133
+ num_inference_steps=50, eps=None
134
+ ):
135
+ current_num_timesteps = len(sd.noise_scheduler.timesteps)
136
+ sd.noise_scheduler.set_timesteps(num_inference_steps, device=sd.device)
137
+
138
+ timesteps = sd.noise_scheduler.timesteps.to(sd.device)
139
+ # variance_noise_shape = (
140
+ # num_inference_steps,
141
+ # sd.unet.in_channels,
142
+ # sd.unet.sample_size,
143
+ # sd.unet.sample_size
144
+ # )
145
+ variance_noise_shape = list(sample.shape)
146
+ variance_noise_shape[0] = num_inference_steps
147
+ if etas is None or (type(etas) in [int, float] and etas == 0):
148
+ eta_is_zero = True
149
+ zs = None
150
+ else:
151
+ eta_is_zero = False
152
+ if type(etas) in [int, float]: etas = [etas] * sd.noise_scheduler.num_inference_steps
153
+ xts = sample_xts_from_x0(sd, sample, num_inference_steps=num_inference_steps)
154
+ alpha_bar = sd.noise_scheduler.alphas_cumprod
155
+ zs = torch.zeros(size=variance_noise_shape, device=sd.device, dtype=torch.float16)
156
+
157
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
158
+ noisy_sample = sample
159
+ op = tqdm(reversed(timesteps), desc="Inverting...") if prog_bar else reversed(timesteps)
160
+
161
+ for timestep in op:
162
+ idx = t_to_idx[int(timestep)]
163
+ # 1. predict noise residual
164
+ if not eta_is_zero:
165
+ noisy_sample = xts[idx][None]
166
+
167
+ added_cond_kwargs = {}
168
+
169
+ with torch.no_grad():
170
+ text_embeddings = train_tools.concat_prompt_embeddings(
171
+ unconditional_embeddings, # negative embedding
172
+ conditional_embeddings, # positive embedding
173
+ 1, # batch size
174
+ )
175
+ if sd.is_xl:
176
+ add_time_ids = get_time_ids_from_latents(sd, noisy_sample)
177
+ # add extra for cfg
178
+ add_time_ids = torch.cat(
179
+ [add_time_ids] * 2, dim=0
180
+ )
181
+
182
+ added_cond_kwargs = {
183
+ "text_embeds": text_embeddings.pooled_embeds,
184
+ "time_ids": add_time_ids,
185
+ }
186
+
187
+ # double up for cfg
188
+ latent_model_input = torch.cat(
189
+ [noisy_sample] * 2, dim=0
190
+ )
191
+
192
+ noise_pred = sd.unet(
193
+ latent_model_input,
194
+ timestep,
195
+ encoder_hidden_states=text_embeddings.text_embeds,
196
+ added_cond_kwargs=added_cond_kwargs,
197
+ ).sample
198
+
199
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
200
+
201
+ # out = sd.unet.forward(noisy_sample, timestep=timestep, encoder_hidden_states=uncond_embedding)
202
+ # cond_out = sd.unet.forward(noisy_sample, timestep=timestep, encoder_hidden_states=text_embeddings)
203
+
204
+ noise_pred = noise_pred_uncond + cfg_scale * (noise_pred_text - noise_pred_uncond)
205
+
206
+ if eta_is_zero:
207
+ # 2. compute more noisy image and set x_t -> x_t+1
208
+ noisy_sample = forward_step(sd, noise_pred, timestep, noisy_sample)
209
+ xts = None
210
+
211
+ else:
212
+ xtm1 = xts[idx + 1][None]
213
+ # pred of x0
214
+ pred_original_sample = (noisy_sample - (1 - alpha_bar[timestep]) ** 0.5 * noise_pred) / alpha_bar[
215
+ timestep] ** 0.5
216
+
217
+ # direction to xt
218
+ prev_timestep = timestep - sd.noise_scheduler.config[
219
+ 'num_train_timesteps'] // sd.noise_scheduler.num_inference_steps
220
+ alpha_prod_t_prev = sd.noise_scheduler.alphas_cumprod[
221
+ prev_timestep] if prev_timestep >= 0 else sd.noise_scheduler.final_alpha_cumprod
222
+
223
+ variance = get_variance(sd, timestep)
224
+ pred_sample_direction = (1 - alpha_prod_t_prev - etas[idx] * variance) ** (0.5) * noise_pred
225
+
226
+ mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
227
+
228
+ z = (xtm1 - mu_xt) / (etas[idx] * variance ** 0.5)
229
+ zs[idx] = z
230
+
231
+ # correction to avoid error accumulation
232
+ xtm1 = mu_xt + (etas[idx] * variance ** 0.5) * z
233
+ xts[idx + 1] = xtm1
234
+
235
+ if not zs is None:
236
+ zs[-1] = torch.zeros_like(zs[-1])
237
+
238
+ # restore timesteps
239
+ sd.noise_scheduler.set_timesteps(current_num_timesteps, device=sd.device)
240
+
241
+ return noisy_sample, zs, xts
242
+
243
+
244
+ #
245
+ # def inversion_forward_process(
246
+ # model,
247
+ # sample,
248
+ # etas=None,
249
+ # prog_bar=False,
250
+ # prompt="",
251
+ # cfg_scale=3.5,
252
+ # num_inference_steps=50, eps=None
253
+ # ):
254
+ # if not prompt == "":
255
+ # text_embeddings = encode_text(model, prompt)
256
+ # uncond_embedding = encode_text(model, "")
257
+ # timesteps = model.scheduler.timesteps.to(model.device)
258
+ # variance_noise_shape = (
259
+ # num_inference_steps,
260
+ # model.unet.in_channels,
261
+ # model.unet.sample_size,
262
+ # model.unet.sample_size)
263
+ # if etas is None or (type(etas) in [int, float] and etas == 0):
264
+ # eta_is_zero = True
265
+ # zs = None
266
+ # else:
267
+ # eta_is_zero = False
268
+ # if type(etas) in [int, float]: etas = [etas] * model.scheduler.num_inference_steps
269
+ # xts = sample_xts_from_x0(model, sample, num_inference_steps=num_inference_steps)
270
+ # alpha_bar = model.scheduler.alphas_cumprod
271
+ # zs = torch.zeros(size=variance_noise_shape, device=model.device, dtype=torch.float16)
272
+ #
273
+ # t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
274
+ # noisy_sample = sample
275
+ # op = tqdm(reversed(timesteps), desc="Inverting...") if prog_bar else reversed(timesteps)
276
+ #
277
+ # for t in op:
278
+ # idx = t_to_idx[int(t)]
279
+ # # 1. predict noise residual
280
+ # if not eta_is_zero:
281
+ # noisy_sample = xts[idx][None]
282
+ #
283
+ # with torch.no_grad():
284
+ # out = model.unet.forward(noisy_sample, timestep=t, encoder_hidden_states=uncond_embedding)
285
+ # if not prompt == "":
286
+ # cond_out = model.unet.forward(noisy_sample, timestep=t, encoder_hidden_states=text_embeddings)
287
+ #
288
+ # if not prompt == "":
289
+ # ## classifier free guidance
290
+ # noise_pred = out.sample + cfg_scale * (cond_out.sample - out.sample)
291
+ # else:
292
+ # noise_pred = out.sample
293
+ #
294
+ # if eta_is_zero:
295
+ # # 2. compute more noisy image and set x_t -> x_t+1
296
+ # noisy_sample = forward_step(model, noise_pred, t, noisy_sample)
297
+ #
298
+ # else:
299
+ # xtm1 = xts[idx + 1][None]
300
+ # # pred of x0
301
+ # pred_original_sample = (noisy_sample - (1 - alpha_bar[t]) ** 0.5 * noise_pred) / alpha_bar[t] ** 0.5
302
+ #
303
+ # # direction to xt
304
+ # prev_timestep = t - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
305
+ # alpha_prod_t_prev = model.scheduler.alphas_cumprod[
306
+ # prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
307
+ #
308
+ # variance = get_variance(model, t)
309
+ # pred_sample_direction = (1 - alpha_prod_t_prev - etas[idx] * variance) ** (0.5) * noise_pred
310
+ #
311
+ # mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
312
+ #
313
+ # z = (xtm1 - mu_xt) / (etas[idx] * variance ** 0.5)
314
+ # zs[idx] = z
315
+ #
316
+ # # correction to avoid error accumulation
317
+ # xtm1 = mu_xt + (etas[idx] * variance ** 0.5) * z
318
+ # xts[idx + 1] = xtm1
319
+ #
320
+ # if not zs is None:
321
+ # zs[-1] = torch.zeros_like(zs[-1])
322
+ #
323
+ # return noisy_sample, zs, xts
324
+
325
+
326
+ def reverse_step(model, model_output, timestep, sample, eta=0, variance_noise=None):
327
+ # 1. get previous step value (=t-1)
328
+ prev_timestep = timestep - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
329
+ # 2. compute alphas, betas
330
+ alpha_prod_t = model.scheduler.alphas_cumprod[timestep]
331
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[
332
+ prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
333
+ beta_prod_t = 1 - alpha_prod_t
334
+ # 3. compute predicted original sample from predicted noise also called
335
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
336
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
337
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
338
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
339
+ # variance = self.scheduler._get_variance(timestep, prev_timestep)
340
+ variance = get_variance(model, timestep) # , prev_timestep)
341
+ std_dev_t = eta * variance ** (0.5)
342
+ # Take care of asymetric reverse process (asyrp)
343
+ model_output_direction = model_output
344
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
345
+ # pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output_direction
346
+ pred_sample_direction = (1 - alpha_prod_t_prev - eta * variance) ** (0.5) * model_output_direction
347
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
348
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
349
+ # 8. Add noice if eta > 0
350
+ if eta > 0:
351
+ if variance_noise is None:
352
+ variance_noise = torch.randn(model_output.shape, device=model.device, dtype=torch.float16)
353
+ sigma_z = eta * variance ** (0.5) * variance_noise
354
+ prev_sample = prev_sample + sigma_z
355
+
356
+ return prev_sample
357
+
358
+
359
+ def inversion_reverse_process(
360
+ model,
361
+ xT,
362
+ etas=0,
363
+ prompts="",
364
+ cfg_scales=None,
365
+ prog_bar=False,
366
+ zs=None,
367
+ controller=None,
368
+ asyrp=False):
369
+ batch_size = len(prompts)
370
+
371
+ cfg_scales_tensor = torch.Tensor(cfg_scales).view(-1, 1, 1, 1).to(model.device, dtype=torch.float16)
372
+
373
+ text_embeddings = encode_text(model, prompts)
374
+ uncond_embedding = encode_text(model, [""] * batch_size)
375
+
376
+ if etas is None: etas = 0
377
+ if type(etas) in [int, float]: etas = [etas] * model.scheduler.num_inference_steps
378
+ assert len(etas) == model.scheduler.num_inference_steps
379
+ timesteps = model.scheduler.timesteps.to(model.device)
380
+
381
+ xt = xT.expand(batch_size, -1, -1, -1)
382
+ op = tqdm(timesteps[-zs.shape[0]:]) if prog_bar else timesteps[-zs.shape[0]:]
383
+
384
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps[-zs.shape[0]:])}
385
+
386
+ for t in op:
387
+ idx = t_to_idx[int(t)]
388
+ ## Unconditional embedding
389
+ with torch.no_grad():
390
+ uncond_out = model.unet.forward(xt, timestep=t,
391
+ encoder_hidden_states=uncond_embedding)
392
+
393
+ ## Conditional embedding
394
+ if prompts:
395
+ with torch.no_grad():
396
+ cond_out = model.unet.forward(xt, timestep=t,
397
+ encoder_hidden_states=text_embeddings)
398
+
399
+ z = zs[idx] if not zs is None else None
400
+ z = z.expand(batch_size, -1, -1, -1)
401
+ if prompts:
402
+ ## classifier free guidance
403
+ noise_pred = uncond_out.sample + cfg_scales_tensor * (cond_out.sample - uncond_out.sample)
404
+ else:
405
+ noise_pred = uncond_out.sample
406
+ # 2. compute less noisy image and set x_t -> x_t-1
407
+ xt = reverse_step(model, noise_pred, t, xt, eta=etas[idx], variance_noise=z)
408
+ if controller is not None:
409
+ xt = controller.step_callback(xt)
410
+ return xt, zs
toolkit/ip_adapter.py ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import torch
4
+ import sys
5
+
6
+ from diffusers import Transformer2DModel
7
+ from torch import nn
8
+ from torch.nn import Parameter
9
+ from torch.nn.modules.module import T
10
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
11
+
12
+ from toolkit.models.clip_pre_processor import CLIPImagePreProcessor
13
+ from toolkit.models.zipper_resampler import ZipperResampler
14
+ from toolkit.saving import load_ip_adapter_model
15
+ from toolkit.train_tools import get_torch_dtype
16
+ from toolkit.util.inverse_cfg import inverse_classifier_guidance
17
+
18
+ from typing import TYPE_CHECKING, Union, Iterator, Mapping, Any, Tuple, List, Optional
19
+ from collections import OrderedDict
20
+ from toolkit.util.ip_adapter_utils import AttnProcessor2_0, IPAttnProcessor2_0, ImageProjModel
21
+ from toolkit.resampler import Resampler
22
+ from toolkit.config_modules import AdapterConfig
23
+ from toolkit.prompt_utils import PromptEmbeds
24
+ import weakref
25
+ from diffusers import FluxTransformer2DModel
26
+
27
+ if TYPE_CHECKING:
28
+ from toolkit.stable_diffusion_model import StableDiffusion
29
+
30
+ from transformers import (
31
+ CLIPImageProcessor,
32
+ CLIPVisionModelWithProjection,
33
+ AutoImageProcessor,
34
+ ConvNextV2ForImageClassification,
35
+ ConvNextForImageClassification,
36
+ ConvNextImageProcessor
37
+ )
38
+ from toolkit.models.size_agnostic_feature_encoder import SAFEImageProcessor, SAFEVisionModel
39
+
40
+ import torch.nn.functional as F
41
+
42
+
43
+ class MLPProjModelClipFace(torch.nn.Module):
44
+ def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
45
+ super().__init__()
46
+
47
+ self.cross_attention_dim = cross_attention_dim
48
+ self.num_tokens = num_tokens
49
+ self.norm = torch.nn.LayerNorm(id_embeddings_dim)
50
+
51
+ self.proj = torch.nn.Sequential(
52
+ torch.nn.Linear(id_embeddings_dim, id_embeddings_dim * 2),
53
+ torch.nn.GELU(),
54
+ torch.nn.Linear(id_embeddings_dim * 2, cross_attention_dim * num_tokens),
55
+ )
56
+ # Initialize the last linear layer weights near zero
57
+ torch.nn.init.uniform_(self.proj[2].weight, a=-0.01, b=0.01)
58
+ torch.nn.init.zeros_(self.proj[2].bias)
59
+ # # Custom initialization for LayerNorm to output near zero
60
+ # torch.nn.init.constant_(self.norm.weight, 0.1) # Small weights near zero
61
+ # torch.nn.init.zeros_(self.norm.bias) # Bias to zero
62
+
63
+ def forward(self, x):
64
+ x = self.norm(x)
65
+ x = self.proj(x)
66
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
67
+ return x
68
+
69
+
70
+ class CustomIPAttentionProcessor(IPAttnProcessor2_0):
71
+ def __init__(self, hidden_size, cross_attention_dim, scale=1.0, num_tokens=4, adapter=None, train_scaler=False, full_token_scaler=False):
72
+ super().__init__(hidden_size, cross_attention_dim, scale=scale, num_tokens=num_tokens)
73
+ self.adapter_ref: weakref.ref = weakref.ref(adapter)
74
+ self.train_scaler = train_scaler
75
+ if train_scaler:
76
+ if full_token_scaler:
77
+ self.ip_scaler = torch.nn.Parameter(torch.ones([num_tokens], dtype=torch.float32) * 0.999)
78
+ else:
79
+ self.ip_scaler = torch.nn.Parameter(torch.ones([1], dtype=torch.float32) * 0.999)
80
+ # self.ip_scaler = torch.nn.Parameter(torch.ones([1], dtype=torch.float32) * 0.9999)
81
+ self.ip_scaler.requires_grad_(True)
82
+
83
+ def __call__(
84
+ self,
85
+ attn,
86
+ hidden_states,
87
+ encoder_hidden_states=None,
88
+ attention_mask=None,
89
+ temb=None,
90
+ ):
91
+ is_active = self.adapter_ref().is_active
92
+ residual = hidden_states
93
+
94
+ if attn.spatial_norm is not None:
95
+ hidden_states = attn.spatial_norm(hidden_states, temb)
96
+
97
+ input_ndim = hidden_states.ndim
98
+
99
+ if input_ndim == 4:
100
+ batch_size, channel, height, width = hidden_states.shape
101
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
102
+
103
+ batch_size, sequence_length, _ = (
104
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
105
+ )
106
+
107
+ if is_active:
108
+ # since we are removing tokens, we need to adjust the sequence length
109
+ sequence_length = sequence_length - self.num_tokens
110
+
111
+ if attention_mask is not None:
112
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
113
+ # scaled_dot_product_attention expects attention_mask shape to be
114
+ # (batch, heads, source_length, target_length)
115
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
116
+
117
+ if attn.group_norm is not None:
118
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
119
+
120
+ query = attn.to_q(hidden_states)
121
+
122
+ if encoder_hidden_states is None:
123
+ encoder_hidden_states = hidden_states
124
+
125
+ # will be none if disabled
126
+ if not is_active:
127
+ ip_hidden_states = None
128
+ if encoder_hidden_states is None:
129
+ encoder_hidden_states = hidden_states
130
+ elif attn.norm_cross:
131
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
132
+ else:
133
+ # get encoder_hidden_states, ip_hidden_states
134
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
135
+ encoder_hidden_states, ip_hidden_states = (
136
+ encoder_hidden_states[:, :end_pos, :],
137
+ encoder_hidden_states[:, end_pos:, :],
138
+ )
139
+ if attn.norm_cross:
140
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
141
+
142
+ key = attn.to_k(encoder_hidden_states)
143
+ value = attn.to_v(encoder_hidden_states)
144
+
145
+ inner_dim = key.shape[-1]
146
+ head_dim = inner_dim // attn.heads
147
+
148
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
149
+
150
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
151
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
152
+
153
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
154
+ # TODO: add support for attn.scale when we move to Torch 2.1
155
+ try:
156
+ hidden_states = F.scaled_dot_product_attention(
157
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
158
+ )
159
+ except Exception as e:
160
+ print(e)
161
+ raise e
162
+
163
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
164
+ hidden_states = hidden_states.to(query.dtype)
165
+
166
+ # will be none if disabled
167
+ if ip_hidden_states is not None:
168
+ # apply scaler
169
+ if self.train_scaler:
170
+ weight = self.ip_scaler
171
+ # reshape to (1, self.num_tokens, 1)
172
+ weight = weight.view(1, -1, 1)
173
+ ip_hidden_states = ip_hidden_states * weight
174
+
175
+ # for ip-adapter
176
+ ip_key = self.to_k_ip(ip_hidden_states)
177
+ ip_value = self.to_v_ip(ip_hidden_states)
178
+
179
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
180
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
181
+
182
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
183
+ # TODO: add support for attn.scale when we move to Torch 2.1
184
+ ip_hidden_states = F.scaled_dot_product_attention(
185
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
186
+ )
187
+
188
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
189
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
190
+
191
+ scale = self.scale
192
+ hidden_states = hidden_states + scale * ip_hidden_states
193
+
194
+ # linear proj
195
+ hidden_states = attn.to_out[0](hidden_states)
196
+ # dropout
197
+ hidden_states = attn.to_out[1](hidden_states)
198
+
199
+ if input_ndim == 4:
200
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
201
+
202
+ if attn.residual_connection:
203
+ hidden_states = hidden_states + residual
204
+
205
+ hidden_states = hidden_states / attn.rescale_output_factor
206
+
207
+ return hidden_states
208
+
209
+ # this ensures that the ip_scaler is not changed when we load the model
210
+ # def _apply(self, fn):
211
+ # if hasattr(self, "ip_scaler"):
212
+ # # Overriding the _apply method to prevent the special_parameter from changing dtype
213
+ # self.ip_scaler = fn(self.ip_scaler)
214
+ # # Temporarily set the special_parameter to None to exclude it from default _apply processing
215
+ # ip_scaler = self.ip_scaler
216
+ # self.ip_scaler = None
217
+ # super(CustomIPAttentionProcessor, self)._apply(fn)
218
+ # # Restore the special_parameter after the default _apply processing
219
+ # self.ip_scaler = ip_scaler
220
+ # return self
221
+ # else:
222
+ # return super(CustomIPAttentionProcessor, self)._apply(fn)
223
+
224
+
225
+ class CustomIPFluxAttnProcessor2_0(torch.nn.Module):
226
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
227
+
228
+ def __init__(self, hidden_size, cross_attention_dim, scale=1.0, num_tokens=4, adapter=None, train_scaler=False,
229
+ full_token_scaler=False):
230
+ super().__init__()
231
+ self.hidden_size = hidden_size
232
+ self.cross_attention_dim = cross_attention_dim
233
+ self.scale = scale
234
+ self.num_tokens = num_tokens
235
+
236
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
237
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
238
+ self.adapter_ref: weakref.ref = weakref.ref(adapter)
239
+ self.train_scaler = train_scaler
240
+ self.num_tokens = num_tokens
241
+ if train_scaler:
242
+ if full_token_scaler:
243
+ self.ip_scaler = torch.nn.Parameter(torch.ones([num_tokens], dtype=torch.float32) * 0.999)
244
+ else:
245
+ self.ip_scaler = torch.nn.Parameter(torch.ones([1], dtype=torch.float32) * 0.999)
246
+ # self.ip_scaler = torch.nn.Parameter(torch.ones([1], dtype=torch.float32) * 0.9999)
247
+ self.ip_scaler.requires_grad_(True)
248
+
249
+ def __call__(
250
+ self,
251
+ attn,
252
+ hidden_states: torch.FloatTensor,
253
+ encoder_hidden_states: torch.FloatTensor = None,
254
+ attention_mask: Optional[torch.FloatTensor] = None,
255
+ image_rotary_emb: Optional[torch.Tensor] = None,
256
+ ) -> torch.FloatTensor:
257
+ is_active = self.adapter_ref().is_active
258
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
259
+
260
+ # `sample` projections.
261
+ query = attn.to_q(hidden_states)
262
+ key = attn.to_k(hidden_states)
263
+ value = attn.to_v(hidden_states)
264
+
265
+ inner_dim = key.shape[-1]
266
+ head_dim = inner_dim // attn.heads
267
+
268
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
269
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
270
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
271
+
272
+ if attn.norm_q is not None:
273
+ query = attn.norm_q(query)
274
+ if attn.norm_k is not None:
275
+ key = attn.norm_k(key)
276
+
277
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
278
+ if encoder_hidden_states is not None:
279
+ # `context` projections.
280
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
281
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
282
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
283
+
284
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
285
+ batch_size, -1, attn.heads, head_dim
286
+ ).transpose(1, 2)
287
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
288
+ batch_size, -1, attn.heads, head_dim
289
+ ).transpose(1, 2)
290
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
291
+ batch_size, -1, attn.heads, head_dim
292
+ ).transpose(1, 2)
293
+
294
+ if attn.norm_added_q is not None:
295
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
296
+ if attn.norm_added_k is not None:
297
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
298
+
299
+ # attention
300
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
301
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
302
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
303
+
304
+ if image_rotary_emb is not None:
305
+ from diffusers.models.embeddings import apply_rotary_emb
306
+
307
+ query = apply_rotary_emb(query, image_rotary_emb)
308
+ key = apply_rotary_emb(key, image_rotary_emb)
309
+
310
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
311
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
312
+ hidden_states = hidden_states.to(query.dtype)
313
+
314
+ # begin ip adapter
315
+ if not is_active:
316
+ ip_hidden_states = None
317
+ else:
318
+ # get ip hidden states. Should be stored
319
+ ip_hidden_states = self.adapter_ref().last_conditional
320
+ # add unconditional to front if it exists
321
+ if ip_hidden_states.shape[0] * 2 == batch_size:
322
+ if self.adapter_ref().last_unconditional is None:
323
+ raise ValueError("Unconditional is None but should not be")
324
+ ip_hidden_states = torch.cat([self.adapter_ref().last_unconditional, ip_hidden_states], dim=0)
325
+
326
+ if ip_hidden_states is not None:
327
+ # apply scaler
328
+ if self.train_scaler:
329
+ weight = self.ip_scaler
330
+ # reshape to (1, self.num_tokens, 1)
331
+ weight = weight.view(1, -1, 1)
332
+ ip_hidden_states = ip_hidden_states * weight
333
+
334
+ # for ip-adapter
335
+ ip_key = self.to_k_ip(ip_hidden_states)
336
+ ip_value = self.to_v_ip(ip_hidden_states)
337
+
338
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
339
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
340
+
341
+ ip_hidden_states = F.scaled_dot_product_attention(
342
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
343
+ )
344
+
345
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
346
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
347
+
348
+ scale = self.scale
349
+ hidden_states = hidden_states + scale * ip_hidden_states
350
+ # end ip adapter
351
+
352
+ if encoder_hidden_states is not None:
353
+ encoder_hidden_states, hidden_states = (
354
+ hidden_states[:, : encoder_hidden_states.shape[1]],
355
+ hidden_states[:, encoder_hidden_states.shape[1] :],
356
+ )
357
+
358
+ # linear proj
359
+ hidden_states = attn.to_out[0](hidden_states)
360
+ # dropout
361
+ hidden_states = attn.to_out[1](hidden_states)
362
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
363
+
364
+ return hidden_states, encoder_hidden_states
365
+ else:
366
+ return hidden_states
367
+
368
+ # loosely based on # ref https://github.com/tencent-ailab/IP-Adapter/blob/main/tutorial_train.py
369
+ class IPAdapter(torch.nn.Module):
370
+ """IP-Adapter"""
371
+
372
+ def __init__(self, sd: 'StableDiffusion', adapter_config: 'AdapterConfig'):
373
+ super().__init__()
374
+ self.config = adapter_config
375
+ self.sd_ref: weakref.ref = weakref.ref(sd)
376
+ self.device = self.sd_ref().unet.device
377
+ self.preprocessor: Optional[CLIPImagePreProcessor] = None
378
+ self.input_size = 224
379
+ self.clip_noise_zero = True
380
+ self.unconditional: torch.Tensor = None
381
+
382
+ self.last_conditional: torch.Tensor = None
383
+ self.last_unconditional: torch.Tensor = None
384
+
385
+ self.additional_loss = None
386
+ if self.config.image_encoder_arch.startswith("clip"):
387
+ try:
388
+ self.clip_image_processor = CLIPImageProcessor.from_pretrained(adapter_config.image_encoder_path)
389
+ except EnvironmentError:
390
+ self.clip_image_processor = CLIPImageProcessor()
391
+ self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(
392
+ adapter_config.image_encoder_path,
393
+ ignore_mismatched_sizes=True).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
394
+ elif self.config.image_encoder_arch == 'siglip':
395
+ from transformers import SiglipImageProcessor, SiglipVisionModel
396
+ try:
397
+ self.clip_image_processor = SiglipImageProcessor.from_pretrained(adapter_config.image_encoder_path)
398
+ except EnvironmentError:
399
+ self.clip_image_processor = SiglipImageProcessor()
400
+ self.image_encoder = SiglipVisionModel.from_pretrained(
401
+ adapter_config.image_encoder_path,
402
+ ignore_mismatched_sizes=True).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
403
+ elif self.config.image_encoder_arch == 'safe':
404
+ try:
405
+ self.clip_image_processor = SAFEImageProcessor.from_pretrained(adapter_config.image_encoder_path)
406
+ except EnvironmentError:
407
+ self.clip_image_processor = SAFEImageProcessor()
408
+ self.image_encoder = SAFEVisionModel(
409
+ in_channels=3,
410
+ num_tokens=self.config.safe_tokens,
411
+ num_vectors=sd.unet.config['cross_attention_dim'],
412
+ reducer_channels=self.config.safe_reducer_channels,
413
+ channels=self.config.safe_channels,
414
+ downscale_factor=8
415
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
416
+ elif self.config.image_encoder_arch == 'convnext':
417
+ try:
418
+ self.clip_image_processor = ConvNextImageProcessor.from_pretrained(adapter_config.image_encoder_path)
419
+ except EnvironmentError:
420
+ print(f"could not load image processor from {adapter_config.image_encoder_path}")
421
+ self.clip_image_processor = ConvNextImageProcessor(
422
+ size=320,
423
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
424
+ image_std=[0.26862954, 0.26130258, 0.27577711],
425
+ )
426
+ self.image_encoder = ConvNextForImageClassification.from_pretrained(
427
+ adapter_config.image_encoder_path,
428
+ use_safetensors=True,
429
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
430
+ elif self.config.image_encoder_arch == 'convnextv2':
431
+ try:
432
+ self.clip_image_processor = AutoImageProcessor.from_pretrained(adapter_config.image_encoder_path)
433
+ except EnvironmentError:
434
+ print(f"could not load image processor from {adapter_config.image_encoder_path}")
435
+ self.clip_image_processor = ConvNextImageProcessor(
436
+ size=512,
437
+ image_mean=[0.485, 0.456, 0.406],
438
+ image_std=[0.229, 0.224, 0.225],
439
+ )
440
+ self.image_encoder = ConvNextV2ForImageClassification.from_pretrained(
441
+ adapter_config.image_encoder_path,
442
+ use_safetensors=True,
443
+ ).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
444
+ else:
445
+ raise ValueError(f"unknown image encoder arch: {adapter_config.image_encoder_arch}")
446
+
447
+ if not self.config.train_image_encoder:
448
+ # compile it
449
+ print('Compiling image encoder')
450
+ #torch.compile(self.image_encoder, fullgraph=True)
451
+
452
+ self.input_size = self.image_encoder.config.image_size
453
+
454
+ if self.config.quad_image: # 4x4 image
455
+ # self.clip_image_processor.config
456
+ # We do a 3x downscale of the image, so we need to adjust the input size
457
+ preprocessor_input_size = self.image_encoder.config.image_size * 2
458
+
459
+ # update the preprocessor so images come in at the right size
460
+ if 'height' in self.clip_image_processor.size:
461
+ self.clip_image_processor.size['height'] = preprocessor_input_size
462
+ self.clip_image_processor.size['width'] = preprocessor_input_size
463
+ elif hasattr(self.clip_image_processor, 'crop_size'):
464
+ self.clip_image_processor.size['shortest_edge'] = preprocessor_input_size
465
+ self.clip_image_processor.crop_size['height'] = preprocessor_input_size
466
+ self.clip_image_processor.crop_size['width'] = preprocessor_input_size
467
+
468
+ if self.config.image_encoder_arch == 'clip+':
469
+ # self.clip_image_processor.config
470
+ # We do a 3x downscale of the image, so we need to adjust the input size
471
+ preprocessor_input_size = self.image_encoder.config.image_size * 4
472
+
473
+ # update the preprocessor so images come in at the right size
474
+ self.clip_image_processor.size['shortest_edge'] = preprocessor_input_size
475
+ self.clip_image_processor.crop_size['height'] = preprocessor_input_size
476
+ self.clip_image_processor.crop_size['width'] = preprocessor_input_size
477
+
478
+ self.preprocessor = CLIPImagePreProcessor(
479
+ input_size=preprocessor_input_size,
480
+ clip_input_size=self.image_encoder.config.image_size,
481
+ )
482
+ if not self.config.image_encoder_arch == 'safe':
483
+ if 'height' in self.clip_image_processor.size:
484
+ self.input_size = self.clip_image_processor.size['height']
485
+ elif hasattr(self.clip_image_processor, 'crop_size'):
486
+ self.input_size = self.clip_image_processor.crop_size['height']
487
+ elif 'shortest_edge' in self.clip_image_processor.size.keys():
488
+ self.input_size = self.clip_image_processor.size['shortest_edge']
489
+ else:
490
+ raise ValueError(f"unknown image processor size: {self.clip_image_processor.size}")
491
+ self.current_scale = 1.0
492
+ self.is_active = True
493
+ is_pixart = sd.is_pixart
494
+ is_flux = sd.is_flux
495
+ if adapter_config.type == 'ip':
496
+ # ip-adapter
497
+ image_proj_model = ImageProjModel(
498
+ cross_attention_dim=sd.unet.config['cross_attention_dim'],
499
+ clip_embeddings_dim=self.image_encoder.config.projection_dim,
500
+ clip_extra_context_tokens=self.config.num_tokens, # usually 4
501
+ )
502
+ elif adapter_config.type == 'ip_clip_face':
503
+ cross_attn_dim = 4096 if is_pixart else sd.unet.config['cross_attention_dim']
504
+ image_proj_model = MLPProjModelClipFace(
505
+ cross_attention_dim=cross_attn_dim,
506
+ id_embeddings_dim=self.image_encoder.config.projection_dim,
507
+ num_tokens=self.config.num_tokens, # usually 4
508
+ )
509
+ elif adapter_config.type == 'ip+':
510
+ heads = 12 if not sd.is_xl else 20
511
+ if is_flux:
512
+ dim = 1280
513
+ else:
514
+ dim = sd.unet.config['cross_attention_dim'] if not sd.is_xl else 1280
515
+ embedding_dim = self.image_encoder.config.hidden_size if not self.config.image_encoder_arch.startswith(
516
+ 'convnext') else \
517
+ self.image_encoder.config.hidden_sizes[-1]
518
+
519
+ image_encoder_state_dict = self.image_encoder.state_dict()
520
+ # max_seq_len = CLIP tokens + CLS token
521
+ max_seq_len = 257
522
+ if "vision_model.embeddings.position_embedding.weight" in image_encoder_state_dict:
523
+ # clip
524
+ max_seq_len = int(
525
+ image_encoder_state_dict["vision_model.embeddings.position_embedding.weight"].shape[0])
526
+
527
+ if is_pixart:
528
+ heads = 20
529
+ dim = 1280
530
+ output_dim = 4096
531
+ elif is_flux:
532
+ heads = 20
533
+ dim = 1280
534
+ output_dim = 3072
535
+ else:
536
+ output_dim = sd.unet.config['cross_attention_dim']
537
+
538
+ if self.config.image_encoder_arch.startswith('convnext'):
539
+ in_tokens = 16 * 16
540
+ embedding_dim = self.image_encoder.config.hidden_sizes[-1]
541
+
542
+ # ip-adapter-plus
543
+ image_proj_model = Resampler(
544
+ dim=dim,
545
+ depth=4,
546
+ dim_head=64,
547
+ heads=heads,
548
+ num_queries=self.config.num_tokens if self.config.num_tokens > 0 else max_seq_len,
549
+ embedding_dim=embedding_dim,
550
+ max_seq_len=max_seq_len,
551
+ output_dim=output_dim,
552
+ ff_mult=4
553
+ )
554
+ elif adapter_config.type == 'ipz':
555
+ dim = sd.unet.config['cross_attention_dim']
556
+ if hasattr(self.image_encoder.config, 'hidden_sizes'):
557
+ embedding_dim = self.image_encoder.config.hidden_sizes[-1]
558
+ else:
559
+ embedding_dim = self.image_encoder.config.target_hidden_size
560
+
561
+ image_encoder_state_dict = self.image_encoder.state_dict()
562
+ # max_seq_len = CLIP tokens + CLS token
563
+ in_tokens = 257
564
+ if "vision_model.embeddings.position_embedding.weight" in image_encoder_state_dict:
565
+ # clip
566
+ in_tokens = int(image_encoder_state_dict["vision_model.embeddings.position_embedding.weight"].shape[0])
567
+
568
+ if self.config.image_encoder_arch.startswith('convnext'):
569
+ in_tokens = 16 * 16
570
+ embedding_dim = self.image_encoder.config.hidden_sizes[-1]
571
+
572
+ is_conv_next = self.config.image_encoder_arch.startswith('convnext')
573
+
574
+ out_tokens = self.config.num_tokens if self.config.num_tokens > 0 else in_tokens
575
+ # ip-adapter-plus
576
+ image_proj_model = ZipperResampler(
577
+ in_size=embedding_dim,
578
+ in_tokens=in_tokens,
579
+ out_size=dim,
580
+ out_tokens=out_tokens,
581
+ hidden_size=embedding_dim,
582
+ hidden_tokens=in_tokens,
583
+ # num_blocks=1 if not is_conv_next else 2,
584
+ num_blocks=1 if not is_conv_next else 2,
585
+ is_conv_input=is_conv_next
586
+ )
587
+ elif adapter_config.type == 'ilora':
588
+ # we apply the clip encodings to the LoRA
589
+ image_proj_model = None
590
+ else:
591
+ raise ValueError(f"unknown adapter type: {adapter_config.type}")
592
+
593
+ # init adapter modules
594
+ attn_procs = {}
595
+ unet_sd = sd.unet.state_dict()
596
+ attn_processor_keys = []
597
+ if is_pixart:
598
+ transformer: Transformer2DModel = sd.unet
599
+ for i, module in transformer.transformer_blocks.named_children():
600
+ attn_processor_keys.append(f"transformer_blocks.{i}.attn1")
601
+
602
+ # cross attention
603
+ attn_processor_keys.append(f"transformer_blocks.{i}.attn2")
604
+ elif is_flux:
605
+ transformer: FluxTransformer2DModel = sd.unet
606
+ for i, module in transformer.transformer_blocks.named_children():
607
+ attn_processor_keys.append(f"transformer_blocks.{i}.attn")
608
+
609
+ # single transformer blocks do not have cross attn, but we will do them anyway
610
+ for i, module in transformer.single_transformer_blocks.named_children():
611
+ attn_processor_keys.append(f"single_transformer_blocks.{i}.attn")
612
+ else:
613
+ attn_processor_keys = list(sd.unet.attn_processors.keys())
614
+
615
+ attn_processor_names = []
616
+
617
+ blocks = []
618
+ transformer_blocks = []
619
+ for name in attn_processor_keys:
620
+ name_split = name.split(".")
621
+ block_name = f"{name_split[0]}.{name_split[1]}"
622
+ transformer_idx = name_split.index("transformer_blocks") if "transformer_blocks" in name_split else -1
623
+ if transformer_idx >= 0:
624
+ transformer_name = ".".join(name_split[:2])
625
+ transformer_name += "." + ".".join(name_split[transformer_idx:transformer_idx + 2])
626
+ if transformer_name not in transformer_blocks:
627
+ transformer_blocks.append(transformer_name)
628
+
629
+
630
+ if block_name not in blocks:
631
+ blocks.append(block_name)
632
+ if is_flux:
633
+ cross_attention_dim = None
634
+ else:
635
+ cross_attention_dim = None if name.endswith("attn1.processor") or name.endswith("attn.1") or name.endswith("attn1") else \
636
+ sd.unet.config['cross_attention_dim']
637
+ if name.startswith("mid_block"):
638
+ hidden_size = sd.unet.config['block_out_channels'][-1]
639
+ elif name.startswith("up_blocks"):
640
+ block_id = int(name[len("up_blocks.")])
641
+ hidden_size = list(reversed(sd.unet.config['block_out_channels']))[block_id]
642
+ elif name.startswith("down_blocks"):
643
+ block_id = int(name[len("down_blocks.")])
644
+ hidden_size = sd.unet.config['block_out_channels'][block_id]
645
+ elif name.startswith("transformer") or name.startswith("single_transformer"):
646
+ if is_flux:
647
+ hidden_size = 3072
648
+ else:
649
+ hidden_size = sd.unet.config['cross_attention_dim']
650
+ else:
651
+ # they didnt have this, but would lead to undefined below
652
+ raise ValueError(f"unknown attn processor name: {name}")
653
+ if cross_attention_dim is None and not is_flux:
654
+ attn_procs[name] = AttnProcessor2_0()
655
+ else:
656
+ layer_name = name.split(".processor")[0]
657
+
658
+ # if quantized, we need to scale the weights
659
+ if f"{layer_name}.to_k.weight._data" in unet_sd and is_flux:
660
+ # is quantized
661
+
662
+ k_weight = torch.randn(hidden_size, hidden_size) * 0.01
663
+ v_weight = torch.randn(hidden_size, hidden_size) * 0.01
664
+ k_weight = k_weight.to(self.sd_ref().torch_dtype)
665
+ v_weight = v_weight.to(self.sd_ref().torch_dtype)
666
+ else:
667
+ k_weight = unet_sd[layer_name + ".to_k.weight"]
668
+ v_weight = unet_sd[layer_name + ".to_v.weight"]
669
+
670
+ weights = {
671
+ "to_k_ip.weight": k_weight,
672
+ "to_v_ip.weight": v_weight
673
+ }
674
+
675
+ if is_flux:
676
+ attn_procs[name] = CustomIPFluxAttnProcessor2_0(
677
+ hidden_size=hidden_size,
678
+ cross_attention_dim=cross_attention_dim,
679
+ scale=1.0,
680
+ num_tokens=self.config.num_tokens,
681
+ adapter=self,
682
+ train_scaler=self.config.train_scaler or self.config.merge_scaler,
683
+ full_token_scaler=False
684
+ )
685
+ else:
686
+ attn_procs[name] = CustomIPAttentionProcessor(
687
+ hidden_size=hidden_size,
688
+ cross_attention_dim=cross_attention_dim,
689
+ scale=1.0,
690
+ num_tokens=self.config.num_tokens,
691
+ adapter=self,
692
+ train_scaler=self.config.train_scaler or self.config.merge_scaler,
693
+ # full_token_scaler=self.config.train_scaler # full token cannot be merged in, only use if training an actual scaler
694
+ full_token_scaler=False
695
+ )
696
+ if self.sd_ref().is_pixart or self.sd_ref().is_flux:
697
+ # pixart is much more sensitive
698
+ weights = {
699
+ "to_k_ip.weight": weights["to_k_ip.weight"] * 0.01,
700
+ "to_v_ip.weight": weights["to_v_ip.weight"] * 0.01,
701
+ }
702
+
703
+ attn_procs[name].load_state_dict(weights, strict=False)
704
+ attn_processor_names.append(name)
705
+ print(f"Attn Processors")
706
+ print(attn_processor_names)
707
+ if self.sd_ref().is_pixart:
708
+ # we have to set them ourselves
709
+ transformer: Transformer2DModel = sd.unet
710
+ for i, module in transformer.transformer_blocks.named_children():
711
+ module.attn1.processor = attn_procs[f"transformer_blocks.{i}.attn1"]
712
+ module.attn2.processor = attn_procs[f"transformer_blocks.{i}.attn2"]
713
+ self.adapter_modules = torch.nn.ModuleList(
714
+ [
715
+ transformer.transformer_blocks[i].attn2.processor for i in
716
+ range(len(transformer.transformer_blocks))
717
+ ])
718
+ elif self.sd_ref().is_flux:
719
+ # we have to set them ourselves
720
+ transformer: FluxTransformer2DModel = sd.unet
721
+ for i, module in transformer.transformer_blocks.named_children():
722
+ module.attn.processor = attn_procs[f"transformer_blocks.{i}.attn"]
723
+
724
+ # do single blocks too even though they dont have cross attn
725
+ for i, module in transformer.single_transformer_blocks.named_children():
726
+ module.attn.processor = attn_procs[f"single_transformer_blocks.{i}.attn"]
727
+
728
+ self.adapter_modules = torch.nn.ModuleList(
729
+ [
730
+ transformer.transformer_blocks[i].attn.processor for i in
731
+ range(len(transformer.transformer_blocks))
732
+ ] + [
733
+ transformer.single_transformer_blocks[i].attn.processor for i in
734
+ range(len(transformer.single_transformer_blocks))
735
+ ]
736
+ )
737
+ else:
738
+ sd.unet.set_attn_processor(attn_procs)
739
+ self.adapter_modules = torch.nn.ModuleList(sd.unet.attn_processors.values())
740
+
741
+ sd.adapter = self
742
+ self.unet_ref: weakref.ref = weakref.ref(sd.unet)
743
+ self.image_proj_model = image_proj_model
744
+ # load the weights if we have some
745
+ if self.config.name_or_path:
746
+ loaded_state_dict = load_ip_adapter_model(
747
+ self.config.name_or_path,
748
+ device='cpu',
749
+ dtype=sd.torch_dtype
750
+ )
751
+ self.load_state_dict(loaded_state_dict)
752
+
753
+ self.set_scale(1.0)
754
+
755
+ if self.config.train_image_encoder:
756
+ self.image_encoder.train()
757
+ self.image_encoder.requires_grad_(True)
758
+
759
+ # premake a unconditional
760
+ zerod = torch.zeros(1, 3, self.input_size, self.input_size, device=self.device, dtype=torch.float16)
761
+ self.unconditional = self.clip_image_processor(
762
+ images=zerod,
763
+ return_tensors="pt",
764
+ do_resize=True,
765
+ do_rescale=False,
766
+ ).pixel_values
767
+
768
+ def to(self, *args, **kwargs):
769
+ super().to(*args, **kwargs)
770
+ self.image_encoder.to(*args, **kwargs)
771
+ self.image_proj_model.to(*args, **kwargs)
772
+ self.adapter_modules.to(*args, **kwargs)
773
+ if self.preprocessor is not None:
774
+ self.preprocessor.to(*args, **kwargs)
775
+ return self
776
+
777
+ # def load_ip_adapter(self, state_dict: Union[OrderedDict, dict]):
778
+ # self.image_proj_model.load_state_dict(state_dict["image_proj"])
779
+ # ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
780
+ # ip_layers.load_state_dict(state_dict["ip_adapter"])
781
+ # if self.config.train_image_encoder and 'image_encoder' in state_dict:
782
+ # self.image_encoder.load_state_dict(state_dict["image_encoder"])
783
+ # if self.preprocessor is not None and 'preprocessor' in state_dict:
784
+ # self.preprocessor.load_state_dict(state_dict["preprocessor"])
785
+
786
+ # def load_state_dict(self, state_dict: Union[OrderedDict, dict]):
787
+ # self.load_ip_adapter(state_dict)
788
+
789
+ def state_dict(self) -> OrderedDict:
790
+ state_dict = OrderedDict()
791
+ if self.config.train_only_image_encoder:
792
+ return self.image_encoder.state_dict()
793
+ if self.config.train_scaler:
794
+ state_dict["ip_scale"] = self.adapter_modules.state_dict()
795
+ # remove items that are not scalers
796
+ for key in list(state_dict["ip_scale"].keys()):
797
+ if not key.endswith("ip_scaler"):
798
+ del state_dict["ip_scale"][key]
799
+ return state_dict
800
+
801
+ state_dict["image_proj"] = self.image_proj_model.state_dict()
802
+ state_dict["ip_adapter"] = self.adapter_modules.state_dict()
803
+ # handle merge scaler training
804
+ if self.config.merge_scaler:
805
+ for key in list(state_dict["ip_adapter"].keys()):
806
+ if key.endswith("ip_scaler"):
807
+ # merge in the scaler so we dont have to save it and it will be compatible with other ip adapters
808
+ scale = state_dict["ip_adapter"][key].clone()
809
+
810
+ key_start = key.split(".")[-2]
811
+ # reshape to (1, 1)
812
+ scale = scale.view(1, 1)
813
+ del state_dict["ip_adapter"][key]
814
+ # find the to_k_ip and to_v_ip keys
815
+ for key2 in list(state_dict["ip_adapter"].keys()):
816
+ if key2.endswith(f"{key_start}.to_k_ip.weight"):
817
+ state_dict["ip_adapter"][key2] = state_dict["ip_adapter"][key2].clone() * scale
818
+ if key2.endswith(f"{key_start}.to_v_ip.weight"):
819
+ state_dict["ip_adapter"][key2] = state_dict["ip_adapter"][key2].clone() * scale
820
+
821
+ if self.config.train_image_encoder:
822
+ state_dict["image_encoder"] = self.image_encoder.state_dict()
823
+ if self.preprocessor is not None:
824
+ state_dict["preprocessor"] = self.preprocessor.state_dict()
825
+ return state_dict
826
+
827
+ def get_scale(self):
828
+ return self.current_scale
829
+
830
+ def set_scale(self, scale):
831
+ self.current_scale = scale
832
+ if not self.sd_ref().is_pixart and not self.sd_ref().is_flux:
833
+ for attn_processor in self.sd_ref().unet.attn_processors.values():
834
+ if isinstance(attn_processor, CustomIPAttentionProcessor):
835
+ attn_processor.scale = scale
836
+
837
+ # @torch.no_grad()
838
+ # def get_clip_image_embeds_from_pil(self, pil_image: Union[Image.Image, List[Image.Image]],
839
+ # drop=False) -> torch.Tensor:
840
+ # # todo: add support for sdxl
841
+ # if isinstance(pil_image, Image.Image):
842
+ # pil_image = [pil_image]
843
+ # clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
844
+ # clip_image = clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
845
+ # if drop:
846
+ # clip_image = clip_image * 0
847
+ # clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
848
+ # return clip_image_embeds
849
+
850
+ def to(self, *args, **kwargs):
851
+ super().to(*args, **kwargs)
852
+ self.image_encoder.to(*args, **kwargs)
853
+ self.image_proj_model.to(*args, **kwargs)
854
+ self.adapter_modules.to(*args, **kwargs)
855
+ if self.preprocessor is not None:
856
+ self.preprocessor.to(*args, **kwargs)
857
+ return self
858
+
859
+ def parse_clip_image_embeds_from_cache(
860
+ self,
861
+ image_embeds_list: List[dict], # has ['last_hidden_state', 'image_embeds', 'penultimate_hidden_states']
862
+ quad_count=4,
863
+ ):
864
+ with torch.no_grad():
865
+ device = self.sd_ref().unet.device
866
+ clip_image_embeds = torch.cat([x[self.config.clip_layer] for x in image_embeds_list], dim=0)
867
+
868
+ if self.config.quad_image:
869
+ # get the outputs of the quat
870
+ chunks = clip_image_embeds.chunk(quad_count, dim=0)
871
+ chunk_sum = torch.zeros_like(chunks[0])
872
+ for chunk in chunks:
873
+ chunk_sum = chunk_sum + chunk
874
+ # get the mean of them
875
+
876
+ clip_image_embeds = chunk_sum / quad_count
877
+
878
+ clip_image_embeds = clip_image_embeds.to(device, dtype=get_torch_dtype(self.sd_ref().dtype)).detach()
879
+ return clip_image_embeds
880
+
881
+ def get_empty_clip_image(self, batch_size: int) -> torch.Tensor:
882
+ with torch.no_grad():
883
+ tensors_0_1 = torch.rand([batch_size, 3, self.input_size, self.input_size], device=self.device)
884
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
885
+ dtype=get_torch_dtype(self.sd_ref().dtype))
886
+ tensors_0_1 = tensors_0_1 * noise_scale
887
+ # tensors_0_1 = tensors_0_1 * 0
888
+ mean = torch.tensor(self.clip_image_processor.image_mean).to(
889
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
890
+ ).detach()
891
+ std = torch.tensor(self.clip_image_processor.image_std).to(
892
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
893
+ ).detach()
894
+ tensors_0_1 = torch.clip((255. * tensors_0_1), 0, 255).round() / 255.0
895
+ clip_image = (tensors_0_1 - mean.view([1, 3, 1, 1])) / std.view([1, 3, 1, 1])
896
+ return clip_image.detach()
897
+
898
+ def get_clip_image_embeds_from_tensors(
899
+ self,
900
+ tensors_0_1: torch.Tensor,
901
+ drop=False,
902
+ is_training=False,
903
+ has_been_preprocessed=False,
904
+ quad_count=4,
905
+ cfg_embed_strength=None, # perform CFG on embeds with unconditional as negative
906
+ ) -> torch.Tensor:
907
+ if self.sd_ref().unet.device != self.device:
908
+ self.to(self.sd_ref().unet.device)
909
+ if self.sd_ref().unet.device != self.image_encoder.device:
910
+ self.to(self.sd_ref().unet.device)
911
+ if not self.config.train:
912
+ is_training = False
913
+ uncond_clip = None
914
+ with torch.no_grad():
915
+ # on training the clip image is created in the dataloader
916
+ if not has_been_preprocessed:
917
+ # tensors should be 0-1
918
+ if tensors_0_1.ndim == 3:
919
+ tensors_0_1 = tensors_0_1.unsqueeze(0)
920
+ # training tensors are 0 - 1
921
+ tensors_0_1 = tensors_0_1.to(self.device, dtype=torch.float16)
922
+
923
+ # if images are out of this range throw error
924
+ if tensors_0_1.min() < -0.3 or tensors_0_1.max() > 1.3:
925
+ raise ValueError("image tensor values must be between 0 and 1. Got min: {}, max: {}".format(
926
+ tensors_0_1.min(), tensors_0_1.max()
927
+ ))
928
+ # unconditional
929
+ if drop:
930
+ if self.clip_noise_zero:
931
+ tensors_0_1 = torch.rand_like(tensors_0_1).detach()
932
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
933
+ dtype=get_torch_dtype(self.sd_ref().dtype))
934
+ tensors_0_1 = tensors_0_1 * noise_scale
935
+ else:
936
+ tensors_0_1 = torch.zeros_like(tensors_0_1).detach()
937
+ # tensors_0_1 = tensors_0_1 * 0
938
+ clip_image = self.clip_image_processor(
939
+ images=tensors_0_1,
940
+ return_tensors="pt",
941
+ do_resize=True,
942
+ do_rescale=False,
943
+ ).pixel_values
944
+ else:
945
+ if drop:
946
+ # scale the noise down
947
+ if self.clip_noise_zero:
948
+ tensors_0_1 = torch.rand_like(tensors_0_1).detach()
949
+ noise_scale = torch.rand([tensors_0_1.shape[0], 1, 1, 1], device=self.device,
950
+ dtype=get_torch_dtype(self.sd_ref().dtype))
951
+ tensors_0_1 = tensors_0_1 * noise_scale
952
+ else:
953
+ tensors_0_1 = torch.zeros_like(tensors_0_1).detach()
954
+ # tensors_0_1 = tensors_0_1 * 0
955
+ mean = torch.tensor(self.clip_image_processor.image_mean).to(
956
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
957
+ ).detach()
958
+ std = torch.tensor(self.clip_image_processor.image_std).to(
959
+ self.device, dtype=get_torch_dtype(self.sd_ref().dtype)
960
+ ).detach()
961
+ tensors_0_1 = torch.clip((255. * tensors_0_1), 0, 255).round() / 255.0
962
+ clip_image = (tensors_0_1 - mean.view([1, 3, 1, 1])) / std.view([1, 3, 1, 1])
963
+
964
+ else:
965
+ clip_image = tensors_0_1
966
+ clip_image = clip_image.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype)).detach()
967
+
968
+ if self.config.quad_image:
969
+ # split the 4x4 grid and stack on batch
970
+ ci1, ci2 = clip_image.chunk(2, dim=2)
971
+ ci1, ci3 = ci1.chunk(2, dim=3)
972
+ ci2, ci4 = ci2.chunk(2, dim=3)
973
+ to_cat = []
974
+ for i, ci in enumerate([ci1, ci2, ci3, ci4]):
975
+ if i < quad_count:
976
+ to_cat.append(ci)
977
+ else:
978
+ break
979
+
980
+ clip_image = torch.cat(to_cat, dim=0).detach()
981
+
982
+ # if drop:
983
+ # clip_image = clip_image * 0
984
+ with torch.set_grad_enabled(is_training):
985
+ if is_training and self.config.train_image_encoder:
986
+ self.image_encoder.train()
987
+ clip_image = clip_image.requires_grad_(True)
988
+ if self.preprocessor is not None:
989
+ clip_image = self.preprocessor(clip_image)
990
+ clip_output = self.image_encoder(
991
+ clip_image,
992
+ output_hidden_states=True
993
+ )
994
+ else:
995
+ self.image_encoder.eval()
996
+ if self.preprocessor is not None:
997
+ clip_image = self.preprocessor(clip_image)
998
+ clip_output = self.image_encoder(
999
+ clip_image, output_hidden_states=True
1000
+ )
1001
+
1002
+ if self.config.clip_layer == 'penultimate_hidden_states':
1003
+ # they skip last layer for ip+
1004
+ # https://github.com/tencent-ailab/IP-Adapter/blob/f4b6742db35ea6d81c7b829a55b0a312c7f5a677/tutorial_train_plus.py#L403C26-L403C26
1005
+ clip_image_embeds = clip_output.hidden_states[-2]
1006
+ elif self.config.clip_layer == 'last_hidden_state':
1007
+ clip_image_embeds = clip_output.hidden_states[-1]
1008
+ else:
1009
+ clip_image_embeds = clip_output.image_embeds
1010
+
1011
+ if self.config.adapter_type == "clip_face":
1012
+ l2_norm = torch.norm(clip_image_embeds, p=2)
1013
+ clip_image_embeds = clip_image_embeds / l2_norm
1014
+
1015
+ if self.config.image_encoder_arch.startswith('convnext'):
1016
+ # flatten the width height layers to make the token space
1017
+ clip_image_embeds = clip_image_embeds.view(clip_image_embeds.size(0), clip_image_embeds.size(1), -1)
1018
+ # rearrange to (batch, tokens, size)
1019
+ clip_image_embeds = clip_image_embeds.permute(0, 2, 1)
1020
+
1021
+ # apply unconditional if doing cfg on embeds
1022
+ with torch.no_grad():
1023
+ if cfg_embed_strength is not None:
1024
+ uncond_clip = self.get_empty_clip_image(tensors_0_1.shape[0]).to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
1025
+ if self.config.quad_image:
1026
+ # split the 4x4 grid and stack on batch
1027
+ ci1, ci2 = uncond_clip.chunk(2, dim=2)
1028
+ ci1, ci3 = ci1.chunk(2, dim=3)
1029
+ ci2, ci4 = ci2.chunk(2, dim=3)
1030
+ to_cat = []
1031
+ for i, ci in enumerate([ci1, ci2, ci3, ci4]):
1032
+ if i < quad_count:
1033
+ to_cat.append(ci)
1034
+ else:
1035
+ break
1036
+
1037
+ uncond_clip = torch.cat(to_cat, dim=0).detach()
1038
+ uncond_clip_output = self.image_encoder(
1039
+ uncond_clip, output_hidden_states=True
1040
+ )
1041
+
1042
+ if self.config.clip_layer == 'penultimate_hidden_states':
1043
+ uncond_clip_output_embeds = uncond_clip_output.hidden_states[-2]
1044
+ elif self.config.clip_layer == 'last_hidden_state':
1045
+ uncond_clip_output_embeds = uncond_clip_output.hidden_states[-1]
1046
+ else:
1047
+ uncond_clip_output_embeds = uncond_clip_output.image_embeds
1048
+ if self.config.adapter_type == "clip_face":
1049
+ l2_norm = torch.norm(uncond_clip_output_embeds, p=2)
1050
+ uncond_clip_output_embeds = uncond_clip_output_embeds / l2_norm
1051
+
1052
+ uncond_clip_output_embeds = uncond_clip_output_embeds.detach()
1053
+
1054
+
1055
+ # apply inverse cfg
1056
+ clip_image_embeds = inverse_classifier_guidance(
1057
+ clip_image_embeds,
1058
+ uncond_clip_output_embeds,
1059
+ cfg_embed_strength
1060
+ )
1061
+
1062
+
1063
+ if self.config.quad_image:
1064
+ # get the outputs of the quat
1065
+ chunks = clip_image_embeds.chunk(quad_count, dim=0)
1066
+ if self.config.train_image_encoder and is_training:
1067
+ # perform a loss across all chunks this will teach the vision encoder to
1068
+ # identify similarities in our pairs of images and ignore things that do not make them similar
1069
+ num_losses = 0
1070
+ total_loss = None
1071
+ for chunk in chunks:
1072
+ for chunk2 in chunks:
1073
+ if chunk is not chunk2:
1074
+ loss = F.mse_loss(chunk, chunk2)
1075
+ if total_loss is None:
1076
+ total_loss = loss
1077
+ else:
1078
+ total_loss = total_loss + loss
1079
+ num_losses += 1
1080
+ if total_loss is not None:
1081
+ total_loss = total_loss / num_losses
1082
+ total_loss = total_loss * 1e-2
1083
+ if self.additional_loss is not None:
1084
+ total_loss = total_loss + self.additional_loss
1085
+ self.additional_loss = total_loss
1086
+
1087
+ chunk_sum = torch.zeros_like(chunks[0])
1088
+ for chunk in chunks:
1089
+ chunk_sum = chunk_sum + chunk
1090
+ # get the mean of them
1091
+
1092
+ clip_image_embeds = chunk_sum / quad_count
1093
+
1094
+ if not is_training or not self.config.train_image_encoder:
1095
+ clip_image_embeds = clip_image_embeds.detach()
1096
+
1097
+ return clip_image_embeds
1098
+
1099
+ # use drop for prompt dropout, or negatives
1100
+ def forward(self, embeddings: PromptEmbeds, clip_image_embeds: torch.Tensor, is_unconditional=False) -> PromptEmbeds:
1101
+ clip_image_embeds = clip_image_embeds.to(self.device, dtype=get_torch_dtype(self.sd_ref().dtype))
1102
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
1103
+ if self.sd_ref().is_flux:
1104
+ # do not attach to text embeds for flux, we will save and grab them as it messes
1105
+ # with the RoPE to have them in the same tensor
1106
+ if is_unconditional:
1107
+ self.last_unconditional = image_prompt_embeds
1108
+ else:
1109
+ self.last_conditional = image_prompt_embeds
1110
+ else:
1111
+ embeddings.text_embeds = torch.cat([embeddings.text_embeds, image_prompt_embeds], dim=1)
1112
+ return embeddings
1113
+
1114
+ def train(self: T, mode: bool = True) -> T:
1115
+ if self.config.train_image_encoder:
1116
+ self.image_encoder.train(mode)
1117
+ if not self.config.train_only_image_encoder:
1118
+ for attn_processor in self.adapter_modules:
1119
+ attn_processor.train(mode)
1120
+ if self.image_proj_model is not None:
1121
+ self.image_proj_model.train(mode)
1122
+ return super().train(mode)
1123
+
1124
+ def get_parameter_groups(self, adapter_lr):
1125
+ param_groups = []
1126
+ # when training just scaler, we do not train anything else
1127
+ if not self.config.train_scaler:
1128
+ param_groups.append({
1129
+ "params": list(self.get_non_scaler_parameters()),
1130
+ "lr": adapter_lr,
1131
+ })
1132
+ if self.config.train_scaler or self.config.merge_scaler:
1133
+ scaler_lr = adapter_lr if self.config.scaler_lr is None else self.config.scaler_lr
1134
+ param_groups.append({
1135
+ "params": list(self.get_scaler_parameters()),
1136
+ "lr": scaler_lr,
1137
+ })
1138
+ return param_groups
1139
+
1140
+ def get_scaler_parameters(self):
1141
+ # only get the scalera from the adapter modules
1142
+ for attn_processor in self.adapter_modules:
1143
+ # only get the scaler
1144
+ # check if it has ip_scaler attribute
1145
+ if hasattr(attn_processor, "ip_scaler"):
1146
+ scaler_param = attn_processor.ip_scaler
1147
+ yield scaler_param
1148
+
1149
+ def get_non_scaler_parameters(self, recurse: bool = True) -> Iterator[Parameter]:
1150
+ if self.config.train_only_image_encoder:
1151
+ if self.config.train_only_image_encoder_positional_embedding:
1152
+ yield from self.image_encoder.vision_model.embeddings.position_embedding.parameters(recurse)
1153
+ else:
1154
+ yield from self.image_encoder.parameters(recurse)
1155
+ return
1156
+ if self.config.train_scaler:
1157
+ # no params
1158
+ return
1159
+
1160
+ for attn_processor in self.adapter_modules:
1161
+ if self.config.train_scaler or self.config.merge_scaler:
1162
+ # todo remove scaler
1163
+ if hasattr(attn_processor, "to_k_ip"):
1164
+ # yield the linear layer
1165
+ yield from attn_processor.to_k_ip.parameters(recurse)
1166
+ if hasattr(attn_processor, "to_v_ip"):
1167
+ # yield the linear layer
1168
+ yield from attn_processor.to_v_ip.parameters(recurse)
1169
+ else:
1170
+ yield from attn_processor.parameters(recurse)
1171
+ yield from self.image_proj_model.parameters(recurse)
1172
+ if self.config.train_image_encoder:
1173
+ yield from self.image_encoder.parameters(recurse)
1174
+ if self.preprocessor is not None:
1175
+ yield from self.preprocessor.parameters(recurse)
1176
+
1177
+ def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
1178
+ yield from self.get_non_scaler_parameters(recurse)
1179
+ if self.config.train_scaler or self.config.merge_scaler:
1180
+ yield from self.get_scaler_parameters()
1181
+
1182
+ def merge_in_weights(self, state_dict: Mapping[str, Any]):
1183
+ # merge in img_proj weights
1184
+ current_img_proj_state_dict = self.image_proj_model.state_dict()
1185
+ for key, value in state_dict["image_proj"].items():
1186
+ if key in current_img_proj_state_dict:
1187
+ current_shape = current_img_proj_state_dict[key].shape
1188
+ new_shape = value.shape
1189
+ if current_shape != new_shape:
1190
+ try:
1191
+ # merge in what we can and leave the other values as they are
1192
+ if len(current_shape) == 1:
1193
+ current_img_proj_state_dict[key][:new_shape[0]] = value
1194
+ elif len(current_shape) == 2:
1195
+ current_img_proj_state_dict[key][:new_shape[0], :new_shape[1]] = value
1196
+ elif len(current_shape) == 3:
1197
+ current_img_proj_state_dict[key][:new_shape[0], :new_shape[1], :new_shape[2]] = value
1198
+ elif len(current_shape) == 4:
1199
+ current_img_proj_state_dict[key][:new_shape[0], :new_shape[1], :new_shape[2],
1200
+ :new_shape[3]] = value
1201
+ else:
1202
+ raise ValueError(f"unknown shape: {current_shape}")
1203
+ except RuntimeError as e:
1204
+ print(e)
1205
+ print(
1206
+ f"could not merge in {key}: {list(current_shape)} <<< {list(new_shape)}. Trying other way")
1207
+
1208
+ if len(current_shape) == 1:
1209
+ current_img_proj_state_dict[key][:current_shape[0]] = value[:current_shape[0]]
1210
+ elif len(current_shape) == 2:
1211
+ current_img_proj_state_dict[key][:current_shape[0], :current_shape[1]] = value[
1212
+ :current_shape[0],
1213
+ :current_shape[1]]
1214
+ elif len(current_shape) == 3:
1215
+ current_img_proj_state_dict[key][:current_shape[0], :current_shape[1],
1216
+ :current_shape[2]] = value[:current_shape[0], :current_shape[1], :current_shape[2]]
1217
+ elif len(current_shape) == 4:
1218
+ current_img_proj_state_dict[key][:current_shape[0], :current_shape[1], :current_shape[2],
1219
+ :current_shape[3]] = value[:current_shape[0], :current_shape[1], :current_shape[2],
1220
+ :current_shape[3]]
1221
+ else:
1222
+ raise ValueError(f"unknown shape: {current_shape}")
1223
+ print(f"Force merged in {key}: {list(current_shape)} <<< {list(new_shape)}")
1224
+ else:
1225
+ current_img_proj_state_dict[key] = value
1226
+ self.image_proj_model.load_state_dict(current_img_proj_state_dict)
1227
+
1228
+ # merge in ip adapter weights
1229
+ current_ip_adapter_state_dict = self.adapter_modules.state_dict()
1230
+ for key, value in state_dict["ip_adapter"].items():
1231
+ if key in current_ip_adapter_state_dict:
1232
+ current_shape = current_ip_adapter_state_dict[key].shape
1233
+ new_shape = value.shape
1234
+ if current_shape != new_shape:
1235
+ try:
1236
+ # merge in what we can and leave the other values as they are
1237
+ if len(current_shape) == 1:
1238
+ current_ip_adapter_state_dict[key][:new_shape[0]] = value
1239
+ elif len(current_shape) == 2:
1240
+ current_ip_adapter_state_dict[key][:new_shape[0], :new_shape[1]] = value
1241
+ elif len(current_shape) == 3:
1242
+ current_ip_adapter_state_dict[key][:new_shape[0], :new_shape[1], :new_shape[2]] = value
1243
+ elif len(current_shape) == 4:
1244
+ current_ip_adapter_state_dict[key][:new_shape[0], :new_shape[1], :new_shape[2],
1245
+ :new_shape[3]] = value
1246
+ else:
1247
+ raise ValueError(f"unknown shape: {current_shape}")
1248
+ print(f"Force merged in {key}: {list(current_shape)} <<< {list(new_shape)}")
1249
+ except RuntimeError as e:
1250
+ print(e)
1251
+ print(
1252
+ f"could not merge in {key}: {list(current_shape)} <<< {list(new_shape)}. Trying other way")
1253
+
1254
+ if (len(current_shape) == 1):
1255
+ current_ip_adapter_state_dict[key][:current_shape[0]] = value[:current_shape[0]]
1256
+ elif (len(current_shape) == 2):
1257
+ current_ip_adapter_state_dict[key][:current_shape[0], :current_shape[1]] = value[
1258
+ :current_shape[
1259
+ 0],
1260
+ :current_shape[
1261
+ 1]]
1262
+ elif (len(current_shape) == 3):
1263
+ current_ip_adapter_state_dict[key][:current_shape[0], :current_shape[1],
1264
+ :current_shape[2]] = value[:current_shape[0], :current_shape[1], :current_shape[2]]
1265
+ elif (len(current_shape) == 4):
1266
+ current_ip_adapter_state_dict[key][:current_shape[0], :current_shape[1], :current_shape[2],
1267
+ :current_shape[3]] = value[:current_shape[0], :current_shape[1], :current_shape[2],
1268
+ :current_shape[3]]
1269
+ else:
1270
+ raise ValueError(f"unknown shape: {current_shape}")
1271
+ print(f"Force merged in {key}: {list(current_shape)} <<< {list(new_shape)}")
1272
+
1273
+ else:
1274
+ current_ip_adapter_state_dict[key] = value
1275
+ self.adapter_modules.load_state_dict(current_ip_adapter_state_dict)
1276
+
1277
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
1278
+ strict = False
1279
+ if self.config.train_scaler and 'ip_scale' in state_dict:
1280
+ self.adapter_modules.load_state_dict(state_dict["ip_scale"], strict=False)
1281
+ if 'ip_adapter' in state_dict:
1282
+ try:
1283
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=strict)
1284
+ self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=strict)
1285
+ except Exception as e:
1286
+ print(e)
1287
+ print("could not load ip adapter weights, trying to merge in weights")
1288
+ self.merge_in_weights(state_dict)
1289
+ if self.config.train_image_encoder and 'image_encoder' in state_dict:
1290
+ self.image_encoder.load_state_dict(state_dict["image_encoder"], strict=strict)
1291
+ if self.preprocessor is not None and 'preprocessor' in state_dict:
1292
+ self.preprocessor.load_state_dict(state_dict["preprocessor"], strict=strict)
1293
+
1294
+ if self.config.train_only_image_encoder and 'ip_adapter' not in state_dict:
1295
+ # we are loading pure clip weights.
1296
+ self.image_encoder.load_state_dict(state_dict, strict=strict)
1297
+
1298
+ def enable_gradient_checkpointing(self):
1299
+ if hasattr(self.image_encoder, "enable_gradient_checkpointing"):
1300
+ self.image_encoder.enable_gradient_checkpointing()
1301
+ elif hasattr(self.image_encoder, 'gradient_checkpointing'):
1302
+ self.image_encoder.gradient_checkpointing = True
toolkit/job.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, OrderedDict
2
+
3
+ from toolkit.config import get_config
4
+
5
+
6
+ def get_job(
7
+ config_path: Union[str, dict, OrderedDict],
8
+ name=None
9
+ ):
10
+ config = get_config(config_path, name)
11
+ if not config['job']:
12
+ raise ValueError('config file is invalid. Missing "job" key')
13
+
14
+ job = config['job']
15
+ if job == 'extract':
16
+ from jobs import ExtractJob
17
+ return ExtractJob(config)
18
+ if job == 'train':
19
+ from jobs import TrainJob
20
+ return TrainJob(config)
21
+ if job == 'mod':
22
+ from jobs import ModJob
23
+ return ModJob(config)
24
+ if job == 'generate':
25
+ from jobs import GenerateJob
26
+ return GenerateJob(config)
27
+ if job == 'extension':
28
+ from jobs import ExtensionJob
29
+ return ExtensionJob(config)
30
+
31
+ # elif job == 'train':
32
+ # from jobs import TrainJob
33
+ # return TrainJob(config)
34
+ else:
35
+ raise ValueError(f'Unknown job type {job}')
36
+
37
+
38
+ def run_job(
39
+ config: Union[str, dict, OrderedDict],
40
+ name=None
41
+ ):
42
+ job = get_job(config, name)
43
+ job.run()
44
+ job.cleanup()
toolkit/kohya_lora.py ADDED
@@ -0,0 +1,1221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA network module
2
+ # reference:
3
+ # https://github.com/microsoft/LoRA/blob/main/loralib/layers.py
4
+ # https://github.com/cloneofsimo/lora/blob/master/lora_diffusion/lora.py
5
+
6
+ # taken from kohya lora sd scripts
7
+
8
+ import math
9
+ import os
10
+ from typing import Dict, List, Optional, Tuple, Type, Union
11
+ from diffusers import AutoencoderKL
12
+ from transformers import CLIPTextModel
13
+ import numpy as np
14
+ import torch
15
+ import re
16
+
17
+
18
+ RE_UPDOWN = re.compile(r"(up|down)_blocks_(\d+)_(resnets|upsamplers|downsamplers|attentions)_(\d+)_")
19
+
20
+
21
+ class LoRAModule(torch.nn.Module):
22
+ """
23
+ replaces forward method of the original Linear, instead of replacing the original Linear module.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ lora_name,
29
+ org_module: torch.nn.Module,
30
+ multiplier=1.0,
31
+ lora_dim=4,
32
+ alpha=1,
33
+ dropout=None,
34
+ rank_dropout=None,
35
+ module_dropout=None,
36
+ ):
37
+ """if alpha == 0 or None, alpha is rank (no scaling)."""
38
+ super().__init__()
39
+ self.lora_name = lora_name
40
+
41
+ if org_module.__class__.__name__ == "Conv2d":
42
+ in_dim = org_module.in_channels
43
+ out_dim = org_module.out_channels
44
+ else:
45
+ in_dim = org_module.in_features
46
+ out_dim = org_module.out_features
47
+
48
+ # if limit_rank:
49
+ # self.lora_dim = min(lora_dim, in_dim, out_dim)
50
+ # if self.lora_dim != lora_dim:
51
+ # print(f"{lora_name} dim (rank) is changed to: {self.lora_dim}")
52
+ # else:
53
+ self.lora_dim = lora_dim
54
+
55
+ if org_module.__class__.__name__ == "Conv2d":
56
+ kernel_size = org_module.kernel_size
57
+ stride = org_module.stride
58
+ padding = org_module.padding
59
+ self.lora_down = torch.nn.Conv2d(in_dim, self.lora_dim, kernel_size, stride, padding, bias=False)
60
+ self.lora_up = torch.nn.Conv2d(self.lora_dim, out_dim, (1, 1), (1, 1), bias=False)
61
+ else:
62
+ self.lora_down = torch.nn.Linear(in_dim, self.lora_dim, bias=False)
63
+ self.lora_up = torch.nn.Linear(self.lora_dim, out_dim, bias=False)
64
+
65
+ if type(alpha) == torch.Tensor:
66
+ alpha = alpha.detach().float().numpy() # without casting, bf16 causes error
67
+ alpha = self.lora_dim if alpha is None or alpha == 0 else alpha
68
+ self.scale = alpha / self.lora_dim
69
+ self.register_buffer("alpha", torch.tensor(alpha)) # 定数として扱える
70
+
71
+ # same as microsoft's
72
+ torch.nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))
73
+ torch.nn.init.zeros_(self.lora_up.weight)
74
+
75
+ self.multiplier = multiplier
76
+ self.org_module = org_module # remove in applying
77
+ self.dropout = dropout
78
+ self.rank_dropout = rank_dropout
79
+ self.module_dropout = module_dropout
80
+
81
+ def apply_to(self):
82
+ self.org_forward = self.org_module.forward
83
+ self.org_module.forward = self.forward
84
+ del self.org_module
85
+
86
+ def forward(self, x):
87
+ org_forwarded = self.org_forward(x)
88
+
89
+ # module dropout
90
+ if self.module_dropout is not None and self.training:
91
+ if torch.rand(1) < self.module_dropout:
92
+ return org_forwarded
93
+
94
+ lx = self.lora_down(x)
95
+
96
+ # normal dropout
97
+ if self.dropout is not None and self.training:
98
+ lx = torch.nn.functional.dropout(lx, p=self.dropout)
99
+
100
+ # rank dropout
101
+ if self.rank_dropout is not None and self.training:
102
+ mask = torch.rand((lx.size(0), self.lora_dim), device=lx.device) > self.rank_dropout
103
+ if len(lx.size()) == 3:
104
+ mask = mask.unsqueeze(1) # for Text Encoder
105
+ elif len(lx.size()) == 4:
106
+ mask = mask.unsqueeze(-1).unsqueeze(-1) # for Conv2d
107
+ lx = lx * mask
108
+
109
+ # scaling for rank dropout: treat as if the rank is changed
110
+ # maskから計算することも考えられるが、augmentation的な効果を期待してrank_dropoutを用いる
111
+ scale = self.scale * (1.0 / (1.0 - self.rank_dropout)) # redundant for readability
112
+ else:
113
+ scale = self.scale
114
+
115
+ lx = self.lora_up(lx)
116
+
117
+ return org_forwarded + lx * self.multiplier * scale
118
+
119
+
120
+ class LoRAInfModule(LoRAModule):
121
+ def __init__(
122
+ self,
123
+ lora_name,
124
+ org_module: torch.nn.Module,
125
+ multiplier=1.0,
126
+ lora_dim=4,
127
+ alpha=1,
128
+ **kwargs,
129
+ ):
130
+ # no dropout for inference
131
+ super().__init__(lora_name, org_module, multiplier, lora_dim, alpha)
132
+
133
+ self.org_module_ref = [org_module] # 後から参照できるように
134
+ self.enabled = True
135
+
136
+ # check regional or not by lora_name
137
+ self.text_encoder = False
138
+ if lora_name.startswith("lora_te_"):
139
+ self.regional = False
140
+ self.use_sub_prompt = True
141
+ self.text_encoder = True
142
+ elif "attn2_to_k" in lora_name or "attn2_to_v" in lora_name:
143
+ self.regional = False
144
+ self.use_sub_prompt = True
145
+ elif "time_emb" in lora_name:
146
+ self.regional = False
147
+ self.use_sub_prompt = False
148
+ else:
149
+ self.regional = True
150
+ self.use_sub_prompt = False
151
+
152
+ self.network: LoRANetwork = None
153
+
154
+ def set_network(self, network):
155
+ self.network = network
156
+
157
+ # freezeしてマージする
158
+ def merge_to(self, sd, dtype, device):
159
+ # get up/down weight
160
+ up_weight = sd["lora_up.weight"].to(torch.float).to(device)
161
+ down_weight = sd["lora_down.weight"].to(torch.float).to(device)
162
+
163
+ # extract weight from org_module
164
+ org_sd = self.org_module.state_dict()
165
+ weight = org_sd["weight"].to(torch.float)
166
+
167
+ # merge weight
168
+ if len(weight.size()) == 2:
169
+ # linear
170
+ weight = weight + self.multiplier * (up_weight @ down_weight) * self.scale
171
+ elif down_weight.size()[2:4] == (1, 1):
172
+ # conv2d 1x1
173
+ weight = (
174
+ weight
175
+ + self.multiplier
176
+ * (up_weight.squeeze(3).squeeze(2) @ down_weight.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)
177
+ * self.scale
178
+ )
179
+ else:
180
+ # conv2d 3x3
181
+ conved = torch.nn.functional.conv2d(down_weight.permute(1, 0, 2, 3), up_weight).permute(1, 0, 2, 3)
182
+ # print(conved.size(), weight.size(), module.stride, module.padding)
183
+ weight = weight + self.multiplier * conved * self.scale
184
+
185
+ # set weight to org_module
186
+ org_sd["weight"] = weight.to(dtype)
187
+ self.org_module.load_state_dict(org_sd)
188
+
189
+ # 復元できるマージのため、このモジュールのweightを返す
190
+ def get_weight(self, multiplier=None):
191
+ if multiplier is None:
192
+ multiplier = self.multiplier
193
+
194
+ # get up/down weight from module
195
+ up_weight = self.lora_up.weight.to(torch.float)
196
+ down_weight = self.lora_down.weight.to(torch.float)
197
+
198
+ # pre-calculated weight
199
+ if len(down_weight.size()) == 2:
200
+ # linear
201
+ weight = self.multiplier * (up_weight @ down_weight) * self.scale
202
+ elif down_weight.size()[2:4] == (1, 1):
203
+ # conv2d 1x1
204
+ weight = (
205
+ self.multiplier
206
+ * (up_weight.squeeze(3).squeeze(2) @ down_weight.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)
207
+ * self.scale
208
+ )
209
+ else:
210
+ # conv2d 3x3
211
+ conved = torch.nn.functional.conv2d(down_weight.permute(1, 0, 2, 3), up_weight).permute(1, 0, 2, 3)
212
+ weight = self.multiplier * conved * self.scale
213
+
214
+ return weight
215
+
216
+ def set_region(self, region):
217
+ self.region = region
218
+ self.region_mask = None
219
+
220
+ def default_forward(self, x):
221
+ # print("default_forward", self.lora_name, x.size())
222
+ return self.org_forward(x) + self.lora_up(self.lora_down(x)) * self.multiplier * self.scale
223
+
224
+ def forward(self, x):
225
+ if not self.enabled:
226
+ return self.org_forward(x)
227
+
228
+ if self.network is None or self.network.sub_prompt_index is None:
229
+ return self.default_forward(x)
230
+ if not self.regional and not self.use_sub_prompt:
231
+ return self.default_forward(x)
232
+
233
+ if self.regional:
234
+ return self.regional_forward(x)
235
+ else:
236
+ return self.sub_prompt_forward(x)
237
+
238
+ def get_mask_for_x(self, x):
239
+ # calculate size from shape of x
240
+ if len(x.size()) == 4:
241
+ h, w = x.size()[2:4]
242
+ area = h * w
243
+ else:
244
+ area = x.size()[1]
245
+
246
+ mask = self.network.mask_dic[area]
247
+ if mask is None:
248
+ raise ValueError(f"mask is None for resolution {area}")
249
+ if len(x.size()) != 4:
250
+ mask = torch.reshape(mask, (1, -1, 1))
251
+ return mask
252
+
253
+ def regional_forward(self, x):
254
+ if "attn2_to_out" in self.lora_name:
255
+ return self.to_out_forward(x)
256
+
257
+ if self.network.mask_dic is None: # sub_prompt_index >= 3
258
+ return self.default_forward(x)
259
+
260
+ # apply mask for LoRA result
261
+ lx = self.lora_up(self.lora_down(x)) * self.multiplier * self.scale
262
+ mask = self.get_mask_for_x(lx)
263
+ # print("regional", self.lora_name, self.network.sub_prompt_index, lx.size(), mask.size())
264
+ lx = lx * mask
265
+
266
+ x = self.org_forward(x)
267
+ x = x + lx
268
+
269
+ if "attn2_to_q" in self.lora_name and self.network.is_last_network:
270
+ x = self.postp_to_q(x)
271
+
272
+ return x
273
+
274
+ def postp_to_q(self, x):
275
+ # repeat x to num_sub_prompts
276
+ has_real_uncond = x.size()[0] // self.network.batch_size == 3
277
+ qc = self.network.batch_size # uncond
278
+ qc += self.network.batch_size * self.network.num_sub_prompts # cond
279
+ if has_real_uncond:
280
+ qc += self.network.batch_size # real_uncond
281
+
282
+ query = torch.zeros((qc, x.size()[1], x.size()[2]), device=x.device, dtype=x.dtype)
283
+ query[: self.network.batch_size] = x[: self.network.batch_size]
284
+
285
+ for i in range(self.network.batch_size):
286
+ qi = self.network.batch_size + i * self.network.num_sub_prompts
287
+ query[qi : qi + self.network.num_sub_prompts] = x[self.network.batch_size + i]
288
+
289
+ if has_real_uncond:
290
+ query[-self.network.batch_size :] = x[-self.network.batch_size :]
291
+
292
+ # print("postp_to_q", self.lora_name, x.size(), query.size(), self.network.num_sub_prompts)
293
+ return query
294
+
295
+ def sub_prompt_forward(self, x):
296
+ if x.size()[0] == self.network.batch_size: # if uncond in text_encoder, do not apply LoRA
297
+ return self.org_forward(x)
298
+
299
+ emb_idx = self.network.sub_prompt_index
300
+ if not self.text_encoder:
301
+ emb_idx += self.network.batch_size
302
+
303
+ # apply sub prompt of X
304
+ lx = x[emb_idx :: self.network.num_sub_prompts]
305
+ lx = self.lora_up(self.lora_down(lx)) * self.multiplier * self.scale
306
+
307
+ # print("sub_prompt_forward", self.lora_name, x.size(), lx.size(), emb_idx)
308
+
309
+ x = self.org_forward(x)
310
+ x[emb_idx :: self.network.num_sub_prompts] += lx
311
+
312
+ return x
313
+
314
+ def to_out_forward(self, x):
315
+ # print("to_out_forward", self.lora_name, x.size(), self.network.is_last_network)
316
+
317
+ if self.network.is_last_network:
318
+ masks = [None] * self.network.num_sub_prompts
319
+ self.network.shared[self.lora_name] = (None, masks)
320
+ else:
321
+ lx, masks = self.network.shared[self.lora_name]
322
+
323
+ # call own LoRA
324
+ x1 = x[self.network.batch_size + self.network.sub_prompt_index :: self.network.num_sub_prompts]
325
+ lx1 = self.lora_up(self.lora_down(x1)) * self.multiplier * self.scale
326
+
327
+ if self.network.is_last_network:
328
+ lx = torch.zeros(
329
+ (self.network.num_sub_prompts * self.network.batch_size, *lx1.size()[1:]), device=lx1.device, dtype=lx1.dtype
330
+ )
331
+ self.network.shared[self.lora_name] = (lx, masks)
332
+
333
+ # print("to_out_forward", lx.size(), lx1.size(), self.network.sub_prompt_index, self.network.num_sub_prompts)
334
+ lx[self.network.sub_prompt_index :: self.network.num_sub_prompts] += lx1
335
+ masks[self.network.sub_prompt_index] = self.get_mask_for_x(lx1)
336
+
337
+ # if not last network, return x and masks
338
+ x = self.org_forward(x)
339
+ if not self.network.is_last_network:
340
+ return x
341
+
342
+ lx, masks = self.network.shared.pop(self.lora_name)
343
+
344
+ # if last network, combine separated x with mask weighted sum
345
+ has_real_uncond = x.size()[0] // self.network.batch_size == self.network.num_sub_prompts + 2
346
+
347
+ out = torch.zeros((self.network.batch_size * (3 if has_real_uncond else 2), *x.size()[1:]), device=x.device, dtype=x.dtype)
348
+ out[: self.network.batch_size] = x[: self.network.batch_size] # uncond
349
+ if has_real_uncond:
350
+ out[-self.network.batch_size :] = x[-self.network.batch_size :] # real_uncond
351
+
352
+ # print("to_out_forward", self.lora_name, self.network.sub_prompt_index, self.network.num_sub_prompts)
353
+ # for i in range(len(masks)):
354
+ # if masks[i] is None:
355
+ # masks[i] = torch.zeros_like(masks[-1])
356
+
357
+ mask = torch.cat(masks)
358
+ mask_sum = torch.sum(mask, dim=0) + 1e-4
359
+ for i in range(self.network.batch_size):
360
+ # 1枚の画像ごとに処理する
361
+ lx1 = lx[i * self.network.num_sub_prompts : (i + 1) * self.network.num_sub_prompts]
362
+ lx1 = lx1 * mask
363
+ lx1 = torch.sum(lx1, dim=0)
364
+
365
+ xi = self.network.batch_size + i * self.network.num_sub_prompts
366
+ x1 = x[xi : xi + self.network.num_sub_prompts]
367
+ x1 = x1 * mask
368
+ x1 = torch.sum(x1, dim=0)
369
+ x1 = x1 / mask_sum
370
+
371
+ x1 = x1 + lx1
372
+ out[self.network.batch_size + i] = x1
373
+
374
+ # print("to_out_forward", x.size(), out.size(), has_real_uncond)
375
+ return out
376
+
377
+
378
+ def parse_block_lr_kwargs(nw_kwargs):
379
+ down_lr_weight = nw_kwargs.get("down_lr_weight", None)
380
+ mid_lr_weight = nw_kwargs.get("mid_lr_weight", None)
381
+ up_lr_weight = nw_kwargs.get("up_lr_weight", None)
382
+
383
+ # 以上のいずれにも設定がない場合は無効としてNoneを返す
384
+ if down_lr_weight is None and mid_lr_weight is None and up_lr_weight is None:
385
+ return None, None, None
386
+
387
+ # extract learning rate weight for each block
388
+ if down_lr_weight is not None:
389
+ # if some parameters are not set, use zero
390
+ if "," in down_lr_weight:
391
+ down_lr_weight = [(float(s) if s else 0.0) for s in down_lr_weight.split(",")]
392
+
393
+ if mid_lr_weight is not None:
394
+ mid_lr_weight = float(mid_lr_weight)
395
+
396
+ if up_lr_weight is not None:
397
+ if "," in up_lr_weight:
398
+ up_lr_weight = [(float(s) if s else 0.0) for s in up_lr_weight.split(",")]
399
+
400
+ down_lr_weight, mid_lr_weight, up_lr_weight = get_block_lr_weight(
401
+ down_lr_weight, mid_lr_weight, up_lr_weight, float(nw_kwargs.get("block_lr_zero_threshold", 0.0))
402
+ )
403
+
404
+ return down_lr_weight, mid_lr_weight, up_lr_weight
405
+
406
+
407
+ def create_network(
408
+ multiplier: float,
409
+ network_dim: Optional[int],
410
+ network_alpha: Optional[float],
411
+ vae: AutoencoderKL,
412
+ text_encoder: Union[CLIPTextModel, List[CLIPTextModel]],
413
+ unet,
414
+ neuron_dropout: Optional[float] = None,
415
+ **kwargs,
416
+ ):
417
+ if network_dim is None:
418
+ network_dim = 4 # default
419
+ if network_alpha is None:
420
+ network_alpha = 1.0
421
+
422
+ # extract dim/alpha for conv2d, and block dim
423
+ conv_dim = kwargs.get("conv_dim", None)
424
+ conv_alpha = kwargs.get("conv_alpha", None)
425
+ if conv_dim is not None:
426
+ conv_dim = int(conv_dim)
427
+ if conv_alpha is None:
428
+ conv_alpha = 1.0
429
+ else:
430
+ conv_alpha = float(conv_alpha)
431
+
432
+ # block dim/alpha/lr
433
+ block_dims = kwargs.get("block_dims", None)
434
+ down_lr_weight, mid_lr_weight, up_lr_weight = parse_block_lr_kwargs(kwargs)
435
+
436
+ # 以上のいずれかに指定があればblockごとのdim(rank)を有効にする
437
+ if block_dims is not None or down_lr_weight is not None or mid_lr_weight is not None or up_lr_weight is not None:
438
+ block_alphas = kwargs.get("block_alphas", None)
439
+ conv_block_dims = kwargs.get("conv_block_dims", None)
440
+ conv_block_alphas = kwargs.get("conv_block_alphas", None)
441
+
442
+ block_dims, block_alphas, conv_block_dims, conv_block_alphas = get_block_dims_and_alphas(
443
+ block_dims, block_alphas, network_dim, network_alpha, conv_block_dims, conv_block_alphas, conv_dim, conv_alpha
444
+ )
445
+
446
+ # remove block dim/alpha without learning rate
447
+ block_dims, block_alphas, conv_block_dims, conv_block_alphas = remove_block_dims_and_alphas(
448
+ block_dims, block_alphas, conv_block_dims, conv_block_alphas, down_lr_weight, mid_lr_weight, up_lr_weight
449
+ )
450
+
451
+ else:
452
+ block_alphas = None
453
+ conv_block_dims = None
454
+ conv_block_alphas = None
455
+
456
+ # rank/module dropout
457
+ rank_dropout = kwargs.get("rank_dropout", None)
458
+ if rank_dropout is not None:
459
+ rank_dropout = float(rank_dropout)
460
+ module_dropout = kwargs.get("module_dropout", None)
461
+ if module_dropout is not None:
462
+ module_dropout = float(module_dropout)
463
+
464
+ # すごく引数が多いな ( ^ω^)・・・
465
+ network = LoRANetwork(
466
+ text_encoder,
467
+ unet,
468
+ multiplier=multiplier,
469
+ lora_dim=network_dim,
470
+ alpha=network_alpha,
471
+ dropout=neuron_dropout,
472
+ rank_dropout=rank_dropout,
473
+ module_dropout=module_dropout,
474
+ conv_lora_dim=conv_dim,
475
+ conv_alpha=conv_alpha,
476
+ block_dims=block_dims,
477
+ block_alphas=block_alphas,
478
+ conv_block_dims=conv_block_dims,
479
+ conv_block_alphas=conv_block_alphas,
480
+ varbose=True,
481
+ )
482
+
483
+ if up_lr_weight is not None or mid_lr_weight is not None or down_lr_weight is not None:
484
+ network.set_block_lr_weight(up_lr_weight, mid_lr_weight, down_lr_weight)
485
+
486
+ return network
487
+
488
+
489
+ # このメソッドは外部から呼び出される可能性を考慮しておく
490
+ # network_dim, network_alpha にはデフォルト値が入っている。
491
+ # block_dims, block_alphas は両方ともNoneまたは両方とも値が入っている
492
+ # conv_dim, conv_alpha は両方ともNoneまたは両方とも値が入っている
493
+ def get_block_dims_and_alphas(
494
+ block_dims, block_alphas, network_dim, network_alpha, conv_block_dims, conv_block_alphas, conv_dim, conv_alpha
495
+ ):
496
+ num_total_blocks = LoRANetwork.NUM_OF_BLOCKS * 2 + 1
497
+
498
+ def parse_ints(s):
499
+ return [int(i) for i in s.split(",")]
500
+
501
+ def parse_floats(s):
502
+ return [float(i) for i in s.split(",")]
503
+
504
+ # block_dimsとblock_alphasをパースする。必ず値が入る
505
+ if block_dims is not None:
506
+ block_dims = parse_ints(block_dims)
507
+ assert (
508
+ len(block_dims) == num_total_blocks
509
+ ), f"block_dims must have {num_total_blocks} elements / block_dimsは{num_total_blocks}個指定してください"
510
+ else:
511
+ print(f"block_dims is not specified. all dims are set to {network_dim} / block_dimsが指定されていません。すべてのdimは{network_dim}になります")
512
+ block_dims = [network_dim] * num_total_blocks
513
+
514
+ if block_alphas is not None:
515
+ block_alphas = parse_floats(block_alphas)
516
+ assert (
517
+ len(block_alphas) == num_total_blocks
518
+ ), f"block_alphas must have {num_total_blocks} elements / block_alphasは{num_total_blocks}個指定してください"
519
+ else:
520
+ print(
521
+ f"block_alphas is not specified. all alphas are set to {network_alpha} / block_alphasが指定されていません。すべてのalphaは{network_alpha}になります"
522
+ )
523
+ block_alphas = [network_alpha] * num_total_blocks
524
+
525
+ # conv_block_dimsとconv_block_alphasを、指定がある��合のみパースする。指定がなければconv_dimとconv_alphaを使う
526
+ if conv_block_dims is not None:
527
+ conv_block_dims = parse_ints(conv_block_dims)
528
+ assert (
529
+ len(conv_block_dims) == num_total_blocks
530
+ ), f"conv_block_dims must have {num_total_blocks} elements / conv_block_dimsは{num_total_blocks}個指定してください"
531
+
532
+ if conv_block_alphas is not None:
533
+ conv_block_alphas = parse_floats(conv_block_alphas)
534
+ assert (
535
+ len(conv_block_alphas) == num_total_blocks
536
+ ), f"conv_block_alphas must have {num_total_blocks} elements / conv_block_alphasは{num_total_blocks}個指定してください"
537
+ else:
538
+ if conv_alpha is None:
539
+ conv_alpha = 1.0
540
+ print(
541
+ f"conv_block_alphas is not specified. all alphas are set to {conv_alpha} / conv_block_alphasが指定されていません。すべてのalphaは{conv_alpha}になります"
542
+ )
543
+ conv_block_alphas = [conv_alpha] * num_total_blocks
544
+ else:
545
+ if conv_dim is not None:
546
+ print(
547
+ f"conv_dim/alpha for all blocks are set to {conv_dim} and {conv_alpha} / すべてのブロックのconv_dimとalphaは{conv_dim}および{conv_alpha}になります"
548
+ )
549
+ conv_block_dims = [conv_dim] * num_total_blocks
550
+ conv_block_alphas = [conv_alpha] * num_total_blocks
551
+ else:
552
+ conv_block_dims = None
553
+ conv_block_alphas = None
554
+
555
+ return block_dims, block_alphas, conv_block_dims, conv_block_alphas
556
+
557
+
558
+ # 層別学習率用に層ごとの学習率に対する倍率を定義する、外部から呼び出される可能性を考慮しておく
559
+ def get_block_lr_weight(
560
+ down_lr_weight, mid_lr_weight, up_lr_weight, zero_threshold
561
+ ) -> Tuple[List[float], List[float], List[float]]:
562
+ # パラメータ未指定時は何もせず、今までと同じ動作とする
563
+ if up_lr_weight is None and mid_lr_weight is None and down_lr_weight is None:
564
+ return None, None, None
565
+
566
+ max_len = LoRANetwork.NUM_OF_BLOCKS # フルモデル相当でのup,downの層の数
567
+
568
+ def get_list(name_with_suffix) -> List[float]:
569
+ import math
570
+
571
+ tokens = name_with_suffix.split("+")
572
+ name = tokens[0]
573
+ base_lr = float(tokens[1]) if len(tokens) > 1 else 0.0
574
+
575
+ if name == "cosine":
576
+ return [math.sin(math.pi * (i / (max_len - 1)) / 2) + base_lr for i in reversed(range(max_len))]
577
+ elif name == "sine":
578
+ return [math.sin(math.pi * (i / (max_len - 1)) / 2) + base_lr for i in range(max_len)]
579
+ elif name == "linear":
580
+ return [i / (max_len - 1) + base_lr for i in range(max_len)]
581
+ elif name == "reverse_linear":
582
+ return [i / (max_len - 1) + base_lr for i in reversed(range(max_len))]
583
+ elif name == "zeros":
584
+ return [0.0 + base_lr] * max_len
585
+ else:
586
+ print(
587
+ "Unknown lr_weight argument %s is used. Valid arguments: / 不明なlr_weightの引数 %s が使われました。有効な引数:\n\tcosine, sine, linear, reverse_linear, zeros"
588
+ % (name)
589
+ )
590
+ return None
591
+
592
+ if type(down_lr_weight) == str:
593
+ down_lr_weight = get_list(down_lr_weight)
594
+ if type(up_lr_weight) == str:
595
+ up_lr_weight = get_list(up_lr_weight)
596
+
597
+ if (up_lr_weight != None and len(up_lr_weight) > max_len) or (down_lr_weight != None and len(down_lr_weight) > max_len):
598
+ print("down_weight or up_weight is too long. Parameters after %d-th are ignored." % max_len)
599
+ print("down_weightもしくはup_weightが長すぎます。%d個目以降のパラメータは無視されます。" % max_len)
600
+ up_lr_weight = up_lr_weight[:max_len]
601
+ down_lr_weight = down_lr_weight[:max_len]
602
+
603
+ if (up_lr_weight != None and len(up_lr_weight) < max_len) or (down_lr_weight != None and len(down_lr_weight) < max_len):
604
+ print("down_weight or up_weight is too short. Parameters after %d-th are filled with 1." % max_len)
605
+ print("down_weightもしくはup_weightが短すぎます。%d個目までの不足したパラメータは1で補われます。" % max_len)
606
+
607
+ if down_lr_weight != None and len(down_lr_weight) < max_len:
608
+ down_lr_weight = down_lr_weight + [1.0] * (max_len - len(down_lr_weight))
609
+ if up_lr_weight != None and len(up_lr_weight) < max_len:
610
+ up_lr_weight = up_lr_weight + [1.0] * (max_len - len(up_lr_weight))
611
+
612
+ if (up_lr_weight != None) or (mid_lr_weight != None) or (down_lr_weight != None):
613
+ print("apply block learning rate / 階層別学習率を適用します。")
614
+ if down_lr_weight != None:
615
+ down_lr_weight = [w if w > zero_threshold else 0 for w in down_lr_weight]
616
+ print("down_lr_weight (shallower -> deeper, 浅い層->深い層):", down_lr_weight)
617
+ else:
618
+ print("down_lr_weight: all 1.0, すべて1.0")
619
+
620
+ if mid_lr_weight != None:
621
+ mid_lr_weight = mid_lr_weight if mid_lr_weight > zero_threshold else 0
622
+ print("mid_lr_weight:", mid_lr_weight)
623
+ else:
624
+ print("mid_lr_weight: 1.0")
625
+
626
+ if up_lr_weight != None:
627
+ up_lr_weight = [w if w > zero_threshold else 0 for w in up_lr_weight]
628
+ print("up_lr_weight (deeper -> shallower, 深い層->浅い層):", up_lr_weight)
629
+ else:
630
+ print("up_lr_weight: all 1.0, すべて1.0")
631
+
632
+ return down_lr_weight, mid_lr_weight, up_lr_weight
633
+
634
+
635
+ # lr_weightが0のblockをblock_dimsから除外する、外部から呼び出す可能性を考慮しておく
636
+ def remove_block_dims_and_alphas(
637
+ block_dims, block_alphas, conv_block_dims, conv_block_alphas, down_lr_weight, mid_lr_weight, up_lr_weight
638
+ ):
639
+ # set 0 to block dim without learning rate to remove the block
640
+ if down_lr_weight != None:
641
+ for i, lr in enumerate(down_lr_weight):
642
+ if lr == 0:
643
+ block_dims[i] = 0
644
+ if conv_block_dims is not None:
645
+ conv_block_dims[i] = 0
646
+ if mid_lr_weight != None:
647
+ if mid_lr_weight == 0:
648
+ block_dims[LoRANetwork.NUM_OF_BLOCKS] = 0
649
+ if conv_block_dims is not None:
650
+ conv_block_dims[LoRANetwork.NUM_OF_BLOCKS] = 0
651
+ if up_lr_weight != None:
652
+ for i, lr in enumerate(up_lr_weight):
653
+ if lr == 0:
654
+ block_dims[LoRANetwork.NUM_OF_BLOCKS + 1 + i] = 0
655
+ if conv_block_dims is not None:
656
+ conv_block_dims[LoRANetwork.NUM_OF_BLOCKS + 1 + i] = 0
657
+
658
+ return block_dims, block_alphas, conv_block_dims, conv_block_alphas
659
+
660
+
661
+ # 外部から呼び出す可能性を考慮しておく
662
+ def get_block_index(lora_name: str) -> int:
663
+ block_idx = -1 # invalid lora name
664
+
665
+ m = RE_UPDOWN.search(lora_name)
666
+ if m:
667
+ g = m.groups()
668
+ i = int(g[1])
669
+ j = int(g[3])
670
+ if g[2] == "resnets":
671
+ idx = 3 * i + j
672
+ elif g[2] == "attentions":
673
+ idx = 3 * i + j
674
+ elif g[2] == "upsamplers" or g[2] == "downsamplers":
675
+ idx = 3 * i + 2
676
+
677
+ if g[0] == "down":
678
+ block_idx = 1 + idx # 0に該当するLoRAは存在しない
679
+ elif g[0] == "up":
680
+ block_idx = LoRANetwork.NUM_OF_BLOCKS + 1 + idx
681
+
682
+ elif "mid_block_" in lora_name:
683
+ block_idx = LoRANetwork.NUM_OF_BLOCKS # idx=12
684
+
685
+ return block_idx
686
+
687
+
688
+ # Create network from weights for inference, weights are not loaded here (because can be merged)
689
+ def create_network_from_weights(multiplier, file, vae, text_encoder, unet, weights_sd=None, for_inference=False, **kwargs):
690
+ if weights_sd is None:
691
+ if os.path.splitext(file)[1] == ".safetensors":
692
+ from safetensors.torch import load_file, safe_open
693
+
694
+ weights_sd = load_file(file)
695
+ else:
696
+ weights_sd = torch.load(file, map_location="cpu")
697
+
698
+ # get dim/alpha mapping
699
+ modules_dim = {}
700
+ modules_alpha = {}
701
+ for key, value in weights_sd.items():
702
+ if "." not in key:
703
+ continue
704
+
705
+ lora_name = key.split(".")[0]
706
+ if "alpha" in key:
707
+ modules_alpha[lora_name] = value
708
+ elif "lora_down" in key:
709
+ dim = value.size()[0]
710
+ modules_dim[lora_name] = dim
711
+ # print(lora_name, value.size(), dim)
712
+
713
+ # support old LoRA without alpha
714
+ for key in modules_dim.keys():
715
+ if key not in modules_alpha:
716
+ modules_alpha[key] = modules_dim[key]
717
+
718
+ module_class = LoRAInfModule if for_inference else LoRAModule
719
+
720
+ network = LoRANetwork(
721
+ text_encoder, unet, multiplier=multiplier, modules_dim=modules_dim, modules_alpha=modules_alpha, module_class=module_class
722
+ )
723
+
724
+ # block lr
725
+ down_lr_weight, mid_lr_weight, up_lr_weight = parse_block_lr_kwargs(kwargs)
726
+ if up_lr_weight is not None or mid_lr_weight is not None or down_lr_weight is not None:
727
+ network.set_block_lr_weight(up_lr_weight, mid_lr_weight, down_lr_weight)
728
+
729
+ return network, weights_sd
730
+
731
+
732
+ class LoRANetwork(torch.nn.Module):
733
+ NUM_OF_BLOCKS = 12 # フルモデル相当でのup,downの層の数
734
+
735
+ UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel"]
736
+ UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
737
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
738
+ LORA_PREFIX_UNET = "lora_unet"
739
+ LORA_PREFIX_TEXT_ENCODER = "lora_te"
740
+
741
+ # SDXL: must starts with LORA_PREFIX_TEXT_ENCODER
742
+ LORA_PREFIX_TEXT_ENCODER1 = "lora_te1"
743
+ LORA_PREFIX_TEXT_ENCODER2 = "lora_te2"
744
+
745
+ def __init__(
746
+ self,
747
+ text_encoder: Union[List[CLIPTextModel], CLIPTextModel],
748
+ unet,
749
+ multiplier: float = 1.0,
750
+ lora_dim: int = 4,
751
+ alpha: float = 1,
752
+ dropout: Optional[float] = None,
753
+ rank_dropout: Optional[float] = None,
754
+ module_dropout: Optional[float] = None,
755
+ conv_lora_dim: Optional[int] = None,
756
+ conv_alpha: Optional[float] = None,
757
+ block_dims: Optional[List[int]] = None,
758
+ block_alphas: Optional[List[float]] = None,
759
+ conv_block_dims: Optional[List[int]] = None,
760
+ conv_block_alphas: Optional[List[float]] = None,
761
+ modules_dim: Optional[Dict[str, int]] = None,
762
+ modules_alpha: Optional[Dict[str, int]] = None,
763
+ module_class: Type[object] = LoRAModule,
764
+ varbose: Optional[bool] = False,
765
+ ) -> None:
766
+ """
767
+ LoRA network: すごく引数が多いが、パターンは以下の通り
768
+ 1. lora_dimとalphaを指定
769
+ 2. lora_dim、alpha、conv_lora_dim、conv_alphaを指定
770
+ 3. block_dimsとblock_alphasを指定 : Conv2d3x3には適用しない
771
+ 4. block_dims、block_alphas、conv_block_dims、conv_block_alphasを指定 : Conv2d3x3にも適用する
772
+ 5. modules_dimとmodules_alphaを指定 (推論用)
773
+ """
774
+ super().__init__()
775
+ self.multiplier = multiplier
776
+
777
+ self.lora_dim = lora_dim
778
+ self.alpha = alpha
779
+ self.conv_lora_dim = conv_lora_dim
780
+ self.conv_alpha = conv_alpha
781
+ self.dropout = dropout
782
+ self.rank_dropout = rank_dropout
783
+ self.module_dropout = module_dropout
784
+
785
+ if modules_dim is not None:
786
+ print(f"create LoRA network from weights")
787
+ elif block_dims is not None:
788
+ print(f"create LoRA network from block_dims")
789
+ print(f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
790
+ print(f"block_dims: {block_dims}")
791
+ print(f"block_alphas: {block_alphas}")
792
+ if conv_block_dims is not None:
793
+ print(f"conv_block_dims: {conv_block_dims}")
794
+ print(f"conv_block_alphas: {conv_block_alphas}")
795
+ else:
796
+ print(f"create LoRA network. base dim (rank): {lora_dim}, alpha: {alpha}")
797
+ print(f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
798
+ if self.conv_lora_dim is not None:
799
+ print(f"apply LoRA to Conv2d with kernel size (3,3). dim (rank): {self.conv_lora_dim}, alpha: {self.conv_alpha}")
800
+
801
+ # create module instances
802
+ def create_modules(
803
+ is_unet: bool,
804
+ text_encoder_idx: Optional[int], # None, 1, 2
805
+ root_module: torch.nn.Module,
806
+ target_replace_modules: List[torch.nn.Module],
807
+ ) -> List[LoRAModule]:
808
+ prefix = (
809
+ self.LORA_PREFIX_UNET
810
+ if is_unet
811
+ else (
812
+ self.LORA_PREFIX_TEXT_ENCODER
813
+ if text_encoder_idx is None
814
+ else (self.LORA_PREFIX_TEXT_ENCODER1 if text_encoder_idx == 1 else self.LORA_PREFIX_TEXT_ENCODER2)
815
+ )
816
+ )
817
+ loras = []
818
+ skipped = []
819
+ for name, module in root_module.named_modules():
820
+ if module.__class__.__name__ in target_replace_modules:
821
+ for child_name, child_module in module.named_modules():
822
+ is_linear = child_module.__class__.__name__ == "Linear"
823
+ is_conv2d = child_module.__class__.__name__ == "Conv2d"
824
+ is_conv2d_1x1 = is_conv2d and child_module.kernel_size == (1, 1)
825
+
826
+ if is_linear or is_conv2d:
827
+ lora_name = prefix + "." + name + "." + child_name
828
+ lora_name = lora_name.replace(".", "_")
829
+
830
+ dim = None
831
+ alpha = None
832
+
833
+ if modules_dim is not None:
834
+ # モジュール指定あり
835
+ if lora_name in modules_dim:
836
+ dim = modules_dim[lora_name]
837
+ alpha = modules_alpha[lora_name]
838
+ elif is_unet and block_dims is not None:
839
+ # U-Netでblock_dims指定あり
840
+ block_idx = get_block_index(lora_name)
841
+ if is_linear or is_conv2d_1x1:
842
+ dim = block_dims[block_idx]
843
+ alpha = block_alphas[block_idx]
844
+ elif conv_block_dims is not None:
845
+ dim = conv_block_dims[block_idx]
846
+ alpha = conv_block_alphas[block_idx]
847
+ else:
848
+ # 通常、すべて対象とする
849
+ if is_linear or is_conv2d_1x1:
850
+ dim = self.lora_dim
851
+ alpha = self.alpha
852
+ elif self.conv_lora_dim is not None:
853
+ dim = self.conv_lora_dim
854
+ alpha = self.conv_alpha
855
+
856
+ if dim is None or dim == 0:
857
+ # skipした情報を出力
858
+ if is_linear or is_conv2d_1x1 or (self.conv_lora_dim is not None or conv_block_dims is not None):
859
+ skipped.append(lora_name)
860
+ continue
861
+
862
+ lora = module_class(
863
+ lora_name,
864
+ child_module,
865
+ self.multiplier,
866
+ dim,
867
+ alpha,
868
+ dropout=dropout,
869
+ rank_dropout=rank_dropout,
870
+ module_dropout=module_dropout,
871
+ )
872
+ loras.append(lora)
873
+ return loras, skipped
874
+
875
+ text_encoders = text_encoder if type(text_encoder) == list else [text_encoder]
876
+
877
+ # create LoRA for text encoder
878
+ # 毎回すべてのモジュールを作るのは無駄なので要検討
879
+ self.text_encoder_loras = []
880
+ skipped_te = []
881
+ for i, text_encoder in enumerate(text_encoders):
882
+ if len(text_encoders) > 1:
883
+ index = i + 1
884
+ print(f"create LoRA for Text Encoder {index}:")
885
+ else:
886
+ index = None
887
+ print(f"create LoRA for Text Encoder:")
888
+
889
+ text_encoder_loras, skipped = create_modules(False, index, text_encoder, LoRANetwork.TEXT_ENCODER_TARGET_REPLACE_MODULE)
890
+ self.text_encoder_loras.extend(text_encoder_loras)
891
+ skipped_te += skipped
892
+ print(f"create LoRA for Text Encoder: {len(self.text_encoder_loras)} modules.")
893
+
894
+ # extend U-Net target modules if conv2d 3x3 is enabled, or load from weights
895
+ target_modules = LoRANetwork.UNET_TARGET_REPLACE_MODULE
896
+ if modules_dim is not None or self.conv_lora_dim is not None or conv_block_dims is not None:
897
+ target_modules += LoRANetwork.UNET_TARGET_REPLACE_MODULE_CONV2D_3X3
898
+
899
+ self.unet_loras, skipped_un = create_modules(True, None, unet, target_modules)
900
+ print(f"create LoRA for U-Net: {len(self.unet_loras)} modules.")
901
+
902
+ skipped = skipped_te + skipped_un
903
+ if varbose and len(skipped) > 0:
904
+ print(
905
+ f"because block_lr_weight is 0 or dim (rank) is 0, {len(skipped)} LoRA modules are skipped / block_lr_weightまたはdim (rank)が0の為、次の{len(skipped)}個のLoRAモジュールはスキップされます:"
906
+ )
907
+ for name in skipped:
908
+ print(f"\t{name}")
909
+
910
+ self.up_lr_weight: List[float] = None
911
+ self.down_lr_weight: List[float] = None
912
+ self.mid_lr_weight: float = None
913
+ self.block_lr = False
914
+
915
+ # assertion
916
+ names = set()
917
+ for lora in self.text_encoder_loras + self.unet_loras:
918
+ assert lora.lora_name not in names, f"duplicated lora name: {lora.lora_name}"
919
+ names.add(lora.lora_name)
920
+
921
+ def set_multiplier(self, multiplier):
922
+ self.multiplier = multiplier
923
+ for lora in self.text_encoder_loras + self.unet_loras:
924
+ lora.multiplier = self.multiplier
925
+
926
+ def load_weights(self, file):
927
+ if os.path.splitext(file)[1] == ".safetensors":
928
+ from safetensors.torch import load_file
929
+
930
+ weights_sd = load_file(file)
931
+ else:
932
+ weights_sd = torch.load(file, map_location="cpu")
933
+
934
+ info = self.load_state_dict(weights_sd, False)
935
+ return info
936
+
937
+ def apply_to(self, text_encoder, unet, apply_text_encoder=True, apply_unet=True):
938
+ if apply_text_encoder:
939
+ print("enable LoRA for text encoder")
940
+ else:
941
+ self.text_encoder_loras = []
942
+
943
+ if apply_unet:
944
+ print("enable LoRA for U-Net")
945
+ else:
946
+ self.unet_loras = []
947
+
948
+ for lora in self.text_encoder_loras + self.unet_loras:
949
+ lora.apply_to()
950
+ self.add_module(lora.lora_name, lora)
951
+
952
+ # マージできるかどうかを返す
953
+ def is_mergeable(self):
954
+ return True
955
+
956
+ # TODO refactor to common function with apply_to
957
+ def merge_to(self, text_encoder, unet, weights_sd, dtype, device):
958
+ apply_text_encoder = apply_unet = False
959
+ for key in weights_sd.keys():
960
+ if key.startswith(LoRANetwork.LORA_PREFIX_TEXT_ENCODER):
961
+ apply_text_encoder = True
962
+ elif key.startswith(LoRANetwork.LORA_PREFIX_UNET):
963
+ apply_unet = True
964
+
965
+ if apply_text_encoder:
966
+ print("enable LoRA for text encoder")
967
+ else:
968
+ self.text_encoder_loras = []
969
+
970
+ if apply_unet:
971
+ print("enable LoRA for U-Net")
972
+ else:
973
+ self.unet_loras = []
974
+
975
+ for lora in self.text_encoder_loras + self.unet_loras:
976
+ sd_for_lora = {}
977
+ for key in weights_sd.keys():
978
+ if key.startswith(lora.lora_name):
979
+ sd_for_lora[key[len(lora.lora_name) + 1 :]] = weights_sd[key]
980
+ lora.merge_to(sd_for_lora, dtype, device)
981
+
982
+ print(f"weights are merged")
983
+
984
+ # 層別学習率用に層ごとの学習率に対する倍率を定義する 引数の順番が逆だがとりあえず気にしない
985
+ def set_block_lr_weight(
986
+ self,
987
+ up_lr_weight: List[float] = None,
988
+ mid_lr_weight: float = None,
989
+ down_lr_weight: List[float] = None,
990
+ ):
991
+ self.block_lr = True
992
+ self.down_lr_weight = down_lr_weight
993
+ self.mid_lr_weight = mid_lr_weight
994
+ self.up_lr_weight = up_lr_weight
995
+
996
+ def get_lr_weight(self, lora: LoRAModule) -> float:
997
+ lr_weight = 1.0
998
+ block_idx = get_block_index(lora.lora_name)
999
+ if block_idx < 0:
1000
+ return lr_weight
1001
+
1002
+ if block_idx < LoRANetwork.NUM_OF_BLOCKS:
1003
+ if self.down_lr_weight != None:
1004
+ lr_weight = self.down_lr_weight[block_idx]
1005
+ elif block_idx == LoRANetwork.NUM_OF_BLOCKS:
1006
+ if self.mid_lr_weight != None:
1007
+ lr_weight = self.mid_lr_weight
1008
+ elif block_idx > LoRANetwork.NUM_OF_BLOCKS:
1009
+ if self.up_lr_weight != None:
1010
+ lr_weight = self.up_lr_weight[block_idx - LoRANetwork.NUM_OF_BLOCKS - 1]
1011
+
1012
+ return lr_weight
1013
+
1014
+ # 二つのText Encoderに別々の学習率を設定できるようにするといいかも
1015
+ def prepare_optimizer_params(self, text_encoder_lr, unet_lr, default_lr):
1016
+ self.requires_grad_(True)
1017
+ all_params = []
1018
+
1019
+ def enumerate_params(loras):
1020
+ params = []
1021
+ for lora in loras:
1022
+ params.extend(lora.parameters())
1023
+ return params
1024
+
1025
+ if self.text_encoder_loras:
1026
+ param_data = {"params": enumerate_params(self.text_encoder_loras)}
1027
+ if text_encoder_lr is not None:
1028
+ param_data["lr"] = text_encoder_lr
1029
+ all_params.append(param_data)
1030
+
1031
+ if self.unet_loras:
1032
+ if self.block_lr:
1033
+ # 学習率のグラフをblockごとにしたいので、blockごとにloraを分類
1034
+ block_idx_to_lora = {}
1035
+ for lora in self.unet_loras:
1036
+ idx = get_block_index(lora.lora_name)
1037
+ if idx not in block_idx_to_lora:
1038
+ block_idx_to_lora[idx] = []
1039
+ block_idx_to_lora[idx].append(lora)
1040
+
1041
+ # blockごとにパラメータを設定する
1042
+ for idx, block_loras in block_idx_to_lora.items():
1043
+ param_data = {"params": enumerate_params(block_loras)}
1044
+
1045
+ if unet_lr is not None:
1046
+ param_data["lr"] = unet_lr * self.get_lr_weight(block_loras[0])
1047
+ elif default_lr is not None:
1048
+ param_data["lr"] = default_lr * self.get_lr_weight(block_loras[0])
1049
+ if ("lr" in param_data) and (param_data["lr"] == 0):
1050
+ continue
1051
+ all_params.append(param_data)
1052
+
1053
+ else:
1054
+ param_data = {"params": enumerate_params(self.unet_loras)}
1055
+ if unet_lr is not None:
1056
+ param_data["lr"] = unet_lr
1057
+ all_params.append(param_data)
1058
+
1059
+ return all_params
1060
+
1061
+ def enable_gradient_checkpointing(self):
1062
+ # not supported
1063
+ pass
1064
+
1065
+ def prepare_grad_etc(self, text_encoder, unet):
1066
+ self.requires_grad_(True)
1067
+
1068
+ def on_epoch_start(self, text_encoder, unet):
1069
+ self.train()
1070
+
1071
+ def get_trainable_params(self):
1072
+ return self.parameters()
1073
+
1074
+ def save_weights(self, file, dtype, metadata):
1075
+ if metadata is not None and len(metadata) == 0:
1076
+ metadata = None
1077
+
1078
+ state_dict = self.state_dict()
1079
+
1080
+ if dtype is not None:
1081
+ for key in list(state_dict.keys()):
1082
+ v = state_dict[key]
1083
+ v = v.detach().clone().to("cpu").to(dtype)
1084
+ state_dict[key] = v
1085
+
1086
+ if os.path.splitext(file)[1] == ".safetensors":
1087
+ from safetensors.torch import save_file
1088
+
1089
+ # Precalculate model hashes to save time on indexing
1090
+ if metadata is None:
1091
+ metadata = {}
1092
+ # model_hash, legacy_hash = train_util.precalculate_safetensors_hashes(state_dict, metadata)
1093
+ # metadata["sshs_model_hash"] = model_hash
1094
+ # metadata["sshs_legacy_hash"] = legacy_hash
1095
+
1096
+ save_file(state_dict, file, metadata)
1097
+ else:
1098
+ torch.save(state_dict, file)
1099
+
1100
+ # mask is a tensor with values from 0 to 1
1101
+ def set_region(self, sub_prompt_index, is_last_network, mask):
1102
+ if mask.max() == 0:
1103
+ mask = torch.ones_like(mask)
1104
+
1105
+ self.mask = mask
1106
+ self.sub_prompt_index = sub_prompt_index
1107
+ self.is_last_network = is_last_network
1108
+
1109
+ for lora in self.text_encoder_loras + self.unet_loras:
1110
+ lora.set_network(self)
1111
+
1112
+ def set_current_generation(self, batch_size, num_sub_prompts, width, height, shared):
1113
+ self.batch_size = batch_size
1114
+ self.num_sub_prompts = num_sub_prompts
1115
+ self.current_size = (height, width)
1116
+ self.shared = shared
1117
+
1118
+ # create masks
1119
+ mask = self.mask
1120
+ mask_dic = {}
1121
+ mask = mask.unsqueeze(0).unsqueeze(1) # b(1),c(1),h,w
1122
+ ref_weight = self.text_encoder_loras[0].lora_down.weight if self.text_encoder_loras else self.unet_loras[0].lora_down.weight
1123
+ dtype = ref_weight.dtype
1124
+ device = ref_weight.device
1125
+
1126
+ def resize_add(mh, mw):
1127
+ # print(mh, mw, mh * mw)
1128
+ m = torch.nn.functional.interpolate(mask, (mh, mw), mode="bilinear") # doesn't work in bf16
1129
+ m = m.to(device, dtype=dtype)
1130
+ mask_dic[mh * mw] = m
1131
+
1132
+ h = height // 8
1133
+ w = width // 8
1134
+ for _ in range(4):
1135
+ resize_add(h, w)
1136
+ if h % 2 == 1 or w % 2 == 1: # add extra shape if h/w is not divisible by 2
1137
+ resize_add(h + h % 2, w + w % 2)
1138
+ h = (h + 1) // 2
1139
+ w = (w + 1) // 2
1140
+
1141
+ self.mask_dic = mask_dic
1142
+
1143
+ def backup_weights(self):
1144
+ # 重みのバックアップを行う
1145
+ loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
1146
+ for lora in loras:
1147
+ org_module = lora.org_module_ref[0]
1148
+ if not hasattr(org_module, "_lora_org_weight"):
1149
+ sd = org_module.state_dict()
1150
+ org_module._lora_org_weight = sd["weight"].detach().clone()
1151
+ org_module._lora_restored = True
1152
+
1153
+ def restore_weights(self):
1154
+ # 重みのリストアを行う
1155
+ loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
1156
+ for lora in loras:
1157
+ org_module = lora.org_module_ref[0]
1158
+ if not org_module._lora_restored:
1159
+ sd = org_module.state_dict()
1160
+ sd["weight"] = org_module._lora_org_weight
1161
+ org_module.load_state_dict(sd)
1162
+ org_module._lora_restored = True
1163
+
1164
+ def pre_calculation(self):
1165
+ # 事前計算を行う
1166
+ loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
1167
+ for lora in loras:
1168
+ org_module = lora.org_module_ref[0]
1169
+ sd = org_module.state_dict()
1170
+
1171
+ org_weight = sd["weight"]
1172
+ lora_weight = lora.get_weight().to(org_weight.device, dtype=org_weight.dtype)
1173
+ sd["weight"] = org_weight + lora_weight
1174
+ assert sd["weight"].shape == org_weight.shape
1175
+ org_module.load_state_dict(sd)
1176
+
1177
+ org_module._lora_restored = False
1178
+ lora.enabled = False
1179
+
1180
+ def apply_max_norm_regularization(self, max_norm_value, device):
1181
+ downkeys = []
1182
+ upkeys = []
1183
+ alphakeys = []
1184
+ norms = []
1185
+ keys_scaled = 0
1186
+
1187
+ state_dict = self.state_dict()
1188
+ for key in state_dict.keys():
1189
+ if "lora_down" in key and "weight" in key:
1190
+ downkeys.append(key)
1191
+ upkeys.append(key.replace("lora_down", "lora_up"))
1192
+ alphakeys.append(key.replace("lora_down.weight", "alpha"))
1193
+
1194
+ for i in range(len(downkeys)):
1195
+ down = state_dict[downkeys[i]].to(device)
1196
+ up = state_dict[upkeys[i]].to(device)
1197
+ alpha = state_dict[alphakeys[i]].to(device)
1198
+ dim = down.shape[0]
1199
+ scale = alpha / dim
1200
+
1201
+ if up.shape[2:] == (1, 1) and down.shape[2:] == (1, 1):
1202
+ updown = (up.squeeze(2).squeeze(2) @ down.squeeze(2).squeeze(2)).unsqueeze(2).unsqueeze(3)
1203
+ elif up.shape[2:] == (3, 3) or down.shape[2:] == (3, 3):
1204
+ updown = torch.nn.functional.conv2d(down.permute(1, 0, 2, 3), up).permute(1, 0, 2, 3)
1205
+ else:
1206
+ updown = up @ down
1207
+
1208
+ updown *= scale
1209
+
1210
+ norm = updown.norm().clamp(min=max_norm_value / 2)
1211
+ desired = torch.clamp(norm, max=max_norm_value)
1212
+ ratio = desired.cpu() / norm.cpu()
1213
+ sqrt_ratio = ratio**0.5
1214
+ if ratio != 1:
1215
+ keys_scaled += 1
1216
+ state_dict[upkeys[i]] *= sqrt_ratio
1217
+ state_dict[downkeys[i]] *= sqrt_ratio
1218
+ scalednorm = updown.norm() * ratio
1219
+ norms.append(scalednorm.item())
1220
+
1221
+ return keys_scaled, sum(norms) / len(norms), max(norms)
toolkit/kohya_model_util.py ADDED
@@ -0,0 +1,1533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mostly from https://github.com/kohya-ss/sd-scripts/blob/main/library/model_util.py
2
+ # I am infinitely grateful to @kohya-ss for their amazing work in this field.
3
+ # This version is updated to handle the latest version of the diffusers library.
4
+ import json
5
+ # v1: split from train_db_fixed.py.
6
+ # v2: support safetensors
7
+
8
+ import math
9
+ import os
10
+ import re
11
+
12
+ import torch
13
+ from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextConfig, logging
14
+ from diffusers import AutoencoderKL, DDIMScheduler, StableDiffusionPipeline, UNet2DConditionModel
15
+ from safetensors.torch import load_file, save_file
16
+ from collections import OrderedDict
17
+
18
+ # DiffUsers版StableDiffusionのモデルパラメータ
19
+ NUM_TRAIN_TIMESTEPS = 1000
20
+ BETA_START = 0.00085
21
+ BETA_END = 0.0120
22
+
23
+ UNET_PARAMS_MODEL_CHANNELS = 320
24
+ UNET_PARAMS_CHANNEL_MULT = [1, 2, 4, 4]
25
+ UNET_PARAMS_ATTENTION_RESOLUTIONS = [4, 2, 1]
26
+ UNET_PARAMS_IMAGE_SIZE = 64 # fixed from old invalid value `32`
27
+ UNET_PARAMS_IN_CHANNELS = 4
28
+ UNET_PARAMS_OUT_CHANNELS = 4
29
+ UNET_PARAMS_NUM_RES_BLOCKS = 2
30
+ UNET_PARAMS_CONTEXT_DIM = 768
31
+ UNET_PARAMS_NUM_HEADS = 8
32
+ # UNET_PARAMS_USE_LINEAR_PROJECTION = False
33
+
34
+ VAE_PARAMS_Z_CHANNELS = 4
35
+ VAE_PARAMS_RESOLUTION = 256
36
+ VAE_PARAMS_IN_CHANNELS = 3
37
+ VAE_PARAMS_OUT_CH = 3
38
+ VAE_PARAMS_CH = 128
39
+ VAE_PARAMS_CH_MULT = [1, 2, 4, 4]
40
+ VAE_PARAMS_NUM_RES_BLOCKS = 2
41
+
42
+ # V2
43
+ V2_UNET_PARAMS_ATTENTION_HEAD_DIM = [5, 10, 20, 20]
44
+ V2_UNET_PARAMS_CONTEXT_DIM = 1024
45
+ # V2_UNET_PARAMS_USE_LINEAR_PROJECTION = True
46
+
47
+ # Diffusersの設定を読み込むための参照モデル
48
+ DIFFUSERS_REF_MODEL_ID_V1 = "runwayml/stable-diffusion-v1-5"
49
+ DIFFUSERS_REF_MODEL_ID_V2 = "stabilityai/stable-diffusion-2-1"
50
+
51
+
52
+ # region StableDiffusion->Diffusersの変換コード
53
+ # convert_original_stable_diffusion_to_diffusers をコピーして修正している(ASL 2.0)
54
+
55
+
56
+ def shave_segments(path, n_shave_prefix_segments=1):
57
+ """
58
+ Removes segments. Positive values shave the first segments, negative shave the last segments.
59
+ """
60
+ if n_shave_prefix_segments >= 0:
61
+ return ".".join(path.split(".")[n_shave_prefix_segments:])
62
+ else:
63
+ return ".".join(path.split(".")[:n_shave_prefix_segments])
64
+
65
+
66
+ def renew_resnet_paths(old_list, n_shave_prefix_segments=0):
67
+ """
68
+ Updates paths inside resnets to the new naming scheme (local renaming)
69
+ """
70
+ mapping = []
71
+ for old_item in old_list:
72
+ new_item = old_item.replace("in_layers.0", "norm1")
73
+ new_item = new_item.replace("in_layers.2", "conv1")
74
+
75
+ new_item = new_item.replace("out_layers.0", "norm2")
76
+ new_item = new_item.replace("out_layers.3", "conv2")
77
+
78
+ new_item = new_item.replace("emb_layers.1", "time_emb_proj")
79
+ new_item = new_item.replace("skip_connection", "conv_shortcut")
80
+
81
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
82
+
83
+ mapping.append({"old": old_item, "new": new_item})
84
+
85
+ return mapping
86
+
87
+
88
+ def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0):
89
+ """
90
+ Updates paths inside resnets to the new naming scheme (local renaming)
91
+ """
92
+ mapping = []
93
+ for old_item in old_list:
94
+ new_item = old_item
95
+
96
+ new_item = new_item.replace("nin_shortcut", "conv_shortcut")
97
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
98
+
99
+ mapping.append({"old": old_item, "new": new_item})
100
+
101
+ return mapping
102
+
103
+
104
+ def renew_attention_paths(old_list, n_shave_prefix_segments=0):
105
+ """
106
+ Updates paths inside attentions to the new naming scheme (local renaming)
107
+ """
108
+ mapping = []
109
+ for old_item in old_list:
110
+ new_item = old_item
111
+
112
+ # new_item = new_item.replace('norm.weight', 'group_norm.weight')
113
+ # new_item = new_item.replace('norm.bias', 'group_norm.bias')
114
+
115
+ # new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')
116
+ # new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')
117
+
118
+ # new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
119
+
120
+ mapping.append({"old": old_item, "new": new_item})
121
+
122
+ return mapping
123
+
124
+
125
+ def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):
126
+ """
127
+ Updates paths inside attentions to the new naming scheme (local renaming)
128
+ """
129
+ mapping = []
130
+ for old_item in old_list:
131
+ new_item = old_item
132
+
133
+ # updated for latest diffusers
134
+ new_item = new_item.replace("norm.weight", "group_norm.weight")
135
+ new_item = new_item.replace("norm.bias", "group_norm.bias")
136
+
137
+ new_item = new_item.replace("q.weight", "to_q.weight")
138
+ new_item = new_item.replace("q.bias", "to_q.bias")
139
+
140
+ new_item = new_item.replace("k.weight", "to_k.weight")
141
+ new_item = new_item.replace("k.bias", "to_k.bias")
142
+
143
+ new_item = new_item.replace("v.weight", "to_v.weight")
144
+ new_item = new_item.replace("v.bias", "to_v.bias")
145
+
146
+ new_item = new_item.replace("proj_out.weight", "to_out.0.weight")
147
+ new_item = new_item.replace("proj_out.bias", "to_out.0.bias")
148
+
149
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
150
+
151
+ mapping.append({"old": old_item, "new": new_item})
152
+
153
+ return mapping
154
+
155
+
156
+ def assign_to_checkpoint(
157
+ paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None
158
+ ):
159
+ """
160
+ This does the final conversion step: take locally converted weights and apply a global renaming
161
+ to them. It splits attention layers, and takes into account additional replacements
162
+ that may arise.
163
+
164
+ Assigns the weights to the new checkpoint.
165
+ """
166
+ assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."
167
+
168
+ # Splits the attention layers into three variables.
169
+ if attention_paths_to_split is not None:
170
+ for path, path_map in attention_paths_to_split.items():
171
+ old_tensor = old_checkpoint[path]
172
+ channels = old_tensor.shape[0] // 3
173
+
174
+ target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)
175
+
176
+ num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3
177
+
178
+ old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])
179
+ query, key, value = old_tensor.split(channels // num_heads, dim=1)
180
+
181
+ checkpoint[path_map["query"]] = query.reshape(target_shape)
182
+ checkpoint[path_map["key"]] = key.reshape(target_shape)
183
+ checkpoint[path_map["value"]] = value.reshape(target_shape)
184
+
185
+ for path in paths:
186
+ new_path = path["new"]
187
+
188
+ # These have already been assigned
189
+ if attention_paths_to_split is not None and new_path in attention_paths_to_split:
190
+ continue
191
+
192
+ # Global renaming happens here
193
+ new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")
194
+ new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")
195
+ new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")
196
+
197
+ if additional_replacements is not None:
198
+ for replacement in additional_replacements:
199
+ new_path = new_path.replace(replacement["old"], replacement["new"])
200
+
201
+ # proj_attn.weight has to be converted from conv 1D to linear
202
+ is_attn_weight = "proj_attn.weight" in new_path or ("attentions" in new_path and "to_" in new_path)
203
+ shape = old_checkpoint[path["old"]].shape
204
+ if is_attn_weight and len(shape) == 3:
205
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]
206
+ elif is_attn_weight and len(shape) == 4:
207
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0, 0]
208
+ else:
209
+ checkpoint[new_path] = old_checkpoint[path["old"]]
210
+
211
+
212
+ def conv_attn_to_linear(checkpoint):
213
+ keys = list(checkpoint.keys())
214
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
215
+ for key in keys:
216
+ if ".".join(key.split(".")[-2:]) in attn_keys:
217
+ if checkpoint[key].ndim > 2:
218
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
219
+ elif "proj_attn.weight" in key:
220
+ if checkpoint[key].ndim > 2:
221
+ checkpoint[key] = checkpoint[key][:, :, 0]
222
+
223
+
224
+ def linear_transformer_to_conv(checkpoint):
225
+ keys = list(checkpoint.keys())
226
+ tf_keys = ["proj_in.weight", "proj_out.weight"]
227
+ for key in keys:
228
+ if ".".join(key.split(".")[-2:]) in tf_keys:
229
+ if checkpoint[key].ndim == 2:
230
+ checkpoint[key] = checkpoint[key].unsqueeze(2).unsqueeze(2)
231
+
232
+
233
+ def convert_ldm_unet_checkpoint(v2, checkpoint, config):
234
+ mapping = {}
235
+ """
236
+ Takes a state dict and a config, and returns a converted checkpoint.
237
+ """
238
+
239
+ # extract state_dict for UNet
240
+ unet_state_dict = {}
241
+ unet_key = "model.diffusion_model."
242
+ keys = list(checkpoint.keys())
243
+ for key in keys:
244
+ if key.startswith(unet_key):
245
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
246
+
247
+ new_checkpoint = {}
248
+
249
+ new_checkpoint["time_embedding.linear_1.weight"] = unet_state_dict["time_embed.0.weight"]
250
+ new_checkpoint["time_embedding.linear_1.bias"] = unet_state_dict["time_embed.0.bias"]
251
+ new_checkpoint["time_embedding.linear_2.weight"] = unet_state_dict["time_embed.2.weight"]
252
+ new_checkpoint["time_embedding.linear_2.bias"] = unet_state_dict["time_embed.2.bias"]
253
+
254
+ new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]
255
+ new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]
256
+
257
+ new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]
258
+ new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]
259
+ new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]
260
+ new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]
261
+
262
+ # Retrieves the keys for the input blocks only
263
+ num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
264
+ input_blocks = {
265
+ layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}." in key] for layer_id in
266
+ range(num_input_blocks)
267
+ }
268
+
269
+ # Retrieves the keys for the middle blocks only
270
+ num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
271
+ middle_blocks = {
272
+ layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}." in key] for layer_id in
273
+ range(num_middle_blocks)
274
+ }
275
+
276
+ # Retrieves the keys for the output blocks only
277
+ num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
278
+ output_blocks = {
279
+ layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}." in key] for layer_id in
280
+ range(num_output_blocks)
281
+ }
282
+
283
+ for i in range(1, num_input_blocks):
284
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
285
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
286
+
287
+ resnets = [key for key in input_blocks[i] if
288
+ f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key]
289
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
290
+
291
+ if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
292
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
293
+ f"input_blocks.{i}.0.op.weight"
294
+ )
295
+ mapping[f'input_blocks.{i}.0.op.weight'] = f"down_blocks.{block_id}.downsamplers.0.conv.weight"
296
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
297
+ f"input_blocks.{i}.0.op.bias")
298
+ mapping[f'input_blocks.{i}.0.op.bias'] = f"down_blocks.{block_id}.downsamplers.0.conv.bias"
299
+
300
+ paths = renew_resnet_paths(resnets)
301
+ meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"}
302
+ assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config)
303
+
304
+ if len(attentions):
305
+ paths = renew_attention_paths(attentions)
306
+ meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}
307
+ assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path],
308
+ config=config)
309
+
310
+ resnet_0 = middle_blocks[0]
311
+ attentions = middle_blocks[1]
312
+ resnet_1 = middle_blocks[2]
313
+
314
+ resnet_0_paths = renew_resnet_paths(resnet_0)
315
+ assign_to_checkpoint(resnet_0_paths, new_checkpoint, unet_state_dict, config=config)
316
+
317
+ resnet_1_paths = renew_resnet_paths(resnet_1)
318
+ assign_to_checkpoint(resnet_1_paths, new_checkpoint, unet_state_dict, config=config)
319
+
320
+ attentions_paths = renew_attention_paths(attentions)
321
+ meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}
322
+ assign_to_checkpoint(attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path],
323
+ config=config)
324
+
325
+ for i in range(num_output_blocks):
326
+ block_id = i // (config["layers_per_block"] + 1)
327
+ layer_in_block_id = i % (config["layers_per_block"] + 1)
328
+ output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]
329
+ output_block_list = {}
330
+
331
+ for layer in output_block_layers:
332
+ layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)
333
+ if layer_id in output_block_list:
334
+ output_block_list[layer_id].append(layer_name)
335
+ else:
336
+ output_block_list[layer_id] = [layer_name]
337
+
338
+ if len(output_block_list) > 1:
339
+ resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0" in key]
340
+ attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key]
341
+
342
+ resnet_0_paths = renew_resnet_paths(resnets)
343
+ paths = renew_resnet_paths(resnets)
344
+
345
+ meta_path = {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"}
346
+ assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path],
347
+ config=config)
348
+
349
+ # オリジナル:
350
+ # if ["conv.weight", "conv.bias"] in output_block_list.values():
351
+ # index = list(output_block_list.values()).index(["conv.weight", "conv.bias"])
352
+
353
+ # biasとweightの順番に依存しないようにする:もっといいやり方がありそうだが
354
+ for l in output_block_list.values():
355
+ l.sort()
356
+
357
+ if ["conv.bias", "conv.weight"] in output_block_list.values():
358
+ index = list(output_block_list.values()).index(["conv.bias", "conv.weight"])
359
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
360
+ f"output_blocks.{i}.{index}.conv.bias"
361
+ ]
362
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
363
+ f"output_blocks.{i}.{index}.conv.weight"
364
+ ]
365
+
366
+ # Clear attentions as they have been attributed above.
367
+ if len(attentions) == 2:
368
+ attentions = []
369
+
370
+ if len(attentions):
371
+ paths = renew_attention_paths(attentions)
372
+ meta_path = {
373
+ "old": f"output_blocks.{i}.1",
374
+ "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",
375
+ }
376
+ assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path],
377
+ config=config)
378
+ else:
379
+ resnet_0_paths = renew_resnet_paths(output_block_layers, n_shave_prefix_segments=1)
380
+ for path in resnet_0_paths:
381
+ old_path = ".".join(["output_blocks", str(i), path["old"]])
382
+ new_path = ".".join(["up_blocks", str(block_id), "resnets", str(layer_in_block_id), path["new"]])
383
+
384
+ new_checkpoint[new_path] = unet_state_dict[old_path]
385
+
386
+ # SDのv2では1*1のconv2dがlinearに変わっている
387
+ # 誤って Diffusers 側を conv2d のままにしてしまったので、変換必要
388
+ if v2 and not config.get('use_linear_projection', False):
389
+ linear_transformer_to_conv(new_checkpoint)
390
+
391
+ # print("mapping: ", json.dumps(mapping, indent=4))
392
+ return new_checkpoint
393
+
394
+
395
+ # ldm key: diffusers key
396
+ vae_ldm_to_diffusers_dict = {
397
+ "decoder.conv_in.bias": "decoder.conv_in.bias",
398
+ "decoder.conv_in.weight": "decoder.conv_in.weight",
399
+ "decoder.conv_out.bias": "decoder.conv_out.bias",
400
+ "decoder.conv_out.weight": "decoder.conv_out.weight",
401
+ "decoder.mid.attn_1.k.bias": "decoder.mid_block.attentions.0.to_k.bias",
402
+ "decoder.mid.attn_1.k.weight": "decoder.mid_block.attentions.0.to_k.weight",
403
+ "decoder.mid.attn_1.norm.bias": "decoder.mid_block.attentions.0.group_norm.bias",
404
+ "decoder.mid.attn_1.norm.weight": "decoder.mid_block.attentions.0.group_norm.weight",
405
+ "decoder.mid.attn_1.proj_out.bias": "decoder.mid_block.attentions.0.to_out.0.bias",
406
+ "decoder.mid.attn_1.proj_out.weight": "decoder.mid_block.attentions.0.to_out.0.weight",
407
+ "decoder.mid.attn_1.q.bias": "decoder.mid_block.attentions.0.to_q.bias",
408
+ "decoder.mid.attn_1.q.weight": "decoder.mid_block.attentions.0.to_q.weight",
409
+ "decoder.mid.attn_1.v.bias": "decoder.mid_block.attentions.0.to_v.bias",
410
+ "decoder.mid.attn_1.v.weight": "decoder.mid_block.attentions.0.to_v.weight",
411
+ "decoder.mid.block_1.conv1.bias": "decoder.mid_block.resnets.0.conv1.bias",
412
+ "decoder.mid.block_1.conv1.weight": "decoder.mid_block.resnets.0.conv1.weight",
413
+ "decoder.mid.block_1.conv2.bias": "decoder.mid_block.resnets.0.conv2.bias",
414
+ "decoder.mid.block_1.conv2.weight": "decoder.mid_block.resnets.0.conv2.weight",
415
+ "decoder.mid.block_1.norm1.bias": "decoder.mid_block.resnets.0.norm1.bias",
416
+ "decoder.mid.block_1.norm1.weight": "decoder.mid_block.resnets.0.norm1.weight",
417
+ "decoder.mid.block_1.norm2.bias": "decoder.mid_block.resnets.0.norm2.bias",
418
+ "decoder.mid.block_1.norm2.weight": "decoder.mid_block.resnets.0.norm2.weight",
419
+ "decoder.mid.block_2.conv1.bias": "decoder.mid_block.resnets.1.conv1.bias",
420
+ "decoder.mid.block_2.conv1.weight": "decoder.mid_block.resnets.1.conv1.weight",
421
+ "decoder.mid.block_2.conv2.bias": "decoder.mid_block.resnets.1.conv2.bias",
422
+ "decoder.mid.block_2.conv2.weight": "decoder.mid_block.resnets.1.conv2.weight",
423
+ "decoder.mid.block_2.norm1.bias": "decoder.mid_block.resnets.1.norm1.bias",
424
+ "decoder.mid.block_2.norm1.weight": "decoder.mid_block.resnets.1.norm1.weight",
425
+ "decoder.mid.block_2.norm2.bias": "decoder.mid_block.resnets.1.norm2.bias",
426
+ "decoder.mid.block_2.norm2.weight": "decoder.mid_block.resnets.1.norm2.weight",
427
+ "decoder.norm_out.bias": "decoder.conv_norm_out.bias",
428
+ "decoder.norm_out.weight": "decoder.conv_norm_out.weight",
429
+ "decoder.up.0.block.0.conv1.bias": "decoder.up_blocks.3.resnets.0.conv1.bias",
430
+ "decoder.up.0.block.0.conv1.weight": "decoder.up_blocks.3.resnets.0.conv1.weight",
431
+ "decoder.up.0.block.0.conv2.bias": "decoder.up_blocks.3.resnets.0.conv2.bias",
432
+ "decoder.up.0.block.0.conv2.weight": "decoder.up_blocks.3.resnets.0.conv2.weight",
433
+ "decoder.up.0.block.0.nin_shortcut.bias": "decoder.up_blocks.3.resnets.0.conv_shortcut.bias",
434
+ "decoder.up.0.block.0.nin_shortcut.weight": "decoder.up_blocks.3.resnets.0.conv_shortcut.weight",
435
+ "decoder.up.0.block.0.norm1.bias": "decoder.up_blocks.3.resnets.0.norm1.bias",
436
+ "decoder.up.0.block.0.norm1.weight": "decoder.up_blocks.3.resnets.0.norm1.weight",
437
+ "decoder.up.0.block.0.norm2.bias": "decoder.up_blocks.3.resnets.0.norm2.bias",
438
+ "decoder.up.0.block.0.norm2.weight": "decoder.up_blocks.3.resnets.0.norm2.weight",
439
+ "decoder.up.0.block.1.conv1.bias": "decoder.up_blocks.3.resnets.1.conv1.bias",
440
+ "decoder.up.0.block.1.conv1.weight": "decoder.up_blocks.3.resnets.1.conv1.weight",
441
+ "decoder.up.0.block.1.conv2.bias": "decoder.up_blocks.3.resnets.1.conv2.bias",
442
+ "decoder.up.0.block.1.conv2.weight": "decoder.up_blocks.3.resnets.1.conv2.weight",
443
+ "decoder.up.0.block.1.norm1.bias": "decoder.up_blocks.3.resnets.1.norm1.bias",
444
+ "decoder.up.0.block.1.norm1.weight": "decoder.up_blocks.3.resnets.1.norm1.weight",
445
+ "decoder.up.0.block.1.norm2.bias": "decoder.up_blocks.3.resnets.1.norm2.bias",
446
+ "decoder.up.0.block.1.norm2.weight": "decoder.up_blocks.3.resnets.1.norm2.weight",
447
+ "decoder.up.0.block.2.conv1.bias": "decoder.up_blocks.3.resnets.2.conv1.bias",
448
+ "decoder.up.0.block.2.conv1.weight": "decoder.up_blocks.3.resnets.2.conv1.weight",
449
+ "decoder.up.0.block.2.conv2.bias": "decoder.up_blocks.3.resnets.2.conv2.bias",
450
+ "decoder.up.0.block.2.conv2.weight": "decoder.up_blocks.3.resnets.2.conv2.weight",
451
+ "decoder.up.0.block.2.norm1.bias": "decoder.up_blocks.3.resnets.2.norm1.bias",
452
+ "decoder.up.0.block.2.norm1.weight": "decoder.up_blocks.3.resnets.2.norm1.weight",
453
+ "decoder.up.0.block.2.norm2.bias": "decoder.up_blocks.3.resnets.2.norm2.bias",
454
+ "decoder.up.0.block.2.norm2.weight": "decoder.up_blocks.3.resnets.2.norm2.weight",
455
+ "decoder.up.1.block.0.conv1.bias": "decoder.up_blocks.2.resnets.0.conv1.bias",
456
+ "decoder.up.1.block.0.conv1.weight": "decoder.up_blocks.2.resnets.0.conv1.weight",
457
+ "decoder.up.1.block.0.conv2.bias": "decoder.up_blocks.2.resnets.0.conv2.bias",
458
+ "decoder.up.1.block.0.conv2.weight": "decoder.up_blocks.2.resnets.0.conv2.weight",
459
+ "decoder.up.1.block.0.nin_shortcut.bias": "decoder.up_blocks.2.resnets.0.conv_shortcut.bias",
460
+ "decoder.up.1.block.0.nin_shortcut.weight": "decoder.up_blocks.2.resnets.0.conv_shortcut.weight",
461
+ "decoder.up.1.block.0.norm1.bias": "decoder.up_blocks.2.resnets.0.norm1.bias",
462
+ "decoder.up.1.block.0.norm1.weight": "decoder.up_blocks.2.resnets.0.norm1.weight",
463
+ "decoder.up.1.block.0.norm2.bias": "decoder.up_blocks.2.resnets.0.norm2.bias",
464
+ "decoder.up.1.block.0.norm2.weight": "decoder.up_blocks.2.resnets.0.norm2.weight",
465
+ "decoder.up.1.block.1.conv1.bias": "decoder.up_blocks.2.resnets.1.conv1.bias",
466
+ "decoder.up.1.block.1.conv1.weight": "decoder.up_blocks.2.resnets.1.conv1.weight",
467
+ "decoder.up.1.block.1.conv2.bias": "decoder.up_blocks.2.resnets.1.conv2.bias",
468
+ "decoder.up.1.block.1.conv2.weight": "decoder.up_blocks.2.resnets.1.conv2.weight",
469
+ "decoder.up.1.block.1.norm1.bias": "decoder.up_blocks.2.resnets.1.norm1.bias",
470
+ "decoder.up.1.block.1.norm1.weight": "decoder.up_blocks.2.resnets.1.norm1.weight",
471
+ "decoder.up.1.block.1.norm2.bias": "decoder.up_blocks.2.resnets.1.norm2.bias",
472
+ "decoder.up.1.block.1.norm2.weight": "decoder.up_blocks.2.resnets.1.norm2.weight",
473
+ "decoder.up.1.block.2.conv1.bias": "decoder.up_blocks.2.resnets.2.conv1.bias",
474
+ "decoder.up.1.block.2.conv1.weight": "decoder.up_blocks.2.resnets.2.conv1.weight",
475
+ "decoder.up.1.block.2.conv2.bias": "decoder.up_blocks.2.resnets.2.conv2.bias",
476
+ "decoder.up.1.block.2.conv2.weight": "decoder.up_blocks.2.resnets.2.conv2.weight",
477
+ "decoder.up.1.block.2.norm1.bias": "decoder.up_blocks.2.resnets.2.norm1.bias",
478
+ "decoder.up.1.block.2.norm1.weight": "decoder.up_blocks.2.resnets.2.norm1.weight",
479
+ "decoder.up.1.block.2.norm2.bias": "decoder.up_blocks.2.resnets.2.norm2.bias",
480
+ "decoder.up.1.block.2.norm2.weight": "decoder.up_blocks.2.resnets.2.norm2.weight",
481
+ "decoder.up.1.upsample.conv.bias": "decoder.up_blocks.2.upsamplers.0.conv.bias",
482
+ "decoder.up.1.upsample.conv.weight": "decoder.up_blocks.2.upsamplers.0.conv.weight",
483
+ "decoder.up.2.block.0.conv1.bias": "decoder.up_blocks.1.resnets.0.conv1.bias",
484
+ "decoder.up.2.block.0.conv1.weight": "decoder.up_blocks.1.resnets.0.conv1.weight",
485
+ "decoder.up.2.block.0.conv2.bias": "decoder.up_blocks.1.resnets.0.conv2.bias",
486
+ "decoder.up.2.block.0.conv2.weight": "decoder.up_blocks.1.resnets.0.conv2.weight",
487
+ "decoder.up.2.block.0.norm1.bias": "decoder.up_blocks.1.resnets.0.norm1.bias",
488
+ "decoder.up.2.block.0.norm1.weight": "decoder.up_blocks.1.resnets.0.norm1.weight",
489
+ "decoder.up.2.block.0.norm2.bias": "decoder.up_blocks.1.resnets.0.norm2.bias",
490
+ "decoder.up.2.block.0.norm2.weight": "decoder.up_blocks.1.resnets.0.norm2.weight",
491
+ "decoder.up.2.block.1.conv1.bias": "decoder.up_blocks.1.resnets.1.conv1.bias",
492
+ "decoder.up.2.block.1.conv1.weight": "decoder.up_blocks.1.resnets.1.conv1.weight",
493
+ "decoder.up.2.block.1.conv2.bias": "decoder.up_blocks.1.resnets.1.conv2.bias",
494
+ "decoder.up.2.block.1.conv2.weight": "decoder.up_blocks.1.resnets.1.conv2.weight",
495
+ "decoder.up.2.block.1.norm1.bias": "decoder.up_blocks.1.resnets.1.norm1.bias",
496
+ "decoder.up.2.block.1.norm1.weight": "decoder.up_blocks.1.resnets.1.norm1.weight",
497
+ "decoder.up.2.block.1.norm2.bias": "decoder.up_blocks.1.resnets.1.norm2.bias",
498
+ "decoder.up.2.block.1.norm2.weight": "decoder.up_blocks.1.resnets.1.norm2.weight",
499
+ "decoder.up.2.block.2.conv1.bias": "decoder.up_blocks.1.resnets.2.conv1.bias",
500
+ "decoder.up.2.block.2.conv1.weight": "decoder.up_blocks.1.resnets.2.conv1.weight",
501
+ "decoder.up.2.block.2.conv2.bias": "decoder.up_blocks.1.resnets.2.conv2.bias",
502
+ "decoder.up.2.block.2.conv2.weight": "decoder.up_blocks.1.resnets.2.conv2.weight",
503
+ "decoder.up.2.block.2.norm1.bias": "decoder.up_blocks.1.resnets.2.norm1.bias",
504
+ "decoder.up.2.block.2.norm1.weight": "decoder.up_blocks.1.resnets.2.norm1.weight",
505
+ "decoder.up.2.block.2.norm2.bias": "decoder.up_blocks.1.resnets.2.norm2.bias",
506
+ "decoder.up.2.block.2.norm2.weight": "decoder.up_blocks.1.resnets.2.norm2.weight",
507
+ "decoder.up.2.upsample.conv.bias": "decoder.up_blocks.1.upsamplers.0.conv.bias",
508
+ "decoder.up.2.upsample.conv.weight": "decoder.up_blocks.1.upsamplers.0.conv.weight",
509
+ "decoder.up.3.block.0.conv1.bias": "decoder.up_blocks.0.resnets.0.conv1.bias",
510
+ "decoder.up.3.block.0.conv1.weight": "decoder.up_blocks.0.resnets.0.conv1.weight",
511
+ "decoder.up.3.block.0.conv2.bias": "decoder.up_blocks.0.resnets.0.conv2.bias",
512
+ "decoder.up.3.block.0.conv2.weight": "decoder.up_blocks.0.resnets.0.conv2.weight",
513
+ "decoder.up.3.block.0.norm1.bias": "decoder.up_blocks.0.resnets.0.norm1.bias",
514
+ "decoder.up.3.block.0.norm1.weight": "decoder.up_blocks.0.resnets.0.norm1.weight",
515
+ "decoder.up.3.block.0.norm2.bias": "decoder.up_blocks.0.resnets.0.norm2.bias",
516
+ "decoder.up.3.block.0.norm2.weight": "decoder.up_blocks.0.resnets.0.norm2.weight",
517
+ "decoder.up.3.block.1.conv1.bias": "decoder.up_blocks.0.resnets.1.conv1.bias",
518
+ "decoder.up.3.block.1.conv1.weight": "decoder.up_blocks.0.resnets.1.conv1.weight",
519
+ "decoder.up.3.block.1.conv2.bias": "decoder.up_blocks.0.resnets.1.conv2.bias",
520
+ "decoder.up.3.block.1.conv2.weight": "decoder.up_blocks.0.resnets.1.conv2.weight",
521
+ "decoder.up.3.block.1.norm1.bias": "decoder.up_blocks.0.resnets.1.norm1.bias",
522
+ "decoder.up.3.block.1.norm1.weight": "decoder.up_blocks.0.resnets.1.norm1.weight",
523
+ "decoder.up.3.block.1.norm2.bias": "decoder.up_blocks.0.resnets.1.norm2.bias",
524
+ "decoder.up.3.block.1.norm2.weight": "decoder.up_blocks.0.resnets.1.norm2.weight",
525
+ "decoder.up.3.block.2.conv1.bias": "decoder.up_blocks.0.resnets.2.conv1.bias",
526
+ "decoder.up.3.block.2.conv1.weight": "decoder.up_blocks.0.resnets.2.conv1.weight",
527
+ "decoder.up.3.block.2.conv2.bias": "decoder.up_blocks.0.resnets.2.conv2.bias",
528
+ "decoder.up.3.block.2.conv2.weight": "decoder.up_blocks.0.resnets.2.conv2.weight",
529
+ "decoder.up.3.block.2.norm1.bias": "decoder.up_blocks.0.resnets.2.norm1.bias",
530
+ "decoder.up.3.block.2.norm1.weight": "decoder.up_blocks.0.resnets.2.norm1.weight",
531
+ "decoder.up.3.block.2.norm2.bias": "decoder.up_blocks.0.resnets.2.norm2.bias",
532
+ "decoder.up.3.block.2.norm2.weight": "decoder.up_blocks.0.resnets.2.norm2.weight",
533
+ "decoder.up.3.upsample.conv.bias": "decoder.up_blocks.0.upsamplers.0.conv.bias",
534
+ "decoder.up.3.upsample.conv.weight": "decoder.up_blocks.0.upsamplers.0.conv.weight",
535
+ "encoder.conv_in.bias": "encoder.conv_in.bias",
536
+ "encoder.conv_in.weight": "encoder.conv_in.weight",
537
+ "encoder.conv_out.bias": "encoder.conv_out.bias",
538
+ "encoder.conv_out.weight": "encoder.conv_out.weight",
539
+ "encoder.down.0.block.0.conv1.bias": "encoder.down_blocks.0.resnets.0.conv1.bias",
540
+ "encoder.down.0.block.0.conv1.weight": "encoder.down_blocks.0.resnets.0.conv1.weight",
541
+ "encoder.down.0.block.0.conv2.bias": "encoder.down_blocks.0.resnets.0.conv2.bias",
542
+ "encoder.down.0.block.0.conv2.weight": "encoder.down_blocks.0.resnets.0.conv2.weight",
543
+ "encoder.down.0.block.0.norm1.bias": "encoder.down_blocks.0.resnets.0.norm1.bias",
544
+ "encoder.down.0.block.0.norm1.weight": "encoder.down_blocks.0.resnets.0.norm1.weight",
545
+ "encoder.down.0.block.0.norm2.bias": "encoder.down_blocks.0.resnets.0.norm2.bias",
546
+ "encoder.down.0.block.0.norm2.weight": "encoder.down_blocks.0.resnets.0.norm2.weight",
547
+ "encoder.down.0.block.1.conv1.bias": "encoder.down_blocks.0.resnets.1.conv1.bias",
548
+ "encoder.down.0.block.1.conv1.weight": "encoder.down_blocks.0.resnets.1.conv1.weight",
549
+ "encoder.down.0.block.1.conv2.bias": "encoder.down_blocks.0.resnets.1.conv2.bias",
550
+ "encoder.down.0.block.1.conv2.weight": "encoder.down_blocks.0.resnets.1.conv2.weight",
551
+ "encoder.down.0.block.1.norm1.bias": "encoder.down_blocks.0.resnets.1.norm1.bias",
552
+ "encoder.down.0.block.1.norm1.weight": "encoder.down_blocks.0.resnets.1.norm1.weight",
553
+ "encoder.down.0.block.1.norm2.bias": "encoder.down_blocks.0.resnets.1.norm2.bias",
554
+ "encoder.down.0.block.1.norm2.weight": "encoder.down_blocks.0.resnets.1.norm2.weight",
555
+ "encoder.down.0.downsample.conv.bias": "encoder.down_blocks.0.downsamplers.0.conv.bias",
556
+ "encoder.down.0.downsample.conv.weight": "encoder.down_blocks.0.downsamplers.0.conv.weight",
557
+ "encoder.down.1.block.0.conv1.bias": "encoder.down_blocks.1.resnets.0.conv1.bias",
558
+ "encoder.down.1.block.0.conv1.weight": "encoder.down_blocks.1.resnets.0.conv1.weight",
559
+ "encoder.down.1.block.0.conv2.bias": "encoder.down_blocks.1.resnets.0.conv2.bias",
560
+ "encoder.down.1.block.0.conv2.weight": "encoder.down_blocks.1.resnets.0.conv2.weight",
561
+ "encoder.down.1.block.0.nin_shortcut.bias": "encoder.down_blocks.1.resnets.0.conv_shortcut.bias",
562
+ "encoder.down.1.block.0.nin_shortcut.weight": "encoder.down_blocks.1.resnets.0.conv_shortcut.weight",
563
+ "encoder.down.1.block.0.norm1.bias": "encoder.down_blocks.1.resnets.0.norm1.bias",
564
+ "encoder.down.1.block.0.norm1.weight": "encoder.down_blocks.1.resnets.0.norm1.weight",
565
+ "encoder.down.1.block.0.norm2.bias": "encoder.down_blocks.1.resnets.0.norm2.bias",
566
+ "encoder.down.1.block.0.norm2.weight": "encoder.down_blocks.1.resnets.0.norm2.weight",
567
+ "encoder.down.1.block.1.conv1.bias": "encoder.down_blocks.1.resnets.1.conv1.bias",
568
+ "encoder.down.1.block.1.conv1.weight": "encoder.down_blocks.1.resnets.1.conv1.weight",
569
+ "encoder.down.1.block.1.conv2.bias": "encoder.down_blocks.1.resnets.1.conv2.bias",
570
+ "encoder.down.1.block.1.conv2.weight": "encoder.down_blocks.1.resnets.1.conv2.weight",
571
+ "encoder.down.1.block.1.norm1.bias": "encoder.down_blocks.1.resnets.1.norm1.bias",
572
+ "encoder.down.1.block.1.norm1.weight": "encoder.down_blocks.1.resnets.1.norm1.weight",
573
+ "encoder.down.1.block.1.norm2.bias": "encoder.down_blocks.1.resnets.1.norm2.bias",
574
+ "encoder.down.1.block.1.norm2.weight": "encoder.down_blocks.1.resnets.1.norm2.weight",
575
+ "encoder.down.1.downsample.conv.bias": "encoder.down_blocks.1.downsamplers.0.conv.bias",
576
+ "encoder.down.1.downsample.conv.weight": "encoder.down_blocks.1.downsamplers.0.conv.weight",
577
+ "encoder.down.2.block.0.conv1.bias": "encoder.down_blocks.2.resnets.0.conv1.bias",
578
+ "encoder.down.2.block.0.conv1.weight": "encoder.down_blocks.2.resnets.0.conv1.weight",
579
+ "encoder.down.2.block.0.conv2.bias": "encoder.down_blocks.2.resnets.0.conv2.bias",
580
+ "encoder.down.2.block.0.conv2.weight": "encoder.down_blocks.2.resnets.0.conv2.weight",
581
+ "encoder.down.2.block.0.nin_shortcut.bias": "encoder.down_blocks.2.resnets.0.conv_shortcut.bias",
582
+ "encoder.down.2.block.0.nin_shortcut.weight": "encoder.down_blocks.2.resnets.0.conv_shortcut.weight",
583
+ "encoder.down.2.block.0.norm1.bias": "encoder.down_blocks.2.resnets.0.norm1.bias",
584
+ "encoder.down.2.block.0.norm1.weight": "encoder.down_blocks.2.resnets.0.norm1.weight",
585
+ "encoder.down.2.block.0.norm2.bias": "encoder.down_blocks.2.resnets.0.norm2.bias",
586
+ "encoder.down.2.block.0.norm2.weight": "encoder.down_blocks.2.resnets.0.norm2.weight",
587
+ "encoder.down.2.block.1.conv1.bias": "encoder.down_blocks.2.resnets.1.conv1.bias",
588
+ "encoder.down.2.block.1.conv1.weight": "encoder.down_blocks.2.resnets.1.conv1.weight",
589
+ "encoder.down.2.block.1.conv2.bias": "encoder.down_blocks.2.resnets.1.conv2.bias",
590
+ "encoder.down.2.block.1.conv2.weight": "encoder.down_blocks.2.resnets.1.conv2.weight",
591
+ "encoder.down.2.block.1.norm1.bias": "encoder.down_blocks.2.resnets.1.norm1.bias",
592
+ "encoder.down.2.block.1.norm1.weight": "encoder.down_blocks.2.resnets.1.norm1.weight",
593
+ "encoder.down.2.block.1.norm2.bias": "encoder.down_blocks.2.resnets.1.norm2.bias",
594
+ "encoder.down.2.block.1.norm2.weight": "encoder.down_blocks.2.resnets.1.norm2.weight",
595
+ "encoder.down.2.downsample.conv.bias": "encoder.down_blocks.2.downsamplers.0.conv.bias",
596
+ "encoder.down.2.downsample.conv.weight": "encoder.down_blocks.2.downsamplers.0.conv.weight",
597
+ "encoder.down.3.block.0.conv1.bias": "encoder.down_blocks.3.resnets.0.conv1.bias",
598
+ "encoder.down.3.block.0.conv1.weight": "encoder.down_blocks.3.resnets.0.conv1.weight",
599
+ "encoder.down.3.block.0.conv2.bias": "encoder.down_blocks.3.resnets.0.conv2.bias",
600
+ "encoder.down.3.block.0.conv2.weight": "encoder.down_blocks.3.resnets.0.conv2.weight",
601
+ "encoder.down.3.block.0.norm1.bias": "encoder.down_blocks.3.resnets.0.norm1.bias",
602
+ "encoder.down.3.block.0.norm1.weight": "encoder.down_blocks.3.resnets.0.norm1.weight",
603
+ "encoder.down.3.block.0.norm2.bias": "encoder.down_blocks.3.resnets.0.norm2.bias",
604
+ "encoder.down.3.block.0.norm2.weight": "encoder.down_blocks.3.resnets.0.norm2.weight",
605
+ "encoder.down.3.block.1.conv1.bias": "encoder.down_blocks.3.resnets.1.conv1.bias",
606
+ "encoder.down.3.block.1.conv1.weight": "encoder.down_blocks.3.resnets.1.conv1.weight",
607
+ "encoder.down.3.block.1.conv2.bias": "encoder.down_blocks.3.resnets.1.conv2.bias",
608
+ "encoder.down.3.block.1.conv2.weight": "encoder.down_blocks.3.resnets.1.conv2.weight",
609
+ "encoder.down.3.block.1.norm1.bias": "encoder.down_blocks.3.resnets.1.norm1.bias",
610
+ "encoder.down.3.block.1.norm1.weight": "encoder.down_blocks.3.resnets.1.norm1.weight",
611
+ "encoder.down.3.block.1.norm2.bias": "encoder.down_blocks.3.resnets.1.norm2.bias",
612
+ "encoder.down.3.block.1.norm2.weight": "encoder.down_blocks.3.resnets.1.norm2.weight",
613
+ "encoder.mid.attn_1.k.bias": "encoder.mid_block.attentions.0.to_k.bias",
614
+ "encoder.mid.attn_1.k.weight": "encoder.mid_block.attentions.0.to_k.weight",
615
+ "encoder.mid.attn_1.norm.bias": "encoder.mid_block.attentions.0.group_norm.bias",
616
+ "encoder.mid.attn_1.norm.weight": "encoder.mid_block.attentions.0.group_norm.weight",
617
+ "encoder.mid.attn_1.proj_out.bias": "encoder.mid_block.attentions.0.to_out.0.bias",
618
+ "encoder.mid.attn_1.proj_out.weight": "encoder.mid_block.attentions.0.to_out.0.weight",
619
+ "encoder.mid.attn_1.q.bias": "encoder.mid_block.attentions.0.to_q.bias",
620
+ "encoder.mid.attn_1.q.weight": "encoder.mid_block.attentions.0.to_q.weight",
621
+ "encoder.mid.attn_1.v.bias": "encoder.mid_block.attentions.0.to_v.bias",
622
+ "encoder.mid.attn_1.v.weight": "encoder.mid_block.attentions.0.to_v.weight",
623
+ "encoder.mid.block_1.conv1.bias": "encoder.mid_block.resnets.0.conv1.bias",
624
+ "encoder.mid.block_1.conv1.weight": "encoder.mid_block.resnets.0.conv1.weight",
625
+ "encoder.mid.block_1.conv2.bias": "encoder.mid_block.resnets.0.conv2.bias",
626
+ "encoder.mid.block_1.conv2.weight": "encoder.mid_block.resnets.0.conv2.weight",
627
+ "encoder.mid.block_1.norm1.bias": "encoder.mid_block.resnets.0.norm1.bias",
628
+ "encoder.mid.block_1.norm1.weight": "encoder.mid_block.resnets.0.norm1.weight",
629
+ "encoder.mid.block_1.norm2.bias": "encoder.mid_block.resnets.0.norm2.bias",
630
+ "encoder.mid.block_1.norm2.weight": "encoder.mid_block.resnets.0.norm2.weight",
631
+ "encoder.mid.block_2.conv1.bias": "encoder.mid_block.resnets.1.conv1.bias",
632
+ "encoder.mid.block_2.conv1.weight": "encoder.mid_block.resnets.1.conv1.weight",
633
+ "encoder.mid.block_2.conv2.bias": "encoder.mid_block.resnets.1.conv2.bias",
634
+ "encoder.mid.block_2.conv2.weight": "encoder.mid_block.resnets.1.conv2.weight",
635
+ "encoder.mid.block_2.norm1.bias": "encoder.mid_block.resnets.1.norm1.bias",
636
+ "encoder.mid.block_2.norm1.weight": "encoder.mid_block.resnets.1.norm1.weight",
637
+ "encoder.mid.block_2.norm2.bias": "encoder.mid_block.resnets.1.norm2.bias",
638
+ "encoder.mid.block_2.norm2.weight": "encoder.mid_block.resnets.1.norm2.weight",
639
+ "encoder.norm_out.bias": "encoder.conv_norm_out.bias",
640
+ "encoder.norm_out.weight": "encoder.conv_norm_out.weight",
641
+ "post_quant_conv.bias": "post_quant_conv.bias",
642
+ "post_quant_conv.weight": "post_quant_conv.weight",
643
+ "quant_conv.bias": "quant_conv.bias",
644
+ "quant_conv.weight": "quant_conv.weight"
645
+ }
646
+
647
+
648
+ def get_diffusers_vae_key_from_ldm_key(target_ldm_key, i=None):
649
+ for ldm_key, diffusers_key in vae_ldm_to_diffusers_dict.items():
650
+ if i is not None:
651
+ ldm_key = ldm_key.replace("{i}", str(i))
652
+ diffusers_key = diffusers_key.replace("{i}", str(i))
653
+ if ldm_key == target_ldm_key:
654
+ return diffusers_key
655
+
656
+ if ldm_key in vae_ldm_to_diffusers_dict:
657
+ return vae_ldm_to_diffusers_dict[ldm_key]
658
+ else:
659
+ return None
660
+
661
+ # def get_ldm_vae_key_from_diffusers_key(target_diffusers_key):
662
+ # for ldm_key, diffusers_key in vae_ldm_to_diffusers_dict.items():
663
+ # if diffusers_key == target_diffusers_key:
664
+ # return ldm_key
665
+ # return None
666
+
667
+ def get_ldm_vae_key_from_diffusers_key(target_diffusers_key):
668
+ for ldm_key, diffusers_key in vae_ldm_to_diffusers_dict.items():
669
+ if "{" in diffusers_key: # if we have a placeholder
670
+ # escape special characters in the key, and replace the placeholder with a regex group
671
+ pattern = re.escape(diffusers_key).replace("\\{i\\}", "(\\d+)")
672
+ match = re.match(pattern, target_diffusers_key)
673
+ if match: # if we found a match
674
+ return ldm_key.format(i=match.group(1))
675
+ elif diffusers_key == target_diffusers_key:
676
+ return ldm_key
677
+ return None
678
+
679
+
680
+ vae_keys_squished_on_diffusers = [
681
+ "decoder.mid_block.attentions.0.to_k.weight",
682
+ "decoder.mid_block.attentions.0.to_out.0.weight",
683
+ "decoder.mid_block.attentions.0.to_q.weight",
684
+ "decoder.mid_block.attentions.0.to_v.weight",
685
+ "encoder.mid_block.attentions.0.to_k.weight",
686
+ "encoder.mid_block.attentions.0.to_out.0.weight",
687
+ "encoder.mid_block.attentions.0.to_q.weight",
688
+ "encoder.mid_block.attentions.0.to_v.weight"
689
+ ]
690
+
691
+ def convert_diffusers_back_to_ldm(diffusers_vae):
692
+ new_state_dict = OrderedDict()
693
+ diffusers_state_dict = diffusers_vae.state_dict()
694
+ for key, value in diffusers_state_dict.items():
695
+ val_to_save = value
696
+ if key in vae_keys_squished_on_diffusers:
697
+ val_to_save = value.clone()
698
+ # (512, 512) diffusers and (512, 512, 1, 1) ldm
699
+ val_to_save = val_to_save.unsqueeze(-1).unsqueeze(-1)
700
+ ldm_key = get_ldm_vae_key_from_diffusers_key(key)
701
+ if ldm_key is not None:
702
+ new_state_dict[ldm_key] = val_to_save
703
+ else:
704
+ # for now add current key
705
+ new_state_dict[key] = val_to_save
706
+ return new_state_dict
707
+
708
+
709
+ def convert_ldm_vae_checkpoint(checkpoint, config):
710
+ mapping = {}
711
+ # extract state dict for VAE
712
+ vae_state_dict = {}
713
+ vae_key = "first_stage_model."
714
+ keys = list(checkpoint.keys())
715
+ for key in keys:
716
+ if key.startswith(vae_key):
717
+ vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
718
+ # if len(vae_state_dict) == 0:
719
+ # # 渡されたcheckpointは.ckptから読み込んだcheckpointではなくvaeのstate_dict
720
+ # vae_state_dict = checkpoint
721
+
722
+ new_checkpoint = {}
723
+
724
+ # for key in list(vae_state_dict.keys()):
725
+ # diffusers_key = get_diffusers_vae_key_from_ldm_key(key)
726
+ # if diffusers_key is not None:
727
+ # new_checkpoint[diffusers_key] = vae_state_dict[key]
728
+
729
+ new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]
730
+ new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]
731
+ new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]
732
+ new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]
733
+ new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]
734
+ new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]
735
+
736
+ new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]
737
+ new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]
738
+ new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]
739
+ new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]
740
+ new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]
741
+ new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]
742
+
743
+ new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
744
+ new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
745
+ new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]
746
+ new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]
747
+
748
+ # Retrieves the keys for the encoder down blocks only
749
+ num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})
750
+ down_blocks = {layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in
751
+ range(num_down_blocks)}
752
+
753
+ # Retrieves the keys for the decoder up blocks only
754
+ num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})
755
+ up_blocks = {layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in
756
+ range(num_up_blocks)}
757
+
758
+ for i in range(num_down_blocks):
759
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
760
+
761
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
762
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
763
+ f"encoder.down.{i}.downsample.conv.weight"
764
+ )
765
+ mapping[f"encoder.down.{i}.downsample.conv.weight"] = f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"
766
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
767
+ f"encoder.down.{i}.downsample.conv.bias"
768
+ )
769
+ mapping[f"encoder.down.{i}.downsample.conv.bias"] = f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"
770
+
771
+ paths = renew_vae_resnet_paths(resnets)
772
+ meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}
773
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
774
+
775
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
776
+ num_mid_res_blocks = 2
777
+ for i in range(1, num_mid_res_blocks + 1):
778
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
779
+
780
+ paths = renew_vae_resnet_paths(resnets)
781
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
782
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
783
+
784
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
785
+ paths = renew_vae_attention_paths(mid_attentions)
786
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
787
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
788
+ conv_attn_to_linear(new_checkpoint)
789
+
790
+ for i in range(num_up_blocks):
791
+ block_id = num_up_blocks - 1 - i
792
+ resnets = [key for key in up_blocks[block_id] if
793
+ f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key]
794
+
795
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
796
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
797
+ f"decoder.up.{block_id}.upsample.conv.weight"
798
+ ]
799
+ mapping[f"decoder.up.{block_id}.upsample.conv.weight"] = f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"
800
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
801
+ f"decoder.up.{block_id}.upsample.conv.bias"
802
+ ]
803
+ mapping[f"decoder.up.{block_id}.upsample.conv.bias"] = f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"
804
+
805
+ paths = renew_vae_resnet_paths(resnets)
806
+ meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}
807
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
808
+
809
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
810
+ num_mid_res_blocks = 2
811
+ for i in range(1, num_mid_res_blocks + 1):
812
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
813
+
814
+ paths = renew_vae_resnet_paths(resnets)
815
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
816
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
817
+
818
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
819
+ paths = renew_vae_attention_paths(mid_attentions)
820
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
821
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
822
+ conv_attn_to_linear(new_checkpoint)
823
+ return new_checkpoint
824
+
825
+
826
+ def create_unet_diffusers_config(v2, use_linear_projection_in_v2=False):
827
+ """
828
+ Creates a config for the diffusers based on the config of the LDM model.
829
+ """
830
+ # unet_params = original_config.model.params.unet_config.params
831
+
832
+ block_out_channels = [UNET_PARAMS_MODEL_CHANNELS * mult for mult in UNET_PARAMS_CHANNEL_MULT]
833
+
834
+ down_block_types = []
835
+ resolution = 1
836
+ for i in range(len(block_out_channels)):
837
+ block_type = "CrossAttnDownBlock2D" if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS else "DownBlock2D"
838
+ down_block_types.append(block_type)
839
+ if i != len(block_out_channels) - 1:
840
+ resolution *= 2
841
+
842
+ up_block_types = []
843
+ for i in range(len(block_out_channels)):
844
+ block_type = "CrossAttnUpBlock2D" if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS else "UpBlock2D"
845
+ up_block_types.append(block_type)
846
+ resolution //= 2
847
+
848
+ config = dict(
849
+ sample_size=UNET_PARAMS_IMAGE_SIZE,
850
+ in_channels=UNET_PARAMS_IN_CHANNELS,
851
+ out_channels=UNET_PARAMS_OUT_CHANNELS,
852
+ down_block_types=tuple(down_block_types),
853
+ up_block_types=tuple(up_block_types),
854
+ block_out_channels=tuple(block_out_channels),
855
+ layers_per_block=UNET_PARAMS_NUM_RES_BLOCKS,
856
+ cross_attention_dim=UNET_PARAMS_CONTEXT_DIM if not v2 else V2_UNET_PARAMS_CONTEXT_DIM,
857
+ attention_head_dim=UNET_PARAMS_NUM_HEADS if not v2 else V2_UNET_PARAMS_ATTENTION_HEAD_DIM,
858
+ # use_linear_projection=UNET_PARAMS_USE_LINEAR_PROJECTION if not v2 else V2_UNET_PARAMS_USE_LINEAR_PROJECTION,
859
+ )
860
+ if v2 and use_linear_projection_in_v2:
861
+ config["use_linear_projection"] = True
862
+
863
+ return config
864
+
865
+
866
+ def create_vae_diffusers_config():
867
+ """
868
+ Creates a config for the diffusers based on the config of the LDM model.
869
+ """
870
+ # vae_params = original_config.model.params.first_stage_config.params.ddconfig
871
+ # _ = original_config.model.params.first_stage_config.params.embed_dim
872
+ block_out_channels = [VAE_PARAMS_CH * mult for mult in VAE_PARAMS_CH_MULT]
873
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
874
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
875
+
876
+ config = dict(
877
+ sample_size=VAE_PARAMS_RESOLUTION,
878
+ in_channels=VAE_PARAMS_IN_CHANNELS,
879
+ out_channels=VAE_PARAMS_OUT_CH,
880
+ down_block_types=tuple(down_block_types),
881
+ up_block_types=tuple(up_block_types),
882
+ block_out_channels=tuple(block_out_channels),
883
+ latent_channels=VAE_PARAMS_Z_CHANNELS,
884
+ layers_per_block=VAE_PARAMS_NUM_RES_BLOCKS,
885
+ )
886
+ return config
887
+
888
+
889
+ def convert_ldm_clip_checkpoint_v1(checkpoint):
890
+ keys = list(checkpoint.keys())
891
+ text_model_dict = {}
892
+ for key in keys:
893
+ if key.startswith("cond_stage_model.transformer"):
894
+ text_model_dict[key[len("cond_stage_model.transformer."):]] = checkpoint[key]
895
+ # support checkpoint without position_ids (invalid checkpoint)
896
+ if "text_model.embeddings.position_ids" not in text_model_dict:
897
+ text_model_dict["text_model.embeddings.position_ids"] = torch.arange(77).unsqueeze(0) # 77 is the max length of the text
898
+ return text_model_dict
899
+
900
+
901
+ def convert_ldm_clip_checkpoint_v2(checkpoint, max_length):
902
+ # 嫌になるくらい違うぞ!
903
+ def convert_key(key):
904
+ if not key.startswith("cond_stage_model"):
905
+ return None
906
+
907
+ # common conversion
908
+ key = key.replace("cond_stage_model.model.transformer.", "text_model.encoder.")
909
+ key = key.replace("cond_stage_model.model.", "text_model.")
910
+
911
+ if "resblocks" in key:
912
+ # resblocks conversion
913
+ key = key.replace(".resblocks.", ".layers.")
914
+ if ".ln_" in key:
915
+ key = key.replace(".ln_", ".layer_norm")
916
+ elif ".mlp." in key:
917
+ key = key.replace(".c_fc.", ".fc1.")
918
+ key = key.replace(".c_proj.", ".fc2.")
919
+ elif ".attn.out_proj" in key:
920
+ key = key.replace(".attn.out_proj.", ".self_attn.out_proj.")
921
+ elif ".attn.in_proj" in key:
922
+ key = None # 特殊なので後で処理する
923
+ else:
924
+ raise ValueError(f"unexpected key in SD: {key}")
925
+ elif ".positional_embedding" in key:
926
+ key = key.replace(".positional_embedding", ".embeddings.position_embedding.weight")
927
+ elif ".text_projection" in key:
928
+ key = None # 使われない???
929
+ elif ".logit_scale" in key:
930
+ key = None # 使われない???
931
+ elif ".token_embedding" in key:
932
+ key = key.replace(".token_embedding.weight", ".embeddings.token_embedding.weight")
933
+ elif ".ln_final" in key:
934
+ key = key.replace(".ln_final", ".final_layer_norm")
935
+ return key
936
+
937
+ keys = list(checkpoint.keys())
938
+ new_sd = {}
939
+ for key in keys:
940
+ # remove resblocks 23
941
+ if ".resblocks.23." in key:
942
+ continue
943
+ new_key = convert_key(key)
944
+ if new_key is None:
945
+ continue
946
+ new_sd[new_key] = checkpoint[key]
947
+
948
+ # attnの変換
949
+ for key in keys:
950
+ if ".resblocks.23." in key:
951
+ continue
952
+ if ".resblocks" in key and ".attn.in_proj_" in key:
953
+ # 三つに分割
954
+ values = torch.chunk(checkpoint[key], 3)
955
+
956
+ key_suffix = ".weight" if "weight" in key else ".bias"
957
+ key_pfx = key.replace("cond_stage_model.model.transformer.resblocks.", "text_model.encoder.layers.")
958
+ key_pfx = key_pfx.replace("_weight", "")
959
+ key_pfx = key_pfx.replace("_bias", "")
960
+ key_pfx = key_pfx.replace(".attn.in_proj", ".self_attn.")
961
+ new_sd[key_pfx + "q_proj" + key_suffix] = values[0]
962
+ new_sd[key_pfx + "k_proj" + key_suffix] = values[1]
963
+ new_sd[key_pfx + "v_proj" + key_suffix] = values[2]
964
+
965
+ # rename or add position_ids
966
+ ANOTHER_POSITION_IDS_KEY = "text_model.encoder.text_model.embeddings.position_ids"
967
+ if ANOTHER_POSITION_IDS_KEY in new_sd:
968
+ # waifu diffusion v1.4
969
+ position_ids = new_sd[ANOTHER_POSITION_IDS_KEY]
970
+ del new_sd[ANOTHER_POSITION_IDS_KEY]
971
+ else:
972
+ position_ids = torch.Tensor([list(range(max_length))]).to(torch.int64)
973
+
974
+ new_sd["text_model.embeddings.position_ids"] = position_ids
975
+ return new_sd
976
+
977
+
978
+ # endregion
979
+
980
+
981
+ # region Diffusers->StableDiffusion の変換コード
982
+ # convert_diffusers_to_original_stable_diffusion をコピーして修正している(ASL 2.0)
983
+
984
+
985
+ def conv_transformer_to_linear(checkpoint):
986
+ keys = list(checkpoint.keys())
987
+ tf_keys = ["proj_in.weight", "proj_out.weight"]
988
+ for key in keys:
989
+ if ".".join(key.split(".")[-2:]) in tf_keys:
990
+ if checkpoint[key].ndim > 2:
991
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
992
+
993
+
994
+ def convert_unet_state_dict_to_sd(v2, unet_state_dict):
995
+ unet_conversion_map = [
996
+ # (stable-diffusion, HF Diffusers)
997
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
998
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
999
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
1000
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
1001
+ ("input_blocks.0.0.weight", "conv_in.weight"),
1002
+ ("input_blocks.0.0.bias", "conv_in.bias"),
1003
+ ("out.0.weight", "conv_norm_out.weight"),
1004
+ ("out.0.bias", "conv_norm_out.bias"),
1005
+ ("out.2.weight", "conv_out.weight"),
1006
+ ("out.2.bias", "conv_out.bias"),
1007
+ ]
1008
+
1009
+ unet_conversion_map_resnet = [
1010
+ # (stable-diffusion, HF Diffusers)
1011
+ ("in_layers.0", "norm1"),
1012
+ ("in_layers.2", "conv1"),
1013
+ ("out_layers.0", "norm2"),
1014
+ ("out_layers.3", "conv2"),
1015
+ ("emb_layers.1", "time_emb_proj"),
1016
+ ("skip_connection", "conv_shortcut"),
1017
+ ]
1018
+
1019
+ unet_conversion_map_layer = []
1020
+ for i in range(4):
1021
+ # loop over downblocks/upblocks
1022
+
1023
+ for j in range(2):
1024
+ # loop over resnets/attentions for downblocks
1025
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
1026
+ sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
1027
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
1028
+
1029
+ if i < 3:
1030
+ # no attention layers in down_blocks.3
1031
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
1032
+ sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
1033
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
1034
+
1035
+ for j in range(3):
1036
+ # loop over resnets/attentions for upblocks
1037
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
1038
+ sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
1039
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
1040
+
1041
+ if i > 0:
1042
+ # no attention layers in up_blocks.0
1043
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
1044
+ sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
1045
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
1046
+
1047
+ if i < 3:
1048
+ # no downsample in down_blocks.3
1049
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
1050
+ sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
1051
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
1052
+
1053
+ # no upsample in up_blocks.3
1054
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
1055
+ sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
1056
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
1057
+
1058
+ hf_mid_atn_prefix = "mid_block.attentions.0."
1059
+ sd_mid_atn_prefix = "middle_block.1."
1060
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
1061
+
1062
+ for j in range(2):
1063
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
1064
+ sd_mid_res_prefix = f"middle_block.{2 * j}."
1065
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
1066
+
1067
+ # buyer beware: this is a *brittle* function,
1068
+ # and correct output requires that all of these pieces interact in
1069
+ # the exact order in which I have arranged them.
1070
+ mapping = {k: k for k in unet_state_dict.keys()}
1071
+ for sd_name, hf_name in unet_conversion_map:
1072
+ mapping[hf_name] = sd_name
1073
+ for k, v in mapping.items():
1074
+ if "resnets" in k:
1075
+ for sd_part, hf_part in unet_conversion_map_resnet:
1076
+ v = v.replace(hf_part, sd_part)
1077
+ mapping[k] = v
1078
+ for k, v in mapping.items():
1079
+ for sd_part, hf_part in unet_conversion_map_layer:
1080
+ v = v.replace(hf_part, sd_part)
1081
+ mapping[k] = v
1082
+ new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
1083
+
1084
+ if v2:
1085
+ conv_transformer_to_linear(new_state_dict)
1086
+
1087
+ return new_state_dict
1088
+
1089
+
1090
+ # ================#
1091
+ # VAE Conversion #
1092
+ # ================#
1093
+
1094
+
1095
+ def reshape_weight_for_sd(w):
1096
+ # convert HF linear weights to SD conv2d weights
1097
+ return w.reshape(*w.shape, 1, 1)
1098
+
1099
+
1100
+ def convert_vae_state_dict(vae_state_dict):
1101
+ vae_conversion_map = [
1102
+ # (stable-diffusion, HF Diffusers)
1103
+ ("nin_shortcut", "conv_shortcut"),
1104
+ ("norm_out", "conv_norm_out"),
1105
+ ("mid.attn_1.", "mid_block.attentions.0."),
1106
+ ]
1107
+
1108
+ for i in range(4):
1109
+ # down_blocks have two resnets
1110
+ for j in range(2):
1111
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
1112
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
1113
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
1114
+
1115
+ if i < 3:
1116
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
1117
+ sd_downsample_prefix = f"down.{i}.downsample."
1118
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
1119
+
1120
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
1121
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
1122
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
1123
+
1124
+ # up_blocks have three resnets
1125
+ # also, up blocks in hf are numbered in reverse from sd
1126
+ for j in range(3):
1127
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
1128
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
1129
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
1130
+
1131
+ # this part accounts for mid blocks in both the encoder and the decoder
1132
+ for i in range(2):
1133
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
1134
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
1135
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
1136
+
1137
+ vae_conversion_map_attn = [
1138
+ # (stable-diffusion, HF Diffusers)
1139
+ ("norm.", "group_norm."),
1140
+ ("q.", "query."),
1141
+ ("k.", "key."),
1142
+ ("v.", "value."),
1143
+ ("proj_out.", "proj_attn."),
1144
+ ]
1145
+
1146
+ mapping = {k: k for k in vae_state_dict.keys()}
1147
+ for k, v in mapping.items():
1148
+ for sd_part, hf_part in vae_conversion_map:
1149
+ v = v.replace(hf_part, sd_part)
1150
+ mapping[k] = v
1151
+ for k, v in mapping.items():
1152
+ if "attentions" in k:
1153
+ for sd_part, hf_part in vae_conversion_map_attn:
1154
+ v = v.replace(hf_part, sd_part)
1155
+ mapping[k] = v
1156
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
1157
+ weights_to_convert = ["q", "k", "v", "proj_out"]
1158
+ for k, v in new_state_dict.items():
1159
+ for weight_name in weights_to_convert:
1160
+ if f"mid.attn_1.{weight_name}.weight" in k:
1161
+ # print(f"Reshaping {k} for SD format")
1162
+ new_state_dict[k] = reshape_weight_for_sd(v)
1163
+
1164
+ return new_state_dict
1165
+
1166
+
1167
+ # endregion
1168
+
1169
+ # region 自作のモデル読み書きなど
1170
+
1171
+
1172
+ def is_safetensors(path):
1173
+ return os.path.splitext(path)[1].lower() == ".safetensors"
1174
+
1175
+
1176
+ def load_checkpoint_with_text_encoder_conversion(ckpt_path, device="cpu"):
1177
+ # text encoderの格納形式が違うモデルに対応する ('text_model'がない)
1178
+ TEXT_ENCODER_KEY_REPLACEMENTS = [
1179
+ ("cond_stage_model.transformer.embeddings.", "cond_stage_model.transformer.text_model.embeddings."),
1180
+ ("cond_stage_model.transformer.encoder.", "cond_stage_model.transformer.text_model.encoder."),
1181
+ ("cond_stage_model.transformer.final_layer_norm.", "cond_stage_model.transformer.text_model.final_layer_norm."),
1182
+ ]
1183
+
1184
+ if is_safetensors(ckpt_path):
1185
+ checkpoint = None
1186
+ state_dict = load_file(ckpt_path) # , device) # may causes error
1187
+ else:
1188
+ checkpoint = torch.load(ckpt_path, map_location=device)
1189
+ if "state_dict" in checkpoint:
1190
+ state_dict = checkpoint["state_dict"]
1191
+ else:
1192
+ state_dict = checkpoint
1193
+ checkpoint = None
1194
+
1195
+ key_reps = []
1196
+ for rep_from, rep_to in TEXT_ENCODER_KEY_REPLACEMENTS:
1197
+ for key in state_dict.keys():
1198
+ if key.startswith(rep_from):
1199
+ new_key = rep_to + key[len(rep_from):]
1200
+ key_reps.append((key, new_key))
1201
+
1202
+ for key, new_key in key_reps:
1203
+ state_dict[new_key] = state_dict[key]
1204
+ del state_dict[key]
1205
+
1206
+ return checkpoint, state_dict
1207
+
1208
+
1209
+ # TODO dtype指定の動作が怪しいので確認する text_encoderを指定形式で作れるか未確認
1210
+ def load_models_from_stable_diffusion_checkpoint(v2, ckpt_path, device="cpu", dtype=None,
1211
+ unet_use_linear_projection_in_v2=False):
1212
+ _, state_dict = load_checkpoint_with_text_encoder_conversion(ckpt_path, device)
1213
+
1214
+ # Convert the UNet2DConditionModel model.
1215
+ unet_config = create_unet_diffusers_config(v2, unet_use_linear_projection_in_v2)
1216
+ converted_unet_checkpoint = convert_ldm_unet_checkpoint(v2, state_dict, unet_config)
1217
+
1218
+ unet = UNet2DConditionModel(**unet_config).to(device)
1219
+ info = unet.load_state_dict(converted_unet_checkpoint)
1220
+ print("loading u-net:", info)
1221
+
1222
+ # Convert the VAE model.
1223
+ vae_config = create_vae_diffusers_config()
1224
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(state_dict, vae_config)
1225
+
1226
+ vae = AutoencoderKL(**vae_config).to(device)
1227
+ info = vae.load_state_dict(converted_vae_checkpoint)
1228
+ print("loading vae:", info)
1229
+
1230
+ # convert text_model
1231
+ if v2:
1232
+ converted_text_encoder_checkpoint = convert_ldm_clip_checkpoint_v2(state_dict, 77)
1233
+ cfg = CLIPTextConfig(
1234
+ vocab_size=49408,
1235
+ hidden_size=1024,
1236
+ intermediate_size=4096,
1237
+ num_hidden_layers=23,
1238
+ num_attention_heads=16,
1239
+ max_position_embeddings=77,
1240
+ hidden_act="gelu",
1241
+ layer_norm_eps=1e-05,
1242
+ dropout=0.0,
1243
+ attention_dropout=0.0,
1244
+ initializer_range=0.02,
1245
+ initializer_factor=1.0,
1246
+ pad_token_id=1,
1247
+ bos_token_id=0,
1248
+ eos_token_id=2,
1249
+ model_type="clip_text_model",
1250
+ projection_dim=512,
1251
+ torch_dtype="float32",
1252
+ transformers_version="4.25.0.dev0",
1253
+ )
1254
+ text_model = CLIPTextModel._from_config(cfg)
1255
+ info = text_model.load_state_dict(converted_text_encoder_checkpoint)
1256
+ else:
1257
+ converted_text_encoder_checkpoint = convert_ldm_clip_checkpoint_v1(state_dict)
1258
+
1259
+ logging.set_verbosity_error() # don't show annoying warning
1260
+ text_model = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(device)
1261
+ logging.set_verbosity_warning()
1262
+
1263
+ # latest transformers doesnt have position ids. Do we remove it?
1264
+ if "text_model.embeddings.position_ids" not in text_model.state_dict():
1265
+ del converted_text_encoder_checkpoint["text_model.embeddings.position_ids"]
1266
+
1267
+ info = text_model.load_state_dict(converted_text_encoder_checkpoint)
1268
+ print("loading text encoder:", info)
1269
+
1270
+ return text_model, vae, unet
1271
+
1272
+
1273
+ def convert_text_encoder_state_dict_to_sd_v2(checkpoint, make_dummy_weights=False):
1274
+ def convert_key(key):
1275
+ # position_idsの除去
1276
+ if ".position_ids" in key:
1277
+ return None
1278
+
1279
+ # common
1280
+ key = key.replace("text_model.encoder.", "transformer.")
1281
+ key = key.replace("text_model.", "")
1282
+ if "layers" in key:
1283
+ # resblocks conversion
1284
+ key = key.replace(".layers.", ".resblocks.")
1285
+ if ".layer_norm" in key:
1286
+ key = key.replace(".layer_norm", ".ln_")
1287
+ elif ".mlp." in key:
1288
+ key = key.replace(".fc1.", ".c_fc.")
1289
+ key = key.replace(".fc2.", ".c_proj.")
1290
+ elif ".self_attn.out_proj" in key:
1291
+ key = key.replace(".self_attn.out_proj.", ".attn.out_proj.")
1292
+ elif ".self_attn." in key:
1293
+ key = None # 特殊なので後で処理する
1294
+ else:
1295
+ raise ValueError(f"unexpected key in DiffUsers model: {key}")
1296
+ elif ".position_embedding" in key:
1297
+ key = key.replace("embeddings.position_embedding.weight", "positional_embedding")
1298
+ elif ".token_embedding" in key:
1299
+ key = key.replace("embeddings.token_embedding.weight", "token_embedding.weight")
1300
+ elif "final_layer_norm" in key:
1301
+ key = key.replace("final_layer_norm", "ln_final")
1302
+ return key
1303
+
1304
+ keys = list(checkpoint.keys())
1305
+ new_sd = {}
1306
+ for key in keys:
1307
+ new_key = convert_key(key)
1308
+ if new_key is None:
1309
+ continue
1310
+ new_sd[new_key] = checkpoint[key]
1311
+
1312
+ # attnの変換
1313
+ for key in keys:
1314
+ if "layers" in key and "q_proj" in key:
1315
+ # 三つを結合
1316
+ key_q = key
1317
+ key_k = key.replace("q_proj", "k_proj")
1318
+ key_v = key.replace("q_proj", "v_proj")
1319
+
1320
+ value_q = checkpoint[key_q]
1321
+ value_k = checkpoint[key_k]
1322
+ value_v = checkpoint[key_v]
1323
+ value = torch.cat([value_q, value_k, value_v])
1324
+
1325
+ new_key = key.replace("text_model.encoder.layers.", "transformer.resblocks.")
1326
+ new_key = new_key.replace(".self_attn.q_proj.", ".attn.in_proj_")
1327
+ new_sd[new_key] = value
1328
+
1329
+ # 最後の層などを捏造するか
1330
+ if make_dummy_weights:
1331
+ print("make dummy weights for resblock.23, text_projection and logit scale.")
1332
+ keys = list(new_sd.keys())
1333
+ for key in keys:
1334
+ if key.startswith("transformer.resblocks.22."):
1335
+ new_sd[key.replace(".22.", ".23.")] = new_sd[key].clone() # copyしないとsafetensorsの保存で落ちる
1336
+
1337
+ # Diffusersに含まれない重みを作っておく
1338
+ new_sd["text_projection"] = torch.ones((1024, 1024), dtype=new_sd[keys[0]].dtype, device=new_sd[keys[0]].device)
1339
+ new_sd["logit_scale"] = torch.tensor(1)
1340
+
1341
+ return new_sd
1342
+
1343
+
1344
+ def save_stable_diffusion_checkpoint(v2, output_file, text_encoder, unet, ckpt_path, epochs, steps, save_dtype=None,
1345
+ vae=None):
1346
+ if ckpt_path is not None:
1347
+ # epoch/stepを参照する。またVAEがメモリ上にないときなど、もう一度VAEを含めて読み込む
1348
+ checkpoint, state_dict = load_checkpoint_with_text_encoder_conversion(ckpt_path)
1349
+ if checkpoint is None: # safetensors または state_dictのckpt
1350
+ checkpoint = {}
1351
+ strict = False
1352
+ else:
1353
+ strict = True
1354
+ if "state_dict" in state_dict:
1355
+ del state_dict["state_dict"]
1356
+ else:
1357
+ # 新しく作る
1358
+ assert vae is not None, "VAE is required to save a checkpoint without a given checkpoint"
1359
+ checkpoint = {}
1360
+ state_dict = {}
1361
+ strict = False
1362
+
1363
+ def update_sd(prefix, sd):
1364
+ for k, v in sd.items():
1365
+ key = prefix + k
1366
+ assert not strict or key in state_dict, f"Illegal key in save SD: {key}"
1367
+ if save_dtype is not None:
1368
+ v = v.detach().clone().to("cpu").to(save_dtype)
1369
+ state_dict[key] = v
1370
+
1371
+ # Convert the UNet model
1372
+ unet_state_dict = convert_unet_state_dict_to_sd(v2, unet.state_dict())
1373
+ update_sd("model.diffusion_model.", unet_state_dict)
1374
+
1375
+ # Convert the text encoder model
1376
+ if v2:
1377
+ make_dummy = ckpt_path is None # 参照元のcheckpointがない場合は最後の層を前の層から複製して作るなどダミーの重みを入れる
1378
+ text_enc_dict = convert_text_encoder_state_dict_to_sd_v2(text_encoder.state_dict(), make_dummy)
1379
+ update_sd("cond_stage_model.model.", text_enc_dict)
1380
+ else:
1381
+ text_enc_dict = text_encoder.state_dict()
1382
+ update_sd("cond_stage_model.transformer.", text_enc_dict)
1383
+
1384
+ # Convert the VAE
1385
+ if vae is not None:
1386
+ vae_dict = convert_vae_state_dict(vae.state_dict())
1387
+ update_sd("first_stage_model.", vae_dict)
1388
+
1389
+ # Put together new checkpoint
1390
+ key_count = len(state_dict.keys())
1391
+ new_ckpt = {"state_dict": state_dict}
1392
+
1393
+ # epoch and global_step are sometimes not int
1394
+ try:
1395
+ if "epoch" in checkpoint:
1396
+ epochs += checkpoint["epoch"]
1397
+ if "global_step" in checkpoint:
1398
+ steps += checkpoint["global_step"]
1399
+ except:
1400
+ pass
1401
+
1402
+ new_ckpt["epoch"] = epochs
1403
+ new_ckpt["global_step"] = steps
1404
+
1405
+ if is_safetensors(output_file):
1406
+ # TODO Tensor以外のdictの値を削除したほうがいいか
1407
+ save_file(state_dict, output_file)
1408
+ else:
1409
+ torch.save(new_ckpt, output_file)
1410
+
1411
+ return key_count
1412
+
1413
+
1414
+ def save_diffusers_checkpoint(v2, output_dir, text_encoder, unet, pretrained_model_name_or_path, vae=None,
1415
+ use_safetensors=False):
1416
+ if pretrained_model_name_or_path is None:
1417
+ # load default settings for v1/v2
1418
+ if v2:
1419
+ pretrained_model_name_or_path = DIFFUSERS_REF_MODEL_ID_V2
1420
+ else:
1421
+ pretrained_model_name_or_path = DIFFUSERS_REF_MODEL_ID_V1
1422
+
1423
+ scheduler = DDIMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
1424
+ tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer")
1425
+ if vae is None:
1426
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
1427
+
1428
+ pipeline = StableDiffusionPipeline(
1429
+ unet=unet,
1430
+ text_encoder=text_encoder,
1431
+ vae=vae,
1432
+ scheduler=scheduler,
1433
+ tokenizer=tokenizer,
1434
+ safety_checker=None,
1435
+ feature_extractor=None,
1436
+ requires_safety_checker=None,
1437
+ )
1438
+ pipeline.save_pretrained(output_dir, safe_serialization=use_safetensors)
1439
+
1440
+
1441
+ VAE_PREFIX = "first_stage_model."
1442
+
1443
+
1444
+ def load_vae(vae_id, dtype):
1445
+ print(f"load VAE: {vae_id}")
1446
+ if os.path.isdir(vae_id) or not os.path.isfile(vae_id):
1447
+ # Diffusers local/remote
1448
+ try:
1449
+ vae = AutoencoderKL.from_pretrained(vae_id, subfolder=None, torch_dtype=dtype)
1450
+ except EnvironmentError as e:
1451
+ print(f"exception occurs in loading vae: {e}")
1452
+ print("retry with subfolder='vae'")
1453
+ vae = AutoencoderKL.from_pretrained(vae_id, subfolder="vae", torch_dtype=dtype)
1454
+ return vae
1455
+
1456
+ # local
1457
+ vae_config = create_vae_diffusers_config()
1458
+
1459
+ if vae_id.endswith(".bin"):
1460
+ # SD 1.5 VAE on Huggingface
1461
+ converted_vae_checkpoint = torch.load(vae_id, map_location="cpu")
1462
+ else:
1463
+ # StableDiffusion
1464
+ vae_model = load_file(vae_id, "cpu") if is_safetensors(vae_id) else torch.load(vae_id, map_location="cpu")
1465
+ vae_sd = vae_model["state_dict"] if "state_dict" in vae_model else vae_model
1466
+
1467
+ # vae only or full model
1468
+ full_model = False
1469
+ for vae_key in vae_sd:
1470
+ if vae_key.startswith(VAE_PREFIX):
1471
+ full_model = True
1472
+ break
1473
+ if not full_model:
1474
+ sd = {}
1475
+ for key, value in vae_sd.items():
1476
+ sd[VAE_PREFIX + key] = value
1477
+ vae_sd = sd
1478
+ del sd
1479
+
1480
+ # Convert the VAE model.
1481
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(vae_sd, vae_config)
1482
+
1483
+ vae = AutoencoderKL(**vae_config)
1484
+ vae.load_state_dict(converted_vae_checkpoint)
1485
+ return vae
1486
+
1487
+
1488
+ # endregion
1489
+
1490
+
1491
+ def make_bucket_resolutions(max_reso, min_size=256, max_size=1024, divisible=64):
1492
+ max_width, max_height = max_reso
1493
+ max_area = (max_width // divisible) * (max_height // divisible)
1494
+
1495
+ resos = set()
1496
+
1497
+ size = int(math.sqrt(max_area)) * divisible
1498
+ resos.add((size, size))
1499
+
1500
+ size = min_size
1501
+ while size <= max_size:
1502
+ width = size
1503
+ height = min(max_size, (max_area // (width // divisible)) * divisible)
1504
+ resos.add((width, height))
1505
+ resos.add((height, width))
1506
+
1507
+ # # make additional resos
1508
+ # if width >= height and width - divisible >= min_size:
1509
+ # resos.add((width - divisible, height))
1510
+ # resos.add((height, width - divisible))
1511
+ # if height >= width and height - divisible >= min_size:
1512
+ # resos.add((width, height - divisible))
1513
+ # resos.add((height - divisible, width))
1514
+
1515
+ size += divisible
1516
+
1517
+ resos = list(resos)
1518
+ resos.sort()
1519
+ return resos
1520
+
1521
+
1522
+ if __name__ == "__main__":
1523
+ resos = make_bucket_resolutions((512, 768))
1524
+ print(len(resos))
1525
+ print(resos)
1526
+ aspect_ratios = [w / h for w, h in resos]
1527
+ print(aspect_ratios)
1528
+
1529
+ ars = set()
1530
+ for ar in aspect_ratios:
1531
+ if ar in ars:
1532
+ print("error! duplicate ar:", ar)
1533
+ ars.add(ar)
toolkit/layers.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from torch.utils.checkpoint import checkpoint
5
+
6
+
7
+ class ReductionKernel(nn.Module):
8
+ # Tensorflow
9
+ def __init__(self, in_channels, kernel_size=2, dtype=torch.float32, device=None):
10
+ if device is None:
11
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
12
+ super(ReductionKernel, self).__init__()
13
+ self.kernel_size = kernel_size
14
+ self.in_channels = in_channels
15
+ numpy_kernel = self.build_kernel()
16
+ self.kernel = torch.from_numpy(numpy_kernel).to(device=device, dtype=dtype)
17
+
18
+ def build_kernel(self):
19
+ # tensorflow kernel is (height, width, in_channels, out_channels)
20
+ # pytorch kernel is (out_channels, in_channels, height, width)
21
+ kernel_size = self.kernel_size
22
+ channels = self.in_channels
23
+ kernel_shape = [channels, channels, kernel_size, kernel_size]
24
+ kernel = np.zeros(kernel_shape, np.float32)
25
+
26
+ kernel_value = 1.0 / (kernel_size * kernel_size)
27
+ for i in range(0, channels):
28
+ kernel[i, i, :, :] = kernel_value
29
+ return kernel
30
+
31
+ def forward(self, x):
32
+ return nn.functional.conv2d(x, self.kernel, stride=self.kernel_size, padding=0, groups=1)
33
+
34
+
35
+ class CheckpointGradients(nn.Module):
36
+ def __init__(self, is_gradient_checkpointing=True):
37
+ super(CheckpointGradients, self).__init__()
38
+ self.is_gradient_checkpointing = is_gradient_checkpointing
39
+
40
+ def forward(self, module, *args, num_chunks=1):
41
+ if self.is_gradient_checkpointing:
42
+ return checkpoint(module, *args, num_chunks=self.num_chunks)
43
+ else:
44
+ return module(*args)
toolkit/logging_aitk.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import OrderedDict, Optional
2
+ from PIL import Image
3
+
4
+ from toolkit.config_modules import LoggingConfig
5
+ import os
6
+ import sqlite3
7
+ import time
8
+ from typing import Any, Dict, Tuple, List
9
+
10
+
11
+ # Base logger class
12
+ # This class does nothing, it's just a placeholder
13
+ class EmptyLogger:
14
+ def __init__(self, *args, **kwargs) -> None:
15
+ pass
16
+
17
+ # start logging the training
18
+ def start(self):
19
+ pass
20
+
21
+ # collect the log to send
22
+ def log(self, *args, **kwargs):
23
+ pass
24
+
25
+ # send the log
26
+ def commit(self, step: Optional[int] = None):
27
+ pass
28
+
29
+ # log image
30
+ def log_image(self, *args, **kwargs):
31
+ pass
32
+
33
+ # finish logging
34
+ def finish(self):
35
+ pass
36
+
37
+
38
+ # Wandb logger class
39
+ # This class logs the data to wandb
40
+ class WandbLogger(EmptyLogger):
41
+ def __init__(self, project: str, run_name: str | None, config: OrderedDict) -> None:
42
+ self.project = project
43
+ self.run_name = run_name
44
+ self.config = config
45
+
46
+ def start(self):
47
+ try:
48
+ import wandb
49
+ except ImportError:
50
+ raise ImportError(
51
+ "Failed to import wandb. Please install wandb by running `pip install wandb`"
52
+ )
53
+
54
+ # send the whole config to wandb
55
+ run = wandb.init(project=self.project, name=self.run_name, config=self.config)
56
+ self.run = run
57
+ self._log = wandb.log # log function
58
+ self._image = wandb.Image # image object
59
+
60
+ def log(self, *args, **kwargs):
61
+ # when commit is False, wandb increments the step,
62
+ # but we don't want that to happen, so we set commit=False
63
+ self._log(*args, **kwargs, commit=False)
64
+
65
+ def commit(self, step: Optional[int] = None):
66
+ # after overall one step is done, we commit the log
67
+ # by log empty object with commit=True
68
+ self._log({}, step=step, commit=True)
69
+
70
+ def log_image(
71
+ self,
72
+ image: Image,
73
+ id, # sample index
74
+ caption: str | None = None, # positive prompt
75
+ *args,
76
+ **kwargs,
77
+ ):
78
+ # create a wandb image object and log it
79
+ image = self._image(image, caption=caption, *args, **kwargs)
80
+ self._log({f"sample_{id}": image}, commit=False)
81
+
82
+ def finish(self):
83
+ self.run.finish()
84
+
85
+
86
+ class UILogger:
87
+ def __init__(
88
+ self,
89
+ log_file: str,
90
+ flush_every_n: int = 256,
91
+ flush_every_secs: float = 0.25,
92
+ ) -> None:
93
+ self.log_file = log_file
94
+ self._log_to_commit: Dict[str, Any] = {}
95
+
96
+ self._con: Optional[sqlite3.Connection] = None
97
+ self._started = False
98
+
99
+ self._step_counter = 0
100
+
101
+ # buffered writes
102
+ self._pending_steps: List[Tuple[int, float]] = []
103
+ self._pending_metrics: List[
104
+ Tuple[int, str, Optional[float], Optional[str]]
105
+ ] = []
106
+ self._pending_key_minmax: Dict[str, Tuple[int, int]] = {}
107
+
108
+ self._flush_every_n = int(flush_every_n)
109
+ self._flush_every_secs = float(flush_every_secs)
110
+ self._last_flush = time.time()
111
+
112
+ self._first_commit_done = False
113
+
114
+ # start logging the training
115
+ def start(self):
116
+ if self._started:
117
+ return
118
+
119
+ parent = os.path.dirname(os.path.abspath(self.log_file))
120
+ if parent and not os.path.exists(parent):
121
+ os.makedirs(parent, exist_ok=True)
122
+
123
+ self._con = sqlite3.connect(self.log_file, timeout=30.0, isolation_level=None)
124
+ self._con.execute("PRAGMA journal_mode=WAL;")
125
+ self._con.execute("PRAGMA synchronous=NORMAL;")
126
+ self._con.execute("PRAGMA temp_store=MEMORY;")
127
+ self._con.execute("PRAGMA foreign_keys=ON;")
128
+ self._con.execute("PRAGMA busy_timeout=30000;")
129
+
130
+ self._init_schema(self._con)
131
+
132
+ self._started = True
133
+ self._last_flush = time.time()
134
+
135
+ # collect the log to send
136
+ def log(self, log_dict):
137
+ # log_dict is like {'learning_rate': learning_rate}
138
+ if not isinstance(log_dict, dict):
139
+ raise TypeError("log_dict must be a dict")
140
+ self._log_to_commit.update(log_dict)
141
+
142
+ # send the log
143
+ def commit(self, step: Optional[int] = None):
144
+ if not self._started:
145
+ self.start()
146
+
147
+ if not self._log_to_commit:
148
+ return
149
+
150
+ if step is None:
151
+ step = self._step_counter
152
+ self._step_counter += 1
153
+ else:
154
+ step = int(step)
155
+ if step >= self._step_counter:
156
+ self._step_counter = step + 1
157
+
158
+ # On the first commit of this run, prune any rows from a prior run
159
+ # whose step is greater than where we are resuming from.
160
+ if not self._first_commit_done:
161
+ self._prune_future_steps(step)
162
+ self._first_commit_done = True
163
+
164
+ wall_time = time.time()
165
+
166
+ # buffer step row (upsert later)
167
+ self._pending_steps.append((step, wall_time))
168
+
169
+ # buffer metrics rows + key min/max updates
170
+ for k, v in self._log_to_commit.items():
171
+ k = k if isinstance(k, str) else str(k)
172
+ vr, vt = self._coerce_value(v)
173
+
174
+ self._pending_metrics.append((step, k, vr, vt))
175
+
176
+ if k in self._pending_key_minmax:
177
+ lo, hi = self._pending_key_minmax[k]
178
+ if step < lo:
179
+ lo = step
180
+ if step > hi:
181
+ hi = step
182
+ self._pending_key_minmax[k] = (lo, hi)
183
+ else:
184
+ self._pending_key_minmax[k] = (step, step)
185
+
186
+ self._log_to_commit = {}
187
+
188
+ # flush conditions
189
+ now = time.time()
190
+ if (
191
+ len(self._pending_metrics) >= self._flush_every_n
192
+ or (now - self._last_flush) >= self._flush_every_secs
193
+ ):
194
+ self._flush()
195
+
196
+ # log image
197
+ def log_image(self, *args, **kwargs):
198
+ # this doesnt log images for now
199
+ pass
200
+
201
+ # finish logging
202
+ def finish(self):
203
+ if not self._started:
204
+ return
205
+
206
+ self._flush()
207
+
208
+ assert self._con is not None
209
+ self._con.close()
210
+ self._con = None
211
+ self._started = False
212
+
213
+ # -------------------------
214
+ # internal
215
+ # -------------------------
216
+
217
+ def _init_schema(self, con: sqlite3.Connection) -> None:
218
+ con.execute("BEGIN;")
219
+
220
+ con.execute("""
221
+ CREATE TABLE IF NOT EXISTS steps (
222
+ step INTEGER PRIMARY KEY,
223
+ wall_time REAL NOT NULL
224
+ );
225
+ """)
226
+
227
+ con.execute("""
228
+ CREATE TABLE IF NOT EXISTS metric_keys (
229
+ key TEXT PRIMARY KEY,
230
+ first_seen_step INTEGER,
231
+ last_seen_step INTEGER
232
+ );
233
+ """)
234
+
235
+ con.execute("""
236
+ CREATE TABLE IF NOT EXISTS metrics (
237
+ step INTEGER NOT NULL,
238
+ key TEXT NOT NULL,
239
+ value_real REAL,
240
+ value_text TEXT,
241
+ PRIMARY KEY (step, key),
242
+ FOREIGN KEY (step) REFERENCES steps(step) ON DELETE CASCADE
243
+ );
244
+ """)
245
+
246
+ con.execute(
247
+ "CREATE INDEX IF NOT EXISTS idx_metrics_key_step ON metrics (key, step);"
248
+ )
249
+
250
+ con.execute("COMMIT;")
251
+
252
+ def _coerce_value(self, v: Any) -> Tuple[Optional[float], Optional[str]]:
253
+ if v is None:
254
+ return None, None
255
+ if isinstance(v, bool):
256
+ return float(int(v)), None
257
+ if isinstance(v, (int, float)):
258
+ return float(v), None
259
+ try:
260
+ return float(v), None # type: ignore[arg-type]
261
+ except Exception:
262
+ return None, str(v)
263
+
264
+ def _prune_future_steps(self, current_step: int) -> None:
265
+ assert self._con is not None
266
+ con = self._con
267
+
268
+ con.execute("BEGIN;")
269
+ # metrics rows cascade via FK ON DELETE CASCADE
270
+ con.execute("DELETE FROM steps WHERE step > ?;", (current_step,))
271
+ # drop any keys that no longer have any metrics, and clamp last_seen_step
272
+ con.execute(
273
+ "DELETE FROM metric_keys "
274
+ "WHERE NOT EXISTS (SELECT 1 FROM metrics WHERE metrics.key = metric_keys.key);"
275
+ )
276
+ con.execute(
277
+ "UPDATE metric_keys "
278
+ "SET last_seen_step = (SELECT MAX(step) FROM metrics WHERE metrics.key = metric_keys.key) "
279
+ "WHERE last_seen_step > ?;",
280
+ (current_step,),
281
+ )
282
+ con.execute("COMMIT;")
283
+
284
+ def _flush(self) -> None:
285
+ if not self._pending_steps and not self._pending_metrics:
286
+ return
287
+
288
+ assert self._con is not None
289
+ con = self._con
290
+
291
+ con.execute("BEGIN;")
292
+
293
+ # steps upsert
294
+ if self._pending_steps:
295
+ con.executemany(
296
+ "INSERT INTO steps(step, wall_time) VALUES(?, ?) "
297
+ "ON CONFLICT(step) DO UPDATE SET wall_time=excluded.wall_time;",
298
+ self._pending_steps,
299
+ )
300
+
301
+ # keys table upsert (maintains list of keys + seen range)
302
+ if self._pending_key_minmax:
303
+ con.executemany(
304
+ "INSERT INTO metric_keys(key, first_seen_step, last_seen_step) VALUES(?, ?, ?) "
305
+ "ON CONFLICT(key) DO UPDATE SET "
306
+ "first_seen_step=MIN(metric_keys.first_seen_step, excluded.first_seen_step), "
307
+ "last_seen_step=MAX(metric_keys.last_seen_step, excluded.last_seen_step);",
308
+ [(k, lo, hi) for k, (lo, hi) in self._pending_key_minmax.items()],
309
+ )
310
+
311
+ # metrics upsert
312
+ if self._pending_metrics:
313
+ con.executemany(
314
+ "INSERT INTO metrics(step, key, value_real, value_text) VALUES(?, ?, ?, ?) "
315
+ "ON CONFLICT(step, key) DO UPDATE SET "
316
+ "value_real=excluded.value_real, value_text=excluded.value_text;",
317
+ self._pending_metrics,
318
+ )
319
+
320
+ con.execute("COMMIT;")
321
+
322
+ self._pending_steps.clear()
323
+ self._pending_metrics.clear()
324
+ self._pending_key_minmax.clear()
325
+ self._last_flush = time.time()
326
+
327
+
328
+ # create logger based on the logging config
329
+ def create_logger(
330
+ logging_config: LoggingConfig,
331
+ all_config: OrderedDict,
332
+ save_root: Optional[str] = None,
333
+ ):
334
+ if logging_config.use_wandb:
335
+ project_name = logging_config.project_name
336
+ run_name = logging_config.run_name
337
+ return WandbLogger(project=project_name, run_name=run_name, config=all_config)
338
+ elif logging_config.use_ui_logger:
339
+ if save_root is None:
340
+ raise ValueError("save_root must be provided when using UILogger")
341
+ log_file = os.path.join(save_root, "loss_log.db")
342
+ return UILogger(log_file=log_file)
343
+ else:
344
+ return EmptyLogger()
toolkit/lora_special.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import math
4
+ import weakref
5
+ import os
6
+ import re
7
+ import sys
8
+ from typing import List, Optional, Dict, Type, Union
9
+ import torch
10
+ from diffusers import UNet2DConditionModel, PixArtTransformer2DModel, AuraFlowTransformer2DModel, WanTransformer3DModel
11
+ from transformers import CLIPTextModel
12
+ from toolkit.models.lokr import LokrModule
13
+
14
+ from .config_modules import NetworkConfig
15
+ from .lorm import count_parameters
16
+ from .network_mixins import ToolkitNetworkMixin, ToolkitModuleMixin, ExtractableModuleMixin
17
+
18
+ from toolkit.kohya_lora import LoRANetwork
19
+ from toolkit.models.DoRA import DoRAModule
20
+ from typing import TYPE_CHECKING
21
+
22
+ if TYPE_CHECKING:
23
+ from toolkit.stable_diffusion_model import StableDiffusion
24
+
25
+ RE_UPDOWN = re.compile(r"(up|down)_blocks_(\d+)_(resnets|upsamplers|downsamplers|attentions)_(\d+)_")
26
+
27
+
28
+ # diffusers specific stuff
29
+ LINEAR_MODULES = [
30
+ 'Linear',
31
+ 'LoRACompatibleLinear',
32
+ 'QLinear',
33
+ # 'GroupNorm',
34
+ ]
35
+ CONV_MODULES = [
36
+ 'Conv2d',
37
+ 'LoRACompatibleConv',
38
+ 'QConv2d',
39
+ ]
40
+
41
+ class IdentityModule(torch.nn.Module):
42
+ def forward(self, x):
43
+ return x
44
+
45
+ class LoRAModule(ToolkitModuleMixin, ExtractableModuleMixin, torch.nn.Module):
46
+ """
47
+ replaces forward method of the original Linear, instead of replacing the original Linear module.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ lora_name,
53
+ org_module: torch.nn.Module,
54
+ multiplier=1.0,
55
+ lora_dim=4,
56
+ alpha=1,
57
+ dropout=None,
58
+ rank_dropout=None,
59
+ module_dropout=None,
60
+ network: 'LoRASpecialNetwork' = None,
61
+ use_bias: bool = False,
62
+ is_ara: bool = False,
63
+ **kwargs
64
+ ):
65
+ self.can_merge_in = True
66
+ """if alpha == 0 or None, alpha is rank (no scaling)."""
67
+ ToolkitModuleMixin.__init__(self, network=network)
68
+ torch.nn.Module.__init__(self)
69
+ self.lora_name = lora_name
70
+ self.orig_module_ref = weakref.ref(org_module)
71
+ self.scalar = torch.tensor(1.0, device=org_module.weight.device)
72
+
73
+ # if is ara lora module, mark it on the layer so memory manager can handle it
74
+ if is_ara:
75
+ org_module.ara_lora_ref = weakref.ref(self)
76
+ # check if parent has bias. if not force use_bias to False
77
+ if org_module.bias is None:
78
+ use_bias = False
79
+
80
+ if org_module.__class__.__name__ in CONV_MODULES:
81
+ in_dim = org_module.in_channels
82
+ out_dim = org_module.out_channels
83
+ else:
84
+ in_dim = org_module.in_features
85
+ out_dim = org_module.out_features
86
+
87
+ # if limit_rank:
88
+ # self.lora_dim = min(lora_dim, in_dim, out_dim)
89
+ # if self.lora_dim != lora_dim:
90
+ # print(f"{lora_name} dim (rank) is changed to: {self.lora_dim}")
91
+ # else:
92
+ self.lora_dim = lora_dim
93
+ self.full_rank = network.network_type.lower() == "fullrank"
94
+
95
+ if org_module.__class__.__name__ in CONV_MODULES:
96
+ kernel_size = org_module.kernel_size
97
+ stride = org_module.stride
98
+ padding = org_module.padding
99
+ if self.full_rank:
100
+ self.lora_down = torch.nn.Conv2d(in_dim, out_dim, kernel_size, stride, padding, bias=False)
101
+ self.lora_up = IdentityModule()
102
+ else:
103
+ self.lora_down = torch.nn.Conv2d(in_dim, self.lora_dim, kernel_size, stride, padding, bias=False)
104
+ self.lora_up = torch.nn.Conv2d(self.lora_dim, out_dim, (1, 1), (1, 1), bias=use_bias)
105
+ else:
106
+ if self.full_rank:
107
+ self.lora_down = torch.nn.Linear(in_dim, out_dim, bias=False)
108
+ self.lora_up = IdentityModule()
109
+ else:
110
+ self.lora_down = torch.nn.Linear(in_dim, self.lora_dim, bias=False)
111
+ self.lora_up = torch.nn.Linear(self.lora_dim, out_dim, bias=use_bias)
112
+
113
+ if type(alpha) == torch.Tensor:
114
+ alpha = alpha.detach().float().numpy() # without casting, bf16 causes error
115
+ alpha = self.lora_dim if alpha is None or alpha == 0 else alpha
116
+ self.scale = alpha / self.lora_dim
117
+ self.register_buffer("alpha", torch.tensor(alpha)) # 定数として扱える
118
+
119
+ # same as microsoft's
120
+ torch.nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))
121
+ if not self.full_rank:
122
+ torch.nn.init.zeros_(self.lora_up.weight)
123
+
124
+ self.multiplier: Union[float, List[float]] = multiplier
125
+ # wrap the original module so it doesn't get weights updated
126
+ self.org_module = [org_module]
127
+ self.dropout = dropout
128
+ self.rank_dropout = rank_dropout
129
+ self.module_dropout = module_dropout
130
+ self.is_checkpointing = False
131
+
132
+ def apply_to(self):
133
+ self.org_forward = self.org_module[0].forward
134
+ self.org_module[0].forward = self.forward
135
+ # del self.org_module
136
+
137
+
138
+ class LoRASpecialNetwork(ToolkitNetworkMixin, LoRANetwork):
139
+ NUM_OF_BLOCKS = 12 # フルモデル相当でのup,downの層の数
140
+
141
+ # UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel"]
142
+ # UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel", "ResnetBlock2D"]
143
+ UNET_TARGET_REPLACE_MODULE = ["UNet2DConditionModel"]
144
+ # UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
145
+ UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["UNet2DConditionModel"]
146
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
147
+ LORA_PREFIX_UNET = "lora_unet"
148
+ PEFT_PREFIX_UNET = "unet"
149
+ LORA_PREFIX_TEXT_ENCODER = "lora_te"
150
+
151
+ # SDXL: must starts with LORA_PREFIX_TEXT_ENCODER
152
+ LORA_PREFIX_TEXT_ENCODER1 = "lora_te1"
153
+ LORA_PREFIX_TEXT_ENCODER2 = "lora_te2"
154
+
155
+ def __init__(
156
+ self,
157
+ text_encoder: Union[List[CLIPTextModel], CLIPTextModel],
158
+ unet,
159
+ multiplier: float = 1.0,
160
+ lora_dim: int = 4,
161
+ alpha: float = 1,
162
+ dropout: Optional[float] = None,
163
+ rank_dropout: Optional[float] = None,
164
+ module_dropout: Optional[float] = None,
165
+ conv_lora_dim: Optional[int] = None,
166
+ conv_alpha: Optional[float] = None,
167
+ block_dims: Optional[List[int]] = None,
168
+ block_alphas: Optional[List[float]] = None,
169
+ conv_block_dims: Optional[List[int]] = None,
170
+ conv_block_alphas: Optional[List[float]] = None,
171
+ modules_dim: Optional[Dict[str, int]] = None,
172
+ modules_alpha: Optional[Dict[str, int]] = None,
173
+ module_class: Type[object] = LoRAModule,
174
+ varbose: Optional[bool] = False,
175
+ train_text_encoder: Optional[bool] = True,
176
+ use_text_encoder_1: bool = True,
177
+ use_text_encoder_2: bool = True,
178
+ train_unet: Optional[bool] = True,
179
+ is_sdxl=False,
180
+ is_v2=False,
181
+ is_v3=False,
182
+ is_pixart: bool = False,
183
+ is_auraflow: bool = False,
184
+ is_flux: bool = False,
185
+ is_lumina2: bool = False,
186
+ use_bias: bool = False,
187
+ is_lorm: bool = False,
188
+ ignore_if_contains = None,
189
+ only_if_contains = None,
190
+ parameter_threshold: float = 0.0,
191
+ attn_only: bool = False,
192
+ target_lin_modules=LoRANetwork.UNET_TARGET_REPLACE_MODULE,
193
+ target_conv_modules=LoRANetwork.UNET_TARGET_REPLACE_MODULE_CONV2D_3X3,
194
+ network_type: str = "lora",
195
+ full_train_in_out: bool = False,
196
+ transformer_only: bool = False,
197
+ peft_format: bool = False,
198
+ is_assistant_adapter: bool = False,
199
+ is_transformer: bool = False,
200
+ base_model: 'StableDiffusion' = None,
201
+ is_ara: bool = False,
202
+ **kwargs
203
+ ) -> None:
204
+ """
205
+ LoRA network: すごく引数が多いが、パターンは以下の通り
206
+ 1. lora_dimとalphaを指定
207
+ 2. lora_dim、alpha、conv_lora_dim、conv_alphaを指定
208
+ 3. block_dimsとblock_alphasを指定 : Conv2d3x3には適用しない
209
+ 4. block_dims、block_alphas、conv_block_dims、conv_block_alphasを指定 : Conv2d3x3にも適用する
210
+ 5. modules_dimとmodules_alphaを指定 (推論用)
211
+ """
212
+ # call the parent of the parent we are replacing (LoRANetwork) init
213
+ torch.nn.Module.__init__(self)
214
+ ToolkitNetworkMixin.__init__(
215
+ self,
216
+ train_text_encoder=train_text_encoder,
217
+ train_unet=train_unet,
218
+ is_sdxl=is_sdxl,
219
+ is_v2=is_v2,
220
+ is_lorm=is_lorm,
221
+ **kwargs
222
+ )
223
+ if ignore_if_contains is None:
224
+ ignore_if_contains = []
225
+ self.ignore_if_contains = ignore_if_contains
226
+ self.transformer_only = transformer_only
227
+ self.base_model_ref = None
228
+ if base_model is not None:
229
+ self.base_model_ref = weakref.ref(base_model)
230
+
231
+ self.only_if_contains: Union[List, None] = only_if_contains
232
+
233
+ self.lora_dim = lora_dim
234
+ self.alpha = alpha
235
+ self.conv_lora_dim = conv_lora_dim
236
+ self.conv_alpha = conv_alpha
237
+ self.dropout = dropout
238
+ self.rank_dropout = rank_dropout
239
+ self.module_dropout = module_dropout
240
+ self.is_checkpointing = False
241
+ self._multiplier: float = 1.0
242
+ self.is_active: bool = False
243
+ self.torch_multiplier = None
244
+ # triggers the state updates
245
+ self.multiplier = multiplier
246
+ self.is_sdxl = is_sdxl
247
+ self.is_v2 = is_v2
248
+ self.is_v3 = is_v3
249
+ self.is_pixart = is_pixart
250
+ self.is_auraflow = is_auraflow
251
+ self.is_flux = is_flux
252
+ self.is_lumina2 = is_lumina2
253
+ self.network_type = network_type
254
+ self.is_assistant_adapter = is_assistant_adapter
255
+ self.full_rank = network_type.lower() == "fullrank"
256
+ self.is_ara = is_ara
257
+ if self.network_type.lower() == "dora":
258
+ self.module_class = DoRAModule
259
+ module_class = DoRAModule
260
+ elif self.network_type.lower() == "lokr":
261
+ self.module_class = LokrModule
262
+ module_class = LokrModule
263
+ self.network_config: NetworkConfig = kwargs.get("network_config", None)
264
+
265
+ self.peft_format = peft_format
266
+ self.is_transformer = is_transformer
267
+
268
+ # use the old format for older models unless the user has specified otherwise
269
+ self.use_old_lokr_format = False
270
+ if self.network_config is not None and hasattr(self.network_config, 'old_lokr_format'):
271
+ self.use_old_lokr_format = self.network_config.old_lokr_format
272
+ # also allow a false from the model itself
273
+ if base_model is not None and not base_model.use_old_lokr_format:
274
+ self.use_old_lokr_format = False
275
+
276
+ # always do peft for flux only for now
277
+ if self.is_flux or self.is_v3 or self.is_lumina2 or is_transformer:
278
+ # don't do peft format for lokr if using old format
279
+ if self.network_type.lower() != "lokr" or not self.use_old_lokr_format:
280
+ self.peft_format = True
281
+
282
+ if self.peft_format:
283
+ # no alpha for peft
284
+ self.alpha = self.lora_dim
285
+ alpha = self.alpha
286
+ self.conv_alpha = self.conv_lora_dim
287
+ conv_alpha = self.conv_alpha
288
+
289
+ self.full_train_in_out = full_train_in_out
290
+
291
+ if modules_dim is not None:
292
+ print(f"create LoRA network from weights")
293
+ elif block_dims is not None:
294
+ print(f"create LoRA network from block_dims")
295
+ print(
296
+ f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
297
+ print(f"block_dims: {block_dims}")
298
+ print(f"block_alphas: {block_alphas}")
299
+ if conv_block_dims is not None:
300
+ print(f"conv_block_dims: {conv_block_dims}")
301
+ print(f"conv_block_alphas: {conv_block_alphas}")
302
+ else:
303
+ print(f"create LoRA network. base dim (rank): {lora_dim}, alpha: {alpha}")
304
+ print(
305
+ f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
306
+ if self.conv_lora_dim is not None:
307
+ print(
308
+ f"apply LoRA to Conv2d with kernel size (3,3). dim (rank): {self.conv_lora_dim}, alpha: {self.conv_alpha}")
309
+
310
+ # create module instances
311
+ def create_modules(
312
+ is_unet: bool,
313
+ text_encoder_idx: Optional[int], # None, 1, 2
314
+ root_module: torch.nn.Module,
315
+ target_replace_modules: List[torch.nn.Module],
316
+ ) -> List[LoRAModule]:
317
+ unet_prefix = self.LORA_PREFIX_UNET
318
+ if self.peft_format:
319
+ unet_prefix = self.PEFT_PREFIX_UNET
320
+ if is_pixart or is_v3 or is_auraflow or is_flux or is_lumina2 or self.is_transformer:
321
+ unet_prefix = f"lora_transformer"
322
+ if self.peft_format:
323
+ unet_prefix = "transformer"
324
+
325
+ prefix = (
326
+ unet_prefix
327
+ if is_unet
328
+ else (
329
+ self.LORA_PREFIX_TEXT_ENCODER
330
+ if text_encoder_idx is None
331
+ else (self.LORA_PREFIX_TEXT_ENCODER1 if text_encoder_idx == 1 else self.LORA_PREFIX_TEXT_ENCODER2)
332
+ )
333
+ )
334
+ loras = []
335
+ skipped = []
336
+ attached_modules = []
337
+ lora_shape_dict = {}
338
+ for name, module in root_module.named_modules():
339
+ if module.__class__.__name__ in target_replace_modules:
340
+ for child_name, child_module in module.named_modules():
341
+ is_linear = child_module.__class__.__name__ in LINEAR_MODULES
342
+ is_conv2d = child_module.__class__.__name__ in CONV_MODULES
343
+ is_conv2d_1x1 = is_conv2d and child_module.kernel_size == (1, 1)
344
+
345
+
346
+ lora_name = [prefix, name, child_name]
347
+ # filter out blank
348
+ lora_name = [x for x in lora_name if x and x != ""]
349
+ lora_name = ".".join(lora_name)
350
+ # if it doesnt have a name, it wil have two dots
351
+ lora_name.replace("..", ".")
352
+ clean_name = lora_name
353
+ if self.peft_format:
354
+ # we replace this on saving
355
+ lora_name = lora_name.replace(".", "$$")
356
+ else:
357
+ lora_name = lora_name.replace(".", "_")
358
+
359
+ skip = False
360
+ if any([word in clean_name for word in self.ignore_if_contains]):
361
+ skip = True
362
+
363
+ # see if it is over threshold
364
+ if count_parameters(child_module) < parameter_threshold:
365
+ skip = True
366
+
367
+ if self.transformer_only and is_unet:
368
+ transformer_block_names = None
369
+ if base_model is not None:
370
+ transformer_block_names = base_model.get_transformer_block_names()
371
+
372
+ if transformer_block_names is not None:
373
+ if not any([name in lora_name for name in transformer_block_names]):
374
+ skip = True
375
+ else:
376
+ if self.is_pixart:
377
+ if "transformer_blocks" not in lora_name:
378
+ skip = True
379
+ if self.is_flux:
380
+ if "transformer_blocks" not in lora_name:
381
+ skip = True
382
+ if self.is_lumina2:
383
+ if "layers$$" not in lora_name and "noise_refiner$$" not in lora_name and "context_refiner$$" not in lora_name:
384
+ skip = True
385
+ if self.is_v3:
386
+ if "transformer_blocks" not in lora_name:
387
+ skip = True
388
+
389
+ # handle custom models
390
+ if hasattr(root_module, 'transformer_blocks'):
391
+ if "transformer_blocks" not in lora_name:
392
+ skip = True
393
+
394
+ if hasattr(root_module, 'blocks'):
395
+ if "blocks" not in lora_name:
396
+ skip = True
397
+
398
+ if hasattr(root_module, 'single_blocks'):
399
+ if "single_blocks" not in lora_name and "double_blocks" not in lora_name:
400
+ skip = True
401
+
402
+ if (is_linear or is_conv2d) and not skip:
403
+
404
+ if self.only_if_contains is not None:
405
+ if not any([word in clean_name for word in self.only_if_contains]) and not any([word in lora_name for word in self.only_if_contains]):
406
+ continue
407
+
408
+ dim = None
409
+ alpha = None
410
+
411
+ if modules_dim is not None:
412
+ # モジュール指定あり
413
+ if lora_name in modules_dim:
414
+ dim = modules_dim[lora_name]
415
+ alpha = modules_alpha[lora_name]
416
+ else:
417
+ # 通常、すべて対象とする
418
+ if is_linear or is_conv2d_1x1:
419
+ dim = self.lora_dim
420
+ alpha = self.alpha
421
+ elif self.conv_lora_dim is not None:
422
+ dim = self.conv_lora_dim
423
+ alpha = self.conv_alpha
424
+
425
+ if dim is None or dim == 0:
426
+ # skipした情報を出力
427
+ if is_linear or is_conv2d_1x1 or (
428
+ self.conv_lora_dim is not None or conv_block_dims is not None):
429
+ skipped.append(lora_name)
430
+ continue
431
+
432
+ module_kwargs = {}
433
+
434
+ if self.network_type.lower() == "lokr":
435
+ module_kwargs["factor"] = self.network_config.lokr_factor
436
+
437
+ if self.is_ara:
438
+ module_kwargs["is_ara"] = True
439
+
440
+ lora = module_class(
441
+ lora_name,
442
+ child_module,
443
+ self.multiplier,
444
+ dim,
445
+ alpha,
446
+ dropout=dropout,
447
+ rank_dropout=rank_dropout,
448
+ module_dropout=module_dropout,
449
+ network=self,
450
+ parent=module,
451
+ use_bias=use_bias,
452
+ **module_kwargs
453
+ )
454
+ loras.append(lora)
455
+ if self.network_type.lower() == "lokr":
456
+ try:
457
+ lora_shape_dict[lora_name] = [list(lora.lokr_w1.weight.shape), list(lora.lokr_w2.weight.shape)]
458
+ except:
459
+ pass
460
+ else:
461
+ if self.full_rank:
462
+ lora_shape_dict[lora_name] = [list(lora.lora_down.weight.shape)]
463
+ else:
464
+ lora_shape_dict[lora_name] = [list(lora.lora_down.weight.shape), list(lora.lora_up.weight.shape)]
465
+ return loras, skipped
466
+
467
+ text_encoders = text_encoder if type(text_encoder) == list else [text_encoder]
468
+
469
+ # create LoRA for text encoder
470
+ # 毎回すべてのモジュールを作るのは無駄なので要検討
471
+ self.text_encoder_loras = []
472
+ skipped_te = []
473
+ if train_text_encoder:
474
+ for i, text_encoder in enumerate(text_encoders):
475
+ if not use_text_encoder_1 and i == 0:
476
+ continue
477
+ if not use_text_encoder_2 and i == 1:
478
+ continue
479
+ if len(text_encoders) > 1:
480
+ index = i + 1
481
+ print(f"create LoRA for Text Encoder {index}:")
482
+ else:
483
+ index = None
484
+ print(f"create LoRA for Text Encoder:")
485
+
486
+ replace_modules = LoRANetwork.TEXT_ENCODER_TARGET_REPLACE_MODULE
487
+
488
+ if self.is_pixart:
489
+ replace_modules = ["T5EncoderModel"]
490
+
491
+ text_encoder_loras, skipped = create_modules(False, index, text_encoder, replace_modules)
492
+ self.text_encoder_loras.extend(text_encoder_loras)
493
+ skipped_te += skipped
494
+ print(f"create LoRA for Text Encoder: {len(self.text_encoder_loras)} modules.")
495
+
496
+ # extend U-Net target modules if conv2d 3x3 is enabled, or load from weights
497
+ target_modules = target_lin_modules
498
+ if modules_dim is not None or self.conv_lora_dim is not None or conv_block_dims is not None:
499
+ target_modules += target_conv_modules
500
+
501
+ if is_v3:
502
+ target_modules = ["SD3Transformer2DModel"]
503
+
504
+ if is_pixart:
505
+ target_modules = ["PixArtTransformer2DModel"]
506
+
507
+ if is_auraflow:
508
+ target_modules = ["AuraFlowTransformer2DModel"]
509
+
510
+ if is_flux:
511
+ target_modules = ["FluxTransformer2DModel"]
512
+
513
+ if is_lumina2:
514
+ target_modules = ["Lumina2Transformer2DModel"]
515
+
516
+ if train_unet:
517
+ self.unet_loras, skipped_un = create_modules(True, None, unet, target_modules)
518
+ else:
519
+ self.unet_loras = []
520
+ skipped_un = []
521
+ print(f"create LoRA for U-Net: {len(self.unet_loras)} modules.")
522
+
523
+ skipped = skipped_te + skipped_un
524
+ if varbose and len(skipped) > 0:
525
+ print(
526
+ f"because block_lr_weight is 0 or dim (rank) is 0, {len(skipped)} LoRA modules are skipped / block_lr_weightまたはdim (rank)が0の為、次の{len(skipped)}個のLoRAモジュールはスキップされます:"
527
+ )
528
+ for name in skipped:
529
+ print(f"\t{name}")
530
+
531
+ self.up_lr_weight: List[float] = None
532
+ self.down_lr_weight: List[float] = None
533
+ self.mid_lr_weight: float = None
534
+ self.block_lr = False
535
+
536
+ # assertion
537
+ names = set()
538
+ for lora in self.text_encoder_loras + self.unet_loras:
539
+ assert lora.lora_name not in names, f"duplicated lora name: {lora.lora_name}"
540
+ names.add(lora.lora_name)
541
+
542
+ if self.full_train_in_out:
543
+ print("full train in out")
544
+ # we are going to retrain the main in out layers for VAE change usually
545
+ if self.is_pixart:
546
+ transformer: PixArtTransformer2DModel = unet
547
+ self.transformer_pos_embed = copy.deepcopy(transformer.pos_embed)
548
+ self.transformer_proj_out = copy.deepcopy(transformer.proj_out)
549
+
550
+ transformer.pos_embed = self.transformer_pos_embed
551
+ transformer.proj_out = self.transformer_proj_out
552
+
553
+ elif self.is_auraflow:
554
+ transformer: AuraFlowTransformer2DModel = unet
555
+ self.transformer_pos_embed = copy.deepcopy(transformer.pos_embed)
556
+ self.transformer_proj_out = copy.deepcopy(transformer.proj_out)
557
+
558
+ transformer.pos_embed = self.transformer_pos_embed
559
+ transformer.proj_out = self.transformer_proj_out
560
+
561
+ elif base_model is not None and base_model.arch == "wan21":
562
+ transformer: WanTransformer3DModel = unet
563
+ self.transformer_pos_embed = copy.deepcopy(transformer.patch_embedding)
564
+ self.transformer_proj_out = copy.deepcopy(transformer.proj_out)
565
+
566
+ transformer.patch_embedding = self.transformer_pos_embed
567
+ transformer.proj_out = self.transformer_proj_out
568
+
569
+ else:
570
+ unet: UNet2DConditionModel = unet
571
+ unet_conv_in: torch.nn.Conv2d = unet.conv_in
572
+ unet_conv_out: torch.nn.Conv2d = unet.conv_out
573
+
574
+ # clone these and replace their forwards with ours
575
+ self.unet_conv_in = copy.deepcopy(unet_conv_in)
576
+ self.unet_conv_out = copy.deepcopy(unet_conv_out)
577
+ unet.conv_in = self.unet_conv_in
578
+ unet.conv_out = self.unet_conv_out
579
+
580
+ def prepare_optimizer_params(self, text_encoder_lr, unet_lr, default_lr):
581
+ # call Lora prepare_optimizer_params
582
+ all_params = super().prepare_optimizer_params(text_encoder_lr, unet_lr, default_lr)
583
+
584
+ if self.full_train_in_out:
585
+ base_model = self.base_model_ref() if self.base_model_ref is not None else None
586
+ if self.is_pixart or self.is_auraflow or self.is_flux or (base_model is not None and base_model.arch == "wan21"):
587
+ all_params.append({"lr": unet_lr, "params": list(self.transformer_pos_embed.parameters())})
588
+ all_params.append({"lr": unet_lr, "params": list(self.transformer_proj_out.parameters())})
589
+ else:
590
+ all_params.append({"lr": unet_lr, "params": list(self.unet_conv_in.parameters())})
591
+ all_params.append({"lr": unet_lr, "params": list(self.unet_conv_out.parameters())})
592
+
593
+ return all_params
594
+
595
+
toolkit/lorm.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Tuple, Literal, Optional
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from diffusers import UNet2DConditionModel
6
+ from torch import Tensor
7
+ from tqdm import tqdm
8
+
9
+ from toolkit.config_modules import LoRMConfig
10
+
11
+ conv = nn.Conv2d
12
+ lin = nn.Linear
13
+ _size_2_t = Union[int, Tuple[int, int]]
14
+
15
+ ExtractMode = Union[
16
+ 'fixed',
17
+ 'threshold',
18
+ 'ratio',
19
+ 'quantile',
20
+ 'percentage'
21
+ ]
22
+
23
+ LINEAR_MODULES = [
24
+ 'Linear',
25
+ 'LoRACompatibleLinear'
26
+ ]
27
+ CONV_MODULES = [
28
+ # 'Conv2d',
29
+ # 'LoRACompatibleConv'
30
+ ]
31
+
32
+ UNET_TARGET_REPLACE_MODULE = [
33
+ "Transformer2DModel",
34
+ # "ResnetBlock2D",
35
+ "Downsample2D",
36
+ "Upsample2D",
37
+ ]
38
+
39
+ LORM_TARGET_REPLACE_MODULE = UNET_TARGET_REPLACE_MODULE
40
+
41
+ UNET_TARGET_REPLACE_NAME = [
42
+ "conv_in",
43
+ "conv_out",
44
+ "time_embedding.linear_1",
45
+ "time_embedding.linear_2",
46
+ ]
47
+
48
+ UNET_MODULES_TO_AVOID = [
49
+ ]
50
+
51
+
52
+ # Low Rank Convolution
53
+ class LoRMCon2d(nn.Module):
54
+ def __init__(
55
+ self,
56
+ in_channels: int,
57
+ lorm_channels: int,
58
+ out_channels: int,
59
+ kernel_size: _size_2_t,
60
+ stride: _size_2_t = 1,
61
+ padding: Union[str, _size_2_t] = 'same',
62
+ dilation: _size_2_t = 1,
63
+ groups: int = 1,
64
+ bias: bool = True,
65
+ padding_mode: str = 'zeros',
66
+ device=None,
67
+ dtype=None
68
+ ) -> None:
69
+ super().__init__()
70
+ self.in_channels = in_channels
71
+ self.lorm_channels = lorm_channels
72
+ self.out_channels = out_channels
73
+ self.kernel_size = kernel_size
74
+ self.stride = stride
75
+ self.padding = padding
76
+ self.dilation = dilation
77
+ self.groups = groups
78
+ self.padding_mode = padding_mode
79
+
80
+ self.down = nn.Conv2d(
81
+ in_channels=in_channels,
82
+ out_channels=lorm_channels,
83
+ kernel_size=kernel_size,
84
+ stride=stride,
85
+ padding=padding,
86
+ dilation=dilation,
87
+ groups=groups,
88
+ bias=False,
89
+ padding_mode=padding_mode,
90
+ device=device,
91
+ dtype=dtype
92
+ )
93
+
94
+ # Kernel size on the up is always 1x1.
95
+ # I don't think you could calculate a dual 3x3, or I can't at least
96
+
97
+ self.up = nn.Conv2d(
98
+ in_channels=lorm_channels,
99
+ out_channels=out_channels,
100
+ kernel_size=(1, 1),
101
+ stride=1,
102
+ padding='same',
103
+ dilation=1,
104
+ groups=1,
105
+ bias=bias,
106
+ padding_mode='zeros',
107
+ device=device,
108
+ dtype=dtype
109
+ )
110
+
111
+ def forward(self, input: Tensor, *args, **kwargs) -> Tensor:
112
+ x = input
113
+ x = self.down(x)
114
+ x = self.up(x)
115
+ return x
116
+
117
+
118
+ class LoRMLinear(nn.Module):
119
+ def __init__(
120
+ self,
121
+ in_features: int,
122
+ lorm_features: int,
123
+ out_features: int,
124
+ bias: bool = True,
125
+ device=None,
126
+ dtype=None
127
+ ) -> None:
128
+ super().__init__()
129
+ self.in_features = in_features
130
+ self.lorm_features = lorm_features
131
+ self.out_features = out_features
132
+
133
+ self.down = nn.Linear(
134
+ in_features=in_features,
135
+ out_features=lorm_features,
136
+ bias=False,
137
+ device=device,
138
+ dtype=dtype
139
+
140
+ )
141
+ self.up = nn.Linear(
142
+ in_features=lorm_features,
143
+ out_features=out_features,
144
+ bias=bias,
145
+ # bias=True,
146
+ device=device,
147
+ dtype=dtype
148
+ )
149
+
150
+ def forward(self, input: Tensor, *args, **kwargs) -> Tensor:
151
+ x = input
152
+ x = self.down(x)
153
+ x = self.up(x)
154
+ return x
155
+
156
+
157
+ def extract_conv(
158
+ weight: Union[torch.Tensor, nn.Parameter],
159
+ mode='fixed',
160
+ mode_param=0,
161
+ device='cpu'
162
+ ) -> Tuple[Tensor, Tensor, int, Tensor]:
163
+ weight = weight.to(device)
164
+ out_ch, in_ch, kernel_size, _ = weight.shape
165
+
166
+ U, S, Vh = torch.linalg.svd(weight.reshape(out_ch, -1))
167
+ if mode == 'percentage':
168
+ assert 0 <= mode_param <= 1 # Ensure it's a valid percentage.
169
+ original_params = out_ch * in_ch * kernel_size * kernel_size
170
+ desired_params = mode_param * original_params
171
+ # Solve for lora_rank from the equation
172
+ lora_rank = int(desired_params / (in_ch * kernel_size * kernel_size + out_ch))
173
+ elif mode == 'fixed':
174
+ lora_rank = mode_param
175
+ elif mode == 'threshold':
176
+ assert mode_param >= 0
177
+ lora_rank = torch.sum(S > mode_param).item()
178
+ elif mode == 'ratio':
179
+ assert 1 >= mode_param >= 0
180
+ min_s = torch.max(S) * mode_param
181
+ lora_rank = torch.sum(S > min_s).item()
182
+ elif mode == 'quantile' or mode == 'percentile':
183
+ assert 1 >= mode_param >= 0
184
+ s_cum = torch.cumsum(S, dim=0)
185
+ min_cum_sum = mode_param * torch.sum(S)
186
+ lora_rank = torch.sum(s_cum < min_cum_sum).item()
187
+ else:
188
+ raise NotImplementedError('Extract mode should be "fixed", "threshold", "ratio" or "quantile"')
189
+ lora_rank = max(1, lora_rank)
190
+ lora_rank = min(out_ch, in_ch, lora_rank)
191
+ if lora_rank >= out_ch / 2:
192
+ lora_rank = int(out_ch / 2)
193
+ print(f"rank is higher than it should be")
194
+ # print(f"Skipping layer as determined rank is too high")
195
+ # return None, None, None, None
196
+ # return weight, 'full'
197
+
198
+ U = U[:, :lora_rank]
199
+ S = S[:lora_rank]
200
+ U = U @ torch.diag(S)
201
+ Vh = Vh[:lora_rank, :]
202
+
203
+ diff = (weight - (U @ Vh).reshape(out_ch, in_ch, kernel_size, kernel_size)).detach()
204
+ extract_weight_A = Vh.reshape(lora_rank, in_ch, kernel_size, kernel_size).detach()
205
+ extract_weight_B = U.reshape(out_ch, lora_rank, 1, 1).detach()
206
+ del U, S, Vh, weight
207
+ return extract_weight_A, extract_weight_B, lora_rank, diff
208
+
209
+
210
+ def extract_linear(
211
+ weight: Union[torch.Tensor, nn.Parameter],
212
+ mode='fixed',
213
+ mode_param=0,
214
+ device='cpu',
215
+ ) -> Tuple[Tensor, Tensor, int, Tensor]:
216
+ weight = weight.to(device)
217
+ out_ch, in_ch = weight.shape
218
+
219
+ U, S, Vh = torch.linalg.svd(weight)
220
+
221
+ if mode == 'percentage':
222
+ assert 0 <= mode_param <= 1 # Ensure it's a valid percentage.
223
+ desired_params = mode_param * out_ch * in_ch
224
+ # Solve for lora_rank from the equation
225
+ lora_rank = int(desired_params / (in_ch + out_ch))
226
+ elif mode == 'fixed':
227
+ lora_rank = mode_param
228
+ elif mode == 'threshold':
229
+ assert mode_param >= 0
230
+ lora_rank = torch.sum(S > mode_param).item()
231
+ elif mode == 'ratio':
232
+ assert 1 >= mode_param >= 0
233
+ min_s = torch.max(S) * mode_param
234
+ lora_rank = torch.sum(S > min_s).item()
235
+ elif mode == 'quantile':
236
+ assert 1 >= mode_param >= 0
237
+ s_cum = torch.cumsum(S, dim=0)
238
+ min_cum_sum = mode_param * torch.sum(S)
239
+ lora_rank = torch.sum(s_cum < min_cum_sum).item()
240
+ else:
241
+ raise NotImplementedError('Extract mode should be "fixed", "threshold", "ratio" or "quantile"')
242
+ lora_rank = max(1, lora_rank)
243
+ lora_rank = min(out_ch, in_ch, lora_rank)
244
+ if lora_rank >= out_ch / 2:
245
+ # print(f"rank is higher than it should be")
246
+ lora_rank = int(out_ch / 2)
247
+ # return weight, 'full'
248
+ # print(f"Skipping layer as determined rank is too high")
249
+ # return None, None, None, None
250
+
251
+ U = U[:, :lora_rank]
252
+ S = S[:lora_rank]
253
+ U = U @ torch.diag(S)
254
+ Vh = Vh[:lora_rank, :]
255
+
256
+ diff = (weight - U @ Vh).detach()
257
+ extract_weight_A = Vh.reshape(lora_rank, in_ch).detach()
258
+ extract_weight_B = U.reshape(out_ch, lora_rank).detach()
259
+ del U, S, Vh, weight
260
+ return extract_weight_A, extract_weight_B, lora_rank, diff
261
+
262
+
263
+ def replace_module_by_path(network, name, module):
264
+ """Replace a module in a network by its name."""
265
+ name_parts = name.split('.')
266
+ current_module = network
267
+ for part in name_parts[:-1]:
268
+ current_module = getattr(current_module, part)
269
+ try:
270
+ setattr(current_module, name_parts[-1], module)
271
+ except Exception as e:
272
+ print(e)
273
+
274
+
275
+ def count_parameters(module):
276
+ return sum(p.numel() for p in module.parameters())
277
+
278
+
279
+ def compute_optimal_bias(original_module, linear_down, linear_up, X):
280
+ Y_original = original_module(X)
281
+ Y_approx = linear_up(linear_down(X))
282
+ E = Y_original - Y_approx
283
+
284
+ optimal_bias = E.mean(dim=0)
285
+
286
+ return optimal_bias
287
+
288
+
289
+ def format_with_commas(n):
290
+ return f"{n:,}"
291
+
292
+
293
+ def print_lorm_extract_details(
294
+ start_num_params: int,
295
+ end_num_params: int,
296
+ num_replaced: int,
297
+ ):
298
+ start_formatted = format_with_commas(start_num_params)
299
+ end_formatted = format_with_commas(end_num_params)
300
+ num_replaced_formatted = format_with_commas(num_replaced)
301
+
302
+ width = max(len(start_formatted), len(end_formatted), len(num_replaced_formatted))
303
+
304
+ print(f"Convert UNet result:")
305
+ print(f" - converted: {num_replaced:>{width},} modules")
306
+ print(f" - start: {start_num_params:>{width},} params")
307
+ print(f" - end: {end_num_params:>{width},} params")
308
+
309
+
310
+ lorm_ignore_if_contains = [
311
+ 'proj_out', 'proj_in',
312
+ ]
313
+
314
+ lorm_parameter_threshold = 1000000
315
+
316
+
317
+ @torch.no_grad()
318
+ def convert_diffusers_unet_to_lorm(
319
+ unet: UNet2DConditionModel,
320
+ config: LoRMConfig,
321
+ ):
322
+ print('Converting UNet to LoRM UNet')
323
+ start_num_params = count_parameters(unet)
324
+ named_modules = list(unet.named_modules())
325
+
326
+ num_replaced = 0
327
+
328
+ pbar = tqdm(total=len(named_modules), desc="UNet -> LoRM UNet")
329
+ layer_names_replaced = []
330
+ converted_modules = []
331
+ ignore_if_contains = [
332
+ 'proj_out', 'proj_in',
333
+ ]
334
+
335
+ for name, module in named_modules:
336
+ module_name = module.__class__.__name__
337
+ if module_name in UNET_TARGET_REPLACE_MODULE:
338
+ for child_name, child_module in module.named_modules():
339
+ new_module: Union[LoRMCon2d, LoRMLinear, None] = None
340
+ # if child name includes attn, skip it
341
+ combined_name = combined_name = f"{name}.{child_name}"
342
+ # if child_module.__class__.__name__ in LINEAR_MODULES and child_module.bias is None:
343
+ # pass
344
+
345
+ lorm_config = config.get_config_for_module(combined_name)
346
+
347
+ extract_mode = lorm_config.extract_mode
348
+ extract_mode_param = lorm_config.extract_mode_param
349
+ parameter_threshold = lorm_config.parameter_threshold
350
+
351
+ if any([word in child_name for word in ignore_if_contains]):
352
+ pass
353
+
354
+ elif child_module.__class__.__name__ in LINEAR_MODULES:
355
+ if count_parameters(child_module) > parameter_threshold:
356
+
357
+ # dtype = child_module.weight.dtype
358
+ dtype = torch.float32
359
+ # extract and convert
360
+ down_weight, up_weight, lora_dim, diff = extract_linear(
361
+ weight=child_module.weight.clone().detach().float(),
362
+ mode=extract_mode,
363
+ mode_param=extract_mode_param,
364
+ device=child_module.weight.device,
365
+ )
366
+ if down_weight is None:
367
+ continue
368
+ down_weight = down_weight.to(dtype=dtype)
369
+ up_weight = up_weight.to(dtype=dtype)
370
+ bias_weight = None
371
+ if child_module.bias is not None:
372
+ bias_weight = child_module.bias.data.clone().detach().to(dtype=dtype)
373
+ # linear layer weights = (out_features, in_features)
374
+ new_module = LoRMLinear(
375
+ in_features=down_weight.shape[1],
376
+ lorm_features=lora_dim,
377
+ out_features=up_weight.shape[0],
378
+ bias=bias_weight is not None,
379
+ device=down_weight.device,
380
+ dtype=down_weight.dtype
381
+ )
382
+
383
+ # replace the weights
384
+ new_module.down.weight.data = down_weight
385
+ new_module.up.weight.data = up_weight
386
+ if bias_weight is not None:
387
+ new_module.up.bias.data = bias_weight
388
+ # else:
389
+ # new_module.up.bias.data = torch.zeros_like(new_module.up.bias.data)
390
+
391
+ # bias_correction = compute_optimal_bias(
392
+ # child_module,
393
+ # new_module.down,
394
+ # new_module.up,
395
+ # torch.randn((1000, down_weight.shape[1])).to(device=down_weight.device, dtype=dtype)
396
+ # )
397
+ # new_module.up.bias.data += bias_correction
398
+
399
+ elif child_module.__class__.__name__ in CONV_MODULES:
400
+ if count_parameters(child_module) > parameter_threshold:
401
+ dtype = child_module.weight.dtype
402
+ down_weight, up_weight, lora_dim, diff = extract_conv(
403
+ weight=child_module.weight.clone().detach().float(),
404
+ mode=extract_mode,
405
+ mode_param=extract_mode_param,
406
+ device=child_module.weight.device,
407
+ )
408
+ if down_weight is None:
409
+ continue
410
+ down_weight = down_weight.to(dtype=dtype)
411
+ up_weight = up_weight.to(dtype=dtype)
412
+ bias_weight = None
413
+ if child_module.bias is not None:
414
+ bias_weight = child_module.bias.data.clone().detach().to(dtype=dtype)
415
+
416
+ new_module = LoRMCon2d(
417
+ in_channels=down_weight.shape[1],
418
+ lorm_channels=lora_dim,
419
+ out_channels=up_weight.shape[0],
420
+ kernel_size=child_module.kernel_size,
421
+ dilation=child_module.dilation,
422
+ padding=child_module.padding,
423
+ padding_mode=child_module.padding_mode,
424
+ stride=child_module.stride,
425
+ bias=bias_weight is not None,
426
+ device=down_weight.device,
427
+ dtype=down_weight.dtype
428
+ )
429
+ # replace the weights
430
+ new_module.down.weight.data = down_weight
431
+ new_module.up.weight.data = up_weight
432
+ if bias_weight is not None:
433
+ new_module.up.bias.data = bias_weight
434
+
435
+ if new_module:
436
+ combined_name = f"{name}.{child_name}"
437
+ replace_module_by_path(unet, combined_name, new_module)
438
+ converted_modules.append(new_module)
439
+ num_replaced += 1
440
+ layer_names_replaced.append(
441
+ f"{combined_name} - {format_with_commas(count_parameters(child_module))}")
442
+
443
+ pbar.update(1)
444
+ pbar.close()
445
+ end_num_params = count_parameters(unet)
446
+
447
+ def sorting_key(s):
448
+ # Extract the number part, remove commas, and convert to integer
449
+ return int(s.split("-")[1].strip().replace(",", ""))
450
+
451
+ sorted_layer_names_replaced = sorted(layer_names_replaced, key=sorting_key, reverse=True)
452
+ for layer_name in sorted_layer_names_replaced:
453
+ print(layer_name)
454
+
455
+ print_lorm_extract_details(
456
+ start_num_params=start_num_params,
457
+ end_num_params=end_num_params,
458
+ num_replaced=num_replaced,
459
+ )
460
+
461
+ return converted_modules
toolkit/losses.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .llvae import LosslessLatentEncoder
3
+
4
+
5
+ def total_variation(image):
6
+ """
7
+ Compute normalized total variation.
8
+ Inputs:
9
+ - image: PyTorch Variable of shape (N, C, H, W)
10
+ Returns:
11
+ - TV: total variation normalized by the number of elements
12
+ """
13
+ n_elements = image.shape[1] * image.shape[2] * image.shape[3]
14
+ return ((torch.sum(torch.abs(image[:, :, :, :-1] - image[:, :, :, 1:])) +
15
+ torch.sum(torch.abs(image[:, :, :-1, :] - image[:, :, 1:, :]))) / n_elements)
16
+
17
+ def total_variation_deltas(image):
18
+ """
19
+ Compute per-pixel total variation deltas.
20
+ Input:
21
+ - image: Tensor of shape (N, C, H, W)
22
+ Returns:
23
+ - Tensor with shape (N, C, H, W), padded to match input shape
24
+ """
25
+ dh = torch.zeros_like(image)
26
+ dv = torch.zeros_like(image)
27
+
28
+ dh[:, :, :, :-1] = torch.abs(image[:, :, :, 1:] - image[:, :, :, :-1])
29
+ dv[:, :, :-1, :] = torch.abs(image[:, :, 1:, :] - image[:, :, :-1, :])
30
+
31
+ return dh + dv
32
+
33
+
34
+ class ComparativeTotalVariation(torch.nn.Module):
35
+ """
36
+ Compute the comparative loss in tv between two images. to match their tv
37
+ """
38
+
39
+ def forward(self, pred, target):
40
+ return torch.abs(total_variation(pred) - total_variation(target))
41
+
42
+
43
+ # Gradient penalty
44
+ def get_gradient_penalty(critic, real, fake, device):
45
+ with torch.autocast(device_type='cuda'):
46
+ real = real.float()
47
+ fake = fake.float()
48
+ alpha = torch.rand(real.size(0), 1, 1, 1).to(device).float()
49
+ interpolates = (alpha * real + ((1 - alpha) * fake)).requires_grad_(True)
50
+ if torch.isnan(interpolates).any():
51
+ print('d_interpolates is nan')
52
+ d_interpolates = critic(interpolates)
53
+ fake = torch.ones(real.size(0), 1, device=device)
54
+
55
+ if torch.isnan(d_interpolates).any():
56
+ print('fake is nan')
57
+ gradients = torch.autograd.grad(
58
+ outputs=d_interpolates,
59
+ inputs=interpolates,
60
+ grad_outputs=fake,
61
+ create_graph=True,
62
+ retain_graph=True,
63
+ only_inputs=True,
64
+ )[0]
65
+
66
+ # see if any are nan
67
+ if torch.isnan(gradients).any():
68
+ print('gradients is nan')
69
+
70
+ gradients = gradients.view(gradients.size(0), -1)
71
+ gradient_norm = gradients.norm(2, dim=1)
72
+ gradient_penalty = ((gradient_norm - 1) ** 2).mean()
73
+ return gradient_penalty.float()
74
+
75
+
76
+ class PatternLoss(torch.nn.Module):
77
+ def __init__(self, pattern_size=4, dtype=torch.float32):
78
+ super().__init__()
79
+ self.pattern_size = pattern_size
80
+ self.llvae_encoder = LosslessLatentEncoder(3, pattern_size, dtype=dtype)
81
+
82
+ def forward(self, pred, target):
83
+ pred_latents = self.llvae_encoder(pred)
84
+ target_latents = self.llvae_encoder(target)
85
+
86
+ matrix_pixels = self.pattern_size * self.pattern_size
87
+
88
+ color_chans = pred_latents.shape[1] // 3
89
+ # pytorch
90
+ r_chans, g_chans, b_chans = torch.split(pred_latents, [color_chans, color_chans, color_chans], 1)
91
+ r_chans_target, g_chans_target, b_chans_target = torch.split(target_latents, [color_chans, color_chans, color_chans], 1)
92
+
93
+ def separated_chan_loss(latent_chan):
94
+ nonlocal matrix_pixels
95
+ chan_mean = torch.mean(latent_chan, dim=[1, 2, 3])
96
+ chan_splits = torch.split(latent_chan, [1 for i in range(matrix_pixels)], 1)
97
+ chan_loss = None
98
+ for chan in chan_splits:
99
+ this_mean = torch.mean(chan, dim=[1, 2, 3])
100
+ this_chan_loss = torch.abs(this_mean - chan_mean)
101
+ if chan_loss is None:
102
+ chan_loss = this_chan_loss
103
+ else:
104
+ chan_loss = chan_loss + this_chan_loss
105
+ chan_loss = chan_loss * (1 / matrix_pixels)
106
+ return chan_loss
107
+
108
+ r_chan_loss = torch.abs(separated_chan_loss(r_chans) - separated_chan_loss(r_chans_target))
109
+ g_chan_loss = torch.abs(separated_chan_loss(g_chans) - separated_chan_loss(g_chans_target))
110
+ b_chan_loss = torch.abs(separated_chan_loss(b_chans) - separated_chan_loss(b_chans_target))
111
+ return (r_chan_loss + g_chan_loss + b_chan_loss) * 0.3333
112
+
113
+
toolkit/lycoris_special.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ from typing import Optional, Union, List, Type
4
+
5
+ import torch
6
+ from lycoris.kohya import LycorisNetwork, LoConModule
7
+ from lycoris.modules.glora import GLoRAModule
8
+ from torch import nn
9
+ from transformers import CLIPTextModel
10
+ from torch.nn import functional as F
11
+ from toolkit.network_mixins import ToolkitNetworkMixin, ToolkitModuleMixin, ExtractableModuleMixin
12
+
13
+ # diffusers specific stuff
14
+ LINEAR_MODULES = [
15
+ 'Linear',
16
+ 'LoRACompatibleLinear'
17
+ ]
18
+ CONV_MODULES = [
19
+ 'Conv2d',
20
+ 'LoRACompatibleConv'
21
+ ]
22
+
23
+ class LoConSpecialModule(ToolkitModuleMixin, LoConModule, ExtractableModuleMixin):
24
+ def __init__(
25
+ self,
26
+ lora_name, org_module: nn.Module,
27
+ multiplier=1.0,
28
+ lora_dim=4, alpha=1,
29
+ dropout=0., rank_dropout=0., module_dropout=0.,
30
+ use_cp=False,
31
+ network: 'LycorisSpecialNetwork' = None,
32
+ use_bias=False,
33
+ **kwargs,
34
+ ):
35
+ """ if alpha == 0 or None, alpha is rank (no scaling). """
36
+ # call super of super
37
+ ToolkitModuleMixin.__init__(self, network=network)
38
+ torch.nn.Module.__init__(self)
39
+ self.lora_name = lora_name
40
+ self.lora_dim = lora_dim
41
+ self.cp = False
42
+
43
+ # check if parent has bias. if not force use_bias to False
44
+ if org_module.bias is None:
45
+ use_bias = False
46
+
47
+ self.scalar = nn.Parameter(torch.tensor(0.0))
48
+ orig_module_name = org_module.__class__.__name__
49
+ if orig_module_name in CONV_MODULES:
50
+ self.isconv = True
51
+ # For general LoCon
52
+ in_dim = org_module.in_channels
53
+ k_size = org_module.kernel_size
54
+ stride = org_module.stride
55
+ padding = org_module.padding
56
+ out_dim = org_module.out_channels
57
+ self.down_op = F.conv2d
58
+ self.up_op = F.conv2d
59
+ if use_cp and k_size != (1, 1):
60
+ self.lora_down = nn.Conv2d(in_dim, lora_dim, (1, 1), bias=False)
61
+ self.lora_mid = nn.Conv2d(lora_dim, lora_dim, k_size, stride, padding, bias=False)
62
+ self.cp = True
63
+ else:
64
+ self.lora_down = nn.Conv2d(in_dim, lora_dim, k_size, stride, padding, bias=False)
65
+ self.lora_up = nn.Conv2d(lora_dim, out_dim, (1, 1), bias=use_bias)
66
+ elif orig_module_name in LINEAR_MODULES:
67
+ self.isconv = False
68
+ self.down_op = F.linear
69
+ self.up_op = F.linear
70
+ if orig_module_name == 'GroupNorm':
71
+ # RuntimeError: mat1 and mat2 shapes cannot be multiplied (56320x120 and 320x32)
72
+ in_dim = org_module.num_channels
73
+ out_dim = org_module.num_channels
74
+ else:
75
+ in_dim = org_module.in_features
76
+ out_dim = org_module.out_features
77
+ self.lora_down = nn.Linear(in_dim, lora_dim, bias=False)
78
+ self.lora_up = nn.Linear(lora_dim, out_dim, bias=use_bias)
79
+ else:
80
+ raise NotImplementedError
81
+ self.shape = org_module.weight.shape
82
+
83
+ if dropout:
84
+ self.dropout = nn.Dropout(dropout)
85
+ else:
86
+ self.dropout = nn.Identity()
87
+ self.rank_dropout = rank_dropout
88
+ self.module_dropout = module_dropout
89
+
90
+ if type(alpha) == torch.Tensor:
91
+ alpha = alpha.detach().float().numpy() # without casting, bf16 causes error
92
+ alpha = lora_dim if alpha is None or alpha == 0 else alpha
93
+ self.scale = alpha / self.lora_dim
94
+ self.register_buffer('alpha', torch.tensor(alpha)) # 定数として扱える
95
+
96
+ # same as microsoft's
97
+ torch.nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))
98
+ torch.nn.init.kaiming_uniform_(self.lora_up.weight)
99
+ if self.cp:
100
+ torch.nn.init.kaiming_uniform_(self.lora_mid.weight, a=math.sqrt(5))
101
+
102
+ self.multiplier = multiplier
103
+ self.org_module = [org_module]
104
+ self.register_load_state_dict_post_hook(self.load_weight_hook)
105
+
106
+ def load_weight_hook(self, *args, **kwargs):
107
+ self.scalar = nn.Parameter(torch.ones_like(self.scalar))
108
+
109
+
110
+ class LycorisSpecialNetwork(ToolkitNetworkMixin, LycorisNetwork):
111
+ UNET_TARGET_REPLACE_MODULE = [
112
+ "Transformer2DModel",
113
+ "ResnetBlock2D",
114
+ "Downsample2D",
115
+ "Upsample2D",
116
+ # 'UNet2DConditionModel',
117
+ # 'Conv2d',
118
+ # 'Timesteps',
119
+ # 'TimestepEmbedding',
120
+ # 'Linear',
121
+ # 'SiLU',
122
+ # 'ModuleList',
123
+ # 'DownBlock2D',
124
+ # 'ResnetBlock2D', # need
125
+ # 'GroupNorm',
126
+ # 'LoRACompatibleConv',
127
+ # 'LoRACompatibleLinear',
128
+ # 'Dropout',
129
+ # 'CrossAttnDownBlock2D', # needed
130
+ # 'Transformer2DModel', # maybe not, has duplicates
131
+ # 'BasicTransformerBlock', # duplicates
132
+ # 'LayerNorm',
133
+ # 'Attention',
134
+ # 'FeedForward',
135
+ # 'GEGLU',
136
+ # 'UpBlock2D',
137
+ # 'UNetMidBlock2DCrossAttn'
138
+ ]
139
+ UNET_TARGET_REPLACE_NAME = [
140
+ "conv_in",
141
+ "conv_out",
142
+ "time_embedding.linear_1",
143
+ "time_embedding.linear_2",
144
+ ]
145
+ def __init__(
146
+ self,
147
+ text_encoder: Union[List[CLIPTextModel], CLIPTextModel],
148
+ unet,
149
+ multiplier: float = 1.0,
150
+ lora_dim: int = 4,
151
+ alpha: float = 1,
152
+ dropout: Optional[float] = None,
153
+ rank_dropout: Optional[float] = None,
154
+ module_dropout: Optional[float] = None,
155
+ conv_lora_dim: Optional[int] = None,
156
+ conv_alpha: Optional[float] = None,
157
+ use_cp: Optional[bool] = False,
158
+ network_module: Type[object] = LoConSpecialModule,
159
+ train_unet: bool = True,
160
+ train_text_encoder: bool = True,
161
+ use_text_encoder_1: bool = True,
162
+ use_text_encoder_2: bool = True,
163
+ use_bias: bool = False,
164
+ is_lorm: bool = False,
165
+ **kwargs,
166
+ ) -> None:
167
+ # call ToolkitNetworkMixin super
168
+ ToolkitNetworkMixin.__init__(
169
+ self,
170
+ train_text_encoder=train_text_encoder,
171
+ train_unet=train_unet,
172
+ is_lorm=is_lorm,
173
+ **kwargs
174
+ )
175
+ # call the parent of the parent LycorisNetwork
176
+ torch.nn.Module.__init__(self)
177
+
178
+ # LyCORIS unique stuff
179
+ if dropout is None:
180
+ dropout = 0
181
+ if rank_dropout is None:
182
+ rank_dropout = 0
183
+ if module_dropout is None:
184
+ module_dropout = 0
185
+ self.train_unet = train_unet
186
+ self.train_text_encoder = train_text_encoder
187
+
188
+ self.torch_multiplier = None
189
+ # triggers a tensor update
190
+ self.multiplier = multiplier
191
+ self.lora_dim = lora_dim
192
+
193
+ if not self.ENABLE_CONV or conv_lora_dim is None:
194
+ conv_lora_dim = 0
195
+ conv_alpha = 0
196
+
197
+ self.conv_lora_dim = int(conv_lora_dim)
198
+ if self.conv_lora_dim and self.conv_lora_dim != self.lora_dim:
199
+ print('Apply different lora dim for conv layer')
200
+ print(f'Conv Dim: {conv_lora_dim}, Linear Dim: {lora_dim}')
201
+ elif self.conv_lora_dim == 0:
202
+ print('Disable conv layer')
203
+
204
+ self.alpha = alpha
205
+ self.conv_alpha = float(conv_alpha)
206
+ if self.conv_lora_dim and self.alpha != self.conv_alpha:
207
+ print('Apply different alpha value for conv layer')
208
+ print(f'Conv alpha: {conv_alpha}, Linear alpha: {alpha}')
209
+
210
+ if 1 >= dropout >= 0:
211
+ print(f'Use Dropout value: {dropout}')
212
+ self.dropout = dropout
213
+ self.rank_dropout = rank_dropout
214
+ self.module_dropout = module_dropout
215
+
216
+ # create module instances
217
+ def create_modules(
218
+ prefix,
219
+ root_module: torch.nn.Module,
220
+ target_replace_modules,
221
+ target_replace_names=[]
222
+ ) -> List[network_module]:
223
+ print('Create LyCORIS Module')
224
+ loras = []
225
+ # remove this
226
+ named_modules = root_module.named_modules()
227
+ # add a few to tthe generator
228
+
229
+ for name, module in named_modules:
230
+ module_name = module.__class__.__name__
231
+ if module_name in target_replace_modules:
232
+ if module_name in self.MODULE_ALGO_MAP:
233
+ algo = self.MODULE_ALGO_MAP[module_name]
234
+ else:
235
+ algo = network_module
236
+ for child_name, child_module in module.named_modules():
237
+ lora_name = prefix + '.' + name + '.' + child_name
238
+ lora_name = lora_name.replace('.', '_')
239
+ if lora_name.startswith('lora_unet_input_blocks_1_0_emb_layers_1'):
240
+ print(f"{lora_name}")
241
+
242
+ if child_module.__class__.__name__ in LINEAR_MODULES and lora_dim > 0:
243
+ lora = algo(
244
+ lora_name, child_module, self.multiplier,
245
+ self.lora_dim, self.alpha,
246
+ self.dropout, self.rank_dropout, self.module_dropout,
247
+ use_cp,
248
+ network=self,
249
+ parent=module,
250
+ use_bias=use_bias,
251
+ **kwargs
252
+ )
253
+ elif child_module.__class__.__name__ in CONV_MODULES:
254
+ k_size, *_ = child_module.kernel_size
255
+ if k_size == 1 and lora_dim > 0:
256
+ lora = algo(
257
+ lora_name, child_module, self.multiplier,
258
+ self.lora_dim, self.alpha,
259
+ self.dropout, self.rank_dropout, self.module_dropout,
260
+ use_cp,
261
+ network=self,
262
+ parent=module,
263
+ use_bias=use_bias,
264
+ **kwargs
265
+ )
266
+ elif conv_lora_dim > 0:
267
+ lora = algo(
268
+ lora_name, child_module, self.multiplier,
269
+ self.conv_lora_dim, self.conv_alpha,
270
+ self.dropout, self.rank_dropout, self.module_dropout,
271
+ use_cp,
272
+ network=self,
273
+ parent=module,
274
+ use_bias=use_bias,
275
+ **kwargs
276
+ )
277
+ else:
278
+ continue
279
+ else:
280
+ continue
281
+ loras.append(lora)
282
+ elif name in target_replace_names:
283
+ if name in self.NAME_ALGO_MAP:
284
+ algo = self.NAME_ALGO_MAP[name]
285
+ else:
286
+ algo = network_module
287
+ lora_name = prefix + '.' + name
288
+ lora_name = lora_name.replace('.', '_')
289
+ if module.__class__.__name__ == 'Linear' and lora_dim > 0:
290
+ lora = algo(
291
+ lora_name, module, self.multiplier,
292
+ self.lora_dim, self.alpha,
293
+ self.dropout, self.rank_dropout, self.module_dropout,
294
+ use_cp,
295
+ parent=module,
296
+ network=self,
297
+ use_bias=use_bias,
298
+ **kwargs
299
+ )
300
+ elif module.__class__.__name__ == 'Conv2d':
301
+ k_size, *_ = module.kernel_size
302
+ if k_size == 1 and lora_dim > 0:
303
+ lora = algo(
304
+ lora_name, module, self.multiplier,
305
+ self.lora_dim, self.alpha,
306
+ self.dropout, self.rank_dropout, self.module_dropout,
307
+ use_cp,
308
+ network=self,
309
+ parent=module,
310
+ use_bias=use_bias,
311
+ **kwargs
312
+ )
313
+ elif conv_lora_dim > 0:
314
+ lora = algo(
315
+ lora_name, module, self.multiplier,
316
+ self.conv_lora_dim, self.conv_alpha,
317
+ self.dropout, self.rank_dropout, self.module_dropout,
318
+ use_cp,
319
+ network=self,
320
+ parent=module,
321
+ use_bias=use_bias,
322
+ **kwargs
323
+ )
324
+ else:
325
+ continue
326
+ else:
327
+ continue
328
+ loras.append(lora)
329
+ return loras
330
+
331
+ if network_module == GLoRAModule:
332
+ print('GLoRA enabled, only train transformer')
333
+ # only train transformer (for GLoRA)
334
+ LycorisSpecialNetwork.UNET_TARGET_REPLACE_MODULE = [
335
+ "Transformer2DModel",
336
+ "Attention",
337
+ ]
338
+ LycorisSpecialNetwork.UNET_TARGET_REPLACE_NAME = []
339
+
340
+ if isinstance(text_encoder, list):
341
+ text_encoders = text_encoder
342
+ use_index = True
343
+ else:
344
+ text_encoders = [text_encoder]
345
+ use_index = False
346
+
347
+ self.text_encoder_loras = []
348
+ if self.train_text_encoder:
349
+ for i, te in enumerate(text_encoders):
350
+ if not use_text_encoder_1 and i == 0:
351
+ continue
352
+ if not use_text_encoder_2 and i == 1:
353
+ continue
354
+ self.text_encoder_loras.extend(create_modules(
355
+ LycorisSpecialNetwork.LORA_PREFIX_TEXT_ENCODER + (f'{i + 1}' if use_index else ''),
356
+ te,
357
+ LycorisSpecialNetwork.TEXT_ENCODER_TARGET_REPLACE_MODULE
358
+ ))
359
+ print(f"create LyCORIS for Text Encoder: {len(self.text_encoder_loras)} modules.")
360
+ if self.train_unet:
361
+ self.unet_loras = create_modules(LycorisSpecialNetwork.LORA_PREFIX_UNET, unet,
362
+ LycorisSpecialNetwork.UNET_TARGET_REPLACE_MODULE)
363
+ else:
364
+ self.unet_loras = []
365
+ print(f"create LyCORIS for U-Net: {len(self.unet_loras)} modules.")
366
+
367
+ self.weights_sd = None
368
+
369
+ # assertion
370
+ names = set()
371
+ for lora in self.text_encoder_loras + self.unet_loras:
372
+ assert lora.lora_name not in names, f"duplicated lora name: {lora.lora_name}"
373
+ names.add(lora.lora_name)
toolkit/lycoris_utils.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # heavily based on https://github.com/KohakuBlueleaf/LyCORIS/blob/main/lycoris/utils.py
2
+
3
+ from typing import *
4
+
5
+ import numpy as np
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ import torch.linalg as linalg
12
+
13
+ from tqdm import tqdm
14
+ from collections import OrderedDict
15
+
16
+
17
+ def make_sparse(t: torch.Tensor, sparsity=0.95):
18
+ abs_t = torch.abs(t)
19
+ np_array = abs_t.detach().cpu().numpy()
20
+ quan = float(np.quantile(np_array, sparsity))
21
+ sparse_t = t.masked_fill(abs_t < quan, 0)
22
+ return sparse_t
23
+
24
+
25
+ def extract_conv(
26
+ weight: Union[torch.Tensor, nn.Parameter],
27
+ mode='fixed',
28
+ mode_param=0,
29
+ device='cpu',
30
+ is_cp=False,
31
+ ) -> Tuple[nn.Parameter, nn.Parameter]:
32
+ weight = weight.to(device)
33
+ out_ch, in_ch, kernel_size, _ = weight.shape
34
+
35
+ U, S, Vh = linalg.svd(weight.reshape(out_ch, -1))
36
+
37
+ if mode == 'fixed':
38
+ lora_rank = mode_param
39
+ elif mode == 'threshold':
40
+ assert mode_param >= 0
41
+ lora_rank = torch.sum(S > mode_param)
42
+ elif mode == 'ratio':
43
+ assert 1 >= mode_param >= 0
44
+ min_s = torch.max(S) * mode_param
45
+ lora_rank = torch.sum(S > min_s)
46
+ elif mode == 'quantile' or mode == 'percentile':
47
+ assert 1 >= mode_param >= 0
48
+ s_cum = torch.cumsum(S, dim=0)
49
+ min_cum_sum = mode_param * torch.sum(S)
50
+ lora_rank = torch.sum(s_cum < min_cum_sum)
51
+ else:
52
+ raise NotImplementedError('Extract mode should be "fixed", "threshold", "ratio" or "quantile"')
53
+ lora_rank = max(1, lora_rank)
54
+ lora_rank = min(out_ch, in_ch, lora_rank)
55
+ if lora_rank >= out_ch / 2 and not is_cp:
56
+ return weight, 'full'
57
+
58
+ U = U[:, :lora_rank]
59
+ S = S[:lora_rank]
60
+ U = U @ torch.diag(S)
61
+ Vh = Vh[:lora_rank, :]
62
+
63
+ diff = (weight - (U @ Vh).reshape(out_ch, in_ch, kernel_size, kernel_size)).detach()
64
+ extract_weight_A = Vh.reshape(lora_rank, in_ch, kernel_size, kernel_size).detach()
65
+ extract_weight_B = U.reshape(out_ch, lora_rank, 1, 1).detach()
66
+ del U, S, Vh, weight
67
+ return (extract_weight_A, extract_weight_B, diff), 'low rank'
68
+
69
+
70
+ def extract_linear(
71
+ weight: Union[torch.Tensor, nn.Parameter],
72
+ mode='fixed',
73
+ mode_param=0,
74
+ device='cpu',
75
+ ) -> Tuple[nn.Parameter, nn.Parameter]:
76
+ weight = weight.to(device)
77
+ out_ch, in_ch = weight.shape
78
+
79
+ U, S, Vh = linalg.svd(weight)
80
+
81
+ if mode == 'fixed':
82
+ lora_rank = mode_param
83
+ elif mode == 'threshold':
84
+ assert mode_param >= 0
85
+ lora_rank = torch.sum(S > mode_param)
86
+ elif mode == 'ratio':
87
+ assert 1 >= mode_param >= 0
88
+ min_s = torch.max(S) * mode_param
89
+ lora_rank = torch.sum(S > min_s)
90
+ elif mode == 'quantile' or mode == 'percentile':
91
+ assert 1 >= mode_param >= 0
92
+ s_cum = torch.cumsum(S, dim=0)
93
+ min_cum_sum = mode_param * torch.sum(S)
94
+ lora_rank = torch.sum(s_cum < min_cum_sum)
95
+ else:
96
+ raise NotImplementedError('Extract mode should be "fixed", "threshold", "ratio" or "quantile"')
97
+ lora_rank = max(1, lora_rank)
98
+ lora_rank = min(out_ch, in_ch, lora_rank)
99
+ if lora_rank >= out_ch / 2:
100
+ return weight, 'full'
101
+
102
+ U = U[:, :lora_rank]
103
+ S = S[:lora_rank]
104
+ U = U @ torch.diag(S)
105
+ Vh = Vh[:lora_rank, :]
106
+
107
+ diff = (weight - U @ Vh).detach()
108
+ extract_weight_A = Vh.reshape(lora_rank, in_ch).detach()
109
+ extract_weight_B = U.reshape(out_ch, lora_rank).detach()
110
+ del U, S, Vh, weight
111
+ return (extract_weight_A, extract_weight_B, diff), 'low rank'
112
+
113
+
114
+ def extract_diff(
115
+ base_model,
116
+ db_model,
117
+ mode='fixed',
118
+ linear_mode_param=0,
119
+ conv_mode_param=0,
120
+ extract_device='cpu',
121
+ use_bias=False,
122
+ sparsity=0.98,
123
+ small_conv=True,
124
+ linear_only=False,
125
+ extract_unet=True,
126
+ extract_text_encoder=True,
127
+ ):
128
+ meta = OrderedDict()
129
+
130
+ UNET_TARGET_REPLACE_MODULE = [
131
+ "Transformer2DModel",
132
+ "Attention",
133
+ "ResnetBlock2D",
134
+ "Downsample2D",
135
+ "Upsample2D"
136
+ ]
137
+ UNET_TARGET_REPLACE_NAME = [
138
+ "conv_in",
139
+ "conv_out",
140
+ "time_embedding.linear_1",
141
+ "time_embedding.linear_2",
142
+ ]
143
+ if linear_only:
144
+ UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel", "Attention"]
145
+ UNET_TARGET_REPLACE_NAME = [
146
+ "conv_in",
147
+ "conv_out",
148
+ ]
149
+
150
+ if not extract_unet:
151
+ UNET_TARGET_REPLACE_MODULE = []
152
+ UNET_TARGET_REPLACE_NAME = []
153
+
154
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
155
+
156
+ if not extract_text_encoder:
157
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = []
158
+
159
+ LORA_PREFIX_UNET = 'lora_unet'
160
+ LORA_PREFIX_TEXT_ENCODER = 'lora_te'
161
+
162
+ def make_state_dict(
163
+ prefix,
164
+ root_module: torch.nn.Module,
165
+ target_module: torch.nn.Module,
166
+ target_replace_modules,
167
+ target_replace_names=[]
168
+ ):
169
+ loras = {}
170
+ temp = {}
171
+ temp_name = {}
172
+
173
+ for name, module in root_module.named_modules():
174
+ if module.__class__.__name__ in target_replace_modules:
175
+ temp[name] = {}
176
+ for child_name, child_module in module.named_modules():
177
+ if child_module.__class__.__name__ not in {'Linear', 'LoRACompatibleLinear', 'Conv2d', 'LoRACompatibleConv'}:
178
+ continue
179
+ temp[name][child_name] = child_module.weight
180
+ elif name in target_replace_names:
181
+ temp_name[name] = module.weight
182
+
183
+ for name, module in tqdm(list(target_module.named_modules())):
184
+ if name in temp:
185
+ weights = temp[name]
186
+ for child_name, child_module in module.named_modules():
187
+ lora_name = prefix + '.' + name + '.' + child_name
188
+ lora_name = lora_name.replace('.', '_')
189
+ layer = child_module.__class__.__name__
190
+ if layer in {'Linear', 'LoRACompatibleLinear', 'Conv2d', 'LoRACompatibleConv'}:
191
+ root_weight = child_module.weight
192
+ if torch.allclose(root_weight, weights[child_name]):
193
+ continue
194
+
195
+ if layer == 'Linear' or layer == 'LoRACompatibleLinear':
196
+ weight, decompose_mode = extract_linear(
197
+ (child_module.weight - weights[child_name]),
198
+ mode,
199
+ linear_mode_param,
200
+ device=extract_device,
201
+ )
202
+ if decompose_mode == 'low rank':
203
+ extract_a, extract_b, diff = weight
204
+ elif layer == 'Conv2d' or layer == 'LoRACompatibleConv':
205
+ is_linear = (child_module.weight.shape[2] == 1
206
+ and child_module.weight.shape[3] == 1)
207
+ if not is_linear and linear_only:
208
+ continue
209
+ weight, decompose_mode = extract_conv(
210
+ (child_module.weight - weights[child_name]),
211
+ mode,
212
+ linear_mode_param if is_linear else conv_mode_param,
213
+ device=extract_device,
214
+ )
215
+ if decompose_mode == 'low rank':
216
+ extract_a, extract_b, diff = weight
217
+ if small_conv and not is_linear and decompose_mode == 'low rank':
218
+ dim = extract_a.size(0)
219
+ (extract_c, extract_a, _), _ = extract_conv(
220
+ extract_a.transpose(0, 1),
221
+ 'fixed', dim,
222
+ extract_device, True
223
+ )
224
+ extract_a = extract_a.transpose(0, 1)
225
+ extract_c = extract_c.transpose(0, 1)
226
+ loras[f'{lora_name}.lora_mid.weight'] = extract_c.detach().cpu().contiguous().half()
227
+ diff = child_module.weight - torch.einsum(
228
+ 'i j k l, j r, p i -> p r k l',
229
+ extract_c, extract_a.flatten(1, -1), extract_b.flatten(1, -1)
230
+ ).detach().cpu().contiguous()
231
+ del extract_c
232
+ else:
233
+ continue
234
+ if decompose_mode == 'low rank':
235
+ loras[f'{lora_name}.lora_down.weight'] = extract_a.detach().cpu().contiguous().half()
236
+ loras[f'{lora_name}.lora_up.weight'] = extract_b.detach().cpu().contiguous().half()
237
+ loras[f'{lora_name}.alpha'] = torch.Tensor([extract_a.shape[0]]).half()
238
+ if use_bias:
239
+ diff = diff.detach().cpu().reshape(extract_b.size(0), -1)
240
+ sparse_diff = make_sparse(diff, sparsity).to_sparse().coalesce()
241
+
242
+ indices = sparse_diff.indices().to(torch.int16)
243
+ values = sparse_diff.values().half()
244
+ loras[f'{lora_name}.bias_indices'] = indices
245
+ loras[f'{lora_name}.bias_values'] = values
246
+ loras[f'{lora_name}.bias_size'] = torch.tensor(diff.shape).to(torch.int16)
247
+ del extract_a, extract_b, diff
248
+ elif decompose_mode == 'full':
249
+ loras[f'{lora_name}.diff'] = weight.detach().cpu().contiguous().half()
250
+ else:
251
+ raise NotImplementedError
252
+ elif name in temp_name:
253
+ weights = temp_name[name]
254
+ lora_name = prefix + '.' + name
255
+ lora_name = lora_name.replace('.', '_')
256
+ layer = module.__class__.__name__
257
+
258
+ if layer in {'Linear', 'LoRACompatibleLinear', 'Conv2d', 'LoRACompatibleConv'}:
259
+ root_weight = module.weight
260
+ if torch.allclose(root_weight, weights):
261
+ continue
262
+
263
+ if layer == 'Linear' or layer == 'LoRACompatibleLinear':
264
+ weight, decompose_mode = extract_linear(
265
+ (root_weight - weights),
266
+ mode,
267
+ linear_mode_param,
268
+ device=extract_device,
269
+ )
270
+ if decompose_mode == 'low rank':
271
+ extract_a, extract_b, diff = weight
272
+ elif layer == 'Conv2d' or layer == 'LoRACompatibleConv':
273
+ is_linear = (
274
+ root_weight.shape[2] == 1
275
+ and root_weight.shape[3] == 1
276
+ )
277
+ if not is_linear and linear_only:
278
+ continue
279
+ weight, decompose_mode = extract_conv(
280
+ (root_weight - weights),
281
+ mode,
282
+ linear_mode_param if is_linear else conv_mode_param,
283
+ device=extract_device,
284
+ )
285
+ if decompose_mode == 'low rank':
286
+ extract_a, extract_b, diff = weight
287
+ if small_conv and not is_linear and decompose_mode == 'low rank':
288
+ dim = extract_a.size(0)
289
+ (extract_c, extract_a, _), _ = extract_conv(
290
+ extract_a.transpose(0, 1),
291
+ 'fixed', dim,
292
+ extract_device, True
293
+ )
294
+ extract_a = extract_a.transpose(0, 1)
295
+ extract_c = extract_c.transpose(0, 1)
296
+ loras[f'{lora_name}.lora_mid.weight'] = extract_c.detach().cpu().contiguous().half()
297
+ diff = root_weight - torch.einsum(
298
+ 'i j k l, j r, p i -> p r k l',
299
+ extract_c, extract_a.flatten(1, -1), extract_b.flatten(1, -1)
300
+ ).detach().cpu().contiguous()
301
+ del extract_c
302
+ else:
303
+ continue
304
+ if decompose_mode == 'low rank':
305
+ loras[f'{lora_name}.lora_down.weight'] = extract_a.detach().cpu().contiguous().half()
306
+ loras[f'{lora_name}.lora_up.weight'] = extract_b.detach().cpu().contiguous().half()
307
+ loras[f'{lora_name}.alpha'] = torch.Tensor([extract_a.shape[0]]).half()
308
+ if use_bias:
309
+ diff = diff.detach().cpu().reshape(extract_b.size(0), -1)
310
+ sparse_diff = make_sparse(diff, sparsity).to_sparse().coalesce()
311
+
312
+ indices = sparse_diff.indices().to(torch.int16)
313
+ values = sparse_diff.values().half()
314
+ loras[f'{lora_name}.bias_indices'] = indices
315
+ loras[f'{lora_name}.bias_values'] = values
316
+ loras[f'{lora_name}.bias_size'] = torch.tensor(diff.shape).to(torch.int16)
317
+ del extract_a, extract_b, diff
318
+ elif decompose_mode == 'full':
319
+ loras[f'{lora_name}.diff'] = weight.detach().cpu().contiguous().half()
320
+ else:
321
+ raise NotImplementedError
322
+ return loras
323
+
324
+ text_encoder_loras = make_state_dict(
325
+ LORA_PREFIX_TEXT_ENCODER,
326
+ base_model[0], db_model[0],
327
+ TEXT_ENCODER_TARGET_REPLACE_MODULE
328
+ )
329
+
330
+ unet_loras = make_state_dict(
331
+ LORA_PREFIX_UNET,
332
+ base_model[2], db_model[2],
333
+ UNET_TARGET_REPLACE_MODULE,
334
+ UNET_TARGET_REPLACE_NAME
335
+ )
336
+ print(len(text_encoder_loras), len(unet_loras))
337
+ # the | will
338
+ return (text_encoder_loras | unet_loras), meta
339
+
340
+
341
+ def get_module(
342
+ lyco_state_dict: Dict,
343
+ lora_name
344
+ ):
345
+ if f'{lora_name}.lora_up.weight' in lyco_state_dict:
346
+ up = lyco_state_dict[f'{lora_name}.lora_up.weight']
347
+ down = lyco_state_dict[f'{lora_name}.lora_down.weight']
348
+ mid = lyco_state_dict.get(f'{lora_name}.lora_mid.weight', None)
349
+ alpha = lyco_state_dict.get(f'{lora_name}.alpha', None)
350
+ return 'locon', (up, down, mid, alpha)
351
+ elif f'{lora_name}.hada_w1_a' in lyco_state_dict:
352
+ w1a = lyco_state_dict[f'{lora_name}.hada_w1_a']
353
+ w1b = lyco_state_dict[f'{lora_name}.hada_w1_b']
354
+ w2a = lyco_state_dict[f'{lora_name}.hada_w2_a']
355
+ w2b = lyco_state_dict[f'{lora_name}.hada_w2_b']
356
+ t1 = lyco_state_dict.get(f'{lora_name}.hada_t1', None)
357
+ t2 = lyco_state_dict.get(f'{lora_name}.hada_t2', None)
358
+ alpha = lyco_state_dict.get(f'{lora_name}.alpha', None)
359
+ return 'hada', (w1a, w1b, w2a, w2b, t1, t2, alpha)
360
+ elif f'{lora_name}.weight' in lyco_state_dict:
361
+ weight = lyco_state_dict[f'{lora_name}.weight']
362
+ on_input = lyco_state_dict.get(f'{lora_name}.on_input', False)
363
+ return 'ia3', (weight, on_input)
364
+ elif (f'{lora_name}.lokr_w1' in lyco_state_dict
365
+ or f'{lora_name}.lokr_w1_a' in lyco_state_dict):
366
+ w1 = lyco_state_dict.get(f'{lora_name}.lokr_w1', None)
367
+ w1a = lyco_state_dict.get(f'{lora_name}.lokr_w1_a', None)
368
+ w1b = lyco_state_dict.get(f'{lora_name}.lokr_w1_b', None)
369
+ w2 = lyco_state_dict.get(f'{lora_name}.lokr_w2', None)
370
+ w2a = lyco_state_dict.get(f'{lora_name}.lokr_w2_a', None)
371
+ w2b = lyco_state_dict.get(f'{lora_name}.lokr_w2_b', None)
372
+ t1 = lyco_state_dict.get(f'{lora_name}.lokr_t1', None)
373
+ t2 = lyco_state_dict.get(f'{lora_name}.lokr_t2', None)
374
+ alpha = lyco_state_dict.get(f'{lora_name}.alpha', None)
375
+ return 'kron', (w1, w1a, w1b, w2, w2a, w2b, t1, t2, alpha)
376
+ elif f'{lora_name}.diff' in lyco_state_dict:
377
+ return 'full', lyco_state_dict[f'{lora_name}.diff']
378
+ else:
379
+ return 'None', ()
380
+
381
+
382
+ def cp_weight_from_conv(
383
+ up, down, mid
384
+ ):
385
+ up = up.reshape(up.size(0), up.size(1))
386
+ down = down.reshape(down.size(0), down.size(1))
387
+ return torch.einsum('m n w h, i m, n j -> i j w h', mid, up, down)
388
+
389
+
390
+ def cp_weight(
391
+ wa, wb, t
392
+ ):
393
+ temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
394
+ return torch.einsum('i j k l, i r -> r j k l', temp, wa)
395
+
396
+
397
+ @torch.no_grad()
398
+ def rebuild_weight(module_type, params, orig_weight, scale=1):
399
+ if orig_weight is None:
400
+ return orig_weight
401
+ merged = orig_weight
402
+ if module_type == 'locon':
403
+ up, down, mid, alpha = params
404
+ if alpha is not None:
405
+ scale *= alpha / up.size(1)
406
+ if mid is not None:
407
+ rebuild = cp_weight_from_conv(up, down, mid)
408
+ else:
409
+ rebuild = up.reshape(up.size(0), -1) @ down.reshape(down.size(0), -1)
410
+ merged = orig_weight + rebuild.reshape(orig_weight.shape) * scale
411
+ del up, down, mid, alpha, params, rebuild
412
+ elif module_type == 'hada':
413
+ w1a, w1b, w2a, w2b, t1, t2, alpha = params
414
+ if alpha is not None:
415
+ scale *= alpha / w1b.size(0)
416
+ if t1 is not None:
417
+ rebuild1 = cp_weight(w1a, w1b, t1)
418
+ else:
419
+ rebuild1 = w1a @ w1b
420
+ if t2 is not None:
421
+ rebuild2 = cp_weight(w2a, w2b, t2)
422
+ else:
423
+ rebuild2 = w2a @ w2b
424
+ rebuild = (rebuild1 * rebuild2).reshape(orig_weight.shape)
425
+ merged = orig_weight + rebuild * scale
426
+ del w1a, w1b, w2a, w2b, t1, t2, alpha, params, rebuild, rebuild1, rebuild2
427
+ elif module_type == 'ia3':
428
+ weight, on_input = params
429
+ if not on_input:
430
+ weight = weight.reshape(-1, 1)
431
+ merged = orig_weight + weight * orig_weight * scale
432
+ del weight, on_input, params
433
+ elif module_type == 'kron':
434
+ w1, w1a, w1b, w2, w2a, w2b, t1, t2, alpha = params
435
+ if alpha is not None and (w1b is not None or w2b is not None):
436
+ scale *= alpha / (w1b.size(0) if w1b else w2b.size(0))
437
+ if w1a is not None and w1b is not None:
438
+ if t1:
439
+ w1 = cp_weight(w1a, w1b, t1)
440
+ else:
441
+ w1 = w1a @ w1b
442
+ if w2a is not None and w2b is not None:
443
+ if t2:
444
+ w2 = cp_weight(w2a, w2b, t2)
445
+ else:
446
+ w2 = w2a @ w2b
447
+ rebuild = torch.kron(w1, w2).reshape(orig_weight.shape)
448
+ merged = orig_weight + rebuild * scale
449
+ del w1, w1a, w1b, w2, w2a, w2b, t1, t2, alpha, params, rebuild
450
+ elif module_type == 'full':
451
+ rebuild = params.reshape(orig_weight.shape)
452
+ merged = orig_weight + rebuild * scale
453
+ del params, rebuild
454
+
455
+ return merged
456
+
457
+
458
+ def merge(
459
+ base_model,
460
+ lyco_state_dict,
461
+ scale: float = 1.0,
462
+ device='cpu'
463
+ ):
464
+ UNET_TARGET_REPLACE_MODULE = [
465
+ "Transformer2DModel",
466
+ "Attention",
467
+ "ResnetBlock2D",
468
+ "Downsample2D",
469
+ "Upsample2D"
470
+ ]
471
+ UNET_TARGET_REPLACE_NAME = [
472
+ "conv_in",
473
+ "conv_out",
474
+ "time_embedding.linear_1",
475
+ "time_embedding.linear_2",
476
+ ]
477
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
478
+ LORA_PREFIX_UNET = 'lora_unet'
479
+ LORA_PREFIX_TEXT_ENCODER = 'lora_te'
480
+ merged = 0
481
+
482
+ def merge_state_dict(
483
+ prefix,
484
+ root_module: torch.nn.Module,
485
+ lyco_state_dict: Dict[str, torch.Tensor],
486
+ target_replace_modules,
487
+ target_replace_names=[]
488
+ ):
489
+ nonlocal merged
490
+ for name, module in tqdm(list(root_module.named_modules()), desc=f'Merging {prefix}'):
491
+ if module.__class__.__name__ in target_replace_modules:
492
+ for child_name, child_module in module.named_modules():
493
+ if child_module.__class__.__name__ not in {'Linear', 'LoRACompatibleLinear', 'Conv2d',
494
+ 'LoRACompatibleConv'}:
495
+ continue
496
+ lora_name = prefix + '.' + name + '.' + child_name
497
+ lora_name = lora_name.replace('.', '_')
498
+
499
+ result = rebuild_weight(*get_module(
500
+ lyco_state_dict, lora_name
501
+ ), getattr(child_module, 'weight'), scale)
502
+ if result is not None:
503
+ merged += 1
504
+ child_module.requires_grad_(False)
505
+ child_module.weight.copy_(result)
506
+ elif name in target_replace_names:
507
+ lora_name = prefix + '.' + name
508
+ lora_name = lora_name.replace('.', '_')
509
+
510
+ result = rebuild_weight(*get_module(
511
+ lyco_state_dict, lora_name
512
+ ), getattr(module, 'weight'), scale)
513
+ if result is not None:
514
+ merged += 1
515
+ module.requires_grad_(False)
516
+ module.weight.copy_(result)
517
+
518
+ if device == 'cpu':
519
+ for k, v in tqdm(list(lyco_state_dict.items()), desc='Converting Dtype'):
520
+ lyco_state_dict[k] = v.float()
521
+
522
+ merge_state_dict(
523
+ LORA_PREFIX_TEXT_ENCODER,
524
+ base_model[0],
525
+ lyco_state_dict,
526
+ TEXT_ENCODER_TARGET_REPLACE_MODULE,
527
+ UNET_TARGET_REPLACE_NAME
528
+ )
529
+ merge_state_dict(
530
+ LORA_PREFIX_UNET,
531
+ base_model[2],
532
+ lyco_state_dict,
533
+ UNET_TARGET_REPLACE_MODULE,
534
+ UNET_TARGET_REPLACE_NAME
535
+ )
536
+ print(f'{merged} Modules been merged')
toolkit/metadata.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections import OrderedDict
3
+ from io import BytesIO
4
+
5
+ import safetensors
6
+ from safetensors import safe_open
7
+
8
+ from info import software_meta
9
+ from toolkit.train_tools import addnet_hash_legacy
10
+ from toolkit.train_tools import addnet_hash_safetensors
11
+
12
+
13
+ def get_meta_for_safetensors(meta: OrderedDict, name=None, add_software_info=True) -> OrderedDict:
14
+ # stringify the meta and reparse OrderedDict to replace [name] with name
15
+ meta_string = json.dumps(meta)
16
+ if name is not None:
17
+ meta_string = meta_string.replace("[name]", name)
18
+ save_meta = json.loads(meta_string, object_pairs_hook=OrderedDict)
19
+ if add_software_info:
20
+ save_meta["software"] = software_meta
21
+ # safetensors can only be one level deep
22
+ for key, value in save_meta.items():
23
+ # if not float, int, bool, or str, convert to json string
24
+ if not isinstance(value, str):
25
+ save_meta[key] = json.dumps(value)
26
+ # add the pt format
27
+ save_meta["format"] = "pt"
28
+ return save_meta
29
+
30
+
31
+ def add_model_hash_to_meta(state_dict, meta: OrderedDict) -> OrderedDict:
32
+ """Precalculate the model hashes needed by sd-webui-additional-networks to
33
+ save time on indexing the model later."""
34
+
35
+ # Because writing user metadata to the file can change the result of
36
+ # sd_models.model_hash(), only retain the training metadata for purposes of
37
+ # calculating the hash, as they are meant to be immutable
38
+ metadata = {k: v for k, v in meta.items() if k.startswith("ss_")}
39
+
40
+ bytes = safetensors.torch.save(state_dict, metadata)
41
+ b = BytesIO(bytes)
42
+
43
+ model_hash = addnet_hash_safetensors(b)
44
+ legacy_hash = addnet_hash_legacy(b)
45
+ meta["sshs_model_hash"] = model_hash
46
+ meta["sshs_legacy_hash"] = legacy_hash
47
+ return meta
48
+
49
+
50
+ def add_base_model_info_to_meta(
51
+ meta: OrderedDict,
52
+ base_model: str = None,
53
+ is_v1: bool = False,
54
+ is_v2: bool = False,
55
+ is_xl: bool = False,
56
+ ) -> OrderedDict:
57
+ if base_model is not None:
58
+ meta['ss_base_model'] = base_model
59
+ elif is_v2:
60
+ meta['ss_v2'] = True
61
+ meta['ss_base_model_version'] = 'sd_2.1'
62
+
63
+ elif is_xl:
64
+ meta['ss_base_model_version'] = 'sdxl_1.0'
65
+ else:
66
+ # default to v1.5
67
+ meta['ss_base_model_version'] = 'sd_1.5'
68
+ return meta
69
+
70
+
71
+ def parse_metadata_from_safetensors(meta: OrderedDict) -> OrderedDict:
72
+ parsed_meta = OrderedDict()
73
+ for key, value in meta.items():
74
+ try:
75
+ parsed_meta[key] = json.loads(value)
76
+ except json.decoder.JSONDecodeError:
77
+ parsed_meta[key] = value
78
+ return parsed_meta
79
+
80
+
81
+ def load_metadata_from_safetensors(file_path: str) -> OrderedDict:
82
+ try:
83
+ with safe_open(file_path, framework="pt") as f:
84
+ metadata = f.metadata()
85
+ return parse_metadata_from_safetensors(metadata)
86
+ except Exception as e:
87
+ print(f"Error loading metadata from {file_path}: {e}")
88
+ return OrderedDict()