hungho77 commited on
Commit
9ffb41e
·
verified ·
1 Parent(s): b9649a1

Upload 37 files

Browse files
Files changed (37) hide show
  1. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/.github/workflows/publish.yml +20 -0
  2. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/.gitignore +160 -0
  3. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/LICENSE +674 -0
  4. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/README.md +202 -0
  5. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/__init__.py +3 -0
  6. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc +0 -0
  7. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc +0 -0
  8. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc +0 -0
  9. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc +0 -0
  10. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc +0 -0
  11. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc +0 -0
  12. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc +0 -0
  13. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc +0 -0
  14. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc +0 -0
  15. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc +0 -0
  16. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc +0 -0
  17. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_main.cpython-310.pyc +0 -0
  18. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc +0 -0
  19. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc +0 -0
  20. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc +0 -0
  21. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc +0 -0
  22. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control.py +911 -0
  23. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py +254 -0
  24. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_reference.py +835 -0
  25. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py +1056 -0
  26. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_svd.py +518 -0
  27. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/logger.py +36 -0
  28. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes.py +249 -0
  29. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py +71 -0
  30. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py +461 -0
  31. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_loosecontrol.py +67 -0
  32. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_reference.py +90 -0
  33. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_sparsectrl.py +182 -0
  34. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py +235 -0
  35. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/utils.py +955 -0
  36. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/pyproject.toml +15 -0
  37. ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/requirements.txt +0 -0
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/.github/workflows/publish.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: Publish Custom Node to registry
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out code
16
+ uses: actions/checkout@v4
17
+ - name: Publish Custom Node
18
+ uses: Comfy-Org/publish-node-action@main
19
+ with:
20
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ## Add your own personal access token to your Github Repository secrets and reference it here.
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/README.md ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-Advanced-ControlNet
2
+ Nodes for scheduling ControlNet strength across timesteps and batched latents, as well as applying custom weights and attention masks. The ControlNet nodes here fully support sliding context sampling, like the one used in the [ComfyUI-AnimateDiff-Evolved](https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved) nodes. Currently supports ControlNets, T2IAdapters, ControlLoRAs, ControlLLLite, SparseCtrls, SVD-ControlNets, and Reference.
3
+
4
+ Custom weights allow replication of the "My prompt is more important" feature of Auto1111's sd-webui ControlNet extension via Soft Weights, and the "ControlNet is more important" feature can be granularly controlled by changing the uncond_multiplier on the same Soft Weights.
5
+
6
+ ControlNet preprocessors are available through [comfyui_controlnet_aux](https://github.com/Fannovel16/comfyui_controlnet_aux) nodes.
7
+
8
+ ## Features
9
+ - Timestep and latent strength scheduling
10
+ - Attention masks
11
+ - Replicate ***"My prompt is more important"*** feature from sd-webui-controlnet extension via ***Soft Weights***, and allow softness to be tweaked via ***base_multiplier***
12
+ - Replicate ***"ControlNet is more important"*** feature from sd-webui-controlnet extension via ***uncond_multiplier*** on ***Soft Weights***
13
+ - uncond_multiplier=0.0 gives identical results of auto1111's feature, but values between 0.0 and 1.0 can be used without issue to granularly control the setting.
14
+ - ControlNet, T2IAdapter, and ControlLoRA support for sliding context windows
15
+ - ControlLLLite support (requires model_optional to be passed into and out of Apply Advanced ControlNet node)
16
+ - SparseCtrl support
17
+ - SVD-ControlNet support
18
+ - Stable Video Diffusion ControlNets trained by **CiaraRowles**: [Depth](https://huggingface.co/CiaraRowles/temporal-controlnet-depth-svd-v1/tree/main/controlnet), [Lineart](https://huggingface.co/CiaraRowles/temporal-controlnet-lineart-svd-v1/tree/main/controlnet)
19
+ - Reference support
20
+ - Supports ```reference_attn```, ```reference_adain```, and ```refrence_adain+attn``` modes. ```style_fidelity``` and ```ref_weight``` are equivalent to style_fidelity and control_weight in Auto1111, respectively, and strength of the Apply ControlNet is the balance between ref-influenced result and no-ref result. There is also a Reference ControlNet (Finetune) node that allows adjust the style_fidelity, weight, and strength of attn and adain separately.
21
+
22
+ ## Table of Contents:
23
+ - [Scheduling Explanation](#scheduling-explanation)
24
+ - [Nodes](#nodes)
25
+ - [Usage](#usage) (will fill this out soon)
26
+
27
+
28
+ # Scheduling Explanation
29
+
30
+ The two core concepts for scheduling are ***Timestep Keyframes*** and ***Latent Keyframes***.
31
+
32
+ ***Timestep Keyframes*** hold the values that guide the settings for a controlnet, and begin to take effect based on their start_percent, which corresponds to the percentage of the sampling process. They can contain masks for the strengths of each latent, control_net_weights, and latent_keyframes (specific strengths for each latent), all optional.
33
+
34
+ ***Latent Keyframes*** determine the strength of the controlnet for specific latents - all they contain is the batch_index of the latent, and the strength the controlnet should apply for that latent. As a concept, latent keyframes achieve the same affect as a uniform mask with the chosen strength value.
35
+
36
+ ![advcn_image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/e6275264-6c3f-4246-a319-111ee48f4cd9)
37
+
38
+ # Nodes
39
+
40
+ The ControlNet nodes provided here are the ***Apply Advanced ControlNet*** and ***Load Advanced ControlNet Model*** (or diff) nodes. The vanilla ControlNet nodes are also compatible, and can be used almost interchangeably - the only difference is that **at least one of these nodes must be used** for Advanced versions of ControlNets to be used (important for sliding context sampling, like with AnimateDiff-Evolved).
41
+
42
+ Key:
43
+ - 🟩 - required inputs
44
+ - 🟨 - optional inputs
45
+ - 🟦 - start as widgets, can be converted to inputs
46
+ - 🟥 - optional input/output, but not recommended to use unless needed
47
+ - 🟪 - output
48
+
49
+ ## Apply Advanced ControlNet
50
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/dc541d41-70df-4a71-b832-efa65af98f06)
51
+
52
+ Same functionality as the vanilla Apply Advanced ControlNet (Advanced) node, except with Advanced ControlNet features added to it. Automatically converts any ControlNet from ControlNet loaders into Advanced versions.
53
+
54
+ ### Inputs
55
+ - 🟩***positive***: conditioning (positive).
56
+ - 🟩***negative***: conditioning (negative).
57
+ - 🟩***control_net***: loaded controlnet; will be converted to Advanced version automatically by this node, if it's a supported type.
58
+ - 🟩***image***: images to guide controlnets - if the loaded controlnet requires it, they must preprocessed images. If one image provided, will be used for all latents. If more images provided, will use each image separately for each latent. If not enough images to meet latent count, will repeat the images from the beginning to match vanilla ControlNet functionality.
59
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as image input, if you provide more than one mask, each can apply to a different latent.
60
+ - 🟨***timestep_kf***: timestep keyframes to guide controlnet effect throughout sampling steps.
61
+ - 🟨***latent_kf_override***: override for latent keyframes, useful if no other features from timestep keyframes is needed. *NOTE: this latent keyframe will be applied to ALL timesteps, regardless if there are other latent keyframes attached to connected timestep keyframes.*
62
+ - 🟨***weights_override***: override for weights, useful if no other features from timestep keyframes is needed. *NOTE: this weight will be applied to ALL timesteps, regardless if there are other weights attached to connected timestep keyframes.*
63
+ - 🟦***strength***: strength of controlnet; 1.0 is full strength, 0.0 is no effect at all.
64
+ - 🟦***start_percent***: sampling step percentage at which controlnet should start to be applied - no matter what start_percent is set on timestep keyframes, they won't take effect until this start_percent is reached.
65
+ - 🟦***stop_percent***: sampling step percentage at which controlnet should stop being applied - no matter what start_percent is set on timestep keyframes, they won't take effect once this end_percent is reached.
66
+
67
+ ### Outputs
68
+ - 🟪***positive***: conditioning (positive) with applied controlnets
69
+ - 🟪***negative***: conditioning (negative) with applied controlnets
70
+
71
+ ## Load Advanced ControlNet Model
72
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/4a7f58a9-783d-4da4-bf82-bc9c167e4722)
73
+
74
+ Loads a ControlNet model and converts it into an Advanced version that supports all the features in this repo. When used with **Apply Advanced ControlNet** node, there is no reason to use the timestep_keyframe input on this node - use timestep_kf on the Apply node instead.
75
+
76
+ ### Inputs
77
+ - 🟥***timestep_keyframe***: optional and likely unnecessary input to have ControlNet use selected timestep_keyframes - should not be used unless you need to. Useful if this node is not attached to **Apply Advanced ControlNet** node, but still want to use Timestep Keyframe, or to use TK_SHORTCUT outputs from ControlWeights in the same scenario. Will be overriden by the timestep_kf input on **Apply Advanced ControlNet** node, if one is provided there.
78
+ - 🟨***model***: model to plug into the diff version of the node. Some controlnets are designed for receive the model; if you don't know what this does, you probably don't want tot use the diff version of the node.
79
+
80
+ ### Outputs
81
+ - 🟪***CONTROL_NET***: loaded Advanced ControlNet
82
+
83
+ ## Timestep Keyframe
84
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/404f3cfe-5852-4eed-935b-37e32493d1b5)
85
+
86
+ Scheduling node across timesteps (sampling steps) based on the set start_percent. Chaining Timestep Keyframes allows ControlNet scheduling across sampling steps (percentage-wise), through a timestep keyframe schedule.
87
+
88
+ ### Inputs
89
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
90
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
91
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
92
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
93
+ - 🟦***start_percent***: sampling step percentage at which this Timestep Keyframe qualifies to be used. Acts as the 'key' for the Timestep Keyframe in the timestep keyframe schedule.
94
+ - 🟦***strength***: strength of the controlnet; multiplies the controlnet by this value, basically, applied alongside the strength on the Apply ControlNet node. If set to 0.0 will not have any effect during the duration of this Timestep Keyframe's effect, and will increase sampling speed by not doing any work.
95
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
96
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
97
+ - 🟦***guarantee_steps***: when 1 or greater, even if a Timestep Keyframe's start_percent ahead of this one in the schedule is closer to current sampling percentage, this Timestep Keyframe will still be used for the specified amount of steps before moving on to the next selected Timestep Keyframe in the following step. Whether the Timestep Keyframe is used or not, its inputs will still be accounted for inherit_missing purposes.
98
+
99
+ ### Outputs
100
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
101
+
102
+ ## Timestep Keyframe Interpolation
103
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9789617c-202c-4271-92a2-0909bcf9b108)
104
+
105
+ Allows to create Timestep Keyframe with interpolated strength values in a given percent range. (The first generated keyframe will have guarantee_steps=1, rest that follow will have guarantee_steps=0).
106
+
107
+ ### Inputs
108
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
109
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
110
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
111
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
112
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
113
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
114
+ - 🟦***strength_start***: strength of the Timestep Keyframe at start of range.
115
+ - 🟦***strength_end***: strength of the Timestep Keyframe at end of range.
116
+ - 🟦***interpolation***: the method of interpolation.
117
+ - 🟦***intervals***: the amount of keyframes to generate in total - the first will have its start_percent equal to start_percent, the last will have its start_percent equal to end_percent.
118
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
119
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
120
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
121
+
122
+ ### Outputs
123
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
124
+
125
+ ## Timestep Keyframe From List
126
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9e9c23bf-6f82-4ce7-b4d1-3016fd14707d)
127
+
128
+ Allows to create Timestep Keyframe via a list of floats, such as with Batch Value Schedule from [ComfyUI_FizzNodes](https://github.com/FizzleDorf/ComfyUI_FizzNodes) nodes. (The first generated keyframe will have guarantee_steps=1, rest that follow will have guarantee_steps=0).
129
+
130
+ ### Inputs
131
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
132
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
133
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
134
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
135
+ - 🟩***float_strengths***: a list of floats, that will correspond to the strength of each Timestep Keyframe; first will be assigned to start_percent, last will be assigned to end_percent, and the rest spread linearly between.
136
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
137
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
138
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
139
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
140
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
141
+
142
+ ### Outputs
143
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
144
+
145
+ ## Latent Keyframe
146
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7eb2cc4c-255c-4f32-b09b-699f713fada3)
147
+
148
+ A singular Latent Keyframe, selects the strength for a specific batch_index. If batch_index is not present during sampling, will simply have no effect. Can be chained with any other Latent Keyframe-type node to create a latent keyframe schedule.
149
+
150
+ ### Inputs
151
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If a Latent Keyframe contained in prev_latent_keyframes have the same batch_index as this Latent Keyframe, they will take priority over this node's value.*
152
+ - 🟦***batch_index***: index of latent in batch to apply controlnet strength to. Acts as the 'key' for the Latent Keyframe in the latent keyframe schedule.
153
+ - 🟦***strength***: strength of controlnet to apply to the corresponding latent.
154
+
155
+ ### Outputs
156
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
157
+
158
+ ## Latent Keyframe Group
159
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/5ce3b795-f5fc-4dc3-ae30-a4c7f87e278c)
160
+
161
+ Allows to create Latent Keyframes via individual indeces or python-style ranges.
162
+
163
+ ### Inputs
164
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
165
+ - 🟨***latent_optional***: the latents expected to be passed in for sampling; only required if you wish to use negative indeces (will be automatically converted to real values).
166
+ - 🟦***index_strengths***: string list of indeces or python-style ranges of indeces to assign strengths to. If latent_optional is passed in, can contain negative indeces or ranges that contain negative numbers, python-style. The different indeces must be comma separated. Individual latents can be specified by ```batch_index=strength```, like ```0=0.9```. Ranges can be specified by ```start_index_inclusive:end_index_exclusive=strength```, like ```0:8=strength```. Negative indeces are possible when latents_optional has an input, with a string such as ```0,-4=0.25```.
167
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
168
+
169
+ ### Outputs
170
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
171
+
172
+ ## Latent Keyframe Interpolation
173
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7986c737-83b9-46bc-aab0-ae4c368df446)
174
+
175
+ Allows to create Latent Keyframes with interpolated values in a range.
176
+
177
+ ### Inputs
178
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
179
+ - 🟦***batch_index_from***: starting batch_index of range, included.
180
+ - 🟦***batch_index_to***: end batch_index of range, excluded (python-style range).
181
+ - 🟦***strength_from***: starting strength of interpolation.
182
+ - 🟦***strength_to***: end strength of interpolation.
183
+ - 🟦***interpolation***: the method of interpolation.
184
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
185
+
186
+ ### Outputs
187
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
188
+
189
+ ## Latent Keyframe From List
190
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/6cec701f-6183-4aeb-af5c-cac76f5591b7)
191
+
192
+ Allows to create Latent Keyframes via a list of floats, such as with Batch Value Schedule from [ComfyUI_FizzNodes](https://github.com/FizzleDorf/ComfyUI_FizzNodes) nodes.
193
+
194
+ ### Inputs
195
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
196
+ - 🟩***float_strengths***: a list of floats, that will correspond to the strength of each Latent Keyframe; the batch_index is the index of each float value in the list.
197
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
198
+
199
+ ### Outputs
200
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
201
+
202
+ # There are more nodes to document and show usage - will add this soon! TODO
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .adv_control.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+
3
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (303 Bytes). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc ADDED
Binary file (26.7 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc ADDED
Binary file (6.5 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc ADDED
Binary file (24.9 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc ADDED
Binary file (30.9 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc ADDED
Binary file (1.14 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (7.8 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_main.cpython-310.pyc ADDED
Binary file (5.74 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc ADDED
Binary file (6.63 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc ADDED
Binary file (6.63 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc ADDED
Binary file (32.1 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control.py ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+ from torch import Tensor
3
+ import torch
4
+ import os
5
+
6
+ import comfy.ops
7
+ import comfy.utils
8
+ import comfy.model_management
9
+ import comfy.model_detection
10
+ import comfy.controlnet as comfy_cn
11
+ from comfy.controlnet import ControlBase, ControlNet, ControlLora, T2IAdapter
12
+ from comfy.model_patcher import ModelPatcher
13
+
14
+ from .control_sparsectrl import SparseModelPatcher, SparseControlNet, SparseCtrlMotionWrapper, SparseSettings, SparseConst
15
+ from .control_lllite import LLLiteModule, LLLitePatch
16
+ from .control_svd import svd_unet_config_from_diffusers_unet, SVDControlNet, svd_unet_to_diffusers
17
+ from .utils import (AdvancedControlBase, TimestepKeyframeGroup, LatentKeyframeGroup, AbstractPreprocWrapper, ControlWeightType, ControlWeights, WeightTypeException,
18
+ manual_cast_clean_groupnorm, disable_weight_init_clean_groupnorm, prepare_mask_batch, get_properly_arranged_t2i_weights, load_torch_file_with_dict_factory,
19
+ broadcast_image_to_extend, extend_to_batch_size)
20
+ from .logger import logger
21
+
22
+
23
+ class ControlNetAdvanced(ControlNet, AdvancedControlBase):
24
+ def __init__(self, control_model, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None):
25
+ super().__init__(control_model=control_model, global_average_pooling=global_average_pooling, compression_ratio=compression_ratio, latent_format=latent_format, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
26
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controlnet())
27
+
28
+ def get_universal_weights(self) -> ControlWeights:
29
+ raw_weights = [(self.weights.base_multiplier ** float(12 - i)) for i in range(13)]
30
+ return self.weights.copy_with_new_weights(raw_weights)
31
+
32
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
33
+ # perform special version of get_control that supports sliding context and masks
34
+ return self.sliding_get_control(x_noisy, t, cond, batched_number)
35
+
36
+ def sliding_get_control(self, x_noisy: Tensor, t, cond, batched_number):
37
+ control_prev = None
38
+ if self.previous_controlnet is not None:
39
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
40
+
41
+ if self.timestep_range is not None:
42
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
43
+ if control_prev is not None:
44
+ return control_prev
45
+ else:
46
+ return None
47
+
48
+ dtype = self.control_model.dtype
49
+ if self.manual_cast_dtype is not None:
50
+ dtype = self.manual_cast_dtype
51
+
52
+ output_dtype = x_noisy.dtype
53
+ # make cond_hint appropriate dimensions
54
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
55
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
56
+ if self.cond_hint is not None:
57
+ del self.cond_hint
58
+ self.cond_hint = None
59
+ compression_ratio = self.compression_ratio
60
+ if self.vae is not None:
61
+ compression_ratio *= self.vae.downscale_ratio
62
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
63
+ if self.sub_idxs is not None:
64
+ actual_cond_hint_orig = self.cond_hint_original
65
+ if self.cond_hint_original.size(0) < self.full_latent_length:
66
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
67
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, 'nearest-exact', "center")
68
+ else:
69
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, 'nearest-exact', "center")
70
+ if self.vae is not None:
71
+ loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
72
+ self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
73
+ comfy.model_management.load_models_gpu(loaded_models)
74
+ if self.latent_format is not None:
75
+ self.cond_hint = self.latent_format.process_in(self.cond_hint)
76
+ self.cond_hint = self.cond_hint.to(device=self.device, dtype=dtype)
77
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
78
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
79
+
80
+ # prepare mask_cond_hint
81
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
82
+
83
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
84
+ y = cond.get('y', None)
85
+ if y is not None:
86
+ y = y.to(dtype)
87
+ timestep = self.model_sampling_current.timestep(t)
88
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
89
+
90
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
91
+ return self.control_merge(control, control_prev, output_dtype)
92
+
93
+ def copy(self):
94
+ c = ControlNetAdvanced(self.control_model, self.timestep_keyframes, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
95
+ self.copy_to(c)
96
+ self.copy_to_advanced(c)
97
+ return c
98
+
99
+ @staticmethod
100
+ def from_vanilla(v: ControlNet, timestep_keyframe: TimestepKeyframeGroup=None) -> 'ControlNetAdvanced':
101
+ return ControlNetAdvanced(control_model=v.control_model, timestep_keyframes=timestep_keyframe,
102
+ global_average_pooling=v.global_average_pooling, compression_ratio=v.compression_ratio, latent_format=v.latent_format, device=v.device, load_device=v.load_device, manual_cast_dtype=v.manual_cast_dtype)
103
+
104
+
105
+ class T2IAdapterAdvanced(T2IAdapter, AdvancedControlBase):
106
+ def __init__(self, t2i_model, timestep_keyframes: TimestepKeyframeGroup, channels_in, compression_ratio=8, upscale_algorithm="nearest_exact", device=None):
107
+ super().__init__(t2i_model=t2i_model, channels_in=channels_in, compression_ratio=compression_ratio, upscale_algorithm=upscale_algorithm, device=device)
108
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.t2iadapter())
109
+
110
+ def control_merge_inject(self, control: dict[str, list[Tensor]], control_prev, output_dtype):
111
+ # match batch_size
112
+ # TODO: make this more efficient by modifying the cached self.control_input val instead of doing this every step
113
+ for key in control:
114
+ control_current = control[key]
115
+ for i in range(len(control_current)):
116
+ x = control_current[i]
117
+ if x is not None and x.size(0) == 1 and x.size(0) != self.batch_size:
118
+ control_current[i] = x.repeat(self.batch_size, 1, 1, 1)[:self.batch_size]
119
+ return AdvancedControlBase.control_merge_inject(self, control, control_prev, output_dtype)
120
+
121
+ def get_universal_weights(self) -> ControlWeights:
122
+ raw_weights = [(self.weights.base_multiplier ** float(7 - i)) for i in range(8)]
123
+ raw_weights = [raw_weights[-8], raw_weights[-3], raw_weights[-2], raw_weights[-1]]
124
+ raw_weights = get_properly_arranged_t2i_weights(raw_weights)
125
+ raw_weights.reverse() # need to reverse to match recent ComfyUI changes
126
+ return self.weights.copy_with_new_weights(raw_weights)
127
+
128
+ def get_calc_pow(self, idx: int, control: dict[str, list[Tensor]], key: str) -> int:
129
+ # match how T2IAdapterAdvanced deals with universal weights
130
+ indeces = [7 - i for i in range(8)]
131
+ indeces = [indeces[-8], indeces[-3], indeces[-2], indeces[-1]]
132
+ indeces = get_properly_arranged_t2i_weights(indeces)
133
+ indeces.reverse() # need to reverse to match recent ComfyUI changes
134
+ return indeces[idx]
135
+
136
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
137
+ try:
138
+ # if sub indexes present, replace original hint with subsection
139
+ if self.sub_idxs is not None:
140
+ # cond hints
141
+ full_cond_hint_original = self.cond_hint_original
142
+ actual_cond_hint_orig = full_cond_hint_original
143
+ del self.cond_hint
144
+ self.cond_hint = None
145
+ if full_cond_hint_original.size(0) < self.full_latent_length:
146
+ actual_cond_hint_orig = extend_to_batch_size(tensor=full_cond_hint_original, batch_size=full_cond_hint_original.size(0))
147
+ self.cond_hint_original = actual_cond_hint_orig[self.sub_idxs]
148
+ # mask hints
149
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
150
+ return super().get_control(x_noisy, t, cond, batched_number)
151
+ finally:
152
+ if self.sub_idxs is not None:
153
+ # replace original cond hint
154
+ self.cond_hint_original = full_cond_hint_original
155
+ del full_cond_hint_original
156
+
157
+ def copy(self):
158
+ c = T2IAdapterAdvanced(self.t2i_model, self.timestep_keyframes, self.channels_in, self.compression_ratio, self.upscale_algorithm)
159
+ self.copy_to(c)
160
+ self.copy_to_advanced(c)
161
+ return c
162
+
163
+ def cleanup(self):
164
+ super().cleanup()
165
+ self.cleanup_advanced()
166
+
167
+ @staticmethod
168
+ def from_vanilla(v: T2IAdapter, timestep_keyframe: TimestepKeyframeGroup=None) -> 'T2IAdapterAdvanced':
169
+ return T2IAdapterAdvanced(t2i_model=v.t2i_model, timestep_keyframes=timestep_keyframe, channels_in=v.channels_in,
170
+ compression_ratio=v.compression_ratio, upscale_algorithm=v.upscale_algorithm, device=v.device)
171
+
172
+
173
+ class ControlLoraAdvanced(ControlLora, AdvancedControlBase):
174
+ def __init__(self, control_weights, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, device=None):
175
+ super().__init__(control_weights=control_weights, global_average_pooling=global_average_pooling, device=device)
176
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllora())
177
+ # use some functions from ControlNetAdvanced
178
+ self.get_control_advanced = ControlNetAdvanced.get_control_advanced.__get__(self, type(self))
179
+ self.sliding_get_control = ControlNetAdvanced.sliding_get_control.__get__(self, type(self))
180
+
181
+ def get_universal_weights(self) -> ControlWeights:
182
+ raw_weights = [(self.weights.base_multiplier ** float(9 - i)) for i in range(10)]
183
+ return self.weights.copy_with_new_weights(raw_weights)
184
+
185
+ def copy(self):
186
+ c = ControlLoraAdvanced(self.control_weights, self.timestep_keyframes, global_average_pooling=self.global_average_pooling)
187
+ self.copy_to(c)
188
+ self.copy_to_advanced(c)
189
+ return c
190
+
191
+ def cleanup(self):
192
+ super().cleanup()
193
+ self.cleanup_advanced()
194
+
195
+ @staticmethod
196
+ def from_vanilla(v: ControlLora, timestep_keyframe: TimestepKeyframeGroup=None) -> 'ControlLoraAdvanced':
197
+ return ControlLoraAdvanced(control_weights=v.control_weights, timestep_keyframes=timestep_keyframe,
198
+ global_average_pooling=v.global_average_pooling, device=v.device)
199
+
200
+
201
+ class SVDControlNetAdvanced(ControlNetAdvanced):
202
+ def __init__(self, control_model: SVDControlNet, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
203
+ super().__init__(control_model=control_model, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
204
+
205
+ def set_cond_hint_inject(self, *args, **kwargs):
206
+ to_return = super().set_cond_hint_inject(*args, **kwargs)
207
+ # cond hint for SVD-ControlNet needs to be scaled between (-1, 1) instead of (0, 1)
208
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
209
+ return to_return
210
+
211
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
212
+ control_prev = None
213
+ if self.previous_controlnet is not None:
214
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
215
+
216
+ if self.timestep_range is not None:
217
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
218
+ if control_prev is not None:
219
+ return control_prev
220
+ else:
221
+ return None
222
+
223
+ dtype = self.control_model.dtype
224
+ if self.manual_cast_dtype is not None:
225
+ dtype = self.manual_cast_dtype
226
+
227
+ output_dtype = x_noisy.dtype
228
+ # make cond_hint appropriate dimensions
229
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
230
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
231
+ if self.cond_hint is not None:
232
+ del self.cond_hint
233
+ self.cond_hint = None
234
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
235
+ if self.sub_idxs is not None:
236
+ actual_cond_hint_orig = self.cond_hint_original
237
+ if self.cond_hint_original.size(0) < self.full_latent_length:
238
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
239
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
240
+ else:
241
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
242
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
243
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
244
+
245
+ # prepare mask_cond_hint
246
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
247
+
248
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
249
+ # uses 'y' in new ComfyUI update
250
+ y = cond.get('y', None)
251
+ if y is not None:
252
+ y = y.to(dtype)
253
+ timestep = self.model_sampling_current.timestep(t)
254
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
255
+ # concat c_concat if exists (should exist for SVD), doubling channels to 8
256
+ if cond.get('c_concat', None) is not None:
257
+ x_noisy = torch.cat([x_noisy] + [cond['c_concat']], dim=1)
258
+
259
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, cond=cond)
260
+ return self.control_merge(control, control_prev, output_dtype)
261
+
262
+ def copy(self):
263
+ c = SVDControlNetAdvanced(self.control_model, self.timestep_keyframes, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
264
+ self.copy_to(c)
265
+ self.copy_to_advanced(c)
266
+ return c
267
+
268
+
269
+ class SparseCtrlAdvanced(ControlNetAdvanced):
270
+ def __init__(self, control_model, timestep_keyframes: TimestepKeyframeGroup, sparse_settings: SparseSettings=None, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
271
+ super().__init__(control_model=control_model, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
272
+ self.control_model_wrapped = SparseModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
273
+ self.add_compatible_weight(ControlWeightType.SPARSECTRL)
274
+ self.control_model: SparseControlNet = self.control_model # does nothing except help with IDE hints
275
+ if self.control_model.use_simplified_conditioning_embedding:
276
+ # TODO: allow vae_optional to be used instead of preprocessor
277
+ #self.require_vae = True
278
+ self.allow_condhint_latents = True
279
+ self.sparse_settings = sparse_settings if sparse_settings is not None else SparseSettings.default()
280
+ self.model_latent_format = None # latent format for active SD model, NOT controlnet
281
+ self.preprocessed = False
282
+
283
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
284
+ # normal ControlNet stuff
285
+ control_prev = None
286
+ if self.previous_controlnet is not None:
287
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
288
+
289
+ if self.timestep_range is not None:
290
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
291
+ if control_prev is not None:
292
+ return control_prev
293
+ else:
294
+ return None
295
+
296
+ dtype = self.control_model.dtype
297
+ if self.manual_cast_dtype is not None:
298
+ dtype = self.manual_cast_dtype
299
+ output_dtype = x_noisy.dtype
300
+ # set actual input length on motion model
301
+ actual_length = x_noisy.size(0)//batched_number
302
+ full_length = actual_length if self.sub_idxs is None else self.full_latent_length
303
+ self.control_model.set_actual_length(actual_length=actual_length, full_length=full_length)
304
+ # prepare cond_hint, if needed
305
+ dim_mult = 1 if self.control_model.use_simplified_conditioning_embedding else 8
306
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2]*dim_mult != self.cond_hint.shape[2] or x_noisy.shape[3]*dim_mult != self.cond_hint.shape[3]:
307
+ # clear out cond_hint and conditioning_mask
308
+ if self.cond_hint is not None:
309
+ del self.cond_hint
310
+ self.cond_hint = None
311
+ # first, figure out which cond idxs are relevant, and where they fit in
312
+ cond_idxs, hint_order = self.sparse_settings.sparse_method.get_indexes(hint_length=self.cond_hint_original.size(0), full_length=full_length,
313
+ sub_idxs=self.sub_idxs if self.sparse_settings.is_context_aware() else None)
314
+ range_idxs = list(range(full_length)) if self.sub_idxs is None else self.sub_idxs
315
+ hint_idxs = [] # idxs in cond_idxs
316
+ local_idxs = [] # idx to put in final cond_hint
317
+ for i,cond_idx in enumerate(cond_idxs):
318
+ if cond_idx in range_idxs:
319
+ hint_idxs.append(i)
320
+ local_idxs.append(range_idxs.index(cond_idx))
321
+ # log_string = f"cond_idxs: {cond_idxs}, local_idxs: {local_idxs}, hint_idxs: {hint_idxs}, hint_order: {hint_order}"
322
+ # if self.sub_idxs is not None:
323
+ # log_string += f" sub_idxs: {self.sub_idxs[0]}-{self.sub_idxs[-1]}"
324
+ # logger.warn(log_string)
325
+ # determine cond/uncond indexes that will get masked
326
+ self.local_sparse_idxs = []
327
+ self.local_sparse_idxs_inverse = list(range(x_noisy.size(0)))
328
+ for batch_idx in range(batched_number):
329
+ for i in local_idxs:
330
+ actual_i = i+(batch_idx*actual_length)
331
+ self.local_sparse_idxs.append(actual_i)
332
+ if actual_i in self.local_sparse_idxs_inverse:
333
+ self.local_sparse_idxs_inverse.remove(actual_i)
334
+ # sub_cond_hint now contains the hints relevant to current x_noisy
335
+ if hint_order is None:
336
+ sub_cond_hint = self.cond_hint_original[hint_idxs].to(dtype).to(self.device)
337
+ else:
338
+ sub_cond_hint = self.cond_hint_original[hint_order][hint_idxs].to(dtype).to(self.device)
339
+ # scale cond_hints to match noisy input
340
+ if self.control_model.use_simplified_conditioning_embedding:
341
+ # RGB SparseCtrl; the inputs are latents - use bilinear to avoid blocky artifacts
342
+ sub_cond_hint = self.model_latent_format.process_in(sub_cond_hint) # multiplies by model scale factor
343
+ sub_cond_hint = comfy.utils.common_upscale(sub_cond_hint, x_noisy.shape[3], x_noisy.shape[2], "nearest-exact", "center").to(dtype).to(self.device)
344
+ else:
345
+ # other SparseCtrl; inputs are typical images
346
+ sub_cond_hint = comfy.utils.common_upscale(sub_cond_hint, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
347
+ # prepare cond_hint (b, c, h ,w)
348
+ cond_shape = list(sub_cond_hint.shape)
349
+ cond_shape[0] = len(range_idxs)
350
+ self.cond_hint = torch.zeros(cond_shape).to(dtype).to(self.device)
351
+ self.cond_hint[local_idxs] = sub_cond_hint[:]
352
+ # prepare cond_mask (b, 1, h, w)
353
+ cond_shape[1] = 1
354
+ cond_mask = torch.zeros(cond_shape).to(dtype).to(self.device)
355
+ cond_mask[local_idxs] = self.sparse_settings.sparse_mask_mult * self.weights.extras.get(SparseConst.MASK_MULT, 1.0)
356
+ # combine cond_hint and cond_mask into (b, c+1, h, w)
357
+ if not self.sparse_settings.merged:
358
+ self.cond_hint = torch.cat([self.cond_hint, cond_mask], dim=1)
359
+ del sub_cond_hint
360
+ del cond_mask
361
+ # make cond_hint match x_noisy batch
362
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
363
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
364
+
365
+ # prepare mask_cond_hint
366
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
367
+
368
+ context = cond['c_crossattn']
369
+ y = cond.get('y', None)
370
+ if y is not None:
371
+ y = y.to(dtype)
372
+ timestep = self.model_sampling_current.timestep(t)
373
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
374
+
375
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
376
+ return self.control_merge(control, control_prev, output_dtype)
377
+
378
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int):
379
+ # apply mults to indexes with and without a direct condhint
380
+ x[self.local_sparse_idxs] *= self.sparse_settings.sparse_hint_mult * self.weights.extras.get(SparseConst.HINT_MULT, 1.0)
381
+ x[self.local_sparse_idxs_inverse] *= self.sparse_settings.sparse_nonhint_mult * self.weights.extras.get(SparseConst.NONHINT_MULT, 1.0)
382
+ return super().apply_advanced_strengths_and_masks(x, batched_number)
383
+
384
+ def pre_run_advanced(self, model, percent_to_timestep_function):
385
+ super().pre_run_advanced(model, percent_to_timestep_function)
386
+ if isinstance(self.cond_hint_original, AbstractPreprocWrapper):
387
+ if not self.control_model.use_simplified_conditioning_embedding:
388
+ raise ValueError("Any model besides RGB SparseCtrl should NOT have its images go through the RGB SparseCtrl preprocessor.")
389
+ self.cond_hint_original = self.cond_hint_original.condhint
390
+ self.model_latent_format = model.latent_format # LatentFormat object, used to process_in latent cond hint
391
+ if self.control_model.motion_wrapper is not None:
392
+ self.control_model.motion_wrapper.reset()
393
+ self.control_model.motion_wrapper.set_strength(self.sparse_settings.motion_strength)
394
+ self.control_model.motion_wrapper.set_scale_multiplier(self.sparse_settings.motion_scale)
395
+
396
+ def cleanup_advanced(self):
397
+ super().cleanup_advanced()
398
+ if self.model_latent_format is not None:
399
+ del self.model_latent_format
400
+ self.model_latent_format = None
401
+ self.local_sparse_idxs = None
402
+ self.local_sparse_idxs_inverse = None
403
+
404
+ def copy(self):
405
+ c = SparseCtrlAdvanced(self.control_model, self.timestep_keyframes, self.sparse_settings, self.global_average_pooling, self.device, self.load_device, self.manual_cast_dtype)
406
+ self.copy_to(c)
407
+ self.copy_to_advanced(c)
408
+ return c
409
+
410
+
411
+ class ControlLLLiteAdvanced(ControlBase, AdvancedControlBase):
412
+ # This ControlNet is more of an attention patch than a traditional controlnet
413
+ def __init__(self, patch_attn1: LLLitePatch, patch_attn2: LLLitePatch, timestep_keyframes: TimestepKeyframeGroup, device=None):
414
+ super().__init__(device)
415
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite(), require_model=True)
416
+ self.patch_attn1 = patch_attn1.set_control(self)
417
+ self.patch_attn2 = patch_attn2.set_control(self)
418
+ self.latent_dims_div2 = None
419
+ self.latent_dims_div4 = None
420
+
421
+ def patch_model(self, model: ModelPatcher):
422
+ model.set_model_attn1_patch(self.patch_attn1)
423
+ model.set_model_attn2_patch(self.patch_attn2)
424
+
425
+ def set_cond_hint_inject(self, *args, **kwargs):
426
+ to_return = super().set_cond_hint_inject(*args, **kwargs)
427
+ # cond hint for LLLite needs to be scaled between (-1, 1) instead of (0, 1)
428
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
429
+ return to_return
430
+
431
+ def pre_run_advanced(self, *args, **kwargs):
432
+ AdvancedControlBase.pre_run_advanced(self, *args, **kwargs)
433
+ #logger.error(f"in cn: {id(self.patch_attn1)},{id(self.patch_attn2)}")
434
+ self.patch_attn1.set_control(self)
435
+ self.patch_attn2.set_control(self)
436
+ #logger.warn(f"in pre_run_advanced: {id(self)}")
437
+
438
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
439
+ # normal ControlNet stuff
440
+ control_prev = None
441
+ if self.previous_controlnet is not None:
442
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
443
+
444
+ if self.timestep_range is not None:
445
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
446
+ return control_prev
447
+
448
+ dtype = x_noisy.dtype
449
+ # prepare cond_hint
450
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
451
+ if self.cond_hint is not None:
452
+ del self.cond_hint
453
+ self.cond_hint = None
454
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
455
+ if self.sub_idxs is not None:
456
+ actual_cond_hint_orig = self.cond_hint_original
457
+ if self.cond_hint_original.size(0) < self.full_latent_length:
458
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
459
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
460
+ else:
461
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
462
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
463
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
464
+ # some special logic here compared to other controlnets:
465
+ # * The cond_emb in attn patches will divide latent dims by 2 or 4, integer
466
+ # * Due to this loss, the cond_emb will become smaller than x input if latent dims are not divisble by 2 or 4
467
+ divisible_by_2_h = x_noisy.shape[2]%2==0
468
+ divisible_by_2_w = x_noisy.shape[3]%2==0
469
+ if not (divisible_by_2_h and divisible_by_2_w):
470
+ #logger.warn(f"{x_noisy.shape} not divisible by 2!")
471
+ new_h = (x_noisy.shape[2]//2)*2
472
+ new_w = (x_noisy.shape[3]//2)*2
473
+ if not divisible_by_2_h:
474
+ new_h += 2
475
+ if not divisible_by_2_w:
476
+ new_w += 2
477
+ self.latent_dims_div2 = (new_h, new_w)
478
+ divisible_by_4_h = x_noisy.shape[2]%4==0
479
+ divisible_by_4_w = x_noisy.shape[3]%4==0
480
+ if not (divisible_by_4_h and divisible_by_4_w):
481
+ #logger.warn(f"{x_noisy.shape} not divisible by 4!")
482
+ new_h = (x_noisy.shape[2]//4)*4
483
+ new_w = (x_noisy.shape[3]//4)*4
484
+ if not divisible_by_4_h:
485
+ new_h += 4
486
+ if not divisible_by_4_w:
487
+ new_w += 4
488
+ self.latent_dims_div4 = (new_h, new_w)
489
+ # prepare mask
490
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
491
+ # done preparing; model patches will take care of everything now.
492
+ # return normal controlnet stuff
493
+ return control_prev
494
+
495
+ def cleanup_advanced(self):
496
+ super().cleanup_advanced()
497
+ self.patch_attn1.cleanup()
498
+ self.patch_attn2.cleanup()
499
+ self.latent_dims_div2 = None
500
+ self.latent_dims_div4 = None
501
+
502
+ def copy(self):
503
+ c = ControlLLLiteAdvanced(self.patch_attn1, self.patch_attn2, self.timestep_keyframes)
504
+ self.copy_to(c)
505
+ self.copy_to_advanced(c)
506
+ return c
507
+
508
+ # deepcopy needs to properly keep track of objects to work between model.clone calls!
509
+ # def __deepcopy__(self, *args, **kwargs):
510
+ # self.cleanup_advanced()
511
+ # return self
512
+
513
+ # def get_models(self):
514
+ # # get_models is called once at the start of every KSampler run - use to reset already_patched status
515
+ # out = super().get_models()
516
+ # logger.error(f"in get_models! {id(self)}")
517
+ # return out
518
+
519
+
520
+ def load_controlnet(ckpt_path, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
521
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
522
+ control = None
523
+ # check if a non-vanilla ControlNet
524
+ controlnet_type = ControlWeightType.DEFAULT
525
+ has_controlnet_key = False
526
+ has_motion_modules_key = False
527
+ has_temporal_res_block_key = False
528
+ for key in controlnet_data:
529
+ # LLLite check
530
+ if "lllite" in key:
531
+ controlnet_type = ControlWeightType.CONTROLLLLITE
532
+ break
533
+ # SparseCtrl check
534
+ elif "motion_modules" in key:
535
+ has_motion_modules_key = True
536
+ elif "controlnet" in key:
537
+ has_controlnet_key = True
538
+ # SVD-ControlNet check
539
+ elif "temporal_res_block" in key:
540
+ has_temporal_res_block_key = True
541
+ if has_controlnet_key and has_motion_modules_key:
542
+ controlnet_type = ControlWeightType.SPARSECTRL
543
+ elif has_controlnet_key and has_temporal_res_block_key:
544
+ controlnet_type = ControlWeightType.SVD_CONTROLNET
545
+
546
+ if controlnet_type != ControlWeightType.DEFAULT:
547
+ if controlnet_type == ControlWeightType.CONTROLLLLITE:
548
+ control = load_controllllite(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
549
+ elif controlnet_type == ControlWeightType.SPARSECTRL:
550
+ control = load_sparsectrl(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe, model=model)
551
+ elif controlnet_type == ControlWeightType.SVD_CONTROLNET:
552
+ control = load_svdcontrolnet(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
553
+ # otherwise, load vanilla ControlNet
554
+ else:
555
+ try:
556
+ # hacky way of getting load_torch_file in load_controlnet to use already-present controlnet_data and not redo loading
557
+ orig_load_torch_file = comfy.utils.load_torch_file
558
+ comfy.utils.load_torch_file = load_torch_file_with_dict_factory(controlnet_data, orig_load_torch_file)
559
+ control = comfy_cn.load_controlnet(ckpt_path, model=model)
560
+ finally:
561
+ comfy.utils.load_torch_file = orig_load_torch_file
562
+ return convert_to_advanced(control, timestep_keyframe=timestep_keyframe)
563
+
564
+
565
+ def convert_to_advanced(control, timestep_keyframe: TimestepKeyframeGroup=None):
566
+ # if already advanced, leave it be
567
+ if is_advanced_controlnet(control):
568
+ return control
569
+ # if exactly ControlNet returned, transform it into ControlNetAdvanced
570
+ if type(control) == ControlNet:
571
+ control = ControlNetAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
572
+ if is_sd3_advanced_controlnet(control):
573
+ control.require_vae = True
574
+ return control
575
+ # if exactly ControlLora returned, transform it into ControlLoraAdvanced
576
+ elif type(control) == ControlLora:
577
+ return ControlLoraAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
578
+ # if T2IAdapter returned, transform it into T2IAdapterAdvanced
579
+ elif isinstance(control, T2IAdapter):
580
+ return T2IAdapterAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
581
+ # otherwise, leave it be - might be something I am not supporting yet
582
+ return control
583
+
584
+
585
+ def is_advanced_controlnet(input_object):
586
+ return hasattr(input_object, "sub_idxs")
587
+
588
+
589
+ def is_sd3_advanced_controlnet(input_object: ControlNetAdvanced):
590
+ return type(input_object) == ControlNetAdvanced and input_object.latent_format is not None
591
+
592
+
593
+ def load_sparsectrl(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, sparse_settings=SparseSettings.default(), model=None) -> SparseCtrlAdvanced:
594
+ if controlnet_data is None:
595
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
596
+ # first, separate out motion part from normal controlnet part and attempt to load that portion
597
+ motion_data = {}
598
+ for key in list(controlnet_data.keys()):
599
+ if "temporal" in key:
600
+ motion_data[key] = controlnet_data.pop(key)
601
+ if len(motion_data) == 0:
602
+ raise ValueError(f"No motion-related keys in '{ckpt_path}'; not a valid SparseCtrl model!")
603
+
604
+ # now, load as if it was a normal controlnet - mostly copied from comfy load_controlnet function
605
+ controlnet_config: dict[str] = None
606
+ is_diffusers = False
607
+ use_simplified_conditioning_embedding = False
608
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data:
609
+ is_diffusers = True
610
+ if "controlnet_cond_embedding.weight" in controlnet_data:
611
+ is_diffusers = True
612
+ use_simplified_conditioning_embedding = True
613
+ if is_diffusers: #diffusers format
614
+ unet_dtype = comfy.model_management.unet_dtype()
615
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
616
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
617
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
618
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
619
+
620
+ count = 0
621
+ loop = True
622
+ while loop:
623
+ suffix = [".weight", ".bias"]
624
+ for s in suffix:
625
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
626
+ k_out = "zero_convs.{}.0{}".format(count, s)
627
+ if k_in not in controlnet_data:
628
+ loop = False
629
+ break
630
+ diffusers_keys[k_in] = k_out
631
+ count += 1
632
+ # normal conditioning embedding
633
+ if not use_simplified_conditioning_embedding:
634
+ count = 0
635
+ loop = True
636
+ while loop:
637
+ suffix = [".weight", ".bias"]
638
+ for s in suffix:
639
+ if count == 0:
640
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
641
+ else:
642
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
643
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
644
+ if k_in not in controlnet_data:
645
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
646
+ loop = False
647
+ diffusers_keys[k_in] = k_out
648
+ count += 1
649
+ # simplified conditioning embedding
650
+ else:
651
+ count = 0
652
+ suffix = [".weight", ".bias"]
653
+ for s in suffix:
654
+ k_in = "controlnet_cond_embedding{}".format(s)
655
+ k_out = "input_hint_block.{}{}".format(count, s)
656
+ diffusers_keys[k_in] = k_out
657
+
658
+ new_sd = {}
659
+ for k in diffusers_keys:
660
+ if k in controlnet_data:
661
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
662
+
663
+ leftover_keys = controlnet_data.keys()
664
+ if len(leftover_keys) > 0:
665
+ logger.info("leftover keys:", leftover_keys)
666
+ controlnet_data = new_sd
667
+
668
+ pth_key = 'control_model.zero_convs.0.0.weight'
669
+ pth = False
670
+ key = 'zero_convs.0.0.weight'
671
+ if pth_key in controlnet_data:
672
+ pth = True
673
+ key = pth_key
674
+ prefix = "control_model."
675
+ elif key in controlnet_data:
676
+ prefix = ""
677
+ else:
678
+ raise ValueError("The provided model is not a valid SparseCtrl model! [ErrorCode: HORSERADISH]")
679
+
680
+ if controlnet_config is None:
681
+ unet_dtype = comfy.model_management.unet_dtype()
682
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
683
+ load_device = comfy.model_management.get_torch_device()
684
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
685
+ if manual_cast_dtype is not None:
686
+ controlnet_config["operations"] = manual_cast_clean_groupnorm
687
+ else:
688
+ controlnet_config["operations"] = disable_weight_init_clean_groupnorm
689
+ controlnet_config.pop("out_channels")
690
+ # get proper hint channels
691
+ if use_simplified_conditioning_embedding:
692
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
693
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
694
+ else:
695
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
696
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
697
+ control_model = SparseControlNet(**controlnet_config)
698
+
699
+ if pth:
700
+ if 'difference' in controlnet_data:
701
+ if model is not None:
702
+ comfy.model_management.load_models_gpu([model])
703
+ model_sd = model.model_state_dict()
704
+ for x in controlnet_data:
705
+ c_m = "control_model."
706
+ if x.startswith(c_m):
707
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
708
+ if sd_key in model_sd:
709
+ cd = controlnet_data[x]
710
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
711
+ else:
712
+ logger.warning("WARNING: Loaded a diff SparseCtrl without a model. It will very likely not work.")
713
+
714
+ class WeightsLoader(torch.nn.Module):
715
+ pass
716
+ w = WeightsLoader()
717
+ w.control_model = control_model
718
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
719
+ else:
720
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
721
+ if len(missing) > 0 or len(unexpected) > 0:
722
+ logger.info(f"SparseCtrl ControlNet: {missing}, {unexpected}")
723
+
724
+ global_average_pooling = False
725
+ filename = os.path.splitext(ckpt_path)[0]
726
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
727
+ global_average_pooling = True
728
+
729
+ # actually load motion portion of model now
730
+ motion_wrapper: SparseCtrlMotionWrapper = SparseCtrlMotionWrapper(motion_data, ops=controlnet_config.get("operations", None)).to(comfy.model_management.unet_dtype())
731
+ missing, unexpected = motion_wrapper.load_state_dict(motion_data)
732
+ if len(missing) > 0 or len(unexpected) > 0:
733
+ logger.info(f"SparseCtrlMotionWrapper: {missing}, {unexpected}")
734
+
735
+ # both motion portion and controlnet portions are loaded; bring them together if using motion model
736
+ if sparse_settings.use_motion:
737
+ motion_wrapper.inject(control_model)
738
+
739
+ control = SparseCtrlAdvanced(control_model, timestep_keyframes=timestep_keyframe, sparse_settings=sparse_settings, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
740
+ return control
741
+
742
+
743
+ def load_controllllite(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None):
744
+ if controlnet_data is None:
745
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
746
+ # adapted from https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
747
+ # first, split weights for each module
748
+ module_weights = {}
749
+ for key, value in controlnet_data.items():
750
+ fragments = key.split(".")
751
+ module_name = fragments[0]
752
+ weight_name = ".".join(fragments[1:])
753
+
754
+ if module_name not in module_weights:
755
+ module_weights[module_name] = {}
756
+ module_weights[module_name][weight_name] = value
757
+
758
+ # next, load each module
759
+ modules = {}
760
+ for module_name, weights in module_weights.items():
761
+ # kohya planned to do something about how these should be chosen, so I'm not touching this
762
+ # since I am not familiar with the logic for this
763
+ if "conditioning1.4.weight" in weights:
764
+ depth = 3
765
+ elif weights["conditioning1.2.weight"].shape[-1] == 4:
766
+ depth = 2
767
+ else:
768
+ depth = 1
769
+
770
+ module = LLLiteModule(
771
+ name=module_name,
772
+ is_conv2d=weights["down.0.weight"].ndim == 4,
773
+ in_dim=weights["down.0.weight"].shape[1],
774
+ depth=depth,
775
+ cond_emb_dim=weights["conditioning1.0.weight"].shape[0] * 2,
776
+ mlp_dim=weights["down.0.weight"].shape[0],
777
+ )
778
+ # load weights into module
779
+ module.load_state_dict(weights)
780
+ modules[module_name] = module
781
+ if len(modules) == 1:
782
+ module.is_first = True
783
+
784
+ #logger.info(f"loaded {ckpt_path} successfully, {len(modules)} modules")
785
+
786
+ patch_attn1 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN1)
787
+ patch_attn2 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN2)
788
+ control = ControlLLLiteAdvanced(patch_attn1=patch_attn1, patch_attn2=patch_attn2, timestep_keyframes=timestep_keyframe)
789
+ return control
790
+
791
+
792
+ def load_svdcontrolnet(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
793
+ if controlnet_data is None:
794
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
795
+
796
+ controlnet_config = None
797
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
798
+ unet_dtype = comfy.model_management.unet_dtype()
799
+ controlnet_config = svd_unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
800
+ diffusers_keys = svd_unet_to_diffusers(controlnet_config)
801
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
802
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
803
+
804
+ count = 0
805
+ loop = True
806
+ while loop:
807
+ suffix = [".weight", ".bias"]
808
+ for s in suffix:
809
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
810
+ k_out = "zero_convs.{}.0{}".format(count, s)
811
+ if k_in not in controlnet_data:
812
+ loop = False
813
+ break
814
+ diffusers_keys[k_in] = k_out
815
+ count += 1
816
+
817
+ count = 0
818
+ loop = True
819
+ while loop:
820
+ suffix = [".weight", ".bias"]
821
+ for s in suffix:
822
+ if count == 0:
823
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
824
+ else:
825
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
826
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
827
+ if k_in not in controlnet_data:
828
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
829
+ loop = False
830
+ diffusers_keys[k_in] = k_out
831
+ count += 1
832
+
833
+ new_sd = {}
834
+ for k in diffusers_keys:
835
+ if k in controlnet_data:
836
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
837
+
838
+ leftover_keys = controlnet_data.keys()
839
+ if len(leftover_keys) > 0:
840
+ spatial_leftover_keys = []
841
+ temporal_leftover_keys = []
842
+ other_leftover_keys = []
843
+ for key in leftover_keys:
844
+ if "spatial" in key:
845
+ spatial_leftover_keys.append(key)
846
+ elif "temporal" in key:
847
+ temporal_leftover_keys.append(key)
848
+ else:
849
+ other_leftover_keys.append(key)
850
+ logger.warn(f"spatial_leftover_keys ({len(spatial_leftover_keys)}): {spatial_leftover_keys}")
851
+ logger.warn(f"temporal_leftover_keys ({len(temporal_leftover_keys)}): {temporal_leftover_keys}")
852
+ logger.warn(f"other_leftover_keys ({len(other_leftover_keys)}): {other_leftover_keys}")
853
+ #print("leftover keys:", leftover_keys)
854
+ controlnet_data = new_sd
855
+
856
+ pth_key = 'control_model.zero_convs.0.0.weight'
857
+ pth = False
858
+ key = 'zero_convs.0.0.weight'
859
+ if pth_key in controlnet_data:
860
+ pth = True
861
+ key = pth_key
862
+ prefix = "control_model."
863
+ elif key in controlnet_data:
864
+ prefix = ""
865
+ else:
866
+ raise ValueError("The provided model is not a valid SVD-ControlNet model! [ErrorCode: MUSTARD]")
867
+
868
+ if controlnet_config is None:
869
+ unet_dtype = comfy.model_management.unet_dtype()
870
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
871
+ load_device = comfy.model_management.get_torch_device()
872
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
873
+ if manual_cast_dtype is not None:
874
+ controlnet_config["operations"] = comfy.ops.manual_cast
875
+ controlnet_config.pop("out_channels")
876
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
877
+ control_model = SVDControlNet(**controlnet_config)
878
+
879
+ if pth:
880
+ if 'difference' in controlnet_data:
881
+ if model is not None:
882
+ comfy.model_management.load_models_gpu([model])
883
+ model_sd = model.model_state_dict()
884
+ for x in controlnet_data:
885
+ c_m = "control_model."
886
+ if x.startswith(c_m):
887
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
888
+ if sd_key in model_sd:
889
+ cd = controlnet_data[x]
890
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
891
+ else:
892
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
893
+
894
+ class WeightsLoader(torch.nn.Module):
895
+ pass
896
+ w = WeightsLoader()
897
+ w.control_model = control_model
898
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
899
+ else:
900
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
901
+ if len(missing) > 0 or len(unexpected) > 0:
902
+ logger.info(f"SVD-ControlNet: {missing}, {unexpected}")
903
+
904
+ global_average_pooling = False
905
+ filename = os.path.splitext(ckpt_path)[0]
906
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
907
+ global_average_pooling = True
908
+
909
+ control = SVDControlNetAdvanced(control_model, timestep_keyframes=timestep_keyframe, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
910
+ return control
911
+
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adapted from https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
2
+ # basically, all the LLLite core code is from there, which I then combined with
3
+ # Advanced-ControlNet features and QoL
4
+ import math
5
+ from typing import Union
6
+ from torch import Tensor
7
+ import torch
8
+ import os
9
+
10
+ import comfy.utils
11
+ from comfy.controlnet import ControlBase
12
+
13
+ from .logger import logger
14
+ from .utils import AdvancedControlBase, deepcopy_with_sharing, prepare_mask_batch
15
+
16
+
17
+ def extra_options_to_module_prefix(extra_options):
18
+ # extra_options = {'transformer_index': 2, 'block_index': 8, 'original_shape': [2, 4, 128, 128], 'block': ('input', 7), 'n_heads': 20, 'dim_head': 64}
19
+
20
+ # block is: [('input', 4), ('input', 5), ('input', 7), ('input', 8), ('middle', 0),
21
+ # ('output', 0), ('output', 1), ('output', 2), ('output', 3), ('output', 4), ('output', 5)]
22
+ # transformer_index is: [0, 1, 2, 3, 4, 5, 6, 7, 8], for each block
23
+ # block_index is: 0-1 or 0-9, depends on the block
24
+ # input 7 and 8, middle has 10 blocks
25
+
26
+ # make module name from extra_options
27
+ block = extra_options["block"]
28
+ block_index = extra_options["block_index"]
29
+ if block[0] == "input":
30
+ module_pfx = f"lllite_unet_input_blocks_{block[1]}_1_transformer_blocks_{block_index}"
31
+ elif block[0] == "middle":
32
+ module_pfx = f"lllite_unet_middle_block_1_transformer_blocks_{block_index}"
33
+ elif block[0] == "output":
34
+ module_pfx = f"lllite_unet_output_blocks_{block[1]}_1_transformer_blocks_{block_index}"
35
+ else:
36
+ raise Exception(f"ControlLLLite: invalid block name '{block[0]}'. Expected 'input', 'middle', or 'output'.")
37
+ return module_pfx
38
+
39
+
40
+ class LLLitePatch:
41
+ ATTN1 = "attn1"
42
+ ATTN2 = "attn2"
43
+ def __init__(self, modules: dict[str, 'LLLiteModule'], patch_type: str, control: Union[AdvancedControlBase, ControlBase]=None):
44
+ self.modules = modules
45
+ self.control = control
46
+ self.patch_type = patch_type
47
+ #logger.error(f"create LLLitePatch: {id(self)},{control}")
48
+
49
+ def __call__(self, q, k, v, extra_options):
50
+ #logger.error(f"in __call__: {id(self)}")
51
+ # determine if have anything to run
52
+ if self.control.timestep_range is not None:
53
+ # it turns out comparing single-value tensors to floats is extremely slow
54
+ # a: Tensor = extra_options["sigmas"][0]
55
+ if self.control.t > self.control.timestep_range[0] or self.control.t < self.control.timestep_range[1]:
56
+ return q, k, v
57
+
58
+ module_pfx = extra_options_to_module_prefix(extra_options)
59
+
60
+ is_attn1 = q.shape[-1] == k.shape[-1] # self attention
61
+ if is_attn1:
62
+ module_pfx = module_pfx + "_attn1"
63
+ else:
64
+ module_pfx = module_pfx + "_attn2"
65
+
66
+ module_pfx_to_q = module_pfx + "_to_q"
67
+ module_pfx_to_k = module_pfx + "_to_k"
68
+ module_pfx_to_v = module_pfx + "_to_v"
69
+
70
+ if module_pfx_to_q in self.modules:
71
+ q = q + self.modules[module_pfx_to_q](q, self.control)
72
+ if module_pfx_to_k in self.modules:
73
+ k = k + self.modules[module_pfx_to_k](k, self.control)
74
+ if module_pfx_to_v in self.modules:
75
+ v = v + self.modules[module_pfx_to_v](v, self.control)
76
+
77
+ return q, k, v
78
+
79
+ def to(self, device):
80
+ #logger.info(f"to... has control? {self.control}")
81
+ for d in self.modules.keys():
82
+ self.modules[d] = self.modules[d].to(device)
83
+ return self
84
+
85
+ def set_control(self, control: Union[AdvancedControlBase, ControlBase]) -> 'LLLitePatch':
86
+ self.control = control
87
+ return self
88
+ #logger.error(f"set control for LLLitePatch: {id(self)}, cn: {id(control)}")
89
+
90
+ def clone_with_control(self, control: AdvancedControlBase):
91
+ #logger.error(f"clone-set control for LLLitePatch: {id(self)},{id(control)}")
92
+ return LLLitePatch(self.modules, self.patch_type, control)
93
+
94
+ def cleanup(self):
95
+ #total_cleaned = 0
96
+ for module in self.modules.values():
97
+ module.cleanup()
98
+ # total_cleaned += 1
99
+ #logger.info(f"cleaned modules: {total_cleaned}, {id(self)}")
100
+ #logger.error(f"cleanup LLLitePatch: {id(self)}")
101
+
102
+ # make sure deepcopy does not copy control, and deepcopied LLLitePatch should be assigned to control
103
+ def __deepcopy__(self, memo):
104
+ self.cleanup()
105
+ to_return: LLLitePatch = deepcopy_with_sharing(self, shared_attribute_names = ['control'], memo=memo)
106
+ #logger.warn(f"patch {id(self)} turned into {id(to_return)}")
107
+ try:
108
+ if self.patch_type == self.ATTN1:
109
+ to_return.control.patch_attn1 = to_return
110
+ elif self.patch_type == self.ATTN2:
111
+ to_return.control.patch_attn2 = to_return
112
+ except Exception:
113
+ pass
114
+ return to_return
115
+
116
+
117
+ # TODO: use comfy.ops to support fp8 properly
118
+ class LLLiteModule(torch.nn.Module):
119
+ def __init__(
120
+ self,
121
+ name: str,
122
+ is_conv2d: bool,
123
+ in_dim: int,
124
+ depth: int,
125
+ cond_emb_dim: int,
126
+ mlp_dim: int,
127
+ ):
128
+ super().__init__()
129
+ self.name = name
130
+ self.is_conv2d = is_conv2d
131
+ self.is_first = False
132
+
133
+ modules = []
134
+ modules.append(torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size*2
135
+ if depth == 1:
136
+ modules.append(torch.nn.ReLU(inplace=True))
137
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
138
+ elif depth == 2:
139
+ modules.append(torch.nn.ReLU(inplace=True))
140
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
141
+ elif depth == 3:
142
+ # kernel size 8 is too large, so set it to 4
143
+ modules.append(torch.nn.ReLU(inplace=True))
144
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
145
+ modules.append(torch.nn.ReLU(inplace=True))
146
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
147
+
148
+ self.conditioning1 = torch.nn.Sequential(*modules)
149
+
150
+ if self.is_conv2d:
151
+ self.down = torch.nn.Sequential(
152
+ torch.nn.Conv2d(in_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
153
+ torch.nn.ReLU(inplace=True),
154
+ )
155
+ self.mid = torch.nn.Sequential(
156
+ torch.nn.Conv2d(mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
157
+ torch.nn.ReLU(inplace=True),
158
+ )
159
+ self.up = torch.nn.Sequential(
160
+ torch.nn.Conv2d(mlp_dim, in_dim, kernel_size=1, stride=1, padding=0),
161
+ )
162
+ else:
163
+ self.down = torch.nn.Sequential(
164
+ torch.nn.Linear(in_dim, mlp_dim),
165
+ torch.nn.ReLU(inplace=True),
166
+ )
167
+ self.mid = torch.nn.Sequential(
168
+ torch.nn.Linear(mlp_dim + cond_emb_dim, mlp_dim),
169
+ torch.nn.ReLU(inplace=True),
170
+ )
171
+ self.up = torch.nn.Sequential(
172
+ torch.nn.Linear(mlp_dim, in_dim),
173
+ )
174
+
175
+ self.depth = depth
176
+ self.cond_emb = None
177
+ self.cx_shape = None
178
+ self.prev_batch = 0
179
+ self.prev_sub_idxs = None
180
+
181
+ def cleanup(self):
182
+ del self.cond_emb
183
+ self.cond_emb = None
184
+ self.cx_shape = None
185
+ self.prev_batch = 0
186
+ self.prev_sub_idxs = None
187
+
188
+ def forward(self, x: Tensor, control: Union[AdvancedControlBase, ControlBase]):
189
+ mask = None
190
+ mask_tk = None
191
+ #logger.info(x.shape)
192
+ if self.cond_emb is None or control.sub_idxs != self.prev_sub_idxs or x.shape[0] != self.prev_batch:
193
+ # print(f"cond_emb is None, {self.name}")
194
+ cond_hint = control.cond_hint.to(x.device, dtype=x.dtype)
195
+ if control.latent_dims_div2 is not None and x.shape[-1] != 1280:
196
+ cond_hint = comfy.utils.common_upscale(cond_hint, control.latent_dims_div2[0] * 8, control.latent_dims_div2[1] * 8, 'nearest-exact', "center").to(x.device, dtype=x.dtype)
197
+ elif control.latent_dims_div4 is not None and x.shape[-1] == 1280:
198
+ cond_hint = comfy.utils.common_upscale(cond_hint, control.latent_dims_div4[0] * 8, control.latent_dims_div4[1] * 8, 'nearest-exact', "center").to(x.device, dtype=x.dtype)
199
+ cx = self.conditioning1(cond_hint)
200
+ self.cx_shape = cx.shape
201
+ if not self.is_conv2d:
202
+ # reshape / b,c,h,w -> b,h*w,c
203
+ n, c, h, w = cx.shape
204
+ cx = cx.view(n, c, h * w).permute(0, 2, 1)
205
+ self.cond_emb = cx
206
+ # save prev values
207
+ self.prev_batch = x.shape[0]
208
+ self.prev_sub_idxs = control.sub_idxs
209
+
210
+ cx: torch.Tensor = self.cond_emb
211
+ # print(f"forward {self.name}, {cx.shape}, {x.shape}")
212
+
213
+ # TODO: make masks work for conv2d (could not find any ControlLLLites at this time that use them)
214
+ # create masks
215
+ if not self.is_conv2d:
216
+ n, c, h, w = self.cx_shape
217
+ if control.mask_cond_hint is not None:
218
+ mask = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
219
+ mask = mask.view(mask.shape[0], 1, h * w).permute(0, 2, 1)
220
+ if control.tk_mask_cond_hint is not None:
221
+ mask_tk = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
222
+ mask_tk = mask_tk.view(mask_tk.shape[0], 1, h * w).permute(0, 2, 1)
223
+
224
+ # x in uncond/cond doubles batch size
225
+ if x.shape[0] != cx.shape[0]:
226
+ if self.is_conv2d:
227
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1, 1)
228
+ else:
229
+ # print("x.shape[0] != cx.shape[0]", x.shape[0], cx.shape[0])
230
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1)
231
+ if mask is not None:
232
+ mask = mask.repeat(x.shape[0] // mask.shape[0], 1, 1)
233
+ if mask_tk is not None:
234
+ mask_tk = mask_tk.repeat(x.shape[0] // mask_tk.shape[0], 1, 1)
235
+
236
+ if mask is None:
237
+ mask = 1.0
238
+ elif mask_tk is not None:
239
+ mask = mask * mask_tk
240
+
241
+ #logger.info(f"cs: {cx.shape}, x: {x.shape}, is_conv2d: {self.is_conv2d}")
242
+ cx = torch.cat([cx, self.down(x)], dim=1 if self.is_conv2d else 2)
243
+ cx = self.mid(cx)
244
+ cx = self.up(cx)
245
+ if control.latent_keyframes is not None:
246
+ cx = cx * control.calc_latent_keyframe_mults(x=cx, batched_number=control.batched_number)
247
+ if control.weights is not None and control.weights.has_uncond_multiplier:
248
+ cond_or_uncond = control.batched_number.cond_or_uncond
249
+ actual_length = cx.size(0) // control.batched_number
250
+ for idx, cond_type in enumerate(cond_or_uncond):
251
+ # if uncond, set to weight's uncond_multiplier
252
+ if cond_type == 1:
253
+ cx[actual_length*idx:actual_length*(idx+1)] *= control.weights.uncond_multiplier
254
+ return cx * mask * control.strength * control._current_timestep_keyframe.strength
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_reference.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+
3
+ import math
4
+ import torch
5
+ from torch import Tensor
6
+
7
+ import comfy.sample
8
+ import comfy.model_patcher
9
+ import comfy.utils
10
+ from comfy.controlnet import ControlBase
11
+ from comfy.model_patcher import ModelPatcher
12
+ from comfy.ldm.modules.attention import BasicTransformerBlock
13
+ from comfy.ldm.modules.diffusionmodules import openaimodel
14
+
15
+ from .logger import logger
16
+ from .utils import (AdvancedControlBase, ControlWeights, TimestepKeyframeGroup, AbstractPreprocWrapper,
17
+ deepcopy_with_sharing, prepare_mask_batch, broadcast_image_to_extend)
18
+
19
+
20
+ def refcn_sample_factory(orig_comfy_sample: Callable, is_custom=False) -> Callable:
21
+ def get_refcn(control: ControlBase, order: int=-1):
22
+ ref_set: set[ReferenceAdvanced] = set()
23
+ if control is None:
24
+ return ref_set
25
+ if type(control) == ReferenceAdvanced:
26
+ control.order = order
27
+ order -= 1
28
+ ref_set.add(control)
29
+ ref_set.update(get_refcn(control.previous_controlnet, order=order))
30
+ return ref_set
31
+
32
+ def refcn_sample(model: ModelPatcher, *args, **kwargs):
33
+ # check if positive or negative conds contain ref cn
34
+ positive = args[-3]
35
+ negative = args[-2]
36
+ ref_set = set()
37
+ if positive is not None:
38
+ for cond in positive:
39
+ if "control" in cond[1]:
40
+ ref_set.update(get_refcn(cond[1]["control"]))
41
+ if negative is not None:
42
+ for cond in negative:
43
+ if "control" in cond[1]:
44
+ ref_set.update(get_refcn(cond[1]["control"]))
45
+ # if no ref cn found, do original function immediately
46
+ if len(ref_set) == 0:
47
+ return orig_comfy_sample(model, *args, **kwargs)
48
+ # otherwise, injection time
49
+ try:
50
+ # inject
51
+ # storage for all Reference-related injections
52
+ reference_injections = ReferenceInjections()
53
+
54
+ # first, handle attn module injection
55
+ all_modules = torch_dfs(model.model)
56
+ attn_modules: list[RefBasicTransformerBlock] = []
57
+ for module in all_modules:
58
+ if isinstance(module, BasicTransformerBlock):
59
+ attn_modules.append(module)
60
+ attn_modules = [module for module in all_modules if isinstance(module, BasicTransformerBlock)]
61
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
62
+ for i, module in enumerate(attn_modules):
63
+ injection_holder = InjectionBasicTransformerBlockHolder(block=module, idx=i)
64
+ injection_holder.attn_weight = float(i) / float(len(attn_modules))
65
+ if hasattr(module, "_forward"): # backward compatibility
66
+ module._forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
67
+ else:
68
+ module.forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
69
+ module.injection_holder = injection_holder
70
+ reference_injections.attn_modules.append(module)
71
+ # figure out which module is middle block
72
+ if hasattr(model.model.diffusion_model, "middle_block"):
73
+ mid_modules = torch_dfs(model.model.diffusion_model.middle_block)
74
+ mid_attn_modules: list[RefBasicTransformerBlock] = [module for module in mid_modules if isinstance(module, BasicTransformerBlock)]
75
+ for module in mid_attn_modules:
76
+ module.injection_holder.is_middle = True
77
+
78
+ # next, handle gn module injection (TimestepEmbedSequential)
79
+ # TODO: figure out the logic behind these hardcoded indexes
80
+ if type(model.model).__name__ == "SDXL":
81
+ input_block_indices = [4, 5, 7, 8]
82
+ output_block_indices = [0, 1, 2, 3, 4, 5]
83
+ else:
84
+ input_block_indices = [4, 5, 7, 8, 10, 11]
85
+ output_block_indices = [0, 1, 2, 3, 4, 5, 6, 7]
86
+ if hasattr(model.model.diffusion_model, "middle_block"):
87
+ module = model.model.diffusion_model.middle_block
88
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=0, is_middle=True)
89
+ injection_holder.gn_weight = 0.0
90
+ module.injection_holder = injection_holder
91
+ reference_injections.gn_modules.append(module)
92
+ for w, i in enumerate(input_block_indices):
93
+ module = model.model.diffusion_model.input_blocks[i]
94
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_input=True)
95
+ injection_holder.gn_weight = 1.0 - float(w) / float(len(input_block_indices))
96
+ module.injection_holder = injection_holder
97
+ reference_injections.gn_modules.append(module)
98
+ for w, i in enumerate(output_block_indices):
99
+ module = model.model.diffusion_model.output_blocks[i]
100
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_output=True)
101
+ injection_holder.gn_weight = float(w) / float(len(output_block_indices))
102
+ module.injection_holder = injection_holder
103
+ reference_injections.gn_modules.append(module)
104
+ # hack gn_module forwards and update weights
105
+ for i, module in enumerate(reference_injections.gn_modules):
106
+ module.injection_holder.gn_weight *= 2
107
+
108
+ # handle diffusion_model forward injection
109
+ reference_injections.diffusion_model_orig_forward = model.model.diffusion_model.forward
110
+ model.model.diffusion_model.forward = factory_forward_inject_UNetModel(reference_injections).__get__(model.model.diffusion_model, type(model.model.diffusion_model))
111
+ # store ordered ref cns in model's transformer options
112
+ orig_model_options = model.model_options
113
+ new_model_options = model.model_options.copy()
114
+ new_model_options["transformer_options"] = model.model_options["transformer_options"].copy()
115
+ ref_list: list[ReferenceAdvanced] = list(ref_set)
116
+ new_model_options["transformer_options"][REF_CONTROL_LIST_ALL] = sorted(ref_list, key=lambda x: x.order)
117
+ model.model_options = new_model_options
118
+ # continue with original function
119
+ return orig_comfy_sample(model, *args, **kwargs)
120
+ finally:
121
+ # cleanup injections
122
+ # restore attn modules
123
+ attn_modules: list[RefBasicTransformerBlock] = reference_injections.attn_modules
124
+ for module in attn_modules:
125
+ module.injection_holder.restore(module)
126
+ module.injection_holder.clean()
127
+ del module.injection_holder
128
+ del attn_modules
129
+ # restore gn modules
130
+ gn_modules: list[RefTimestepEmbedSequential] = reference_injections.gn_modules
131
+ for module in gn_modules:
132
+ module.injection_holder.restore(module)
133
+ module.injection_holder.clean()
134
+ del module.injection_holder
135
+ del gn_modules
136
+ # restore diffusion_model forward function
137
+ model.model.diffusion_model.forward = reference_injections.diffusion_model_orig_forward.__get__(model.model.diffusion_model, type(model.model.diffusion_model))
138
+ # restore model_options
139
+ model.model_options = orig_model_options
140
+ # cleanup
141
+ reference_injections.cleanup()
142
+ return refcn_sample
143
+ # inject sample functions
144
+ comfy.sample.sample = refcn_sample_factory(comfy.sample.sample)
145
+ comfy.sample.sample_custom = refcn_sample_factory(comfy.sample.sample_custom, is_custom=True)
146
+
147
+
148
+ REF_ATTN_CONTROL_LIST = "ref_attn_control_list"
149
+ REF_ADAIN_CONTROL_LIST = "ref_adain_control_list"
150
+ REF_CONTROL_LIST_ALL = "ref_control_list_all"
151
+ REF_CONTROL_INFO = "ref_control_info"
152
+ REF_ATTN_MACHINE_STATE = "ref_attn_machine_state"
153
+ REF_ADAIN_MACHINE_STATE = "ref_adain_machine_state"
154
+ REF_COND_IDXS = "ref_cond_idxs"
155
+ REF_UNCOND_IDXS = "ref_uncond_idxs"
156
+
157
+
158
+ class MachineState:
159
+ WRITE = "write"
160
+ READ = "read"
161
+ STYLEALIGN = "stylealign"
162
+ OFF = "off"
163
+
164
+
165
+ class ReferenceType:
166
+ ATTN = "reference_attn"
167
+ ADAIN = "reference_adain"
168
+ ATTN_ADAIN = "reference_attn+adain"
169
+ STYLE_ALIGN = "StyleAlign"
170
+
171
+ _LIST = [ATTN, ADAIN, ATTN_ADAIN]
172
+ _LIST_ATTN = [ATTN, ATTN_ADAIN]
173
+ _LIST_ADAIN = [ADAIN, ATTN_ADAIN]
174
+
175
+ @classmethod
176
+ def is_attn(cls, ref_type: str):
177
+ return ref_type in cls._LIST_ATTN
178
+
179
+ @classmethod
180
+ def is_adain(cls, ref_type: str):
181
+ return ref_type in cls._LIST_ADAIN
182
+
183
+
184
+ class ReferenceOptions:
185
+ def __init__(self, reference_type: str,
186
+ attn_style_fidelity: float, adain_style_fidelity: float,
187
+ attn_ref_weight: float, adain_ref_weight: float,
188
+ attn_strength: float=1.0, adain_strength: float=1.0,
189
+ ref_with_other_cns: bool=False):
190
+ self.reference_type = reference_type
191
+ # attn
192
+ self.original_attn_style_fidelity = attn_style_fidelity
193
+ self.attn_style_fidelity = attn_style_fidelity
194
+ self.attn_ref_weight = attn_ref_weight
195
+ self.attn_strength = attn_strength
196
+ # adain
197
+ self.original_adain_style_fidelity = adain_style_fidelity
198
+ self.adain_style_fidelity = adain_style_fidelity
199
+ self.adain_ref_weight = adain_ref_weight
200
+ self.adain_strength = adain_strength
201
+ # other
202
+ self.ref_with_other_cns = ref_with_other_cns
203
+
204
+ def clone(self):
205
+ return ReferenceOptions(reference_type=self.reference_type,
206
+ attn_style_fidelity=self.original_attn_style_fidelity, adain_style_fidelity=self.original_adain_style_fidelity,
207
+ attn_ref_weight=self.attn_ref_weight, adain_ref_weight=self.adain_ref_weight,
208
+ attn_strength=self.attn_strength, adain_strength=self.adain_strength,
209
+ ref_with_other_cns=self.ref_with_other_cns)
210
+
211
+ @staticmethod
212
+ def create_combo(reference_type: str, style_fidelity: float, ref_weight: float, ref_with_other_cns: bool=False):
213
+ return ReferenceOptions(reference_type=reference_type,
214
+ attn_style_fidelity=style_fidelity, adain_style_fidelity=style_fidelity,
215
+ attn_ref_weight=ref_weight, adain_ref_weight=ref_weight,
216
+ ref_with_other_cns=ref_with_other_cns)
217
+
218
+
219
+
220
+ class ReferencePreprocWrapper(AbstractPreprocWrapper):
221
+ error_msg = error_msg = "Invalid use of Reference Preprocess output. The output of Reference preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply Advanced ControlNet node. It cannot be used for anything else that accepts IMAGE input."
222
+ def __init__(self, condhint: Tensor):
223
+ super().__init__(condhint)
224
+
225
+
226
+ class ReferenceAdvanced(ControlBase, AdvancedControlBase):
227
+ CHANNEL_TO_MULT = {320: 1, 640: 2, 1280: 4}
228
+
229
+ def __init__(self, ref_opts: ReferenceOptions, timestep_keyframes: TimestepKeyframeGroup, device=None):
230
+ super().__init__(device)
231
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite(), allow_condhint_latents=True)
232
+ # TODO: allow vae_optional to be used instead of preprocessor
233
+ #require_vae=True
234
+ self.ref_opts = ref_opts
235
+ self.order = 0
236
+ self.model_latent_format = None
237
+ self.model_sampling_current = None
238
+ self.should_apply_attn_effective_strength = False
239
+ self.should_apply_adain_effective_strength = False
240
+ self.should_apply_effective_masks = False
241
+ self.latent_shape = None
242
+
243
+ def any_attn_strength_to_apply(self):
244
+ return self.should_apply_attn_effective_strength or self.should_apply_effective_masks
245
+
246
+ def any_adain_strength_to_apply(self):
247
+ return self.should_apply_adain_effective_strength or self.should_apply_effective_masks
248
+
249
+ def get_effective_strength(self):
250
+ effective_strength = self.strength
251
+ if self._current_timestep_keyframe is not None:
252
+ effective_strength = effective_strength * self._current_timestep_keyframe.strength
253
+ return effective_strength
254
+
255
+ def get_effective_attn_mask_or_float(self, x: Tensor, channels: int, is_mid: bool):
256
+ if not self.should_apply_effective_masks:
257
+ return self.get_effective_strength() * self.ref_opts.attn_strength
258
+ if is_mid:
259
+ div = 8
260
+ else:
261
+ div = self.CHANNEL_TO_MULT[channels]
262
+ real_mask = torch.ones([self.latent_shape[0], 1, self.latent_shape[2]//div, self.latent_shape[3]//div]).to(dtype=x.dtype, device=x.device) * self.strength * self.ref_opts.attn_strength
263
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
264
+ # mask is now shape [b, 1, h ,w]; need to turn into [b, h*w, 1]
265
+ b, c, h, w = real_mask.shape
266
+ real_mask = real_mask.permute(0, 2, 3, 1).reshape(b, h*w, c)
267
+ return real_mask
268
+
269
+ def get_effective_adain_mask_or_float(self, x: Tensor):
270
+ if not self.should_apply_effective_masks:
271
+ return self.get_effective_strength() * self.ref_opts.adain_strength
272
+ b, c, h, w = x.shape
273
+ real_mask = torch.ones([b, 1, h, w]).to(dtype=x.dtype, device=x.device) * self.strength * self.ref_opts.adain_strength
274
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
275
+ return real_mask
276
+
277
+ def should_run(self):
278
+ running = super().should_run()
279
+ if not running:
280
+ return running
281
+ attn_run = False
282
+ adain_run = False
283
+ if ReferenceType.is_attn(self.ref_opts.reference_type):
284
+ # attn will run as long as neither weight or strength is zero
285
+ attn_run = not (math.isclose(self.ref_opts.attn_ref_weight, 0.0) or math.isclose(self.ref_opts.attn_strength, 0.0))
286
+ if ReferenceType.is_adain(self.ref_opts.reference_type):
287
+ # adain will run as long as neither weight or strength is zero
288
+ adain_run = not (math.isclose(self.ref_opts.adain_ref_weight, 0.0) or math.isclose(self.ref_opts.adain_strength, 0.0))
289
+ return attn_run or adain_run
290
+
291
+ def pre_run_advanced(self, model, percent_to_timestep_function):
292
+ AdvancedControlBase.pre_run_advanced(self, model, percent_to_timestep_function)
293
+ if isinstance(self.cond_hint_original, AbstractPreprocWrapper):
294
+ self.cond_hint_original = self.cond_hint_original.condhint
295
+ self.model_latent_format = model.latent_format # LatentFormat object, used to process_in latent cond_hint
296
+ self.model_sampling_current = model.model_sampling
297
+ # SDXL is more sensitive to style_fidelity according to sd-webui-controlnet comments
298
+ if type(model).__name__ == "SDXL":
299
+ self.ref_opts.attn_style_fidelity = self.ref_opts.original_attn_style_fidelity ** 3.0
300
+ self.ref_opts.adain_style_fidelity = self.ref_opts.original_adain_style_fidelity ** 3.0
301
+ else:
302
+ self.ref_opts.attn_style_fidelity = self.ref_opts.original_attn_style_fidelity
303
+ self.ref_opts.adain_style_fidelity = self.ref_opts.original_adain_style_fidelity
304
+
305
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
306
+ # normal ControlNet stuff
307
+ control_prev = None
308
+ if self.previous_controlnet is not None:
309
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
310
+
311
+ if self.timestep_range is not None:
312
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
313
+ return control_prev
314
+
315
+ dtype = x_noisy.dtype
316
+ # prepare cond_hint - it is a latent, NOT an image
317
+ #if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] != self.cond_hint.shape[2] or x_noisy.shape[3] != self.cond_hint.shape[3]:
318
+ if self.cond_hint is not None:
319
+ del self.cond_hint
320
+ self.cond_hint = None
321
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
322
+ if self.sub_idxs is not None and self.cond_hint_original.size(0) >= self.full_latent_length:
323
+ self.cond_hint = comfy.utils.common_upscale(
324
+ self.cond_hint_original[self.sub_idxs],
325
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(self.device)
326
+ else:
327
+ self.cond_hint = comfy.utils.common_upscale(
328
+ self.cond_hint_original,
329
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(self.device)
330
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
331
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number, except_one=False)
332
+ # noise cond_hint based on sigma (current step)
333
+ self.cond_hint = self.model_latent_format.process_in(self.cond_hint)
334
+ self.cond_hint = ref_noise_latents(self.cond_hint, sigma=t, noise=None)
335
+ timestep = self.model_sampling_current.timestep(t)
336
+ self.should_apply_attn_effective_strength = not (math.isclose(self.strength, 1.0) and math.isclose(self._current_timestep_keyframe.strength, 1.0) and math.isclose(self.ref_opts.attn_strength, 1.0))
337
+ self.should_apply_adain_effective_strength = not (math.isclose(self.strength, 1.0) and math.isclose(self._current_timestep_keyframe.strength, 1.0) and math.isclose(self.ref_opts.adain_strength, 1.0))
338
+ # prepare mask - use direct_attn, so the mask dims will match source latents (and be smaller)
339
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, direct_attn=True)
340
+ self.should_apply_effective_masks = self.latent_keyframes is not None or self.mask_cond_hint is not None or self.tk_mask_cond_hint is not None
341
+ self.latent_shape = list(x_noisy.shape)
342
+ # done preparing; model patches will take care of everything now.
343
+ # return normal controlnet stuff
344
+ return control_prev
345
+
346
+ def cleanup_advanced(self):
347
+ super().cleanup_advanced()
348
+ del self.model_latent_format
349
+ self.model_latent_format = None
350
+ del self.model_sampling_current
351
+ self.model_sampling_current = None
352
+ self.should_apply_attn_effective_strength = False
353
+ self.should_apply_adain_effective_strength = False
354
+ self.should_apply_effective_masks = False
355
+
356
+ def copy(self):
357
+ c = ReferenceAdvanced(self.ref_opts, self.timestep_keyframes)
358
+ c.order = self.order
359
+ self.copy_to(c)
360
+ self.copy_to_advanced(c)
361
+ return c
362
+
363
+ # avoid deepcopy shenanigans by making deepcopy not do anything to the reference
364
+ # TODO: do the bookkeeping to do this in a proper way for all Adv-ControlNets
365
+ def __deepcopy__(self, memo):
366
+ return self
367
+
368
+
369
+ def ref_noise_latents(latents: Tensor, sigma: Tensor, noise: Tensor=None):
370
+ sigma = sigma.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
371
+ alpha_cumprod = 1 / ((sigma * sigma) + 1)
372
+ sqrt_alpha_prod = alpha_cumprod ** 0.5
373
+ sqrt_one_minus_alpha_prod = (1. - alpha_cumprod) ** 0.5
374
+ if noise is None:
375
+ # generator = torch.Generator(device="cuda")
376
+ # generator.manual_seed(0)
377
+ # noise = torch.empty_like(latents).normal_(generator=generator)
378
+ # generator = torch.Generator()
379
+ # generator.manual_seed(0)
380
+ # noise = torch.randn(latents.size(), generator=generator).to(latents.device)
381
+ noise = torch.randn_like(latents).to(latents.device)
382
+ return sqrt_alpha_prod * latents + sqrt_one_minus_alpha_prod * noise
383
+
384
+
385
+ def simple_noise_latents(latents: Tensor, sigma: float, noise: Tensor=None):
386
+ if noise is None:
387
+ noise = torch.rand_like(latents)
388
+ return latents + noise * sigma
389
+
390
+
391
+ class BankStylesBasicTransformerBlock:
392
+ def __init__(self):
393
+ self.bank = []
394
+ self.style_cfgs = []
395
+ self.cn_idx: list[int] = []
396
+
397
+ def get_avg_style_fidelity(self):
398
+ return sum(self.style_cfgs) / float(len(self.style_cfgs))
399
+
400
+ def clean(self):
401
+ del self.bank
402
+ self.bank = []
403
+ del self.style_cfgs
404
+ self.style_cfgs = []
405
+ del self.cn_idx
406
+ self.cn_idx = []
407
+
408
+
409
+ class BankStylesTimestepEmbedSequential:
410
+ def __init__(self):
411
+ self.var_bank = []
412
+ self.mean_bank = []
413
+ self.style_cfgs = []
414
+ self.cn_idx: list[int] = []
415
+
416
+ def get_avg_var_bank(self):
417
+ return sum(self.var_bank) / float(len(self.var_bank))
418
+
419
+ def get_avg_mean_bank(self):
420
+ return sum(self.mean_bank) / float(len(self.mean_bank))
421
+
422
+ def get_avg_style_fidelity(self):
423
+ return sum(self.style_cfgs) / float(len(self.style_cfgs))
424
+
425
+ def clean(self):
426
+ del self.mean_bank
427
+ self.mean_bank = []
428
+ del self.var_bank
429
+ self.var_bank = []
430
+ del self.style_cfgs
431
+ self.style_cfgs = []
432
+ del self.cn_idx
433
+ self.cn_idx = []
434
+
435
+
436
+ class InjectionBasicTransformerBlockHolder:
437
+ def __init__(self, block: BasicTransformerBlock, idx=None):
438
+ if hasattr(block, "_forward"): # backward compatibility
439
+ self.original_forward = block._forward
440
+ else:
441
+ self.original_forward = block.forward
442
+ self.idx = idx
443
+ self.attn_weight = 1.0
444
+ self.is_middle = False
445
+ self.bank_styles = BankStylesBasicTransformerBlock()
446
+
447
+ def restore(self, block: BasicTransformerBlock):
448
+ if hasattr(block, "_forward"): # backward compatibility
449
+ block._forward = self.original_forward
450
+ else:
451
+ block.forward = self.original_forward
452
+
453
+ def clean(self):
454
+ self.bank_styles.clean()
455
+
456
+
457
+ class InjectionTimestepEmbedSequentialHolder:
458
+ def __init__(self, block: openaimodel.TimestepEmbedSequential, idx=None, is_middle=False, is_input=False, is_output=False):
459
+ self.original_forward = block.forward
460
+ self.idx = idx
461
+ self.gn_weight = 1.0
462
+ self.is_middle = is_middle
463
+ self.is_input = is_input
464
+ self.is_output = is_output
465
+ self.bank_styles = BankStylesTimestepEmbedSequential()
466
+
467
+ def restore(self, block: openaimodel.TimestepEmbedSequential):
468
+ block.forward = self.original_forward
469
+
470
+ def clean(self):
471
+ self.bank_styles.clean()
472
+
473
+
474
+ class ReferenceInjections:
475
+ def __init__(self, attn_modules: list['RefBasicTransformerBlock']=None, gn_modules: list['RefTimestepEmbedSequential']=None):
476
+ self.attn_modules = attn_modules if attn_modules else []
477
+ self.gn_modules = gn_modules if gn_modules else []
478
+ self.diffusion_model_orig_forward: Callable = None
479
+
480
+ def clean_module_mem(self):
481
+ for attn_module in self.attn_modules:
482
+ try:
483
+ attn_module.injection_holder.clean()
484
+ except Exception:
485
+ pass
486
+ for gn_module in self.gn_modules:
487
+ try:
488
+ gn_module.injection_holder.clean()
489
+ except Exception:
490
+ pass
491
+
492
+ def cleanup(self):
493
+ self.clean_module_mem()
494
+ del self.attn_modules
495
+ self.attn_modules = []
496
+ del self.gn_modules
497
+ self.gn_modules = []
498
+ self.diffusion_model_orig_forward = None
499
+
500
+
501
+ def factory_forward_inject_UNetModel(reference_injections: ReferenceInjections):
502
+ def forward_inject_UNetModel(self, x: Tensor, *args, **kwargs):
503
+ # get control and transformer_options from kwargs
504
+ real_args = list(args)
505
+ real_kwargs = list(kwargs.keys())
506
+ control = kwargs.get("control", None)
507
+ transformer_options = kwargs.get("transformer_options", None)
508
+ # look for ReferenceAttnPatch objects to get ReferenceAdvanced objects
509
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options[REF_CONTROL_LIST_ALL]
510
+ # discard any controlnets that should not run
511
+ ref_controlnets = [x for x in ref_controlnets if x.should_run()]
512
+ # if nothing related to reference controlnets, do nothing special
513
+ if len(ref_controlnets) == 0:
514
+ return reference_injections.diffusion_model_orig_forward(x, *args, **kwargs)
515
+ try:
516
+ # assign cond and uncond idxs
517
+ batched_number = len(transformer_options["cond_or_uncond"])
518
+ per_batch = x.shape[0] // batched_number
519
+ indiv_conds = []
520
+ for cond_type in transformer_options["cond_or_uncond"]:
521
+ indiv_conds.extend([cond_type] * per_batch)
522
+ transformer_options[REF_UNCOND_IDXS] = [i for i, x in enumerate(indiv_conds) if x == 1]
523
+ transformer_options[REF_COND_IDXS] = [i for i, x in enumerate(indiv_conds) if x == 0]
524
+ # check which controlnets do which thing
525
+ attn_controlnets = []
526
+ adain_controlnets = []
527
+ for control in ref_controlnets:
528
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
529
+ attn_controlnets.append(control)
530
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
531
+ adain_controlnets.append(control)
532
+ if len(adain_controlnets) > 0:
533
+ # ComfyUI uses forward_timestep_embed with the TimestepEmbedSequential passed into it
534
+ orig_forward_timestep_embed = openaimodel.forward_timestep_embed
535
+ openaimodel.forward_timestep_embed = forward_timestep_embed_ref_inject_factory(orig_forward_timestep_embed)
536
+ # handle running diffusion with ref cond hints
537
+ for control in ref_controlnets:
538
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
539
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.WRITE
540
+ else:
541
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.OFF
542
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
543
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.WRITE
544
+ else:
545
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.OFF
546
+ transformer_options[REF_ATTN_CONTROL_LIST] = [control]
547
+ transformer_options[REF_ADAIN_CONTROL_LIST] = [control]
548
+
549
+ orig_kwargs = kwargs
550
+ if not control.ref_opts.ref_with_other_cns:
551
+ kwargs = kwargs.copy()
552
+ kwargs["control"] = None
553
+ reference_injections.diffusion_model_orig_forward(control.cond_hint.to(dtype=x.dtype).to(device=x.device), *args, **kwargs)
554
+ kwargs = orig_kwargs
555
+ # run diffusion for real now
556
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.READ
557
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.READ
558
+ transformer_options[REF_ATTN_CONTROL_LIST] = attn_controlnets
559
+ transformer_options[REF_ADAIN_CONTROL_LIST] = adain_controlnets
560
+ return reference_injections.diffusion_model_orig_forward(x, *args, **kwargs)
561
+ finally:
562
+ # make sure banks are cleared no matter what happens - otherwise, RIP VRAM
563
+ reference_injections.clean_module_mem()
564
+ if len(adain_controlnets) > 0:
565
+ openaimodel.forward_timestep_embed = orig_forward_timestep_embed
566
+
567
+ return forward_inject_UNetModel
568
+
569
+
570
+ # dummy class just to help IDE keep track of injected variables
571
+ class RefBasicTransformerBlock(BasicTransformerBlock):
572
+ injection_holder: InjectionBasicTransformerBlockHolder = None
573
+
574
+ def _forward_inject_BasicTransformerBlock(self: RefBasicTransformerBlock, x: Tensor, context: Tensor=None, transformer_options: dict[str]={}):
575
+ extra_options = {}
576
+ block = transformer_options.get("block", None)
577
+ block_index = transformer_options.get("block_index", 0)
578
+ transformer_patches = {}
579
+ transformer_patches_replace = {}
580
+
581
+ for k in transformer_options:
582
+ if k == "patches":
583
+ transformer_patches = transformer_options[k]
584
+ elif k == "patches_replace":
585
+ transformer_patches_replace = transformer_options[k]
586
+ else:
587
+ extra_options[k] = transformer_options[k]
588
+
589
+ extra_options["n_heads"] = self.n_heads
590
+ extra_options["dim_head"] = self.d_head
591
+
592
+ if self.ff_in:
593
+ x_skip = x
594
+ x = self.ff_in(self.norm_in(x))
595
+ if self.is_res:
596
+ x += x_skip
597
+
598
+ n: Tensor = self.norm1(x)
599
+ if self.disable_self_attn:
600
+ context_attn1 = context
601
+ else:
602
+ context_attn1 = None
603
+ value_attn1 = None
604
+
605
+ # Reference CN stuff
606
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
607
+ c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
608
+ # WRITE mode will only have one ReferenceAdvanced, other modes will have all ReferenceAdvanced
609
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options.get(REF_ATTN_CONTROL_LIST, None)
610
+ ref_machine_state: str = transformer_options.get(REF_ATTN_MACHINE_STATE, None)
611
+ # if in WRITE mode, save n and style_fidelity
612
+ if ref_controlnets and ref_machine_state == MachineState.WRITE:
613
+ if ref_controlnets[0].ref_opts.attn_ref_weight > self.injection_holder.attn_weight:
614
+ self.injection_holder.bank_styles.bank.append(n.detach().clone())
615
+ self.injection_holder.bank_styles.style_cfgs.append(ref_controlnets[0].ref_opts.attn_style_fidelity)
616
+ self.injection_holder.bank_styles.cn_idx.append(ref_controlnets[0].order)
617
+
618
+ if "attn1_patch" in transformer_patches:
619
+ patch = transformer_patches["attn1_patch"]
620
+ if context_attn1 is None:
621
+ context_attn1 = n
622
+ value_attn1 = context_attn1
623
+ for p in patch:
624
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
625
+
626
+ if block is not None:
627
+ transformer_block = (block[0], block[1], block_index)
628
+ else:
629
+ transformer_block = None
630
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
631
+ block_attn1 = transformer_block
632
+ if block_attn1 not in attn1_replace_patch:
633
+ block_attn1 = block
634
+
635
+ if block_attn1 in attn1_replace_patch:
636
+ if context_attn1 is None:
637
+ context_attn1 = n
638
+ value_attn1 = n
639
+ n = self.attn1.to_q(n)
640
+ # Reference CN READ - use attn1_replace_patch appropriately
641
+ if ref_machine_state == MachineState.READ and len(self.injection_holder.bank_styles.bank) > 0:
642
+ bank_styles = self.injection_holder.bank_styles
643
+ style_fidelity = bank_styles.get_avg_style_fidelity()
644
+ real_bank = bank_styles.bank.copy()
645
+ cn_idx = 0
646
+ for idx, order in enumerate(bank_styles.cn_idx):
647
+ # make sure matching ref cn is selected
648
+ for i in range(cn_idx, len(ref_controlnets)):
649
+ if ref_controlnets[i].order == order:
650
+ cn_idx = i
651
+ break
652
+ assert order == ref_controlnets[cn_idx].order
653
+ if ref_controlnets[cn_idx].any_attn_strength_to_apply():
654
+ effective_strength = ref_controlnets[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
655
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
656
+ n_uc = self.attn1.to_out(attn1_replace_patch[block_attn1](
657
+ n,
658
+ self.attn1.to_k(torch.cat([context_attn1] + real_bank, dim=1)),
659
+ self.attn1.to_v(torch.cat([value_attn1] + real_bank, dim=1)),
660
+ extra_options))
661
+ n_c = n_uc.clone()
662
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
663
+ n_c[uc_idx_mask] = self.attn1.to_out(attn1_replace_patch[block_attn1](
664
+ n[uc_idx_mask],
665
+ self.attn1.to_k(context_attn1[uc_idx_mask]),
666
+ self.attn1.to_v(value_attn1[uc_idx_mask]),
667
+ extra_options))
668
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
669
+ bank_styles.clean()
670
+ else:
671
+ context_attn1 = self.attn1.to_k(context_attn1)
672
+ value_attn1 = self.attn1.to_v(value_attn1)
673
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
674
+ n = self.attn1.to_out(n)
675
+ else:
676
+ # Reference CN READ - no attn1_replace_patch
677
+ if ref_machine_state == MachineState.READ and len(self.injection_holder.bank_styles.bank) > 0:
678
+ if context_attn1 is None:
679
+ context_attn1 = n
680
+ bank_styles = self.injection_holder.bank_styles
681
+ style_fidelity = bank_styles.get_avg_style_fidelity()
682
+ real_bank = bank_styles.bank.copy()
683
+ cn_idx = 0
684
+ for idx, order in enumerate(bank_styles.cn_idx):
685
+ # make sure matching ref cn is selected
686
+ for i in range(cn_idx, len(ref_controlnets)):
687
+ if ref_controlnets[i].order == order:
688
+ cn_idx = i
689
+ break
690
+ assert order == ref_controlnets[cn_idx].order
691
+ if ref_controlnets[cn_idx].any_attn_strength_to_apply():
692
+ effective_strength = ref_controlnets[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
693
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
694
+ n_uc: Tensor = self.attn1(
695
+ n,
696
+ context=torch.cat([context_attn1] + real_bank, dim=1),
697
+ value=torch.cat([value_attn1] + real_bank, dim=1) if value_attn1 is not None else value_attn1)
698
+ n_c = n_uc.clone()
699
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
700
+ n_c[uc_idx_mask] = self.attn1(
701
+ n[uc_idx_mask],
702
+ context=context_attn1[uc_idx_mask],
703
+ value=value_attn1[uc_idx_mask] if value_attn1 is not None else value_attn1)
704
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
705
+ bank_styles.clean()
706
+ else:
707
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
708
+
709
+ if "attn1_output_patch" in transformer_patches:
710
+ patch = transformer_patches["attn1_output_patch"]
711
+ for p in patch:
712
+ n = p(n, extra_options)
713
+
714
+ x += n
715
+ if "middle_patch" in transformer_patches:
716
+ patch = transformer_patches["middle_patch"]
717
+ for p in patch:
718
+ x = p(x, extra_options)
719
+
720
+ if self.attn2 is not None:
721
+ n = self.norm2(x)
722
+ if self.switch_temporal_ca_to_sa:
723
+ context_attn2 = n
724
+ else:
725
+ context_attn2 = context
726
+ value_attn2 = None
727
+ if "attn2_patch" in transformer_patches:
728
+ patch = transformer_patches["attn2_patch"]
729
+ value_attn2 = context_attn2
730
+ for p in patch:
731
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
732
+
733
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
734
+ block_attn2 = transformer_block
735
+ if block_attn2 not in attn2_replace_patch:
736
+ block_attn2 = block
737
+
738
+ if block_attn2 in attn2_replace_patch:
739
+ if value_attn2 is None:
740
+ value_attn2 = context_attn2
741
+ n = self.attn2.to_q(n)
742
+ context_attn2 = self.attn2.to_k(context_attn2)
743
+ value_attn2 = self.attn2.to_v(value_attn2)
744
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
745
+ n = self.attn2.to_out(n)
746
+ else:
747
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
748
+
749
+ if "attn2_output_patch" in transformer_patches:
750
+ patch = transformer_patches["attn2_output_patch"]
751
+ for p in patch:
752
+ n = p(n, extra_options)
753
+
754
+ x += n
755
+ if self.is_res:
756
+ x_skip = x
757
+ x = self.ff(self.norm3(x))
758
+ if self.is_res:
759
+ x += x_skip
760
+
761
+ return x
762
+
763
+
764
+ class RefTimestepEmbedSequential(openaimodel.TimestepEmbedSequential):
765
+ injection_holder: InjectionTimestepEmbedSequentialHolder = None
766
+
767
+ def forward_timestep_embed_ref_inject_factory(orig_timestep_embed_inject_factory: Callable):
768
+ def forward_timestep_embed_ref_inject(*args, **kwargs):
769
+ ts: RefTimestepEmbedSequential = args[0]
770
+ if not hasattr(ts, "injection_holder"):
771
+ return orig_timestep_embed_inject_factory(*args, **kwargs)
772
+ eps = 1e-6
773
+ x: Tensor = orig_timestep_embed_inject_factory(*args, **kwargs)
774
+ y: Tensor = None
775
+ transformer_options: dict[str] = args[4]
776
+ # Reference CN stuff
777
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
778
+ c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
779
+ # WRITE mode will only have one ReferenceAdvanced, other modes will have all ReferenceAdvanced
780
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options.get(REF_ADAIN_CONTROL_LIST, None)
781
+ ref_machine_state: str = transformer_options.get(REF_ADAIN_MACHINE_STATE, None)
782
+
783
+ # if in WRITE mode, save var, mean, and style_cfg
784
+ if ref_machine_state == MachineState.WRITE:
785
+ if ref_controlnets[0].ref_opts.adain_ref_weight > ts.injection_holder.gn_weight:
786
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
787
+ ts.injection_holder.bank_styles.var_bank.append(var)
788
+ ts.injection_holder.bank_styles.mean_bank.append(mean)
789
+ ts.injection_holder.bank_styles.style_cfgs.append(ref_controlnets[0].ref_opts.adain_style_fidelity)
790
+ ts.injection_holder.bank_styles.cn_idx.append(ref_controlnets[0].order)
791
+ # if in READ mode, do math with saved var, mean, and style_cfg
792
+ if ref_machine_state == MachineState.READ:
793
+ if len(ts.injection_holder.bank_styles.var_bank) > 0:
794
+ bank_styles = ts.injection_holder.bank_styles
795
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
796
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
797
+ y_uc = torch.zeros_like(x)
798
+ cn_idx = 0
799
+ for idx, order in enumerate(bank_styles.cn_idx):
800
+ # make sure matching ref cn is selected
801
+ for i in range(cn_idx, len(ref_controlnets)):
802
+ if ref_controlnets[i].order == order:
803
+ cn_idx = i
804
+ break
805
+ assert order == ref_controlnets[cn_idx].order
806
+ style_fidelity = bank_styles.style_cfgs[idx]
807
+ var_acc = bank_styles.var_bank[idx]
808
+ mean_acc = bank_styles.mean_bank[idx]
809
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
810
+ sub_y_uc = (((x - mean) / std) * std_acc) + mean_acc
811
+ if ref_controlnets[cn_idx].any_adain_strength_to_apply():
812
+ effective_strength = ref_controlnets[cn_idx].get_effective_adain_mask_or_float(x=x)
813
+ sub_y_uc = sub_y_uc * effective_strength + x * (1-effective_strength)
814
+ y_uc += sub_y_uc
815
+ # get average, if more than one
816
+ if len(bank_styles.cn_idx) > 1:
817
+ y_uc /= len(bank_styles.cn_idx)
818
+ y_c = y_uc.clone()
819
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
820
+ y_c[uc_idx_mask] = x.to(y_c.dtype)[uc_idx_mask]
821
+ y = style_fidelity * y_c + (1.0 - style_fidelity) * y_uc
822
+ ts.injection_holder.bank_styles.clean()
823
+
824
+ if y is None:
825
+ y = x
826
+ return y.to(x.dtype)
827
+
828
+ return forward_timestep_embed_ref_inject
829
+
830
+ # DFS Search for Torch.nn.Module, Written by Lvmin
831
+ def torch_dfs(model: torch.nn.Module):
832
+ result = [model]
833
+ for child in model.children():
834
+ result += torch_dfs(child)
835
+ return result
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py ADDED
@@ -0,0 +1,1056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #taken from: https://github.com/lllyasviel/ControlNet
2
+ #and modified
3
+ #and then taken from comfy/cldm/cldm.py and modified again
4
+
5
+ from abc import ABC, abstractmethod
6
+ import copy
7
+ import math
8
+ import numpy as np
9
+ from typing import Iterable, Union
10
+ import torch
11
+ import torch as th
12
+ import torch.nn as nn
13
+ from torch import Tensor
14
+ from einops import rearrange, repeat
15
+
16
+ from comfy.ldm.modules.diffusionmodules.util import (
17
+ zero_module,
18
+ timestep_embedding,
19
+ )
20
+
21
+ from comfy.cli_args import args
22
+ from comfy.cldm.cldm import ControlNet as ControlNetCLDM
23
+ from comfy.ldm.modules.attention import SpatialTransformer
24
+ from comfy.ldm.modules.attention import attention_basic, attention_pytorch, attention_split, attention_sub_quad, default
25
+ from comfy.ldm.modules.attention import FeedForward, SpatialTransformer
26
+ from comfy.ldm.modules.diffusionmodules.openaimodel import TimestepEmbedSequential
27
+ from comfy.model_patcher import ModelPatcher
28
+ import comfy.ops
29
+ import comfy.model_management
30
+
31
+ from .logger import logger
32
+ from .utils import (BIGMAX, AbstractPreprocWrapper, disable_weight_init_clean_groupnorm,
33
+ prepare_mask_batch, broadcast_image_to_extend, extend_to_batch_size)
34
+
35
+
36
+ # until xformers bug is fixed, do not use xformers for VersatileAttention! TODO: change this when fix is out
37
+ # logic for choosing optimized_attention method taken from comfy/ldm/modules/attention.py
38
+ # a fallback_attention_mm is selected to avoid CUDA configuration limitation with pytorch's scaled_dot_product
39
+ optimized_attention_mm = attention_basic
40
+ fallback_attention_mm = attention_basic
41
+ if comfy.model_management.xformers_enabled():
42
+ pass
43
+ #optimized_attention_mm = attention_xformers
44
+ if comfy.model_management.pytorch_attention_enabled():
45
+ optimized_attention_mm = attention_pytorch
46
+ if args.use_split_cross_attention:
47
+ fallback_attention_mm = attention_split
48
+ else:
49
+ fallback_attention_mm = attention_sub_quad
50
+ else:
51
+ if args.use_split_cross_attention:
52
+ optimized_attention_mm = attention_split
53
+ else:
54
+ optimized_attention_mm = attention_sub_quad
55
+
56
+
57
+ class SparseConst:
58
+ HINT_MULT = "sparse_hint_mult"
59
+ NONHINT_MULT = "sparse_nonhint_mult"
60
+ MASK_MULT = "sparse_mask_mult"
61
+
62
+
63
+ class SparseControlNet(ControlNetCLDM):
64
+ def __init__(self, *args,**kwargs):
65
+ super().__init__(*args, **kwargs)
66
+ hint_channels = kwargs.get("hint_channels")
67
+ operations: disable_weight_init_clean_groupnorm = kwargs.get("operations", disable_weight_init_clean_groupnorm)
68
+ device = kwargs.get("device", None)
69
+ self.use_simplified_conditioning_embedding = kwargs.get("use_simplified_conditioning_embedding", False)
70
+ if self.use_simplified_conditioning_embedding:
71
+ self.input_hint_block = TimestepEmbedSequential(
72
+ zero_module(operations.conv_nd(self.dims, hint_channels, self.model_channels, 3, padding=1, dtype=self.dtype, device=device)),
73
+ )
74
+ self.motion_wrapper: SparseCtrlMotionWrapper = None
75
+
76
+ def set_actual_length(self, actual_length: int, full_length: int):
77
+ if self.motion_wrapper is not None:
78
+ self.motion_wrapper.set_video_length(video_length=actual_length, full_length=full_length)
79
+
80
+ def forward(self, x: Tensor, hint: Tensor, timesteps, context, y=None, **kwargs):
81
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
82
+ emb = self.time_embed(t_emb)
83
+
84
+ # SparseCtrl sets noisy input to zeros
85
+ x = torch.zeros_like(x)
86
+ guided_hint = self.input_hint_block(hint, emb, context)
87
+
88
+ out_output = []
89
+ out_middle = []
90
+
91
+ hs = []
92
+ if self.num_classes is not None:
93
+ assert y.shape[0] == x.shape[0]
94
+ emb = emb + self.label_emb(y)
95
+
96
+ h = x
97
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
98
+ if guided_hint is not None:
99
+ h = module(h, emb, context)
100
+ h += guided_hint
101
+ guided_hint = None
102
+ else:
103
+ h = module(h, emb, context)
104
+ out_output.append(zero_conv(h, emb, context))
105
+
106
+ h = self.middle_block(h, emb, context)
107
+ out_middle.append(self.middle_block_out(h, emb, context))
108
+
109
+ return {"middle": out_middle, "output": out_output}
110
+
111
+
112
+ class SparseModelPatcher(ModelPatcher):
113
+ def __init__(self, *args, **kwargs):
114
+ self.model: SparseControlNet
115
+ super().__init__(*args, **kwargs)
116
+
117
+ def patch_model_lowvram(self, device_to=None, *args, **kwargs):
118
+ patched_model = super().patch_model_lowvram(device_to, *args, **kwargs)
119
+
120
+ if self.model.motion_wrapper is not None:
121
+ # figure out the tensors (likely pe's) that should be cast to device besides just the named_modules
122
+ remaining_tensors = list(self.model.motion_wrapper.state_dict().keys())
123
+ named_modules = []
124
+ for n, _ in self.model.motion_wrapper.named_modules():
125
+ named_modules.append(n)
126
+ named_modules.append(f"{n}.weight")
127
+ named_modules.append(f"{n}.bias")
128
+ for name in named_modules:
129
+ if name in remaining_tensors:
130
+ remaining_tensors.remove(name)
131
+
132
+ for key in remaining_tensors:
133
+ self.patch_weight_to_device(key, device_to)
134
+ if device_to is not None:
135
+ comfy.utils.set_attr(self.model.motion_wrapper, key, comfy.utils.get_attr(self.model.motion_wrapper, key).to(device_to))
136
+
137
+ return patched_model
138
+
139
+ def clone(self):
140
+ # normal ModelPatcher clone actions
141
+ n = SparseModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
142
+ n.patches = {}
143
+ for k in self.patches:
144
+ n.patches[k] = self.patches[k][:]
145
+ if hasattr(n, "patches_uuid"):
146
+ self.patches_uuid = n.patches_uuid
147
+
148
+ n.object_patches = self.object_patches.copy()
149
+ n.model_options = copy.deepcopy(self.model_options)
150
+ if hasattr(n, "model_keys"):
151
+ n.model_keys = self.model_keys
152
+ if hasattr(n, "backup"):
153
+ self.backup = n.backup
154
+ if hasattr(n, "object_patches_backup"):
155
+ self.object_patches_backup = n.object_patches_backup
156
+
157
+
158
+ class PreprocSparseRGBWrapper(AbstractPreprocWrapper):
159
+ error_msg = error_msg = "Invalid use of RGB SparseCtrl output. The output of RGB SparseCtrl preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply ControlNet node (advanced or otherwise). It cannot be used for anything else that accepts IMAGE input."
160
+ def __init__(self, condhint: Tensor):
161
+ super().__init__(condhint)
162
+
163
+
164
+ class SparseContextAware:
165
+ NEAREST_HINT = "nearest_hint"
166
+ OFF = "off"
167
+
168
+ LIST = [NEAREST_HINT, OFF]
169
+
170
+
171
+ class SparseSettings:
172
+ def __init__(self, sparse_method: 'SparseMethod', use_motion: bool=True, motion_strength=1.0, motion_scale=1.0, merged=False,
173
+ sparse_mask_mult=1.0, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, context_aware=SparseContextAware.NEAREST_HINT):
174
+ # account for Steerable-Motion workflow incompatibility;
175
+ # doing this to for my own peace of mind (not an issue with my code)
176
+ if type(sparse_method) == str:
177
+ logger.warn("Outdated Steerable-Motion workflow detected; attempting to auto-convert indexes input. If you experience an error here, consult Steerable-Motion github, NOT Advanced-ControlNet.")
178
+ sparse_method = SparseIndexMethod(get_idx_list_from_str(sparse_method))
179
+ self.sparse_method = sparse_method
180
+ self.use_motion = use_motion
181
+ self.motion_strength = motion_strength
182
+ self.motion_scale = motion_scale
183
+ self.merged = merged
184
+ self.sparse_mask_mult = float(sparse_mask_mult)
185
+ self.sparse_hint_mult = float(sparse_hint_mult)
186
+ self.sparse_nonhint_mult = float(sparse_nonhint_mult)
187
+ self.context_aware = context_aware
188
+
189
+ def is_context_aware(self):
190
+ return self.context_aware != SparseContextAware.OFF
191
+
192
+ @classmethod
193
+ def default(cls):
194
+ return SparseSettings(sparse_method=SparseSpreadMethod(), use_motion=True)
195
+
196
+
197
+ class SparseMethod(ABC):
198
+ SPREAD = "spread"
199
+ INDEX = "index"
200
+ def __init__(self, method: str):
201
+ self.method = method
202
+
203
+ @abstractmethod
204
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
205
+ pass
206
+
207
+ def get_indexes(self, hint_length: int, full_length: int, sub_idxs: list[int]=None) -> tuple[list[int], list[int]]:
208
+ returned_idxs = self._get_indexes(hint_length, full_length)
209
+ if sub_idxs is None:
210
+ return returned_idxs, None
211
+ # need to map full indexes to condhint indexes
212
+ index_mapping = {}
213
+ for i, value in enumerate(returned_idxs):
214
+ index_mapping[value] = i
215
+ def get_mapped_idxs(idxs: list[int]):
216
+ return [index_mapping[idx] for idx in idxs]
217
+ # check if returned_idxs fit within subidxs
218
+ fitting_idxs = []
219
+ for sub_idx in sub_idxs:
220
+ if sub_idx in returned_idxs:
221
+ fitting_idxs.append(sub_idx)
222
+ # if have any fitting_idxs, deal with it
223
+ if len(fitting_idxs) > 0:
224
+ return fitting_idxs, get_mapped_idxs(fitting_idxs)
225
+
226
+ # since no returned_idxs fit in sub_idxs, need to get the next-closest hint images based on strategy
227
+ def get_closest_idx(target_idx: int, idxs: list[int]):
228
+ min_idx = -1
229
+ min_dist = BIGMAX
230
+ for idx in idxs:
231
+ new_dist = abs(idx-target_idx)
232
+ if new_dist < min_dist:
233
+ min_idx = idx
234
+ min_dist = new_dist
235
+ if min_dist == 1:
236
+ return min_idx, min_dist
237
+ return min_idx, min_dist
238
+ start_closest_idx, start_dist = get_closest_idx(sub_idxs[0], returned_idxs)
239
+ end_closest_idx, end_dist = get_closest_idx(sub_idxs[-1], returned_idxs)
240
+ # if only one cond hint exists, do special behavior
241
+ if hint_length == 1:
242
+ # if same distance from start and end,
243
+ if start_dist == end_dist:
244
+ # find center index of sub_idxs
245
+ center_idx = sub_idxs[np.linspace(0, len(sub_idxs)-1, 3, endpoint=True, dtype=int)[1]]
246
+ return [center_idx], get_mapped_idxs([start_closest_idx])
247
+ # otherwise, return closest
248
+ if start_dist < end_dist:
249
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
250
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
251
+ # otherwise, select up to two closest images, or just 1, whichever one applies best
252
+ # if same distance from start and end, return two images to use
253
+ if start_dist == end_dist:
254
+ return [sub_idxs[0], sub_idxs[-1]], get_mapped_idxs([start_closest_idx, end_closest_idx])
255
+ # else, use just one
256
+ if start_dist < end_dist:
257
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
258
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
259
+
260
+
261
+ class SparseSpreadMethod(SparseMethod):
262
+ UNIFORM = "uniform"
263
+ STARTING = "starting"
264
+ ENDING = "ending"
265
+ CENTER = "center"
266
+
267
+ LIST = [UNIFORM, STARTING, ENDING, CENTER]
268
+
269
+ def __init__(self, spread=UNIFORM):
270
+ super().__init__(self.SPREAD)
271
+ self.spread = spread
272
+
273
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
274
+ # if hint_length >= full_length, limit hints to full_length
275
+ if hint_length >= full_length:
276
+ return list(range(full_length))
277
+ # handle special case of 1 hint image
278
+ if hint_length == 1:
279
+ if self.spread in [self.UNIFORM, self.STARTING]:
280
+ return [0]
281
+ elif self.spread == self.ENDING:
282
+ return [full_length-1]
283
+ elif self.spread == self.CENTER:
284
+ # return second (of three) values as the center
285
+ return [np.linspace(0, full_length-1, 3, endpoint=True, dtype=int)[1]]
286
+ else:
287
+ raise ValueError(f"Unrecognized spread: {self.spread}")
288
+ # otherwise, handle other cases
289
+ if self.spread == self.UNIFORM:
290
+ return list(np.linspace(0, full_length-1, hint_length, endpoint=True, dtype=int))
291
+ elif self.spread == self.STARTING:
292
+ # make split 1 larger, remove last element
293
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
294
+ elif self.spread == self.ENDING:
295
+ # make split 1 larger, remove first element
296
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[1:]
297
+ elif self.spread == self.CENTER:
298
+ # if hint length is not 3 greater than full length, do STARTING behavior
299
+ if full_length-hint_length < 3:
300
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
301
+ # otherwise, get linspace of 2 greater than needed, then cut off first and last
302
+ return list(np.linspace(0, full_length-1, hint_length+2, endpoint=True, dtype=int))[1:-1]
303
+ return ValueError(f"Unrecognized spread: {self.spread}")
304
+
305
+
306
+ class SparseIndexMethod(SparseMethod):
307
+ def __init__(self, idxs: list[int]):
308
+ super().__init__(self.INDEX)
309
+ self.idxs = idxs
310
+
311
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
312
+ orig_hint_length = hint_length
313
+ if hint_length > full_length:
314
+ hint_length = full_length
315
+ # if idxs is less than hint_length, throw error
316
+ if len(self.idxs) < hint_length:
317
+ err_msg = f"There are not enough indexes ({len(self.idxs)}) provided to fit the usable {hint_length} input images."
318
+ if orig_hint_length != hint_length:
319
+ err_msg = f"{err_msg} (original input images: {orig_hint_length})"
320
+ raise ValueError(err_msg)
321
+ # cap idxs to hint_length
322
+ idxs = self.idxs[:hint_length]
323
+ new_idxs = []
324
+ real_idxs = set()
325
+ for idx in idxs:
326
+ if idx < 0:
327
+ real_idx = full_length+idx
328
+ if real_idx in real_idxs:
329
+ raise ValueError(f"Index '{idx}' maps to '{real_idx}' and is duplicate - indexes in Sparse Index Method must be unique.")
330
+ else:
331
+ real_idx = idx
332
+ if real_idx in real_idxs:
333
+ raise ValueError(f"Index '{idx}' is duplicate (or a negative index is equivalent) - indexes in Sparse Index Method must be unique.")
334
+ real_idxs.add(real_idx)
335
+ new_idxs.append(real_idx)
336
+ return new_idxs
337
+
338
+
339
+ def get_idx_list_from_str(indexes: str) -> list[int]:
340
+ idxs = []
341
+ unique_idxs = set()
342
+ # get indeces from string
343
+ str_idxs = [x.strip() for x in indexes.strip().split(",")]
344
+ for str_idx in str_idxs:
345
+ try:
346
+ idx = int(str_idx)
347
+ if idx in unique_idxs:
348
+ raise ValueError(f"'{idx}' is duplicated; indexes must be unique.")
349
+ idxs.append(idx)
350
+ unique_idxs.add(idx)
351
+ except ValueError:
352
+ raise ValueError(f"'{str_idx}' is not a valid integer index.")
353
+ if len(idxs) == 0:
354
+ raise ValueError(f"No indexes were listed in Sparse Index Method.")
355
+ return idxs
356
+
357
+
358
+ #########################################
359
+ # motion-related portion of controlnet
360
+ class BlockType:
361
+ UP = "up"
362
+ DOWN = "down"
363
+ MID = "mid"
364
+
365
+ def get_down_block_max(mm_state_dict: dict[str, Tensor]) -> int:
366
+ return get_block_max(mm_state_dict, "down_blocks")
367
+
368
+ def get_up_block_max(mm_state_dict: dict[str, Tensor]) -> int:
369
+ return get_block_max(mm_state_dict, "up_blocks")
370
+
371
+ def get_block_max(mm_state_dict: dict[str, Tensor], block_name: str) -> int:
372
+ # keep track of biggest down_block count in module
373
+ biggest_block = -1
374
+ for key in mm_state_dict.keys():
375
+ if block_name in key:
376
+ try:
377
+ block_int = key.split(".")[1]
378
+ block_num = int(block_int)
379
+ if block_num > biggest_block:
380
+ biggest_block = block_num
381
+ except ValueError:
382
+ pass
383
+ return biggest_block
384
+
385
+ def has_mid_block(mm_state_dict: dict[str, Tensor]):
386
+ # check if keys contain mid_block
387
+ for key in mm_state_dict.keys():
388
+ if key.startswith("mid_block."):
389
+ return True
390
+ return False
391
+
392
+ def get_position_encoding_max_len(mm_state_dict: dict[str, Tensor], mm_name: str=None) -> int:
393
+ # use pos_encoder.pe entries to determine max length - [1, {max_length}, {320|640|1280}]
394
+ for key in mm_state_dict.keys():
395
+ if key.endswith("pos_encoder.pe"):
396
+ return mm_state_dict[key].size(1) # get middle dim
397
+ raise ValueError(f"No pos_encoder.pe found in SparseCtrl state_dict - {mm_name} is not a valid SparseCtrl model!")
398
+
399
+
400
+ class SparseCtrlMotionWrapper(nn.Module):
401
+ def __init__(self, mm_state_dict: dict[str, Tensor], ops=disable_weight_init_clean_groupnorm):
402
+ super().__init__()
403
+ self.down_blocks: Iterable[MotionModule] = None
404
+ self.up_blocks: Iterable[MotionModule] = None
405
+ self.mid_block: MotionModule = None
406
+ self.encoding_max_len = get_position_encoding_max_len(mm_state_dict, "")
407
+ layer_channels = (320, 640, 1280, 1280)
408
+ if get_down_block_max(mm_state_dict) > -1:
409
+ self.down_blocks = nn.ModuleList([])
410
+ for c in layer_channels:
411
+ self.down_blocks.append(MotionModule(c, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.DOWN, ops=ops))
412
+ if get_up_block_max(mm_state_dict) > -1:
413
+ self.up_blocks = nn.ModuleList([])
414
+ for c in reversed(layer_channels):
415
+ self.up_blocks.append(MotionModule(c, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.UP, ops=ops))
416
+ if has_mid_block(mm_state_dict):
417
+ self.mid_block = MotionModule(1280, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.MID, ops=ops)
418
+
419
+ def inject(self, unet: SparseControlNet):
420
+ # inject input (down) blocks
421
+ self._inject(unet.input_blocks, self.down_blocks)
422
+ # inject mid block, if present
423
+ if self.mid_block is not None:
424
+ self._inject([unet.middle_block], [self.mid_block])
425
+ unet.motion_wrapper = self
426
+
427
+ def _inject(self, unet_blocks: nn.ModuleList, mm_blocks: nn.ModuleList):
428
+ # Rules for injection:
429
+ # For each component list in a unet block:
430
+ # if SpatialTransformer exists in list, place next block after last occurrence
431
+ # elif ResBlock exists in list, place next block after first occurrence
432
+ # else don't place block
433
+ injection_count = 0
434
+ unet_idx = 0
435
+ # details about blocks passed in
436
+ per_block = len(mm_blocks[0].motion_modules)
437
+ injection_goal = len(mm_blocks) * per_block
438
+ # only stop injecting when modules exhausted
439
+ while injection_count < injection_goal:
440
+ # figure out which VanillaTemporalModule from mm to inject
441
+ mm_blk_idx, mm_vtm_idx = injection_count // per_block, injection_count % per_block
442
+ # figure out layout of unet block components
443
+ st_idx = -1 # SpatialTransformer index
444
+ res_idx = -1 # first ResBlock index
445
+ # first, figure out indeces of relevant blocks
446
+ for idx, component in enumerate(unet_blocks[unet_idx]):
447
+ if type(component) == SpatialTransformer:
448
+ st_idx = idx
449
+ elif type(component).__name__ == "ResBlock" and res_idx < 0:
450
+ res_idx = idx
451
+ # if SpatialTransformer exists, inject right after
452
+ if st_idx >= 0:
453
+ unet_blocks[unet_idx].insert(st_idx+1, mm_blocks[mm_blk_idx].motion_modules[mm_vtm_idx])
454
+ injection_count += 1
455
+ # otherwise, if only ResBlock exists, inject right after
456
+ elif res_idx >= 0:
457
+ unet_blocks[unet_idx].insert(res_idx+1, mm_blocks[mm_blk_idx].motion_modules[mm_vtm_idx])
458
+ injection_count += 1
459
+ # increment unet_idx
460
+ unet_idx += 1
461
+
462
+ def eject(self, unet: SparseControlNet):
463
+ # remove from input blocks (downblocks)
464
+ self._eject(unet.input_blocks)
465
+ # remove from middle block (encapsulate in list to make compatible)
466
+ self._eject([unet.middle_block])
467
+ del unet.motion_wrapper
468
+ unet.motion_wrapper = None
469
+
470
+ def _eject(self, unet_blocks: nn.ModuleList):
471
+ # eject all VanillaTemporalModule objects from all blocks
472
+ for block in unet_blocks:
473
+ idx_to_pop = []
474
+ for idx, component in enumerate(block):
475
+ if type(component) == VanillaTemporalModule:
476
+ idx_to_pop.append(idx)
477
+ # pop in backwards order, as to not disturb what the indeces refer to
478
+ for idx in sorted(idx_to_pop, reverse=True):
479
+ block.pop(idx)
480
+
481
+ def set_video_length(self, video_length: int, full_length: int):
482
+ self.AD_video_length = video_length
483
+ if self.down_blocks is not None:
484
+ for block in self.down_blocks:
485
+ block.set_video_length(video_length, full_length)
486
+ if self.up_blocks is not None:
487
+ for block in self.up_blocks:
488
+ block.set_video_length(video_length, full_length)
489
+ if self.mid_block is not None:
490
+ self.mid_block.set_video_length(video_length, full_length)
491
+
492
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
493
+ if self.down_blocks is not None:
494
+ for block in self.down_blocks:
495
+ block.set_scale_multiplier(multiplier)
496
+ if self.up_blocks is not None:
497
+ for block in self.up_blocks:
498
+ block.set_scale_multiplier(multiplier)
499
+ if self.mid_block is not None:
500
+ self.mid_block.set_scale_multiplier(multiplier)
501
+
502
+ def set_strength(self, strength: float):
503
+ if self.down_blocks is not None:
504
+ for block in self.down_blocks:
505
+ block.set_strength(strength)
506
+ if self.up_blocks is not None:
507
+ for block in self.up_blocks:
508
+ block.set_strength(strength)
509
+ if self.mid_block is not None:
510
+ self.mid_block.set_strength(strength)
511
+
512
+ def reset_temp_vars(self):
513
+ if self.down_blocks is not None:
514
+ for block in self.down_blocks:
515
+ block.reset_temp_vars()
516
+ if self.up_blocks is not None:
517
+ for block in self.up_blocks:
518
+ block.reset_temp_vars()
519
+ if self.mid_block is not None:
520
+ self.mid_block.reset_temp_vars()
521
+
522
+ def reset_scale_multiplier(self):
523
+ self.set_scale_multiplier(None)
524
+
525
+ def reset(self):
526
+ self.reset_scale_multiplier()
527
+ self.reset_temp_vars()
528
+
529
+
530
+ class MotionModule(nn.Module):
531
+ def __init__(self, in_channels, temporal_position_encoding_max_len=24, block_type: str=BlockType.DOWN, ops=disable_weight_init_clean_groupnorm):
532
+ super().__init__()
533
+ if block_type == BlockType.MID:
534
+ # mid blocks contain only a single VanillaTemporalModule
535
+ self.motion_modules: Iterable[VanillaTemporalModule] = nn.ModuleList([get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops)])
536
+ else:
537
+ # down blocks contain two VanillaTemporalModules
538
+ self.motion_modules: Iterable[VanillaTemporalModule] = nn.ModuleList(
539
+ [
540
+ get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops),
541
+ get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops)
542
+ ]
543
+ )
544
+ # up blocks contain one additional VanillaTemporalModule
545
+ if block_type == BlockType.UP:
546
+ self.motion_modules.append(get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops))
547
+
548
+ def set_video_length(self, video_length: int, full_length: int):
549
+ for motion_module in self.motion_modules:
550
+ motion_module.set_video_length(video_length, full_length)
551
+
552
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
553
+ for motion_module in self.motion_modules:
554
+ motion_module.set_scale_multiplier(multiplier)
555
+
556
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
557
+ for motion_module in self.motion_modules:
558
+ motion_module.set_masks(masks, min_val, max_val)
559
+
560
+ def set_sub_idxs(self, sub_idxs: list[int]):
561
+ for motion_module in self.motion_modules:
562
+ motion_module.set_sub_idxs(sub_idxs)
563
+
564
+ def set_strength(self, strength: float):
565
+ for motion_module in self.motion_modules:
566
+ motion_module.set_strength(strength)
567
+
568
+ def reset_temp_vars(self):
569
+ for motion_module in self.motion_modules:
570
+ motion_module.reset_temp_vars()
571
+
572
+
573
+ def get_motion_module(in_channels, temporal_position_encoding_max_len, ops=disable_weight_init_clean_groupnorm):
574
+ # unlike normal AD, there is only one attention block expected in SparseCtrl models
575
+ return VanillaTemporalModule(in_channels=in_channels, attention_block_types=("Temporal_Self",), temporal_position_encoding_max_len=temporal_position_encoding_max_len, ops=ops)
576
+
577
+
578
+ class VanillaTemporalModule(nn.Module):
579
+ def __init__(
580
+ self,
581
+ in_channels,
582
+ num_attention_heads=8,
583
+ num_transformer_block=1,
584
+ attention_block_types=("Temporal_Self", "Temporal_Self"),
585
+ cross_frame_attention_mode=None,
586
+ temporal_position_encoding=True,
587
+ temporal_position_encoding_max_len=24,
588
+ temporal_attention_dim_div=1,
589
+ zero_initialize=True,
590
+ ops=disable_weight_init_clean_groupnorm,
591
+ ):
592
+ super().__init__()
593
+ self.strength = 1.0
594
+ self.temporal_transformer = TemporalTransformer3DModel(
595
+ in_channels=in_channels,
596
+ num_attention_heads=num_attention_heads,
597
+ attention_head_dim=in_channels
598
+ // num_attention_heads
599
+ // temporal_attention_dim_div,
600
+ num_layers=num_transformer_block,
601
+ attention_block_types=attention_block_types,
602
+ cross_frame_attention_mode=cross_frame_attention_mode,
603
+ temporal_position_encoding=temporal_position_encoding,
604
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
605
+ ops=ops,
606
+ )
607
+
608
+ if zero_initialize:
609
+ self.temporal_transformer.proj_out = zero_module(
610
+ self.temporal_transformer.proj_out
611
+ )
612
+
613
+ def set_video_length(self, video_length: int, full_length: int):
614
+ self.temporal_transformer.set_video_length(video_length, full_length)
615
+
616
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
617
+ self.temporal_transformer.set_scale_multiplier(multiplier)
618
+
619
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
620
+ self.temporal_transformer.set_masks(masks, min_val, max_val)
621
+
622
+ def set_sub_idxs(self, sub_idxs: list[int]):
623
+ self.temporal_transformer.set_sub_idxs(sub_idxs)
624
+
625
+ def set_strength(self, strength: float):
626
+ self.strength = strength
627
+
628
+ def reset_temp_vars(self):
629
+ self.set_strength(1.0)
630
+ self.temporal_transformer.reset_temp_vars()
631
+
632
+ def forward(self, input_tensor, encoder_hidden_states=None, attention_mask=None):
633
+ if math.isclose(self.strength, 1.0):
634
+ return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)
635
+ elif math.isclose(self.strength, 0.0):
636
+ return input_tensor
637
+ # elif self.strength > 1.0:
638
+ # return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)*self.strength
639
+ else:
640
+ return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)*self.strength + input_tensor*(1.0-self.strength)
641
+
642
+
643
+ class TemporalTransformer3DModel(nn.Module):
644
+ def __init__(
645
+ self,
646
+ in_channels,
647
+ num_attention_heads,
648
+ attention_head_dim,
649
+ num_layers,
650
+ attention_block_types=(
651
+ "Temporal_Self",
652
+ "Temporal_Self",
653
+ ),
654
+ dropout=0.0,
655
+ norm_num_groups=32,
656
+ cross_attention_dim=768,
657
+ activation_fn="geglu",
658
+ attention_bias=False,
659
+ upcast_attention=False,
660
+ cross_frame_attention_mode=None,
661
+ temporal_position_encoding=False,
662
+ temporal_position_encoding_max_len=24,
663
+ ops=disable_weight_init_clean_groupnorm,
664
+ ):
665
+ super().__init__()
666
+ self.video_length = 16
667
+ self.full_length = 16
668
+ self.scale_min = 1.0
669
+ self.scale_max = 1.0
670
+ self.raw_scale_mask: Union[Tensor, None] = None
671
+ self.temp_scale_mask: Union[Tensor, None] = None
672
+ self.sub_idxs: Union[list[int], None] = None
673
+ self.prev_hidden_states_batch = 0
674
+
675
+
676
+ inner_dim = num_attention_heads * attention_head_dim
677
+
678
+ self.norm = ops.GroupNorm(
679
+ num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True
680
+ )
681
+ self.proj_in = ops.Linear(in_channels, inner_dim)
682
+
683
+ self.transformer_blocks: Iterable[TemporalTransformerBlock] = nn.ModuleList(
684
+ [
685
+ TemporalTransformerBlock(
686
+ dim=inner_dim,
687
+ num_attention_heads=num_attention_heads,
688
+ attention_head_dim=attention_head_dim,
689
+ attention_block_types=attention_block_types,
690
+ dropout=dropout,
691
+ norm_num_groups=norm_num_groups,
692
+ cross_attention_dim=cross_attention_dim,
693
+ activation_fn=activation_fn,
694
+ attention_bias=attention_bias,
695
+ upcast_attention=upcast_attention,
696
+ cross_frame_attention_mode=cross_frame_attention_mode,
697
+ temporal_position_encoding=temporal_position_encoding,
698
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
699
+ ops=ops,
700
+ )
701
+ for d in range(num_layers)
702
+ ]
703
+ )
704
+ self.proj_out = ops.Linear(inner_dim, in_channels)
705
+
706
+ def set_video_length(self, video_length: int, full_length: int):
707
+ self.video_length = video_length
708
+ self.full_length = full_length
709
+
710
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
711
+ for block in self.transformer_blocks:
712
+ block.set_scale_multiplier(multiplier)
713
+
714
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
715
+ self.scale_min = min_val
716
+ self.scale_max = max_val
717
+ self.raw_scale_mask = masks
718
+
719
+ def set_sub_idxs(self, sub_idxs: list[int]):
720
+ self.sub_idxs = sub_idxs
721
+ for block in self.transformer_blocks:
722
+ block.set_sub_idxs(sub_idxs)
723
+
724
+ def reset_temp_vars(self):
725
+ del self.temp_scale_mask
726
+ self.temp_scale_mask = None
727
+ self.prev_hidden_states_batch = 0
728
+ for block in self.transformer_blocks:
729
+ block.reset_temp_vars()
730
+
731
+ def get_scale_mask(self, hidden_states: Tensor) -> Union[Tensor, None]:
732
+ # if no raw mask, return None
733
+ if self.raw_scale_mask is None:
734
+ return None
735
+ shape = hidden_states.shape
736
+ batch, channel, height, width = shape
737
+ # if temp mask already calculated, return it
738
+ if self.temp_scale_mask != None:
739
+ # check if hidden_states batch matches
740
+ if batch == self.prev_hidden_states_batch:
741
+ if self.sub_idxs is not None:
742
+ return self.temp_scale_mask[:, self.sub_idxs, :]
743
+ return self.temp_scale_mask
744
+ # if does not match, reset cached temp_scale_mask and recalculate it
745
+ del self.temp_scale_mask
746
+ self.temp_scale_mask = None
747
+ # otherwise, calculate temp mask
748
+ self.prev_hidden_states_batch = batch
749
+ mask = prepare_mask_batch(self.raw_scale_mask, shape=(self.full_length, 1, height, width))
750
+ mask = extend_to_batch_size(mask, self.full_length)
751
+ # if mask not the same amount length as full length, make it match
752
+ if self.full_length != mask.shape[0]:
753
+ mask = broadcast_image_to_extend(mask, self.full_length, 1)
754
+ # reshape mask to attention K shape (h*w, latent_count, 1)
755
+ batch, channel, height, width = mask.shape
756
+ # first, perform same operations as on hidden_states,
757
+ # turning (b, c, h, w) -> (b, h*w, c)
758
+ mask = mask.permute(0, 2, 3, 1).reshape(batch, height*width, channel)
759
+ # then, make it the same shape as attention's k, (h*w, b, c)
760
+ mask = mask.permute(1, 0, 2)
761
+ # make masks match the expected length of h*w
762
+ batched_number = shape[0] // self.video_length
763
+ if batched_number > 1:
764
+ mask = torch.cat([mask] * batched_number, dim=0)
765
+ # cache mask and set to proper device
766
+ self.temp_scale_mask = mask
767
+ # move temp_scale_mask to proper dtype + device
768
+ self.temp_scale_mask = self.temp_scale_mask.to(dtype=hidden_states.dtype, device=hidden_states.device)
769
+ # return subset of masks, if needed
770
+ if self.sub_idxs is not None:
771
+ return self.temp_scale_mask[:, self.sub_idxs, :]
772
+ return self.temp_scale_mask
773
+
774
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
775
+ batch, channel, height, width = hidden_states.shape
776
+ residual = hidden_states
777
+ scale_mask = self.get_scale_mask(hidden_states)
778
+ # add some casts for fp8 purposes - does not affect speed otherwise
779
+ hidden_states = self.norm(hidden_states).to(hidden_states.dtype)
780
+ inner_dim = hidden_states.shape[1]
781
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
782
+ batch, height * width, inner_dim
783
+ )
784
+ hidden_states = self.proj_in(hidden_states).to(hidden_states.dtype)
785
+
786
+ # Transformer Blocks
787
+ for block in self.transformer_blocks:
788
+ hidden_states = block(
789
+ hidden_states,
790
+ encoder_hidden_states=encoder_hidden_states,
791
+ attention_mask=attention_mask,
792
+ video_length=self.video_length,
793
+ scale_mask=scale_mask
794
+ )
795
+
796
+ # output
797
+ hidden_states = self.proj_out(hidden_states)
798
+ hidden_states = (
799
+ hidden_states.reshape(batch, height, width, inner_dim)
800
+ .permute(0, 3, 1, 2)
801
+ .contiguous()
802
+ )
803
+
804
+ output = hidden_states + residual
805
+
806
+ return output
807
+
808
+
809
+ class TemporalTransformerBlock(nn.Module):
810
+ def __init__(
811
+ self,
812
+ dim,
813
+ num_attention_heads,
814
+ attention_head_dim,
815
+ attention_block_types=(
816
+ "Temporal_Self",
817
+ "Temporal_Self",
818
+ ),
819
+ dropout=0.0,
820
+ norm_num_groups=32,
821
+ cross_attention_dim=768,
822
+ activation_fn="geglu",
823
+ attention_bias=False,
824
+ upcast_attention=False,
825
+ cross_frame_attention_mode=None,
826
+ temporal_position_encoding=False,
827
+ temporal_position_encoding_max_len=24,
828
+ ops=disable_weight_init_clean_groupnorm,
829
+ ):
830
+ super().__init__()
831
+
832
+ attention_blocks = []
833
+ norms = []
834
+
835
+ for block_name in attention_block_types:
836
+ attention_blocks.append(
837
+ VersatileAttention(
838
+ attention_mode=block_name.split("_")[0],
839
+ context_dim=cross_attention_dim # called context_dim for ComfyUI impl
840
+ if block_name.endswith("_Cross")
841
+ else None,
842
+ query_dim=dim,
843
+ heads=num_attention_heads,
844
+ dim_head=attention_head_dim,
845
+ dropout=dropout,
846
+ #bias=attention_bias, # remove for Comfy CrossAttention
847
+ #upcast_attention=upcast_attention, # remove for Comfy CrossAttention
848
+ cross_frame_attention_mode=cross_frame_attention_mode,
849
+ temporal_position_encoding=temporal_position_encoding,
850
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
851
+ ops=ops,
852
+ )
853
+ )
854
+ norms.append(ops.LayerNorm(dim))
855
+
856
+ self.attention_blocks: Iterable[VersatileAttention] = nn.ModuleList(attention_blocks)
857
+ self.norms = nn.ModuleList(norms)
858
+
859
+ self.ff = FeedForward(dim, dropout=dropout, glu=(activation_fn == "geglu"), operations=ops)
860
+ self.ff_norm = ops.LayerNorm(dim)
861
+
862
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
863
+ for block in self.attention_blocks:
864
+ block.set_scale_multiplier(multiplier)
865
+
866
+ def set_sub_idxs(self, sub_idxs: list[int]):
867
+ for block in self.attention_blocks:
868
+ block.set_sub_idxs(sub_idxs)
869
+
870
+ def reset_temp_vars(self):
871
+ for block in self.attention_blocks:
872
+ block.reset_temp_vars()
873
+
874
+ def forward(
875
+ self,
876
+ hidden_states,
877
+ encoder_hidden_states=None,
878
+ attention_mask=None,
879
+ video_length=None,
880
+ scale_mask=None
881
+ ):
882
+ for attention_block, norm in zip(self.attention_blocks, self.norms):
883
+ norm_hidden_states = norm(hidden_states).to(hidden_states.dtype)
884
+ hidden_states = (
885
+ attention_block(
886
+ norm_hidden_states,
887
+ encoder_hidden_states=encoder_hidden_states
888
+ if attention_block.is_cross_attention
889
+ else None,
890
+ attention_mask=attention_mask,
891
+ video_length=video_length,
892
+ scale_mask=scale_mask
893
+ )
894
+ + hidden_states
895
+ )
896
+
897
+ hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
898
+
899
+ output = hidden_states
900
+ return output
901
+
902
+
903
+ class PositionalEncoding(nn.Module):
904
+ def __init__(self, d_model, dropout=0.0, max_len=24):
905
+ super().__init__()
906
+ self.dropout = nn.Dropout(p=dropout)
907
+ position = torch.arange(max_len).unsqueeze(1)
908
+ div_term = torch.exp(
909
+ torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)
910
+ )
911
+ pe = torch.zeros(1, max_len, d_model)
912
+ pe[0, :, 0::2] = torch.sin(position * div_term)
913
+ pe[0, :, 1::2] = torch.cos(position * div_term)
914
+ self.register_buffer("pe", pe)
915
+ self.sub_idxs = None
916
+
917
+ def set_sub_idxs(self, sub_idxs: list[int]):
918
+ self.sub_idxs = sub_idxs
919
+
920
+ def forward(self, x):
921
+ #if self.sub_idxs is not None:
922
+ # x = x + self.pe[:, self.sub_idxs]
923
+ #else:
924
+ x = x + self.pe[:, : x.size(1)]
925
+ return self.dropout(x)
926
+
927
+
928
+ class CrossAttentionMMSparse(nn.Module):
929
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None,
930
+ operations=disable_weight_init_clean_groupnorm):
931
+ super().__init__()
932
+ inner_dim = dim_head * heads
933
+ context_dim = default(context_dim, query_dim)
934
+
935
+ self.actual_attention = optimized_attention_mm
936
+ self.heads = heads
937
+ self.dim_head = dim_head
938
+ self.scale = None
939
+
940
+ self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
941
+ self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
942
+ self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
943
+
944
+ self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
945
+
946
+ def reset_attention_type(self):
947
+ self.actual_attention = optimized_attention_mm
948
+
949
+ def forward(self, x, context=None, value=None, mask=None, scale_mask=None):
950
+ q = self.to_q(x)
951
+ context = default(context, x)
952
+ k: Tensor = self.to_k(context)
953
+ if value is not None:
954
+ v = self.to_v(value)
955
+ del value
956
+ else:
957
+ v = self.to_v(context)
958
+
959
+ # apply custom scale by multiplying k by scale factor
960
+ if self.scale is not None:
961
+ k *= self.scale
962
+
963
+ # apply scale mask, if present
964
+ if scale_mask is not None:
965
+ k *= scale_mask
966
+
967
+ try:
968
+ out = self.actual_attention(q, k, v, self.heads, mask)
969
+ except RuntimeError as e:
970
+ if str(e).startswith("CUDA error: invalid configuration argument"):
971
+ self.actual_attention = fallback_attention_mm
972
+ out = self.actual_attention(q, k, v, self.heads, mask)
973
+ else:
974
+ raise
975
+ return self.to_out(out)
976
+
977
+
978
+ class VersatileAttention(CrossAttentionMMSparse):
979
+ def __init__(
980
+ self,
981
+ attention_mode=None,
982
+ cross_frame_attention_mode=None,
983
+ temporal_position_encoding=False,
984
+ temporal_position_encoding_max_len=24,
985
+ ops=disable_weight_init_clean_groupnorm,
986
+ *args,
987
+ **kwargs,
988
+ ):
989
+ super().__init__(operations=ops, *args, **kwargs)
990
+ assert attention_mode == "Temporal"
991
+
992
+ self.attention_mode = attention_mode
993
+ self.is_cross_attention = kwargs["context_dim"] is not None
994
+
995
+ self.pos_encoder = (
996
+ PositionalEncoding(
997
+ kwargs["query_dim"],
998
+ dropout=0.0,
999
+ max_len=temporal_position_encoding_max_len,
1000
+ )
1001
+ if (temporal_position_encoding and attention_mode == "Temporal")
1002
+ else None
1003
+ )
1004
+
1005
+ def extra_repr(self):
1006
+ return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
1007
+
1008
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
1009
+ if multiplier is None or math.isclose(multiplier, 1.0):
1010
+ self.scale = None
1011
+ else:
1012
+ self.scale = multiplier
1013
+
1014
+ def set_sub_idxs(self, sub_idxs: list[int]):
1015
+ if self.pos_encoder != None:
1016
+ self.pos_encoder.set_sub_idxs(sub_idxs)
1017
+
1018
+ def reset_temp_vars(self):
1019
+ self.reset_attention_type()
1020
+
1021
+ def forward(
1022
+ self,
1023
+ hidden_states: Tensor,
1024
+ encoder_hidden_states=None,
1025
+ attention_mask=None,
1026
+ video_length=None,
1027
+ scale_mask=None,
1028
+ ):
1029
+ if self.attention_mode != "Temporal":
1030
+ raise NotImplementedError
1031
+
1032
+ d = hidden_states.shape[1]
1033
+ hidden_states = rearrange(
1034
+ hidden_states, "(b f) d c -> (b d) f c", f=video_length
1035
+ )
1036
+
1037
+ if self.pos_encoder is not None:
1038
+ hidden_states = self.pos_encoder(hidden_states).to(hidden_states.dtype)
1039
+
1040
+ encoder_hidden_states = (
1041
+ repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d)
1042
+ if encoder_hidden_states is not None
1043
+ else encoder_hidden_states
1044
+ )
1045
+
1046
+ hidden_states = super().forward(
1047
+ hidden_states,
1048
+ encoder_hidden_states,
1049
+ value=None,
1050
+ mask=attention_mask,
1051
+ scale_mask=scale_mask,
1052
+ )
1053
+
1054
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
1055
+
1056
+ return hidden_states
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/control_svd.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch import Tensor
4
+
5
+ import comfy.model_detection
6
+ from comfy.utils import UNET_MAP_BASIC, UNET_MAP_RESNET, UNET_MAP_ATTENTIONS, TRANSFORMER_BLOCKS
7
+
8
+ import torch
9
+
10
+
11
+ from comfy.ldm.modules.diffusionmodules.util import (
12
+ zero_module,
13
+ timestep_embedding,
14
+ )
15
+
16
+ from comfy.ldm.modules.attention import SpatialVideoTransformer
17
+ from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, VideoResBlock, Downsample
18
+ from comfy.ldm.util import exists
19
+ import comfy.ops
20
+
21
+
22
+ class SVDControlNet(nn.Module):
23
+ def __init__(
24
+ self,
25
+ image_size,
26
+ in_channels,
27
+ model_channels,
28
+ hint_channels,
29
+ num_res_blocks,
30
+ dropout=0,
31
+ channel_mult=(1, 2, 4, 8),
32
+ conv_resample=True,
33
+ dims=2,
34
+ num_classes=None,
35
+ use_checkpoint=False,
36
+ dtype=torch.float32,
37
+ num_heads=-1,
38
+ num_head_channels=-1,
39
+ num_heads_upsample=-1,
40
+ use_scale_shift_norm=False,
41
+ resblock_updown=False,
42
+ use_new_attention_order=False,
43
+ use_spatial_transformer=False, # custom transformer support
44
+ transformer_depth=1, # custom transformer support
45
+ context_dim=None, # custom transformer support
46
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
47
+ legacy=True,
48
+ disable_self_attentions=None,
49
+ num_attention_blocks=None,
50
+ disable_middle_self_attn=False,
51
+ use_linear_in_transformer=False,
52
+ adm_in_channels=None,
53
+ transformer_depth_middle=None,
54
+ transformer_depth_output=None,
55
+ use_spatial_context=False,
56
+ extra_ff_mix_layer=False,
57
+ merge_strategy="fixed",
58
+ merge_factor=0.5,
59
+ video_kernel_size=3,
60
+ device=None,
61
+ operations=comfy.ops.disable_weight_init,
62
+ **kwargs,
63
+ ):
64
+ super().__init__()
65
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
66
+ if use_spatial_transformer:
67
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
68
+
69
+ if context_dim is not None:
70
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
71
+ # from omegaconf.listconfig import ListConfig
72
+ # if type(context_dim) == ListConfig:
73
+ # context_dim = list(context_dim)
74
+
75
+ if num_heads_upsample == -1:
76
+ num_heads_upsample = num_heads
77
+
78
+ if num_heads == -1:
79
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
80
+
81
+ if num_head_channels == -1:
82
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
83
+
84
+ self.dims = dims
85
+ self.image_size = image_size
86
+ self.in_channels = in_channels
87
+ self.model_channels = model_channels
88
+
89
+ if isinstance(num_res_blocks, int):
90
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
91
+ else:
92
+ if len(num_res_blocks) != len(channel_mult):
93
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
94
+ "as a list/tuple (per-level) with the same length as channel_mult")
95
+ self.num_res_blocks = num_res_blocks
96
+
97
+ if disable_self_attentions is not None:
98
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
99
+ assert len(disable_self_attentions) == len(channel_mult)
100
+ if num_attention_blocks is not None:
101
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
102
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
103
+
104
+ transformer_depth = transformer_depth[:]
105
+
106
+ self.dropout = dropout
107
+ self.channel_mult = channel_mult
108
+ self.conv_resample = conv_resample
109
+ self.num_classes = num_classes
110
+ self.use_checkpoint = use_checkpoint
111
+ self.dtype = dtype
112
+ self.num_heads = num_heads
113
+ self.num_head_channels = num_head_channels
114
+ self.num_heads_upsample = num_heads_upsample
115
+ self.predict_codebook_ids = n_embed is not None
116
+
117
+ time_embed_dim = model_channels * 4
118
+ self.time_embed = nn.Sequential(
119
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
120
+ nn.SiLU(),
121
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
122
+ )
123
+
124
+ if self.num_classes is not None:
125
+ if isinstance(self.num_classes, int):
126
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
127
+ elif self.num_classes == "continuous":
128
+ print("setting up linear c_adm embedding layer")
129
+ self.label_emb = nn.Linear(1, time_embed_dim)
130
+ elif self.num_classes == "sequential":
131
+ assert adm_in_channels is not None
132
+ self.label_emb = nn.Sequential(
133
+ nn.Sequential(
134
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
135
+ nn.SiLU(),
136
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
137
+ )
138
+ )
139
+ else:
140
+ raise ValueError()
141
+
142
+ self.input_blocks = nn.ModuleList(
143
+ [
144
+ TimestepEmbedSequential(
145
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
146
+ )
147
+ ]
148
+ )
149
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
150
+
151
+ self.input_hint_block = TimestepEmbedSequential(
152
+ operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
153
+ nn.SiLU(),
154
+ operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
155
+ nn.SiLU(),
156
+ operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
157
+ nn.SiLU(),
158
+ operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
159
+ nn.SiLU(),
160
+ operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
161
+ nn.SiLU(),
162
+ operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
163
+ nn.SiLU(),
164
+ operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
165
+ nn.SiLU(),
166
+ operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
167
+ )
168
+
169
+ self._feature_size = model_channels
170
+ input_block_chans = [model_channels]
171
+ ch = model_channels
172
+ ds = 1
173
+ for level, mult in enumerate(channel_mult):
174
+ for nr in range(self.num_res_blocks[level]):
175
+ layers = [
176
+ VideoResBlock(
177
+ ch,
178
+ time_embed_dim,
179
+ dropout,
180
+ out_channels=mult * model_channels,
181
+ dims=dims,
182
+ use_checkpoint=use_checkpoint,
183
+ use_scale_shift_norm=use_scale_shift_norm,
184
+ dtype=self.dtype,
185
+ device=device,
186
+ operations=operations,
187
+ video_kernel_size=video_kernel_size,
188
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
189
+ )
190
+ ]
191
+ ch = mult * model_channels
192
+ num_transformers = transformer_depth.pop(0)
193
+ if num_transformers > 0:
194
+ if num_head_channels == -1:
195
+ dim_head = ch // num_heads
196
+ else:
197
+ num_heads = ch // num_head_channels
198
+ dim_head = num_head_channels
199
+ if legacy:
200
+ #num_heads = 1
201
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
202
+ if exists(disable_self_attentions):
203
+ disabled_sa = disable_self_attentions[level]
204
+ else:
205
+ disabled_sa = False
206
+
207
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
208
+ layers.append(
209
+ SpatialVideoTransformer(
210
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
211
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
212
+ checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations,
213
+ use_spatial_context=use_spatial_context, ff_in=extra_ff_mix_layer,
214
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
215
+ )
216
+ )
217
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
218
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
219
+ self._feature_size += ch
220
+ input_block_chans.append(ch)
221
+ if level != len(channel_mult) - 1:
222
+ out_ch = ch
223
+ self.input_blocks.append(
224
+ TimestepEmbedSequential(
225
+ VideoResBlock(
226
+ ch,
227
+ time_embed_dim,
228
+ dropout,
229
+ out_channels=out_ch,
230
+ dims=dims,
231
+ use_checkpoint=use_checkpoint,
232
+ use_scale_shift_norm=use_scale_shift_norm,
233
+ down=True,
234
+ dtype=self.dtype,
235
+ device=device,
236
+ operations=operations,
237
+ video_kernel_size=video_kernel_size,
238
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
239
+ )
240
+ if resblock_updown
241
+ else Downsample(
242
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
243
+ )
244
+ )
245
+ )
246
+ ch = out_ch
247
+ input_block_chans.append(ch)
248
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
249
+ ds *= 2
250
+ self._feature_size += ch
251
+
252
+ if num_head_channels == -1:
253
+ dim_head = ch // num_heads
254
+ else:
255
+ num_heads = ch // num_head_channels
256
+ dim_head = num_head_channels
257
+ if legacy:
258
+ #num_heads = 1
259
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
260
+ mid_block = [
261
+ VideoResBlock(
262
+ ch,
263
+ time_embed_dim,
264
+ dropout,
265
+ dims=dims,
266
+ use_checkpoint=use_checkpoint,
267
+ use_scale_shift_norm=use_scale_shift_norm,
268
+ dtype=self.dtype,
269
+ device=device,
270
+ operations=operations,
271
+ video_kernel_size=video_kernel_size,
272
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
273
+ )]
274
+ if transformer_depth_middle >= 0:
275
+ mid_block += [SpatialVideoTransformer( # always uses a self-attn
276
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
277
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
278
+ checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations,
279
+ use_spatial_context=use_spatial_context, ff_in=extra_ff_mix_layer,
280
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
281
+ ),
282
+ VideoResBlock(
283
+ ch,
284
+ time_embed_dim,
285
+ dropout,
286
+ dims=dims,
287
+ use_checkpoint=use_checkpoint,
288
+ use_scale_shift_norm=use_scale_shift_norm,
289
+ dtype=self.dtype,
290
+ device=device,
291
+ operations=operations,
292
+ video_kernel_size=video_kernel_size,
293
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
294
+ )]
295
+ self.middle_block = TimestepEmbedSequential(*mid_block)
296
+ self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
297
+ self._feature_size += ch
298
+
299
+ def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
300
+ return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
301
+
302
+ def forward(self, x, hint, timesteps, context, y=None, **kwargs):
303
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
304
+ emb = self.time_embed(t_emb)
305
+
306
+ cond = kwargs["cond"]
307
+ num_video_frames = cond["num_video_frames"]
308
+ image_only_indicator = cond.get("image_only_indicator", None)
309
+ time_context = cond.get("time_context", None)
310
+ del cond
311
+
312
+ guided_hint = self.input_hint_block(hint, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
313
+
314
+ out_output = []
315
+ out_middle = []
316
+
317
+ hs = []
318
+ if self.num_classes is not None:
319
+ assert y.shape[0] == x.shape[0]
320
+ emb = emb + self.label_emb(y)
321
+
322
+ h = x
323
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
324
+ if guided_hint is not None:
325
+ h = module(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
326
+ h += guided_hint
327
+ guided_hint = None
328
+ else:
329
+ h = module(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
330
+ out_output.append(zero_conv(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator))
331
+
332
+ h = self.middle_block(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
333
+ out_middle.append(self.middle_block_out(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator))
334
+
335
+ return {"middle": out_middle, "output": out_output}
336
+
337
+
338
+ TEMPORAL_TRANSFORMER_BLOCKS = {
339
+ "norm_in.weight",
340
+ "norm_in.bias",
341
+ "ff_in.net.0.proj.weight",
342
+ "ff_in.net.0.proj.bias",
343
+ "ff_in.net.2.weight",
344
+ "ff_in.net.2.bias",
345
+ }
346
+ TEMPORAL_TRANSFORMER_BLOCKS.update(TRANSFORMER_BLOCKS)
347
+
348
+
349
+ TEMPORAL_UNET_MAP_ATTENTIONS = {
350
+ "time_mixer.mix_factor",
351
+ }
352
+ TEMPORAL_UNET_MAP_ATTENTIONS.update(UNET_MAP_ATTENTIONS)
353
+
354
+
355
+ TEMPORAL_TRANSFORMER_MAP = {
356
+ "time_pos_embed.0.weight": "time_pos_embed.linear_1.weight",
357
+ "time_pos_embed.0.bias": "time_pos_embed.linear_1.bias",
358
+ "time_pos_embed.2.weight": "time_pos_embed.linear_2.weight",
359
+ "time_pos_embed.2.bias": "time_pos_embed.linear_2.bias",
360
+ }
361
+
362
+
363
+ TEMPORAL_RESNET = {
364
+ "time_mixer.mix_factor",
365
+ }
366
+
367
+
368
+ def svd_unet_config_from_diffusers_unet(state_dict: dict[str, Tensor], dtype):
369
+ match = {}
370
+ transformer_depth = []
371
+
372
+ attn_res = 1
373
+ down_blocks = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}")
374
+ for i in range(down_blocks):
375
+ attn_blocks = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
376
+ for ab in range(attn_blocks):
377
+ transformer_count = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
378
+ transformer_depth.append(transformer_count)
379
+ if transformer_count > 0:
380
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
381
+
382
+ attn_res *= 2
383
+ if attn_blocks == 0:
384
+ transformer_depth.append(0)
385
+ transformer_depth.append(0)
386
+
387
+ match["transformer_depth"] = transformer_depth
388
+
389
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
390
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
391
+ match["adm_in_channels"] = None
392
+ if "class_embedding.linear_1.weight" in state_dict:
393
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
394
+ elif "add_embedding.linear_1.weight" in state_dict:
395
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
396
+
397
+ # based on unet_config of SVD
398
+ SVD = {
399
+ 'use_checkpoint': False,
400
+ 'image_size': 32,
401
+ 'use_spatial_transformer': True,
402
+ 'legacy': False,
403
+ 'num_classes': 'sequential',
404
+ 'adm_in_channels': 768,
405
+ 'dtype': dtype,
406
+ 'in_channels': 8,
407
+ 'out_channels': 4,
408
+ 'model_channels': 320,
409
+ 'num_res_blocks': [2, 2, 2, 2],
410
+ 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0],
411
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
412
+ 'channel_mult': [1, 2, 4, 4],
413
+ 'transformer_depth_middle': 1,
414
+ 'use_linear_in_transformer': True,
415
+ 'context_dim': 1024,
416
+ 'extra_ff_mix_layer': True,
417
+ 'use_spatial_context': True,
418
+ 'merge_strategy': 'learned_with_images',
419
+ 'merge_factor': 0.0,
420
+ 'video_kernel_size': [3, 1, 1],
421
+ 'use_temporal_attention': True,
422
+ 'use_temporal_resblock': True,
423
+ 'num_heads': -1,
424
+ 'num_head_channels': 64,
425
+ }
426
+
427
+ supported_models = [SVD]
428
+
429
+ for unet_config in supported_models:
430
+ matches = True
431
+ for k in match:
432
+ if match[k] != unet_config[k]:
433
+ matches = False
434
+ break
435
+ if matches:
436
+ return comfy.model_detection.convert_config(unet_config)
437
+ return None
438
+
439
+
440
+ def svd_unet_to_diffusers(unet_config):
441
+ num_res_blocks = unet_config["num_res_blocks"]
442
+ channel_mult = unet_config["channel_mult"]
443
+ transformer_depth = unet_config["transformer_depth"][:]
444
+ transformer_depth_output = unet_config["transformer_depth_output"][:]
445
+ num_blocks = len(channel_mult)
446
+
447
+ transformers_mid = unet_config.get("transformer_depth_middle", None)
448
+
449
+ diffusers_unet_map = {}
450
+ for x in range(num_blocks):
451
+ n = 1 + (num_res_blocks[x] + 1) * x
452
+ for i in range(num_res_blocks[x]):
453
+ for b in TEMPORAL_RESNET:
454
+ diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, b)] = "input_blocks.{}.0.{}".format(n, b)
455
+ for b in UNET_MAP_RESNET:
456
+ diffusers_unet_map["down_blocks.{}.resnets.{}.spatial_res_block.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
457
+ diffusers_unet_map["down_blocks.{}.resnets.{}.temporal_res_block.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.time_stack.{}".format(n, b)
458
+ #diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
459
+ num_transformers = transformer_depth.pop(0)
460
+ if num_transformers > 0:
461
+ for b in TEMPORAL_UNET_MAP_ATTENTIONS:
462
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b)
463
+ for b in TEMPORAL_TRANSFORMER_MAP:
464
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, TEMPORAL_TRANSFORMER_MAP[b])] = "input_blocks.{}.1.{}".format(n, b)
465
+ for t in range(num_transformers):
466
+ for b in TRANSFORMER_BLOCKS:
467
+ diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
468
+ for b in TEMPORAL_TRANSFORMER_BLOCKS:
469
+ diffusers_unet_map["down_blocks.{}.attentions.{}.temporal_transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.time_stack.{}.{}".format(n, t, b)
470
+ n += 1
471
+ for k in ["weight", "bias"]:
472
+ diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k)
473
+
474
+ i = 0
475
+ for b in TEMPORAL_UNET_MAP_ATTENTIONS:
476
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b)
477
+ for b in TEMPORAL_TRANSFORMER_MAP:
478
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, TEMPORAL_TRANSFORMER_MAP[b])] = "middle_block.1.{}".format(b)
479
+ for t in range(transformers_mid):
480
+ for b in TRANSFORMER_BLOCKS:
481
+ diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b)
482
+ for b in TEMPORAL_TRANSFORMER_BLOCKS:
483
+ diffusers_unet_map["mid_block.attentions.{}.temporal_transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.time_stack.{}.{}".format(t, b)
484
+
485
+ for i, n in enumerate([0, 2]):
486
+ for b in TEMPORAL_RESNET:
487
+ diffusers_unet_map["mid_block.resnets.{}.{}".format(i, b)] = "middle_block.{}.{}".format(n, b)
488
+ for b in UNET_MAP_RESNET:
489
+ diffusers_unet_map["mid_block.resnets.{}.spatial_res_block.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
490
+ diffusers_unet_map["mid_block.resnets.{}.temporal_res_block.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.time_stack.{}".format(n, b)
491
+ #diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
492
+
493
+ num_res_blocks = list(reversed(num_res_blocks))
494
+ for x in range(num_blocks):
495
+ n = (num_res_blocks[x] + 1) * x
496
+ l = num_res_blocks[x] + 1
497
+ for i in range(l):
498
+ c = 0
499
+ for b in UNET_MAP_RESNET:
500
+ diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b)
501
+ c += 1
502
+ num_transformers = transformer_depth_output.pop()
503
+ if num_transformers > 0:
504
+ c += 1
505
+ for b in UNET_MAP_ATTENTIONS:
506
+ diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b)
507
+ for t in range(num_transformers):
508
+ for b in TRANSFORMER_BLOCKS:
509
+ diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
510
+ if i == l - 1:
511
+ for k in ["weight", "bias"]:
512
+ diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k)
513
+ n += 1
514
+
515
+ for k in UNET_MAP_BASIC:
516
+ diffusers_unet_map[k[1]] = k[0]
517
+
518
+ return diffusers_unet_map
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/logger.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import copy
3
+ import logging
4
+
5
+
6
+ class ColoredFormatter(logging.Formatter):
7
+ COLORS = {
8
+ "DEBUG": "\033[0;36m", # CYAN
9
+ "INFO": "\033[0;32m", # GREEN
10
+ "WARNING": "\033[0;33m", # YELLOW
11
+ "ERROR": "\033[0;31m", # RED
12
+ "CRITICAL": "\033[0;37;41m", # WHITE ON RED
13
+ "RESET": "\033[0m", # RESET COLOR
14
+ }
15
+
16
+ def format(self, record):
17
+ colored_record = copy.copy(record)
18
+ levelname = colored_record.levelname
19
+ seq = self.COLORS.get(levelname, self.COLORS["RESET"])
20
+ colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
21
+ return super().format(colored_record)
22
+
23
+
24
+ # Create a new logger
25
+ logger = logging.getLogger("Advanced-ControlNet")
26
+ logger.propagate = False
27
+
28
+ # Add handler if we don't have one.
29
+ if not logger.handlers:
30
+ handler = logging.StreamHandler(sys.stdout)
31
+ handler.setFormatter(ColoredFormatter("[%(name)s] - %(levelname)s - %(message)s"))
32
+ logger.addHandler(handler)
33
+
34
+ # Configure logger
35
+ loglevel = logging.INFO
36
+ logger.setLevel(loglevel)
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from torch import Tensor
3
+
4
+ import folder_paths
5
+ from comfy.model_patcher import ModelPatcher
6
+
7
+ from .control import load_controlnet, convert_to_advanced, is_advanced_controlnet, is_sd3_advanced_controlnet
8
+ from .utils import ControlWeights, LatentKeyframeGroup, TimestepKeyframeGroup, AbstractPreprocWrapper, BIGMAX
9
+ from .nodes_weight import (DefaultWeights, ScaledSoftMaskedUniversalWeights, ScaledSoftUniversalWeights, SoftControlNetWeights, CustomControlNetWeights,
10
+ SoftT2IAdapterWeights, CustomT2IAdapterWeights)
11
+ from .nodes_keyframes import (LatentKeyframeGroupNode, LatentKeyframeInterpolationNode, LatentKeyframeBatchedGroupNode, LatentKeyframeNode,
12
+ TimestepKeyframeNode, TimestepKeyframeInterpolationNode, TimestepKeyframeFromStrengthListNode)
13
+ from .nodes_sparsectrl import SparseCtrlMergedLoaderAdvanced, SparseCtrlLoaderAdvanced, SparseIndexMethodNode, SparseSpreadMethodNode, RgbSparseCtrlPreprocessor, SparseWeightExtras
14
+ from .nodes_reference import ReferenceControlNetNode, ReferenceControlFinetune, ReferencePreprocessorNode
15
+ from .nodes_loosecontrol import ControlNetLoaderWithLoraAdvanced
16
+ from .nodes_deprecated import LoadImagesFromDirectory
17
+ from .logger import logger
18
+
19
+
20
+ class ControlNetLoaderAdvanced:
21
+ @classmethod
22
+ def INPUT_TYPES(s):
23
+ return {
24
+ "required": {
25
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
26
+ },
27
+ "optional": {
28
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
29
+ }
30
+ }
31
+
32
+ RETURN_TYPES = ("CONTROL_NET", )
33
+ FUNCTION = "load_controlnet"
34
+
35
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
36
+
37
+ def load_controlnet(self, control_net_name,
38
+ timestep_keyframe: TimestepKeyframeGroup=None
39
+ ):
40
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
41
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe)
42
+ return (controlnet,)
43
+
44
+
45
+ class DiffControlNetLoaderAdvanced:
46
+ @classmethod
47
+ def INPUT_TYPES(s):
48
+ return {
49
+ "required": {
50
+ "model": ("MODEL",),
51
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )
52
+ },
53
+ "optional": {
54
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
55
+ }
56
+ }
57
+
58
+ RETURN_TYPES = ("CONTROL_NET", )
59
+ FUNCTION = "load_controlnet"
60
+
61
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
62
+
63
+ def load_controlnet(self, control_net_name, model,
64
+ timestep_keyframe: TimestepKeyframeGroup=None
65
+ ):
66
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
67
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe, model)
68
+ if is_advanced_controlnet(controlnet):
69
+ controlnet.verify_all_weights()
70
+ return (controlnet,)
71
+
72
+
73
+ class AdvancedControlNetApply:
74
+ @classmethod
75
+ def INPUT_TYPES(s):
76
+ return {
77
+ "required": {
78
+ "positive": ("CONDITIONING", ),
79
+ "negative": ("CONDITIONING", ),
80
+ "control_net": ("CONTROL_NET", ),
81
+ "image": ("IMAGE", ),
82
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
83
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
84
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
85
+ },
86
+ "optional": {
87
+ "mask_optional": ("MASK", ),
88
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
89
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
90
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
91
+ "model_optional": ("MODEL",),
92
+ "vae_optional": ("VAE",),
93
+ }
94
+ }
95
+
96
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING","MODEL",)
97
+ RETURN_NAMES = ("positive", "negative", "model_opt")
98
+ FUNCTION = "apply_controlnet"
99
+
100
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
101
+
102
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent,
103
+ mask_optional: Tensor=None, model_optional: ModelPatcher=None, vae_optional=None,
104
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override: LatentKeyframeGroup=None,
105
+ weights_override: ControlWeights=None):
106
+ if strength == 0:
107
+ return (positive, negative, model_optional)
108
+ if model_optional:
109
+ model_optional = model_optional.clone()
110
+
111
+ control_hint = image.movedim(-1,1)
112
+ cnets = {}
113
+
114
+ out = []
115
+ for conditioning in [positive, negative]:
116
+ c = []
117
+ for t in conditioning:
118
+ d = t[1].copy()
119
+
120
+ prev_cnet = d.get('control', None)
121
+ if prev_cnet in cnets:
122
+ c_net = cnets[prev_cnet]
123
+ else:
124
+ # copy, convert to advanced if needed, and set cond
125
+ c_net = convert_to_advanced(control_net.copy()).set_cond_hint(control_hint, strength, (start_percent, end_percent), vae_optional)
126
+ if is_advanced_controlnet(c_net):
127
+ # disarm node check
128
+ c_net.disarm()
129
+ # if model required, verify model is passed in, and if so patch it
130
+ if c_net.require_model:
131
+ if not model_optional:
132
+ raise Exception(f"Type '{type(c_net).__name__}' requires model_optional input, but got None.")
133
+ c_net.patch_model(model=model_optional)
134
+ # if vae required, verify vae is passed in
135
+ if c_net.require_vae:
136
+ # if controlnet can accept preprocced condhint latents and is the case, ignore vae requirement
137
+ if c_net.allow_condhint_latents and isinstance(control_hint, AbstractPreprocWrapper):
138
+ pass
139
+ elif not vae_optional:
140
+ # make sure SD3 ControlNet will get a special message instead of generic type mention
141
+ if is_sd3_advanced_controlnet:
142
+ raise Exception(f"SD3 ControlNet requires vae_optional input, but got None.")
143
+ else:
144
+ raise Exception(f"Type '{type(c_net).__name__}' requires vae_optional input, but got None.")
145
+ # apply optional parameters and overrides, if provided
146
+ if timestep_kf is not None:
147
+ c_net.set_timestep_keyframes(timestep_kf)
148
+ if latent_kf_override is not None:
149
+ c_net.latent_keyframe_override = latent_kf_override
150
+ if weights_override is not None:
151
+ c_net.weights_override = weights_override
152
+ # verify weights are compatible
153
+ c_net.verify_all_weights()
154
+ # set cond hint mask
155
+ if mask_optional is not None:
156
+ mask_optional = mask_optional.clone()
157
+ # if not in the form of a batch, make it so
158
+ if len(mask_optional.shape) < 3:
159
+ mask_optional = mask_optional.unsqueeze(0)
160
+ c_net.set_cond_hint_mask(mask_optional)
161
+ c_net.set_previous_controlnet(prev_cnet)
162
+ cnets[prev_cnet] = c_net
163
+
164
+ d['control'] = c_net
165
+ d['control_apply_to_uncond'] = False
166
+ n = [t[0], d]
167
+ c.append(n)
168
+ out.append(c)
169
+ return (out[0], out[1], model_optional)
170
+
171
+
172
+ # NODE MAPPING
173
+ NODE_CLASS_MAPPINGS = {
174
+ # Keyframes
175
+ "TimestepKeyframe": TimestepKeyframeNode,
176
+ "ACN_TimestepKeyframeInterpolation": TimestepKeyframeInterpolationNode,
177
+ "ACN_TimestepKeyframeFromStrengthList": TimestepKeyframeFromStrengthListNode,
178
+ "LatentKeyframe": LatentKeyframeNode,
179
+ "LatentKeyframeTiming": LatentKeyframeInterpolationNode,
180
+ "LatentKeyframeBatchedGroup": LatentKeyframeBatchedGroupNode,
181
+ "LatentKeyframeGroup": LatentKeyframeGroupNode,
182
+ # Conditioning
183
+ "ACN_AdvancedControlNetApply": AdvancedControlNetApply,
184
+ # Loaders
185
+ "ControlNetLoaderAdvanced": ControlNetLoaderAdvanced,
186
+ "DiffControlNetLoaderAdvanced": DiffControlNetLoaderAdvanced,
187
+ # Weights
188
+ "ScaledSoftControlNetWeights": ScaledSoftUniversalWeights,
189
+ "ScaledSoftMaskedUniversalWeights": ScaledSoftMaskedUniversalWeights,
190
+ "SoftControlNetWeights": SoftControlNetWeights,
191
+ "CustomControlNetWeights": CustomControlNetWeights,
192
+ "SoftT2IAdapterWeights": SoftT2IAdapterWeights,
193
+ "CustomT2IAdapterWeights": CustomT2IAdapterWeights,
194
+ "ACN_DefaultUniversalWeights": DefaultWeights,
195
+ # SparseCtrl
196
+ "ACN_SparseCtrlRGBPreprocessor": RgbSparseCtrlPreprocessor,
197
+ "ACN_SparseCtrlLoaderAdvanced": SparseCtrlLoaderAdvanced,
198
+ "ACN_SparseCtrlMergedLoaderAdvanced": SparseCtrlMergedLoaderAdvanced,
199
+ "ACN_SparseCtrlIndexMethodNode": SparseIndexMethodNode,
200
+ "ACN_SparseCtrlSpreadMethodNode": SparseSpreadMethodNode,
201
+ "ACN_SparseCtrlWeightExtras": SparseWeightExtras,
202
+ # Reference
203
+ "ACN_ReferencePreprocessor": ReferencePreprocessorNode,
204
+ "ACN_ReferenceControlNet": ReferenceControlNetNode,
205
+ "ACN_ReferenceControlNetFinetune": ReferenceControlFinetune,
206
+ # LOOSEControl
207
+ #"ACN_ControlNetLoaderWithLoraAdvanced": ControlNetLoaderWithLoraAdvanced,
208
+ # Deprecated
209
+ "LoadImagesFromDirectory": LoadImagesFromDirectory,
210
+ }
211
+
212
+ NODE_DISPLAY_NAME_MAPPINGS = {
213
+ # Keyframes
214
+ "TimestepKeyframe": "Timestep Keyframe 🛂🅐🅒🅝",
215
+ "ACN_TimestepKeyframeInterpolation": "Timestep Keyframe Interpolation 🛂🅐🅒🅝",
216
+ "ACN_TimestepKeyframeFromStrengthList": "Timestep Keyframe From List 🛂🅐🅒🅝",
217
+ "LatentKeyframe": "Latent Keyframe 🛂🅐🅒🅝",
218
+ "LatentKeyframeTiming": "Latent Keyframe Interpolation 🛂🅐🅒🅝",
219
+ "LatentKeyframeBatchedGroup": "Latent Keyframe From List 🛂🅐🅒🅝",
220
+ "LatentKeyframeGroup": "Latent Keyframe Group 🛂🅐🅒🅝",
221
+ # Conditioning
222
+ "ACN_AdvancedControlNetApply": "Apply Advanced ControlNet 🛂🅐🅒🅝",
223
+ # Loaders
224
+ "ControlNetLoaderAdvanced": "Load Advanced ControlNet Model 🛂🅐🅒🅝",
225
+ "DiffControlNetLoaderAdvanced": "Load Advanced ControlNet Model (diff) 🛂🅐🅒🅝",
226
+ # Weights
227
+ "ScaledSoftControlNetWeights": "Scaled Soft Weights 🛂🅐🅒🅝",
228
+ "ScaledSoftMaskedUniversalWeights": "Scaled Soft Masked Weights 🛂🅐🅒🅝",
229
+ "SoftControlNetWeights": "ControlNet Soft Weights 🛂🅐🅒🅝",
230
+ "CustomControlNetWeights": "ControlNet Custom Weights 🛂🅐🅒🅝",
231
+ "SoftT2IAdapterWeights": "T2IAdapter Soft Weights 🛂🅐🅒🅝",
232
+ "CustomT2IAdapterWeights": "T2IAdapter Custom Weights 🛂🅐🅒🅝",
233
+ "ACN_DefaultUniversalWeights": "Default Weights 🛂🅐🅒🅝",
234
+ # SparseCtrl
235
+ "ACN_SparseCtrlRGBPreprocessor": "RGB SparseCtrl 🛂🅐🅒🅝",
236
+ "ACN_SparseCtrlLoaderAdvanced": "Load SparseCtrl Model 🛂🅐🅒🅝",
237
+ "ACN_SparseCtrlMergedLoaderAdvanced": "🧪Load Merged SparseCtrl Model 🛂🅐🅒🅝",
238
+ "ACN_SparseCtrlIndexMethodNode": "SparseCtrl Index Method 🛂🅐🅒🅝",
239
+ "ACN_SparseCtrlSpreadMethodNode": "SparseCtrl Spread Method 🛂🅐🅒🅝",
240
+ "ACN_SparseCtrlWeightExtras": "SparseCtrl Weight Extras 🛂🅐🅒🅝",
241
+ # Reference
242
+ "ACN_ReferencePreprocessor": "Reference Preproccessor 🛂🅐🅒🅝",
243
+ "ACN_ReferenceControlNet": "Reference ControlNet 🛂🅐🅒🅝",
244
+ "ACN_ReferenceControlNetFinetune": "Reference ControlNet (Finetune) 🛂🅐🅒🅝",
245
+ # LOOSEControl
246
+ #"ACN_ControlNetLoaderWithLoraAdvanced": "Load Adv. ControlNet Model w/ LoRA 🛂🅐🅒🅝",
247
+ # Deprecated
248
+ "LoadImagesFromDirectory": "🚫Load Images [DEPRECATED] 🛂🅐🅒🅝",
249
+ }
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageOps
7
+ from .utils import BIGMAX
8
+ from .logger import logger
9
+
10
+
11
+ class LoadImagesFromDirectory:
12
+ @classmethod
13
+ def INPUT_TYPES(s):
14
+ return {
15
+ "required": {
16
+ "directory": ("STRING", {"default": ""}),
17
+ },
18
+ "optional": {
19
+ "image_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
20
+ "start_index": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
21
+ }
22
+ }
23
+
24
+ RETURN_TYPES = ("IMAGE", "MASK", "INT")
25
+ FUNCTION = "load_images"
26
+
27
+ CATEGORY = ""
28
+
29
+ def load_images(self, directory: str, image_load_cap: int = 0, start_index: int = 0):
30
+ if not os.path.isdir(directory):
31
+ raise FileNotFoundError(f"Directory '{directory} cannot be found.'")
32
+ dir_files = os.listdir(directory)
33
+ if len(dir_files) == 0:
34
+ raise FileNotFoundError(f"No files in directory '{directory}'.")
35
+
36
+ dir_files = sorted(dir_files)
37
+ dir_files = [os.path.join(directory, x) for x in dir_files]
38
+ # start at start_index
39
+ dir_files = dir_files[start_index:]
40
+
41
+ images = []
42
+ masks = []
43
+
44
+ limit_images = False
45
+ if image_load_cap > 0:
46
+ limit_images = True
47
+ image_count = 0
48
+
49
+ for image_path in dir_files:
50
+ if os.path.isdir(image_path):
51
+ continue
52
+ if limit_images and image_count >= image_load_cap:
53
+ break
54
+ i = Image.open(image_path)
55
+ i = ImageOps.exif_transpose(i)
56
+ image = i.convert("RGB")
57
+ image = np.array(image).astype(np.float32) / 255.0
58
+ image = torch.from_numpy(image)[None,]
59
+ if 'A' in i.getbands():
60
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
61
+ mask = 1. - torch.from_numpy(mask)
62
+ else:
63
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
64
+ images.append(image)
65
+ masks.append(mask)
66
+ image_count += 1
67
+
68
+ if len(images) == 0:
69
+ raise FileNotFoundError(f"No images could be loaded from directory '{directory}'.")
70
+
71
+ return (torch.cat(images, dim=0), torch.stack(masks, dim=0), image_count)
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import numpy as np
3
+ from collections.abc import Iterable
4
+
5
+ from .utils import ControlWeights, TimestepKeyframe, TimestepKeyframeGroup, LatentKeyframe, LatentKeyframeGroup, BIGMIN, BIGMAX
6
+ from .utils import StrengthInterpolation as SI
7
+ from .logger import logger
8
+
9
+
10
+ class TimestepKeyframeNode:
11
+ OUTDATED_DUMMY = -39
12
+
13
+ @classmethod
14
+ def INPUT_TYPES(s):
15
+ return {
16
+ "required": {
17
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
18
+ },
19
+ "optional": {
20
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
21
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
22
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
23
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
24
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
25
+ "inherit_missing": ("BOOLEAN", {"default": True}, ),
26
+ "guarantee_steps": ("INT", {"default": 1, "min": 0, "max": BIGMAX}),
27
+ "mask_optional": ("MASK", ),
28
+ }
29
+ }
30
+
31
+ RETURN_NAMES = ("TIMESTEP_KF", )
32
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
33
+ FUNCTION = "load_keyframe"
34
+
35
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
36
+
37
+ def load_keyframe(self,
38
+ start_percent: float,
39
+ strength: float=1.0,
40
+ cn_weights: ControlWeights=None, control_net_weights: ControlWeights=None, # old name
41
+ latent_keyframe: LatentKeyframeGroup=None,
42
+ prev_timestep_kf: TimestepKeyframeGroup=None, prev_timestep_keyframe: TimestepKeyframeGroup=None, # old name
43
+ null_latent_kf_strength: float=0.0,
44
+ inherit_missing=True,
45
+ guarantee_steps=OUTDATED_DUMMY,
46
+ guarantee_usage=True, # old input
47
+ mask_optional=None,):
48
+ # if using outdated dummy value, means node on workflow is outdated and should appropriately convert behavior
49
+ if guarantee_steps == self.OUTDATED_DUMMY:
50
+ guarantee_steps = int(guarantee_usage)
51
+ control_net_weights = control_net_weights if control_net_weights else cn_weights
52
+ prev_timestep_keyframe = prev_timestep_keyframe if prev_timestep_keyframe else prev_timestep_kf
53
+ if not prev_timestep_keyframe:
54
+ prev_timestep_keyframe = TimestepKeyframeGroup()
55
+ else:
56
+ prev_timestep_keyframe = prev_timestep_keyframe.clone()
57
+ keyframe = TimestepKeyframe(start_percent=start_percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
58
+ control_weights=control_net_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
59
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional)
60
+ prev_timestep_keyframe.add(keyframe)
61
+ return (prev_timestep_keyframe,)
62
+
63
+
64
+ class TimestepKeyframeInterpolationNode:
65
+ @classmethod
66
+ def INPUT_TYPES(s):
67
+ return {
68
+ "required": {
69
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
70
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
71
+ "strength_start": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
72
+ "strength_end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
73
+ "interpolation": (SI._LIST, ),
74
+ "intervals": ("INT", {"default": 50, "min": 2, "max": 100, "step": 1}),
75
+ },
76
+ "optional": {
77
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
78
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
79
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
80
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
81
+ "inherit_missing": ("BOOLEAN", {"default": True},),
82
+ "mask_optional": ("MASK", ),
83
+ "print_keyframes": ("BOOLEAN", {"default": False}),
84
+ }
85
+ }
86
+
87
+ RETURN_NAMES = ("TIMESTEP_KF", )
88
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
89
+ FUNCTION = "load_keyframe"
90
+
91
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
92
+
93
+ def load_keyframe(self,
94
+ start_percent: float, end_percent: float,
95
+ strength_start: float, strength_end: float, interpolation: str, intervals: int,
96
+ cn_weights: ControlWeights=None,
97
+ latent_keyframe: LatentKeyframeGroup=None,
98
+ prev_timestep_kf: TimestepKeyframeGroup=None,
99
+ null_latent_kf_strength: float=0.0,
100
+ inherit_missing=True,
101
+ guarantee_steps=1,
102
+ mask_optional=None, print_keyframes=False):
103
+ if not prev_timestep_kf:
104
+ prev_timestep_kf = TimestepKeyframeGroup()
105
+ else:
106
+ prev_timestep_kf = prev_timestep_kf.clone()
107
+
108
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=intervals, method=SI.LINEAR)
109
+ strengths = SI.get_weights(num_from=strength_start, num_to=strength_end, length=intervals, method=interpolation)
110
+
111
+ is_first = True
112
+ for percent, strength in zip(percents, strengths):
113
+ guarantee_steps = 0
114
+ if is_first:
115
+ guarantee_steps = 1
116
+ is_first = False
117
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
118
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
119
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
120
+ if print_keyframes:
121
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
122
+ return (prev_timestep_kf,)
123
+
124
+
125
+ class TimestepKeyframeFromStrengthListNode:
126
+ @classmethod
127
+ def INPUT_TYPES(s):
128
+ return {
129
+ "required": {
130
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
131
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
132
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
133
+ },
134
+ "optional": {
135
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
136
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
137
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
138
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
139
+ "inherit_missing": ("BOOLEAN", {"default": True},),
140
+ "mask_optional": ("MASK", ),
141
+ "print_keyframes": ("BOOLEAN", {"default": False}),
142
+ }
143
+ }
144
+
145
+ RETURN_NAMES = ("TIMESTEP_KF", )
146
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
147
+ FUNCTION = "load_keyframe"
148
+
149
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
150
+
151
+ def load_keyframe(self,
152
+ start_percent: float, end_percent: float,
153
+ float_strengths: float,
154
+ cn_weights: ControlWeights=None,
155
+ latent_keyframe: LatentKeyframeGroup=None,
156
+ prev_timestep_kf: TimestepKeyframeGroup=None,
157
+ null_latent_kf_strength: float=0.0,
158
+ inherit_missing=True,
159
+ guarantee_steps=1,
160
+ mask_optional=None, print_keyframes=False):
161
+ if not prev_timestep_kf:
162
+ prev_timestep_kf = TimestepKeyframeGroup()
163
+ else:
164
+ prev_timestep_kf = prev_timestep_kf.clone()
165
+
166
+ if type(float_strengths) in (float, int):
167
+ float_strengths = [float(float_strengths)]
168
+ elif isinstance(float_strengths, Iterable):
169
+ pass
170
+ else:
171
+ raise Exception(f"strengths_float must be either an iterable input or a float, but was {type(float_strengths).__repr__}.")
172
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=len(float_strengths), method=SI.LINEAR)
173
+
174
+ is_first = True
175
+ for percent, strength in zip(percents, float_strengths):
176
+ guarantee_steps = 0
177
+ if is_first:
178
+ guarantee_steps = 1
179
+ is_first = False
180
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
181
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
182
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
183
+ if print_keyframes:
184
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
185
+ return (prev_timestep_kf,)
186
+
187
+
188
+ class LatentKeyframeNode:
189
+ @classmethod
190
+ def INPUT_TYPES(s):
191
+ return {
192
+ "required": {
193
+ "batch_index": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
194
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
195
+ },
196
+ "optional": {
197
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
198
+ }
199
+ }
200
+
201
+ RETURN_NAMES = ("LATENT_KF", )
202
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
203
+ FUNCTION = "load_keyframe"
204
+
205
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
206
+
207
+ def load_keyframe(self,
208
+ batch_index: int,
209
+ strength: float,
210
+ prev_latent_kf: LatentKeyframeGroup=None,
211
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
212
+ ):
213
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
214
+ if not prev_latent_keyframe:
215
+ prev_latent_keyframe = LatentKeyframeGroup()
216
+ else:
217
+ prev_latent_keyframe = prev_latent_keyframe.clone()
218
+ keyframe = LatentKeyframe(batch_index, strength)
219
+ prev_latent_keyframe.add(keyframe)
220
+ return (prev_latent_keyframe,)
221
+
222
+
223
+ class LatentKeyframeGroupNode:
224
+ @classmethod
225
+ def INPUT_TYPES(s):
226
+ return {
227
+ "required": {
228
+ "index_strengths": ("STRING", {"multiline": True, "default": ""}),
229
+ },
230
+ "optional": {
231
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
232
+ "latent_optional": ("LATENT", ),
233
+ "print_keyframes": ("BOOLEAN", {"default": False})
234
+ }
235
+ }
236
+
237
+ RETURN_NAMES = ("LATENT_KF", )
238
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
239
+ FUNCTION = "load_keyframes"
240
+
241
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
242
+
243
+ def validate_index(self, index: int, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
244
+ # if part of range, do nothing
245
+ if is_range:
246
+ return index
247
+ # otherwise, validate index
248
+ # validate not out of range - only when latent_count is passed in
249
+ if latent_count > 0 and index > latent_count-1:
250
+ raise IndexError(f"Index '{index}' out of range for the total {latent_count} latents.")
251
+ # if negative, validate not out of range
252
+ if index < 0:
253
+ if not allow_negative:
254
+ raise IndexError(f"Negative indeces not allowed, but was {index}.")
255
+ conv_index = latent_count+index
256
+ if conv_index < 0:
257
+ raise IndexError(f"Index '{index}', converted to '{conv_index}' out of range for the total {latent_count} latents.")
258
+ index = conv_index
259
+ return index
260
+
261
+ def convert_to_index_int(self, raw_index: str, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
262
+ try:
263
+ return self.validate_index(int(raw_index), latent_count=latent_count, is_range=is_range, allow_negative=allow_negative)
264
+ except ValueError as e:
265
+ raise ValueError(f"index '{raw_index}' must be an integer.", e)
266
+
267
+ def convert_to_latent_keyframes(self, latent_indeces: str, latent_count: int) -> set[LatentKeyframe]:
268
+ if not latent_indeces:
269
+ return set()
270
+ int_latent_indeces = [i for i in range(0, latent_count)]
271
+ allow_negative = latent_count > 0
272
+ chosen_indeces = set()
273
+ # parse string - allow positive ints, negative ints, and ranges separated by ':'
274
+ groups = latent_indeces.split(",")
275
+ groups = [g.strip() for g in groups]
276
+ for g in groups:
277
+ # parse strengths - default to 1.0 if no strength given
278
+ strength = 1.0
279
+ if '=' in g:
280
+ g, strength_str = g.split("=", 1)
281
+ g = g.strip()
282
+ try:
283
+ strength = float(strength_str.strip())
284
+ except ValueError as e:
285
+ raise ValueError(f"strength '{strength_str}' must be a float.", e)
286
+ if strength < 0:
287
+ raise ValueError(f"Strength '{strength}' cannot be negative.")
288
+ # parse range of indeces (e.g. 2:16)
289
+ if ':' in g:
290
+ index_range = g.split(":", 1)
291
+ index_range = [r.strip() for r in index_range]
292
+ start_index = self.convert_to_index_int(index_range[0], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
293
+ end_index = self.convert_to_index_int(index_range[1], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
294
+ # if latents were passed in, base indeces on known latent count
295
+ if len(int_latent_indeces) > 0:
296
+ for i in int_latent_indeces[start_index:end_index]:
297
+ chosen_indeces.add(LatentKeyframe(i, strength))
298
+ # otherwise, assume indeces are valid
299
+ else:
300
+ for i in range(start_index, end_index):
301
+ chosen_indeces.add(LatentKeyframe(i, strength))
302
+ # parse individual indeces
303
+ else:
304
+ chosen_indeces.add(LatentKeyframe(self.convert_to_index_int(g, latent_count=latent_count, allow_negative=allow_negative), strength))
305
+ return chosen_indeces
306
+
307
+ def load_keyframes(self,
308
+ index_strengths: str,
309
+ prev_latent_kf: LatentKeyframeGroup=None,
310
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
311
+ latent_image_opt=None,
312
+ print_keyframes=False):
313
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
314
+ if not prev_latent_keyframe:
315
+ prev_latent_keyframe = LatentKeyframeGroup()
316
+ else:
317
+ prev_latent_keyframe = prev_latent_keyframe.clone()
318
+ curr_latent_keyframe = LatentKeyframeGroup()
319
+
320
+ latent_count = -1
321
+ if latent_image_opt:
322
+ latent_count = latent_image_opt['samples'].size()[0]
323
+ latent_keyframes = self.convert_to_latent_keyframes(index_strengths, latent_count=latent_count)
324
+
325
+ for latent_keyframe in latent_keyframes:
326
+ curr_latent_keyframe.add(latent_keyframe)
327
+
328
+ if print_keyframes:
329
+ for keyframe in curr_latent_keyframe.keyframes:
330
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
331
+
332
+ # replace values with prev_latent_keyframes
333
+ for latent_keyframe in prev_latent_keyframe.keyframes:
334
+ curr_latent_keyframe.add(latent_keyframe)
335
+
336
+ return (curr_latent_keyframe,)
337
+
338
+
339
+ class LatentKeyframeInterpolationNode:
340
+ @classmethod
341
+ def INPUT_TYPES(s):
342
+ return {
343
+ "required": {
344
+ "batch_index_from": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
345
+ "batch_index_to_excl": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
346
+ "strength_from": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
347
+ "strength_to": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
348
+ "interpolation": (SI._LIST, ),
349
+ },
350
+ "optional": {
351
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
352
+ "print_keyframes": ("BOOLEAN", {"default": False})
353
+ }
354
+ }
355
+
356
+ RETURN_NAMES = ("LATENT_KF", )
357
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
358
+ FUNCTION = "load_keyframe"
359
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
360
+
361
+ def load_keyframe(self,
362
+ batch_index_from: int,
363
+ strength_from: float,
364
+ batch_index_to_excl: int,
365
+ strength_to: float,
366
+ interpolation: str,
367
+ prev_latent_kf: LatentKeyframeGroup=None,
368
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
369
+ print_keyframes=False):
370
+
371
+ if (batch_index_from > batch_index_to_excl):
372
+ raise ValueError("batch_index_from must be less than or equal to batch_index_to.")
373
+
374
+ if (batch_index_from < 0 and batch_index_to_excl >= 0):
375
+ raise ValueError("batch_index_from and batch_index_to must be either both positive or both negative.")
376
+
377
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
378
+ if not prev_latent_keyframe:
379
+ prev_latent_keyframe = LatentKeyframeGroup()
380
+ else:
381
+ prev_latent_keyframe = prev_latent_keyframe.clone()
382
+ curr_latent_keyframe = LatentKeyframeGroup()
383
+
384
+ steps = batch_index_to_excl - batch_index_from
385
+ diff = strength_to - strength_from
386
+ if interpolation == SI.LINEAR:
387
+ weights = np.linspace(strength_from, strength_to, steps)
388
+ elif interpolation == SI.EASE_IN:
389
+ index = np.linspace(0, 1, steps)
390
+ weights = diff * np.power(index, 2) + strength_from
391
+ elif interpolation == SI.EASE_OUT:
392
+ index = np.linspace(0, 1, steps)
393
+ weights = diff * (1 - np.power(1 - index, 2)) + strength_from
394
+ elif interpolation == SI.EASE_IN_OUT:
395
+ index = np.linspace(0, 1, steps)
396
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + strength_from
397
+
398
+ for i in range(steps):
399
+ keyframe = LatentKeyframe(batch_index_from + i, float(weights[i]))
400
+ curr_latent_keyframe.add(keyframe)
401
+
402
+ if print_keyframes:
403
+ for keyframe in curr_latent_keyframe.keyframes:
404
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
405
+
406
+ # replace values with prev_latent_keyframes
407
+ for latent_keyframe in prev_latent_keyframe.keyframes:
408
+ curr_latent_keyframe.add(latent_keyframe)
409
+
410
+ return (curr_latent_keyframe,)
411
+
412
+
413
+ class LatentKeyframeBatchedGroupNode:
414
+ @classmethod
415
+ def INPUT_TYPES(s):
416
+ return {
417
+ "required": {
418
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
419
+ },
420
+ "optional": {
421
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
422
+ "print_keyframes": ("BOOLEAN", {"default": False})
423
+ }
424
+ }
425
+
426
+ RETURN_NAMES = ("LATENT_KF", )
427
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
428
+ FUNCTION = "load_keyframe"
429
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
430
+
431
+ def load_keyframe(self, float_strengths: Union[float, list[float]],
432
+ prev_latent_kf: LatentKeyframeGroup=None,
433
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
434
+ print_keyframes=False):
435
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
436
+ if not prev_latent_keyframe:
437
+ prev_latent_keyframe = LatentKeyframeGroup()
438
+ else:
439
+ prev_latent_keyframe = prev_latent_keyframe.clone()
440
+ curr_latent_keyframe = LatentKeyframeGroup()
441
+
442
+ # if received a normal float input, do nothing
443
+ if type(float_strengths) in (float, int):
444
+ logger.info("No batched float_strengths passed into Latent Keyframe Batch Group node; will not create any new keyframes.")
445
+ # if iterable, attempt to create LatentKeyframes with chosen strengths
446
+ elif isinstance(float_strengths, Iterable):
447
+ for idx, strength in enumerate(float_strengths):
448
+ keyframe = LatentKeyframe(idx, strength)
449
+ curr_latent_keyframe.add(keyframe)
450
+ else:
451
+ raise ValueError(f"Expected strengths to be an iterable input, but was {type(float_strengths).__repr__}.")
452
+
453
+ if print_keyframes:
454
+ for keyframe in curr_latent_keyframe.keyframes:
455
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
456
+
457
+ # replace values with prev_latent_keyframes
458
+ for latent_keyframe in prev_latent_keyframe.keyframes:
459
+ curr_latent_keyframe.add(latent_keyframe)
460
+
461
+ return (curr_latent_keyframe,)
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_loosecontrol.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import folder_paths
2
+ import comfy.utils
3
+ import comfy.model_detection
4
+ import comfy.model_management
5
+ import comfy.lora
6
+ from comfy.model_patcher import ModelPatcher
7
+
8
+ from .utils import TimestepKeyframeGroup
9
+ from .control import ControlNetAdvanced, load_controlnet
10
+
11
+
12
+
13
+
14
+ def convert_cn_lora_from_diffusers(cn_model: ModelPatcher, lora_path: str):
15
+ lora_data = comfy.utils.load_torch_file(lora_path, safe_load=True)
16
+ unet_dtype = comfy.model_management.unet_dtype()
17
+ for key, value in lora_data.items():
18
+ lora_data[key] = value.to(unet_dtype)
19
+ diffusers_keys = comfy.utils.unet_to_diffusers(cn_model.model.state_dict())
20
+
21
+ #lora_data = comfy.model_detection.unet_config_from_diffusers_unet(lora_data, dtype=unet_dtype)
22
+
23
+
24
+
25
+ #key_map = comfy.lora.model_lora_keys_unet(cn_model.model, key_map)
26
+ lora_data = comfy.lora.load_lora(lora_data, to_load=diffusers_keys)
27
+
28
+ # TODO: detect if diffusers for sure? not sure if needed at this time, since cn loras are
29
+ # only used currently for LOOSEControl, and those are all in diffusers format
30
+ #unet_dtype = comfy.model_management.unet_dtype()
31
+ #lora_data = comfy.model_detection.unet_config_from_diffusers_unet(lora_data, unet_dtype)
32
+ return lora_data
33
+
34
+
35
+ class ControlNetLoaderWithLoraAdvanced:
36
+ @classmethod
37
+ def INPUT_TYPES(s):
38
+ return {
39
+ "required": {
40
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
41
+ "cn_lora_name": (folder_paths.get_filename_list("controlnet"), ),
42
+ "cn_lora_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
43
+ },
44
+ "optional": {
45
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
46
+ }
47
+ }
48
+
49
+ RETURN_TYPES = ("CONTROL_NET", )
50
+ FUNCTION = "load_controlnet"
51
+
52
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/LOOSEControl"
53
+
54
+ def load_controlnet(self, control_net_name, cn_lora_name, cn_lora_strength: float,
55
+ timestep_keyframe: TimestepKeyframeGroup=None
56
+ ):
57
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
58
+ controlnet: ControlNetAdvanced = load_controlnet(controlnet_path, timestep_keyframe)
59
+ if not isinstance(controlnet, ControlNetAdvanced):
60
+ raise ValueError("Type {} is not compatible with CN LoRA features at this time.")
61
+ # now, try to load CN LoRA
62
+ lora_path = folder_paths.get_full_path("controlnet", cn_lora_name)
63
+ lora_data = convert_cn_lora_from_diffusers(cn_model=controlnet.control_model_wrapped, lora_path=lora_path)
64
+ # apply patches to wrapped control_model
65
+ controlnet.control_model_wrapped.add_patches(lora_data, strength_patch=cn_lora_strength)
66
+ # all done
67
+ return (controlnet,)
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_reference.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ from nodes import VAEEncode
4
+ import comfy.utils
5
+ from comfy.sd import VAE
6
+
7
+ from .control_reference import ReferenceAdvanced, ReferenceOptions, ReferenceType, ReferencePreprocWrapper
8
+
9
+
10
+ # node for ReferenceCN
11
+ class ReferenceControlNetNode:
12
+ @classmethod
13
+ def INPUT_TYPES(s):
14
+ return {
15
+ "required": {
16
+ "reference_type": (ReferenceType._LIST,),
17
+ "style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
18
+ "ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
19
+ },
20
+ }
21
+
22
+ RETURN_TYPES = ("CONTROL_NET", )
23
+ FUNCTION = "load_controlnet"
24
+
25
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference"
26
+
27
+ def load_controlnet(self, reference_type: str, style_fidelity: float, ref_weight: float):
28
+ ref_opts = ReferenceOptions.create_combo(reference_type=reference_type, style_fidelity=style_fidelity, ref_weight=ref_weight)
29
+ controlnet = ReferenceAdvanced(ref_opts=ref_opts, timestep_keyframes=None)
30
+ return (controlnet,)
31
+
32
+
33
+ class ReferenceControlFinetune:
34
+ @classmethod
35
+ def INPUT_TYPES(s):
36
+ return {
37
+ "required": {
38
+ "attn_style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
39
+ "attn_ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
40
+ "attn_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
41
+ "adain_style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
42
+ "adain_ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
43
+ "adain_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
44
+ },
45
+ }
46
+
47
+ RETURN_TYPES = ("CONTROL_NET", )
48
+ FUNCTION = "load_controlnet"
49
+
50
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference"
51
+
52
+ def load_controlnet(self,
53
+ attn_style_fidelity: float, attn_ref_weight: float, attn_strength: float,
54
+ adain_style_fidelity: float, adain_ref_weight: float, adain_strength: float):
55
+ ref_opts = ReferenceOptions(reference_type=ReferenceType.ATTN_ADAIN,
56
+ attn_style_fidelity=attn_style_fidelity, attn_ref_weight=attn_ref_weight, attn_strength=attn_strength,
57
+ adain_style_fidelity=adain_style_fidelity, adain_ref_weight=adain_ref_weight, adain_strength=adain_strength)
58
+ controlnet = ReferenceAdvanced(ref_opts=ref_opts, timestep_keyframes=None)
59
+ return (controlnet,)
60
+
61
+
62
+ class ReferencePreprocessorNode:
63
+ @classmethod
64
+ def INPUT_TYPES(s):
65
+ return {
66
+ "required": {
67
+ "image": ("IMAGE", ),
68
+ "vae": ("VAE", ),
69
+ "latent_size": ("LATENT", ),
70
+ }
71
+ }
72
+
73
+ RETURN_TYPES = ("IMAGE",)
74
+ RETURN_NAMES = ("proc_IMAGE",)
75
+ FUNCTION = "preprocess_images"
76
+
77
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference/preprocess"
78
+
79
+ def preprocess_images(self, vae: VAE, image: Tensor, latent_size: Tensor):
80
+ # first, resize image to match latents
81
+ image = image.movedim(-1,1)
82
+ image = comfy.utils.common_upscale(image, latent_size["samples"].shape[3] * 8, latent_size["samples"].shape[2] * 8, 'nearest-exact', "center")
83
+ image = image.movedim(1,-1)
84
+ # then, vae encode
85
+ try:
86
+ image = vae.vae_encode_crop_pixels(image)
87
+ except Exception:
88
+ image = VAEEncode.vae_encode_crop_pixels(image)
89
+ encoded = vae.encode(image[:,:,:,:3])
90
+ return (ReferencePreprocWrapper(condhint=encoded),)
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_sparsectrl.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ import folder_paths
4
+ from nodes import VAEEncode
5
+ import comfy.utils
6
+ from comfy.sd import VAE
7
+
8
+ from .utils import TimestepKeyframeGroup
9
+ from .control_sparsectrl import SparseMethod, SparseIndexMethod, SparseSettings, SparseSpreadMethod, PreprocSparseRGBWrapper, SparseConst, SparseContextAware, get_idx_list_from_str
10
+ from .control import load_sparsectrl, load_controlnet, ControlNetAdvanced, SparseCtrlAdvanced
11
+
12
+
13
+ # node for SparseCtrl loading
14
+ class SparseCtrlLoaderAdvanced:
15
+ @classmethod
16
+ def INPUT_TYPES(s):
17
+ return {
18
+ "required": {
19
+ "sparsectrl_name": (folder_paths.get_filename_list("controlnet"), ),
20
+ "use_motion": ("BOOLEAN", {"default": True}, ),
21
+ "motion_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
22
+ "motion_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
23
+ },
24
+ "optional": {
25
+ "sparse_method": ("SPARSE_METHOD", ),
26
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
27
+ "context_aware": (SparseContextAware.LIST, ),
28
+ "sparse_hint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
29
+ "sparse_nonhint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
30
+ "sparse_mask_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
31
+ }
32
+ }
33
+
34
+ RETURN_TYPES = ("CONTROL_NET", )
35
+ FUNCTION = "load_controlnet"
36
+
37
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
38
+
39
+ def load_controlnet(self, sparsectrl_name: str, use_motion: bool, motion_strength: float, motion_scale: float, sparse_method: SparseMethod=SparseSpreadMethod(), tk_optional: TimestepKeyframeGroup=None,
40
+ context_aware=SparseContextAware.NEAREST_HINT, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, sparse_mask_mult=1.0):
41
+ sparsectrl_path = folder_paths.get_full_path("controlnet", sparsectrl_name)
42
+ sparse_settings = SparseSettings(sparse_method=sparse_method, use_motion=use_motion, motion_strength=motion_strength, motion_scale=motion_scale,
43
+ context_aware=context_aware,
44
+ sparse_mask_mult=sparse_mask_mult, sparse_hint_mult=sparse_hint_mult, sparse_nonhint_mult=sparse_nonhint_mult)
45
+ sparsectrl = load_sparsectrl(sparsectrl_path, timestep_keyframe=tk_optional, sparse_settings=sparse_settings)
46
+ return (sparsectrl,)
47
+
48
+
49
+ class SparseCtrlMergedLoaderAdvanced:
50
+ @classmethod
51
+ def INPUT_TYPES(s):
52
+ return {
53
+ "required": {
54
+ "sparsectrl_name": (folder_paths.get_filename_list("controlnet"), ),
55
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
56
+ "use_motion": ("BOOLEAN", {"default": True}, ),
57
+ "motion_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
58
+ "motion_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
59
+ },
60
+ "optional": {
61
+ "sparse_method": ("SPARSE_METHOD", ),
62
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
63
+ }
64
+ }
65
+
66
+ RETURN_TYPES = ("CONTROL_NET", )
67
+ FUNCTION = "load_controlnet"
68
+
69
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/experimental"
70
+
71
+ def load_controlnet(self, sparsectrl_name: str, control_net_name: str, use_motion: bool, motion_strength: float, motion_scale: float, sparse_method: SparseMethod=SparseSpreadMethod(), tk_optional: TimestepKeyframeGroup=None):
72
+ sparsectrl_path = folder_paths.get_full_path("controlnet", sparsectrl_name)
73
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
74
+ sparse_settings = SparseSettings(sparse_method=sparse_method, use_motion=use_motion, motion_strength=motion_strength, motion_scale=motion_scale, merged=True)
75
+ # first, load normal controlnet
76
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe=tk_optional)
77
+ # confirm that controlnet is ControlNetAdvanced
78
+ if controlnet is None or type(controlnet) != ControlNetAdvanced:
79
+ raise ValueError(f"controlnet_path must point to a normal ControlNet, but instead: {type(controlnet).__name__}")
80
+ # next, load sparsectrl, making sure to load motion portion
81
+ sparsectrl = load_sparsectrl(sparsectrl_path, timestep_keyframe=tk_optional, sparse_settings=SparseSettings.default())
82
+ # now, combine state dicts
83
+ new_state_dict = controlnet.control_model.state_dict()
84
+ for key, value in sparsectrl.control_model.motion_holder.motion_wrapper.state_dict().items():
85
+ new_state_dict[key] = value
86
+ # now, reload sparsectrl with real settings
87
+ sparsectrl = load_sparsectrl(sparsectrl_path, controlnet_data=new_state_dict, timestep_keyframe=tk_optional, sparse_settings=sparse_settings)
88
+ return (sparsectrl,)
89
+
90
+
91
+ class SparseIndexMethodNode:
92
+ @classmethod
93
+ def INPUT_TYPES(s):
94
+ return {
95
+ "required": {
96
+ "indexes": ("STRING", {"default": "0"}),
97
+ }
98
+ }
99
+
100
+ RETURN_TYPES = ("SPARSE_METHOD",)
101
+ FUNCTION = "get_method"
102
+
103
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
104
+
105
+ def get_method(self, indexes: str):
106
+ idxs = get_idx_list_from_str(indexes)
107
+ return (SparseIndexMethod(idxs),)
108
+
109
+
110
+ class SparseSpreadMethodNode:
111
+ @classmethod
112
+ def INPUT_TYPES(s):
113
+ return {
114
+ "required": {
115
+ "spread": (SparseSpreadMethod.LIST,),
116
+ }
117
+ }
118
+
119
+ RETURN_TYPES = ("SPARSE_METHOD",)
120
+ FUNCTION = "get_method"
121
+
122
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
123
+
124
+ def get_method(self, spread: str):
125
+ return (SparseSpreadMethod(spread=spread),)
126
+
127
+
128
+ class RgbSparseCtrlPreprocessor:
129
+ @classmethod
130
+ def INPUT_TYPES(s):
131
+ return {
132
+ "required": {
133
+ "image": ("IMAGE", ),
134
+ "vae": ("VAE", ),
135
+ "latent_size": ("LATENT", ),
136
+ }
137
+ }
138
+
139
+ RETURN_TYPES = ("IMAGE",)
140
+ RETURN_NAMES = ("proc_IMAGE",)
141
+ FUNCTION = "preprocess_images"
142
+
143
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/preprocess"
144
+
145
+ def preprocess_images(self, vae: VAE, image: Tensor, latent_size: Tensor):
146
+ # first, resize image to match latents
147
+ image = image.movedim(-1,1)
148
+ image = comfy.utils.common_upscale(image, latent_size["samples"].shape[3] * 8, latent_size["samples"].shape[2] * 8, 'nearest-exact', "center")
149
+ image = image.movedim(1,-1)
150
+ # then, vae encode
151
+ try:
152
+ image = vae.vae_encode_crop_pixels(image)
153
+ except Exception:
154
+ image = VAEEncode.vae_encode_crop_pixels(image)
155
+ encoded = vae.encode(image[:,:,:,:3])
156
+ return (PreprocSparseRGBWrapper(condhint=encoded),)
157
+
158
+
159
+ class SparseWeightExtras:
160
+ @classmethod
161
+ def INPUT_TYPES(s):
162
+ return {
163
+ "optional": {
164
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
165
+ "sparse_hint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
166
+ "sparse_nonhint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
167
+ "sparse_mask_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
168
+ }
169
+ }
170
+
171
+ RETURN_TYPES = ("CN_WEIGHTS_EXTRAS", )
172
+ RETURN_NAMES = ("cn_extras", )
173
+ FUNCTION = "create_weight_extras"
174
+
175
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/extras"
176
+
177
+ def create_weight_extras(self, cn_extras: dict[str]={}, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, sparse_mask_mult=1.0):
178
+ cn_extras = cn_extras.copy()
179
+ cn_extras[SparseConst.HINT_MULT] = sparse_hint_mult
180
+ cn_extras[SparseConst.NONHINT_MULT] = sparse_nonhint_mult
181
+ cn_extras[SparseConst.MASK_MULT] = sparse_mask_mult
182
+ return (cn_extras, )
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+ import torch
3
+ from .utils import TimestepKeyframe, TimestepKeyframeGroup, ControlWeights, get_properly_arranged_t2i_weights, linear_conversion
4
+ from .logger import logger
5
+
6
+
7
+ WEIGHTS_RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
8
+
9
+
10
+ class DefaultWeights:
11
+ @classmethod
12
+ def INPUT_TYPES(s):
13
+ return {
14
+ "optional": {
15
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
16
+ }
17
+ }
18
+
19
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
20
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
21
+ FUNCTION = "load_weights"
22
+
23
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
24
+
25
+ def load_weights(self, cn_extras: dict[str]={}):
26
+ weights = ControlWeights.default(extras=cn_extras)
27
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
28
+
29
+
30
+ class ScaledSoftMaskedUniversalWeights:
31
+ @classmethod
32
+ def INPUT_TYPES(s):
33
+ return {
34
+ "required": {
35
+ "mask": ("MASK", ),
36
+ "min_base_multiplier": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
37
+ "max_base_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
38
+ #"lock_min": ("BOOLEAN", {"default": False}, ),
39
+ #"lock_max": ("BOOLEAN", {"default": False}, ),
40
+ },
41
+ "optional": {
42
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
43
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
44
+ }
45
+ }
46
+
47
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
48
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
49
+ FUNCTION = "load_weights"
50
+
51
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
52
+
53
+ def load_weights(self, mask: Tensor, min_base_multiplier: float, max_base_multiplier: float, lock_min=False, lock_max=False,
54
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
55
+ # normalize mask
56
+ mask = mask.clone()
57
+ x_min = 0.0 if lock_min else mask.min()
58
+ x_max = 1.0 if lock_max else mask.max()
59
+ if x_min == x_max:
60
+ mask = torch.ones_like(mask) * max_base_multiplier
61
+ else:
62
+ mask = linear_conversion(mask, x_min, x_max, min_base_multiplier, max_base_multiplier)
63
+ weights = ControlWeights.universal_mask(weight_mask=mask, uncond_multiplier=uncond_multiplier, extras=cn_extras)
64
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
65
+
66
+
67
+ class ScaledSoftUniversalWeights:
68
+ @classmethod
69
+ def INPUT_TYPES(s):
70
+ return {
71
+ "required": {
72
+ "base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
73
+ "flip_weights": ("BOOLEAN", {"default": False}),
74
+ },
75
+ "optional": {
76
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
77
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
78
+ }
79
+ }
80
+
81
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
82
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
83
+ FUNCTION = "load_weights"
84
+
85
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
86
+
87
+ def load_weights(self, base_multiplier, flip_weights, uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
88
+ weights = ControlWeights.universal(base_multiplier=base_multiplier, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
89
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
90
+
91
+
92
+ class SoftControlNetWeights:
93
+ @classmethod
94
+ def INPUT_TYPES(s):
95
+ return {
96
+ "required": {
97
+ "weight_00": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
98
+ "weight_01": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
99
+ "weight_02": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
100
+ "weight_03": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
101
+ "weight_04": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
102
+ "weight_05": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
103
+ "weight_06": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
104
+ "weight_07": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
105
+ "weight_08": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
106
+ "weight_09": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
107
+ "weight_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
108
+ "weight_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
109
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
110
+ "flip_weights": ("BOOLEAN", {"default": False}),
111
+ },
112
+ "optional": {
113
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
114
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
115
+ }
116
+ }
117
+
118
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
119
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
120
+ FUNCTION = "load_weights"
121
+
122
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
123
+
124
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
125
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
126
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
127
+ weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
128
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
129
+ weights = ControlWeights.controlnet(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
130
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
131
+
132
+
133
+ class CustomControlNetWeights:
134
+ @classmethod
135
+ def INPUT_TYPES(s):
136
+ return {
137
+ "required": {
138
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
139
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
140
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
141
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
142
+ "weight_04": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
143
+ "weight_05": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
144
+ "weight_06": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
145
+ "weight_07": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
146
+ "weight_08": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
147
+ "weight_09": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
148
+ "weight_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
149
+ "weight_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
150
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
151
+ "flip_weights": ("BOOLEAN", {"default": False}),
152
+ },
153
+ "optional": {
154
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
155
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
156
+ }
157
+ }
158
+
159
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
160
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
161
+ FUNCTION = "load_weights"
162
+
163
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
164
+
165
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
166
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
167
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
168
+ weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
169
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
170
+ weights = ControlWeights.controlnet(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
171
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
172
+
173
+
174
+ class SoftT2IAdapterWeights:
175
+ @classmethod
176
+ def INPUT_TYPES(s):
177
+ return {
178
+ "required": {
179
+ "weight_00": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
180
+ "weight_01": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
181
+ "weight_02": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
182
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
183
+ "flip_weights": ("BOOLEAN", {"default": False}),
184
+ },
185
+ "optional": {
186
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
187
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
188
+ }
189
+ }
190
+
191
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
192
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
193
+ FUNCTION = "load_weights"
194
+
195
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒���/weights/T2IAdapter"
196
+
197
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
198
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
199
+ weights = [weight_00, weight_01, weight_02, weight_03]
200
+ weights = get_properly_arranged_t2i_weights(weights)
201
+ weights.reverse() # to account for recent ComfyUI changes
202
+ weights = ControlWeights.t2iadapter(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
203
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
204
+
205
+
206
+ class CustomT2IAdapterWeights:
207
+ @classmethod
208
+ def INPUT_TYPES(s):
209
+ return {
210
+ "required": {
211
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
212
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
213
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
214
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
215
+ "flip_weights": ("BOOLEAN", {"default": False}),
216
+ },
217
+ "optional": {
218
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
219
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
220
+ }
221
+ }
222
+
223
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
224
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
225
+ FUNCTION = "load_weights"
226
+
227
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
228
+
229
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
230
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
231
+ weights = [weight_00, weight_01, weight_02, weight_03]
232
+ weights = get_properly_arranged_t2i_weights(weights)
233
+ weights.reverse() # to account for recent ComfyUI changes
234
+ weights = ControlWeights.t2iadapter(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
235
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/adv_control/utils.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from typing import Callable, Union
3
+ import torch
4
+ from torch import Tensor
5
+ import torch.nn.functional
6
+ import numpy as np
7
+ import math
8
+
9
+ import comfy.ops
10
+ import comfy.utils
11
+ import comfy.sample
12
+ import comfy.samplers
13
+ import comfy.model_base
14
+
15
+ from comfy.controlnet import ControlBase
16
+ from comfy.model_patcher import ModelPatcher
17
+ from comfy.sd import VAE
18
+
19
+ from .logger import logger
20
+
21
+ BIGMIN = -(2**53-1)
22
+ BIGMAX = (2**53-1)
23
+
24
+ def load_torch_file_with_dict_factory(controlnet_data: dict[str, Tensor], orig_load_torch_file: Callable):
25
+ def load_torch_file_with_dict(*args, **kwargs):
26
+ # immediately restore load_torch_file to original version
27
+ comfy.utils.load_torch_file = orig_load_torch_file
28
+ return controlnet_data
29
+ return load_torch_file_with_dict
30
+
31
+ # wrapping len function so that it will save the thing len is trying to get the length of;
32
+ # this will be assumed to be the cond_or_uncond variable;
33
+ # automatically restores len to original function after running
34
+ def wrapper_len_factory(orig_len: Callable) -> Callable:
35
+ def wrapper_len(*args, **kwargs):
36
+ cond_or_uncond = args[0]
37
+ real_length = orig_len(*args, **kwargs)
38
+ if real_length > 0 and type(cond_or_uncond) == list and (cond_or_uncond[0] in [0, 1]):
39
+ try:
40
+ to_return = IntWithCondOrUncond(real_length)
41
+ setattr(to_return, "cond_or_uncond", cond_or_uncond)
42
+ return to_return
43
+ finally:
44
+ __builtins__["len"] = orig_len
45
+ else:
46
+ return real_length
47
+ return wrapper_len
48
+
49
+ # wrapping cond_cat function so that it will wrap around len function to get cond_or_uncond variable value
50
+ # from comfy.samplers.calc_conds_batch
51
+ def wrapper_cond_cat_factory(orig_cond_cat: Callable):
52
+ def wrapper_cond_cat(*args, **kwargs):
53
+ __builtins__["len"] = wrapper_len_factory(__builtins__["len"])
54
+ return orig_cond_cat(*args, **kwargs)
55
+ return wrapper_cond_cat
56
+ orig_cond_cat = comfy.samplers.cond_cat
57
+ comfy.samplers.cond_cat = wrapper_cond_cat_factory(orig_cond_cat)
58
+
59
+
60
+ # wrapping apply_model so that len function will be cleaned up fairly soon after being injected
61
+ def apply_model_uncond_cleanup_factory(orig_apply_model, orig_len):
62
+ def apply_model_uncond_cleanup_wrapper(self, *args, **kwargs):
63
+ __builtins__["len"] = orig_len
64
+ return orig_apply_model(self, *args, **kwargs)
65
+ return apply_model_uncond_cleanup_wrapper
66
+ global_orig_len = __builtins__["len"]
67
+ orig_apply_model = comfy.model_base.BaseModel.apply_model
68
+ comfy.model_base.BaseModel.apply_model = apply_model_uncond_cleanup_factory(orig_apply_model, global_orig_len)
69
+
70
+
71
+ def uncond_multiplier_check_cn_sample_factory(orig_comfy_sample: Callable, is_custom=False) -> Callable:
72
+ def contains_uncond_multiplier(control: Union[ControlBase, 'AdvancedControlBase']):
73
+ if control is None:
74
+ return False
75
+ if not isinstance(control, AdvancedControlBase):
76
+ return contains_uncond_multiplier(control.previous_controlnet)
77
+ # check if weights_override has an uncond_multiplier
78
+ if control.weights_override is not None and control.weights_override.has_uncond_multiplier:
79
+ return True
80
+ # check if any timestep_keyframes have an uncond_multiplier on their weights
81
+ if control.timestep_keyframes is not None:
82
+ for tk in control.timestep_keyframes.keyframes:
83
+ if tk.has_control_weights() and tk.control_weights.has_uncond_multiplier:
84
+ return True
85
+ return contains_uncond_multiplier(control.previous_controlnet)
86
+
87
+ # check if positive or negative conds contain Adv. Cns that use multiply_negative on weights
88
+ def uncond_multiplier_check_cn_sample(model: ModelPatcher, *args, **kwargs):
89
+ positive = args[-3]
90
+ negative = args[-2]
91
+ has_uncond_multiplier = False
92
+ if positive is not None:
93
+ for cond in positive:
94
+ if "control" in cond[1]:
95
+ has_uncond_multiplier = contains_uncond_multiplier(cond[1]["control"])
96
+ if has_uncond_multiplier:
97
+ break
98
+ if negative is not None and not has_uncond_multiplier:
99
+ for cond in negative:
100
+ if "control" in cond[1]:
101
+ has_uncond_multiplier = contains_uncond_multiplier(cond[1]["control"])
102
+ if has_uncond_multiplier:
103
+ break
104
+ try:
105
+ # if uncond_multiplier found, continue to use wrapped version of function
106
+ if has_uncond_multiplier:
107
+ return orig_comfy_sample(model, *args, **kwargs)
108
+ # otherwise, use original version of function to prevent even the smallest of slowdowns (0.XX%)
109
+ try:
110
+ wrapped_cond_cat = comfy.samplers.cond_cat
111
+ comfy.samplers.cond_cat = orig_cond_cat
112
+ return orig_comfy_sample(model, *args, **kwargs)
113
+ finally:
114
+ comfy.samplers.cond_cat = wrapped_cond_cat
115
+ finally:
116
+ # make sure len function is unwrapped by the time sampling is done, just in case
117
+ __builtins__["len"] = global_orig_len
118
+ return uncond_multiplier_check_cn_sample
119
+ # inject sample functions
120
+ comfy.sample.sample = uncond_multiplier_check_cn_sample_factory(comfy.sample.sample)
121
+ comfy.sample.sample_custom = uncond_multiplier_check_cn_sample_factory(comfy.sample.sample_custom, is_custom=True)
122
+
123
+
124
+ class IntWithCondOrUncond(int):
125
+ def __new__(cls, *args, **kwargs):
126
+ return super(IntWithCondOrUncond, cls).__new__(cls, *args, **kwargs)
127
+
128
+ def __init__(self, *args, **kwargs):
129
+ super().__init__()
130
+ self.cond_or_uncond = None
131
+
132
+
133
+
134
+ def get_properly_arranged_t2i_weights(initial_weights: list[float]):
135
+ new_weights = []
136
+ new_weights.extend([initial_weights[0]]*3)
137
+ new_weights.extend([initial_weights[1]]*3)
138
+ new_weights.extend([initial_weights[2]]*3)
139
+ new_weights.extend([initial_weights[3]]*3)
140
+ return new_weights
141
+
142
+
143
+ class ControlWeightType:
144
+ DEFAULT = "default"
145
+ UNIVERSAL = "universal"
146
+ T2IADAPTER = "t2iadapter"
147
+ CONTROLNET = "controlnet"
148
+ CONTROLLORA = "controllora"
149
+ CONTROLLLLITE = "controllllite"
150
+ SVD_CONTROLNET = "svd_controlnet"
151
+ SPARSECTRL = "sparsectrl"
152
+
153
+
154
+ class ControlWeights:
155
+ def __init__(self, weight_type: str, base_multiplier: float=1.0, flip_weights: bool=False, weights: list[float]=None, weight_mask: Tensor=None,
156
+ uncond_multiplier=1.0, uncond_mask: Tensor=None, extras: dict[str]={},):
157
+ self.weight_type = weight_type
158
+ self.base_multiplier = base_multiplier
159
+ self.flip_weights = flip_weights
160
+ self.weights = weights
161
+ if self.weights is not None and self.flip_weights:
162
+ self.weights.reverse()
163
+ self.weight_mask = weight_mask
164
+ self.uncond_multiplier = float(uncond_multiplier)
165
+ self.has_uncond_multiplier = not math.isclose(self.uncond_multiplier, 1.0)
166
+ self.uncond_mask = uncond_mask if uncond_mask is not None else 1.0
167
+ self.has_uncond_mask = uncond_mask is not None
168
+ self.extras = extras
169
+
170
+ def get(self, idx: int, control: dict[str, list[Tensor]], key: str, default=1.0) -> Union[float, Tensor]:
171
+ # if weights is not none, return index
172
+ if self.weights is not None:
173
+ # if middle weight, need to pretend index is actually after all the output weights (if applicable)
174
+ if key == "middle" and "output" in control:
175
+ idx += len(control["output"])
176
+
177
+ if key == "output":
178
+ # this implies weights list is not aligning with expectations - will need to adjust code
179
+ if idx >= len(self.weights)-1:
180
+ return default
181
+ else:
182
+ # this implies weights list is not aligning with expectations - will need to adjust code
183
+ if idx >= len(self.weights):
184
+ return default
185
+ return self.weights[idx]
186
+ return 1.0
187
+
188
+ def copy_with_new_weights(self, new_weights: list[float]):
189
+ return ControlWeights(weight_type=self.weight_type, base_multiplier=self.base_multiplier, flip_weights=self.flip_weights,
190
+ weights=new_weights, weight_mask=self.weight_mask, uncond_multiplier=self.uncond_multiplier, extras=self.extras)
191
+
192
+ @classmethod
193
+ def default(cls, extras: dict[str]={}):
194
+ return cls(ControlWeightType.DEFAULT, extras=extras)
195
+
196
+ @classmethod
197
+ def universal(cls, base_multiplier: float, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
198
+ return cls(ControlWeightType.UNIVERSAL, base_multiplier=base_multiplier, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
199
+
200
+ @classmethod
201
+ def universal_mask(cls, weight_mask: Tensor, uncond_multiplier: float=1.0, extras: dict[str]={}):
202
+ return cls(ControlWeightType.UNIVERSAL, weight_mask=weight_mask, uncond_multiplier=uncond_multiplier, extras=extras)
203
+
204
+ @classmethod
205
+ def t2iadapter(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
206
+ if weights is None:
207
+ weights = [1.0]*12
208
+ return cls(ControlWeightType.T2IADAPTER, weights=weights,flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
209
+
210
+ @classmethod
211
+ def controlnet(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
212
+ if weights is None:
213
+ weights = [1.0]*13
214
+ return cls(ControlWeightType.CONTROLNET, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
215
+
216
+ @classmethod
217
+ def controllora(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
218
+ if weights is None:
219
+ weights = [1.0]*10
220
+ return cls(ControlWeightType.CONTROLLORA, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
221
+
222
+ @classmethod
223
+ def controllllite(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
224
+ if weights is None:
225
+ # TODO: make this have a real value
226
+ weights = [1.0]*200
227
+ return cls(ControlWeightType.CONTROLLLLITE, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
228
+
229
+
230
+ class StrengthInterpolation:
231
+ LINEAR = "linear"
232
+ EASE_IN = "ease-in"
233
+ EASE_OUT = "ease-out"
234
+ EASE_IN_OUT = "ease-in-out"
235
+ NONE = "none"
236
+
237
+ _LIST = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT]
238
+ _LIST_WITH_NONE = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT, NONE]
239
+
240
+ @classmethod
241
+ def get_weights(cls, num_from: float, num_to: float, length: int, method: str, reverse=False):
242
+ diff = num_to - num_from
243
+ if method == cls.LINEAR:
244
+ weights = torch.linspace(num_from, num_to, length)
245
+ elif method == cls.EASE_IN:
246
+ index = torch.linspace(0, 1, length)
247
+ weights = diff * np.power(index, 2) + num_from
248
+ elif method == cls.EASE_OUT:
249
+ index = torch.linspace(0, 1, length)
250
+ weights = diff * (1 - np.power(1 - index, 2)) + num_from
251
+ elif method == cls.EASE_IN_OUT:
252
+ index = torch.linspace(0, 1, length)
253
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + num_from
254
+ else:
255
+ raise ValueError(f"Unrecognized interpolation method '{method}'.")
256
+ if reverse:
257
+ weights = weights.flip(dims=(0,))
258
+ return weights
259
+
260
+
261
+ class LatentKeyframe:
262
+ def __init__(self, batch_index: int, strength: float) -> None:
263
+ self.batch_index = batch_index
264
+ self.strength = strength
265
+
266
+
267
+ # always maintain sorted state (by batch_index of LatentKeyframe)
268
+ class LatentKeyframeGroup:
269
+ def __init__(self) -> None:
270
+ self.keyframes: list[LatentKeyframe] = []
271
+
272
+ def add(self, keyframe: LatentKeyframe) -> None:
273
+ added = False
274
+ # replace existing keyframe if same batch_index
275
+ for i in range(len(self.keyframes)):
276
+ if self.keyframes[i].batch_index == keyframe.batch_index:
277
+ self.keyframes[i] = keyframe
278
+ added = True
279
+ break
280
+ if not added:
281
+ self.keyframes.append(keyframe)
282
+ self.keyframes.sort(key=lambda k: k.batch_index)
283
+
284
+ def get_index(self, index: int) -> Union[LatentKeyframe, None]:
285
+ try:
286
+ return self.keyframes[index]
287
+ except IndexError:
288
+ return None
289
+
290
+ def __getitem__(self, index) -> LatentKeyframe:
291
+ return self.keyframes[index]
292
+
293
+ def is_empty(self) -> bool:
294
+ return len(self.keyframes) == 0
295
+
296
+ def clone(self) -> 'LatentKeyframeGroup':
297
+ cloned = LatentKeyframeGroup()
298
+ for tk in self.keyframes:
299
+ cloned.add(tk)
300
+ return cloned
301
+
302
+
303
+ class TimestepKeyframe:
304
+ def __init__(self,
305
+ start_percent: float = 0.0,
306
+ strength: float = 1.0,
307
+ control_weights: ControlWeights = None,
308
+ latent_keyframes: LatentKeyframeGroup = None,
309
+ null_latent_kf_strength: float = 0.0,
310
+ inherit_missing: bool = True,
311
+ guarantee_steps: int = 1,
312
+ mask_hint_orig: Tensor = None) -> None:
313
+ self.start_percent = float(start_percent)
314
+ self.start_t = 999999999.9
315
+ self.strength = strength
316
+ self.control_weights = control_weights
317
+ self.latent_keyframes = latent_keyframes
318
+ self.null_latent_kf_strength = null_latent_kf_strength
319
+ self.inherit_missing = inherit_missing
320
+ self.guarantee_steps = guarantee_steps
321
+ self.mask_hint_orig = mask_hint_orig
322
+
323
+ def has_control_weights(self):
324
+ return self.control_weights is not None
325
+
326
+ def has_latent_keyframes(self):
327
+ return self.latent_keyframes is not None
328
+
329
+ def has_mask_hint(self):
330
+ return self.mask_hint_orig is not None
331
+
332
+
333
+ @staticmethod
334
+ def default() -> 'TimestepKeyframe':
335
+ return TimestepKeyframe(start_percent=0.0, guarantee_steps=0)
336
+
337
+
338
+ # always maintain sorted state (by start_percent of TimestepKeyFrame)
339
+ class TimestepKeyframeGroup:
340
+ def __init__(self) -> None:
341
+ self.keyframes: list[TimestepKeyframe] = []
342
+ self.keyframes.append(TimestepKeyframe.default())
343
+
344
+ def add(self, keyframe: TimestepKeyframe) -> None:
345
+ # add to end of list, then sort
346
+ self.keyframes.append(keyframe)
347
+ self.keyframes = get_sorted_list_via_attr(self.keyframes, attr="start_percent")
348
+
349
+ def get_index(self, index: int) -> Union[TimestepKeyframe, None]:
350
+ try:
351
+ return self.keyframes[index]
352
+ except IndexError:
353
+ return None
354
+
355
+ def has_index(self, index: int) -> int:
356
+ return index >=0 and index < len(self.keyframes)
357
+
358
+ def __getitem__(self, index) -> TimestepKeyframe:
359
+ return self.keyframes[index]
360
+
361
+ def __len__(self) -> int:
362
+ return len(self.keyframes)
363
+
364
+ def is_empty(self) -> bool:
365
+ return len(self.keyframes) == 0
366
+
367
+ def clone(self) -> 'TimestepKeyframeGroup':
368
+ cloned = TimestepKeyframeGroup()
369
+ # already sorted, so don't use add function to make cloning quicker
370
+ for tk in self.keyframes:
371
+ cloned.keyframes.append(tk)
372
+ return cloned
373
+
374
+ @classmethod
375
+ def default(cls, keyframe: TimestepKeyframe) -> 'TimestepKeyframeGroup':
376
+ group = cls()
377
+ group.keyframes[0] = keyframe
378
+ return group
379
+
380
+
381
+ class AbstractPreprocWrapper:
382
+ error_msg = "Invalid use of [InsertHere] output. The output of [InsertHere] preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply ControlNet node (advanced or otherwise). It cannot be used for anything else that accepts IMAGE input."
383
+ def __init__(self, condhint: Tensor):
384
+ self.condhint = condhint
385
+
386
+ def movedim(self, *args, **kwargs):
387
+ return self
388
+
389
+ def __getattr__(self, *args, **kwargs):
390
+ raise AttributeError(self.error_msg)
391
+
392
+ def __setattr__(self, name, value):
393
+ if name != "condhint":
394
+ raise AttributeError(self.error_msg)
395
+ super().__setattr__(name, value)
396
+
397
+ def __iter__(self, *args, **kwargs):
398
+ raise AttributeError(self.error_msg)
399
+
400
+ def __next__(self, *args, **kwargs):
401
+ raise AttributeError(self.error_msg)
402
+
403
+ def __len__(self, *args, **kwargs):
404
+ raise AttributeError(self.error_msg)
405
+
406
+ def __getitem__(self, *args, **kwargs):
407
+ raise AttributeError(self.error_msg)
408
+
409
+ def __setitem__(self, *args, **kwargs):
410
+ raise AttributeError(self.error_msg)
411
+
412
+
413
+ # depending on model, AnimateDiff may inject into GroupNorm, so make sure GroupNorm will be clean
414
+ class disable_weight_init_clean_groupnorm(comfy.ops.disable_weight_init):
415
+ class GroupNorm(comfy.ops.disable_weight_init.GroupNorm):
416
+ def forward_comfy_cast_weights(self, input):
417
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
418
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
419
+
420
+ def forward(self, input):
421
+ if self.comfy_cast_weights:
422
+ return self.forward_comfy_cast_weights(input)
423
+ else:
424
+ return torch.nn.functional.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
425
+
426
+ class manual_cast_clean_groupnorm(comfy.ops.manual_cast):
427
+ class GroupNorm(disable_weight_init_clean_groupnorm.GroupNorm):
428
+ comfy_cast_weights = True
429
+
430
+
431
+ # adapted from comfy/sample.py
432
+ def prepare_mask_batch(mask: Tensor, shape: Tensor, multiplier: int=1, match_dim1=False, match_shape=False):
433
+ mask = mask.clone()
434
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[-2]*multiplier, shape[-1]*multiplier), mode="bilinear")
435
+ if match_dim1:
436
+ if match_shape and len(shape) < 4:
437
+ raise Exception(f"match_dim1 cannot be True if shape is under 4 dims; was {len(shape)}.")
438
+ mask = torch.cat([mask] * shape[1], dim=1)
439
+ if match_shape and len(shape) == 3:
440
+ mask = mask.squeeze(1)
441
+ return mask
442
+
443
+
444
+ # applies min-max normalization, from:
445
+ # https://stackoverflow.com/questions/68791508/min-max-normalization-of-a-tensor-in-pytorch
446
+ def normalize_min_max(x: Tensor, new_min = 0.0, new_max = 1.0):
447
+ x_min, x_max = x.min(), x.max()
448
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
449
+
450
+ def linear_conversion(x, x_min=0.0, x_max=1.0, new_min=0.0, new_max=1.0):
451
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
452
+
453
+ def extend_to_batch_size(tensor: Tensor, batch_size: int):
454
+ if tensor.shape[0] > batch_size:
455
+ return tensor[:batch_size]
456
+ elif tensor.shape[0] < batch_size:
457
+ remainder = batch_size-tensor.shape[0]
458
+ return torch.cat([tensor] + [tensor[-1:]]*remainder, dim=0)
459
+ return tensor
460
+
461
+ def broadcast_image_to_extend(tensor, target_batch_size, batched_number, except_one=True):
462
+ current_batch_size = tensor.shape[0]
463
+ #print(current_batch_size, target_batch_size)
464
+ if except_one and current_batch_size == 1:
465
+ return tensor
466
+
467
+ per_batch = target_batch_size // batched_number
468
+ tensor = tensor[:per_batch]
469
+
470
+ if per_batch > tensor.shape[0]:
471
+ tensor = extend_to_batch_size(tensor=tensor, batch_size=per_batch)
472
+
473
+ current_batch_size = tensor.shape[0]
474
+ if current_batch_size == target_batch_size:
475
+ return tensor
476
+ else:
477
+ return torch.cat([tensor] * batched_number, dim=0)
478
+
479
+
480
+ # from https://stackoverflow.com/a/24621200
481
+ def deepcopy_with_sharing(obj, shared_attribute_names, memo=None):
482
+ '''
483
+ Deepcopy an object, except for a given list of attributes, which should
484
+ be shared between the original object and its copy.
485
+
486
+ obj is some object
487
+ shared_attribute_names: A list of strings identifying the attributes that
488
+ should be shared between the original and its copy.
489
+ memo is the dictionary passed into __deepcopy__. Ignore this argument if
490
+ not calling from within __deepcopy__.
491
+ '''
492
+ assert isinstance(shared_attribute_names, (list, tuple))
493
+
494
+ shared_attributes = {k: getattr(obj, k) for k in shared_attribute_names}
495
+
496
+ if hasattr(obj, '__deepcopy__'):
497
+ # Do hack to prevent infinite recursion in call to deepcopy
498
+ deepcopy_method = obj.__deepcopy__
499
+ obj.__deepcopy__ = None
500
+
501
+ for attr in shared_attribute_names:
502
+ del obj.__dict__[attr]
503
+
504
+ clone = deepcopy(obj)
505
+
506
+ for attr, val in shared_attributes.items():
507
+ setattr(obj, attr, val)
508
+ setattr(clone, attr, val)
509
+
510
+ if hasattr(obj, '__deepcopy__'):
511
+ # Undo hack
512
+ obj.__deepcopy__ = deepcopy_method
513
+ del clone.__deepcopy__
514
+
515
+ return clone
516
+
517
+
518
+ def get_sorted_list_via_attr(objects: list, attr: str) -> list:
519
+ if not objects:
520
+ return objects
521
+ elif len(objects) <= 1:
522
+ return [x for x in objects]
523
+ # now that we know we have to sort, do it following these rules:
524
+ # a) if objects have same value of attribute, maintain their relative order
525
+ # b) perform sorting of the groups of objects with same attributes
526
+ unique_attrs = {}
527
+ for o in objects:
528
+ val_attr = getattr(o, attr)
529
+ attr_list: list = unique_attrs.get(val_attr, list())
530
+ attr_list.append(o)
531
+ if val_attr not in unique_attrs:
532
+ unique_attrs[val_attr] = attr_list
533
+ # now that we have the unique attr values grouped together in relative order, sort them by key
534
+ sorted_attrs = dict(sorted(unique_attrs.items()))
535
+ # now flatten out the dict into a list to return
536
+ sorted_list = []
537
+ for object_list in sorted_attrs.values():
538
+ sorted_list.extend(object_list)
539
+ return sorted_list
540
+
541
+
542
+ class WeightTypeException(TypeError):
543
+ "Raised when weight not compatible with AdvancedControlBase object"
544
+ pass
545
+
546
+
547
+ class AdvancedControlBase:
548
+ def __init__(self, base: ControlBase, timestep_keyframes: TimestepKeyframeGroup, weights_default: ControlWeights, require_model=False, require_vae=False, allow_condhint_latents=False):
549
+ self.base = base
550
+ self.compatible_weights = [ControlWeightType.UNIVERSAL, ControlWeightType.DEFAULT]
551
+ self.add_compatible_weight(weights_default.weight_type)
552
+ # mask for which parts of controlnet output to keep
553
+ self.mask_cond_hint_original = None
554
+ self.mask_cond_hint = None
555
+ self.tk_mask_cond_hint_original = None
556
+ self.tk_mask_cond_hint = None
557
+ self.weight_mask_cond_hint = None
558
+ # actual index values
559
+ self.sub_idxs = None
560
+ self.full_latent_length = 0
561
+ self.context_length = 0
562
+ # timesteps
563
+ self.t: Tensor = None
564
+ self.batched_number: Union[int, IntWithCondOrUncond] = None
565
+ self.batch_size: int = 0
566
+ # weights + override
567
+ self.weights: ControlWeights = None
568
+ self.weights_default: ControlWeights = weights_default
569
+ self.weights_override: ControlWeights = None
570
+ # latent keyframe + override
571
+ self.latent_keyframes: LatentKeyframeGroup = None
572
+ self.latent_keyframe_override: LatentKeyframeGroup = None
573
+ # initialize timestep_keyframes
574
+ self.set_timestep_keyframes(timestep_keyframes)
575
+ # override some functions
576
+ self.get_control = self.get_control_inject
577
+ self.control_merge = self.control_merge_inject
578
+ self.pre_run = self.pre_run_inject
579
+ self.cleanup = self.cleanup_inject
580
+ self.set_previous_controlnet = self.set_previous_controlnet_inject
581
+ self.set_cond_hint = self.set_cond_hint_inject
582
+ # vae to store
583
+ self.adv_vae = None
584
+ # require model/vae to be passed into Apply Advanced ControlNet 🛂🅐🅒🅝 node
585
+ self.require_model = require_model
586
+ self.require_vae = require_vae
587
+ self.allow_condhint_latents = allow_condhint_latents
588
+ # disarm - when set to False, used to force usage of Apply Advanced ControlNet 🛂🅐🅒🅝 node (which will set it to True)
589
+ self.disarmed = not require_model
590
+
591
+ def patch_model(self, model: ModelPatcher):
592
+ pass
593
+
594
+ def add_compatible_weight(self, control_weight_type: str):
595
+ self.compatible_weights.append(control_weight_type)
596
+
597
+ def verify_all_weights(self, throw_error=True):
598
+ # first, check if override exists - if so, only need to check the override
599
+ if self.weights_override is not None:
600
+ if self.weights_override.weight_type not in self.compatible_weights:
601
+ msg = f"Weight override is type {self.weights_override.weight_type}, but loaded {type(self).__name__}" + \
602
+ f"only supports {self.compatible_weights} weights."
603
+ raise WeightTypeException(msg)
604
+ # otherwise, check all timestep keyframe weights
605
+ else:
606
+ for tk in self.timestep_keyframes.keyframes:
607
+ if tk.has_control_weights() and tk.control_weights.weight_type not in self.compatible_weights:
608
+ msg = f"Weight on Timestep Keyframe with start_percent={tk.start_percent} is type " + \
609
+ f"{tk.control_weights.weight_type}, but loaded {type(self).__name__} only supports {self.compatible_weights} weights."
610
+ raise WeightTypeException(msg)
611
+
612
+ def set_timestep_keyframes(self, timestep_keyframes: TimestepKeyframeGroup):
613
+ self.timestep_keyframes = timestep_keyframes if timestep_keyframes else TimestepKeyframeGroup()
614
+ # prepare first timestep_keyframe related stuff
615
+ self._current_timestep_keyframe = None
616
+ self._current_timestep_index = -1
617
+ self._current_used_steps = 0
618
+ self.weights = None
619
+ self.latent_keyframes = None
620
+
621
+ def prepare_current_timestep(self, t: Tensor, batched_number: int):
622
+ self.t = float(t[0])
623
+ self.batched_number = batched_number
624
+ self.batch_size = len(t)
625
+ # get current step percent
626
+ curr_t: float = self.t
627
+ prev_index = self._current_timestep_index
628
+ # if met guaranteed steps (or no current keyframe), look for next keyframe in case need to switch
629
+ if self._current_timestep_keyframe is None or self._current_used_steps >= self._current_timestep_keyframe.guarantee_steps:
630
+ # if has next index, loop through and see if need to switch
631
+ if self.timestep_keyframes.has_index(self._current_timestep_index+1):
632
+ for i in range(self._current_timestep_index+1, len(self.timestep_keyframes)):
633
+ eval_tk = self.timestep_keyframes[i]
634
+ # check if start percent is less or equal to curr_t
635
+ if eval_tk.start_t >= curr_t:
636
+ self._current_timestep_index = i
637
+ self._current_timestep_keyframe = eval_tk
638
+ self._current_used_steps = 0
639
+ # keep track of control weights, latent keyframes, and masks,
640
+ # accounting for inherit_missing
641
+ if self._current_timestep_keyframe.has_control_weights():
642
+ self.weights = self._current_timestep_keyframe.control_weights
643
+ elif not self._current_timestep_keyframe.inherit_missing:
644
+ self.weights = self.weights_default
645
+ if self._current_timestep_keyframe.has_latent_keyframes():
646
+ self.latent_keyframes = self._current_timestep_keyframe.latent_keyframes
647
+ elif not self._current_timestep_keyframe.inherit_missing:
648
+ self.latent_keyframes = None
649
+ if self._current_timestep_keyframe.has_mask_hint():
650
+ self.tk_mask_cond_hint_original = self._current_timestep_keyframe.mask_hint_orig
651
+ elif not self._current_timestep_keyframe.inherit_missing:
652
+ del self.tk_mask_cond_hint_original
653
+ self.tk_mask_cond_hint_original = None
654
+ # if guarantee_steps greater than zero, stop searching for other keyframes
655
+ if self._current_timestep_keyframe.guarantee_steps > 0:
656
+ break
657
+ # if eval_tk is outside of percent range, stop looking further
658
+ else:
659
+ break
660
+
661
+ # update steps current keyframe is used
662
+ self._current_used_steps += 1
663
+ # if index changed, apply overrides
664
+ if prev_index != self._current_timestep_index:
665
+ if self.weights_override is not None:
666
+ self.weights = self.weights_override
667
+ if self.latent_keyframe_override is not None:
668
+ self.latent_keyframes = self.latent_keyframe_override
669
+
670
+ # make sure weights and latent_keyframes are in a workable state
671
+ # Note: each AdvancedControlBase should create their own get_universal_weights class
672
+ self.prepare_weights()
673
+
674
+ def prepare_weights(self):
675
+ if self.weights is None:
676
+ self.weights = self.weights_default
677
+ elif self.weights.weight_type == ControlWeightType.UNIVERSAL:
678
+ # if universal and weight_mask present, no need to convert
679
+ if self.weights.weight_mask is not None:
680
+ return
681
+ self.weights = self.get_universal_weights()
682
+
683
+ def get_universal_weights(self) -> ControlWeights:
684
+ return self.weights
685
+
686
+ def set_cond_hint_mask(self, mask_hint):
687
+ self.mask_cond_hint_original = mask_hint
688
+ return self
689
+
690
+ def set_cond_hint_inject(self, *args, **kwargs):
691
+ to_return = self.base.set_cond_hint(*args, **kwargs)
692
+ # if vae required, look in args and kwargs for it
693
+ if self.require_vae:
694
+ # check args first, as that's the default way vae param is used in ComfyUI
695
+ for arg in args:
696
+ if isinstance(arg, VAE):
697
+ self.adv_vae = arg
698
+ break
699
+ # if not in args, check kwargs now
700
+ if self.adv_vae is None:
701
+ if 'vae' in kwargs:
702
+ self.adv_vae = kwargs['vae']
703
+ return to_return
704
+
705
+ def pre_run_inject(self, model, percent_to_timestep_function):
706
+ self.base.pre_run(model, percent_to_timestep_function)
707
+ self.pre_run_advanced(model, percent_to_timestep_function)
708
+
709
+ def pre_run_advanced(self, model, percent_to_timestep_function):
710
+ # for each timestep keyframe, calculate the start_t
711
+ for tk in self.timestep_keyframes.keyframes:
712
+ tk.start_t = percent_to_timestep_function(tk.start_percent)
713
+ # clear variables
714
+ self.cleanup_advanced()
715
+
716
+ def set_previous_controlnet_inject(self, *args, **kwargs):
717
+ to_return = self.base.set_previous_controlnet(*args, **kwargs)
718
+ if not self.disarmed:
719
+ raise Exception(f"Type '{type(self).__name__}' must be used with Apply Advanced ControlNet 🛂🅐🅒🅝 node (with model_optional passed in); otherwise, it will not work.")
720
+ return to_return
721
+
722
+ def disarm(self):
723
+ self.disarmed = True
724
+
725
+ def should_run(self):
726
+ if math.isclose(self.strength, 0.0) or math.isclose(self._current_timestep_keyframe.strength, 0.0):
727
+ return False
728
+ if self.timestep_range is not None:
729
+ if self.t > self.timestep_range[0] or self.t < self.timestep_range[1]:
730
+ return False
731
+ return True
732
+
733
+ def get_control_inject(self, x_noisy, t, cond, batched_number):
734
+ # prepare timestep and everything related
735
+ self.prepare_current_timestep(t=t, batched_number=batched_number)
736
+ # if should not perform any actions for the controlnet, exit without doing any work
737
+ if self.strength == 0.0 or self._current_timestep_keyframe.strength == 0.0:
738
+ return self.default_control_actions(x_noisy, t, cond, batched_number)
739
+ # otherwise, perform normal function
740
+ return self.get_control_advanced(x_noisy, t, cond, batched_number)
741
+
742
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
743
+ return self.default_control_actions(x_noisy, t, cond, batched_number)
744
+
745
+ def default_control_actions(self, x_noisy, t, cond, batched_number):
746
+ control_prev = None
747
+ if self.previous_controlnet is not None:
748
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
749
+ return control_prev
750
+
751
+ def calc_weight(self, idx: int, x: Tensor, control: dict[str, list[Tensor]], key: str) -> Union[float, Tensor]:
752
+ if self.weights.weight_mask is not None:
753
+ # prepare weight mask
754
+ self.prepare_weight_mask_cond_hint(x, self.batched_number)
755
+ # adjust mask for current layer and return
756
+ return torch.pow(self.weight_mask_cond_hint, self.get_calc_pow(idx=idx, control=control, key=key))
757
+ return self.weights.get(idx=idx, control=control, key=key)
758
+
759
+ def get_calc_pow(self, idx: int, control: dict[str, list[Tensor]], key: str) -> int:
760
+ c_len = len(control[key])-1
761
+ if key == "output":
762
+ if "middle" in control:
763
+ c_len += len(control["middle"])
764
+ return c_len-idx
765
+
766
+ def calc_latent_keyframe_mults(self, x: Tensor, batched_number: int) -> Tensor:
767
+ # apply strengths, and get batch indeces to null out
768
+ # AKA latents that should not be influenced by ControlNet
769
+ final_mults = [1.0] * x.shape[0]
770
+ if self.latent_keyframes:
771
+ latent_count = x.shape[0] // batched_number
772
+ indeces_to_null = set(range(latent_count))
773
+ mapped_indeces = None
774
+ # if expecting subdivision, will need to translate between subset and actual idx values
775
+ if self.sub_idxs:
776
+ mapped_indeces = {}
777
+ for i, actual in enumerate(self.sub_idxs):
778
+ mapped_indeces[actual] = i
779
+ for keyframe in self.latent_keyframes:
780
+ real_index = keyframe.batch_index
781
+ # if negative, count from end
782
+ if real_index < 0:
783
+ real_index += latent_count if self.sub_idxs is None else self.full_latent_length
784
+
785
+ # if not mapping indeces, what you see is what you get
786
+ if mapped_indeces is None:
787
+ if real_index in indeces_to_null:
788
+ indeces_to_null.remove(real_index)
789
+ # otherwise, see if batch_index is even included in this set of latents
790
+ else:
791
+ real_index = mapped_indeces.get(real_index, None)
792
+ if real_index is None:
793
+ continue
794
+ indeces_to_null.remove(real_index)
795
+
796
+ # if real_index is outside the bounds of latents, don't apply
797
+ if real_index >= latent_count or real_index < 0:
798
+ continue
799
+
800
+ # apply strength for each batched cond/uncond
801
+ for b in range(batched_number):
802
+ final_mults[(latent_count*b)+real_index] = keyframe.strength
803
+ # null them out by multiplying by null_latent_kf_strength
804
+ for batch_index in indeces_to_null:
805
+ # apply null for each batched cond/uncond
806
+ for b in range(batched_number):
807
+ final_mults[(latent_count*b)+batch_index] = self._current_timestep_keyframe.null_latent_kf_strength
808
+ # convert final_mults into tensor and match expected dimension count
809
+ final_tensor = torch.tensor(final_mults, dtype=x.dtype, device=x.device)
810
+ while len(final_tensor.shape) < len(x.shape):
811
+ final_tensor = final_tensor.unsqueeze(-1)
812
+ return final_tensor
813
+
814
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int):
815
+ # handle weight's uncond_multiplier, if applicable
816
+ if self.weights.has_uncond_multiplier:
817
+ cond_or_uncond = self.batched_number.cond_or_uncond
818
+ actual_length = x.size(0) // batched_number
819
+ for idx, cond_type in enumerate(cond_or_uncond):
820
+ # if uncond, set to weight's uncond_multiplier
821
+ if cond_type == 1:
822
+ x[actual_length*idx:actual_length*(idx+1)] *= self.weights.uncond_multiplier
823
+ if self.weights.has_uncond_mask:
824
+ pass
825
+
826
+ if self.latent_keyframes is not None:
827
+ x[:] = x[:] * self.calc_latent_keyframe_mults(x=x, batched_number=batched_number)
828
+ # apply masks, resizing mask to required dims
829
+ if self.mask_cond_hint is not None:
830
+ masks = prepare_mask_batch(self.mask_cond_hint, x.shape, match_shape=True)
831
+ x[:] = x[:] * masks
832
+ if self.tk_mask_cond_hint is not None:
833
+ masks = prepare_mask_batch(self.tk_mask_cond_hint, x.shape, match_shape=True)
834
+ x[:] = x[:] * masks
835
+ # apply timestep keyframe strengths
836
+ if self._current_timestep_keyframe.strength != 1.0:
837
+ x[:] *= self._current_timestep_keyframe.strength
838
+
839
+ def control_merge_inject(self: 'AdvancedControlBase', control: dict[str, list[Tensor]], control_prev: dict, output_dtype):
840
+ out = {'input':[], 'middle':[], 'output': []}
841
+
842
+ for key in control:
843
+ control_output = control[key]
844
+ applied_to = set()
845
+ for i in range(len(control_output)):
846
+ x = control_output[i]
847
+ if x is not None:
848
+ if self.global_average_pooling:
849
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
850
+
851
+ if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
852
+ applied_to.add(x)
853
+ self.apply_advanced_strengths_and_masks(x, self.batched_number)
854
+ x *= self.strength * self.calc_weight(i, x, control, key)
855
+
856
+ if x.dtype != output_dtype:
857
+ x = x.to(output_dtype)
858
+
859
+ out[key].append(x)
860
+
861
+ if control_prev is not None:
862
+ for x in ['input', 'middle', 'output']:
863
+ o = out[x]
864
+ for i in range(len(control_prev[x])):
865
+ prev_val = control_prev[x][i]
866
+ if i >= len(o):
867
+ o.append(prev_val)
868
+ elif prev_val is not None:
869
+ if o[i] is None:
870
+ o[i] = prev_val
871
+ else:
872
+ if o[i].shape[0] < prev_val.shape[0]:
873
+ o[i] = prev_val + o[i]
874
+ else:
875
+ o[i] = prev_val + o[i] # TODO from base ComfyUI: change back to inplace add if shared tensors stop being an issue
876
+ return out
877
+
878
+ def prepare_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
879
+ self._prepare_mask("mask_cond_hint", self.mask_cond_hint_original, x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
880
+ self.prepare_tk_mask_cond_hint(x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
881
+
882
+ def prepare_tk_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
883
+ return self._prepare_mask("tk_mask_cond_hint", self._current_timestep_keyframe.mask_hint_orig, x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
884
+
885
+ def prepare_weight_mask_cond_hint(self, x_noisy: Tensor, batched_number, dtype=None):
886
+ return self._prepare_mask("weight_mask_cond_hint", self.weights.weight_mask, x_noisy, t=None, cond=None, batched_number=batched_number, dtype=dtype, direct_attn=True)
887
+
888
+ def _prepare_mask(self, attr_name, orig_mask: Tensor, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
889
+ # make mask appropriate dimensions, if present
890
+ if orig_mask is not None:
891
+ out_mask = getattr(self, attr_name)
892
+ multiplier = 1 if direct_attn else 8
893
+ if self.sub_idxs is not None or out_mask is None or x_noisy.shape[2] * multiplier != out_mask.shape[1] or x_noisy.shape[3] * multiplier != out_mask.shape[2]:
894
+ self._reset_attr(attr_name)
895
+ del out_mask
896
+ # TODO: perform upscale on only the sub_idxs masks at a time instead of all to conserve RAM
897
+ # resize mask and match batch count
898
+ out_mask = prepare_mask_batch(orig_mask, x_noisy.shape, multiplier=multiplier)
899
+ actual_latent_length = x_noisy.shape[0] // batched_number
900
+ out_mask = extend_to_batch_size(out_mask, actual_latent_length if self.sub_idxs is None else self.full_latent_length)
901
+ if self.sub_idxs is not None:
902
+ out_mask = out_mask[self.sub_idxs]
903
+ # make cond_hint_mask length match x_noise
904
+ if x_noisy.shape[0] != out_mask.shape[0]:
905
+ out_mask = broadcast_image_to_extend(out_mask, x_noisy.shape[0], batched_number)
906
+ # default dtype to be same as x_noisy
907
+ if dtype is None:
908
+ dtype = x_noisy.dtype
909
+ setattr(self, attr_name, out_mask.to(dtype=dtype).to(self.device))
910
+ del out_mask
911
+
912
+ def _reset_attr(self, attr_name, new_value=None):
913
+ if hasattr(self, attr_name):
914
+ delattr(self, attr_name)
915
+ setattr(self, attr_name, new_value)
916
+
917
+ def cleanup_inject(self):
918
+ self.base.cleanup()
919
+ self.cleanup_advanced()
920
+
921
+ def cleanup_advanced(self):
922
+ self.sub_idxs = None
923
+ self.full_latent_length = 0
924
+ self.context_length = 0
925
+ self.t = None
926
+ self.batched_number = None
927
+ self.batch_size = 0
928
+ self.weights = None
929
+ self.latent_keyframes = None
930
+ # timestep stuff
931
+ self._current_timestep_keyframe = None
932
+ self._current_timestep_index = -1
933
+ self._current_used_steps = 0
934
+ # clear mask hints
935
+ if self.mask_cond_hint is not None:
936
+ del self.mask_cond_hint
937
+ self.mask_cond_hint = None
938
+ if self.tk_mask_cond_hint_original is not None:
939
+ del self.tk_mask_cond_hint_original
940
+ self.tk_mask_cond_hint_original = None
941
+ if self.tk_mask_cond_hint is not None:
942
+ del self.tk_mask_cond_hint
943
+ self.tk_mask_cond_hint = None
944
+ if self.weight_mask_cond_hint is not None:
945
+ del self.weight_mask_cond_hint
946
+ self.weight_mask_cond_hint = None
947
+
948
+ def copy_to_advanced(self, copied: 'AdvancedControlBase'):
949
+ copied.mask_cond_hint_original = self.mask_cond_hint_original
950
+ copied.weights_override = self.weights_override
951
+ copied.latent_keyframe_override = self.latent_keyframe_override
952
+ copied.adv_vae = self.adv_vae
953
+ copied.require_vae = self.require_vae
954
+ copied.allow_condhint_latents = self.allow_condhint_latents
955
+ copied.disarmed = self.disarmed
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "comfyui-advanced-controlnet"
3
+ description = "Nodes for scheduling ControlNet strength across timesteps and batched latents, as well as applying custom weights and attention masks."
4
+ version = "1.1.0"
5
+ license = "LICENSE"
6
+ dependencies = []
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet"
10
+
11
+ # Used by Comfy Registry https://comfyregistry.org
12
+ [tool.comfy]
13
+ PublisherId = "kosinkadink"
14
+ DisplayName = "ComfyUI-Advanced-ControlNet"
15
+ Icon = ""
ComfyUI/custom_nodes/ComfyUI-Advanced-ControlNet/requirements.txt ADDED
File without changes