Upload 1784 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- BrushNet/.gitignore +178 -0
- BrushNet/.idea/.gitignore +8 -0
- BrushNet/.idea/BrushNet.iml +17 -0
- BrushNet/.idea/inspectionProfiles/profiles_settings.xml +7 -0
- BrushNet/.idea/modules.xml +8 -0
- BrushNet/.idea/workspace.xml +37 -0
- BrushNet/CITATION.cff +42 -0
- BrushNet/CODE_OF_CONDUCT.md +130 -0
- BrushNet/CONTRIBUTING.md +505 -0
- BrushNet/LICENSE +210 -0
- BrushNet/MANIFEST.in +2 -0
- BrushNet/Makefile +94 -0
- BrushNet/PHILOSOPHY.md +110 -0
- BrushNet/README.md +109 -0
- BrushNet/README_original.md +248 -0
- BrushNet/_typos.toml +13 -0
- BrushNet/benchmarks/base_classes.py +346 -0
- BrushNet/benchmarks/benchmark_controlnet.py +26 -0
- BrushNet/benchmarks/benchmark_ip_adapters.py +32 -0
- BrushNet/benchmarks/benchmark_sd_img.py +29 -0
- BrushNet/benchmarks/benchmark_sd_inpainting.py +28 -0
- BrushNet/benchmarks/benchmark_t2i_adapter.py +28 -0
- BrushNet/benchmarks/benchmark_t2i_lcm_lora.py +23 -0
- BrushNet/benchmarks/benchmark_text_to_image.py +40 -0
- BrushNet/benchmarks/push_results.py +72 -0
- BrushNet/benchmarks/run_all.py +97 -0
- BrushNet/benchmarks/utils.py +98 -0
- BrushNet/build/lib/diffusers/__init__.py +789 -0
- BrushNet/build/lib/diffusers/commands/__init__.py +27 -0
- BrushNet/build/lib/diffusers/commands/diffusers_cli.py +43 -0
- BrushNet/build/lib/diffusers/commands/env.py +84 -0
- BrushNet/build/lib/diffusers/commands/fp16_safetensors.py +132 -0
- BrushNet/build/lib/diffusers/configuration_utils.py +703 -0
- BrushNet/build/lib/diffusers/dependency_versions_check.py +34 -0
- BrushNet/build/lib/diffusers/dependency_versions_table.py +45 -0
- BrushNet/build/lib/diffusers/experimental/__init__.py +1 -0
- BrushNet/build/lib/diffusers/experimental/rl/__init__.py +1 -0
- BrushNet/build/lib/diffusers/experimental/rl/value_guided_sampling.py +153 -0
- BrushNet/build/lib/diffusers/image_processor.py +990 -0
- BrushNet/build/lib/diffusers/loaders/__init__.py +88 -0
- BrushNet/build/lib/diffusers/loaders/autoencoder.py +146 -0
- BrushNet/build/lib/diffusers/loaders/controlnet.py +136 -0
- BrushNet/build/lib/diffusers/loaders/ip_adapter.py +281 -0
- BrushNet/build/lib/diffusers/loaders/lora.py +1349 -0
- BrushNet/build/lib/diffusers/loaders/lora_conversion_utils.py +284 -0
- BrushNet/build/lib/diffusers/loaders/peft.py +186 -0
- BrushNet/build/lib/diffusers/loaders/single_file.py +313 -0
- BrushNet/build/lib/diffusers/loaders/single_file_utils.py +1513 -0
- BrushNet/build/lib/diffusers/loaders/textual_inversion.py +562 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
BrushNet/docs/source/en/imgs/access_request.png filter=lfs diff=lfs merge=lfs -text
|
37 |
+
Color-Invariant-Skin-Segmentation/color[[:space:]]augmentation/color_augmentation.png filter=lfs diff=lfs merge=lfs -text
|
BrushNet/.gitignore
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Initially taken from GitHub's Python gitignore file
|
2 |
+
|
3 |
+
# Byte-compiled / optimized / DLL files
|
4 |
+
__pycache__/
|
5 |
+
*.py[cod]
|
6 |
+
*$py.class
|
7 |
+
|
8 |
+
# C extensions
|
9 |
+
*.so
|
10 |
+
|
11 |
+
# tests and logs
|
12 |
+
tests/fixtures/cached_*_text.txt
|
13 |
+
logs/
|
14 |
+
lightning_logs/
|
15 |
+
lang_code_data/
|
16 |
+
|
17 |
+
# Distribution / packaging
|
18 |
+
.Python
|
19 |
+
build/
|
20 |
+
develop-eggs/
|
21 |
+
dist/
|
22 |
+
downloads/
|
23 |
+
eggs/
|
24 |
+
.eggs/
|
25 |
+
lib/
|
26 |
+
lib64/
|
27 |
+
parts/
|
28 |
+
sdist/
|
29 |
+
var/
|
30 |
+
wheels/
|
31 |
+
*.egg-info/
|
32 |
+
.installed.cfg
|
33 |
+
*.egg
|
34 |
+
MANIFEST
|
35 |
+
|
36 |
+
# PyInstaller
|
37 |
+
# Usually these files are written by a Python script from a template
|
38 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
39 |
+
*.manifest
|
40 |
+
*.spec
|
41 |
+
|
42 |
+
# Installer logs
|
43 |
+
pip-log.txt
|
44 |
+
pip-delete-this-directory.txt
|
45 |
+
|
46 |
+
# Unit test / coverage reports
|
47 |
+
htmlcov/
|
48 |
+
.tox/
|
49 |
+
.nox/
|
50 |
+
.coverage
|
51 |
+
.coverage.*
|
52 |
+
.cache
|
53 |
+
nosetests.xml
|
54 |
+
coverage.xml
|
55 |
+
*.cover
|
56 |
+
.hypothesis/
|
57 |
+
.pytest_cache/
|
58 |
+
|
59 |
+
# Translations
|
60 |
+
*.mo
|
61 |
+
*.pot
|
62 |
+
|
63 |
+
# Django stuff:
|
64 |
+
*.log
|
65 |
+
local_settings.py
|
66 |
+
db.sqlite3
|
67 |
+
|
68 |
+
# Flask stuff:
|
69 |
+
instance/
|
70 |
+
.webassets-cache
|
71 |
+
|
72 |
+
# Scrapy stuff:
|
73 |
+
.scrapy
|
74 |
+
|
75 |
+
# Sphinx documentation
|
76 |
+
docs/_build/
|
77 |
+
|
78 |
+
# PyBuilder
|
79 |
+
target/
|
80 |
+
|
81 |
+
# Jupyter Notebook
|
82 |
+
.ipynb_checkpoints
|
83 |
+
|
84 |
+
# IPython
|
85 |
+
profile_default/
|
86 |
+
ipython_config.py
|
87 |
+
|
88 |
+
# pyenv
|
89 |
+
.python-version
|
90 |
+
|
91 |
+
# celery beat schedule file
|
92 |
+
celerybeat-schedule
|
93 |
+
|
94 |
+
# SageMath parsed files
|
95 |
+
*.sage.py
|
96 |
+
|
97 |
+
# Environments
|
98 |
+
.env
|
99 |
+
.venv
|
100 |
+
env/
|
101 |
+
venv/
|
102 |
+
ENV/
|
103 |
+
env.bak/
|
104 |
+
venv.bak/
|
105 |
+
|
106 |
+
# Spyder project settings
|
107 |
+
.spyderproject
|
108 |
+
.spyproject
|
109 |
+
|
110 |
+
# Rope project settings
|
111 |
+
.ropeproject
|
112 |
+
|
113 |
+
# mkdocs documentation
|
114 |
+
/site
|
115 |
+
|
116 |
+
# mypy
|
117 |
+
.mypy_cache/
|
118 |
+
.dmypy.json
|
119 |
+
dmypy.json
|
120 |
+
|
121 |
+
# Pyre type checker
|
122 |
+
.pyre/
|
123 |
+
|
124 |
+
# vscode
|
125 |
+
.vs
|
126 |
+
.vscode
|
127 |
+
|
128 |
+
# Pycharm
|
129 |
+
.idea
|
130 |
+
|
131 |
+
# TF code
|
132 |
+
tensorflow_code
|
133 |
+
|
134 |
+
# Models
|
135 |
+
proc_data
|
136 |
+
|
137 |
+
# examples
|
138 |
+
runs
|
139 |
+
/runs_old
|
140 |
+
/wandb
|
141 |
+
/examples/runs
|
142 |
+
/examples/**/*.args
|
143 |
+
/examples/rag/sweep
|
144 |
+
|
145 |
+
# data
|
146 |
+
/data
|
147 |
+
serialization_dir
|
148 |
+
|
149 |
+
# emacs
|
150 |
+
*.*~
|
151 |
+
debug.env
|
152 |
+
|
153 |
+
# vim
|
154 |
+
.*.swp
|
155 |
+
|
156 |
+
# ctags
|
157 |
+
tags
|
158 |
+
|
159 |
+
# pre-commit
|
160 |
+
.pre-commit*
|
161 |
+
|
162 |
+
# .lock
|
163 |
+
*.lock
|
164 |
+
|
165 |
+
# DS_Store (MacOS)
|
166 |
+
.DS_Store
|
167 |
+
|
168 |
+
# RL pipelines may produce mp4 outputs
|
169 |
+
*.mp4
|
170 |
+
|
171 |
+
# dependencies
|
172 |
+
/transformers
|
173 |
+
|
174 |
+
# ruff
|
175 |
+
.ruff_cache
|
176 |
+
|
177 |
+
# wandb
|
178 |
+
wandb
|
BrushNet/.idea/.gitignore
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Default ignored files
|
2 |
+
/shelf/
|
3 |
+
/workspace.xml
|
4 |
+
# Datasource local storage ignored files
|
5 |
+
/dataSources/
|
6 |
+
/dataSources.local.xml
|
7 |
+
# Editor-based HTTP Client requests
|
8 |
+
/httpRequests/
|
BrushNet/.idea/BrushNet.iml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<module type="PYTHON_MODULE" version="4">
|
3 |
+
<component name="NewModuleRootManager">
|
4 |
+
<content url="file://$MODULE_DIR$">
|
5 |
+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
6 |
+
</content>
|
7 |
+
<orderEntry type="inheritedJdk" />
|
8 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
9 |
+
</component>
|
10 |
+
<component name="PyDocumentationSettings">
|
11 |
+
<option name="format" value="PLAIN" />
|
12 |
+
<option name="myDocStringFormat" value="Plain" />
|
13 |
+
</component>
|
14 |
+
<component name="TestRunnerService">
|
15 |
+
<option name="PROJECT_TEST_RUNNER" value="py.test" />
|
16 |
+
</component>
|
17 |
+
</module>
|
BrushNet/.idea/inspectionProfiles/profiles_settings.xml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<settings>
|
3 |
+
<option name="PROJECT_PROFILE" />
|
4 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
5 |
+
<version value="1.0" />
|
6 |
+
</settings>
|
7 |
+
</component>
|
BrushNet/.idea/modules.xml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectModuleManager">
|
4 |
+
<modules>
|
5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/BrushNet.iml" filepath="$PROJECT_DIR$/.idea/BrushNet.iml" />
|
6 |
+
</modules>
|
7 |
+
</component>
|
8 |
+
</project>
|
BrushNet/.idea/workspace.xml
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ChangeListManager">
|
4 |
+
<list default="true" id="fa859d17-9dde-408a-9d30-adae1a2516fa" name="Changes" comment="" />
|
5 |
+
<option name="SHOW_DIALOG" value="false" />
|
6 |
+
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
7 |
+
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
8 |
+
<option name="LAST_RESOLUTION" value="IGNORE" />
|
9 |
+
</component>
|
10 |
+
<component name="ProjectId" id="2xAsvrecTT99A5HOsFvRdDIMpnE" />
|
11 |
+
<component name="ProjectViewState">
|
12 |
+
<option name="hideEmptyMiddlePackages" value="true" />
|
13 |
+
<option name="showLibraryContents" value="true" />
|
14 |
+
</component>
|
15 |
+
<component name="PropertiesComponent">
|
16 |
+
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
|
17 |
+
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
|
18 |
+
<property name="WebServerToolWindowFactoryState" value="false" />
|
19 |
+
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
|
20 |
+
<property name="settings.editor.selected.configurable" value="com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable" />
|
21 |
+
</component>
|
22 |
+
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
23 |
+
<component name="TaskManager">
|
24 |
+
<task active="true" id="Default" summary="Default task">
|
25 |
+
<changelist id="fa859d17-9dde-408a-9d30-adae1a2516fa" name="Changes" comment="" />
|
26 |
+
<created>1747392449310</created>
|
27 |
+
<option name="number" value="Default" />
|
28 |
+
<option name="presentableId" value="Default" />
|
29 |
+
<updated>1747392449310</updated>
|
30 |
+
<workItem from="1747392451397" duration="733000" />
|
31 |
+
</task>
|
32 |
+
<servers />
|
33 |
+
</component>
|
34 |
+
<component name="TypeScriptGeneratedFilesManager">
|
35 |
+
<option name="version" value="3" />
|
36 |
+
</component>
|
37 |
+
</project>
|
BrushNet/CITATION.cff
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cff-version: 1.2.0
|
2 |
+
title: 'Diffusers: State-of-the-art diffusion models'
|
3 |
+
message: >-
|
4 |
+
If you use this software, please cite it using the
|
5 |
+
metadata from this file.
|
6 |
+
type: software
|
7 |
+
authors:
|
8 |
+
- given-names: Patrick
|
9 |
+
family-names: von Platen
|
10 |
+
- given-names: Suraj
|
11 |
+
family-names: Patil
|
12 |
+
- given-names: Anton
|
13 |
+
family-names: Lozhkov
|
14 |
+
- given-names: Pedro
|
15 |
+
family-names: Cuenca
|
16 |
+
- given-names: Nathan
|
17 |
+
family-names: Lambert
|
18 |
+
- given-names: Kashif
|
19 |
+
family-names: Rasul
|
20 |
+
- given-names: Mishig
|
21 |
+
family-names: Davaadorj
|
22 |
+
- given-names: Thomas
|
23 |
+
family-names: Wolf
|
24 |
+
repository-code: 'https://github.com/huggingface/diffusers'
|
25 |
+
abstract: >-
|
26 |
+
Diffusers provides pretrained diffusion models across
|
27 |
+
multiple modalities, such as vision and audio, and serves
|
28 |
+
as a modular toolbox for inference and training of
|
29 |
+
diffusion models.
|
30 |
+
keywords:
|
31 |
+
- deep-learning
|
32 |
+
- pytorch
|
33 |
+
- image-generation
|
34 |
+
- hacktoberfest
|
35 |
+
- diffusion
|
36 |
+
- text2image
|
37 |
+
- image2image
|
38 |
+
- score-based-generative-modeling
|
39 |
+
- stable-diffusion
|
40 |
+
- stable-diffusion-diffusers
|
41 |
+
license: Apache-2.0
|
42 |
+
version: 0.12.1
|
BrushNet/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# Contributor Covenant Code of Conduct
|
3 |
+
|
4 |
+
## Our Pledge
|
5 |
+
|
6 |
+
We as members, contributors, and leaders pledge to make participation in our
|
7 |
+
community a harassment-free experience for everyone, regardless of age, body
|
8 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
9 |
+
identity and expression, level of experience, education, socio-economic status,
|
10 |
+
nationality, personal appearance, race, caste, color, religion, or sexual identity
|
11 |
+
and orientation.
|
12 |
+
|
13 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
14 |
+
diverse, inclusive, and healthy community.
|
15 |
+
|
16 |
+
## Our Standards
|
17 |
+
|
18 |
+
Examples of behavior that contributes to a positive environment for our
|
19 |
+
community include:
|
20 |
+
|
21 |
+
* Demonstrating empathy and kindness toward other people
|
22 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
23 |
+
* Giving and gracefully accepting constructive feedback
|
24 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
25 |
+
and learning from the experience
|
26 |
+
* Focusing on what is best not just for us as individuals, but for the
|
27 |
+
overall Diffusers community
|
28 |
+
|
29 |
+
Examples of unacceptable behavior include:
|
30 |
+
|
31 |
+
* The use of sexualized language or imagery, and sexual attention or
|
32 |
+
advances of any kind
|
33 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
34 |
+
* Public or private harassment
|
35 |
+
* Publishing others' private information, such as a physical or email
|
36 |
+
address, without their explicit permission
|
37 |
+
* Spamming issues or PRs with links to projects unrelated to this library
|
38 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
39 |
+
professional setting
|
40 |
+
|
41 |
+
## Enforcement Responsibilities
|
42 |
+
|
43 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
44 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
45 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
46 |
+
or harmful.
|
47 |
+
|
48 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
49 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
50 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
51 |
+
decisions when appropriate.
|
52 |
+
|
53 |
+
## Scope
|
54 |
+
|
55 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
56 |
+
an individual is officially representing the community in public spaces.
|
57 |
+
Examples of representing our community include using an official e-mail address,
|
58 |
+
posting via an official social media account, or acting as an appointed
|
59 |
+
representative at an online or offline event.
|
60 |
+
|
61 |
+
## Enforcement
|
62 |
+
|
63 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
64 |
+
reported to the community leaders responsible for enforcement at
|
65 | |
66 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
67 |
+
|
68 |
+
All community leaders are obligated to respect the privacy and security of the
|
69 |
+
reporter of any incident.
|
70 |
+
|
71 |
+
## Enforcement Guidelines
|
72 |
+
|
73 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
74 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
75 |
+
|
76 |
+
### 1. Correction
|
77 |
+
|
78 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
79 |
+
unprofessional or unwelcome in the community.
|
80 |
+
|
81 |
+
**Consequence**: A private, written warning from community leaders, providing
|
82 |
+
clarity around the nature of the violation and an explanation of why the
|
83 |
+
behavior was inappropriate. A public apology may be requested.
|
84 |
+
|
85 |
+
### 2. Warning
|
86 |
+
|
87 |
+
**Community Impact**: A violation through a single incident or series
|
88 |
+
of actions.
|
89 |
+
|
90 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
91 |
+
interaction with the people involved, including unsolicited interaction with
|
92 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
93 |
+
includes avoiding interactions in community spaces as well as external channels
|
94 |
+
like social media. Violating these terms may lead to a temporary or
|
95 |
+
permanent ban.
|
96 |
+
|
97 |
+
### 3. Temporary Ban
|
98 |
+
|
99 |
+
**Community Impact**: A serious violation of community standards, including
|
100 |
+
sustained inappropriate behavior.
|
101 |
+
|
102 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
103 |
+
communication with the community for a specified period of time. No public or
|
104 |
+
private interaction with the people involved, including unsolicited interaction
|
105 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
106 |
+
Violating these terms may lead to a permanent ban.
|
107 |
+
|
108 |
+
### 4. Permanent Ban
|
109 |
+
|
110 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
111 |
+
standards, including sustained inappropriate behavior, harassment of an
|
112 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
113 |
+
|
114 |
+
**Consequence**: A permanent ban from any sort of public interaction within
|
115 |
+
the community.
|
116 |
+
|
117 |
+
## Attribution
|
118 |
+
|
119 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
120 |
+
version 2.1, available at
|
121 |
+
https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
|
122 |
+
|
123 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
124 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
125 |
+
|
126 |
+
[homepage]: https://www.contributor-covenant.org
|
127 |
+
|
128 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
129 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
130 |
+
https://www.contributor-covenant.org/translations.
|
BrushNet/CONTRIBUTING.md
ADDED
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
2 |
+
|
3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
4 |
+
the License. You may obtain a copy of the License at
|
5 |
+
|
6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
7 |
+
|
8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
10 |
+
specific language governing permissions and limitations under the License.
|
11 |
+
-->
|
12 |
+
|
13 |
+
# How to contribute to Diffusers 🧨
|
14 |
+
|
15 |
+
We ❤️ contributions from the open-source community! Everyone is welcome, and all types of participation –not just code– are valued and appreciated. Answering questions, helping others, reaching out, and improving the documentation are all immensely valuable to the community, so don't be afraid and get involved if you're up for it!
|
16 |
+
|
17 |
+
Everyone is encouraged to start by saying 👋 in our public Discord channel. We discuss the latest trends in diffusion models, ask questions, show off personal projects, help each other with contributions, or just hang out ☕. <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=Discord&logoColor=white"></a>
|
18 |
+
|
19 |
+
Whichever way you choose to contribute, we strive to be part of an open, welcoming, and kind community. Please, read our [code of conduct](https://github.com/huggingface/diffusers/blob/main/CODE_OF_CONDUCT.md) and be mindful to respect it during your interactions. We also recommend you become familiar with the [ethical guidelines](https://huggingface.co/docs/diffusers/conceptual/ethical_guidelines) that guide our project and ask you to adhere to the same principles of transparency and responsibility.
|
20 |
+
|
21 |
+
We enormously value feedback from the community, so please do not be afraid to speak up if you believe you have valuable feedback that can help improve the library - every message, comment, issue, and pull request (PR) is read and considered.
|
22 |
+
|
23 |
+
## Overview
|
24 |
+
|
25 |
+
You can contribute in many ways ranging from answering questions on issues to adding new diffusion models to
|
26 |
+
the core library.
|
27 |
+
|
28 |
+
In the following, we give an overview of different ways to contribute, ranked by difficulty in ascending order. All of them are valuable to the community.
|
29 |
+
|
30 |
+
* 1. Asking and answering questions on [the Diffusers discussion forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers) or on [Discord](https://discord.gg/G7tWnz98XR).
|
31 |
+
* 2. Opening new issues on [the GitHub Issues tab](https://github.com/huggingface/diffusers/issues/new/choose).
|
32 |
+
* 3. Answering issues on [the GitHub Issues tab](https://github.com/huggingface/diffusers/issues).
|
33 |
+
* 4. Fix a simple issue, marked by the "Good first issue" label, see [here](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22).
|
34 |
+
* 5. Contribute to the [documentation](https://github.com/huggingface/diffusers/tree/main/docs/source).
|
35 |
+
* 6. Contribute a [Community Pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3Acommunity-examples).
|
36 |
+
* 7. Contribute to the [examples](https://github.com/huggingface/diffusers/tree/main/examples).
|
37 |
+
* 8. Fix a more difficult issue, marked by the "Good second issue" label, see [here](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22).
|
38 |
+
* 9. Add a new pipeline, model, or scheduler, see ["New Pipeline/Model"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) and ["New scheduler"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22) issues. For this contribution, please have a look at [Design Philosophy](https://github.com/huggingface/diffusers/blob/main/PHILOSOPHY.md).
|
39 |
+
|
40 |
+
As said before, **all contributions are valuable to the community**.
|
41 |
+
In the following, we will explain each contribution a bit more in detail.
|
42 |
+
|
43 |
+
For all contributions 4-9, you will need to open a PR. It is explained in detail how to do so in [Opening a pull request](#how-to-open-a-pr).
|
44 |
+
|
45 |
+
### 1. Asking and answering questions on the Diffusers discussion forum or on the Diffusers Discord
|
46 |
+
|
47 |
+
Any question or comment related to the Diffusers library can be asked on the [discussion forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/) or on [Discord](https://discord.gg/G7tWnz98XR). Such questions and comments include (but are not limited to):
|
48 |
+
- Reports of training or inference experiments in an attempt to share knowledge
|
49 |
+
- Presentation of personal projects
|
50 |
+
- Questions to non-official training examples
|
51 |
+
- Project proposals
|
52 |
+
- General feedback
|
53 |
+
- Paper summaries
|
54 |
+
- Asking for help on personal projects that build on top of the Diffusers library
|
55 |
+
- General questions
|
56 |
+
- Ethical questions regarding diffusion models
|
57 |
+
- ...
|
58 |
+
|
59 |
+
Every question that is asked on the forum or on Discord actively encourages the community to publicly
|
60 |
+
share knowledge and might very well help a beginner in the future that has the same question you're
|
61 |
+
having. Please do pose any questions you might have.
|
62 |
+
In the same spirit, you are of immense help to the community by answering such questions because this way you are publicly documenting knowledge for everybody to learn from.
|
63 |
+
|
64 |
+
**Please** keep in mind that the more effort you put into asking or answering a question, the higher
|
65 |
+
the quality of the publicly documented knowledge. In the same way, well-posed and well-answered questions create a high-quality knowledge database accessible to everybody, while badly posed questions or answers reduce the overall quality of the public knowledge database.
|
66 |
+
In short, a high quality question or answer is *precise*, *concise*, *relevant*, *easy-to-understand*, *accessible*, and *well-formated/well-posed*. For more information, please have a look through the [How to write a good issue](#how-to-write-a-good-issue) section.
|
67 |
+
|
68 |
+
**NOTE about channels**:
|
69 |
+
[*The forum*](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) is much better indexed by search engines, such as Google. Posts are ranked by popularity rather than chronologically. Hence, it's easier to look up questions and answers that we posted some time ago.
|
70 |
+
In addition, questions and answers posted in the forum can easily be linked to.
|
71 |
+
In contrast, *Discord* has a chat-like format that invites fast back-and-forth communication.
|
72 |
+
While it will most likely take less time for you to get an answer to your question on Discord, your
|
73 |
+
question won't be visible anymore over time. Also, it's much harder to find information that was posted a while back on Discord. We therefore strongly recommend using the forum for high-quality questions and answers in an attempt to create long-lasting knowledge for the community. If discussions on Discord lead to very interesting answers and conclusions, we recommend posting the results on the forum to make the information more available for future readers.
|
74 |
+
|
75 |
+
### 2. Opening new issues on the GitHub issues tab
|
76 |
+
|
77 |
+
The 🧨 Diffusers library is robust and reliable thanks to the users who notify us of
|
78 |
+
the problems they encounter. So thank you for reporting an issue.
|
79 |
+
|
80 |
+
Remember, GitHub issues are reserved for technical questions directly related to the Diffusers library, bug reports, feature requests, or feedback on the library design.
|
81 |
+
|
82 |
+
In a nutshell, this means that everything that is **not** related to the **code of the Diffusers library** (including the documentation) should **not** be asked on GitHub, but rather on either the [forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) or [Discord](https://discord.gg/G7tWnz98XR).
|
83 |
+
|
84 |
+
**Please consider the following guidelines when opening a new issue**:
|
85 |
+
- Make sure you have searched whether your issue has already been asked before (use the search bar on GitHub under Issues).
|
86 |
+
- Please never report a new issue on another (related) issue. If another issue is highly related, please
|
87 |
+
open a new issue nevertheless and link to the related issue.
|
88 |
+
- Make sure your issue is written in English. Please use one of the great, free online translation services, such as [DeepL](https://www.deepl.com/translator) to translate from your native language to English if you are not comfortable in English.
|
89 |
+
- Check whether your issue might be solved by updating to the newest Diffusers version. Before posting your issue, please make sure that `python -c "import diffusers; print(diffusers.__version__)"` is higher or matches the latest Diffusers version.
|
90 |
+
- Remember that the more effort you put into opening a new issue, the higher the quality of your answer will be and the better the overall quality of the Diffusers issues.
|
91 |
+
|
92 |
+
New issues usually include the following.
|
93 |
+
|
94 |
+
#### 2.1. Reproducible, minimal bug reports
|
95 |
+
|
96 |
+
A bug report should always have a reproducible code snippet and be as minimal and concise as possible.
|
97 |
+
This means in more detail:
|
98 |
+
- Narrow the bug down as much as you can, **do not just dump your whole code file**.
|
99 |
+
- Format your code.
|
100 |
+
- Do not include any external libraries except for Diffusers depending on them.
|
101 |
+
- **Always** provide all necessary information about your environment; for this, you can run: `diffusers-cli env` in your shell and copy-paste the displayed information to the issue.
|
102 |
+
- Explain the issue. If the reader doesn't know what the issue is and why it is an issue, she cannot solve it.
|
103 |
+
- **Always** make sure the reader can reproduce your issue with as little effort as possible. If your code snippet cannot be run because of missing libraries or undefined variables, the reader cannot help you. Make sure your reproducible code snippet is as minimal as possible and can be copy-pasted into a simple Python shell.
|
104 |
+
- If in order to reproduce your issue a model and/or dataset is required, make sure the reader has access to that model or dataset. You can always upload your model or dataset to the [Hub](https://huggingface.co) to make it easily downloadable. Try to keep your model and dataset as small as possible, to make the reproduction of your issue as effortless as possible.
|
105 |
+
|
106 |
+
For more information, please have a look through the [How to write a good issue](#how-to-write-a-good-issue) section.
|
107 |
+
|
108 |
+
You can open a bug report [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml).
|
109 |
+
|
110 |
+
#### 2.2. Feature requests
|
111 |
+
|
112 |
+
A world-class feature request addresses the following points:
|
113 |
+
|
114 |
+
1. Motivation first:
|
115 |
+
* Is it related to a problem/frustration with the library? If so, please explain
|
116 |
+
why. Providing a code snippet that demonstrates the problem is best.
|
117 |
+
* Is it related to something you would need for a project? We'd love to hear
|
118 |
+
about it!
|
119 |
+
* Is it something you worked on and think could benefit the community?
|
120 |
+
Awesome! Tell us what problem it solved for you.
|
121 |
+
2. Write a *full paragraph* describing the feature;
|
122 |
+
3. Provide a **code snippet** that demonstrates its future use;
|
123 |
+
4. In case this is related to a paper, please attach a link;
|
124 |
+
5. Attach any additional information (drawings, screenshots, etc.) you think may help.
|
125 |
+
|
126 |
+
You can open a feature request [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=).
|
127 |
+
|
128 |
+
#### 2.3 Feedback
|
129 |
+
|
130 |
+
Feedback about the library design and why it is good or not good helps the core maintainers immensely to build a user-friendly library. To understand the philosophy behind the current design philosophy, please have a look [here](https://huggingface.co/docs/diffusers/conceptual/philosophy). If you feel like a certain design choice does not fit with the current design philosophy, please explain why and how it should be changed. If a certain design choice follows the design philosophy too much, hence restricting use cases, explain why and how it should be changed.
|
131 |
+
If a certain design choice is very useful for you, please also leave a note as this is great feedback for future design decisions.
|
132 |
+
|
133 |
+
You can open an issue about feedback [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=).
|
134 |
+
|
135 |
+
#### 2.4 Technical questions
|
136 |
+
|
137 |
+
Technical questions are mainly about why certain code of the library was written in a certain way, or what a certain part of the code does. Please make sure to link to the code in question and please provide detail on
|
138 |
+
why this part of the code is difficult to understand.
|
139 |
+
|
140 |
+
You can open an issue about a technical question [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&template=bug-report.yml).
|
141 |
+
|
142 |
+
#### 2.5 Proposal to add a new model, scheduler, or pipeline
|
143 |
+
|
144 |
+
If the diffusion model community released a new model, pipeline, or scheduler that you would like to see in the Diffusers library, please provide the following information:
|
145 |
+
|
146 |
+
* Short description of the diffusion pipeline, model, or scheduler and link to the paper or public release.
|
147 |
+
* Link to any of its open-source implementation.
|
148 |
+
* Link to the model weights if they are available.
|
149 |
+
|
150 |
+
If you are willing to contribute to the model yourself, let us know so we can best guide you. Also, don't forget
|
151 |
+
to tag the original author of the component (model, scheduler, pipeline, etc.) by GitHub handle if you can find it.
|
152 |
+
|
153 |
+
You can open a request for a model/pipeline/scheduler [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=New+model%2Fpipeline%2Fscheduler&template=new-model-addition.yml).
|
154 |
+
|
155 |
+
### 3. Answering issues on the GitHub issues tab
|
156 |
+
|
157 |
+
Answering issues on GitHub might require some technical knowledge of Diffusers, but we encourage everybody to give it a try even if you are not 100% certain that your answer is correct.
|
158 |
+
Some tips to give a high-quality answer to an issue:
|
159 |
+
- Be as concise and minimal as possible.
|
160 |
+
- Stay on topic. An answer to the issue should concern the issue and only the issue.
|
161 |
+
- Provide links to code, papers, or other sources that prove or encourage your point.
|
162 |
+
- Answer in code. If a simple code snippet is the answer to the issue or shows how the issue can be solved, please provide a fully reproducible code snippet.
|
163 |
+
|
164 |
+
Also, many issues tend to be simply off-topic, duplicates of other issues, or irrelevant. It is of great
|
165 |
+
help to the maintainers if you can answer such issues, encouraging the author of the issue to be
|
166 |
+
more precise, provide the link to a duplicated issue or redirect them to [the forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) or [Discord](https://discord.gg/G7tWnz98XR).
|
167 |
+
|
168 |
+
If you have verified that the issued bug report is correct and requires a correction in the source code,
|
169 |
+
please have a look at the next sections.
|
170 |
+
|
171 |
+
For all of the following contributions, you will need to open a PR. It is explained in detail how to do so in the [Opening a pull request](#how-to-open-a-pr) section.
|
172 |
+
|
173 |
+
### 4. Fixing a "Good first issue"
|
174 |
+
|
175 |
+
*Good first issues* are marked by the [Good first issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) label. Usually, the issue already
|
176 |
+
explains how a potential solution should look so that it is easier to fix.
|
177 |
+
If the issue hasn't been closed and you would like to try to fix this issue, you can just leave a message "I would like to try this issue.". There are usually three scenarios:
|
178 |
+
- a.) The issue description already proposes a fix. In this case and if the solution makes sense to you, you can open a PR or draft PR to fix it.
|
179 |
+
- b.) The issue description does not propose a fix. In this case, you can ask what a proposed fix could look like and someone from the Diffusers team should answer shortly. If you have a good idea of how to fix it, feel free to directly open a PR.
|
180 |
+
- c.) There is already an open PR to fix the issue, but the issue hasn't been closed yet. If the PR has gone stale, you can simply open a new PR and link to the stale PR. PRs often go stale if the original contributor who wanted to fix the issue suddenly cannot find the time anymore to proceed. This often happens in open-source and is very normal. In this case, the community will be very happy if you give it a new try and leverage the knowledge of the existing PR. If there is already a PR and it is active, you can help the author by giving suggestions, reviewing the PR or even asking whether you can contribute to the PR.
|
181 |
+
|
182 |
+
|
183 |
+
### 5. Contribute to the documentation
|
184 |
+
|
185 |
+
A good library **always** has good documentation! The official documentation is often one of the first points of contact for new users of the library, and therefore contributing to the documentation is a **highly
|
186 |
+
valuable contribution**.
|
187 |
+
|
188 |
+
Contributing to the library can have many forms:
|
189 |
+
|
190 |
+
- Correcting spelling or grammatical errors.
|
191 |
+
- Correct incorrect formatting of the docstring. If you see that the official documentation is weirdly displayed or a link is broken, we are very happy if you take some time to correct it.
|
192 |
+
- Correct the shape or dimensions of a docstring input or output tensor.
|
193 |
+
- Clarify documentation that is hard to understand or incorrect.
|
194 |
+
- Update outdated code examples.
|
195 |
+
- Translating the documentation to another language.
|
196 |
+
|
197 |
+
Anything displayed on [the official Diffusers doc page](https://huggingface.co/docs/diffusers/index) is part of the official documentation and can be corrected, adjusted in the respective [documentation source](https://github.com/huggingface/diffusers/tree/main/docs/source).
|
198 |
+
|
199 |
+
Please have a look at [this page](https://github.com/huggingface/diffusers/tree/main/docs) on how to verify changes made to the documentation locally.
|
200 |
+
|
201 |
+
|
202 |
+
### 6. Contribute a community pipeline
|
203 |
+
|
204 |
+
[Pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview) are usually the first point of contact between the Diffusers library and the user.
|
205 |
+
Pipelines are examples of how to use Diffusers [models](https://huggingface.co/docs/diffusers/api/models/overview) and [schedulers](https://huggingface.co/docs/diffusers/api/schedulers/overview).
|
206 |
+
We support two types of pipelines:
|
207 |
+
|
208 |
+
- Official Pipelines
|
209 |
+
- Community Pipelines
|
210 |
+
|
211 |
+
Both official and community pipelines follow the same design and consist of the same type of components.
|
212 |
+
|
213 |
+
Official pipelines are tested and maintained by the core maintainers of Diffusers. Their code
|
214 |
+
resides in [src/diffusers/pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines).
|
215 |
+
In contrast, community pipelines are contributed and maintained purely by the **community** and are **not** tested.
|
216 |
+
They reside in [examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) and while they can be accessed via the [PyPI diffusers package](https://pypi.org/project/diffusers/), their code is not part of the PyPI distribution.
|
217 |
+
|
218 |
+
The reason for the distinction is that the core maintainers of the Diffusers library cannot maintain and test all
|
219 |
+
possible ways diffusion models can be used for inference, but some of them may be of interest to the community.
|
220 |
+
Officially released diffusion pipelines,
|
221 |
+
such as Stable Diffusion are added to the core src/diffusers/pipelines package which ensures
|
222 |
+
high quality of maintenance, no backward-breaking code changes, and testing.
|
223 |
+
More bleeding edge pipelines should be added as community pipelines. If usage for a community pipeline is high, the pipeline can be moved to the official pipelines upon request from the community. This is one of the ways we strive to be a community-driven library.
|
224 |
+
|
225 |
+
To add a community pipeline, one should add a <name-of-the-community>.py file to [examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) and adapt the [examples/community/README.md](https://github.com/huggingface/diffusers/tree/main/examples/community/README.md) to include an example of the new pipeline.
|
226 |
+
|
227 |
+
An example can be seen [here](https://github.com/huggingface/diffusers/pull/2400).
|
228 |
+
|
229 |
+
Community pipeline PRs are only checked at a superficial level and ideally they should be maintained by their original authors.
|
230 |
+
|
231 |
+
Contributing a community pipeline is a great way to understand how Diffusers models and schedulers work. Having contributed a community pipeline is usually the first stepping stone to contributing an official pipeline to the
|
232 |
+
core package.
|
233 |
+
|
234 |
+
### 7. Contribute to training examples
|
235 |
+
|
236 |
+
Diffusers examples are a collection of training scripts that reside in [examples](https://github.com/huggingface/diffusers/tree/main/examples).
|
237 |
+
|
238 |
+
We support two types of training examples:
|
239 |
+
|
240 |
+
- Official training examples
|
241 |
+
- Research training examples
|
242 |
+
|
243 |
+
Research training examples are located in [examples/research_projects](https://github.com/huggingface/diffusers/tree/main/examples/research_projects) whereas official training examples include all folders under [examples](https://github.com/huggingface/diffusers/tree/main/examples) except the `research_projects` and `community` folders.
|
244 |
+
The official training examples are maintained by the Diffusers' core maintainers whereas the research training examples are maintained by the community.
|
245 |
+
This is because of the same reasons put forward in [6. Contribute a community pipeline](#6-contribute-a-community-pipeline) for official pipelines vs. community pipelines: It is not feasible for the core maintainers to maintain all possible training methods for diffusion models.
|
246 |
+
If the Diffusers core maintainers and the community consider a certain training paradigm to be too experimental or not popular enough, the corresponding training code should be put in the `research_projects` folder and maintained by the author.
|
247 |
+
|
248 |
+
Both official training and research examples consist of a directory that contains one or more training scripts, a requirements.txt file, and a README.md file. In order for the user to make use of the
|
249 |
+
training examples, it is required to clone the repository:
|
250 |
+
|
251 |
+
```bash
|
252 |
+
git clone https://github.com/huggingface/diffusers
|
253 |
+
```
|
254 |
+
|
255 |
+
as well as to install all additional dependencies required for training:
|
256 |
+
|
257 |
+
```bash
|
258 |
+
pip install -r /examples/<your-example-folder>/requirements.txt
|
259 |
+
```
|
260 |
+
|
261 |
+
Therefore when adding an example, the `requirements.txt` file shall define all pip dependencies required for your training example so that once all those are installed, the user can run the example's training script. See, for example, the [DreamBooth `requirements.txt` file](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/requirements.txt).
|
262 |
+
|
263 |
+
Training examples of the Diffusers library should adhere to the following philosophy:
|
264 |
+
- All the code necessary to run the examples should be found in a single Python file.
|
265 |
+
- One should be able to run the example from the command line with `python <your-example>.py --args`.
|
266 |
+
- Examples should be kept simple and serve as **an example** on how to use Diffusers for training. The purpose of example scripts is **not** to create state-of-the-art diffusion models, but rather to reproduce known training schemes without adding too much custom logic. As a byproduct of this point, our examples also strive to serve as good educational materials.
|
267 |
+
|
268 |
+
To contribute an example, it is highly recommended to look at already existing examples such as [dreambooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py) to get an idea of how they should look like.
|
269 |
+
We strongly advise contributors to make use of the [Accelerate library](https://github.com/huggingface/accelerate) as it's tightly integrated
|
270 |
+
with Diffusers.
|
271 |
+
Once an example script works, please make sure to add a comprehensive `README.md` that states how to use the example exactly. This README should include:
|
272 |
+
- An example command on how to run the example script as shown [here e.g.](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth#running-locally-with-pytorch).
|
273 |
+
- A link to some training results (logs, models, ...) that show what the user can expect as shown [here e.g.](https://api.wandb.ai/report/patrickvonplaten/xm6cd5q5).
|
274 |
+
- If you are adding a non-official/research training example, **please don't forget** to add a sentence that you are maintaining this training example which includes your git handle as shown [here](https://github.com/huggingface/diffusers/tree/main/examples/research_projects/intel_opts#diffusers-examples-with-intel-optimizations).
|
275 |
+
|
276 |
+
If you are contributing to the official training examples, please also make sure to add a test to [examples/test_examples.py](https://github.com/huggingface/diffusers/blob/main/examples/test_examples.py). This is not necessary for non-official training examples.
|
277 |
+
|
278 |
+
### 8. Fixing a "Good second issue"
|
279 |
+
|
280 |
+
*Good second issues* are marked by the [Good second issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22) label. Good second issues are
|
281 |
+
usually more complicated to solve than [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22).
|
282 |
+
The issue description usually gives less guidance on how to fix the issue and requires
|
283 |
+
a decent understanding of the library by the interested contributor.
|
284 |
+
If you are interested in tackling a good second issue, feel free to open a PR to fix it and link the PR to the issue. If you see that a PR has already been opened for this issue but did not get merged, have a look to understand why it wasn't merged and try to open an improved PR.
|
285 |
+
Good second issues are usually more difficult to get merged compared to good first issues, so don't hesitate to ask for help from the core maintainers. If your PR is almost finished the core maintainers can also jump into your PR and commit to it in order to get it merged.
|
286 |
+
|
287 |
+
### 9. Adding pipelines, models, schedulers
|
288 |
+
|
289 |
+
Pipelines, models, and schedulers are the most important pieces of the Diffusers library.
|
290 |
+
They provide easy access to state-of-the-art diffusion technologies and thus allow the community to
|
291 |
+
build powerful generative AI applications.
|
292 |
+
|
293 |
+
By adding a new model, pipeline, or scheduler you might enable a new powerful use case for any of the user interfaces relying on Diffusers which can be of immense value for the whole generative AI ecosystem.
|
294 |
+
|
295 |
+
Diffusers has a couple of open feature requests for all three components - feel free to gloss over them
|
296 |
+
if you don't know yet what specific component you would like to add:
|
297 |
+
- [Model or pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22)
|
298 |
+
- [Scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
|
299 |
+
|
300 |
+
Before adding any of the three components, it is strongly recommended that you give the [Philosophy guide](https://github.com/huggingface/diffusers/blob/main/PHILOSOPHY.md) a read to better understand the design of any of the three components. Please be aware that
|
301 |
+
we cannot merge model, scheduler, or pipeline additions that strongly diverge from our design philosophy
|
302 |
+
as it will lead to API inconsistencies. If you fundamentally disagree with a design choice, please
|
303 |
+
open a [Feedback issue](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=) instead so that it can be discussed whether a certain design
|
304 |
+
pattern/design choice shall be changed everywhere in the library and whether we shall update our design philosophy. Consistency across the library is very important for us.
|
305 |
+
|
306 |
+
Please make sure to add links to the original codebase/paper to the PR and ideally also ping the
|
307 |
+
original author directly on the PR so that they can follow the progress and potentially help with questions.
|
308 |
+
|
309 |
+
If you are unsure or stuck in the PR, don't hesitate to leave a message to ask for a first review or help.
|
310 |
+
|
311 |
+
## How to write a good issue
|
312 |
+
|
313 |
+
**The better your issue is written, the higher the chances that it will be quickly resolved.**
|
314 |
+
|
315 |
+
1. Make sure that you've used the correct template for your issue. You can pick between *Bug Report*, *Feature Request*, *Feedback about API Design*, *New model/pipeline/scheduler addition*, *Forum*, or a blank issue. Make sure to pick the correct one when opening [a new issue](https://github.com/huggingface/diffusers/issues/new/choose).
|
316 |
+
2. **Be precise**: Give your issue a fitting title. Try to formulate your issue description as simple as possible. The more precise you are when submitting an issue, the less time it takes to understand the issue and potentially solve it. Make sure to open an issue for one issue only and not for multiple issues. If you found multiple issues, simply open multiple issues. If your issue is a bug, try to be as precise as possible about what bug it is - you should not just write "Error in diffusers".
|
317 |
+
3. **Reproducibility**: No reproducible code snippet == no solution. If you encounter a bug, maintainers **have to be able to reproduce** it. Make sure that you include a code snippet that can be copy-pasted into a Python interpreter to reproduce the issue. Make sure that your code snippet works, *i.e.* that there are no missing imports or missing links to images, ... Your issue should contain an error message **and** a code snippet that can be copy-pasted without any changes to reproduce the exact same error message. If your issue is using local model weights or local data that cannot be accessed by the reader, the issue cannot be solved. If you cannot share your data or model, try to make a dummy model or dummy data.
|
318 |
+
4. **Minimalistic**: Try to help the reader as much as you can to understand the issue as quickly as possible by staying as concise as possible. Remove all code / all information that is irrelevant to the issue. If you have found a bug, try to create the easiest code example you can to demonstrate your issue, do not just dump your whole workflow into the issue as soon as you have found a bug. E.g., if you train a model and get an error at some point during the training, you should first try to understand what part of the training code is responsible for the error and try to reproduce it with a couple of lines. Try to use dummy data instead of full datasets.
|
319 |
+
5. Add links. If you are referring to a certain naming, method, or model make sure to provide a link so that the reader can better understand what you mean. If you are referring to a specific PR or issue, make sure to link it to your issue. Do not assume that the reader knows what you are talking about. The more links you add to your issue the better.
|
320 |
+
6. Formatting. Make sure to nicely format your issue by formatting code into Python code syntax, and error messages into normal code syntax. See the [official GitHub formatting docs](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) for more information.
|
321 |
+
7. Think of your issue not as a ticket to be solved, but rather as a beautiful entry to a well-written encyclopedia. Every added issue is a contribution to publicly available knowledge. By adding a nicely written issue you not only make it easier for maintainers to solve your issue, but you are helping the whole community to better understand a certain aspect of the library.
|
322 |
+
|
323 |
+
## How to write a good PR
|
324 |
+
|
325 |
+
1. Be a chameleon. Understand existing design patterns and syntax and make sure your code additions flow seamlessly into the existing code base. Pull requests that significantly diverge from existing design patterns or user interfaces will not be merged.
|
326 |
+
2. Be laser focused. A pull request should solve one problem and one problem only. Make sure to not fall into the trap of "also fixing another problem while we're adding it". It is much more difficult to review pull requests that solve multiple, unrelated problems at once.
|
327 |
+
3. If helpful, try to add a code snippet that displays an example of how your addition can be used.
|
328 |
+
4. The title of your pull request should be a summary of its contribution.
|
329 |
+
5. If your pull request addresses an issue, please mention the issue number in
|
330 |
+
the pull request description to make sure they are linked (and people
|
331 |
+
consulting the issue know you are working on it);
|
332 |
+
6. To indicate a work in progress please prefix the title with `[WIP]`. These
|
333 |
+
are useful to avoid duplicated work, and to differentiate it from PRs ready
|
334 |
+
to be merged;
|
335 |
+
7. Try to formulate and format your text as explained in [How to write a good issue](#how-to-write-a-good-issue).
|
336 |
+
8. Make sure existing tests pass;
|
337 |
+
9. Add high-coverage tests. No quality testing = no merge.
|
338 |
+
- If you are adding new `@slow` tests, make sure they pass using
|
339 |
+
`RUN_SLOW=1 python -m pytest tests/test_my_new_model.py`.
|
340 |
+
CircleCI does not run the slow tests, but GitHub Actions does every night!
|
341 |
+
10. All public methods must have informative docstrings that work nicely with markdown. See [`pipeline_latent_diffusion.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py) for an example.
|
342 |
+
11. Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
|
343 |
+
[`hf-internal-testing`](https://huggingface.co/hf-internal-testing) or [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images) to place these files.
|
344 |
+
If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
|
345 |
+
to this dataset.
|
346 |
+
|
347 |
+
## How to open a PR
|
348 |
+
|
349 |
+
Before writing code, we strongly advise you to search through the existing PRs or
|
350 |
+
issues to make sure that nobody is already working on the same thing. If you are
|
351 |
+
unsure, it is always a good idea to open an issue to get some feedback.
|
352 |
+
|
353 |
+
You will need basic `git` proficiency to be able to contribute to
|
354 |
+
🧨 Diffusers. `git` is not the easiest tool to use but it has the greatest
|
355 |
+
manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
|
356 |
+
Git](https://git-scm.com/book/en/v2) is a very good reference.
|
357 |
+
|
358 |
+
Follow these steps to start contributing ([supported Python versions](https://github.com/huggingface/diffusers/blob/main/setup.py#L265)):
|
359 |
+
|
360 |
+
1. Fork the [repository](https://github.com/huggingface/diffusers) by
|
361 |
+
clicking on the 'Fork' button on the repository's page. This creates a copy of the code
|
362 |
+
under your GitHub user account.
|
363 |
+
|
364 |
+
2. Clone your fork to your local disk, and add the base repository as a remote:
|
365 |
+
|
366 |
+
```bash
|
367 |
+
$ git clone [email protected]:<your GitHub handle>/diffusers.git
|
368 |
+
$ cd diffusers
|
369 |
+
$ git remote add upstream https://github.com/huggingface/diffusers.git
|
370 |
+
```
|
371 |
+
|
372 |
+
3. Create a new branch to hold your development changes:
|
373 |
+
|
374 |
+
```bash
|
375 |
+
$ git checkout -b a-descriptive-name-for-my-changes
|
376 |
+
```
|
377 |
+
|
378 |
+
**Do not** work on the `main` branch.
|
379 |
+
|
380 |
+
4. Set up a development environment by running the following command in a virtual environment:
|
381 |
+
|
382 |
+
```bash
|
383 |
+
$ pip install -e ".[dev]"
|
384 |
+
```
|
385 |
+
|
386 |
+
If you have already cloned the repo, you might need to `git pull` to get the most recent changes in the
|
387 |
+
library.
|
388 |
+
|
389 |
+
5. Develop the features on your branch.
|
390 |
+
|
391 |
+
As you work on the features, you should make sure that the test suite
|
392 |
+
passes. You should run the tests impacted by your changes like this:
|
393 |
+
|
394 |
+
```bash
|
395 |
+
$ pytest tests/<TEST_TO_RUN>.py
|
396 |
+
```
|
397 |
+
|
398 |
+
Before you run the tests, please make sure you install the dependencies required for testing. You can do so
|
399 |
+
with this command:
|
400 |
+
|
401 |
+
```bash
|
402 |
+
$ pip install -e ".[test]"
|
403 |
+
```
|
404 |
+
|
405 |
+
You can also run the full test suite with the following command, but it takes
|
406 |
+
a beefy machine to produce a result in a decent amount of time now that
|
407 |
+
Diffusers has grown a lot. Here is the command for it:
|
408 |
+
|
409 |
+
```bash
|
410 |
+
$ make test
|
411 |
+
```
|
412 |
+
|
413 |
+
🧨 Diffusers relies on `ruff` and `isort` to format its source code
|
414 |
+
consistently. After you make changes, apply automatic style corrections and code verifications
|
415 |
+
that can't be automated in one go with:
|
416 |
+
|
417 |
+
```bash
|
418 |
+
$ make style
|
419 |
+
```
|
420 |
+
|
421 |
+
🧨 Diffusers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality
|
422 |
+
control runs in CI, however, you can also run the same checks with:
|
423 |
+
|
424 |
+
```bash
|
425 |
+
$ make quality
|
426 |
+
```
|
427 |
+
|
428 |
+
Once you're happy with your changes, add changed files using `git add` and
|
429 |
+
make a commit with `git commit` to record your changes locally:
|
430 |
+
|
431 |
+
```bash
|
432 |
+
$ git add modified_file.py
|
433 |
+
$ git commit -m "A descriptive message about your changes."
|
434 |
+
```
|
435 |
+
|
436 |
+
It is a good idea to sync your copy of the code with the original
|
437 |
+
repository regularly. This way you can quickly account for changes:
|
438 |
+
|
439 |
+
```bash
|
440 |
+
$ git pull upstream main
|
441 |
+
```
|
442 |
+
|
443 |
+
Push the changes to your account using:
|
444 |
+
|
445 |
+
```bash
|
446 |
+
$ git push -u origin a-descriptive-name-for-my-changes
|
447 |
+
```
|
448 |
+
|
449 |
+
6. Once you are satisfied, go to the
|
450 |
+
webpage of your fork on GitHub. Click on 'Pull request' to send your changes
|
451 |
+
to the project maintainers for review.
|
452 |
+
|
453 |
+
7. It's ok if maintainers ask you for changes. It happens to core contributors
|
454 |
+
too! So everyone can see the changes in the Pull request, work in your local
|
455 |
+
branch and push the changes to your fork. They will automatically appear in
|
456 |
+
the pull request.
|
457 |
+
|
458 |
+
### Tests
|
459 |
+
|
460 |
+
An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
|
461 |
+
the [tests folder](https://github.com/huggingface/diffusers/tree/main/tests).
|
462 |
+
|
463 |
+
We like `pytest` and `pytest-xdist` because it's faster. From the root of the
|
464 |
+
repository, here's how to run tests with `pytest` for the library:
|
465 |
+
|
466 |
+
```bash
|
467 |
+
$ python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
468 |
+
```
|
469 |
+
|
470 |
+
In fact, that's how `make test` is implemented!
|
471 |
+
|
472 |
+
You can specify a smaller set of tests in order to test only the feature
|
473 |
+
you're working on.
|
474 |
+
|
475 |
+
By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to
|
476 |
+
`yes` to run them. This will download many gigabytes of models — make sure you
|
477 |
+
have enough disk space and a good Internet connection, or a lot of patience!
|
478 |
+
|
479 |
+
```bash
|
480 |
+
$ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
481 |
+
```
|
482 |
+
|
483 |
+
`unittest` is fully supported, here's how to run tests with it:
|
484 |
+
|
485 |
+
```bash
|
486 |
+
$ python -m unittest discover -s tests -t . -v
|
487 |
+
$ python -m unittest discover -s examples -t examples -v
|
488 |
+
```
|
489 |
+
|
490 |
+
### Syncing forked main with upstream (HuggingFace) main
|
491 |
+
|
492 |
+
To avoid pinging the upstream repository which adds reference notes to each upstream PR and sends unnecessary notifications to the developers involved in these PRs,
|
493 |
+
when syncing the main branch of a forked repository, please, follow these steps:
|
494 |
+
1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main.
|
495 |
+
2. If a PR is absolutely necessary, use the following steps after checking out your branch:
|
496 |
+
```bash
|
497 |
+
$ git checkout -b your-branch-for-syncing
|
498 |
+
$ git pull --squash --no-commit upstream main
|
499 |
+
$ git commit -m '<your message without GitHub references>'
|
500 |
+
$ git push --set-upstream origin your-branch-for-syncing
|
501 |
+
```
|
502 |
+
|
503 |
+
### Style guide
|
504 |
+
|
505 |
+
For documentation strings, 🧨 Diffusers follows the [Google style](https://google.github.io/styleguide/pyguide.html).
|
BrushNet/LICENSE
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Tencent is pleased to support the open-source community by making BrushNet available.
|
2 |
+
|
3 |
+
Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
|
4 |
+
|
5 |
+
BrushNet is licensed under the Apache License Version 2.0 except for the third-party components listed below.
|
6 |
+
|
7 |
+
Terms of the Apache License Version 2.0:
|
8 |
+
---------------------------------------------
|
9 |
+
|
10 |
+
Apache License
|
11 |
+
Version 2.0, January 2004
|
12 |
+
http://www.apache.org/licenses/
|
13 |
+
|
14 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
15 |
+
|
16 |
+
1. Definitions.
|
17 |
+
|
18 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
19 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
20 |
+
|
21 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
22 |
+
the copyright owner that is granting the License.
|
23 |
+
|
24 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
25 |
+
other entities that control, are controlled by, or are under common
|
26 |
+
control with that entity. For the purposes of this definition,
|
27 |
+
"control" means (i) the power, direct or indirect, to cause the
|
28 |
+
direction or management of such entity, whether by contract or
|
29 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
30 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
31 |
+
|
32 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
33 |
+
exercising permissions granted by this License.
|
34 |
+
|
35 |
+
"Source" form shall mean the preferred form for making modifications,
|
36 |
+
including but not limited to software source code, documentation
|
37 |
+
source, and configuration files.
|
38 |
+
|
39 |
+
"Object" form shall mean any form resulting from mechanical
|
40 |
+
transformation or translation of a Source form, including but
|
41 |
+
not limited to compiled object code, generated documentation,
|
42 |
+
and conversions to other media types.
|
43 |
+
|
44 |
+
"Work" shall mean the work of authorship, whether in Source or
|
45 |
+
Object form, made available under the License, as indicated by a
|
46 |
+
copyright notice that is included in or attached to the work
|
47 |
+
(an example is provided in the Appendix below).
|
48 |
+
|
49 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
50 |
+
form, that is based on (or derived from) the Work and for which the
|
51 |
+
editorial revisions, annotations, elaborations, or other modifications
|
52 |
+
represent, as a whole, an original work of authorship. For the purposes
|
53 |
+
of this License, Derivative Works shall not include works that remain
|
54 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
55 |
+
the Work and Derivative Works thereof.
|
56 |
+
|
57 |
+
"Contribution" shall mean any work of authorship, including
|
58 |
+
the original version of the Work and any modifications or additions
|
59 |
+
to that Work or Derivative Works thereof, that is intentionally
|
60 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
61 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
62 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
63 |
+
means any form of electronic, verbal, or written communication sent
|
64 |
+
to the Licensor or its representatives, including but not limited to
|
65 |
+
communication on electronic mailing lists, source code control systems,
|
66 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
67 |
+
Licensor for the purpose of discussing and improving the Work, but
|
68 |
+
excluding communication that is conspicuously marked or otherwise
|
69 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
70 |
+
|
71 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
72 |
+
on behalf of whom a Contribution has been received by Licensor and
|
73 |
+
subsequently incorporated within the Work.
|
74 |
+
|
75 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
76 |
+
this License, each Contributor hereby grants to You a perpetual,
|
77 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
78 |
+
copyright license to reproduce, prepare Derivative Works of,
|
79 |
+
publicly display, publicly perform, sublicense, and distribute the
|
80 |
+
Work and such Derivative Works in Source or Object form.
|
81 |
+
|
82 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
83 |
+
this License, each Contributor hereby grants to You a perpetual,
|
84 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
85 |
+
(except as stated in this section) patent license to make, have made,
|
86 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
87 |
+
where such license applies only to those patent claims licensable
|
88 |
+
by such Contributor that are necessarily infringed by their
|
89 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
90 |
+
with the Work to which such Contribution(s) was submitted. If You
|
91 |
+
institute patent litigation against any entity (including a
|
92 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
93 |
+
or a Contribution incorporated within the Work constitutes direct
|
94 |
+
or contributory patent infringement, then any patent licenses
|
95 |
+
granted to You under this License for that Work shall terminate
|
96 |
+
as of the date such litigation is filed.
|
97 |
+
|
98 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
99 |
+
Work or Derivative Works thereof in any medium, with or without
|
100 |
+
modifications, and in Source or Object form, provided that You
|
101 |
+
meet the following conditions:
|
102 |
+
|
103 |
+
(a) You must give any other recipients of the Work or
|
104 |
+
Derivative Works a copy of this License; and
|
105 |
+
|
106 |
+
(b) You must cause any modified files to carry prominent notices
|
107 |
+
stating that You changed the files; and
|
108 |
+
|
109 |
+
(c) You must retain, in the Source form of any Derivative Works
|
110 |
+
that You distribute, all copyright, patent, trademark, and
|
111 |
+
attribution notices from the Source form of the Work,
|
112 |
+
excluding those notices that do not pertain to any part of
|
113 |
+
the Derivative Works; and
|
114 |
+
|
115 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
116 |
+
distribution, then any Derivative Works that You distribute must
|
117 |
+
include a readable copy of the attribution notices contained
|
118 |
+
within such NOTICE file, excluding those notices that do not
|
119 |
+
pertain to any part of the Derivative Works, in at least one
|
120 |
+
of the following places: within a NOTICE text file distributed
|
121 |
+
as part of the Derivative Works; within the Source form or
|
122 |
+
documentation, if provided along with the Derivative Works; or,
|
123 |
+
within a display generated by the Derivative Works, if and
|
124 |
+
wherever such third-party notices normally appear. The contents
|
125 |
+
of the NOTICE file are for informational purposes only and
|
126 |
+
do not modify the License. You may add Your own attribution
|
127 |
+
notices within Derivative Works that You distribute, alongside
|
128 |
+
or as an addendum to the NOTICE text from the Work, provided
|
129 |
+
that such additional attribution notices cannot be construed
|
130 |
+
as modifying the License.
|
131 |
+
|
132 |
+
You may add Your own copyright statement to Your modifications and
|
133 |
+
may provide additional or different license terms and conditions
|
134 |
+
for use, reproduction, or distribution of Your modifications, or
|
135 |
+
for any such Derivative Works as a whole, provided Your use,
|
136 |
+
reproduction, and distribution of the Work otherwise complies with
|
137 |
+
the conditions stated in this License.
|
138 |
+
|
139 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
140 |
+
any Contribution intentionally submitted for inclusion in the Work
|
141 |
+
by You to the Licensor shall be under the terms and conditions of
|
142 |
+
this License, without any additional terms or conditions.
|
143 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
144 |
+
the terms of any separate license agreement you may have executed
|
145 |
+
with Licensor regarding such Contributions.
|
146 |
+
|
147 |
+
6. Trademarks. This License does not grant permission to use the trade
|
148 |
+
names, trademarks, service marks, or product names of the Licensor,
|
149 |
+
except as required for reasonable and customary use in describing the
|
150 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
151 |
+
|
152 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
153 |
+
agreed to in writing, Licensor provides the Work (and each
|
154 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
155 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
156 |
+
implied, including, without limitation, any warranties or conditions
|
157 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
158 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
159 |
+
appropriateness of using or redistributing the Work and assume any
|
160 |
+
risks associated with Your exercise of permissions under this License.
|
161 |
+
|
162 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
163 |
+
whether in tort (including negligence), contract, or otherwise,
|
164 |
+
unless required by applicable law (such as deliberate and grossly
|
165 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
166 |
+
liable to You for damages, including any direct, indirect, special,
|
167 |
+
incidental, or consequential damages of any character arising as a
|
168 |
+
result of this License or out of the use or inability to use the
|
169 |
+
Work (including but not limited to damages for loss of goodwill,
|
170 |
+
work stoppage, computer failure or malfunction, or any and all
|
171 |
+
other commercial damages or losses), even if such Contributor
|
172 |
+
has been advised of the possibility of such damages.
|
173 |
+
|
174 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
175 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
176 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
177 |
+
or other liability obligations and/or rights consistent with this
|
178 |
+
License. However, in accepting such obligations, You may act only
|
179 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
180 |
+
of any other Contributor, and only if You agree to indemnify,
|
181 |
+
defend, and hold each Contributor harmless for any liability
|
182 |
+
incurred by, or claims asserted against, such Contributor by reason
|
183 |
+
of your accepting any such warranty or additional liability.
|
184 |
+
|
185 |
+
END OF TERMS AND CONDITIONS
|
186 |
+
|
187 |
+
APPENDIX: How to apply the Apache License to your work.
|
188 |
+
|
189 |
+
To apply the Apache License to your work, attach the following
|
190 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
191 |
+
replaced with your own identifying information. (Don't include
|
192 |
+
the brackets!) The text should be enclosed in the appropriate
|
193 |
+
comment syntax for the file format. We also recommend that a
|
194 |
+
file or class name and description of purpose be included on the
|
195 |
+
same "printed page" as the copyright notice for easier
|
196 |
+
identification within third-party archives.
|
197 |
+
|
198 |
+
Copyright [yyyy] [name of copyright owner]
|
199 |
+
|
200 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
201 |
+
you may not use this file except in compliance with the License.
|
202 |
+
You may obtain a copy of the License at
|
203 |
+
|
204 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
205 |
+
|
206 |
+
Unless required by applicable law or agreed to in writing, software
|
207 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
208 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
209 |
+
See the License for the specific language governing permissions and
|
210 |
+
limitations under the License.
|
BrushNet/MANIFEST.in
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
include LICENSE
|
2 |
+
include src/diffusers/utils/model_card_template.md
|
BrushNet/Makefile
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples
|
2 |
+
|
3 |
+
# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
|
4 |
+
export PYTHONPATH = src
|
5 |
+
|
6 |
+
check_dirs := examples scripts src tests utils benchmarks
|
7 |
+
|
8 |
+
modified_only_fixup:
|
9 |
+
$(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs)))
|
10 |
+
@if test -n "$(modified_py_files)"; then \
|
11 |
+
echo "Checking/fixing $(modified_py_files)"; \
|
12 |
+
ruff check $(modified_py_files) --fix; \
|
13 |
+
ruff format $(modified_py_files);\
|
14 |
+
else \
|
15 |
+
echo "No library .py files were modified"; \
|
16 |
+
fi
|
17 |
+
|
18 |
+
# Update src/diffusers/dependency_versions_table.py
|
19 |
+
|
20 |
+
deps_table_update:
|
21 |
+
@python setup.py deps_table_update
|
22 |
+
|
23 |
+
deps_table_check_updated:
|
24 |
+
@md5sum src/diffusers/dependency_versions_table.py > md5sum.saved
|
25 |
+
@python setup.py deps_table_update
|
26 |
+
@md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1)
|
27 |
+
@rm md5sum.saved
|
28 |
+
|
29 |
+
# autogenerating code
|
30 |
+
|
31 |
+
autogenerate_code: deps_table_update
|
32 |
+
|
33 |
+
# Check that the repo is in a good state
|
34 |
+
|
35 |
+
repo-consistency:
|
36 |
+
python utils/check_dummies.py
|
37 |
+
python utils/check_repo.py
|
38 |
+
python utils/check_inits.py
|
39 |
+
|
40 |
+
# this target runs checks on all files
|
41 |
+
|
42 |
+
quality:
|
43 |
+
ruff check $(check_dirs) setup.py
|
44 |
+
ruff format --check $(check_dirs) setup.py
|
45 |
+
python utils/check_doc_toc.py
|
46 |
+
|
47 |
+
# Format source code automatically and check is there are any problems left that need manual fixing
|
48 |
+
|
49 |
+
extra_style_checks:
|
50 |
+
python utils/custom_init_isort.py
|
51 |
+
python utils/check_doc_toc.py --fix_and_overwrite
|
52 |
+
|
53 |
+
# this target runs checks on all files and potentially modifies some of them
|
54 |
+
|
55 |
+
style:
|
56 |
+
ruff check $(check_dirs) setup.py --fix
|
57 |
+
ruff format $(check_dirs) setup.py
|
58 |
+
${MAKE} autogenerate_code
|
59 |
+
${MAKE} extra_style_checks
|
60 |
+
|
61 |
+
# Super fast fix and check target that only works on relevant modified files since the branch was made
|
62 |
+
|
63 |
+
fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency
|
64 |
+
|
65 |
+
# Make marked copies of snippets of codes conform to the original
|
66 |
+
|
67 |
+
fix-copies:
|
68 |
+
python utils/check_copies.py --fix_and_overwrite
|
69 |
+
python utils/check_dummies.py --fix_and_overwrite
|
70 |
+
|
71 |
+
# Run tests for the library
|
72 |
+
|
73 |
+
test:
|
74 |
+
python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
75 |
+
|
76 |
+
# Run tests for examples
|
77 |
+
|
78 |
+
test-examples:
|
79 |
+
python -m pytest -n auto --dist=loadfile -s -v ./examples/
|
80 |
+
|
81 |
+
|
82 |
+
# Release stuff
|
83 |
+
|
84 |
+
pre-release:
|
85 |
+
python utils/release.py
|
86 |
+
|
87 |
+
pre-patch:
|
88 |
+
python utils/release.py --patch
|
89 |
+
|
90 |
+
post-release:
|
91 |
+
python utils/release.py --post_release
|
92 |
+
|
93 |
+
post-patch:
|
94 |
+
python utils/release.py --post_release --patch
|
BrushNet/PHILOSOPHY.md
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
2 |
+
|
3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
4 |
+
the License. You may obtain a copy of the License at
|
5 |
+
|
6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
7 |
+
|
8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
10 |
+
specific language governing permissions and limitations under the License.
|
11 |
+
-->
|
12 |
+
|
13 |
+
# Philosophy
|
14 |
+
|
15 |
+
🧨 Diffusers provides **state-of-the-art** pretrained diffusion models across multiple modalities.
|
16 |
+
Its purpose is to serve as a **modular toolbox** for both inference and training.
|
17 |
+
|
18 |
+
We aim at building a library that stands the test of time and therefore take API design very seriously.
|
19 |
+
|
20 |
+
In a nutshell, Diffusers is built to be a natural extension of PyTorch. Therefore, most of our design choices are based on [PyTorch's Design Principles](https://pytorch.org/docs/stable/community/design.html#pytorch-design-philosophy). Let's go over the most important ones:
|
21 |
+
|
22 |
+
## Usability over Performance
|
23 |
+
|
24 |
+
- While Diffusers has many built-in performance-enhancing features (see [Memory and Speed](https://huggingface.co/docs/diffusers/optimization/fp16)), models are always loaded with the highest precision and lowest optimization. Therefore, by default diffusion pipelines are always instantiated on CPU with float32 precision if not otherwise defined by the user. This ensures usability across different platforms and accelerators and means that no complex installations are required to run the library.
|
25 |
+
- Diffusers aims to be a **light-weight** package and therefore has very few required dependencies, but many soft dependencies that can improve performance (such as `accelerate`, `safetensors`, `onnx`, etc...). We strive to keep the library as lightweight as possible so that it can be added without much concern as a dependency on other packages.
|
26 |
+
- Diffusers prefers simple, self-explainable code over condensed, magic code. This means that short-hand code syntaxes such as lambda functions, and advanced PyTorch operators are often not desired.
|
27 |
+
|
28 |
+
## Simple over easy
|
29 |
+
|
30 |
+
As PyTorch states, **explicit is better than implicit** and **simple is better than complex**. This design philosophy is reflected in multiple parts of the library:
|
31 |
+
- We follow PyTorch's API with methods like [`DiffusionPipeline.to`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.to) to let the user handle device management.
|
32 |
+
- Raising concise error messages is preferred to silently correct erroneous input. Diffusers aims at teaching the user, rather than making the library as easy to use as possible.
|
33 |
+
- Complex model vs. scheduler logic is exposed instead of magically handled inside. Schedulers/Samplers are separated from diffusion models with minimal dependencies on each other. This forces the user to write the unrolled denoising loop. However, the separation allows for easier debugging and gives the user more control over adapting the denoising process or switching out diffusion models or schedulers.
|
34 |
+
- Separately trained components of the diffusion pipeline, *e.g.* the text encoder, the UNet, and the variational autoencoder, each has their own model class. This forces the user to handle the interaction between the different model components, and the serialization format separates the model components into different files. However, this allows for easier debugging and customization. DreamBooth or Textual Inversion training
|
35 |
+
is very simple thanks to Diffusers' ability to separate single components of the diffusion pipeline.
|
36 |
+
|
37 |
+
## Tweakable, contributor-friendly over abstraction
|
38 |
+
|
39 |
+
For large parts of the library, Diffusers adopts an important design principle of the [Transformers library](https://github.com/huggingface/transformers), which is to prefer copy-pasted code over hasty abstractions. This design principle is very opinionated and stands in stark contrast to popular design principles such as [Don't repeat yourself (DRY)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
|
40 |
+
In short, just like Transformers does for modeling files, Diffusers prefers to keep an extremely low level of abstraction and very self-contained code for pipelines and schedulers.
|
41 |
+
Functions, long code blocks, and even classes can be copied across multiple files which at first can look like a bad, sloppy design choice that makes the library unmaintainable.
|
42 |
+
**However**, this design has proven to be extremely successful for Transformers and makes a lot of sense for community-driven, open-source machine learning libraries because:
|
43 |
+
- Machine Learning is an extremely fast-moving field in which paradigms, model architectures, and algorithms are changing rapidly, which therefore makes it very difficult to define long-lasting code abstractions.
|
44 |
+
- Machine Learning practitioners like to be able to quickly tweak existing code for ideation and research and therefore prefer self-contained code over one that contains many abstractions.
|
45 |
+
- Open-source libraries rely on community contributions and therefore must build a library that is easy to contribute to. The more abstract the code, the more dependencies, the harder to read, and the harder to contribute to. Contributors simply stop contributing to very abstract libraries out of fear of breaking vital functionality. If contributing to a library cannot break other fundamental code, not only is it more inviting for potential new contributors, but it is also easier to review and contribute to multiple parts in parallel.
|
46 |
+
|
47 |
+
At Hugging Face, we call this design the **single-file policy** which means that almost all of the code of a certain class should be written in a single, self-contained file. To read more about the philosophy, you can have a look
|
48 |
+
at [this blog post](https://huggingface.co/blog/transformers-design-philosophy).
|
49 |
+
|
50 |
+
In Diffusers, we follow this philosophy for both pipelines and schedulers, but only partly for diffusion models. The reason we don't follow this design fully for diffusion models is because almost all diffusion pipelines, such
|
51 |
+
as [DDPM](https://huggingface.co/docs/diffusers/api/pipelines/ddpm), [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview#stable-diffusion-pipelines), [unCLIP (DALL·E 2)](https://huggingface.co/docs/diffusers/api/pipelines/unclip) and [Imagen](https://imagen.research.google/) all rely on the same diffusion model, the [UNet](https://huggingface.co/docs/diffusers/api/models/unet2d-cond).
|
52 |
+
|
53 |
+
Great, now you should have generally understood why 🧨 Diffusers is designed the way it is 🤗.
|
54 |
+
We try to apply these design principles consistently across the library. Nevertheless, there are some minor exceptions to the philosophy or some unlucky design choices. If you have feedback regarding the design, we would ❤️ to hear it [directly on GitHub](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=).
|
55 |
+
|
56 |
+
## Design Philosophy in Details
|
57 |
+
|
58 |
+
Now, let's look a bit into the nitty-gritty details of the design philosophy. Diffusers essentially consists of three major classes: [pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines), [models](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models), and [schedulers](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers).
|
59 |
+
Let's walk through more detailed design decisions for each class.
|
60 |
+
|
61 |
+
### Pipelines
|
62 |
+
|
63 |
+
Pipelines are designed to be easy to use (therefore do not follow [*Simple over easy*](#simple-over-easy) 100%), are not feature complete, and should loosely be seen as examples of how to use [models](#models) and [schedulers](#schedulers) for inference.
|
64 |
+
|
65 |
+
The following design principles are followed:
|
66 |
+
- Pipelines follow the single-file policy. All pipelines can be found in individual directories under src/diffusers/pipelines. One pipeline folder corresponds to one diffusion paper/project/release. Multiple pipeline files can be gathered in one pipeline folder, as it’s done for [`src/diffusers/pipelines/stable-diffusion`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion). If pipelines share similar functionality, one can make use of the [#Copied from mechanism](https://github.com/huggingface/diffusers/blob/125d783076e5bd9785beb05367a2d2566843a271/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L251).
|
67 |
+
- Pipelines all inherit from [`DiffusionPipeline`].
|
68 |
+
- Every pipeline consists of different model and scheduler components, that are documented in the [`model_index.json` file](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/model_index.json), are accessible under the same name as attributes of the pipeline and can be shared between pipelines with [`DiffusionPipeline.components`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.components) function.
|
69 |
+
- Every pipeline should be loadable via the [`DiffusionPipeline.from_pretrained`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.from_pretrained) function.
|
70 |
+
- Pipelines should be used **only** for inference.
|
71 |
+
- Pipelines should be very readable, self-explanatory, and easy to tweak.
|
72 |
+
- Pipelines should be designed to build on top of each other and be easy to integrate into higher-level APIs.
|
73 |
+
- Pipelines are **not** intended to be feature-complete user interfaces. For future complete user interfaces one should rather have a look at [InvokeAI](https://github.com/invoke-ai/InvokeAI), [Diffuzers](https://github.com/abhishekkrthakur/diffuzers), and [lama-cleaner](https://github.com/Sanster/lama-cleaner).
|
74 |
+
- Every pipeline should have one and only one way to run it via a `__call__` method. The naming of the `__call__` arguments should be shared across all pipelines.
|
75 |
+
- Pipelines should be named after the task they are intended to solve.
|
76 |
+
- In almost all cases, novel diffusion pipelines shall be implemented in a new pipeline folder/file.
|
77 |
+
|
78 |
+
### Models
|
79 |
+
|
80 |
+
Models are designed as configurable toolboxes that are natural extensions of [PyTorch's Module class](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). They only partly follow the **single-file policy**.
|
81 |
+
|
82 |
+
The following design principles are followed:
|
83 |
+
- Models correspond to **a type of model architecture**. *E.g.* the [`UNet2DConditionModel`] class is used for all UNet variations that expect 2D image inputs and are conditioned on some context.
|
84 |
+
- All models can be found in [`src/diffusers/models`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models) and every model architecture shall be defined in its file, e.g. [`unet_2d_condition.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py), [`transformer_2d.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformer_2d.py), etc...
|
85 |
+
- Models **do not** follow the single-file policy and should make use of smaller model building blocks, such as [`attention.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py), [`resnet.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py), [`embeddings.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py), etc... **Note**: This is in stark contrast to Transformers' modeling files and shows that models do not really follow the single-file policy.
|
86 |
+
- Models intend to expose complexity, just like PyTorch's `Module` class, and give clear error messages.
|
87 |
+
- Models all inherit from `ModelMixin` and `ConfigMixin`.
|
88 |
+
- Models can be optimized for performance when it doesn’t demand major code changes, keep backward compatibility, and give significant memory or compute gain.
|
89 |
+
- Models should by default have the highest precision and lowest performance setting.
|
90 |
+
- To integrate new model checkpoints whose general architecture can be classified as an architecture that already exists in Diffusers, the existing model architecture shall be adapted to make it work with the new checkpoint. One should only create a new file if the model architecture is fundamentally different.
|
91 |
+
- Models should be designed to be easily extendable to future changes. This can be achieved by limiting public function arguments, configuration arguments, and "foreseeing" future changes, *e.g.* it is usually better to add `string` "...type" arguments that can easily be extended to new future types instead of boolean `is_..._type` arguments. Only the minimum amount of changes shall be made to existing architectures to make a new model checkpoint work.
|
92 |
+
- The model design is a difficult trade-off between keeping code readable and concise and supporting many model checkpoints. For most parts of the modeling code, classes shall be adapted for new model checkpoints, while there are some exceptions where it is preferred to add new classes to make sure the code is kept concise and
|
93 |
+
readable long-term, such as [UNet blocks](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py) and [Attention processors](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
94 |
+
|
95 |
+
### Schedulers
|
96 |
+
|
97 |
+
Schedulers are responsible to guide the denoising process for inference as well as to define a noise schedule for training. They are designed as individual classes with loadable configuration files and strongly follow the **single-file policy**.
|
98 |
+
|
99 |
+
The following design principles are followed:
|
100 |
+
- All schedulers are found in [`src/diffusers/schedulers`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers).
|
101 |
+
- Schedulers are **not** allowed to import from large utils files and shall be kept very self-contained.
|
102 |
+
- One scheduler Python file corresponds to one scheduler algorithm (as might be defined in a paper).
|
103 |
+
- If schedulers share similar functionalities, we can make use of the `#Copied from` mechanism.
|
104 |
+
- Schedulers all inherit from `SchedulerMixin` and `ConfigMixin`.
|
105 |
+
- Schedulers can be easily swapped out with the [`ConfigMixin.from_config`](https://huggingface.co/docs/diffusers/main/en/api/configuration#diffusers.ConfigMixin.from_config) method as explained in detail [here](./docs/source/en/using-diffusers/schedulers.md).
|
106 |
+
- Every scheduler has to have a `set_num_inference_steps`, and a `step` function. `set_num_inference_steps(...)` has to be called before every denoising process, *i.e.* before `step(...)` is called.
|
107 |
+
- Every scheduler exposes the timesteps to be "looped over" via a `timesteps` attribute, which is an array of timesteps the model will be called upon.
|
108 |
+
- The `step(...)` function takes a predicted model output and the "current" sample (x_t) and returns the "previous", slightly more denoised sample (x_t-1).
|
109 |
+
- Given the complexity of diffusion schedulers, the `step` function does not expose all the complexity and can be a bit of a "black box".
|
110 |
+
- In almost all cases, novel schedulers shall be implemented in a new scheduling file.
|
BrushNet/README.md
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# BrushNet
|
2 |
+
|
3 |
+
This repository contains a fork of the implementation of the paper "BrushNet: A Plug-and-Play Image Inpainting Model with Decomposed Dual-Branch Diffusion" that was used for generating PinPoint counterfactuals.
|
4 |
+
Please, refer to the <a href="https://tencentarc.github.io/BrushNet/">Original Project</a> for details on the environment installation and a complete description of BrushNet's features.
|
5 |
+
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
## Getting Started
|
10 |
+
|
11 |
+
### Environment Requirement 🌍
|
12 |
+
|
13 |
+
BrushNet has been implemented and tested on Pytorch 1.12.1 with python 3.9.
|
14 |
+
|
15 |
+
Clone the repo:
|
16 |
+
|
17 |
+
```
|
18 |
+
git clone https://github.com/TencentARC/BrushNet.git
|
19 |
+
```
|
20 |
+
|
21 |
+
We recommend you first use `conda` to create virtual environment, and install `pytorch` following [official instructions](https://pytorch.org/). For example:
|
22 |
+
|
23 |
+
|
24 |
+
```
|
25 |
+
conda create -n diffusers python=3.9 -y
|
26 |
+
conda activate diffusers
|
27 |
+
python -m pip install --upgrade pip
|
28 |
+
pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu116
|
29 |
+
```
|
30 |
+
|
31 |
+
Then, you can install diffusers (implemented in this repo) with:
|
32 |
+
|
33 |
+
```
|
34 |
+
pip install -e .
|
35 |
+
```
|
36 |
+
|
37 |
+
After that, you can install required packages thourgh:
|
38 |
+
|
39 |
+
```
|
40 |
+
cd examples/brushnet/
|
41 |
+
pip install -r requirements.txt
|
42 |
+
```
|
43 |
+
|
44 |
+
### Data Download ⬇️
|
45 |
+
|
46 |
+
|
47 |
+
**Dataset**
|
48 |
+
|
49 |
+
After downloading the datasets (CC3M: https://ai.google.com/research/ConceptualCaptions/download and FACET https://ai.meta.com/datasets/facet-downloads/), edit the paths in
|
50 |
+
`./examples/brushnet/inpaint_cc3m.py`, and
|
51 |
+
`./examples/brushnet/inpaint_facet.py`.
|
52 |
+
|
53 |
+
**Checkpoints**
|
54 |
+
|
55 |
+
Checkpoints of BrushNet can be downloaded from [here](https://drive.google.com/drive/folders/1fqmS1CEOvXCxNWFrsSYd_jHYXxrydh1n?usp=drive_link). The ckpt folder needs to contain pretrained checkpoints and pretrained Stable Diffusion checkpoint (realisticVisionV60B1_v51VAE from [Civitai](https://civitai.com/)). The data structure should be like:
|
56 |
+
|
57 |
+
```
|
58 |
+
|-- data
|
59 |
+
|-- BrushData
|
60 |
+
|-- BrushDench
|
61 |
+
|-- EditBench
|
62 |
+
|-- ckpt
|
63 |
+
|-- realisticVisionV60B1_v51VAE
|
64 |
+
|-- model_index.json
|
65 |
+
|-- vae
|
66 |
+
|-- ...
|
67 |
+
|-- segmentation_mask_brushnet_ckpt
|
68 |
+
```
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
## 🏃🏼 Running Scripts
|
73 |
+
|
74 |
+
### Inference 📜
|
75 |
+
|
76 |
+
You can in-paint FACET with the script:
|
77 |
+
|
78 |
+
```
|
79 |
+
python examples/brushnet/inpaint_facet.py
|
80 |
+
```
|
81 |
+
|
82 |
+
You can experiment with different prompts for in-painting different values of protected attributes. For in-painting PP*, WB*, and C&A* setups, change the corresponding prompts to `f"A photo of a man/woman who is a {category}."`, otherwise leave it as `f"A photo of a man/woman."`
|
83 |
+
|
84 |
+
For in-paintinf CC3M use the script:
|
85 |
+
|
86 |
+
```
|
87 |
+
python examples/brushnet/inpaint_cc3m.py
|
88 |
+
```
|
89 |
+
|
90 |
+
|
91 |
+
### Evaluation 📏
|
92 |
+
|
93 |
+
You can evaluate the image realism using the following script, first installing the required dependencies:
|
94 |
+
|
95 |
+
```
|
96 |
+
python examples/brushnet/evaluate_dir.py
|
97 |
+
```
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
Make sure to set the paths to the image directories before running the script.
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
Note that the evaluation script requires the following additional dependencies:
|
106 |
+
- open_clip
|
107 |
+
- hpsv2
|
108 |
+
- ImageReward
|
109 |
+
- CLIPScore
|
BrushNet/README_original.md
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!---
|
2 |
+
Copyright 2022 - The HuggingFace Team. All rights reserved.
|
3 |
+
|
4 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
you may not use this file except in compliance with the License.
|
6 |
+
You may obtain a copy of the License at
|
7 |
+
|
8 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
|
10 |
+
Unless required by applicable law or agreed to in writing, software
|
11 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
See the License for the specific language governing permissions and
|
14 |
+
limitations under the License.
|
15 |
+
-->
|
16 |
+
|
17 |
+
<p align="center">
|
18 |
+
<br>
|
19 |
+
<img src="https://raw.githubusercontent.com/huggingface/diffusers/main/docs/source/en/imgs/diffusers_library.jpg" width="400"/>
|
20 |
+
<br>
|
21 |
+
<p>
|
22 |
+
<p align="center">
|
23 |
+
<a href="https://github.com/huggingface/diffusers/blob/main/LICENSE">
|
24 |
+
<img alt="GitHub" src="https://img.shields.io/github/license/huggingface/datasets.svg?color=blue">
|
25 |
+
</a>
|
26 |
+
<a href="https://github.com/huggingface/diffusers/releases">
|
27 |
+
<img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/diffusers.svg">
|
28 |
+
</a>
|
29 |
+
<a href="https://pepy.tech/project/diffusers">
|
30 |
+
<img alt="GitHub release" src="https://static.pepy.tech/badge/diffusers/month">
|
31 |
+
</a>
|
32 |
+
<a href="CODE_OF_CONDUCT.md">
|
33 |
+
<img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg">
|
34 |
+
</a>
|
35 |
+
<a href="https://twitter.com/diffuserslib">
|
36 |
+
<img alt="X account" src="https://img.shields.io/twitter/url/https/twitter.com/diffuserslib.svg?style=social&label=Follow%20%40diffuserslib">
|
37 |
+
</a>
|
38 |
+
</p>
|
39 |
+
|
40 |
+
🤗 Diffusers is the go-to library for state-of-the-art pretrained diffusion models for generating images, audio, and even 3D structures of molecules. Whether you're looking for a simple inference solution or training your own diffusion models, 🤗 Diffusers is a modular toolbox that supports both. Our library is designed with a focus on [usability over performance](https://huggingface.co/docs/diffusers/conceptual/philosophy#usability-over-performance), [simple over easy](https://huggingface.co/docs/diffusers/conceptual/philosophy#simple-over-easy), and [customizability over abstractions](https://huggingface.co/docs/diffusers/conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
|
41 |
+
|
42 |
+
🤗 Diffusers offers three core components:
|
43 |
+
|
44 |
+
- State-of-the-art [diffusion pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview) that can be run in inference with just a few lines of code.
|
45 |
+
- Interchangeable noise [schedulers](https://huggingface.co/docs/diffusers/api/schedulers/overview) for different diffusion speeds and output quality.
|
46 |
+
- Pretrained [models](https://huggingface.co/docs/diffusers/api/models/overview) that can be used as building blocks, and combined with schedulers, for creating your own end-to-end diffusion systems.
|
47 |
+
|
48 |
+
## Installation
|
49 |
+
|
50 |
+
We recommend installing 🤗 Diffusers in a virtual environment from PyPI or Conda. For more details about installing [PyTorch](https://pytorch.org/get-started/locally/) and [Flax](https://flax.readthedocs.io/en/latest/#installation), please refer to their official documentation.
|
51 |
+
|
52 |
+
### PyTorch
|
53 |
+
|
54 |
+
With `pip` (official package):
|
55 |
+
|
56 |
+
```bash
|
57 |
+
pip install --upgrade diffusers[torch]
|
58 |
+
```
|
59 |
+
|
60 |
+
With `conda` (maintained by the community):
|
61 |
+
|
62 |
+
```sh
|
63 |
+
conda install -c conda-forge diffusers
|
64 |
+
```
|
65 |
+
|
66 |
+
### Flax
|
67 |
+
|
68 |
+
With `pip` (official package):
|
69 |
+
|
70 |
+
```bash
|
71 |
+
pip install --upgrade diffusers[flax]
|
72 |
+
```
|
73 |
+
|
74 |
+
### Apple Silicon (M1/M2) support
|
75 |
+
|
76 |
+
Please refer to the [How to use Stable Diffusion in Apple Silicon](https://huggingface.co/docs/diffusers/optimization/mps) guide.
|
77 |
+
|
78 |
+
## Quickstart
|
79 |
+
|
80 |
+
Generating outputs is super easy with 🤗 Diffusers. To generate an image from text, use the `from_pretrained` method to load any pretrained diffusion model (browse the [Hub](https://huggingface.co/models?library=diffusers&sort=downloads) for 19000+ checkpoints):
|
81 |
+
|
82 |
+
```python
|
83 |
+
from diffusers import DiffusionPipeline
|
84 |
+
import torch
|
85 |
+
|
86 |
+
pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
|
87 |
+
pipeline.to("cuda")
|
88 |
+
pipeline("An image of a squirrel in Picasso style").images[0]
|
89 |
+
```
|
90 |
+
|
91 |
+
You can also dig into the models and schedulers toolbox to build your own diffusion system:
|
92 |
+
|
93 |
+
```python
|
94 |
+
from diffusers import DDPMScheduler, UNet2DModel
|
95 |
+
from PIL import Image
|
96 |
+
import torch
|
97 |
+
|
98 |
+
scheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
|
99 |
+
model = UNet2DModel.from_pretrained("google/ddpm-cat-256").to("cuda")
|
100 |
+
scheduler.set_timesteps(50)
|
101 |
+
|
102 |
+
sample_size = model.config.sample_size
|
103 |
+
noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")
|
104 |
+
input = noise
|
105 |
+
|
106 |
+
for t in scheduler.timesteps:
|
107 |
+
with torch.no_grad():
|
108 |
+
noisy_residual = model(input, t).sample
|
109 |
+
prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
|
110 |
+
input = prev_noisy_sample
|
111 |
+
|
112 |
+
image = (input / 2 + 0.5).clamp(0, 1)
|
113 |
+
image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
|
114 |
+
image = Image.fromarray((image * 255).round().astype("uint8"))
|
115 |
+
image
|
116 |
+
```
|
117 |
+
|
118 |
+
Check out the [Quickstart](https://huggingface.co/docs/diffusers/quicktour) to launch your diffusion journey today!
|
119 |
+
|
120 |
+
## How to navigate the documentation
|
121 |
+
|
122 |
+
| **Documentation** | **What can I learn?** |
|
123 |
+
|---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
124 |
+
| [Tutorial](https://huggingface.co/docs/diffusers/tutorials/tutorial_overview) | A basic crash course for learning how to use the library's most important features like using models and schedulers to build your own diffusion system, and training your own diffusion model. |
|
125 |
+
| [Loading](https://huggingface.co/docs/diffusers/using-diffusers/loading_overview) | Guides for how to load and configure all the components (pipelines, models, and schedulers) of the library, as well as how to use different schedulers. |
|
126 |
+
| [Pipelines for inference](https://huggingface.co/docs/diffusers/using-diffusers/pipeline_overview) | Guides for how to use pipelines for different inference tasks, batched generation, controlling generated outputs and randomness, and how to contribute a pipeline to the library. |
|
127 |
+
| [Optimization](https://huggingface.co/docs/diffusers/optimization/opt_overview) | Guides for how to optimize your diffusion model to run faster and consume less memory. |
|
128 |
+
| [Training](https://huggingface.co/docs/diffusers/training/overview) | Guides for how to train a diffusion model for different tasks with different training techniques. |
|
129 |
+
## Contribution
|
130 |
+
|
131 |
+
We ❤️ contributions from the open-source community!
|
132 |
+
If you want to contribute to this library, please check out our [Contribution guide](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md).
|
133 |
+
You can look out for [issues](https://github.com/huggingface/diffusers/issues) you'd like to tackle to contribute to the library.
|
134 |
+
- See [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) for general opportunities to contribute
|
135 |
+
- See [New model/pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) to contribute exciting new diffusion models / diffusion pipelines
|
136 |
+
- See [New scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
|
137 |
+
|
138 |
+
Also, say 👋 in our public Discord channel <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>. We discuss the hottest trends about diffusion models, help each other with contributions, personal projects or just hang out ☕.
|
139 |
+
|
140 |
+
|
141 |
+
## Popular Tasks & Pipelines
|
142 |
+
|
143 |
+
<table>
|
144 |
+
<tr>
|
145 |
+
<th>Task</th>
|
146 |
+
<th>Pipeline</th>
|
147 |
+
<th>🤗 Hub</th>
|
148 |
+
</tr>
|
149 |
+
<tr style="border-top: 2px solid black">
|
150 |
+
<td>Unconditional Image Generation</td>
|
151 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/ddpm"> DDPM </a></td>
|
152 |
+
<td><a href="https://huggingface.co/google/ddpm-ema-church-256"> google/ddpm-ema-church-256 </a></td>
|
153 |
+
</tr>
|
154 |
+
<tr style="border-top: 2px solid black">
|
155 |
+
<td>Text-to-Image</td>
|
156 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img">Stable Diffusion Text-to-Image</a></td>
|
157 |
+
<td><a href="https://huggingface.co/runwayml/stable-diffusion-v1-5"> runwayml/stable-diffusion-v1-5 </a></td>
|
158 |
+
</tr>
|
159 |
+
<tr>
|
160 |
+
<td>Text-to-Image</td>
|
161 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/unclip">unCLIP</a></td>
|
162 |
+
<td><a href="https://huggingface.co/kakaobrain/karlo-v1-alpha"> kakaobrain/karlo-v1-alpha </a></td>
|
163 |
+
</tr>
|
164 |
+
<tr>
|
165 |
+
<td>Text-to-Image</td>
|
166 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/deepfloyd_if">DeepFloyd IF</a></td>
|
167 |
+
<td><a href="https://huggingface.co/DeepFloyd/IF-I-XL-v1.0"> DeepFloyd/IF-I-XL-v1.0 </a></td>
|
168 |
+
</tr>
|
169 |
+
<tr>
|
170 |
+
<td>Text-to-Image</td>
|
171 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/kandinsky">Kandinsky</a></td>
|
172 |
+
<td><a href="https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder"> kandinsky-community/kandinsky-2-2-decoder </a></td>
|
173 |
+
</tr>
|
174 |
+
<tr style="border-top: 2px solid black">
|
175 |
+
<td>Text-guided Image-to-Image</td>
|
176 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/controlnet">ControlNet</a></td>
|
177 |
+
<td><a href="https://huggingface.co/lllyasviel/sd-controlnet-canny"> lllyasviel/sd-controlnet-canny </a></td>
|
178 |
+
</tr>
|
179 |
+
<tr>
|
180 |
+
<td>Text-guided Image-to-Image</td>
|
181 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/pix2pix">InstructPix2Pix</a></td>
|
182 |
+
<td><a href="https://huggingface.co/timbrooks/instruct-pix2pix"> timbrooks/instruct-pix2pix </a></td>
|
183 |
+
</tr>
|
184 |
+
<tr>
|
185 |
+
<td>Text-guided Image-to-Image</td>
|
186 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/img2img">Stable Diffusion Image-to-Image</a></td>
|
187 |
+
<td><a href="https://huggingface.co/runwayml/stable-diffusion-v1-5"> runwayml/stable-diffusion-v1-5 </a></td>
|
188 |
+
</tr>
|
189 |
+
<tr style="border-top: 2px solid black">
|
190 |
+
<td>Text-guided Image Inpainting</td>
|
191 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/inpaint">Stable Diffusion Inpainting</a></td>
|
192 |
+
<td><a href="https://huggingface.co/runwayml/stable-diffusion-inpainting"> runwayml/stable-diffusion-inpainting </a></td>
|
193 |
+
</tr>
|
194 |
+
<tr style="border-top: 2px solid black">
|
195 |
+
<td>Image Variation</td>
|
196 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/image_variation">Stable Diffusion Image Variation</a></td>
|
197 |
+
<td><a href="https://huggingface.co/lambdalabs/sd-image-variations-diffusers"> lambdalabs/sd-image-variations-diffusers </a></td>
|
198 |
+
</tr>
|
199 |
+
<tr style="border-top: 2px solid black">
|
200 |
+
<td>Super Resolution</td>
|
201 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/upscale">Stable Diffusion Upscale</a></td>
|
202 |
+
<td><a href="https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler"> stabilityai/stable-diffusion-x4-upscaler </a></td>
|
203 |
+
</tr>
|
204 |
+
<tr>
|
205 |
+
<td>Super Resolution</td>
|
206 |
+
<td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/latent_upscale">Stable Diffusion Latent Upscale</a></td>
|
207 |
+
<td><a href="https://huggingface.co/stabilityai/sd-x2-latent-upscaler"> stabilityai/sd-x2-latent-upscaler </a></td>
|
208 |
+
</tr>
|
209 |
+
</table>
|
210 |
+
|
211 |
+
## Popular libraries using 🧨 Diffusers
|
212 |
+
|
213 |
+
- https://github.com/microsoft/TaskMatrix
|
214 |
+
- https://github.com/invoke-ai/InvokeAI
|
215 |
+
- https://github.com/apple/ml-stable-diffusion
|
216 |
+
- https://github.com/Sanster/lama-cleaner
|
217 |
+
- https://github.com/IDEA-Research/Grounded-Segment-Anything
|
218 |
+
- https://github.com/ashawkey/stable-dreamfusion
|
219 |
+
- https://github.com/deep-floyd/IF
|
220 |
+
- https://github.com/bentoml/BentoML
|
221 |
+
- https://github.com/bmaltais/kohya_ss
|
222 |
+
- +8000 other amazing GitHub repositories 💪
|
223 |
+
|
224 |
+
Thank you for using us ❤️.
|
225 |
+
|
226 |
+
## Credits
|
227 |
+
|
228 |
+
This library concretizes previous work by many different authors and would not have been possible without their great research and implementations. We'd like to thank, in particular, the following implementations which have helped us in our development and without which the API could not have been as polished today:
|
229 |
+
|
230 |
+
- @CompVis' latent diffusion models library, available [here](https://github.com/CompVis/latent-diffusion)
|
231 |
+
- @hojonathanho original DDPM implementation, available [here](https://github.com/hojonathanho/diffusion) as well as the extremely useful translation into PyTorch by @pesser, available [here](https://github.com/pesser/pytorch_diffusion)
|
232 |
+
- @ermongroup's DDIM implementation, available [here](https://github.com/ermongroup/ddim)
|
233 |
+
- @yang-song's Score-VE and Score-VP implementations, available [here](https://github.com/yang-song/score_sde_pytorch)
|
234 |
+
|
235 |
+
We also want to thank @heejkoo for the very helpful overview of papers, code and resources on diffusion models, available [here](https://github.com/heejkoo/Awesome-Diffusion-Models) as well as @crowsonkb and @rromb for useful discussions and insights.
|
236 |
+
|
237 |
+
## Citation
|
238 |
+
|
239 |
+
```bibtex
|
240 |
+
@misc{von-platen-etal-2022-diffusers,
|
241 |
+
author = {Patrick von Platen and Suraj Patil and Anton Lozhkov and Pedro Cuenca and Nathan Lambert and Kashif Rasul and Mishig Davaadorj and Thomas Wolf},
|
242 |
+
title = {Diffusers: State-of-the-art diffusion models},
|
243 |
+
year = {2022},
|
244 |
+
publisher = {GitHub},
|
245 |
+
journal = {GitHub repository},
|
246 |
+
howpublished = {\url{https://github.com/huggingface/diffusers}}
|
247 |
+
}
|
248 |
+
```
|
BrushNet/_typos.toml
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Files for typos
|
2 |
+
# Instruction: https://github.com/marketplace/actions/typos-action#getting-started
|
3 |
+
|
4 |
+
[default.extend-identifiers]
|
5 |
+
|
6 |
+
[default.extend-words]
|
7 |
+
NIN="NIN" # NIN is used in scripts/convert_ncsnpp_original_checkpoint_to_diffusers.py
|
8 |
+
nd="np" # nd may be np (numpy)
|
9 |
+
parms="parms" # parms is used in scripts/convert_original_stable_diffusion_to_diffusers.py
|
10 |
+
|
11 |
+
|
12 |
+
[files]
|
13 |
+
extend-exclude = ["_typos.toml"]
|
BrushNet/benchmarks/base_classes.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from diffusers import (
|
7 |
+
AutoPipelineForImage2Image,
|
8 |
+
AutoPipelineForInpainting,
|
9 |
+
AutoPipelineForText2Image,
|
10 |
+
ControlNetModel,
|
11 |
+
LCMScheduler,
|
12 |
+
StableDiffusionAdapterPipeline,
|
13 |
+
StableDiffusionControlNetPipeline,
|
14 |
+
StableDiffusionXLAdapterPipeline,
|
15 |
+
StableDiffusionXLControlNetPipeline,
|
16 |
+
T2IAdapter,
|
17 |
+
WuerstchenCombinedPipeline,
|
18 |
+
)
|
19 |
+
from diffusers.utils import load_image
|
20 |
+
|
21 |
+
|
22 |
+
sys.path.append(".")
|
23 |
+
|
24 |
+
from utils import ( # noqa: E402
|
25 |
+
BASE_PATH,
|
26 |
+
PROMPT,
|
27 |
+
BenchmarkInfo,
|
28 |
+
benchmark_fn,
|
29 |
+
bytes_to_giga_bytes,
|
30 |
+
flush,
|
31 |
+
generate_csv_dict,
|
32 |
+
write_to_csv,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
RESOLUTION_MAPPING = {
|
37 |
+
"runwayml/stable-diffusion-v1-5": (512, 512),
|
38 |
+
"lllyasviel/sd-controlnet-canny": (512, 512),
|
39 |
+
"diffusers/controlnet-canny-sdxl-1.0": (1024, 1024),
|
40 |
+
"TencentARC/t2iadapter_canny_sd14v1": (512, 512),
|
41 |
+
"TencentARC/t2i-adapter-canny-sdxl-1.0": (1024, 1024),
|
42 |
+
"stabilityai/stable-diffusion-2-1": (768, 768),
|
43 |
+
"stabilityai/stable-diffusion-xl-base-1.0": (1024, 1024),
|
44 |
+
"stabilityai/stable-diffusion-xl-refiner-1.0": (1024, 1024),
|
45 |
+
"stabilityai/sdxl-turbo": (512, 512),
|
46 |
+
}
|
47 |
+
|
48 |
+
|
49 |
+
class BaseBenchmak:
|
50 |
+
pipeline_class = None
|
51 |
+
|
52 |
+
def __init__(self, args):
|
53 |
+
super().__init__()
|
54 |
+
|
55 |
+
def run_inference(self, args):
|
56 |
+
raise NotImplementedError
|
57 |
+
|
58 |
+
def benchmark(self, args):
|
59 |
+
raise NotImplementedError
|
60 |
+
|
61 |
+
def get_result_filepath(self, args):
|
62 |
+
pipeline_class_name = str(self.pipe.__class__.__name__)
|
63 |
+
name = (
|
64 |
+
args.ckpt.replace("/", "_")
|
65 |
+
+ "_"
|
66 |
+
+ pipeline_class_name
|
67 |
+
+ f"-bs@{args.batch_size}-steps@{args.num_inference_steps}-mco@{args.model_cpu_offload}-compile@{args.run_compile}.csv"
|
68 |
+
)
|
69 |
+
filepath = os.path.join(BASE_PATH, name)
|
70 |
+
return filepath
|
71 |
+
|
72 |
+
|
73 |
+
class TextToImageBenchmark(BaseBenchmak):
|
74 |
+
pipeline_class = AutoPipelineForText2Image
|
75 |
+
|
76 |
+
def __init__(self, args):
|
77 |
+
pipe = self.pipeline_class.from_pretrained(args.ckpt, torch_dtype=torch.float16)
|
78 |
+
pipe = pipe.to("cuda")
|
79 |
+
|
80 |
+
if args.run_compile:
|
81 |
+
if not isinstance(pipe, WuerstchenCombinedPipeline):
|
82 |
+
pipe.unet.to(memory_format=torch.channels_last)
|
83 |
+
print("Run torch compile")
|
84 |
+
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
|
85 |
+
|
86 |
+
if hasattr(pipe, "movq") and getattr(pipe, "movq", None) is not None:
|
87 |
+
pipe.movq.to(memory_format=torch.channels_last)
|
88 |
+
pipe.movq = torch.compile(pipe.movq, mode="reduce-overhead", fullgraph=True)
|
89 |
+
else:
|
90 |
+
print("Run torch compile")
|
91 |
+
pipe.decoder = torch.compile(pipe.decoder, mode="reduce-overhead", fullgraph=True)
|
92 |
+
pipe.vqgan = torch.compile(pipe.vqgan, mode="reduce-overhead", fullgraph=True)
|
93 |
+
|
94 |
+
pipe.set_progress_bar_config(disable=True)
|
95 |
+
self.pipe = pipe
|
96 |
+
|
97 |
+
def run_inference(self, pipe, args):
|
98 |
+
_ = pipe(
|
99 |
+
prompt=PROMPT,
|
100 |
+
num_inference_steps=args.num_inference_steps,
|
101 |
+
num_images_per_prompt=args.batch_size,
|
102 |
+
)
|
103 |
+
|
104 |
+
def benchmark(self, args):
|
105 |
+
flush()
|
106 |
+
|
107 |
+
print(f"[INFO] {self.pipe.__class__.__name__}: Running benchmark with: {vars(args)}\n")
|
108 |
+
|
109 |
+
time = benchmark_fn(self.run_inference, self.pipe, args) # in seconds.
|
110 |
+
memory = bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) # in GBs.
|
111 |
+
benchmark_info = BenchmarkInfo(time=time, memory=memory)
|
112 |
+
|
113 |
+
pipeline_class_name = str(self.pipe.__class__.__name__)
|
114 |
+
flush()
|
115 |
+
csv_dict = generate_csv_dict(
|
116 |
+
pipeline_cls=pipeline_class_name, ckpt=args.ckpt, args=args, benchmark_info=benchmark_info
|
117 |
+
)
|
118 |
+
filepath = self.get_result_filepath(args)
|
119 |
+
write_to_csv(filepath, csv_dict)
|
120 |
+
print(f"Logs written to: {filepath}")
|
121 |
+
flush()
|
122 |
+
|
123 |
+
|
124 |
+
class TurboTextToImageBenchmark(TextToImageBenchmark):
|
125 |
+
def __init__(self, args):
|
126 |
+
super().__init__(args)
|
127 |
+
|
128 |
+
def run_inference(self, pipe, args):
|
129 |
+
_ = pipe(
|
130 |
+
prompt=PROMPT,
|
131 |
+
num_inference_steps=args.num_inference_steps,
|
132 |
+
num_images_per_prompt=args.batch_size,
|
133 |
+
guidance_scale=0.0,
|
134 |
+
)
|
135 |
+
|
136 |
+
|
137 |
+
class LCMLoRATextToImageBenchmark(TextToImageBenchmark):
|
138 |
+
lora_id = "latent-consistency/lcm-lora-sdxl"
|
139 |
+
|
140 |
+
def __init__(self, args):
|
141 |
+
super().__init__(args)
|
142 |
+
self.pipe.load_lora_weights(self.lora_id)
|
143 |
+
self.pipe.fuse_lora()
|
144 |
+
self.pipe.unload_lora_weights()
|
145 |
+
self.pipe.scheduler = LCMScheduler.from_config(self.pipe.scheduler.config)
|
146 |
+
|
147 |
+
def get_result_filepath(self, args):
|
148 |
+
pipeline_class_name = str(self.pipe.__class__.__name__)
|
149 |
+
name = (
|
150 |
+
self.lora_id.replace("/", "_")
|
151 |
+
+ "_"
|
152 |
+
+ pipeline_class_name
|
153 |
+
+ f"-bs@{args.batch_size}-steps@{args.num_inference_steps}-mco@{args.model_cpu_offload}-compile@{args.run_compile}.csv"
|
154 |
+
)
|
155 |
+
filepath = os.path.join(BASE_PATH, name)
|
156 |
+
return filepath
|
157 |
+
|
158 |
+
def run_inference(self, pipe, args):
|
159 |
+
_ = pipe(
|
160 |
+
prompt=PROMPT,
|
161 |
+
num_inference_steps=args.num_inference_steps,
|
162 |
+
num_images_per_prompt=args.batch_size,
|
163 |
+
guidance_scale=1.0,
|
164 |
+
)
|
165 |
+
|
166 |
+
def benchmark(self, args):
|
167 |
+
flush()
|
168 |
+
|
169 |
+
print(f"[INFO] {self.pipe.__class__.__name__}: Running benchmark with: {vars(args)}\n")
|
170 |
+
|
171 |
+
time = benchmark_fn(self.run_inference, self.pipe, args) # in seconds.
|
172 |
+
memory = bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) # in GBs.
|
173 |
+
benchmark_info = BenchmarkInfo(time=time, memory=memory)
|
174 |
+
|
175 |
+
pipeline_class_name = str(self.pipe.__class__.__name__)
|
176 |
+
flush()
|
177 |
+
csv_dict = generate_csv_dict(
|
178 |
+
pipeline_cls=pipeline_class_name, ckpt=self.lora_id, args=args, benchmark_info=benchmark_info
|
179 |
+
)
|
180 |
+
filepath = self.get_result_filepath(args)
|
181 |
+
write_to_csv(filepath, csv_dict)
|
182 |
+
print(f"Logs written to: {filepath}")
|
183 |
+
flush()
|
184 |
+
|
185 |
+
|
186 |
+
class ImageToImageBenchmark(TextToImageBenchmark):
|
187 |
+
pipeline_class = AutoPipelineForImage2Image
|
188 |
+
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/benchmarking/1665_Girl_with_a_Pearl_Earring.jpg"
|
189 |
+
image = load_image(url).convert("RGB")
|
190 |
+
|
191 |
+
def __init__(self, args):
|
192 |
+
super().__init__(args)
|
193 |
+
self.image = self.image.resize(RESOLUTION_MAPPING[args.ckpt])
|
194 |
+
|
195 |
+
def run_inference(self, pipe, args):
|
196 |
+
_ = pipe(
|
197 |
+
prompt=PROMPT,
|
198 |
+
image=self.image,
|
199 |
+
num_inference_steps=args.num_inference_steps,
|
200 |
+
num_images_per_prompt=args.batch_size,
|
201 |
+
)
|
202 |
+
|
203 |
+
|
204 |
+
class TurboImageToImageBenchmark(ImageToImageBenchmark):
|
205 |
+
def __init__(self, args):
|
206 |
+
super().__init__(args)
|
207 |
+
|
208 |
+
def run_inference(self, pipe, args):
|
209 |
+
_ = pipe(
|
210 |
+
prompt=PROMPT,
|
211 |
+
image=self.image,
|
212 |
+
num_inference_steps=args.num_inference_steps,
|
213 |
+
num_images_per_prompt=args.batch_size,
|
214 |
+
guidance_scale=0.0,
|
215 |
+
strength=0.5,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
class InpaintingBenchmark(ImageToImageBenchmark):
|
220 |
+
pipeline_class = AutoPipelineForInpainting
|
221 |
+
mask_url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/benchmarking/overture-creations-5sI6fQgYIuo_mask.png"
|
222 |
+
mask = load_image(mask_url).convert("RGB")
|
223 |
+
|
224 |
+
def __init__(self, args):
|
225 |
+
super().__init__(args)
|
226 |
+
self.image = self.image.resize(RESOLUTION_MAPPING[args.ckpt])
|
227 |
+
self.mask = self.mask.resize(RESOLUTION_MAPPING[args.ckpt])
|
228 |
+
|
229 |
+
def run_inference(self, pipe, args):
|
230 |
+
_ = pipe(
|
231 |
+
prompt=PROMPT,
|
232 |
+
image=self.image,
|
233 |
+
mask_image=self.mask,
|
234 |
+
num_inference_steps=args.num_inference_steps,
|
235 |
+
num_images_per_prompt=args.batch_size,
|
236 |
+
)
|
237 |
+
|
238 |
+
|
239 |
+
class IPAdapterTextToImageBenchmark(TextToImageBenchmark):
|
240 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_neg_embed.png"
|
241 |
+
image = load_image(url)
|
242 |
+
|
243 |
+
def __init__(self, args):
|
244 |
+
pipe = self.pipeline_class.from_pretrained(args.ckpt, torch_dtype=torch.float16).to("cuda")
|
245 |
+
pipe.load_ip_adapter(
|
246 |
+
args.ip_adapter_id[0],
|
247 |
+
subfolder="models" if "sdxl" not in args.ip_adapter_id[1] else "sdxl_models",
|
248 |
+
weight_name=args.ip_adapter_id[1],
|
249 |
+
)
|
250 |
+
|
251 |
+
if args.run_compile:
|
252 |
+
pipe.unet.to(memory_format=torch.channels_last)
|
253 |
+
print("Run torch compile")
|
254 |
+
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
|
255 |
+
|
256 |
+
pipe.set_progress_bar_config(disable=True)
|
257 |
+
self.pipe = pipe
|
258 |
+
|
259 |
+
def run_inference(self, pipe, args):
|
260 |
+
_ = pipe(
|
261 |
+
prompt=PROMPT,
|
262 |
+
ip_adapter_image=self.image,
|
263 |
+
num_inference_steps=args.num_inference_steps,
|
264 |
+
num_images_per_prompt=args.batch_size,
|
265 |
+
)
|
266 |
+
|
267 |
+
|
268 |
+
class ControlNetBenchmark(TextToImageBenchmark):
|
269 |
+
pipeline_class = StableDiffusionControlNetPipeline
|
270 |
+
aux_network_class = ControlNetModel
|
271 |
+
root_ckpt = "runwayml/stable-diffusion-v1-5"
|
272 |
+
|
273 |
+
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/benchmarking/canny_image_condition.png"
|
274 |
+
image = load_image(url).convert("RGB")
|
275 |
+
|
276 |
+
def __init__(self, args):
|
277 |
+
aux_network = self.aux_network_class.from_pretrained(args.ckpt, torch_dtype=torch.float16)
|
278 |
+
pipe = self.pipeline_class.from_pretrained(self.root_ckpt, controlnet=aux_network, torch_dtype=torch.float16)
|
279 |
+
pipe = pipe.to("cuda")
|
280 |
+
|
281 |
+
pipe.set_progress_bar_config(disable=True)
|
282 |
+
self.pipe = pipe
|
283 |
+
|
284 |
+
if args.run_compile:
|
285 |
+
pipe.unet.to(memory_format=torch.channels_last)
|
286 |
+
pipe.controlnet.to(memory_format=torch.channels_last)
|
287 |
+
|
288 |
+
print("Run torch compile")
|
289 |
+
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
|
290 |
+
pipe.controlnet = torch.compile(pipe.controlnet, mode="reduce-overhead", fullgraph=True)
|
291 |
+
|
292 |
+
self.image = self.image.resize(RESOLUTION_MAPPING[args.ckpt])
|
293 |
+
|
294 |
+
def run_inference(self, pipe, args):
|
295 |
+
_ = pipe(
|
296 |
+
prompt=PROMPT,
|
297 |
+
image=self.image,
|
298 |
+
num_inference_steps=args.num_inference_steps,
|
299 |
+
num_images_per_prompt=args.batch_size,
|
300 |
+
)
|
301 |
+
|
302 |
+
|
303 |
+
class ControlNetSDXLBenchmark(ControlNetBenchmark):
|
304 |
+
pipeline_class = StableDiffusionXLControlNetPipeline
|
305 |
+
root_ckpt = "stabilityai/stable-diffusion-xl-base-1.0"
|
306 |
+
|
307 |
+
def __init__(self, args):
|
308 |
+
super().__init__(args)
|
309 |
+
|
310 |
+
|
311 |
+
class T2IAdapterBenchmark(ControlNetBenchmark):
|
312 |
+
pipeline_class = StableDiffusionAdapterPipeline
|
313 |
+
aux_network_class = T2IAdapter
|
314 |
+
root_ckpt = "CompVis/stable-diffusion-v1-4"
|
315 |
+
|
316 |
+
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/benchmarking/canny_for_adapter.png"
|
317 |
+
image = load_image(url).convert("L")
|
318 |
+
|
319 |
+
def __init__(self, args):
|
320 |
+
aux_network = self.aux_network_class.from_pretrained(args.ckpt, torch_dtype=torch.float16)
|
321 |
+
pipe = self.pipeline_class.from_pretrained(self.root_ckpt, adapter=aux_network, torch_dtype=torch.float16)
|
322 |
+
pipe = pipe.to("cuda")
|
323 |
+
|
324 |
+
pipe.set_progress_bar_config(disable=True)
|
325 |
+
self.pipe = pipe
|
326 |
+
|
327 |
+
if args.run_compile:
|
328 |
+
pipe.unet.to(memory_format=torch.channels_last)
|
329 |
+
pipe.adapter.to(memory_format=torch.channels_last)
|
330 |
+
|
331 |
+
print("Run torch compile")
|
332 |
+
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
|
333 |
+
pipe.adapter = torch.compile(pipe.adapter, mode="reduce-overhead", fullgraph=True)
|
334 |
+
|
335 |
+
self.image = self.image.resize(RESOLUTION_MAPPING[args.ckpt])
|
336 |
+
|
337 |
+
|
338 |
+
class T2IAdapterSDXLBenchmark(T2IAdapterBenchmark):
|
339 |
+
pipeline_class = StableDiffusionXLAdapterPipeline
|
340 |
+
root_ckpt = "stabilityai/stable-diffusion-xl-base-1.0"
|
341 |
+
|
342 |
+
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/benchmarking/canny_for_adapter_sdxl.png"
|
343 |
+
image = load_image(url)
|
344 |
+
|
345 |
+
def __init__(self, args):
|
346 |
+
super().__init__(args)
|
BrushNet/benchmarks/benchmark_controlnet.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import ControlNetBenchmark, ControlNetSDXLBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument(
|
12 |
+
"--ckpt",
|
13 |
+
type=str,
|
14 |
+
default="lllyasviel/sd-controlnet-canny",
|
15 |
+
choices=["lllyasviel/sd-controlnet-canny", "diffusers/controlnet-canny-sdxl-1.0"],
|
16 |
+
)
|
17 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
18 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
19 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
20 |
+
parser.add_argument("--run_compile", action="store_true")
|
21 |
+
args = parser.parse_args()
|
22 |
+
|
23 |
+
benchmark_pipe = (
|
24 |
+
ControlNetBenchmark(args) if args.ckpt == "lllyasviel/sd-controlnet-canny" else ControlNetSDXLBenchmark(args)
|
25 |
+
)
|
26 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_ip_adapters.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import IPAdapterTextToImageBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
IP_ADAPTER_CKPTS = {
|
10 |
+
"runwayml/stable-diffusion-v1-5": ("h94/IP-Adapter", "ip-adapter_sd15.bin"),
|
11 |
+
"stabilityai/stable-diffusion-xl-base-1.0": ("h94/IP-Adapter", "ip-adapter_sdxl.bin"),
|
12 |
+
}
|
13 |
+
|
14 |
+
|
15 |
+
if __name__ == "__main__":
|
16 |
+
parser = argparse.ArgumentParser()
|
17 |
+
parser.add_argument(
|
18 |
+
"--ckpt",
|
19 |
+
type=str,
|
20 |
+
default="runwayml/stable-diffusion-v1-5",
|
21 |
+
choices=list(IP_ADAPTER_CKPTS.keys()),
|
22 |
+
)
|
23 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
24 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
25 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
26 |
+
parser.add_argument("--run_compile", action="store_true")
|
27 |
+
args = parser.parse_args()
|
28 |
+
|
29 |
+
args.ip_adapter_id = IP_ADAPTER_CKPTS[args.ckpt]
|
30 |
+
benchmark_pipe = IPAdapterTextToImageBenchmark(args)
|
31 |
+
args.ckpt = f"{args.ckpt} (IP-Adapter)"
|
32 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_sd_img.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import ImageToImageBenchmark, TurboImageToImageBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument(
|
12 |
+
"--ckpt",
|
13 |
+
type=str,
|
14 |
+
default="runwayml/stable-diffusion-v1-5",
|
15 |
+
choices=[
|
16 |
+
"runwayml/stable-diffusion-v1-5",
|
17 |
+
"stabilityai/stable-diffusion-2-1",
|
18 |
+
"stabilityai/stable-diffusion-xl-refiner-1.0",
|
19 |
+
"stabilityai/sdxl-turbo",
|
20 |
+
],
|
21 |
+
)
|
22 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
23 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
24 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
25 |
+
parser.add_argument("--run_compile", action="store_true")
|
26 |
+
args = parser.parse_args()
|
27 |
+
|
28 |
+
benchmark_pipe = ImageToImageBenchmark(args) if "turbo" not in args.ckpt else TurboImageToImageBenchmark(args)
|
29 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_sd_inpainting.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import InpaintingBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument(
|
12 |
+
"--ckpt",
|
13 |
+
type=str,
|
14 |
+
default="runwayml/stable-diffusion-v1-5",
|
15 |
+
choices=[
|
16 |
+
"runwayml/stable-diffusion-v1-5",
|
17 |
+
"stabilityai/stable-diffusion-2-1",
|
18 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
19 |
+
],
|
20 |
+
)
|
21 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
22 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
23 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
24 |
+
parser.add_argument("--run_compile", action="store_true")
|
25 |
+
args = parser.parse_args()
|
26 |
+
|
27 |
+
benchmark_pipe = InpaintingBenchmark(args)
|
28 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_t2i_adapter.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import T2IAdapterBenchmark, T2IAdapterSDXLBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument(
|
12 |
+
"--ckpt",
|
13 |
+
type=str,
|
14 |
+
default="TencentARC/t2iadapter_canny_sd14v1",
|
15 |
+
choices=["TencentARC/t2iadapter_canny_sd14v1", "TencentARC/t2i-adapter-canny-sdxl-1.0"],
|
16 |
+
)
|
17 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
18 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
19 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
20 |
+
parser.add_argument("--run_compile", action="store_true")
|
21 |
+
args = parser.parse_args()
|
22 |
+
|
23 |
+
benchmark_pipe = (
|
24 |
+
T2IAdapterBenchmark(args)
|
25 |
+
if args.ckpt == "TencentARC/t2iadapter_canny_sd14v1"
|
26 |
+
else T2IAdapterSDXLBenchmark(args)
|
27 |
+
)
|
28 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_t2i_lcm_lora.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import LCMLoRATextToImageBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument(
|
12 |
+
"--ckpt",
|
13 |
+
type=str,
|
14 |
+
default="stabilityai/stable-diffusion-xl-base-1.0",
|
15 |
+
)
|
16 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
17 |
+
parser.add_argument("--num_inference_steps", type=int, default=4)
|
18 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
19 |
+
parser.add_argument("--run_compile", action="store_true")
|
20 |
+
args = parser.parse_args()
|
21 |
+
|
22 |
+
benchmark_pipe = LCMLoRATextToImageBenchmark(args)
|
23 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/benchmark_text_to_image.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
|
4 |
+
|
5 |
+
sys.path.append(".")
|
6 |
+
from base_classes import TextToImageBenchmark, TurboTextToImageBenchmark # noqa: E402
|
7 |
+
|
8 |
+
|
9 |
+
ALL_T2I_CKPTS = [
|
10 |
+
"runwayml/stable-diffusion-v1-5",
|
11 |
+
"segmind/SSD-1B",
|
12 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
13 |
+
"kandinsky-community/kandinsky-2-2-decoder",
|
14 |
+
"warp-ai/wuerstchen",
|
15 |
+
"stabilityai/sdxl-turbo",
|
16 |
+
]
|
17 |
+
|
18 |
+
|
19 |
+
if __name__ == "__main__":
|
20 |
+
parser = argparse.ArgumentParser()
|
21 |
+
parser.add_argument(
|
22 |
+
"--ckpt",
|
23 |
+
type=str,
|
24 |
+
default="runwayml/stable-diffusion-v1-5",
|
25 |
+
choices=ALL_T2I_CKPTS,
|
26 |
+
)
|
27 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
28 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
29 |
+
parser.add_argument("--model_cpu_offload", action="store_true")
|
30 |
+
parser.add_argument("--run_compile", action="store_true")
|
31 |
+
args = parser.parse_args()
|
32 |
+
|
33 |
+
benchmark_cls = None
|
34 |
+
if "turbo" in args.ckpt:
|
35 |
+
benchmark_cls = TurboTextToImageBenchmark
|
36 |
+
else:
|
37 |
+
benchmark_cls = TextToImageBenchmark
|
38 |
+
|
39 |
+
benchmark_pipe = benchmark_cls(args)
|
40 |
+
benchmark_pipe.benchmark(args)
|
BrushNet/benchmarks/push_results.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import sys
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from huggingface_hub import hf_hub_download, upload_file
|
6 |
+
from huggingface_hub.utils._errors import EntryNotFoundError
|
7 |
+
|
8 |
+
|
9 |
+
sys.path.append(".")
|
10 |
+
from utils import BASE_PATH, FINAL_CSV_FILE, GITHUB_SHA, REPO_ID, collate_csv # noqa: E402
|
11 |
+
|
12 |
+
|
13 |
+
def has_previous_benchmark() -> str:
|
14 |
+
csv_path = None
|
15 |
+
try:
|
16 |
+
csv_path = hf_hub_download(repo_id=REPO_ID, repo_type="dataset", filename=FINAL_CSV_FILE)
|
17 |
+
except EntryNotFoundError:
|
18 |
+
csv_path = None
|
19 |
+
return csv_path
|
20 |
+
|
21 |
+
|
22 |
+
def filter_float(value):
|
23 |
+
if isinstance(value, str):
|
24 |
+
return float(value.split()[0])
|
25 |
+
return value
|
26 |
+
|
27 |
+
|
28 |
+
def push_to_hf_dataset():
|
29 |
+
all_csvs = sorted(glob.glob(f"{BASE_PATH}/*.csv"))
|
30 |
+
collate_csv(all_csvs, FINAL_CSV_FILE)
|
31 |
+
|
32 |
+
# If there's an existing benchmark file, we should report the changes.
|
33 |
+
csv_path = has_previous_benchmark()
|
34 |
+
if csv_path is not None:
|
35 |
+
current_results = pd.read_csv(FINAL_CSV_FILE)
|
36 |
+
previous_results = pd.read_csv(csv_path)
|
37 |
+
|
38 |
+
numeric_columns = current_results.select_dtypes(include=["float64", "int64"]).columns
|
39 |
+
numeric_columns = [
|
40 |
+
c for c in numeric_columns if c not in ["batch_size", "num_inference_steps", "actual_gpu_memory (gbs)"]
|
41 |
+
]
|
42 |
+
|
43 |
+
for column in numeric_columns:
|
44 |
+
previous_results[column] = previous_results[column].map(lambda x: filter_float(x))
|
45 |
+
|
46 |
+
# Calculate the percentage change
|
47 |
+
current_results[column] = current_results[column].astype(float)
|
48 |
+
previous_results[column] = previous_results[column].astype(float)
|
49 |
+
percent_change = ((current_results[column] - previous_results[column]) / previous_results[column]) * 100
|
50 |
+
|
51 |
+
# Format the values with '+' or '-' sign and append to original values
|
52 |
+
current_results[column] = current_results[column].map(str) + percent_change.map(
|
53 |
+
lambda x: f" ({'+' if x > 0 else ''}{x:.2f}%)"
|
54 |
+
)
|
55 |
+
# There might be newly added rows. So, filter out the NaNs.
|
56 |
+
current_results[column] = current_results[column].map(lambda x: x.replace(" (nan%)", ""))
|
57 |
+
|
58 |
+
# Overwrite the current result file.
|
59 |
+
current_results.to_csv(FINAL_CSV_FILE, index=False)
|
60 |
+
|
61 |
+
commit_message = f"upload from sha: {GITHUB_SHA}" if GITHUB_SHA is not None else "upload benchmark results"
|
62 |
+
upload_file(
|
63 |
+
repo_id=REPO_ID,
|
64 |
+
path_in_repo=FINAL_CSV_FILE,
|
65 |
+
path_or_fileobj=FINAL_CSV_FILE,
|
66 |
+
repo_type="dataset",
|
67 |
+
commit_message=commit_message,
|
68 |
+
)
|
69 |
+
|
70 |
+
|
71 |
+
if __name__ == "__main__":
|
72 |
+
push_to_hf_dataset()
|
BrushNet/benchmarks/run_all.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import subprocess
|
3 |
+
import sys
|
4 |
+
from typing import List
|
5 |
+
|
6 |
+
|
7 |
+
sys.path.append(".")
|
8 |
+
from benchmark_text_to_image import ALL_T2I_CKPTS # noqa: E402
|
9 |
+
|
10 |
+
|
11 |
+
PATTERN = "benchmark_*.py"
|
12 |
+
|
13 |
+
|
14 |
+
class SubprocessCallException(Exception):
|
15 |
+
pass
|
16 |
+
|
17 |
+
|
18 |
+
# Taken from `test_examples_utils.py`
|
19 |
+
def run_command(command: List[str], return_stdout=False):
|
20 |
+
"""
|
21 |
+
Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
|
22 |
+
if an error occurred while running `command`
|
23 |
+
"""
|
24 |
+
try:
|
25 |
+
output = subprocess.check_output(command, stderr=subprocess.STDOUT)
|
26 |
+
if return_stdout:
|
27 |
+
if hasattr(output, "decode"):
|
28 |
+
output = output.decode("utf-8")
|
29 |
+
return output
|
30 |
+
except subprocess.CalledProcessError as e:
|
31 |
+
raise SubprocessCallException(
|
32 |
+
f"Command `{' '.join(command)}` failed with the following error:\n\n{e.output.decode()}"
|
33 |
+
) from e
|
34 |
+
|
35 |
+
|
36 |
+
def main():
|
37 |
+
python_files = glob.glob(PATTERN)
|
38 |
+
|
39 |
+
for file in python_files:
|
40 |
+
print(f"****** Running file: {file} ******")
|
41 |
+
|
42 |
+
# Run with canonical settings.
|
43 |
+
if file != "benchmark_text_to_image.py":
|
44 |
+
command = f"python {file}"
|
45 |
+
run_command(command.split())
|
46 |
+
|
47 |
+
command += " --run_compile"
|
48 |
+
run_command(command.split())
|
49 |
+
|
50 |
+
# Run variants.
|
51 |
+
for file in python_files:
|
52 |
+
if file == "benchmark_text_to_image.py":
|
53 |
+
for ckpt in ALL_T2I_CKPTS:
|
54 |
+
command = f"python {file} --ckpt {ckpt}"
|
55 |
+
|
56 |
+
if "turbo" in ckpt:
|
57 |
+
command += " --num_inference_steps 1"
|
58 |
+
|
59 |
+
run_command(command.split())
|
60 |
+
|
61 |
+
command += " --run_compile"
|
62 |
+
run_command(command.split())
|
63 |
+
|
64 |
+
elif file == "benchmark_sd_img.py":
|
65 |
+
for ckpt in ["stabilityai/stable-diffusion-xl-refiner-1.0", "stabilityai/sdxl-turbo"]:
|
66 |
+
command = f"python {file} --ckpt {ckpt}"
|
67 |
+
|
68 |
+
if ckpt == "stabilityai/sdxl-turbo":
|
69 |
+
command += " --num_inference_steps 2"
|
70 |
+
|
71 |
+
run_command(command.split())
|
72 |
+
command += " --run_compile"
|
73 |
+
run_command(command.split())
|
74 |
+
|
75 |
+
elif file in ["benchmark_sd_inpainting.py", "benchmark_ip_adapters.py"]:
|
76 |
+
sdxl_ckpt = "stabilityai/stable-diffusion-xl-base-1.0"
|
77 |
+
command = f"python {file} --ckpt {sdxl_ckpt}"
|
78 |
+
run_command(command.split())
|
79 |
+
|
80 |
+
command += " --run_compile"
|
81 |
+
run_command(command.split())
|
82 |
+
|
83 |
+
elif file in ["benchmark_controlnet.py", "benchmark_t2i_adapter.py"]:
|
84 |
+
sdxl_ckpt = (
|
85 |
+
"diffusers/controlnet-canny-sdxl-1.0"
|
86 |
+
if "controlnet" in file
|
87 |
+
else "TencentARC/t2i-adapter-canny-sdxl-1.0"
|
88 |
+
)
|
89 |
+
command = f"python {file} --ckpt {sdxl_ckpt}"
|
90 |
+
run_command(command.split())
|
91 |
+
|
92 |
+
command += " --run_compile"
|
93 |
+
run_command(command.split())
|
94 |
+
|
95 |
+
|
96 |
+
if __name__ == "__main__":
|
97 |
+
main()
|
BrushNet/benchmarks/utils.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import csv
|
3 |
+
import gc
|
4 |
+
import os
|
5 |
+
from dataclasses import dataclass
|
6 |
+
from typing import Dict, List, Union
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.utils.benchmark as benchmark
|
10 |
+
|
11 |
+
|
12 |
+
GITHUB_SHA = os.getenv("GITHUB_SHA", None)
|
13 |
+
BENCHMARK_FIELDS = [
|
14 |
+
"pipeline_cls",
|
15 |
+
"ckpt_id",
|
16 |
+
"batch_size",
|
17 |
+
"num_inference_steps",
|
18 |
+
"model_cpu_offload",
|
19 |
+
"run_compile",
|
20 |
+
"time (secs)",
|
21 |
+
"memory (gbs)",
|
22 |
+
"actual_gpu_memory (gbs)",
|
23 |
+
"github_sha",
|
24 |
+
]
|
25 |
+
|
26 |
+
PROMPT = "ghibli style, a fantasy landscape with castles"
|
27 |
+
BASE_PATH = os.getenv("BASE_PATH", ".")
|
28 |
+
TOTAL_GPU_MEMORY = float(os.getenv("TOTAL_GPU_MEMORY", torch.cuda.get_device_properties(0).total_memory / (1024**3)))
|
29 |
+
|
30 |
+
REPO_ID = "diffusers/benchmarks"
|
31 |
+
FINAL_CSV_FILE = "collated_results.csv"
|
32 |
+
|
33 |
+
|
34 |
+
@dataclass
|
35 |
+
class BenchmarkInfo:
|
36 |
+
time: float
|
37 |
+
memory: float
|
38 |
+
|
39 |
+
|
40 |
+
def flush():
|
41 |
+
"""Wipes off memory."""
|
42 |
+
gc.collect()
|
43 |
+
torch.cuda.empty_cache()
|
44 |
+
torch.cuda.reset_max_memory_allocated()
|
45 |
+
torch.cuda.reset_peak_memory_stats()
|
46 |
+
|
47 |
+
|
48 |
+
def bytes_to_giga_bytes(bytes):
|
49 |
+
return f"{(bytes / 1024 / 1024 / 1024):.3f}"
|
50 |
+
|
51 |
+
|
52 |
+
def benchmark_fn(f, *args, **kwargs):
|
53 |
+
t0 = benchmark.Timer(
|
54 |
+
stmt="f(*args, **kwargs)",
|
55 |
+
globals={"args": args, "kwargs": kwargs, "f": f},
|
56 |
+
num_threads=torch.get_num_threads(),
|
57 |
+
)
|
58 |
+
return f"{(t0.blocked_autorange().mean):.3f}"
|
59 |
+
|
60 |
+
|
61 |
+
def generate_csv_dict(
|
62 |
+
pipeline_cls: str, ckpt: str, args: argparse.Namespace, benchmark_info: BenchmarkInfo
|
63 |
+
) -> Dict[str, Union[str, bool, float]]:
|
64 |
+
"""Packs benchmarking data into a dictionary for latter serialization."""
|
65 |
+
data_dict = {
|
66 |
+
"pipeline_cls": pipeline_cls,
|
67 |
+
"ckpt_id": ckpt,
|
68 |
+
"batch_size": args.batch_size,
|
69 |
+
"num_inference_steps": args.num_inference_steps,
|
70 |
+
"model_cpu_offload": args.model_cpu_offload,
|
71 |
+
"run_compile": args.run_compile,
|
72 |
+
"time (secs)": benchmark_info.time,
|
73 |
+
"memory (gbs)": benchmark_info.memory,
|
74 |
+
"actual_gpu_memory (gbs)": f"{(TOTAL_GPU_MEMORY):.3f}",
|
75 |
+
"github_sha": GITHUB_SHA,
|
76 |
+
}
|
77 |
+
return data_dict
|
78 |
+
|
79 |
+
|
80 |
+
def write_to_csv(file_name: str, data_dict: Dict[str, Union[str, bool, float]]):
|
81 |
+
"""Serializes a dictionary into a CSV file."""
|
82 |
+
with open(file_name, mode="w", newline="") as csvfile:
|
83 |
+
writer = csv.DictWriter(csvfile, fieldnames=BENCHMARK_FIELDS)
|
84 |
+
writer.writeheader()
|
85 |
+
writer.writerow(data_dict)
|
86 |
+
|
87 |
+
|
88 |
+
def collate_csv(input_files: List[str], output_file: str):
|
89 |
+
"""Collates multiple identically structured CSVs into a single CSV file."""
|
90 |
+
with open(output_file, mode="w", newline="") as outfile:
|
91 |
+
writer = csv.DictWriter(outfile, fieldnames=BENCHMARK_FIELDS)
|
92 |
+
writer.writeheader()
|
93 |
+
|
94 |
+
for file in input_files:
|
95 |
+
with open(file, mode="r") as infile:
|
96 |
+
reader = csv.DictReader(infile)
|
97 |
+
for row in reader:
|
98 |
+
writer.writerow(row)
|
BrushNet/build/lib/diffusers/__init__.py
ADDED
@@ -0,0 +1,789 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__version__ = "0.27.0.dev0"
|
2 |
+
|
3 |
+
from typing import TYPE_CHECKING
|
4 |
+
|
5 |
+
from .utils import (
|
6 |
+
DIFFUSERS_SLOW_IMPORT,
|
7 |
+
OptionalDependencyNotAvailable,
|
8 |
+
_LazyModule,
|
9 |
+
is_flax_available,
|
10 |
+
is_k_diffusion_available,
|
11 |
+
is_librosa_available,
|
12 |
+
is_note_seq_available,
|
13 |
+
is_onnx_available,
|
14 |
+
is_scipy_available,
|
15 |
+
is_torch_available,
|
16 |
+
is_torchsde_available,
|
17 |
+
is_transformers_available,
|
18 |
+
)
|
19 |
+
|
20 |
+
|
21 |
+
# Lazy Import based on
|
22 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/__init__.py
|
23 |
+
|
24 |
+
# When adding a new object to this init, please add it to `_import_structure`. The `_import_structure` is a dictionary submodule to list of object names,
|
25 |
+
# and is used to defer the actual importing for when the objects are requested.
|
26 |
+
# This way `import diffusers` provides the names in the namespace without actually importing anything (and especially none of the backends).
|
27 |
+
|
28 |
+
_import_structure = {
|
29 |
+
"configuration_utils": ["ConfigMixin"],
|
30 |
+
"models": [],
|
31 |
+
"pipelines": [],
|
32 |
+
"schedulers": [],
|
33 |
+
"utils": [
|
34 |
+
"OptionalDependencyNotAvailable",
|
35 |
+
"is_flax_available",
|
36 |
+
"is_inflect_available",
|
37 |
+
"is_invisible_watermark_available",
|
38 |
+
"is_k_diffusion_available",
|
39 |
+
"is_k_diffusion_version",
|
40 |
+
"is_librosa_available",
|
41 |
+
"is_note_seq_available",
|
42 |
+
"is_onnx_available",
|
43 |
+
"is_scipy_available",
|
44 |
+
"is_torch_available",
|
45 |
+
"is_torchsde_available",
|
46 |
+
"is_transformers_available",
|
47 |
+
"is_transformers_version",
|
48 |
+
"is_unidecode_available",
|
49 |
+
"logging",
|
50 |
+
],
|
51 |
+
}
|
52 |
+
|
53 |
+
try:
|
54 |
+
if not is_onnx_available():
|
55 |
+
raise OptionalDependencyNotAvailable()
|
56 |
+
except OptionalDependencyNotAvailable:
|
57 |
+
from .utils import dummy_onnx_objects # noqa F403
|
58 |
+
|
59 |
+
_import_structure["utils.dummy_onnx_objects"] = [
|
60 |
+
name for name in dir(dummy_onnx_objects) if not name.startswith("_")
|
61 |
+
]
|
62 |
+
|
63 |
+
else:
|
64 |
+
_import_structure["pipelines"].extend(["OnnxRuntimeModel"])
|
65 |
+
|
66 |
+
try:
|
67 |
+
if not is_torch_available():
|
68 |
+
raise OptionalDependencyNotAvailable()
|
69 |
+
except OptionalDependencyNotAvailable:
|
70 |
+
from .utils import dummy_pt_objects # noqa F403
|
71 |
+
|
72 |
+
_import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
|
73 |
+
|
74 |
+
else:
|
75 |
+
_import_structure["models"].extend(
|
76 |
+
[
|
77 |
+
"AsymmetricAutoencoderKL",
|
78 |
+
"AutoencoderKL",
|
79 |
+
"AutoencoderKLTemporalDecoder",
|
80 |
+
"AutoencoderTiny",
|
81 |
+
"ConsistencyDecoderVAE",
|
82 |
+
"BrushNetModel",
|
83 |
+
"ControlNetModel",
|
84 |
+
"I2VGenXLUNet",
|
85 |
+
"Kandinsky3UNet",
|
86 |
+
"ModelMixin",
|
87 |
+
"MotionAdapter",
|
88 |
+
"MultiAdapter",
|
89 |
+
"PriorTransformer",
|
90 |
+
"StableCascadeUNet",
|
91 |
+
"T2IAdapter",
|
92 |
+
"T5FilmDecoder",
|
93 |
+
"Transformer2DModel",
|
94 |
+
"UNet1DModel",
|
95 |
+
"UNet2DConditionModel",
|
96 |
+
"UNet2DModel",
|
97 |
+
"UNet3DConditionModel",
|
98 |
+
"UNetMotionModel",
|
99 |
+
"UNetSpatioTemporalConditionModel",
|
100 |
+
"UVit2DModel",
|
101 |
+
"VQModel",
|
102 |
+
]
|
103 |
+
)
|
104 |
+
|
105 |
+
_import_structure["optimization"] = [
|
106 |
+
"get_constant_schedule",
|
107 |
+
"get_constant_schedule_with_warmup",
|
108 |
+
"get_cosine_schedule_with_warmup",
|
109 |
+
"get_cosine_with_hard_restarts_schedule_with_warmup",
|
110 |
+
"get_linear_schedule_with_warmup",
|
111 |
+
"get_polynomial_decay_schedule_with_warmup",
|
112 |
+
"get_scheduler",
|
113 |
+
]
|
114 |
+
_import_structure["pipelines"].extend(
|
115 |
+
[
|
116 |
+
"AudioPipelineOutput",
|
117 |
+
"AutoPipelineForImage2Image",
|
118 |
+
"AutoPipelineForInpainting",
|
119 |
+
"AutoPipelineForText2Image",
|
120 |
+
"ConsistencyModelPipeline",
|
121 |
+
"DanceDiffusionPipeline",
|
122 |
+
"DDIMPipeline",
|
123 |
+
"DDPMPipeline",
|
124 |
+
"DiffusionPipeline",
|
125 |
+
"DiTPipeline",
|
126 |
+
"ImagePipelineOutput",
|
127 |
+
"KarrasVePipeline",
|
128 |
+
"LDMPipeline",
|
129 |
+
"LDMSuperResolutionPipeline",
|
130 |
+
"PNDMPipeline",
|
131 |
+
"RePaintPipeline",
|
132 |
+
"ScoreSdeVePipeline",
|
133 |
+
"StableDiffusionMixin",
|
134 |
+
]
|
135 |
+
)
|
136 |
+
_import_structure["schedulers"].extend(
|
137 |
+
[
|
138 |
+
"AmusedScheduler",
|
139 |
+
"CMStochasticIterativeScheduler",
|
140 |
+
"DDIMInverseScheduler",
|
141 |
+
"DDIMParallelScheduler",
|
142 |
+
"DDIMScheduler",
|
143 |
+
"DDPMParallelScheduler",
|
144 |
+
"DDPMScheduler",
|
145 |
+
"DDPMWuerstchenScheduler",
|
146 |
+
"DEISMultistepScheduler",
|
147 |
+
"DPMSolverMultistepInverseScheduler",
|
148 |
+
"DPMSolverMultistepScheduler",
|
149 |
+
"DPMSolverSinglestepScheduler",
|
150 |
+
"EDMDPMSolverMultistepScheduler",
|
151 |
+
"EDMEulerScheduler",
|
152 |
+
"EulerAncestralDiscreteScheduler",
|
153 |
+
"EulerDiscreteScheduler",
|
154 |
+
"HeunDiscreteScheduler",
|
155 |
+
"IPNDMScheduler",
|
156 |
+
"KarrasVeScheduler",
|
157 |
+
"KDPM2AncestralDiscreteScheduler",
|
158 |
+
"KDPM2DiscreteScheduler",
|
159 |
+
"LCMScheduler",
|
160 |
+
"PNDMScheduler",
|
161 |
+
"RePaintScheduler",
|
162 |
+
"SASolverScheduler",
|
163 |
+
"SchedulerMixin",
|
164 |
+
"ScoreSdeVeScheduler",
|
165 |
+
"TCDScheduler",
|
166 |
+
"UnCLIPScheduler",
|
167 |
+
"UniPCMultistepScheduler",
|
168 |
+
"VQDiffusionScheduler",
|
169 |
+
]
|
170 |
+
)
|
171 |
+
_import_structure["training_utils"] = ["EMAModel"]
|
172 |
+
|
173 |
+
try:
|
174 |
+
if not (is_torch_available() and is_scipy_available()):
|
175 |
+
raise OptionalDependencyNotAvailable()
|
176 |
+
except OptionalDependencyNotAvailable:
|
177 |
+
from .utils import dummy_torch_and_scipy_objects # noqa F403
|
178 |
+
|
179 |
+
_import_structure["utils.dummy_torch_and_scipy_objects"] = [
|
180 |
+
name for name in dir(dummy_torch_and_scipy_objects) if not name.startswith("_")
|
181 |
+
]
|
182 |
+
|
183 |
+
else:
|
184 |
+
_import_structure["schedulers"].extend(["LMSDiscreteScheduler"])
|
185 |
+
|
186 |
+
try:
|
187 |
+
if not (is_torch_available() and is_torchsde_available()):
|
188 |
+
raise OptionalDependencyNotAvailable()
|
189 |
+
except OptionalDependencyNotAvailable:
|
190 |
+
from .utils import dummy_torch_and_torchsde_objects # noqa F403
|
191 |
+
|
192 |
+
_import_structure["utils.dummy_torch_and_torchsde_objects"] = [
|
193 |
+
name for name in dir(dummy_torch_and_torchsde_objects) if not name.startswith("_")
|
194 |
+
]
|
195 |
+
|
196 |
+
else:
|
197 |
+
_import_structure["schedulers"].extend(["DPMSolverSDEScheduler"])
|
198 |
+
|
199 |
+
try:
|
200 |
+
if not (is_torch_available() and is_transformers_available()):
|
201 |
+
raise OptionalDependencyNotAvailable()
|
202 |
+
except OptionalDependencyNotAvailable:
|
203 |
+
from .utils import dummy_torch_and_transformers_objects # noqa F403
|
204 |
+
|
205 |
+
_import_structure["utils.dummy_torch_and_transformers_objects"] = [
|
206 |
+
name for name in dir(dummy_torch_and_transformers_objects) if not name.startswith("_")
|
207 |
+
]
|
208 |
+
|
209 |
+
else:
|
210 |
+
_import_structure["pipelines"].extend(
|
211 |
+
[
|
212 |
+
"AltDiffusionImg2ImgPipeline",
|
213 |
+
"AltDiffusionPipeline",
|
214 |
+
"AmusedImg2ImgPipeline",
|
215 |
+
"AmusedInpaintPipeline",
|
216 |
+
"AmusedPipeline",
|
217 |
+
"AnimateDiffPipeline",
|
218 |
+
"AnimateDiffVideoToVideoPipeline",
|
219 |
+
"AudioLDM2Pipeline",
|
220 |
+
"AudioLDM2ProjectionModel",
|
221 |
+
"AudioLDM2UNet2DConditionModel",
|
222 |
+
"AudioLDMPipeline",
|
223 |
+
"BlipDiffusionControlNetPipeline",
|
224 |
+
"BlipDiffusionPipeline",
|
225 |
+
"CLIPImageProjection",
|
226 |
+
"CycleDiffusionPipeline",
|
227 |
+
"I2VGenXLPipeline",
|
228 |
+
"IFImg2ImgPipeline",
|
229 |
+
"IFImg2ImgSuperResolutionPipeline",
|
230 |
+
"IFInpaintingPipeline",
|
231 |
+
"IFInpaintingSuperResolutionPipeline",
|
232 |
+
"IFPipeline",
|
233 |
+
"IFSuperResolutionPipeline",
|
234 |
+
"ImageTextPipelineOutput",
|
235 |
+
"Kandinsky3Img2ImgPipeline",
|
236 |
+
"Kandinsky3Pipeline",
|
237 |
+
"KandinskyCombinedPipeline",
|
238 |
+
"KandinskyImg2ImgCombinedPipeline",
|
239 |
+
"KandinskyImg2ImgPipeline",
|
240 |
+
"KandinskyInpaintCombinedPipeline",
|
241 |
+
"KandinskyInpaintPipeline",
|
242 |
+
"KandinskyPipeline",
|
243 |
+
"KandinskyPriorPipeline",
|
244 |
+
"KandinskyV22CombinedPipeline",
|
245 |
+
"KandinskyV22ControlnetImg2ImgPipeline",
|
246 |
+
"KandinskyV22ControlnetPipeline",
|
247 |
+
"KandinskyV22Img2ImgCombinedPipeline",
|
248 |
+
"KandinskyV22Img2ImgPipeline",
|
249 |
+
"KandinskyV22InpaintCombinedPipeline",
|
250 |
+
"KandinskyV22InpaintPipeline",
|
251 |
+
"KandinskyV22Pipeline",
|
252 |
+
"KandinskyV22PriorEmb2EmbPipeline",
|
253 |
+
"KandinskyV22PriorPipeline",
|
254 |
+
"LatentConsistencyModelImg2ImgPipeline",
|
255 |
+
"LatentConsistencyModelPipeline",
|
256 |
+
"LDMTextToImagePipeline",
|
257 |
+
"MusicLDMPipeline",
|
258 |
+
"PaintByExamplePipeline",
|
259 |
+
"PIAPipeline",
|
260 |
+
"PixArtAlphaPipeline",
|
261 |
+
"SemanticStableDiffusionPipeline",
|
262 |
+
"ShapEImg2ImgPipeline",
|
263 |
+
"ShapEPipeline",
|
264 |
+
"StableCascadeCombinedPipeline",
|
265 |
+
"StableCascadeDecoderPipeline",
|
266 |
+
"StableCascadePriorPipeline",
|
267 |
+
"StableDiffusionAdapterPipeline",
|
268 |
+
"StableDiffusionAttendAndExcitePipeline",
|
269 |
+
"StableDiffusionBrushNetPipeline",
|
270 |
+
"StableDiffusionControlNetImg2ImgPipeline",
|
271 |
+
"StableDiffusionControlNetInpaintPipeline",
|
272 |
+
"StableDiffusionControlNetPipeline",
|
273 |
+
"StableDiffusionDepth2ImgPipeline",
|
274 |
+
"StableDiffusionDiffEditPipeline",
|
275 |
+
"StableDiffusionGLIGENPipeline",
|
276 |
+
"StableDiffusionGLIGENTextImagePipeline",
|
277 |
+
"StableDiffusionImageVariationPipeline",
|
278 |
+
"StableDiffusionImg2ImgPipeline",
|
279 |
+
"StableDiffusionInpaintPipeline",
|
280 |
+
"StableDiffusionInpaintPipelineLegacy",
|
281 |
+
"StableDiffusionInstructPix2PixPipeline",
|
282 |
+
"StableDiffusionLatentUpscalePipeline",
|
283 |
+
"StableDiffusionLDM3DPipeline",
|
284 |
+
"StableDiffusionModelEditingPipeline",
|
285 |
+
"StableDiffusionPanoramaPipeline",
|
286 |
+
"StableDiffusionParadigmsPipeline",
|
287 |
+
"StableDiffusionPipeline",
|
288 |
+
"StableDiffusionPipelineSafe",
|
289 |
+
"StableDiffusionPix2PixZeroPipeline",
|
290 |
+
"StableDiffusionSAGPipeline",
|
291 |
+
"StableDiffusionUpscalePipeline",
|
292 |
+
"StableDiffusionXLAdapterPipeline",
|
293 |
+
"StableDiffusionXLBrushNetPipeline",
|
294 |
+
"StableDiffusionXLControlNetImg2ImgPipeline",
|
295 |
+
"StableDiffusionXLControlNetInpaintPipeline",
|
296 |
+
"StableDiffusionXLControlNetPipeline",
|
297 |
+
"StableDiffusionXLImg2ImgPipeline",
|
298 |
+
"StableDiffusionXLInpaintPipeline",
|
299 |
+
"StableDiffusionXLInstructPix2PixPipeline",
|
300 |
+
"StableDiffusionXLPipeline",
|
301 |
+
"StableUnCLIPImg2ImgPipeline",
|
302 |
+
"StableUnCLIPPipeline",
|
303 |
+
"StableVideoDiffusionPipeline",
|
304 |
+
"TextToVideoSDPipeline",
|
305 |
+
"TextToVideoZeroPipeline",
|
306 |
+
"TextToVideoZeroSDXLPipeline",
|
307 |
+
"UnCLIPImageVariationPipeline",
|
308 |
+
"UnCLIPPipeline",
|
309 |
+
"UniDiffuserModel",
|
310 |
+
"UniDiffuserPipeline",
|
311 |
+
"UniDiffuserTextDecoder",
|
312 |
+
"VersatileDiffusionDualGuidedPipeline",
|
313 |
+
"VersatileDiffusionImageVariationPipeline",
|
314 |
+
"VersatileDiffusionPipeline",
|
315 |
+
"VersatileDiffusionTextToImagePipeline",
|
316 |
+
"VideoToVideoSDPipeline",
|
317 |
+
"VQDiffusionPipeline",
|
318 |
+
"WuerstchenCombinedPipeline",
|
319 |
+
"WuerstchenDecoderPipeline",
|
320 |
+
"WuerstchenPriorPipeline",
|
321 |
+
]
|
322 |
+
)
|
323 |
+
|
324 |
+
try:
|
325 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
326 |
+
raise OptionalDependencyNotAvailable()
|
327 |
+
except OptionalDependencyNotAvailable:
|
328 |
+
from .utils import dummy_torch_and_transformers_and_k_diffusion_objects # noqa F403
|
329 |
+
|
330 |
+
_import_structure["utils.dummy_torch_and_transformers_and_k_diffusion_objects"] = [
|
331 |
+
name for name in dir(dummy_torch_and_transformers_and_k_diffusion_objects) if not name.startswith("_")
|
332 |
+
]
|
333 |
+
|
334 |
+
else:
|
335 |
+
_import_structure["pipelines"].extend(["StableDiffusionKDiffusionPipeline", "StableDiffusionXLKDiffusionPipeline"])
|
336 |
+
|
337 |
+
try:
|
338 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
339 |
+
raise OptionalDependencyNotAvailable()
|
340 |
+
except OptionalDependencyNotAvailable:
|
341 |
+
from .utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
|
342 |
+
|
343 |
+
_import_structure["utils.dummy_torch_and_transformers_and_onnx_objects"] = [
|
344 |
+
name for name in dir(dummy_torch_and_transformers_and_onnx_objects) if not name.startswith("_")
|
345 |
+
]
|
346 |
+
|
347 |
+
else:
|
348 |
+
_import_structure["pipelines"].extend(
|
349 |
+
[
|
350 |
+
"OnnxStableDiffusionImg2ImgPipeline",
|
351 |
+
"OnnxStableDiffusionInpaintPipeline",
|
352 |
+
"OnnxStableDiffusionInpaintPipelineLegacy",
|
353 |
+
"OnnxStableDiffusionPipeline",
|
354 |
+
"OnnxStableDiffusionUpscalePipeline",
|
355 |
+
"StableDiffusionOnnxPipeline",
|
356 |
+
]
|
357 |
+
)
|
358 |
+
|
359 |
+
try:
|
360 |
+
if not (is_torch_available() and is_librosa_available()):
|
361 |
+
raise OptionalDependencyNotAvailable()
|
362 |
+
except OptionalDependencyNotAvailable:
|
363 |
+
from .utils import dummy_torch_and_librosa_objects # noqa F403
|
364 |
+
|
365 |
+
_import_structure["utils.dummy_torch_and_librosa_objects"] = [
|
366 |
+
name for name in dir(dummy_torch_and_librosa_objects) if not name.startswith("_")
|
367 |
+
]
|
368 |
+
|
369 |
+
else:
|
370 |
+
_import_structure["pipelines"].extend(["AudioDiffusionPipeline", "Mel"])
|
371 |
+
|
372 |
+
try:
|
373 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
374 |
+
raise OptionalDependencyNotAvailable()
|
375 |
+
except OptionalDependencyNotAvailable:
|
376 |
+
from .utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
|
377 |
+
|
378 |
+
_import_structure["utils.dummy_transformers_and_torch_and_note_seq_objects"] = [
|
379 |
+
name for name in dir(dummy_transformers_and_torch_and_note_seq_objects) if not name.startswith("_")
|
380 |
+
]
|
381 |
+
|
382 |
+
|
383 |
+
else:
|
384 |
+
_import_structure["pipelines"].extend(["SpectrogramDiffusionPipeline"])
|
385 |
+
|
386 |
+
try:
|
387 |
+
if not is_flax_available():
|
388 |
+
raise OptionalDependencyNotAvailable()
|
389 |
+
except OptionalDependencyNotAvailable:
|
390 |
+
from .utils import dummy_flax_objects # noqa F403
|
391 |
+
|
392 |
+
_import_structure["utils.dummy_flax_objects"] = [
|
393 |
+
name for name in dir(dummy_flax_objects) if not name.startswith("_")
|
394 |
+
]
|
395 |
+
|
396 |
+
|
397 |
+
else:
|
398 |
+
_import_structure["models.controlnet_flax"] = ["FlaxControlNetModel"]
|
399 |
+
_import_structure["models.modeling_flax_utils"] = ["FlaxModelMixin"]
|
400 |
+
_import_structure["models.unets.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
|
401 |
+
_import_structure["models.vae_flax"] = ["FlaxAutoencoderKL"]
|
402 |
+
_import_structure["pipelines"].extend(["FlaxDiffusionPipeline"])
|
403 |
+
_import_structure["schedulers"].extend(
|
404 |
+
[
|
405 |
+
"FlaxDDIMScheduler",
|
406 |
+
"FlaxDDPMScheduler",
|
407 |
+
"FlaxDPMSolverMultistepScheduler",
|
408 |
+
"FlaxEulerDiscreteScheduler",
|
409 |
+
"FlaxKarrasVeScheduler",
|
410 |
+
"FlaxLMSDiscreteScheduler",
|
411 |
+
"FlaxPNDMScheduler",
|
412 |
+
"FlaxSchedulerMixin",
|
413 |
+
"FlaxScoreSdeVeScheduler",
|
414 |
+
]
|
415 |
+
)
|
416 |
+
|
417 |
+
|
418 |
+
try:
|
419 |
+
if not (is_flax_available() and is_transformers_available()):
|
420 |
+
raise OptionalDependencyNotAvailable()
|
421 |
+
except OptionalDependencyNotAvailable:
|
422 |
+
from .utils import dummy_flax_and_transformers_objects # noqa F403
|
423 |
+
|
424 |
+
_import_structure["utils.dummy_flax_and_transformers_objects"] = [
|
425 |
+
name for name in dir(dummy_flax_and_transformers_objects) if not name.startswith("_")
|
426 |
+
]
|
427 |
+
|
428 |
+
|
429 |
+
else:
|
430 |
+
_import_structure["pipelines"].extend(
|
431 |
+
[
|
432 |
+
"FlaxStableDiffusionControlNetPipeline",
|
433 |
+
"FlaxStableDiffusionImg2ImgPipeline",
|
434 |
+
"FlaxStableDiffusionInpaintPipeline",
|
435 |
+
"FlaxStableDiffusionPipeline",
|
436 |
+
"FlaxStableDiffusionXLPipeline",
|
437 |
+
]
|
438 |
+
)
|
439 |
+
|
440 |
+
try:
|
441 |
+
if not (is_note_seq_available()):
|
442 |
+
raise OptionalDependencyNotAvailable()
|
443 |
+
except OptionalDependencyNotAvailable:
|
444 |
+
from .utils import dummy_note_seq_objects # noqa F403
|
445 |
+
|
446 |
+
_import_structure["utils.dummy_note_seq_objects"] = [
|
447 |
+
name for name in dir(dummy_note_seq_objects) if not name.startswith("_")
|
448 |
+
]
|
449 |
+
|
450 |
+
|
451 |
+
else:
|
452 |
+
_import_structure["pipelines"].extend(["MidiProcessor"])
|
453 |
+
|
454 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
455 |
+
from .configuration_utils import ConfigMixin
|
456 |
+
|
457 |
+
try:
|
458 |
+
if not is_onnx_available():
|
459 |
+
raise OptionalDependencyNotAvailable()
|
460 |
+
except OptionalDependencyNotAvailable:
|
461 |
+
from .utils.dummy_onnx_objects import * # noqa F403
|
462 |
+
else:
|
463 |
+
from .pipelines import OnnxRuntimeModel
|
464 |
+
|
465 |
+
try:
|
466 |
+
if not is_torch_available():
|
467 |
+
raise OptionalDependencyNotAvailable()
|
468 |
+
except OptionalDependencyNotAvailable:
|
469 |
+
from .utils.dummy_pt_objects import * # noqa F403
|
470 |
+
else:
|
471 |
+
from .models import (
|
472 |
+
AsymmetricAutoencoderKL,
|
473 |
+
AutoencoderKL,
|
474 |
+
AutoencoderKLTemporalDecoder,
|
475 |
+
AutoencoderTiny,
|
476 |
+
ConsistencyDecoderVAE,
|
477 |
+
BrushNetModel,
|
478 |
+
ControlNetModel,
|
479 |
+
I2VGenXLUNet,
|
480 |
+
Kandinsky3UNet,
|
481 |
+
ModelMixin,
|
482 |
+
MotionAdapter,
|
483 |
+
MultiAdapter,
|
484 |
+
PriorTransformer,
|
485 |
+
T2IAdapter,
|
486 |
+
T5FilmDecoder,
|
487 |
+
Transformer2DModel,
|
488 |
+
UNet1DModel,
|
489 |
+
UNet2DConditionModel,
|
490 |
+
UNet2DModel,
|
491 |
+
UNet3DConditionModel,
|
492 |
+
UNetMotionModel,
|
493 |
+
UNetSpatioTemporalConditionModel,
|
494 |
+
UVit2DModel,
|
495 |
+
VQModel,
|
496 |
+
)
|
497 |
+
from .optimization import (
|
498 |
+
get_constant_schedule,
|
499 |
+
get_constant_schedule_with_warmup,
|
500 |
+
get_cosine_schedule_with_warmup,
|
501 |
+
get_cosine_with_hard_restarts_schedule_with_warmup,
|
502 |
+
get_linear_schedule_with_warmup,
|
503 |
+
get_polynomial_decay_schedule_with_warmup,
|
504 |
+
get_scheduler,
|
505 |
+
)
|
506 |
+
from .pipelines import (
|
507 |
+
AudioPipelineOutput,
|
508 |
+
AutoPipelineForImage2Image,
|
509 |
+
AutoPipelineForInpainting,
|
510 |
+
AutoPipelineForText2Image,
|
511 |
+
BlipDiffusionControlNetPipeline,
|
512 |
+
BlipDiffusionPipeline,
|
513 |
+
CLIPImageProjection,
|
514 |
+
ConsistencyModelPipeline,
|
515 |
+
DanceDiffusionPipeline,
|
516 |
+
DDIMPipeline,
|
517 |
+
DDPMPipeline,
|
518 |
+
DiffusionPipeline,
|
519 |
+
DiTPipeline,
|
520 |
+
ImagePipelineOutput,
|
521 |
+
KarrasVePipeline,
|
522 |
+
LDMPipeline,
|
523 |
+
LDMSuperResolutionPipeline,
|
524 |
+
PNDMPipeline,
|
525 |
+
RePaintPipeline,
|
526 |
+
ScoreSdeVePipeline,
|
527 |
+
StableDiffusionMixin,
|
528 |
+
)
|
529 |
+
from .schedulers import (
|
530 |
+
AmusedScheduler,
|
531 |
+
CMStochasticIterativeScheduler,
|
532 |
+
DDIMInverseScheduler,
|
533 |
+
DDIMParallelScheduler,
|
534 |
+
DDIMScheduler,
|
535 |
+
DDPMParallelScheduler,
|
536 |
+
DDPMScheduler,
|
537 |
+
DDPMWuerstchenScheduler,
|
538 |
+
DEISMultistepScheduler,
|
539 |
+
DPMSolverMultistepInverseScheduler,
|
540 |
+
DPMSolverMultistepScheduler,
|
541 |
+
DPMSolverSinglestepScheduler,
|
542 |
+
EDMDPMSolverMultistepScheduler,
|
543 |
+
EDMEulerScheduler,
|
544 |
+
EulerAncestralDiscreteScheduler,
|
545 |
+
EulerDiscreteScheduler,
|
546 |
+
HeunDiscreteScheduler,
|
547 |
+
IPNDMScheduler,
|
548 |
+
KarrasVeScheduler,
|
549 |
+
KDPM2AncestralDiscreteScheduler,
|
550 |
+
KDPM2DiscreteScheduler,
|
551 |
+
LCMScheduler,
|
552 |
+
PNDMScheduler,
|
553 |
+
RePaintScheduler,
|
554 |
+
SASolverScheduler,
|
555 |
+
SchedulerMixin,
|
556 |
+
ScoreSdeVeScheduler,
|
557 |
+
TCDScheduler,
|
558 |
+
UnCLIPScheduler,
|
559 |
+
UniPCMultistepScheduler,
|
560 |
+
VQDiffusionScheduler,
|
561 |
+
)
|
562 |
+
from .training_utils import EMAModel
|
563 |
+
|
564 |
+
try:
|
565 |
+
if not (is_torch_available() and is_scipy_available()):
|
566 |
+
raise OptionalDependencyNotAvailable()
|
567 |
+
except OptionalDependencyNotAvailable:
|
568 |
+
from .utils.dummy_torch_and_scipy_objects import * # noqa F403
|
569 |
+
else:
|
570 |
+
from .schedulers import LMSDiscreteScheduler
|
571 |
+
|
572 |
+
try:
|
573 |
+
if not (is_torch_available() and is_torchsde_available()):
|
574 |
+
raise OptionalDependencyNotAvailable()
|
575 |
+
except OptionalDependencyNotAvailable:
|
576 |
+
from .utils.dummy_torch_and_torchsde_objects import * # noqa F403
|
577 |
+
else:
|
578 |
+
from .schedulers import DPMSolverSDEScheduler
|
579 |
+
|
580 |
+
try:
|
581 |
+
if not (is_torch_available() and is_transformers_available()):
|
582 |
+
raise OptionalDependencyNotAvailable()
|
583 |
+
except OptionalDependencyNotAvailable:
|
584 |
+
from .utils.dummy_torch_and_transformers_objects import * # noqa F403
|
585 |
+
else:
|
586 |
+
from .pipelines import (
|
587 |
+
AltDiffusionImg2ImgPipeline,
|
588 |
+
AltDiffusionPipeline,
|
589 |
+
AmusedImg2ImgPipeline,
|
590 |
+
AmusedInpaintPipeline,
|
591 |
+
AmusedPipeline,
|
592 |
+
AnimateDiffPipeline,
|
593 |
+
AnimateDiffVideoToVideoPipeline,
|
594 |
+
AudioLDM2Pipeline,
|
595 |
+
AudioLDM2ProjectionModel,
|
596 |
+
AudioLDM2UNet2DConditionModel,
|
597 |
+
AudioLDMPipeline,
|
598 |
+
CLIPImageProjection,
|
599 |
+
CycleDiffusionPipeline,
|
600 |
+
I2VGenXLPipeline,
|
601 |
+
IFImg2ImgPipeline,
|
602 |
+
IFImg2ImgSuperResolutionPipeline,
|
603 |
+
IFInpaintingPipeline,
|
604 |
+
IFInpaintingSuperResolutionPipeline,
|
605 |
+
IFPipeline,
|
606 |
+
IFSuperResolutionPipeline,
|
607 |
+
ImageTextPipelineOutput,
|
608 |
+
Kandinsky3Img2ImgPipeline,
|
609 |
+
Kandinsky3Pipeline,
|
610 |
+
KandinskyCombinedPipeline,
|
611 |
+
KandinskyImg2ImgCombinedPipeline,
|
612 |
+
KandinskyImg2ImgPipeline,
|
613 |
+
KandinskyInpaintCombinedPipeline,
|
614 |
+
KandinskyInpaintPipeline,
|
615 |
+
KandinskyPipeline,
|
616 |
+
KandinskyPriorPipeline,
|
617 |
+
KandinskyV22CombinedPipeline,
|
618 |
+
KandinskyV22ControlnetImg2ImgPipeline,
|
619 |
+
KandinskyV22ControlnetPipeline,
|
620 |
+
KandinskyV22Img2ImgCombinedPipeline,
|
621 |
+
KandinskyV22Img2ImgPipeline,
|
622 |
+
KandinskyV22InpaintCombinedPipeline,
|
623 |
+
KandinskyV22InpaintPipeline,
|
624 |
+
KandinskyV22Pipeline,
|
625 |
+
KandinskyV22PriorEmb2EmbPipeline,
|
626 |
+
KandinskyV22PriorPipeline,
|
627 |
+
LatentConsistencyModelImg2ImgPipeline,
|
628 |
+
LatentConsistencyModelPipeline,
|
629 |
+
LDMTextToImagePipeline,
|
630 |
+
MusicLDMPipeline,
|
631 |
+
PaintByExamplePipeline,
|
632 |
+
PIAPipeline,
|
633 |
+
PixArtAlphaPipeline,
|
634 |
+
SemanticStableDiffusionPipeline,
|
635 |
+
ShapEImg2ImgPipeline,
|
636 |
+
ShapEPipeline,
|
637 |
+
StableCascadeCombinedPipeline,
|
638 |
+
StableCascadeDecoderPipeline,
|
639 |
+
StableCascadePriorPipeline,
|
640 |
+
StableDiffusionAdapterPipeline,
|
641 |
+
StableDiffusionAttendAndExcitePipeline,
|
642 |
+
StableDiffusionBrushNetPipeline,
|
643 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
644 |
+
StableDiffusionControlNetInpaintPipeline,
|
645 |
+
StableDiffusionControlNetPipeline,
|
646 |
+
StableDiffusionDepth2ImgPipeline,
|
647 |
+
StableDiffusionDiffEditPipeline,
|
648 |
+
StableDiffusionGLIGENPipeline,
|
649 |
+
StableDiffusionGLIGENTextImagePipeline,
|
650 |
+
StableDiffusionImageVariationPipeline,
|
651 |
+
StableDiffusionImg2ImgPipeline,
|
652 |
+
StableDiffusionInpaintPipeline,
|
653 |
+
StableDiffusionInpaintPipelineLegacy,
|
654 |
+
StableDiffusionInstructPix2PixPipeline,
|
655 |
+
StableDiffusionLatentUpscalePipeline,
|
656 |
+
StableDiffusionLDM3DPipeline,
|
657 |
+
StableDiffusionModelEditingPipeline,
|
658 |
+
StableDiffusionPanoramaPipeline,
|
659 |
+
StableDiffusionParadigmsPipeline,
|
660 |
+
StableDiffusionPipeline,
|
661 |
+
StableDiffusionPipelineSafe,
|
662 |
+
StableDiffusionPix2PixZeroPipeline,
|
663 |
+
StableDiffusionSAGPipeline,
|
664 |
+
StableDiffusionUpscalePipeline,
|
665 |
+
StableDiffusionXLAdapterPipeline,
|
666 |
+
StableDiffusionXLBrushNetPipeline,
|
667 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
668 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
669 |
+
StableDiffusionXLControlNetPipeline,
|
670 |
+
StableDiffusionXLImg2ImgPipeline,
|
671 |
+
StableDiffusionXLInpaintPipeline,
|
672 |
+
StableDiffusionXLInstructPix2PixPipeline,
|
673 |
+
StableDiffusionXLPipeline,
|
674 |
+
StableUnCLIPImg2ImgPipeline,
|
675 |
+
StableUnCLIPPipeline,
|
676 |
+
StableVideoDiffusionPipeline,
|
677 |
+
TextToVideoSDPipeline,
|
678 |
+
TextToVideoZeroPipeline,
|
679 |
+
TextToVideoZeroSDXLPipeline,
|
680 |
+
UnCLIPImageVariationPipeline,
|
681 |
+
UnCLIPPipeline,
|
682 |
+
UniDiffuserModel,
|
683 |
+
UniDiffuserPipeline,
|
684 |
+
UniDiffuserTextDecoder,
|
685 |
+
VersatileDiffusionDualGuidedPipeline,
|
686 |
+
VersatileDiffusionImageVariationPipeline,
|
687 |
+
VersatileDiffusionPipeline,
|
688 |
+
VersatileDiffusionTextToImagePipeline,
|
689 |
+
VideoToVideoSDPipeline,
|
690 |
+
VQDiffusionPipeline,
|
691 |
+
WuerstchenCombinedPipeline,
|
692 |
+
WuerstchenDecoderPipeline,
|
693 |
+
WuerstchenPriorPipeline,
|
694 |
+
)
|
695 |
+
|
696 |
+
try:
|
697 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
698 |
+
raise OptionalDependencyNotAvailable()
|
699 |
+
except OptionalDependencyNotAvailable:
|
700 |
+
from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
|
701 |
+
else:
|
702 |
+
from .pipelines import StableDiffusionKDiffusionPipeline, StableDiffusionXLKDiffusionPipeline
|
703 |
+
|
704 |
+
try:
|
705 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
706 |
+
raise OptionalDependencyNotAvailable()
|
707 |
+
except OptionalDependencyNotAvailable:
|
708 |
+
from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
|
709 |
+
else:
|
710 |
+
from .pipelines import (
|
711 |
+
OnnxStableDiffusionImg2ImgPipeline,
|
712 |
+
OnnxStableDiffusionInpaintPipeline,
|
713 |
+
OnnxStableDiffusionInpaintPipelineLegacy,
|
714 |
+
OnnxStableDiffusionPipeline,
|
715 |
+
OnnxStableDiffusionUpscalePipeline,
|
716 |
+
StableDiffusionOnnxPipeline,
|
717 |
+
)
|
718 |
+
|
719 |
+
try:
|
720 |
+
if not (is_torch_available() and is_librosa_available()):
|
721 |
+
raise OptionalDependencyNotAvailable()
|
722 |
+
except OptionalDependencyNotAvailable:
|
723 |
+
from .utils.dummy_torch_and_librosa_objects import * # noqa F403
|
724 |
+
else:
|
725 |
+
from .pipelines import AudioDiffusionPipeline, Mel
|
726 |
+
|
727 |
+
try:
|
728 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
729 |
+
raise OptionalDependencyNotAvailable()
|
730 |
+
except OptionalDependencyNotAvailable:
|
731 |
+
from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
|
732 |
+
else:
|
733 |
+
from .pipelines import SpectrogramDiffusionPipeline
|
734 |
+
|
735 |
+
try:
|
736 |
+
if not is_flax_available():
|
737 |
+
raise OptionalDependencyNotAvailable()
|
738 |
+
except OptionalDependencyNotAvailable:
|
739 |
+
from .utils.dummy_flax_objects import * # noqa F403
|
740 |
+
else:
|
741 |
+
from .models.controlnet_flax import FlaxControlNetModel
|
742 |
+
from .models.modeling_flax_utils import FlaxModelMixin
|
743 |
+
from .models.unets.unet_2d_condition_flax import FlaxUNet2DConditionModel
|
744 |
+
from .models.vae_flax import FlaxAutoencoderKL
|
745 |
+
from .pipelines import FlaxDiffusionPipeline
|
746 |
+
from .schedulers import (
|
747 |
+
FlaxDDIMScheduler,
|
748 |
+
FlaxDDPMScheduler,
|
749 |
+
FlaxDPMSolverMultistepScheduler,
|
750 |
+
FlaxEulerDiscreteScheduler,
|
751 |
+
FlaxKarrasVeScheduler,
|
752 |
+
FlaxLMSDiscreteScheduler,
|
753 |
+
FlaxPNDMScheduler,
|
754 |
+
FlaxSchedulerMixin,
|
755 |
+
FlaxScoreSdeVeScheduler,
|
756 |
+
)
|
757 |
+
|
758 |
+
try:
|
759 |
+
if not (is_flax_available() and is_transformers_available()):
|
760 |
+
raise OptionalDependencyNotAvailable()
|
761 |
+
except OptionalDependencyNotAvailable:
|
762 |
+
from .utils.dummy_flax_and_transformers_objects import * # noqa F403
|
763 |
+
else:
|
764 |
+
from .pipelines import (
|
765 |
+
FlaxStableDiffusionControlNetPipeline,
|
766 |
+
FlaxStableDiffusionImg2ImgPipeline,
|
767 |
+
FlaxStableDiffusionInpaintPipeline,
|
768 |
+
FlaxStableDiffusionPipeline,
|
769 |
+
FlaxStableDiffusionXLPipeline,
|
770 |
+
)
|
771 |
+
|
772 |
+
try:
|
773 |
+
if not (is_note_seq_available()):
|
774 |
+
raise OptionalDependencyNotAvailable()
|
775 |
+
except OptionalDependencyNotAvailable:
|
776 |
+
from .utils.dummy_note_seq_objects import * # noqa F403
|
777 |
+
else:
|
778 |
+
from .pipelines import MidiProcessor
|
779 |
+
|
780 |
+
else:
|
781 |
+
import sys
|
782 |
+
|
783 |
+
sys.modules[__name__] = _LazyModule(
|
784 |
+
__name__,
|
785 |
+
globals()["__file__"],
|
786 |
+
_import_structure,
|
787 |
+
module_spec=__spec__,
|
788 |
+
extra_objects={"__version__": __version__},
|
789 |
+
)
|
BrushNet/build/lib/diffusers/commands/__init__.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from abc import ABC, abstractmethod
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
|
19 |
+
class BaseDiffusersCLICommand(ABC):
|
20 |
+
@staticmethod
|
21 |
+
@abstractmethod
|
22 |
+
def register_subcommand(parser: ArgumentParser):
|
23 |
+
raise NotImplementedError()
|
24 |
+
|
25 |
+
@abstractmethod
|
26 |
+
def run(self):
|
27 |
+
raise NotImplementedError()
|
BrushNet/build/lib/diffusers/commands/diffusers_cli.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
from .env import EnvironmentCommand
|
19 |
+
from .fp16_safetensors import FP16SafetensorsCommand
|
20 |
+
|
21 |
+
|
22 |
+
def main():
|
23 |
+
parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
|
24 |
+
commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
|
25 |
+
|
26 |
+
# Register commands
|
27 |
+
EnvironmentCommand.register_subcommand(commands_parser)
|
28 |
+
FP16SafetensorsCommand.register_subcommand(commands_parser)
|
29 |
+
|
30 |
+
# Let's go
|
31 |
+
args = parser.parse_args()
|
32 |
+
|
33 |
+
if not hasattr(args, "func"):
|
34 |
+
parser.print_help()
|
35 |
+
exit(1)
|
36 |
+
|
37 |
+
# Run
|
38 |
+
service = args.func(args)
|
39 |
+
service.run()
|
40 |
+
|
41 |
+
|
42 |
+
if __name__ == "__main__":
|
43 |
+
main()
|
BrushNet/build/lib/diffusers/commands/env.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 platform
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
import huggingface_hub
|
19 |
+
|
20 |
+
from .. import __version__ as version
|
21 |
+
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
|
22 |
+
from . import BaseDiffusersCLICommand
|
23 |
+
|
24 |
+
|
25 |
+
def info_command_factory(_):
|
26 |
+
return EnvironmentCommand()
|
27 |
+
|
28 |
+
|
29 |
+
class EnvironmentCommand(BaseDiffusersCLICommand):
|
30 |
+
@staticmethod
|
31 |
+
def register_subcommand(parser: ArgumentParser):
|
32 |
+
download_parser = parser.add_parser("env")
|
33 |
+
download_parser.set_defaults(func=info_command_factory)
|
34 |
+
|
35 |
+
def run(self):
|
36 |
+
hub_version = huggingface_hub.__version__
|
37 |
+
|
38 |
+
pt_version = "not installed"
|
39 |
+
pt_cuda_available = "NA"
|
40 |
+
if is_torch_available():
|
41 |
+
import torch
|
42 |
+
|
43 |
+
pt_version = torch.__version__
|
44 |
+
pt_cuda_available = torch.cuda.is_available()
|
45 |
+
|
46 |
+
transformers_version = "not installed"
|
47 |
+
if is_transformers_available():
|
48 |
+
import transformers
|
49 |
+
|
50 |
+
transformers_version = transformers.__version__
|
51 |
+
|
52 |
+
accelerate_version = "not installed"
|
53 |
+
if is_accelerate_available():
|
54 |
+
import accelerate
|
55 |
+
|
56 |
+
accelerate_version = accelerate.__version__
|
57 |
+
|
58 |
+
xformers_version = "not installed"
|
59 |
+
if is_xformers_available():
|
60 |
+
import xformers
|
61 |
+
|
62 |
+
xformers_version = xformers.__version__
|
63 |
+
|
64 |
+
info = {
|
65 |
+
"`diffusers` version": version,
|
66 |
+
"Platform": platform.platform(),
|
67 |
+
"Python version": platform.python_version(),
|
68 |
+
"PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
|
69 |
+
"Huggingface_hub version": hub_version,
|
70 |
+
"Transformers version": transformers_version,
|
71 |
+
"Accelerate version": accelerate_version,
|
72 |
+
"xFormers version": xformers_version,
|
73 |
+
"Using GPU in script?": "<fill in>",
|
74 |
+
"Using distributed or parallel set-up in script?": "<fill in>",
|
75 |
+
}
|
76 |
+
|
77 |
+
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
|
78 |
+
print(self.format_dict(info))
|
79 |
+
|
80 |
+
return info
|
81 |
+
|
82 |
+
@staticmethod
|
83 |
+
def format_dict(d):
|
84 |
+
return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
|
BrushNet/build/lib/diffusers/commands/fp16_safetensors.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
"""
|
16 |
+
Usage example:
|
17 |
+
diffusers-cli fp16_safetensors --ckpt_id=openai/shap-e --fp16 --use_safetensors
|
18 |
+
"""
|
19 |
+
|
20 |
+
import glob
|
21 |
+
import json
|
22 |
+
import warnings
|
23 |
+
from argparse import ArgumentParser, Namespace
|
24 |
+
from importlib import import_module
|
25 |
+
|
26 |
+
import huggingface_hub
|
27 |
+
import torch
|
28 |
+
from huggingface_hub import hf_hub_download
|
29 |
+
from packaging import version
|
30 |
+
|
31 |
+
from ..utils import logging
|
32 |
+
from . import BaseDiffusersCLICommand
|
33 |
+
|
34 |
+
|
35 |
+
def conversion_command_factory(args: Namespace):
|
36 |
+
if args.use_auth_token:
|
37 |
+
warnings.warn(
|
38 |
+
"The `--use_auth_token` flag is deprecated and will be removed in a future version. Authentication is now"
|
39 |
+
" handled automatically if user is logged in."
|
40 |
+
)
|
41 |
+
return FP16SafetensorsCommand(args.ckpt_id, args.fp16, args.use_safetensors)
|
42 |
+
|
43 |
+
|
44 |
+
class FP16SafetensorsCommand(BaseDiffusersCLICommand):
|
45 |
+
@staticmethod
|
46 |
+
def register_subcommand(parser: ArgumentParser):
|
47 |
+
conversion_parser = parser.add_parser("fp16_safetensors")
|
48 |
+
conversion_parser.add_argument(
|
49 |
+
"--ckpt_id",
|
50 |
+
type=str,
|
51 |
+
help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
|
52 |
+
)
|
53 |
+
conversion_parser.add_argument(
|
54 |
+
"--fp16", action="store_true", help="If serializing the variables in FP16 precision."
|
55 |
+
)
|
56 |
+
conversion_parser.add_argument(
|
57 |
+
"--use_safetensors", action="store_true", help="If serializing in the safetensors format."
|
58 |
+
)
|
59 |
+
conversion_parser.add_argument(
|
60 |
+
"--use_auth_token",
|
61 |
+
action="store_true",
|
62 |
+
help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
|
63 |
+
)
|
64 |
+
conversion_parser.set_defaults(func=conversion_command_factory)
|
65 |
+
|
66 |
+
def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool):
|
67 |
+
self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
|
68 |
+
self.ckpt_id = ckpt_id
|
69 |
+
self.local_ckpt_dir = f"/tmp/{ckpt_id}"
|
70 |
+
self.fp16 = fp16
|
71 |
+
|
72 |
+
self.use_safetensors = use_safetensors
|
73 |
+
|
74 |
+
if not self.use_safetensors and not self.fp16:
|
75 |
+
raise NotImplementedError(
|
76 |
+
"When `use_safetensors` and `fp16` both are False, then this command is of no use."
|
77 |
+
)
|
78 |
+
|
79 |
+
def run(self):
|
80 |
+
if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
|
81 |
+
raise ImportError(
|
82 |
+
"The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
|
83 |
+
" installation."
|
84 |
+
)
|
85 |
+
else:
|
86 |
+
from huggingface_hub import create_commit
|
87 |
+
from huggingface_hub._commit_api import CommitOperationAdd
|
88 |
+
|
89 |
+
model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json")
|
90 |
+
with open(model_index, "r") as f:
|
91 |
+
pipeline_class_name = json.load(f)["_class_name"]
|
92 |
+
pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
|
93 |
+
self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
|
94 |
+
|
95 |
+
# Load the appropriate pipeline. We could have use `DiffusionPipeline`
|
96 |
+
# here, but just to avoid any rough edge cases.
|
97 |
+
pipeline = pipeline_class.from_pretrained(
|
98 |
+
self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32
|
99 |
+
)
|
100 |
+
pipeline.save_pretrained(
|
101 |
+
self.local_ckpt_dir,
|
102 |
+
safe_serialization=True if self.use_safetensors else False,
|
103 |
+
variant="fp16" if self.fp16 else None,
|
104 |
+
)
|
105 |
+
self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
|
106 |
+
|
107 |
+
# Fetch all the paths.
|
108 |
+
if self.fp16:
|
109 |
+
modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
|
110 |
+
elif self.use_safetensors:
|
111 |
+
modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
|
112 |
+
|
113 |
+
# Prepare for the PR.
|
114 |
+
commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
|
115 |
+
operations = []
|
116 |
+
for path in modified_paths:
|
117 |
+
operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
|
118 |
+
|
119 |
+
# Open the PR.
|
120 |
+
commit_description = (
|
121 |
+
"Variables converted by the [`diffusers`' `fp16_safetensors`"
|
122 |
+
" CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
|
123 |
+
)
|
124 |
+
hub_pr_url = create_commit(
|
125 |
+
repo_id=self.ckpt_id,
|
126 |
+
operations=operations,
|
127 |
+
commit_message=commit_message,
|
128 |
+
commit_description=commit_description,
|
129 |
+
repo_type="model",
|
130 |
+
create_pr=True,
|
131 |
+
).pr_url
|
132 |
+
self.logger.info(f"PR created here: {hub_pr_url}.")
|
BrushNet/build/lib/diffusers/configuration_utils.py
ADDED
@@ -0,0 +1,703 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
""" ConfigMixin base class and utilities."""
|
17 |
+
import dataclasses
|
18 |
+
import functools
|
19 |
+
import importlib
|
20 |
+
import inspect
|
21 |
+
import json
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
from collections import OrderedDict
|
25 |
+
from pathlib import PosixPath
|
26 |
+
from typing import Any, Dict, Tuple, Union
|
27 |
+
|
28 |
+
import numpy as np
|
29 |
+
from huggingface_hub import create_repo, hf_hub_download
|
30 |
+
from huggingface_hub.utils import (
|
31 |
+
EntryNotFoundError,
|
32 |
+
RepositoryNotFoundError,
|
33 |
+
RevisionNotFoundError,
|
34 |
+
validate_hf_hub_args,
|
35 |
+
)
|
36 |
+
from requests import HTTPError
|
37 |
+
|
38 |
+
from . import __version__
|
39 |
+
from .utils import (
|
40 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
41 |
+
DummyObject,
|
42 |
+
deprecate,
|
43 |
+
extract_commit_hash,
|
44 |
+
http_user_agent,
|
45 |
+
logging,
|
46 |
+
)
|
47 |
+
|
48 |
+
|
49 |
+
logger = logging.get_logger(__name__)
|
50 |
+
|
51 |
+
_re_configuration_file = re.compile(r"config\.(.*)\.json")
|
52 |
+
|
53 |
+
|
54 |
+
class FrozenDict(OrderedDict):
|
55 |
+
def __init__(self, *args, **kwargs):
|
56 |
+
super().__init__(*args, **kwargs)
|
57 |
+
|
58 |
+
for key, value in self.items():
|
59 |
+
setattr(self, key, value)
|
60 |
+
|
61 |
+
self.__frozen = True
|
62 |
+
|
63 |
+
def __delitem__(self, *args, **kwargs):
|
64 |
+
raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
|
65 |
+
|
66 |
+
def setdefault(self, *args, **kwargs):
|
67 |
+
raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
|
68 |
+
|
69 |
+
def pop(self, *args, **kwargs):
|
70 |
+
raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
|
71 |
+
|
72 |
+
def update(self, *args, **kwargs):
|
73 |
+
raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
|
74 |
+
|
75 |
+
def __setattr__(self, name, value):
|
76 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
77 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
78 |
+
super().__setattr__(name, value)
|
79 |
+
|
80 |
+
def __setitem__(self, name, value):
|
81 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
82 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
83 |
+
super().__setitem__(name, value)
|
84 |
+
|
85 |
+
|
86 |
+
class ConfigMixin:
|
87 |
+
r"""
|
88 |
+
Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
|
89 |
+
provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
|
90 |
+
saving classes that inherit from [`ConfigMixin`].
|
91 |
+
|
92 |
+
Class attributes:
|
93 |
+
- **config_name** (`str`) -- A filename under which the config should stored when calling
|
94 |
+
[`~ConfigMixin.save_config`] (should be overridden by parent class).
|
95 |
+
- **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
|
96 |
+
overridden by subclass).
|
97 |
+
- **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
|
98 |
+
- **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
|
99 |
+
should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
|
100 |
+
subclass).
|
101 |
+
"""
|
102 |
+
|
103 |
+
config_name = None
|
104 |
+
ignore_for_config = []
|
105 |
+
has_compatibles = False
|
106 |
+
|
107 |
+
_deprecated_kwargs = []
|
108 |
+
|
109 |
+
def register_to_config(self, **kwargs):
|
110 |
+
if self.config_name is None:
|
111 |
+
raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
|
112 |
+
# Special case for `kwargs` used in deprecation warning added to schedulers
|
113 |
+
# TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
|
114 |
+
# or solve in a more general way.
|
115 |
+
kwargs.pop("kwargs", None)
|
116 |
+
|
117 |
+
if not hasattr(self, "_internal_dict"):
|
118 |
+
internal_dict = kwargs
|
119 |
+
else:
|
120 |
+
previous_dict = dict(self._internal_dict)
|
121 |
+
internal_dict = {**self._internal_dict, **kwargs}
|
122 |
+
logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
|
123 |
+
|
124 |
+
self._internal_dict = FrozenDict(internal_dict)
|
125 |
+
|
126 |
+
def __getattr__(self, name: str) -> Any:
|
127 |
+
"""The only reason we overwrite `getattr` here is to gracefully deprecate accessing
|
128 |
+
config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
|
129 |
+
|
130 |
+
This function is mostly copied from PyTorch's __getattr__ overwrite:
|
131 |
+
https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
|
132 |
+
"""
|
133 |
+
|
134 |
+
is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
|
135 |
+
is_attribute = name in self.__dict__
|
136 |
+
|
137 |
+
if is_in_config and not is_attribute:
|
138 |
+
deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'."
|
139 |
+
deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
|
140 |
+
return self._internal_dict[name]
|
141 |
+
|
142 |
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
|
143 |
+
|
144 |
+
def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
|
145 |
+
"""
|
146 |
+
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
|
147 |
+
[`~ConfigMixin.from_config`] class method.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
save_directory (`str` or `os.PathLike`):
|
151 |
+
Directory where the configuration JSON file is saved (will be created if it does not exist).
|
152 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
153 |
+
Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
|
154 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
155 |
+
namespace).
|
156 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
157 |
+
Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
158 |
+
"""
|
159 |
+
if os.path.isfile(save_directory):
|
160 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
161 |
+
|
162 |
+
os.makedirs(save_directory, exist_ok=True)
|
163 |
+
|
164 |
+
# If we save using the predefined names, we can load using `from_config`
|
165 |
+
output_config_file = os.path.join(save_directory, self.config_name)
|
166 |
+
|
167 |
+
self.to_json_file(output_config_file)
|
168 |
+
logger.info(f"Configuration saved in {output_config_file}")
|
169 |
+
|
170 |
+
if push_to_hub:
|
171 |
+
commit_message = kwargs.pop("commit_message", None)
|
172 |
+
private = kwargs.pop("private", False)
|
173 |
+
create_pr = kwargs.pop("create_pr", False)
|
174 |
+
token = kwargs.pop("token", None)
|
175 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
176 |
+
repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
|
177 |
+
|
178 |
+
self._upload_folder(
|
179 |
+
save_directory,
|
180 |
+
repo_id,
|
181 |
+
token=token,
|
182 |
+
commit_message=commit_message,
|
183 |
+
create_pr=create_pr,
|
184 |
+
)
|
185 |
+
|
186 |
+
@classmethod
|
187 |
+
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
|
188 |
+
r"""
|
189 |
+
Instantiate a Python class from a config dictionary.
|
190 |
+
|
191 |
+
Parameters:
|
192 |
+
config (`Dict[str, Any]`):
|
193 |
+
A config dictionary from which the Python class is instantiated. Make sure to only load configuration
|
194 |
+
files of compatible classes.
|
195 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
196 |
+
Whether kwargs that are not consumed by the Python class should be returned or not.
|
197 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
198 |
+
Can be used to update the configuration object (after it is loaded) and initiate the Python class.
|
199 |
+
`**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
|
200 |
+
overwrite the same named arguments in `config`.
|
201 |
+
|
202 |
+
Returns:
|
203 |
+
[`ModelMixin`] or [`SchedulerMixin`]:
|
204 |
+
A model or scheduler object instantiated from a config dictionary.
|
205 |
+
|
206 |
+
Examples:
|
207 |
+
|
208 |
+
```python
|
209 |
+
>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
|
210 |
+
|
211 |
+
>>> # Download scheduler from huggingface.co and cache.
|
212 |
+
>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
|
213 |
+
|
214 |
+
>>> # Instantiate DDIM scheduler class with same config as DDPM
|
215 |
+
>>> scheduler = DDIMScheduler.from_config(scheduler.config)
|
216 |
+
|
217 |
+
>>> # Instantiate PNDM scheduler class with same config as DDPM
|
218 |
+
>>> scheduler = PNDMScheduler.from_config(scheduler.config)
|
219 |
+
```
|
220 |
+
"""
|
221 |
+
# <===== TO BE REMOVED WITH DEPRECATION
|
222 |
+
# TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
|
223 |
+
if "pretrained_model_name_or_path" in kwargs:
|
224 |
+
config = kwargs.pop("pretrained_model_name_or_path")
|
225 |
+
|
226 |
+
if config is None:
|
227 |
+
raise ValueError("Please make sure to provide a config as the first positional argument.")
|
228 |
+
# ======>
|
229 |
+
|
230 |
+
if not isinstance(config, dict):
|
231 |
+
deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
|
232 |
+
if "Scheduler" in cls.__name__:
|
233 |
+
deprecation_message += (
|
234 |
+
f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
|
235 |
+
" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
|
236 |
+
" be removed in v1.0.0."
|
237 |
+
)
|
238 |
+
elif "Model" in cls.__name__:
|
239 |
+
deprecation_message += (
|
240 |
+
f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
|
241 |
+
f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
|
242 |
+
" instead. This functionality will be removed in v1.0.0."
|
243 |
+
)
|
244 |
+
deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
|
245 |
+
config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
|
246 |
+
|
247 |
+
init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
|
248 |
+
|
249 |
+
# Allow dtype to be specified on initialization
|
250 |
+
if "dtype" in unused_kwargs:
|
251 |
+
init_dict["dtype"] = unused_kwargs.pop("dtype")
|
252 |
+
|
253 |
+
# add possible deprecated kwargs
|
254 |
+
for deprecated_kwarg in cls._deprecated_kwargs:
|
255 |
+
if deprecated_kwarg in unused_kwargs:
|
256 |
+
init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
|
257 |
+
|
258 |
+
# Return model and optionally state and/or unused_kwargs
|
259 |
+
model = cls(**init_dict)
|
260 |
+
|
261 |
+
# make sure to also save config parameters that might be used for compatible classes
|
262 |
+
# update _class_name
|
263 |
+
if "_class_name" in hidden_dict:
|
264 |
+
hidden_dict["_class_name"] = cls.__name__
|
265 |
+
|
266 |
+
model.register_to_config(**hidden_dict)
|
267 |
+
|
268 |
+
# add hidden kwargs of compatible classes to unused_kwargs
|
269 |
+
unused_kwargs = {**unused_kwargs, **hidden_dict}
|
270 |
+
|
271 |
+
if return_unused_kwargs:
|
272 |
+
return (model, unused_kwargs)
|
273 |
+
else:
|
274 |
+
return model
|
275 |
+
|
276 |
+
@classmethod
|
277 |
+
def get_config_dict(cls, *args, **kwargs):
|
278 |
+
deprecation_message = (
|
279 |
+
f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
|
280 |
+
" removed in version v1.0.0"
|
281 |
+
)
|
282 |
+
deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
|
283 |
+
return cls.load_config(*args, **kwargs)
|
284 |
+
|
285 |
+
@classmethod
|
286 |
+
@validate_hf_hub_args
|
287 |
+
def load_config(
|
288 |
+
cls,
|
289 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
290 |
+
return_unused_kwargs=False,
|
291 |
+
return_commit_hash=False,
|
292 |
+
**kwargs,
|
293 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
294 |
+
r"""
|
295 |
+
Load a model or scheduler configuration.
|
296 |
+
|
297 |
+
Parameters:
|
298 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
299 |
+
Can be either:
|
300 |
+
|
301 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
302 |
+
the Hub.
|
303 |
+
- A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
|
304 |
+
[`~ConfigMixin.save_config`].
|
305 |
+
|
306 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
307 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
308 |
+
is not used.
|
309 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
310 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
311 |
+
cached versions if they exist.
|
312 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
313 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
314 |
+
incompletely downloaded files are deleted.
|
315 |
+
proxies (`Dict[str, str]`, *optional*):
|
316 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
317 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
318 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
319 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
320 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
321 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
322 |
+
won't be downloaded from the Hub.
|
323 |
+
token (`str` or *bool*, *optional*):
|
324 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
325 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
326 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
327 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
328 |
+
allowed by Git.
|
329 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
330 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
331 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False):
|
332 |
+
Whether unused keyword arguments of the config are returned.
|
333 |
+
return_commit_hash (`bool`, *optional*, defaults to `False):
|
334 |
+
Whether the `commit_hash` of the loaded configuration are returned.
|
335 |
+
|
336 |
+
Returns:
|
337 |
+
`dict`:
|
338 |
+
A dictionary of all the parameters stored in a JSON configuration file.
|
339 |
+
|
340 |
+
"""
|
341 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
342 |
+
force_download = kwargs.pop("force_download", False)
|
343 |
+
resume_download = kwargs.pop("resume_download", False)
|
344 |
+
proxies = kwargs.pop("proxies", None)
|
345 |
+
token = kwargs.pop("token", None)
|
346 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
347 |
+
revision = kwargs.pop("revision", None)
|
348 |
+
_ = kwargs.pop("mirror", None)
|
349 |
+
subfolder = kwargs.pop("subfolder", None)
|
350 |
+
user_agent = kwargs.pop("user_agent", {})
|
351 |
+
|
352 |
+
user_agent = {**user_agent, "file_type": "config"}
|
353 |
+
user_agent = http_user_agent(user_agent)
|
354 |
+
|
355 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
356 |
+
|
357 |
+
if cls.config_name is None:
|
358 |
+
raise ValueError(
|
359 |
+
"`self.config_name` is not defined. Note that one should not load a config from "
|
360 |
+
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
|
361 |
+
)
|
362 |
+
|
363 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
364 |
+
config_file = pretrained_model_name_or_path
|
365 |
+
elif os.path.isdir(pretrained_model_name_or_path):
|
366 |
+
if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
|
367 |
+
# Load from a PyTorch checkpoint
|
368 |
+
config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
|
369 |
+
elif subfolder is not None and os.path.isfile(
|
370 |
+
os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
371 |
+
):
|
372 |
+
config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
373 |
+
else:
|
374 |
+
raise EnvironmentError(
|
375 |
+
f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
|
376 |
+
)
|
377 |
+
else:
|
378 |
+
try:
|
379 |
+
# Load from URL or cache if already cached
|
380 |
+
config_file = hf_hub_download(
|
381 |
+
pretrained_model_name_or_path,
|
382 |
+
filename=cls.config_name,
|
383 |
+
cache_dir=cache_dir,
|
384 |
+
force_download=force_download,
|
385 |
+
proxies=proxies,
|
386 |
+
resume_download=resume_download,
|
387 |
+
local_files_only=local_files_only,
|
388 |
+
token=token,
|
389 |
+
user_agent=user_agent,
|
390 |
+
subfolder=subfolder,
|
391 |
+
revision=revision,
|
392 |
+
)
|
393 |
+
except RepositoryNotFoundError:
|
394 |
+
raise EnvironmentError(
|
395 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
|
396 |
+
" listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
|
397 |
+
" token having permission to this repo with `token` or log in with `huggingface-cli login`."
|
398 |
+
)
|
399 |
+
except RevisionNotFoundError:
|
400 |
+
raise EnvironmentError(
|
401 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
|
402 |
+
" this model name. Check the model page at"
|
403 |
+
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
404 |
+
)
|
405 |
+
except EntryNotFoundError:
|
406 |
+
raise EnvironmentError(
|
407 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
|
408 |
+
)
|
409 |
+
except HTTPError as err:
|
410 |
+
raise EnvironmentError(
|
411 |
+
"There was a specific connection error when trying to load"
|
412 |
+
f" {pretrained_model_name_or_path}:\n{err}"
|
413 |
+
)
|
414 |
+
except ValueError:
|
415 |
+
raise EnvironmentError(
|
416 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
417 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
418 |
+
f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
|
419 |
+
" run the library in offline mode at"
|
420 |
+
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
|
421 |
+
)
|
422 |
+
except EnvironmentError:
|
423 |
+
raise EnvironmentError(
|
424 |
+
f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
425 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
426 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
427 |
+
f"containing a {cls.config_name} file"
|
428 |
+
)
|
429 |
+
|
430 |
+
try:
|
431 |
+
# Load config dict
|
432 |
+
config_dict = cls._dict_from_json_file(config_file)
|
433 |
+
|
434 |
+
commit_hash = extract_commit_hash(config_file)
|
435 |
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
436 |
+
raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
|
437 |
+
|
438 |
+
if not (return_unused_kwargs or return_commit_hash):
|
439 |
+
return config_dict
|
440 |
+
|
441 |
+
outputs = (config_dict,)
|
442 |
+
|
443 |
+
if return_unused_kwargs:
|
444 |
+
outputs += (kwargs,)
|
445 |
+
|
446 |
+
if return_commit_hash:
|
447 |
+
outputs += (commit_hash,)
|
448 |
+
|
449 |
+
return outputs
|
450 |
+
|
451 |
+
@staticmethod
|
452 |
+
def _get_init_keys(cls):
|
453 |
+
return set(dict(inspect.signature(cls.__init__).parameters).keys())
|
454 |
+
|
455 |
+
@classmethod
|
456 |
+
def extract_init_dict(cls, config_dict, **kwargs):
|
457 |
+
# Skip keys that were not present in the original config, so default __init__ values were used
|
458 |
+
used_defaults = config_dict.get("_use_default_values", [])
|
459 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
|
460 |
+
|
461 |
+
# 0. Copy origin config dict
|
462 |
+
original_dict = dict(config_dict.items())
|
463 |
+
|
464 |
+
# 1. Retrieve expected config attributes from __init__ signature
|
465 |
+
expected_keys = cls._get_init_keys(cls)
|
466 |
+
expected_keys.remove("self")
|
467 |
+
# remove general kwargs if present in dict
|
468 |
+
if "kwargs" in expected_keys:
|
469 |
+
expected_keys.remove("kwargs")
|
470 |
+
# remove flax internal keys
|
471 |
+
if hasattr(cls, "_flax_internal_args"):
|
472 |
+
for arg in cls._flax_internal_args:
|
473 |
+
expected_keys.remove(arg)
|
474 |
+
|
475 |
+
# 2. Remove attributes that cannot be expected from expected config attributes
|
476 |
+
# remove keys to be ignored
|
477 |
+
if len(cls.ignore_for_config) > 0:
|
478 |
+
expected_keys = expected_keys - set(cls.ignore_for_config)
|
479 |
+
|
480 |
+
# load diffusers library to import compatible and original scheduler
|
481 |
+
diffusers_library = importlib.import_module(__name__.split(".")[0])
|
482 |
+
|
483 |
+
if cls.has_compatibles:
|
484 |
+
compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
|
485 |
+
else:
|
486 |
+
compatible_classes = []
|
487 |
+
|
488 |
+
expected_keys_comp_cls = set()
|
489 |
+
for c in compatible_classes:
|
490 |
+
expected_keys_c = cls._get_init_keys(c)
|
491 |
+
expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
|
492 |
+
expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
|
493 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
|
494 |
+
|
495 |
+
# remove attributes from orig class that cannot be expected
|
496 |
+
orig_cls_name = config_dict.pop("_class_name", cls.__name__)
|
497 |
+
if (
|
498 |
+
isinstance(orig_cls_name, str)
|
499 |
+
and orig_cls_name != cls.__name__
|
500 |
+
and hasattr(diffusers_library, orig_cls_name)
|
501 |
+
):
|
502 |
+
orig_cls = getattr(diffusers_library, orig_cls_name)
|
503 |
+
unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
|
504 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
|
505 |
+
elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
|
506 |
+
raise ValueError(
|
507 |
+
"Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
|
508 |
+
)
|
509 |
+
|
510 |
+
# remove private attributes
|
511 |
+
config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
|
512 |
+
|
513 |
+
# 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
|
514 |
+
init_dict = {}
|
515 |
+
for key in expected_keys:
|
516 |
+
# if config param is passed to kwarg and is present in config dict
|
517 |
+
# it should overwrite existing config dict key
|
518 |
+
if key in kwargs and key in config_dict:
|
519 |
+
config_dict[key] = kwargs.pop(key)
|
520 |
+
|
521 |
+
if key in kwargs:
|
522 |
+
# overwrite key
|
523 |
+
init_dict[key] = kwargs.pop(key)
|
524 |
+
elif key in config_dict:
|
525 |
+
# use value from config dict
|
526 |
+
init_dict[key] = config_dict.pop(key)
|
527 |
+
|
528 |
+
# 4. Give nice warning if unexpected values have been passed
|
529 |
+
if len(config_dict) > 0:
|
530 |
+
logger.warning(
|
531 |
+
f"The config attributes {config_dict} were passed to {cls.__name__}, "
|
532 |
+
"but are not expected and will be ignored. Please verify your "
|
533 |
+
f"{cls.config_name} configuration file."
|
534 |
+
)
|
535 |
+
|
536 |
+
# 5. Give nice info if config attributes are initialized to default because they have not been passed
|
537 |
+
passed_keys = set(init_dict.keys())
|
538 |
+
if len(expected_keys - passed_keys) > 0:
|
539 |
+
logger.info(
|
540 |
+
f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
|
541 |
+
)
|
542 |
+
|
543 |
+
# 6. Define unused keyword arguments
|
544 |
+
unused_kwargs = {**config_dict, **kwargs}
|
545 |
+
|
546 |
+
# 7. Define "hidden" config parameters that were saved for compatible classes
|
547 |
+
hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
|
548 |
+
|
549 |
+
return init_dict, unused_kwargs, hidden_config_dict
|
550 |
+
|
551 |
+
@classmethod
|
552 |
+
def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
|
553 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
554 |
+
text = reader.read()
|
555 |
+
return json.loads(text)
|
556 |
+
|
557 |
+
def __repr__(self):
|
558 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
559 |
+
|
560 |
+
@property
|
561 |
+
def config(self) -> Dict[str, Any]:
|
562 |
+
"""
|
563 |
+
Returns the config of the class as a frozen dictionary
|
564 |
+
|
565 |
+
Returns:
|
566 |
+
`Dict[str, Any]`: Config of the class.
|
567 |
+
"""
|
568 |
+
return self._internal_dict
|
569 |
+
|
570 |
+
def to_json_string(self) -> str:
|
571 |
+
"""
|
572 |
+
Serializes the configuration instance to a JSON string.
|
573 |
+
|
574 |
+
Returns:
|
575 |
+
`str`:
|
576 |
+
String containing all the attributes that make up the configuration instance in JSON format.
|
577 |
+
"""
|
578 |
+
config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
|
579 |
+
config_dict["_class_name"] = self.__class__.__name__
|
580 |
+
config_dict["_diffusers_version"] = __version__
|
581 |
+
|
582 |
+
def to_json_saveable(value):
|
583 |
+
if isinstance(value, np.ndarray):
|
584 |
+
value = value.tolist()
|
585 |
+
elif isinstance(value, PosixPath):
|
586 |
+
value = str(value)
|
587 |
+
return value
|
588 |
+
|
589 |
+
config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
|
590 |
+
# Don't save "_ignore_files" or "_use_default_values"
|
591 |
+
config_dict.pop("_ignore_files", None)
|
592 |
+
config_dict.pop("_use_default_values", None)
|
593 |
+
|
594 |
+
return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
595 |
+
|
596 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
597 |
+
"""
|
598 |
+
Save the configuration instance's parameters to a JSON file.
|
599 |
+
|
600 |
+
Args:
|
601 |
+
json_file_path (`str` or `os.PathLike`):
|
602 |
+
Path to the JSON file to save a configuration instance's parameters.
|
603 |
+
"""
|
604 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
605 |
+
writer.write(self.to_json_string())
|
606 |
+
|
607 |
+
|
608 |
+
def register_to_config(init):
|
609 |
+
r"""
|
610 |
+
Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
|
611 |
+
automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
|
612 |
+
shouldn't be registered in the config, use the `ignore_for_config` class variable
|
613 |
+
|
614 |
+
Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
|
615 |
+
"""
|
616 |
+
|
617 |
+
@functools.wraps(init)
|
618 |
+
def inner_init(self, *args, **kwargs):
|
619 |
+
# Ignore private kwargs in the init.
|
620 |
+
init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
|
621 |
+
config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
|
622 |
+
if not isinstance(self, ConfigMixin):
|
623 |
+
raise RuntimeError(
|
624 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
625 |
+
"not inherit from `ConfigMixin`."
|
626 |
+
)
|
627 |
+
|
628 |
+
ignore = getattr(self, "ignore_for_config", [])
|
629 |
+
# Get positional arguments aligned with kwargs
|
630 |
+
new_kwargs = {}
|
631 |
+
signature = inspect.signature(init)
|
632 |
+
parameters = {
|
633 |
+
name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
|
634 |
+
}
|
635 |
+
for arg, name in zip(args, parameters.keys()):
|
636 |
+
new_kwargs[name] = arg
|
637 |
+
|
638 |
+
# Then add all kwargs
|
639 |
+
new_kwargs.update(
|
640 |
+
{
|
641 |
+
k: init_kwargs.get(k, default)
|
642 |
+
for k, default in parameters.items()
|
643 |
+
if k not in ignore and k not in new_kwargs
|
644 |
+
}
|
645 |
+
)
|
646 |
+
|
647 |
+
# Take note of the parameters that were not present in the loaded config
|
648 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
649 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
650 |
+
|
651 |
+
new_kwargs = {**config_init_kwargs, **new_kwargs}
|
652 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
653 |
+
init(self, *args, **init_kwargs)
|
654 |
+
|
655 |
+
return inner_init
|
656 |
+
|
657 |
+
|
658 |
+
def flax_register_to_config(cls):
|
659 |
+
original_init = cls.__init__
|
660 |
+
|
661 |
+
@functools.wraps(original_init)
|
662 |
+
def init(self, *args, **kwargs):
|
663 |
+
if not isinstance(self, ConfigMixin):
|
664 |
+
raise RuntimeError(
|
665 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
666 |
+
"not inherit from `ConfigMixin`."
|
667 |
+
)
|
668 |
+
|
669 |
+
# Ignore private kwargs in the init. Retrieve all passed attributes
|
670 |
+
init_kwargs = dict(kwargs.items())
|
671 |
+
|
672 |
+
# Retrieve default values
|
673 |
+
fields = dataclasses.fields(self)
|
674 |
+
default_kwargs = {}
|
675 |
+
for field in fields:
|
676 |
+
# ignore flax specific attributes
|
677 |
+
if field.name in self._flax_internal_args:
|
678 |
+
continue
|
679 |
+
if type(field.default) == dataclasses._MISSING_TYPE:
|
680 |
+
default_kwargs[field.name] = None
|
681 |
+
else:
|
682 |
+
default_kwargs[field.name] = getattr(self, field.name)
|
683 |
+
|
684 |
+
# Make sure init_kwargs override default kwargs
|
685 |
+
new_kwargs = {**default_kwargs, **init_kwargs}
|
686 |
+
# dtype should be part of `init_kwargs`, but not `new_kwargs`
|
687 |
+
if "dtype" in new_kwargs:
|
688 |
+
new_kwargs.pop("dtype")
|
689 |
+
|
690 |
+
# Get positional arguments aligned with kwargs
|
691 |
+
for i, arg in enumerate(args):
|
692 |
+
name = fields[i].name
|
693 |
+
new_kwargs[name] = arg
|
694 |
+
|
695 |
+
# Take note of the parameters that were not present in the loaded config
|
696 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
697 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
698 |
+
|
699 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
700 |
+
original_init(self, *args, **kwargs)
|
701 |
+
|
702 |
+
cls.__init__ = init
|
703 |
+
return cls
|
BrushNet/build/lib/diffusers/dependency_versions_check.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from .dependency_versions_table import deps
|
16 |
+
from .utils.versions import require_version, require_version_core
|
17 |
+
|
18 |
+
|
19 |
+
# define which module versions we always want to check at run time
|
20 |
+
# (usually the ones defined in `install_requires` in setup.py)
|
21 |
+
#
|
22 |
+
# order specific notes:
|
23 |
+
# - tqdm must be checked before tokenizers
|
24 |
+
|
25 |
+
pkgs_to_check_at_runtime = "python requests filelock numpy".split()
|
26 |
+
for pkg in pkgs_to_check_at_runtime:
|
27 |
+
if pkg in deps:
|
28 |
+
require_version_core(deps[pkg])
|
29 |
+
else:
|
30 |
+
raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
|
31 |
+
|
32 |
+
|
33 |
+
def dep_version_check(pkg, hint=None):
|
34 |
+
require_version(deps[pkg], hint)
|
BrushNet/build/lib/diffusers/dependency_versions_table.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# THIS FILE HAS BEEN AUTOGENERATED. To update:
|
2 |
+
# 1. modify the `_deps` dict in setup.py
|
3 |
+
# 2. run `make deps_table_update`
|
4 |
+
deps = {
|
5 |
+
"Pillow": "Pillow",
|
6 |
+
"accelerate": "accelerate>=0.11.0",
|
7 |
+
"compel": "compel==0.1.8",
|
8 |
+
"datasets": "datasets",
|
9 |
+
"filelock": "filelock",
|
10 |
+
"flax": "flax>=0.4.1",
|
11 |
+
"hf-doc-builder": "hf-doc-builder>=0.3.0",
|
12 |
+
"huggingface-hub": "huggingface-hub",
|
13 |
+
"requests-mock": "requests-mock==1.10.0",
|
14 |
+
"importlib_metadata": "importlib_metadata",
|
15 |
+
"invisible-watermark": "invisible-watermark>=0.2.0",
|
16 |
+
"isort": "isort>=5.5.4",
|
17 |
+
"jax": "jax>=0.4.1",
|
18 |
+
"jaxlib": "jaxlib>=0.4.1",
|
19 |
+
"Jinja2": "Jinja2",
|
20 |
+
"k-diffusion": "k-diffusion>=0.0.12",
|
21 |
+
"torchsde": "torchsde",
|
22 |
+
"note_seq": "note_seq",
|
23 |
+
"librosa": "librosa",
|
24 |
+
"numpy": "numpy",
|
25 |
+
"parameterized": "parameterized",
|
26 |
+
"peft": "peft>=0.6.0",
|
27 |
+
"protobuf": "protobuf>=3.20.3,<4",
|
28 |
+
"pytest": "pytest",
|
29 |
+
"pytest-timeout": "pytest-timeout",
|
30 |
+
"pytest-xdist": "pytest-xdist",
|
31 |
+
"python": "python>=3.8.0",
|
32 |
+
"ruff": "ruff==0.1.5",
|
33 |
+
"safetensors": "safetensors>=0.3.1",
|
34 |
+
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
|
35 |
+
"GitPython": "GitPython<3.1.19",
|
36 |
+
"scipy": "scipy",
|
37 |
+
"onnx": "onnx",
|
38 |
+
"regex": "regex!=2019.12.17",
|
39 |
+
"requests": "requests",
|
40 |
+
"tensorboard": "tensorboard",
|
41 |
+
"torch": "torch>=1.4",
|
42 |
+
"torchvision": "torchvision",
|
43 |
+
"transformers": "transformers>=4.25.1",
|
44 |
+
"urllib3": "urllib3<=2.0.0",
|
45 |
+
}
|
BrushNet/build/lib/diffusers/experimental/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .rl import ValueGuidedRLPipeline
|
BrushNet/build/lib/diffusers/experimental/rl/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .value_guided_sampling import ValueGuidedRLPipeline
|
BrushNet/build/lib/diffusers/experimental/rl/value_guided_sampling.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 numpy as np
|
16 |
+
import torch
|
17 |
+
import tqdm
|
18 |
+
|
19 |
+
from ...models.unets.unet_1d import UNet1DModel
|
20 |
+
from ...pipelines import DiffusionPipeline
|
21 |
+
from ...utils.dummy_pt_objects import DDPMScheduler
|
22 |
+
from ...utils.torch_utils import randn_tensor
|
23 |
+
|
24 |
+
|
25 |
+
class ValueGuidedRLPipeline(DiffusionPipeline):
|
26 |
+
r"""
|
27 |
+
Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states.
|
28 |
+
|
29 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
30 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
31 |
+
|
32 |
+
Parameters:
|
33 |
+
value_function ([`UNet1DModel`]):
|
34 |
+
A specialized UNet for fine-tuning trajectories base on reward.
|
35 |
+
unet ([`UNet1DModel`]):
|
36 |
+
UNet architecture to denoise the encoded trajectories.
|
37 |
+
scheduler ([`SchedulerMixin`]):
|
38 |
+
A scheduler to be used in combination with `unet` to denoise the encoded trajectories. Default for this
|
39 |
+
application is [`DDPMScheduler`].
|
40 |
+
env ():
|
41 |
+
An environment following the OpenAI gym API to act in. For now only Hopper has pretrained models.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def __init__(
|
45 |
+
self,
|
46 |
+
value_function: UNet1DModel,
|
47 |
+
unet: UNet1DModel,
|
48 |
+
scheduler: DDPMScheduler,
|
49 |
+
env,
|
50 |
+
):
|
51 |
+
super().__init__()
|
52 |
+
|
53 |
+
self.register_modules(value_function=value_function, unet=unet, scheduler=scheduler, env=env)
|
54 |
+
|
55 |
+
self.data = env.get_dataset()
|
56 |
+
self.means = {}
|
57 |
+
for key in self.data.keys():
|
58 |
+
try:
|
59 |
+
self.means[key] = self.data[key].mean()
|
60 |
+
except: # noqa: E722
|
61 |
+
pass
|
62 |
+
self.stds = {}
|
63 |
+
for key in self.data.keys():
|
64 |
+
try:
|
65 |
+
self.stds[key] = self.data[key].std()
|
66 |
+
except: # noqa: E722
|
67 |
+
pass
|
68 |
+
self.state_dim = env.observation_space.shape[0]
|
69 |
+
self.action_dim = env.action_space.shape[0]
|
70 |
+
|
71 |
+
def normalize(self, x_in, key):
|
72 |
+
return (x_in - self.means[key]) / self.stds[key]
|
73 |
+
|
74 |
+
def de_normalize(self, x_in, key):
|
75 |
+
return x_in * self.stds[key] + self.means[key]
|
76 |
+
|
77 |
+
def to_torch(self, x_in):
|
78 |
+
if isinstance(x_in, dict):
|
79 |
+
return {k: self.to_torch(v) for k, v in x_in.items()}
|
80 |
+
elif torch.is_tensor(x_in):
|
81 |
+
return x_in.to(self.unet.device)
|
82 |
+
return torch.tensor(x_in, device=self.unet.device)
|
83 |
+
|
84 |
+
def reset_x0(self, x_in, cond, act_dim):
|
85 |
+
for key, val in cond.items():
|
86 |
+
x_in[:, key, act_dim:] = val.clone()
|
87 |
+
return x_in
|
88 |
+
|
89 |
+
def run_diffusion(self, x, conditions, n_guide_steps, scale):
|
90 |
+
batch_size = x.shape[0]
|
91 |
+
y = None
|
92 |
+
for i in tqdm.tqdm(self.scheduler.timesteps):
|
93 |
+
# create batch of timesteps to pass into model
|
94 |
+
timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
|
95 |
+
for _ in range(n_guide_steps):
|
96 |
+
with torch.enable_grad():
|
97 |
+
x.requires_grad_()
|
98 |
+
|
99 |
+
# permute to match dimension for pre-trained models
|
100 |
+
y = self.value_function(x.permute(0, 2, 1), timesteps).sample
|
101 |
+
grad = torch.autograd.grad([y.sum()], [x])[0]
|
102 |
+
|
103 |
+
posterior_variance = self.scheduler._get_variance(i)
|
104 |
+
model_std = torch.exp(0.5 * posterior_variance)
|
105 |
+
grad = model_std * grad
|
106 |
+
|
107 |
+
grad[timesteps < 2] = 0
|
108 |
+
x = x.detach()
|
109 |
+
x = x + scale * grad
|
110 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
111 |
+
|
112 |
+
prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
|
113 |
+
|
114 |
+
# TODO: verify deprecation of this kwarg
|
115 |
+
x = self.scheduler.step(prev_x, i, x)["prev_sample"]
|
116 |
+
|
117 |
+
# apply conditions to the trajectory (set the initial state)
|
118 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
119 |
+
x = self.to_torch(x)
|
120 |
+
return x, y
|
121 |
+
|
122 |
+
def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
|
123 |
+
# normalize the observations and create batch dimension
|
124 |
+
obs = self.normalize(obs, "observations")
|
125 |
+
obs = obs[None].repeat(batch_size, axis=0)
|
126 |
+
|
127 |
+
conditions = {0: self.to_torch(obs)}
|
128 |
+
shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
|
129 |
+
|
130 |
+
# generate initial noise and apply our conditions (to make the trajectories start at current state)
|
131 |
+
x1 = randn_tensor(shape, device=self.unet.device)
|
132 |
+
x = self.reset_x0(x1, conditions, self.action_dim)
|
133 |
+
x = self.to_torch(x)
|
134 |
+
|
135 |
+
# run the diffusion process
|
136 |
+
x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
|
137 |
+
|
138 |
+
# sort output trajectories by value
|
139 |
+
sorted_idx = y.argsort(0, descending=True).squeeze()
|
140 |
+
sorted_values = x[sorted_idx]
|
141 |
+
actions = sorted_values[:, :, : self.action_dim]
|
142 |
+
actions = actions.detach().cpu().numpy()
|
143 |
+
denorm_actions = self.de_normalize(actions, key="actions")
|
144 |
+
|
145 |
+
# select the action with the highest value
|
146 |
+
if y is not None:
|
147 |
+
selected_index = 0
|
148 |
+
else:
|
149 |
+
# if we didn't run value guiding, select a random action
|
150 |
+
selected_index = np.random.randint(0, batch_size)
|
151 |
+
|
152 |
+
denorm_actions = denorm_actions[selected_index, 0]
|
153 |
+
return denorm_actions
|
BrushNet/build/lib/diffusers/image_processor.py
ADDED
@@ -0,0 +1,990 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
import warnings
|
17 |
+
from typing import List, Optional, Tuple, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
import PIL.Image
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
from PIL import Image, ImageFilter, ImageOps
|
24 |
+
|
25 |
+
from .configuration_utils import ConfigMixin, register_to_config
|
26 |
+
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
|
27 |
+
|
28 |
+
|
29 |
+
PipelineImageInput = Union[
|
30 |
+
PIL.Image.Image,
|
31 |
+
np.ndarray,
|
32 |
+
torch.FloatTensor,
|
33 |
+
List[PIL.Image.Image],
|
34 |
+
List[np.ndarray],
|
35 |
+
List[torch.FloatTensor],
|
36 |
+
]
|
37 |
+
|
38 |
+
PipelineDepthInput = PipelineImageInput
|
39 |
+
|
40 |
+
|
41 |
+
class VaeImageProcessor(ConfigMixin):
|
42 |
+
"""
|
43 |
+
Image processor for VAE.
|
44 |
+
|
45 |
+
Args:
|
46 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
47 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
|
48 |
+
`height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
|
49 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
50 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
51 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
52 |
+
Resampling filter to use when resizing the image.
|
53 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
54 |
+
Whether to normalize the image to [-1,1].
|
55 |
+
do_binarize (`bool`, *optional*, defaults to `False`):
|
56 |
+
Whether to binarize the image to 0/1.
|
57 |
+
do_convert_rgb (`bool`, *optional*, defaults to be `False`):
|
58 |
+
Whether to convert the images to RGB format.
|
59 |
+
do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
|
60 |
+
Whether to convert the images to grayscale format.
|
61 |
+
"""
|
62 |
+
|
63 |
+
config_name = CONFIG_NAME
|
64 |
+
|
65 |
+
@register_to_config
|
66 |
+
def __init__(
|
67 |
+
self,
|
68 |
+
do_resize: bool = True,
|
69 |
+
vae_scale_factor: int = 8,
|
70 |
+
resample: str = "lanczos",
|
71 |
+
do_normalize: bool = True,
|
72 |
+
do_binarize: bool = False,
|
73 |
+
do_convert_rgb: bool = False,
|
74 |
+
do_convert_grayscale: bool = False,
|
75 |
+
):
|
76 |
+
super().__init__()
|
77 |
+
if do_convert_rgb and do_convert_grayscale:
|
78 |
+
raise ValueError(
|
79 |
+
"`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
|
80 |
+
" if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
|
81 |
+
" if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
|
82 |
+
)
|
83 |
+
self.config.do_convert_rgb = False
|
84 |
+
|
85 |
+
@staticmethod
|
86 |
+
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
|
87 |
+
"""
|
88 |
+
Convert a numpy image or a batch of images to a PIL image.
|
89 |
+
"""
|
90 |
+
if images.ndim == 3:
|
91 |
+
images = images[None, ...]
|
92 |
+
images = (images * 255).round().astype("uint8")
|
93 |
+
if images.shape[-1] == 1:
|
94 |
+
# special case for grayscale (single channel) images
|
95 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
96 |
+
else:
|
97 |
+
pil_images = [Image.fromarray(image) for image in images]
|
98 |
+
|
99 |
+
return pil_images
|
100 |
+
|
101 |
+
@staticmethod
|
102 |
+
def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
103 |
+
"""
|
104 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
105 |
+
"""
|
106 |
+
if not isinstance(images, list):
|
107 |
+
images = [images]
|
108 |
+
images = [np.array(image).astype(np.float32) / 255.0 for image in images]
|
109 |
+
images = np.stack(images, axis=0)
|
110 |
+
|
111 |
+
return images
|
112 |
+
|
113 |
+
@staticmethod
|
114 |
+
def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
|
115 |
+
"""
|
116 |
+
Convert a NumPy image to a PyTorch tensor.
|
117 |
+
"""
|
118 |
+
if images.ndim == 3:
|
119 |
+
images = images[..., None]
|
120 |
+
|
121 |
+
images = torch.from_numpy(images.transpose(0, 3, 1, 2))
|
122 |
+
return images
|
123 |
+
|
124 |
+
@staticmethod
|
125 |
+
def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
|
126 |
+
"""
|
127 |
+
Convert a PyTorch tensor to a NumPy image.
|
128 |
+
"""
|
129 |
+
images = images.cpu().permute(0, 2, 3, 1).float().numpy()
|
130 |
+
return images
|
131 |
+
|
132 |
+
@staticmethod
|
133 |
+
def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
134 |
+
"""
|
135 |
+
Normalize an image array to [-1,1].
|
136 |
+
"""
|
137 |
+
return 2.0 * images - 1.0
|
138 |
+
|
139 |
+
@staticmethod
|
140 |
+
def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
141 |
+
"""
|
142 |
+
Denormalize an image array to [0,1].
|
143 |
+
"""
|
144 |
+
return (images / 2 + 0.5).clamp(0, 1)
|
145 |
+
|
146 |
+
@staticmethod
|
147 |
+
def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
|
148 |
+
"""
|
149 |
+
Converts a PIL image to RGB format.
|
150 |
+
"""
|
151 |
+
image = image.convert("RGB")
|
152 |
+
|
153 |
+
return image
|
154 |
+
|
155 |
+
@staticmethod
|
156 |
+
def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
|
157 |
+
"""
|
158 |
+
Converts a PIL image to grayscale format.
|
159 |
+
"""
|
160 |
+
image = image.convert("L")
|
161 |
+
|
162 |
+
return image
|
163 |
+
|
164 |
+
@staticmethod
|
165 |
+
def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
|
166 |
+
"""
|
167 |
+
Applies Gaussian blur to an image.
|
168 |
+
"""
|
169 |
+
image = image.filter(ImageFilter.GaussianBlur(blur_factor))
|
170 |
+
|
171 |
+
return image
|
172 |
+
|
173 |
+
@staticmethod
|
174 |
+
def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
|
175 |
+
"""
|
176 |
+
Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect ratio of the original image;
|
177 |
+
for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128.
|
178 |
+
|
179 |
+
Args:
|
180 |
+
mask_image (PIL.Image.Image): Mask image.
|
181 |
+
width (int): Width of the image to be processed.
|
182 |
+
height (int): Height of the image to be processed.
|
183 |
+
pad (int, optional): Padding to be added to the crop region. Defaults to 0.
|
184 |
+
|
185 |
+
Returns:
|
186 |
+
tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and matches the original aspect ratio.
|
187 |
+
"""
|
188 |
+
|
189 |
+
mask_image = mask_image.convert("L")
|
190 |
+
mask = np.array(mask_image)
|
191 |
+
|
192 |
+
# 1. find a rectangular region that contains all masked ares in an image
|
193 |
+
h, w = mask.shape
|
194 |
+
crop_left = 0
|
195 |
+
for i in range(w):
|
196 |
+
if not (mask[:, i] == 0).all():
|
197 |
+
break
|
198 |
+
crop_left += 1
|
199 |
+
|
200 |
+
crop_right = 0
|
201 |
+
for i in reversed(range(w)):
|
202 |
+
if not (mask[:, i] == 0).all():
|
203 |
+
break
|
204 |
+
crop_right += 1
|
205 |
+
|
206 |
+
crop_top = 0
|
207 |
+
for i in range(h):
|
208 |
+
if not (mask[i] == 0).all():
|
209 |
+
break
|
210 |
+
crop_top += 1
|
211 |
+
|
212 |
+
crop_bottom = 0
|
213 |
+
for i in reversed(range(h)):
|
214 |
+
if not (mask[i] == 0).all():
|
215 |
+
break
|
216 |
+
crop_bottom += 1
|
217 |
+
|
218 |
+
# 2. add padding to the crop region
|
219 |
+
x1, y1, x2, y2 = (
|
220 |
+
int(max(crop_left - pad, 0)),
|
221 |
+
int(max(crop_top - pad, 0)),
|
222 |
+
int(min(w - crop_right + pad, w)),
|
223 |
+
int(min(h - crop_bottom + pad, h)),
|
224 |
+
)
|
225 |
+
|
226 |
+
# 3. expands crop region to match the aspect ratio of the image to be processed
|
227 |
+
ratio_crop_region = (x2 - x1) / (y2 - y1)
|
228 |
+
ratio_processing = width / height
|
229 |
+
|
230 |
+
if ratio_crop_region > ratio_processing:
|
231 |
+
desired_height = (x2 - x1) / ratio_processing
|
232 |
+
desired_height_diff = int(desired_height - (y2 - y1))
|
233 |
+
y1 -= desired_height_diff // 2
|
234 |
+
y2 += desired_height_diff - desired_height_diff // 2
|
235 |
+
if y2 >= mask_image.height:
|
236 |
+
diff = y2 - mask_image.height
|
237 |
+
y2 -= diff
|
238 |
+
y1 -= diff
|
239 |
+
if y1 < 0:
|
240 |
+
y2 -= y1
|
241 |
+
y1 -= y1
|
242 |
+
if y2 >= mask_image.height:
|
243 |
+
y2 = mask_image.height
|
244 |
+
else:
|
245 |
+
desired_width = (y2 - y1) * ratio_processing
|
246 |
+
desired_width_diff = int(desired_width - (x2 - x1))
|
247 |
+
x1 -= desired_width_diff // 2
|
248 |
+
x2 += desired_width_diff - desired_width_diff // 2
|
249 |
+
if x2 >= mask_image.width:
|
250 |
+
diff = x2 - mask_image.width
|
251 |
+
x2 -= diff
|
252 |
+
x1 -= diff
|
253 |
+
if x1 < 0:
|
254 |
+
x2 -= x1
|
255 |
+
x1 -= x1
|
256 |
+
if x2 >= mask_image.width:
|
257 |
+
x2 = mask_image.width
|
258 |
+
|
259 |
+
return x1, y1, x2, y2
|
260 |
+
|
261 |
+
def _resize_and_fill(
|
262 |
+
self,
|
263 |
+
image: PIL.Image.Image,
|
264 |
+
width: int,
|
265 |
+
height: int,
|
266 |
+
) -> PIL.Image.Image:
|
267 |
+
"""
|
268 |
+
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
|
269 |
+
|
270 |
+
Args:
|
271 |
+
image: The image to resize.
|
272 |
+
width: The width to resize the image to.
|
273 |
+
height: The height to resize the image to.
|
274 |
+
"""
|
275 |
+
|
276 |
+
ratio = width / height
|
277 |
+
src_ratio = image.width / image.height
|
278 |
+
|
279 |
+
src_w = width if ratio < src_ratio else image.width * height // image.height
|
280 |
+
src_h = height if ratio >= src_ratio else image.height * width // image.width
|
281 |
+
|
282 |
+
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
|
283 |
+
res = Image.new("RGB", (width, height))
|
284 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
285 |
+
|
286 |
+
if ratio < src_ratio:
|
287 |
+
fill_height = height // 2 - src_h // 2
|
288 |
+
if fill_height > 0:
|
289 |
+
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
|
290 |
+
res.paste(
|
291 |
+
resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
|
292 |
+
box=(0, fill_height + src_h),
|
293 |
+
)
|
294 |
+
elif ratio > src_ratio:
|
295 |
+
fill_width = width // 2 - src_w // 2
|
296 |
+
if fill_width > 0:
|
297 |
+
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
|
298 |
+
res.paste(
|
299 |
+
resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
|
300 |
+
box=(fill_width + src_w, 0),
|
301 |
+
)
|
302 |
+
|
303 |
+
return res
|
304 |
+
|
305 |
+
def _resize_and_crop(
|
306 |
+
self,
|
307 |
+
image: PIL.Image.Image,
|
308 |
+
width: int,
|
309 |
+
height: int,
|
310 |
+
) -> PIL.Image.Image:
|
311 |
+
"""
|
312 |
+
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
|
313 |
+
|
314 |
+
Args:
|
315 |
+
image: The image to resize.
|
316 |
+
width: The width to resize the image to.
|
317 |
+
height: The height to resize the image to.
|
318 |
+
"""
|
319 |
+
ratio = width / height
|
320 |
+
src_ratio = image.width / image.height
|
321 |
+
|
322 |
+
src_w = width if ratio > src_ratio else image.width * height // image.height
|
323 |
+
src_h = height if ratio <= src_ratio else image.height * width // image.width
|
324 |
+
|
325 |
+
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
|
326 |
+
res = Image.new("RGB", (width, height))
|
327 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
328 |
+
return res
|
329 |
+
|
330 |
+
def resize(
|
331 |
+
self,
|
332 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
333 |
+
height: int,
|
334 |
+
width: int,
|
335 |
+
resize_mode: str = "default", # "default", "fill", "crop"
|
336 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
|
337 |
+
"""
|
338 |
+
Resize image.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
342 |
+
The image input, can be a PIL image, numpy array or pytorch tensor.
|
343 |
+
height (`int`):
|
344 |
+
The height to resize to.
|
345 |
+
width (`int`):
|
346 |
+
The width to resize to.
|
347 |
+
resize_mode (`str`, *optional*, defaults to `default`):
|
348 |
+
The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
|
349 |
+
within the specified width and height, and it may not maintaining the original aspect ratio.
|
350 |
+
If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
351 |
+
within the dimensions, filling empty with data from image.
|
352 |
+
If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
353 |
+
within the dimensions, cropping the excess.
|
354 |
+
Note that resize_mode `fill` and `crop` are only supported for PIL image input.
|
355 |
+
|
356 |
+
Returns:
|
357 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
|
358 |
+
The resized image.
|
359 |
+
"""
|
360 |
+
if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
|
361 |
+
raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
|
362 |
+
if isinstance(image, PIL.Image.Image):
|
363 |
+
if resize_mode == "default":
|
364 |
+
image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
|
365 |
+
elif resize_mode == "fill":
|
366 |
+
image = self._resize_and_fill(image, width, height)
|
367 |
+
elif resize_mode == "crop":
|
368 |
+
image = self._resize_and_crop(image, width, height)
|
369 |
+
else:
|
370 |
+
raise ValueError(f"resize_mode {resize_mode} is not supported")
|
371 |
+
|
372 |
+
elif isinstance(image, torch.Tensor):
|
373 |
+
image = torch.nn.functional.interpolate(
|
374 |
+
image,
|
375 |
+
size=(height, width),
|
376 |
+
)
|
377 |
+
elif isinstance(image, np.ndarray):
|
378 |
+
image = self.numpy_to_pt(image)
|
379 |
+
image = torch.nn.functional.interpolate(
|
380 |
+
image,
|
381 |
+
size=(height, width),
|
382 |
+
)
|
383 |
+
image = self.pt_to_numpy(image)
|
384 |
+
return image
|
385 |
+
|
386 |
+
def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
|
387 |
+
"""
|
388 |
+
Create a mask.
|
389 |
+
|
390 |
+
Args:
|
391 |
+
image (`PIL.Image.Image`):
|
392 |
+
The image input, should be a PIL image.
|
393 |
+
|
394 |
+
Returns:
|
395 |
+
`PIL.Image.Image`:
|
396 |
+
The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
|
397 |
+
"""
|
398 |
+
image[image < 0.5] = 0
|
399 |
+
image[image >= 0.5] = 1
|
400 |
+
|
401 |
+
return image
|
402 |
+
|
403 |
+
def get_default_height_width(
|
404 |
+
self,
|
405 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
406 |
+
height: Optional[int] = None,
|
407 |
+
width: Optional[int] = None,
|
408 |
+
) -> Tuple[int, int]:
|
409 |
+
"""
|
410 |
+
This function return the height and width that are downscaled to the next integer multiple of
|
411 |
+
`vae_scale_factor`.
|
412 |
+
|
413 |
+
Args:
|
414 |
+
image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
415 |
+
The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
|
416 |
+
shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
|
417 |
+
have shape `[batch, channel, height, width]`.
|
418 |
+
height (`int`, *optional*, defaults to `None`):
|
419 |
+
The height in preprocessed image. If `None`, will use the height of `image` input.
|
420 |
+
width (`int`, *optional*`, defaults to `None`):
|
421 |
+
The width in preprocessed. If `None`, will use the width of the `image` input.
|
422 |
+
"""
|
423 |
+
|
424 |
+
if height is None:
|
425 |
+
if isinstance(image, PIL.Image.Image):
|
426 |
+
height = image.height
|
427 |
+
elif isinstance(image, torch.Tensor):
|
428 |
+
height = image.shape[2]
|
429 |
+
else:
|
430 |
+
height = image.shape[1]
|
431 |
+
|
432 |
+
if width is None:
|
433 |
+
if isinstance(image, PIL.Image.Image):
|
434 |
+
width = image.width
|
435 |
+
elif isinstance(image, torch.Tensor):
|
436 |
+
width = image.shape[3]
|
437 |
+
else:
|
438 |
+
width = image.shape[2]
|
439 |
+
|
440 |
+
width, height = (
|
441 |
+
x - x % self.config.vae_scale_factor for x in (width, height)
|
442 |
+
) # resize to integer multiple of vae_scale_factor
|
443 |
+
|
444 |
+
return height, width
|
445 |
+
|
446 |
+
def preprocess(
|
447 |
+
self,
|
448 |
+
image: PipelineImageInput,
|
449 |
+
height: Optional[int] = None,
|
450 |
+
width: Optional[int] = None,
|
451 |
+
resize_mode: str = "default", # "default", "fill", "crop"
|
452 |
+
crops_coords: Optional[Tuple[int, int, int, int]] = None,
|
453 |
+
) -> torch.Tensor:
|
454 |
+
"""
|
455 |
+
Preprocess the image input.
|
456 |
+
|
457 |
+
Args:
|
458 |
+
image (`pipeline_image_input`):
|
459 |
+
The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of supported formats.
|
460 |
+
height (`int`, *optional*, defaults to `None`):
|
461 |
+
The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default height.
|
462 |
+
width (`int`, *optional*`, defaults to `None`):
|
463 |
+
The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
|
464 |
+
resize_mode (`str`, *optional*, defaults to `default`):
|
465 |
+
The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit
|
466 |
+
within the specified width and height, and it may not maintaining the original aspect ratio.
|
467 |
+
If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
468 |
+
within the dimensions, filling empty with data from image.
|
469 |
+
If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
470 |
+
within the dimensions, cropping the excess.
|
471 |
+
Note that resize_mode `fill` and `crop` are only supported for PIL image input.
|
472 |
+
crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
|
473 |
+
The crop coordinates for each image in the batch. If `None`, will not crop the image.
|
474 |
+
"""
|
475 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
476 |
+
|
477 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
478 |
+
if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
|
479 |
+
if isinstance(image, torch.Tensor):
|
480 |
+
# if image is a pytorch tensor could have 2 possible shapes:
|
481 |
+
# 1. batch x height x width: we should insert the channel dimension at position 1
|
482 |
+
# 2. channel x height x width: we should insert batch dimension at position 0,
|
483 |
+
# however, since both channel and batch dimension has same size 1, it is same to insert at position 1
|
484 |
+
# for simplicity, we insert a dimension of size 1 at position 1 for both cases
|
485 |
+
image = image.unsqueeze(1)
|
486 |
+
else:
|
487 |
+
# if it is a numpy array, it could have 2 possible shapes:
|
488 |
+
# 1. batch x height x width: insert channel dimension on last position
|
489 |
+
# 2. height x width x channel: insert batch dimension on first position
|
490 |
+
if image.shape[-1] == 1:
|
491 |
+
image = np.expand_dims(image, axis=0)
|
492 |
+
else:
|
493 |
+
image = np.expand_dims(image, axis=-1)
|
494 |
+
|
495 |
+
if isinstance(image, supported_formats):
|
496 |
+
image = [image]
|
497 |
+
elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
|
498 |
+
raise ValueError(
|
499 |
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
|
500 |
+
)
|
501 |
+
|
502 |
+
if isinstance(image[0], PIL.Image.Image):
|
503 |
+
if crops_coords is not None:
|
504 |
+
image = [i.crop(crops_coords) for i in image]
|
505 |
+
if self.config.do_resize:
|
506 |
+
height, width = self.get_default_height_width(image[0], height, width)
|
507 |
+
image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
|
508 |
+
if self.config.do_convert_rgb:
|
509 |
+
image = [self.convert_to_rgb(i) for i in image]
|
510 |
+
elif self.config.do_convert_grayscale:
|
511 |
+
image = [self.convert_to_grayscale(i) for i in image]
|
512 |
+
image = self.pil_to_numpy(image) # to np
|
513 |
+
image = self.numpy_to_pt(image) # to pt
|
514 |
+
|
515 |
+
elif isinstance(image[0], np.ndarray):
|
516 |
+
image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
|
517 |
+
|
518 |
+
image = self.numpy_to_pt(image)
|
519 |
+
|
520 |
+
height, width = self.get_default_height_width(image, height, width)
|
521 |
+
if self.config.do_resize:
|
522 |
+
image = self.resize(image, height, width)
|
523 |
+
|
524 |
+
elif isinstance(image[0], torch.Tensor):
|
525 |
+
image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
|
526 |
+
|
527 |
+
if self.config.do_convert_grayscale and image.ndim == 3:
|
528 |
+
image = image.unsqueeze(1)
|
529 |
+
|
530 |
+
channel = image.shape[1]
|
531 |
+
# don't need any preprocess if the image is latents
|
532 |
+
if channel == 4:
|
533 |
+
return image
|
534 |
+
|
535 |
+
height, width = self.get_default_height_width(image, height, width)
|
536 |
+
if self.config.do_resize:
|
537 |
+
image = self.resize(image, height, width)
|
538 |
+
|
539 |
+
# expected range [0,1], normalize to [-1,1]
|
540 |
+
do_normalize = self.config.do_normalize
|
541 |
+
if do_normalize and image.min() < 0:
|
542 |
+
warnings.warn(
|
543 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
544 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
|
545 |
+
FutureWarning,
|
546 |
+
)
|
547 |
+
do_normalize = False
|
548 |
+
|
549 |
+
if do_normalize:
|
550 |
+
image = self.normalize(image)
|
551 |
+
|
552 |
+
if self.config.do_binarize:
|
553 |
+
image = self.binarize(image)
|
554 |
+
|
555 |
+
return image
|
556 |
+
|
557 |
+
def postprocess(
|
558 |
+
self,
|
559 |
+
image: torch.FloatTensor,
|
560 |
+
output_type: str = "pil",
|
561 |
+
do_denormalize: Optional[List[bool]] = None,
|
562 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
563 |
+
"""
|
564 |
+
Postprocess the image output from tensor to `output_type`.
|
565 |
+
|
566 |
+
Args:
|
567 |
+
image (`torch.FloatTensor`):
|
568 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
569 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
570 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
571 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
572 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
573 |
+
`VaeImageProcessor` config.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
577 |
+
The postprocessed image.
|
578 |
+
"""
|
579 |
+
if not isinstance(image, torch.Tensor):
|
580 |
+
raise ValueError(
|
581 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
582 |
+
)
|
583 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
584 |
+
deprecation_message = (
|
585 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
586 |
+
"`pil`, `np`, `pt`, `latent`"
|
587 |
+
)
|
588 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
589 |
+
output_type = "np"
|
590 |
+
|
591 |
+
if output_type == "latent":
|
592 |
+
return image
|
593 |
+
|
594 |
+
if do_denormalize is None:
|
595 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
596 |
+
|
597 |
+
image = torch.stack(
|
598 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
599 |
+
)
|
600 |
+
|
601 |
+
if output_type == "pt":
|
602 |
+
return image
|
603 |
+
|
604 |
+
image = self.pt_to_numpy(image)
|
605 |
+
|
606 |
+
if output_type == "np":
|
607 |
+
return image
|
608 |
+
|
609 |
+
if output_type == "pil":
|
610 |
+
return self.numpy_to_pil(image)
|
611 |
+
|
612 |
+
def apply_overlay(
|
613 |
+
self,
|
614 |
+
mask: PIL.Image.Image,
|
615 |
+
init_image: PIL.Image.Image,
|
616 |
+
image: PIL.Image.Image,
|
617 |
+
crop_coords: Optional[Tuple[int, int, int, int]] = None,
|
618 |
+
) -> PIL.Image.Image:
|
619 |
+
"""
|
620 |
+
overlay the inpaint output to the original image
|
621 |
+
"""
|
622 |
+
|
623 |
+
width, height = image.width, image.height
|
624 |
+
|
625 |
+
init_image = self.resize(init_image, width=width, height=height)
|
626 |
+
mask = self.resize(mask, width=width, height=height)
|
627 |
+
|
628 |
+
init_image_masked = PIL.Image.new("RGBa", (width, height))
|
629 |
+
init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
|
630 |
+
init_image_masked = init_image_masked.convert("RGBA")
|
631 |
+
|
632 |
+
if crop_coords is not None:
|
633 |
+
x, y, x2, y2 = crop_coords
|
634 |
+
w = x2 - x
|
635 |
+
h = y2 - y
|
636 |
+
base_image = PIL.Image.new("RGBA", (width, height))
|
637 |
+
image = self.resize(image, height=h, width=w, resize_mode="crop")
|
638 |
+
base_image.paste(image, (x, y))
|
639 |
+
image = base_image.convert("RGB")
|
640 |
+
|
641 |
+
image = image.convert("RGBA")
|
642 |
+
image.alpha_composite(init_image_masked)
|
643 |
+
image = image.convert("RGB")
|
644 |
+
|
645 |
+
return image
|
646 |
+
|
647 |
+
|
648 |
+
class VaeImageProcessorLDM3D(VaeImageProcessor):
|
649 |
+
"""
|
650 |
+
Image processor for VAE LDM3D.
|
651 |
+
|
652 |
+
Args:
|
653 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
654 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
|
655 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
656 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
657 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
658 |
+
Resampling filter to use when resizing the image.
|
659 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
660 |
+
Whether to normalize the image to [-1,1].
|
661 |
+
"""
|
662 |
+
|
663 |
+
config_name = CONFIG_NAME
|
664 |
+
|
665 |
+
@register_to_config
|
666 |
+
def __init__(
|
667 |
+
self,
|
668 |
+
do_resize: bool = True,
|
669 |
+
vae_scale_factor: int = 8,
|
670 |
+
resample: str = "lanczos",
|
671 |
+
do_normalize: bool = True,
|
672 |
+
):
|
673 |
+
super().__init__()
|
674 |
+
|
675 |
+
@staticmethod
|
676 |
+
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
|
677 |
+
"""
|
678 |
+
Convert a NumPy image or a batch of images to a PIL image.
|
679 |
+
"""
|
680 |
+
if images.ndim == 3:
|
681 |
+
images = images[None, ...]
|
682 |
+
images = (images * 255).round().astype("uint8")
|
683 |
+
if images.shape[-1] == 1:
|
684 |
+
# special case for grayscale (single channel) images
|
685 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
686 |
+
else:
|
687 |
+
pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
|
688 |
+
|
689 |
+
return pil_images
|
690 |
+
|
691 |
+
@staticmethod
|
692 |
+
def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
693 |
+
"""
|
694 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
695 |
+
"""
|
696 |
+
if not isinstance(images, list):
|
697 |
+
images = [images]
|
698 |
+
|
699 |
+
images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
|
700 |
+
images = np.stack(images, axis=0)
|
701 |
+
return images
|
702 |
+
|
703 |
+
@staticmethod
|
704 |
+
def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
705 |
+
"""
|
706 |
+
Args:
|
707 |
+
image: RGB-like depth image
|
708 |
+
|
709 |
+
Returns: depth map
|
710 |
+
|
711 |
+
"""
|
712 |
+
return image[:, :, 1] * 2**8 + image[:, :, 2]
|
713 |
+
|
714 |
+
def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
|
715 |
+
"""
|
716 |
+
Convert a NumPy depth image or a batch of images to a PIL image.
|
717 |
+
"""
|
718 |
+
if images.ndim == 3:
|
719 |
+
images = images[None, ...]
|
720 |
+
images_depth = images[:, :, :, 3:]
|
721 |
+
if images.shape[-1] == 6:
|
722 |
+
images_depth = (images_depth * 255).round().astype("uint8")
|
723 |
+
pil_images = [
|
724 |
+
Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
|
725 |
+
]
|
726 |
+
elif images.shape[-1] == 4:
|
727 |
+
images_depth = (images_depth * 65535.0).astype(np.uint16)
|
728 |
+
pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
|
729 |
+
else:
|
730 |
+
raise Exception("Not supported")
|
731 |
+
|
732 |
+
return pil_images
|
733 |
+
|
734 |
+
def postprocess(
|
735 |
+
self,
|
736 |
+
image: torch.FloatTensor,
|
737 |
+
output_type: str = "pil",
|
738 |
+
do_denormalize: Optional[List[bool]] = None,
|
739 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
740 |
+
"""
|
741 |
+
Postprocess the image output from tensor to `output_type`.
|
742 |
+
|
743 |
+
Args:
|
744 |
+
image (`torch.FloatTensor`):
|
745 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
746 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
747 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
748 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
749 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
750 |
+
`VaeImageProcessor` config.
|
751 |
+
|
752 |
+
Returns:
|
753 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
754 |
+
The postprocessed image.
|
755 |
+
"""
|
756 |
+
if not isinstance(image, torch.Tensor):
|
757 |
+
raise ValueError(
|
758 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
759 |
+
)
|
760 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
761 |
+
deprecation_message = (
|
762 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
763 |
+
"`pil`, `np`, `pt`, `latent`"
|
764 |
+
)
|
765 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
766 |
+
output_type = "np"
|
767 |
+
|
768 |
+
if do_denormalize is None:
|
769 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
770 |
+
|
771 |
+
image = torch.stack(
|
772 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
773 |
+
)
|
774 |
+
|
775 |
+
image = self.pt_to_numpy(image)
|
776 |
+
|
777 |
+
if output_type == "np":
|
778 |
+
if image.shape[-1] == 6:
|
779 |
+
image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
|
780 |
+
else:
|
781 |
+
image_depth = image[:, :, :, 3:]
|
782 |
+
return image[:, :, :, :3], image_depth
|
783 |
+
|
784 |
+
if output_type == "pil":
|
785 |
+
return self.numpy_to_pil(image), self.numpy_to_depth(image)
|
786 |
+
else:
|
787 |
+
raise Exception(f"This type {output_type} is not supported")
|
788 |
+
|
789 |
+
def preprocess(
|
790 |
+
self,
|
791 |
+
rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
792 |
+
depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
793 |
+
height: Optional[int] = None,
|
794 |
+
width: Optional[int] = None,
|
795 |
+
target_res: Optional[int] = None,
|
796 |
+
) -> torch.Tensor:
|
797 |
+
"""
|
798 |
+
Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
|
799 |
+
"""
|
800 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
801 |
+
|
802 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
803 |
+
if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
|
804 |
+
raise Exception("This is not yet supported")
|
805 |
+
|
806 |
+
if isinstance(rgb, supported_formats):
|
807 |
+
rgb = [rgb]
|
808 |
+
depth = [depth]
|
809 |
+
elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
|
810 |
+
raise ValueError(
|
811 |
+
f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
|
812 |
+
)
|
813 |
+
|
814 |
+
if isinstance(rgb[0], PIL.Image.Image):
|
815 |
+
if self.config.do_convert_rgb:
|
816 |
+
raise Exception("This is not yet supported")
|
817 |
+
# rgb = [self.convert_to_rgb(i) for i in rgb]
|
818 |
+
# depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
|
819 |
+
if self.config.do_resize or target_res:
|
820 |
+
height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
|
821 |
+
rgb = [self.resize(i, height, width) for i in rgb]
|
822 |
+
depth = [self.resize(i, height, width) for i in depth]
|
823 |
+
rgb = self.pil_to_numpy(rgb) # to np
|
824 |
+
rgb = self.numpy_to_pt(rgb) # to pt
|
825 |
+
|
826 |
+
depth = self.depth_pil_to_numpy(depth) # to np
|
827 |
+
depth = self.numpy_to_pt(depth) # to pt
|
828 |
+
|
829 |
+
elif isinstance(rgb[0], np.ndarray):
|
830 |
+
rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
|
831 |
+
rgb = self.numpy_to_pt(rgb)
|
832 |
+
height, width = self.get_default_height_width(rgb, height, width)
|
833 |
+
if self.config.do_resize:
|
834 |
+
rgb = self.resize(rgb, height, width)
|
835 |
+
|
836 |
+
depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
|
837 |
+
depth = self.numpy_to_pt(depth)
|
838 |
+
height, width = self.get_default_height_width(depth, height, width)
|
839 |
+
if self.config.do_resize:
|
840 |
+
depth = self.resize(depth, height, width)
|
841 |
+
|
842 |
+
elif isinstance(rgb[0], torch.Tensor):
|
843 |
+
raise Exception("This is not yet supported")
|
844 |
+
# rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
|
845 |
+
|
846 |
+
# if self.config.do_convert_grayscale and rgb.ndim == 3:
|
847 |
+
# rgb = rgb.unsqueeze(1)
|
848 |
+
|
849 |
+
# channel = rgb.shape[1]
|
850 |
+
|
851 |
+
# height, width = self.get_default_height_width(rgb, height, width)
|
852 |
+
# if self.config.do_resize:
|
853 |
+
# rgb = self.resize(rgb, height, width)
|
854 |
+
|
855 |
+
# depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
|
856 |
+
|
857 |
+
# if self.config.do_convert_grayscale and depth.ndim == 3:
|
858 |
+
# depth = depth.unsqueeze(1)
|
859 |
+
|
860 |
+
# channel = depth.shape[1]
|
861 |
+
# # don't need any preprocess if the image is latents
|
862 |
+
# if depth == 4:
|
863 |
+
# return rgb, depth
|
864 |
+
|
865 |
+
# height, width = self.get_default_height_width(depth, height, width)
|
866 |
+
# if self.config.do_resize:
|
867 |
+
# depth = self.resize(depth, height, width)
|
868 |
+
# expected range [0,1], normalize to [-1,1]
|
869 |
+
do_normalize = self.config.do_normalize
|
870 |
+
if rgb.min() < 0 and do_normalize:
|
871 |
+
warnings.warn(
|
872 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
873 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
|
874 |
+
FutureWarning,
|
875 |
+
)
|
876 |
+
do_normalize = False
|
877 |
+
|
878 |
+
if do_normalize:
|
879 |
+
rgb = self.normalize(rgb)
|
880 |
+
depth = self.normalize(depth)
|
881 |
+
|
882 |
+
if self.config.do_binarize:
|
883 |
+
rgb = self.binarize(rgb)
|
884 |
+
depth = self.binarize(depth)
|
885 |
+
|
886 |
+
return rgb, depth
|
887 |
+
|
888 |
+
|
889 |
+
class IPAdapterMaskProcessor(VaeImageProcessor):
|
890 |
+
"""
|
891 |
+
Image processor for IP Adapter image masks.
|
892 |
+
|
893 |
+
Args:
|
894 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
895 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
|
896 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
897 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
898 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
899 |
+
Resampling filter to use when resizing the image.
|
900 |
+
do_normalize (`bool`, *optional*, defaults to `False`):
|
901 |
+
Whether to normalize the image to [-1,1].
|
902 |
+
do_binarize (`bool`, *optional*, defaults to `True`):
|
903 |
+
Whether to binarize the image to 0/1.
|
904 |
+
do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
|
905 |
+
Whether to convert the images to grayscale format.
|
906 |
+
|
907 |
+
"""
|
908 |
+
|
909 |
+
config_name = CONFIG_NAME
|
910 |
+
|
911 |
+
@register_to_config
|
912 |
+
def __init__(
|
913 |
+
self,
|
914 |
+
do_resize: bool = True,
|
915 |
+
vae_scale_factor: int = 8,
|
916 |
+
resample: str = "lanczos",
|
917 |
+
do_normalize: bool = False,
|
918 |
+
do_binarize: bool = True,
|
919 |
+
do_convert_grayscale: bool = True,
|
920 |
+
):
|
921 |
+
super().__init__(
|
922 |
+
do_resize=do_resize,
|
923 |
+
vae_scale_factor=vae_scale_factor,
|
924 |
+
resample=resample,
|
925 |
+
do_normalize=do_normalize,
|
926 |
+
do_binarize=do_binarize,
|
927 |
+
do_convert_grayscale=do_convert_grayscale,
|
928 |
+
)
|
929 |
+
|
930 |
+
@staticmethod
|
931 |
+
def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
|
932 |
+
"""
|
933 |
+
Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention.
|
934 |
+
If the aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
|
935 |
+
|
936 |
+
Args:
|
937 |
+
mask (`torch.FloatTensor`):
|
938 |
+
The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
|
939 |
+
batch_size (`int`):
|
940 |
+
The batch size.
|
941 |
+
num_queries (`int`):
|
942 |
+
The number of queries.
|
943 |
+
value_embed_dim (`int`):
|
944 |
+
The dimensionality of the value embeddings.
|
945 |
+
|
946 |
+
Returns:
|
947 |
+
`torch.FloatTensor`:
|
948 |
+
The downsampled mask tensor.
|
949 |
+
|
950 |
+
"""
|
951 |
+
o_h = mask.shape[1]
|
952 |
+
o_w = mask.shape[2]
|
953 |
+
ratio = o_w / o_h
|
954 |
+
mask_h = int(math.sqrt(num_queries / ratio))
|
955 |
+
mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
|
956 |
+
mask_w = num_queries // mask_h
|
957 |
+
|
958 |
+
mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
|
959 |
+
|
960 |
+
# Repeat batch_size times
|
961 |
+
if mask_downsample.shape[0] < batch_size:
|
962 |
+
mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
|
963 |
+
|
964 |
+
mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
|
965 |
+
|
966 |
+
downsampled_area = mask_h * mask_w
|
967 |
+
# If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
|
968 |
+
# Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
|
969 |
+
if downsampled_area < num_queries:
|
970 |
+
warnings.warn(
|
971 |
+
"The aspect ratio of the mask does not match the aspect ratio of the output image. "
|
972 |
+
"Please update your masks or adjust the output size for optimal performance.",
|
973 |
+
UserWarning,
|
974 |
+
)
|
975 |
+
mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
|
976 |
+
# Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
|
977 |
+
if downsampled_area > num_queries:
|
978 |
+
warnings.warn(
|
979 |
+
"The aspect ratio of the mask does not match the aspect ratio of the output image. "
|
980 |
+
"Please update your masks or adjust the output size for optimal performance.",
|
981 |
+
UserWarning,
|
982 |
+
)
|
983 |
+
mask_downsample = mask_downsample[:, :num_queries]
|
984 |
+
|
985 |
+
# Repeat last dimension to match SDPA output shape
|
986 |
+
mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
|
987 |
+
1, 1, value_embed_dim
|
988 |
+
)
|
989 |
+
|
990 |
+
return mask_downsample
|
BrushNet/build/lib/diffusers/loaders/__init__.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import TYPE_CHECKING
|
2 |
+
|
3 |
+
from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
|
4 |
+
from ..utils.import_utils import is_peft_available, is_torch_available, is_transformers_available
|
5 |
+
|
6 |
+
|
7 |
+
def text_encoder_lora_state_dict(text_encoder):
|
8 |
+
deprecate(
|
9 |
+
"text_encoder_load_state_dict in `models`",
|
10 |
+
"0.27.0",
|
11 |
+
"`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
|
12 |
+
)
|
13 |
+
state_dict = {}
|
14 |
+
|
15 |
+
for name, module in text_encoder_attn_modules(text_encoder):
|
16 |
+
for k, v in module.q_proj.lora_linear_layer.state_dict().items():
|
17 |
+
state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
|
18 |
+
|
19 |
+
for k, v in module.k_proj.lora_linear_layer.state_dict().items():
|
20 |
+
state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
|
21 |
+
|
22 |
+
for k, v in module.v_proj.lora_linear_layer.state_dict().items():
|
23 |
+
state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
|
24 |
+
|
25 |
+
for k, v in module.out_proj.lora_linear_layer.state_dict().items():
|
26 |
+
state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
|
27 |
+
|
28 |
+
return state_dict
|
29 |
+
|
30 |
+
|
31 |
+
if is_transformers_available():
|
32 |
+
|
33 |
+
def text_encoder_attn_modules(text_encoder):
|
34 |
+
deprecate(
|
35 |
+
"text_encoder_attn_modules in `models`",
|
36 |
+
"0.27.0",
|
37 |
+
"`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
|
38 |
+
)
|
39 |
+
from transformers import CLIPTextModel, CLIPTextModelWithProjection
|
40 |
+
|
41 |
+
attn_modules = []
|
42 |
+
|
43 |
+
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
|
44 |
+
for i, layer in enumerate(text_encoder.text_model.encoder.layers):
|
45 |
+
name = f"text_model.encoder.layers.{i}.self_attn"
|
46 |
+
mod = layer.self_attn
|
47 |
+
attn_modules.append((name, mod))
|
48 |
+
else:
|
49 |
+
raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
|
50 |
+
|
51 |
+
return attn_modules
|
52 |
+
|
53 |
+
|
54 |
+
_import_structure = {}
|
55 |
+
|
56 |
+
if is_torch_available():
|
57 |
+
_import_structure["autoencoder"] = ["FromOriginalVAEMixin"]
|
58 |
+
|
59 |
+
_import_structure["controlnet"] = ["FromOriginalControlNetMixin"]
|
60 |
+
_import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
|
61 |
+
_import_structure["utils"] = ["AttnProcsLayers"]
|
62 |
+
if is_transformers_available():
|
63 |
+
_import_structure["single_file"] = ["FromSingleFileMixin"]
|
64 |
+
_import_structure["lora"] = ["LoraLoaderMixin", "StableDiffusionXLLoraLoaderMixin"]
|
65 |
+
_import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
|
66 |
+
_import_structure["ip_adapter"] = ["IPAdapterMixin"]
|
67 |
+
|
68 |
+
_import_structure["peft"] = ["PeftAdapterMixin"]
|
69 |
+
|
70 |
+
|
71 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
72 |
+
if is_torch_available():
|
73 |
+
from .autoencoder import FromOriginalVAEMixin
|
74 |
+
from .controlnet import FromOriginalControlNetMixin
|
75 |
+
from .unet import UNet2DConditionLoadersMixin
|
76 |
+
from .utils import AttnProcsLayers
|
77 |
+
|
78 |
+
if is_transformers_available():
|
79 |
+
from .ip_adapter import IPAdapterMixin
|
80 |
+
from .lora import LoraLoaderMixin, StableDiffusionXLLoraLoaderMixin
|
81 |
+
from .single_file import FromSingleFileMixin
|
82 |
+
from .textual_inversion import TextualInversionLoaderMixin
|
83 |
+
|
84 |
+
from .peft import PeftAdapterMixin
|
85 |
+
else:
|
86 |
+
import sys
|
87 |
+
|
88 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
BrushNet/build/lib/diffusers/loaders/autoencoder.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
16 |
+
|
17 |
+
from .single_file_utils import (
|
18 |
+
create_diffusers_vae_model_from_ldm,
|
19 |
+
fetch_ldm_config_and_checkpoint,
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
class FromOriginalVAEMixin:
|
24 |
+
"""
|
25 |
+
Load pretrained AutoencoderKL weights saved in the `.ckpt` or `.safetensors` format into a [`AutoencoderKL`].
|
26 |
+
"""
|
27 |
+
|
28 |
+
@classmethod
|
29 |
+
@validate_hf_hub_args
|
30 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
31 |
+
r"""
|
32 |
+
Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
33 |
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
34 |
+
|
35 |
+
Parameters:
|
36 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
37 |
+
Can be either:
|
38 |
+
- A link to the `.ckpt` file (for example
|
39 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
40 |
+
- A path to a *file* containing all pipeline weights.
|
41 |
+
config_file (`str`, *optional*):
|
42 |
+
Filepath to the configuration YAML file associated with the model. If not provided it will default to:
|
43 |
+
https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
|
44 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
45 |
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
46 |
+
dtype is automatically derived from the model's weights.
|
47 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
48 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
49 |
+
cached versions if they exist.
|
50 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
51 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
52 |
+
is not used.
|
53 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
54 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
55 |
+
incompletely downloaded files are deleted.
|
56 |
+
proxies (`Dict[str, str]`, *optional*):
|
57 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
58 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
59 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
60 |
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
61 |
+
won't be downloaded from the Hub.
|
62 |
+
token (`str` or *bool*, *optional*):
|
63 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
64 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
65 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
66 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
67 |
+
allowed by Git.
|
68 |
+
image_size (`int`, *optional*, defaults to 512):
|
69 |
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
70 |
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
71 |
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
72 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
73 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
74 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
75 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
|
76 |
+
= 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
|
77 |
+
Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
78 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
79 |
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
80 |
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
81 |
+
method. See example below for more information.
|
82 |
+
|
83 |
+
<Tip warning={true}>
|
84 |
+
|
85 |
+
Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
|
86 |
+
a VAE from SDXL or a Stable Diffusion v2 model or higher.
|
87 |
+
|
88 |
+
</Tip>
|
89 |
+
|
90 |
+
Examples:
|
91 |
+
|
92 |
+
```py
|
93 |
+
from diffusers import AutoencoderKL
|
94 |
+
|
95 |
+
url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
|
96 |
+
model = AutoencoderKL.from_single_file(url)
|
97 |
+
```
|
98 |
+
"""
|
99 |
+
|
100 |
+
original_config_file = kwargs.pop("original_config_file", None)
|
101 |
+
config_file = kwargs.pop("config_file", None)
|
102 |
+
resume_download = kwargs.pop("resume_download", False)
|
103 |
+
force_download = kwargs.pop("force_download", False)
|
104 |
+
proxies = kwargs.pop("proxies", None)
|
105 |
+
token = kwargs.pop("token", None)
|
106 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
107 |
+
local_files_only = kwargs.pop("local_files_only", None)
|
108 |
+
revision = kwargs.pop("revision", None)
|
109 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
110 |
+
|
111 |
+
class_name = cls.__name__
|
112 |
+
|
113 |
+
if (config_file is not None) and (original_config_file is not None):
|
114 |
+
raise ValueError(
|
115 |
+
"You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
|
116 |
+
)
|
117 |
+
|
118 |
+
original_config_file = original_config_file or config_file
|
119 |
+
original_config, checkpoint = fetch_ldm_config_and_checkpoint(
|
120 |
+
pretrained_model_link_or_path=pretrained_model_link_or_path,
|
121 |
+
class_name=class_name,
|
122 |
+
original_config_file=original_config_file,
|
123 |
+
resume_download=resume_download,
|
124 |
+
force_download=force_download,
|
125 |
+
proxies=proxies,
|
126 |
+
token=token,
|
127 |
+
revision=revision,
|
128 |
+
local_files_only=local_files_only,
|
129 |
+
cache_dir=cache_dir,
|
130 |
+
)
|
131 |
+
|
132 |
+
image_size = kwargs.pop("image_size", None)
|
133 |
+
scaling_factor = kwargs.pop("scaling_factor", None)
|
134 |
+
component = create_diffusers_vae_model_from_ldm(
|
135 |
+
class_name,
|
136 |
+
original_config,
|
137 |
+
checkpoint,
|
138 |
+
image_size=image_size,
|
139 |
+
scaling_factor=scaling_factor,
|
140 |
+
torch_dtype=torch_dtype,
|
141 |
+
)
|
142 |
+
vae = component["vae"]
|
143 |
+
if torch_dtype is not None:
|
144 |
+
vae = vae.to(torch_dtype)
|
145 |
+
|
146 |
+
return vae
|
BrushNet/build/lib/diffusers/loaders/controlnet.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
16 |
+
|
17 |
+
from .single_file_utils import (
|
18 |
+
create_diffusers_controlnet_model_from_ldm,
|
19 |
+
fetch_ldm_config_and_checkpoint,
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
class FromOriginalControlNetMixin:
|
24 |
+
"""
|
25 |
+
Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
|
26 |
+
"""
|
27 |
+
|
28 |
+
@classmethod
|
29 |
+
@validate_hf_hub_args
|
30 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
31 |
+
r"""
|
32 |
+
Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
33 |
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
34 |
+
|
35 |
+
Parameters:
|
36 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
37 |
+
Can be either:
|
38 |
+
- A link to the `.ckpt` file (for example
|
39 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
40 |
+
- A path to a *file* containing all pipeline weights.
|
41 |
+
config_file (`str`, *optional*):
|
42 |
+
Filepath to the configuration YAML file associated with the model. If not provided it will default to:
|
43 |
+
https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml
|
44 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
45 |
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
46 |
+
dtype is automatically derived from the model's weights.
|
47 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
48 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
49 |
+
cached versions if they exist.
|
50 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
51 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
52 |
+
is not used.
|
53 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
54 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
55 |
+
incompletely downloaded files are deleted.
|
56 |
+
proxies (`Dict[str, str]`, *optional*):
|
57 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
58 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
59 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
60 |
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
61 |
+
won't be downloaded from the Hub.
|
62 |
+
token (`str` or *bool*, *optional*):
|
63 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
64 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
65 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
66 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
67 |
+
allowed by Git.
|
68 |
+
image_size (`int`, *optional*, defaults to 512):
|
69 |
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
70 |
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
71 |
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
72 |
+
Whether the attention computation should always be upcasted.
|
73 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
74 |
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
75 |
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
76 |
+
method. See example below for more information.
|
77 |
+
|
78 |
+
Examples:
|
79 |
+
|
80 |
+
```py
|
81 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
82 |
+
|
83 |
+
url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
|
84 |
+
model = ControlNetModel.from_single_file(url)
|
85 |
+
|
86 |
+
url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
|
87 |
+
pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
|
88 |
+
```
|
89 |
+
"""
|
90 |
+
original_config_file = kwargs.pop("original_config_file", None)
|
91 |
+
config_file = kwargs.pop("config_file", None)
|
92 |
+
resume_download = kwargs.pop("resume_download", False)
|
93 |
+
force_download = kwargs.pop("force_download", False)
|
94 |
+
proxies = kwargs.pop("proxies", None)
|
95 |
+
token = kwargs.pop("token", None)
|
96 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
97 |
+
local_files_only = kwargs.pop("local_files_only", None)
|
98 |
+
revision = kwargs.pop("revision", None)
|
99 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
100 |
+
|
101 |
+
class_name = cls.__name__
|
102 |
+
if (config_file is not None) and (original_config_file is not None):
|
103 |
+
raise ValueError(
|
104 |
+
"You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
|
105 |
+
)
|
106 |
+
|
107 |
+
original_config_file = config_file or original_config_file
|
108 |
+
original_config, checkpoint = fetch_ldm_config_and_checkpoint(
|
109 |
+
pretrained_model_link_or_path=pretrained_model_link_or_path,
|
110 |
+
class_name=class_name,
|
111 |
+
original_config_file=original_config_file,
|
112 |
+
resume_download=resume_download,
|
113 |
+
force_download=force_download,
|
114 |
+
proxies=proxies,
|
115 |
+
token=token,
|
116 |
+
revision=revision,
|
117 |
+
local_files_only=local_files_only,
|
118 |
+
cache_dir=cache_dir,
|
119 |
+
)
|
120 |
+
|
121 |
+
upcast_attention = kwargs.pop("upcast_attention", False)
|
122 |
+
image_size = kwargs.pop("image_size", None)
|
123 |
+
|
124 |
+
component = create_diffusers_controlnet_model_from_ldm(
|
125 |
+
class_name,
|
126 |
+
original_config,
|
127 |
+
checkpoint,
|
128 |
+
upcast_attention=upcast_attention,
|
129 |
+
image_size=image_size,
|
130 |
+
torch_dtype=torch_dtype,
|
131 |
+
)
|
132 |
+
controlnet = component["controlnet"]
|
133 |
+
if torch_dtype is not None:
|
134 |
+
controlnet = controlnet.to(torch_dtype)
|
135 |
+
|
136 |
+
return controlnet
|
BrushNet/build/lib/diffusers/loaders/ip_adapter.py
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from pathlib import Path
|
16 |
+
from typing import Dict, List, Optional, Union
|
17 |
+
|
18 |
+
import torch
|
19 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
20 |
+
from safetensors import safe_open
|
21 |
+
|
22 |
+
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
|
23 |
+
from ..utils import (
|
24 |
+
_get_model_file,
|
25 |
+
is_accelerate_available,
|
26 |
+
is_torch_version,
|
27 |
+
is_transformers_available,
|
28 |
+
logging,
|
29 |
+
)
|
30 |
+
|
31 |
+
|
32 |
+
if is_transformers_available():
|
33 |
+
from transformers import (
|
34 |
+
CLIPImageProcessor,
|
35 |
+
CLIPVisionModelWithProjection,
|
36 |
+
)
|
37 |
+
|
38 |
+
from ..models.attention_processor import (
|
39 |
+
IPAdapterAttnProcessor,
|
40 |
+
IPAdapterAttnProcessor2_0,
|
41 |
+
)
|
42 |
+
|
43 |
+
logger = logging.get_logger(__name__)
|
44 |
+
|
45 |
+
|
46 |
+
class IPAdapterMixin:
|
47 |
+
"""Mixin for handling IP Adapters."""
|
48 |
+
|
49 |
+
@validate_hf_hub_args
|
50 |
+
def load_ip_adapter(
|
51 |
+
self,
|
52 |
+
pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]],
|
53 |
+
subfolder: Union[str, List[str]],
|
54 |
+
weight_name: Union[str, List[str]],
|
55 |
+
image_encoder_folder: Optional[str] = "image_encoder",
|
56 |
+
**kwargs,
|
57 |
+
):
|
58 |
+
"""
|
59 |
+
Parameters:
|
60 |
+
pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
|
61 |
+
Can be either:
|
62 |
+
|
63 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
64 |
+
the Hub.
|
65 |
+
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
|
66 |
+
with [`ModelMixin.save_pretrained`].
|
67 |
+
- A [torch state
|
68 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
69 |
+
subfolder (`str` or `List[str]`):
|
70 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
71 |
+
If a list is passed, it should have the same length as `weight_name`.
|
72 |
+
weight_name (`str` or `List[str]`):
|
73 |
+
The name of the weight file to load. If a list is passed, it should have the same length as
|
74 |
+
`weight_name`.
|
75 |
+
image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
|
76 |
+
The subfolder location of the image encoder within a larger model repository on the Hub or locally.
|
77 |
+
Pass `None` to not load the image encoder. If the image encoder is located in a folder inside `subfolder`,
|
78 |
+
you only need to pass the name of the folder that contains image encoder weights, e.g. `image_encoder_folder="image_encoder"`.
|
79 |
+
If the image encoder is located in a folder other than `subfolder`, you should pass the path to the folder that contains image encoder weights,
|
80 |
+
for example, `image_encoder_folder="different_subfolder/image_encoder"`.
|
81 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
82 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
83 |
+
is not used.
|
84 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
85 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
86 |
+
cached versions if they exist.
|
87 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
88 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
89 |
+
incompletely downloaded files are deleted.
|
90 |
+
proxies (`Dict[str, str]`, *optional*):
|
91 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
92 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
93 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
94 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
95 |
+
won't be downloaded from the Hub.
|
96 |
+
token (`str` or *bool*, *optional*):
|
97 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
98 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
99 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
100 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
101 |
+
allowed by Git.
|
102 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
103 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
104 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
105 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
106 |
+
argument to `True` will raise an error.
|
107 |
+
"""
|
108 |
+
|
109 |
+
# handle the list inputs for multiple IP Adapters
|
110 |
+
if not isinstance(weight_name, list):
|
111 |
+
weight_name = [weight_name]
|
112 |
+
|
113 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, list):
|
114 |
+
pretrained_model_name_or_path_or_dict = [pretrained_model_name_or_path_or_dict]
|
115 |
+
if len(pretrained_model_name_or_path_or_dict) == 1:
|
116 |
+
pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict * len(weight_name)
|
117 |
+
|
118 |
+
if not isinstance(subfolder, list):
|
119 |
+
subfolder = [subfolder]
|
120 |
+
if len(subfolder) == 1:
|
121 |
+
subfolder = subfolder * len(weight_name)
|
122 |
+
|
123 |
+
if len(weight_name) != len(pretrained_model_name_or_path_or_dict):
|
124 |
+
raise ValueError("`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.")
|
125 |
+
|
126 |
+
if len(weight_name) != len(subfolder):
|
127 |
+
raise ValueError("`weight_name` and `subfolder` must have the same length.")
|
128 |
+
|
129 |
+
# Load the main state dict first.
|
130 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
131 |
+
force_download = kwargs.pop("force_download", False)
|
132 |
+
resume_download = kwargs.pop("resume_download", False)
|
133 |
+
proxies = kwargs.pop("proxies", None)
|
134 |
+
local_files_only = kwargs.pop("local_files_only", None)
|
135 |
+
token = kwargs.pop("token", None)
|
136 |
+
revision = kwargs.pop("revision", None)
|
137 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
138 |
+
|
139 |
+
if low_cpu_mem_usage and not is_accelerate_available():
|
140 |
+
low_cpu_mem_usage = False
|
141 |
+
logger.warning(
|
142 |
+
"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
|
143 |
+
" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
|
144 |
+
" `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
|
145 |
+
" install accelerate\n```\n."
|
146 |
+
)
|
147 |
+
|
148 |
+
if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
|
149 |
+
raise NotImplementedError(
|
150 |
+
"Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
|
151 |
+
" `low_cpu_mem_usage=False`."
|
152 |
+
)
|
153 |
+
|
154 |
+
user_agent = {
|
155 |
+
"file_type": "attn_procs_weights",
|
156 |
+
"framework": "pytorch",
|
157 |
+
}
|
158 |
+
state_dicts = []
|
159 |
+
for pretrained_model_name_or_path_or_dict, weight_name, subfolder in zip(
|
160 |
+
pretrained_model_name_or_path_or_dict, weight_name, subfolder
|
161 |
+
):
|
162 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
163 |
+
model_file = _get_model_file(
|
164 |
+
pretrained_model_name_or_path_or_dict,
|
165 |
+
weights_name=weight_name,
|
166 |
+
cache_dir=cache_dir,
|
167 |
+
force_download=force_download,
|
168 |
+
resume_download=resume_download,
|
169 |
+
proxies=proxies,
|
170 |
+
local_files_only=local_files_only,
|
171 |
+
token=token,
|
172 |
+
revision=revision,
|
173 |
+
subfolder=subfolder,
|
174 |
+
user_agent=user_agent,
|
175 |
+
)
|
176 |
+
if weight_name.endswith(".safetensors"):
|
177 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
178 |
+
with safe_open(model_file, framework="pt", device="cpu") as f:
|
179 |
+
for key in f.keys():
|
180 |
+
if key.startswith("image_proj."):
|
181 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
182 |
+
elif key.startswith("ip_adapter."):
|
183 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
184 |
+
else:
|
185 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
186 |
+
else:
|
187 |
+
state_dict = pretrained_model_name_or_path_or_dict
|
188 |
+
|
189 |
+
keys = list(state_dict.keys())
|
190 |
+
if keys != ["image_proj", "ip_adapter"]:
|
191 |
+
raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
|
192 |
+
|
193 |
+
state_dicts.append(state_dict)
|
194 |
+
|
195 |
+
# load CLIP image encoder here if it has not been registered to the pipeline yet
|
196 |
+
if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
|
197 |
+
if image_encoder_folder is not None:
|
198 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
199 |
+
logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
|
200 |
+
if image_encoder_folder.count("/") == 0:
|
201 |
+
image_encoder_subfolder = Path(subfolder, image_encoder_folder).as_posix()
|
202 |
+
else:
|
203 |
+
image_encoder_subfolder = Path(image_encoder_folder).as_posix()
|
204 |
+
|
205 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
206 |
+
pretrained_model_name_or_path_or_dict,
|
207 |
+
subfolder=image_encoder_subfolder,
|
208 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
209 |
+
).to(self.device, dtype=self.dtype)
|
210 |
+
self.register_modules(image_encoder=image_encoder)
|
211 |
+
else:
|
212 |
+
raise ValueError(
|
213 |
+
"`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict."
|
214 |
+
)
|
215 |
+
else:
|
216 |
+
logger.warning(
|
217 |
+
"image_encoder is not loaded since `image_encoder_folder=None` passed. You will not be able to use `ip_adapter_image` when calling the pipeline with IP-Adapter."
|
218 |
+
"Use `ip_adapter_image_embeds` to pass pre-generated image embedding instead."
|
219 |
+
)
|
220 |
+
|
221 |
+
# create feature extractor if it has not been registered to the pipeline yet
|
222 |
+
if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
|
223 |
+
feature_extractor = CLIPImageProcessor()
|
224 |
+
self.register_modules(feature_extractor=feature_extractor)
|
225 |
+
|
226 |
+
# load ip-adapter into unet
|
227 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
228 |
+
unet._load_ip_adapter_weights(state_dicts, low_cpu_mem_usage=low_cpu_mem_usage)
|
229 |
+
|
230 |
+
def set_ip_adapter_scale(self, scale):
|
231 |
+
"""
|
232 |
+
Sets the conditioning scale between text and image.
|
233 |
+
|
234 |
+
Example:
|
235 |
+
|
236 |
+
```py
|
237 |
+
pipeline.set_ip_adapter_scale(0.5)
|
238 |
+
```
|
239 |
+
"""
|
240 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
241 |
+
for attn_processor in unet.attn_processors.values():
|
242 |
+
if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
|
243 |
+
if not isinstance(scale, list):
|
244 |
+
scale = [scale] * len(attn_processor.scale)
|
245 |
+
if len(attn_processor.scale) != len(scale):
|
246 |
+
raise ValueError(
|
247 |
+
f"`scale` should be a list of same length as the number if ip-adapters "
|
248 |
+
f"Expected {len(attn_processor.scale)} but got {len(scale)}."
|
249 |
+
)
|
250 |
+
attn_processor.scale = scale
|
251 |
+
|
252 |
+
def unload_ip_adapter(self):
|
253 |
+
"""
|
254 |
+
Unloads the IP Adapter weights
|
255 |
+
|
256 |
+
Examples:
|
257 |
+
|
258 |
+
```python
|
259 |
+
>>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
|
260 |
+
>>> pipeline.unload_ip_adapter()
|
261 |
+
>>> ...
|
262 |
+
```
|
263 |
+
"""
|
264 |
+
# remove CLIP image encoder
|
265 |
+
if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is not None:
|
266 |
+
self.image_encoder = None
|
267 |
+
self.register_to_config(image_encoder=[None, None])
|
268 |
+
|
269 |
+
# remove feature extractor only when safety_checker is None as safety_checker uses
|
270 |
+
# the feature_extractor later
|
271 |
+
if not hasattr(self, "safety_checker"):
|
272 |
+
if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is not None:
|
273 |
+
self.feature_extractor = None
|
274 |
+
self.register_to_config(feature_extractor=[None, None])
|
275 |
+
|
276 |
+
# remove hidden encoder
|
277 |
+
self.unet.encoder_hid_proj = None
|
278 |
+
self.config.encoder_hid_dim_type = None
|
279 |
+
|
280 |
+
# restore original Unet attention processors layers
|
281 |
+
self.unet.set_default_attn_processor()
|
BrushNet/build/lib/diffusers/loaders/lora.py
ADDED
@@ -0,0 +1,1349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
import inspect
|
15 |
+
import os
|
16 |
+
from pathlib import Path
|
17 |
+
from typing import Callable, Dict, List, Optional, Union
|
18 |
+
|
19 |
+
import safetensors
|
20 |
+
import torch
|
21 |
+
from huggingface_hub import model_info
|
22 |
+
from huggingface_hub.constants import HF_HUB_OFFLINE
|
23 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
24 |
+
from packaging import version
|
25 |
+
from torch import nn
|
26 |
+
|
27 |
+
from .. import __version__
|
28 |
+
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
|
29 |
+
from ..utils import (
|
30 |
+
USE_PEFT_BACKEND,
|
31 |
+
_get_model_file,
|
32 |
+
convert_state_dict_to_diffusers,
|
33 |
+
convert_state_dict_to_peft,
|
34 |
+
convert_unet_state_dict_to_peft,
|
35 |
+
delete_adapter_layers,
|
36 |
+
get_adapter_name,
|
37 |
+
get_peft_kwargs,
|
38 |
+
is_accelerate_available,
|
39 |
+
is_transformers_available,
|
40 |
+
logging,
|
41 |
+
recurse_remove_peft_layers,
|
42 |
+
scale_lora_layers,
|
43 |
+
set_adapter_layers,
|
44 |
+
set_weights_and_activate_adapters,
|
45 |
+
)
|
46 |
+
from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
|
47 |
+
|
48 |
+
|
49 |
+
if is_transformers_available():
|
50 |
+
from transformers import PreTrainedModel
|
51 |
+
|
52 |
+
from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
|
53 |
+
|
54 |
+
if is_accelerate_available():
|
55 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
56 |
+
|
57 |
+
logger = logging.get_logger(__name__)
|
58 |
+
|
59 |
+
TEXT_ENCODER_NAME = "text_encoder"
|
60 |
+
UNET_NAME = "unet"
|
61 |
+
TRANSFORMER_NAME = "transformer"
|
62 |
+
|
63 |
+
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
|
64 |
+
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
|
65 |
+
|
66 |
+
LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
|
67 |
+
|
68 |
+
|
69 |
+
class LoraLoaderMixin:
|
70 |
+
r"""
|
71 |
+
Load LoRA layers into [`UNet2DConditionModel`] and
|
72 |
+
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
|
73 |
+
"""
|
74 |
+
|
75 |
+
text_encoder_name = TEXT_ENCODER_NAME
|
76 |
+
unet_name = UNET_NAME
|
77 |
+
transformer_name = TRANSFORMER_NAME
|
78 |
+
num_fused_loras = 0
|
79 |
+
|
80 |
+
def load_lora_weights(
|
81 |
+
self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
|
82 |
+
):
|
83 |
+
"""
|
84 |
+
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
85 |
+
`self.text_encoder`.
|
86 |
+
|
87 |
+
All kwargs are forwarded to `self.lora_state_dict`.
|
88 |
+
|
89 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
90 |
+
|
91 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
92 |
+
`self.unet`.
|
93 |
+
|
94 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
95 |
+
into `self.text_encoder`.
|
96 |
+
|
97 |
+
Parameters:
|
98 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
99 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
100 |
+
kwargs (`dict`, *optional*):
|
101 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
102 |
+
adapter_name (`str`, *optional*):
|
103 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
104 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
105 |
+
"""
|
106 |
+
if not USE_PEFT_BACKEND:
|
107 |
+
raise ValueError("PEFT backend is required for this method.")
|
108 |
+
|
109 |
+
# if a dict is passed, copy it instead of modifying it inplace
|
110 |
+
if isinstance(pretrained_model_name_or_path_or_dict, dict):
|
111 |
+
pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
|
112 |
+
|
113 |
+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
114 |
+
state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
|
115 |
+
|
116 |
+
is_correct_format = all("lora" in key for key in state_dict.keys())
|
117 |
+
if not is_correct_format:
|
118 |
+
raise ValueError("Invalid LoRA checkpoint.")
|
119 |
+
|
120 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
121 |
+
|
122 |
+
self.load_lora_into_unet(
|
123 |
+
state_dict,
|
124 |
+
network_alphas=network_alphas,
|
125 |
+
unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
|
126 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
127 |
+
adapter_name=adapter_name,
|
128 |
+
_pipeline=self,
|
129 |
+
)
|
130 |
+
self.load_lora_into_text_encoder(
|
131 |
+
state_dict,
|
132 |
+
network_alphas=network_alphas,
|
133 |
+
text_encoder=getattr(self, self.text_encoder_name)
|
134 |
+
if not hasattr(self, "text_encoder")
|
135 |
+
else self.text_encoder,
|
136 |
+
lora_scale=self.lora_scale,
|
137 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
138 |
+
adapter_name=adapter_name,
|
139 |
+
_pipeline=self,
|
140 |
+
)
|
141 |
+
|
142 |
+
@classmethod
|
143 |
+
@validate_hf_hub_args
|
144 |
+
def lora_state_dict(
|
145 |
+
cls,
|
146 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
147 |
+
**kwargs,
|
148 |
+
):
|
149 |
+
r"""
|
150 |
+
Return state dict for lora weights and the network alphas.
|
151 |
+
|
152 |
+
<Tip warning={true}>
|
153 |
+
|
154 |
+
We support loading A1111 formatted LoRA checkpoints in a limited capacity.
|
155 |
+
|
156 |
+
This function is experimental and might change in the future.
|
157 |
+
|
158 |
+
</Tip>
|
159 |
+
|
160 |
+
Parameters:
|
161 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
162 |
+
Can be either:
|
163 |
+
|
164 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
165 |
+
the Hub.
|
166 |
+
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
|
167 |
+
with [`ModelMixin.save_pretrained`].
|
168 |
+
- A [torch state
|
169 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
170 |
+
|
171 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
172 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
173 |
+
is not used.
|
174 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
175 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
176 |
+
cached versions if they exist.
|
177 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
178 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
179 |
+
incompletely downloaded files are deleted.
|
180 |
+
proxies (`Dict[str, str]`, *optional*):
|
181 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
182 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
183 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
184 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
185 |
+
won't be downloaded from the Hub.
|
186 |
+
token (`str` or *bool*, *optional*):
|
187 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
188 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
189 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
190 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
191 |
+
allowed by Git.
|
192 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
193 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
194 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
195 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
196 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
197 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
198 |
+
argument to `True` will raise an error.
|
199 |
+
mirror (`str`, *optional*):
|
200 |
+
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
201 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
202 |
+
information.
|
203 |
+
|
204 |
+
"""
|
205 |
+
# Load the main state dict first which has the LoRA layers for either of
|
206 |
+
# UNet and text encoder or both.
|
207 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
208 |
+
force_download = kwargs.pop("force_download", False)
|
209 |
+
resume_download = kwargs.pop("resume_download", False)
|
210 |
+
proxies = kwargs.pop("proxies", None)
|
211 |
+
local_files_only = kwargs.pop("local_files_only", None)
|
212 |
+
token = kwargs.pop("token", None)
|
213 |
+
revision = kwargs.pop("revision", None)
|
214 |
+
subfolder = kwargs.pop("subfolder", None)
|
215 |
+
weight_name = kwargs.pop("weight_name", None)
|
216 |
+
unet_config = kwargs.pop("unet_config", None)
|
217 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
218 |
+
|
219 |
+
allow_pickle = False
|
220 |
+
if use_safetensors is None:
|
221 |
+
use_safetensors = True
|
222 |
+
allow_pickle = True
|
223 |
+
|
224 |
+
user_agent = {
|
225 |
+
"file_type": "attn_procs_weights",
|
226 |
+
"framework": "pytorch",
|
227 |
+
}
|
228 |
+
|
229 |
+
model_file = None
|
230 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
231 |
+
# Let's first try to load .safetensors weights
|
232 |
+
if (use_safetensors and weight_name is None) or (
|
233 |
+
weight_name is not None and weight_name.endswith(".safetensors")
|
234 |
+
):
|
235 |
+
try:
|
236 |
+
# Here we're relaxing the loading check to enable more Inference API
|
237 |
+
# friendliness where sometimes, it's not at all possible to automatically
|
238 |
+
# determine `weight_name`.
|
239 |
+
if weight_name is None:
|
240 |
+
weight_name = cls._best_guess_weight_name(
|
241 |
+
pretrained_model_name_or_path_or_dict,
|
242 |
+
file_extension=".safetensors",
|
243 |
+
local_files_only=local_files_only,
|
244 |
+
)
|
245 |
+
model_file = _get_model_file(
|
246 |
+
pretrained_model_name_or_path_or_dict,
|
247 |
+
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
248 |
+
cache_dir=cache_dir,
|
249 |
+
force_download=force_download,
|
250 |
+
resume_download=resume_download,
|
251 |
+
proxies=proxies,
|
252 |
+
local_files_only=local_files_only,
|
253 |
+
token=token,
|
254 |
+
revision=revision,
|
255 |
+
subfolder=subfolder,
|
256 |
+
user_agent=user_agent,
|
257 |
+
)
|
258 |
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
259 |
+
except (IOError, safetensors.SafetensorError) as e:
|
260 |
+
if not allow_pickle:
|
261 |
+
raise e
|
262 |
+
# try loading non-safetensors weights
|
263 |
+
model_file = None
|
264 |
+
pass
|
265 |
+
|
266 |
+
if model_file is None:
|
267 |
+
if weight_name is None:
|
268 |
+
weight_name = cls._best_guess_weight_name(
|
269 |
+
pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
|
270 |
+
)
|
271 |
+
model_file = _get_model_file(
|
272 |
+
pretrained_model_name_or_path_or_dict,
|
273 |
+
weights_name=weight_name or LORA_WEIGHT_NAME,
|
274 |
+
cache_dir=cache_dir,
|
275 |
+
force_download=force_download,
|
276 |
+
resume_download=resume_download,
|
277 |
+
proxies=proxies,
|
278 |
+
local_files_only=local_files_only,
|
279 |
+
token=token,
|
280 |
+
revision=revision,
|
281 |
+
subfolder=subfolder,
|
282 |
+
user_agent=user_agent,
|
283 |
+
)
|
284 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
285 |
+
else:
|
286 |
+
state_dict = pretrained_model_name_or_path_or_dict
|
287 |
+
|
288 |
+
network_alphas = None
|
289 |
+
# TODO: replace it with a method from `state_dict_utils`
|
290 |
+
if all(
|
291 |
+
(
|
292 |
+
k.startswith("lora_te_")
|
293 |
+
or k.startswith("lora_unet_")
|
294 |
+
or k.startswith("lora_te1_")
|
295 |
+
or k.startswith("lora_te2_")
|
296 |
+
)
|
297 |
+
for k in state_dict.keys()
|
298 |
+
):
|
299 |
+
# Map SDXL blocks correctly.
|
300 |
+
if unet_config is not None:
|
301 |
+
# use unet config to remap block numbers
|
302 |
+
state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
|
303 |
+
state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
|
304 |
+
|
305 |
+
return state_dict, network_alphas
|
306 |
+
|
307 |
+
@classmethod
|
308 |
+
def _best_guess_weight_name(
|
309 |
+
cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
|
310 |
+
):
|
311 |
+
if local_files_only or HF_HUB_OFFLINE:
|
312 |
+
raise ValueError("When using the offline mode, you must specify a `weight_name`.")
|
313 |
+
|
314 |
+
targeted_files = []
|
315 |
+
|
316 |
+
if os.path.isfile(pretrained_model_name_or_path_or_dict):
|
317 |
+
return
|
318 |
+
elif os.path.isdir(pretrained_model_name_or_path_or_dict):
|
319 |
+
targeted_files = [
|
320 |
+
f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
|
321 |
+
]
|
322 |
+
else:
|
323 |
+
files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
|
324 |
+
targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
|
325 |
+
if len(targeted_files) == 0:
|
326 |
+
return
|
327 |
+
|
328 |
+
# "scheduler" does not correspond to a LoRA checkpoint.
|
329 |
+
# "optimizer" does not correspond to a LoRA checkpoint
|
330 |
+
# only top-level checkpoints are considered and not the other ones, hence "checkpoint".
|
331 |
+
unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
|
332 |
+
targeted_files = list(
|
333 |
+
filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
|
334 |
+
)
|
335 |
+
|
336 |
+
if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
|
337 |
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
|
338 |
+
elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
|
339 |
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
|
340 |
+
|
341 |
+
if len(targeted_files) > 1:
|
342 |
+
raise ValueError(
|
343 |
+
f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
|
344 |
+
)
|
345 |
+
weight_name = targeted_files[0]
|
346 |
+
return weight_name
|
347 |
+
|
348 |
+
@classmethod
|
349 |
+
def _optionally_disable_offloading(cls, _pipeline):
|
350 |
+
"""
|
351 |
+
Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
|
352 |
+
|
353 |
+
Args:
|
354 |
+
_pipeline (`DiffusionPipeline`):
|
355 |
+
The pipeline to disable offloading for.
|
356 |
+
|
357 |
+
Returns:
|
358 |
+
tuple:
|
359 |
+
A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
|
360 |
+
"""
|
361 |
+
is_model_cpu_offload = False
|
362 |
+
is_sequential_cpu_offload = False
|
363 |
+
|
364 |
+
if _pipeline is not None:
|
365 |
+
for _, component in _pipeline.components.items():
|
366 |
+
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
367 |
+
if not is_model_cpu_offload:
|
368 |
+
is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
|
369 |
+
if not is_sequential_cpu_offload:
|
370 |
+
is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
|
371 |
+
|
372 |
+
logger.info(
|
373 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
374 |
+
)
|
375 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
376 |
+
|
377 |
+
return (is_model_cpu_offload, is_sequential_cpu_offload)
|
378 |
+
|
379 |
+
@classmethod
|
380 |
+
def load_lora_into_unet(
|
381 |
+
cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
|
382 |
+
):
|
383 |
+
"""
|
384 |
+
This will load the LoRA layers specified in `state_dict` into `unet`.
|
385 |
+
|
386 |
+
Parameters:
|
387 |
+
state_dict (`dict`):
|
388 |
+
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
|
389 |
+
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
|
390 |
+
encoder lora layers.
|
391 |
+
network_alphas (`Dict[str, float]`):
|
392 |
+
See `LoRALinearLayer` for more details.
|
393 |
+
unet (`UNet2DConditionModel`):
|
394 |
+
The UNet model to load the LoRA layers into.
|
395 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
396 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
397 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
398 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
399 |
+
argument to `True` will raise an error.
|
400 |
+
adapter_name (`str`, *optional*):
|
401 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
402 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
403 |
+
"""
|
404 |
+
if not USE_PEFT_BACKEND:
|
405 |
+
raise ValueError("PEFT backend is required for this method.")
|
406 |
+
|
407 |
+
from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
|
408 |
+
|
409 |
+
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
410 |
+
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
411 |
+
# then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
|
412 |
+
# their prefixes.
|
413 |
+
keys = list(state_dict.keys())
|
414 |
+
|
415 |
+
if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
|
416 |
+
# Load the layers corresponding to UNet.
|
417 |
+
logger.info(f"Loading {cls.unet_name}.")
|
418 |
+
|
419 |
+
unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
|
420 |
+
state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
|
421 |
+
|
422 |
+
if network_alphas is not None:
|
423 |
+
alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
|
424 |
+
network_alphas = {
|
425 |
+
k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
426 |
+
}
|
427 |
+
|
428 |
+
else:
|
429 |
+
# Otherwise, we're dealing with the old format. This means the `state_dict` should only
|
430 |
+
# contain the module names of the `unet` as its keys WITHOUT any prefix.
|
431 |
+
if not USE_PEFT_BACKEND:
|
432 |
+
warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
|
433 |
+
logger.warn(warn_message)
|
434 |
+
|
435 |
+
if len(state_dict.keys()) > 0:
|
436 |
+
if adapter_name in getattr(unet, "peft_config", {}):
|
437 |
+
raise ValueError(
|
438 |
+
f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
|
439 |
+
)
|
440 |
+
|
441 |
+
state_dict = convert_unet_state_dict_to_peft(state_dict)
|
442 |
+
|
443 |
+
if network_alphas is not None:
|
444 |
+
# The alphas state dict have the same structure as Unet, thus we convert it to peft format using
|
445 |
+
# `convert_unet_state_dict_to_peft` method.
|
446 |
+
network_alphas = convert_unet_state_dict_to_peft(network_alphas)
|
447 |
+
|
448 |
+
rank = {}
|
449 |
+
for key, val in state_dict.items():
|
450 |
+
if "lora_B" in key:
|
451 |
+
rank[key] = val.shape[1]
|
452 |
+
|
453 |
+
lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
|
454 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
455 |
+
|
456 |
+
# adapter_name
|
457 |
+
if adapter_name is None:
|
458 |
+
adapter_name = get_adapter_name(unet)
|
459 |
+
|
460 |
+
# In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
|
461 |
+
# otherwise loading LoRA weights will lead to an error
|
462 |
+
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
463 |
+
|
464 |
+
inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
|
465 |
+
incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
|
466 |
+
|
467 |
+
if incompatible_keys is not None:
|
468 |
+
# check only for unexpected keys
|
469 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
470 |
+
if unexpected_keys:
|
471 |
+
logger.warning(
|
472 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
473 |
+
f" {unexpected_keys}. "
|
474 |
+
)
|
475 |
+
|
476 |
+
# Offload back.
|
477 |
+
if is_model_cpu_offload:
|
478 |
+
_pipeline.enable_model_cpu_offload()
|
479 |
+
elif is_sequential_cpu_offload:
|
480 |
+
_pipeline.enable_sequential_cpu_offload()
|
481 |
+
# Unsafe code />
|
482 |
+
|
483 |
+
unet.load_attn_procs(
|
484 |
+
state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
|
485 |
+
)
|
486 |
+
|
487 |
+
@classmethod
|
488 |
+
def load_lora_into_text_encoder(
|
489 |
+
cls,
|
490 |
+
state_dict,
|
491 |
+
network_alphas,
|
492 |
+
text_encoder,
|
493 |
+
prefix=None,
|
494 |
+
lora_scale=1.0,
|
495 |
+
low_cpu_mem_usage=None,
|
496 |
+
adapter_name=None,
|
497 |
+
_pipeline=None,
|
498 |
+
):
|
499 |
+
"""
|
500 |
+
This will load the LoRA layers specified in `state_dict` into `text_encoder`
|
501 |
+
|
502 |
+
Parameters:
|
503 |
+
state_dict (`dict`):
|
504 |
+
A standard state dict containing the lora layer parameters. The key should be prefixed with an
|
505 |
+
additional `text_encoder` to distinguish between unet lora layers.
|
506 |
+
network_alphas (`Dict[str, float]`):
|
507 |
+
See `LoRALinearLayer` for more details.
|
508 |
+
text_encoder (`CLIPTextModel`):
|
509 |
+
The text encoder model to load the LoRA layers into.
|
510 |
+
prefix (`str`):
|
511 |
+
Expected prefix of the `text_encoder` in the `state_dict`.
|
512 |
+
lora_scale (`float`):
|
513 |
+
How much to scale the output of the lora linear layer before it is added with the output of the regular
|
514 |
+
lora layer.
|
515 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
516 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
517 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
518 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
519 |
+
argument to `True` will raise an error.
|
520 |
+
adapter_name (`str`, *optional*):
|
521 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
522 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
523 |
+
"""
|
524 |
+
if not USE_PEFT_BACKEND:
|
525 |
+
raise ValueError("PEFT backend is required for this method.")
|
526 |
+
|
527 |
+
from peft import LoraConfig
|
528 |
+
|
529 |
+
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
530 |
+
|
531 |
+
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
532 |
+
# then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
|
533 |
+
# their prefixes.
|
534 |
+
keys = list(state_dict.keys())
|
535 |
+
prefix = cls.text_encoder_name if prefix is None else prefix
|
536 |
+
|
537 |
+
# Safe prefix to check with.
|
538 |
+
if any(cls.text_encoder_name in key for key in keys):
|
539 |
+
# Load the layers corresponding to text encoder and make necessary adjustments.
|
540 |
+
text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
|
541 |
+
text_encoder_lora_state_dict = {
|
542 |
+
k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
|
543 |
+
}
|
544 |
+
|
545 |
+
if len(text_encoder_lora_state_dict) > 0:
|
546 |
+
logger.info(f"Loading {prefix}.")
|
547 |
+
rank = {}
|
548 |
+
text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
|
549 |
+
|
550 |
+
# convert state dict
|
551 |
+
text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
|
552 |
+
|
553 |
+
for name, _ in text_encoder_attn_modules(text_encoder):
|
554 |
+
rank_key = f"{name}.out_proj.lora_B.weight"
|
555 |
+
rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
|
556 |
+
|
557 |
+
patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
|
558 |
+
if patch_mlp:
|
559 |
+
for name, _ in text_encoder_mlp_modules(text_encoder):
|
560 |
+
rank_key_fc1 = f"{name}.fc1.lora_B.weight"
|
561 |
+
rank_key_fc2 = f"{name}.fc2.lora_B.weight"
|
562 |
+
|
563 |
+
rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
|
564 |
+
rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
|
565 |
+
|
566 |
+
if network_alphas is not None:
|
567 |
+
alpha_keys = [
|
568 |
+
k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
|
569 |
+
]
|
570 |
+
network_alphas = {
|
571 |
+
k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
572 |
+
}
|
573 |
+
|
574 |
+
lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
|
575 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
576 |
+
|
577 |
+
# adapter_name
|
578 |
+
if adapter_name is None:
|
579 |
+
adapter_name = get_adapter_name(text_encoder)
|
580 |
+
|
581 |
+
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
582 |
+
|
583 |
+
# inject LoRA layers and load the state dict
|
584 |
+
# in transformers we automatically check whether the adapter name is already in use or not
|
585 |
+
text_encoder.load_adapter(
|
586 |
+
adapter_name=adapter_name,
|
587 |
+
adapter_state_dict=text_encoder_lora_state_dict,
|
588 |
+
peft_config=lora_config,
|
589 |
+
)
|
590 |
+
|
591 |
+
# scale LoRA layers with `lora_scale`
|
592 |
+
scale_lora_layers(text_encoder, weight=lora_scale)
|
593 |
+
|
594 |
+
text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
|
595 |
+
|
596 |
+
# Offload back.
|
597 |
+
if is_model_cpu_offload:
|
598 |
+
_pipeline.enable_model_cpu_offload()
|
599 |
+
elif is_sequential_cpu_offload:
|
600 |
+
_pipeline.enable_sequential_cpu_offload()
|
601 |
+
# Unsafe code />
|
602 |
+
|
603 |
+
@classmethod
|
604 |
+
def load_lora_into_transformer(
|
605 |
+
cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
|
606 |
+
):
|
607 |
+
"""
|
608 |
+
This will load the LoRA layers specified in `state_dict` into `transformer`.
|
609 |
+
|
610 |
+
Parameters:
|
611 |
+
state_dict (`dict`):
|
612 |
+
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
|
613 |
+
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
|
614 |
+
encoder lora layers.
|
615 |
+
network_alphas (`Dict[str, float]`):
|
616 |
+
See `LoRALinearLayer` for more details.
|
617 |
+
unet (`UNet2DConditionModel`):
|
618 |
+
The UNet model to load the LoRA layers into.
|
619 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
620 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
621 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
622 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
623 |
+
argument to `True` will raise an error.
|
624 |
+
adapter_name (`str`, *optional*):
|
625 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
626 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
627 |
+
"""
|
628 |
+
from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
|
629 |
+
|
630 |
+
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
631 |
+
|
632 |
+
keys = list(state_dict.keys())
|
633 |
+
|
634 |
+
transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
|
635 |
+
state_dict = {
|
636 |
+
k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
|
637 |
+
}
|
638 |
+
|
639 |
+
if network_alphas is not None:
|
640 |
+
alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
|
641 |
+
network_alphas = {
|
642 |
+
k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
643 |
+
}
|
644 |
+
|
645 |
+
if len(state_dict.keys()) > 0:
|
646 |
+
if adapter_name in getattr(transformer, "peft_config", {}):
|
647 |
+
raise ValueError(
|
648 |
+
f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
|
649 |
+
)
|
650 |
+
|
651 |
+
rank = {}
|
652 |
+
for key, val in state_dict.items():
|
653 |
+
if "lora_B" in key:
|
654 |
+
rank[key] = val.shape[1]
|
655 |
+
|
656 |
+
lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
|
657 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
658 |
+
|
659 |
+
# adapter_name
|
660 |
+
if adapter_name is None:
|
661 |
+
adapter_name = get_adapter_name(transformer)
|
662 |
+
|
663 |
+
# In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
|
664 |
+
# otherwise loading LoRA weights will lead to an error
|
665 |
+
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
666 |
+
|
667 |
+
inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
|
668 |
+
incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
|
669 |
+
|
670 |
+
if incompatible_keys is not None:
|
671 |
+
# check only for unexpected keys
|
672 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
673 |
+
if unexpected_keys:
|
674 |
+
logger.warning(
|
675 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
676 |
+
f" {unexpected_keys}. "
|
677 |
+
)
|
678 |
+
|
679 |
+
# Offload back.
|
680 |
+
if is_model_cpu_offload:
|
681 |
+
_pipeline.enable_model_cpu_offload()
|
682 |
+
elif is_sequential_cpu_offload:
|
683 |
+
_pipeline.enable_sequential_cpu_offload()
|
684 |
+
# Unsafe code />
|
685 |
+
|
686 |
+
@property
|
687 |
+
def lora_scale(self) -> float:
|
688 |
+
# property function that returns the lora scale which can be set at run time by the pipeline.
|
689 |
+
# if _lora_scale has not been set, return 1
|
690 |
+
return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
|
691 |
+
|
692 |
+
def _remove_text_encoder_monkey_patch(self):
|
693 |
+
remove_method = recurse_remove_peft_layers
|
694 |
+
if hasattr(self, "text_encoder"):
|
695 |
+
remove_method(self.text_encoder)
|
696 |
+
# In case text encoder have no Lora attached
|
697 |
+
if getattr(self.text_encoder, "peft_config", None) is not None:
|
698 |
+
del self.text_encoder.peft_config
|
699 |
+
self.text_encoder._hf_peft_config_loaded = None
|
700 |
+
|
701 |
+
if hasattr(self, "text_encoder_2"):
|
702 |
+
remove_method(self.text_encoder_2)
|
703 |
+
if getattr(self.text_encoder_2, "peft_config", None) is not None:
|
704 |
+
del self.text_encoder_2.peft_config
|
705 |
+
self.text_encoder_2._hf_peft_config_loaded = None
|
706 |
+
|
707 |
+
@classmethod
|
708 |
+
def save_lora_weights(
|
709 |
+
cls,
|
710 |
+
save_directory: Union[str, os.PathLike],
|
711 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
712 |
+
text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
|
713 |
+
transformer_lora_layers: Dict[str, torch.nn.Module] = None,
|
714 |
+
is_main_process: bool = True,
|
715 |
+
weight_name: str = None,
|
716 |
+
save_function: Callable = None,
|
717 |
+
safe_serialization: bool = True,
|
718 |
+
):
|
719 |
+
r"""
|
720 |
+
Save the LoRA parameters corresponding to the UNet and text encoder.
|
721 |
+
|
722 |
+
Arguments:
|
723 |
+
save_directory (`str` or `os.PathLike`):
|
724 |
+
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
725 |
+
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
726 |
+
State dict of the LoRA layers corresponding to the `unet`.
|
727 |
+
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
728 |
+
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
729 |
+
encoder LoRA state dict because it comes from 🤗 Transformers.
|
730 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
731 |
+
Whether the process calling this is the main process or not. Useful during distributed training and you
|
732 |
+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
733 |
+
process to avoid race conditions.
|
734 |
+
save_function (`Callable`):
|
735 |
+
The function to use to save the state dictionary. Useful during distributed training when you need to
|
736 |
+
replace `torch.save` with another method. Can be configured with the environment variable
|
737 |
+
`DIFFUSERS_SAVE_MODE`.
|
738 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
739 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
740 |
+
"""
|
741 |
+
state_dict = {}
|
742 |
+
|
743 |
+
def pack_weights(layers, prefix):
|
744 |
+
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
745 |
+
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
746 |
+
return layers_state_dict
|
747 |
+
|
748 |
+
if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
|
749 |
+
raise ValueError(
|
750 |
+
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
|
751 |
+
)
|
752 |
+
|
753 |
+
if unet_lora_layers:
|
754 |
+
state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
|
755 |
+
|
756 |
+
if text_encoder_lora_layers:
|
757 |
+
state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
|
758 |
+
|
759 |
+
if transformer_lora_layers:
|
760 |
+
state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
|
761 |
+
|
762 |
+
# Save the model
|
763 |
+
cls.write_lora_layers(
|
764 |
+
state_dict=state_dict,
|
765 |
+
save_directory=save_directory,
|
766 |
+
is_main_process=is_main_process,
|
767 |
+
weight_name=weight_name,
|
768 |
+
save_function=save_function,
|
769 |
+
safe_serialization=safe_serialization,
|
770 |
+
)
|
771 |
+
|
772 |
+
@staticmethod
|
773 |
+
def write_lora_layers(
|
774 |
+
state_dict: Dict[str, torch.Tensor],
|
775 |
+
save_directory: str,
|
776 |
+
is_main_process: bool,
|
777 |
+
weight_name: str,
|
778 |
+
save_function: Callable,
|
779 |
+
safe_serialization: bool,
|
780 |
+
):
|
781 |
+
if os.path.isfile(save_directory):
|
782 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
783 |
+
return
|
784 |
+
|
785 |
+
if save_function is None:
|
786 |
+
if safe_serialization:
|
787 |
+
|
788 |
+
def save_function(weights, filename):
|
789 |
+
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
790 |
+
|
791 |
+
else:
|
792 |
+
save_function = torch.save
|
793 |
+
|
794 |
+
os.makedirs(save_directory, exist_ok=True)
|
795 |
+
|
796 |
+
if weight_name is None:
|
797 |
+
if safe_serialization:
|
798 |
+
weight_name = LORA_WEIGHT_NAME_SAFE
|
799 |
+
else:
|
800 |
+
weight_name = LORA_WEIGHT_NAME
|
801 |
+
|
802 |
+
save_path = Path(save_directory, weight_name).as_posix()
|
803 |
+
save_function(state_dict, save_path)
|
804 |
+
logger.info(f"Model weights saved in {save_path}")
|
805 |
+
|
806 |
+
def unload_lora_weights(self):
|
807 |
+
"""
|
808 |
+
Unloads the LoRA parameters.
|
809 |
+
|
810 |
+
Examples:
|
811 |
+
|
812 |
+
```python
|
813 |
+
>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
|
814 |
+
>>> pipeline.unload_lora_weights()
|
815 |
+
>>> ...
|
816 |
+
```
|
817 |
+
"""
|
818 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
819 |
+
|
820 |
+
if not USE_PEFT_BACKEND:
|
821 |
+
if version.parse(__version__) > version.parse("0.23"):
|
822 |
+
logger.warning(
|
823 |
+
"You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
|
824 |
+
"you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
|
825 |
+
)
|
826 |
+
|
827 |
+
for _, module in unet.named_modules():
|
828 |
+
if hasattr(module, "set_lora_layer"):
|
829 |
+
module.set_lora_layer(None)
|
830 |
+
else:
|
831 |
+
recurse_remove_peft_layers(unet)
|
832 |
+
if hasattr(unet, "peft_config"):
|
833 |
+
del unet.peft_config
|
834 |
+
|
835 |
+
# Safe to call the following regardless of LoRA.
|
836 |
+
self._remove_text_encoder_monkey_patch()
|
837 |
+
|
838 |
+
def fuse_lora(
|
839 |
+
self,
|
840 |
+
fuse_unet: bool = True,
|
841 |
+
fuse_text_encoder: bool = True,
|
842 |
+
lora_scale: float = 1.0,
|
843 |
+
safe_fusing: bool = False,
|
844 |
+
adapter_names: Optional[List[str]] = None,
|
845 |
+
):
|
846 |
+
r"""
|
847 |
+
Fuses the LoRA parameters into the original parameters of the corresponding blocks.
|
848 |
+
|
849 |
+
<Tip warning={true}>
|
850 |
+
|
851 |
+
This is an experimental API.
|
852 |
+
|
853 |
+
</Tip>
|
854 |
+
|
855 |
+
Args:
|
856 |
+
fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
|
857 |
+
fuse_text_encoder (`bool`, defaults to `True`):
|
858 |
+
Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
859 |
+
LoRA parameters then it won't have any effect.
|
860 |
+
lora_scale (`float`, defaults to 1.0):
|
861 |
+
Controls how much to influence the outputs with the LoRA parameters.
|
862 |
+
safe_fusing (`bool`, defaults to `False`):
|
863 |
+
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
|
864 |
+
adapter_names (`List[str]`, *optional*):
|
865 |
+
Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
|
866 |
+
|
867 |
+
Example:
|
868 |
+
|
869 |
+
```py
|
870 |
+
from diffusers import DiffusionPipeline
|
871 |
+
import torch
|
872 |
+
|
873 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
874 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
875 |
+
).to("cuda")
|
876 |
+
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
|
877 |
+
pipeline.fuse_lora(lora_scale=0.7)
|
878 |
+
```
|
879 |
+
"""
|
880 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
881 |
+
|
882 |
+
if fuse_unet or fuse_text_encoder:
|
883 |
+
self.num_fused_loras += 1
|
884 |
+
if self.num_fused_loras > 1:
|
885 |
+
logger.warn(
|
886 |
+
"The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
|
887 |
+
)
|
888 |
+
|
889 |
+
if fuse_unet:
|
890 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
891 |
+
unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
|
892 |
+
|
893 |
+
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
|
894 |
+
merge_kwargs = {"safe_merge": safe_fusing}
|
895 |
+
|
896 |
+
for module in text_encoder.modules():
|
897 |
+
if isinstance(module, BaseTunerLayer):
|
898 |
+
if lora_scale != 1.0:
|
899 |
+
module.scale_layer(lora_scale)
|
900 |
+
|
901 |
+
# For BC with previous PEFT versions, we need to check the signature
|
902 |
+
# of the `merge` method to see if it supports the `adapter_names` argument.
|
903 |
+
supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
|
904 |
+
if "adapter_names" in supported_merge_kwargs:
|
905 |
+
merge_kwargs["adapter_names"] = adapter_names
|
906 |
+
elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
|
907 |
+
raise ValueError(
|
908 |
+
"The `adapter_names` argument is not supported with your PEFT version. "
|
909 |
+
"Please upgrade to the latest version of PEFT. `pip install -U peft`"
|
910 |
+
)
|
911 |
+
|
912 |
+
module.merge(**merge_kwargs)
|
913 |
+
|
914 |
+
if fuse_text_encoder:
|
915 |
+
if hasattr(self, "text_encoder"):
|
916 |
+
fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
|
917 |
+
if hasattr(self, "text_encoder_2"):
|
918 |
+
fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
|
919 |
+
|
920 |
+
def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
|
921 |
+
r"""
|
922 |
+
Reverses the effect of
|
923 |
+
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
|
924 |
+
|
925 |
+
<Tip warning={true}>
|
926 |
+
|
927 |
+
This is an experimental API.
|
928 |
+
|
929 |
+
</Tip>
|
930 |
+
|
931 |
+
Args:
|
932 |
+
unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
|
933 |
+
unfuse_text_encoder (`bool`, defaults to `True`):
|
934 |
+
Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
935 |
+
LoRA parameters then it won't have any effect.
|
936 |
+
"""
|
937 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
938 |
+
|
939 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
940 |
+
if unfuse_unet:
|
941 |
+
for module in unet.modules():
|
942 |
+
if isinstance(module, BaseTunerLayer):
|
943 |
+
module.unmerge()
|
944 |
+
|
945 |
+
def unfuse_text_encoder_lora(text_encoder):
|
946 |
+
for module in text_encoder.modules():
|
947 |
+
if isinstance(module, BaseTunerLayer):
|
948 |
+
module.unmerge()
|
949 |
+
|
950 |
+
if unfuse_text_encoder:
|
951 |
+
if hasattr(self, "text_encoder"):
|
952 |
+
unfuse_text_encoder_lora(self.text_encoder)
|
953 |
+
if hasattr(self, "text_encoder_2"):
|
954 |
+
unfuse_text_encoder_lora(self.text_encoder_2)
|
955 |
+
|
956 |
+
self.num_fused_loras -= 1
|
957 |
+
|
958 |
+
def set_adapters_for_text_encoder(
|
959 |
+
self,
|
960 |
+
adapter_names: Union[List[str], str],
|
961 |
+
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
962 |
+
text_encoder_weights: List[float] = None,
|
963 |
+
):
|
964 |
+
"""
|
965 |
+
Sets the adapter layers for the text encoder.
|
966 |
+
|
967 |
+
Args:
|
968 |
+
adapter_names (`List[str]` or `str`):
|
969 |
+
The names of the adapters to use.
|
970 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
971 |
+
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
972 |
+
attribute.
|
973 |
+
text_encoder_weights (`List[float]`, *optional*):
|
974 |
+
The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
|
975 |
+
"""
|
976 |
+
if not USE_PEFT_BACKEND:
|
977 |
+
raise ValueError("PEFT backend is required for this method.")
|
978 |
+
|
979 |
+
def process_weights(adapter_names, weights):
|
980 |
+
if weights is None:
|
981 |
+
weights = [1.0] * len(adapter_names)
|
982 |
+
elif isinstance(weights, float):
|
983 |
+
weights = [weights]
|
984 |
+
|
985 |
+
if len(adapter_names) != len(weights):
|
986 |
+
raise ValueError(
|
987 |
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
|
988 |
+
)
|
989 |
+
return weights
|
990 |
+
|
991 |
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
992 |
+
text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
|
993 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
994 |
+
if text_encoder is None:
|
995 |
+
raise ValueError(
|
996 |
+
"The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
|
997 |
+
)
|
998 |
+
set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
|
999 |
+
|
1000 |
+
def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
1001 |
+
"""
|
1002 |
+
Disables the LoRA layers for the text encoder.
|
1003 |
+
|
1004 |
+
Args:
|
1005 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
1006 |
+
The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
|
1007 |
+
`text_encoder` attribute.
|
1008 |
+
"""
|
1009 |
+
if not USE_PEFT_BACKEND:
|
1010 |
+
raise ValueError("PEFT backend is required for this method.")
|
1011 |
+
|
1012 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
1013 |
+
if text_encoder is None:
|
1014 |
+
raise ValueError("Text Encoder not found.")
|
1015 |
+
set_adapter_layers(text_encoder, enabled=False)
|
1016 |
+
|
1017 |
+
def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
1018 |
+
"""
|
1019 |
+
Enables the LoRA layers for the text encoder.
|
1020 |
+
|
1021 |
+
Args:
|
1022 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
1023 |
+
The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
|
1024 |
+
attribute.
|
1025 |
+
"""
|
1026 |
+
if not USE_PEFT_BACKEND:
|
1027 |
+
raise ValueError("PEFT backend is required for this method.")
|
1028 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
1029 |
+
if text_encoder is None:
|
1030 |
+
raise ValueError("Text Encoder not found.")
|
1031 |
+
set_adapter_layers(self.text_encoder, enabled=True)
|
1032 |
+
|
1033 |
+
def set_adapters(
|
1034 |
+
self,
|
1035 |
+
adapter_names: Union[List[str], str],
|
1036 |
+
adapter_weights: Optional[List[float]] = None,
|
1037 |
+
):
|
1038 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1039 |
+
# Handle the UNET
|
1040 |
+
unet.set_adapters(adapter_names, adapter_weights)
|
1041 |
+
|
1042 |
+
# Handle the Text Encoder
|
1043 |
+
if hasattr(self, "text_encoder"):
|
1044 |
+
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
|
1045 |
+
if hasattr(self, "text_encoder_2"):
|
1046 |
+
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
|
1047 |
+
|
1048 |
+
def disable_lora(self):
|
1049 |
+
if not USE_PEFT_BACKEND:
|
1050 |
+
raise ValueError("PEFT backend is required for this method.")
|
1051 |
+
|
1052 |
+
# Disable unet adapters
|
1053 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1054 |
+
unet.disable_lora()
|
1055 |
+
|
1056 |
+
# Disable text encoder adapters
|
1057 |
+
if hasattr(self, "text_encoder"):
|
1058 |
+
self.disable_lora_for_text_encoder(self.text_encoder)
|
1059 |
+
if hasattr(self, "text_encoder_2"):
|
1060 |
+
self.disable_lora_for_text_encoder(self.text_encoder_2)
|
1061 |
+
|
1062 |
+
def enable_lora(self):
|
1063 |
+
if not USE_PEFT_BACKEND:
|
1064 |
+
raise ValueError("PEFT backend is required for this method.")
|
1065 |
+
|
1066 |
+
# Enable unet adapters
|
1067 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1068 |
+
unet.enable_lora()
|
1069 |
+
|
1070 |
+
# Enable text encoder adapters
|
1071 |
+
if hasattr(self, "text_encoder"):
|
1072 |
+
self.enable_lora_for_text_encoder(self.text_encoder)
|
1073 |
+
if hasattr(self, "text_encoder_2"):
|
1074 |
+
self.enable_lora_for_text_encoder(self.text_encoder_2)
|
1075 |
+
|
1076 |
+
def delete_adapters(self, adapter_names: Union[List[str], str]):
|
1077 |
+
"""
|
1078 |
+
Args:
|
1079 |
+
Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
|
1080 |
+
adapter_names (`Union[List[str], str]`):
|
1081 |
+
The names of the adapter to delete. Can be a single string or a list of strings
|
1082 |
+
"""
|
1083 |
+
if not USE_PEFT_BACKEND:
|
1084 |
+
raise ValueError("PEFT backend is required for this method.")
|
1085 |
+
|
1086 |
+
if isinstance(adapter_names, str):
|
1087 |
+
adapter_names = [adapter_names]
|
1088 |
+
|
1089 |
+
# Delete unet adapters
|
1090 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1091 |
+
unet.delete_adapters(adapter_names)
|
1092 |
+
|
1093 |
+
for adapter_name in adapter_names:
|
1094 |
+
# Delete text encoder adapters
|
1095 |
+
if hasattr(self, "text_encoder"):
|
1096 |
+
delete_adapter_layers(self.text_encoder, adapter_name)
|
1097 |
+
if hasattr(self, "text_encoder_2"):
|
1098 |
+
delete_adapter_layers(self.text_encoder_2, adapter_name)
|
1099 |
+
|
1100 |
+
def get_active_adapters(self) -> List[str]:
|
1101 |
+
"""
|
1102 |
+
Gets the list of the current active adapters.
|
1103 |
+
|
1104 |
+
Example:
|
1105 |
+
|
1106 |
+
```python
|
1107 |
+
from diffusers import DiffusionPipeline
|
1108 |
+
|
1109 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
1110 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
1111 |
+
).to("cuda")
|
1112 |
+
pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
|
1113 |
+
pipeline.get_active_adapters()
|
1114 |
+
```
|
1115 |
+
"""
|
1116 |
+
if not USE_PEFT_BACKEND:
|
1117 |
+
raise ValueError(
|
1118 |
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
1119 |
+
)
|
1120 |
+
|
1121 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
1122 |
+
|
1123 |
+
active_adapters = []
|
1124 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1125 |
+
for module in unet.modules():
|
1126 |
+
if isinstance(module, BaseTunerLayer):
|
1127 |
+
active_adapters = module.active_adapters
|
1128 |
+
break
|
1129 |
+
|
1130 |
+
return active_adapters
|
1131 |
+
|
1132 |
+
def get_list_adapters(self) -> Dict[str, List[str]]:
|
1133 |
+
"""
|
1134 |
+
Gets the current list of all available adapters in the pipeline.
|
1135 |
+
"""
|
1136 |
+
if not USE_PEFT_BACKEND:
|
1137 |
+
raise ValueError(
|
1138 |
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
1139 |
+
)
|
1140 |
+
|
1141 |
+
set_adapters = {}
|
1142 |
+
|
1143 |
+
if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
|
1144 |
+
set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
|
1145 |
+
|
1146 |
+
if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
|
1147 |
+
set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
|
1148 |
+
|
1149 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1150 |
+
if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
|
1151 |
+
set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
|
1152 |
+
|
1153 |
+
return set_adapters
|
1154 |
+
|
1155 |
+
def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
|
1156 |
+
"""
|
1157 |
+
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
|
1158 |
+
you want to load multiple adapters and free some GPU memory.
|
1159 |
+
|
1160 |
+
Args:
|
1161 |
+
adapter_names (`List[str]`):
|
1162 |
+
List of adapters to send device to.
|
1163 |
+
device (`Union[torch.device, str, int]`):
|
1164 |
+
Device to send the adapters to. Can be either a torch device, a str or an integer.
|
1165 |
+
"""
|
1166 |
+
if not USE_PEFT_BACKEND:
|
1167 |
+
raise ValueError("PEFT backend is required for this method.")
|
1168 |
+
|
1169 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
1170 |
+
|
1171 |
+
# Handle the UNET
|
1172 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
1173 |
+
for unet_module in unet.modules():
|
1174 |
+
if isinstance(unet_module, BaseTunerLayer):
|
1175 |
+
for adapter_name in adapter_names:
|
1176 |
+
unet_module.lora_A[adapter_name].to(device)
|
1177 |
+
unet_module.lora_B[adapter_name].to(device)
|
1178 |
+
|
1179 |
+
# Handle the text encoder
|
1180 |
+
modules_to_process = []
|
1181 |
+
if hasattr(self, "text_encoder"):
|
1182 |
+
modules_to_process.append(self.text_encoder)
|
1183 |
+
|
1184 |
+
if hasattr(self, "text_encoder_2"):
|
1185 |
+
modules_to_process.append(self.text_encoder_2)
|
1186 |
+
|
1187 |
+
for text_encoder in modules_to_process:
|
1188 |
+
# loop over submodules
|
1189 |
+
for text_encoder_module in text_encoder.modules():
|
1190 |
+
if isinstance(text_encoder_module, BaseTunerLayer):
|
1191 |
+
for adapter_name in adapter_names:
|
1192 |
+
text_encoder_module.lora_A[adapter_name].to(device)
|
1193 |
+
text_encoder_module.lora_B[adapter_name].to(device)
|
1194 |
+
|
1195 |
+
|
1196 |
+
class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
|
1197 |
+
"""This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
|
1198 |
+
|
1199 |
+
# Override to properly handle the loading and unloading of the additional text encoder.
|
1200 |
+
def load_lora_weights(
|
1201 |
+
self,
|
1202 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
1203 |
+
adapter_name: Optional[str] = None,
|
1204 |
+
**kwargs,
|
1205 |
+
):
|
1206 |
+
"""
|
1207 |
+
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
1208 |
+
`self.text_encoder`.
|
1209 |
+
|
1210 |
+
All kwargs are forwarded to `self.lora_state_dict`.
|
1211 |
+
|
1212 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
1213 |
+
|
1214 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
1215 |
+
`self.unet`.
|
1216 |
+
|
1217 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
1218 |
+
into `self.text_encoder`.
|
1219 |
+
|
1220 |
+
Parameters:
|
1221 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
1222 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
1223 |
+
adapter_name (`str`, *optional*):
|
1224 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
1225 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
1226 |
+
kwargs (`dict`, *optional*):
|
1227 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
1228 |
+
"""
|
1229 |
+
if not USE_PEFT_BACKEND:
|
1230 |
+
raise ValueError("PEFT backend is required for this method.")
|
1231 |
+
|
1232 |
+
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
1233 |
+
# it here explicitly to be able to tell that it's coming from an SDXL
|
1234 |
+
# pipeline.
|
1235 |
+
|
1236 |
+
# if a dict is passed, copy it instead of modifying it inplace
|
1237 |
+
if isinstance(pretrained_model_name_or_path_or_dict, dict):
|
1238 |
+
pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
|
1239 |
+
|
1240 |
+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
1241 |
+
state_dict, network_alphas = self.lora_state_dict(
|
1242 |
+
pretrained_model_name_or_path_or_dict,
|
1243 |
+
unet_config=self.unet.config,
|
1244 |
+
**kwargs,
|
1245 |
+
)
|
1246 |
+
is_correct_format = all("lora" in key for key in state_dict.keys())
|
1247 |
+
if not is_correct_format:
|
1248 |
+
raise ValueError("Invalid LoRA checkpoint.")
|
1249 |
+
|
1250 |
+
self.load_lora_into_unet(
|
1251 |
+
state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
|
1252 |
+
)
|
1253 |
+
text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
|
1254 |
+
if len(text_encoder_state_dict) > 0:
|
1255 |
+
self.load_lora_into_text_encoder(
|
1256 |
+
text_encoder_state_dict,
|
1257 |
+
network_alphas=network_alphas,
|
1258 |
+
text_encoder=self.text_encoder,
|
1259 |
+
prefix="text_encoder",
|
1260 |
+
lora_scale=self.lora_scale,
|
1261 |
+
adapter_name=adapter_name,
|
1262 |
+
_pipeline=self,
|
1263 |
+
)
|
1264 |
+
|
1265 |
+
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
|
1266 |
+
if len(text_encoder_2_state_dict) > 0:
|
1267 |
+
self.load_lora_into_text_encoder(
|
1268 |
+
text_encoder_2_state_dict,
|
1269 |
+
network_alphas=network_alphas,
|
1270 |
+
text_encoder=self.text_encoder_2,
|
1271 |
+
prefix="text_encoder_2",
|
1272 |
+
lora_scale=self.lora_scale,
|
1273 |
+
adapter_name=adapter_name,
|
1274 |
+
_pipeline=self,
|
1275 |
+
)
|
1276 |
+
|
1277 |
+
@classmethod
|
1278 |
+
def save_lora_weights(
|
1279 |
+
cls,
|
1280 |
+
save_directory: Union[str, os.PathLike],
|
1281 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
1282 |
+
text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
1283 |
+
text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
1284 |
+
is_main_process: bool = True,
|
1285 |
+
weight_name: str = None,
|
1286 |
+
save_function: Callable = None,
|
1287 |
+
safe_serialization: bool = True,
|
1288 |
+
):
|
1289 |
+
r"""
|
1290 |
+
Save the LoRA parameters corresponding to the UNet and text encoder.
|
1291 |
+
|
1292 |
+
Arguments:
|
1293 |
+
save_directory (`str` or `os.PathLike`):
|
1294 |
+
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
1295 |
+
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
1296 |
+
State dict of the LoRA layers corresponding to the `unet`.
|
1297 |
+
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
1298 |
+
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
1299 |
+
encoder LoRA state dict because it comes from 🤗 Transformers.
|
1300 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
1301 |
+
Whether the process calling this is the main process or not. Useful during distributed training and you
|
1302 |
+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
1303 |
+
process to avoid race conditions.
|
1304 |
+
save_function (`Callable`):
|
1305 |
+
The function to use to save the state dictionary. Useful during distributed training when you need to
|
1306 |
+
replace `torch.save` with another method. Can be configured with the environment variable
|
1307 |
+
`DIFFUSERS_SAVE_MODE`.
|
1308 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
1309 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
1310 |
+
"""
|
1311 |
+
state_dict = {}
|
1312 |
+
|
1313 |
+
def pack_weights(layers, prefix):
|
1314 |
+
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
1315 |
+
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
1316 |
+
return layers_state_dict
|
1317 |
+
|
1318 |
+
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
|
1319 |
+
raise ValueError(
|
1320 |
+
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
1321 |
+
)
|
1322 |
+
|
1323 |
+
if unet_lora_layers:
|
1324 |
+
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
1325 |
+
|
1326 |
+
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
1327 |
+
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
1328 |
+
state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
|
1329 |
+
|
1330 |
+
cls.write_lora_layers(
|
1331 |
+
state_dict=state_dict,
|
1332 |
+
save_directory=save_directory,
|
1333 |
+
is_main_process=is_main_process,
|
1334 |
+
weight_name=weight_name,
|
1335 |
+
save_function=save_function,
|
1336 |
+
safe_serialization=safe_serialization,
|
1337 |
+
)
|
1338 |
+
|
1339 |
+
def _remove_text_encoder_monkey_patch(self):
|
1340 |
+
recurse_remove_peft_layers(self.text_encoder)
|
1341 |
+
# TODO: @younesbelkada handle this in transformers side
|
1342 |
+
if getattr(self.text_encoder, "peft_config", None) is not None:
|
1343 |
+
del self.text_encoder.peft_config
|
1344 |
+
self.text_encoder._hf_peft_config_loaded = None
|
1345 |
+
|
1346 |
+
recurse_remove_peft_layers(self.text_encoder_2)
|
1347 |
+
if getattr(self.text_encoder_2, "peft_config", None) is not None:
|
1348 |
+
del self.text_encoder_2.peft_config
|
1349 |
+
self.text_encoder_2._hf_peft_config_loaded = None
|
BrushNet/build/lib/diffusers/loaders/lora_conversion_utils.py
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 re
|
16 |
+
|
17 |
+
from ..utils import logging
|
18 |
+
|
19 |
+
|
20 |
+
logger = logging.get_logger(__name__)
|
21 |
+
|
22 |
+
|
23 |
+
def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter="_", block_slice_pos=5):
|
24 |
+
# 1. get all state_dict_keys
|
25 |
+
all_keys = list(state_dict.keys())
|
26 |
+
sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
|
27 |
+
|
28 |
+
# 2. check if needs remapping, if not return original dict
|
29 |
+
is_in_sgm_format = False
|
30 |
+
for key in all_keys:
|
31 |
+
if any(p in key for p in sgm_patterns):
|
32 |
+
is_in_sgm_format = True
|
33 |
+
break
|
34 |
+
|
35 |
+
if not is_in_sgm_format:
|
36 |
+
return state_dict
|
37 |
+
|
38 |
+
# 3. Else remap from SGM patterns
|
39 |
+
new_state_dict = {}
|
40 |
+
inner_block_map = ["resnets", "attentions", "upsamplers"]
|
41 |
+
|
42 |
+
# Retrieves # of down, mid and up blocks
|
43 |
+
input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
|
44 |
+
|
45 |
+
for layer in all_keys:
|
46 |
+
if "text" in layer:
|
47 |
+
new_state_dict[layer] = state_dict.pop(layer)
|
48 |
+
else:
|
49 |
+
layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
|
50 |
+
if sgm_patterns[0] in layer:
|
51 |
+
input_block_ids.add(layer_id)
|
52 |
+
elif sgm_patterns[1] in layer:
|
53 |
+
middle_block_ids.add(layer_id)
|
54 |
+
elif sgm_patterns[2] in layer:
|
55 |
+
output_block_ids.add(layer_id)
|
56 |
+
else:
|
57 |
+
raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
|
58 |
+
|
59 |
+
input_blocks = {
|
60 |
+
layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
|
61 |
+
for layer_id in input_block_ids
|
62 |
+
}
|
63 |
+
middle_blocks = {
|
64 |
+
layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
|
65 |
+
for layer_id in middle_block_ids
|
66 |
+
}
|
67 |
+
output_blocks = {
|
68 |
+
layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
|
69 |
+
for layer_id in output_block_ids
|
70 |
+
}
|
71 |
+
|
72 |
+
# Rename keys accordingly
|
73 |
+
for i in input_block_ids:
|
74 |
+
block_id = (i - 1) // (unet_config.layers_per_block + 1)
|
75 |
+
layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
|
76 |
+
|
77 |
+
for key in input_blocks[i]:
|
78 |
+
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
79 |
+
inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
|
80 |
+
inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
|
81 |
+
new_key = delimiter.join(
|
82 |
+
key.split(delimiter)[: block_slice_pos - 1]
|
83 |
+
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
84 |
+
+ key.split(delimiter)[block_slice_pos + 1 :]
|
85 |
+
)
|
86 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
87 |
+
|
88 |
+
for i in middle_block_ids:
|
89 |
+
key_part = None
|
90 |
+
if i == 0:
|
91 |
+
key_part = [inner_block_map[0], "0"]
|
92 |
+
elif i == 1:
|
93 |
+
key_part = [inner_block_map[1], "0"]
|
94 |
+
elif i == 2:
|
95 |
+
key_part = [inner_block_map[0], "1"]
|
96 |
+
else:
|
97 |
+
raise ValueError(f"Invalid middle block id {i}.")
|
98 |
+
|
99 |
+
for key in middle_blocks[i]:
|
100 |
+
new_key = delimiter.join(
|
101 |
+
key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
|
102 |
+
)
|
103 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
104 |
+
|
105 |
+
for i in output_block_ids:
|
106 |
+
block_id = i // (unet_config.layers_per_block + 1)
|
107 |
+
layer_in_block_id = i % (unet_config.layers_per_block + 1)
|
108 |
+
|
109 |
+
for key in output_blocks[i]:
|
110 |
+
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
111 |
+
inner_block_key = inner_block_map[inner_block_id]
|
112 |
+
inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
|
113 |
+
new_key = delimiter.join(
|
114 |
+
key.split(delimiter)[: block_slice_pos - 1]
|
115 |
+
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
116 |
+
+ key.split(delimiter)[block_slice_pos + 1 :]
|
117 |
+
)
|
118 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
119 |
+
|
120 |
+
if len(state_dict) > 0:
|
121 |
+
raise ValueError("At this point all state dict entries have to be converted.")
|
122 |
+
|
123 |
+
return new_state_dict
|
124 |
+
|
125 |
+
|
126 |
+
def _convert_kohya_lora_to_diffusers(state_dict, unet_name="unet", text_encoder_name="text_encoder"):
|
127 |
+
unet_state_dict = {}
|
128 |
+
te_state_dict = {}
|
129 |
+
te2_state_dict = {}
|
130 |
+
network_alphas = {}
|
131 |
+
|
132 |
+
# every down weight has a corresponding up weight and potentially an alpha weight
|
133 |
+
lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
|
134 |
+
for key in lora_keys:
|
135 |
+
lora_name = key.split(".")[0]
|
136 |
+
lora_name_up = lora_name + ".lora_up.weight"
|
137 |
+
lora_name_alpha = lora_name + ".alpha"
|
138 |
+
|
139 |
+
if lora_name.startswith("lora_unet_"):
|
140 |
+
diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
|
141 |
+
|
142 |
+
if "input.blocks" in diffusers_name:
|
143 |
+
diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
|
144 |
+
else:
|
145 |
+
diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
|
146 |
+
|
147 |
+
if "middle.block" in diffusers_name:
|
148 |
+
diffusers_name = diffusers_name.replace("middle.block", "mid_block")
|
149 |
+
else:
|
150 |
+
diffusers_name = diffusers_name.replace("mid.block", "mid_block")
|
151 |
+
if "output.blocks" in diffusers_name:
|
152 |
+
diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
|
153 |
+
else:
|
154 |
+
diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
|
155 |
+
|
156 |
+
diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
|
157 |
+
diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
|
158 |
+
diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
|
159 |
+
diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
|
160 |
+
diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
|
161 |
+
diffusers_name = diffusers_name.replace("proj.in", "proj_in")
|
162 |
+
diffusers_name = diffusers_name.replace("proj.out", "proj_out")
|
163 |
+
diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
|
164 |
+
|
165 |
+
# SDXL specificity.
|
166 |
+
if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
|
167 |
+
pattern = r"\.\d+(?=\D*$)"
|
168 |
+
diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
|
169 |
+
if ".in." in diffusers_name:
|
170 |
+
diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
|
171 |
+
if ".out." in diffusers_name:
|
172 |
+
diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
|
173 |
+
if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
|
174 |
+
diffusers_name = diffusers_name.replace("op", "conv")
|
175 |
+
if "skip" in diffusers_name:
|
176 |
+
diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
|
177 |
+
|
178 |
+
# LyCORIS specificity.
|
179 |
+
if "time.emb.proj" in diffusers_name:
|
180 |
+
diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
|
181 |
+
if "conv.shortcut" in diffusers_name:
|
182 |
+
diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
|
183 |
+
|
184 |
+
# General coverage.
|
185 |
+
if "transformer_blocks" in diffusers_name:
|
186 |
+
if "attn1" in diffusers_name or "attn2" in diffusers_name:
|
187 |
+
diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
|
188 |
+
diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
|
189 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
190 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
191 |
+
elif "ff" in diffusers_name:
|
192 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
193 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
194 |
+
elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
|
195 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
196 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
197 |
+
else:
|
198 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
199 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
200 |
+
|
201 |
+
elif lora_name.startswith("lora_te_"):
|
202 |
+
diffusers_name = key.replace("lora_te_", "").replace("_", ".")
|
203 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
204 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
205 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
206 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
207 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
208 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
209 |
+
if "self_attn" in diffusers_name:
|
210 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
211 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
212 |
+
elif "mlp" in diffusers_name:
|
213 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
214 |
+
# not utilize it yet.
|
215 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
216 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
217 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
218 |
+
|
219 |
+
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
220 |
+
elif lora_name.startswith("lora_te1_"):
|
221 |
+
diffusers_name = key.replace("lora_te1_", "").replace("_", ".")
|
222 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
223 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
224 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
225 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
226 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
227 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
228 |
+
if "self_attn" in diffusers_name:
|
229 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
230 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
231 |
+
elif "mlp" in diffusers_name:
|
232 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
233 |
+
# not utilize it yet.
|
234 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
235 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
236 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
237 |
+
|
238 |
+
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
239 |
+
elif lora_name.startswith("lora_te2_"):
|
240 |
+
diffusers_name = key.replace("lora_te2_", "").replace("_", ".")
|
241 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
242 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
243 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
244 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
245 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
246 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
247 |
+
if "self_attn" in diffusers_name:
|
248 |
+
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
249 |
+
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
250 |
+
elif "mlp" in diffusers_name:
|
251 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
252 |
+
# not utilize it yet.
|
253 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
254 |
+
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
255 |
+
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
256 |
+
|
257 |
+
# Rename the alphas so that they can be mapped appropriately.
|
258 |
+
if lora_name_alpha in state_dict:
|
259 |
+
alpha = state_dict.pop(lora_name_alpha).item()
|
260 |
+
if lora_name_alpha.startswith("lora_unet_"):
|
261 |
+
prefix = "unet."
|
262 |
+
elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
|
263 |
+
prefix = "text_encoder."
|
264 |
+
else:
|
265 |
+
prefix = "text_encoder_2."
|
266 |
+
new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
|
267 |
+
network_alphas.update({new_name: alpha})
|
268 |
+
|
269 |
+
if len(state_dict) > 0:
|
270 |
+
raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
|
271 |
+
|
272 |
+
logger.info("Kohya-style checkpoint detected.")
|
273 |
+
unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
|
274 |
+
te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
|
275 |
+
te2_state_dict = (
|
276 |
+
{f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
|
277 |
+
if len(te2_state_dict) > 0
|
278 |
+
else None
|
279 |
+
)
|
280 |
+
if te2_state_dict is not None:
|
281 |
+
te_state_dict.update(te2_state_dict)
|
282 |
+
|
283 |
+
new_state_dict = {**unet_state_dict, **te_state_dict}
|
284 |
+
return new_state_dict, network_alphas
|
BrushNet/build/lib/diffusers/loaders/peft.py
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
from typing import List, Union
|
16 |
+
|
17 |
+
from ..utils import MIN_PEFT_VERSION, check_peft_version, is_peft_available
|
18 |
+
|
19 |
+
|
20 |
+
class PeftAdapterMixin:
|
21 |
+
"""
|
22 |
+
A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
|
23 |
+
more details about adapters and injecting them in a transformer-based model, check out the PEFT [documentation](https://huggingface.co/docs/peft/index).
|
24 |
+
|
25 |
+
Install the latest version of PEFT, and use this mixin to:
|
26 |
+
|
27 |
+
- Attach new adapters in the model.
|
28 |
+
- Attach multiple adapters and iteratively activate/deactivate them.
|
29 |
+
- Activate/deactivate all adapters from the model.
|
30 |
+
- Get a list of the active adapters.
|
31 |
+
"""
|
32 |
+
|
33 |
+
_hf_peft_config_loaded = False
|
34 |
+
|
35 |
+
def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
|
36 |
+
r"""
|
37 |
+
Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
|
38 |
+
to the adapter to follow the convention of the PEFT library.
|
39 |
+
|
40 |
+
If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
|
41 |
+
[documentation](https://huggingface.co/docs/peft).
|
42 |
+
|
43 |
+
Args:
|
44 |
+
adapter_config (`[~peft.PeftConfig]`):
|
45 |
+
The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
|
46 |
+
methods.
|
47 |
+
adapter_name (`str`, *optional*, defaults to `"default"`):
|
48 |
+
The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
|
49 |
+
"""
|
50 |
+
check_peft_version(min_version=MIN_PEFT_VERSION)
|
51 |
+
|
52 |
+
if not is_peft_available():
|
53 |
+
raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
|
54 |
+
|
55 |
+
from peft import PeftConfig, inject_adapter_in_model
|
56 |
+
|
57 |
+
if not self._hf_peft_config_loaded:
|
58 |
+
self._hf_peft_config_loaded = True
|
59 |
+
elif adapter_name in self.peft_config:
|
60 |
+
raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
|
61 |
+
|
62 |
+
if not isinstance(adapter_config, PeftConfig):
|
63 |
+
raise ValueError(
|
64 |
+
f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
|
65 |
+
)
|
66 |
+
|
67 |
+
# Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
|
68 |
+
# handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.
|
69 |
+
adapter_config.base_model_name_or_path = None
|
70 |
+
inject_adapter_in_model(adapter_config, self, adapter_name)
|
71 |
+
self.set_adapter(adapter_name)
|
72 |
+
|
73 |
+
def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
|
74 |
+
"""
|
75 |
+
Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
|
76 |
+
|
77 |
+
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
|
78 |
+
[documentation](https://huggingface.co/docs/peft).
|
79 |
+
|
80 |
+
Args:
|
81 |
+
adapter_name (Union[str, List[str]])):
|
82 |
+
The list of adapters to set or the adapter name in the case of a single adapter.
|
83 |
+
"""
|
84 |
+
check_peft_version(min_version=MIN_PEFT_VERSION)
|
85 |
+
|
86 |
+
if not self._hf_peft_config_loaded:
|
87 |
+
raise ValueError("No adapter loaded. Please load an adapter first.")
|
88 |
+
|
89 |
+
if isinstance(adapter_name, str):
|
90 |
+
adapter_name = [adapter_name]
|
91 |
+
|
92 |
+
missing = set(adapter_name) - set(self.peft_config)
|
93 |
+
if len(missing) > 0:
|
94 |
+
raise ValueError(
|
95 |
+
f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
|
96 |
+
f" current loaded adapters are: {list(self.peft_config.keys())}"
|
97 |
+
)
|
98 |
+
|
99 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
100 |
+
|
101 |
+
_adapters_has_been_set = False
|
102 |
+
|
103 |
+
for _, module in self.named_modules():
|
104 |
+
if isinstance(module, BaseTunerLayer):
|
105 |
+
if hasattr(module, "set_adapter"):
|
106 |
+
module.set_adapter(adapter_name)
|
107 |
+
# Previous versions of PEFT does not support multi-adapter inference
|
108 |
+
elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
|
109 |
+
raise ValueError(
|
110 |
+
"You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT."
|
111 |
+
" `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
|
112 |
+
)
|
113 |
+
else:
|
114 |
+
module.active_adapter = adapter_name
|
115 |
+
_adapters_has_been_set = True
|
116 |
+
|
117 |
+
if not _adapters_has_been_set:
|
118 |
+
raise ValueError(
|
119 |
+
"Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
|
120 |
+
)
|
121 |
+
|
122 |
+
def disable_adapters(self) -> None:
|
123 |
+
r"""
|
124 |
+
Disable all adapters attached to the model and fallback to inference with the base model only.
|
125 |
+
|
126 |
+
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
|
127 |
+
[documentation](https://huggingface.co/docs/peft).
|
128 |
+
"""
|
129 |
+
check_peft_version(min_version=MIN_PEFT_VERSION)
|
130 |
+
|
131 |
+
if not self._hf_peft_config_loaded:
|
132 |
+
raise ValueError("No adapter loaded. Please load an adapter first.")
|
133 |
+
|
134 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
135 |
+
|
136 |
+
for _, module in self.named_modules():
|
137 |
+
if isinstance(module, BaseTunerLayer):
|
138 |
+
if hasattr(module, "enable_adapters"):
|
139 |
+
module.enable_adapters(enabled=False)
|
140 |
+
else:
|
141 |
+
# support for older PEFT versions
|
142 |
+
module.disable_adapters = True
|
143 |
+
|
144 |
+
def enable_adapters(self) -> None:
|
145 |
+
"""
|
146 |
+
Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the
|
147 |
+
list of adapters to enable.
|
148 |
+
|
149 |
+
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
|
150 |
+
[documentation](https://huggingface.co/docs/peft).
|
151 |
+
"""
|
152 |
+
check_peft_version(min_version=MIN_PEFT_VERSION)
|
153 |
+
|
154 |
+
if not self._hf_peft_config_loaded:
|
155 |
+
raise ValueError("No adapter loaded. Please load an adapter first.")
|
156 |
+
|
157 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
158 |
+
|
159 |
+
for _, module in self.named_modules():
|
160 |
+
if isinstance(module, BaseTunerLayer):
|
161 |
+
if hasattr(module, "enable_adapters"):
|
162 |
+
module.enable_adapters(enabled=True)
|
163 |
+
else:
|
164 |
+
# support for older PEFT versions
|
165 |
+
module.disable_adapters = False
|
166 |
+
|
167 |
+
def active_adapters(self) -> List[str]:
|
168 |
+
"""
|
169 |
+
Gets the current list of active adapters of the model.
|
170 |
+
|
171 |
+
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
|
172 |
+
[documentation](https://huggingface.co/docs/peft).
|
173 |
+
"""
|
174 |
+
check_peft_version(min_version=MIN_PEFT_VERSION)
|
175 |
+
|
176 |
+
if not is_peft_available():
|
177 |
+
raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
|
178 |
+
|
179 |
+
if not self._hf_peft_config_loaded:
|
180 |
+
raise ValueError("No adapter loaded. Please load an adapter first.")
|
181 |
+
|
182 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
183 |
+
|
184 |
+
for _, module in self.named_modules():
|
185 |
+
if isinstance(module, BaseTunerLayer):
|
186 |
+
return module.active_adapter
|
BrushNet/build/lib/diffusers/loaders/single_file.py
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
16 |
+
|
17 |
+
from ..utils import is_transformers_available, logging
|
18 |
+
from .single_file_utils import (
|
19 |
+
create_diffusers_unet_model_from_ldm,
|
20 |
+
create_diffusers_vae_model_from_ldm,
|
21 |
+
create_scheduler_from_ldm,
|
22 |
+
create_text_encoders_and_tokenizers_from_ldm,
|
23 |
+
fetch_ldm_config_and_checkpoint,
|
24 |
+
infer_model_type,
|
25 |
+
)
|
26 |
+
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
# Pipelines that support the SDXL Refiner checkpoint
|
31 |
+
REFINER_PIPELINES = [
|
32 |
+
"StableDiffusionXLImg2ImgPipeline",
|
33 |
+
"StableDiffusionXLInpaintPipeline",
|
34 |
+
"StableDiffusionXLControlNetImg2ImgPipeline",
|
35 |
+
]
|
36 |
+
|
37 |
+
if is_transformers_available():
|
38 |
+
from transformers import AutoFeatureExtractor
|
39 |
+
|
40 |
+
|
41 |
+
def build_sub_model_components(
|
42 |
+
pipeline_components,
|
43 |
+
pipeline_class_name,
|
44 |
+
component_name,
|
45 |
+
original_config,
|
46 |
+
checkpoint,
|
47 |
+
local_files_only=False,
|
48 |
+
load_safety_checker=False,
|
49 |
+
model_type=None,
|
50 |
+
image_size=None,
|
51 |
+
torch_dtype=None,
|
52 |
+
**kwargs,
|
53 |
+
):
|
54 |
+
if component_name in pipeline_components:
|
55 |
+
return {}
|
56 |
+
|
57 |
+
if component_name == "unet":
|
58 |
+
num_in_channels = kwargs.pop("num_in_channels", None)
|
59 |
+
unet_components = create_diffusers_unet_model_from_ldm(
|
60 |
+
pipeline_class_name,
|
61 |
+
original_config,
|
62 |
+
checkpoint,
|
63 |
+
num_in_channels=num_in_channels,
|
64 |
+
image_size=image_size,
|
65 |
+
torch_dtype=torch_dtype,
|
66 |
+
model_type=model_type,
|
67 |
+
)
|
68 |
+
return unet_components
|
69 |
+
|
70 |
+
if component_name == "vae":
|
71 |
+
scaling_factor = kwargs.get("scaling_factor", None)
|
72 |
+
vae_components = create_diffusers_vae_model_from_ldm(
|
73 |
+
pipeline_class_name,
|
74 |
+
original_config,
|
75 |
+
checkpoint,
|
76 |
+
image_size,
|
77 |
+
scaling_factor,
|
78 |
+
torch_dtype,
|
79 |
+
model_type=model_type,
|
80 |
+
)
|
81 |
+
return vae_components
|
82 |
+
|
83 |
+
if component_name == "scheduler":
|
84 |
+
scheduler_type = kwargs.get("scheduler_type", "ddim")
|
85 |
+
prediction_type = kwargs.get("prediction_type", None)
|
86 |
+
|
87 |
+
scheduler_components = create_scheduler_from_ldm(
|
88 |
+
pipeline_class_name,
|
89 |
+
original_config,
|
90 |
+
checkpoint,
|
91 |
+
scheduler_type=scheduler_type,
|
92 |
+
prediction_type=prediction_type,
|
93 |
+
model_type=model_type,
|
94 |
+
)
|
95 |
+
|
96 |
+
return scheduler_components
|
97 |
+
|
98 |
+
if component_name in ["text_encoder", "text_encoder_2", "tokenizer", "tokenizer_2"]:
|
99 |
+
text_encoder_components = create_text_encoders_and_tokenizers_from_ldm(
|
100 |
+
original_config,
|
101 |
+
checkpoint,
|
102 |
+
model_type=model_type,
|
103 |
+
local_files_only=local_files_only,
|
104 |
+
torch_dtype=torch_dtype,
|
105 |
+
)
|
106 |
+
return text_encoder_components
|
107 |
+
|
108 |
+
if component_name == "safety_checker":
|
109 |
+
if load_safety_checker:
|
110 |
+
from ..pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
111 |
+
|
112 |
+
safety_checker = StableDiffusionSafetyChecker.from_pretrained(
|
113 |
+
"CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only, torch_dtype=torch_dtype
|
114 |
+
)
|
115 |
+
else:
|
116 |
+
safety_checker = None
|
117 |
+
return {"safety_checker": safety_checker}
|
118 |
+
|
119 |
+
if component_name == "feature_extractor":
|
120 |
+
if load_safety_checker:
|
121 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
122 |
+
"CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
|
123 |
+
)
|
124 |
+
else:
|
125 |
+
feature_extractor = None
|
126 |
+
return {"feature_extractor": feature_extractor}
|
127 |
+
|
128 |
+
return
|
129 |
+
|
130 |
+
|
131 |
+
def set_additional_components(
|
132 |
+
pipeline_class_name,
|
133 |
+
original_config,
|
134 |
+
checkpoint=None,
|
135 |
+
model_type=None,
|
136 |
+
):
|
137 |
+
components = {}
|
138 |
+
if pipeline_class_name in REFINER_PIPELINES:
|
139 |
+
model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
|
140 |
+
is_refiner = model_type == "SDXL-Refiner"
|
141 |
+
components.update(
|
142 |
+
{
|
143 |
+
"requires_aesthetics_score": is_refiner,
|
144 |
+
"force_zeros_for_empty_prompt": False if is_refiner else True,
|
145 |
+
}
|
146 |
+
)
|
147 |
+
|
148 |
+
return components
|
149 |
+
|
150 |
+
|
151 |
+
class FromSingleFileMixin:
|
152 |
+
"""
|
153 |
+
Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
|
154 |
+
"""
|
155 |
+
|
156 |
+
@classmethod
|
157 |
+
@validate_hf_hub_args
|
158 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
159 |
+
r"""
|
160 |
+
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
|
161 |
+
format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
162 |
+
|
163 |
+
Parameters:
|
164 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
165 |
+
Can be either:
|
166 |
+
- A link to the `.ckpt` file (for example
|
167 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
168 |
+
- A path to a *file* containing all pipeline weights.
|
169 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
170 |
+
Override the default `torch.dtype` and load the model with another dtype.
|
171 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
172 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
173 |
+
cached versions if they exist.
|
174 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
175 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
176 |
+
is not used.
|
177 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
178 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
179 |
+
incompletely downloaded files are deleted.
|
180 |
+
proxies (`Dict[str, str]`, *optional*):
|
181 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
182 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
183 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
184 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
185 |
+
won't be downloaded from the Hub.
|
186 |
+
token (`str` or *bool*, *optional*):
|
187 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
188 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
189 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
190 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
191 |
+
allowed by Git.
|
192 |
+
original_config_file (`str`, *optional*):
|
193 |
+
The path to the original config file that was used to train the model. If not provided, the config file
|
194 |
+
will be inferred from the checkpoint file.
|
195 |
+
model_type (`str`, *optional*):
|
196 |
+
The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
|
197 |
+
image_size (`int`, *optional*):
|
198 |
+
The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE model.
|
199 |
+
load_safety_checker (`bool`, *optional*, defaults to `False`):
|
200 |
+
Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a `safety_checker` component is passed to the `kwargs`.
|
201 |
+
num_in_channels (`int`, *optional*):
|
202 |
+
Specify the number of input channels for the UNet model. Read more about how to configure UNet model with this parameter
|
203 |
+
[here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
|
204 |
+
scaling_factor (`float`, *optional*):
|
205 |
+
The scaling factor to use for the VAE model. If not provided, it is inferred from the config file first.
|
206 |
+
If the scaling factor is not found in the config file, the default value 0.18215 is used.
|
207 |
+
scheduler_type (`str`, *optional*):
|
208 |
+
The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint file.
|
209 |
+
prediction_type (`str`, *optional*):
|
210 |
+
The type of prediction to load. If not provided, the prediction type will be inferred from the checkpoint file.
|
211 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
212 |
+
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
|
213 |
+
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
|
214 |
+
below for more information.
|
215 |
+
|
216 |
+
Examples:
|
217 |
+
|
218 |
+
```py
|
219 |
+
>>> from diffusers import StableDiffusionPipeline
|
220 |
+
|
221 |
+
>>> # Download pipeline from huggingface.co and cache.
|
222 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
223 |
+
... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
|
224 |
+
... )
|
225 |
+
|
226 |
+
>>> # Download pipeline from local file
|
227 |
+
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
|
228 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
|
229 |
+
|
230 |
+
>>> # Enable float16 and move to GPU
|
231 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
232 |
+
... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
|
233 |
+
... torch_dtype=torch.float16,
|
234 |
+
... )
|
235 |
+
>>> pipeline.to("cuda")
|
236 |
+
```
|
237 |
+
"""
|
238 |
+
original_config_file = kwargs.pop("original_config_file", None)
|
239 |
+
resume_download = kwargs.pop("resume_download", False)
|
240 |
+
force_download = kwargs.pop("force_download", False)
|
241 |
+
proxies = kwargs.pop("proxies", None)
|
242 |
+
token = kwargs.pop("token", None)
|
243 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
244 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
245 |
+
revision = kwargs.pop("revision", None)
|
246 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
247 |
+
|
248 |
+
class_name = cls.__name__
|
249 |
+
|
250 |
+
original_config, checkpoint = fetch_ldm_config_and_checkpoint(
|
251 |
+
pretrained_model_link_or_path=pretrained_model_link_or_path,
|
252 |
+
class_name=class_name,
|
253 |
+
original_config_file=original_config_file,
|
254 |
+
resume_download=resume_download,
|
255 |
+
force_download=force_download,
|
256 |
+
proxies=proxies,
|
257 |
+
token=token,
|
258 |
+
revision=revision,
|
259 |
+
local_files_only=local_files_only,
|
260 |
+
cache_dir=cache_dir,
|
261 |
+
)
|
262 |
+
|
263 |
+
from ..pipelines.pipeline_utils import _get_pipeline_class
|
264 |
+
|
265 |
+
pipeline_class = _get_pipeline_class(
|
266 |
+
cls,
|
267 |
+
config=None,
|
268 |
+
cache_dir=cache_dir,
|
269 |
+
)
|
270 |
+
|
271 |
+
expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class)
|
272 |
+
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
|
273 |
+
passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
|
274 |
+
|
275 |
+
model_type = kwargs.pop("model_type", None)
|
276 |
+
image_size = kwargs.pop("image_size", None)
|
277 |
+
load_safety_checker = (kwargs.pop("load_safety_checker", False)) or (
|
278 |
+
passed_class_obj.get("safety_checker", None) is not None
|
279 |
+
)
|
280 |
+
|
281 |
+
init_kwargs = {}
|
282 |
+
for name in expected_modules:
|
283 |
+
if name in passed_class_obj:
|
284 |
+
init_kwargs[name] = passed_class_obj[name]
|
285 |
+
else:
|
286 |
+
components = build_sub_model_components(
|
287 |
+
init_kwargs,
|
288 |
+
class_name,
|
289 |
+
name,
|
290 |
+
original_config,
|
291 |
+
checkpoint,
|
292 |
+
model_type=model_type,
|
293 |
+
image_size=image_size,
|
294 |
+
load_safety_checker=load_safety_checker,
|
295 |
+
local_files_only=local_files_only,
|
296 |
+
torch_dtype=torch_dtype,
|
297 |
+
**kwargs,
|
298 |
+
)
|
299 |
+
if not components:
|
300 |
+
continue
|
301 |
+
init_kwargs.update(components)
|
302 |
+
|
303 |
+
additional_components = set_additional_components(class_name, original_config, model_type=model_type)
|
304 |
+
if additional_components:
|
305 |
+
init_kwargs.update(additional_components)
|
306 |
+
|
307 |
+
init_kwargs.update(passed_pipe_kwargs)
|
308 |
+
pipe = pipeline_class(**init_kwargs)
|
309 |
+
|
310 |
+
if torch_dtype is not None:
|
311 |
+
pipe.to(dtype=torch_dtype)
|
312 |
+
|
313 |
+
return pipe
|
BrushNet/build/lib/diffusers/loaders/single_file_utils.py
ADDED
@@ -0,0 +1,1513 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" Conversion script for the Stable Diffusion checkpoints."""
|
16 |
+
|
17 |
+
import os
|
18 |
+
import re
|
19 |
+
from contextlib import nullcontext
|
20 |
+
from io import BytesIO
|
21 |
+
from urllib.parse import urlparse
|
22 |
+
|
23 |
+
import requests
|
24 |
+
import yaml
|
25 |
+
|
26 |
+
from ..models.modeling_utils import load_state_dict
|
27 |
+
from ..schedulers import (
|
28 |
+
DDIMScheduler,
|
29 |
+
DDPMScheduler,
|
30 |
+
DPMSolverMultistepScheduler,
|
31 |
+
EDMDPMSolverMultistepScheduler,
|
32 |
+
EulerAncestralDiscreteScheduler,
|
33 |
+
EulerDiscreteScheduler,
|
34 |
+
HeunDiscreteScheduler,
|
35 |
+
LMSDiscreteScheduler,
|
36 |
+
PNDMScheduler,
|
37 |
+
)
|
38 |
+
from ..utils import is_accelerate_available, is_transformers_available, logging
|
39 |
+
from ..utils.hub_utils import _get_model_file
|
40 |
+
|
41 |
+
|
42 |
+
if is_transformers_available():
|
43 |
+
from transformers import (
|
44 |
+
CLIPTextConfig,
|
45 |
+
CLIPTextModel,
|
46 |
+
CLIPTextModelWithProjection,
|
47 |
+
CLIPTokenizer,
|
48 |
+
)
|
49 |
+
|
50 |
+
if is_accelerate_available():
|
51 |
+
from accelerate import init_empty_weights
|
52 |
+
|
53 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
54 |
+
|
55 |
+
CONFIG_URLS = {
|
56 |
+
"v1": "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml",
|
57 |
+
"v2": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml",
|
58 |
+
"xl": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml",
|
59 |
+
"xl_refiner": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml",
|
60 |
+
"upscale": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml",
|
61 |
+
"controlnet": "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml",
|
62 |
+
}
|
63 |
+
|
64 |
+
CHECKPOINT_KEY_NAMES = {
|
65 |
+
"v2": "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight",
|
66 |
+
"xl_base": "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias",
|
67 |
+
"xl_refiner": "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias",
|
68 |
+
}
|
69 |
+
|
70 |
+
SCHEDULER_DEFAULT_CONFIG = {
|
71 |
+
"beta_schedule": "scaled_linear",
|
72 |
+
"beta_start": 0.00085,
|
73 |
+
"beta_end": 0.012,
|
74 |
+
"interpolation_type": "linear",
|
75 |
+
"num_train_timesteps": 1000,
|
76 |
+
"prediction_type": "epsilon",
|
77 |
+
"sample_max_value": 1.0,
|
78 |
+
"set_alpha_to_one": False,
|
79 |
+
"skip_prk_steps": True,
|
80 |
+
"steps_offset": 1,
|
81 |
+
"timestep_spacing": "leading",
|
82 |
+
}
|
83 |
+
|
84 |
+
DIFFUSERS_TO_LDM_MAPPING = {
|
85 |
+
"unet": {
|
86 |
+
"layers": {
|
87 |
+
"time_embedding.linear_1.weight": "time_embed.0.weight",
|
88 |
+
"time_embedding.linear_1.bias": "time_embed.0.bias",
|
89 |
+
"time_embedding.linear_2.weight": "time_embed.2.weight",
|
90 |
+
"time_embedding.linear_2.bias": "time_embed.2.bias",
|
91 |
+
"conv_in.weight": "input_blocks.0.0.weight",
|
92 |
+
"conv_in.bias": "input_blocks.0.0.bias",
|
93 |
+
"conv_norm_out.weight": "out.0.weight",
|
94 |
+
"conv_norm_out.bias": "out.0.bias",
|
95 |
+
"conv_out.weight": "out.2.weight",
|
96 |
+
"conv_out.bias": "out.2.bias",
|
97 |
+
},
|
98 |
+
"class_embed_type": {
|
99 |
+
"class_embedding.linear_1.weight": "label_emb.0.0.weight",
|
100 |
+
"class_embedding.linear_1.bias": "label_emb.0.0.bias",
|
101 |
+
"class_embedding.linear_2.weight": "label_emb.0.2.weight",
|
102 |
+
"class_embedding.linear_2.bias": "label_emb.0.2.bias",
|
103 |
+
},
|
104 |
+
"addition_embed_type": {
|
105 |
+
"add_embedding.linear_1.weight": "label_emb.0.0.weight",
|
106 |
+
"add_embedding.linear_1.bias": "label_emb.0.0.bias",
|
107 |
+
"add_embedding.linear_2.weight": "label_emb.0.2.weight",
|
108 |
+
"add_embedding.linear_2.bias": "label_emb.0.2.bias",
|
109 |
+
},
|
110 |
+
},
|
111 |
+
"controlnet": {
|
112 |
+
"layers": {
|
113 |
+
"time_embedding.linear_1.weight": "time_embed.0.weight",
|
114 |
+
"time_embedding.linear_1.bias": "time_embed.0.bias",
|
115 |
+
"time_embedding.linear_2.weight": "time_embed.2.weight",
|
116 |
+
"time_embedding.linear_2.bias": "time_embed.2.bias",
|
117 |
+
"conv_in.weight": "input_blocks.0.0.weight",
|
118 |
+
"conv_in.bias": "input_blocks.0.0.bias",
|
119 |
+
"controlnet_cond_embedding.conv_in.weight": "input_hint_block.0.weight",
|
120 |
+
"controlnet_cond_embedding.conv_in.bias": "input_hint_block.0.bias",
|
121 |
+
"controlnet_cond_embedding.conv_out.weight": "input_hint_block.14.weight",
|
122 |
+
"controlnet_cond_embedding.conv_out.bias": "input_hint_block.14.bias",
|
123 |
+
},
|
124 |
+
"class_embed_type": {
|
125 |
+
"class_embedding.linear_1.weight": "label_emb.0.0.weight",
|
126 |
+
"class_embedding.linear_1.bias": "label_emb.0.0.bias",
|
127 |
+
"class_embedding.linear_2.weight": "label_emb.0.2.weight",
|
128 |
+
"class_embedding.linear_2.bias": "label_emb.0.2.bias",
|
129 |
+
},
|
130 |
+
"addition_embed_type": {
|
131 |
+
"add_embedding.linear_1.weight": "label_emb.0.0.weight",
|
132 |
+
"add_embedding.linear_1.bias": "label_emb.0.0.bias",
|
133 |
+
"add_embedding.linear_2.weight": "label_emb.0.2.weight",
|
134 |
+
"add_embedding.linear_2.bias": "label_emb.0.2.bias",
|
135 |
+
},
|
136 |
+
},
|
137 |
+
"vae": {
|
138 |
+
"encoder.conv_in.weight": "encoder.conv_in.weight",
|
139 |
+
"encoder.conv_in.bias": "encoder.conv_in.bias",
|
140 |
+
"encoder.conv_out.weight": "encoder.conv_out.weight",
|
141 |
+
"encoder.conv_out.bias": "encoder.conv_out.bias",
|
142 |
+
"encoder.conv_norm_out.weight": "encoder.norm_out.weight",
|
143 |
+
"encoder.conv_norm_out.bias": "encoder.norm_out.bias",
|
144 |
+
"decoder.conv_in.weight": "decoder.conv_in.weight",
|
145 |
+
"decoder.conv_in.bias": "decoder.conv_in.bias",
|
146 |
+
"decoder.conv_out.weight": "decoder.conv_out.weight",
|
147 |
+
"decoder.conv_out.bias": "decoder.conv_out.bias",
|
148 |
+
"decoder.conv_norm_out.weight": "decoder.norm_out.weight",
|
149 |
+
"decoder.conv_norm_out.bias": "decoder.norm_out.bias",
|
150 |
+
"quant_conv.weight": "quant_conv.weight",
|
151 |
+
"quant_conv.bias": "quant_conv.bias",
|
152 |
+
"post_quant_conv.weight": "post_quant_conv.weight",
|
153 |
+
"post_quant_conv.bias": "post_quant_conv.bias",
|
154 |
+
},
|
155 |
+
"openclip": {
|
156 |
+
"layers": {
|
157 |
+
"text_model.embeddings.position_embedding.weight": "positional_embedding",
|
158 |
+
"text_model.embeddings.token_embedding.weight": "token_embedding.weight",
|
159 |
+
"text_model.final_layer_norm.weight": "ln_final.weight",
|
160 |
+
"text_model.final_layer_norm.bias": "ln_final.bias",
|
161 |
+
"text_projection.weight": "text_projection",
|
162 |
+
},
|
163 |
+
"transformer": {
|
164 |
+
"text_model.encoder.layers.": "resblocks.",
|
165 |
+
"layer_norm1": "ln_1",
|
166 |
+
"layer_norm2": "ln_2",
|
167 |
+
".fc1.": ".c_fc.",
|
168 |
+
".fc2.": ".c_proj.",
|
169 |
+
".self_attn": ".attn",
|
170 |
+
"transformer.text_model.final_layer_norm.": "ln_final.",
|
171 |
+
"transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
|
172 |
+
"transformer.text_model.embeddings.position_embedding.weight": "positional_embedding",
|
173 |
+
},
|
174 |
+
},
|
175 |
+
}
|
176 |
+
|
177 |
+
LDM_VAE_KEY = "first_stage_model."
|
178 |
+
LDM_VAE_DEFAULT_SCALING_FACTOR = 0.18215
|
179 |
+
PLAYGROUND_VAE_SCALING_FACTOR = 0.5
|
180 |
+
LDM_UNET_KEY = "model.diffusion_model."
|
181 |
+
LDM_CONTROLNET_KEY = "control_model."
|
182 |
+
LDM_CLIP_PREFIX_TO_REMOVE = ["cond_stage_model.transformer.", "conditioner.embedders.0.transformer."]
|
183 |
+
LDM_OPEN_CLIP_TEXT_PROJECTION_DIM = 1024
|
184 |
+
|
185 |
+
SD_2_TEXT_ENCODER_KEYS_TO_IGNORE = [
|
186 |
+
"cond_stage_model.model.transformer.resblocks.23.attn.in_proj_bias",
|
187 |
+
"cond_stage_model.model.transformer.resblocks.23.attn.in_proj_weight",
|
188 |
+
"cond_stage_model.model.transformer.resblocks.23.attn.out_proj.bias",
|
189 |
+
"cond_stage_model.model.transformer.resblocks.23.attn.out_proj.weight",
|
190 |
+
"cond_stage_model.model.transformer.resblocks.23.ln_1.bias",
|
191 |
+
"cond_stage_model.model.transformer.resblocks.23.ln_1.weight",
|
192 |
+
"cond_stage_model.model.transformer.resblocks.23.ln_2.bias",
|
193 |
+
"cond_stage_model.model.transformer.resblocks.23.ln_2.weight",
|
194 |
+
"cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.bias",
|
195 |
+
"cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.weight",
|
196 |
+
"cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.bias",
|
197 |
+
"cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.weight",
|
198 |
+
"cond_stage_model.model.text_projection",
|
199 |
+
]
|
200 |
+
|
201 |
+
|
202 |
+
VALID_URL_PREFIXES = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
|
203 |
+
|
204 |
+
|
205 |
+
def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
|
206 |
+
pattern = r"([^/]+)/([^/]+)/(?:blob/main/)?(.+)"
|
207 |
+
weights_name = None
|
208 |
+
repo_id = (None,)
|
209 |
+
for prefix in VALID_URL_PREFIXES:
|
210 |
+
pretrained_model_name_or_path = pretrained_model_name_or_path.replace(prefix, "")
|
211 |
+
match = re.match(pattern, pretrained_model_name_or_path)
|
212 |
+
if not match:
|
213 |
+
return repo_id, weights_name
|
214 |
+
|
215 |
+
repo_id = f"{match.group(1)}/{match.group(2)}"
|
216 |
+
weights_name = match.group(3)
|
217 |
+
|
218 |
+
return repo_id, weights_name
|
219 |
+
|
220 |
+
|
221 |
+
def fetch_ldm_config_and_checkpoint(
|
222 |
+
pretrained_model_link_or_path,
|
223 |
+
class_name,
|
224 |
+
original_config_file=None,
|
225 |
+
resume_download=False,
|
226 |
+
force_download=False,
|
227 |
+
proxies=None,
|
228 |
+
token=None,
|
229 |
+
cache_dir=None,
|
230 |
+
local_files_only=None,
|
231 |
+
revision=None,
|
232 |
+
):
|
233 |
+
if os.path.isfile(pretrained_model_link_or_path):
|
234 |
+
checkpoint = load_state_dict(pretrained_model_link_or_path)
|
235 |
+
|
236 |
+
else:
|
237 |
+
repo_id, weights_name = _extract_repo_id_and_weights_name(pretrained_model_link_or_path)
|
238 |
+
checkpoint_path = _get_model_file(
|
239 |
+
repo_id,
|
240 |
+
weights_name=weights_name,
|
241 |
+
force_download=force_download,
|
242 |
+
cache_dir=cache_dir,
|
243 |
+
resume_download=resume_download,
|
244 |
+
proxies=proxies,
|
245 |
+
local_files_only=local_files_only,
|
246 |
+
token=token,
|
247 |
+
revision=revision,
|
248 |
+
)
|
249 |
+
checkpoint = load_state_dict(checkpoint_path)
|
250 |
+
|
251 |
+
# some checkpoints contain the model state dict under a "state_dict" key
|
252 |
+
while "state_dict" in checkpoint:
|
253 |
+
checkpoint = checkpoint["state_dict"]
|
254 |
+
|
255 |
+
original_config = fetch_original_config(class_name, checkpoint, original_config_file)
|
256 |
+
|
257 |
+
return original_config, checkpoint
|
258 |
+
|
259 |
+
|
260 |
+
def infer_original_config_file(class_name, checkpoint):
|
261 |
+
if CHECKPOINT_KEY_NAMES["v2"] in checkpoint and checkpoint[CHECKPOINT_KEY_NAMES["v2"]].shape[-1] == 1024:
|
262 |
+
config_url = CONFIG_URLS["v2"]
|
263 |
+
|
264 |
+
elif CHECKPOINT_KEY_NAMES["xl_base"] in checkpoint:
|
265 |
+
config_url = CONFIG_URLS["xl"]
|
266 |
+
|
267 |
+
elif CHECKPOINT_KEY_NAMES["xl_refiner"] in checkpoint:
|
268 |
+
config_url = CONFIG_URLS["xl_refiner"]
|
269 |
+
|
270 |
+
elif class_name == "StableDiffusionUpscalePipeline":
|
271 |
+
config_url = CONFIG_URLS["upscale"]
|
272 |
+
|
273 |
+
elif class_name == "ControlNetModel":
|
274 |
+
config_url = CONFIG_URLS["controlnet"]
|
275 |
+
|
276 |
+
else:
|
277 |
+
config_url = CONFIG_URLS["v1"]
|
278 |
+
|
279 |
+
original_config_file = BytesIO(requests.get(config_url).content)
|
280 |
+
|
281 |
+
return original_config_file
|
282 |
+
|
283 |
+
|
284 |
+
def fetch_original_config(pipeline_class_name, checkpoint, original_config_file=None):
|
285 |
+
def is_valid_url(url):
|
286 |
+
result = urlparse(url)
|
287 |
+
if result.scheme and result.netloc:
|
288 |
+
return True
|
289 |
+
|
290 |
+
return False
|
291 |
+
|
292 |
+
if original_config_file is None:
|
293 |
+
original_config_file = infer_original_config_file(pipeline_class_name, checkpoint)
|
294 |
+
|
295 |
+
elif os.path.isfile(original_config_file):
|
296 |
+
with open(original_config_file, "r") as fp:
|
297 |
+
original_config_file = fp.read()
|
298 |
+
|
299 |
+
elif is_valid_url(original_config_file):
|
300 |
+
original_config_file = BytesIO(requests.get(original_config_file).content)
|
301 |
+
|
302 |
+
else:
|
303 |
+
raise ValueError("Invalid `original_config_file` provided. Please set it to a valid file path or URL.")
|
304 |
+
|
305 |
+
original_config = yaml.safe_load(original_config_file)
|
306 |
+
|
307 |
+
return original_config
|
308 |
+
|
309 |
+
|
310 |
+
def infer_model_type(original_config, checkpoint=None, model_type=None):
|
311 |
+
if model_type is not None:
|
312 |
+
return model_type
|
313 |
+
|
314 |
+
has_cond_stage_config = (
|
315 |
+
"cond_stage_config" in original_config["model"]["params"]
|
316 |
+
and original_config["model"]["params"]["cond_stage_config"] is not None
|
317 |
+
)
|
318 |
+
has_network_config = (
|
319 |
+
"network_config" in original_config["model"]["params"]
|
320 |
+
and original_config["model"]["params"]["network_config"] is not None
|
321 |
+
)
|
322 |
+
|
323 |
+
if has_cond_stage_config:
|
324 |
+
model_type = original_config["model"]["params"]["cond_stage_config"]["target"].split(".")[-1]
|
325 |
+
|
326 |
+
elif has_network_config:
|
327 |
+
context_dim = original_config["model"]["params"]["network_config"]["params"]["context_dim"]
|
328 |
+
if "edm_mean" in checkpoint and "edm_std" in checkpoint:
|
329 |
+
model_type = "Playground"
|
330 |
+
elif context_dim == 2048:
|
331 |
+
model_type = "SDXL"
|
332 |
+
else:
|
333 |
+
model_type = "SDXL-Refiner"
|
334 |
+
else:
|
335 |
+
raise ValueError("Unable to infer model type from config")
|
336 |
+
|
337 |
+
logger.debug(f"No `model_type` given, `model_type` inferred as: {model_type}")
|
338 |
+
|
339 |
+
return model_type
|
340 |
+
|
341 |
+
|
342 |
+
def get_default_scheduler_config():
|
343 |
+
return SCHEDULER_DEFAULT_CONFIG
|
344 |
+
|
345 |
+
|
346 |
+
def set_image_size(pipeline_class_name, original_config, checkpoint, image_size=None, model_type=None):
|
347 |
+
if image_size:
|
348 |
+
return image_size
|
349 |
+
|
350 |
+
global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
|
351 |
+
model_type = infer_model_type(original_config, checkpoint, model_type)
|
352 |
+
|
353 |
+
if pipeline_class_name == "StableDiffusionUpscalePipeline":
|
354 |
+
image_size = original_config["model"]["params"]["unet_config"]["params"]["image_size"]
|
355 |
+
return image_size
|
356 |
+
|
357 |
+
elif model_type in ["SDXL", "SDXL-Refiner", "Playground"]:
|
358 |
+
image_size = 1024
|
359 |
+
return image_size
|
360 |
+
|
361 |
+
elif (
|
362 |
+
"parameterization" in original_config["model"]["params"]
|
363 |
+
and original_config["model"]["params"]["parameterization"] == "v"
|
364 |
+
):
|
365 |
+
# NOTE: For stable diffusion 2 base one has to pass `image_size==512`
|
366 |
+
# as it relies on a brittle global step parameter here
|
367 |
+
image_size = 512 if global_step == 875000 else 768
|
368 |
+
return image_size
|
369 |
+
|
370 |
+
else:
|
371 |
+
image_size = 512
|
372 |
+
return image_size
|
373 |
+
|
374 |
+
|
375 |
+
# Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.conv_attn_to_linear
|
376 |
+
def conv_attn_to_linear(checkpoint):
|
377 |
+
keys = list(checkpoint.keys())
|
378 |
+
attn_keys = ["query.weight", "key.weight", "value.weight"]
|
379 |
+
for key in keys:
|
380 |
+
if ".".join(key.split(".")[-2:]) in attn_keys:
|
381 |
+
if checkpoint[key].ndim > 2:
|
382 |
+
checkpoint[key] = checkpoint[key][:, :, 0, 0]
|
383 |
+
elif "proj_attn.weight" in key:
|
384 |
+
if checkpoint[key].ndim > 2:
|
385 |
+
checkpoint[key] = checkpoint[key][:, :, 0]
|
386 |
+
|
387 |
+
|
388 |
+
def create_unet_diffusers_config(original_config, image_size: int):
|
389 |
+
"""
|
390 |
+
Creates a config for the diffusers based on the config of the LDM model.
|
391 |
+
"""
|
392 |
+
if (
|
393 |
+
"unet_config" in original_config["model"]["params"]
|
394 |
+
and original_config["model"]["params"]["unet_config"] is not None
|
395 |
+
):
|
396 |
+
unet_params = original_config["model"]["params"]["unet_config"]["params"]
|
397 |
+
else:
|
398 |
+
unet_params = original_config["model"]["params"]["network_config"]["params"]
|
399 |
+
|
400 |
+
vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
|
401 |
+
block_out_channels = [unet_params["model_channels"] * mult for mult in unet_params["channel_mult"]]
|
402 |
+
|
403 |
+
down_block_types = []
|
404 |
+
resolution = 1
|
405 |
+
for i in range(len(block_out_channels)):
|
406 |
+
block_type = "CrossAttnDownBlock2D" if resolution in unet_params["attention_resolutions"] else "DownBlock2D"
|
407 |
+
down_block_types.append(block_type)
|
408 |
+
if i != len(block_out_channels) - 1:
|
409 |
+
resolution *= 2
|
410 |
+
|
411 |
+
up_block_types = []
|
412 |
+
for i in range(len(block_out_channels)):
|
413 |
+
block_type = "CrossAttnUpBlock2D" if resolution in unet_params["attention_resolutions"] else "UpBlock2D"
|
414 |
+
up_block_types.append(block_type)
|
415 |
+
resolution //= 2
|
416 |
+
|
417 |
+
if unet_params["transformer_depth"] is not None:
|
418 |
+
transformer_layers_per_block = (
|
419 |
+
unet_params["transformer_depth"]
|
420 |
+
if isinstance(unet_params["transformer_depth"], int)
|
421 |
+
else list(unet_params["transformer_depth"])
|
422 |
+
)
|
423 |
+
else:
|
424 |
+
transformer_layers_per_block = 1
|
425 |
+
|
426 |
+
vae_scale_factor = 2 ** (len(vae_params["ch_mult"]) - 1)
|
427 |
+
|
428 |
+
head_dim = unet_params["num_heads"] if "num_heads" in unet_params else None
|
429 |
+
use_linear_projection = (
|
430 |
+
unet_params["use_linear_in_transformer"] if "use_linear_in_transformer" in unet_params else False
|
431 |
+
)
|
432 |
+
if use_linear_projection:
|
433 |
+
# stable diffusion 2-base-512 and 2-768
|
434 |
+
if head_dim is None:
|
435 |
+
head_dim_mult = unet_params["model_channels"] // unet_params["num_head_channels"]
|
436 |
+
head_dim = [head_dim_mult * c for c in list(unet_params["channel_mult"])]
|
437 |
+
|
438 |
+
class_embed_type = None
|
439 |
+
addition_embed_type = None
|
440 |
+
addition_time_embed_dim = None
|
441 |
+
projection_class_embeddings_input_dim = None
|
442 |
+
context_dim = None
|
443 |
+
|
444 |
+
if unet_params["context_dim"] is not None:
|
445 |
+
context_dim = (
|
446 |
+
unet_params["context_dim"]
|
447 |
+
if isinstance(unet_params["context_dim"], int)
|
448 |
+
else unet_params["context_dim"][0]
|
449 |
+
)
|
450 |
+
|
451 |
+
if "num_classes" in unet_params:
|
452 |
+
if unet_params["num_classes"] == "sequential":
|
453 |
+
if context_dim in [2048, 1280]:
|
454 |
+
# SDXL
|
455 |
+
addition_embed_type = "text_time"
|
456 |
+
addition_time_embed_dim = 256
|
457 |
+
else:
|
458 |
+
class_embed_type = "projection"
|
459 |
+
assert "adm_in_channels" in unet_params
|
460 |
+
projection_class_embeddings_input_dim = unet_params["adm_in_channels"]
|
461 |
+
|
462 |
+
config = {
|
463 |
+
"sample_size": image_size // vae_scale_factor,
|
464 |
+
"in_channels": unet_params["in_channels"],
|
465 |
+
"down_block_types": down_block_types,
|
466 |
+
"block_out_channels": block_out_channels,
|
467 |
+
"layers_per_block": unet_params["num_res_blocks"],
|
468 |
+
"cross_attention_dim": context_dim,
|
469 |
+
"attention_head_dim": head_dim,
|
470 |
+
"use_linear_projection": use_linear_projection,
|
471 |
+
"class_embed_type": class_embed_type,
|
472 |
+
"addition_embed_type": addition_embed_type,
|
473 |
+
"addition_time_embed_dim": addition_time_embed_dim,
|
474 |
+
"projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
|
475 |
+
"transformer_layers_per_block": transformer_layers_per_block,
|
476 |
+
}
|
477 |
+
|
478 |
+
if "disable_self_attentions" in unet_params:
|
479 |
+
config["only_cross_attention"] = unet_params["disable_self_attentions"]
|
480 |
+
|
481 |
+
if "num_classes" in unet_params and isinstance(unet_params["num_classes"], int):
|
482 |
+
config["num_class_embeds"] = unet_params["num_classes"]
|
483 |
+
|
484 |
+
config["out_channels"] = unet_params["out_channels"]
|
485 |
+
config["up_block_types"] = up_block_types
|
486 |
+
|
487 |
+
return config
|
488 |
+
|
489 |
+
|
490 |
+
def create_controlnet_diffusers_config(original_config, image_size: int):
|
491 |
+
unet_params = original_config["model"]["params"]["control_stage_config"]["params"]
|
492 |
+
diffusers_unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
|
493 |
+
|
494 |
+
controlnet_config = {
|
495 |
+
"conditioning_channels": unet_params["hint_channels"],
|
496 |
+
"in_channels": diffusers_unet_config["in_channels"],
|
497 |
+
"down_block_types": diffusers_unet_config["down_block_types"],
|
498 |
+
"block_out_channels": diffusers_unet_config["block_out_channels"],
|
499 |
+
"layers_per_block": diffusers_unet_config["layers_per_block"],
|
500 |
+
"cross_attention_dim": diffusers_unet_config["cross_attention_dim"],
|
501 |
+
"attention_head_dim": diffusers_unet_config["attention_head_dim"],
|
502 |
+
"use_linear_projection": diffusers_unet_config["use_linear_projection"],
|
503 |
+
"class_embed_type": diffusers_unet_config["class_embed_type"],
|
504 |
+
"addition_embed_type": diffusers_unet_config["addition_embed_type"],
|
505 |
+
"addition_time_embed_dim": diffusers_unet_config["addition_time_embed_dim"],
|
506 |
+
"projection_class_embeddings_input_dim": diffusers_unet_config["projection_class_embeddings_input_dim"],
|
507 |
+
"transformer_layers_per_block": diffusers_unet_config["transformer_layers_per_block"],
|
508 |
+
}
|
509 |
+
|
510 |
+
return controlnet_config
|
511 |
+
|
512 |
+
|
513 |
+
def create_vae_diffusers_config(original_config, image_size, scaling_factor=None, latents_mean=None, latents_std=None):
|
514 |
+
"""
|
515 |
+
Creates a config for the diffusers based on the config of the LDM model.
|
516 |
+
"""
|
517 |
+
vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
|
518 |
+
if (scaling_factor is None) and (latents_mean is not None) and (latents_std is not None):
|
519 |
+
scaling_factor = PLAYGROUND_VAE_SCALING_FACTOR
|
520 |
+
elif (scaling_factor is None) and ("scale_factor" in original_config["model"]["params"]):
|
521 |
+
scaling_factor = original_config["model"]["params"]["scale_factor"]
|
522 |
+
elif scaling_factor is None:
|
523 |
+
scaling_factor = LDM_VAE_DEFAULT_SCALING_FACTOR
|
524 |
+
|
525 |
+
block_out_channels = [vae_params["ch"] * mult for mult in vae_params["ch_mult"]]
|
526 |
+
down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
|
527 |
+
up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
|
528 |
+
|
529 |
+
config = {
|
530 |
+
"sample_size": image_size,
|
531 |
+
"in_channels": vae_params["in_channels"],
|
532 |
+
"out_channels": vae_params["out_ch"],
|
533 |
+
"down_block_types": down_block_types,
|
534 |
+
"up_block_types": up_block_types,
|
535 |
+
"block_out_channels": block_out_channels,
|
536 |
+
"latent_channels": vae_params["z_channels"],
|
537 |
+
"layers_per_block": vae_params["num_res_blocks"],
|
538 |
+
"scaling_factor": scaling_factor,
|
539 |
+
}
|
540 |
+
if latents_mean is not None and latents_std is not None:
|
541 |
+
config.update({"latents_mean": latents_mean, "latents_std": latents_std})
|
542 |
+
|
543 |
+
return config
|
544 |
+
|
545 |
+
|
546 |
+
def update_unet_resnet_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping=None):
|
547 |
+
for ldm_key in ldm_keys:
|
548 |
+
diffusers_key = (
|
549 |
+
ldm_key.replace("in_layers.0", "norm1")
|
550 |
+
.replace("in_layers.2", "conv1")
|
551 |
+
.replace("out_layers.0", "norm2")
|
552 |
+
.replace("out_layers.3", "conv2")
|
553 |
+
.replace("emb_layers.1", "time_emb_proj")
|
554 |
+
.replace("skip_connection", "conv_shortcut")
|
555 |
+
)
|
556 |
+
if mapping:
|
557 |
+
diffusers_key = diffusers_key.replace(mapping["old"], mapping["new"])
|
558 |
+
new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
|
559 |
+
|
560 |
+
|
561 |
+
def update_unet_attention_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping):
|
562 |
+
for ldm_key in ldm_keys:
|
563 |
+
diffusers_key = ldm_key.replace(mapping["old"], mapping["new"])
|
564 |
+
new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
|
565 |
+
|
566 |
+
|
567 |
+
def convert_ldm_unet_checkpoint(checkpoint, config, extract_ema=False):
|
568 |
+
"""
|
569 |
+
Takes a state dict and a config, and returns a converted checkpoint.
|
570 |
+
"""
|
571 |
+
# extract state_dict for UNet
|
572 |
+
unet_state_dict = {}
|
573 |
+
keys = list(checkpoint.keys())
|
574 |
+
unet_key = LDM_UNET_KEY
|
575 |
+
|
576 |
+
# at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
|
577 |
+
if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
|
578 |
+
logger.warning("Checkpoint has both EMA and non-EMA weights.")
|
579 |
+
logger.warning(
|
580 |
+
"In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
|
581 |
+
" weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
|
582 |
+
)
|
583 |
+
for key in keys:
|
584 |
+
if key.startswith("model.diffusion_model"):
|
585 |
+
flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
|
586 |
+
unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
|
587 |
+
else:
|
588 |
+
if sum(k.startswith("model_ema") for k in keys) > 100:
|
589 |
+
logger.warning(
|
590 |
+
"In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
|
591 |
+
" weights (usually better for inference), please make sure to add the `--extract_ema` flag."
|
592 |
+
)
|
593 |
+
for key in keys:
|
594 |
+
if key.startswith(unet_key):
|
595 |
+
unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
|
596 |
+
|
597 |
+
new_checkpoint = {}
|
598 |
+
ldm_unet_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["layers"]
|
599 |
+
for diffusers_key, ldm_key in ldm_unet_keys.items():
|
600 |
+
if ldm_key not in unet_state_dict:
|
601 |
+
continue
|
602 |
+
new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
|
603 |
+
|
604 |
+
if ("class_embed_type" in config) and (config["class_embed_type"] in ["timestep", "projection"]):
|
605 |
+
class_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["class_embed_type"]
|
606 |
+
for diffusers_key, ldm_key in class_embed_keys.items():
|
607 |
+
new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
|
608 |
+
|
609 |
+
if ("addition_embed_type" in config) and (config["addition_embed_type"] == "text_time"):
|
610 |
+
addition_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["addition_embed_type"]
|
611 |
+
for diffusers_key, ldm_key in addition_embed_keys.items():
|
612 |
+
new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
|
613 |
+
|
614 |
+
# Relevant to StableDiffusionUpscalePipeline
|
615 |
+
if "num_class_embeds" in config:
|
616 |
+
if (config["num_class_embeds"] is not None) and ("label_emb.weight" in unet_state_dict):
|
617 |
+
new_checkpoint["class_embedding.weight"] = unet_state_dict["label_emb.weight"]
|
618 |
+
|
619 |
+
# Retrieves the keys for the input blocks only
|
620 |
+
num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
|
621 |
+
input_blocks = {
|
622 |
+
layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
|
623 |
+
for layer_id in range(num_input_blocks)
|
624 |
+
}
|
625 |
+
|
626 |
+
# Retrieves the keys for the middle blocks only
|
627 |
+
num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
|
628 |
+
middle_blocks = {
|
629 |
+
layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
|
630 |
+
for layer_id in range(num_middle_blocks)
|
631 |
+
}
|
632 |
+
|
633 |
+
# Retrieves the keys for the output blocks only
|
634 |
+
num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
|
635 |
+
output_blocks = {
|
636 |
+
layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
|
637 |
+
for layer_id in range(num_output_blocks)
|
638 |
+
}
|
639 |
+
|
640 |
+
# Down blocks
|
641 |
+
for i in range(1, num_input_blocks):
|
642 |
+
block_id = (i - 1) // (config["layers_per_block"] + 1)
|
643 |
+
layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
|
644 |
+
|
645 |
+
resnets = [
|
646 |
+
key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
|
647 |
+
]
|
648 |
+
update_unet_resnet_ldm_to_diffusers(
|
649 |
+
resnets,
|
650 |
+
new_checkpoint,
|
651 |
+
unet_state_dict,
|
652 |
+
{"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
|
653 |
+
)
|
654 |
+
|
655 |
+
if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
|
656 |
+
new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
|
657 |
+
f"input_blocks.{i}.0.op.weight"
|
658 |
+
)
|
659 |
+
new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
|
660 |
+
f"input_blocks.{i}.0.op.bias"
|
661 |
+
)
|
662 |
+
|
663 |
+
attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
|
664 |
+
if attentions:
|
665 |
+
update_unet_attention_ldm_to_diffusers(
|
666 |
+
attentions,
|
667 |
+
new_checkpoint,
|
668 |
+
unet_state_dict,
|
669 |
+
{"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
|
670 |
+
)
|
671 |
+
|
672 |
+
# Mid blocks
|
673 |
+
resnet_0 = middle_blocks[0]
|
674 |
+
attentions = middle_blocks[1]
|
675 |
+
resnet_1 = middle_blocks[2]
|
676 |
+
|
677 |
+
update_unet_resnet_ldm_to_diffusers(
|
678 |
+
resnet_0, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"}
|
679 |
+
)
|
680 |
+
update_unet_resnet_ldm_to_diffusers(
|
681 |
+
resnet_1, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"}
|
682 |
+
)
|
683 |
+
update_unet_attention_ldm_to_diffusers(
|
684 |
+
attentions, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"}
|
685 |
+
)
|
686 |
+
|
687 |
+
# Up Blocks
|
688 |
+
for i in range(num_output_blocks):
|
689 |
+
block_id = i // (config["layers_per_block"] + 1)
|
690 |
+
layer_in_block_id = i % (config["layers_per_block"] + 1)
|
691 |
+
|
692 |
+
resnets = [
|
693 |
+
key for key in output_blocks[i] if f"output_blocks.{i}.0" in key and f"output_blocks.{i}.0.op" not in key
|
694 |
+
]
|
695 |
+
update_unet_resnet_ldm_to_diffusers(
|
696 |
+
resnets,
|
697 |
+
new_checkpoint,
|
698 |
+
unet_state_dict,
|
699 |
+
{"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"},
|
700 |
+
)
|
701 |
+
|
702 |
+
attentions = [
|
703 |
+
key for key in output_blocks[i] if f"output_blocks.{i}.1" in key and f"output_blocks.{i}.1.conv" not in key
|
704 |
+
]
|
705 |
+
if attentions:
|
706 |
+
update_unet_attention_ldm_to_diffusers(
|
707 |
+
attentions,
|
708 |
+
new_checkpoint,
|
709 |
+
unet_state_dict,
|
710 |
+
{"old": f"output_blocks.{i}.1", "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}"},
|
711 |
+
)
|
712 |
+
|
713 |
+
if f"output_blocks.{i}.1.conv.weight" in unet_state_dict:
|
714 |
+
new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
|
715 |
+
f"output_blocks.{i}.1.conv.weight"
|
716 |
+
]
|
717 |
+
new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
|
718 |
+
f"output_blocks.{i}.1.conv.bias"
|
719 |
+
]
|
720 |
+
if f"output_blocks.{i}.2.conv.weight" in unet_state_dict:
|
721 |
+
new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
|
722 |
+
f"output_blocks.{i}.2.conv.weight"
|
723 |
+
]
|
724 |
+
new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
|
725 |
+
f"output_blocks.{i}.2.conv.bias"
|
726 |
+
]
|
727 |
+
|
728 |
+
return new_checkpoint
|
729 |
+
|
730 |
+
|
731 |
+
def convert_controlnet_checkpoint(
|
732 |
+
checkpoint,
|
733 |
+
config,
|
734 |
+
):
|
735 |
+
# Some controlnet ckpt files are distributed independently from the rest of the
|
736 |
+
# model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
|
737 |
+
if "time_embed.0.weight" in checkpoint:
|
738 |
+
controlnet_state_dict = checkpoint
|
739 |
+
|
740 |
+
else:
|
741 |
+
controlnet_state_dict = {}
|
742 |
+
keys = list(checkpoint.keys())
|
743 |
+
controlnet_key = LDM_CONTROLNET_KEY
|
744 |
+
for key in keys:
|
745 |
+
if key.startswith(controlnet_key):
|
746 |
+
controlnet_state_dict[key.replace(controlnet_key, "")] = checkpoint.pop(key)
|
747 |
+
|
748 |
+
new_checkpoint = {}
|
749 |
+
ldm_controlnet_keys = DIFFUSERS_TO_LDM_MAPPING["controlnet"]["layers"]
|
750 |
+
for diffusers_key, ldm_key in ldm_controlnet_keys.items():
|
751 |
+
if ldm_key not in controlnet_state_dict:
|
752 |
+
continue
|
753 |
+
new_checkpoint[diffusers_key] = controlnet_state_dict[ldm_key]
|
754 |
+
|
755 |
+
# Retrieves the keys for the input blocks only
|
756 |
+
num_input_blocks = len(
|
757 |
+
{".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "input_blocks" in layer}
|
758 |
+
)
|
759 |
+
input_blocks = {
|
760 |
+
layer_id: [key for key in controlnet_state_dict if f"input_blocks.{layer_id}" in key]
|
761 |
+
for layer_id in range(num_input_blocks)
|
762 |
+
}
|
763 |
+
|
764 |
+
# Down blocks
|
765 |
+
for i in range(1, num_input_blocks):
|
766 |
+
block_id = (i - 1) // (config["layers_per_block"] + 1)
|
767 |
+
layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
|
768 |
+
|
769 |
+
resnets = [
|
770 |
+
key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
|
771 |
+
]
|
772 |
+
update_unet_resnet_ldm_to_diffusers(
|
773 |
+
resnets,
|
774 |
+
new_checkpoint,
|
775 |
+
controlnet_state_dict,
|
776 |
+
{"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
|
777 |
+
)
|
778 |
+
|
779 |
+
if f"input_blocks.{i}.0.op.weight" in controlnet_state_dict:
|
780 |
+
new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = controlnet_state_dict.pop(
|
781 |
+
f"input_blocks.{i}.0.op.weight"
|
782 |
+
)
|
783 |
+
new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = controlnet_state_dict.pop(
|
784 |
+
f"input_blocks.{i}.0.op.bias"
|
785 |
+
)
|
786 |
+
|
787 |
+
attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
|
788 |
+
if attentions:
|
789 |
+
update_unet_attention_ldm_to_diffusers(
|
790 |
+
attentions,
|
791 |
+
new_checkpoint,
|
792 |
+
controlnet_state_dict,
|
793 |
+
{"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
|
794 |
+
)
|
795 |
+
|
796 |
+
# controlnet down blocks
|
797 |
+
for i in range(num_input_blocks):
|
798 |
+
new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.weight")
|
799 |
+
new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.bias")
|
800 |
+
|
801 |
+
# Retrieves the keys for the middle blocks only
|
802 |
+
num_middle_blocks = len(
|
803 |
+
{".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "middle_block" in layer}
|
804 |
+
)
|
805 |
+
middle_blocks = {
|
806 |
+
layer_id: [key for key in controlnet_state_dict if f"middle_block.{layer_id}" in key]
|
807 |
+
for layer_id in range(num_middle_blocks)
|
808 |
+
}
|
809 |
+
if middle_blocks:
|
810 |
+
resnet_0 = middle_blocks[0]
|
811 |
+
attentions = middle_blocks[1]
|
812 |
+
resnet_1 = middle_blocks[2]
|
813 |
+
|
814 |
+
update_unet_resnet_ldm_to_diffusers(
|
815 |
+
resnet_0,
|
816 |
+
new_checkpoint,
|
817 |
+
controlnet_state_dict,
|
818 |
+
mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"},
|
819 |
+
)
|
820 |
+
update_unet_resnet_ldm_to_diffusers(
|
821 |
+
resnet_1,
|
822 |
+
new_checkpoint,
|
823 |
+
controlnet_state_dict,
|
824 |
+
mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"},
|
825 |
+
)
|
826 |
+
update_unet_attention_ldm_to_diffusers(
|
827 |
+
attentions,
|
828 |
+
new_checkpoint,
|
829 |
+
controlnet_state_dict,
|
830 |
+
mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"},
|
831 |
+
)
|
832 |
+
|
833 |
+
# mid block
|
834 |
+
new_checkpoint["controlnet_mid_block.weight"] = controlnet_state_dict.pop("middle_block_out.0.weight")
|
835 |
+
new_checkpoint["controlnet_mid_block.bias"] = controlnet_state_dict.pop("middle_block_out.0.bias")
|
836 |
+
|
837 |
+
# controlnet cond embedding blocks
|
838 |
+
cond_embedding_blocks = {
|
839 |
+
".".join(layer.split(".")[:2])
|
840 |
+
for layer in controlnet_state_dict
|
841 |
+
if "input_hint_block" in layer and ("input_hint_block.0" not in layer) and ("input_hint_block.14" not in layer)
|
842 |
+
}
|
843 |
+
num_cond_embedding_blocks = len(cond_embedding_blocks)
|
844 |
+
|
845 |
+
for idx in range(1, num_cond_embedding_blocks + 1):
|
846 |
+
diffusers_idx = idx - 1
|
847 |
+
cond_block_id = 2 * idx
|
848 |
+
|
849 |
+
new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.weight"] = controlnet_state_dict.pop(
|
850 |
+
f"input_hint_block.{cond_block_id}.weight"
|
851 |
+
)
|
852 |
+
new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.bias"] = controlnet_state_dict.pop(
|
853 |
+
f"input_hint_block.{cond_block_id}.bias"
|
854 |
+
)
|
855 |
+
|
856 |
+
return new_checkpoint
|
857 |
+
|
858 |
+
|
859 |
+
def create_diffusers_controlnet_model_from_ldm(
|
860 |
+
pipeline_class_name, original_config, checkpoint, upcast_attention=False, image_size=None, torch_dtype=None
|
861 |
+
):
|
862 |
+
# import here to avoid circular imports
|
863 |
+
from ..models import ControlNetModel
|
864 |
+
|
865 |
+
image_size = set_image_size(pipeline_class_name, original_config, checkpoint, image_size=image_size)
|
866 |
+
|
867 |
+
diffusers_config = create_controlnet_diffusers_config(original_config, image_size=image_size)
|
868 |
+
diffusers_config["upcast_attention"] = upcast_attention
|
869 |
+
|
870 |
+
diffusers_format_controlnet_checkpoint = convert_controlnet_checkpoint(checkpoint, diffusers_config)
|
871 |
+
|
872 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
873 |
+
with ctx():
|
874 |
+
controlnet = ControlNetModel(**diffusers_config)
|
875 |
+
|
876 |
+
if is_accelerate_available():
|
877 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
878 |
+
|
879 |
+
unexpected_keys = load_model_dict_into_meta(
|
880 |
+
controlnet, diffusers_format_controlnet_checkpoint, dtype=torch_dtype
|
881 |
+
)
|
882 |
+
if controlnet._keys_to_ignore_on_load_unexpected is not None:
|
883 |
+
for pat in controlnet._keys_to_ignore_on_load_unexpected:
|
884 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
885 |
+
|
886 |
+
if len(unexpected_keys) > 0:
|
887 |
+
logger.warn(
|
888 |
+
f"Some weights of the model checkpoint were not used when initializing {controlnet.__name__}: \n {[', '.join(unexpected_keys)]}"
|
889 |
+
)
|
890 |
+
else:
|
891 |
+
controlnet.load_state_dict(diffusers_format_controlnet_checkpoint)
|
892 |
+
|
893 |
+
if torch_dtype is not None:
|
894 |
+
controlnet = controlnet.to(torch_dtype)
|
895 |
+
|
896 |
+
return {"controlnet": controlnet}
|
897 |
+
|
898 |
+
|
899 |
+
def update_vae_resnet_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
|
900 |
+
for ldm_key in keys:
|
901 |
+
diffusers_key = ldm_key.replace(mapping["old"], mapping["new"]).replace("nin_shortcut", "conv_shortcut")
|
902 |
+
new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
|
903 |
+
|
904 |
+
|
905 |
+
def update_vae_attentions_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
|
906 |
+
for ldm_key in keys:
|
907 |
+
diffusers_key = (
|
908 |
+
ldm_key.replace(mapping["old"], mapping["new"])
|
909 |
+
.replace("norm.weight", "group_norm.weight")
|
910 |
+
.replace("norm.bias", "group_norm.bias")
|
911 |
+
.replace("q.weight", "to_q.weight")
|
912 |
+
.replace("q.bias", "to_q.bias")
|
913 |
+
.replace("k.weight", "to_k.weight")
|
914 |
+
.replace("k.bias", "to_k.bias")
|
915 |
+
.replace("v.weight", "to_v.weight")
|
916 |
+
.replace("v.bias", "to_v.bias")
|
917 |
+
.replace("proj_out.weight", "to_out.0.weight")
|
918 |
+
.replace("proj_out.bias", "to_out.0.bias")
|
919 |
+
)
|
920 |
+
new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
|
921 |
+
|
922 |
+
# proj_attn.weight has to be converted from conv 1D to linear
|
923 |
+
shape = new_checkpoint[diffusers_key].shape
|
924 |
+
|
925 |
+
if len(shape) == 3:
|
926 |
+
new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0]
|
927 |
+
elif len(shape) == 4:
|
928 |
+
new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0, 0]
|
929 |
+
|
930 |
+
|
931 |
+
def convert_ldm_vae_checkpoint(checkpoint, config):
|
932 |
+
# extract state dict for VAE
|
933 |
+
# remove the LDM_VAE_KEY prefix from the ldm checkpoint keys so that it is easier to map them to diffusers keys
|
934 |
+
vae_state_dict = {}
|
935 |
+
keys = list(checkpoint.keys())
|
936 |
+
vae_key = LDM_VAE_KEY if any(k.startswith(LDM_VAE_KEY) for k in keys) else ""
|
937 |
+
for key in keys:
|
938 |
+
if key.startswith(vae_key):
|
939 |
+
vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
|
940 |
+
|
941 |
+
new_checkpoint = {}
|
942 |
+
vae_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["vae"]
|
943 |
+
for diffusers_key, ldm_key in vae_diffusers_ldm_map.items():
|
944 |
+
if ldm_key not in vae_state_dict:
|
945 |
+
continue
|
946 |
+
new_checkpoint[diffusers_key] = vae_state_dict[ldm_key]
|
947 |
+
|
948 |
+
# Retrieves the keys for the encoder down blocks only
|
949 |
+
num_down_blocks = len(config["down_block_types"])
|
950 |
+
down_blocks = {
|
951 |
+
layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
|
952 |
+
}
|
953 |
+
|
954 |
+
for i in range(num_down_blocks):
|
955 |
+
resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
|
956 |
+
update_vae_resnet_ldm_to_diffusers(
|
957 |
+
resnets,
|
958 |
+
new_checkpoint,
|
959 |
+
vae_state_dict,
|
960 |
+
mapping={"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"},
|
961 |
+
)
|
962 |
+
if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
|
963 |
+
new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
|
964 |
+
f"encoder.down.{i}.downsample.conv.weight"
|
965 |
+
)
|
966 |
+
new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
|
967 |
+
f"encoder.down.{i}.downsample.conv.bias"
|
968 |
+
)
|
969 |
+
|
970 |
+
mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
|
971 |
+
num_mid_res_blocks = 2
|
972 |
+
for i in range(1, num_mid_res_blocks + 1):
|
973 |
+
resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
|
974 |
+
update_vae_resnet_ldm_to_diffusers(
|
975 |
+
resnets,
|
976 |
+
new_checkpoint,
|
977 |
+
vae_state_dict,
|
978 |
+
mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
|
979 |
+
)
|
980 |
+
|
981 |
+
mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
|
982 |
+
update_vae_attentions_ldm_to_diffusers(
|
983 |
+
mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
|
984 |
+
)
|
985 |
+
|
986 |
+
# Retrieves the keys for the decoder up blocks only
|
987 |
+
num_up_blocks = len(config["up_block_types"])
|
988 |
+
up_blocks = {
|
989 |
+
layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
|
990 |
+
}
|
991 |
+
|
992 |
+
for i in range(num_up_blocks):
|
993 |
+
block_id = num_up_blocks - 1 - i
|
994 |
+
resnets = [
|
995 |
+
key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
|
996 |
+
]
|
997 |
+
update_vae_resnet_ldm_to_diffusers(
|
998 |
+
resnets,
|
999 |
+
new_checkpoint,
|
1000 |
+
vae_state_dict,
|
1001 |
+
mapping={"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"},
|
1002 |
+
)
|
1003 |
+
if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
|
1004 |
+
new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
|
1005 |
+
f"decoder.up.{block_id}.upsample.conv.weight"
|
1006 |
+
]
|
1007 |
+
new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
|
1008 |
+
f"decoder.up.{block_id}.upsample.conv.bias"
|
1009 |
+
]
|
1010 |
+
|
1011 |
+
mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
|
1012 |
+
num_mid_res_blocks = 2
|
1013 |
+
for i in range(1, num_mid_res_blocks + 1):
|
1014 |
+
resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
|
1015 |
+
update_vae_resnet_ldm_to_diffusers(
|
1016 |
+
resnets,
|
1017 |
+
new_checkpoint,
|
1018 |
+
vae_state_dict,
|
1019 |
+
mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
|
1020 |
+
)
|
1021 |
+
|
1022 |
+
mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
|
1023 |
+
update_vae_attentions_ldm_to_diffusers(
|
1024 |
+
mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
|
1025 |
+
)
|
1026 |
+
conv_attn_to_linear(new_checkpoint)
|
1027 |
+
|
1028 |
+
return new_checkpoint
|
1029 |
+
|
1030 |
+
|
1031 |
+
def create_text_encoder_from_ldm_clip_checkpoint(config_name, checkpoint, local_files_only=False, torch_dtype=None):
|
1032 |
+
try:
|
1033 |
+
config = CLIPTextConfig.from_pretrained(config_name, local_files_only=local_files_only)
|
1034 |
+
except Exception:
|
1035 |
+
raise ValueError(
|
1036 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: 'openai/clip-vit-large-patch14'."
|
1037 |
+
)
|
1038 |
+
|
1039 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
1040 |
+
with ctx():
|
1041 |
+
text_model = CLIPTextModel(config)
|
1042 |
+
|
1043 |
+
keys = list(checkpoint.keys())
|
1044 |
+
text_model_dict = {}
|
1045 |
+
|
1046 |
+
remove_prefixes = LDM_CLIP_PREFIX_TO_REMOVE
|
1047 |
+
|
1048 |
+
for key in keys:
|
1049 |
+
for prefix in remove_prefixes:
|
1050 |
+
if key.startswith(prefix):
|
1051 |
+
diffusers_key = key.replace(prefix, "")
|
1052 |
+
text_model_dict[diffusers_key] = checkpoint[key]
|
1053 |
+
|
1054 |
+
if is_accelerate_available():
|
1055 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
1056 |
+
|
1057 |
+
unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
|
1058 |
+
if text_model._keys_to_ignore_on_load_unexpected is not None:
|
1059 |
+
for pat in text_model._keys_to_ignore_on_load_unexpected:
|
1060 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
1061 |
+
|
1062 |
+
if len(unexpected_keys) > 0:
|
1063 |
+
logger.warn(
|
1064 |
+
f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
|
1065 |
+
)
|
1066 |
+
else:
|
1067 |
+
if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
|
1068 |
+
text_model_dict.pop("text_model.embeddings.position_ids", None)
|
1069 |
+
|
1070 |
+
text_model.load_state_dict(text_model_dict)
|
1071 |
+
|
1072 |
+
if torch_dtype is not None:
|
1073 |
+
text_model = text_model.to(torch_dtype)
|
1074 |
+
|
1075 |
+
return text_model
|
1076 |
+
|
1077 |
+
|
1078 |
+
def create_text_encoder_from_open_clip_checkpoint(
|
1079 |
+
config_name,
|
1080 |
+
checkpoint,
|
1081 |
+
prefix="cond_stage_model.model.",
|
1082 |
+
has_projection=False,
|
1083 |
+
local_files_only=False,
|
1084 |
+
torch_dtype=None,
|
1085 |
+
**config_kwargs,
|
1086 |
+
):
|
1087 |
+
try:
|
1088 |
+
config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs, local_files_only=local_files_only)
|
1089 |
+
except Exception:
|
1090 |
+
raise ValueError(
|
1091 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: '{config_name}'."
|
1092 |
+
)
|
1093 |
+
|
1094 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
1095 |
+
with ctx():
|
1096 |
+
text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config)
|
1097 |
+
|
1098 |
+
text_model_dict = {}
|
1099 |
+
text_proj_key = prefix + "text_projection"
|
1100 |
+
text_proj_dim = (
|
1101 |
+
int(checkpoint[text_proj_key].shape[0]) if text_proj_key in checkpoint else LDM_OPEN_CLIP_TEXT_PROJECTION_DIM
|
1102 |
+
)
|
1103 |
+
text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids")
|
1104 |
+
|
1105 |
+
keys = list(checkpoint.keys())
|
1106 |
+
keys_to_ignore = SD_2_TEXT_ENCODER_KEYS_TO_IGNORE
|
1107 |
+
|
1108 |
+
openclip_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["layers"]
|
1109 |
+
for diffusers_key, ldm_key in openclip_diffusers_ldm_map.items():
|
1110 |
+
ldm_key = prefix + ldm_key
|
1111 |
+
if ldm_key not in checkpoint:
|
1112 |
+
continue
|
1113 |
+
if ldm_key in keys_to_ignore:
|
1114 |
+
continue
|
1115 |
+
if ldm_key.endswith("text_projection"):
|
1116 |
+
text_model_dict[diffusers_key] = checkpoint[ldm_key].T.contiguous()
|
1117 |
+
else:
|
1118 |
+
text_model_dict[diffusers_key] = checkpoint[ldm_key]
|
1119 |
+
|
1120 |
+
for key in keys:
|
1121 |
+
if key in keys_to_ignore:
|
1122 |
+
continue
|
1123 |
+
|
1124 |
+
if not key.startswith(prefix + "transformer."):
|
1125 |
+
continue
|
1126 |
+
|
1127 |
+
diffusers_key = key.replace(prefix + "transformer.", "")
|
1128 |
+
transformer_diffusers_to_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["transformer"]
|
1129 |
+
for new_key, old_key in transformer_diffusers_to_ldm_map.items():
|
1130 |
+
diffusers_key = (
|
1131 |
+
diffusers_key.replace(old_key, new_key).replace(".in_proj_weight", "").replace(".in_proj_bias", "")
|
1132 |
+
)
|
1133 |
+
|
1134 |
+
if key.endswith(".in_proj_weight"):
|
1135 |
+
weight_value = checkpoint[key]
|
1136 |
+
|
1137 |
+
text_model_dict[diffusers_key + ".q_proj.weight"] = weight_value[:text_proj_dim, :]
|
1138 |
+
text_model_dict[diffusers_key + ".k_proj.weight"] = weight_value[text_proj_dim : text_proj_dim * 2, :]
|
1139 |
+
text_model_dict[diffusers_key + ".v_proj.weight"] = weight_value[text_proj_dim * 2 :, :]
|
1140 |
+
|
1141 |
+
elif key.endswith(".in_proj_bias"):
|
1142 |
+
weight_value = checkpoint[key]
|
1143 |
+
text_model_dict[diffusers_key + ".q_proj.bias"] = weight_value[:text_proj_dim]
|
1144 |
+
text_model_dict[diffusers_key + ".k_proj.bias"] = weight_value[text_proj_dim : text_proj_dim * 2]
|
1145 |
+
text_model_dict[diffusers_key + ".v_proj.bias"] = weight_value[text_proj_dim * 2 :]
|
1146 |
+
else:
|
1147 |
+
text_model_dict[diffusers_key] = checkpoint[key]
|
1148 |
+
|
1149 |
+
if is_accelerate_available():
|
1150 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
1151 |
+
|
1152 |
+
unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
|
1153 |
+
if text_model._keys_to_ignore_on_load_unexpected is not None:
|
1154 |
+
for pat in text_model._keys_to_ignore_on_load_unexpected:
|
1155 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
1156 |
+
|
1157 |
+
if len(unexpected_keys) > 0:
|
1158 |
+
logger.warn(
|
1159 |
+
f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
|
1160 |
+
)
|
1161 |
+
|
1162 |
+
else:
|
1163 |
+
if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
|
1164 |
+
text_model_dict.pop("text_model.embeddings.position_ids", None)
|
1165 |
+
|
1166 |
+
text_model.load_state_dict(text_model_dict)
|
1167 |
+
|
1168 |
+
if torch_dtype is not None:
|
1169 |
+
text_model = text_model.to(torch_dtype)
|
1170 |
+
|
1171 |
+
return text_model
|
1172 |
+
|
1173 |
+
|
1174 |
+
def create_diffusers_unet_model_from_ldm(
|
1175 |
+
pipeline_class_name,
|
1176 |
+
original_config,
|
1177 |
+
checkpoint,
|
1178 |
+
num_in_channels=None,
|
1179 |
+
upcast_attention=False,
|
1180 |
+
extract_ema=False,
|
1181 |
+
image_size=None,
|
1182 |
+
torch_dtype=None,
|
1183 |
+
model_type=None,
|
1184 |
+
):
|
1185 |
+
from ..models import UNet2DConditionModel
|
1186 |
+
|
1187 |
+
if num_in_channels is None:
|
1188 |
+
if pipeline_class_name in [
|
1189 |
+
"StableDiffusionInpaintPipeline",
|
1190 |
+
"StableDiffusionControlNetInpaintPipeline",
|
1191 |
+
"StableDiffusionXLInpaintPipeline",
|
1192 |
+
"StableDiffusionXLControlNetInpaintPipeline",
|
1193 |
+
]:
|
1194 |
+
num_in_channels = 9
|
1195 |
+
|
1196 |
+
elif pipeline_class_name == "StableDiffusionUpscalePipeline":
|
1197 |
+
num_in_channels = 7
|
1198 |
+
|
1199 |
+
else:
|
1200 |
+
num_in_channels = 4
|
1201 |
+
|
1202 |
+
image_size = set_image_size(
|
1203 |
+
pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
|
1204 |
+
)
|
1205 |
+
unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
|
1206 |
+
unet_config["in_channels"] = num_in_channels
|
1207 |
+
unet_config["upcast_attention"] = upcast_attention
|
1208 |
+
|
1209 |
+
diffusers_format_unet_checkpoint = convert_ldm_unet_checkpoint(checkpoint, unet_config, extract_ema=extract_ema)
|
1210 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
1211 |
+
|
1212 |
+
with ctx():
|
1213 |
+
unet = UNet2DConditionModel(**unet_config)
|
1214 |
+
|
1215 |
+
if is_accelerate_available():
|
1216 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
1217 |
+
|
1218 |
+
unexpected_keys = load_model_dict_into_meta(unet, diffusers_format_unet_checkpoint, dtype=torch_dtype)
|
1219 |
+
if unet._keys_to_ignore_on_load_unexpected is not None:
|
1220 |
+
for pat in unet._keys_to_ignore_on_load_unexpected:
|
1221 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
1222 |
+
|
1223 |
+
if len(unexpected_keys) > 0:
|
1224 |
+
logger.warn(
|
1225 |
+
f"Some weights of the model checkpoint were not used when initializing {unet.__name__}: \n {[', '.join(unexpected_keys)]}"
|
1226 |
+
)
|
1227 |
+
else:
|
1228 |
+
unet.load_state_dict(diffusers_format_unet_checkpoint)
|
1229 |
+
|
1230 |
+
if torch_dtype is not None:
|
1231 |
+
unet = unet.to(torch_dtype)
|
1232 |
+
|
1233 |
+
return {"unet": unet}
|
1234 |
+
|
1235 |
+
|
1236 |
+
def create_diffusers_vae_model_from_ldm(
|
1237 |
+
pipeline_class_name,
|
1238 |
+
original_config,
|
1239 |
+
checkpoint,
|
1240 |
+
image_size=None,
|
1241 |
+
scaling_factor=None,
|
1242 |
+
torch_dtype=None,
|
1243 |
+
model_type=None,
|
1244 |
+
):
|
1245 |
+
# import here to avoid circular imports
|
1246 |
+
from ..models import AutoencoderKL
|
1247 |
+
|
1248 |
+
image_size = set_image_size(
|
1249 |
+
pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
|
1250 |
+
)
|
1251 |
+
model_type = infer_model_type(original_config, checkpoint, model_type)
|
1252 |
+
|
1253 |
+
if model_type == "Playground":
|
1254 |
+
edm_mean = (
|
1255 |
+
checkpoint["edm_mean"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_mean"].tolist()
|
1256 |
+
)
|
1257 |
+
edm_std = (
|
1258 |
+
checkpoint["edm_std"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_std"].tolist()
|
1259 |
+
)
|
1260 |
+
else:
|
1261 |
+
edm_mean = None
|
1262 |
+
edm_std = None
|
1263 |
+
|
1264 |
+
vae_config = create_vae_diffusers_config(
|
1265 |
+
original_config,
|
1266 |
+
image_size=image_size,
|
1267 |
+
scaling_factor=scaling_factor,
|
1268 |
+
latents_mean=edm_mean,
|
1269 |
+
latents_std=edm_std,
|
1270 |
+
)
|
1271 |
+
diffusers_format_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
|
1272 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
1273 |
+
|
1274 |
+
with ctx():
|
1275 |
+
vae = AutoencoderKL(**vae_config)
|
1276 |
+
|
1277 |
+
if is_accelerate_available():
|
1278 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
1279 |
+
|
1280 |
+
unexpected_keys = load_model_dict_into_meta(vae, diffusers_format_vae_checkpoint, dtype=torch_dtype)
|
1281 |
+
if vae._keys_to_ignore_on_load_unexpected is not None:
|
1282 |
+
for pat in vae._keys_to_ignore_on_load_unexpected:
|
1283 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
1284 |
+
|
1285 |
+
if len(unexpected_keys) > 0:
|
1286 |
+
logger.warn(
|
1287 |
+
f"Some weights of the model checkpoint were not used when initializing {vae.__name__}: \n {[', '.join(unexpected_keys)]}"
|
1288 |
+
)
|
1289 |
+
else:
|
1290 |
+
vae.load_state_dict(diffusers_format_vae_checkpoint)
|
1291 |
+
|
1292 |
+
if torch_dtype is not None:
|
1293 |
+
vae = vae.to(torch_dtype)
|
1294 |
+
|
1295 |
+
return {"vae": vae}
|
1296 |
+
|
1297 |
+
|
1298 |
+
def create_text_encoders_and_tokenizers_from_ldm(
|
1299 |
+
original_config,
|
1300 |
+
checkpoint,
|
1301 |
+
model_type=None,
|
1302 |
+
local_files_only=False,
|
1303 |
+
torch_dtype=None,
|
1304 |
+
):
|
1305 |
+
model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
|
1306 |
+
|
1307 |
+
if model_type == "FrozenOpenCLIPEmbedder":
|
1308 |
+
config_name = "stabilityai/stable-diffusion-2"
|
1309 |
+
config_kwargs = {"subfolder": "text_encoder"}
|
1310 |
+
|
1311 |
+
try:
|
1312 |
+
text_encoder = create_text_encoder_from_open_clip_checkpoint(
|
1313 |
+
config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype, **config_kwargs
|
1314 |
+
)
|
1315 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
1316 |
+
config_name, subfolder="tokenizer", local_files_only=local_files_only
|
1317 |
+
)
|
1318 |
+
except Exception:
|
1319 |
+
raise ValueError(
|
1320 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder in the following path: '{config_name}'."
|
1321 |
+
)
|
1322 |
+
else:
|
1323 |
+
return {"text_encoder": text_encoder, "tokenizer": tokenizer}
|
1324 |
+
|
1325 |
+
elif model_type == "FrozenCLIPEmbedder":
|
1326 |
+
try:
|
1327 |
+
config_name = "openai/clip-vit-large-patch14"
|
1328 |
+
text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
|
1329 |
+
config_name,
|
1330 |
+
checkpoint,
|
1331 |
+
local_files_only=local_files_only,
|
1332 |
+
torch_dtype=torch_dtype,
|
1333 |
+
)
|
1334 |
+
tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
|
1335 |
+
|
1336 |
+
except Exception:
|
1337 |
+
raise ValueError(
|
1338 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: '{config_name}'."
|
1339 |
+
)
|
1340 |
+
else:
|
1341 |
+
return {"text_encoder": text_encoder, "tokenizer": tokenizer}
|
1342 |
+
|
1343 |
+
elif model_type == "SDXL-Refiner":
|
1344 |
+
config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
|
1345 |
+
config_kwargs = {"projection_dim": 1280}
|
1346 |
+
prefix = "conditioner.embedders.0.model."
|
1347 |
+
|
1348 |
+
try:
|
1349 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
|
1350 |
+
text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
|
1351 |
+
config_name,
|
1352 |
+
checkpoint,
|
1353 |
+
prefix=prefix,
|
1354 |
+
has_projection=True,
|
1355 |
+
local_files_only=local_files_only,
|
1356 |
+
torch_dtype=torch_dtype,
|
1357 |
+
**config_kwargs,
|
1358 |
+
)
|
1359 |
+
except Exception:
|
1360 |
+
raise ValueError(
|
1361 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
|
1362 |
+
)
|
1363 |
+
|
1364 |
+
else:
|
1365 |
+
return {
|
1366 |
+
"text_encoder": None,
|
1367 |
+
"tokenizer": None,
|
1368 |
+
"tokenizer_2": tokenizer_2,
|
1369 |
+
"text_encoder_2": text_encoder_2,
|
1370 |
+
}
|
1371 |
+
|
1372 |
+
elif model_type in ["SDXL", "Playground"]:
|
1373 |
+
try:
|
1374 |
+
config_name = "openai/clip-vit-large-patch14"
|
1375 |
+
tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
|
1376 |
+
text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
|
1377 |
+
config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype
|
1378 |
+
)
|
1379 |
+
|
1380 |
+
except Exception:
|
1381 |
+
raise ValueError(
|
1382 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder and tokenizer in the following path: 'openai/clip-vit-large-patch14'."
|
1383 |
+
)
|
1384 |
+
|
1385 |
+
try:
|
1386 |
+
config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
|
1387 |
+
config_kwargs = {"projection_dim": 1280}
|
1388 |
+
prefix = "conditioner.embedders.1.model."
|
1389 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
|
1390 |
+
text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
|
1391 |
+
config_name,
|
1392 |
+
checkpoint,
|
1393 |
+
prefix=prefix,
|
1394 |
+
has_projection=True,
|
1395 |
+
local_files_only=local_files_only,
|
1396 |
+
torch_dtype=torch_dtype,
|
1397 |
+
**config_kwargs,
|
1398 |
+
)
|
1399 |
+
except Exception:
|
1400 |
+
raise ValueError(
|
1401 |
+
f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
|
1402 |
+
)
|
1403 |
+
|
1404 |
+
return {
|
1405 |
+
"tokenizer": tokenizer,
|
1406 |
+
"text_encoder": text_encoder,
|
1407 |
+
"tokenizer_2": tokenizer_2,
|
1408 |
+
"text_encoder_2": text_encoder_2,
|
1409 |
+
}
|
1410 |
+
|
1411 |
+
return
|
1412 |
+
|
1413 |
+
|
1414 |
+
def create_scheduler_from_ldm(
|
1415 |
+
pipeline_class_name,
|
1416 |
+
original_config,
|
1417 |
+
checkpoint,
|
1418 |
+
prediction_type=None,
|
1419 |
+
scheduler_type="ddim",
|
1420 |
+
model_type=None,
|
1421 |
+
):
|
1422 |
+
scheduler_config = get_default_scheduler_config()
|
1423 |
+
model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
|
1424 |
+
|
1425 |
+
global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
|
1426 |
+
|
1427 |
+
num_train_timesteps = getattr(original_config["model"]["params"], "timesteps", None) or 1000
|
1428 |
+
scheduler_config["num_train_timesteps"] = num_train_timesteps
|
1429 |
+
|
1430 |
+
if (
|
1431 |
+
"parameterization" in original_config["model"]["params"]
|
1432 |
+
and original_config["model"]["params"]["parameterization"] == "v"
|
1433 |
+
):
|
1434 |
+
if prediction_type is None:
|
1435 |
+
# NOTE: For stable diffusion 2 base it is recommended to pass `prediction_type=="epsilon"`
|
1436 |
+
# as it relies on a brittle global step parameter here
|
1437 |
+
prediction_type = "epsilon" if global_step == 875000 else "v_prediction"
|
1438 |
+
|
1439 |
+
else:
|
1440 |
+
prediction_type = prediction_type or "epsilon"
|
1441 |
+
|
1442 |
+
scheduler_config["prediction_type"] = prediction_type
|
1443 |
+
|
1444 |
+
if model_type in ["SDXL", "SDXL-Refiner"]:
|
1445 |
+
scheduler_type = "euler"
|
1446 |
+
elif model_type == "Playground":
|
1447 |
+
scheduler_type = "edm_dpm_solver_multistep"
|
1448 |
+
else:
|
1449 |
+
beta_start = original_config["model"]["params"].get("linear_start", 0.02)
|
1450 |
+
beta_end = original_config["model"]["params"].get("linear_end", 0.085)
|
1451 |
+
scheduler_config["beta_start"] = beta_start
|
1452 |
+
scheduler_config["beta_end"] = beta_end
|
1453 |
+
scheduler_config["beta_schedule"] = "scaled_linear"
|
1454 |
+
scheduler_config["clip_sample"] = False
|
1455 |
+
scheduler_config["set_alpha_to_one"] = False
|
1456 |
+
|
1457 |
+
if scheduler_type == "pndm":
|
1458 |
+
scheduler_config["skip_prk_steps"] = True
|
1459 |
+
scheduler = PNDMScheduler.from_config(scheduler_config)
|
1460 |
+
|
1461 |
+
elif scheduler_type == "lms":
|
1462 |
+
scheduler = LMSDiscreteScheduler.from_config(scheduler_config)
|
1463 |
+
|
1464 |
+
elif scheduler_type == "heun":
|
1465 |
+
scheduler = HeunDiscreteScheduler.from_config(scheduler_config)
|
1466 |
+
|
1467 |
+
elif scheduler_type == "euler":
|
1468 |
+
scheduler = EulerDiscreteScheduler.from_config(scheduler_config)
|
1469 |
+
|
1470 |
+
elif scheduler_type == "euler-ancestral":
|
1471 |
+
scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler_config)
|
1472 |
+
|
1473 |
+
elif scheduler_type == "dpm":
|
1474 |
+
scheduler = DPMSolverMultistepScheduler.from_config(scheduler_config)
|
1475 |
+
|
1476 |
+
elif scheduler_type == "ddim":
|
1477 |
+
scheduler = DDIMScheduler.from_config(scheduler_config)
|
1478 |
+
|
1479 |
+
elif scheduler_type == "edm_dpm_solver_multistep":
|
1480 |
+
scheduler_config = {
|
1481 |
+
"algorithm_type": "dpmsolver++",
|
1482 |
+
"dynamic_thresholding_ratio": 0.995,
|
1483 |
+
"euler_at_final": False,
|
1484 |
+
"final_sigmas_type": "zero",
|
1485 |
+
"lower_order_final": True,
|
1486 |
+
"num_train_timesteps": 1000,
|
1487 |
+
"prediction_type": "epsilon",
|
1488 |
+
"rho": 7.0,
|
1489 |
+
"sample_max_value": 1.0,
|
1490 |
+
"sigma_data": 0.5,
|
1491 |
+
"sigma_max": 80.0,
|
1492 |
+
"sigma_min": 0.002,
|
1493 |
+
"solver_order": 2,
|
1494 |
+
"solver_type": "midpoint",
|
1495 |
+
"thresholding": False,
|
1496 |
+
}
|
1497 |
+
scheduler = EDMDPMSolverMultistepScheduler(**scheduler_config)
|
1498 |
+
|
1499 |
+
else:
|
1500 |
+
raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")
|
1501 |
+
|
1502 |
+
if pipeline_class_name == "StableDiffusionUpscalePipeline":
|
1503 |
+
scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", subfolder="scheduler")
|
1504 |
+
low_res_scheduler = DDPMScheduler.from_pretrained(
|
1505 |
+
"stabilityai/stable-diffusion-x4-upscaler", subfolder="low_res_scheduler"
|
1506 |
+
)
|
1507 |
+
|
1508 |
+
return {
|
1509 |
+
"scheduler": scheduler,
|
1510 |
+
"low_res_scheduler": low_res_scheduler,
|
1511 |
+
}
|
1512 |
+
|
1513 |
+
return {"scheduler": scheduler}
|
BrushNet/build/lib/diffusers/loaders/textual_inversion.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 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 |
+
from typing import Dict, List, Optional, Union
|
15 |
+
|
16 |
+
import safetensors
|
17 |
+
import torch
|
18 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
19 |
+
from torch import nn
|
20 |
+
|
21 |
+
from ..utils import _get_model_file, is_accelerate_available, is_transformers_available, logging
|
22 |
+
|
23 |
+
|
24 |
+
if is_transformers_available():
|
25 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
26 |
+
|
27 |
+
if is_accelerate_available():
|
28 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
29 |
+
|
30 |
+
logger = logging.get_logger(__name__)
|
31 |
+
|
32 |
+
TEXT_INVERSION_NAME = "learned_embeds.bin"
|
33 |
+
TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
|
34 |
+
|
35 |
+
|
36 |
+
@validate_hf_hub_args
|
37 |
+
def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
|
38 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
39 |
+
force_download = kwargs.pop("force_download", False)
|
40 |
+
resume_download = kwargs.pop("resume_download", False)
|
41 |
+
proxies = kwargs.pop("proxies", None)
|
42 |
+
local_files_only = kwargs.pop("local_files_only", None)
|
43 |
+
token = kwargs.pop("token", None)
|
44 |
+
revision = kwargs.pop("revision", None)
|
45 |
+
subfolder = kwargs.pop("subfolder", None)
|
46 |
+
weight_name = kwargs.pop("weight_name", None)
|
47 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
48 |
+
|
49 |
+
allow_pickle = False
|
50 |
+
if use_safetensors is None:
|
51 |
+
use_safetensors = True
|
52 |
+
allow_pickle = True
|
53 |
+
|
54 |
+
user_agent = {
|
55 |
+
"file_type": "text_inversion",
|
56 |
+
"framework": "pytorch",
|
57 |
+
}
|
58 |
+
state_dicts = []
|
59 |
+
for pretrained_model_name_or_path in pretrained_model_name_or_paths:
|
60 |
+
if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
|
61 |
+
# 3.1. Load textual inversion file
|
62 |
+
model_file = None
|
63 |
+
|
64 |
+
# Let's first try to load .safetensors weights
|
65 |
+
if (use_safetensors and weight_name is None) or (
|
66 |
+
weight_name is not None and weight_name.endswith(".safetensors")
|
67 |
+
):
|
68 |
+
try:
|
69 |
+
model_file = _get_model_file(
|
70 |
+
pretrained_model_name_or_path,
|
71 |
+
weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
|
72 |
+
cache_dir=cache_dir,
|
73 |
+
force_download=force_download,
|
74 |
+
resume_download=resume_download,
|
75 |
+
proxies=proxies,
|
76 |
+
local_files_only=local_files_only,
|
77 |
+
token=token,
|
78 |
+
revision=revision,
|
79 |
+
subfolder=subfolder,
|
80 |
+
user_agent=user_agent,
|
81 |
+
)
|
82 |
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
83 |
+
except Exception as e:
|
84 |
+
if not allow_pickle:
|
85 |
+
raise e
|
86 |
+
|
87 |
+
model_file = None
|
88 |
+
|
89 |
+
if model_file is None:
|
90 |
+
model_file = _get_model_file(
|
91 |
+
pretrained_model_name_or_path,
|
92 |
+
weights_name=weight_name or TEXT_INVERSION_NAME,
|
93 |
+
cache_dir=cache_dir,
|
94 |
+
force_download=force_download,
|
95 |
+
resume_download=resume_download,
|
96 |
+
proxies=proxies,
|
97 |
+
local_files_only=local_files_only,
|
98 |
+
token=token,
|
99 |
+
revision=revision,
|
100 |
+
subfolder=subfolder,
|
101 |
+
user_agent=user_agent,
|
102 |
+
)
|
103 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
104 |
+
else:
|
105 |
+
state_dict = pretrained_model_name_or_path
|
106 |
+
|
107 |
+
state_dicts.append(state_dict)
|
108 |
+
|
109 |
+
return state_dicts
|
110 |
+
|
111 |
+
|
112 |
+
class TextualInversionLoaderMixin:
|
113 |
+
r"""
|
114 |
+
Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
|
115 |
+
"""
|
116 |
+
|
117 |
+
def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
118 |
+
r"""
|
119 |
+
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
|
120 |
+
be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
121 |
+
inversion token or if the textual inversion token is a single vector, the input prompt is returned.
|
122 |
+
|
123 |
+
Parameters:
|
124 |
+
prompt (`str` or list of `str`):
|
125 |
+
The prompt or prompts to guide the image generation.
|
126 |
+
tokenizer (`PreTrainedTokenizer`):
|
127 |
+
The tokenizer responsible for encoding the prompt into input tokens.
|
128 |
+
|
129 |
+
Returns:
|
130 |
+
`str` or list of `str`: The converted prompt
|
131 |
+
"""
|
132 |
+
if not isinstance(prompt, List):
|
133 |
+
prompts = [prompt]
|
134 |
+
else:
|
135 |
+
prompts = prompt
|
136 |
+
|
137 |
+
prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
|
138 |
+
|
139 |
+
if not isinstance(prompt, List):
|
140 |
+
return prompts[0]
|
141 |
+
|
142 |
+
return prompts
|
143 |
+
|
144 |
+
def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
145 |
+
r"""
|
146 |
+
Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
|
147 |
+
to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
|
148 |
+
is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
149 |
+
inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
|
150 |
+
|
151 |
+
Parameters:
|
152 |
+
prompt (`str`):
|
153 |
+
The prompt to guide the image generation.
|
154 |
+
tokenizer (`PreTrainedTokenizer`):
|
155 |
+
The tokenizer responsible for encoding the prompt into input tokens.
|
156 |
+
|
157 |
+
Returns:
|
158 |
+
`str`: The converted prompt
|
159 |
+
"""
|
160 |
+
tokens = tokenizer.tokenize(prompt)
|
161 |
+
unique_tokens = set(tokens)
|
162 |
+
for token in unique_tokens:
|
163 |
+
if token in tokenizer.added_tokens_encoder:
|
164 |
+
replacement = token
|
165 |
+
i = 1
|
166 |
+
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
167 |
+
replacement += f" {token}_{i}"
|
168 |
+
i += 1
|
169 |
+
|
170 |
+
prompt = prompt.replace(token, replacement)
|
171 |
+
|
172 |
+
return prompt
|
173 |
+
|
174 |
+
def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
|
175 |
+
if tokenizer is None:
|
176 |
+
raise ValueError(
|
177 |
+
f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
|
178 |
+
f" `{self.load_textual_inversion.__name__}`"
|
179 |
+
)
|
180 |
+
|
181 |
+
if text_encoder is None:
|
182 |
+
raise ValueError(
|
183 |
+
f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
|
184 |
+
f" `{self.load_textual_inversion.__name__}`"
|
185 |
+
)
|
186 |
+
|
187 |
+
if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
|
188 |
+
raise ValueError(
|
189 |
+
f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
|
190 |
+
f"Make sure both lists have the same length."
|
191 |
+
)
|
192 |
+
|
193 |
+
valid_tokens = [t for t in tokens if t is not None]
|
194 |
+
if len(set(valid_tokens)) < len(valid_tokens):
|
195 |
+
raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
|
196 |
+
|
197 |
+
@staticmethod
|
198 |
+
def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
|
199 |
+
all_tokens = []
|
200 |
+
all_embeddings = []
|
201 |
+
for state_dict, token in zip(state_dicts, tokens):
|
202 |
+
if isinstance(state_dict, torch.Tensor):
|
203 |
+
if token is None:
|
204 |
+
raise ValueError(
|
205 |
+
"You are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`."
|
206 |
+
)
|
207 |
+
loaded_token = token
|
208 |
+
embedding = state_dict
|
209 |
+
elif len(state_dict) == 1:
|
210 |
+
# diffusers
|
211 |
+
loaded_token, embedding = next(iter(state_dict.items()))
|
212 |
+
elif "string_to_param" in state_dict:
|
213 |
+
# A1111
|
214 |
+
loaded_token = state_dict["name"]
|
215 |
+
embedding = state_dict["string_to_param"]["*"]
|
216 |
+
else:
|
217 |
+
raise ValueError(
|
218 |
+
f"Loaded state dictionary is incorrect: {state_dict}. \n\n"
|
219 |
+
"Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
|
220 |
+
" input key."
|
221 |
+
)
|
222 |
+
|
223 |
+
if token is not None and loaded_token != token:
|
224 |
+
logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
|
225 |
+
else:
|
226 |
+
token = loaded_token
|
227 |
+
|
228 |
+
if token in tokenizer.get_vocab():
|
229 |
+
raise ValueError(
|
230 |
+
f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
|
231 |
+
)
|
232 |
+
|
233 |
+
all_tokens.append(token)
|
234 |
+
all_embeddings.append(embedding)
|
235 |
+
|
236 |
+
return all_tokens, all_embeddings
|
237 |
+
|
238 |
+
@staticmethod
|
239 |
+
def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
|
240 |
+
all_tokens = []
|
241 |
+
all_embeddings = []
|
242 |
+
|
243 |
+
for embedding, token in zip(embeddings, tokens):
|
244 |
+
if f"{token}_1" in tokenizer.get_vocab():
|
245 |
+
multi_vector_tokens = [token]
|
246 |
+
i = 1
|
247 |
+
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
248 |
+
multi_vector_tokens.append(f"{token}_{i}")
|
249 |
+
i += 1
|
250 |
+
|
251 |
+
raise ValueError(
|
252 |
+
f"Multi-vector Token {multi_vector_tokens} already in tokenizer vocabulary. Please choose a different token name or remove the {multi_vector_tokens} and embedding from the tokenizer and text encoder."
|
253 |
+
)
|
254 |
+
|
255 |
+
is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
|
256 |
+
if is_multi_vector:
|
257 |
+
all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
|
258 |
+
all_embeddings += [e for e in embedding] # noqa: C416
|
259 |
+
else:
|
260 |
+
all_tokens += [token]
|
261 |
+
all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
|
262 |
+
|
263 |
+
return all_tokens, all_embeddings
|
264 |
+
|
265 |
+
@validate_hf_hub_args
|
266 |
+
def load_textual_inversion(
|
267 |
+
self,
|
268 |
+
pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
|
269 |
+
token: Optional[Union[str, List[str]]] = None,
|
270 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
|
271 |
+
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
272 |
+
**kwargs,
|
273 |
+
):
|
274 |
+
r"""
|
275 |
+
Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
|
276 |
+
Automatic1111 formats are supported).
|
277 |
+
|
278 |
+
Parameters:
|
279 |
+
pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
|
280 |
+
Can be either one of the following or a list of them:
|
281 |
+
|
282 |
+
- A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
|
283 |
+
pretrained model hosted on the Hub.
|
284 |
+
- A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
|
285 |
+
inversion weights.
|
286 |
+
- A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
|
287 |
+
- A [torch state
|
288 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
289 |
+
|
290 |
+
token (`str` or `List[str]`, *optional*):
|
291 |
+
Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
|
292 |
+
list, then `token` must also be a list of equal length.
|
293 |
+
text_encoder ([`~transformers.CLIPTextModel`], *optional*):
|
294 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
295 |
+
If not specified, function will take self.tokenizer.
|
296 |
+
tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
|
297 |
+
A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
|
298 |
+
weight_name (`str`, *optional*):
|
299 |
+
Name of a custom weight file. This should be used when:
|
300 |
+
|
301 |
+
- The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
|
302 |
+
name such as `text_inv.bin`.
|
303 |
+
- The saved textual inversion file is in the Automatic1111 format.
|
304 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
305 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
306 |
+
is not used.
|
307 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
308 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
309 |
+
cached versions if they exist.
|
310 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
311 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
312 |
+
incompletely downloaded files are deleted.
|
313 |
+
proxies (`Dict[str, str]`, *optional*):
|
314 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
315 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
316 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
317 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
318 |
+
won't be downloaded from the Hub.
|
319 |
+
token (`str` or *bool*, *optional*):
|
320 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
321 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
322 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
323 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
324 |
+
allowed by Git.
|
325 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
326 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
327 |
+
mirror (`str`, *optional*):
|
328 |
+
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
329 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
330 |
+
information.
|
331 |
+
|
332 |
+
Example:
|
333 |
+
|
334 |
+
To load a Textual Inversion embedding vector in 🤗 Diffusers format:
|
335 |
+
|
336 |
+
```py
|
337 |
+
from diffusers import StableDiffusionPipeline
|
338 |
+
import torch
|
339 |
+
|
340 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
341 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
342 |
+
|
343 |
+
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
|
344 |
+
|
345 |
+
prompt = "A <cat-toy> backpack"
|
346 |
+
|
347 |
+
image = pipe(prompt, num_inference_steps=50).images[0]
|
348 |
+
image.save("cat-backpack.png")
|
349 |
+
```
|
350 |
+
|
351 |
+
To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
|
352 |
+
(for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
|
353 |
+
locally:
|
354 |
+
|
355 |
+
```py
|
356 |
+
from diffusers import StableDiffusionPipeline
|
357 |
+
import torch
|
358 |
+
|
359 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
360 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
361 |
+
|
362 |
+
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
|
363 |
+
|
364 |
+
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
|
365 |
+
|
366 |
+
image = pipe(prompt, num_inference_steps=50).images[0]
|
367 |
+
image.save("character.png")
|
368 |
+
```
|
369 |
+
|
370 |
+
"""
|
371 |
+
# 1. Set correct tokenizer and text encoder
|
372 |
+
tokenizer = tokenizer or getattr(self, "tokenizer", None)
|
373 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
374 |
+
|
375 |
+
# 2. Normalize inputs
|
376 |
+
pretrained_model_name_or_paths = (
|
377 |
+
[pretrained_model_name_or_path]
|
378 |
+
if not isinstance(pretrained_model_name_or_path, list)
|
379 |
+
else pretrained_model_name_or_path
|
380 |
+
)
|
381 |
+
tokens = [token] if not isinstance(token, list) else token
|
382 |
+
if tokens[0] is None:
|
383 |
+
tokens = tokens * len(pretrained_model_name_or_paths)
|
384 |
+
|
385 |
+
# 3. Check inputs
|
386 |
+
self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
|
387 |
+
|
388 |
+
# 4. Load state dicts of textual embeddings
|
389 |
+
state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
|
390 |
+
|
391 |
+
# 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
|
392 |
+
if len(tokens) > 1 and len(state_dicts) == 1:
|
393 |
+
if isinstance(state_dicts[0], torch.Tensor):
|
394 |
+
state_dicts = list(state_dicts[0])
|
395 |
+
if len(tokens) != len(state_dicts):
|
396 |
+
raise ValueError(
|
397 |
+
f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
|
398 |
+
f"Make sure both have the same length."
|
399 |
+
)
|
400 |
+
|
401 |
+
# 4. Retrieve tokens and embeddings
|
402 |
+
tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
|
403 |
+
|
404 |
+
# 5. Extend tokens and embeddings for multi vector
|
405 |
+
tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
|
406 |
+
|
407 |
+
# 6. Make sure all embeddings have the correct size
|
408 |
+
expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
|
409 |
+
if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
|
410 |
+
raise ValueError(
|
411 |
+
"Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
|
412 |
+
"to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
|
413 |
+
)
|
414 |
+
|
415 |
+
# 7. Now we can be sure that loading the embedding matrix works
|
416 |
+
# < Unsafe code:
|
417 |
+
|
418 |
+
# 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
|
419 |
+
is_model_cpu_offload = False
|
420 |
+
is_sequential_cpu_offload = False
|
421 |
+
for _, component in self.components.items():
|
422 |
+
if isinstance(component, nn.Module):
|
423 |
+
if hasattr(component, "_hf_hook"):
|
424 |
+
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
425 |
+
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
426 |
+
logger.info(
|
427 |
+
"Accelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again."
|
428 |
+
)
|
429 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
430 |
+
|
431 |
+
# 7.2 save expected device and dtype
|
432 |
+
device = text_encoder.device
|
433 |
+
dtype = text_encoder.dtype
|
434 |
+
|
435 |
+
# 7.3 Increase token embedding matrix
|
436 |
+
text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
|
437 |
+
input_embeddings = text_encoder.get_input_embeddings().weight
|
438 |
+
|
439 |
+
# 7.4 Load token and embedding
|
440 |
+
for token, embedding in zip(tokens, embeddings):
|
441 |
+
# add tokens and get ids
|
442 |
+
tokenizer.add_tokens(token)
|
443 |
+
token_id = tokenizer.convert_tokens_to_ids(token)
|
444 |
+
input_embeddings.data[token_id] = embedding
|
445 |
+
logger.info(f"Loaded textual inversion embedding for {token}.")
|
446 |
+
|
447 |
+
input_embeddings.to(dtype=dtype, device=device)
|
448 |
+
|
449 |
+
# 7.5 Offload the model again
|
450 |
+
if is_model_cpu_offload:
|
451 |
+
self.enable_model_cpu_offload()
|
452 |
+
elif is_sequential_cpu_offload:
|
453 |
+
self.enable_sequential_cpu_offload()
|
454 |
+
|
455 |
+
# / Unsafe Code >
|
456 |
+
|
457 |
+
def unload_textual_inversion(
|
458 |
+
self,
|
459 |
+
tokens: Optional[Union[str, List[str]]] = None,
|
460 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None,
|
461 |
+
text_encoder: Optional["PreTrainedModel"] = None,
|
462 |
+
):
|
463 |
+
r"""
|
464 |
+
Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]
|
465 |
+
|
466 |
+
Example:
|
467 |
+
```py
|
468 |
+
from diffusers import AutoPipelineForText2Image
|
469 |
+
import torch
|
470 |
+
|
471 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
|
472 |
+
|
473 |
+
# Example 1
|
474 |
+
pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
|
475 |
+
pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
|
476 |
+
|
477 |
+
# Remove all token embeddings
|
478 |
+
pipeline.unload_textual_inversion()
|
479 |
+
|
480 |
+
# Example 2
|
481 |
+
pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
|
482 |
+
pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
|
483 |
+
|
484 |
+
# Remove just one token
|
485 |
+
pipeline.unload_textual_inversion("<moe-bius>")
|
486 |
+
|
487 |
+
# Example 3: unload from SDXL
|
488 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
|
489 |
+
embedding_path = hf_hub_download(repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model")
|
490 |
+
|
491 |
+
# load embeddings to the text encoders
|
492 |
+
state_dict = load_file(embedding_path)
|
493 |
+
|
494 |
+
# load embeddings of text_encoder 1 (CLIP ViT-L/14)
|
495 |
+
pipeline.load_textual_inversion(state_dict["clip_l"], token=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer)
|
496 |
+
# load embeddings of text_encoder 2 (CLIP ViT-G/14)
|
497 |
+
pipeline.load_textual_inversion(state_dict["clip_g"], token=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2)
|
498 |
+
|
499 |
+
# Unload explicitly from both text encoders abd tokenizers
|
500 |
+
pipeline.unload_textual_inversion(tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer)
|
501 |
+
pipeline.unload_textual_inversion(tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2)
|
502 |
+
|
503 |
+
```
|
504 |
+
"""
|
505 |
+
|
506 |
+
tokenizer = tokenizer or getattr(self, "tokenizer", None)
|
507 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
508 |
+
|
509 |
+
# Get textual inversion tokens and ids
|
510 |
+
token_ids = []
|
511 |
+
last_special_token_id = None
|
512 |
+
|
513 |
+
if tokens:
|
514 |
+
if isinstance(tokens, str):
|
515 |
+
tokens = [tokens]
|
516 |
+
for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
|
517 |
+
if not added_token.special:
|
518 |
+
if added_token.content in tokens:
|
519 |
+
token_ids.append(added_token_id)
|
520 |
+
else:
|
521 |
+
last_special_token_id = added_token_id
|
522 |
+
if len(token_ids) == 0:
|
523 |
+
raise ValueError("No tokens to remove found")
|
524 |
+
else:
|
525 |
+
tokens = []
|
526 |
+
for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
|
527 |
+
if not added_token.special:
|
528 |
+
token_ids.append(added_token_id)
|
529 |
+
tokens.append(added_token.content)
|
530 |
+
else:
|
531 |
+
last_special_token_id = added_token_id
|
532 |
+
|
533 |
+
# Delete from tokenizer
|
534 |
+
for token_id, token_to_remove in zip(token_ids, tokens):
|
535 |
+
del tokenizer._added_tokens_decoder[token_id]
|
536 |
+
del tokenizer._added_tokens_encoder[token_to_remove]
|
537 |
+
|
538 |
+
# Make all token ids sequential in tokenizer
|
539 |
+
key_id = 1
|
540 |
+
for token_id in tokenizer.added_tokens_decoder:
|
541 |
+
if token_id > last_special_token_id and token_id > last_special_token_id + key_id:
|
542 |
+
token = tokenizer._added_tokens_decoder[token_id]
|
543 |
+
tokenizer._added_tokens_decoder[last_special_token_id + key_id] = token
|
544 |
+
del tokenizer._added_tokens_decoder[token_id]
|
545 |
+
tokenizer._added_tokens_encoder[token.content] = last_special_token_id + key_id
|
546 |
+
key_id += 1
|
547 |
+
tokenizer._update_trie()
|
548 |
+
|
549 |
+
# Delete from text encoder
|
550 |
+
text_embedding_dim = text_encoder.get_input_embeddings().embedding_dim
|
551 |
+
temp_text_embedding_weights = text_encoder.get_input_embeddings().weight
|
552 |
+
text_embedding_weights = temp_text_embedding_weights[: last_special_token_id + 1]
|
553 |
+
to_append = []
|
554 |
+
for i in range(last_special_token_id + 1, temp_text_embedding_weights.shape[0]):
|
555 |
+
if i not in token_ids:
|
556 |
+
to_append.append(temp_text_embedding_weights[i].unsqueeze(0))
|
557 |
+
if len(to_append) > 0:
|
558 |
+
to_append = torch.cat(to_append, dim=0)
|
559 |
+
text_embedding_weights = torch.cat([text_embedding_weights, to_append], dim=0)
|
560 |
+
text_embeddings_filtered = nn.Embedding(text_embedding_weights.shape[0], text_embedding_dim)
|
561 |
+
text_embeddings_filtered.weight.data = text_embedding_weights
|
562 |
+
text_encoder.set_input_embeddings(text_embeddings_filtered)
|