王方懿康 commited on
Commit
ab2369a
·
0 Parent(s):

Initial commit

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+
176
+ .idea/
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Fangyikang Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ # 🚀🚀🚀 Improve Diffusion Image Generation Quality using Levenberg-Marquardt-Langevin
4
+
5
+ We introduce **LML**, an accelerated sampler for diffusion models leveraging the second-order Hessian geometry. Our LML imlpementation is completely compatible with the **[diffusers](https://github.com/huggingface/diffusers)**.
6
+
7
+ This repository is the official implementation of the **ICCV 2025** paper:
8
+ _"Unleashing High-Quality Image Generation in Diffusion Sampling Using Second-Order Levenberg-Marquardt-Langevin"_
9
+
10
+
11
+ > **Fangyikang Wang<sup>1,2</sup>, Hubery Yin<sup>2</sup>, Lei Qian<sup>1</sup>, Yinan Li<sup>1</sup>, Shaobin Zhuang<sup>3,2</sup>, Huminhao Zhu<sup>1</sup>, Yilin Zhang<sup>1</sup>, Yanlong Tang<sup>4</sup>, Chao Zhang<sup>1</sup>, Hanbin Zhao<sup>1</sup>, Hui Qian<sup>1</sup>, Chen Li<sup>2</sup>**
12
+ >
13
+ > <sup>1</sup>Zhejiang University <sup>2</sup>WeChat Vision, Tencent Inc <sup>3</sup>Shanghai Jiao Tong University <sup>4</sup>Tencent Lightspeed Studio
14
+
15
+ [![arXiv](https://img.shields.io/badge/arXiv%20paper-2505.24222-b31b1b.svg)](https://www.arxiv.org/abs/2505.24222)&nbsp;
16
+ [![Github](https://img.shields.io/badge/Github-LML-blue)](https://github.com/zituitui/LML-diffusion-sampler)
17
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)&nbsp;
18
+
19
+ <img src="assets/lml-sd-visual_2_new-1.png" alt="SD Results" style="width: 100%;">
20
+
21
+ <img src="assets/lml-celeb-visual-1.png" alt="celeb Results" style="width: 70%;">
22
+
23
+ </div>
24
+
25
+ ## The intuition of our LML diffusion sampler
26
+
27
+ ![anneal](assets/anneal_path.drawio-1.png)
28
+ > **Schematic comparison** between our LML method and baselines. While previous works mainly focus on intriguing designs along the annealing path to improve diffusion sampling, they leave operations at specific noise levels to be performed using first-order Langevin. Our approach proposes to leverage the Levenberg-Marquardt approximated Hessian geometry to guide the Langevin update to be more accurate.
29
+
30
+
31
+ ![Some edits](assets/newton_algos.drawio-1.png)
32
+ > The relation between optimization algorithms and MCMC sampling algorithms. We initially wanted to develop a diffusion sampler utilizing Hessian geometry, following the path of Newton-Langevin dynamics.
33
+ However, this approach proved to be highly computationally expensive within the DM context.
34
+ Drawing inspiration from the Levenberg-Marquardt method used in optimization, our method incorporates low-rank approximation and damping techniques. This enables us to obtain the Hessian geometry in a computationally affordable manner. Subsequently, we use this approximated Hessian geometry to guide the Langevin updates.
35
+
36
+ ## 👨🏻‍💻 Run the code
37
+ ### 1) Get start
38
+
39
+ * Python 3.8.12
40
+ * CUDA 11.7
41
+ * NVIDIA A100 40GB PCIe
42
+ * Torch 2.0.0
43
+ * Torchvision 0.14.0
44
+
45
+ Please follow **[diffusers](https://github.com/huggingface/diffusers)** to install diffusers.
46
+
47
+ ### 2) Sampling
48
+ first, please switch to the root directory.
49
+
50
+ - #### CIFAR-10 sampling
51
+ For baseline, you can do CIAFR-10 sampling as follows, choose sampler_type within [ddim, pndm, dpm, dpm++, unipc]:
52
+ ```bash
53
+ python3 ./scripts/cifar10.py --test_num 1 --batch_size 1 --num_inference_steps 10 --save_dir YOUR/SAVE/DIR --model_id xx/xx/ddpm_ema_cifar10 --sampler_type ddim
54
+ ```
55
+ For our LML sampler, there is an additional $\lambda$ hyperparameter:
56
+ ```bash
57
+ python3 ./scripts/cifar10.py --test_num 1 --batch_size 1 --num_inference_steps 10 --save_dir YOUR/SAVE/DIR --model_id xx/xx/ddpm_ema_cifar10 --sampler_type dpm_lm --lamb 0.0008
58
+ ```
59
+
60
+ For the optimal choice of LML, we have:
61
+ | | 5 NFEs | 6 NFEs | 7 NFEs | 8 NFEs | 9 NFEs | 10 NFEs | 12 NFEs | 15 NFEs | 20 NFEs | 30 NFEs | 50 NFEs | 100 NFEs |
62
+ |---------|---------|---------|---------|---------|---------|----------|----------|----------|----------|----------|----------|-----------|
63
+ | optimal value of lamb | 0.0008 | 0.0008 | 0.001 | 0.001 | 0.001 | 0.0008 | 0.001 | 0.001 | 0.0005 | 0.0003 | 0.0001 | 0.00005 |
64
+
65
+
66
+
67
+ - #### CelebA-HQ sampling
68
+ For baseline:
69
+ ```bash
70
+ python3 ./scripts/celeba.py --test_num 1 --batch_size 1 --num_inference_steps 10 --save_dir YOUR/SAVE/DIR --model_id xx/xx/ldm-celebahq-256 --sampler_type ddim
71
+ ```
72
+
73
+ For our LML:
74
+ ```bash
75
+ python3 ./scripts/celeba.py --test_num 1 --batch_size 1 --num_inference_steps 10 --save_dir YOUR/SAVE/DIR --model_id xx/xx/ldm-celebahq-256 --sampler_type ddim_lm --lamb 0.005
76
+ ```
77
+
78
+ - #### SD-15 and SD-2b on MS-COCO sampling
79
+ ```bash
80
+ python3 ./scripts/StableDiffusion_COCO.py --test_num 30002 --num_inference_steps 10 --save_dir YOUR/SAVE/DIR --model_id xx/xx/stable-diffusion-v1-5 --sampler_type dpm_lm --lamb 0.001
81
+ ```
82
+
83
+ For the optimal choice of LML on MS-COCO, for NFEs of {5, 6, 7, 8, 9, 10, 12, 15}, we always choose $\lambda = 0.001$:
84
+ <!-- |NFEs| 5 | 6 | 7 | 8 | 9 | 10 | 12 | 15 |
85
+ |---------|------|------|------|------|------|------|------|------|
86
+ | SD-15 | -- | -- | 0.001 | - | - | -| 0.001 | 0.001 |
87
+ | SD-2b | -- | - | - | - | - | - | - | - | -->
88
+
89
+
90
+ - #### SD-15, SD-2b, SD-XL, and PixArt-$\alpha$ on T2i-compbench sampling
91
+ Before running the scripts, make sure to clone T2I-CompBench repository. Generated images are stored in the directory "save_dir/model/dataset_category/sampler_type/samples".
92
+
93
+ For baseline, you can do T2i-compbench sampling as follows, choose sampler_type within [ddim, pndm, dpm, dpm++, unipc] and model within [sd15, sd2_base, sdxl, pixart]:
94
+ ```bash
95
+ python3 ./scripts/StableDiffusion_PixArt_T2i_Sampling.py --dataset_category color --dataset_path PATH/TO/T2I-COMPBENCH --test_num 10 --num_inference_steps 10 --model_dir YOUR/MODEL/DIR --save_dir YOUR/SAVE/DIR --model sd15 --sampler_type ddim
96
+ ```
97
+ For our LML sampler, there is an additional $\lambda$ hyperparameter:
98
+ ```bash
99
+ python3 ./scripts/StableDiffusion_PixArt_T2i_Sampling.py --dataset_category color --dataset_path PATH/TO/T2I-COMPBENCH --test_num 10 --num_inference_steps 10 --model_dir YOUR/MODEL/DIR --save_dir YOUR/SAVE/DIR --model sd15 --sampler_type dpm_lm --lamb 0.006
100
+ ```
101
+
102
+ - #### Use our LML diffusion sampler with ControlNet
103
+
104
+ **canny**
105
+ ```bash
106
+ python3 ./scripts/control_net_canny.py --num_inference_steps 10 --original_image_path /xxx/xxx/data/input_image_vermeer.png --controlnet_dir /xxx/xxx/sd-controlnet-canny --sd_dir /xxx/xxx/stable-diffusion-v1-5 --save_dir YOUR/SAVE/DIR --sampler_type dpm_lm --lamb 0.001
107
+ ```
108
+
109
+ **depth**
110
+ ```bash
111
+ python3 ./scripts/control_net_depth.py --num_inference_steps 10 --controlnet_dir /xxx/xxx/control_v11f1p_sd15_depth --sd_dir /xxx/xxx/stable-diffusion-v1-5 --save_dir YOUR/SAVE/DIR --sampler_type dpm_lm --lamb 0.001
112
+ ```
113
+
114
+ **pose**
115
+ ```bash
116
+ python3 ./scripts/control_net_canny.py --num_inference_steps 10 --controlnet_dir /xxx/xxx/sd-controlnet-openpose --sd_dir /xxx/xxx/stable-diffusion-v1-5 --save_dir YOUR/SAVE/DIR --sampler_type dpm_lm --lamb 0.001
117
+ ```
118
+
119
+
120
+ - #### LML sampling on FLUX
121
+ For baseline:
122
+ ```bash
123
+ python3 ./scripts/FLUX_T2i_Sampling.py --dataset_category color --dataset_path PATH/TO/T2I-COMPBENCH --test_num 10 --num_inference_steps 10 --model_id YOUR/MODEL/DIR --save_dir YOUR/SAVE/DIR --sampler_type fm_euler
124
+ ```
125
+ For our LML:
126
+ ```bash
127
+ python3 ./scripts/FLUX_T2i_Sampling.py --dataset_category color --dataset_path PATH/TO/T2I-COMPBENCH --test_num 10 --num_inference_steps 10 --model_id YOUR/MODEL/DIR --save_dir YOUR/SAVE/DIR --sampler_type lml_euler --lamb 0.01
128
+ ```
129
+
130
+
131
+ ### 3) Evaluation
132
+ - #### FID evaluation on CIFAR-10
133
+ [Coming Soon] ⏳
134
+
135
+ - #### FID evaluation on MS-COCO
136
+ [Coming Soon] ⏳
137
+
138
+ - #### T2I-compbench evaluation
139
+ Please refer to the [T2I-CompBench](https://github.com/Karine-Huang/T2I-CompBench) guide. Create a new environment and install the dependencies for T2I-CompBench evaluation.
140
+ For testing combinations of multiple models and samplers, we also provide a convenient one-click script. Place the script file in the corresponding directory of **T2I-CompBench** to replace the origin script. For example:
141
+ ```sh
142
+ # BLIP-VQA for Attribute Binding
143
+ cd T2I-CompBench
144
+ bash BLIPvqa_eval/test.sh
145
+ ||
146
+ ||
147
+ \/
148
+ cp evaluations/T2I-CompBench/BLIPvqa_test.sh T2I-CompBench/BLIPvqa_eval
149
+ cd T2I-CompBench
150
+ bash BLIPvqa_eval/BLIPvqa_test.sh 'save_dir'
151
+ ```
152
+ The directory structure of **'save_dir'** should satisfy the following format:
153
+ ```
154
+ {save_dir}/model/dataset_category/sampler_type/samples/
155
+ ├── a green bench and a blue bowl_000000.png
156
+ ├── a green bench and a blue bowl_000001.png
157
+ └──...
158
+ ```
159
+
160
+
161
+
162
+ ## 🪪 License
163
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE.txt) file for details.
164
+
165
+ ## 📝 Citation
166
+ If our work assists your research, feel free to give us a star ⭐ or cite us using:
167
+ ```
168
+ @article{wang2025unleashing,
169
+ title={Unleashing High-Quality Image Generation in Diffusion Sampling Using Second-Order Levenberg-Marquardt-Langevin},
170
+ author={Wang, Fangyikang and Yin, Hubery and Qian, Lei and Li, Yinan and Zhuang, Shaobin and Zhu, Huminhao and Zhang, Yilin and Tang, Yanlong and Zhang, Chao and Zhao, Hanbin and others},
171
+ journal={arXiv preprint arXiv:2505.24222},
172
+ year={2025}
173
+ }
174
+ ```
175
+
176
+ ## 📩 Contact me
177
+ Our e-mail address:
178
+ ```
179
180
+ ```
assets/anneal_path.drawio-1.png ADDED

Git LFS Details

  • SHA256: c9d6e383ab44c72fb3fb9ebd9766450f885c9f21b0f970843861e50b573557bc
  • Pointer size: 131 Bytes
  • Size of remote file: 265 kB
assets/cifar-lambda.png ADDED
assets/lml-celeb-visual-1.png ADDED

Git LFS Details

  • SHA256: 95812a0a5c9d8633ea0f1f7f0ebef78e4e954923715f0f752da7fa761a3fd423
  • Pointer size: 132 Bytes
  • Size of remote file: 1.04 MB
assets/lml-controlnet-1.png ADDED

Git LFS Details

  • SHA256: 4f8013797e3ee7fb3d0569e55d5e0f7fc7da6c6464f6e24cadc501abee4c6192
  • Pointer size: 132 Bytes
  • Size of remote file: 2.05 MB
assets/lml-sd-visual_2_new-1.png ADDED

Git LFS Details

  • SHA256: 4914c5cb6058d8ee0f5419c355e5c48c5ce3b80e112bf642c1d35ce6448535da
  • Pointer size: 132 Bytes
  • Size of remote file: 3.72 MB
assets/newton_algos.drawio-1.png ADDED

Git LFS Details

  • SHA256: 7234bb15ba34e001ee0825ea83d4316f6192a87291b4c3bbbe1dba9ef2779ea4
  • Pointer size: 131 Bytes
  • Size of remote file: 169 kB
evaluations/T2I-CompBench/3-in-1_test.sh ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export project_dir="3_in_1_eval/"
4
+ cd "$project_dir" || exit
5
+
6
+ save_dir=$1
7
+ model_list=($(ls -d "$save_dir"/*/ | xargs -n1 basename))
8
+
9
+ for model in "${model_list[@]}"
10
+ do
11
+ # attr_list=($(ls -d "$save_dir/$model"/*/ | xargs -n1 basename))
12
+ attr_list=("complex")
13
+ for attr in "${attr_list[@]}"
14
+ do
15
+ sampler_list=($(ls -d "$save_dir/$model/$attr"/*/ | xargs -n1 basename))
16
+ for sampler in "${sampler_list[@]}"
17
+ do
18
+ out_dir="$save_dir/$model/$attr/$sampler"
19
+ # run python script
20
+ echo "Running for model=$model, attr=$attr, sampler=$sampler"
21
+ python 3_in_1.py --outpath="$out_dir"
22
+
23
+ # check if the command was successful
24
+ if [ $? -ne 0 ]; then
25
+ failed_runs+=("model=$model, attr=$attr, sampler=$sampler")
26
+ else
27
+ success_runs+=("model=$model, attr=$attr, sampler=$sampler")
28
+ fi
29
+ done
30
+ done
31
+ done
32
+
33
+ # print count of runs
34
+ echo "Total runs: ${#success_runs[@]} succeeded, ${#failed_runs[@]} failed."
35
+
36
+ # print all failed runs
37
+ if [ ${#failed_runs[@]} -ne 0 ]; then
38
+ echo "The following runs failed:"
39
+ for run in "${failed_runs[@]}"
40
+ do
41
+ echo "$run"
42
+ done
43
+ else
44
+ echo "All runs completed successfully."
45
+ fi
evaluations/T2I-CompBench/BLIPvqa_test.sh ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export project_dir="BLIPvqa_eval/"
4
+ cd "$project_dir" || exit
5
+
6
+ save_dir=$1
7
+ model_list=($(ls -d "$save_dir"/*/ | xargs -n1 basename))
8
+
9
+ for model in "${model_list[@]}"
10
+ do
11
+ # attr_list=($(ls -d "$save_dir/$model"/*/ | xargs -n1 basename))
12
+ attr_list=("color" "shape" "texture") # attribute list
13
+ for attr in "${attr_list[@]}"
14
+ do
15
+ sampler_list=($(ls -d "$save_dir/$model/$attr"/*/ | xargs -n1 basename))
16
+ for sampler in "${sampler_list[@]}"
17
+ do
18
+ out_dir="$save_dir/$model/$attr/$sampler"
19
+ # run python script
20
+ echo "Running for model=$model, attr=$attr, sampler=$sampler"
21
+ python BLIP_vqa.py --out_dir="$out_dir"
22
+
23
+ # check if the command was successful
24
+ if [ $? -ne 0 ]; then
25
+ failed_runs+=("model=$model, attr=$attr, sampler=$sampler")
26
+ else
27
+ success_runs+=("model=$model, attr=$attr, sampler=$sampler")
28
+ fi
29
+ done
30
+ done
31
+ done
32
+
33
+ # print count of runs
34
+ echo "Total runs: ${#success_runs[@]} succeeded, ${#failed_runs[@]} failed."
35
+
36
+ # print all failed runs
37
+ if [ ${#failed_runs[@]} -ne 0 ]; then
38
+ echo "The following runs failed:"
39
+ for run in "${failed_runs[@]}"
40
+ do
41
+ echo "$run"
42
+ done
43
+ else
44
+ echo "All runs completed successfully."
45
+ fi
evaluations/T2I-CompBench/CLIPScore_test.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ save_dir=$1
4
+ model_list=($(ls -d "$save_dir"/*/ | xargs -n1 basename))
5
+
6
+ for model in "${model_list[@]}"
7
+ do
8
+ # attr_list=($(ls -d "$save_dir/$model"/*/ | xargs -n1 basename))
9
+ attr_list=("complex" "non_spatial")
10
+ for attr in "${attr_list[@]}"
11
+ do
12
+ sampler_list=($(ls -d "$save_dir/$model/$attr"/*/ | xargs -n1 basename))
13
+ for sampler in "${sampler_list[@]}"
14
+ do
15
+ out_dir="$save_dir/$model/$attr/$sampler"
16
+ # run python script
17
+ echo "Running for model=$model, attr=$attr, sampler=$sampler"
18
+ if [ "$attr" = "complex" ]; then
19
+ python CLIPScore_eval/CLIP_similarity.py --outpath="$out_dir" --complex=True
20
+ else
21
+ python CLIPScore_eval/CLIP_similarity.py --outpath="$out_dir"
22
+ fi
23
+
24
+ # check if the command was successful
25
+ if [ $? -ne 0 ]; then
26
+ failed_runs+=("model=$model, attr=$attr, sampler=$sampler")
27
+ else
28
+ success_runs+=("model=$model, attr=$attr, sampler=$sampler")
29
+ fi
30
+ done
31
+ done
32
+ done
33
+
34
+ # print count of runs
35
+ echo "Total runs: ${#success_runs[@]} succeeded, ${#failed_runs[@]} failed."
36
+
37
+ # print all failed runs
38
+ if [ ${#failed_runs[@]} -ne 0 ]; then
39
+ echo "The following runs failed:"
40
+ for run in "${failed_runs[@]}"
41
+ do
42
+ echo "$run"
43
+ done
44
+ else
45
+ echo "All runs completed successfully."
46
+ fi
evaluations/T2I-CompBench/UniDet_test.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export project_dir="UniDet_eval/"
4
+ cd "$project_dir" || exit
5
+
6
+ save_dir=$1
7
+ model_list=($(ls -d "$save_dir"/*/ | xargs -n1 basename))
8
+
9
+ for model in "${model_list[@]}"
10
+ do
11
+ # attr_list=($(ls -d "$save_dir/$model"/*/ | xargs -n1 basename))
12
+ attr_list=("spatial" "complex")
13
+ for attr in "${attr_list[@]}"
14
+ do
15
+ sampler_list=($(ls -d "$save_dir/$model/$attr"/*/ | xargs -n1 basename))
16
+ for sampler in "${sampler_list[@]}"
17
+ do
18
+ out_dir="$save_dir/$model/$attr/$sampler/"
19
+
20
+ # run python script
21
+ echo "Running for model=$model, attr=$attr, sampler=$sampler"
22
+ if [ "$attr" = "complex" ]; then
23
+ python 2D_spatial_eval.py --outpath="$out_dir" --complex=True
24
+ else
25
+ python 2D_spatial_eval.py --outpath="$out_dir"
26
+ fi
27
+
28
+ # check if the command was successful
29
+ if [ $? -ne 0 ]; then
30
+ failed_runs+=("model=$model, attr=$attr, sampler=$sampler")
31
+ else
32
+ success_runs+=("model=$model, attr=$attr, sampler=$sampler")
33
+ fi
34
+ done
35
+ done
36
+ done
37
+
38
+ # print count of runs
39
+ echo "Total runs: ${#success_runs[@]} succeeded, ${#failed_runs[@]} failed."
40
+
41
+ # print all failed runs
42
+ if [ ${#failed_runs[@]} -ne 0 ]; then
43
+ echo "The following runs failed:"
44
+ for run in "${failed_runs[@]}"
45
+ do
46
+ echo "$run"
47
+ done
48
+ else
49
+ echo "All runs completed successfully."
50
+ fi
evaluations/fid_score.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calculates the Frechet Inception Distance (FID) to evalulate GANs
2
+
3
+ The FID metric calculates the distance between two distributions of images.
4
+ Typically, we have summary statistics (mean & covariance matrix) of one
5
+ of these distributions, while the 2nd distribution is given by a GAN.
6
+
7
+ When run as a stand-alone program, it compares the distribution of
8
+ images that are stored as PNG/JPEG at a specified location with a
9
+ distribution given by summary statistics (in pickle format).
10
+
11
+ The FID is calculated by assuming that X_1 and X_2 are the activations of
12
+ the pool_3 layer of the inception net for generated samples and real world
13
+ samples respectively.
14
+
15
+ See --help to see further details.
16
+
17
+ Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead
18
+ of Tensorflow
19
+
20
+ Copyright 2018 Institute of Bioinformatics, JKU Linz
21
+
22
+ Licensed under the Apache License, Version 2.0 (the "License");
23
+ you may not use this file except in compliance with the License.
24
+ You may obtain a copy of the License at
25
+
26
+ http://www.apache.org/licenses/LICENSE-2.0
27
+
28
+ Unless required by applicable law or agreed to in writing, software
29
+ distributed under the License is distributed on an "AS IS" BASIS,
30
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
+ See the License for the specific language governing permissions and
32
+ limitations under the License.
33
+ """
34
+ import os
35
+ import pathlib
36
+ from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
37
+
38
+ import numpy as np
39
+ import torch
40
+ import torchvision.transforms as TF
41
+ from PIL import Image
42
+ from scipy import linalg
43
+ from torch.nn.functional import adaptive_avg_pool2d
44
+
45
+ try:
46
+ from tqdm import tqdm
47
+ except ImportError:
48
+ # If tqdm is not available, provide a mock version of it
49
+ def tqdm(x):
50
+ return x
51
+
52
+ from inception import InceptionV3
53
+
54
+ IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
55
+ 'tif', 'tiff', 'webp'}
56
+
57
+
58
+
59
+ class ImagePathDataset(torch.utils.data.Dataset):
60
+ def __init__(self, files, transforms=None):
61
+ self.files = files
62
+ self.transforms = transforms
63
+
64
+ def __len__(self):
65
+ return len(self.files)
66
+
67
+ def __getitem__(self, i):
68
+ path = self.files[i]
69
+ img = Image.open(path).convert('RGB')
70
+ if self.transforms is not None:
71
+ img = self.transforms(img)
72
+ return img
73
+
74
+
75
+ def get_activations(files, model, batch_size=50, dims=2048, device='cpu',
76
+ num_workers=1):
77
+ """Calculates the activations of the pool_3 layer for all images.
78
+
79
+ Params:
80
+ -- files : List of image files paths
81
+ -- model : Instance of inception model
82
+ -- batch_size : Batch size of images for the model to process at once.
83
+ Make sure that the number of samples is a multiple of
84
+ the batch size, otherwise some samples are ignored. This
85
+ behavior is retained to match the original FID score
86
+ implementation.
87
+ -- dims : Dimensionality of features returned by Inception
88
+ -- device : Device to run calculations
89
+ -- num_workers : Number of parallel dataloader workers
90
+
91
+ Returns:
92
+ -- A numpy array of dimension (num images, dims) that contains the
93
+ activations of the given tensor when feeding inception with the
94
+ query tensor.
95
+ """
96
+ model.eval()
97
+
98
+ if batch_size > len(files):
99
+ print(('Warning: batch size is bigger than the data size. '
100
+ 'Setting batch size to data size'))
101
+ batch_size = len(files)
102
+
103
+ coco_transform = TF.Compose([
104
+ TF.Resize(512),
105
+ TF.CenterCrop(512),
106
+ TF.ToTensor()])
107
+
108
+ dataset = ImagePathDataset(files, transforms=coco_transform)
109
+ dataloader = torch.utils.data.DataLoader(dataset,
110
+ batch_size=batch_size,
111
+ shuffle=False,
112
+ drop_last=False,
113
+ num_workers=num_workers)
114
+
115
+ pred_arr = np.empty((len(files), dims))
116
+
117
+ start_idx = 0
118
+
119
+ for batch in tqdm(dataloader):
120
+ batch = batch.to(device)
121
+
122
+ with torch.no_grad():
123
+ pred = model(batch)[0]
124
+
125
+ # If model output is not scalar, apply global spatial average pooling.
126
+ # This happens if you choose a dimensionality not equal 2048.
127
+ if pred.size(2) != 1 or pred.size(3) != 1:
128
+ pred = adaptive_avg_pool2d(pred, output_size=(1, 1))
129
+
130
+ pred = pred.squeeze(3).squeeze(2).cpu().numpy()
131
+
132
+ pred_arr[start_idx:start_idx + pred.shape[0]] = pred
133
+
134
+ start_idx = start_idx + pred.shape[0]
135
+
136
+ return pred_arr
137
+
138
+
139
+ def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
140
+ """Numpy implementation of the Frechet Distance.
141
+ The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
142
+ and X_2 ~ N(mu_2, C_2) is
143
+ d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
144
+
145
+ Stable version by Dougal J. Sutherland.
146
+
147
+ Params:
148
+ -- mu1 : Numpy array containing the activations of a layer of the
149
+ inception net (like returned by the function 'get_predictions')
150
+ for generated samples.
151
+ -- mu2 : The sample mean over activations, precalculated on an
152
+ representative data set.
153
+ -- sigma1: The covariance matrix over activations for generated samples.
154
+ -- sigma2: The covariance matrix over activations, precalculated on an
155
+ representative data set.
156
+
157
+ Returns:
158
+ -- : The Frechet Distance.
159
+ """
160
+
161
+ mu1 = np.atleast_1d(mu1)
162
+ mu2 = np.atleast_1d(mu2)
163
+
164
+ sigma1 = np.atleast_2d(sigma1)
165
+ sigma2 = np.atleast_2d(sigma2)
166
+
167
+ assert mu1.shape == mu2.shape, \
168
+ 'Training and test mean vectors have different lengths'
169
+ assert sigma1.shape == sigma2.shape, \
170
+ 'Training and test covariances have different dimensions'
171
+
172
+ diff = mu1 - mu2
173
+
174
+ # Product might be almost singular
175
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
176
+ if not np.isfinite(covmean).all():
177
+ msg = ('fid calculation produces singular product; '
178
+ 'adding %s to diagonal of cov estimates') % eps
179
+ print(msg)
180
+ offset = np.eye(sigma1.shape[0]) * eps
181
+ covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
182
+
183
+ # Numerical error might give slight imaginary component
184
+ if np.iscomplexobj(covmean):
185
+ if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
186
+ m = np.max(np.abs(covmean.imag))
187
+ raise ValueError('Imaginary component {}'.format(m))
188
+ covmean = covmean.real
189
+
190
+ tr_covmean = np.trace(covmean)
191
+
192
+ return (diff.dot(diff) + np.trace(sigma1)
193
+ + np.trace(sigma2) - 2 * tr_covmean)
194
+
195
+
196
+ def calculate_activation_statistics(files, model, batch_size=50, dims=2048,
197
+ device='cpu', num_workers=1):
198
+ """Calculation of the statistics used by the FID.
199
+ Params:
200
+ -- files : List of image files paths
201
+ -- model : Instance of inception model
202
+ -- batch_size : The images numpy array is split into batches with
203
+ batch size batch_size. A reasonable batch size
204
+ depends on the hardware.
205
+ -- dims : Dimensionality of features returned by Inception
206
+ -- device : Device to run calculations
207
+ -- num_workers : Number of parallel dataloader workers
208
+
209
+ Returns:
210
+ -- mu : The mean over samples of the activations of the pool_3 layer of
211
+ the inception model.
212
+ -- sigma : The covariance matrix of the activations of the pool_3 layer of
213
+ the inception model.
214
+ """
215
+ act = get_activations(files, model, batch_size, dims, device, num_workers)
216
+ mu = np.mean(act, axis=0)
217
+ sigma = np.cov(act, rowvar=False)
218
+ return mu, sigma
219
+
220
+
221
+ def compute_statistics_of_path(path, model, batch_size, dims, device,
222
+ num_workers=1):
223
+ if path.endswith('.npz'):
224
+ with np.load(path) as f:
225
+ m, s = f['mu'][:], f['sigma'][:]
226
+ else:
227
+ path = pathlib.Path(path)
228
+ files = sorted([file for ext in IMAGE_EXTENSIONS
229
+ for file in path.glob('**/*.{}'.format(ext))])
230
+ m, s = calculate_activation_statistics(files, model, batch_size,
231
+ dims, device, num_workers)
232
+
233
+ return m, s
234
+
235
+
236
+ def calculate_fid_given_paths(paths, batch_size, device, dims, num_workers=1, output=''):
237
+ """Calculates the FID of two paths"""
238
+ for p in paths:
239
+ if not os.path.exists(p):
240
+ raise RuntimeError('Invalid path: %s' % p)
241
+
242
+ block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
243
+
244
+ model = InceptionV3([block_idx]).to(device)
245
+
246
+ m1, s1 = compute_statistics_of_path(paths[0], model, batch_size,
247
+ dims, device, num_workers)
248
+
249
+ #np.savez_compressed('./1W.npz', mu=m1, sigma=s1)
250
+
251
+ #np.save('./'+output+'_m.npy', m1)
252
+ #np.save('./'+output+'_s.npy', s1)
253
+ m2, s2 = compute_statistics_of_path(paths[1], model, batch_size,
254
+ dims, device, num_workers)
255
+ fid_value = calculate_frechet_distance(m1, s1, m2, s2)
256
+
257
+ return fid_value
258
+
259
+
260
+ def save_fid_stats(paths, batch_size, device, dims, num_workers=1):
261
+ """Calculates the FID of two paths"""
262
+ if not os.path.exists(paths[0]):
263
+ raise RuntimeError('Invalid path: %s' % paths[0])
264
+
265
+ if os.path.exists(paths[1]):
266
+ raise RuntimeError('Existing output file: %s' % paths[1])
267
+
268
+ block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
269
+
270
+ model = InceptionV3([block_idx]).to(device)
271
+
272
+ print(f"Saving statistics for {paths[0]}")
273
+
274
+ m1, s1 = compute_statistics_of_path(paths[0], model, batch_size,
275
+ dims, device, num_workers)
276
+
277
+ np.savez_compressed(paths[1], mu=m1, sigma=s1)
278
+
279
+
280
+ def main():
281
+ args = parser.parse_args()
282
+
283
+ if args.device is None:
284
+ device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
285
+ else:
286
+ device = torch.device(args.device)
287
+
288
+ if args.num_workers is None:
289
+ try:
290
+ num_cpus = len(os.sched_getaffinity(0))
291
+ except AttributeError:
292
+ # os.sched_getaffinity is not available under Windows, use
293
+ # os.cpu_count instead (which may not return the *available* number
294
+ # of CPUs).
295
+ num_cpus = os.cpu_count()
296
+
297
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
298
+ else:
299
+ num_workers = args.num_workers
300
+
301
+ if args.save_stats:
302
+ save_fid_stats(args.path, args.batch_size, device, args.dims, num_workers)
303
+ return
304
+
305
+ fid_value = calculate_fid_given_paths(args.path,
306
+ args.batch_size,
307
+ device,
308
+ args.dims,
309
+ num_workers,
310
+ args.output)
311
+ print('FID: ', fid_value)
312
+
313
+
314
+ def main():
315
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
316
+ parser.add_argument('--batch-size', type=int, default=50,
317
+ help='Batch size to use')
318
+ parser.add_argument('--num-workers', type=int,
319
+ help=('Number of processes to use for data loading. '
320
+ 'Defaults to `min(8, num_cpus)`'))
321
+ parser.add_argument('--device', type=str, default=None,
322
+ help='Device to use. Like cuda, cuda:0 or cpu')
323
+ parser.add_argument('--dims', type=int, default=2048,
324
+ choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),
325
+ help=('Dimensionality of Inception features to use. '
326
+ 'By default, uses pool3 features'))
327
+ parser.add_argument('--save-stats', action='store_true',
328
+ help=('Generate an npz archive from a directory of samples. '
329
+ 'The first path is used as input and the second as output.'))
330
+ parser.add_argument('path', type=str, nargs=2,
331
+ help=('Paths to the generated images or '
332
+ 'to .npz statistic files'))
333
+ parser.add_argument('--output', type=str, default='',
334
+ help='Device to use. Like cuda, cuda:0 or cpu')
335
+ parser.add_argument('--input', type=str, default='',
336
+ help='Device to use. Like cuda, cuda:0 or cpu')
337
+
338
+ IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
339
+ 'tif', 'tiff', 'webp'}
340
+ args = parser.parse_args()
341
+
342
+ if args.device is None:
343
+ device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
344
+ else:
345
+ device = torch.device(args.device)
346
+
347
+ if args.num_workers is None:
348
+ try:
349
+ num_cpus = len(os.sched_getaffinity(0))
350
+ except AttributeError:
351
+ # os.sched_getaffinity is not available under Windows, use
352
+ # os.cpu_count instead (which may not return the *available* number
353
+ # of CPUs).
354
+ num_cpus = os.cpu_count()
355
+
356
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
357
+ else:
358
+ num_workers = args.num_workers
359
+
360
+ if args.save_stats:
361
+ save_fid_stats(args.path, args.batch_size, device, args.dims, num_workers)
362
+ return
363
+
364
+ fid_value = calculate_fid_given_paths(args.path,
365
+ args.batch_size,
366
+ device,
367
+ args.dims,
368
+ num_workers,
369
+ args.output)
370
+ print('FID: ', fid_value)
371
+
372
+
373
+ def cal_fid():
374
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
375
+ parser.add_argument('--batch-size', type=int, default=50,
376
+ help='Batch size to use')
377
+ parser.add_argument('--num-workers', type=int,
378
+ help=('Number of processes to use for data loading. '
379
+ 'Defaults to `min(8, num_cpus)`'))
380
+ parser.add_argument('--device', type=str, default=None,
381
+ help='Device to use. Like cuda, cuda:0 or cpu')
382
+ parser.add_argument('--dims', type=int, default=2048,
383
+ choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),
384
+ help=('Dimensionality of Inception features to use. '
385
+ 'By default, uses pool3 features'))
386
+ parser.add_argument('--save-stats', action='store_true',
387
+ help=('Generate an npz archive from a directory of samples. '
388
+ 'The first path is used as input and the second as output.'))
389
+ parser.add_argument('path', type=str, nargs=2,
390
+ help=('Paths to the generated images or '
391
+ 'to .npz statistic files'))
392
+ parser.add_argument('--output', type=str, default='',
393
+ help='Device to use. Like cuda, cuda:0 or cpu')
394
+ parser.add_argument('--input', type=str, default='',
395
+ help='Device to use. Like cuda, cuda:0 or cpu')
396
+
397
+ IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
398
+ 'tif', 'tiff', 'webp'}
399
+ args = parser.parse_args()
400
+
401
+ m1 = np.load('./target_fid_test_m.npy')
402
+ s1 = np.load('./target_fid_test_s.npy')
403
+
404
+ m2 = np.load(args.input+'_m.npy')
405
+ s2 = np.load(args.input+'_s.npy')
406
+
407
+ fid_value = calculate_frechet_distance(m1, s1, m2, s2)
408
+
409
+
410
+ print('FID: ', fid_value)
411
+
412
+
413
+ if __name__ == '__main__':
414
+ print("Alibaba")
415
+ main()
416
+
417
+ #cal_fid()
scheduler/scheduling_ddim_lm.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 ZJU Lab304 Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.utils import BaseOutput
27
+ from diffusers.utils.torch_utils import randn_tensor
28
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
29
+
30
+
31
+ @dataclass
32
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
33
+ class DDIMLMSchedulerOutput(BaseOutput):
34
+ """
35
+ Output class for the scheduler's step function output.
36
+
37
+ Args:
38
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
39
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
40
+ denoising loop.
41
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
42
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
43
+ `pred_original_sample` can be used to preview progress or for guidance.
44
+ """
45
+
46
+ prev_sample: torch.FloatTensor
47
+ pred_original_sample: Optional[torch.FloatTensor] = None
48
+
49
+
50
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
51
+ def betas_for_alpha_bar(
52
+ num_diffusion_timesteps,
53
+ max_beta=0.999,
54
+ alpha_transform_type="cosine",
55
+ ):
56
+ """
57
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
58
+ (1-beta) over time from t = [0,1].
59
+
60
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
61
+ to that part of the diffusion process.
62
+
63
+
64
+ Args:
65
+ num_diffusion_timesteps (`int`): the number of betas to produce.
66
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
67
+ prevent singularities.
68
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
69
+ Choose from `cosine` or `exp`
70
+
71
+ Returns:
72
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
73
+ """
74
+ if alpha_transform_type == "cosine":
75
+
76
+ def alpha_bar_fn(t):
77
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
78
+
79
+ elif alpha_transform_type == "exp":
80
+
81
+ def alpha_bar_fn(t):
82
+ return math.exp(t * -12.0)
83
+
84
+ else:
85
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
86
+
87
+ betas = []
88
+ for i in range(num_diffusion_timesteps):
89
+ t1 = i / num_diffusion_timesteps
90
+ t2 = (i + 1) / num_diffusion_timesteps
91
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
92
+ return torch.tensor(betas, dtype=torch.float32)
93
+
94
+
95
+ def rescale_zero_terminal_snr(betas):
96
+ """
97
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
98
+
99
+
100
+ Args:
101
+ betas (`torch.FloatTensor`):
102
+ the betas that the scheduler is being initialized with.
103
+
104
+ Returns:
105
+ `torch.FloatTensor`: rescaled betas with zero terminal SNR
106
+ """
107
+ # Convert betas to alphas_bar_sqrt
108
+ alphas = 1.0 - betas
109
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
110
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
111
+
112
+ # Store old values.
113
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
114
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
115
+
116
+ # Shift so the last timestep is zero.
117
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
118
+
119
+ # Scale so the first timestep is back to the old value.
120
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
121
+
122
+ # Convert alphas_bar_sqrt to betas
123
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
124
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
125
+ alphas = torch.cat([alphas_bar[0:1], alphas])
126
+ betas = 1 - alphas
127
+
128
+ return betas
129
+
130
+
131
+ class DDIMLMScheduler(SchedulerMixin, ConfigMixin):
132
+ """
133
+ Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising
134
+ diffusion probabilistic models (DDPMs) with non-Markovian guidance.
135
+
136
+ [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
137
+ function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
138
+ [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
139
+ [`~SchedulerMixin.from_pretrained`] functions.
140
+
141
+ For more details, see the original paper: https://arxiv.org/abs/2010.02502
142
+
143
+ Args:
144
+ num_train_timesteps (`int`): number of diffusion steps used to train the model.
145
+ beta_start (`float`): the starting `beta` value of inference.
146
+ beta_end (`float`): the final `beta` value.
147
+ beta_schedule (`str`):
148
+ the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
149
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
150
+ trained_betas (`np.ndarray`, optional):
151
+ option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
152
+ clip_sample (`bool`, default `True`):
153
+ option to clip predicted sample for numerical stability.
154
+ clip_sample_range (`float`, default `1.0`):
155
+ the maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
156
+ set_alpha_to_one (`bool`, default `True`):
157
+ each diffusion step uses the value of alphas product at that step and at the previous one. For the final
158
+ step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
159
+ otherwise it uses the value of alpha at step 0.
160
+ steps_offset (`int`, default `0`):
161
+ an offset added to the inference steps. You can use a combination of `offset=1` and
162
+ `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
163
+ stable diffusion.
164
+ prediction_type (`str`, default `epsilon`, optional):
165
+ prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
166
+ process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
167
+ https://imagen.research.google/video/paper.pdf)
168
+ thresholding (`bool`, default `False`):
169
+ whether to use the "dynamic thresholding" method (introduced by Imagen, https://arxiv.org/abs/2205.11487).
170
+ Note that the thresholding method is unsuitable for latent-space diffusion models (such as
171
+ stable-diffusion).
172
+ dynamic_thresholding_ratio (`float`, default `0.995`):
173
+ the ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen
174
+ (https://arxiv.org/abs/2205.11487). Valid only when `thresholding=True`.
175
+ sample_max_value (`float`, default `1.0`):
176
+ the threshold value for dynamic thresholding. Valid only when `thresholding=True`.
177
+ timestep_spacing (`str`, default `"leading"`):
178
+ The way the timesteps should be scaled. Refer to Table 2. of [Common Diffusion Noise Schedules and Sample
179
+ Steps are Flawed](https://arxiv.org/abs/2305.08891) for more information.
180
+ rescale_betas_zero_snr (`bool`, default `False`):
181
+ whether to rescale the betas to have zero terminal SNR (proposed by https://arxiv.org/pdf/2305.08891.pdf).
182
+ This can enable the model to generate very bright and dark samples instead of limiting it to samples with
183
+ medium brightness. Loosely related to
184
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
185
+ """
186
+
187
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
188
+ order = 1
189
+
190
+ @register_to_config
191
+ def __init__(
192
+ self,
193
+ num_train_timesteps: int = 1000,
194
+ beta_start: float = 0.0001,
195
+ beta_end: float = 0.02,
196
+ beta_schedule: str = "linear",
197
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
198
+ clip_sample: bool = True,
199
+ set_alpha_to_one: bool = True,
200
+ steps_offset: int = 0,
201
+ prediction_type: str = "epsilon",
202
+ thresholding: bool = False,
203
+ dynamic_thresholding_ratio: float = 0.995,
204
+ clip_sample_range: float = 1.0,
205
+ sample_max_value: float = 1.0,
206
+ timestep_spacing: str = "leading",
207
+ rescale_betas_zero_snr: bool = False,
208
+ lamb: float = 1.0,
209
+ lm: bool = False,
210
+ kappa: float = 0.0,
211
+ freeze = 0.0,
212
+ ):
213
+ self.lamb = lamb
214
+ self.lm = lm
215
+ self.kappa = kappa
216
+ self.prev_noise = None
217
+ self.freeze = freeze
218
+ if trained_betas is not None:
219
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
220
+ elif beta_schedule == "linear":
221
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
222
+ elif beta_schedule == "scaled_linear":
223
+ # this schedule is very specific to the latent diffusion model.
224
+ self.betas = (
225
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
226
+ )
227
+ elif beta_schedule == "squaredcos_cap_v2":
228
+ # Glide cosine schedule
229
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
230
+ else:
231
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
232
+
233
+ # Rescale for zero SNR
234
+ if rescale_betas_zero_snr:
235
+ self.betas = rescale_zero_terminal_snr(self.betas)
236
+
237
+ self.alphas = 1.0 - self.betas
238
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
239
+
240
+ # At every step in ddim, we are looking into the previous alphas_cumprod
241
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
242
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
243
+ # whether we use the final alpha of the "non-previous" one.
244
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
245
+
246
+ # standard deviation of the initial noise distribution
247
+ self.init_noise_sigma = 1.0
248
+
249
+ # setable values
250
+ self.num_inference_steps = None
251
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
252
+
253
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
254
+ """
255
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
256
+ current timestep.
257
+
258
+ Args:
259
+ sample (`torch.FloatTensor`): input sample
260
+ timestep (`int`, optional): current timestep
261
+
262
+ Returns:
263
+ `torch.FloatTensor`: scaled input sample
264
+ """
265
+ return sample
266
+
267
+ def _get_variance(self, timestep, prev_timestep):
268
+ alpha_prod_t = self.alphas_cumprod[timestep]
269
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
270
+ beta_prod_t = 1 - alpha_prod_t
271
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
272
+
273
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
274
+
275
+ return variance
276
+
277
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
278
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
279
+ """
280
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
281
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
282
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
283
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
284
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
285
+
286
+ https://arxiv.org/abs/2205.11487
287
+ """
288
+ dtype = sample.dtype
289
+ batch_size, channels, height, width = sample.shape
290
+
291
+ if dtype not in (torch.float32, torch.float64):
292
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
293
+
294
+ # Flatten sample for doing quantile calculation along each image
295
+ sample = sample.reshape(batch_size, channels * height * width)
296
+
297
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
298
+
299
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
300
+ s = torch.clamp(
301
+ s, min=1, max=self.config.sample_max_value
302
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
303
+
304
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
305
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
306
+
307
+ sample = sample.reshape(batch_size, channels, height, width)
308
+ sample = sample.to(dtype)
309
+
310
+ return sample
311
+
312
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
313
+ """
314
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
315
+
316
+ Args:
317
+ num_inference_steps (`int`):
318
+ the number of diffusion steps used when generating samples with a pre-trained model.
319
+ """
320
+
321
+ if num_inference_steps > self.config.num_train_timesteps:
322
+ raise ValueError(
323
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
324
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
325
+ f" maximal {self.config.num_train_timesteps} timesteps."
326
+ )
327
+
328
+ self.num_inference_steps = num_inference_steps
329
+
330
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
331
+ if self.config.timestep_spacing == "linspace":
332
+ timesteps = (
333
+ np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps)
334
+ .round()[::-1]
335
+ .copy()
336
+ .astype(np.int64)
337
+ )
338
+ elif self.config.timestep_spacing == "leading":
339
+ step_ratio = self.config.num_train_timesteps // self.num_inference_steps
340
+ # creates integer timesteps by multiplying by ratio
341
+ # casting to int to avoid issues when num_inference_step is power of 3
342
+ timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64)
343
+ timesteps += self.config.steps_offset
344
+ elif self.config.timestep_spacing == "trailing":
345
+ step_ratio = self.config.num_train_timesteps / self.num_inference_steps
346
+ # creates integer timesteps by multiplying by ratio
347
+ # casting to int to avoid issues when num_inference_step is power of 3
348
+ timesteps = np.round(np.arange(self.config.num_train_timesteps, 0, -step_ratio)).astype(np.int64)
349
+ timesteps -= 1
350
+ else:
351
+ raise ValueError(
352
+ f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'leading' or 'trailing'."
353
+ )
354
+
355
+ self.timesteps = torch.from_numpy(timesteps).to(device)
356
+
357
+ def step(
358
+ self,
359
+ model_output: torch.FloatTensor,
360
+ timestep: int,
361
+ sample: torch.FloatTensor,
362
+ eta: float = 0.0,
363
+ use_clipped_model_output: bool = False,
364
+ generator=None,
365
+ variance_noise: Optional[torch.FloatTensor] = None,
366
+ return_dict: bool = True,
367
+ ) -> Union[DDIMLMSchedulerOutput, Tuple]:
368
+ """
369
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
370
+ process from the learned model outputs (most often the predicted noise).
371
+
372
+ Args:
373
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
374
+ timestep (`int`): current discrete timestep in the diffusion chain.
375
+ sample (`torch.FloatTensor`):
376
+ current instance of sample being created by diffusion process.
377
+ eta (`float`): weight of noise for added noise in diffusion step.
378
+ use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped
379
+ predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when
380
+ `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would
381
+ coincide with the one provided as input and `use_clipped_model_output` will have not effect.
382
+ generator: random number generator.
383
+ variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we
384
+ can directly provide the noise for the variance itself. This is useful for methods such as
385
+ CycleDiffusion. (https://arxiv.org/abs/2210.05559)
386
+ return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class
387
+
388
+ Returns:
389
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:
390
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
391
+ returning a tuple, the first element is the sample tensor.
392
+
393
+ """
394
+ if self.num_inference_steps is None:
395
+ raise ValueError(
396
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
397
+ )
398
+
399
+ # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
400
+ # Ideally, read DDIM paper in-detail understanding
401
+
402
+ # Notation (<variable name> -> <name in paper>
403
+ # - pred_noise_t -> e_theta(x_t, t)
404
+ # - pred_original_sample -> f_theta(x_t, t) or x_0
405
+ # - std_dev_t -> sigma_t
406
+ # - eta -> η
407
+ # - pred_sample_direction -> "direction pointing to x_t"
408
+ # - pred_prev_sample -> "x_t-1"
409
+
410
+ # 1. get previous step value (=t-1)
411
+ prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
412
+
413
+ # 2. compute alphas, betas
414
+ alpha_prod_t = self.alphas_cumprod[timestep]
415
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
416
+
417
+ beta_prod_t = 1 - alpha_prod_t
418
+
419
+ # 3. compute predicted original sample from predicted noise also called
420
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
421
+ if self.config.prediction_type == "epsilon":
422
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
423
+ pred_epsilon = model_output
424
+ elif self.config.prediction_type == "sample":
425
+ pred_original_sample = model_output
426
+ pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
427
+ elif self.config.prediction_type == "v_prediction":
428
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
429
+ pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
430
+ else:
431
+ raise ValueError(
432
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
433
+ " `v_prediction`"
434
+ )
435
+
436
+ # 4. Clip or threshold "predicted x_0"
437
+ if self.config.thresholding:
438
+ pred_original_sample = self._threshold_sample(pred_original_sample)
439
+ elif self.config.clip_sample:
440
+ pred_original_sample = pred_original_sample.clamp(
441
+ -self.config.clip_sample_range, self.config.clip_sample_range
442
+ )
443
+
444
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
445
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
446
+ variance = self._get_variance(timestep, prev_timestep)
447
+ std_dev_t = eta * variance ** (0.5)
448
+
449
+ if use_clipped_model_output:
450
+ # the pred_epsilon is always re-derived from the clipped x_0 in Glide
451
+ pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
452
+
453
+
454
+ # 5.2 LM corection
455
+ noise_pred = pred_epsilon
456
+ noise_pred_ema = noise_pred
457
+ if self.prev_noise is not None:
458
+ noise_pred_ema = self.kappa * self.prev_noise + (1 - self.kappa) * noise_pred
459
+ norm_squared = (noise_pred * noise_pred).sum(dim=(1, 2, 3))
460
+ norm_squared = norm_squared.unsqueeze(1).unsqueeze(2).unsqueeze(3)
461
+ part1 = noise_pred
462
+
463
+ norm_squared_ema = (noise_pred_ema * noise_pred_ema).sum(dim=(1, 2, 3))
464
+ norm_squared_ema = norm_squared_ema.unsqueeze(1).unsqueeze(2).unsqueeze(3)
465
+
466
+ inner_product = torch.sum(noise_pred * noise_pred_ema, dim=(1, 2, 3))
467
+ mp = noise_pred_ema * inner_product.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
468
+ # coef_2 = (sigma_t * norm_squared)/(lamb*(lamb+norm_squared_ema))
469
+ part2 = mp / (self.lamb + norm_squared_ema)
470
+
471
+ inversed_pred = part1 - part2
472
+
473
+ # normalize the direction
474
+ norm = torch.sqrt(norm_squared)
475
+ norm_squared_lm = (inversed_pred * inversed_pred).sum(dim=(1, 2, 3))
476
+ norm_squared_lm = norm_squared_lm.unsqueeze(1).unsqueeze(2).unsqueeze(3)
477
+ norm_lm = torch.sqrt(norm_squared_lm)
478
+ inversed_pred = inversed_pred * norm / norm_lm
479
+
480
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
481
+ print(timestep)
482
+ if timestep < 1000 - 1000 * self.freeze and self.lm is True:
483
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * inversed_pred
484
+ print("do lm")
485
+ else:
486
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t ** 2) ** (0.5) * pred_epsilon
487
+ print("freezed")
488
+
489
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
490
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
491
+ self.prev_noise = pred_epsilon
492
+ if eta > 0:
493
+ if variance_noise is not None and generator is not None:
494
+ raise ValueError(
495
+ "Cannot pass both generator and variance_noise. Please make sure that either `generator` or"
496
+ " `variance_noise` stays `None`."
497
+ )
498
+
499
+ if variance_noise is None:
500
+ variance_noise = randn_tensor(
501
+ model_output.shape, generator=generator, device=model_output.device, dtype=model_output.dtype
502
+ )
503
+ variance = std_dev_t * variance_noise
504
+
505
+ prev_sample = prev_sample + variance
506
+
507
+ if not return_dict:
508
+ return (prev_sample,)
509
+
510
+ return DDIMLMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
511
+
512
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
513
+ def add_noise(
514
+ self,
515
+ original_samples: torch.FloatTensor,
516
+ noise: torch.FloatTensor,
517
+ timesteps: torch.IntTensor,
518
+ ) -> torch.FloatTensor:
519
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
520
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
521
+ timesteps = timesteps.to(original_samples.device)
522
+
523
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
524
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
525
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
526
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
527
+
528
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
529
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
530
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
531
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
532
+
533
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
534
+ return noisy_samples
535
+
536
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
537
+ def get_velocity(
538
+ self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
539
+ ) -> torch.FloatTensor:
540
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
541
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
542
+ timesteps = timesteps.to(sample.device)
543
+
544
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
545
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
546
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
547
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
548
+
549
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
550
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
551
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
552
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
553
+
554
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
555
+ return velocity
556
+
557
+ def __len__(self):
558
+ return self.config.num_train_timesteps
scheduler/scheduling_dpmsolver_multistep_lm.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 ZJU Lab304 Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.utils.torch_utils import randn_tensor
25
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
26
+
27
+ def lm_correct(prev_noise, noise_pred, lamb, kappa):
28
+ # print('entered lmc')
29
+ if prev_noise is not None:
30
+ noise_pred_ema = kappa * prev_noise + (1 - kappa) * noise_pred
31
+ else:
32
+ noise_pred_ema = noise_pred
33
+ # lm step for noise
34
+ norm_squared = (noise_pred * noise_pred).sum(dim=(1, 2, 3))
35
+ norm_squared = norm_squared.unsqueeze(1).unsqueeze(2).unsqueeze(3)
36
+ part1 = noise_pred
37
+
38
+ norm_squared_ema = (noise_pred_ema * noise_pred_ema).sum(dim=(1, 2, 3))
39
+ norm_squared_ema = norm_squared_ema.unsqueeze(1).unsqueeze(2).unsqueeze(3)
40
+
41
+ inner_product = torch.sum(noise_pred * noise_pred_ema, dim=(1, 2, 3))
42
+ mp = noise_pred_ema * inner_product.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
43
+ part2 = mp / (lamb + norm_squared_ema)
44
+
45
+ inversed_pred = part1 - part2
46
+
47
+ # normalize the direction
48
+ norm = torch.sqrt(norm_squared)
49
+ norm_squared_lm = (inversed_pred * inversed_pred).sum(dim=(1, 2, 3))
50
+ norm_squared_lm = norm_squared_lm.unsqueeze(1).unsqueeze(2).unsqueeze(3)
51
+ norm_lm = torch.sqrt(norm_squared_lm)
52
+ inversed_pred = inversed_pred * norm / norm_lm
53
+ return inversed_pred
54
+
55
+
56
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
57
+ def betas_for_alpha_bar(
58
+ num_diffusion_timesteps,
59
+ max_beta=0.999,
60
+ alpha_transform_type="cosine",
61
+ ):
62
+ """
63
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
64
+ (1-beta) over time from t = [0,1].
65
+
66
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
67
+ to that part of the diffusion process.
68
+
69
+
70
+ Args:
71
+ num_diffusion_timesteps (`int`): the number of betas to produce.
72
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
73
+ prevent singularities.
74
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
75
+ Choose from `cosine` or `exp`
76
+
77
+ Returns:
78
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
79
+ """
80
+ if alpha_transform_type == "cosine":
81
+
82
+ def alpha_bar_fn(t):
83
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
84
+
85
+ elif alpha_transform_type == "exp":
86
+
87
+ def alpha_bar_fn(t):
88
+ return math.exp(t * -12.0)
89
+
90
+ else:
91
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
92
+
93
+ betas = []
94
+ for i in range(num_diffusion_timesteps):
95
+ t1 = i / num_diffusion_timesteps
96
+ t2 = (i + 1) / num_diffusion_timesteps
97
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
98
+ return torch.tensor(betas, dtype=torch.float32)
99
+
100
+
101
+ class DPMSolverMultistepLMScheduler(SchedulerMixin, ConfigMixin):
102
+ """
103
+ DPM-Solver (and the improved version DPM-Solver++) is a fast dedicated high-order solver for diffusion ODEs with
104
+ the convergence order guarantee. Empirically, sampling by DPM-Solver with only 20 steps can generate high-quality
105
+ samples, and it can generate quite good samples even in only 10 steps.
106
+
107
+ For more details, see the original paper: https://arxiv.org/abs/2206.00927 and https://arxiv.org/abs/2211.01095
108
+
109
+ Currently, we support the multistep DPM-Solver for both noise prediction models and data prediction models. We
110
+ recommend to use `solver_order=2` for guided sampling, and `solver_order=3` for unconditional sampling.
111
+
112
+ We also support the "dynamic thresholding" method in Imagen (https://arxiv.org/abs/2205.11487). For pixel-space
113
+ diffusion models, you can set both `algorithm_type="dpmsolver++"` and `thresholding=True` to use the dynamic
114
+ thresholding. Note that the thresholding method is unsuitable for latent-space diffusion models (such as
115
+ stable-diffusion).
116
+
117
+ We also support the SDE variant of DPM-Solver and DPM-Solver++, which is a fast SDE solver for the reverse
118
+ diffusion SDE. Currently we only support the first-order and second-order solvers. We recommend using the
119
+ second-order `sde-dpmsolver++`.
120
+
121
+ [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
122
+ function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
123
+ [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
124
+ [`~SchedulerMixin.from_pretrained`] functions.
125
+
126
+ Args:
127
+ num_train_timesteps (`int`): number of diffusion steps used to train the model.
128
+ beta_start (`float`): the starting `beta` value of inference.
129
+ beta_end (`float`): the final `beta` value.
130
+ beta_schedule (`str`):
131
+ the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
132
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
133
+ trained_betas (`np.ndarray`, optional):
134
+ option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
135
+ solver_order (`int`, default `2`):
136
+ the order of DPM-Solver; can be `1` or `2` or `3`. We recommend to use `solver_order=2` for guided
137
+ sampling, and `solver_order=3` for unconditional sampling.
138
+ prediction_type (`str`, default `epsilon`, optional):
139
+ prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
140
+ process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
141
+ https://imagen.research.google/video/paper.pdf)
142
+ thresholding (`bool`, default `False`):
143
+ whether to use the "dynamic thresholding" method (introduced by Imagen, https://arxiv.org/abs/2205.11487).
144
+ For pixel-space diffusion models, you can set both `algorithm_type=dpmsolver++` and `thresholding=True` to
145
+ use the dynamic thresholding. Note that the thresholding method is unsuitable for latent-space diffusion
146
+ models (such as stable-diffusion).
147
+ dynamic_thresholding_ratio (`float`, default `0.995`):
148
+ the ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen
149
+ (https://arxiv.org/abs/2205.11487).
150
+ sample_max_value (`float`, default `1.0`):
151
+ the threshold value for dynamic thresholding. Valid only when `thresholding=True` and
152
+ `algorithm_type="dpmsolver++`.
153
+ algorithm_type (`str`, default `dpmsolver++`):
154
+ the algorithm type for the solver. Either `dpmsolver` or `dpmsolver++` or `sde-dpmsolver` or
155
+ `sde-dpmsolver++`. The `dpmsolver` type implements the algorithms in https://arxiv.org/abs/2206.00927, and
156
+ the `dpmsolver++` type implements the algorithms in https://arxiv.org/abs/2211.01095. We recommend to use
157
+ `dpmsolver++` or `sde-dpmsolver++` with `solver_order=2` for guided sampling (e.g. stable-diffusion).
158
+ solver_type (`str`, default `midpoint`):
159
+ the solver type for the second-order solver. Either `midpoint` or `heun`. The solver type slightly affects
160
+ the sample quality, especially for small number of steps. We empirically find that `midpoint` solvers are
161
+ slightly better, so we recommend to use the `midpoint` type.
162
+ lower_order_final (`bool`, default `True`):
163
+ whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. We empirically
164
+ find this trick can stabilize the sampling of DPM-Solver for steps < 15, especially for steps <= 10.
165
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
166
+ This parameter controls whether to use Karras sigmas (Karras et al. (2022) scheme) for step sizes in the
167
+ noise schedule during the sampling process. If True, the sigmas will be determined according to a sequence
168
+ of noise levels {σi} as defined in Equation (5) of the paper https://arxiv.org/pdf/2206.00364.pdf.
169
+ lambda_min_clipped (`float`, default `-inf`):
170
+ the clipping threshold for the minimum value of lambda(t) for numerical stability. This is critical for
171
+ cosine (squaredcos_cap_v2) noise schedule.
172
+ variance_type (`str`, *optional*):
173
+ Set to "learned" or "learned_range" for diffusion models that predict variance. For example, OpenAI's
174
+ guided-diffusion (https://github.com/openai/guided-diffusion) predicts both mean and variance of the
175
+ Gaussian distribution in the model's output. DPM-Solver only needs the "mean" output because it is based on
176
+ diffusion ODEs. whether the model's output contains the predicted Gaussian variance. For example, OpenAI's
177
+ guided-diffusion (https://github.com/openai/guided-diffusion) predicts both mean and variance of the
178
+ Gaussian distribution in the model's output. DPM-Solver only needs the "mean" output because it is based on
179
+ diffusion ODEs.
180
+ timestep_spacing (`str`, default `"linspace"`):
181
+ The way the timesteps should be scaled. Refer to Table 2. of [Common Diffusion Noise Schedules and Sample
182
+ Steps are Flawed](https://arxiv.org/abs/2305.08891) for more information.
183
+ steps_offset (`int`, default `0`):
184
+ an offset added to the inference steps. You can use a combination of `offset=1` and
185
+ `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
186
+ stable diffusion.
187
+ """
188
+
189
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
190
+ order = 1
191
+
192
+ @register_to_config
193
+ def __init__(
194
+ self,
195
+ num_train_timesteps: int = 1000,
196
+ beta_start: float = 0.0001,
197
+ beta_end: float = 0.02,
198
+ beta_schedule: str = "linear",
199
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
200
+ solver_order: int = 2,
201
+ prediction_type: str = "epsilon",
202
+ thresholding: bool = False,
203
+ dynamic_thresholding_ratio: float = 0.995,
204
+ sample_max_value: float = 1.0,
205
+ algorithm_type: str = "dpmsolver++",
206
+ solver_type: str = "midpoint",
207
+ lower_order_final: bool = True,
208
+ use_karras_sigmas: Optional[bool] = False,
209
+ lambda_min_clipped: float = -float("inf"),
210
+ variance_type: Optional[str] = None,
211
+ timestep_spacing: str = "linspace",
212
+ steps_offset: int = 0,
213
+ lamb:float =1.0,
214
+ lm:bool=False,
215
+ kappa: float = 0.0,
216
+ ):
217
+ if trained_betas is not None:
218
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
219
+ elif beta_schedule == "linear":
220
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
221
+ elif beta_schedule == "scaled_linear":
222
+ # this schedule is very specific to the latent diffusion model.
223
+ self.betas = (
224
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
225
+ )
226
+ elif beta_schedule == "squaredcos_cap_v2":
227
+ # Glide cosine schedule
228
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
229
+ else:
230
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
231
+
232
+ self.lamb = lamb
233
+ self.lm = lm
234
+ self.kappa = kappa
235
+ self.prev_noise = None
236
+ self.alphas = 1.0 - self.betas
237
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
238
+ # Currently we only support VP-type noise schedule
239
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
240
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
241
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
242
+
243
+ # standard deviation of the initial noise distribution
244
+ self.init_noise_sigma = 1.0
245
+
246
+ # settings for DPM-Solver
247
+ if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
248
+ if algorithm_type == "deis":
249
+ self.register_to_config(algorithm_type="dpmsolver++")
250
+ else:
251
+ raise NotImplementedError(f"{algorithm_type} does is not implemented for {self.__class__}")
252
+
253
+ if solver_type not in ["midpoint", "heun"]:
254
+ if solver_type in ["logrho", "bh1", "bh2"]:
255
+ self.register_to_config(solver_type="midpoint")
256
+ else:
257
+ raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}")
258
+
259
+ # setable values
260
+ self.num_inference_steps = None
261
+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
262
+ self.timesteps = torch.from_numpy(timesteps)
263
+ self.model_outputs = [None] * solver_order
264
+ self.lower_order_nums = 0
265
+
266
+ def set_timesteps(self, num_inference_steps: int = None, device: Union[str, torch.device] = None):
267
+ """
268
+ Sets the timesteps used for the diffusion chain. Supporting function to be run before inference.
269
+
270
+ Args:
271
+ num_inference_steps (`int`):
272
+ the number of diffusion steps used when generating samples with a pre-trained model.
273
+ device (`str` or `torch.device`, optional):
274
+ the device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
275
+ """
276
+ # Clipping the minimum of all lambda(t) for numerical stability.
277
+ # This is critical for cosine (squaredcos_cap_v2) noise schedule.
278
+ clipped_idx = torch.searchsorted(torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped)
279
+ last_timestep = ((self.config.num_train_timesteps - clipped_idx).numpy()).item()
280
+
281
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
282
+ if self.config.timestep_spacing == "linspace":
283
+ timesteps = (
284
+ np.linspace(0, last_timestep - 1, num_inference_steps + 1).round()[::-1][:-1].copy().astype(np.int64)
285
+ )
286
+ elif self.config.timestep_spacing == "leading":
287
+ step_ratio = last_timestep // (num_inference_steps + 1)
288
+ # creates integer timesteps by multiplying by ratio
289
+ # casting to int to avoid issues when num_inference_step is power of 3
290
+ timesteps = (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64)
291
+ timesteps += self.config.steps_offset
292
+ elif self.config.timestep_spacing == "trailing":
293
+ step_ratio = self.config.num_train_timesteps / num_inference_steps
294
+ # creates integer timesteps by multiplying by ratio
295
+ # casting to int to avoid issues when num_inference_step is power of 3
296
+ timesteps = np.arange(last_timestep, 0, -step_ratio).round().copy().astype(np.int64)
297
+ timesteps -= 1
298
+ else:
299
+ raise ValueError(
300
+ f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
301
+ )
302
+
303
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
304
+ if self.config.use_karras_sigmas:
305
+ log_sigmas = np.log(sigmas)
306
+ sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
307
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
308
+ timesteps = np.flip(timesteps).copy().astype(np.int64)
309
+
310
+ self.sigmas = torch.from_numpy(sigmas)
311
+
312
+ # when num_inference_steps == num_train_timesteps, we can end up with
313
+ # duplicates in timesteps.
314
+ _, unique_indices = np.unique(timesteps, return_index=True)
315
+ timesteps = timesteps[np.sort(unique_indices)]
316
+
317
+ self.timesteps = torch.from_numpy(timesteps).to(device)
318
+
319
+ self.num_inference_steps = len(timesteps)
320
+
321
+ self.model_outputs = [
322
+ None,
323
+ ] * self.config.solver_order
324
+ self.lower_order_nums = 0
325
+
326
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
327
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
328
+ """
329
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
330
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
331
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
332
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
333
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
334
+
335
+ https://arxiv.org/abs/2205.11487
336
+ """
337
+ dtype = sample.dtype
338
+ batch_size, channels, height, width = sample.shape
339
+
340
+ if dtype not in (torch.float32, torch.float64):
341
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
342
+
343
+ # Flatten sample for doing quantile calculation along each image
344
+ sample = sample.reshape(batch_size, channels * height * width)
345
+
346
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
347
+
348
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
349
+ s = torch.clamp(
350
+ s, min=1, max=self.config.sample_max_value
351
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
352
+
353
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
354
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
355
+
356
+ sample = sample.reshape(batch_size, channels, height, width)
357
+ sample = sample.to(dtype)
358
+
359
+ return sample
360
+
361
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
362
+ def _sigma_to_t(self, sigma, log_sigmas):
363
+ # get log sigma
364
+ log_sigma = np.log(sigma)
365
+
366
+ # get distribution
367
+ dists = log_sigma - log_sigmas[:, np.newaxis]
368
+
369
+ # get sigmas range
370
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
371
+ high_idx = low_idx + 1
372
+
373
+ low = log_sigmas[low_idx]
374
+ high = log_sigmas[high_idx]
375
+
376
+ # interpolate sigmas
377
+ w = (low - log_sigma) / (low - high)
378
+ w = np.clip(w, 0, 1)
379
+
380
+ # transform interpolation to time range
381
+ t = (1 - w) * low_idx + w * high_idx
382
+ t = t.reshape(sigma.shape)
383
+ return t
384
+
385
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
386
+ def _convert_to_karras(self, in_sigmas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor:
387
+ """Constructs the noise schedule of Karras et al. (2022)."""
388
+
389
+ sigma_min: float = in_sigmas[-1].item()
390
+ sigma_max: float = in_sigmas[0].item()
391
+
392
+ rho = 7.0 # 7.0 is the value used in the paper
393
+ ramp = np.linspace(0, 1, num_inference_steps)
394
+ min_inv_rho = sigma_min ** (1 / rho)
395
+ max_inv_rho = sigma_max ** (1 / rho)
396
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
397
+ return sigmas
398
+
399
+ def convert_model_output(
400
+ self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor
401
+ ) -> torch.FloatTensor:
402
+ """
403
+ Convert the model output to the corresponding type that the algorithm (DPM-Solver / DPM-Solver++) needs.
404
+
405
+ DPM-Solver is designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to
406
+ discretize an integral of the data prediction model. So we need to first convert the model output to the
407
+ corresponding type to match the algorithm.
408
+
409
+ Note that the algorithm type and the model type is decoupled. That is to say, we can use either DPM-Solver or
410
+ DPM-Solver++ for both noise prediction model and data prediction model.
411
+
412
+ Args:
413
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
414
+ timestep (`int`): current discrete timestep in the diffusion chain.
415
+ sample (`torch.FloatTensor`):
416
+ current instance of sample being created by diffusion process.
417
+
418
+ Returns:
419
+ `torch.FloatTensor`: the converted model output.
420
+ """
421
+
422
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
423
+ if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
424
+ if self.config.prediction_type == "epsilon":
425
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
426
+ if self.config.variance_type in ["learned", "learned_range"]:
427
+ model_output = model_output[:, :3]
428
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
429
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
430
+ elif self.config.prediction_type == "sample":
431
+ x0_pred = model_output
432
+ elif self.config.prediction_type == "v_prediction":
433
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
434
+ x0_pred = alpha_t * sample - sigma_t * model_output
435
+ else:
436
+ raise ValueError(
437
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
438
+ " `v_prediction` for the DPMSolverMultistepScheduler."
439
+ )
440
+
441
+ if self.config.thresholding:
442
+ x0_pred = self._threshold_sample(x0_pred)
443
+
444
+ return x0_pred
445
+
446
+ # DPM-Solver needs to solve an integral of the noise prediction model.
447
+ elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
448
+ if self.config.prediction_type == "epsilon":
449
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
450
+ if self.config.variance_type in ["learned", "learned_range"]:
451
+ epsilon = model_output[:, :3]
452
+ else:
453
+ epsilon = model_output
454
+ elif self.config.prediction_type == "sample":
455
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
456
+ epsilon = (sample - alpha_t * model_output) / sigma_t
457
+ elif self.config.prediction_type == "v_prediction":
458
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
459
+ epsilon = alpha_t * model_output + sigma_t * sample
460
+ else:
461
+ raise ValueError(
462
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
463
+ " `v_prediction` for the DPMSolverMultistepScheduler."
464
+ )
465
+
466
+ if self.config.thresholding:
467
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
468
+ x0_pred = (sample - sigma_t * epsilon) / alpha_t
469
+ x0_pred = self._threshold_sample(x0_pred)
470
+ epsilon = (sample - alpha_t * x0_pred) / sigma_t
471
+
472
+ return epsilon
473
+
474
+ def dpm_solver_first_order_update(
475
+ self,
476
+ model_output: torch.FloatTensor,
477
+ timestep: int,
478
+ prev_timestep: int,
479
+ sample: torch.FloatTensor,
480
+ noise: Optional[torch.FloatTensor] = None,
481
+ lamb: float = 1.0,
482
+ lm=True,
483
+ ) -> torch.FloatTensor:
484
+ """
485
+ One step for the first-order DPM-Solver (equivalent to DDIM).
486
+
487
+ See https://arxiv.org/abs/2206.00927 for the detailed derivation.
488
+
489
+ Args:
490
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
491
+ timestep (`int`): current discrete timestep in the diffusion chain.
492
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
493
+ sample (`torch.FloatTensor`):
494
+ current instance of sample being created by diffusion process.
495
+
496
+ Returns:
497
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
498
+ """
499
+ lambda_t, lambda_s = self.lambda_t[prev_timestep], self.lambda_t[timestep]
500
+ alpha_t, alpha_s = self.alpha_t[prev_timestep], self.alpha_t[timestep]
501
+ sigma_t, sigma_s = self.sigma_t[prev_timestep], self.sigma_t[timestep]
502
+ h = lambda_t - lambda_s
503
+ if self.config.algorithm_type == "dpmsolver++":
504
+ # x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
505
+ noise = - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
506
+ if lm is True:
507
+ x_t = (sigma_t / sigma_s) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
508
+ else:
509
+ x_t = (sigma_t / sigma_s) * sample + noise
510
+ self.prev_noise = noise
511
+ elif self.config.algorithm_type == "dpmsolver":
512
+ # x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output
513
+ noise = - (sigma_t * (torch.exp(h) - 1.0)) * model_output
514
+ if lm is True:
515
+ x_t = (alpha_t / alpha_s) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
516
+ else:
517
+ x_t = (alpha_t / alpha_s) * sample + noise
518
+ self.prev_noise = noise
519
+ elif self.config.algorithm_type == "sde-dpmsolver++":
520
+ assert noise is not None
521
+ x_t = (
522
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
523
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
524
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
525
+ )
526
+ elif self.config.algorithm_type == "sde-dpmsolver":
527
+ assert noise is not None
528
+ x_t = (
529
+ (alpha_t / alpha_s) * sample
530
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output
531
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
532
+ )
533
+ return x_t
534
+
535
+ def multistep_dpm_solver_second_order_update(
536
+ self,
537
+ model_output_list: List[torch.FloatTensor],
538
+ timestep_list: List[int],
539
+ prev_timestep: int,
540
+ sample: torch.FloatTensor,
541
+ noise: Optional[torch.FloatTensor] = None,
542
+ lamb: float = 1.0,
543
+ lm=True,
544
+ ) -> torch.FloatTensor:
545
+ """
546
+ One step for the second-order multistep DPM-Solver.
547
+
548
+ Args:
549
+ model_output_list (`List[torch.FloatTensor]`):
550
+ direct outputs from learned diffusion model at current and latter timesteps.
551
+ timestep (`int`): current and latter discrete timestep in the diffusion chain.
552
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
553
+ sample (`torch.FloatTensor`):
554
+ current instance of sample being created by diffusion process.
555
+
556
+ Returns:
557
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
558
+ """
559
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
560
+ m0, m1 = model_output_list[-1], model_output_list[-2]
561
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
562
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
563
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
564
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
565
+ r0 = h_0 / h
566
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
567
+ if self.config.algorithm_type == "dpmsolver++":
568
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
569
+ if self.config.solver_type == "midpoint":
570
+ # x_t = (
571
+ # (sigma_t / sigma_s0) * sample
572
+ # - (alpha_t * (torch.exp(-h) - 1.0)) * D0
573
+ # - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
574
+ # )
575
+ noise = - (alpha_t * (torch.exp(-h) - 1.0)) * D0 - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
576
+ if lm is True:
577
+ x_t = (sigma_t / sigma_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
578
+ else:
579
+ x_t = (sigma_t / sigma_s0) * sample + noise
580
+ self.prev_noise = noise
581
+ elif self.config.solver_type == "heun":
582
+ # x_t = (
583
+ # (sigma_t / sigma_s0) * sample
584
+ # - (alpha_t * (torch.exp(-h) - 1.0)) * D0
585
+ # + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
586
+ # )
587
+ noise = - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
588
+ if lm is True:
589
+ x_t = (sigma_t / sigma_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
590
+ else:
591
+ x_t = (sigma_t / sigma_s0) * sample + noise
592
+ self.prev_noise = noise
593
+ elif self.config.algorithm_type == "dpmsolver":
594
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
595
+ if self.config.solver_type == "midpoint":
596
+ # x_t = (
597
+ # (alpha_t / alpha_s0) * sample
598
+ # - (sigma_t * (torch.exp(h) - 1.0)) * D0
599
+ # - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
600
+ # )
601
+ noise = - (sigma_t * (torch.exp(h) - 1.0)) * D0 - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
602
+ if lm is True:
603
+ x_t = (alpha_t / alpha_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
604
+ else:
605
+ x_t = (alpha_t / alpha_s0) * sample + noise
606
+ self.prev_noise = noise
607
+ elif self.config.solver_type == "heun":
608
+ # x_t = (
609
+ # (alpha_t / alpha_s0) * sample
610
+ # - (sigma_t * (torch.exp(h) - 1.0)) * D0
611
+ # - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
612
+ # )
613
+ noise = - (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
614
+ if lm is True:
615
+ x_t = (alpha_t / alpha_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
616
+ else:
617
+ x_t = (alpha_t / alpha_s0) * sample + noise
618
+ self.prev_noise = noise
619
+ elif self.config.algorithm_type == "sde-dpmsolver++":
620
+ assert noise is not None
621
+ if self.config.solver_type == "midpoint":
622
+ x_t = (
623
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
624
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
625
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
626
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
627
+ )
628
+ elif self.config.solver_type == "heun":
629
+ x_t = (
630
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
631
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
632
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
633
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
634
+ )
635
+ elif self.config.algorithm_type == "sde-dpmsolver":
636
+ assert noise is not None
637
+ if self.config.solver_type == "midpoint":
638
+ x_t = (
639
+ (alpha_t / alpha_s0) * sample
640
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
641
+ - (sigma_t * (torch.exp(h) - 1.0)) * D1
642
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
643
+ )
644
+ elif self.config.solver_type == "heun":
645
+ x_t = (
646
+ (alpha_t / alpha_s0) * sample
647
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
648
+ - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
649
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
650
+ )
651
+ return x_t
652
+
653
+ def multistep_dpm_solver_third_order_update(
654
+ self,
655
+ model_output_list: List[torch.FloatTensor],
656
+ timestep_list: List[int],
657
+ prev_timestep: int,
658
+ sample: torch.FloatTensor,
659
+ lamb:float = 1.0,
660
+ lm = True,
661
+ ) -> torch.FloatTensor:
662
+ """
663
+ One step for the third-order multistep DPM-Solver.
664
+
665
+ Args:
666
+ model_output_list (`List[torch.FloatTensor]`):
667
+ direct outputs from learned diffusion model at current and latter timesteps.
668
+ timestep (`int`): current and latter discrete timestep in the diffusion chain.
669
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
670
+ sample (`torch.FloatTensor`):
671
+ current instance of sample being created by diffusion process.
672
+
673
+ Returns:
674
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
675
+ """
676
+ t, s0, s1, s2 = prev_timestep, timestep_list[-1], timestep_list[-2], timestep_list[-3]
677
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
678
+ lambda_t, lambda_s0, lambda_s1, lambda_s2 = (
679
+ self.lambda_t[t],
680
+ self.lambda_t[s0],
681
+ self.lambda_t[s1],
682
+ self.lambda_t[s2],
683
+ )
684
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
685
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
686
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
687
+ r0, r1 = h_0 / h, h_1 / h
688
+ D0 = m0
689
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
690
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
691
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
692
+ if self.config.algorithm_type == "dpmsolver++":
693
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
694
+ # x_t = (
695
+ # (sigma_t / sigma_s0) * sample
696
+ # - (alpha_t * (torch.exp(-h) - 1.0)) * D0
697
+ # + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
698
+ # - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
699
+ # )
700
+ noise = - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
701
+ if lm is True:
702
+ x_t = (sigma_t / sigma_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
703
+ else:
704
+ x_t = (sigma_t / sigma_s0) * sample + noise
705
+ self.prev_noise = noise
706
+ elif self.config.algorithm_type == "dpmsolver":
707
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
708
+ # x_t = (
709
+ # (alpha_t / alpha_s0) * sample
710
+ # - (sigma_t * (torch.exp(h) - 1.0)) * D0
711
+ # - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
712
+ # - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
713
+ # )
714
+ noise = - (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
715
+ if lm is True:
716
+ x_t = (alpha_t / alpha_s0) * sample + lm_correct(prev_noise=self.prev_noise, noise_pred = noise, lamb = self.lamb, kappa=self.kappa)
717
+ else:
718
+ x_t = (alpha_t / alpha_s0) * sample + noise
719
+ self.prev_noise = noise
720
+ return x_t
721
+
722
+ def step(
723
+ self,
724
+ model_output: torch.FloatTensor,
725
+ timestep: int,
726
+ sample: torch.FloatTensor,
727
+ generator=None,
728
+ return_dict: bool = True,
729
+ ) -> Union[SchedulerOutput, Tuple]:
730
+ """
731
+ Step function propagating the sample with the multistep DPM-Solver.
732
+
733
+ Args:
734
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
735
+ timestep (`int`): current discrete timestep in the diffusion chain.
736
+ sample (`torch.FloatTensor`):
737
+ current instance of sample being created by diffusion process.
738
+ return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
739
+
740
+ Returns:
741
+ [`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
742
+ True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
743
+
744
+ """
745
+ lamb = self.lamb
746
+ lm = self.lm
747
+ kappa = self.kappa
748
+ if self.num_inference_steps is None:
749
+ raise ValueError(
750
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
751
+ )
752
+
753
+ if isinstance(timestep, torch.Tensor):
754
+ timestep = timestep.to(self.timesteps.device)
755
+ step_index = (self.timesteps == timestep).nonzero()
756
+ if len(step_index) == 0:
757
+ step_index = len(self.timesteps) - 1
758
+ else:
759
+ step_index = step_index.item()
760
+ prev_timestep = 0 if step_index == len(self.timesteps) - 1 else self.timesteps[step_index + 1]
761
+ lower_order_final = (
762
+ (step_index == len(self.timesteps) - 1) and self.config.lower_order_final and len(self.timesteps) < 15
763
+ )
764
+ lower_order_second = (
765
+ (step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
766
+ )
767
+
768
+ model_output = self.convert_model_output(model_output, timestep, sample)
769
+ for i in range(self.config.solver_order - 1):
770
+ self.model_outputs[i] = self.model_outputs[i + 1]
771
+ self.model_outputs[-1] = model_output
772
+
773
+ if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
774
+ noise = randn_tensor(
775
+ model_output.shape, generator=generator, device=model_output.device, dtype=model_output.dtype
776
+ )
777
+ else:
778
+ noise = None
779
+
780
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
781
+ prev_sample = self.dpm_solver_first_order_update(
782
+ model_output, timestep, prev_timestep, sample, noise=noise, lm=lm
783
+ )
784
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
785
+ timestep_list = [self.timesteps[step_index - 1], timestep]
786
+ prev_sample = self.multistep_dpm_solver_second_order_update(
787
+ self.model_outputs, timestep_list, prev_timestep, sample, noise=noise, lm=lm
788
+ )
789
+ else:
790
+ timestep_list = [self.timesteps[step_index - 2], self.timesteps[step_index - 1], timestep]
791
+ prev_sample = self.multistep_dpm_solver_third_order_update(
792
+ self.model_outputs, timestep_list, prev_timestep, sample, lamb=lamb, lm=lm
793
+ )
794
+
795
+ if self.lower_order_nums < self.config.solver_order:
796
+ self.lower_order_nums += 1
797
+
798
+ if not return_dict:
799
+ return (prev_sample,)
800
+
801
+ return SchedulerOutput(prev_sample=prev_sample)
802
+
803
+ def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
804
+ """
805
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
806
+ current timestep.
807
+
808
+ Args:
809
+ sample (`torch.FloatTensor`): input sample
810
+
811
+ Returns:
812
+ `torch.FloatTensor`: scaled input sample
813
+ """
814
+ return sample
815
+
816
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
817
+ def add_noise(
818
+ self,
819
+ original_samples: torch.FloatTensor,
820
+ noise: torch.FloatTensor,
821
+ timesteps: torch.IntTensor,
822
+ ) -> torch.FloatTensor:
823
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
824
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
825
+ timesteps = timesteps.to(original_samples.device)
826
+
827
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
828
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
829
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
830
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
831
+
832
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
833
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
834
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
835
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
836
+
837
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
838
+ return noisy_samples
839
+
840
+ def __len__(self):
841
+ return self.config.num_train_timesteps
scheduler/scheduling_flow_match_euler_discrete_lm.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI, Katherine Crowson and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from dataclasses import dataclass
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
23
+ from diffusers.utils import BaseOutput, is_scipy_available, logging
24
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
25
+
26
+
27
+ if is_scipy_available():
28
+ import scipy.stats
29
+
30
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
31
+
32
+
33
+ def lm_correct(prev_noise, noise_pred, lamb, kappa):
34
+ noise_pred = noise_pred.to(torch.float32)
35
+ if prev_noise is not None:
36
+ noise_pred_ema = kappa * prev_noise + (1 - kappa) * noise_pred
37
+ else:
38
+ noise_pred_ema = noise_pred
39
+
40
+ # lm step for noise
41
+ norm_squared = (noise_pred * noise_pred).sum(dim=(1, 2))
42
+
43
+ norm_squared = norm_squared.unsqueeze(1).unsqueeze(2)
44
+ part1 = noise_pred
45
+
46
+ norm_squared_ema = (noise_pred_ema * noise_pred_ema).sum(dim=(1, 2))
47
+ norm_squared_ema = norm_squared_ema.unsqueeze(1).unsqueeze(2)
48
+ inner_product = torch.sum(noise_pred * noise_pred_ema, dim=(1, 2))
49
+ mp = noise_pred_ema * inner_product.unsqueeze(-1).unsqueeze(-1)
50
+ part2 = mp / (lamb + norm_squared_ema)
51
+
52
+ inversed_pred = part1 - part2
53
+
54
+ # normalize the direction
55
+ norm = torch.sqrt(norm_squared)
56
+ norm_squared_lm = (inversed_pred * inversed_pred).sum(dim=(1, 2))
57
+ norm_squared_lm = norm_squared_lm.unsqueeze(1).unsqueeze(2)
58
+ norm_lm = torch.sqrt(norm_squared_lm)
59
+ inversed_pred = inversed_pred * norm / norm_lm
60
+
61
+ return inversed_pred
62
+
63
+ @dataclass
64
+ class FlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
65
+ """
66
+ Output class for the scheduler's `step` function output.
67
+
68
+ Args:
69
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
70
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
71
+ denoising loop.
72
+ """
73
+
74
+ prev_sample: torch.FloatTensor
75
+
76
+
77
+ class FlowMatchEulerDiscreteLMScheduler(SchedulerMixin, ConfigMixin):
78
+ """
79
+ Euler scheduler.
80
+
81
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
82
+ methods the library implements for all schedulers such as loading and saving.
83
+
84
+ Args:
85
+ num_train_timesteps (`int`, defaults to 1000):
86
+ The number of diffusion steps to train the model.
87
+ shift (`float`, defaults to 1.0):
88
+ The shift value for the timestep schedule.
89
+ use_dynamic_shifting (`bool`, defaults to False):
90
+ Whether to apply timestep shifting on-the-fly based on the image resolution.
91
+ base_shift (`float`, defaults to 0.5):
92
+ Value to stabilize image generation. Increasing `base_shift` reduces variation and image is more consistent
93
+ with desired output.
94
+ max_shift (`float`, defaults to 1.15):
95
+ Value change allowed to latent vectors. Increasing `max_shift` encourages more variation and image may be
96
+ more exaggerated or stylized.
97
+ base_image_seq_len (`int`, defaults to 256):
98
+ The base image sequence length.
99
+ max_image_seq_len (`int`, defaults to 4096):
100
+ The maximum image sequence length.
101
+ invert_sigmas (`bool`, defaults to False):
102
+ Whether to invert the sigmas.
103
+ shift_terminal (`float`, defaults to None):
104
+ The end value of the shifted timestep schedule.
105
+ use_karras_sigmas (`bool`, defaults to False):
106
+ Whether to use Karras sigmas for step sizes in the noise schedule during sampling.
107
+ use_exponential_sigmas (`bool`, defaults to False):
108
+ Whether to use exponential sigmas for step sizes in the noise schedule during sampling.
109
+ use_beta_sigmas (`bool`, defaults to False):
110
+ Whether to use beta sigmas for step sizes in the noise schedule during sampling.
111
+ time_shift_type (`str`, defaults to "exponential"):
112
+ The type of dynamic resolution-dependent timestep shifting to apply. Either "exponential" or "linear".
113
+ stochastic_sampling (`bool`, defaults to False):
114
+ Whether to use stochastic sampling.
115
+ """
116
+
117
+ _compatibles = []
118
+ order = 1
119
+
120
+ @register_to_config
121
+ def __init__(
122
+ self,
123
+ num_train_timesteps: int = 1000,
124
+ shift: float = 1.0,
125
+ use_dynamic_shifting: bool = False,
126
+ base_shift: Optional[float] = 0.5,
127
+ max_shift: Optional[float] = 1.15,
128
+ base_image_seq_len: Optional[int] = 256,
129
+ max_image_seq_len: Optional[int] = 4096,
130
+ invert_sigmas: bool = False,
131
+ shift_terminal: Optional[float] = None,
132
+ use_karras_sigmas: Optional[bool] = False,
133
+ use_exponential_sigmas: Optional[bool] = False,
134
+ use_beta_sigmas: Optional[bool] = False,
135
+ time_shift_type: str = "exponential",
136
+ stochastic_sampling: bool = False,
137
+ lamb: float = 1.0,
138
+ lm: bool = True,
139
+ kappa: float = 0.0,
140
+ ):
141
+ if self.config.use_beta_sigmas and not is_scipy_available():
142
+ raise ImportError("Make sure to install scipy if you want to use beta sigmas.")
143
+ if sum([self.config.use_beta_sigmas, self.config.use_exponential_sigmas, self.config.use_karras_sigmas]) > 1:
144
+ raise ValueError(
145
+ "Only one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used."
146
+ )
147
+ if time_shift_type not in {"exponential", "linear"}:
148
+ raise ValueError("`time_shift_type` must either be 'exponential' or 'linear'.")
149
+
150
+ timesteps = np.linspace(1, num_train_timesteps, num_train_timesteps, dtype=np.float32)[::-1].copy()
151
+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32)
152
+
153
+ sigmas = timesteps / num_train_timesteps
154
+ if not use_dynamic_shifting:
155
+ # when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution
156
+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
157
+
158
+ self.timesteps = sigmas * num_train_timesteps
159
+ self.lamb = lamb
160
+ self.lm = lm
161
+ self.kappa = kappa
162
+ self.prev_noise = None
163
+ self._step_index = None
164
+ self._begin_index = None
165
+
166
+ self._shift = shift
167
+
168
+ self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
169
+ self.sigma_min = self.sigmas[-1].item()
170
+ self.sigma_max = self.sigmas[0].item()
171
+
172
+ @property
173
+ def shift(self):
174
+ """
175
+ The value used for shifting.
176
+ """
177
+ return self._shift
178
+
179
+ @property
180
+ def step_index(self):
181
+ """
182
+ The index counter for current timestep. It will increase 1 after each scheduler step.
183
+ """
184
+ return self._step_index
185
+
186
+ @property
187
+ def begin_index(self):
188
+ """
189
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
190
+ """
191
+ return self._begin_index
192
+
193
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
194
+ def set_begin_index(self, begin_index: int = 0):
195
+ """
196
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
197
+
198
+ Args:
199
+ begin_index (`int`):
200
+ The begin index for the scheduler.
201
+ """
202
+ self._begin_index = begin_index
203
+
204
+ def set_shift(self, shift: float):
205
+ self._shift = shift
206
+
207
+ def scale_noise(
208
+ self,
209
+ sample: torch.FloatTensor,
210
+ timestep: Union[float, torch.FloatTensor],
211
+ noise: Optional[torch.FloatTensor] = None,
212
+ ) -> torch.FloatTensor:
213
+ """
214
+ Forward process in flow-matching
215
+
216
+ Args:
217
+ sample (`torch.FloatTensor`):
218
+ The input sample.
219
+ timestep (`int`, *optional*):
220
+ The current timestep in the diffusion chain.
221
+
222
+ Returns:
223
+ `torch.FloatTensor`:
224
+ A scaled input sample.
225
+ """
226
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
227
+ sigmas = self.sigmas.to(device=sample.device, dtype=sample.dtype)
228
+
229
+ if sample.device.type == "mps" and torch.is_floating_point(timestep):
230
+ # mps does not support float64
231
+ schedule_timesteps = self.timesteps.to(sample.device, dtype=torch.float32)
232
+ timestep = timestep.to(sample.device, dtype=torch.float32)
233
+ else:
234
+ schedule_timesteps = self.timesteps.to(sample.device)
235
+ timestep = timestep.to(sample.device)
236
+
237
+ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
238
+ if self.begin_index is None:
239
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timestep]
240
+ elif self.step_index is not None:
241
+ # add_noise is called after first denoising step (for inpainting)
242
+ step_indices = [self.step_index] * timestep.shape[0]
243
+ else:
244
+ # add noise is called before first denoising step to create initial latent(img2img)
245
+ step_indices = [self.begin_index] * timestep.shape[0]
246
+
247
+ sigma = sigmas[step_indices].flatten()
248
+ while len(sigma.shape) < len(sample.shape):
249
+ sigma = sigma.unsqueeze(-1)
250
+
251
+ sample = sigma * noise + (1.0 - sigma) * sample
252
+
253
+ return sample
254
+
255
+ def _sigma_to_t(self, sigma):
256
+ return sigma * self.config.num_train_timesteps
257
+
258
+ def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
259
+ if self.config.time_shift_type == "exponential":
260
+ return self._time_shift_exponential(mu, sigma, t)
261
+ elif self.config.time_shift_type == "linear":
262
+ return self._time_shift_linear(mu, sigma, t)
263
+
264
+ def stretch_shift_to_terminal(self, t: torch.Tensor) -> torch.Tensor:
265
+ r"""
266
+ Stretches and shifts the timestep schedule to ensure it terminates at the configured `shift_terminal` config
267
+ value.
268
+
269
+ Reference:
270
+ https://github.com/Lightricks/LTX-Video/blob/a01a171f8fe3d99dce2728d60a73fecf4d4238ae/ltx_video/schedulers/rf.py#L51
271
+
272
+ Args:
273
+ t (`torch.Tensor`):
274
+ A tensor of timesteps to be stretched and shifted.
275
+
276
+ Returns:
277
+ `torch.Tensor`:
278
+ A tensor of adjusted timesteps such that the final value equals `self.config.shift_terminal`.
279
+ """
280
+ one_minus_z = 1 - t
281
+ scale_factor = one_minus_z[-1] / (1 - self.config.shift_terminal)
282
+ stretched_t = 1 - (one_minus_z / scale_factor)
283
+ return stretched_t
284
+
285
+ def set_timesteps(
286
+ self,
287
+ num_inference_steps: Optional[int] = None,
288
+ device: Union[str, torch.device] = None,
289
+ sigmas: Optional[List[float]] = None,
290
+ mu: Optional[float] = None,
291
+ timesteps: Optional[List[float]] = None,
292
+ ):
293
+ """
294
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
295
+
296
+ Args:
297
+ num_inference_steps (`int`, *optional*):
298
+ The number of diffusion steps used when generating samples with a pre-trained model.
299
+ device (`str` or `torch.device`, *optional*):
300
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
301
+ sigmas (`List[float]`, *optional*):
302
+ Custom values for sigmas to be used for each diffusion step. If `None`, the sigmas are computed
303
+ automatically.
304
+ mu (`float`, *optional*):
305
+ Determines the amount of shifting applied to sigmas when performing resolution-dependent timestep
306
+ shifting.
307
+ timesteps (`List[float]`, *optional*):
308
+ Custom values for timesteps to be used for each diffusion step. If `None`, the timesteps are computed
309
+ automatically.
310
+ """
311
+ if self.config.use_dynamic_shifting and mu is None:
312
+ raise ValueError("`mu` must be passed when `use_dynamic_shifting` is set to be `True`")
313
+
314
+ if sigmas is not None and timesteps is not None:
315
+ if len(sigmas) != len(timesteps):
316
+ raise ValueError("`sigmas` and `timesteps` should have the same length")
317
+
318
+ if num_inference_steps is not None:
319
+ if (sigmas is not None and len(sigmas) != num_inference_steps) or (
320
+ timesteps is not None and len(timesteps) != num_inference_steps
321
+ ):
322
+ raise ValueError(
323
+ "`sigmas` and `timesteps` should have the same length as num_inference_steps, if `num_inference_steps` is provided"
324
+ )
325
+ else:
326
+ num_inference_steps = len(sigmas) if sigmas is not None else len(timesteps)
327
+
328
+ self.num_inference_steps = num_inference_steps
329
+
330
+ # 1. Prepare default sigmas
331
+ is_timesteps_provided = timesteps is not None
332
+
333
+ if is_timesteps_provided:
334
+ timesteps = np.array(timesteps).astype(np.float32)
335
+
336
+ if sigmas is None:
337
+ if timesteps is None:
338
+ timesteps = np.linspace(
339
+ self._sigma_to_t(self.sigma_max), self._sigma_to_t(self.sigma_min), num_inference_steps
340
+ )
341
+ sigmas = timesteps / self.config.num_train_timesteps
342
+ else:
343
+ sigmas = np.array(sigmas).astype(np.float32)
344
+ num_inference_steps = len(sigmas)
345
+
346
+ # 2. Perform timestep shifting. Either no shifting is applied, or resolution-dependent shifting of
347
+ # "exponential" or "linear" type is applied
348
+ if self.config.use_dynamic_shifting:
349
+ sigmas = self.time_shift(mu, 1.0, sigmas)
350
+ else:
351
+ sigmas = self.shift * sigmas / (1 + (self.shift - 1) * sigmas)
352
+
353
+ # 3. If required, stretch the sigmas schedule to terminate at the configured `shift_terminal` value
354
+ if self.config.shift_terminal:
355
+ sigmas = self.stretch_shift_to_terminal(sigmas)
356
+
357
+ # 4. If required, convert sigmas to one of karras, exponential, or beta sigma schedules
358
+ if self.config.use_karras_sigmas:
359
+ sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
360
+ elif self.config.use_exponential_sigmas:
361
+ sigmas = self._convert_to_exponential(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
362
+ elif self.config.use_beta_sigmas:
363
+ sigmas = self._convert_to_beta(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
364
+
365
+ # 5. Convert sigmas and timesteps to tensors and move to specified device
366
+ sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)
367
+ if not is_timesteps_provided:
368
+ timesteps = sigmas * self.config.num_train_timesteps
369
+ else:
370
+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32, device=device)
371
+
372
+ # 6. Append the terminal sigma value.
373
+ # If a model requires inverted sigma schedule for denoising but timesteps without inversion, the
374
+ # `invert_sigmas` flag can be set to `True`. This case is only required in Mochi
375
+ if self.config.invert_sigmas:
376
+ sigmas = 1.0 - sigmas
377
+ timesteps = sigmas * self.config.num_train_timesteps
378
+ sigmas = torch.cat([sigmas, torch.ones(1, device=sigmas.device)])
379
+ else:
380
+ sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
381
+
382
+ self.timesteps = timesteps
383
+ self.sigmas = sigmas
384
+ self._step_index = None
385
+ self._begin_index = None
386
+
387
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
388
+ if schedule_timesteps is None:
389
+ schedule_timesteps = self.timesteps
390
+
391
+ indices = (schedule_timesteps == timestep).nonzero()
392
+
393
+ # The sigma index that is taken for the **very** first `step`
394
+ # is always the second index (or the last index if there is only 1)
395
+ # This way we can ensure we don't accidentally skip a sigma in
396
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
397
+ pos = 1 if len(indices) > 1 else 0
398
+
399
+ return indices[pos].item()
400
+
401
+ def _init_step_index(self, timestep):
402
+ if self.begin_index is None:
403
+ if isinstance(timestep, torch.Tensor):
404
+ timestep = timestep.to(self.timesteps.device)
405
+ self._step_index = self.index_for_timestep(timestep)
406
+ else:
407
+ self._step_index = self._begin_index
408
+
409
+ def step(
410
+ self,
411
+ model_output: torch.FloatTensor,
412
+ timestep: Union[float, torch.FloatTensor],
413
+ sample: torch.FloatTensor,
414
+ s_churn: float = 0.0,
415
+ s_tmin: float = 0.0,
416
+ s_tmax: float = float("inf"),
417
+ s_noise: float = 1.0,
418
+ generator: Optional[torch.Generator] = None,
419
+ per_token_timesteps: Optional[torch.Tensor] = None,
420
+ return_dict: bool = True,
421
+ ) -> Union[FlowMatchEulerDiscreteSchedulerOutput, Tuple]:
422
+ """
423
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
424
+ process from the learned model outputs (most often the predicted noise).
425
+
426
+ Args:
427
+ model_output (`torch.FloatTensor`):
428
+ The direct output from learned diffusion model.
429
+ timestep (`float`):
430
+ The current discrete timestep in the diffusion chain.
431
+ sample (`torch.FloatTensor`):
432
+ A current instance of a sample created by the diffusion process.
433
+ s_churn (`float`):
434
+ s_tmin (`float`):
435
+ s_tmax (`float`):
436
+ s_noise (`float`, defaults to 1.0):
437
+ Scaling factor for noise added to the sample.
438
+ generator (`torch.Generator`, *optional*):
439
+ A random number generator.
440
+ per_token_timesteps (`torch.Tensor`, *optional*):
441
+ The timesteps for each token in the sample.
442
+ return_dict (`bool`):
443
+ Whether or not to return a
444
+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] or tuple.
445
+
446
+ Returns:
447
+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] or `tuple`:
448
+ If return_dict is `True`,
449
+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] is returned,
450
+ otherwise a tuple is returned where the first element is the sample tensor.
451
+ """
452
+
453
+ if (
454
+ isinstance(timestep, int)
455
+ or isinstance(timestep, torch.IntTensor)
456
+ or isinstance(timestep, torch.LongTensor)
457
+ ):
458
+ raise ValueError(
459
+ (
460
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
461
+ " `FlowMatchEulerDiscreteScheduler.step()` is not supported. Make sure to pass"
462
+ " one of the `scheduler.timesteps` as a timestep."
463
+ ),
464
+ )
465
+
466
+ if self.step_index is None:
467
+ self._init_step_index(timestep)
468
+
469
+ # Upcast to avoid precision issues when computing prev_sample
470
+ sample = sample.to(torch.float32)
471
+
472
+ if per_token_timesteps is not None:
473
+ per_token_sigmas = per_token_timesteps / self.config.num_train_timesteps
474
+
475
+ sigmas = self.sigmas[:, None, None]
476
+ lower_mask = sigmas < per_token_sigmas[None] - 1e-6
477
+ lower_sigmas = lower_mask * sigmas
478
+ lower_sigmas, _ = lower_sigmas.max(dim=0)
479
+
480
+ current_sigma = per_token_sigmas[..., None]
481
+ next_sigma = lower_sigmas[..., None]
482
+ dt = current_sigma - next_sigma
483
+ else:
484
+ sigma_idx = self.step_index
485
+ sigma = self.sigmas[sigma_idx]
486
+ sigma_next = self.sigmas[sigma_idx + 1]
487
+
488
+ current_sigma = sigma
489
+ next_sigma = sigma_next
490
+ dt = sigma_next - sigma
491
+
492
+ if self.config.stochastic_sampling:
493
+ x0 = sample - current_sigma * lm_correct(prev_noise=self.prev_noise, noise_pred = model_output, lamb = self.lamb, kappa=self.kappa)
494
+ noise = torch.randn_like(sample)
495
+ prev_sample = (1.0 - next_sigma) * x0 + next_sigma * noise
496
+ self.prev_noise = model_output
497
+ else:
498
+ prev_sample = sample + dt * lm_correct(prev_noise=self.prev_noise, noise_pred = model_output, lamb = self.lamb, kappa=self.kappa)
499
+ self.prev_noise = model_output
500
+ # upon completion increase step index by one
501
+ self._step_index += 1
502
+ if per_token_timesteps is None:
503
+ # Cast sample back to model compatible dtype
504
+ prev_sample = prev_sample.to(model_output.dtype)
505
+
506
+ if not return_dict:
507
+ return (prev_sample,)
508
+
509
+ return FlowMatchEulerDiscreteSchedulerOutput(prev_sample=prev_sample)
510
+
511
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
512
+ def _convert_to_karras(self, in_sigmas: torch.Tensor, num_inference_steps) -> torch.Tensor:
513
+ """Constructs the noise schedule of Karras et al. (2022)."""
514
+
515
+ # Hack to make sure that other schedulers which copy this function don't break
516
+ # TODO: Add this logic to the other schedulers
517
+ if hasattr(self.config, "sigma_min"):
518
+ sigma_min = self.config.sigma_min
519
+ else:
520
+ sigma_min = None
521
+
522
+ if hasattr(self.config, "sigma_max"):
523
+ sigma_max = self.config.sigma_max
524
+ else:
525
+ sigma_max = None
526
+
527
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
528
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
529
+
530
+ rho = 7.0 # 7.0 is the value used in the paper
531
+ ramp = np.linspace(0, 1, num_inference_steps)
532
+ min_inv_rho = sigma_min ** (1 / rho)
533
+ max_inv_rho = sigma_max ** (1 / rho)
534
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
535
+ return sigmas
536
+
537
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_exponential
538
+ def _convert_to_exponential(self, in_sigmas: torch.Tensor, num_inference_steps: int) -> torch.Tensor:
539
+ """Constructs an exponential noise schedule."""
540
+
541
+ # Hack to make sure that other schedulers which copy this function don't break
542
+ # TODO: Add this logic to the other schedulers
543
+ if hasattr(self.config, "sigma_min"):
544
+ sigma_min = self.config.sigma_min
545
+ else:
546
+ sigma_min = None
547
+
548
+ if hasattr(self.config, "sigma_max"):
549
+ sigma_max = self.config.sigma_max
550
+ else:
551
+ sigma_max = None
552
+
553
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
554
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
555
+
556
+ sigmas = np.exp(np.linspace(math.log(sigma_max), math.log(sigma_min), num_inference_steps))
557
+ return sigmas
558
+
559
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_beta
560
+ def _convert_to_beta(
561
+ self, in_sigmas: torch.Tensor, num_inference_steps: int, alpha: float = 0.6, beta: float = 0.6
562
+ ) -> torch.Tensor:
563
+ """From "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)"""
564
+
565
+ # Hack to make sure that other schedulers which copy this function don't break
566
+ # TODO: Add this logic to the other schedulers
567
+ if hasattr(self.config, "sigma_min"):
568
+ sigma_min = self.config.sigma_min
569
+ else:
570
+ sigma_min = None
571
+
572
+ if hasattr(self.config, "sigma_max"):
573
+ sigma_max = self.config.sigma_max
574
+ else:
575
+ sigma_max = None
576
+
577
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
578
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
579
+
580
+ sigmas = np.array(
581
+ [
582
+ sigma_min + (ppf * (sigma_max - sigma_min))
583
+ for ppf in [
584
+ scipy.stats.beta.ppf(timestep, alpha, beta)
585
+ for timestep in 1 - np.linspace(0, 1, num_inference_steps)
586
+ ]
587
+ ]
588
+ )
589
+ return sigmas
590
+
591
+ def _time_shift_exponential(self, mu, sigma, t):
592
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
593
+
594
+ def _time_shift_linear(self, mu, sigma, t):
595
+ return mu / (mu + (1 / t - 1) ** sigma)
596
+
597
+ def __len__(self):
598
+ return self.config.num_train_timesteps
scripts/FLUX_T2i_Sampling.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import json
6
+ import argparse
7
+
8
+ sys.path.append(os.getcwd())
9
+
10
+ from diffusers import StableDiffusion3Pipeline, FluxPipeline, FlowMatchHeunDiscreteScheduler, FlowMatchEulerDiscreteScheduler
11
+ from scheduler.scheduling_flow_match_euler_discrete_lm import FlowMatchEulerDiscreteLMScheduler
12
+ from tqdm import tqdm
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser(description="sampling script for T2I-Bench.")
16
+ parser.add_argument('--test_num', type=int, default=10)
17
+ parser.add_argument('--start_index', type=int, default=0)
18
+ parser.add_argument('--num_inference_steps', type=int, default=10)
19
+ parser.add_argument('--guidance', type=float, default=7.5)
20
+ parser.add_argument('--sampler_type', type = str, default='fm_euler')
21
+ parser.add_argument('--model_id', type=str, default='XXX')
22
+ parser.add_argument('--save_dir', type=str, default='results/')
23
+ parser.add_argument('--lamb', type=float, default=5.0)
24
+ parser.add_argument('--kappa', type=float, default=0.0)
25
+ parser.add_argument('--freeze', type=float, default=0.0)
26
+ parser.add_argument('--dataset_category', type=str, default="color")
27
+ parser.add_argument('--dataset_path', type=str, default="T2I-CompBench-main")
28
+ parser.add_argument('--dtype', type=str, default='bf16')
29
+ parser.add_argument('--device', type=str, default='cuda')
30
+
31
+ args = parser.parse_args()
32
+ dtype = None
33
+ if args.dtype in ['fp32']:
34
+ dtype = torch.float32
35
+ elif args.dtype in ['fp64']:
36
+ dtype = torch.float64
37
+ elif args.dtype in ['fp16']:
38
+ dtype = torch.float16
39
+ elif args.dtype in ['bf16']:
40
+ dtype = torch.bfloat16
41
+
42
+ start_index = args.start_index
43
+ sampler_type = args.sampler_type
44
+ test_num = args.test_num
45
+ guidance_scale = args.guidance
46
+ num_inference_steps = args.num_inference_steps
47
+ lamb = args.lamb
48
+ freeze = args.freeze
49
+ kappa = args.kappa
50
+ model_id = args.model_id
51
+ device = args.device
52
+
53
+ # load model
54
+ sd_pipe = FluxPipeline.from_pretrained(
55
+ model_id,
56
+ torch_dtype=dtype, safety_checker=None)
57
+ sd_pipe = sd_pipe.to(device)
58
+ print("flux model loaded")
59
+
60
+ if sampler_type in ['fm_euler']:
61
+ pass
62
+ elif sampler_type in ['lml_euler']:
63
+ sd_pipe.scheduler = FlowMatchEulerDiscreteLMScheduler.from_config(sd_pipe.scheduler.config)
64
+ sd_pipe.scheduler.lamb = lamb
65
+ sd_pipe.scheduler.lm = True
66
+ sd_pipe.scheduler.kappa = kappa
67
+ else:
68
+ raise ValueError(f"invalid: '{sampler_type}'.")
69
+
70
+ save_dir = args.save_dir
71
+
72
+ if sampler_type in ['lml_euler']:
73
+ save_dir = os.path.join(save_dir, "flux", args.dataset_category, sampler_type + "_lamda_" + str(lamb))
74
+ else:
75
+ save_dir = os.path.join(save_dir, "flux", args.dataset_category, sampler_type)
76
+
77
+ save_dir = os.path.join(save_dir, "samples")
78
+ if not os.path.exists(save_dir):
79
+ os.makedirs(save_dir, exist_ok=True)
80
+
81
+ def getT2IDataset(file_path):
82
+ with open(file_path, "r", encoding="utf-8") as file:
83
+ for line in file:
84
+ stripped_line = line.strip()
85
+ if stripped_line:
86
+ yield stripped_line
87
+
88
+ # T2I prompts
89
+ dataset_path = os.path.join(args.dataset_path, 'examples/dataset', args.dataset_category + '_val.txt')
90
+ count = 0
91
+ with tqdm(total=300 * test_num, desc="Generating Images") as pbar:
92
+ try:
93
+ for prompt in getT2IDataset(dataset_path):
94
+ for seed in range(start_index, start_index + test_num):
95
+ torch.manual_seed(seed)
96
+ res = sd_pipe(prompt=prompt, num_inference_steps=num_inference_steps,
97
+ guidance_scale=guidance_scale, generator=None, width=512, height=512).images[0]
98
+ res.save(os.path.join(save_dir, f"{prompt}_{count:06d}.png"))
99
+ count += 1
100
+ pbar.update(1)
101
+ except FileNotFoundError:
102
+ print(f"dataset can not be found: {dataset_path}")
103
+ except Exception as e:
104
+ print(f"unknown error: {str(e)}")
105
+ print(f"{dataset_path} finish")
106
+
107
+ if __name__ == '__main__':
108
+ main()
scripts/StableDiffusion_COCO.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import json
6
+ import argparse
7
+ sys.path.append(os.getcwd())
8
+
9
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepLMScheduler, DDIMLMScheduler, PNDMScheduler, UniPCMultistepScheduler
10
+
11
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
12
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser(description="sampling script for COCO14.")
16
+ parser.add_argument('--test_num', type=int, default=1000)
17
+ parser.add_argument('--start_index', type=int, default=0)
18
+ parser.add_argument('--seed', type=int, default=1)
19
+ parser.add_argument('--num_inference_steps', type=int, default=20)
20
+ parser.add_argument('--guidance', type=float, default=7.5)
21
+ parser.add_argument('--sampler_type', type = str, default='ddim')
22
+ parser.add_argument('--model_id', type=str, default='/xxx/xxx/stable-diffusion-v1-5')
23
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx')
24
+ parser.add_argument('--lamb', type=float, default=5.0)
25
+ parser.add_argument('--kappa', type=float, default=0.0)
26
+ parser.add_argument('--device', type=str, default='cuda')
27
+
28
+
29
+ args = parser.parse_args()
30
+
31
+ start_index = args.start_index
32
+ sampler_type = args.sampler_type
33
+ test_num = args.test_num
34
+ guidance_scale = args.guidance
35
+ num_inference_steps = args.num_inference_steps
36
+ lamb = args.lamb
37
+ kappa = args.kappa
38
+ device = args.device
39
+ model_id = args.model_id
40
+
41
+
42
+ # load model
43
+ sd_pipe = None
44
+
45
+ sd_pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32, safety_checker=None)
46
+ sd_pipe = sd_pipe.to(device)
47
+ print("sd model loaded")
48
+
49
+
50
+ if sampler_type in ['dpm_lm']:
51
+ sd_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(sd_pipe.scheduler.config)
52
+ sd_pipe.scheduler.config.solver_order = 3
53
+ sd_pipe.scheduler.config.algorithm_type = "dpmsolver"
54
+ sd_pipe.scheduler.lamb = lamb
55
+ sd_pipe.scheduler.lm = True
56
+ elif sampler_type in ['dpm']:
57
+ sd_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(sd_pipe.scheduler.config)
58
+ sd_pipe.scheduler.config.solver_order = 3
59
+ sd_pipe.scheduler.config.algorithm_type = "dpmsolver"
60
+ sd_pipe.scheduler.lamb = lamb
61
+ sd_pipe.scheduler.lm = False
62
+ elif sampler_type in ['dpm++']:
63
+ sd_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(sd_pipe.scheduler.config)
64
+ sd_pipe.scheduler.config.solver_order = 3
65
+ sd_pipe.scheduler.config.algorithm_type = "dpmsolver++"
66
+ sd_pipe.scheduler.lamb = lamb
67
+ sd_pipe.scheduler.lm = False
68
+ elif sampler_type in ['dpm++_lm']:
69
+ sd_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(sd_pipe.scheduler.config)
70
+ sd_pipe.scheduler.config.solver_order = 3
71
+ sd_pipe.scheduler.config.algorithm_type = "dpmsolver++"
72
+ sd_pipe.scheduler.lamb = lamb
73
+ sd_pipe.scheduler.lm = True
74
+ elif sampler_type in ['pndm']:
75
+ sd_pipe.scheduler = PNDMScheduler.from_config(sd_pipe.scheduler.config)
76
+ elif sampler_type in ['ddim']:
77
+ sd_pipe.scheduler = DDIMLMScheduler.from_config(sd_pipe.scheduler.config)
78
+ sd_pipe.scheduler.lamb = lamb
79
+ sd_pipe.scheduler.lm = False
80
+ sd_pipe.scheduler.kappa = kappa
81
+ elif sampler_type in ['ddim_lm']:
82
+ sd_pipe.scheduler = DDIMLMScheduler.from_config(sd_pipe.scheduler.config)
83
+ sd_pipe.scheduler.lamb = lamb
84
+ sd_pipe.scheduler.lm = True
85
+ sd_pipe.scheduler.kappa = kappa
86
+ elif sampler_type in ['unipc']:
87
+ sd_pipe.scheduler = UniPCMultistepScheduler.from_config(sd_pipe.scheduler.config)
88
+
89
+ save_dir = args.save_dir
90
+ if not os.path.exists(save_dir):
91
+ os.makedirs(save_dir, exist_ok=True)
92
+
93
+ # COCO prompts
94
+ with open('/mnt/chongqinggeminiceph1fs/geminicephfs/mm-base-vision/pazelzhang/make_dataset/fid_3W_json.json') as fr:
95
+ COCO_prompts_dict = json.load(fr)
96
+ image_id = COCO_prompts_dict.keys()
97
+ with torch.no_grad():
98
+ for pi, key in enumerate(image_id):
99
+ if pi >= start_index and pi < start_index + test_num:
100
+ print(key)
101
+ print(COCO_prompts_dict[key])
102
+ prompt = COCO_prompts_dict[key]
103
+ negative_prompt = None
104
+
105
+ for seed in [1]:
106
+ generator = torch.Generator(device='cuda')
107
+ generator = generator.manual_seed(args.seed)
108
+ res = sd_pipe(prompt=prompt, negative_prompt=negative_prompt, num_inference_steps=num_inference_steps,
109
+ guidance_scale=guidance_scale, generator=generator).images[0]
110
+ res.save(os.path.join(save_dir, f"{pi:05d}_{key}_guidance{guidance_scale}_inference{num_inference_steps}_seed{seed}_{sampler_type}.jpg"))
111
+ print(f"{sampler_type}##{key},done")
112
+
113
+
114
+ if __name__ == '__main__':
115
+ main()
scripts/StableDiffusion_PixArt_T2i_Sampling.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import json
6
+ import argparse
7
+
8
+ sys.path.append(os.getcwd())
9
+
10
+ from diffusers import StableDiffusionPipeline, PNDMScheduler, UniPCMultistepScheduler, DDIMScheduler, DiffusionPipeline, PixArtAlphaPipeline
11
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
12
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
13
+
14
+ from tqdm import tqdm
15
+
16
+ def main():
17
+ parser = argparse.ArgumentParser(description="sampling script for T2I-Bench.")
18
+ parser.add_argument('--test_num', type=int, default=10)
19
+ parser.add_argument('--start_index', type=int, default=0)
20
+ parser.add_argument('--num_inference_steps', type=int, default=10)
21
+ parser.add_argument('--guidance', type=float, default=7.5)
22
+ parser.add_argument('--sampler_type', type = str, default='dpm_lm')
23
+ parser.add_argument('--model', type=str, default='sd15', choices=['sd15', 'sd2_base', 'sdxl', 'pixart'])
24
+ parser.add_argument('--model_dir', type=str, default='XXX')
25
+ parser.add_argument('--save_dir', type=str, default='results/')
26
+ parser.add_argument('--lamb', type=float, default=5.0)
27
+ parser.add_argument('--kappa', type=float, default=0.0)
28
+ parser.add_argument('--freeze', type=float, default=0.0)
29
+ parser.add_argument('--dataset_category', type=str, default="color")
30
+ parser.add_argument('--dataset_path', type=str, default="../T2I-CompBench-main")
31
+ parser.add_argument('--dtype', type=str, default='fp32')
32
+ parser.add_argument('--device', type=str, default='cuda')
33
+
34
+ args = parser.parse_args()
35
+ dtype = None
36
+ if args.dtype in ['fp32']:
37
+ dtype = torch.float32
38
+ elif args.dtype in ['fp64']:
39
+ dtype = torch.float64
40
+ elif args.dtype in ['fp16']:
41
+ dtype = torch.float16
42
+ elif args.dtype in ['bf16']:
43
+ dtype = torch.bfloat16
44
+
45
+ device = args.device
46
+ start_index = args.start_index
47
+ sampler_type = args.sampler_type
48
+ test_num = args.test_num
49
+ guidance_scale = args.guidance
50
+ num_inference_steps = args.num_inference_steps
51
+ lamb = args.lamb
52
+ freeze = args.freeze
53
+ kappa = args.kappa
54
+ model_dir = args.model_dir
55
+
56
+ # load model
57
+ sd_pipe = None
58
+ if args.model in ['sd15']:
59
+ sd_pipe = StableDiffusionPipeline.from_pretrained(
60
+ model_dir,
61
+ torch_dtype=dtype, safety_checker=None)
62
+ sd_pipe = sd_pipe.to(device)
63
+ print("sd-1.5 model loaded")
64
+ elif args.model in ['sd2_base']:
65
+ sd_pipe = StableDiffusionPipeline.from_pretrained(
66
+ model_dir,
67
+ torch_dtype=dtype, safety_checker=None)
68
+ sd_pipe = sd_pipe.to(device)
69
+ print("sd-2-base model loaded")
70
+ elif args.model in ['sdxl']:
71
+ sd_pipe = DiffusionPipeline.from_pretrained(
72
+ model_dir,
73
+ torch_dtype=dtype, safety_checker=None)
74
+ sd_pipe = sd_pipe.to(device)
75
+ print("sd-xl-base model loaded")
76
+ elif args.model in ['pixart']:
77
+ sd_pipe = PixArtAlphaPipeline.from_pretrained(
78
+ model_dir,
79
+ torch_dtype=dtype, safety_checker=None)
80
+ sd_pipe = sd_pipe.to(device)
81
+ print("PixArt-XL-2-512x512 model loaded")
82
+
83
+ SAMPLER_CONFIG = {
84
+ 'dpm_lm': {
85
+ 'scheduler': DPMSolverMultistepLMScheduler,
86
+ 'params': {'solver_order': 3, 'algorithm_type': "dpmsolver", 'lm': True, 'lamb': lamb, 'kappa': kappa, 'freeze': freeze}
87
+ },
88
+ 'dpm': {
89
+ 'scheduler': DPMSolverMultistepLMScheduler,
90
+ 'params': {'solver_order': 3, 'algorithm_type': "dpmsolver", 'lm': False}
91
+ },
92
+ 'dpm++': {
93
+ 'scheduler': DPMSolverMultistepLMScheduler,
94
+ 'params': {'solver_order': 3, 'algorithm_type': "dpmsolver++", 'lm': False}
95
+ },
96
+ 'dpm++_lm': {
97
+ 'scheduler': DPMSolverMultistepLMScheduler,
98
+ 'params': {'solver_order': 3, 'algorithm_type': "dpmsolver++", 'lm': True, 'lamb': lamb, 'kappa': kappa, 'freeze': freeze}
99
+ },
100
+ 'pndm': {'scheduler': PNDMScheduler, 'params': {}},
101
+ 'ddim': {'scheduler': DDIMScheduler, 'params': {}},
102
+ 'ddim_lm': {
103
+ 'scheduler': DDIMLMScheduler,
104
+ 'params': {'lm': True, 'lamb': lamb, 'kappa': kappa, 'freeze': freeze}
105
+ },
106
+ 'unipc': {'scheduler': UniPCMultistepScheduler, 'params': {}},
107
+ }
108
+
109
+ if sampler_type in SAMPLER_CONFIG:
110
+ config = SAMPLER_CONFIG[sampler_type]
111
+ scheduler_class = config['scheduler']
112
+ sd_pipe.scheduler = scheduler_class.from_config(sd_pipe.scheduler.config)
113
+
114
+ for param, value in config['params'].items():
115
+ if hasattr(sd_pipe.scheduler, param):
116
+ setattr(sd_pipe.scheduler, param, value)
117
+ elif hasattr(sd_pipe.scheduler.config, param):
118
+ setattr(sd_pipe.scheduler.config, param, value)
119
+ else:
120
+ raise ValueError(f"invalid: '{sampler_type}'.")
121
+
122
+ save_dir = args.save_dir
123
+
124
+ if sampler_type in ['ddim_lm', 'dpm++_lm', 'dpm_lm']:
125
+ save_dir = os.path.join(save_dir, args.model, args.dataset_category, sampler_type + "_lambda_" + str(lamb))
126
+ else:
127
+ save_dir = os.path.join(save_dir, args.model, args.dataset_category, sampler_type)
128
+ save_dir = os.path.join(save_dir, "samples")
129
+ if not os.path.exists(save_dir):
130
+ os.makedirs(save_dir, exist_ok=True)
131
+
132
+ def getT2IDataset(file_path):
133
+ with open(file_path, "r", encoding="utf-8") as file:
134
+ for line in file:
135
+ stripped_line = line.strip()
136
+ if stripped_line:
137
+ yield stripped_line
138
+
139
+ # T2I prompts
140
+ dataset_path = os.path.join(args.dataset_path, 'examples/dataset', args.dataset_category + '_val.txt')
141
+ count = 0
142
+ with tqdm(total=300 * test_num, desc="Generating Images") as pbar:
143
+ try:
144
+ for prompt in getT2IDataset(dataset_path):
145
+ for seed in range(start_index, start_index + test_num):
146
+ torch.manual_seed(seed)
147
+ res = sd_pipe(prompt=prompt, num_inference_steps=num_inference_steps,
148
+ guidance_scale=guidance_scale, generator=None).images[0]
149
+ res.save(os.path.join(save_dir, f"{prompt}_{count:06d}.png"))
150
+ count += 1
151
+ pbar.update(1)
152
+ except FileNotFoundError:
153
+ print(f"dataset can not be found: {dataset_path}")
154
+ except Exception as e:
155
+ print(f"unknown error: {str(e)}")
156
+ print(f"{dataset_path} finish")
157
+
158
+ if __name__ == '__main__':
159
+ main()
scripts/celeba.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import time
3
+ import torch
4
+ import os
5
+
6
+ import json
7
+ import argparse
8
+ sys.path.append(os.getcwd())
9
+ from diffusers import LDMPipeline, DDIMScheduler, PNDMScheduler, UniPCMultistepScheduler, DPMSolverMultistepScheduler
10
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
11
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
12
+
13
+ def main():
14
+ parser = argparse.ArgumentParser(description="sampling script for CelebA-HQ.")
15
+ parser.add_argument('--test_num', type=int, default=1)
16
+ parser.add_argument('--start_index', type=int, default=0)
17
+ parser.add_argument('--batch_size', type=int, default=4)
18
+ parser.add_argument('--num_inference_steps', type=int, default=20)
19
+ parser.add_argument('--sampler_type', type = str,default='lag', choices=[ 'pndm', 'ddim_lm', 'ddim', 'dpm++', 'dpm','dpm_lm', 'unipc'])
20
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx')
21
+ parser.add_argument('--model_id', type=str,
22
+ default='/xxx/xxx/ddpm_ema_cifar10')
23
+ parser.add_argument('--lamb', type=float, default=1.0)
24
+ parser.add_argument('--kappa', type=float, default=0.0)
25
+ parser.add_argument('--dtype', type=str, default='fp32')
26
+ parser.add_argument('--device', type=str, default='cuda')
27
+
28
+ args = parser.parse_args()
29
+
30
+ dtype = None
31
+ if args.dtype in ['fp32']:
32
+ dtype = torch.float32
33
+ elif args.dtype in ['fp64']:
34
+ dtype = torch.float64
35
+ elif args.dtype in ['fp16']:
36
+ dtype = torch.float16
37
+ elif args.dtype in ['bf16']:
38
+ dtype = torch.bfloat16
39
+
40
+ start_index = args.start_index
41
+ batch_size = args.batch_size
42
+ sampler_type = args.sampler_type
43
+ test_num = args.test_num
44
+ num_inference_steps = args.num_inference_steps
45
+ device = args.device
46
+ lamb = args.lamb
47
+ kappa = args.kappa
48
+ model_id = args.model_id
49
+
50
+ save_dir = args.save_dir
51
+ if not os.path.exists(save_dir):
52
+ os.makedirs(save_dir, exist_ok=True)
53
+
54
+ with torch.no_grad():
55
+ # load pipeline
56
+ pipe = LDMPipeline.from_pretrained(model_id, torch_dtype=dtype)
57
+ pipe.unet.to(device)
58
+ pipe.vqvae.to(device)
59
+
60
+ # load scheduler
61
+ if sampler_type in ['pndm']:
62
+ pipe.scheduler = PNDMScheduler.from_config(pipe.scheduler.config)
63
+ elif sampler_type in ['dpm++']:
64
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
65
+ pipe.scheduler.config.solver_order = 3
66
+ pipe.scheduler.config.algorithm_type = "dpmsolver++"
67
+ elif sampler_type in ['dpm_lm']:
68
+ pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(pipe.scheduler.config)
69
+ pipe.scheduler.config.solver_order = 3
70
+ pipe.scheduler.config.algorithm_type = "dpmsolver"
71
+ pipe.scheduler.lamb = lamb
72
+ pipe.scheduler.lm = True
73
+ pipe.scheduler.kappa = kappa
74
+ elif sampler_type in ['dpm']:
75
+ pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(pipe.scheduler.config)
76
+ pipe.scheduler.config.solver_order = 3
77
+ pipe.scheduler.config.algorithm_type = "dpmsolver"
78
+ pipe.scheduler.lm = False
79
+ elif sampler_type in ['ddim']:
80
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
81
+ elif sampler_type in ['ddim_lm']:
82
+ pipe.scheduler = DDIMLMScheduler.from_config(pipe.scheduler.config)
83
+ pipe.scheduler.lamb = lamb
84
+ pipe.scheduler.lm = True
85
+ pipe.scheduler.kappa = kappa
86
+ elif sampler_type in ['unipc']:
87
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
88
+
89
+ for seed in range(start_index, start_index + test_num):
90
+ print('prepare to sample')
91
+ start_time = time.time()
92
+ torch.manual_seed(seed)
93
+
94
+ # sampling process
95
+ images = pipe(batch_size=batch_size, num_inference_steps=num_inference_steps).images
96
+
97
+ # store the generated images
98
+ for i, image in enumerate(images):
99
+ image.save(
100
+ os.path.join(save_dir, f"cifar10_{sampler_type}_inference{num_inference_steps}_seed{seed}_{i}.png"))
101
+ print(f"{sampler_type} batch##{seed},done")
102
+
103
+ # output the sampling time-costs
104
+ end_time = time.time()
105
+ time_difference = end_time - start_time
106
+ print(f"The code took {time_difference} seconds to run.")
107
+
108
+ if __name__ == '__main__':
109
+ main()
110
+
scripts/cifar10.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import time
3
+ import torch
4
+ import os
5
+
6
+ import json
7
+ import argparse
8
+ sys.path.append(os.getcwd())
9
+ from diffusers import DDPMPipeline, DDIMScheduler, PNDMScheduler, UniPCMultistepScheduler, DPMSolverMultistepScheduler
10
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
11
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
12
+
13
+ def main():
14
+ parser = argparse.ArgumentParser(description="sampling script for CIFAR-10.")
15
+ parser.add_argument('--test_num', type=int, default=1)
16
+ parser.add_argument('--start_index', type=int, default=0)
17
+ parser.add_argument('--batch_size', type=int, default=4)
18
+ parser.add_argument('--num_inference_steps', type=int, default=20)
19
+ parser.add_argument('--sampler_type', type = str,default='lag', choices=[ 'pndm', 'ddim', 'dpm++', 'dpm','dpm_lm', 'unipc'])
20
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx')
21
+ parser.add_argument('--model_id', type=str,
22
+ default='/xxx/xxx/ddpm_ema_cifar10')
23
+ parser.add_argument('--lamb', type=float, default=1.0)
24
+ parser.add_argument('--kappa', type=float, default=0.0)
25
+ parser.add_argument('--dtype', type=str, default='fp32')
26
+ parser.add_argument('--device', type=str, default='cuda')
27
+
28
+ args = parser.parse_args()
29
+
30
+ dtype = None
31
+ if args.dtype in ['fp32']:
32
+ dtype = torch.float32
33
+ elif args.dtype in ['fp64']:
34
+ dtype = torch.float64
35
+ elif args.dtype in ['fp16']:
36
+ dtype = torch.float16
37
+ elif args.dtype in ['bf16']:
38
+ dtype = torch.bfloat16
39
+
40
+ start_index = args.start_index
41
+ device = args.device
42
+ batch_size = args.batch_size
43
+ sampler_type = args.sampler_type
44
+ test_num = args.test_num
45
+ num_inference_steps = args.num_inference_steps
46
+ lamb = args.lamb
47
+ kappa = args.kappa
48
+ model_id = args.model_id
49
+
50
+ save_dir = args.save_dir
51
+ if not os.path.exists(save_dir):
52
+ os.makedirs(save_dir, exist_ok=True)
53
+
54
+ with torch.no_grad():
55
+ # load pipeline
56
+ pipe = DDPMPipeline.from_pretrained(model_id, torch_dtype=dtype)
57
+ pipe.unet.to(device)
58
+
59
+ # load scheduler
60
+ if sampler_type in ['pndm']:
61
+ pipe.scheduler = PNDMScheduler.from_config(pipe.scheduler.config)
62
+ elif sampler_type in ['dpm++']:
63
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
64
+ pipe.scheduler.config.solver_order = 3
65
+ pipe.scheduler.config.algorithm_type = "dpmsolver++"
66
+ elif sampler_type in ['dpm_lm']:
67
+ pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(pipe.scheduler.config)
68
+ pipe.scheduler.config.solver_order = 3
69
+ pipe.scheduler.config.algorithm_type = "dpmsolver"
70
+ pipe.scheduler.lamb = lamb
71
+ pipe.scheduler.lm = True
72
+ pipe.scheduler.kappa = kappa
73
+ elif sampler_type in ['dpm']:
74
+ pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(pipe.scheduler.config)
75
+ pipe.scheduler.config.solver_order = 3
76
+ pipe.scheduler.config.algorithm_type = "dpmsolver"
77
+ pipe.scheduler.lm = False
78
+ elif sampler_type in ['ddim']:
79
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
80
+ elif sampler_type in ['unipc']:
81
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
82
+
83
+ for seed in range(start_index, start_index + test_num):
84
+ print('prepare to sample')
85
+ start_time = time.time()
86
+ torch.manual_seed(seed)
87
+
88
+ # sampling process
89
+ images = pipe(batch_size=batch_size, num_inference_steps=num_inference_steps).images
90
+
91
+ # store the generated images
92
+ for i, image in enumerate(images):
93
+ image.save(
94
+ os.path.join(save_dir, f"cifar10_{sampler_type}_inference{num_inference_steps}_seed{seed}_{i}.png"))
95
+ print(f"{sampler_type} batch##{seed},done")
96
+
97
+ # output the sampling time-costs
98
+ end_time = time.time()
99
+ time_difference = end_time - start_time
100
+ print(f"The code took {time_difference} seconds to run.")
101
+
102
+ if __name__ == '__main__':
103
+ main()
104
+
scripts/control_net_canny.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import json
6
+ import argparse
7
+ sys.path.append(os.getcwd())
8
+
9
+ from PIL import Image
10
+ import torchvision.transforms as transforms
11
+ import numpy as np
12
+ import glob
13
+
14
+
15
+ from diffusers import StableDiffusionPipeline, DDIMScheduler
16
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
17
+ from diffusers.utils import load_image
18
+ from diffusers import StableDiffusionPipeline, DDPMPipeline, DDIMPipeline, PNDMPipeline, PNDMLMPipeline, DDPMLMPipeline, DPMLMPipeline, UniPCPipeline, LDMPipeline, PNDMScheduler, UniPCMultistepScheduler,DDIMScheduler
19
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
20
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
21
+
22
+ import cv2
23
+ import numpy as np
24
+
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(description="sampling script for ControlNet-canny.")
29
+ parser.add_argument('--seed', type=int, default=1)
30
+ parser.add_argument('--num_inference_steps', type=int, default=20)
31
+ parser.add_argument('--guidance', type=float, default=7.5)
32
+ parser.add_argument('--sampler_type', type = str,default='lag')
33
+ parser.add_argument('--prompt', type=str, default='an asian girl')
34
+ parser.add_argument('--original_image_path', type=str, default="/xxx/xxx/data/input_image_vermeer.png")
35
+ parser.add_argument('--lamb', type=float, default=5.0)
36
+ parser.add_argument('--kappa', type=float, default=0.0)
37
+ parser.add_argument('--freeze', type=float, default=0.0)
38
+ # parser.add_argument('--prompt_list', nargs='+', type=str,
39
+ # default=['an asian girl'])
40
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx/result/0402')
41
+ parser.add_argument('--controlnet_dir', type=str, default="/xxx/xxx/sd-controlnet-canny")
42
+ parser.add_argument('--sd_dir', type=str, default="/xxx/xxx/stable-diffusion-v1-5")
43
+
44
+
45
+
46
+ args = parser.parse_args()
47
+ if args.sampler_type in ['bdia']:
48
+ parser.add_argument('--bdia_gamma', type=float, default=0.5)
49
+ if args.sampler_type in ['edict']:
50
+ parser.add_argument('--edict_p', type=float, default=0.93)
51
+ args = parser.parse_args()
52
+ device = 'cuda'
53
+ sampler_type = args.sampler_type
54
+ guidance_scale = args.guidance
55
+ num_inference_steps = args.num_inference_steps
56
+ lamb = args.lamb
57
+ freeze = args.freeze
58
+ kappa = args.kappa
59
+
60
+ save_dir = args.save_dir
61
+ if not os.path.exists(save_dir):
62
+ os.makedirs(save_dir, exist_ok=True)
63
+
64
+ torch.manual_seed(args.seed)
65
+ controlnet = ControlNetModel.from_pretrained(args.controlnet_dir, torch_dtype=torch.float16,use_safetensors=True)
66
+
67
+ control_pipe = StableDiffusionControlNetPipeline.from_pretrained(
68
+ args.sd_dir, controlnet=controlnet, torch_dtype=torch.float16, use_safetensors=True
69
+ )
70
+ control_pipe.enable_model_cpu_offload()
71
+ control_pipe.safety_checker = None
72
+
73
+ if sampler_type in ['dpm_lm']:
74
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
75
+ control_pipe.scheduler.config.solver_order = 3
76
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
77
+ control_pipe.scheduler.lamb = lamb
78
+ control_pipe.scheduler.lm = True
79
+ elif sampler_type in ['dpm']:
80
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
81
+ control_pipe.scheduler.config.solver_order = 3
82
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
83
+ control_pipe.scheduler.lamb = lamb
84
+ control_pipe.scheduler.lm = False
85
+ elif sampler_type in ['dpm++']:
86
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
87
+ control_pipe.scheduler.config.solver_order = 3
88
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
89
+ control_pipe.scheduler.lamb = lamb
90
+ control_pipe.scheduler.lm = False
91
+ elif sampler_type in ['dpm++_lm']:
92
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
93
+ control_pipe.scheduler.config.solver_order = 3
94
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
95
+ control_pipe.scheduler.lamb = lamb
96
+ control_pipe.scheduler.lm = True
97
+ elif sampler_type in ['pndm']:
98
+ control_pipe.scheduler = PNDMScheduler.from_config(control_pipe.scheduler.config)
99
+ elif sampler_type in ['ddim']:
100
+ control_pipe.scheduler = DDIMScheduler.from_config(control_pipe.scheduler.config)
101
+ elif sampler_type in ['ddim_lm']:
102
+ control_pipe.scheduler = DDIMLMScheduler.from_config(control_pipe.scheduler.config)
103
+ control_pipe.scheduler.lamb = lamb
104
+ control_pipe.scheduler.lm = True
105
+ control_pipe.scheduler.kappa = kappa
106
+ control_pipe.scheduler.freeze = freeze
107
+ elif sampler_type in ['unipc']:
108
+ control_pipe.scheduler = UniPCMultistepScheduler.from_config(control_pipe.scheduler.config)
109
+
110
+ original_image = load_image(
111
+ args.original_image_path
112
+ )
113
+ image = np.array(original_image)
114
+ low_threshold = 100
115
+ high_threshold = 200
116
+
117
+ image = cv2.Canny(image, low_threshold, high_threshold)
118
+ image = image[:, :, None]
119
+ image = np.concatenate([image, image, image], axis=2)
120
+ canny_image = Image.fromarray(image)
121
+
122
+
123
+ for prompt, negative_prompt in [['the mona lisa',''],
124
+ ['an asian girl',''],
125
+ ['an asian princess',''],
126
+ ['a portrait of a beautiful woman standing amidst a bed of vibrant tulips.',''],
127
+ ['a stunning Arabic woman dressed in traditional clothing',''],
128
+ ['a stunning Asian woman dressed in traditional clothing',''],
129
+ ['a stunning Black woman dressed in traditional clothing', ''],
130
+ ['a stunning German woman dressed in traditional clothing', ''],
131
+ ['a stunning Japan woman dressed in traditional clothing', ''],
132
+ ['a stunning Chinese woman dressed in traditional clothing', ''],
133
+ ['a stunning Jewish woman dressed in traditional clothing', ''],
134
+ ]:
135
+ for seed in range(1):
136
+ torch.manual_seed(seed)
137
+ res = control_pipe(
138
+ prompt=prompt, negative_prompt=negative_prompt, image=canny_image,num_inference_steps=num_inference_steps,
139
+ ).images[0]
140
+
141
+ res.save(os.path.join(save_dir,
142
+ f"{args.model}_{prompt[:20]}_seed{seed}_{sampler_type}_infer{num_inference_steps}_g{guidance_scale}_lamb{args.lamb}.png"))
143
+
144
+
145
+
146
+ if __name__ == '__main__':
147
+ main()
scripts/control_net_depth.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import argparse
6
+ sys.path.append(os.getcwd())
7
+
8
+ from PIL import Image
9
+ import torchvision.transforms as transforms
10
+ import numpy as np
11
+
12
+
13
+ from diffusers import StableDiffusionPipeline, DDIMScheduler
14
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
15
+ from diffusers.utils import load_image
16
+ from diffusers import PNDMScheduler, UniPCMultistepScheduler,DDIMScheduler
17
+ from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel
18
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
19
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
20
+
21
+ from transformers import pipeline
22
+ import cv2
23
+ import numpy as np
24
+
25
+ def main():
26
+ parser = argparse.ArgumentParser(description="sampling script for ControlNet-depth.")
27
+ parser.add_argument('--seed', type=int, default=1)
28
+ parser.add_argument('--num_inference_steps', type=int, default=20)
29
+ parser.add_argument('--guidance', type=float, default=7.5)
30
+ parser.add_argument('--sampler_type', type = str,default='lag')
31
+ parser.add_argument('--model', type=str, default='sd2_base', choices=['sd15', 'sd2_base'])
32
+ parser.add_argument('--prompt', type=str, default='an asian girl')
33
+ parser.add_argument('--lamb', type=float, default=5.0)
34
+ parser.add_argument('--kappa', type=float, default=0.0)
35
+ parser.add_argument('--freeze', type=float, default=0.0)
36
+ parser.add_argument('--prompt_list', nargs='+', type=str,
37
+ default=['an asian girl'])
38
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx/result/0402')
39
+ parser.add_argument('--controlnet_dir', type=str, default="/xxx/xxx/control_v11f1p_sd15_depth")
40
+ parser.add_argument('--sd_dir', type=str, default="/xxx/xxx/stable-diffusion-v1-5")
41
+
42
+
43
+ args = parser.parse_args()
44
+ if args.sampler_type in ['bdia']:
45
+ parser.add_argument('--bdia_gamma', type=float, default=0.5)
46
+ if args.sampler_type in ['edict']:
47
+ parser.add_argument('--edict_p', type=float, default=0.93)
48
+ args = parser.parse_args()
49
+ device = 'cuda'
50
+ sampler_type = args.sampler_type
51
+ guidance_scale = args.guidance
52
+ num_inference_steps = args.num_inference_steps
53
+ lamb = args.lamb
54
+ freeze = args.freeze
55
+ kappa = args.kappa
56
+
57
+ save_dir = args.save_dir
58
+ if not os.path.exists(save_dir):
59
+ os.makedirs(save_dir, exist_ok=True)
60
+
61
+ # torch.manual_seed(args.seed)
62
+ controlnet = ControlNetModel.from_pretrained(args.controlnet_dir, torch_dtype=torch.float16, use_safetensors=True)
63
+
64
+ control_pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
65
+ args.sd_dir,
66
+ controlnet=controlnet, torch_dtype=torch.float16, use_safetensors=True
67
+ )
68
+ control_pipe.enable_model_cpu_offload()
69
+ control_pipe.safety_checker = None
70
+
71
+ if sampler_type in ['dpm_lm']:
72
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
73
+ control_pipe.scheduler.config.solver_order = 3
74
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
75
+ control_pipe.scheduler.lamb = lamb
76
+ control_pipe.scheduler.lm = True
77
+ elif sampler_type in ['dpm']:
78
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
79
+ control_pipe.scheduler.config.solver_order = 3
80
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
81
+ control_pipe.scheduler.lamb = lamb
82
+ control_pipe.scheduler.lm = False
83
+ elif sampler_type in ['dpm++']:
84
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
85
+ control_pipe.scheduler.config.solver_order = 3
86
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
87
+ control_pipe.scheduler.lamb = lamb
88
+ control_pipe.scheduler.lm = False
89
+ elif sampler_type in ['dpm++_lm']:
90
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
91
+ control_pipe.scheduler.config.solver_order = 3
92
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
93
+ control_pipe.scheduler.lamb = lamb
94
+ control_pipe.scheduler.lm = True
95
+ elif sampler_type in ['pndm']:
96
+ control_pipe.scheduler = PNDMScheduler.from_config(control_pipe.scheduler.config)
97
+ elif sampler_type in ['ddim']:
98
+ control_pipe.scheduler = DDIMScheduler.from_config(control_pipe.scheduler.config)
99
+ # control_pipe.scheduler.lamb = lamb
100
+ # control_pipe.scheduler.lm = False
101
+ # control_pipe.scheduler.kappa = kappa
102
+ elif sampler_type in ['ddim_lm']:
103
+ control_pipe.scheduler = DDIMLMScheduler.from_config(control_pipe.scheduler.config)
104
+ control_pipe.scheduler.lamb = lamb
105
+ control_pipe.scheduler.lm = True
106
+ control_pipe.scheduler.kappa = kappa
107
+ control_pipe.scheduler.freeze = freeze
108
+ elif sampler_type in ['unipc']:
109
+ control_pipe.scheduler = UniPCMultistepScheduler.from_config(control_pipe.scheduler.config)
110
+
111
+ image = load_image(
112
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet-img2img.jpg"
113
+ )
114
+
115
+ def get_depth_map(image, depth_estimator):
116
+ image = depth_estimator(image)["depth"]
117
+ image = np.array(image)
118
+ image = image[:, :, None]
119
+ image = np.concatenate([image, image, image], axis=2)
120
+ detected_map = torch.from_numpy(image).float() / 255.0
121
+ depth_map = detected_map.permute(2, 0, 1)
122
+ return depth_map
123
+
124
+ depth_estimator = pipeline("depth-estimation")
125
+ depth_map = get_depth_map(image, depth_estimator).unsqueeze(0).half().to("cuda")
126
+ transforms.ToPILImage()(depth_map[0]).save(os.path.join(save_dir,
127
+ f"depth_map.png"))
128
+
129
+
130
+ for prompt, negative_prompt in [["lego batman and robin",''],
131
+ ["Spider-Man and Superman", ''],
132
+ ["A girl and a boy", ''],
133
+ ["asian woman and asian man", ''],
134
+ ["American Indian woman and American Indian man", ''],
135
+ ["A girl and a girl, monalisa style", ''],
136
+ ["Elsa and Anna, in the movie Frozen", ''],
137
+ ["A woman and a man, wearing suit", ''],
138
+ ]:
139
+ for seed in range(20):
140
+ torch.manual_seed(seed)
141
+ res = control_pipe(
142
+ prompt = prompt, image=image, control_image=depth_map,num_inference_steps=num_inference_steps,
143
+ ).images[0]
144
+
145
+ res.save(os.path.join(save_dir,
146
+ f"{prompt[:20]}_seed{seed}_{sampler_type}_infer{num_inference_steps}_g{guidance_scale}_lamb{args.lamb}.png"))
147
+
148
+
149
+
150
+ if __name__ == '__main__':
151
+ main()
scripts/control_net_pose.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import os
5
+ import json
6
+ import argparse
7
+ sys.path.append(os.getcwd())
8
+
9
+ from PIL import Image
10
+ import torchvision.transforms as transforms
11
+ import numpy as np
12
+ import glob
13
+
14
+ from diffusers import StableDiffusionPipeline, DDIMScheduler
15
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
16
+ from diffusers.utils import load_image
17
+ from diffusers import PNDMScheduler, UniPCMultistepScheduler,DDIMScheduler
18
+ from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel
19
+ from scheduler.scheduling_dpmsolver_multistep_lm import DPMSolverMultistepLMScheduler
20
+ from scheduler.scheduling_ddim_lm import DDIMLMScheduler
21
+
22
+ from controlnet_aux import OpenposeDetector
23
+ import cv2
24
+ import numpy as np
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(description="sampling script for ControlNet-pose.")
29
+ parser.add_argument('--seed', type=int, default=1)
30
+ parser.add_argument('--num_inference_steps', type=int, default=20)
31
+ parser.add_argument('--guidance', type=float, default=7.5)
32
+ parser.add_argument('--sampler_type', type = str,default='lag')
33
+ parser.add_argument('--prompt', type=str, default='an asian girl')
34
+ parser.add_argument('--lamb', type=float, default=5.0)
35
+ parser.add_argument('--kappa', type=float, default=0.0)
36
+ parser.add_argument('--freeze', type=float, default=0.0)
37
+ parser.add_argument('--prompt_list', nargs='+', type=str,
38
+ default=['an asian girl'])
39
+ parser.add_argument('--save_dir', type=str, default='/xxx/xxx/result/0402')
40
+ parser.add_argument('--controlnet_dir', type=str, default="lllyasviel/sd-controlnet-openpose")
41
+ parser.add_argument('--sd_dir', type=str, default="/xxx/xxx/stable-diffusion-v1-5")
42
+
43
+
44
+ args = parser.parse_args()
45
+ if args.sampler_type in ['bdia']:
46
+ parser.add_argument('--bdia_gamma', type=float, default=0.5)
47
+ if args.sampler_type in ['edict']:
48
+ parser.add_argument('--edict_p', type=float, default=0.93)
49
+ args = parser.parse_args()
50
+ device = 'cuda'
51
+ sampler_type = args.sampler_type
52
+ guidance_scale = args.guidance
53
+ num_inference_steps = args.num_inference_steps
54
+ lamb = args.lamb
55
+ freeze = args.freeze
56
+ kappa = args.kappa
57
+
58
+ save_dir = args.save_dir
59
+ if not os.path.exists(save_dir):
60
+ os.makedirs(save_dir, exist_ok=True)
61
+
62
+ # torch.manual_seed(args.seed)
63
+ controlnet = ControlNetModel.from_pretrained(
64
+ args.controlnet_dir, torch_dtype=torch.float16
65
+ )
66
+
67
+ control_pipe = StableDiffusionControlNetPipeline.from_pretrained(
68
+ args.sd_dir,
69
+ controlnet=controlnet, torch_dtype=torch.float16, use_safetensors=True
70
+ )
71
+ control_pipe.enable_model_cpu_offload()
72
+ control_pipe.safety_checker = None
73
+
74
+ if sampler_type in ['dpm_lm']:
75
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
76
+ control_pipe.scheduler.config.solver_order = 3
77
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
78
+ control_pipe.scheduler.lamb = lamb
79
+ control_pipe.scheduler.lm = True
80
+ elif sampler_type in ['dpm']:
81
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
82
+ control_pipe.scheduler.config.solver_order = 3
83
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver"
84
+ control_pipe.scheduler.lamb = lamb
85
+ control_pipe.scheduler.lm = False
86
+ elif sampler_type in ['dpm++']:
87
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
88
+ control_pipe.scheduler.config.solver_order = 3
89
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
90
+ control_pipe.scheduler.lamb = lamb
91
+ control_pipe.scheduler.lm = False
92
+ elif sampler_type in ['dpm++_lm']:
93
+ control_pipe.scheduler = DPMSolverMultistepLMScheduler.from_config(control_pipe.scheduler.config)
94
+ control_pipe.scheduler.config.solver_order = 3
95
+ control_pipe.scheduler.config.algorithm_type = "dpmsolver++"
96
+ control_pipe.scheduler.lamb = lamb
97
+ control_pipe.scheduler.lm = True
98
+ elif sampler_type in ['pndm']:
99
+ control_pipe.scheduler = PNDMScheduler.from_config(control_pipe.scheduler.config)
100
+ elif sampler_type in ['ddim']:
101
+ control_pipe.scheduler = DDIMScheduler.from_config(control_pipe.scheduler.config)
102
+ # control_pipe.scheduler.lamb = lamb
103
+ # control_pipe.scheduler.lm = False
104
+ # control_pipe.scheduler.kappa = kappa
105
+ elif sampler_type in ['ddim_lm']:
106
+ control_pipe.scheduler = DDIMLMScheduler.from_config(control_pipe.scheduler.config)
107
+ control_pipe.scheduler.lamb = lamb
108
+ control_pipe.scheduler.lm = True
109
+ control_pipe.scheduler.kappa = kappa
110
+ control_pipe.scheduler.freeze = freeze
111
+ elif sampler_type in ['unipc']:
112
+ control_pipe.scheduler = UniPCMultistepScheduler.from_config(control_pipe.scheduler.config)
113
+
114
+ openpose = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')
115
+
116
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/person.png")
117
+
118
+ image = openpose(image)
119
+
120
+
121
+ for prompt, negative_prompt in [["chef in the kitchen",''],
122
+ ["Captain America", ''],
123
+ ["Spider-Man", ''],
124
+ ["Superman", ''],
125
+ ["Hulk", ''],
126
+ ["Batman", ''],
127
+ ["Iron Man", ''],
128
+ ["Deadpool", ''],
129
+ ["Winnie-the-Pooh", ''],
130
+ ["Snow White", ''],
131
+ ["Buzz Lightyear", ''],
132
+ ["Cinderella", ''],
133
+ ["Donald Duck", ''],
134
+ ["policeman", ''],
135
+ ["a doctor", ''],
136
+ ["a teacher", ''],
137
+ ['woman standing amidst a sea of wildflowers, with the warm sun shining down on her.',
138
+ ''],
139
+ ['a stunning Arabic woman dressed in traditional clothing', ''],
140
+ ['a stunning Asian woman dressed in traditional clothing', ''],
141
+ ]:
142
+ for seed in range(15):
143
+ torch.manual_seed(seed)
144
+ res = control_pipe(
145
+ prompt = prompt, image=image, num_inference_steps=num_inference_steps,
146
+ ).images[0]
147
+
148
+ res.save(os.path.join(save_dir,
149
+ f"{prompt[:20]}_seed{seed}_{sampler_type}_infer{num_inference_steps}_g{guidance_scale}_lamb{args.lamb}.png"))
150
+
151
+
152
+
153
+ if __name__ == '__main__':
154
+ main()