Blankse commited on
Commit
e5b8fac
·
verified ·
1 Parent(s): 60a10e2

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -0
  2. ComfyUI-Advanced-ControlNet/.gitignore +160 -0
  3. ComfyUI-Advanced-ControlNet/LICENSE +674 -0
  4. ComfyUI-Advanced-ControlNet/README.md +205 -0
  5. ComfyUI-Advanced-ControlNet/__init__.py +11 -0
  6. ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc +0 -0
  7. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc +0 -0
  8. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_ctrlora.cpython-310.pyc +0 -0
  9. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc +0 -0
  10. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_plusplus.cpython-310.pyc +0 -0
  11. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc +0 -0
  12. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc +0 -0
  13. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc +0 -0
  14. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/dinklink.cpython-310.pyc +0 -0
  15. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/documentation.cpython-310.pyc +0 -0
  16. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc +0 -0
  17. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc +0 -0
  18. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_ctrlora.cpython-310.pyc +0 -0
  19. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc +0 -0
  20. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc +0 -0
  21. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc +0 -0
  22. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_main.cpython-310.pyc +0 -0
  23. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_plusplus.cpython-310.pyc +0 -0
  24. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc +0 -0
  25. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc +0 -0
  26. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc +0 -0
  27. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/sampling.cpython-310.pyc +0 -0
  28. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc +0 -0
  29. ComfyUI-Advanced-ControlNet/adv_control/control.py +982 -0
  30. ComfyUI-Advanced-ControlNet/adv_control/control_ctrlora.py +231 -0
  31. ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py +427 -0
  32. ComfyUI-Advanced-ControlNet/adv_control/control_plusplus.py +485 -0
  33. ComfyUI-Advanced-ControlNet/adv_control/control_reference.py +1206 -0
  34. ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py +319 -0
  35. ComfyUI-Advanced-ControlNet/adv_control/control_svd.py +518 -0
  36. ComfyUI-Advanced-ControlNet/adv_control/dinklink.py +112 -0
  37. ComfyUI-Advanced-ControlNet/adv_control/documentation.py +47 -0
  38. ComfyUI-Advanced-ControlNet/adv_control/logger.py +36 -0
  39. ComfyUI-Advanced-ControlNet/adv_control/nodes.py +136 -0
  40. ComfyUI-Advanced-ControlNet/adv_control/nodes_ctrlora.py +25 -0
  41. ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py +416 -0
  42. ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py +482 -0
  43. ComfyUI-Advanced-ControlNet/adv_control/nodes_loosecontrol.py +67 -0
  44. ComfyUI-Advanced-ControlNet/adv_control/nodes_main.py +212 -0
  45. ComfyUI-Advanced-ControlNet/adv_control/nodes_plusplus.py +88 -0
  46. ComfyUI-Advanced-ControlNet/adv_control/nodes_reference.py +90 -0
  47. ComfyUI-Advanced-ControlNet/adv_control/nodes_sparsectrl.py +188 -0
  48. ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py +329 -0
  49. ComfyUI-Advanced-ControlNet/adv_control/sampling.py +225 -0
  50. ComfyUI-Advanced-ControlNet/adv_control/utils.py +924 -0
.gitattributes CHANGED
@@ -57,3 +57,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ comfyui-easy-use/py/modules/kolors/chatglm/tokenizer/vocab.txt filter=lfs diff=lfs merge=lfs -text
61
+ comfyui-easy-use/resources/OpenSans-Medium.ttf filter=lfs diff=lfs merge=lfs -text
62
+ comfyui_controlnet_aux/NotoSans-Regular.ttf filter=lfs diff=lfs merge=lfs -text
63
+ comfyui_controlnet_aux/src/custom_controlnet_aux/mesh_graphormer/hand_landmarker.task filter=lfs diff=lfs merge=lfs -text
64
+ efficiency-nodes-comfyui/__pycache__/efficiency_nodes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
65
+ efficiency-nodes-comfyui/arial.ttf filter=lfs diff=lfs merge=lfs -text
66
+ was-node-suite-comfyui/__pycache__/WAS_Node_Suite.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
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-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-Advanced-ControlNet/README.md ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
16
+ - ControlNet++ support
17
+ - CtrLoRA support
18
+ - Relevant models linked on [CtrLoRA github page](https://github.com/xyfJASON/ctrlora)
19
+ - SparseCtrl support
20
+ - SVD-ControlNet support
21
+ - 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)
22
+ - Reference support
23
+ - 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.
24
+
25
+ ## Table of Contents:
26
+ - [Scheduling Explanation](#scheduling-explanation)
27
+ - [Nodes](#nodes)
28
+ - [Usage](#usage) (will fill this out soon)
29
+
30
+
31
+ # Scheduling Explanation
32
+
33
+ The two core concepts for scheduling are ***Timestep Keyframes*** and ***Latent Keyframes***.
34
+
35
+ ***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.
36
+
37
+ ***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.
38
+
39
+ ![advcn_image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/e6275264-6c3f-4246-a319-111ee48f4cd9)
40
+
41
+ # Nodes
42
+
43
+ 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).
44
+
45
+ Key:
46
+ - 🟩 - required inputs
47
+ - 🟨 - optional inputs
48
+ - 🟦 - start as widgets, can be converted to inputs
49
+ - 🟥 - optional input/output, but not recommended to use unless needed
50
+ - 🟪 - output
51
+
52
+ ## Apply Advanced ControlNet
53
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/dc541d41-70df-4a71-b832-efa65af98f06)
54
+
55
+ 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.
56
+
57
+ ### Inputs
58
+ - 🟩***positive***: conditioning (positive).
59
+ - 🟩***negative***: conditioning (negative).
60
+ - 🟩***control_net***: loaded controlnet; will be converted to Advanced version automatically by this node, if it's a supported type.
61
+ - 🟩***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.
62
+ - 🟨***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.
63
+ - 🟨***timestep_kf***: timestep keyframes to guide controlnet effect throughout sampling steps.
64
+ - 🟨***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.*
65
+ - 🟨***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.*
66
+ - 🟦***strength***: strength of controlnet; 1.0 is full strength, 0.0 is no effect at all.
67
+ - 🟦***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.
68
+ - 🟦***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.
69
+
70
+ ### Outputs
71
+ - 🟪***positive***: conditioning (positive) with applied controlnets
72
+ - 🟪***negative***: conditioning (negative) with applied controlnets
73
+
74
+ ## Load Advanced ControlNet Model
75
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/4a7f58a9-783d-4da4-bf82-bc9c167e4722)
76
+
77
+ 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.
78
+
79
+ ### Inputs
80
+ - 🟥***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.
81
+ - 🟨***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.
82
+
83
+ ### Outputs
84
+ - 🟪***CONTROL_NET***: loaded Advanced ControlNet
85
+
86
+ ## Timestep Keyframe
87
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/404f3cfe-5852-4eed-935b-37e32493d1b5)
88
+
89
+ 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.
90
+
91
+ ### Inputs
92
+ - 🟨***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.*
93
+ - 🟨***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.*
94
+ - 🟨***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.*
95
+ - 🟨***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.
96
+ - 🟦***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.
97
+ - 🟦***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.
98
+ - 🟦***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.
99
+ - 🟦***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.
100
+ - 🟦***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.
101
+
102
+ ### Outputs
103
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
104
+
105
+ ## Timestep Keyframe Interpolation
106
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9789617c-202c-4271-92a2-0909bcf9b108)
107
+
108
+ 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).
109
+
110
+ ### Inputs
111
+ - 🟨***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.*
112
+ - 🟨***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.*
113
+ - 🟨***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.*
114
+ - 🟨***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.
115
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
116
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
117
+ - 🟦***strength_start***: strength of the Timestep Keyframe at start of range.
118
+ - 🟦***strength_end***: strength of the Timestep Keyframe at end of range.
119
+ - 🟦***interpolation***: the method of interpolation.
120
+ - 🟦***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.
121
+ - 🟦***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.
122
+ - 🟦***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.
123
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
124
+
125
+ ### Outputs
126
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
127
+
128
+ ## Timestep Keyframe From List
129
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9e9c23bf-6f82-4ce7-b4d1-3016fd14707d)
130
+
131
+ 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).
132
+
133
+ ### Inputs
134
+ - 🟨***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.*
135
+ - 🟨***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.*
136
+ - 🟨***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.*
137
+ - 🟨***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.
138
+ - 🟩***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.
139
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
140
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
141
+ - 🟦***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.
142
+ - 🟦***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.
143
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
144
+
145
+ ### Outputs
146
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
147
+
148
+ ## Latent Keyframe
149
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7eb2cc4c-255c-4f32-b09b-699f713fada3)
150
+
151
+ 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.
152
+
153
+ ### Inputs
154
+ - 🟨***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.*
155
+ - 🟦***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.
156
+ - 🟦***strength***: strength of controlnet to apply to the corresponding latent.
157
+
158
+ ### Outputs
159
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
160
+
161
+ ## Latent Keyframe Group
162
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/5ce3b795-f5fc-4dc3-ae30-a4c7f87e278c)
163
+
164
+ Allows to create Latent Keyframes via individual indeces or python-style ranges.
165
+
166
+ ### Inputs
167
+ - 🟨***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.*
168
+ - 🟨***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).
169
+ - 🟦***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```.
170
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
171
+
172
+ ### Outputs
173
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
174
+
175
+ ## Latent Keyframe Interpolation
176
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7986c737-83b9-46bc-aab0-ae4c368df446)
177
+
178
+ Allows to create Latent Keyframes with interpolated values in a range.
179
+
180
+ ### Inputs
181
+ - 🟨***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.*
182
+ - 🟦***batch_index_from***: starting batch_index of range, included.
183
+ - 🟦***batch_index_to***: end batch_index of range, excluded (python-style range).
184
+ - 🟦***strength_from***: starting strength of interpolation.
185
+ - 🟦***strength_to***: end strength of interpolation.
186
+ - 🟦***interpolation***: the method of interpolation.
187
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
188
+
189
+ ### Outputs
190
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
191
+
192
+ ## Latent Keyframe From List
193
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/6cec701f-6183-4aeb-af5c-cac76f5591b7)
194
+
195
+ 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.
196
+
197
+ ### Inputs
198
+ - 🟨***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.*
199
+ - 🟩***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.
200
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
201
+
202
+ ### Outputs
203
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
204
+
205
+ # There are more nodes to document and show usage - will add this soon! TODO
ComfyUI-Advanced-ControlNet/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .adv_control.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+ from .adv_control import documentation
3
+ from .adv_control.dinklink import init_dinklink
4
+ from .adv_control.sampling import prepare_dinklink_acn_wrapper
5
+
6
+ WEB_DIRECTORY = "./web"
7
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', "WEB_DIRECTORY"]
8
+ documentation.format_descriptions(NODE_CLASS_MAPPINGS)
9
+
10
+ init_dinklink()
11
+ prepare_dinklink_acn_wrapper()
ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (553 Bytes). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc ADDED
Binary file (29.5 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_ctrlora.cpython-310.pyc ADDED
Binary file (6.56 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_plusplus.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc ADDED
Binary file (35.5 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/dinklink.cpython-310.pyc ADDED
Binary file (4.62 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/documentation.cpython-310.pyc ADDED
Binary file (1.86 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (5.72 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_ctrlora.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc ADDED
Binary file (2.24 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_main.cpython-310.pyc ADDED
Binary file (5.73 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_plusplus.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc ADDED
Binary file (3.47 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc ADDED
Binary file (9.33 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/sampling.cpython-310.pyc ADDED
Binary file (6.58 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc ADDED
Binary file (31.3 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/control.py ADDED
@@ -0,0 +1,982 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, ControlNetSD35, ControlLora, T2IAdapter, StrengthType
12
+ from comfy.model_patcher import ModelPatcher
13
+
14
+ from .control_sparsectrl import SparseControlNet, SparseSettings, SparseConst, InterfaceAnimateDiffModel, create_sparse_modelpatcher, load_sparsectrl_motionmodel
15
+ from .control_lllite import LLLiteModule, LLLitePatch, load_controllllite
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, Extras,
18
+ manual_cast_clean_groupnorm, disable_weight_init_clean_groupnorm, WrapperConsts, prepare_mask_batch, get_properly_arranged_t2i_weights, load_torch_file_with_dict_factory,
19
+ broadcast_image_to_extend, extend_to_batch_size, ORIG_PREVIOUS_CONTROLNET, CONTROL_INIT_BY_ACN)
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, load_device=None, manual_cast_dtype=None,
25
+ extra_conds=["y"], strength_type=StrengthType.CONSTANT, concat_mask=False, preprocess_image=lambda a: a):
26
+ super().__init__(control_model=control_model, global_average_pooling=global_average_pooling, compression_ratio=compression_ratio, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype,
27
+ extra_conds=extra_conds, strength_type=strength_type, concat_mask=concat_mask, preprocess_image=preprocess_image)
28
+ AdvancedControlBase.__init__(self, super(type(self), self), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controlnet())
29
+ self.is_flux = False
30
+ self.x_noisy_shape = None
31
+
32
+ def get_universal_weights(self) -> ControlWeights:
33
+ def cn_weights_func(idx: int, control: dict[str, list[Tensor]], key: str):
34
+ if key == "middle":
35
+ return 1.0 * self.weights.extras.get(Extras.MIDDLE_MULT, 1.0)
36
+ c_len = len(control[key])
37
+ raw_weights = [(self.weights.base_multiplier ** float((c_len) - i)) for i in range(c_len+1)]
38
+ raw_weights = raw_weights[:-1]
39
+ if key == "input":
40
+ raw_weights.reverse()
41
+ return raw_weights[idx]
42
+ return self.weights.copy_with_new_weights(new_weight_func=cn_weights_func)
43
+
44
+ def get_control_advanced(self, x_noisy, t, cond, batched_number, transformer_options):
45
+ # perform special version of get_control that supports sliding context and masks
46
+ return self.sliding_get_control(x_noisy, t, cond, batched_number, transformer_options)
47
+
48
+ def sliding_get_control(self, x_noisy: Tensor, t, cond, batched_number, transformer_options):
49
+ control_prev = None
50
+ if self.previous_controlnet is not None:
51
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
52
+
53
+ if self.timestep_range is not None:
54
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
55
+ if control_prev is not None:
56
+ return control_prev
57
+ else:
58
+ return None
59
+
60
+ dtype = self.control_model.dtype
61
+ if self.manual_cast_dtype is not None:
62
+ dtype = self.manual_cast_dtype
63
+
64
+ # make cond_hint appropriate dimensions
65
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
66
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * self.real_compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.real_compression_ratio != self.cond_hint.shape[3]:
67
+ if self.cond_hint is not None:
68
+ del self.cond_hint
69
+ self.cond_hint = None
70
+ self.real_compression_ratio = self.compression_ratio
71
+ compression_ratio = self.compression_ratio
72
+ if self.vae is not None and self.mult_by_ratio_when_vae:
73
+ compression_ratio *= self.vae.downscale_ratio
74
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
75
+ if self.sub_idxs is not None:
76
+ actual_cond_hint_orig = self.cond_hint_original
77
+ if self.cond_hint_original.size(0) < self.full_latent_length:
78
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
79
+ 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, self.upscale_algorithm, "center")
80
+ else:
81
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, self.upscale_algorithm, "center")
82
+ self.cond_hint = self.preprocess_image(self.cond_hint)
83
+ if self.vae is not None:
84
+ loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
85
+ self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
86
+ comfy.model_management.load_models_gpu(loaded_models)
87
+ if not self.mult_by_ratio_when_vae:
88
+ self.real_compression_ratio = 1
89
+ if self.latent_format is not None:
90
+ self.cond_hint = self.latent_format.process_in(self.cond_hint)
91
+ if len(self.extra_concat_orig) > 0:
92
+ to_concat = []
93
+ for c in self.extra_concat_orig:
94
+ c = c.to(self.cond_hint.device)
95
+ c = comfy.utils.common_upscale(c, self.cond_hint.shape[3], self.cond_hint.shape[2], self.upscale_algorithm, "center")
96
+ to_concat.append(comfy.utils.repeat_to_batch_size(c, self.cond_hint.shape[0]))
97
+ self.cond_hint = torch.cat([self.cond_hint] + to_concat, dim=1)
98
+
99
+ self.cond_hint = self.cond_hint.to(device=x_noisy.device, dtype=dtype)
100
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
101
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
102
+
103
+ # prepare mask_cond_hint
104
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
105
+
106
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
107
+ extra = self.extra_args.copy()
108
+ for c in self.extra_conds:
109
+ temp = cond.get(c, None)
110
+ if temp is not None:
111
+ extra[c] = temp.to(dtype)
112
+
113
+ timestep = self.model_sampling_current.timestep(t)
114
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
115
+ self.x_noisy_shape = x_noisy.shape
116
+
117
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra)
118
+ return self.control_merge(control, control_prev, output_dtype=None)
119
+
120
+ def pre_run_advanced(self, *args, **kwargs):
121
+ self.is_flux = "Flux" in str(type(self.control_model).__name__)
122
+ return super().pre_run_advanced(*args, **kwargs)
123
+
124
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int, flux_shape=None):
125
+ if self.is_flux:
126
+ flux_shape = self.x_noisy_shape
127
+ return super().apply_advanced_strengths_and_masks(x, batched_number, flux_shape)
128
+
129
+ def copy(self, subtype=None):
130
+ if subtype is None:
131
+ subtype = ControlNetAdvanced
132
+ c = subtype(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)
133
+ c.control_model = self.control_model
134
+ c.control_model_wrapped = self.control_model_wrapped
135
+ self.copy_to(c)
136
+ self.copy_to_advanced(c)
137
+ return c
138
+
139
+ def cleanup_advanced(self):
140
+ self.x_noisy_shape = None
141
+ return super().cleanup_advanced()
142
+
143
+ @staticmethod
144
+ def from_vanilla(v: ControlNet, timestep_keyframe: TimestepKeyframeGroup=None, subtype=None) -> 'ControlNetAdvanced':
145
+ if subtype is None:
146
+ subtype = ControlNetAdvanced
147
+ to_return = subtype(control_model=v.control_model, timestep_keyframes=timestep_keyframe,
148
+ global_average_pooling=v.global_average_pooling, compression_ratio=v.compression_ratio, latent_format=v.latent_format, load_device=v.load_device,
149
+ manual_cast_dtype=v.manual_cast_dtype, extra_conds=v.extra_conds, strength_type=v.strength_type, concat_mask=v.concat_mask, preprocess_image=v.preprocess_image)
150
+ v.copy_to(to_return)
151
+ to_return.control_model_wrapped = v.control_model_wrapped.clone() # needed to avoid breaking memory management system (parent tracking)
152
+ return to_return
153
+
154
+
155
+ class ControlNetSD35Advanced(ControlNetSD35, ControlNetAdvanced):
156
+ def __init__(self, *args, **kwargs):
157
+ ControlNetAdvanced.__init__(self, *args, **kwargs)
158
+
159
+ def copy(self):
160
+ return ControlNetAdvanced.copy(self, subtype=ControlNetSD35Advanced)
161
+
162
+ @staticmethod
163
+ def from_vanilla(v: ControlNetSD35, timestep_keyframe=None):
164
+ return ControlNetAdvanced.from_vanilla(v, timestep_keyframe, subtype=ControlNetSD35Advanced)
165
+
166
+
167
+ class T2IAdapterAdvanced(T2IAdapter, AdvancedControlBase):
168
+ def __init__(self, t2i_model, timestep_keyframes: TimestepKeyframeGroup, channels_in, compression_ratio=8, upscale_algorithm="nearest_exact", device=None):
169
+ super().__init__(t2i_model=t2i_model, channels_in=channels_in, compression_ratio=compression_ratio, upscale_algorithm=upscale_algorithm, device=device)
170
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.t2iadapter())
171
+
172
+ def control_merge_inject(self, control: dict[str, list[Tensor]], control_prev, output_dtype):
173
+ # match batch_size
174
+ # TODO: make this more efficient by modifying the cached self.control_input val instead of doing this every step
175
+ for key in control:
176
+ control_current = control[key]
177
+ for i in range(len(control_current)):
178
+ x = control_current[i]
179
+ if x is not None and x.size(0) == 1 and x.size(0) != self.batch_size:
180
+ control_current[i] = x.repeat(self.batch_size, 1, 1, 1)[:self.batch_size]
181
+ return AdvancedControlBase.control_merge_inject(self, control, control_prev, output_dtype)
182
+
183
+ def get_universal_weights(self) -> ControlWeights:
184
+ def t2i_weights_func(idx: int, control: dict[str, list[Tensor]], key: str):
185
+ if key == "middle":
186
+ return 1.0 * self.weights.extras.get(Extras.MIDDLE_MULT, 1.0)
187
+ c_len = 8 #len(control[key])
188
+ raw_weights = [(self.weights.base_multiplier ** float((c_len-1) - i)) for i in range(c_len)]
189
+ raw_weights = [raw_weights[-c_len], raw_weights[-3], raw_weights[-2], raw_weights[-1]]
190
+ raw_weights = get_properly_arranged_t2i_weights(raw_weights)
191
+ if key == "input":
192
+ raw_weights.reverse()
193
+ return raw_weights[idx]
194
+ return self.weights.copy_with_new_weights(new_weight_func=t2i_weights_func)
195
+
196
+ def get_calc_pow(self, idx: int, control: dict[str, list[Tensor]], key: str) -> int:
197
+ if key == "middle":
198
+ return 0
199
+ # match how T2IAdapterAdvanced deals with universal weights
200
+ c_len = 8 #len(control[key])
201
+ indeces = [(c_len-1) - i for i in range(c_len)]
202
+ indeces = [indeces[-c_len], indeces[-3], indeces[-2], indeces[-1]]
203
+ indeces = get_properly_arranged_t2i_weights(indeces)
204
+ if key == "input":
205
+ indeces.reverse() # need to reverse to match recent ComfyUI changes
206
+ return indeces[idx]
207
+
208
+ def get_control_advanced(self, x_noisy, t, cond, batched_number, transformer_options):
209
+ try:
210
+ # if sub indexes present, replace original hint with subsection
211
+ if self.sub_idxs is not None:
212
+ # cond hints
213
+ full_cond_hint_original = self.cond_hint_original
214
+ actual_cond_hint_orig = full_cond_hint_original
215
+ del self.cond_hint
216
+ self.cond_hint = None
217
+ if full_cond_hint_original.size(0) < self.full_latent_length:
218
+ actual_cond_hint_orig = extend_to_batch_size(tensor=full_cond_hint_original, batch_size=full_cond_hint_original.size(0))
219
+ self.cond_hint_original = actual_cond_hint_orig[self.sub_idxs]
220
+ # mask hints
221
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
222
+ return super().get_control(x_noisy, t, cond, batched_number, transformer_options)
223
+ finally:
224
+ if self.sub_idxs is not None:
225
+ # replace original cond hint
226
+ self.cond_hint_original = full_cond_hint_original
227
+ del full_cond_hint_original
228
+
229
+ def copy(self):
230
+ c = T2IAdapterAdvanced(self.t2i_model, self.timestep_keyframes, self.channels_in, self.compression_ratio, self.upscale_algorithm)
231
+ self.copy_to(c)
232
+ self.copy_to_advanced(c)
233
+ return c
234
+
235
+ def cleanup(self):
236
+ super().cleanup()
237
+ self.cleanup_advanced()
238
+
239
+ @staticmethod
240
+ def from_vanilla(v: T2IAdapter, timestep_keyframe: TimestepKeyframeGroup=None) -> 'T2IAdapterAdvanced':
241
+ to_return = T2IAdapterAdvanced(t2i_model=v.t2i_model, timestep_keyframes=timestep_keyframe, channels_in=v.channels_in,
242
+ compression_ratio=v.compression_ratio, upscale_algorithm=v.upscale_algorithm, device=v.device)
243
+ v.copy_to(to_return)
244
+ return to_return
245
+
246
+
247
+ class ControlLoraAdvanced(ControlLora, AdvancedControlBase):
248
+ def __init__(self, control_weights, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False):
249
+ super().__init__(control_weights=control_weights, global_average_pooling=global_average_pooling)
250
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllora())
251
+ # use some functions from ControlNetAdvanced
252
+ self.get_control_advanced = ControlNetAdvanced.get_control_advanced.__get__(self, type(self))
253
+ self.sliding_get_control = ControlNetAdvanced.sliding_get_control.__get__(self, type(self))
254
+
255
+ def get_universal_weights(self) -> ControlWeights:
256
+ raw_weights = [(self.weights.base_multiplier ** float(9 - i)) for i in range(10)]
257
+ return self.weights.copy_with_new_weights(raw_weights)
258
+
259
+ def copy(self):
260
+ c = ControlLoraAdvanced(self.control_weights, self.timestep_keyframes, global_average_pooling=self.global_average_pooling)
261
+ self.copy_to(c)
262
+ self.copy_to_advanced(c)
263
+ return c
264
+
265
+ def cleanup(self):
266
+ super().cleanup()
267
+ self.cleanup_advanced()
268
+
269
+ @staticmethod
270
+ def from_vanilla(v: ControlLora, timestep_keyframe: TimestepKeyframeGroup=None) -> 'ControlLoraAdvanced':
271
+ to_return = ControlLoraAdvanced(control_weights=v.control_weights, timestep_keyframes=timestep_keyframe,
272
+ global_average_pooling=v.global_average_pooling)
273
+ v.copy_to(to_return)
274
+ return to_return
275
+
276
+
277
+ class SVDControlNetAdvanced(ControlNetAdvanced):
278
+ def __init__(self, control_model: SVDControlNet, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, load_device=None, manual_cast_dtype=None):
279
+ super().__init__(control_model=control_model, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
280
+
281
+ def set_cond_hint_inject(self, *args, **kwargs):
282
+ to_return = super().set_cond_hint_inject(*args, **kwargs)
283
+ # cond hint for SVD-ControlNet needs to be scaled between (-1, 1) instead of (0, 1)
284
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
285
+ return to_return
286
+
287
+ def get_control_advanced(self, x_noisy, t, cond, batched_number, transformer_options):
288
+ control_prev = None
289
+ if self.previous_controlnet is not None:
290
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
291
+
292
+ if self.timestep_range is not None:
293
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
294
+ if control_prev is not None:
295
+ return control_prev
296
+ else:
297
+ return None
298
+
299
+ dtype = self.control_model.dtype
300
+ if self.manual_cast_dtype is not None:
301
+ dtype = self.manual_cast_dtype
302
+
303
+ output_dtype = x_noisy.dtype
304
+ # make cond_hint appropriate dimensions
305
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
306
+ 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]:
307
+ if self.cond_hint is not None:
308
+ del self.cond_hint
309
+ self.cond_hint = None
310
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
311
+ if self.sub_idxs is not None:
312
+ actual_cond_hint_orig = self.cond_hint_original
313
+ if self.cond_hint_original.size(0) < self.full_latent_length:
314
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
315
+ 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(x_noisy.device)
316
+ else:
317
+ 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(x_noisy.device)
318
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
319
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
320
+
321
+ # prepare mask_cond_hint
322
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
323
+
324
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
325
+ # uses 'y' in new ComfyUI update
326
+ y = cond.get('y', None)
327
+ if y is not None:
328
+ y = y.to(dtype)
329
+ timestep = self.model_sampling_current.timestep(t)
330
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
331
+ # concat c_concat if exists (should exist for SVD), doubling channels to 8
332
+ if cond.get('c_concat', None) is not None:
333
+ x_noisy = torch.cat([x_noisy] + [cond['c_concat']], dim=1)
334
+
335
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, cond=cond)
336
+ return self.control_merge(control, control_prev, output_dtype)
337
+
338
+ def copy(self):
339
+ 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)
340
+ self.copy_to(c)
341
+ self.copy_to_advanced(c)
342
+ return c
343
+
344
+
345
+ class SparseCtrlAdvanced(ControlNetAdvanced):
346
+ def __init__(self, control_model: SparseControlNet, motion_model: InterfaceAnimateDiffModel,
347
+ timestep_keyframes: TimestepKeyframeGroup, sparse_settings: SparseSettings=None, global_average_pooling=False, load_device=None, manual_cast_dtype=None):
348
+ super().__init__(control_model=None, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
349
+ self.control_model = control_model
350
+ if control_model is not None:
351
+ self.control_model_wrapped: ModelPatcher = create_sparse_modelpatcher(self.control_model, motion_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
352
+ self.prepare_conditioning_info()
353
+ self.add_compatible_weight(ControlWeightType.SPARSECTRL)
354
+ self.postpone_condhint_latents_check = True
355
+ self.sparse_settings = sparse_settings if sparse_settings is not None else SparseSettings.default()
356
+ self.model_latent_format = None # latent format for active SD model, NOT controlnet
357
+ self.preprocessed = False
358
+
359
+ def prepare_conditioning_info(self):
360
+ if self.control_model.use_simplified_conditioning_embedding:
361
+ # TODO: allow vae_optional to be used instead of preprocessor
362
+ #self.require_vae = True
363
+ self.allow_condhint_latents = True
364
+
365
+ @property
366
+ def motion_model(self) -> InterfaceAnimateDiffModel:
367
+ motion_models = self.control_model_wrapped.get_additional_models_with_key(WrapperConsts.ACN)
368
+ if len(motion_models) == 0:
369
+ return None
370
+ return motion_models[0].model
371
+
372
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int, transformer_options):
373
+ # normal ControlNet stuff
374
+ control_prev = None
375
+ if self.previous_controlnet is not None:
376
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
377
+
378
+ if self.timestep_range is not None:
379
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
380
+ if control_prev is not None:
381
+ return control_prev
382
+ else:
383
+ return None
384
+
385
+ dtype = self.control_model.dtype
386
+ if self.manual_cast_dtype is not None:
387
+ dtype = self.manual_cast_dtype
388
+ output_dtype = x_noisy.dtype
389
+ # set actual input length on motion model
390
+ actual_length = x_noisy.size(0)//batched_number
391
+ full_length = actual_length if self.sub_idxs is None else self.full_latent_length
392
+ if self.motion_model is not None:
393
+ self.motion_model.set_video_length(video_length=actual_length, full_length=full_length)
394
+ # prepare cond_hint, if needed
395
+ dim_mult = 1 if self.control_model.use_simplified_conditioning_embedding else 8
396
+ 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]:
397
+ # clear out cond_hint and conditioning_mask
398
+ if self.cond_hint is not None:
399
+ del self.cond_hint
400
+ self.cond_hint = None
401
+ # first, figure out which cond idxs are relevant, and where they fit in
402
+ cond_idxs, hint_order = self.sparse_settings.sparse_method.get_indexes(hint_length=self.cond_hint_original.size(0), full_length=full_length,
403
+ sub_idxs=self.sub_idxs if self.sparse_settings.is_context_aware() else None)
404
+ range_idxs = list(range(full_length)) if self.sub_idxs is None else self.sub_idxs
405
+ hint_idxs = [] # idxs in cond_idxs
406
+ local_idxs = [] # idx to put in final cond_hint
407
+ for i,cond_idx in enumerate(cond_idxs):
408
+ if cond_idx in range_idxs:
409
+ hint_idxs.append(i)
410
+ local_idxs.append(range_idxs.index(cond_idx))
411
+ # log_string = f"cond_idxs: {cond_idxs}, local_idxs: {local_idxs}, hint_idxs: {hint_idxs}, hint_order: {hint_order}"
412
+ # if self.sub_idxs is not None:
413
+ # log_string += f" sub_idxs: {self.sub_idxs[0]}-{self.sub_idxs[-1]}"
414
+ # logger.warn(log_string)
415
+ # determine cond/uncond indexes that will get masked
416
+ self.local_sparse_idxs = []
417
+ self.local_sparse_idxs_inverse = list(range(x_noisy.size(0)))
418
+ for batch_idx in range(batched_number):
419
+ for i in local_idxs:
420
+ actual_i = i+(batch_idx*actual_length)
421
+ self.local_sparse_idxs.append(actual_i)
422
+ if actual_i in self.local_sparse_idxs_inverse:
423
+ self.local_sparse_idxs_inverse.remove(actual_i)
424
+ # sub_cond_hint now contains the hints relevant to current x_noisy
425
+ if hint_order is None:
426
+ sub_cond_hint = self.cond_hint_original[hint_idxs].to(dtype).to(x_noisy.device)
427
+ else:
428
+ sub_cond_hint = self.cond_hint_original[hint_order][hint_idxs].to(dtype).to(x_noisy.device)
429
+ # scale cond_hints to match noisy input
430
+ if self.control_model.use_simplified_conditioning_embedding:
431
+ # RGB SparseCtrl; the inputs are latents - use bilinear to avoid blocky artifacts
432
+ sub_cond_hint = self.model_latent_format.process_in(sub_cond_hint) # multiplies by model scale factor
433
+ sub_cond_hint = comfy.utils.common_upscale(sub_cond_hint, x_noisy.shape[3], x_noisy.shape[2], "nearest-exact", "center").to(dtype).to(x_noisy.device)
434
+ else:
435
+ # other SparseCtrl; inputs are typical images
436
+ 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(x_noisy.device)
437
+ # prepare cond_hint (b, c, h ,w)
438
+ cond_shape = list(sub_cond_hint.shape)
439
+ cond_shape[0] = len(range_idxs)
440
+ self.cond_hint = torch.zeros(cond_shape).to(dtype).to(x_noisy.device)
441
+ self.cond_hint[local_idxs] = sub_cond_hint[:]
442
+ # prepare cond_mask (b, 1, h, w)
443
+ cond_shape[1] = 1
444
+ cond_mask = torch.zeros(cond_shape).to(dtype).to(x_noisy.device)
445
+ cond_mask[local_idxs] = self.sparse_settings.sparse_mask_mult * self.weights.extras.get(SparseConst.MASK_MULT, 1.0)
446
+ # combine cond_hint and cond_mask into (b, c+1, h, w)
447
+ if not self.sparse_settings.merged:
448
+ self.cond_hint = torch.cat([self.cond_hint, cond_mask], dim=1)
449
+ del sub_cond_hint
450
+ del cond_mask
451
+ # make cond_hint match x_noisy batch
452
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
453
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
454
+
455
+ # prepare mask_cond_hint
456
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
457
+
458
+ context = cond['c_crossattn']
459
+ y = cond.get('y', None)
460
+ if y is not None:
461
+ y = y.to(dtype)
462
+ timestep = self.model_sampling_current.timestep(t)
463
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
464
+
465
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
466
+ return self.control_merge(control, control_prev, output_dtype)
467
+
468
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int, *args, **kwargs):
469
+ # apply mults to indexes with and without a direct condhint
470
+ x[self.local_sparse_idxs] *= self.sparse_settings.sparse_hint_mult * self.weights.extras.get(SparseConst.HINT_MULT, 1.0)
471
+ x[self.local_sparse_idxs_inverse] *= self.sparse_settings.sparse_nonhint_mult * self.weights.extras.get(SparseConst.NONHINT_MULT, 1.0)
472
+ return super().apply_advanced_strengths_and_masks(x, batched_number, *args, **kwargs)
473
+
474
+ def pre_run_advanced(self, model, percent_to_timestep_function):
475
+ super().pre_run_advanced(model, percent_to_timestep_function)
476
+ if isinstance(self.cond_hint_original, AbstractPreprocWrapper):
477
+ if not self.control_model.use_simplified_conditioning_embedding:
478
+ raise ValueError("Any model besides RGB SparseCtrl should NOT have its images go through the RGB SparseCtrl preprocessor.")
479
+ self.cond_hint_original = self.cond_hint_original.condhint
480
+ self.model_latent_format = model.latent_format # LatentFormat object, used to process_in latent cond hint
481
+ if self.motion_model is not None:
482
+ self.motion_model.cleanup()
483
+ self.motion_model.set_effect(self.sparse_settings.motion_strength)
484
+ self.motion_model.set_scale(self.sparse_settings.motion_scale)
485
+
486
+ def cleanup_advanced(self):
487
+ super().cleanup_advanced()
488
+ if self.model_latent_format is not None:
489
+ del self.model_latent_format
490
+ self.model_latent_format = None
491
+ self.local_sparse_idxs = None
492
+ self.local_sparse_idxs_inverse = None
493
+ if self.motion_model is not None:
494
+ self.motion_model.cleanup()
495
+
496
+ def copy(self):
497
+ c = SparseCtrlAdvanced(None, None, self.timestep_keyframes, self.sparse_settings, self.global_average_pooling, self.load_device, self.manual_cast_dtype)
498
+ c.control_model = self.control_model
499
+ c.control_model_wrapped = self.control_model_wrapped
500
+ self.prepare_conditioning_info()
501
+ self.copy_to(c)
502
+ self.copy_to_advanced(c)
503
+ return c
504
+
505
+ def get_models(self):
506
+ to_return = super().get_models()
507
+ to_return.extend(self.control_model_wrapped.get_additional_models())
508
+ return to_return
509
+
510
+
511
+ def load_controlnet(ckpt_path, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
512
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
513
+ # from pathlib import Path
514
+ # log_name = ckpt_path.split('\\')[-1]
515
+ # with open(Path(__file__).parent.parent.parent / rf"keys_{log_name}.txt", "w") as afile:
516
+ # for key, value in controlnet_data.items():
517
+ # afile.write(f"{key}:\t{value.shape}\n")
518
+ control = None
519
+ # check if a non-vanilla ControlNet
520
+ controlnet_type = ControlWeightType.DEFAULT
521
+ has_controlnet_key = False
522
+ has_motion_modules_key = False
523
+ has_temporal_res_block_key = False
524
+ for key in controlnet_data:
525
+ # LLLite check
526
+ if "lllite" in key:
527
+ controlnet_type = ControlWeightType.CONTROLLLLITE
528
+ break
529
+ # SparseCtrl check
530
+ elif "motion_modules" in key:
531
+ has_motion_modules_key = True
532
+ elif "controlnet" in key:
533
+ has_controlnet_key = True
534
+ # SVD-ControlNet check
535
+ elif "temporal_res_block" in key:
536
+ has_temporal_res_block_key = True
537
+ # ControlNet++ check
538
+ elif "task_embedding" in key:
539
+ pass
540
+ # CtrLoRA check
541
+ elif "lora_layer" in key:
542
+ controlnet_type = ControlWeightType.CTRLORA
543
+ break
544
+
545
+ if has_controlnet_key and has_motion_modules_key:
546
+ controlnet_type = ControlWeightType.SPARSECTRL
547
+ elif has_controlnet_key and has_temporal_res_block_key:
548
+ controlnet_type = ControlWeightType.SVD_CONTROLNET
549
+
550
+ if controlnet_type != ControlWeightType.DEFAULT:
551
+ if controlnet_type == ControlWeightType.CONTROLLLLITE:
552
+ control = load_controllllite(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
553
+ elif controlnet_type == ControlWeightType.SPARSECTRL:
554
+ control = load_sparsectrl(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe, model=model)
555
+ elif controlnet_type == ControlWeightType.SVD_CONTROLNET:
556
+ control = load_svdcontrolnet(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
557
+ elif controlnet_type == ControlWeightType.CTRLORA:
558
+ raise Exception("This is a CtrLoRA; use the Load CtrLoRA Model node.")
559
+ # otherwise, load vanilla ControlNet
560
+ else:
561
+ try:
562
+ # hacky way of getting load_torch_file in load_controlnet to use already-present controlnet_data and not redo loading
563
+ orig_load_torch_file = comfy.utils.load_torch_file
564
+ comfy.utils.load_torch_file = load_torch_file_with_dict_factory(controlnet_data, orig_load_torch_file)
565
+ control = comfy_cn.load_controlnet(ckpt_path, model=model)
566
+ finally:
567
+ comfy.utils.load_torch_file = orig_load_torch_file
568
+ if control is None:
569
+ raise Exception(f"Something went wrong when loading '{ckpt_path}'; ControlNet is None.")
570
+ return convert_to_advanced(control, timestep_keyframe=timestep_keyframe)
571
+
572
+
573
+ def convert_to_advanced(control, timestep_keyframe: TimestepKeyframeGroup=None):
574
+ # if already advanced, leave it be
575
+ if is_advanced_controlnet(control):
576
+ return control
577
+ # if exactly ControlNet returned, transform it into ControlNetAdvanced
578
+ if type(control) == ControlNet:
579
+ control = ControlNetAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
580
+ if is_sd3_advanced_controlnet(control):
581
+ control.require_vae = True
582
+ return control
583
+ # if exactly ControlNetSD35 returned, transform into ControlNetSD35Advanced
584
+ elif type(control) == ControlNetSD35:
585
+ control = ControlNetSD35Advanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
586
+ if is_sd3_advanced_controlnet(control):
587
+ control.require_vae = True
588
+ return control
589
+ # if exactly ControlLora returned, transform it into ControlLoraAdvanced
590
+ elif type(control) == ControlLora:
591
+ return ControlLoraAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
592
+ # if T2IAdapter returned, transform it into T2IAdapterAdvanced
593
+ elif isinstance(control, T2IAdapter):
594
+ return T2IAdapterAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
595
+ # otherwise, leave it be - might be something I am not supporting yet
596
+ return control
597
+
598
+
599
+ def convert_all_to_advanced(conds: dict[str, list[dict[str]]]) -> tuple[bool, list]:
600
+ cache = {}
601
+ modified = False
602
+ new_conds = {}
603
+ for cond_type in conds:
604
+ converted_cond: list[dict[str]] = None
605
+ cond = conds[cond_type]
606
+ if cond is not None:
607
+ for actual_cond in cond:
608
+ need_to_convert = False
609
+ if "control" in actual_cond:
610
+ if not are_all_advanced_controlnet(actual_cond["control"]):
611
+ need_to_convert = True
612
+ break
613
+ if not need_to_convert:
614
+ converted_cond = cond
615
+ else:
616
+ converted_cond = []
617
+ for actual_cond in cond:
618
+ if not isinstance(actual_cond, dict):
619
+ converted_cond.append(actual_cond)
620
+ continue
621
+ if "control" not in actual_cond:
622
+ converted_cond.append(actual_cond)
623
+ elif are_all_advanced_controlnet(actual_cond["control"]):
624
+ converted_cond.append(actual_cond)
625
+ else:
626
+ actual_cond = actual_cond.copy()
627
+ actual_cond["control"] = _convert_all_control_to_advanced(actual_cond["control"], cache)
628
+ converted_cond.append(actual_cond)
629
+ modified = True
630
+ new_conds[cond_type] = converted_cond
631
+ return modified, new_conds
632
+
633
+
634
+ def _convert_all_control_to_advanced(input_object: ControlBase, cache: dict):
635
+ output_object = input_object
636
+ # iteratively convert to advanced, if needed
637
+ next_cn = None
638
+ curr_cn = input_object
639
+ iter = 0
640
+ while curr_cn is not None:
641
+ if not is_advanced_controlnet(curr_cn):
642
+ # if already in cache, then conversion was done before, so just link it and exit
643
+ if curr_cn in cache:
644
+ new_cn = cache[curr_cn]
645
+ if next_cn is not None:
646
+ setattr(next_cn, ORIG_PREVIOUS_CONTROLNET, next_cn.previous_controlnet)
647
+ next_cn.previous_controlnet = new_cn
648
+ if iter == 0: # if was top-level controlnet, that's the new output
649
+ output_object = new_cn
650
+ break
651
+ try:
652
+ # convert to advanced, and assign previous_controlnet (convert doesn't transfer it)
653
+ new_cn = convert_to_advanced(curr_cn)
654
+ except Exception as e:
655
+ raise Exception("Failed to automatically convert a ControlNet to Advanced to support sliding window context.", e)
656
+ new_cn.previous_controlnet = curr_cn.previous_controlnet
657
+ if iter == 0: # if was top-level controlnet, that's the new output
658
+ output_object = new_cn
659
+ # if next_cn is present, then it needs to be pointed to new_cn
660
+ if next_cn is not None:
661
+ setattr(next_cn, ORIG_PREVIOUS_CONTROLNET, next_cn.previous_controlnet)
662
+ next_cn.previous_controlnet = new_cn
663
+ # add to cache
664
+ cache[curr_cn] = new_cn
665
+ curr_cn = new_cn
666
+ next_cn = curr_cn
667
+ curr_cn = curr_cn.previous_controlnet
668
+ iter += 1
669
+ return output_object
670
+
671
+
672
+ def restore_all_controlnet_conns(conds: dict[str, list[dict[str]]]):
673
+ # if a cn has an _orig_previous_controlnet property, restore it and delete
674
+ for cond_type in conds:
675
+ cond = conds[cond_type]
676
+ if cond is not None:
677
+ for actual_cond in cond:
678
+ if "control" in actual_cond:
679
+ # if ACN is the one to have initialized it, delete it
680
+ # TODO: maybe check if someone else did a similar hack, and carefully pluck out our stuff?
681
+ if CONTROL_INIT_BY_ACN in actual_cond:
682
+ actual_cond.pop("control")
683
+ actual_cond.pop(CONTROL_INIT_BY_ACN)
684
+ else:
685
+ _restore_all_controlnet_conns(actual_cond["control"])
686
+
687
+
688
+
689
+ def _restore_all_controlnet_conns(input_object: ControlBase):
690
+ # restore original previous_controlnet if needed
691
+ curr_cn = input_object
692
+ while curr_cn is not None:
693
+ if hasattr(curr_cn, ORIG_PREVIOUS_CONTROLNET):
694
+ curr_cn.previous_controlnet = getattr(curr_cn, ORIG_PREVIOUS_CONTROLNET)
695
+ delattr(curr_cn, ORIG_PREVIOUS_CONTROLNET)
696
+ curr_cn = curr_cn.previous_controlnet
697
+
698
+
699
+ def are_all_advanced_controlnet(input_object: ControlBase):
700
+ # iteratively check if linked controlnets objects are all advanced
701
+ curr_cn = input_object
702
+ while curr_cn is not None:
703
+ if not is_advanced_controlnet(curr_cn):
704
+ return False
705
+ curr_cn = curr_cn.previous_controlnet
706
+ return True
707
+
708
+
709
+ def is_advanced_controlnet(input_object):
710
+ return hasattr(input_object, "sub_idxs")
711
+
712
+
713
+ def is_sd3_advanced_controlnet(input_object: ControlNetAdvanced):
714
+ return type(input_object) in [ControlNetAdvanced, ControlNetSD35Advanced] and input_object.latent_format is not None
715
+
716
+
717
+ def load_sparsectrl(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, sparse_settings=SparseSettings.default(), model=None) -> SparseCtrlAdvanced:
718
+ if controlnet_data is None:
719
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
720
+ # first, separate out motion part from normal controlnet part and attempt to load that portion
721
+ motion_data = {}
722
+ for key in list(controlnet_data.keys()):
723
+ if "temporal" in key:
724
+ motion_data[key] = controlnet_data.pop(key)
725
+ if len(motion_data) == 0:
726
+ raise ValueError(f"No motion-related keys in '{ckpt_path}'; not a valid SparseCtrl model!")
727
+
728
+ # now, load as if it was a normal controlnet - mostly copied from comfy load_controlnet function
729
+ controlnet_config: dict[str] = None
730
+ is_diffusers = False
731
+ use_simplified_conditioning_embedding = False
732
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data:
733
+ is_diffusers = True
734
+ if "controlnet_cond_embedding.weight" in controlnet_data:
735
+ is_diffusers = True
736
+ use_simplified_conditioning_embedding = True
737
+ if is_diffusers: #diffusers format
738
+ unet_dtype = comfy.model_management.unet_dtype()
739
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
740
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
741
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
742
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
743
+
744
+ count = 0
745
+ loop = True
746
+ while loop:
747
+ suffix = [".weight", ".bias"]
748
+ for s in suffix:
749
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
750
+ k_out = "zero_convs.{}.0{}".format(count, s)
751
+ if k_in not in controlnet_data:
752
+ loop = False
753
+ break
754
+ diffusers_keys[k_in] = k_out
755
+ count += 1
756
+ # normal conditioning embedding
757
+ if not use_simplified_conditioning_embedding:
758
+ count = 0
759
+ loop = True
760
+ while loop:
761
+ suffix = [".weight", ".bias"]
762
+ for s in suffix:
763
+ if count == 0:
764
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
765
+ else:
766
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
767
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
768
+ if k_in not in controlnet_data:
769
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
770
+ loop = False
771
+ diffusers_keys[k_in] = k_out
772
+ count += 1
773
+ # simplified conditioning embedding
774
+ else:
775
+ count = 0
776
+ suffix = [".weight", ".bias"]
777
+ for s in suffix:
778
+ k_in = "controlnet_cond_embedding{}".format(s)
779
+ k_out = "input_hint_block.{}{}".format(count, s)
780
+ diffusers_keys[k_in] = k_out
781
+
782
+ new_sd = {}
783
+ for k in diffusers_keys:
784
+ if k in controlnet_data:
785
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
786
+
787
+ leftover_keys = controlnet_data.keys()
788
+ if len(leftover_keys) > 0:
789
+ logger.info("leftover keys:", leftover_keys)
790
+ controlnet_data = new_sd
791
+
792
+ pth_key = 'control_model.zero_convs.0.0.weight'
793
+ pth = False
794
+ key = 'zero_convs.0.0.weight'
795
+ if pth_key in controlnet_data:
796
+ pth = True
797
+ key = pth_key
798
+ prefix = "control_model."
799
+ elif key in controlnet_data:
800
+ prefix = ""
801
+ else:
802
+ raise ValueError("The provided model is not a valid SparseCtrl model! [ErrorCode: HORSERADISH]")
803
+
804
+ if controlnet_config is None:
805
+ unet_dtype = comfy.model_management.unet_dtype()
806
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
807
+ load_device = comfy.model_management.get_torch_device()
808
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
809
+ if manual_cast_dtype is not None:
810
+ controlnet_config["operations"] = manual_cast_clean_groupnorm
811
+ else:
812
+ controlnet_config["operations"] = disable_weight_init_clean_groupnorm
813
+ controlnet_config.pop("out_channels")
814
+ # get proper hint channels
815
+ if use_simplified_conditioning_embedding:
816
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
817
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
818
+ else:
819
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
820
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
821
+ control_model = SparseControlNet(**controlnet_config)
822
+
823
+ if pth:
824
+ if 'difference' in controlnet_data:
825
+ if model is not None:
826
+ comfy.model_management.load_models_gpu([model])
827
+ model_sd = model.model_state_dict()
828
+ for x in controlnet_data:
829
+ c_m = "control_model."
830
+ if x.startswith(c_m):
831
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
832
+ if sd_key in model_sd:
833
+ cd = controlnet_data[x]
834
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
835
+ else:
836
+ logger.warning("WARNING: Loaded a diff SparseCtrl without a model. It will very likely not work.")
837
+
838
+ class WeightsLoader(torch.nn.Module):
839
+ pass
840
+ w = WeightsLoader()
841
+ w.control_model = control_model
842
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
843
+ else:
844
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
845
+ if len(missing) > 0 or len(unexpected) > 0:
846
+ logger.info(f"SparseCtrl ControlNet: {missing}, {unexpected}")
847
+
848
+ global_average_pooling = False
849
+ filename = os.path.splitext(ckpt_path)[0]
850
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
851
+ global_average_pooling = True
852
+
853
+ # actually load motion portion of model now
854
+ motion_model = load_sparsectrl_motionmodel(ckpt_path=ckpt_path, motion_data=motion_data, ops=controlnet_config.get("operations", None)).to(comfy.model_management.unet_dtype())
855
+ # both motion portion and controlnet portions are loaded; ignore motion_model if shouldn't use motion portion
856
+ if not sparse_settings.use_motion:
857
+ motion_model = None
858
+
859
+ control = SparseCtrlAdvanced(control_model, motion_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)
860
+ return control
861
+
862
+
863
+ def load_svdcontrolnet(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
864
+ if controlnet_data is None:
865
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
866
+
867
+ controlnet_config = None
868
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
869
+ unet_dtype = comfy.model_management.unet_dtype()
870
+ controlnet_config = svd_unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
871
+ diffusers_keys = svd_unet_to_diffusers(controlnet_config)
872
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
873
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
874
+
875
+ count = 0
876
+ loop = True
877
+ while loop:
878
+ suffix = [".weight", ".bias"]
879
+ for s in suffix:
880
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
881
+ k_out = "zero_convs.{}.0{}".format(count, s)
882
+ if k_in not in controlnet_data:
883
+ loop = False
884
+ break
885
+ diffusers_keys[k_in] = k_out
886
+ count += 1
887
+
888
+ count = 0
889
+ loop = True
890
+ while loop:
891
+ suffix = [".weight", ".bias"]
892
+ for s in suffix:
893
+ if count == 0:
894
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
895
+ else:
896
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
897
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
898
+ if k_in not in controlnet_data:
899
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
900
+ loop = False
901
+ diffusers_keys[k_in] = k_out
902
+ count += 1
903
+
904
+ new_sd = {}
905
+ for k in diffusers_keys:
906
+ if k in controlnet_data:
907
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
908
+
909
+ leftover_keys = controlnet_data.keys()
910
+ if len(leftover_keys) > 0:
911
+ spatial_leftover_keys = []
912
+ temporal_leftover_keys = []
913
+ other_leftover_keys = []
914
+ for key in leftover_keys:
915
+ if "spatial" in key:
916
+ spatial_leftover_keys.append(key)
917
+ elif "temporal" in key:
918
+ temporal_leftover_keys.append(key)
919
+ else:
920
+ other_leftover_keys.append(key)
921
+ logger.warn(f"spatial_leftover_keys ({len(spatial_leftover_keys)}): {spatial_leftover_keys}")
922
+ logger.warn(f"temporal_leftover_keys ({len(temporal_leftover_keys)}): {temporal_leftover_keys}")
923
+ logger.warn(f"other_leftover_keys ({len(other_leftover_keys)}): {other_leftover_keys}")
924
+ #print("leftover keys:", leftover_keys)
925
+ controlnet_data = new_sd
926
+
927
+ pth_key = 'control_model.zero_convs.0.0.weight'
928
+ pth = False
929
+ key = 'zero_convs.0.0.weight'
930
+ if pth_key in controlnet_data:
931
+ pth = True
932
+ key = pth_key
933
+ prefix = "control_model."
934
+ elif key in controlnet_data:
935
+ prefix = ""
936
+ else:
937
+ raise ValueError("The provided model is not a valid SVD-ControlNet model! [ErrorCode: MUSTARD]")
938
+
939
+ if controlnet_config is None:
940
+ unet_dtype = comfy.model_management.unet_dtype()
941
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
942
+ load_device = comfy.model_management.get_torch_device()
943
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
944
+ if manual_cast_dtype is not None:
945
+ controlnet_config["operations"] = comfy.ops.manual_cast
946
+ controlnet_config.pop("out_channels")
947
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
948
+ control_model = SVDControlNet(**controlnet_config)
949
+
950
+ if pth:
951
+ if 'difference' in controlnet_data:
952
+ if model is not None:
953
+ comfy.model_management.load_models_gpu([model])
954
+ model_sd = model.model_state_dict()
955
+ for x in controlnet_data:
956
+ c_m = "control_model."
957
+ if x.startswith(c_m):
958
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
959
+ if sd_key in model_sd:
960
+ cd = controlnet_data[x]
961
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
962
+ else:
963
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
964
+
965
+ class WeightsLoader(torch.nn.Module):
966
+ pass
967
+ w = WeightsLoader()
968
+ w.control_model = control_model
969
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
970
+ else:
971
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
972
+ if len(missing) > 0 or len(unexpected) > 0:
973
+ logger.info(f"SVD-ControlNet: {missing}, {unexpected}")
974
+
975
+ global_average_pooling = False
976
+ filename = os.path.splitext(ckpt_path)[0]
977
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
978
+ global_average_pooling = True
979
+
980
+ control = SVDControlNetAdvanced(control_model, timestep_keyframes=timestep_keyframe, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
981
+ return control
982
+
ComfyUI-Advanced-ControlNet/adv_control/control_ctrlora.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core code adapted from CtrLoRA github repo:
2
+ # https://github.com/xyfJASON/ctrlora
3
+ import torch
4
+ from torch import Tensor
5
+
6
+ from comfy.cldm.cldm import ControlNet as ControlNetCLDM
7
+ import comfy.model_detection
8
+ import comfy.model_management
9
+ import comfy.ops
10
+ import comfy.utils
11
+
12
+ from comfy.ldm.modules.diffusionmodules.util import (
13
+ zero_module,
14
+ timestep_embedding,
15
+ )
16
+
17
+ from .control import ControlNetAdvanced
18
+ from .utils import TimestepKeyframeGroup
19
+ from .logger import logger
20
+
21
+
22
+ class ControlNetCtrLoRA(ControlNetCLDM):
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ # delete input hint block
26
+ del self.input_hint_block
27
+
28
+ def forward(self, x: Tensor, hint: Tensor, timesteps, context, y=None, **kwargs):
29
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
30
+ emb = self.time_embed(t_emb)
31
+
32
+ out_output = []
33
+ out_middle = []
34
+
35
+ if self.num_classes is not None:
36
+ assert y.shape[0] == x.shape[0]
37
+ emb = emb + self.label_emb(y)
38
+
39
+ h = hint.to(dtype=x.dtype)
40
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
41
+ h = module(h, emb, context)
42
+ out_output.append(zero_conv(h, emb, context))
43
+
44
+ h = self.middle_block(h, emb, context)
45
+ out_middle.append(self.middle_block_out(h, emb, context))
46
+
47
+ return {"middle": out_middle, "output": out_output}
48
+
49
+
50
+ class CtrLoRAAdvanced(ControlNetAdvanced):
51
+ def __init__(self, *args, **kwargs):
52
+ super().__init__(*args, **kwargs)
53
+ self.preprocess_image = lambda a: (a + 1) / 2.0
54
+ self.require_vae = True
55
+ self.mult_by_ratio_when_vae = False
56
+
57
+ def pre_run_advanced(self, model, percent_to_timestep_function):
58
+ super().pre_run_advanced(model, percent_to_timestep_function)
59
+ self.latent_format = model.latent_format # LatentFormat object, used to process_in latent cond hint
60
+
61
+ def cleanup_advanced(self):
62
+ super().cleanup_advanced()
63
+ if self.latent_format is not None:
64
+ del self.latent_format
65
+ self.latent_format = None
66
+
67
+ def copy(self):
68
+ c = CtrLoRAAdvanced(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)
69
+ c.control_model = self.control_model
70
+ c.control_model_wrapped = self.control_model_wrapped
71
+ self.copy_to(c)
72
+ self.copy_to_advanced(c)
73
+ return c
74
+
75
+
76
+ def load_ctrlora(base_path: str, lora_path: str,
77
+ base_data: dict[str, Tensor]=None, lora_data: dict[str, Tensor]=None,
78
+ timestep_keyframe: TimestepKeyframeGroup=None, model=None, model_options={}):
79
+ if base_data is None:
80
+ base_data = comfy.utils.load_torch_file(base_path, safe_load=True)
81
+ controlnet_data = base_data
82
+
83
+ # first, check that base_data contains keys with lora_layer
84
+ contains_lora_layers = False
85
+ for key in base_data:
86
+ if "lora_layer" in key:
87
+ contains_lora_layers = True
88
+ if not contains_lora_layers:
89
+ raise Exception(f"File '{base_path}' is not a valid CtrLoRA base model; does not contain any lora_layer keys.")
90
+
91
+ controlnet_config = None
92
+ supported_inference_dtypes = None
93
+
94
+ pth_key = 'control_model.zero_convs.0.0.weight'
95
+ pth = False
96
+ key = 'zero_convs.0.0.weight'
97
+ if pth_key in controlnet_data:
98
+ pth = True
99
+ key = pth_key
100
+ prefix = "control_model."
101
+ elif key in controlnet_data:
102
+ prefix = ""
103
+ else:
104
+ raise Exception("")
105
+ net = load_t2i_adapter(controlnet_data, model_options=model_options)
106
+ if net is None:
107
+ logging.error("error could not detect control model type.")
108
+ return net
109
+
110
+ if controlnet_config is None:
111
+ model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
112
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
113
+ controlnet_config = model_config.unet_config
114
+
115
+ unet_dtype = model_options.get("dtype", None)
116
+ if unet_dtype is None:
117
+ weight_dtype = comfy.utils.weight_dtype(controlnet_data)
118
+
119
+ if supported_inference_dtypes is None:
120
+ supported_inference_dtypes = [comfy.model_management.unet_dtype()]
121
+
122
+ if weight_dtype is not None:
123
+ supported_inference_dtypes.append(weight_dtype)
124
+
125
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes)
126
+
127
+ load_device = comfy.model_management.get_torch_device()
128
+
129
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
130
+ operations = model_options.get("custom_operations", None)
131
+ if operations is None:
132
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
133
+
134
+ controlnet_config["operations"] = operations
135
+ controlnet_config["dtype"] = unet_dtype
136
+ controlnet_config["device"] = comfy.model_management.unet_offload_device()
137
+ controlnet_config.pop("out_channels")
138
+ controlnet_config["hint_channels"] = 3
139
+ #controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
140
+ control_model = ControlNetCtrLoRA(**controlnet_config)
141
+
142
+ if pth:
143
+ if 'difference' in controlnet_data:
144
+ if model is not None:
145
+ comfy.model_management.load_models_gpu([model])
146
+ model_sd = model.model_state_dict()
147
+ for x in controlnet_data:
148
+ c_m = "control_model."
149
+ if x.startswith(c_m):
150
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
151
+ if sd_key in model_sd:
152
+ cd = controlnet_data[x]
153
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
154
+ else:
155
+ logger.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
156
+
157
+ class WeightsLoader(torch.nn.Module):
158
+ pass
159
+ w = WeightsLoader()
160
+ w.control_model = control_model
161
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
162
+ else:
163
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
164
+
165
+ if len(missing) > 0:
166
+ logger.warning("missing controlnet keys: {}".format(missing))
167
+
168
+ if len(unexpected) > 0:
169
+ logger.debug("unexpected controlnet keys: {}".format(unexpected))
170
+
171
+ global_average_pooling = model_options.get("global_average_pooling", False)
172
+ control = CtrLoRAAdvanced(control_model, timestep_keyframe, global_average_pooling=global_average_pooling,
173
+ load_device=load_device, manual_cast_dtype=manual_cast_dtype)
174
+ # load lora data onto the controlnet
175
+ if lora_path is not None:
176
+ load_lora_data(control, lora_path)
177
+
178
+ return control
179
+
180
+
181
+ def load_lora_data(control: CtrLoRAAdvanced, lora_path: str, loaded_data: dict[str, Tensor]=None, lora_strength=1.0):
182
+ if loaded_data is None:
183
+ loaded_data = comfy.utils.load_torch_file(lora_path, safe_load=True)
184
+ # check that lora_data contains keys with lora_layer
185
+ contains_lora_layers = False
186
+ for key in loaded_data:
187
+ if "lora_layer" in key:
188
+ contains_lora_layers = True
189
+ if not contains_lora_layers:
190
+ raise Exception(f"File '{lora_path}' is not a valid CtrLoRA lora model; does not contain any lora_layer keys.")
191
+
192
+ # now that we know we have a ctrlora file, separate keys into 'set' and 'lora' keys
193
+ data_set: dict[str, Tensor] = {}
194
+ data_lora: dict[str, Tensor] = {}
195
+
196
+ for key in list(loaded_data.keys()):
197
+ if 'lora_layer' in key:
198
+ data_lora[key] = loaded_data.pop(key)
199
+ else:
200
+ data_set[key] = loaded_data.pop(key)
201
+ # no keys should be left over
202
+ if len(loaded_data) > 0:
203
+ logger.warning("Not all keys from CtrlLoRA lora model's loaded data were parsed!")
204
+
205
+ # turn set/lora data into corresponding patches;
206
+ patches = {}
207
+ # set will replace the values
208
+ for key, value in data_set.items():
209
+ # prase model key from key;
210
+ # remove "control_model."
211
+ model_key = key.replace("control_model.", "")
212
+ patches[model_key] = ("set", (value,))
213
+ # lora will do mm of up and down tensors
214
+ for down_key in data_lora:
215
+ # only process lora down keys; we will process both up+down at the same time
216
+ if ".up." in down_key:
217
+ continue
218
+ # get up version of down key
219
+ up_key = down_key.replace(".down.", ".up.")
220
+ # get key that will match up with model key;
221
+ # remove "lora_layer.down." and "control_model."
222
+ model_key = down_key.replace("lora_layer.down.", "").replace("control_model.", "")
223
+
224
+ weight_down = data_lora[down_key]
225
+ weight_up = data_lora[up_key]
226
+ # currently, ComfyUI expects 6 elements in 'lora' type, but for future-proofing add a bunch more with None
227
+ patches[model_key] = ("lora", (weight_up, weight_down, None, None, None, None,
228
+ None, None, None, None, None, None, None, None))
229
+
230
+ # now that patches are made, add them to model
231
+ control.control_model_wrapped.add_patches(patches, strength_patch=lora_strength)
ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import comfy.ops
12
+ import comfy.model_management
13
+ from comfy.model_patcher import ModelPatcher
14
+ from comfy.controlnet import ControlBase
15
+
16
+ from .logger import logger
17
+ from .utils import (AdvancedControlBase, TimestepKeyframeGroup, ControlWeights, broadcast_image_to_extend, extend_to_batch_size,
18
+ prepare_mask_batch)
19
+
20
+
21
+ # based on set_model_patch code in comfy/model_patcher.py
22
+ def set_model_patch(transformer_options, patch, name):
23
+ to = transformer_options
24
+ # check if patch was already added
25
+ if "patches" in to:
26
+ current_patches = to["patches"].get(name, [])
27
+ if patch in current_patches:
28
+ return
29
+ if "patches" not in to:
30
+ to["patches"] = {}
31
+ to["patches"][name] = to["patches"].get(name, []) + [patch]
32
+
33
+ def set_model_attn1_patch(transformer_options, patch):
34
+ set_model_patch(transformer_options, patch, "attn1_patch")
35
+
36
+ def set_model_attn2_patch(transformer_options, patch):
37
+ set_model_patch(transformer_options, patch, "attn2_patch")
38
+
39
+
40
+ def extra_options_to_module_prefix(extra_options):
41
+ # extra_options = {'transformer_index': 2, 'block_index': 8, 'original_shape': [2, 4, 128, 128], 'block': ('input', 7), 'n_heads': 20, 'dim_head': 64}
42
+
43
+ # block is: [('input', 4), ('input', 5), ('input', 7), ('input', 8), ('middle', 0),
44
+ # ('output', 0), ('output', 1), ('output', 2), ('output', 3), ('output', 4), ('output', 5)]
45
+ # transformer_index is: [0, 1, 2, 3, 4, 5, 6, 7, 8], for each block
46
+ # block_index is: 0-1 or 0-9, depends on the block
47
+ # input 7 and 8, middle has 10 blocks
48
+
49
+ # make module name from extra_options
50
+ block = extra_options["block"]
51
+ block_index = extra_options["block_index"]
52
+ if block[0] == "input":
53
+ module_pfx = f"lllite_unet_input_blocks_{block[1]}_1_transformer_blocks_{block_index}"
54
+ elif block[0] == "middle":
55
+ module_pfx = f"lllite_unet_middle_block_1_transformer_blocks_{block_index}"
56
+ elif block[0] == "output":
57
+ module_pfx = f"lllite_unet_output_blocks_{block[1]}_1_transformer_blocks_{block_index}"
58
+ else:
59
+ raise Exception(f"ControlLLLite: invalid block name '{block[0]}'. Expected 'input', 'middle', or 'output'.")
60
+ return module_pfx
61
+
62
+
63
+ class LLLitePatch:
64
+ ATTN1 = "attn1"
65
+ ATTN2 = "attn2"
66
+ def __init__(self, modules: dict[str, 'LLLiteModule'], patch_type: str, control: Union[AdvancedControlBase, ControlBase]=None):
67
+ self.modules = modules
68
+ self.control = control
69
+ self.patch_type = patch_type
70
+ #logger.error(f"create LLLitePatch: {id(self)},{control}")
71
+
72
+ def __call__(self, q, k, v, extra_options):
73
+ #logger.error(f"in __call__: {id(self)}")
74
+ # determine if have anything to run
75
+ if self.control.timestep_range is not None:
76
+ # it turns out comparing single-value tensors to floats is extremely slow
77
+ # a: Tensor = extra_options["sigmas"][0]
78
+ if self.control.t > self.control.timestep_range[0] or self.control.t < self.control.timestep_range[1]:
79
+ return q, k, v
80
+
81
+ module_pfx = extra_options_to_module_prefix(extra_options)
82
+
83
+ is_attn1 = q.shape[-1] == k.shape[-1] # self attention
84
+ if is_attn1:
85
+ module_pfx = module_pfx + "_attn1"
86
+ else:
87
+ module_pfx = module_pfx + "_attn2"
88
+
89
+ module_pfx_to_q = module_pfx + "_to_q"
90
+ module_pfx_to_k = module_pfx + "_to_k"
91
+ module_pfx_to_v = module_pfx + "_to_v"
92
+
93
+ if module_pfx_to_q in self.modules:
94
+ q = q + self.modules[module_pfx_to_q](q, self.control)
95
+ if module_pfx_to_k in self.modules:
96
+ k = k + self.modules[module_pfx_to_k](k, self.control)
97
+ if module_pfx_to_v in self.modules:
98
+ v = v + self.modules[module_pfx_to_v](v, self.control)
99
+
100
+ return q, k, v
101
+
102
+ def to(self, device):
103
+ #logger.info(f"to... has control? {self.control}")
104
+ for d in self.modules.keys():
105
+ self.modules[d] = self.modules[d].to(device)
106
+ return self
107
+
108
+ def set_control(self, control: Union[AdvancedControlBase, ControlBase]) -> 'LLLitePatch':
109
+ self.control = control
110
+ return self
111
+ #logger.error(f"set control for LLLitePatch: {id(self)}, cn: {id(control)}")
112
+
113
+ def clone_with_control(self, control: AdvancedControlBase):
114
+ #logger.error(f"clone-set control for LLLitePatch: {id(self)},{id(control)}")
115
+ return LLLitePatch(self.modules, self.patch_type, control)
116
+
117
+ def cleanup(self):
118
+ for module in self.modules.values():
119
+ module.cleanup()
120
+
121
+
122
+ # TODO: use comfy.ops to support fp8 properly
123
+ class LLLiteModule(torch.nn.Module):
124
+ def __init__(
125
+ self,
126
+ name: str,
127
+ is_conv2d: bool,
128
+ in_dim: int,
129
+ depth: int,
130
+ cond_emb_dim: int,
131
+ mlp_dim: int,
132
+ ):
133
+ super().__init__()
134
+ self.name = name
135
+ self.is_conv2d = is_conv2d
136
+ self.is_first = False
137
+
138
+ modules = []
139
+ modules.append(torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size*2
140
+ if depth == 1:
141
+ modules.append(torch.nn.ReLU(inplace=True))
142
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
143
+ elif depth == 2:
144
+ modules.append(torch.nn.ReLU(inplace=True))
145
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
146
+ elif depth == 3:
147
+ # kernel size 8 is too large, so set it to 4
148
+ modules.append(torch.nn.ReLU(inplace=True))
149
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
150
+ modules.append(torch.nn.ReLU(inplace=True))
151
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
152
+
153
+ self.conditioning1 = torch.nn.Sequential(*modules)
154
+
155
+ if self.is_conv2d:
156
+ self.down = torch.nn.Sequential(
157
+ torch.nn.Conv2d(in_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
158
+ torch.nn.ReLU(inplace=True),
159
+ )
160
+ self.mid = torch.nn.Sequential(
161
+ torch.nn.Conv2d(mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
162
+ torch.nn.ReLU(inplace=True),
163
+ )
164
+ self.up = torch.nn.Sequential(
165
+ torch.nn.Conv2d(mlp_dim, in_dim, kernel_size=1, stride=1, padding=0),
166
+ )
167
+ else:
168
+ self.down = torch.nn.Sequential(
169
+ torch.nn.Linear(in_dim, mlp_dim),
170
+ torch.nn.ReLU(inplace=True),
171
+ )
172
+ self.mid = torch.nn.Sequential(
173
+ torch.nn.Linear(mlp_dim + cond_emb_dim, mlp_dim),
174
+ torch.nn.ReLU(inplace=True),
175
+ )
176
+ self.up = torch.nn.Sequential(
177
+ torch.nn.Linear(mlp_dim, in_dim),
178
+ )
179
+
180
+ self.depth = depth
181
+ self.cond_emb = None
182
+ self.cx_shape = None
183
+ self.prev_batch = 0
184
+ self.prev_sub_idxs = None
185
+
186
+ def cleanup(self):
187
+ del self.cond_emb
188
+ self.cond_emb = None
189
+ self.cx_shape = None
190
+ self.prev_batch = 0
191
+ self.prev_sub_idxs = None
192
+
193
+ def forward(self, x: Tensor, control: Union[AdvancedControlBase, ControlBase]):
194
+ mask = None
195
+ mask_tk = None
196
+ #logger.info(x.shape)
197
+ if self.cond_emb is None or control.sub_idxs != self.prev_sub_idxs or x.shape[0] != self.prev_batch:
198
+ # print(f"cond_emb is None, {self.name}")
199
+ cond_hint = control.cond_hint.to(x.device, dtype=x.dtype)
200
+ if control.latent_dims_div2 is not None and x.shape[-1] != 1280:
201
+ 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)
202
+ elif control.latent_dims_div4 is not None and x.shape[-1] == 1280:
203
+ 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)
204
+ cx = self.conditioning1(cond_hint)
205
+ self.cx_shape = cx.shape
206
+ if not self.is_conv2d:
207
+ # reshape / b,c,h,w -> b,h*w,c
208
+ n, c, h, w = cx.shape
209
+ cx = cx.view(n, c, h * w).permute(0, 2, 1)
210
+ self.cond_emb = cx
211
+ # save prev values
212
+ self.prev_batch = x.shape[0]
213
+ self.prev_sub_idxs = control.sub_idxs
214
+
215
+ cx: torch.Tensor = self.cond_emb
216
+ # print(f"forward {self.name}, {cx.shape}, {x.shape}")
217
+
218
+ # TODO: make masks work for conv2d (could not find any ControlLLLites at this time that use them)
219
+ # create masks
220
+ if not self.is_conv2d:
221
+ n, c, h, w = self.cx_shape
222
+ if control.mask_cond_hint is not None:
223
+ mask = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
224
+ mask = mask.view(mask.shape[0], 1, h * w).permute(0, 2, 1)
225
+ if control.tk_mask_cond_hint is not None:
226
+ mask_tk = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
227
+ mask_tk = mask_tk.view(mask_tk.shape[0], 1, h * w).permute(0, 2, 1)
228
+
229
+ # x in uncond/cond doubles batch size
230
+ if x.shape[0] != cx.shape[0]:
231
+ if self.is_conv2d:
232
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1, 1)
233
+ else:
234
+ # print("x.shape[0] != cx.shape[0]", x.shape[0], cx.shape[0])
235
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1)
236
+ if mask is not None:
237
+ mask = mask.repeat(x.shape[0] // mask.shape[0], 1, 1)
238
+ if mask_tk is not None:
239
+ mask_tk = mask_tk.repeat(x.shape[0] // mask_tk.shape[0], 1, 1)
240
+
241
+ if mask is None:
242
+ mask = 1.0
243
+ elif mask_tk is not None:
244
+ mask = mask * mask_tk
245
+
246
+ #logger.info(f"cs: {cx.shape}, x: {x.shape}, is_conv2d: {self.is_conv2d}")
247
+ cx = torch.cat([cx, self.down(x)], dim=1 if self.is_conv2d else 2)
248
+ cx = self.mid(cx)
249
+ cx = self.up(cx)
250
+ if control.latent_keyframes is not None:
251
+ cx = cx * control.calc_latent_keyframe_mults(x=cx, batched_number=control.batched_number)
252
+ if control.weights is not None and control.weights.has_uncond_multiplier:
253
+ cond_or_uncond = control.batched_number.cond_or_uncond
254
+ actual_length = cx.size(0) // control.batched_number
255
+ for idx, cond_type in enumerate(cond_or_uncond):
256
+ # if uncond, set to weight's uncond_multiplier
257
+ if cond_type == 1:
258
+ cx[actual_length*idx:actual_length*(idx+1)] *= control.weights.uncond_multiplier
259
+ return cx * mask * control.strength * control._current_timestep_keyframe.strength
260
+
261
+
262
+ class ControlLLLiteModules(torch.nn.Module):
263
+ def __init__(self, patch_attn1: LLLitePatch, patch_attn2: LLLitePatch):
264
+ super().__init__()
265
+ self.patch_attn1_modules = torch.nn.Sequential(*list(patch_attn1.modules.values()))
266
+ self.patch_attn2_modules = torch.nn.Sequential(*list(patch_attn2.modules.values()))
267
+
268
+
269
+ class ControlLLLiteAdvanced(ControlBase, AdvancedControlBase):
270
+ # This ControlNet is more of an attention patch than a traditional controlnet
271
+ def __init__(self, patch_attn1: LLLitePatch, patch_attn2: LLLitePatch, timestep_keyframes: TimestepKeyframeGroup, device, ops: comfy.ops.disable_weight_init):
272
+ super().__init__()
273
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite())
274
+ self.device = device
275
+ self.ops = ops
276
+ self.patch_attn1 = patch_attn1.clone_with_control(self)
277
+ self.patch_attn2 = patch_attn2.clone_with_control(self)
278
+ self.control_model = ControlLLLiteModules(self.patch_attn1, self.patch_attn2)
279
+ self.control_model_wrapped = ModelPatcher(self.control_model, load_device=device, offload_device=comfy.model_management.unet_offload_device())
280
+ self.latent_dims_div2 = None
281
+ self.latent_dims_div4 = None
282
+
283
+ def set_cond_hint_inject(self, *args, **kwargs):
284
+ to_return = super().set_cond_hint_inject(*args, **kwargs)
285
+ # cond hint for LLLite needs to be scaled between (-1, 1) instead of (0, 1)
286
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
287
+ return to_return
288
+
289
+ def pre_run_advanced(self, *args, **kwargs):
290
+ AdvancedControlBase.pre_run_advanced(self, *args, **kwargs)
291
+ #logger.error(f"in cn: {id(self.patch_attn1)},{id(self.patch_attn2)}")
292
+ self.patch_attn1.set_control(self)
293
+ self.patch_attn2.set_control(self)
294
+ #logger.warn(f"in pre_run_advanced: {id(self)}")
295
+
296
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int, transformer_options: dict):
297
+ # normal ControlNet stuff
298
+ control_prev = None
299
+ if self.previous_controlnet is not None:
300
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
301
+
302
+ if self.timestep_range is not None:
303
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
304
+ return control_prev
305
+
306
+ dtype = x_noisy.dtype
307
+ # prepare cond_hint
308
+ 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]:
309
+ if self.cond_hint is not None:
310
+ del self.cond_hint
311
+ self.cond_hint = None
312
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
313
+ if self.sub_idxs is not None:
314
+ actual_cond_hint_orig = self.cond_hint_original
315
+ if self.cond_hint_original.size(0) < self.full_latent_length:
316
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
317
+ 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(x_noisy.device)
318
+ else:
319
+ 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(x_noisy.device)
320
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
321
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
322
+ # some special logic here compared to other controlnets:
323
+ # * The cond_emb in attn patches will divide latent dims by 2 or 4, integer
324
+ # * Due to this loss, the cond_emb will become smaller than x input if latent dims are not divisble by 2 or 4
325
+ divisible_by_2_h = x_noisy.shape[2]%2==0
326
+ divisible_by_2_w = x_noisy.shape[3]%2==0
327
+ if not (divisible_by_2_h and divisible_by_2_w):
328
+ #logger.warn(f"{x_noisy.shape} not divisible by 2!")
329
+ new_h = (x_noisy.shape[2]//2)*2
330
+ new_w = (x_noisy.shape[3]//2)*2
331
+ if not divisible_by_2_h:
332
+ new_h += 2
333
+ if not divisible_by_2_w:
334
+ new_w += 2
335
+ self.latent_dims_div2 = (new_h, new_w)
336
+ divisible_by_4_h = x_noisy.shape[2]%4==0
337
+ divisible_by_4_w = x_noisy.shape[3]%4==0
338
+ if not (divisible_by_4_h and divisible_by_4_w):
339
+ #logger.warn(f"{x_noisy.shape} not divisible by 4!")
340
+ new_h = (x_noisy.shape[2]//4)*4
341
+ new_w = (x_noisy.shape[3]//4)*4
342
+ if not divisible_by_4_h:
343
+ new_h += 4
344
+ if not divisible_by_4_w:
345
+ new_w += 4
346
+ self.latent_dims_div4 = (new_h, new_w)
347
+ # prepare mask
348
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
349
+ # done preparing; model patches will take care of everything now
350
+ set_model_attn1_patch(transformer_options, self.patch_attn1.set_control(self))
351
+ set_model_attn2_patch(transformer_options, self.patch_attn2.set_control(self))
352
+ # return normal controlnet stuff
353
+ return control_prev
354
+
355
+ def get_models(self):
356
+ to_return: list = super().get_models()
357
+ to_return.append(self.control_model_wrapped)
358
+ return to_return
359
+
360
+ def cleanup_advanced(self):
361
+ super().cleanup_advanced()
362
+ self.patch_attn1.cleanup()
363
+ self.patch_attn2.cleanup()
364
+ self.latent_dims_div2 = None
365
+ self.latent_dims_div4 = None
366
+
367
+ def copy(self):
368
+ c = ControlLLLiteAdvanced(self.patch_attn1, self.patch_attn2, self.timestep_keyframes, self.device, self.ops)
369
+ self.copy_to(c)
370
+ self.copy_to_advanced(c)
371
+ return c
372
+
373
+
374
+ def load_controllllite(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None):
375
+ if controlnet_data is None:
376
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
377
+ # adapted from https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
378
+ # first, split weights for each module
379
+ module_weights = {}
380
+ for key, value in controlnet_data.items():
381
+ fragments = key.split(".")
382
+ module_name = fragments[0]
383
+ weight_name = ".".join(fragments[1:])
384
+
385
+ if module_name not in module_weights:
386
+ module_weights[module_name] = {}
387
+ module_weights[module_name][weight_name] = value
388
+
389
+ unet_dtype = comfy.model_management.unet_dtype()
390
+ load_device = comfy.model_management.get_torch_device()
391
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
392
+ ops = comfy.ops.disable_weight_init
393
+ if manual_cast_dtype is not None:
394
+ ops = comfy.ops.manual_cast
395
+
396
+ # next, load each module
397
+ modules = {}
398
+ for module_name, weights in module_weights.items():
399
+ # kohya planned to do something about how these should be chosen, so I'm not touching this
400
+ # since I am not familiar with the logic for this
401
+ if "conditioning1.4.weight" in weights:
402
+ depth = 3
403
+ elif weights["conditioning1.2.weight"].shape[-1] == 4:
404
+ depth = 2
405
+ else:
406
+ depth = 1
407
+
408
+ module = LLLiteModule(
409
+ name=module_name,
410
+ is_conv2d=weights["down.0.weight"].ndim == 4,
411
+ in_dim=weights["down.0.weight"].shape[1],
412
+ depth=depth,
413
+ cond_emb_dim=weights["conditioning1.0.weight"].shape[0] * 2,
414
+ mlp_dim=weights["down.0.weight"].shape[0],
415
+ )
416
+ # load weights into module
417
+ module.load_state_dict(weights)
418
+ modules[module_name] = module.to(dtype=unet_dtype)
419
+ if len(modules) == 1:
420
+ module.is_first = True
421
+
422
+ #logger.info(f"loaded {ckpt_path} successfully, {len(modules)} modules")
423
+
424
+ patch_attn1 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN1)
425
+ patch_attn2 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN2)
426
+ control = ControlLLLiteAdvanced(patch_attn1=patch_attn1, patch_attn2=patch_attn2, timestep_keyframes=timestep_keyframe, device=load_device, ops=ops)
427
+ return control
ComfyUI-Advanced-ControlNet/adv_control/control_plusplus.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code ported and modified from the diffusers ControlNetPlus repo by Qi Xin:
2
+ # https://github.com/xinsir6/ControlNetPlus/blob/main/models/controlnet_union.py
3
+ from typing import Union
4
+
5
+ import os
6
+ import torch
7
+ import torch as th
8
+ import torch.nn as nn
9
+ from torch import Tensor
10
+ from collections import OrderedDict
11
+
12
+
13
+ from comfy.ldm.modules.diffusionmodules.util import (zero_module, timestep_embedding)
14
+
15
+ from comfy.cldm.cldm import ControlNet as ControlNetCLDM
16
+ import comfy.cldm.cldm
17
+ from comfy.controlnet import ControlNet
18
+ #from comfy.t2i_adapter.adapter import ResidualAttentionBlock
19
+ from comfy.ldm.modules.attention import optimized_attention
20
+ import comfy.ops
21
+ import comfy.model_management
22
+ import comfy.model_detection
23
+ import comfy.utils
24
+
25
+ from .utils import (AdvancedControlBase, ControlWeights, ControlWeightType, TimestepKeyframeGroup, AbstractPreprocWrapper, Extras,
26
+ extend_to_batch_size, broadcast_image_to_extend)
27
+ from .logger import logger
28
+
29
+
30
+ class PlusPlusType:
31
+ OPENPOSE = "openpose"
32
+ DEPTH = "depth"
33
+ THICKLINE = "hed/pidi/scribble/ted"
34
+ THINLINE = "canny/lineart/mlsd"
35
+ NORMAL = "normal"
36
+ SEGMENT = "segment"
37
+ TILE = "tile"
38
+ REPAINT = "inpaint/outpaint"
39
+ NONE = "none"
40
+ _LIST_WITH_NONE = [OPENPOSE, DEPTH, THICKLINE, THINLINE, NORMAL, SEGMENT, TILE, REPAINT, NONE]
41
+ _LIST = [OPENPOSE, DEPTH, THICKLINE, THINLINE, NORMAL, SEGMENT, TILE, REPAINT]
42
+ _DICT = {OPENPOSE: 0, DEPTH: 1, THICKLINE: 2, THINLINE: 3, NORMAL: 4, SEGMENT: 5, TILE: 6, REPAINT: 7, NONE: -1}
43
+
44
+ @classmethod
45
+ def to_idx(cls, control_type: str):
46
+ try:
47
+ return cls._DICT[control_type]
48
+ except KeyError:
49
+ raise Exception(f"Unknown control type '{control_type}'.")
50
+
51
+
52
+ class PlusPlusInput:
53
+ def __init__(self, image: Tensor, control_type: str, strength: float):
54
+ self.image = image
55
+ self.control_type = control_type
56
+ self.strength = strength
57
+
58
+ def clone(self):
59
+ return PlusPlusInput(self.image, self.control_type, self.strength)
60
+
61
+
62
+ class PlusPlusInputGroup:
63
+ def __init__(self):
64
+ self.controls: dict[str, PlusPlusInput] = {}
65
+
66
+ def add(self, pp_input: PlusPlusInput):
67
+ if pp_input.control_type in self.controls:
68
+ raise Exception(f"Control type '{pp_input.control_type}' is already present; ControlNet++ does not allow more than 1 of each type.")
69
+ self.controls[pp_input.control_type] = pp_input
70
+
71
+ def clone(self) -> 'PlusPlusInputGroup':
72
+ cloned = PlusPlusInputGroup()
73
+ for key, value in self.controls.items():
74
+ cloned.controls[key] = value.clone()
75
+ return cloned
76
+
77
+
78
+ class PlusPlusImageWrapper(AbstractPreprocWrapper):
79
+ error_msg = error_msg = "Invalid use of ControlNet++ Image Wrapper. The output of ControlNet++ Image Wrapper is NOT a usual image, but an object holding the images and extra info - you must connect the output directly to an Apply Advanced ControlNet node. It cannot be used for anything else that accepts IMAGE input."
80
+ def __init__(self, condhint: PlusPlusInputGroup):
81
+ super().__init__(condhint)
82
+ # just an IDE type hint
83
+ self.condhint: PlusPlusInputGroup
84
+
85
+ def movedim(self, source: int, destination: int):
86
+ condhint = self.condhint.clone()
87
+ for pp_input in condhint.controls.values():
88
+ pp_input.image = pp_input.image.movedim(source, destination)
89
+ return PlusPlusImageWrapper(condhint)
90
+
91
+ # parts taken from comfy/cldm/cldm.py
92
+ class OptimizedAttention(nn.Module):
93
+ def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
94
+ super().__init__()
95
+ self.heads = nhead
96
+ self.c = c
97
+
98
+ self.in_proj = operations.Linear(c, c * 3, bias=True, dtype=dtype, device=device)
99
+ self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
100
+
101
+ def forward(self, x):
102
+ x = self.in_proj(x)
103
+ q, k, v = x.split(self.c, dim=2)
104
+ out = optimized_attention(q, k, v, self.heads)
105
+ return self.out_proj(out)
106
+
107
+ class QuickGELU(nn.Module):
108
+ def forward(self, x: torch.Tensor):
109
+ return x * torch.sigmoid(1.702 * x)
110
+
111
+ class ResBlockUnionControlnet(nn.Module):
112
+ def __init__(self, dim, nhead, dtype=None, device=None, operations=None):
113
+ super().__init__()
114
+ self.attn = OptimizedAttention(dim, nhead, dtype=dtype, device=device, operations=operations)
115
+ self.ln_1 = operations.LayerNorm(dim, dtype=dtype, device=device)
116
+ self.mlp = nn.Sequential(
117
+ OrderedDict([("c_fc", operations.Linear(dim, dim * 4, dtype=dtype, device=device)), ("gelu", QuickGELU()),
118
+ ("c_proj", operations.Linear(dim * 4, dim, dtype=dtype, device=device))]))
119
+ self.ln_2 = operations.LayerNorm(dim, dtype=dtype, device=device)
120
+
121
+ def attention(self, x: torch.Tensor):
122
+ return self.attn(x)
123
+
124
+ def forward(self, x: torch.Tensor):
125
+ x = x + self.attention(self.ln_1(x))
126
+ x = x + self.mlp(self.ln_2(x))
127
+ return x
128
+
129
+
130
+ class ControlAddEmbeddingAdv(nn.Module):
131
+ def __init__(self, in_dim, out_dim, num_control_type, dtype=None, device=None, operations: comfy.ops.disable_weight_init=None):
132
+ super().__init__()
133
+ self.num_control_type = num_control_type
134
+ self.in_dim = in_dim
135
+ self.linear_1 = operations.Linear(in_dim * num_control_type, out_dim, dtype=dtype, device=device)
136
+ self.linear_2 = operations.Linear(out_dim, out_dim, dtype=dtype, device=device)
137
+
138
+ def forward(self, control_type, dtype, device):
139
+ if control_type is None:
140
+ control_type = torch.zeros((self.num_control_type,), device=device)
141
+ c_type = timestep_embedding(control_type.flatten(), self.in_dim, repeat_only=False).to(dtype).reshape((-1, self.num_control_type * self.in_dim))
142
+ return self.linear_2(torch.nn.functional.silu(self.linear_1(c_type)))
143
+
144
+
145
+ class ControlNetPlusPlus(ControlNetCLDM):
146
+ def __init__(self, *args,**kwargs):
147
+ super().__init__(*args, **kwargs)
148
+
149
+ operations: comfy.ops.disable_weight_init = kwargs.get("operations", comfy.ops.disable_weight_init)
150
+ device = kwargs.get("device", None)
151
+
152
+ time_embed_dim = self.model_channels * 4
153
+ control_add_embed_dim = 256
154
+
155
+ self.control_add_embedding = ControlAddEmbeddingAdv(control_add_embed_dim, time_embed_dim, self.num_control_type, dtype=self.dtype, device=device, operations=operations)
156
+
157
+ def union_controlnet_merge(self, hint: list[Tensor], control_type, emb, context):
158
+ # Equivalent to: https://github.com/xinsir6/ControlNetPlus/tree/main
159
+ indexes = torch.nonzero(control_type[0])
160
+ inputs = []
161
+ condition_list = []
162
+
163
+ for idx in range(indexes.shape[0]):
164
+ controlnet_cond = self.input_hint_block(hint[indexes[idx][0]], emb, context)
165
+ feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
166
+ if idx < indexes.shape[0]:
167
+ feat_seq += self.task_embedding[indexes[idx][0]].to(dtype=feat_seq.dtype, device=feat_seq.device)
168
+
169
+ inputs.append(feat_seq.unsqueeze(1))
170
+ condition_list.append(controlnet_cond)
171
+
172
+ x = torch.cat(inputs, dim=1)
173
+ x = self.transformer_layes(x)
174
+
175
+ controlnet_cond_fuser = None
176
+ for idx in range(indexes.shape[0]):
177
+ alpha = self.spatial_ch_projs(x[:, idx])
178
+ alpha = alpha.unsqueeze(-1).unsqueeze(-1)
179
+ o = condition_list[idx] + alpha
180
+ if controlnet_cond_fuser is None:
181
+ controlnet_cond_fuser = o
182
+ else:
183
+ controlnet_cond_fuser += o
184
+ return controlnet_cond_fuser
185
+
186
+ def forward(self, x: Tensor, hint: list[Tensor], timesteps, context, y: Tensor=None, **kwargs):
187
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
188
+ emb = self.time_embed(t_emb)
189
+
190
+ guided_hint = None
191
+ if self.control_add_embedding is not None:
192
+ control_type = kwargs.get("control_type", None)
193
+
194
+ emb += self.control_add_embedding(control_type, emb.dtype, emb.device)
195
+ if control_type is not None:
196
+ guided_hint = self.union_controlnet_merge(hint, control_type, emb, context)
197
+
198
+ if guided_hint is None:
199
+ guided_hint = self.input_hint_block(hint[0], emb, context)
200
+
201
+ out_output = []
202
+ out_middle = []
203
+
204
+ hs = []
205
+ if self.num_classes is not None:
206
+ assert y.shape[0] == x.shape[0]
207
+ emb = emb + self.label_emb(y)
208
+
209
+ h = x
210
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
211
+ if guided_hint is not None:
212
+ h = module(h, emb, context)
213
+ h += guided_hint
214
+ guided_hint = None
215
+ else:
216
+ h = module(h, emb, context)
217
+ out_output.append(zero_conv(h, emb, context))
218
+
219
+ h = self.middle_block(h, emb, context)
220
+ out_middle.append(self.middle_block_out(h, emb, context))
221
+
222
+ return {"middle": out_middle, "output": out_output}
223
+
224
+
225
+ class ControlNetPlusPlusAdvanced(ControlNet, AdvancedControlBase):
226
+ def __init__(self, control_model: ControlNetPlusPlus, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, load_device=None, manual_cast_dtype=None):
227
+ super().__init__(control_model=control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
228
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controlnet())
229
+ self.add_compatible_weight(ControlWeightType.CONTROLNETPLUSPLUS)
230
+ # for IDE type hint purposes
231
+ self.control_model: ControlNetPlusPlus
232
+ self.cond_hint_original: Union[PlusPlusImageWrapper, PlusPlusInputGroup]
233
+ self.cond_hint: list[Union[Tensor, None]]
234
+ self.cond_hint_shape: Tensor = None
235
+ self.cond_hint_types: Tensor = None
236
+ # in case it is using the single loader
237
+ self.single_control_type: str = None
238
+
239
+ def get_universal_weights(self) -> ControlWeights:
240
+ def cn_weights_func(idx: int, control: dict[str, list[Tensor]], key: str):
241
+ if key == "middle":
242
+ return 1.0 * self.weights.extras.get(Extras.MIDDLE_MULT, 1.0)
243
+ c_len = len(control[key])
244
+ raw_weights = [(self.weights.base_multiplier ** float((c_len) - i)) for i in range(c_len+1)]
245
+ raw_weights = raw_weights[:-1]
246
+ if key == "input":
247
+ raw_weights.reverse()
248
+ return raw_weights[idx]
249
+ return self.weights.copy_with_new_weights(new_weight_func=cn_weights_func)
250
+
251
+ def verify_control_type(self, model_name: str, pp_group: PlusPlusInputGroup=None):
252
+ if pp_group is not None:
253
+ for pp_input in pp_group.controls.values():
254
+ if PlusPlusType.to_idx(pp_input.control_type) >= self.control_model.num_control_type:
255
+ raise Exception(f"ControlNet++ model '{model_name}' does not support control_type '{pp_input.control_type}'.")
256
+ if self.single_control_type is not None:
257
+ if PlusPlusType.to_idx(self.single_control_type) >= self.control_model.num_control_type:
258
+ raise Exception(f"ControlNet++ model '{model_name}' does not support control_type '{self.single_control_type}'.")
259
+
260
+ def set_cond_hint_inject(self, *args, **kwargs):
261
+ to_return = super().set_cond_hint_inject(*args, **kwargs)
262
+ # if not single_control_type, expect PlusPlusImageWrapper
263
+ if self.single_control_type is None:
264
+ # check that cond_hint is wrapped, and unwrap it
265
+ if type(self.cond_hint_original) != PlusPlusImageWrapper:
266
+ raise Exception("ControlNet++ (Multi) expects image input from the Load ControlNet++ Model node, NOT from anything else. Images are provided to that node via ControlNet++ Input nodes.")
267
+ self.cond_hint_original = self.cond_hint_original.condhint.clone()
268
+ # otherwise, expect single image input (AKA, usual controlnet input)
269
+ else:
270
+ # check that cond_hint is not a PlusPlusImageWrapper
271
+ if type(self.cond_hint_original) == PlusPlusImageWrapper:
272
+ raise Exception("ControlNet++ (Single) expects usual image input, NOT the image input from a Load ControlNet++ Model (Multi) node.")
273
+ pp_group = PlusPlusInputGroup()
274
+ pp_input = PlusPlusInput(self.cond_hint_original, self.single_control_type, 1.0)
275
+ pp_group.add(pp_input)
276
+ self.cond_hint_original = pp_group
277
+ return to_return
278
+
279
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number, transformer_options):
280
+ control_prev = None
281
+ if self.previous_controlnet is not None:
282
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
283
+
284
+ if self.timestep_range is not None:
285
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
286
+ if control_prev is not None:
287
+ return control_prev
288
+ else:
289
+ return None
290
+
291
+ dtype = self.control_model.dtype
292
+ if self.manual_cast_dtype is not None:
293
+ dtype = self.manual_cast_dtype
294
+
295
+ output_dtype = x_noisy.dtype
296
+
297
+ # make all cond_hints appropriate dimensions
298
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs is present
299
+ 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]:
300
+ if self.cond_hint is not None:
301
+ del self.cond_hint
302
+ self.cond_hint = [None] * self.control_model.num_control_type
303
+ self.cond_hint_types = torch.tensor([0.0] * self.control_model.num_control_type)
304
+ self.cond_hint_shape = None
305
+ compression_ratio = self.compression_ratio
306
+ # unlike normal controlnet, need to handle each input image tensor (for each type)
307
+ for pp_type, pp_input in self.cond_hint_original.controls.items():
308
+ pp_idx = PlusPlusType.to_idx(pp_type)
309
+ # if negative, means no type should be selected (single only)
310
+ if pp_idx < 0:
311
+ pp_idx = 0
312
+ else:
313
+ self.cond_hint_types[pp_idx] = pp_input.strength
314
+ # if self.cond_hint_original lengths greater or equal to latent count, subdivide
315
+ if self.sub_idxs is not None:
316
+ actual_cond_hint_orig = pp_input.image
317
+ if pp_input.image.size(0) < self.full_latent_length:
318
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
319
+ self.cond_hint[pp_idx] = 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")
320
+ else:
321
+ self.cond_hint[pp_idx] = comfy.utils.common_upscale(pp_input.image, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, 'nearest-exact', "center")
322
+ self.cond_hint[pp_idx] = self.cond_hint[pp_idx].to(device=x_noisy.device, dtype=dtype)
323
+ self.cond_hint_shape = self.cond_hint[pp_idx].shape
324
+ # prepare cond_hint_controls to match batchsize
325
+ if self.cond_hint_types.count_nonzero() == 0:
326
+ self.cond_hint_types = None
327
+ else:
328
+ self.cond_hint_types = self.cond_hint_types.unsqueeze(0).to(device=x_noisy.device, dtype=dtype).repeat(x_noisy.shape[0], 1)
329
+ for i in range(len(self.cond_hint)):
330
+ if self.cond_hint[i] is not None:
331
+ if x_noisy.shape[0] != self.cond_hint[i].shape[0]:
332
+ self.cond_hint[i] = broadcast_image_to_extend(self.cond_hint[i], x_noisy.shape[0], batched_number)
333
+ if self.cond_hint_types is not None and x_noisy.shape[0] != self.cond_hint_types.shape[0]:
334
+ self.cond_hint_types = broadcast_image_to_extend(self.cond_hint_types, x_noisy.shape[0], batched_number, False)
335
+
336
+ # prepare mask_cond_hint
337
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
338
+
339
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
340
+ y = cond.get('y', None)
341
+ if y is not None:
342
+ y = y.to(dtype)
343
+ timestep = self.model_sampling_current.timestep(t)
344
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
345
+
346
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, control_type=self.cond_hint_types)
347
+ return self.control_merge(control, control_prev, output_dtype)
348
+
349
+ def copy(self):
350
+ c = ControlNetPlusPlusAdvanced(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)
351
+ self.copy_to(c)
352
+ self.copy_to_advanced(c)
353
+ c.single_control_type = self.single_control_type
354
+ return c
355
+
356
+
357
+ def load_controlnetplusplus(ckpt_path: str, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
358
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
359
+ # check that actually is ControlNet++ model
360
+ if "task_embedding" not in controlnet_data:
361
+ raise Exception(f"'{ckpt_path}' is not a valid ControlNet++ model.")
362
+
363
+ controlnet_config = None
364
+ supported_inference_dtypes = None
365
+
366
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
367
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
368
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
369
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
370
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
371
+
372
+ count = 0
373
+ loop = True
374
+ while loop:
375
+ suffix = [".weight", ".bias"]
376
+ for s in suffix:
377
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
378
+ k_out = "zero_convs.{}.0{}".format(count, s)
379
+ if k_in not in controlnet_data:
380
+ loop = False
381
+ break
382
+ diffusers_keys[k_in] = k_out
383
+ count += 1
384
+
385
+ count = 0
386
+ loop = True
387
+ while loop:
388
+ suffix = [".weight", ".bias"]
389
+ for s in suffix:
390
+ if count == 0:
391
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
392
+ else:
393
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
394
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
395
+ if k_in not in controlnet_data:
396
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
397
+ loop = False
398
+ diffusers_keys[k_in] = k_out
399
+ count += 1
400
+
401
+ new_sd = {}
402
+ for k in diffusers_keys:
403
+ if k in controlnet_data:
404
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
405
+
406
+ if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
407
+ controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
408
+ for k in list(controlnet_data.keys()):
409
+ new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
410
+ new_sd[new_k] = controlnet_data.pop(k)
411
+
412
+ leftover_keys = controlnet_data.keys()
413
+ if len(leftover_keys) > 0:
414
+ logger.warning("leftover ControlNet++ keys: {}".format(leftover_keys))
415
+ controlnet_data = new_sd
416
+ elif "controlnet_blocks.0.weight" in controlnet_data: #SD3 diffusers format
417
+ raise Exception("Unexpected SD3 diffusers format for ControlNet++ model. Something is very wrong.")
418
+
419
+ pth_key = 'control_model.zero_convs.0.0.weight'
420
+ pth = False
421
+ key = 'zero_convs.0.0.weight'
422
+ if pth_key in controlnet_data:
423
+ pth = True
424
+ key = pth_key
425
+ prefix = "control_model."
426
+ elif key in controlnet_data:
427
+ prefix = ""
428
+ else:
429
+ raise Exception("Unexpected T2IAdapter format for ControlNet++ model. Something is very wrong.")
430
+
431
+ if controlnet_config is None:
432
+ model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
433
+ supported_inference_dtypes = model_config.supported_inference_dtypes
434
+ controlnet_config = model_config.unet_config
435
+
436
+ load_device = comfy.model_management.get_torch_device()
437
+ if supported_inference_dtypes is None:
438
+ unet_dtype = comfy.model_management.unet_dtype()
439
+ else:
440
+ unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
441
+
442
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
443
+ if manual_cast_dtype is not None:
444
+ controlnet_config["operations"] = comfy.ops.manual_cast
445
+ controlnet_config["dtype"] = unet_dtype
446
+ controlnet_config.pop("out_channels")
447
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
448
+ control_model = ControlNetPlusPlus(**controlnet_config)
449
+
450
+ if pth:
451
+ if 'difference' in controlnet_data:
452
+ if model is not None:
453
+ comfy.model_management.load_models_gpu([model])
454
+ model_sd = model.model_state_dict()
455
+ for x in controlnet_data:
456
+ c_m = "control_model."
457
+ if x.startswith(c_m):
458
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
459
+ if sd_key in model_sd:
460
+ cd = controlnet_data[x]
461
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
462
+ else:
463
+ logger.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
464
+
465
+ class WeightsLoader(torch.nn.Module):
466
+ pass
467
+ w = WeightsLoader()
468
+ w.control_model = control_model
469
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
470
+ else:
471
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
472
+
473
+ if len(missing) > 0:
474
+ logger.warning("missing ControlNet++ keys: {}".format(missing))
475
+
476
+ if len(unexpected) > 0:
477
+ logger.debug("unexpected ControlNet++ keys: {}".format(unexpected))
478
+
479
+ global_average_pooling = False
480
+ filename = os.path.splitext(ckpt_path)[0]
481
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
482
+ global_average_pooling = True
483
+
484
+ control = ControlNetPlusPlusAdvanced(control_model, timestep_keyframes=timestep_keyframe, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
485
+ return control
ComfyUI-Advanced-ControlNet/adv_control/control_reference.py ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+
3
+ from uuid import UUID
4
+ import math
5
+ import torch
6
+ from torch import Tensor
7
+
8
+ import comfy.model_management
9
+ import comfy.patcher_extension
10
+ import comfy.sample
11
+ import comfy.hooks
12
+ import comfy.model_patcher
13
+ import comfy.utils
14
+ from comfy.controlnet import ControlBase
15
+ from comfy.model_patcher import ModelPatcher
16
+ from comfy.ldm.modules.attention import BasicTransformerBlock
17
+ from comfy.ldm.modules.diffusionmodules import openaimodel
18
+
19
+ from .logger import logger
20
+ from .utils import (AdvancedControlBase, ControlWeights, TimestepKeyframeGroup, TimestepKeyframe, AbstractPreprocWrapper,
21
+ broadcast_image_to_extend, ORIG_PREVIOUS_CONTROLNET, CONTROL_INIT_BY_ACN)
22
+
23
+
24
+ REF_READ_ATTN_CONTROL_LIST = "ref_read_attn_control_list"
25
+ REF_WRITE_ATTN_CONTROL_LIST = "ref_write_attn_control_list"
26
+ REF_READ_ADAIN_CONTROL_LIST = "ref_read_adain_control_list"
27
+ REF_WRITE_ADAIN_CONTROL_LIST = "ref_write_adain_control_list"
28
+
29
+ REF_ATTN_CONTROL_LIST = "ref_attn_control_list"
30
+ REF_ADAIN_CONTROL_LIST = "ref_adain_control_list"
31
+ REF_CONTROL_LIST_ALL = "ref_control_list_all"
32
+ REF_CONTROL_INFO = "ref_control_info"
33
+ REF_ATTN_MACHINE_STATE = "ref_attn_machine_state"
34
+ REF_ADAIN_MACHINE_STATE = "ref_adain_machine_state"
35
+ REF_COND_IDXS = "ref_cond_idxs"
36
+ REF_UNCOND_IDXS = "ref_uncond_idxs"
37
+
38
+ CONTEXTREF_OPTIONS_CLASS = "contextref_options_class"
39
+ CONTEXTREF_CLEAN_FUNC = "contextref_clean_func"
40
+ CONTEXTREF_CONTROL_LIST_ALL = "contextref_control_list_all"
41
+ CONTEXTREF_MACHINE_STATE = "contextref_machine_state"
42
+ CONTEXTREF_TEMP_COND_IDX = "contextref_temp_cond_idx"
43
+
44
+ HIGHEST_VERSION_SUPPORT = 1
45
+ RETURNED_CONTEXTREF_VERSION = 1
46
+
47
+
48
+ class RefConst:
49
+ OPTS = "refcn_opts"
50
+ CREF_MODE = "contextref_mode"
51
+ REFCN_PRESENT_IN_CONDS = "refcn_present_in_conds"
52
+
53
+
54
+ class MachineState:
55
+ WRITE = "write"
56
+ READ = "read"
57
+ READ_WRITE = "read_write"
58
+ STYLEALIGN = "stylealign"
59
+ OFF = "off"
60
+
61
+ def is_read(state: str):
62
+ return state in [MachineState.READ, MachineState.READ_WRITE]
63
+
64
+ def is_write(state: str):
65
+ return state in [MachineState.WRITE, MachineState.READ_WRITE]
66
+
67
+
68
+ class ReferenceType:
69
+ ATTN = "reference_attn"
70
+ ADAIN = "reference_adain"
71
+ ATTN_ADAIN = "reference_attn+adain"
72
+ STYLE_ALIGN = "StyleAlign"
73
+
74
+ _LIST = [ATTN, ADAIN, ATTN_ADAIN]
75
+ _LIST_ATTN = [ATTN, ATTN_ADAIN]
76
+ _LIST_ADAIN = [ADAIN, ATTN_ADAIN]
77
+
78
+ @classmethod
79
+ def is_attn(cls, ref_type: str):
80
+ return ref_type in cls._LIST_ATTN
81
+
82
+ @classmethod
83
+ def is_adain(cls, ref_type: str):
84
+ return ref_type in cls._LIST_ADAIN
85
+
86
+
87
+ class ReferenceOptions:
88
+ def __init__(self, reference_type: str,
89
+ attn_style_fidelity: float, adain_style_fidelity: float,
90
+ attn_ref_weight: float, adain_ref_weight: float,
91
+ attn_strength: float=1.0, adain_strength: float=1.0,
92
+ ref_with_other_cns: bool=False):
93
+ self.reference_type = reference_type
94
+ # attn
95
+ self.original_attn_style_fidelity = attn_style_fidelity
96
+ self.attn_style_fidelity = attn_style_fidelity
97
+ self.attn_ref_weight = attn_ref_weight
98
+ self.attn_strength = attn_strength
99
+ # adain
100
+ self.original_adain_style_fidelity = adain_style_fidelity
101
+ self.adain_style_fidelity = adain_style_fidelity
102
+ self.adain_ref_weight = adain_ref_weight
103
+ self.adain_strength = adain_strength
104
+ # other
105
+ self.ref_with_other_cns = ref_with_other_cns
106
+
107
+ def clone(self):
108
+ return ReferenceOptions(reference_type=self.reference_type,
109
+ attn_style_fidelity=self.original_attn_style_fidelity, adain_style_fidelity=self.original_adain_style_fidelity,
110
+ attn_ref_weight=self.attn_ref_weight, adain_ref_weight=self.adain_ref_weight,
111
+ attn_strength=self.attn_strength, adain_strength=self.adain_strength,
112
+ ref_with_other_cns=self.ref_with_other_cns)
113
+
114
+ @staticmethod
115
+ def create_combo(reference_type: str, style_fidelity: float, ref_weight: float, ref_with_other_cns: bool=False):
116
+ return ReferenceOptions(reference_type=reference_type,
117
+ attn_style_fidelity=style_fidelity, adain_style_fidelity=style_fidelity,
118
+ attn_ref_weight=ref_weight, adain_ref_weight=ref_weight,
119
+ ref_with_other_cns=ref_with_other_cns)
120
+
121
+ @staticmethod
122
+ def create_from_kwargs(attn_style_fidelity=0.0, adain_style_fidelity=0.0,
123
+ attn_ref_weight=0.0, adain_ref_weight=0.0,
124
+ attn_strength=0.0, adain_strength=0.0, **kwargs):
125
+ has_attn = attn_strength > 0.0
126
+ has_adain = adain_strength > 0.0
127
+ if has_attn and has_adain:
128
+ reference_type = ReferenceType.ATTN_ADAIN
129
+ elif has_adain:
130
+ reference_type = ReferenceType.ADAIN
131
+ else:
132
+ reference_type = ReferenceType.ATTN
133
+ return ReferenceOptions(reference_type=reference_type,
134
+ attn_style_fidelity=float(attn_style_fidelity), adain_style_fidelity=float(adain_style_fidelity),
135
+ attn_ref_weight=float(attn_ref_weight), adain_ref_weight=float(adain_ref_weight),
136
+ attn_strength=float(attn_strength), adain_strength=float(adain_strength))
137
+
138
+
139
+ class ReferencePreprocWrapper(AbstractPreprocWrapper):
140
+ 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."
141
+ def __init__(self, condhint: Tensor):
142
+ super().__init__(condhint)
143
+
144
+
145
+ class ReferenceAdvanced(ControlBase, AdvancedControlBase):
146
+ CHANNEL_TO_MULT = {320: 1, 640: 2, 1280: 4}
147
+
148
+ def __init__(self, ref_opts: ReferenceOptions, timestep_keyframes: TimestepKeyframeGroup, extra_hooks: comfy.hooks.HookGroup=None):
149
+ super().__init__()
150
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite(), allow_condhint_latents=True)
151
+ # TODO: allow vae_optional to be used instead of preprocessor
152
+ #require_vae=True
153
+ self._ref_opts = ref_opts
154
+ self.order = 0
155
+ self.model_latent_format = None
156
+ self.model_sampling_current = None
157
+ self.should_apply_attn_effective_strength = False
158
+ self.should_apply_adain_effective_strength = False
159
+ self.should_apply_effective_masks = False
160
+ self.latent_shape = None
161
+ # wrapper hooks
162
+ self.extra_hooks = extra_hooks.clone() if extra_hooks else self.import_and_create_wrapper_hooks()
163
+ # ContextRef stuff
164
+ self.is_context_ref = False
165
+ self.contextref_cond_idx = -1 # NOTE: does nothing ever since conds got uuids associated with them; can remove
166
+ self.contextref_version = RETURNED_CONTEXTREF_VERSION
167
+
168
+ @property
169
+ def ref_opts(self):
170
+ if self._current_timestep_keyframe is not None and self._current_timestep_keyframe.has_control_weights():
171
+ return self._current_timestep_keyframe.control_weights.extras.get(RefConst.OPTS, self._ref_opts)
172
+ return self._ref_opts
173
+
174
+ def import_and_create_wrapper_hooks(self):
175
+ from .sampling import create_wrapper_hooks
176
+ return create_wrapper_hooks()
177
+
178
+ def any_attn_strength_to_apply(self):
179
+ return self.should_apply_attn_effective_strength or self.should_apply_effective_masks
180
+
181
+ def any_adain_strength_to_apply(self):
182
+ return self.should_apply_adain_effective_strength or self.should_apply_effective_masks
183
+
184
+ def get_effective_strength(self):
185
+ effective_strength = self.strength
186
+ if self._current_timestep_keyframe is not None:
187
+ effective_strength = effective_strength * self._current_timestep_keyframe.strength
188
+ return effective_strength
189
+
190
+ def get_effective_attn_mask_or_float(self, x: Tensor, channels: int, is_mid: bool):
191
+ if not self.should_apply_effective_masks:
192
+ return self.get_effective_strength() * self.ref_opts.attn_strength
193
+ if is_mid:
194
+ div = 8
195
+ else:
196
+ div = self.CHANNEL_TO_MULT[channels]
197
+ 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
198
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
199
+ # mask is now shape [b, 1, h ,w]; need to turn into [b, h*w, 1]
200
+ b, c, h, w = real_mask.shape
201
+ real_mask = real_mask.permute(0, 2, 3, 1).reshape(b, h*w, c)
202
+ return real_mask
203
+
204
+ def get_effective_adain_mask_or_float(self, x: Tensor):
205
+ if not self.should_apply_effective_masks:
206
+ return self.get_effective_strength() * self.ref_opts.adain_strength
207
+ b, c, h, w = x.shape
208
+ real_mask = torch.ones([b, 1, h, w]).to(dtype=x.dtype, device=x.device) * self.strength * self.ref_opts.adain_strength
209
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
210
+ return real_mask
211
+
212
+ def get_contextref_mode_replace(self):
213
+ # used by ADE to get mode_replace for current keyframe
214
+ if self._current_timestep_keyframe.has_control_weights():
215
+ return self._current_timestep_keyframe.control_weights.extras.get(RefConst.CREF_MODE, None)
216
+ return None
217
+
218
+ def should_run(self):
219
+ running = super().should_run()
220
+ if not running:
221
+ return running
222
+ attn_run = False
223
+ adain_run = False
224
+ if ReferenceType.is_attn(self.ref_opts.reference_type):
225
+ # attn will run as long as neither weight or strength is zero
226
+ attn_run = not (math.isclose(self.ref_opts.attn_ref_weight, 0.0) or math.isclose(self.ref_opts.attn_strength, 0.0))
227
+ if ReferenceType.is_adain(self.ref_opts.reference_type):
228
+ # adain will run as long as neither weight or strength is zero
229
+ adain_run = not (math.isclose(self.ref_opts.adain_ref_weight, 0.0) or math.isclose(self.ref_opts.adain_strength, 0.0))
230
+ return attn_run or adain_run
231
+
232
+ def pre_run_advanced(self, model, percent_to_timestep_function):
233
+ AdvancedControlBase.pre_run_advanced(self, model, percent_to_timestep_function)
234
+ if isinstance(self.cond_hint_original, AbstractPreprocWrapper):
235
+ self.cond_hint_original = self.cond_hint_original.condhint
236
+ self.model_latent_format = model.latent_format # LatentFormat object, used to process_in latent cond_hint
237
+ self.model_sampling_current = model.model_sampling
238
+ # SDXL is more sensitive to style_fidelity according to sd-webui-controlnet comments;
239
+ # prepare all ref_opts accordingly
240
+ all_ref_opts = [self._ref_opts]
241
+ for kf in self.timestep_keyframes.keyframes:
242
+ if kf.has_control_weights() and RefConst.OPTS in kf.control_weights.extras:
243
+ all_ref_opts.append(kf.control_weights.extras[RefConst.OPTS])
244
+ for ropts in all_ref_opts:
245
+ if type(model).__name__ == "SDXL":
246
+ ropts.attn_style_fidelity = ropts.original_attn_style_fidelity ** 3.0
247
+ ropts.adain_style_fidelity = ropts.original_adain_style_fidelity ** 3.0
248
+ else:
249
+ ropts.attn_style_fidelity = ropts.original_attn_style_fidelity
250
+ ropts.adain_style_fidelity = ropts.original_adain_style_fidelity
251
+
252
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int, transformer_options):
253
+ # normal ControlNet stuff
254
+ control_prev = None
255
+ if self.previous_controlnet is not None:
256
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
257
+
258
+ if self.timestep_range is not None:
259
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
260
+ return control_prev
261
+
262
+ dtype = x_noisy.dtype
263
+ # cond_hint_original only matters for RefCN, NOT ContextRef
264
+ if self.cond_hint_original is not None:
265
+ # prepare cond_hint - it is a latent, NOT an image
266
+ #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]:
267
+ if self.cond_hint is not None:
268
+ del self.cond_hint
269
+ self.cond_hint = None
270
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
271
+ if self.sub_idxs is not None and self.cond_hint_original.size(0) >= self.full_latent_length:
272
+ self.cond_hint = comfy.utils.common_upscale(
273
+ self.cond_hint_original[self.sub_idxs],
274
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(x_noisy.device)
275
+ else:
276
+ self.cond_hint = comfy.utils.common_upscale(
277
+ self.cond_hint_original,
278
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(x_noisy.device)
279
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
280
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number, except_one=False)
281
+ # noise cond_hint based on sigma (current step)
282
+ self.cond_hint = self.model_latent_format.process_in(self.cond_hint)
283
+ self.cond_hint = ref_noise_latents(self.cond_hint, sigma=t, noise=None)
284
+ timestep = self.model_sampling_current.timestep(t)
285
+ 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))
286
+ 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))
287
+ # prepare mask - use direct_attn, so the mask dims will match source latents (and be smaller)
288
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, direct_attn=True)
289
+ 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
290
+ self.latent_shape = list(x_noisy.shape)
291
+ # done preparing; model patches will take care of everything now.
292
+ transformer_options[RefConst.REFCN_PRESENT_IN_CONDS] = True
293
+ # return normal controlnet stuff
294
+ return control_prev
295
+
296
+ def cleanup_advanced(self):
297
+ super().cleanup_advanced()
298
+ del self.model_latent_format
299
+ self.model_latent_format = None
300
+ del self.model_sampling_current
301
+ self.model_sampling_current = None
302
+ self.should_apply_attn_effective_strength = False
303
+ self.should_apply_adain_effective_strength = False
304
+ self.should_apply_effective_masks = False
305
+
306
+ def copy(self):
307
+ c = ReferenceAdvanced(self.ref_opts, self.timestep_keyframes, self.extra_hooks)
308
+ c.order = self.order
309
+ c.is_context_ref = self.is_context_ref
310
+ self.copy_to(c)
311
+ self.copy_to_advanced(c)
312
+ return c
313
+
314
+ # avoid deepcopy shenanigans by making deepcopy not do anything to the reference
315
+ # TODO: do the bookkeeping to do this in a proper way for all Adv-ControlNets
316
+ def __deepcopy__(self, memo):
317
+ return self
318
+
319
+
320
+ def handle_context_ref_setup(contextref_obj, transformer_options: dict, conds: dict[str, list[dict, str]]):
321
+ transformer_options[CONTEXTREF_MACHINE_STATE] = MachineState.OFF
322
+ # verify version is compatible
323
+ if contextref_obj.version > HIGHEST_VERSION_SUPPORT:
324
+ raise Exception(f"AnimateDiff-Evolved's ContextRef v{contextref_obj.version} is not supported in currently-installed Advanced-ControlNet (only supports ContextRef up to v{HIGHEST_VERSION_SUPPORT}); " +
325
+ f"update your Advanced-ControlNet nodes for ContextRef to work.")
326
+ # init ReferenceOptions
327
+ cref_opt_dict = contextref_obj.tune.create_dict() # ContextRefTune obj from ADE
328
+ opts = ReferenceOptions.create_from_kwargs(**cref_opt_dict)
329
+ # init TimestepKeyframes
330
+ cref_tks_list = contextref_obj.keyframe.create_list_of_dicts() # ContextRefKeyframeGroup obj from ADE
331
+ timestep_keyframes = _create_tks_from_dict_list(cref_tks_list)
332
+ # create ReferenceAdvanced
333
+ cref = ReferenceAdvanced(ref_opts=opts, timestep_keyframes=timestep_keyframes)
334
+ cref.strength = contextref_obj.strength # ContextRef obj from ADE
335
+ cref.set_cond_hint_mask(contextref_obj.mask)
336
+ cref.order = 99
337
+ cref.is_context_ref = True
338
+ context_ref_list = [cref]
339
+ transformer_options[CONTEXTREF_CONTROL_LIST_ALL] = context_ref_list
340
+ transformer_options[CONTEXTREF_OPTIONS_CLASS] = ReferenceOptions
341
+ _add_context_ref_to_conds(conds, cref)
342
+ return context_ref_list
343
+
344
+
345
+ def _create_tks_from_dict_list(dlist: list[dict[str]]) -> TimestepKeyframeGroup:
346
+ tks = TimestepKeyframeGroup()
347
+ if dlist is None or len(dlist) == 0:
348
+ return tks
349
+ for d in dlist:
350
+ # scheduling
351
+ start_percent = d["start_percent"]
352
+ guarantee_steps = d["guarantee_steps"]
353
+ inherit_missing = d["inherit_missing"]
354
+ # values
355
+ strength = d["strength"]
356
+ mask = d["mask"]
357
+ tune = d["tune"]
358
+ mode = d["mode"]
359
+ weights = None
360
+ extras = {}
361
+ if tune is not None:
362
+ cref_opt_dict = tune.create_dict() # ContextRefTune obj from ADE
363
+ opts = ReferenceOptions.create_from_kwargs(**cref_opt_dict)
364
+ extras[RefConst.OPTS] = opts
365
+ if mode is not None:
366
+ extras[RefConst.CREF_MODE] = mode
367
+ weights = ControlWeights.default(extras=extras)
368
+ # create keyframe
369
+ tk = TimestepKeyframe(start_percent=start_percent, guarantee_steps=guarantee_steps, inherit_missing=inherit_missing,
370
+ strength=strength, mask_hint_orig=mask, control_weights=weights)
371
+ tks.add(tk)
372
+ return tks
373
+
374
+
375
+ def _add_context_ref_to_conds(conds: dict[list[dict[str]]], context_ref: ReferenceAdvanced):
376
+ def _add_context_ref_to_existing_control(control: ControlBase, context_ref: ReferenceAdvanced):
377
+ curr_cn = control
378
+ while curr_cn is not None:
379
+ if type(curr_cn) == ReferenceAdvanced and curr_cn.is_context_ref:
380
+ break
381
+ if curr_cn.previous_controlnet is not None:
382
+ curr_cn = curr_cn.previous_controlnet
383
+ continue
384
+ orig_previous_controlnet = curr_cn.previous_controlnet
385
+ # NOTE: code is already in place to restore any ORIG_PREVIOUS_CONTROLNET props
386
+ setattr(curr_cn, ORIG_PREVIOUS_CONTROLNET, orig_previous_controlnet)
387
+ curr_cn.previous_controlnet = context_ref
388
+ curr_cn = orig_previous_controlnet
389
+
390
+ def _add_context_ref(actual_cond: dict[str], context_ref: ReferenceAdvanced):
391
+ # if controls already present on cond, add it to the last previous_controlnet
392
+ if "control" in actual_cond:
393
+ return _add_context_ref_to_existing_control(actual_cond["control"], context_ref)
394
+ # otherwise, need to add it to begin with, and should mark that it should be cleaned after
395
+ actual_cond["control"] = context_ref
396
+ actual_cond[CONTROL_INIT_BY_ACN] = True
397
+
398
+ # either add context_ref to end of existing cnet chain, or init 'control' key on actual cond
399
+ for cond_type in conds:
400
+ cond = conds[cond_type]
401
+ if cond is not None:
402
+ for actual_cond in cond:
403
+ _add_context_ref(actual_cond, context_ref)
404
+
405
+
406
+ def ref_noise_latents(latents: Tensor, sigma: Tensor, noise: Tensor=None):
407
+ sigma = sigma.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
408
+ alpha_cumprod = 1 / ((sigma * sigma) + 1)
409
+ sqrt_alpha_prod = alpha_cumprod ** 0.5
410
+ sqrt_one_minus_alpha_prod = (1. - alpha_cumprod) ** 0.5
411
+ if noise is None:
412
+ # generator = torch.Generator(device="cuda")
413
+ # generator.manual_seed(0)
414
+ # noise = torch.empty_like(latents).normal_(generator=generator)
415
+ # generator = torch.Generator()
416
+ # generator.manual_seed(0)
417
+ # noise = torch.randn(latents.size(), generator=generator).to(latents.device)
418
+ noise = torch.randn_like(latents).to(latents.device)
419
+ return sqrt_alpha_prod * latents + sqrt_one_minus_alpha_prod * noise
420
+
421
+
422
+ def simple_noise_latents(latents: Tensor, sigma: float, noise: Tensor=None):
423
+ if noise is None:
424
+ noise = torch.rand_like(latents)
425
+ return latents + noise * sigma
426
+
427
+
428
+ class BankStylesBasicTransformerBlock:
429
+ def __init__(self):
430
+ # ref
431
+ self.bank = []
432
+ self.style_cfgs = []
433
+ self.cn_idx: list[int] = []
434
+ # contextref - list of lists as each cond/uncond stored separately
435
+ self.c_bank: dict[UUID, list[Tensor]] = {}
436
+ self.c_style_cfgs: dict[UUID, list[float]] = {}
437
+ self.c_cn_idx: dict[UUID, list[int]] = {}
438
+
439
+ def set_c_bank_for_uuids(self, x: Tensor, uuids: list[UUID]):
440
+ per_uuid = len(x) // len(uuids)
441
+ for uuid, i in zip(uuids, list(range(0, len(x), per_uuid))):
442
+ self.c_bank.setdefault(uuid, []).append(x[i:i+per_uuid])
443
+
444
+ def _get_c_bank_for_uuids(self, uuids: list[UUID]):
445
+ per_i: list[list[Tensor]] = []
446
+ for uuid in uuids:
447
+ for i, bank in enumerate(self.c_bank[uuid]):
448
+ if i >= len(per_i):
449
+ per_i.append([])
450
+ per_i[i].append(bank)
451
+ real_banks = []
452
+ for bank in per_i:
453
+ if len(bank) == 1:
454
+ combined = bank[0]
455
+ else:
456
+ combined = torch.cat(bank, dim=0)
457
+ real_banks.append(combined)
458
+ return real_banks
459
+
460
+ def get_bank(self, uuids: list[UUID], ignore_contextref, cdevice=None):
461
+ if ignore_contextref:
462
+ return self.bank
463
+ real_c_bank_list = self._get_c_bank_for_uuids(uuids)
464
+ if cdevice != None:
465
+ real_c_bank_list = real_c_bank_list.copy()
466
+ for i in range(len(real_c_bank_list)):
467
+ real_c_bank_list[i] = real_c_bank_list[i].to(cdevice)
468
+ return self.bank + real_c_bank_list
469
+
470
+
471
+ def set_c_style_cfgs_for_uuids(self, style_cfg: float, uuids: list[UUID]):
472
+ for uuid in uuids:
473
+ self.c_style_cfgs.setdefault(uuid, []).append(style_cfg)
474
+
475
+ def get_avg_style_fidelity(self, uuids: list[UUID], ignore_contextref):
476
+ if ignore_contextref:
477
+ return sum(self.style_cfgs) / float(len(self.style_cfgs))
478
+ combined = self.style_cfgs + self._get_c_style_cfgs_for_uuids(uuids)
479
+ return sum(combined) / float(len(combined))
480
+
481
+ def _get_c_style_cfgs_for_uuids(self, uuids: list[UUID]):
482
+ # c_style_cfgs will be the same for all provided uuids
483
+ return self.c_style_cfgs[uuids[0]]
484
+
485
+
486
+ def set_c_cn_idx_for_uuids(self, cn_idx: int, uuids: list[UUID]):
487
+ for uuid in uuids:
488
+ self.c_cn_idx.setdefault(uuid, []).append(cn_idx)
489
+
490
+ def get_cn_idxs(self, uuids: list[UUID], ignore_contxtref):
491
+ if ignore_contxtref:
492
+ return self.cn_idx
493
+ return self.cn_idx + self._get_c_cn_idxs_for_uuids(uuids)
494
+
495
+ def _get_c_cn_idxs_for_uuids(self, uuids: list[UUID]):
496
+ # c_cn_idxs will be the same for all provided uuids
497
+ return self.c_cn_idx.get(uuids[0], [])
498
+
499
+
500
+ def init_cref_for_uuids(self, uuids: list[UUID]):
501
+ for uuid in uuids:
502
+ self.c_bank.setdefault(uuid, [])
503
+ self.c_style_cfgs.setdefault(uuid, [])
504
+ self.c_cn_idx.setdefault(uuid, [])
505
+
506
+ def clear_cref_for_uuids(self, uuids: list[UUID]):
507
+ for uuid in uuids:
508
+ self.c_bank[uuid] = []
509
+ self.c_style_cfgs[uuid] = []
510
+ self.c_cn_idx[uuid] = []
511
+
512
+ def clean_ref(self):
513
+ del self.bank
514
+ del self.style_cfgs
515
+ del self.cn_idx
516
+ self.bank = []
517
+ self.style_cfgs = []
518
+ self.cn_idx = []
519
+
520
+ def clean_contextref(self):
521
+ del self.c_bank
522
+ del self.c_style_cfgs
523
+ del self.c_cn_idx
524
+ self.c_bank = {}
525
+ self.c_style_cfgs = {}
526
+ self.c_cn_idx = {}
527
+
528
+ def clean_all(self):
529
+ self.clean_ref()
530
+ self.clean_contextref()
531
+
532
+
533
+ class BankStylesTimestepEmbedSequential:
534
+ def __init__(self):
535
+ # ref
536
+ self.var_bank = []
537
+ self.mean_bank = []
538
+ self.style_cfgs = []
539
+ self.cn_idx: list[int] = []
540
+ # cref
541
+ self.c_var_bank: dict[UUID, list[Tensor]] = {}
542
+ self.c_mean_bank: dict[UUID, list[Tensor]] = {}
543
+ self.c_style_cfgs: dict[UUID, list[float]] = {}
544
+ self.c_cn_idx: dict[UUID, list[int]] = {}
545
+
546
+ def set_c_var_bank_for_uuids(self, var: Tensor, uuids: list[UUID]):
547
+ for uuid in uuids:
548
+ self.c_var_bank.setdefault(uuid, []).append(var)
549
+
550
+ def get_var_bank(self, uuids: list[UUID], ignore_contextref):
551
+ if ignore_contextref:
552
+ return self.var_bank
553
+ return self.var_bank + self._get_c_var_bank_for_uuids(uuids)
554
+
555
+ def _get_c_var_bank_for_uuids(self, uuids: list[UUID]):
556
+ return self.c_var_bank.get(uuids[0], [])
557
+
558
+
559
+ def set_c_mean_bank_for_uuids(self, mean: Tensor, uuids: list[UUID]):
560
+ for uuid in uuids:
561
+ self.c_mean_bank.setdefault(uuid, []).append(mean)
562
+
563
+ def get_mean_bank(self, uuids: list[UUID], ignore_contextref):
564
+ if ignore_contextref:
565
+ return self.mean_bank
566
+ return self.mean_bank + self._get_c_mean_bank_for_uuids(uuids)
567
+
568
+ def _get_c_mean_bank_for_uuids(self, uuids: list[UUID]):
569
+ return self.c_mean_bank.get(uuids[0], [])
570
+
571
+
572
+ def set_c_style_cfgs_for_uuids(self, style_cfg: float, uuids: list[UUID]):
573
+ for uuid in uuids:
574
+ self.c_style_cfgs.setdefault(uuid, []).append(style_cfg)
575
+
576
+ def get_style_cfgs(self, uuids: list[UUID], ignore_contextref):
577
+ if ignore_contextref:
578
+ return self.style_cfgs
579
+ return self.style_cfgs + self._get_c_style_cfgs_for_uuids(uuids)
580
+
581
+ def _get_c_style_cfgs_for_uuids(self, uuids: list[UUID]):
582
+ return self.c_style_cfgs.get(uuids[0], [])
583
+
584
+
585
+ def set_c_cn_idx_for_uuids(self, cn_idx: int, uuids: list[UUID]):
586
+ for uuid in uuids:
587
+ self.c_cn_idx.setdefault(uuid, []).append(cn_idx)
588
+
589
+ def get_cn_idxs(self, uuids: list[UUID], ignore_contextref):
590
+ if ignore_contextref:
591
+ return self.cn_idx
592
+ return self.cn_idx + self._get_c_cn_idxs_for_uuids(uuids)
593
+
594
+ def _get_c_cn_idxs_for_uuids(self, uuids: list[UUID]):
595
+ return self.c_cn_idx.get(uuids[0], [])
596
+
597
+
598
+ def init_cref_for_uuids(self, uuids: list[UUID]):
599
+ for uuid in uuids:
600
+ self.c_var_bank.setdefault(uuid, [])
601
+ self.c_mean_bank.setdefault(uuid, [])
602
+ self.c_style_cfgs.setdefault(uuid, [])
603
+ self.c_cn_idx.setdefault(uuid, [])
604
+
605
+ def clear_cref_for_uuids(self, uuids: list[UUID]):
606
+ for uuid in uuids:
607
+ self.c_var_bank[uuid] = []
608
+ self.c_mean_bank[uuid] = []
609
+ self.c_style_cfgs[uuid] = []
610
+ self.c_cn_idx[uuid] = []
611
+
612
+ def clean_ref(self):
613
+ del self.mean_bank
614
+ del self.var_bank
615
+ del self.style_cfgs
616
+ del self.cn_idx
617
+ self.mean_bank = []
618
+ self.var_bank = []
619
+ self.style_cfgs = []
620
+ self.cn_idx = []
621
+
622
+ def clean_contextref(self):
623
+ del self.c_var_bank
624
+ del self.c_mean_bank
625
+ del self.c_style_cfgs
626
+ del self.c_cn_idx
627
+ self.c_var_bank = {}
628
+ self.c_mean_bank = {}
629
+ self.c_style_cfgs = {}
630
+ self.c_cn_idx = {}
631
+
632
+ def clean_all(self):
633
+ self.clean_ref()
634
+ self.clean_contextref()
635
+
636
+
637
+ class InjectionBasicTransformerBlockHolder:
638
+ def __init__(self, block: BasicTransformerBlock, idx=None):
639
+ if hasattr(block, "_forward"): # backward compatibility
640
+ self.original_forward = block._forward
641
+ else:
642
+ self.original_forward = block.forward
643
+ self.idx = idx
644
+ self.attn_weight = 1.0
645
+ self.is_middle = False
646
+ self.bank_styles = BankStylesBasicTransformerBlock()
647
+
648
+ def restore(self, block: BasicTransformerBlock):
649
+ if hasattr(block, "_forward"): # backward compatibility
650
+ block._forward = self.original_forward
651
+ else:
652
+ block.forward = self.original_forward
653
+
654
+ def clean_ref(self):
655
+ self.bank_styles.clean_ref()
656
+
657
+ def clean_contextref(self):
658
+ self.bank_styles.clean_contextref()
659
+
660
+ def clean_all(self):
661
+ self.bank_styles.clean_all()
662
+
663
+
664
+ class InjectionTimestepEmbedSequentialHolder:
665
+ def __init__(self, block: openaimodel.TimestepEmbedSequential, idx=None, is_middle=False, is_input=False, is_output=False):
666
+ self.original_forward = block.forward
667
+ self.idx = idx
668
+ self.gn_weight = 1.0
669
+ self.is_middle = is_middle
670
+ self.is_input = is_input
671
+ self.is_output = is_output
672
+ self.bank_styles = BankStylesTimestepEmbedSequential()
673
+
674
+ def restore(self, block: openaimodel.TimestepEmbedSequential):
675
+ block.forward = self.original_forward
676
+
677
+ def clean_ref(self):
678
+ self.bank_styles.clean_ref()
679
+
680
+ def clean_contextref(self):
681
+ self.bank_styles.clean_contextref()
682
+
683
+ def clean_all(self):
684
+ self.bank_styles.clean_all()
685
+
686
+
687
+ class ReferenceInjections:
688
+ def __init__(self, attn_modules: list['RefBasicTransformerBlock']=None, gn_modules: list['RefTimestepEmbedSequential']=None):
689
+ self.attn_modules = attn_modules if attn_modules else []
690
+ self.gn_modules = gn_modules if gn_modules else []
691
+
692
+ def clean_ref_module_mem(self):
693
+ for attn_module in self.attn_modules:
694
+ try:
695
+ attn_module.injection_holder.clean_ref()
696
+ except Exception:
697
+ pass
698
+ for gn_module in self.gn_modules:
699
+ try:
700
+ gn_module.injection_holder.clean_ref()
701
+ except Exception:
702
+ pass
703
+
704
+ def clean_contextref_module_mem(self):
705
+ for attn_module in self.attn_modules:
706
+ try:
707
+ attn_module.injection_holder.clean_contextref()
708
+ except Exception:
709
+ pass
710
+ for gn_module in self.gn_modules:
711
+ try:
712
+ gn_module.injection_holder.clean_contextref()
713
+ except Exception:
714
+ pass
715
+
716
+ def clean_all_module_mem(self):
717
+ for attn_module in self.attn_modules:
718
+ try:
719
+ attn_module.injection_holder.clean_all()
720
+ except Exception:
721
+ pass
722
+ for gn_module in self.gn_modules:
723
+ try:
724
+ gn_module.injection_holder.clean_all()
725
+ except Exception:
726
+ pass
727
+
728
+ def cleanup(self):
729
+ self.clean_all_module_mem()
730
+ del self.attn_modules
731
+ self.attn_modules = []
732
+ del self.gn_modules
733
+ self.gn_modules = []
734
+
735
+
736
+ def handle_reference_injection(model_options: dict, reference_injections: ReferenceInjections):
737
+ # register wrapper functions on transformer_options
738
+ comfy.patcher_extension.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL,
739
+ "ACN_refcn_diffusion_model",
740
+ refcn_diffusion_model_wrapper_factory(reference_injections),
741
+ model_options, is_model_options=True)
742
+
743
+
744
+ def refcn_diffusion_model_wrapper_factory(reference_injections: ReferenceInjections):
745
+ def refcn_diffusion_model_wrapper(executor, x, *args, **kwargs):
746
+ # get control and transformer_options from args
747
+ real_args = list(args)
748
+ real_kwargs = list(kwargs.keys())
749
+ # args values (x is treated separately, so all args are actually shifted by -1):
750
+ # -1: x
751
+ # 0: timesteps
752
+ # 1: context
753
+ # 2: y
754
+ # 3: control
755
+ # 4: transformer_options
756
+ control = args[3]
757
+ transformer_options = args[4]
758
+ # NOTE: adds support for both ReferenceCN and ContextRef, so need to track them separately
759
+ # get ReferenceAdvanced objects
760
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options.get(REF_CONTROL_LIST_ALL, [])
761
+ context_controlnets: list[ReferenceAdvanced] = transformer_options.get(CONTEXTREF_CONTROL_LIST_ALL, [])
762
+ # clean contextref stuff if OFF
763
+ if len(context_controlnets) > 0 and transformer_options[CONTEXTREF_MACHINE_STATE] == MachineState.OFF:
764
+ reference_injections.clean_contextref_module_mem()
765
+ context_controlnets = []
766
+ # discard any controlnets that should not run
767
+ refcn_present_in_conds = transformer_options.get(RefConst.REFCN_PRESENT_IN_CONDS, False)
768
+ if refcn_present_in_conds:
769
+ ref_controlnets = [z for z in ref_controlnets if z.should_run()]
770
+ else:
771
+ ref_controlnets = []
772
+ context_controlnets = [z for z in context_controlnets if z.should_run()]
773
+ # if nothing related to reference controlnets, do nothing special
774
+ if len(ref_controlnets) == 0 and len(context_controlnets) == 0:
775
+ return executor(x, *args, **kwargs)
776
+ try:
777
+ # assign cond and uncond idxs
778
+ batched_number = len(transformer_options["cond_or_uncond"])
779
+ per_batch = x.shape[0] // batched_number
780
+ indiv_conds = []
781
+ for cond_type in transformer_options["cond_or_uncond"]:
782
+ indiv_conds.extend([cond_type] * per_batch)
783
+ transformer_options[REF_UNCOND_IDXS] = [i for i, z in enumerate(indiv_conds) if z == 1]
784
+ transformer_options[REF_COND_IDXS] = [i for i, z in enumerate(indiv_conds) if z == 0]
785
+ # check which controlnets do which thing
786
+ attn_controlnets = []
787
+ adain_controlnets = []
788
+ for control in ref_controlnets:
789
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
790
+ attn_controlnets.append(control)
791
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
792
+ adain_controlnets.append(control)
793
+ context_attn_controlnets = []
794
+ context_adain_controlnets = []
795
+ # for ease of access, store current contextref_cond_idx value
796
+ if len(context_controlnets) == 0:
797
+ transformer_options[CONTEXTREF_TEMP_COND_IDX] = -1
798
+ else:
799
+ transformer_options[CONTEXTREF_TEMP_COND_IDX] = context_controlnets[0].contextref_cond_idx
800
+ # logger.info(f"{transformer_options[CONTEXTREF_MACHINE_STATE]}: {transformer_options[CONTEXTREF_TEMP_COND_IDX]}")
801
+
802
+ for control in context_controlnets:
803
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
804
+ context_attn_controlnets.append(control)
805
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
806
+ context_adain_controlnets.append(control)
807
+ if len(adain_controlnets) > 0 or len(context_adain_controlnets) > 0:
808
+ # ComfyUI uses forward_timestep_embed with the TimestepEmbedSequential passed into it
809
+ orig_forward_timestep_embed = openaimodel.forward_timestep_embed
810
+ openaimodel.forward_timestep_embed = forward_timestep_embed_ref_inject_factory(orig_forward_timestep_embed)
811
+
812
+ # if RefCN to be used, handle running diffusion with ref cond hints
813
+ if len(ref_controlnets) > 0:
814
+ for control in ref_controlnets:
815
+ read_attn_list = []
816
+ write_attn_list = []
817
+ read_adain_list = []
818
+ write_adain_list = []
819
+
820
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
821
+ write_attn_list.append(control)
822
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
823
+ write_adain_list.append(control)
824
+ # apply lists
825
+ transformer_options[REF_READ_ATTN_CONTROL_LIST] = read_attn_list
826
+ transformer_options[REF_WRITE_ATTN_CONTROL_LIST] = write_attn_list
827
+ transformer_options[REF_READ_ADAIN_CONTROL_LIST] = read_adain_list
828
+ transformer_options[REF_WRITE_ADAIN_CONTROL_LIST] = write_adain_list
829
+
830
+ orig_args = args
831
+ # disable other controlnets for this run, if specified
832
+ if not control.ref_opts.ref_with_other_cns:
833
+ args = list(args)
834
+ args[3] = None
835
+ args = tuple(args)
836
+ executor(control.cond_hint.to(dtype=x.dtype).to(device=x.device), *args, **kwargs)
837
+ args = orig_args
838
+ # prepare running diffusion for real now
839
+ read_attn_list = []
840
+ write_attn_list = []
841
+ read_adain_list = []
842
+ write_adain_list = []
843
+
844
+ # add RefCNs to read lists
845
+ read_attn_list.extend(attn_controlnets)
846
+ read_adain_list.extend(adain_controlnets)
847
+
848
+ # do contextref stuff, if needed
849
+ if len(context_controlnets) > 0:
850
+ # clean contextref stuff if first WRITE
851
+ # if context_controlnets[0].contextref_cond_idx == 0 and is_write(transformer_options[CONTEXTREF_MACHINE_STATE]):
852
+ # reference_injections.clean_contextref_module_mem()
853
+ ### add ContextRef to appropriate lists
854
+ # attn
855
+ if is_read(transformer_options[CONTEXTREF_MACHINE_STATE]):
856
+ read_attn_list.extend(context_attn_controlnets)
857
+ if is_write(transformer_options[CONTEXTREF_MACHINE_STATE]):
858
+ write_attn_list.extend(context_attn_controlnets)
859
+ # adain
860
+ if is_read(transformer_options[CONTEXTREF_MACHINE_STATE]):
861
+ read_adain_list.extend(context_adain_controlnets)
862
+ if is_write(transformer_options[CONTEXTREF_MACHINE_STATE]):
863
+ write_adain_list.extend(context_adain_controlnets)
864
+ # apply lists, containing both RefCN and ContextRef
865
+ transformer_options[REF_READ_ATTN_CONTROL_LIST] = read_attn_list
866
+ transformer_options[REF_WRITE_ATTN_CONTROL_LIST] = write_attn_list
867
+ transformer_options[REF_READ_ADAIN_CONTROL_LIST] = read_adain_list
868
+ transformer_options[REF_WRITE_ADAIN_CONTROL_LIST] = write_adain_list
869
+ # run diffusion for real
870
+ try:
871
+ return executor(x, *args, **kwargs)
872
+ finally:
873
+ # increment current cond idx
874
+ if len(context_controlnets) > 0:
875
+ for cn in context_controlnets:
876
+ cn.contextref_cond_idx += 1
877
+ finally:
878
+ # make sure ref banks are cleared no matter what happens - otherwise, RIP VRAM
879
+ reference_injections.clean_ref_module_mem()
880
+ if len(adain_controlnets) > 0 or len(context_adain_controlnets) > 0:
881
+ openaimodel.forward_timestep_embed = orig_forward_timestep_embed
882
+ return refcn_diffusion_model_wrapper
883
+
884
+
885
+ # dummy class just to help IDE keep track of injected variables
886
+ class RefBasicTransformerBlock(BasicTransformerBlock):
887
+ injection_holder: InjectionBasicTransformerBlockHolder = None
888
+
889
+ def _forward_inject_BasicTransformerBlock(self: RefBasicTransformerBlock, x: Tensor, context: Tensor=None, transformer_options: dict[str]={}):
890
+ extra_options = {}
891
+ block = transformer_options.get("block", None)
892
+ block_index = transformer_options.get("block_index", 0)
893
+ transformer_patches = {}
894
+ transformer_patches_replace = {}
895
+
896
+ for k in transformer_options:
897
+ if k == "patches":
898
+ transformer_patches = transformer_options[k]
899
+ elif k == "patches_replace":
900
+ transformer_patches_replace = transformer_options[k]
901
+ else:
902
+ extra_options[k] = transformer_options[k]
903
+
904
+ extra_options["n_heads"] = self.n_heads
905
+ extra_options["dim_head"] = self.d_head
906
+
907
+ if self.ff_in:
908
+ x_skip = x
909
+ x = self.ff_in(self.norm_in(x))
910
+ if self.is_res:
911
+ x += x_skip
912
+
913
+ n: Tensor = self.norm1(x)
914
+ if self.disable_self_attn:
915
+ context_attn1 = context
916
+ else:
917
+ context_attn1 = None
918
+ value_attn1 = None
919
+
920
+ # Reference CN stuff
921
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
922
+ uuids = transformer_options["uuids"]
923
+ cref_mode = transformer_options.get(CONTEXTREF_MACHINE_STATE, MachineState.OFF)
924
+ #c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
925
+ # WRITE mode may have only 1 ReferenceAdvanced for RefCN at a time, other modes will have all ReferenceAdvanced
926
+ ref_write_cns: list[ReferenceAdvanced] = transformer_options.get(REF_WRITE_ATTN_CONTROL_LIST, [])
927
+ ref_read_cns: list[ReferenceAdvanced] = transformer_options.get(REF_READ_ATTN_CONTROL_LIST, [])
928
+ ignore_contextref_read = cref_mode in [MachineState.OFF, MachineState.WRITE]
929
+ #logger.info(f"cref: {cref_cond_idx}, cmode: {cref_mode}, ignored: {ignore_contextref_read}")
930
+
931
+ cached_n = None
932
+ cref_write_cns: list[ReferenceAdvanced] = []
933
+ # check if any WRITE cns are applicable; Reference CN WRITEs immediately, ContextREF WRITEs after READ completed
934
+ # if any refs to WRITE, save n and style_fidelity
935
+ for refcn in ref_write_cns:
936
+ if refcn.ref_opts.attn_ref_weight > self.injection_holder.attn_weight:
937
+ if cached_n is None:
938
+ cached_n = n.detach().clone()
939
+ # for ContextRef, make sure relevant lists are long enough to cond_idx
940
+ # store RefCN and ContextRef stuff separately
941
+ if refcn.is_context_ref:
942
+ cref_write_cns.append(refcn)
943
+ self.injection_holder.bank_styles.init_cref_for_uuids(uuids)
944
+ else: # Reference CN WRITE
945
+ self.injection_holder.bank_styles.bank.append(cached_n)
946
+ self.injection_holder.bank_styles.style_cfgs.append(refcn.ref_opts.attn_style_fidelity)
947
+ self.injection_holder.bank_styles.cn_idx.append(refcn.order)
948
+ if len(cref_write_cns) == 0:
949
+ del cached_n
950
+
951
+ if "attn1_patch" in transformer_patches:
952
+ patch = transformer_patches["attn1_patch"]
953
+ if context_attn1 is None:
954
+ context_attn1 = n
955
+ value_attn1 = context_attn1
956
+ for p in patch:
957
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
958
+
959
+ if block is not None:
960
+ transformer_block = (block[0], block[1], block_index)
961
+ else:
962
+ transformer_block = None
963
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
964
+ block_attn1 = transformer_block
965
+ if block_attn1 not in attn1_replace_patch:
966
+ block_attn1 = block
967
+
968
+ if block_attn1 in attn1_replace_patch:
969
+ if context_attn1 is None:
970
+ context_attn1 = n
971
+ value_attn1 = n
972
+ n = self.attn1.to_q(n)
973
+ # Reference CN READ - use attn1_replace_patch appropriately
974
+ if len(ref_read_cns) > 0 and len(self.injection_holder.bank_styles.get_cn_idxs(uuids, ignore_contextref_read)) > 0:
975
+ bank_styles = self.injection_holder.bank_styles
976
+ style_fidelity = bank_styles.get_avg_style_fidelity(uuids, ignore_contextref_read)
977
+ real_bank = bank_styles.get_bank(uuids, ignore_contextref_read, cdevice=n.device).copy()
978
+ real_cn_idxs = bank_styles.get_cn_idxs(uuids, ignore_contextref_read)
979
+ cn_idx = 0
980
+ for idx, order in enumerate(real_cn_idxs):
981
+ # make sure matching ref cn is selected
982
+ for i in range(cn_idx, len(ref_read_cns)):
983
+ if ref_read_cns[i].order == order:
984
+ cn_idx = i
985
+ break
986
+ assert order == ref_read_cns[cn_idx].order
987
+ if ref_read_cns[cn_idx].any_attn_strength_to_apply():
988
+ effective_strength = ref_read_cns[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
989
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
990
+ n_uc = self.attn1.to_out(attn1_replace_patch[block_attn1](
991
+ n,
992
+ self.attn1.to_k(torch.cat([context_attn1] + real_bank, dim=1)),
993
+ self.attn1.to_v(torch.cat([value_attn1] + real_bank, dim=1)),
994
+ extra_options))
995
+ n_c = n_uc.clone()
996
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
997
+ n_c[uc_idx_mask] = self.attn1.to_out(attn1_replace_patch[block_attn1](
998
+ n[uc_idx_mask],
999
+ self.attn1.to_k(context_attn1[uc_idx_mask]),
1000
+ self.attn1.to_v(value_attn1[uc_idx_mask]),
1001
+ extra_options))
1002
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
1003
+ bank_styles.clean_ref()
1004
+ else:
1005
+ context_attn1 = self.attn1.to_k(context_attn1)
1006
+ value_attn1 = self.attn1.to_v(value_attn1)
1007
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
1008
+ n = self.attn1.to_out(n)
1009
+ else:
1010
+ # Reference CN READ - no attn1_replace_patch
1011
+ if len(ref_read_cns) > 0 and len(self.injection_holder.bank_styles.get_cn_idxs(uuids, ignore_contextref_read)) > 0:
1012
+ if context_attn1 is None:
1013
+ context_attn1 = n
1014
+ bank_styles = self.injection_holder.bank_styles
1015
+ style_fidelity = bank_styles.get_avg_style_fidelity(uuids, ignore_contextref_read)
1016
+ real_bank = bank_styles.get_bank(uuids, ignore_contextref_read, cdevice=n.device).copy()
1017
+ real_cn_idxs = bank_styles.get_cn_idxs(uuids, ignore_contextref_read)
1018
+ cn_idx = 0
1019
+ for idx, order in enumerate(real_cn_idxs):
1020
+ # make sure matching ref cn is selected
1021
+ for i in range(cn_idx, len(ref_read_cns)):
1022
+ if ref_read_cns[i].order == order:
1023
+ cn_idx = i
1024
+ break
1025
+ assert order == ref_read_cns[cn_idx].order
1026
+ if ref_read_cns[cn_idx].any_attn_strength_to_apply():
1027
+ effective_strength = ref_read_cns[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
1028
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
1029
+ n_uc: Tensor = self.attn1(
1030
+ n,
1031
+ context=torch.cat([context_attn1] + real_bank, dim=1),
1032
+ value=torch.cat([value_attn1] + real_bank, dim=1) if value_attn1 is not None else value_attn1)
1033
+ n_c = n_uc.clone()
1034
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
1035
+ n_c[uc_idx_mask] = self.attn1(
1036
+ n[uc_idx_mask],
1037
+ context=context_attn1[uc_idx_mask],
1038
+ value=value_attn1[uc_idx_mask] if value_attn1 is not None else value_attn1)
1039
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
1040
+ bank_styles.clean_ref()
1041
+ else:
1042
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
1043
+
1044
+ # ContextRef CN WRITE
1045
+ if len(cref_write_cns) > 0:
1046
+ # clear so that ContextRef CNs can properly 'replace' previous value at relevant uuids
1047
+ self.injection_holder.bank_styles.clear_cref_for_uuids(uuids)
1048
+ for refcn in cref_write_cns:
1049
+ # add a whole list to match expected type when combining
1050
+ self.injection_holder.bank_styles.set_c_bank_for_uuids(cached_n.to(comfy.model_management.unet_offload_device()), uuids)
1051
+ self.injection_holder.bank_styles.set_c_style_cfgs_for_uuids(refcn.ref_opts.attn_style_fidelity, uuids)
1052
+ self.injection_holder.bank_styles.set_c_cn_idx_for_uuids(refcn.order, uuids)
1053
+ del cached_n
1054
+
1055
+ if "attn1_output_patch" in transformer_patches:
1056
+ patch = transformer_patches["attn1_output_patch"]
1057
+ for p in patch:
1058
+ n = p(n, extra_options)
1059
+
1060
+ x += n
1061
+ if "middle_patch" in transformer_patches:
1062
+ patch = transformer_patches["middle_patch"]
1063
+ for p in patch:
1064
+ x = p(x, extra_options)
1065
+
1066
+ if self.attn2 is not None:
1067
+ n = self.norm2(x)
1068
+ if self.switch_temporal_ca_to_sa:
1069
+ context_attn2 = n
1070
+ else:
1071
+ context_attn2 = context
1072
+ value_attn2 = None
1073
+ if "attn2_patch" in transformer_patches:
1074
+ patch = transformer_patches["attn2_patch"]
1075
+ value_attn2 = context_attn2
1076
+ for p in patch:
1077
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
1078
+
1079
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
1080
+ block_attn2 = transformer_block
1081
+ if block_attn2 not in attn2_replace_patch:
1082
+ block_attn2 = block
1083
+
1084
+ if block_attn2 in attn2_replace_patch:
1085
+ if value_attn2 is None:
1086
+ value_attn2 = context_attn2
1087
+ n = self.attn2.to_q(n)
1088
+ context_attn2 = self.attn2.to_k(context_attn2)
1089
+ value_attn2 = self.attn2.to_v(value_attn2)
1090
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
1091
+ n = self.attn2.to_out(n)
1092
+ else:
1093
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
1094
+
1095
+ if "attn2_output_patch" in transformer_patches:
1096
+ patch = transformer_patches["attn2_output_patch"]
1097
+ for p in patch:
1098
+ n = p(n, extra_options)
1099
+
1100
+ x += n
1101
+ if self.is_res:
1102
+ x_skip = x
1103
+ x = self.ff(self.norm3(x))
1104
+ if self.is_res:
1105
+ x += x_skip
1106
+
1107
+ return x
1108
+
1109
+
1110
+ class RefTimestepEmbedSequential(openaimodel.TimestepEmbedSequential):
1111
+ injection_holder: InjectionTimestepEmbedSequentialHolder = None
1112
+
1113
+ def forward_timestep_embed_ref_inject_factory(orig_timestep_embed_inject_factory: Callable):
1114
+ def forward_timestep_embed_ref_inject(*args, **kwargs):
1115
+ ts: RefTimestepEmbedSequential = args[0]
1116
+ if not hasattr(ts, "injection_holder"):
1117
+ return orig_timestep_embed_inject_factory(*args, **kwargs)
1118
+ eps = 1e-6
1119
+ x: Tensor = orig_timestep_embed_inject_factory(*args, **kwargs)
1120
+ y: Tensor = None
1121
+ transformer_options: dict[str] = args[4]
1122
+ # Reference CN stuff
1123
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
1124
+ uuids = transformer_options["uuids"]
1125
+ cref_mode = transformer_options.get(CONTEXTREF_MACHINE_STATE, MachineState.OFF)
1126
+ #c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
1127
+ # WRITE mode will only have one ReferenceAdvanced, other modes will have all ReferenceAdvanced
1128
+ ref_write_cns: list[ReferenceAdvanced] = transformer_options.get(REF_WRITE_ADAIN_CONTROL_LIST, [])
1129
+ ref_read_cns: list[ReferenceAdvanced] = transformer_options.get(REF_READ_ADAIN_CONTROL_LIST, [])
1130
+ ignore_contextref_read = cref_mode in [MachineState.OFF, MachineState.WRITE]
1131
+
1132
+ cached_var = None
1133
+ cached_mean = None
1134
+ cref_write_cns: list[ReferenceAdvanced] = []
1135
+ # if any refs to WRITE, save var, mean, and style_cfg
1136
+ for refcn in ref_write_cns:
1137
+ if refcn.ref_opts.adain_ref_weight > ts.injection_holder.gn_weight:
1138
+ if cached_var is None:
1139
+ cached_var, cached_mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
1140
+ if refcn.is_context_ref:
1141
+ cref_write_cns.append(refcn)
1142
+ ts.injection_holder.bank_styles.init_cref_for_uuids(uuids)
1143
+ else:
1144
+ ts.injection_holder.bank_styles.var_bank.append(cached_var)
1145
+ ts.injection_holder.bank_styles.mean_bank.append(cached_mean)
1146
+ ts.injection_holder.bank_styles.style_cfgs.append(refcn.ref_opts.adain_style_fidelity)
1147
+ ts.injection_holder.bank_styles.cn_idx.append(refcn.order)
1148
+ if len(cref_write_cns) == 0:
1149
+ del cached_var
1150
+ del cached_mean
1151
+
1152
+ # if any refs to READ, do math with saved var, mean, and style_cfg
1153
+ if len(ref_read_cns) > 0:
1154
+ if len(ts.injection_holder.bank_styles.get_cn_idxs(uuids, ignore_contextref_read)) > 0:
1155
+ bank_styles = ts.injection_holder.bank_styles
1156
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
1157
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
1158
+ y_uc = torch.zeros_like(x)
1159
+ cn_idx = 0
1160
+ real_style_cfgs = bank_styles.get_style_cfgs(uuids, ignore_contextref_read)
1161
+ real_var_bank = bank_styles.get_var_bank(uuids, ignore_contextref_read)
1162
+ real_mean_bank = bank_styles.get_mean_bank(uuids, ignore_contextref_read)
1163
+ real_cn_idxs = bank_styles.get_cn_idxs(uuids, ignore_contextref_read)
1164
+ for idx, order in enumerate(real_cn_idxs):
1165
+ # make sure matching ref cn is selected
1166
+ for i in range(cn_idx, len(ref_read_cns)):
1167
+ if ref_read_cns[i].order == order:
1168
+ cn_idx = i
1169
+ break
1170
+ assert order == ref_read_cns[cn_idx].order
1171
+ style_fidelity = real_style_cfgs[idx]
1172
+ var_acc = real_var_bank[idx]
1173
+ mean_acc = real_mean_bank[idx]
1174
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
1175
+ sub_y_uc = (((x - mean) / std) * std_acc) + mean_acc
1176
+ if ref_read_cns[cn_idx].any_adain_strength_to_apply():
1177
+ effective_strength = ref_read_cns[cn_idx].get_effective_adain_mask_or_float(x=x)
1178
+ sub_y_uc = sub_y_uc * effective_strength + x * (1-effective_strength)
1179
+ y_uc += sub_y_uc
1180
+ # get average, if more than one
1181
+ if len(real_cn_idxs) > 1:
1182
+ y_uc /= len(real_cn_idxs)
1183
+ y_c = y_uc.clone()
1184
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
1185
+ y_c[uc_idx_mask] = x.to(y_c.dtype)[uc_idx_mask]
1186
+ y = style_fidelity * y_c + (1.0 - style_fidelity) * y_uc
1187
+ ts.injection_holder.bank_styles.clean_ref()
1188
+
1189
+ # ContextRef CN WRITE
1190
+ if len(cref_write_cns) > 0:
1191
+ # clear so that ContextRef CNs can properly 'replace' previous value at cond_idx
1192
+ ts.injection_holder.bank_styles.clear_cref_for_uuids(uuids)
1193
+ for refcn in cref_write_cns:
1194
+ # add a whole list to match expected type when combining
1195
+ ts.injection_holder.bank_styles.set_c_var_bank_for_uuids(cached_var, uuids)
1196
+ ts.injection_holder.bank_styles.set_c_mean_bank_for_uuids(cached_mean, uuids)
1197
+ ts.injection_holder.bank_styles.set_c_style_cfgs_for_uuids(refcn.ref_opts.adain_style_fidelity, uuids)
1198
+ ts.injection_holder.bank_styles.set_c_cn_idx_for_uuids(refcn.order, uuids)
1199
+ del cached_var
1200
+ del cached_mean
1201
+
1202
+ if y is None:
1203
+ y = x
1204
+ return y.to(x.dtype)
1205
+
1206
+ return forward_timestep_embed_ref_inject
ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 numpy as np
7
+ import torch
8
+ from torch import Tensor
9
+
10
+ from comfy.ldm.modules.diffusionmodules.util import (
11
+ zero_module,
12
+ timestep_embedding,
13
+ )
14
+
15
+ from comfy.cldm.cldm import ControlNet as ControlNetCLDM
16
+ from comfy.ldm.modules.diffusionmodules.openaimodel import TimestepEmbedSequential
17
+ from comfy.model_patcher import ModelPatcher
18
+ from comfy.patcher_extension import PatcherInjection
19
+
20
+ from .dinklink import (InterfaceAnimateDiffInfo, InterfaceAnimateDiffModel,
21
+ get_CreateMotionModelPatcher, get_AnimateDiffModel, get_AnimateDiffInfo)
22
+ from .logger import logger
23
+ from .utils import (BIGMAX, AbstractPreprocWrapper, disable_weight_init_clean_groupnorm, WrapperConsts)
24
+
25
+
26
+ class SparseMotionModelPatcher(ModelPatcher):
27
+ '''Class only used for IDE type hints.'''
28
+ def __init__(self, *args, **kwargs):
29
+ self.model = InterfaceAnimateDiffModel
30
+
31
+
32
+ class SparseConst:
33
+ HINT_MULT = "sparse_hint_mult"
34
+ NONHINT_MULT = "sparse_nonhint_mult"
35
+ MASK_MULT = "sparse_mask_mult"
36
+
37
+
38
+ class SparseControlNet(ControlNetCLDM):
39
+ def __init__(self, *args,**kwargs):
40
+ super().__init__(*args, **kwargs)
41
+ hint_channels = kwargs.get("hint_channels")
42
+ operations: disable_weight_init_clean_groupnorm = kwargs.get("operations", disable_weight_init_clean_groupnorm)
43
+ device = kwargs.get("device", None)
44
+ self.use_simplified_conditioning_embedding = kwargs.get("use_simplified_conditioning_embedding", False)
45
+ if self.use_simplified_conditioning_embedding:
46
+ self.input_hint_block = TimestepEmbedSequential(
47
+ zero_module(operations.conv_nd(self.dims, hint_channels, self.model_channels, 3, padding=1, dtype=self.dtype, device=device)),
48
+ )
49
+
50
+ def forward(self, x: Tensor, hint: Tensor, timesteps, context, y=None, **kwargs):
51
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
52
+ emb = self.time_embed(t_emb)
53
+
54
+ # SparseCtrl sets noisy input to zeros
55
+ x = torch.zeros_like(x)
56
+ guided_hint = self.input_hint_block(hint, emb, context)
57
+
58
+ out_output = []
59
+ out_middle = []
60
+
61
+ hs = []
62
+ if self.num_classes is not None:
63
+ assert y.shape[0] == x.shape[0]
64
+ emb = emb + self.label_emb(y)
65
+
66
+ h = x
67
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
68
+ if guided_hint is not None:
69
+ h = module(h, emb, context)
70
+ h += guided_hint
71
+ guided_hint = None
72
+ else:
73
+ h = module(h, emb, context)
74
+ out_output.append(zero_conv(h, emb, context))
75
+
76
+ h = self.middle_block(h, emb, context)
77
+ out_middle.append(self.middle_block_out(h, emb, context))
78
+
79
+ return {"middle": out_middle, "output": out_output}
80
+
81
+
82
+ def load_sparsectrl_motionmodel(ckpt_path: str, motion_data: dict[str, Tensor], ops=None) -> InterfaceAnimateDiffModel:
83
+ mm_info: InterfaceAnimateDiffInfo = get_AnimateDiffInfo()("SD1.5", "AnimateDiff", "v3", ckpt_path)
84
+ init_kwargs = {
85
+ "ops": ops,
86
+ "get_unet_func": _get_unet_func,
87
+ }
88
+ motion_model: InterfaceAnimateDiffModel = get_AnimateDiffModel()(mm_state_dict=motion_data, mm_info=mm_info, init_kwargs=init_kwargs)
89
+ missing, unexpected = motion_model.load_state_dict(motion_data)
90
+ if len(missing) > 0 or len(unexpected) > 0:
91
+ logger.info(f"SparseCtrl MotionModel: {missing}, {unexpected}")
92
+ return motion_model
93
+
94
+
95
+ def create_sparse_modelpatcher(model, motion_model, load_device, offload_device):
96
+ patcher = ModelPatcher(model, load_device=load_device, offload_device=offload_device)
97
+ if motion_model is not None:
98
+ _motionpatcher = _create_sparse_motionmodelpatcher(motion_model, load_device, offload_device)
99
+ patcher.set_additional_models(WrapperConsts.ACN, [_motionpatcher])
100
+ patcher.set_injections(WrapperConsts.ACN,
101
+ [PatcherInjection(inject=_inject_motion_models, eject=_eject_motion_models)])
102
+ return patcher
103
+
104
+ def _create_sparse_motionmodelpatcher(motion_model, load_device, offload_device) -> SparseMotionModelPatcher:
105
+ return get_CreateMotionModelPatcher()(motion_model, load_device, offload_device)
106
+
107
+
108
+ def _inject_motion_models(patcher: ModelPatcher):
109
+ motion_models: list[SparseMotionModelPatcher] = patcher.get_additional_models_with_key(WrapperConsts.ACN)
110
+ for mm in motion_models:
111
+ mm.model.inject(patcher)
112
+
113
+ def _eject_motion_models(patcher: ModelPatcher):
114
+ motion_models: list[SparseMotionModelPatcher] = patcher.get_additional_models_with_key(WrapperConsts.ACN)
115
+ for mm in motion_models:
116
+ mm.model.eject(patcher)
117
+
118
+ def _get_unet_func(wrapper, model: ModelPatcher):
119
+ return model.model
120
+
121
+
122
+ class PreprocSparseRGBWrapper(AbstractPreprocWrapper):
123
+ 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."
124
+ def __init__(self, condhint: Tensor):
125
+ super().__init__(condhint)
126
+
127
+
128
+ class SparseContextAware:
129
+ NEAREST_HINT = "nearest_hint"
130
+ OFF = "off"
131
+
132
+ LIST = [NEAREST_HINT, OFF]
133
+
134
+
135
+ class SparseSettings:
136
+ def __init__(self, sparse_method: 'SparseMethod', use_motion: bool=True, motion_strength=1.0, motion_scale=1.0, merged=False,
137
+ sparse_mask_mult=1.0, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, context_aware=SparseContextAware.NEAREST_HINT):
138
+ # account for Steerable-Motion workflow incompatibility;
139
+ # doing this to for my own peace of mind (not an issue with my code)
140
+ if type(sparse_method) == str:
141
+ 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.")
142
+ sparse_method = SparseIndexMethod(get_idx_list_from_str(sparse_method))
143
+ self.sparse_method = sparse_method
144
+ self.use_motion = use_motion
145
+ self.motion_strength = motion_strength
146
+ self.motion_scale = motion_scale
147
+ self.merged = merged
148
+ self.sparse_mask_mult = float(sparse_mask_mult)
149
+ self.sparse_hint_mult = float(sparse_hint_mult)
150
+ self.sparse_nonhint_mult = float(sparse_nonhint_mult)
151
+ self.context_aware = context_aware
152
+
153
+ def is_context_aware(self):
154
+ return self.context_aware != SparseContextAware.OFF
155
+
156
+ @classmethod
157
+ def default(cls):
158
+ return SparseSettings(sparse_method=SparseSpreadMethod(), use_motion=True)
159
+
160
+
161
+ class SparseMethod(ABC):
162
+ SPREAD = "spread"
163
+ INDEX = "index"
164
+ def __init__(self, method: str):
165
+ self.method = method
166
+
167
+ @abstractmethod
168
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
169
+ pass
170
+
171
+ def get_indexes(self, hint_length: int, full_length: int, sub_idxs: list[int]=None) -> tuple[list[int], list[int]]:
172
+ returned_idxs = self._get_indexes(hint_length, full_length)
173
+ if sub_idxs is None:
174
+ return returned_idxs, None
175
+ # need to map full indexes to condhint indexes
176
+ index_mapping = {}
177
+ for i, value in enumerate(returned_idxs):
178
+ index_mapping[value] = i
179
+ def get_mapped_idxs(idxs: list[int]):
180
+ return [index_mapping[idx] for idx in idxs]
181
+ # check if returned_idxs fit within subidxs
182
+ fitting_idxs = []
183
+ for sub_idx in sub_idxs:
184
+ if sub_idx in returned_idxs:
185
+ fitting_idxs.append(sub_idx)
186
+ # if have any fitting_idxs, deal with it
187
+ if len(fitting_idxs) > 0:
188
+ return fitting_idxs, get_mapped_idxs(fitting_idxs)
189
+
190
+ # since no returned_idxs fit in sub_idxs, need to get the next-closest hint images based on strategy
191
+ def get_closest_idx(target_idx: int, idxs: list[int]):
192
+ min_idx = -1
193
+ min_dist = BIGMAX
194
+ for idx in idxs:
195
+ new_dist = abs(idx-target_idx)
196
+ if new_dist < min_dist:
197
+ min_idx = idx
198
+ min_dist = new_dist
199
+ if min_dist == 1:
200
+ return min_idx, min_dist
201
+ return min_idx, min_dist
202
+ start_closest_idx, start_dist = get_closest_idx(sub_idxs[0], returned_idxs)
203
+ end_closest_idx, end_dist = get_closest_idx(sub_idxs[-1], returned_idxs)
204
+ # if only one cond hint exists, do special behavior
205
+ if hint_length == 1:
206
+ # if same distance from start and end,
207
+ if start_dist == end_dist:
208
+ # find center index of sub_idxs
209
+ center_idx = sub_idxs[np.linspace(0, len(sub_idxs)-1, 3, endpoint=True, dtype=int)[1]]
210
+ return [center_idx], get_mapped_idxs([start_closest_idx])
211
+ # otherwise, return closest
212
+ if start_dist < end_dist:
213
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
214
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
215
+ # otherwise, select up to two closest images, or just 1, whichever one applies best
216
+ # if same distance from start and end, return two images to use
217
+ if start_dist == end_dist:
218
+ return [sub_idxs[0], sub_idxs[-1]], get_mapped_idxs([start_closest_idx, end_closest_idx])
219
+ # else, use just one
220
+ if start_dist < end_dist:
221
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
222
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
223
+
224
+
225
+ class SparseSpreadMethod(SparseMethod):
226
+ UNIFORM = "uniform"
227
+ STARTING = "starting"
228
+ ENDING = "ending"
229
+ CENTER = "center"
230
+
231
+ LIST = [UNIFORM, STARTING, ENDING, CENTER]
232
+
233
+ def __init__(self, spread=UNIFORM):
234
+ super().__init__(self.SPREAD)
235
+ self.spread = spread
236
+
237
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
238
+ # if hint_length >= full_length, limit hints to full_length
239
+ if hint_length >= full_length:
240
+ return list(range(full_length))
241
+ # handle special case of 1 hint image
242
+ if hint_length == 1:
243
+ if self.spread in [self.UNIFORM, self.STARTING]:
244
+ return [0]
245
+ elif self.spread == self.ENDING:
246
+ return [full_length-1]
247
+ elif self.spread == self.CENTER:
248
+ # return second (of three) values as the center
249
+ return [np.linspace(0, full_length-1, 3, endpoint=True, dtype=int)[1]]
250
+ else:
251
+ raise ValueError(f"Unrecognized spread: {self.spread}")
252
+ # otherwise, handle other cases
253
+ if self.spread == self.UNIFORM:
254
+ return list(np.linspace(0, full_length-1, hint_length, endpoint=True, dtype=int))
255
+ elif self.spread == self.STARTING:
256
+ # make split 1 larger, remove last element
257
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
258
+ elif self.spread == self.ENDING:
259
+ # make split 1 larger, remove first element
260
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[1:]
261
+ elif self.spread == self.CENTER:
262
+ # if hint length is not 3 greater than full length, do STARTING behavior
263
+ if full_length-hint_length < 3:
264
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
265
+ # otherwise, get linspace of 2 greater than needed, then cut off first and last
266
+ return list(np.linspace(0, full_length-1, hint_length+2, endpoint=True, dtype=int))[1:-1]
267
+ return ValueError(f"Unrecognized spread: {self.spread}")
268
+
269
+
270
+ class SparseIndexMethod(SparseMethod):
271
+ def __init__(self, idxs: list[int]):
272
+ super().__init__(self.INDEX)
273
+ self.idxs = idxs
274
+
275
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
276
+ orig_hint_length = hint_length
277
+ if hint_length > full_length:
278
+ hint_length = full_length
279
+ # if idxs is less than hint_length, throw error
280
+ if len(self.idxs) < hint_length:
281
+ err_msg = f"There are not enough indexes ({len(self.idxs)}) provided to fit the usable {hint_length} input images."
282
+ if orig_hint_length != hint_length:
283
+ err_msg = f"{err_msg} (original input images: {orig_hint_length})"
284
+ raise ValueError(err_msg)
285
+ # cap idxs to hint_length
286
+ idxs = self.idxs[:hint_length]
287
+ new_idxs = []
288
+ real_idxs = set()
289
+ for idx in idxs:
290
+ if idx < 0:
291
+ real_idx = full_length+idx
292
+ if real_idx in real_idxs:
293
+ raise ValueError(f"Index '{idx}' maps to '{real_idx}' and is duplicate - indexes in Sparse Index Method must be unique.")
294
+ else:
295
+ real_idx = idx
296
+ if real_idx in real_idxs:
297
+ raise ValueError(f"Index '{idx}' is duplicate (or a negative index is equivalent) - indexes in Sparse Index Method must be unique.")
298
+ real_idxs.add(real_idx)
299
+ new_idxs.append(real_idx)
300
+ return new_idxs
301
+
302
+
303
+ def get_idx_list_from_str(indexes: str) -> list[int]:
304
+ idxs = []
305
+ unique_idxs = set()
306
+ # get indeces from string
307
+ str_idxs = [x.strip() for x in indexes.strip().split(",")]
308
+ for str_idx in str_idxs:
309
+ try:
310
+ idx = int(str_idx)
311
+ if idx in unique_idxs:
312
+ raise ValueError(f"'{idx}' is duplicated; indexes must be unique.")
313
+ idxs.append(idx)
314
+ unique_idxs.add(idx)
315
+ except ValueError:
316
+ raise ValueError(f"'{str_idx}' is not a valid integer index.")
317
+ if len(idxs) == 0:
318
+ raise ValueError(f"No indexes were listed in Sparse Index Method.")
319
+ return idxs
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-Advanced-ControlNet/adv_control/dinklink.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ####################################################################################################
2
+ # DinkLink is my method of sharing classes/functions between my nodes.
3
+ #
4
+ # My DinkLink-compatible nodes will inject comfy.hooks with a __DINKLINK attr
5
+ # that stores a dictionary, where any of my node packs can store their stuff.
6
+ #
7
+ # It is not intended to be accessed by node packs that I don't develop, so things may change
8
+ # at any time.
9
+ #
10
+ # DinkLink also serves as a proof-of-concept for a future ComfyUI implementation of
11
+ # purposely exposing node pack classes/functions with other node packs.
12
+ ####################################################################################################
13
+ from __future__ import annotations
14
+ from typing import Union
15
+ from torch import Tensor, nn
16
+
17
+ from comfy.model_patcher import ModelPatcher
18
+ import comfy.hooks
19
+
20
+ DINKLINK = "__DINKLINK"
21
+
22
+
23
+ def init_dinklink():
24
+ create_dinklink()
25
+ prepare_dinklink()
26
+
27
+ def create_dinklink():
28
+ if not hasattr(comfy.hooks, DINKLINK):
29
+ setattr(comfy.hooks, DINKLINK, {})
30
+
31
+ def get_dinklink() -> dict[str, dict[str]]:
32
+ create_dinklink()
33
+ return getattr(comfy.hooks, DINKLINK)
34
+
35
+
36
+ class DinkLinkConst:
37
+ VERSION = "version"
38
+ # ADE
39
+ ADE = "ADE"
40
+ ADE_ANIMATEDIFFMODEL = "AnimateDiffModel"
41
+ ADE_ANIMATEDIFFINFO = "AnimateDiffInfo"
42
+ ADE_CREATE_MOTIONMODELPATCHER = "create_MotionModelPatcher"
43
+
44
+ def prepare_dinklink():
45
+ pass
46
+
47
+
48
+ class InterfaceAnimateDiffInfo:
49
+ '''Class only used for IDE type hints; interface of ADE's AnimateDiffInfo'''
50
+ def __init__(self, sd_type: str, mm_format: str, mm_version: str, mm_name: str):
51
+ self.sd_type = sd_type
52
+ self.mm_format = mm_format
53
+ self.mm_version = mm_version
54
+ self.mm_name = mm_name
55
+
56
+
57
+ class InterfaceAnimateDiffModel(nn.Module):
58
+ '''Class only used for IDE type hints; interface of ADE's AnimateDiffModel'''
59
+ def __init__(self, mm_state_dict: dict[str, Tensor], mm_info: InterfaceAnimateDiffInfo, init_kwargs: dict[str]={}):
60
+ pass
61
+
62
+ def set_video_length(self, video_length: int, full_length: int) -> None:
63
+ raise NotImplemented()
64
+
65
+ def set_scale(self, scale: Union[float, Tensor, None], per_block_list: Union[list, None]=None) -> None:
66
+ raise NotImplemented()
67
+
68
+ def set_effect(self, multival: Union[float, Tensor, None], per_block_list: Union[list, None]=None) -> None:
69
+ raise NotImplemented()
70
+
71
+ def cleanup(self):
72
+ raise NotImplemented()
73
+
74
+ def inject(self, model: ModelPatcher):
75
+ pass
76
+
77
+ def eject(self, model: ModelPatcher):
78
+ pass
79
+
80
+
81
+ def get_CreateMotionModelPatcher(throw_exception=True):
82
+ d = get_dinklink()
83
+ try:
84
+ link_ade = d[DinkLinkConst.ADE]
85
+ return link_ade[DinkLinkConst.ADE_CREATE_MOTIONMODELPATCHER]
86
+ except KeyError:
87
+ if throw_exception:
88
+ raise Exception("Could not get create_MotionModelPatcher function. AnimateDiff-Evolved nodes need to be installed to use SparseCtrl; " + \
89
+ "they are either not installed or are of an insufficient version.")
90
+ return None
91
+
92
+ def get_AnimateDiffModel(throw_exception=True):
93
+ d = get_dinklink()
94
+ try:
95
+ link_ade = d[DinkLinkConst.ADE]
96
+ return link_ade[DinkLinkConst.ADE_ANIMATEDIFFMODEL]
97
+ except KeyError:
98
+ if throw_exception:
99
+ raise Exception("Could not get AnimateDiffModel class. AnimateDiff-Evolved nodes need to be installed to use SparseCtrl; " + \
100
+ "they are either not installed or are of an insufficient version.")
101
+ return None
102
+
103
+ def get_AnimateDiffInfo(throw_exception=True) -> InterfaceAnimateDiffInfo:
104
+ d = get_dinklink()
105
+ try:
106
+ link_ade = d[DinkLinkConst.ADE]
107
+ return link_ade[DinkLinkConst.ADE_ANIMATEDIFFINFO]
108
+ except KeyError:
109
+ if throw_exception:
110
+ raise Exception("Could not get AnimateDiffInfo class - AnimateDiff-Evolved nodes need to be installed to use SparseCtrl; " + \
111
+ "they are either not installed or are of an insufficient version.")
112
+ return None
ComfyUI-Advanced-ControlNet/adv_control/documentation.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .logger import logger
2
+
3
+ def image(src):
4
+ return f'<img src={src} style="width: 0px; min-width: 100%">'
5
+ def video(src):
6
+ return f'<video src={src} autoplay muted loop controls controlslist="nodownload noremoteplayback noplaybackrate" style="width: 0px; min-width: 100%" class="VHS_loopedvideo">'
7
+ def short_desc(desc):
8
+ return f'<div id=VHS_shortdesc style="font-size: .8em">{desc}</div>'
9
+
10
+ descriptions = {
11
+ }
12
+
13
+ sizes = ['1.4','1.2','1']
14
+ def as_html(entry, depth=0):
15
+ if isinstance(entry, dict):
16
+ size = 0.8 if depth < 2 else 1
17
+ html = ''
18
+ for k in entry:
19
+ if k == "collapsed":
20
+ continue
21
+ collapse_single = k.endswith("_collapsed")
22
+ if collapse_single:
23
+ name = k[:-len("_collapsed")]
24
+ else:
25
+ name = k
26
+ collapse_flag = ' VHS_precollapse' if entry.get("collapsed", False) or collapse_single else ''
27
+ html += f'<div vhs_title=\"{name}\" style=\"display: flex; font-size: {size}em\" class=\"VHS_collapse{collapse_flag}\"><div style=\"color: #AAA; height: 1.5em;\">[<span style=\"font-family: monospace\">-</span>]</div><div style=\"width: 100%\">{name}: {as_html(entry[k], depth=depth+1)}</div></div>'
28
+ return html
29
+ if isinstance(entry, list):
30
+ html = ''
31
+ for i in entry:
32
+ html += f'<div>{as_html(i, depth=depth)}</div>'
33
+ return html
34
+ return str(entry)
35
+
36
+ def format_descriptions(nodes):
37
+ for k in descriptions:
38
+ if k.endswith("_collapsed"):
39
+ k = k[:-len("_collapsed")]
40
+ nodes[k].DESCRIPTION = as_html(descriptions[k])
41
+ # undocumented_nodes = []
42
+ # for k in nodes:
43
+ # if not hasattr(nodes[k], "DESCRIPTION"):
44
+ # undocumented_nodes.append(k)
45
+ # if len(undocumented_nodes) > 0:
46
+ # logger.info(f"Undocumented nodes: {undocumented_nodes}")
47
+
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-Advanced-ControlNet/adv_control/nodes.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import comfy.sample
2
+
3
+ from .nodes_main import (ControlNetLoaderAdvanced, DiffControlNetLoaderAdvanced,
4
+ AdvancedControlNetApply, AdvancedControlNetApplySingle)
5
+ from .nodes_weight import (DefaultWeights, ScaledSoftMaskedUniversalWeights, ScaledSoftUniversalWeights,
6
+ SoftControlNetWeightsSD15, CustomControlNetWeightsSD15, CustomControlNetWeightsFlux,
7
+ SoftT2IAdapterWeights, CustomT2IAdapterWeights, ExtrasMiddleMultNode)
8
+ from .nodes_keyframes import (LatentKeyframeGroupNode, LatentKeyframeInterpolationNode, LatentKeyframeBatchedGroupNode, LatentKeyframeNode,
9
+ TimestepKeyframeNode, TimestepKeyframeInterpolationNode, TimestepKeyframeFromStrengthListNode)
10
+ from .nodes_sparsectrl import SparseCtrlMergedLoaderAdvanced, SparseCtrlLoaderAdvanced, SparseIndexMethodNode, SparseSpreadMethodNode, RgbSparseCtrlPreprocessor, SparseWeightExtras
11
+ from .nodes_reference import ReferenceControlNetNode, ReferenceControlFinetune, ReferencePreprocessorNode
12
+ from .nodes_plusplus import PlusPlusLoaderAdvanced, PlusPlusLoaderSingle, PlusPlusInputNode
13
+ from .nodes_ctrlora import CtrLoRALoader
14
+ from .nodes_loosecontrol import ControlNetLoaderWithLoraAdvanced
15
+ from .nodes_deprecated import (LoadImagesFromDirectory, ScaledSoftUniversalWeightsDeprecated,
16
+ SoftControlNetWeightsDeprecated, CustomControlNetWeightsDeprecated,
17
+ SoftT2IAdapterWeightsDeprecated, CustomT2IAdapterWeightsDeprecated,
18
+ AdvancedControlNetApplyDEPR, AdvancedControlNetApplySingleDEPR,
19
+ ControlNetLoaderAdvancedDEPR, DiffControlNetLoaderAdvancedDEPR)
20
+ from .logger import logger
21
+
22
+
23
+ # NODE MAPPING
24
+ NODE_CLASS_MAPPINGS = {
25
+ # Keyframes
26
+ "TimestepKeyframe": TimestepKeyframeNode,
27
+ "ACN_TimestepKeyframeInterpolation": TimestepKeyframeInterpolationNode,
28
+ "ACN_TimestepKeyframeFromStrengthList": TimestepKeyframeFromStrengthListNode,
29
+ "LatentKeyframe": LatentKeyframeNode,
30
+ "LatentKeyframeTiming": LatentKeyframeInterpolationNode,
31
+ "LatentKeyframeBatchedGroup": LatentKeyframeBatchedGroupNode,
32
+ "LatentKeyframeGroup": LatentKeyframeGroupNode,
33
+ # Conditioning
34
+ "ACN_AdvancedControlNetApply_v2": AdvancedControlNetApply,
35
+ "ACN_AdvancedControlNetApplySingle_v2": AdvancedControlNetApplySingle,
36
+ # Loaders
37
+ "ACN_ControlNetLoaderAdvanced": ControlNetLoaderAdvanced,
38
+ "ACN_DiffControlNetLoaderAdvanced": DiffControlNetLoaderAdvanced,
39
+ # Weights
40
+ "ACN_ScaledSoftControlNetWeights": ScaledSoftUniversalWeights,
41
+ "ScaledSoftMaskedUniversalWeights": ScaledSoftMaskedUniversalWeights,
42
+ "ACN_SoftControlNetWeightsSD15": SoftControlNetWeightsSD15,
43
+ "ACN_CustomControlNetWeightsSD15": CustomControlNetWeightsSD15,
44
+ "ACN_CustomControlNetWeightsFlux": CustomControlNetWeightsFlux,
45
+ "ACN_SoftT2IAdapterWeights": SoftT2IAdapterWeights,
46
+ "ACN_CustomT2IAdapterWeights": CustomT2IAdapterWeights,
47
+ "ACN_DefaultUniversalWeights": DefaultWeights,
48
+ "ACN_ExtrasMiddleMult": ExtrasMiddleMultNode,
49
+ # SparseCtrl
50
+ "ACN_SparseCtrlRGBPreprocessor": RgbSparseCtrlPreprocessor,
51
+ "ACN_SparseCtrlLoaderAdvanced": SparseCtrlLoaderAdvanced,
52
+ "ACN_SparseCtrlMergedLoaderAdvanced": SparseCtrlMergedLoaderAdvanced,
53
+ "ACN_SparseCtrlIndexMethodNode": SparseIndexMethodNode,
54
+ "ACN_SparseCtrlSpreadMethodNode": SparseSpreadMethodNode,
55
+ "ACN_SparseCtrlWeightExtras": SparseWeightExtras,
56
+ # ControlNet++
57
+ "ACN_ControlNet++LoaderSingle": PlusPlusLoaderSingle,
58
+ "ACN_ControlNet++LoaderAdvanced": PlusPlusLoaderAdvanced,
59
+ "ACN_ControlNet++InputNode": PlusPlusInputNode,
60
+ # CtrLoRA
61
+ "ACN_CtrLoRALoader": CtrLoRALoader,
62
+ # Reference
63
+ "ACN_ReferencePreprocessor": ReferencePreprocessorNode,
64
+ "ACN_ReferenceControlNet": ReferenceControlNetNode,
65
+ "ACN_ReferenceControlNetFinetune": ReferenceControlFinetune,
66
+ # LOOSEControl
67
+ #"ACN_ControlNetLoaderWithLoraAdvanced": ControlNetLoaderWithLoraAdvanced,
68
+ # Deprecated
69
+ "LoadImagesFromDirectory": LoadImagesFromDirectory,
70
+ "ScaledSoftControlNetWeights": ScaledSoftUniversalWeightsDeprecated,
71
+ "SoftControlNetWeights": SoftControlNetWeightsDeprecated,
72
+ "CustomControlNetWeights": CustomControlNetWeightsDeprecated,
73
+ "SoftT2IAdapterWeights": SoftT2IAdapterWeightsDeprecated,
74
+ "CustomT2IAdapterWeights": CustomT2IAdapterWeightsDeprecated,
75
+ "ACN_AdvancedControlNetApply": AdvancedControlNetApplyDEPR,
76
+ "ACN_AdvancedControlNetApplySingle": AdvancedControlNetApplySingleDEPR,
77
+ "ControlNetLoaderAdvanced": ControlNetLoaderAdvancedDEPR,
78
+ "DiffControlNetLoaderAdvanced": DiffControlNetLoaderAdvancedDEPR,
79
+ }
80
+
81
+ NODE_DISPLAY_NAME_MAPPINGS = {
82
+ # Keyframes
83
+ "TimestepKeyframe": "Timestep Keyframe 🛂🅐🅒🅝",
84
+ "ACN_TimestepKeyframeInterpolation": "Timestep Keyframe Interp. 🛂🅐🅒🅝",
85
+ "ACN_TimestepKeyframeFromStrengthList": "Timestep Keyframe From List 🛂🅐🅒🅝",
86
+ "LatentKeyframe": "Latent Keyframe 🛂🅐🅒🅝",
87
+ "LatentKeyframeTiming": "Latent Keyframe Interp. 🛂🅐🅒🅝",
88
+ "LatentKeyframeBatchedGroup": "Latent Keyframe From List 🛂🅐🅒🅝",
89
+ "LatentKeyframeGroup": "Latent Keyframe Group 🛂🅐🅒🅝",
90
+ # Conditioning
91
+ "ACN_AdvancedControlNetApply_v2": "Apply Advanced ControlNet 🛂🅐🅒🅝",
92
+ "ACN_AdvancedControlNetApplySingle_v2": "Apply Advanced ControlNet(1) 🛂🅐🅒🅝",
93
+ # Loaders
94
+ "ACN_ControlNetLoaderAdvanced": "Load Advanced ControlNet Model 🛂🅐🅒🅝",
95
+ "ACN_DiffControlNetLoaderAdvanced": "Load Advanced ControlNet Model (diff) 🛂🅐🅒🅝",
96
+ # Weights
97
+ "ACN_ScaledSoftControlNetWeights": "Scaled Soft Weights 🛂🅐🅒🅝",
98
+ "ScaledSoftMaskedUniversalWeights": "Scaled Soft Masked Weights 🛂🅐🅒🅝",
99
+ "ACN_SoftControlNetWeightsSD15": "ControlNet Soft Weights [SD1.5] 🛂🅐🅒🅝",
100
+ "ACN_CustomControlNetWeightsSD15": "ControlNet Custom Weights [SD1.5] 🛂🅐🅒🅝",
101
+ "ACN_CustomControlNetWeightsFlux": "ControlNet Custom Weights [Flux] 🛂🅐🅒🅝",
102
+ "ACN_SoftT2IAdapterWeights": "T2IAdapter Soft Weights 🛂🅐🅒🅝",
103
+ "ACN_CustomT2IAdapterWeights": "T2IAdapter Custom Weights 🛂🅐🅒🅝",
104
+ "ACN_DefaultUniversalWeights": "Default Weights 🛂🅐🅒🅝",
105
+ "ACN_ExtrasMiddleMult": "Middle Weight Extras 🛂🅐🅒🅝",
106
+ # SparseCtrl
107
+ "ACN_SparseCtrlRGBPreprocessor": "RGB SparseCtrl 🛂🅐🅒🅝",
108
+ "ACN_SparseCtrlLoaderAdvanced": "Load SparseCtrl Model 🛂🅐🅒🅝",
109
+ "ACN_SparseCtrlMergedLoaderAdvanced": "🧪Load Merged SparseCtrl Model 🛂🅐🅒🅝",
110
+ "ACN_SparseCtrlIndexMethodNode": "SparseCtrl Index Method 🛂🅐🅒🅝",
111
+ "ACN_SparseCtrlSpreadMethodNode": "SparseCtrl Spread Method 🛂🅐🅒🅝",
112
+ "ACN_SparseCtrlWeightExtras": "SparseCtrl Weight Extras 🛂🅐🅒🅝",
113
+ # ControlNet++
114
+ "ACN_ControlNet++LoaderSingle": "Load ControlNet++ Model (Single) 🛂🅐🅒🅝",
115
+ "ACN_ControlNet++LoaderAdvanced": "Load ControlNet++ Model (Multi) 🛂🅐🅒🅝",
116
+ "ACN_ControlNet++InputNode": "ControlNet++ Input 🛂🅐🅒🅝",
117
+ # CtrLoRA
118
+ "ACN_CtrLoRALoader": "Load CtrLoRA Model 🛂🅐🅒🅝",
119
+ # Reference
120
+ "ACN_ReferencePreprocessor": "Reference Preproccessor 🛂🅐🅒🅝",
121
+ "ACN_ReferenceControlNet": "Reference ControlNet 🛂🅐🅒🅝",
122
+ "ACN_ReferenceControlNetFinetune": "Reference ControlNet (Finetune) 🛂🅐🅒🅝",
123
+ # LOOSEControl
124
+ #"ACN_ControlNetLoaderWithLoraAdvanced": "Load Adv. ControlNet Model w/ LoRA 🛂🅐🅒🅝",
125
+ # Deprecated
126
+ "LoadImagesFromDirectory": "🚫Load Images [DEPRECATED] 🛂🅐🅒🅝",
127
+ "ScaledSoftControlNetWeights": "Scaled Soft Weights 🛂🅐🅒🅝",
128
+ "SoftControlNetWeights": "ControlNet Soft Weights 🛂🅐🅒🅝",
129
+ "CustomControlNetWeights": "ControlNet Custom Weights 🛂🅐🅒🅝",
130
+ "SoftT2IAdapterWeights": "T2IAdapter Soft Weights 🛂🅐🅒🅝",
131
+ "CustomT2IAdapterWeights": "T2IAdapter Custom Weights 🛂🅐🅒🅝",
132
+ "ACN_AdvancedControlNetApply": "Apply Advanced ControlNet 🛂🅐🅒🅝",
133
+ "ACN_AdvancedControlNetApplySingle": "Apply Advanced ControlNet(1) 🛂🅐🅒🅝",
134
+ "ControlNetLoaderAdvanced": "Load Advanced ControlNet Model 🛂🅐🅒🅝",
135
+ "DiffControlNetLoaderAdvanced": "Load Advanced ControlNet Model (diff) 🛂🅐🅒🅝",
136
+ }
ComfyUI-Advanced-ControlNet/adv_control/nodes_ctrlora.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import folder_paths
2
+
3
+ from .control_ctrlora import load_ctrlora
4
+
5
+
6
+ class CtrLoRALoader:
7
+ @classmethod
8
+ def INPUT_TYPES(s):
9
+ return {
10
+ "required": {
11
+ "base": (folder_paths.get_filename_list("controlnet"), ),
12
+ "lora": (folder_paths.get_filename_list("controlnet"), ),
13
+ }
14
+ }
15
+
16
+ RETURN_TYPES = ("CONTROL_NET",)
17
+ FUNCTION = "load_controlnet_plusplus"
18
+
19
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/CtrLoRA"
20
+
21
+ def load_controlnet_plusplus(self, base: str, lora: str):
22
+ base_path = folder_paths.get_full_path("controlnet", base)
23
+ lora_path = folder_paths.get_full_path("controlnet", lora)
24
+ controlnet = load_ctrlora(base_path, lora_path)
25
+ return (controlnet,)
ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import folder_paths
5
+
6
+ import numpy as np
7
+ from PIL import Image, ImageOps
8
+ from .control import load_controlnet, is_advanced_controlnet
9
+ from .nodes_main import AdvancedControlNetApply
10
+ from .utils import BIGMAX, ControlWeights, TimestepKeyframeGroup, TimestepKeyframe, get_properly_arranged_t2i_weights
11
+ from .logger import logger
12
+
13
+
14
+ class LoadImagesFromDirectory:
15
+ @classmethod
16
+ def INPUT_TYPES(s):
17
+ return {
18
+ "required": {
19
+ "directory": ("STRING", {"default": ""}),
20
+ },
21
+ "optional": {
22
+ "image_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
23
+ "start_index": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
24
+ }
25
+ }
26
+
27
+ RETURN_TYPES = ("IMAGE", "MASK", "INT")
28
+ FUNCTION = "load_images"
29
+
30
+ CATEGORY = ""
31
+
32
+ def load_images(self, directory: str, image_load_cap: int = 0, start_index: int = 0):
33
+ if not os.path.isdir(directory):
34
+ raise FileNotFoundError(f"Directory '{directory} cannot be found.'")
35
+ dir_files = os.listdir(directory)
36
+ if len(dir_files) == 0:
37
+ raise FileNotFoundError(f"No files in directory '{directory}'.")
38
+
39
+ dir_files = sorted(dir_files)
40
+ dir_files = [os.path.join(directory, x) for x in dir_files]
41
+ # start at start_index
42
+ dir_files = dir_files[start_index:]
43
+
44
+ images = []
45
+ masks = []
46
+
47
+ limit_images = False
48
+ if image_load_cap > 0:
49
+ limit_images = True
50
+ image_count = 0
51
+
52
+ for image_path in dir_files:
53
+ if os.path.isdir(image_path):
54
+ continue
55
+ if limit_images and image_count >= image_load_cap:
56
+ break
57
+ i = Image.open(image_path)
58
+ i = ImageOps.exif_transpose(i)
59
+ image = i.convert("RGB")
60
+ image = np.array(image).astype(np.float32) / 255.0
61
+ image = torch.from_numpy(image)[None,]
62
+ if 'A' in i.getbands():
63
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
64
+ mask = 1. - torch.from_numpy(mask)
65
+ else:
66
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
67
+ images.append(image)
68
+ masks.append(mask)
69
+ image_count += 1
70
+
71
+ if len(images) == 0:
72
+ raise FileNotFoundError(f"No images could be loaded from directory '{directory}'.")
73
+
74
+ return (torch.cat(images, dim=0), torch.stack(masks, dim=0), image_count)
75
+
76
+
77
+ class ScaledSoftUniversalWeightsDeprecated:
78
+ @classmethod
79
+ def INPUT_TYPES(s):
80
+ return {
81
+ "required": {
82
+ "base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
83
+ "flip_weights": ("BOOLEAN", {"default": False}),
84
+ },
85
+ "optional": {
86
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
87
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
88
+ },
89
+ "hidden": {
90
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
91
+ }
92
+ }
93
+
94
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
95
+ RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
96
+ FUNCTION = "load_weights"
97
+
98
+ CATEGORY = ""
99
+
100
+ def load_weights(self, base_multiplier, flip_weights, uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
101
+ weights = ControlWeights.universal(base_multiplier=base_multiplier, uncond_multiplier=uncond_multiplier, extras=cn_extras)
102
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
103
+
104
+
105
+ class SoftControlNetWeightsDeprecated:
106
+ @classmethod
107
+ def INPUT_TYPES(s):
108
+ return {
109
+ "required": {
110
+ "weight_00": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
111
+ "weight_01": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
112
+ "weight_02": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
113
+ "weight_03": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
114
+ "weight_04": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
115
+ "weight_05": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
116
+ "weight_06": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
117
+ "weight_07": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
118
+ "weight_08": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
119
+ "weight_09": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
120
+ "weight_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
121
+ "weight_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
122
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
123
+ "flip_weights": ("BOOLEAN", {"default": False}),
124
+ },
125
+ "optional": {
126
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
127
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
128
+ },
129
+ "hidden": {
130
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
131
+ }
132
+ }
133
+
134
+ DEPRECATED = True
135
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
136
+ RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
137
+ FUNCTION = "load_weights"
138
+
139
+ CATEGORY = ""
140
+
141
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
142
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
143
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
144
+ weights_output = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
145
+ weight_07, weight_08, weight_09, weight_10, weight_11]
146
+ weights_middle = [weight_12]
147
+ weights = ControlWeights.controlnet(weights_output=weights_output, weights_middle=weights_middle, uncond_multiplier=uncond_multiplier, extras=cn_extras)
148
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
149
+
150
+
151
+ class CustomControlNetWeightsDeprecated:
152
+ @classmethod
153
+ def INPUT_TYPES(s):
154
+ return {
155
+ "required": {
156
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
157
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
158
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
159
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
160
+ "weight_04": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
161
+ "weight_05": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
162
+ "weight_06": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
163
+ "weight_07": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
164
+ "weight_08": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
165
+ "weight_09": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
166
+ "weight_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
167
+ "weight_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
168
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
169
+ "flip_weights": ("BOOLEAN", {"default": False}),
170
+ },
171
+ "optional": {
172
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
173
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
174
+ },
175
+ "hidden": {
176
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
177
+ }
178
+ }
179
+
180
+ DEPRECATED = True
181
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
182
+ RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
183
+ FUNCTION = "load_weights"
184
+
185
+ CATEGORY = ""
186
+
187
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
188
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
189
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
190
+ weights_output = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
191
+ weight_07, weight_08, weight_09, weight_10, weight_11]
192
+ weights_middle = [weight_12]
193
+ weights = ControlWeights.controlnet(weights_output=weights_output, weights_middle=weights_middle, uncond_multiplier=uncond_multiplier, extras=cn_extras)
194
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
195
+
196
+
197
+ class SoftT2IAdapterWeightsDeprecated:
198
+ @classmethod
199
+ def INPUT_TYPES(s):
200
+ return {
201
+ "required": {
202
+ "weight_00": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
203
+ "weight_01": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
204
+ "weight_02": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
205
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
206
+ "flip_weights": ("BOOLEAN", {"default": False}),
207
+ },
208
+ "optional": {
209
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
210
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
211
+ },
212
+ "hidden": {
213
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
214
+ }
215
+ }
216
+
217
+ DEPRECATED = True
218
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
219
+ RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
220
+ FUNCTION = "load_weights"
221
+
222
+ CATEGORY = ""
223
+
224
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
225
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
226
+ weights = [weight_00, weight_01, weight_02, weight_03]
227
+ weights = get_properly_arranged_t2i_weights(weights)
228
+ weights = ControlWeights.t2iadapter(weights_input=weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
229
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
230
+
231
+
232
+ class CustomT2IAdapterWeightsDeprecated:
233
+ @classmethod
234
+ def INPUT_TYPES(s):
235
+ return {
236
+ "required": {
237
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
238
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
239
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
240
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
241
+ "flip_weights": ("BOOLEAN", {"default": False}),
242
+ },
243
+ "optional": {
244
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
245
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
246
+ },
247
+ "hidden": {
248
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
249
+ }
250
+ }
251
+
252
+ DEPRECATED = True
253
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
254
+ RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
255
+ FUNCTION = "load_weights"
256
+
257
+ CATEGORY = ""
258
+
259
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
260
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
261
+ weights = [weight_00, weight_01, weight_02, weight_03]
262
+ weights = get_properly_arranged_t2i_weights(weights)
263
+ weights = ControlWeights.t2iadapter(weights_input=weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
264
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
265
+
266
+
267
+ class AdvancedControlNetApplyDEPR:
268
+ @classmethod
269
+ def INPUT_TYPES(s):
270
+ return {
271
+ "required": {
272
+ "positive": ("CONDITIONING", ),
273
+ "negative": ("CONDITIONING", ),
274
+ "control_net": ("CONTROL_NET", ),
275
+ "image": ("IMAGE", ),
276
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
277
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
278
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
279
+ },
280
+ "optional": {
281
+ "mask_optional": ("MASK", ),
282
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
283
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
284
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
285
+ "model_optional": ("MODEL",),
286
+ "vae_optional": ("VAE",),
287
+ },
288
+ "hidden": {
289
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
290
+ }
291
+ }
292
+
293
+ DEPRECATED = True
294
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING","MODEL",)
295
+ RETURN_NAMES = ("positive", "negative", "model_opt")
296
+ FUNCTION = "apply_controlnet"
297
+
298
+ CATEGORY = ""
299
+
300
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent,
301
+ mask_optional=None, model_optional=None, vae_optional=None,
302
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override=None,
303
+ weights_override: ControlWeights=None, control_apply_to_uncond=False):
304
+ new_positive, new_negative = AdvancedControlNetApply.apply_controlnet(self, positive=positive, negative=negative, control_net=control_net, image=image,
305
+ strength=strength, start_percent=start_percent, end_percent=end_percent,
306
+ mask_optional=mask_optional, vae_optional=vae_optional,
307
+ timestep_kf=timestep_kf, latent_kf_override=latent_kf_override, weights_override=weights_override,)
308
+ return (new_positive, new_negative, model_optional)
309
+
310
+
311
+ class AdvancedControlNetApplySingleDEPR:
312
+ @classmethod
313
+ def INPUT_TYPES(s):
314
+ return {
315
+ "required": {
316
+ "conditioning": ("CONDITIONING", ),
317
+ "control_net": ("CONTROL_NET", ),
318
+ "image": ("IMAGE", ),
319
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
320
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
321
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
322
+ },
323
+ "optional": {
324
+ "mask_optional": ("MASK", ),
325
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
326
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
327
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
328
+ "model_optional": ("MODEL",),
329
+ "vae_optional": ("VAE",),
330
+ },
331
+ "hidden": {
332
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
333
+ }
334
+ }
335
+
336
+ DEPRECATED = True
337
+ RETURN_TYPES = ("CONDITIONING","MODEL",)
338
+ RETURN_NAMES = ("CONDITIONING", "model_opt")
339
+ FUNCTION = "apply_controlnet"
340
+
341
+ CATEGORY = ""
342
+
343
+ def apply_controlnet(self, conditioning, control_net, image, strength, start_percent, end_percent,
344
+ mask_optional=None, model_optional=None, vae_optional=None,
345
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override=None,
346
+ weights_override: ControlWeights=None):
347
+ values = AdvancedControlNetApply.apply_controlnet(self, positive=conditioning, negative=None, control_net=control_net, image=image,
348
+ strength=strength, start_percent=start_percent, end_percent=end_percent,
349
+ mask_optional=mask_optional, vae_optional=vae_optional,
350
+ timestep_kf=timestep_kf, latent_kf_override=latent_kf_override, weights_override=weights_override,
351
+ control_apply_to_uncond=True)
352
+ return (values[0], model_optional)
353
+
354
+
355
+ class ControlNetLoaderAdvancedDEPR:
356
+ @classmethod
357
+ def INPUT_TYPES(s):
358
+ return {
359
+ "required": {
360
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
361
+ },
362
+ "optional": {
363
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
364
+ }
365
+ }
366
+
367
+ DEPRECATED = True
368
+ RETURN_TYPES = ("CONTROL_NET", )
369
+ FUNCTION = "load_controlnet"
370
+
371
+ CATEGORY = ""
372
+
373
+ def load_controlnet(self, control_net_name,
374
+ tk_optional: TimestepKeyframeGroup=None,
375
+ timestep_keyframe: TimestepKeyframeGroup=None,
376
+ ):
377
+ if timestep_keyframe is not None: # backwards compatibility
378
+ tk_optional = timestep_keyframe
379
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
380
+ controlnet = load_controlnet(controlnet_path, tk_optional)
381
+ return (controlnet,)
382
+
383
+
384
+ class DiffControlNetLoaderAdvancedDEPR:
385
+ @classmethod
386
+ def INPUT_TYPES(s):
387
+ return {
388
+ "required": {
389
+ "model": ("MODEL",),
390
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )
391
+ },
392
+ "optional": {
393
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
394
+ },
395
+ "hidden": {
396
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
397
+ }
398
+ }
399
+
400
+ DEPRECATED = True
401
+ RETURN_TYPES = ("CONTROL_NET", )
402
+ FUNCTION = "load_controlnet"
403
+
404
+ CATEGORY = ""
405
+
406
+ def load_controlnet(self, control_net_name, model,
407
+ tk_optional: TimestepKeyframeGroup=None,
408
+ timestep_keyframe: TimestepKeyframeGroup=None
409
+ ):
410
+ if timestep_keyframe is not None: # backwards compatibility
411
+ tk_optional = timestep_keyframe
412
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
413
+ controlnet = load_controlnet(controlnet_path, tk_optional, model)
414
+ if is_advanced_controlnet(controlnet):
415
+ controlnet.verify_all_weights()
416
+ return (controlnet,)
ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "hidden": {
30
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
31
+ }
32
+ }
33
+
34
+ RETURN_NAMES = ("TIMESTEP_KF", )
35
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
36
+ FUNCTION = "load_keyframe"
37
+
38
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
39
+
40
+ def load_keyframe(self,
41
+ start_percent: float,
42
+ strength: float=1.0,
43
+ cn_weights: ControlWeights=None, control_net_weights: ControlWeights=None, # old name
44
+ latent_keyframe: LatentKeyframeGroup=None,
45
+ prev_timestep_kf: TimestepKeyframeGroup=None, prev_timestep_keyframe: TimestepKeyframeGroup=None, # old name
46
+ null_latent_kf_strength: float=0.0,
47
+ inherit_missing=True,
48
+ guarantee_steps=OUTDATED_DUMMY,
49
+ guarantee_usage=True, # old input
50
+ mask_optional=None,):
51
+ # if using outdated dummy value, means node on workflow is outdated and should appropriately convert behavior
52
+ if guarantee_steps == self.OUTDATED_DUMMY:
53
+ guarantee_steps = int(guarantee_usage)
54
+ control_net_weights = control_net_weights if control_net_weights else cn_weights
55
+ prev_timestep_keyframe = prev_timestep_keyframe if prev_timestep_keyframe else prev_timestep_kf
56
+ if not prev_timestep_keyframe:
57
+ prev_timestep_keyframe = TimestepKeyframeGroup()
58
+ else:
59
+ prev_timestep_keyframe = prev_timestep_keyframe.clone()
60
+ keyframe = TimestepKeyframe(start_percent=start_percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
61
+ control_weights=control_net_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
62
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional)
63
+ prev_timestep_keyframe.add(keyframe)
64
+ return (prev_timestep_keyframe,)
65
+
66
+
67
+ class TimestepKeyframeInterpolationNode:
68
+ @classmethod
69
+ def INPUT_TYPES(s):
70
+ return {
71
+ "required": {
72
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
73
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
74
+ "strength_start": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
75
+ "strength_end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
76
+ "interpolation": (SI._LIST, ),
77
+ "intervals": ("INT", {"default": 50, "min": 2, "max": 100, "step": 1}),
78
+ },
79
+ "optional": {
80
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
81
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
82
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
83
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
84
+ "inherit_missing": ("BOOLEAN", {"default": True},),
85
+ "mask_optional": ("MASK", ),
86
+ "print_keyframes": ("BOOLEAN", {"default": False}),
87
+ },
88
+ "hidden": {
89
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
90
+ }
91
+ }
92
+
93
+ RETURN_NAMES = ("TIMESTEP_KF", )
94
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
95
+ FUNCTION = "load_keyframe"
96
+
97
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
98
+
99
+ def load_keyframe(self,
100
+ start_percent: float, end_percent: float,
101
+ strength_start: float, strength_end: float, interpolation: str, intervals: int,
102
+ cn_weights: ControlWeights=None,
103
+ latent_keyframe: LatentKeyframeGroup=None,
104
+ prev_timestep_kf: TimestepKeyframeGroup=None,
105
+ null_latent_kf_strength: float=0.0,
106
+ inherit_missing=True,
107
+ guarantee_steps=1,
108
+ mask_optional=None, print_keyframes=False):
109
+ if not prev_timestep_kf:
110
+ prev_timestep_kf = TimestepKeyframeGroup()
111
+ else:
112
+ prev_timestep_kf = prev_timestep_kf.clone()
113
+
114
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=intervals, method=SI.LINEAR)
115
+ strengths = SI.get_weights(num_from=strength_start, num_to=strength_end, length=intervals, method=interpolation)
116
+
117
+ is_first = True
118
+ for percent, strength in zip(percents, strengths):
119
+ guarantee_steps = 0
120
+ if is_first:
121
+ guarantee_steps = 1
122
+ is_first = False
123
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
124
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
125
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
126
+ if print_keyframes:
127
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
128
+ return (prev_timestep_kf,)
129
+
130
+
131
+ class TimestepKeyframeFromStrengthListNode:
132
+ @classmethod
133
+ def INPUT_TYPES(s):
134
+ return {
135
+ "required": {
136
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
137
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
138
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
139
+ },
140
+ "optional": {
141
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
142
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
143
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
144
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
145
+ "inherit_missing": ("BOOLEAN", {"default": True},),
146
+ "mask_optional": ("MASK", ),
147
+ "print_keyframes": ("BOOLEAN", {"default": False}),
148
+ },
149
+ "hidden": {
150
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
151
+ }
152
+ }
153
+
154
+ RETURN_NAMES = ("TIMESTEP_KF", )
155
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
156
+ FUNCTION = "load_keyframe"
157
+
158
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
159
+
160
+ def load_keyframe(self,
161
+ start_percent: float, end_percent: float,
162
+ float_strengths: float,
163
+ cn_weights: ControlWeights=None,
164
+ latent_keyframe: LatentKeyframeGroup=None,
165
+ prev_timestep_kf: TimestepKeyframeGroup=None,
166
+ null_latent_kf_strength: float=0.0,
167
+ inherit_missing=True,
168
+ guarantee_steps=1,
169
+ mask_optional=None, print_keyframes=False):
170
+ if not prev_timestep_kf:
171
+ prev_timestep_kf = TimestepKeyframeGroup()
172
+ else:
173
+ prev_timestep_kf = prev_timestep_kf.clone()
174
+
175
+ if type(float_strengths) in (float, int):
176
+ float_strengths = [float(float_strengths)]
177
+ elif isinstance(float_strengths, Iterable):
178
+ pass
179
+ else:
180
+ raise Exception(f"strengths_float must be either an iterable input or a float, but was {type(float_strengths).__repr__}.")
181
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=len(float_strengths), method=SI.LINEAR)
182
+
183
+ is_first = True
184
+ for percent, strength in zip(percents, float_strengths):
185
+ guarantee_steps = 0
186
+ if is_first:
187
+ guarantee_steps = 1
188
+ is_first = False
189
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
190
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
191
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
192
+ if print_keyframes:
193
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
194
+ return (prev_timestep_kf,)
195
+
196
+
197
+ class LatentKeyframeNode:
198
+ @classmethod
199
+ def INPUT_TYPES(s):
200
+ return {
201
+ "required": {
202
+ "batch_index": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
203
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
204
+ },
205
+ "optional": {
206
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
207
+ },
208
+ "hidden": {
209
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
210
+ }
211
+ }
212
+
213
+ RETURN_NAMES = ("LATENT_KF", )
214
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
215
+ FUNCTION = "load_keyframe"
216
+
217
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
218
+
219
+ def load_keyframe(self,
220
+ batch_index: int,
221
+ strength: float,
222
+ prev_latent_kf: LatentKeyframeGroup=None,
223
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
224
+ ):
225
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
226
+ if not prev_latent_keyframe:
227
+ prev_latent_keyframe = LatentKeyframeGroup()
228
+ else:
229
+ prev_latent_keyframe = prev_latent_keyframe.clone()
230
+ keyframe = LatentKeyframe(batch_index, strength)
231
+ prev_latent_keyframe.add(keyframe)
232
+ return (prev_latent_keyframe,)
233
+
234
+
235
+ class LatentKeyframeGroupNode:
236
+ @classmethod
237
+ def INPUT_TYPES(s):
238
+ return {
239
+ "required": {
240
+ "index_strengths": ("STRING", {"multiline": True, "default": ""}),
241
+ },
242
+ "optional": {
243
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
244
+ "latent_optional": ("LATENT", ),
245
+ "print_keyframes": ("BOOLEAN", {"default": False}),
246
+ },
247
+ "hidden": {
248
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
249
+ }
250
+ }
251
+
252
+ RETURN_NAMES = ("LATENT_KF", )
253
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
254
+ FUNCTION = "load_keyframes"
255
+
256
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
257
+
258
+ def validate_index(self, index: int, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
259
+ # if part of range, do nothing
260
+ if is_range:
261
+ return index
262
+ # otherwise, validate index
263
+ # validate not out of range - only when latent_count is passed in
264
+ if latent_count > 0 and index > latent_count-1:
265
+ raise IndexError(f"Index '{index}' out of range for the total {latent_count} latents.")
266
+ # if negative, validate not out of range
267
+ if index < 0:
268
+ if not allow_negative:
269
+ raise IndexError(f"Negative indeces not allowed, but was {index}.")
270
+ conv_index = latent_count+index
271
+ if conv_index < 0:
272
+ raise IndexError(f"Index '{index}', converted to '{conv_index}' out of range for the total {latent_count} latents.")
273
+ index = conv_index
274
+ return index
275
+
276
+ def convert_to_index_int(self, raw_index: str, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
277
+ try:
278
+ return self.validate_index(int(raw_index), latent_count=latent_count, is_range=is_range, allow_negative=allow_negative)
279
+ except ValueError as e:
280
+ raise ValueError(f"index '{raw_index}' must be an integer.", e)
281
+
282
+ def convert_to_latent_keyframes(self, latent_indeces: str, latent_count: int) -> set[LatentKeyframe]:
283
+ if not latent_indeces:
284
+ return set()
285
+ int_latent_indeces = [i for i in range(0, latent_count)]
286
+ allow_negative = latent_count > 0
287
+ chosen_indeces = set()
288
+ # parse string - allow positive ints, negative ints, and ranges separated by ':'
289
+ groups = latent_indeces.split(",")
290
+ groups = [g.strip() for g in groups]
291
+ for g in groups:
292
+ # parse strengths - default to 1.0 if no strength given
293
+ strength = 1.0
294
+ if '=' in g:
295
+ g, strength_str = g.split("=", 1)
296
+ g = g.strip()
297
+ try:
298
+ strength = float(strength_str.strip())
299
+ except ValueError as e:
300
+ raise ValueError(f"strength '{strength_str}' must be a float.", e)
301
+ if strength < 0:
302
+ raise ValueError(f"Strength '{strength}' cannot be negative.")
303
+ # parse range of indeces (e.g. 2:16)
304
+ if ':' in g:
305
+ index_range = g.split(":", 1)
306
+ index_range = [r.strip() for r in index_range]
307
+ start_index = self.convert_to_index_int(index_range[0], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
308
+ end_index = self.convert_to_index_int(index_range[1], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
309
+ # if latents were passed in, base indeces on known latent count
310
+ if len(int_latent_indeces) > 0:
311
+ for i in int_latent_indeces[start_index:end_index]:
312
+ chosen_indeces.add(LatentKeyframe(i, strength))
313
+ # otherwise, assume indeces are valid
314
+ else:
315
+ for i in range(start_index, end_index):
316
+ chosen_indeces.add(LatentKeyframe(i, strength))
317
+ # parse individual indeces
318
+ else:
319
+ chosen_indeces.add(LatentKeyframe(self.convert_to_index_int(g, latent_count=latent_count, allow_negative=allow_negative), strength))
320
+ return chosen_indeces
321
+
322
+ def load_keyframes(self,
323
+ index_strengths: str,
324
+ prev_latent_kf: LatentKeyframeGroup=None,
325
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
326
+ latent_image_opt=None,
327
+ print_keyframes=False):
328
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
329
+ if not prev_latent_keyframe:
330
+ prev_latent_keyframe = LatentKeyframeGroup()
331
+ else:
332
+ prev_latent_keyframe = prev_latent_keyframe.clone()
333
+ curr_latent_keyframe = LatentKeyframeGroup()
334
+
335
+ latent_count = -1
336
+ if latent_image_opt:
337
+ latent_count = latent_image_opt['samples'].size()[0]
338
+ latent_keyframes = self.convert_to_latent_keyframes(index_strengths, latent_count=latent_count)
339
+
340
+ for latent_keyframe in latent_keyframes:
341
+ curr_latent_keyframe.add(latent_keyframe)
342
+
343
+ if print_keyframes:
344
+ for keyframe in curr_latent_keyframe.keyframes:
345
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
346
+
347
+ # replace values with prev_latent_keyframes
348
+ for latent_keyframe in prev_latent_keyframe.keyframes:
349
+ curr_latent_keyframe.add(latent_keyframe)
350
+
351
+ return (curr_latent_keyframe,)
352
+
353
+
354
+ class LatentKeyframeInterpolationNode:
355
+ @classmethod
356
+ def INPUT_TYPES(s):
357
+ return {
358
+ "required": {
359
+ "batch_index_from": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
360
+ "batch_index_to_excl": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
361
+ "strength_from": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
362
+ "strength_to": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
363
+ "interpolation": (SI._LIST, ),
364
+ },
365
+ "optional": {
366
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
367
+ "print_keyframes": ("BOOLEAN", {"default": False}),
368
+ },
369
+ "hidden": {
370
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
371
+ }
372
+ }
373
+
374
+ RETURN_NAMES = ("LATENT_KF", )
375
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
376
+ FUNCTION = "load_keyframe"
377
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
378
+
379
+ def load_keyframe(self,
380
+ batch_index_from: int,
381
+ strength_from: float,
382
+ batch_index_to_excl: int,
383
+ strength_to: float,
384
+ interpolation: str,
385
+ prev_latent_kf: LatentKeyframeGroup=None,
386
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
387
+ print_keyframes=False):
388
+
389
+ if (batch_index_from > batch_index_to_excl):
390
+ raise ValueError("batch_index_from must be less than or equal to batch_index_to.")
391
+
392
+ if (batch_index_from < 0 and batch_index_to_excl >= 0):
393
+ raise ValueError("batch_index_from and batch_index_to must be either both positive or both negative.")
394
+
395
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
396
+ if not prev_latent_keyframe:
397
+ prev_latent_keyframe = LatentKeyframeGroup()
398
+ else:
399
+ prev_latent_keyframe = prev_latent_keyframe.clone()
400
+ curr_latent_keyframe = LatentKeyframeGroup()
401
+
402
+ steps = batch_index_to_excl - batch_index_from
403
+ diff = strength_to - strength_from
404
+ if interpolation == SI.LINEAR:
405
+ weights = np.linspace(strength_from, strength_to, steps)
406
+ elif interpolation == SI.EASE_IN:
407
+ index = np.linspace(0, 1, steps)
408
+ weights = diff * np.power(index, 2) + strength_from
409
+ elif interpolation == SI.EASE_OUT:
410
+ index = np.linspace(0, 1, steps)
411
+ weights = diff * (1 - np.power(1 - index, 2)) + strength_from
412
+ elif interpolation == SI.EASE_IN_OUT:
413
+ index = np.linspace(0, 1, steps)
414
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + strength_from
415
+
416
+ for i in range(steps):
417
+ keyframe = LatentKeyframe(batch_index_from + i, float(weights[i]))
418
+ curr_latent_keyframe.add(keyframe)
419
+
420
+ if print_keyframes:
421
+ for keyframe in curr_latent_keyframe.keyframes:
422
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
423
+
424
+ # replace values with prev_latent_keyframes
425
+ for latent_keyframe in prev_latent_keyframe.keyframes:
426
+ curr_latent_keyframe.add(latent_keyframe)
427
+
428
+ return (curr_latent_keyframe,)
429
+
430
+
431
+ class LatentKeyframeBatchedGroupNode:
432
+ @classmethod
433
+ def INPUT_TYPES(s):
434
+ return {
435
+ "required": {
436
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
437
+ },
438
+ "optional": {
439
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
440
+ "print_keyframes": ("BOOLEAN", {"default": False}),
441
+ },
442
+ "hidden": {
443
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
444
+ }
445
+ }
446
+
447
+ RETURN_NAMES = ("LATENT_KF", )
448
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
449
+ FUNCTION = "load_keyframe"
450
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
451
+
452
+ def load_keyframe(self, float_strengths: Union[float, list[float]],
453
+ prev_latent_kf: LatentKeyframeGroup=None,
454
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
455
+ print_keyframes=False):
456
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
457
+ if not prev_latent_keyframe:
458
+ prev_latent_keyframe = LatentKeyframeGroup()
459
+ else:
460
+ prev_latent_keyframe = prev_latent_keyframe.clone()
461
+ curr_latent_keyframe = LatentKeyframeGroup()
462
+
463
+ # if received a normal float input, do nothing
464
+ if type(float_strengths) in (float, int):
465
+ logger.info("No batched float_strengths passed into Latent Keyframe Batch Group node; will not create any new keyframes.")
466
+ # if iterable, attempt to create LatentKeyframes with chosen strengths
467
+ elif isinstance(float_strengths, Iterable):
468
+ for idx, strength in enumerate(float_strengths):
469
+ keyframe = LatentKeyframe(idx, strength)
470
+ curr_latent_keyframe.add(keyframe)
471
+ else:
472
+ raise ValueError(f"Expected strengths to be an iterable input, but was {type(float_strengths).__repr__}.")
473
+
474
+ if print_keyframes:
475
+ for keyframe in curr_latent_keyframe.keyframes:
476
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
477
+
478
+ # replace values with prev_latent_keyframes
479
+ for latent_keyframe in prev_latent_keyframe.keyframes:
480
+ curr_latent_keyframe.add(latent_keyframe)
481
+
482
+ return (curr_latent_keyframe,)
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-Advanced-ControlNet/adv_control/nodes_main.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ import folder_paths
4
+ from comfy.model_patcher import ModelPatcher
5
+
6
+ from .control import load_controlnet, convert_to_advanced, is_advanced_controlnet, is_sd3_advanced_controlnet
7
+ from .utils import ControlWeights, LatentKeyframeGroup, TimestepKeyframeGroup, AbstractPreprocWrapper, BIGMAX
8
+
9
+ from .logger import logger
10
+
11
+
12
+ class ControlNetLoaderAdvanced:
13
+ @classmethod
14
+ def INPUT_TYPES(s):
15
+ return {
16
+ "required": {
17
+ "cnet": (folder_paths.get_filename_list("controlnet"), ),
18
+ },
19
+ "optional": {
20
+ "_tk_opt": ("TIMESTEP_KEYFRAME", ),
21
+ }
22
+ }
23
+
24
+ RETURN_TYPES = ("CONTROL_NET", )
25
+ FUNCTION = "load_controlnet"
26
+
27
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
28
+
29
+ def load_controlnet(self, cnet,
30
+ _tk_opt: TimestepKeyframeGroup=None,
31
+ ):
32
+ controlnet_path = folder_paths.get_full_path("controlnet", cnet)
33
+ controlnet = load_controlnet(controlnet_path, _tk_opt)
34
+ return (controlnet,)
35
+
36
+
37
+ class DiffControlNetLoaderAdvanced:
38
+ @classmethod
39
+ def INPUT_TYPES(s):
40
+ return {
41
+ "required": {
42
+ "model": ("MODEL",),
43
+ "cnet": (folder_paths.get_filename_list("controlnet"), )
44
+ },
45
+ "optional": {
46
+ "_tk_opt": ("TIMESTEP_KEYFRAME", ),
47
+ },
48
+ "hidden": {
49
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
50
+ }
51
+ }
52
+
53
+ RETURN_TYPES = ("CONTROL_NET", )
54
+ FUNCTION = "load_controlnet"
55
+
56
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
57
+
58
+ def load_controlnet(self, cnet, model,
59
+ _tk_opt: TimestepKeyframeGroup=None,
60
+ ):
61
+ controlnet_path = folder_paths.get_full_path("controlnet", cnet)
62
+ controlnet = load_controlnet(controlnet_path, _tk_opt, model)
63
+ if is_advanced_controlnet(controlnet):
64
+ controlnet.verify_all_weights()
65
+ return (controlnet,)
66
+
67
+
68
+ class AdvancedControlNetApply:
69
+ @classmethod
70
+ def INPUT_TYPES(s):
71
+ return {
72
+ "required": {
73
+ "positive": ("CONDITIONING", ),
74
+ "negative": ("CONDITIONING", ),
75
+ "control_net": ("CONTROL_NET", ),
76
+ "image": ("IMAGE", ),
77
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
78
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
79
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
80
+ },
81
+ "optional": {
82
+ "mask_optional": ("MASK", ),
83
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
84
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
85
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
86
+ "vae_optional": ("VAE",),
87
+ },
88
+ "hidden": {
89
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
90
+ }
91
+ }
92
+
93
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
94
+ RETURN_NAMES = ("positive", "negative")
95
+ FUNCTION = "apply_controlnet"
96
+
97
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
98
+
99
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent,
100
+ mask_optional: Tensor=None, vae_optional=None,
101
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override: LatentKeyframeGroup=None,
102
+ weights_override: ControlWeights=None, control_apply_to_uncond=False):
103
+ if strength == 0:
104
+ return (positive, negative)
105
+
106
+ control_hint = image.movedim(-1,1)
107
+ cnets = {}
108
+
109
+ out = []
110
+ for conditioning in [positive, negative]:
111
+ c = []
112
+ if conditioning is not None:
113
+ for t in conditioning:
114
+ d = t[1].copy()
115
+
116
+ prev_cnet = d.get('control', None)
117
+ if prev_cnet in cnets:
118
+ c_net = cnets[prev_cnet]
119
+ else:
120
+ # make sure control_net is not None to avoid confusing error messages
121
+ if control_net is None:
122
+ raise Exception("Passed in control_net is None; something must have went wrong when loading it from a Load ControlNet node.")
123
+ # copy, convert to advanced if needed, and set cond
124
+ c_net = convert_to_advanced(control_net.copy()).set_cond_hint(control_hint, strength, (start_percent, end_percent), vae_optional)
125
+ if is_advanced_controlnet(c_net):
126
+ # disarm node check
127
+ c_net.disarm()
128
+ # check for allow_condhint_latents where vae_optional can't handle it itself
129
+ if c_net.allow_condhint_latents and not c_net.require_vae:
130
+ if not isinstance(control_hint, AbstractPreprocWrapper):
131
+ raise Exception(f"Type '{type(c_net).__name__}' requires proc_IMAGE input via a corresponding preprocessor, but received a normal Image instead.")
132
+ else:
133
+ if isinstance(control_hint, AbstractPreprocWrapper) and not c_net.postpone_condhint_latents_check:
134
+ raise Exception(f"Type '{type(c_net).__name__}' requires a normal Image input, but received a proc_IMAGE input instead.")
135
+ # if vae required, verify vae is passed in
136
+ if c_net.require_vae:
137
+ # if controlnet can accept preprocced condhint latents and is the case, ignore vae requirement
138
+ if c_net.allow_condhint_latents and isinstance(control_hint, AbstractPreprocWrapper):
139
+ pass
140
+ elif not vae_optional:
141
+ # make sure SD3 ControlNet will get a special message instead of generic type mention
142
+ if is_sd3_advanced_controlnet(c_net):
143
+ raise Exception(f"SD3 ControlNet requires vae_optional input, but got None.")
144
+ else:
145
+ raise Exception(f"Type '{type(c_net).__name__}' requires vae_optional input, but got None.")
146
+ # apply optional parameters and overrides, if provided
147
+ if timestep_kf is not None:
148
+ c_net.set_timestep_keyframes(timestep_kf)
149
+ if latent_kf_override is not None:
150
+ c_net.latent_keyframe_override = latent_kf_override
151
+ if weights_override is not None:
152
+ c_net.weights_override = weights_override
153
+ # verify weights are compatible
154
+ c_net.verify_all_weights()
155
+ # set cond hint mask
156
+ if mask_optional is not None:
157
+ mask_optional = mask_optional.clone()
158
+ # if not in the form of a batch, make it so
159
+ if len(mask_optional.shape) < 3:
160
+ mask_optional = mask_optional.unsqueeze(0)
161
+ c_net.set_cond_hint_mask(mask_optional)
162
+ c_net.set_previous_controlnet(prev_cnet)
163
+ cnets[prev_cnet] = c_net
164
+
165
+ d['control'] = c_net
166
+ d['control_apply_to_uncond'] = control_apply_to_uncond
167
+ n = [t[0], d]
168
+ c.append(n)
169
+ out.append(c)
170
+ return (out[0], out[1])
171
+
172
+
173
+ class AdvancedControlNetApplySingle:
174
+ @classmethod
175
+ def INPUT_TYPES(s):
176
+ return {
177
+ "required": {
178
+ "conditioning": ("CONDITIONING", ),
179
+ "control_net": ("CONTROL_NET", ),
180
+ "image": ("IMAGE", ),
181
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
182
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
183
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
184
+ },
185
+ "optional": {
186
+ "mask_optional": ("MASK", ),
187
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
188
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
189
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
190
+ "vae_optional": ("VAE",),
191
+ },
192
+ "hidden": {
193
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
194
+ }
195
+ }
196
+
197
+ RETURN_TYPES = ("CONDITIONING","MODEL",)
198
+ RETURN_NAMES = ("CONDITIONING", "model_opt")
199
+ FUNCTION = "apply_controlnet"
200
+
201
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
202
+
203
+ def apply_controlnet(self, conditioning, control_net, image, strength, start_percent, end_percent,
204
+ mask_optional: Tensor=None, vae_optional=None,
205
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override: LatentKeyframeGroup=None,
206
+ weights_override: ControlWeights=None):
207
+ values = AdvancedControlNetApply.apply_controlnet(self, positive=conditioning, negative=None, control_net=control_net, image=image,
208
+ strength=strength, start_percent=start_percent, end_percent=end_percent,
209
+ mask_optional=mask_optional, vae_optional=vae_optional,
210
+ timestep_kf=timestep_kf, latent_kf_override=latent_kf_override, weights_override=weights_override,
211
+ control_apply_to_uncond=True)
212
+ return (values[0],)
ComfyUI-Advanced-ControlNet/adv_control/nodes_plusplus.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+ import math
3
+
4
+ import folder_paths
5
+
6
+ from .control_plusplus import load_controlnetplusplus, PlusPlusType, PlusPlusInput, PlusPlusInputGroup, PlusPlusImageWrapper
7
+ from .utils import BIGMAX
8
+
9
+
10
+ class PlusPlusLoaderAdvanced:
11
+ @classmethod
12
+ def INPUT_TYPES(s):
13
+ return {
14
+ "required": {
15
+ "plus_input": ("PLUS_INPUT", ),
16
+ "name": (folder_paths.get_filename_list("controlnet"), ),
17
+ }
18
+ }
19
+
20
+ RETURN_TYPES = ("CONTROL_NET", "IMAGE",)
21
+ FUNCTION = "load_controlnet_plusplus"
22
+
23
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/ControlNet++"
24
+
25
+ def load_controlnet_plusplus(self, plus_input: PlusPlusInputGroup, name: str):
26
+ controlnet_path = folder_paths.get_full_path("controlnet", name)
27
+ controlnet = load_controlnetplusplus(controlnet_path)
28
+ controlnet.verify_control_type(name, plus_input)
29
+ controlnet.allow_condhint_latents = True
30
+ return (controlnet, PlusPlusImageWrapper(plus_input),)
31
+
32
+
33
+ class PlusPlusLoaderSingle:
34
+ @classmethod
35
+ def INPUT_TYPES(s):
36
+ return {
37
+ "required": {
38
+ "name": (folder_paths.get_filename_list("controlnet"), ),
39
+ "control_type": (PlusPlusType._LIST_WITH_NONE, {"default": PlusPlusType.NONE}, ),
40
+ }
41
+ }
42
+
43
+ RETURN_TYPES = ("CONTROL_NET",)
44
+ FUNCTION = "load_controlnet_plusplus"
45
+
46
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/ControlNet++"
47
+
48
+ def load_controlnet_plusplus(self, name: str, control_type: str):
49
+ controlnet_path = folder_paths.get_full_path("controlnet", name)
50
+ controlnet = load_controlnetplusplus(controlnet_path)
51
+ controlnet.single_control_type = control_type
52
+ controlnet.verify_control_type(name)
53
+ return (controlnet,)
54
+
55
+
56
+ class PlusPlusInputNode:
57
+ @classmethod
58
+ def INPUT_TYPES(s):
59
+ return {
60
+ "required": {
61
+ "image": ("IMAGE",),
62
+ "control_type": (PlusPlusType._LIST,),
63
+ },
64
+ "optional": {
65
+ "prev_plus_input": ("PLUS_INPUT",),
66
+ #"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": BIGMAX, "step": 0.01}),
67
+ },
68
+ "hidden": {
69
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
70
+ }
71
+ }
72
+
73
+ RETURN_TYPES = ("PLUS_INPUT", )
74
+ FUNCTION = "wrap_images"
75
+
76
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/ControlNet++"
77
+
78
+ def wrap_images(self, image: Tensor, control_type: str, strength=1.0, prev_plus_input: PlusPlusInputGroup=None):
79
+ if prev_plus_input is None:
80
+ prev_plus_input = PlusPlusInputGroup()
81
+ prev_plus_input = prev_plus_input.clone()
82
+
83
+ if math.isclose(strength, 0.0):
84
+ strength = 0.0000001
85
+ pp_input = PlusPlusInput(image, control_type, strength)
86
+ prev_plus_input.add(pp_input)
87
+
88
+ return (prev_plus_input,)
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-Advanced-ControlNet/adv_control/nodes_sparsectrl.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "hidden": {
138
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
139
+ }
140
+ }
141
+
142
+ RETURN_TYPES = ("IMAGE",)
143
+ RETURN_NAMES = ("proc_IMAGE",)
144
+ FUNCTION = "preprocess_images"
145
+
146
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/preprocess"
147
+
148
+ def preprocess_images(self, vae: VAE, image: Tensor, latent_size: Tensor):
149
+ # first, resize image to match latents
150
+ image = image.movedim(-1,1)
151
+ image = comfy.utils.common_upscale(image, latent_size["samples"].shape[3] * 8, latent_size["samples"].shape[2] * 8, 'nearest-exact', "center")
152
+ image = image.movedim(1,-1)
153
+ # then, vae encode
154
+ try:
155
+ image = vae.vae_encode_crop_pixels(image)
156
+ except Exception:
157
+ image = VAEEncode.vae_encode_crop_pixels(image)
158
+ encoded = vae.encode(image[:,:,:,:3])
159
+ return (PreprocSparseRGBWrapper(condhint=encoded),)
160
+
161
+
162
+ class SparseWeightExtras:
163
+ @classmethod
164
+ def INPUT_TYPES(s):
165
+ return {
166
+ "optional": {
167
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
168
+ "sparse_hint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
169
+ "sparse_nonhint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
170
+ "sparse_mask_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
171
+ },
172
+ "hidden": {
173
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
174
+ }
175
+ }
176
+
177
+ RETURN_TYPES = ("CN_WEIGHTS_EXTRAS", )
178
+ RETURN_NAMES = ("cn_extras", )
179
+ FUNCTION = "create_weight_extras"
180
+
181
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/extras"
182
+
183
+ def create_weight_extras(self, cn_extras: dict[str]={}, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, sparse_mask_mult=1.0):
184
+ cn_extras = cn_extras.copy()
185
+ cn_extras[SparseConst.HINT_MULT] = sparse_hint_mult
186
+ cn_extras[SparseConst.NONHINT_MULT] = sparse_nonhint_mult
187
+ cn_extras[SparseConst.MASK_MULT] = sparse_mask_mult
188
+ return (cn_extras, )
ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+ import torch
3
+ from .utils import TimestepKeyframe, TimestepKeyframeGroup, ControlWeights, Extras, 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
+ "hidden": {
18
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
19
+ }
20
+ }
21
+
22
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
23
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
24
+ FUNCTION = "load_weights"
25
+
26
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
27
+
28
+ def load_weights(self, cn_extras: dict[str]={}):
29
+ weights = ControlWeights.default(extras=cn_extras)
30
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
31
+
32
+
33
+ class ScaledSoftMaskedUniversalWeights:
34
+ @classmethod
35
+ def INPUT_TYPES(s):
36
+ return {
37
+ "required": {
38
+ "mask": ("MASK", ),
39
+ "min_base_multiplier": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
40
+ "max_base_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
41
+ #"lock_min": ("BOOLEAN", {"default": False}, ),
42
+ #"lock_max": ("BOOLEAN", {"default": False}, ),
43
+ },
44
+ "optional": {
45
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
46
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
47
+ },
48
+ "hidden": {
49
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
50
+ }
51
+ }
52
+
53
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
54
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
55
+ FUNCTION = "load_weights"
56
+
57
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
58
+
59
+ def load_weights(self, mask: Tensor, min_base_multiplier: float, max_base_multiplier: float, lock_min=False, lock_max=False,
60
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
61
+ # normalize mask
62
+ mask = mask.clone()
63
+ x_min = 0.0 if lock_min else mask.min()
64
+ x_max = 1.0 if lock_max else mask.max()
65
+ if x_min == x_max:
66
+ mask = torch.ones_like(mask) * max_base_multiplier
67
+ else:
68
+ mask = linear_conversion(mask, x_min, x_max, min_base_multiplier, max_base_multiplier)
69
+ weights = ControlWeights.universal_mask(weight_mask=mask, uncond_multiplier=uncond_multiplier, extras=cn_extras)
70
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
71
+
72
+
73
+ class ScaledSoftUniversalWeights:
74
+ @classmethod
75
+ def INPUT_TYPES(s):
76
+ return {
77
+ "required": {
78
+ "base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
79
+ },
80
+ "optional": {
81
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
82
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
83
+ },
84
+ "hidden": {
85
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
86
+ }
87
+ }
88
+
89
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
90
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
91
+ FUNCTION = "load_weights"
92
+
93
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
94
+
95
+ def load_weights(self, base_multiplier, uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
96
+ weights = ControlWeights.universal(base_multiplier=base_multiplier, uncond_multiplier=uncond_multiplier, extras=cn_extras)
97
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
98
+
99
+
100
+ class SoftControlNetWeightsSD15:
101
+ @classmethod
102
+ def INPUT_TYPES(s):
103
+ return {
104
+ "required": {
105
+ "output_0": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
106
+ "output_1": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
107
+ "output_2": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
108
+ "output_3": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
109
+ "output_4": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
110
+ "output_5": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
111
+ "output_6": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
112
+ "output_7": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
113
+ "output_8": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
114
+ "output_9": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
115
+ "output_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
116
+ "output_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
117
+ "middle_0": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
118
+ },
119
+ "optional": {
120
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
121
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
122
+ },
123
+ "hidden": {
124
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
125
+ }
126
+ }
127
+
128
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
129
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
130
+ FUNCTION = "load_weights"
131
+
132
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
133
+
134
+ def load_weights(self, output_0, output_1, output_2, output_3, output_4, output_5, output_6,
135
+ output_7, output_8, output_9, output_10, output_11, middle_0,
136
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
137
+ return CustomControlNetWeightsSD15.load_weights(self,
138
+ output_0=output_0, output_1=output_1, output_2=output_2, output_3=output_3,
139
+ output_4=output_4, output_5=output_5, output_6=output_6, output_7=output_7,
140
+ output_8=output_8, output_9=output_9, output_10=output_10, output_11=output_11,
141
+ middle_0=middle_0,
142
+ uncond_multiplier=uncond_multiplier, cn_extras=cn_extras)
143
+
144
+
145
+ class CustomControlNetWeightsSD15:
146
+ @classmethod
147
+ def INPUT_TYPES(s):
148
+ return {
149
+ "required": {
150
+ "output_0": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
151
+ "output_1": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
152
+ "output_2": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
153
+ "output_3": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
154
+ "output_4": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
155
+ "output_5": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
156
+ "output_6": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
157
+ "output_7": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
158
+ "output_8": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
159
+ "output_9": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
160
+ "output_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
161
+ "output_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
162
+ "middle_0": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
163
+ },
164
+ "optional": {
165
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
166
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
167
+ },
168
+ "hidden": {
169
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
170
+ }
171
+ }
172
+
173
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
174
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
175
+ FUNCTION = "load_weights"
176
+
177
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
178
+
179
+ def load_weights(self, output_0, output_1, output_2, output_3, output_4, output_5, output_6,
180
+ output_7, output_8, output_9, output_10, output_11, middle_0,
181
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
182
+ weights_output = [output_0, output_1, output_2, output_3, output_4, output_5, output_6,
183
+ output_7, output_8, output_9, output_10, output_11]
184
+ weights_middle = [middle_0]
185
+ weights = ControlWeights.controlnet(weights_output=weights_output, weights_middle=weights_middle, uncond_multiplier=uncond_multiplier,
186
+ extras=cn_extras, disable_applied_to=True)
187
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
188
+
189
+
190
+ class CustomControlNetWeightsFlux:
191
+ @classmethod
192
+ def INPUT_TYPES(s):
193
+ return {
194
+ "required": {
195
+ "input_0": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
196
+ "input_1": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
197
+ "input_2": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
198
+ "input_3": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
199
+ "input_4": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
200
+ "input_5": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
201
+ "input_6": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
202
+ "input_7": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
203
+ "input_8": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
204
+ "input_9": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
205
+ "input_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
206
+ "input_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
207
+ "input_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
208
+ "input_13": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
209
+ "input_14": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
210
+ "input_15": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
211
+ "input_16": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
212
+ "input_17": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
213
+ "input_18": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
214
+ },
215
+ "optional": {
216
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
217
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
218
+ },
219
+ "hidden": {
220
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
221
+ }
222
+ }
223
+
224
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
225
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
226
+ FUNCTION = "load_weights"
227
+
228
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
229
+
230
+ def load_weights(self, input_0, input_1, input_2, input_3, input_4, input_5, input_6,
231
+ input_7, input_8, input_9, input_10, input_11, input_12, input_13,
232
+ input_14, input_15, input_16, input_17, input_18,
233
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
234
+ weights_input = [input_0, input_1, input_2, input_3, input_4, input_5,
235
+ input_6, input_7, input_8, input_9, input_10, input_11,
236
+ input_12, input_13, input_14, input_15, input_16, input_17, input_18]
237
+ weights = ControlWeights.controlnet(weights_input=weights_input, uncond_multiplier=uncond_multiplier, extras=cn_extras, disable_applied_to=True)
238
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
239
+
240
+
241
+ class SoftT2IAdapterWeights:
242
+ @classmethod
243
+ def INPUT_TYPES(s):
244
+ return {
245
+ "required": {
246
+ "input_0": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
247
+ "input_1": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
248
+ "input_2": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
249
+ "input_3": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
250
+ },
251
+ "optional": {
252
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
253
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
254
+ },
255
+ "hidden": {
256
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
257
+ }
258
+ }
259
+
260
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
261
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
262
+ FUNCTION = "load_weights"
263
+
264
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
265
+
266
+ def load_weights(self, input_0, input_1, input_2, input_3,
267
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
268
+ return CustomT2IAdapterWeights.load_weights(self, input_0=input_0, input_1=input_1, input_2=input_2, input_3=input_3,
269
+ uncond_multiplier=uncond_multiplier, cn_extras=cn_extras)
270
+
271
+
272
+ class CustomT2IAdapterWeights:
273
+ @classmethod
274
+ def INPUT_TYPES(s):
275
+ return {
276
+ "required": {
277
+ "input_0": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
278
+ "input_1": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
279
+ "input_2": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
280
+ "input_3": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
281
+ },
282
+ "optional": {
283
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
284
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
285
+ },
286
+ "hidden": {
287
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
288
+ }
289
+ }
290
+
291
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
292
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
293
+ FUNCTION = "load_weights"
294
+
295
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
296
+
297
+ def load_weights(self, input_0, input_1, input_2, input_3,
298
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
299
+ weights = [input_0, input_1, input_2, input_3]
300
+ weights = get_properly_arranged_t2i_weights(weights)
301
+ weights = ControlWeights.t2iadapter(weights_input=weights, uncond_multiplier=uncond_multiplier, extras=cn_extras, disable_applied_to=True)
302
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
303
+
304
+
305
+ class ExtrasMiddleMultNode:
306
+ @classmethod
307
+ def INPUT_TYPES(s):
308
+ return {
309
+ "required": {
310
+ "middle_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}),
311
+ },
312
+ "optional": {
313
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
314
+ },
315
+ "hidden": {
316
+ "autosize": ("ACNAUTOSIZE", {"padding": 0}),
317
+ }
318
+ }
319
+
320
+ RETURN_TYPES = ("CN_WEIGHTS_EXTRAS",)
321
+ RETURN_NAMES = ("cn_extras",)
322
+ FUNCTION = "create_extras"
323
+
324
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/extras"
325
+
326
+ def create_extras(self, middle_mult: float, cn_extras: dict[str]={}):
327
+ cn_extras = cn_extras.copy()
328
+ cn_extras[Extras.MIDDLE_MULT] = middle_mult
329
+ return (cn_extras,)
ComfyUI-Advanced-ControlNet/adv_control/sampling.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+
3
+ import comfy.hooks
4
+ import comfy.model_patcher
5
+ import comfy.patcher_extension
6
+ import comfy.sample
7
+ import comfy.samplers
8
+ from comfy.model_patcher import ModelPatcher
9
+ from comfy.controlnet import ControlBase
10
+ from comfy.ldm.modules.attention import BasicTransformerBlock
11
+
12
+
13
+ from .control import convert_all_to_advanced, restore_all_controlnet_conns
14
+ from .control_reference import (ReferenceAdvanced, ReferenceInjections,
15
+ RefBasicTransformerBlock, RefTimestepEmbedSequential,
16
+ InjectionBasicTransformerBlockHolder, InjectionTimestepEmbedSequentialHolder,
17
+ _forward_inject_BasicTransformerBlock,
18
+ handle_context_ref_setup, handle_reference_injection,
19
+ REF_CONTROL_LIST_ALL, CONTEXTREF_CLEAN_FUNC)
20
+ from .dinklink import get_dinklink
21
+ from .utils import torch_dfs, WrapperConsts, CURRENT_WRAPPER_VERSION
22
+
23
+ def prepare_dinklink_acn_wrapper():
24
+ # expose acn_sampler_sample_wrapper
25
+ d = get_dinklink()
26
+ link_acn = d.setdefault(WrapperConsts.ACN, {})
27
+ link_acn[WrapperConsts.VERSION] = CURRENT_WRAPPER_VERSION
28
+ link_acn[WrapperConsts.ACN_CREATE_SAMPLER_SAMPLE_WRAPPER] = (comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
29
+ WrapperConsts.ACN_OUTER_SAMPLE_WRAPPER_KEY,
30
+ acn_outer_sample_wrapper)
31
+
32
+
33
+ def support_sliding_context_windows(conds) -> tuple[bool, list[dict]]:
34
+ # convert to advanced, with report if anything was actually modified
35
+ modified, new_conds = convert_all_to_advanced(conds)
36
+ return modified, new_conds
37
+
38
+
39
+ def has_sliding_context_windows(model: ModelPatcher):
40
+ params = model.get_attachment("ADE_params")
41
+ if params is None:
42
+ # backwards compatibility
43
+ params = getattr(model, "motion_injection_params", None)
44
+ if params is None:
45
+ return False
46
+ context_options = getattr(params, "context_options")
47
+ return context_options.context_length is not None
48
+
49
+
50
+ def get_contextref_obj(model: ModelPatcher):
51
+ params = model.get_attachment("ADE_params")
52
+ if params is None:
53
+ # backwards compatibility
54
+ params = getattr(model, "motion_injection_params", None)
55
+ if params is None:
56
+ return None
57
+ context_options = getattr(params, "context_options")
58
+ extras = getattr(context_options, "extras", None)
59
+ if extras is None:
60
+ return None
61
+ return getattr(extras, "context_ref", None)
62
+
63
+
64
+ def get_refcn(control: ControlBase, order: int=-1):
65
+ ref_set: set[ReferenceAdvanced] = set()
66
+ if control is None:
67
+ return ref_set
68
+ if type(control) == ReferenceAdvanced and not control.is_context_ref:
69
+ control.order = order
70
+ order -= 1
71
+ ref_set.add(control)
72
+ ref_set.update(get_refcn(control.previous_controlnet, order=order))
73
+ return ref_set
74
+
75
+
76
+ def should_register_outer_sample_wrapper(hook, model, model_options: dict, target, registered: list):
77
+ wrappers = comfy.patcher_extension.get_wrappers_with_key(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
78
+ WrapperConsts.ACN_OUTER_SAMPLE_WRAPPER_KEY,
79
+ model_options, is_model_options=True)
80
+ return len(wrappers) == 0
81
+
82
+ def create_wrapper_hooks():
83
+ wrappers = {}
84
+ comfy.patcher_extension.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
85
+ WrapperConsts.ACN_OUTER_SAMPLE_WRAPPER_KEY,
86
+ acn_outer_sample_wrapper,
87
+ transformer_options=wrappers)
88
+ hooks = comfy.hooks.HookGroup()
89
+ hook = comfy.hooks.WrapperHook(wrappers)
90
+ hook.hook_id = WrapperConsts.ACN_OUTER_SAMPLE_WRAPPER_KEY
91
+ hook.custom_should_register = should_register_outer_sample_wrapper
92
+ hooks.add(hook)
93
+ return hooks
94
+
95
+ def acn_outer_sample_wrapper(executor, *args, **kwargs):
96
+ controlnets_modified = False
97
+ guider: comfy.samplers.CFGGuider = executor.class_obj
98
+ model = guider.model_patcher
99
+ orig_conds = guider.conds
100
+ orig_model_options = guider.model_options
101
+ try:
102
+ new_model_options = orig_model_options
103
+ # if context options present, perform some special actions that may be required
104
+ context_refs = []
105
+ if has_sliding_context_windows(guider.model_patcher):
106
+ new_model_options = comfy.model_patcher.create_model_options_clone(new_model_options)
107
+ # convert all CNs to Advanced if needed
108
+ controlnets_modified, conds = support_sliding_context_windows(orig_conds)
109
+ if controlnets_modified:
110
+ guider.conds = conds
111
+ # enable ContextRef, if requested
112
+ existing_contextref_obj = get_contextref_obj(guider.model_patcher)
113
+ if existing_contextref_obj is not None:
114
+ context_refs = handle_context_ref_setup(existing_contextref_obj, new_model_options["transformer_options"], guider.conds)
115
+ controlnets_modified = True
116
+ # look for Advanced ControlNets that will require intervention to work
117
+ ref_set = set()
118
+ for outer_cond in guider.conds.values():
119
+ for cond in outer_cond:
120
+ if "control" in cond:
121
+ ref_set.update(get_refcn(cond["control"]))
122
+ # if no ref cn found, do original function immediately
123
+ if len(ref_set) == 0 and len(context_refs) == 0:
124
+ return executor(*args, **kwargs)
125
+ # otherwise, injection time
126
+ try:
127
+ # inject
128
+ # storage for all Reference-related injections
129
+ reference_injections = ReferenceInjections()
130
+
131
+ # first, handle attn module injection
132
+ all_modules = torch_dfs(model.model)
133
+ attn_modules: list[RefBasicTransformerBlock] = []
134
+ for module in all_modules:
135
+ if isinstance(module, BasicTransformerBlock):
136
+ attn_modules.append(module)
137
+ attn_modules = [module for module in all_modules if isinstance(module, BasicTransformerBlock)]
138
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
139
+ for i, module in enumerate(attn_modules):
140
+ injection_holder = InjectionBasicTransformerBlockHolder(block=module, idx=i)
141
+ injection_holder.attn_weight = float(i) / float(len(attn_modules))
142
+ if hasattr(module, "_forward"): # backward compatibility
143
+ module._forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
144
+ else:
145
+ module.forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
146
+ module.injection_holder = injection_holder
147
+ reference_injections.attn_modules.append(module)
148
+ # figure out which module is middle block
149
+ if hasattr(model.model.diffusion_model, "middle_block"):
150
+ mid_modules = torch_dfs(model.model.diffusion_model.middle_block)
151
+ mid_attn_modules: list[RefBasicTransformerBlock] = [module for module in mid_modules if isinstance(module, BasicTransformerBlock)]
152
+ for module in mid_attn_modules:
153
+ module.injection_holder.is_middle = True
154
+
155
+ # next, handle gn module injection (TimestepEmbedSequential)
156
+ # TODO: figure out the logic behind these hardcoded indexes
157
+ if type(model.model).__name__ == "SDXL":
158
+ input_block_indices = [4, 5, 7, 8]
159
+ output_block_indices = [0, 1, 2, 3, 4, 5]
160
+ else:
161
+ input_block_indices = [4, 5, 7, 8, 10, 11]
162
+ output_block_indices = [0, 1, 2, 3, 4, 5, 6, 7]
163
+ if hasattr(model.model.diffusion_model, "middle_block"):
164
+ module = model.model.diffusion_model.middle_block
165
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=0, is_middle=True)
166
+ injection_holder.gn_weight = 0.0
167
+ module.injection_holder = injection_holder
168
+ reference_injections.gn_modules.append(module)
169
+ for w, i in enumerate(input_block_indices):
170
+ module = model.model.diffusion_model.input_blocks[i]
171
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_input=True)
172
+ injection_holder.gn_weight = 1.0 - float(w) / float(len(input_block_indices))
173
+ module.injection_holder = injection_holder
174
+ reference_injections.gn_modules.append(module)
175
+ for w, i in enumerate(output_block_indices):
176
+ module = model.model.diffusion_model.output_blocks[i]
177
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_output=True)
178
+ injection_holder.gn_weight = float(w) / float(len(output_block_indices))
179
+ module.injection_holder = injection_holder
180
+ reference_injections.gn_modules.append(module)
181
+ # hack gn_module forwards and update weights
182
+ for i, module in enumerate(reference_injections.gn_modules):
183
+ module.injection_holder.gn_weight *= 2
184
+
185
+ # store ordered ref cns in model's transformer options
186
+ new_model_options = comfy.model_patcher.create_model_options_clone(new_model_options)
187
+ # handle diffusion_model forward injection
188
+ handle_reference_injection(new_model_options, reference_injections)
189
+
190
+ ref_list: list[ReferenceAdvanced] = list(ref_set)
191
+ new_model_options["transformer_options"][REF_CONTROL_LIST_ALL] = sorted(ref_list, key=lambda x: x.order)
192
+ new_model_options["transformer_options"][CONTEXTREF_CLEAN_FUNC] = reference_injections.clean_contextref_module_mem
193
+ guider.model_options = new_model_options
194
+ # continue with original function
195
+ return executor(*args, **kwargs)
196
+ finally:
197
+ # cleanup injections
198
+ # restore attn modules
199
+ attn_modules: list[RefBasicTransformerBlock] = reference_injections.attn_modules
200
+ for module in attn_modules:
201
+ module.injection_holder.restore(module)
202
+ module.injection_holder.clean_all()
203
+ del module.injection_holder
204
+ del attn_modules
205
+ # restore gn modules
206
+ gn_modules: list[RefTimestepEmbedSequential] = reference_injections.gn_modules
207
+ for module in gn_modules:
208
+ module.injection_holder.restore(module)
209
+ module.injection_holder.clean_all()
210
+ del module.injection_holder
211
+ del gn_modules
212
+ # cleanup
213
+ reference_injections.cleanup()
214
+ finally:
215
+ # restore model_options
216
+ guider.model_options = orig_model_options
217
+ # restore guider.conds
218
+ guider.conds = orig_conds
219
+ # restore controlnets in conds, if needed
220
+ if controlnets_modified:
221
+ restore_all_controlnet_conns(guider.conds)
222
+ del orig_conds
223
+ del orig_model_options
224
+ del model
225
+ del guider
ComfyUI-Advanced-ControlNet/adv_control/utils.py ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from einops import rearrange
7
+ import numpy as np
8
+ import math
9
+
10
+ import comfy.ops
11
+ import comfy.utils
12
+
13
+ from comfy.controlnet import ControlBase
14
+ from comfy.model_patcher import ModelPatcher
15
+ from comfy.sd import VAE
16
+
17
+ from .logger import logger
18
+
19
+ BIGMIN = -(2**53-1)
20
+ BIGMAX = (2**53-1)
21
+ BIGMAX_TENSOR = torch.tensor(9999999999.9)
22
+
23
+ ORIG_PREVIOUS_CONTROLNET = "_orig_previous_controlnet"
24
+ CONTROL_INIT_BY_ACN = "_control_init_by_ACN"
25
+
26
+ class Extras:
27
+ MIDDLE_MULT = "middle_mult"
28
+
29
+
30
+ def load_torch_file_with_dict_factory(controlnet_data: dict[str, Tensor], orig_load_torch_file: Callable):
31
+ def load_torch_file_with_dict(*args, **kwargs):
32
+ # immediately restore load_torch_file to original version
33
+ comfy.utils.load_torch_file = orig_load_torch_file
34
+ return controlnet_data
35
+ return load_torch_file_with_dict
36
+
37
+
38
+ CURRENT_WRAPPER_VERSION = 10002
39
+
40
+ class WrapperConsts:
41
+ ACN = "ACN"
42
+ VERSION = "version"
43
+ ACN_OUTER_SAMPLE_WRAPPER_KEY = "ACN_outer_sample_wrapper"
44
+ ACN_CREATE_SAMPLER_SAMPLE_WRAPPER = "create_outer_sample_wrapper"
45
+
46
+
47
+ def get_properly_arranged_t2i_weights(initial_weights: list[float]):
48
+ new_weights = []
49
+ new_weights.extend([initial_weights[0]]*3)
50
+ new_weights.extend([initial_weights[1]]*3)
51
+ new_weights.extend([initial_weights[2]]*3)
52
+ new_weights.extend([initial_weights[3]]*3)
53
+ return new_weights
54
+
55
+
56
+ class ControlWeightType:
57
+ DEFAULT = "default"
58
+ UNIVERSAL = "universal"
59
+ T2IADAPTER = "t2iadapter"
60
+ CONTROLNET = "controlnet"
61
+ CONTROLNETPLUSPLUS = "controlnet++"
62
+ CONTROLLORA = "controllora"
63
+ CONTROLLLLITE = "controllllite"
64
+ SVD_CONTROLNET = "svd_controlnet"
65
+ SPARSECTRL = "sparsectrl"
66
+ CTRLORA = "ctrlora"
67
+
68
+
69
+ class ControlWeights:
70
+ def __init__(self, weight_type: str, base_multiplier: float=1.0,
71
+ weights_input: list[float]=None, weights_middle: list[float]=None, weights_output: list[float]=None,
72
+ weight_func: Callable=None, weight_mask: Tensor=None,
73
+ uncond_multiplier=1.0, uncond_mask: Tensor=None,
74
+ extras: dict[str]={}, disable_applied_to=False):
75
+ self.weight_type = weight_type
76
+ self.base_multiplier = base_multiplier
77
+ self.weights_input = weights_input
78
+ self.weights_middle = weights_middle
79
+ self.weights_output = weights_output
80
+ self.weight_func = weight_func
81
+ self.weight_mask = weight_mask
82
+ self.uncond_multiplier = float(uncond_multiplier)
83
+ self.has_uncond_multiplier = not math.isclose(self.uncond_multiplier, 1.0)
84
+ self.uncond_mask = uncond_mask if uncond_mask is not None else 1.0
85
+ self.has_uncond_mask = uncond_mask is not None
86
+ self.extras = extras.copy()
87
+ self.disable_applied_to = disable_applied_to
88
+
89
+ def get(self, idx: int, control: dict[str, list[Tensor]], key: str, default=1.0) -> Union[float, Tensor]:
90
+ # if weight_func present, use it
91
+ if self.weight_func is not None:
92
+ return self.weight_func(idx=idx, control=control, key=key)
93
+ effective_mult = 1.0
94
+ # if weights is not none, return index
95
+ relevant_weights = None
96
+ if key == "middle":
97
+ relevant_weights = self.weights_middle
98
+ effective_mult *= self.extras.get(Extras.MIDDLE_MULT, 1.0)
99
+ elif key == "input":
100
+ relevant_weights = self.weights_input
101
+ if relevant_weights is not None:
102
+ relevant_weights = list(reversed(relevant_weights))
103
+ else:
104
+ relevant_weights = self.weights_output
105
+ if relevant_weights is None:
106
+ return default * effective_mult
107
+ elif idx >= len(relevant_weights):
108
+ return default * effective_mult
109
+ return relevant_weights[idx] * effective_mult
110
+
111
+ def copy_with_new_weights(self, new_weights_input: list[float]=None, new_weights_middle: list[float]=None, new_weights_output: list[float]=None,
112
+ new_weight_func: Callable=None):
113
+ return ControlWeights(weight_type=self.weight_type, base_multiplier=self.base_multiplier,
114
+ weights_input=new_weights_input, weights_middle=new_weights_middle, weights_output=new_weights_output,
115
+ weight_func=new_weight_func, weight_mask=self.weight_mask,
116
+ uncond_multiplier=self.uncond_multiplier,
117
+ extras=self.extras, disable_applied_to=self.disable_applied_to)
118
+
119
+ @classmethod
120
+ def default(cls, extras: dict[str]={}):
121
+ return cls(ControlWeightType.DEFAULT, extras=extras)
122
+
123
+ @classmethod
124
+ def universal(cls, base_multiplier: float, uncond_multiplier: float=1.0, extras: dict[str]={}):
125
+ return cls(ControlWeightType.UNIVERSAL, base_multiplier=base_multiplier, uncond_multiplier=uncond_multiplier, disable_applied_to=True, extras=extras)
126
+
127
+ @classmethod
128
+ def universal_mask(cls, weight_mask: Tensor, uncond_multiplier: float=1.0, extras: dict[str]={}):
129
+ return cls(ControlWeightType.UNIVERSAL, weight_mask=weight_mask, uncond_multiplier=uncond_multiplier, disable_applied_to=True, extras=extras)
130
+
131
+ @classmethod
132
+ def t2iadapter(cls, weights_input: list[float]=None, uncond_multiplier: float=1.0, extras: dict[str]={}, disable_applied_to=False):
133
+ return cls(ControlWeightType.T2IADAPTER, weights_input=weights_input, uncond_multiplier=uncond_multiplier, extras=extras, disable_applied_to=disable_applied_to)
134
+
135
+ @classmethod
136
+ def controlnet(cls, weights_output: list[float]=None, weights_middle: list[float]=None, weights_input: list[float]=None, uncond_multiplier: float=1.0, extras: dict[str]={}, disable_applied_to=False):
137
+ return cls(ControlWeightType.CONTROLNET, weights_output=weights_output, weights_middle=weights_middle, weights_input=weights_input, uncond_multiplier=uncond_multiplier, extras=extras, disable_applied_to=disable_applied_to)
138
+
139
+ @classmethod
140
+ def controllora(cls, weights_output: list[float]=None, weights_middle: list[float]=None, weights_input: list[float]=None, uncond_multiplier: float=1.0, extras: dict[str]={}, disable_applied_to=False):
141
+ return cls(ControlWeightType.CONTROLLORA, weights_output=weights_output, weights_middle=weights_middle, weights_input=weights_input, uncond_multiplier=uncond_multiplier, extras=extras, disable_applied_to=disable_applied_to)
142
+
143
+ @classmethod
144
+ def controllllite(cls, weights_output: list[float]=None, weights_middle: list[float]=None, weights_input: list[float]=None, uncond_multiplier: float=1.0, extras: dict[str]={}, disable_applied_to=False):
145
+ return cls(ControlWeightType.CONTROLLLLITE, weights_output=weights_output, weights_middle=weights_middle, weights_input=weights_input, uncond_multiplier=uncond_multiplier, extras=extras, disable_applied_to=disable_applied_to)
146
+
147
+
148
+ class StrengthInterpolation:
149
+ LINEAR = "linear"
150
+ EASE_IN = "ease-in"
151
+ EASE_OUT = "ease-out"
152
+ EASE_IN_OUT = "ease-in-out"
153
+ NONE = "none"
154
+
155
+ _LIST = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT]
156
+ _LIST_WITH_NONE = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT, NONE]
157
+
158
+ @classmethod
159
+ def get_weights(cls, num_from: float, num_to: float, length: int, method: str, reverse=False):
160
+ diff = num_to - num_from
161
+ if method == cls.LINEAR:
162
+ weights = torch.linspace(num_from, num_to, length)
163
+ elif method == cls.EASE_IN:
164
+ index = torch.linspace(0, 1, length)
165
+ weights = diff * np.power(index, 2) + num_from
166
+ elif method == cls.EASE_OUT:
167
+ index = torch.linspace(0, 1, length)
168
+ weights = diff * (1 - np.power(1 - index, 2)) + num_from
169
+ elif method == cls.EASE_IN_OUT:
170
+ index = torch.linspace(0, 1, length)
171
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + num_from
172
+ else:
173
+ raise ValueError(f"Unrecognized interpolation method '{method}'.")
174
+ if reverse:
175
+ weights = weights.flip(dims=(0,))
176
+ return weights
177
+
178
+
179
+ class LatentKeyframe:
180
+ def __init__(self, batch_index: int, strength: float) -> None:
181
+ self.batch_index = batch_index
182
+ self.strength = strength
183
+
184
+
185
+ # always maintain sorted state (by batch_index of LatentKeyframe)
186
+ class LatentKeyframeGroup:
187
+ def __init__(self) -> None:
188
+ self.keyframes: list[LatentKeyframe] = []
189
+
190
+ def add(self, keyframe: LatentKeyframe) -> None:
191
+ added = False
192
+ # replace existing keyframe if same batch_index
193
+ for i in range(len(self.keyframes)):
194
+ if self.keyframes[i].batch_index == keyframe.batch_index:
195
+ self.keyframes[i] = keyframe
196
+ added = True
197
+ break
198
+ if not added:
199
+ self.keyframes.append(keyframe)
200
+ self.keyframes.sort(key=lambda k: k.batch_index)
201
+
202
+ def get_index(self, index: int) -> Union[LatentKeyframe, None]:
203
+ try:
204
+ return self.keyframes[index]
205
+ except IndexError:
206
+ return None
207
+
208
+ def __getitem__(self, index) -> LatentKeyframe:
209
+ return self.keyframes[index]
210
+
211
+ def is_empty(self) -> bool:
212
+ return len(self.keyframes) == 0
213
+
214
+ def clone(self) -> 'LatentKeyframeGroup':
215
+ cloned = LatentKeyframeGroup()
216
+ for tk in self.keyframes:
217
+ cloned.add(tk)
218
+ return cloned
219
+
220
+
221
+ class TimestepKeyframe:
222
+ def __init__(self,
223
+ start_percent: float = 0.0,
224
+ strength: float = 1.0,
225
+ control_weights: ControlWeights = None,
226
+ latent_keyframes: LatentKeyframeGroup = None,
227
+ null_latent_kf_strength: float = 0.0,
228
+ inherit_missing: bool = True,
229
+ guarantee_steps: int = 1,
230
+ mask_hint_orig: Tensor = None) -> None:
231
+ self.start_percent = float(start_percent)
232
+ self.start_t = 999999999.9
233
+ self.strength = strength
234
+ self.control_weights = control_weights
235
+ self.latent_keyframes = latent_keyframes
236
+ self.null_latent_kf_strength = null_latent_kf_strength
237
+ self.inherit_missing = inherit_missing
238
+ self.guarantee_steps = guarantee_steps
239
+ self.mask_hint_orig = mask_hint_orig
240
+
241
+ def has_control_weights(self):
242
+ return self.control_weights is not None
243
+
244
+ def has_latent_keyframes(self):
245
+ return self.latent_keyframes is not None
246
+
247
+ def has_mask_hint(self):
248
+ return self.mask_hint_orig is not None
249
+
250
+ def get_effective_guarantee_steps(self, max_sigma: torch.Tensor):
251
+ '''If keyframe starts before current sampling range (max_sigma), treat as 0.'''
252
+ if self.start_t > max_sigma:
253
+ return 0
254
+ return self.guarantee_steps
255
+
256
+ @staticmethod
257
+ def default() -> 'TimestepKeyframe':
258
+ return TimestepKeyframe(start_percent=0.0, guarantee_steps=0)
259
+
260
+
261
+ # always maintain sorted state (by start_percent of TimestepKeyFrame)
262
+ class TimestepKeyframeGroup:
263
+ def __init__(self, add_default=True) -> None:
264
+ self.keyframes: list[TimestepKeyframe] = []
265
+ if add_default:
266
+ self.keyframes.append(TimestepKeyframe.default())
267
+
268
+ def add(self, keyframe: TimestepKeyframe) -> None:
269
+ # add to end of list, then sort
270
+ self.keyframes.append(keyframe)
271
+ self.keyframes = get_sorted_list_via_attr(self.keyframes, attr="start_percent")
272
+
273
+ def get_index(self, index: int) -> Union[TimestepKeyframe, None]:
274
+ try:
275
+ return self.keyframes[index]
276
+ except IndexError:
277
+ return None
278
+
279
+ def has_index(self, index: int) -> int:
280
+ return index >=0 and index < len(self.keyframes)
281
+
282
+ def __getitem__(self, index) -> TimestepKeyframe:
283
+ return self.keyframes[index]
284
+
285
+ def __len__(self) -> int:
286
+ return len(self.keyframes)
287
+
288
+ def is_empty(self) -> bool:
289
+ return len(self.keyframes) == 0
290
+
291
+ def clone(self) -> 'TimestepKeyframeGroup':
292
+ cloned = TimestepKeyframeGroup(add_default=False)
293
+ # already sorted, so don't use add function to make cloning quicker
294
+ for tk in self.keyframes:
295
+ cloned.keyframes.append(tk)
296
+ return cloned
297
+
298
+ @classmethod
299
+ def default(cls, keyframe: TimestepKeyframe) -> 'TimestepKeyframeGroup':
300
+ group = cls()
301
+ group.keyframes[0] = keyframe
302
+ return group
303
+
304
+
305
+ class AbstractPreprocWrapper:
306
+ 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."
307
+ def __init__(self, condhint):
308
+ self.condhint = condhint
309
+
310
+ def movedim(self, *args, **kwargs):
311
+ return self
312
+
313
+ def __getattr__(self, *args, **kwargs):
314
+ raise AttributeError(self.error_msg)
315
+
316
+ def __setattr__(self, name, value):
317
+ if name != "condhint":
318
+ raise AttributeError(self.error_msg)
319
+ super().__setattr__(name, value)
320
+
321
+ def __iter__(self, *args, **kwargs):
322
+ raise AttributeError(self.error_msg)
323
+
324
+ def __next__(self, *args, **kwargs):
325
+ raise AttributeError(self.error_msg)
326
+
327
+ def __len__(self, *args, **kwargs):
328
+ raise AttributeError(self.error_msg)
329
+
330
+ def __getitem__(self, *args, **kwargs):
331
+ raise AttributeError(self.error_msg)
332
+
333
+ def __setitem__(self, *args, **kwargs):
334
+ raise AttributeError(self.error_msg)
335
+
336
+
337
+ # depending on model, AnimateDiff may inject into GroupNorm, so make sure GroupNorm will be clean
338
+ class disable_weight_init_clean_groupnorm(comfy.ops.disable_weight_init):
339
+ class GroupNorm(comfy.ops.disable_weight_init.GroupNorm):
340
+ def forward_comfy_cast_weights(self, input):
341
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
342
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
343
+
344
+ def forward(self, input):
345
+ if self.comfy_cast_weights:
346
+ return self.forward_comfy_cast_weights(input)
347
+ else:
348
+ return torch.nn.functional.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
349
+
350
+ class manual_cast_clean_groupnorm(comfy.ops.manual_cast):
351
+ class GroupNorm(disable_weight_init_clean_groupnorm.GroupNorm):
352
+ comfy_cast_weights = True
353
+
354
+
355
+ # adapted from comfy/sample.py
356
+ def prepare_mask_batch(mask: Tensor, shape: Tensor, multiplier: int=1, match_dim1=False, match_shape=False, flux_shape=None):
357
+ mask = mask.clone()
358
+ if flux_shape is not None:
359
+ multiplier = multiplier * 0.5
360
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(round(flux_shape[-2]*multiplier), round(flux_shape[-1]*multiplier)), mode="bilinear")
361
+ mask = rearrange(mask, "b c h w -> b (h w) c")
362
+ else:
363
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(round(shape[-2]*multiplier), round(shape[-1]*multiplier)), mode="bilinear")
364
+ if match_dim1:
365
+ if match_shape and len(shape) < 4:
366
+ raise Exception(f"match_dim1 cannot be True if shape is under 4 dims; was {len(shape)}.")
367
+ mask = torch.cat([mask] * shape[1], dim=1)
368
+ if match_shape and len(shape) == 3 and len(mask.shape) != 3:
369
+ mask = mask.squeeze(1)
370
+ return mask
371
+
372
+
373
+ # applies min-max normalization, from:
374
+ # https://stackoverflow.com/questions/68791508/min-max-normalization-of-a-tensor-in-pytorch
375
+ def normalize_min_max(x: Tensor, new_min = 0.0, new_max = 1.0):
376
+ x_min, x_max = x.min(), x.max()
377
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
378
+
379
+ def linear_conversion(x, x_min=0.0, x_max=1.0, new_min=0.0, new_max=1.0):
380
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
381
+
382
+ def extend_to_batch_size(tensor: Tensor, batch_size: int):
383
+ if tensor.shape[0] > batch_size:
384
+ return tensor[:batch_size]
385
+ elif tensor.shape[0] < batch_size:
386
+ remainder = batch_size-tensor.shape[0]
387
+ return torch.cat([tensor] + [tensor[-1:]]*remainder, dim=0)
388
+ return tensor
389
+
390
+ def broadcast_image_to_extend(tensor, target_batch_size, batched_number, except_one=True):
391
+ current_batch_size = tensor.shape[0]
392
+ #print(current_batch_size, target_batch_size)
393
+ if except_one and current_batch_size == 1:
394
+ return tensor
395
+
396
+ per_batch = target_batch_size // batched_number
397
+ tensor = tensor[:per_batch]
398
+
399
+ if per_batch > tensor.shape[0]:
400
+ tensor = extend_to_batch_size(tensor=tensor, batch_size=per_batch)
401
+
402
+ current_batch_size = tensor.shape[0]
403
+ if current_batch_size == target_batch_size:
404
+ return tensor
405
+ else:
406
+ return torch.cat([tensor] * batched_number, dim=0)
407
+
408
+
409
+ # from https://stackoverflow.com/a/24621200
410
+ def deepcopy_with_sharing(obj, shared_attribute_names, memo=None):
411
+ '''
412
+ Deepcopy an object, except for a given list of attributes, which should
413
+ be shared between the original object and its copy.
414
+
415
+ obj is some object
416
+ shared_attribute_names: A list of strings identifying the attributes that
417
+ should be shared between the original and its copy.
418
+ memo is the dictionary passed into __deepcopy__. Ignore this argument if
419
+ not calling from within __deepcopy__.
420
+ '''
421
+ assert isinstance(shared_attribute_names, (list, tuple))
422
+
423
+ shared_attributes = {k: getattr(obj, k) for k in shared_attribute_names}
424
+
425
+ if hasattr(obj, '__deepcopy__'):
426
+ # Do hack to prevent infinite recursion in call to deepcopy
427
+ deepcopy_method = obj.__deepcopy__
428
+ obj.__deepcopy__ = None
429
+
430
+ for attr in shared_attribute_names:
431
+ del obj.__dict__[attr]
432
+
433
+ clone = deepcopy(obj)
434
+
435
+ for attr, val in shared_attributes.items():
436
+ setattr(obj, attr, val)
437
+ setattr(clone, attr, val)
438
+
439
+ if hasattr(obj, '__deepcopy__'):
440
+ # Undo hack
441
+ obj.__deepcopy__ = deepcopy_method
442
+ del clone.__deepcopy__
443
+
444
+ return clone
445
+
446
+
447
+ def get_sorted_list_via_attr(objects: list, attr: str) -> list:
448
+ if not objects:
449
+ return objects
450
+ elif len(objects) <= 1:
451
+ return [x for x in objects]
452
+ # now that we know we have to sort, do it following these rules:
453
+ # a) if objects have same value of attribute, maintain their relative order
454
+ # b) perform sorting of the groups of objects with same attributes
455
+ unique_attrs = {}
456
+ for o in objects:
457
+ val_attr = getattr(o, attr)
458
+ attr_list: list = unique_attrs.get(val_attr, list())
459
+ attr_list.append(o)
460
+ if val_attr not in unique_attrs:
461
+ unique_attrs[val_attr] = attr_list
462
+ # now that we have the unique attr values grouped together in relative order, sort them by key
463
+ sorted_attrs = dict(sorted(unique_attrs.items()))
464
+ # now flatten out the dict into a list to return
465
+ sorted_list = []
466
+ for object_list in sorted_attrs.values():
467
+ sorted_list.extend(object_list)
468
+ return sorted_list
469
+
470
+
471
+ # DFS Search for Torch.nn.Module, Written by Lvmin
472
+ def torch_dfs(model: torch.nn.Module):
473
+ result = [model]
474
+ for child in model.children():
475
+ result += torch_dfs(child)
476
+ return result
477
+
478
+
479
+ class WeightTypeException(TypeError):
480
+ "Raised when weight not compatible with AdvancedControlBase object"
481
+ pass
482
+
483
+
484
+ class AdvancedControlBase:
485
+ ACN_VERSION = CURRENT_WRAPPER_VERSION
486
+
487
+ def __init__(self, base: ControlBase, timestep_keyframes: TimestepKeyframeGroup, weights_default: ControlWeights, require_vae=False, allow_condhint_latents=False):
488
+ self.base = base
489
+ self.compatible_weights = [ControlWeightType.UNIVERSAL, ControlWeightType.DEFAULT]
490
+ self.add_compatible_weight(weights_default.weight_type)
491
+ # mask for which parts of controlnet output to keep
492
+ self.mask_cond_hint_original = None
493
+ self.mask_cond_hint = None
494
+ self.tk_mask_cond_hint_original = None
495
+ self.tk_mask_cond_hint = None
496
+ self.weight_mask_cond_hint = None
497
+ # actual index values
498
+ self.sub_idxs = None
499
+ self.full_latent_length = 0
500
+ self.context_length = 0
501
+ # timesteps
502
+ self.t: float = None
503
+ self.prev_t: float = None
504
+ self.batched_number: int = None
505
+ self.batch_size: int = 0
506
+ self.cond_or_uncond: list[int] = None
507
+ # weights + override
508
+ self.weights: ControlWeights = None
509
+ self.weights_default: ControlWeights = weights_default
510
+ self.weights_override: ControlWeights = None
511
+ # latent keyframe + override
512
+ self.latent_keyframes: LatentKeyframeGroup = None
513
+ self.latent_keyframe_override: LatentKeyframeGroup = None
514
+ # initialize timestep_keyframes
515
+ self.set_timestep_keyframes(timestep_keyframes)
516
+ # override some functions
517
+ self.get_control = self.get_control_inject
518
+ self.control_merge = self.control_merge_inject
519
+ self.pre_run = self.pre_run_inject
520
+ self.cleanup = self.cleanup_inject
521
+ self.set_previous_controlnet = self.set_previous_controlnet_inject
522
+ self.set_cond_hint = self.set_cond_hint_inject
523
+ # vae to store
524
+ self.adv_vae = None
525
+ self.mult_by_ratio_when_vae = True
526
+ # compression ratio stuff
527
+ self.real_compression_ratio = None
528
+ # require model/vae to be passed into Apply Advanced ControlNet 🛂🅐🅒🅝 node
529
+ self.require_vae = require_vae
530
+ self.allow_condhint_latents = allow_condhint_latents
531
+ self.postpone_condhint_latents_check = False
532
+ # disarm - when set to False, used to force usage of Apply Advanced ControlNet 🛂🅐🅒🅝 node (which will set it to True)
533
+ self.disarmed = True
534
+
535
+ def add_compatible_weight(self, control_weight_type: str):
536
+ self.compatible_weights.append(control_weight_type)
537
+
538
+ def verify_all_weights(self, throw_error=True):
539
+ # first, check if override exists - if so, only need to check the override
540
+ if self.weights_override is not None:
541
+ if self.weights_override.weight_type not in self.compatible_weights:
542
+ msg = f"Weight override is type {self.weights_override.weight_type}, but loaded {type(self).__name__}" + \
543
+ f"only supports {self.compatible_weights} weights."
544
+ raise WeightTypeException(msg)
545
+ # otherwise, check all timestep keyframe weights
546
+ else:
547
+ for tk in self.timestep_keyframes.keyframes:
548
+ if tk.has_control_weights() and tk.control_weights.weight_type not in self.compatible_weights:
549
+ msg = f"Weight on Timestep Keyframe with start_percent={tk.start_percent} is type " + \
550
+ f"{tk.control_weights.weight_type}, but loaded {type(self).__name__} only supports {self.compatible_weights} weights."
551
+ raise WeightTypeException(msg)
552
+
553
+ def set_timestep_keyframes(self, timestep_keyframes: TimestepKeyframeGroup):
554
+ self.timestep_keyframes = timestep_keyframes if timestep_keyframes else TimestepKeyframeGroup()
555
+ # prepare first timestep_keyframe related stuff
556
+ self._current_timestep_keyframe = None
557
+ self._current_timestep_index = -1
558
+ self._current_used_steps = 0
559
+ self.weights = None
560
+ self.latent_keyframes = None
561
+
562
+ def prepare_current_timestep(self, t: Tensor, transformer_options: dict[str, torch.Tensor]):
563
+ self.t = float(t[0])
564
+ # check if t has changed (otherwise do nothing, as step already accounted for)
565
+ if self.t == self.prev_t:
566
+ return
567
+ # get current step percent
568
+ curr_t: float = self.t
569
+ prev_index = self._current_timestep_index
570
+ max_sigma = torch.max(transformer_options.get("sample_sigmas", BIGMAX_TENSOR))
571
+ # if met guaranteed steps (or no current keyframe), look for next keyframe in case need to switch
572
+ if self._current_timestep_keyframe is None or self._current_used_steps >= self._current_timestep_keyframe.get_effective_guarantee_steps(max_sigma):
573
+ # if has next index, loop through and see if need to switch
574
+ if self.timestep_keyframes.has_index(self._current_timestep_index+1):
575
+ for i in range(self._current_timestep_index+1, len(self.timestep_keyframes)):
576
+ eval_tk = self.timestep_keyframes[i]
577
+ # check if start percent is less or equal to curr_t
578
+ if eval_tk.start_t >= curr_t:
579
+ self._current_timestep_index = i
580
+ self._current_timestep_keyframe = eval_tk
581
+ self._current_used_steps = 0
582
+ # keep track of control weights, latent keyframes, and masks,
583
+ # accounting for inherit_missing
584
+ if self._current_timestep_keyframe.has_control_weights():
585
+ self.weights = self._current_timestep_keyframe.control_weights
586
+ elif not self._current_timestep_keyframe.inherit_missing:
587
+ self.weights = self.weights_default
588
+ if self._current_timestep_keyframe.has_latent_keyframes():
589
+ self.latent_keyframes = self._current_timestep_keyframe.latent_keyframes
590
+ elif not self._current_timestep_keyframe.inherit_missing:
591
+ self.latent_keyframes = None
592
+ if self._current_timestep_keyframe.has_mask_hint():
593
+ self.tk_mask_cond_hint_original = self._current_timestep_keyframe.mask_hint_orig
594
+ elif not self._current_timestep_keyframe.inherit_missing:
595
+ del self.tk_mask_cond_hint_original
596
+ self.tk_mask_cond_hint_original = None
597
+ # if guarantee_steps greater than zero, stop searching for other keyframes
598
+ if self._current_timestep_keyframe.get_effective_guarantee_steps(max_sigma) > 0:
599
+ break
600
+ # if eval_tk is outside of percent range, stop looking further
601
+ else:
602
+ break
603
+ # update prev_t
604
+ self.prev_t = self.t
605
+ # update steps current keyframe is used
606
+ self._current_used_steps += 1
607
+ # if index changed, apply overrides
608
+ if prev_index != self._current_timestep_index:
609
+ if self.weights_override is not None:
610
+ self.weights = self.weights_override
611
+ if self.latent_keyframe_override is not None:
612
+ self.latent_keyframes = self.latent_keyframe_override
613
+
614
+ # make sure weights and latent_keyframes are in a workable state
615
+ # Note: each AdvancedControlBase should create their own get_universal_weights class
616
+ self.prepare_weights()
617
+
618
+ def prepare_weights(self):
619
+ if self.weights is None:
620
+ self.weights = self.weights_default
621
+ elif self.weights.weight_type == ControlWeightType.UNIVERSAL:
622
+ # if universal and weight_mask present, no need to convert
623
+ if self.weights.weight_mask is not None:
624
+ return
625
+ self.weights = self.get_universal_weights()
626
+
627
+ def get_universal_weights(self) -> ControlWeights:
628
+ return self.weights
629
+
630
+ def set_cond_hint_mask(self, mask_hint):
631
+ self.mask_cond_hint_original = mask_hint
632
+ return self
633
+
634
+ def set_cond_hint_inject(self, *args, **kwargs):
635
+ to_return = self.base.set_cond_hint(*args, **kwargs)
636
+ # if vae required, look in args and kwargs for it
637
+ if self.require_vae:
638
+ # check args first, as that's the default way vae param is used in ComfyUI
639
+ for arg in args:
640
+ if isinstance(arg, VAE):
641
+ self.adv_vae = arg
642
+ self.vae = arg
643
+ break
644
+ # if not in args, check kwargs now
645
+ if self.adv_vae is None:
646
+ if 'vae' in kwargs:
647
+ self.adv_vae = kwargs['vae']
648
+ self.vae = kwargs['vae']
649
+ return to_return
650
+
651
+ def pre_run_inject(self, model, percent_to_timestep_function):
652
+ self.base.pre_run(model, percent_to_timestep_function)
653
+ self.pre_run_advanced(model, percent_to_timestep_function)
654
+
655
+ def pre_run_advanced(self, model, percent_to_timestep_function):
656
+ # for each timestep keyframe, calculate the start_t
657
+ for tk in self.timestep_keyframes.keyframes:
658
+ tk.start_t = percent_to_timestep_function(tk.start_percent)
659
+ # set real_compression_ratio to compression_ratio
660
+ if hasattr(self, "compression_ratio"):
661
+ self.real_compression_ratio = self.compression_ratio
662
+ # clear variables
663
+ self.cleanup_advanced()
664
+
665
+ def set_previous_controlnet_inject(self, *args, **kwargs):
666
+ to_return = self.base.set_previous_controlnet(*args, **kwargs)
667
+ if not self.disarmed:
668
+ 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.")
669
+ return to_return
670
+
671
+ def disarm(self):
672
+ self.disarmed = True
673
+
674
+ def should_run(self):
675
+ if math.isclose(self.strength, 0.0) or math.isclose(self._current_timestep_keyframe.strength, 0.0):
676
+ return False
677
+ if self.timestep_range is not None:
678
+ if self.t > self.timestep_range[0] or self.t < self.timestep_range[1]:
679
+ return False
680
+ return True
681
+
682
+ def get_control_inject(self, x_noisy, t, cond, batched_number, transformer_options: dict):
683
+ self.batched_number = batched_number
684
+ self.batch_size = len(t)
685
+ self.cond_or_uncond = transformer_options.get("cond_or_uncond", None)
686
+ # fill out ad_param-related fields, if present
687
+ if "ad_params" in transformer_options:
688
+ self.sub_idxs = transformer_options["ad_params"]["sub_idxs"]
689
+ self.full_latent_length = transformer_options["ad_params"]["full_length"]
690
+ self.context_length = transformer_options["ad_params"]["context_length"]
691
+ # prepare timestep and everything related
692
+ self.prepare_current_timestep(t=t, transformer_options=transformer_options)
693
+ # if should not perform any actions for the controlnet, exit without doing any work
694
+ if self.strength == 0.0 or self._current_timestep_keyframe.strength == 0.0:
695
+ return self.default_control_actions(x_noisy, t, cond, batched_number, transformer_options)
696
+ # otherwise, perform normal function
697
+ return self.get_control_advanced(x_noisy, t, cond, batched_number, transformer_options)
698
+
699
+ def get_control_advanced(self, x_noisy, t, cond, batched_number, transformer_options):
700
+ return self.default_control_actions(x_noisy, t, cond, batched_number, transformer_options)
701
+
702
+ def default_control_actions(self, x_noisy, t, cond, batched_number, transformer_options):
703
+ control_prev = None
704
+ if self.previous_controlnet is not None:
705
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
706
+ return control_prev
707
+
708
+ def calc_weight(self, idx: int, x: Tensor, control: dict[str, list[Tensor]], key: str) -> Union[float, Tensor]:
709
+ if self.weights.weight_mask is not None:
710
+ # prepare weight mask
711
+ self.prepare_weight_mask_cond_hint(x, self.batched_number)
712
+ # adjust mask for current layer and return
713
+ return torch.pow(self.weight_mask_cond_hint, self.get_calc_pow(idx=idx, control=control, key=key))
714
+ return self.weights.get(idx=idx, control=control, key=key)
715
+
716
+ def get_calc_pow(self, idx: int, control: dict[str, list[Tensor]], key: str) -> int:
717
+ if key == "middle":
718
+ return 0
719
+ else:
720
+ c_len = len(control[key])
721
+ real_idx = c_len-idx
722
+ if key == "input":
723
+ real_idx = c_len - real_idx + 1
724
+ return real_idx
725
+
726
+ def calc_latent_keyframe_mults(self, x: Tensor, batched_number: int) -> Tensor:
727
+ # apply strengths, and get batch indeces to null out
728
+ # AKA latents that should not be influenced by ControlNet
729
+ final_mults = [1.0] * x.shape[0]
730
+ if self.latent_keyframes:
731
+ latent_count = x.shape[0] // batched_number
732
+ indeces_to_null = set(range(latent_count))
733
+ mapped_indeces = None
734
+ # if expecting subdivision, will need to translate between subset and actual idx values
735
+ if self.sub_idxs:
736
+ mapped_indeces = {}
737
+ for i, actual in enumerate(self.sub_idxs):
738
+ mapped_indeces[actual] = i
739
+ for keyframe in self.latent_keyframes:
740
+ real_index = keyframe.batch_index
741
+ # if negative, count from end
742
+ if real_index < 0:
743
+ real_index += latent_count if self.sub_idxs is None else self.full_latent_length
744
+
745
+ # if not mapping indeces, what you see is what you get
746
+ if mapped_indeces is None:
747
+ if real_index in indeces_to_null:
748
+ indeces_to_null.remove(real_index)
749
+ # otherwise, see if batch_index is even included in this set of latents
750
+ else:
751
+ real_index = mapped_indeces.get(real_index, None)
752
+ if real_index is None:
753
+ continue
754
+ indeces_to_null.remove(real_index)
755
+
756
+ # if real_index is outside the bounds of latents, don't apply
757
+ if real_index >= latent_count or real_index < 0:
758
+ continue
759
+
760
+ # apply strength for each batched cond/uncond
761
+ for b in range(batched_number):
762
+ final_mults[(latent_count*b)+real_index] = keyframe.strength
763
+ # null them out by multiplying by null_latent_kf_strength
764
+ for batch_index in indeces_to_null:
765
+ # apply null for each batched cond/uncond
766
+ for b in range(batched_number):
767
+ final_mults[(latent_count*b)+batch_index] = self._current_timestep_keyframe.null_latent_kf_strength
768
+ # convert final_mults into tensor and match expected dimension count
769
+ final_tensor = torch.tensor(final_mults, dtype=x.dtype, device=x.device)
770
+ while len(final_tensor.shape) < len(x.shape):
771
+ final_tensor = final_tensor.unsqueeze(-1)
772
+ return final_tensor
773
+
774
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int, flux_shape: tuple=None):
775
+ # handle weight's uncond_multiplier, if applicable
776
+ if self.weights.has_uncond_multiplier:
777
+ actual_length = x.size(0) // batched_number
778
+ for idx, cond_type in enumerate(self.cond_or_uncond):
779
+ # if uncond, set to weight's uncond_multiplier
780
+ if cond_type == 1:
781
+ x[actual_length*idx:actual_length*(idx+1)] *= self.weights.uncond_multiplier
782
+ if self.weights.has_uncond_mask:
783
+ pass
784
+
785
+ if self.latent_keyframes is not None:
786
+ x[:] = x[:] * self.calc_latent_keyframe_mults(x=x, batched_number=batched_number)
787
+ # apply masks, resizing mask to required dims
788
+ if self.mask_cond_hint is not None:
789
+ masks = prepare_mask_batch(self.mask_cond_hint, x.shape, match_shape=True, flux_shape=flux_shape)
790
+ x[:] = x[:] * masks
791
+ if self.tk_mask_cond_hint is not None:
792
+ masks = prepare_mask_batch(self.tk_mask_cond_hint, x.shape, match_shape=True, flux_shape=flux_shape)
793
+ x[:] = x[:] * masks
794
+ # apply timestep keyframe strengths
795
+ if self._current_timestep_keyframe.strength != 1.0:
796
+ x[:] *= self._current_timestep_keyframe.strength
797
+
798
+ def control_merge_inject(self: 'AdvancedControlBase', control: dict[str, list[Tensor]], control_prev: dict, output_dtype):
799
+ out = {'input':[], 'middle':[], 'output': []}
800
+
801
+ for key in control:
802
+ control_output = control[key]
803
+ applied_to = set()
804
+ for i in range(len(control_output)):
805
+ x = control_output[i]
806
+ if x is not None:
807
+ if self.global_average_pooling:
808
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
809
+
810
+ # if should disable applied_to optimization, clone the weight if in applied_to
811
+ if self.weights.disable_applied_to and x in applied_to:
812
+ x = x.clone()
813
+
814
+ if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
815
+ applied_to.add(x)
816
+ self.apply_advanced_strengths_and_masks(x, self.batched_number)
817
+ x *= self.strength * self.calc_weight(i, x, control, key)
818
+
819
+ if output_dtype is not None and x.dtype != output_dtype:
820
+ x = x.to(output_dtype)
821
+
822
+ out[key].append(x)
823
+
824
+ if control_prev is not None:
825
+ for x in ['input', 'middle', 'output']:
826
+ o = out[x]
827
+ for i in range(len(control_prev[x])):
828
+ prev_val = control_prev[x][i]
829
+ if i >= len(o):
830
+ o.append(prev_val)
831
+ elif prev_val is not None:
832
+ if o[i] is None:
833
+ o[i] = prev_val
834
+ else:
835
+ if o[i].shape[0] < prev_val.shape[0]:
836
+ o[i] = prev_val + o[i]
837
+ else:
838
+ o[i] = prev_val + o[i] # TODO from base ComfyUI: change back to inplace add if shared tensors stop being an issue
839
+ return out
840
+
841
+ def prepare_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
842
+ self._prepare_mask("mask_cond_hint", self.mask_cond_hint_original, x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
843
+ self.prepare_tk_mask_cond_hint(x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
844
+
845
+ def prepare_tk_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
846
+ 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)
847
+
848
+ def prepare_weight_mask_cond_hint(self, x_noisy: Tensor, batched_number, dtype=None):
849
+ 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)
850
+
851
+ def _prepare_mask(self, attr_name, orig_mask: Tensor, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
852
+ # make mask appropriate dimensions, if present
853
+ if orig_mask is not None:
854
+ out_mask = getattr(self, attr_name)
855
+ multiplier = 1 if direct_attn else 8
856
+ 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]:
857
+ self._reset_attr(attr_name)
858
+ del out_mask
859
+ # TODO: perform upscale on only the sub_idxs masks at a time instead of all to conserve RAM
860
+ # resize mask and match batch count
861
+ out_mask = prepare_mask_batch(orig_mask, x_noisy.shape, multiplier=multiplier, match_shape=True)
862
+ actual_latent_length = x_noisy.shape[0] // batched_number
863
+ out_mask = extend_to_batch_size(out_mask, actual_latent_length if self.sub_idxs is None else self.full_latent_length)
864
+ if self.sub_idxs is not None:
865
+ out_mask = out_mask[self.sub_idxs]
866
+ # make cond_hint_mask length match x_noise
867
+ if x_noisy.shape[0] != out_mask.shape[0]:
868
+ out_mask = broadcast_image_to_extend(out_mask, x_noisy.shape[0], batched_number)
869
+ # default dtype to be same as x_noisy
870
+ if dtype is None:
871
+ dtype = x_noisy.dtype
872
+ setattr(self, attr_name, out_mask.to(dtype=dtype).to(x_noisy.device))
873
+ del out_mask
874
+
875
+ def _reset_attr(self, attr_name, new_value=None):
876
+ if hasattr(self, attr_name):
877
+ delattr(self, attr_name)
878
+ setattr(self, attr_name, new_value)
879
+
880
+ def cleanup_inject(self):
881
+ self.base.cleanup()
882
+ self.cleanup_advanced()
883
+
884
+ def cleanup_advanced(self):
885
+ self.sub_idxs = None
886
+ self.full_latent_length = 0
887
+ self.context_length = 0
888
+ self.t = None
889
+ self.prev_t = None
890
+ self.batched_number = None
891
+ self.batch_size = 0
892
+ self.weights = None
893
+ self.latent_keyframes = None
894
+ # set effective_compression_ratio to compression_ratio
895
+ if hasattr(self, "compression_ratio"):
896
+ self.real_compression_ratio = self.compression_ratio
897
+ # timestep stuff
898
+ self._current_timestep_keyframe = None
899
+ self._current_timestep_index = -1
900
+ self._current_used_steps = 0
901
+ # clear mask hints
902
+ if self.mask_cond_hint is not None:
903
+ del self.mask_cond_hint
904
+ self.mask_cond_hint = None
905
+ if self.tk_mask_cond_hint_original is not None:
906
+ del self.tk_mask_cond_hint_original
907
+ self.tk_mask_cond_hint_original = None
908
+ if self.tk_mask_cond_hint is not None:
909
+ del self.tk_mask_cond_hint
910
+ self.tk_mask_cond_hint = None
911
+ if self.weight_mask_cond_hint is not None:
912
+ del self.weight_mask_cond_hint
913
+ self.weight_mask_cond_hint = None
914
+
915
+ def copy_to_advanced(self, copied: 'AdvancedControlBase'):
916
+ copied.mask_cond_hint_original = self.mask_cond_hint_original
917
+ copied.weights_override = self.weights_override
918
+ copied.latent_keyframe_override = self.latent_keyframe_override
919
+ copied.adv_vae = self.adv_vae
920
+ copied.mult_by_ratio_when_vae = self.mult_by_ratio_when_vae
921
+ copied.require_vae = self.require_vae
922
+ copied.allow_condhint_latents = self.allow_condhint_latents
923
+ copied.postpone_condhint_latents_check = self.postpone_condhint_latents_check
924
+ copied.disarmed = self.disarmed