p101111 commited on
Commit
bf357f5
·
verified ·
1 Parent(s): ed7836a

custom nodes

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 +36 -0
  2. custom_nodes/ComfyUI-Anima-LLLite/.gitignore +2 -0
  3. custom_nodes/ComfyUI-Anima-LLLite/LICENSE +201 -0
  4. custom_nodes/ComfyUI-Anima-LLLite/README.md +159 -0
  5. custom_nodes/ComfyUI-Anima-LLLite/__init__.py +3 -0
  6. custom_nodes/ComfyUI-Anima-LLLite/__pycache__/__init__.cpython-312.pyc +0 -0
  7. custom_nodes/ComfyUI-Anima-LLLite/__pycache__/control_net_lllite_anima.cpython-312.pyc +0 -0
  8. custom_nodes/ComfyUI-Anima-LLLite/__pycache__/nodes.cpython-312.pyc +0 -0
  9. custom_nodes/ComfyUI-Anima-LLLite/control_net_lllite_anima.py +543 -0
  10. custom_nodes/ComfyUI-Anima-LLLite/nodes.py +287 -0
  11. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/.DS_Store +0 -0
  12. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/.github/workflows/publish.yml +28 -0
  13. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/README.md +13 -0
  14. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/__init__.py +191 -0
  15. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/__pycache__/__init__.cpython-312.pyc +0 -0
  16. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/js/resolution_display.js +188 -0
  17. custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/pyproject.toml +36 -0
  18. custom_nodes/ComfyUi-Untwisting-RoPE/.DS_Store +0 -0
  19. custom_nodes/ComfyUi-Untwisting-RoPE/.github/workflows/publish.yml +28 -0
  20. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/anima_1.jpg +3 -0
  21. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_1.jpg +3 -0
  22. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_10.jpg +3 -0
  23. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_2.jpg +3 -0
  24. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_3.jpg +3 -0
  25. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_4.jpg +3 -0
  26. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_5.jpg +3 -0
  27. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_6.jpg +3 -0
  28. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_7.jpg +3 -0
  29. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_8.jpg +3 -0
  30. custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_9.jpg +3 -0
  31. custom_nodes/ComfyUi-Untwisting-RoPE/README.md +35 -0
  32. custom_nodes/ComfyUi-Untwisting-RoPE/__init__.py +0 -0
  33. custom_nodes/ComfyUi-Untwisting-RoPE/__pycache__/__init__.cpython-312.pyc +3 -0
  34. custom_nodes/ComfyUi-Untwisting-RoPE/__pycache__/verbose_prints.cpython-312.pyc +0 -0
  35. custom_nodes/ComfyUi-Untwisting-RoPE/documentation/parameters.md +30 -0
  36. custom_nodes/ComfyUi-Untwisting-RoPE/documentation/unofficial_extensions.md +29 -0
  37. custom_nodes/ComfyUi-Untwisting-RoPE/models/__init__.py +277 -0
  38. custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/__init__.cpython-312.pyc +0 -0
  39. custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/anima.cpython-312.pyc +0 -0
  40. custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/flux2.cpython-312.pyc +0 -0
  41. custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/zimage.cpython-312.pyc +0 -0
  42. custom_nodes/ComfyUi-Untwisting-RoPE/models/_template.py +673 -0
  43. custom_nodes/ComfyUi-Untwisting-RoPE/models/anima.py +426 -0
  44. custom_nodes/ComfyUi-Untwisting-RoPE/models/flux2.py +760 -0
  45. custom_nodes/ComfyUi-Untwisting-RoPE/models/supported_models.txt +88 -0
  46. custom_nodes/ComfyUi-Untwisting-RoPE/models/zimage.py +304 -0
  47. custom_nodes/ComfyUi-Untwisting-RoPE/pyproject.toml +17 -0
  48. custom_nodes/ComfyUi-Untwisting-RoPE/verbose_prints.py +812 -0
  49. custom_nodes/ComfyUi-Untwisting-RoPE/workflows/workflow_anima.json +1290 -0
  50. custom_nodes/ComfyUi-Untwisting-RoPE/workflows/workflow_flux2_klein_4b.json +1448 -0
.gitattributes CHANGED
@@ -34,3 +34,39 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  example.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  example.png filter=lfs diff=lfs merge=lfs -text
37
+ custom_nodes/comfyui_controlnet_aux/examples/CNAuxBanner.jpg filter=lfs diff=lfs merge=lfs -text
38
+ custom_nodes/comfyui_controlnet_aux/examples/comfyui-controlnet-aux-logo.png filter=lfs diff=lfs merge=lfs -text
39
+ custom_nodes/comfyui_controlnet_aux/examples/example_animal_pose.png filter=lfs diff=lfs merge=lfs -text
40
+ custom_nodes/comfyui_controlnet_aux/examples/example_anime_face_segmentor.png filter=lfs diff=lfs merge=lfs -text
41
+ custom_nodes/comfyui_controlnet_aux/examples/example_anyline.png filter=lfs diff=lfs merge=lfs -text
42
+ custom_nodes/comfyui_controlnet_aux/examples/example_densepose.png filter=lfs diff=lfs merge=lfs -text
43
+ custom_nodes/comfyui_controlnet_aux/examples/example_depth_anything_v2.png filter=lfs diff=lfs merge=lfs -text
44
+ custom_nodes/comfyui_controlnet_aux/examples/example_depth_anything.png filter=lfs diff=lfs merge=lfs -text
45
+ custom_nodes/comfyui_controlnet_aux/examples/example_dsine.png filter=lfs diff=lfs merge=lfs -text
46
+ custom_nodes/comfyui_controlnet_aux/examples/example_marigold_flat.jpg filter=lfs diff=lfs merge=lfs -text
47
+ custom_nodes/comfyui_controlnet_aux/examples/example_marigold.png filter=lfs diff=lfs merge=lfs -text
48
+ custom_nodes/comfyui_controlnet_aux/examples/example_mesh_graphormer.png filter=lfs diff=lfs merge=lfs -text
49
+ custom_nodes/comfyui_controlnet_aux/examples/example_metric3d.png filter=lfs diff=lfs merge=lfs -text
50
+ custom_nodes/comfyui_controlnet_aux/examples/example_recolor.png filter=lfs diff=lfs merge=lfs -text
51
+ custom_nodes/comfyui_controlnet_aux/examples/example_save_kps.png filter=lfs diff=lfs merge=lfs -text
52
+ custom_nodes/comfyui_controlnet_aux/examples/example_teed.png filter=lfs diff=lfs merge=lfs -text
53
+ custom_nodes/comfyui_controlnet_aux/examples/example_torchscript.png filter=lfs diff=lfs merge=lfs -text
54
+ custom_nodes/comfyui_controlnet_aux/examples/example_unimatch.png filter=lfs diff=lfs merge=lfs -text
55
+ custom_nodes/comfyui_controlnet_aux/examples/ExecuteAll.png filter=lfs diff=lfs merge=lfs -text
56
+ custom_nodes/comfyui_controlnet_aux/examples/ExecuteAll1.jpg filter=lfs diff=lfs merge=lfs -text
57
+ custom_nodes/comfyui_controlnet_aux/examples/ExecuteAll2.jpg filter=lfs diff=lfs merge=lfs -text
58
+ custom_nodes/comfyui_controlnet_aux/NotoSans-Regular.ttf filter=lfs diff=lfs merge=lfs -text
59
+ custom_nodes/comfyui_controlnet_aux/src/custom_controlnet_aux/mesh_graphormer/hand_landmarker.task filter=lfs diff=lfs merge=lfs -text
60
+ custom_nodes/comfyui_controlnet_aux/tests/pose.png filter=lfs diff=lfs merge=lfs -text
61
+ custom_nodes/ComfyUi-Untwisting-RoPE/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
62
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/anima_1.jpg filter=lfs diff=lfs merge=lfs -text
63
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_1.jpg filter=lfs diff=lfs merge=lfs -text
64
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_10.jpg filter=lfs diff=lfs merge=lfs -text
65
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_2.jpg filter=lfs diff=lfs merge=lfs -text
66
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_3.jpg filter=lfs diff=lfs merge=lfs -text
67
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_4.jpg filter=lfs diff=lfs merge=lfs -text
68
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_5.jpg filter=lfs diff=lfs merge=lfs -text
69
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_6.jpg filter=lfs diff=lfs merge=lfs -text
70
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_7.jpg filter=lfs diff=lfs merge=lfs -text
71
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_8.jpg filter=lfs diff=lfs merge=lfs -text
72
+ custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_9.jpg filter=lfs diff=lfs merge=lfs -text
custom_nodes/ComfyUI-Anima-LLLite/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ models/
custom_nodes/ComfyUI-Anima-LLLite/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
custom_nodes/ComfyUI-Anima-LLLite/README.md ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-Anima-LLLite
2
+
3
+ ComfyUI custom node for **ControlNet-LLLite for Anima** (DiT-based).
4
+
5
+ LLLite is a lightweight ControlNet variant that injects a low-rank correction
6
+ into the attention (and optionally MLP) projections of the DiT. This node
7
+ loads weights trained with
8
+ [kohya-ss/sd-scripts](https://github.com/kohya-ss/sd-scripts) and applies them
9
+ to the ComfyUI Anima model at inference time.
10
+
11
+ This is intended as a **minimal reference implementation**. Community nodes
12
+ with extra features (per-step scheduling, multi-cond, region masks, per-block
13
+ selection, …) are welcome and can build on this codebase.
14
+
15
+ ## Install
16
+
17
+ Clone into `ComfyUI/custom_nodes/`:
18
+
19
+ ```
20
+ cd ComfyUI/custom_nodes
21
+ git clone <this-repo> ComfyUI-Anima-LLLite
22
+ ```
23
+
24
+ Place LLLite weights (`.safetensors`) under `ComfyUI/models/controlnet/`.
25
+
26
+ ## Node
27
+
28
+ **Apply Anima ControlNet-LLLite** (`loaders` category)
29
+
30
+ | Input | Type | Notes |
31
+ |---|---|---|
32
+ | `model` | MODEL | Anima checkpoint |
33
+ | `lllite_name` | filename | from `models/controlnet/` |
34
+ | `image` | IMAGE | control image (any resolution; auto-resized to latent×8) |
35
+ | `strength` | FLOAT | LLLite multiplier (default 1.0) |
36
+ | `start_percent` | FLOAT | start of the active sampling window (0.0 = sigma_max) |
37
+ | `end_percent` | FLOAT | end of the active sampling window (1.0 = sigma_min) |
38
+ | `preserve_wrapper` | BOOLEAN | if a previous node already installed a `model_function_wrapper`, delegate to it from inside this node's wrapper so they cascade instead of overwriting (default `True`) |
39
+ | `mask` *(optional)* | MASK | required when the weights are 4-channel (inpaint); white = inpaint area, black = keep |
40
+
41
+ Output: patched `MODEL`.
42
+
43
+ All architectural parameters (`cond_emb_dim`, `mlp_dim`, `cond_dim`,
44
+ `cond_resblocks`, `use_aspp`, `aspp_dilations`, `target_layers`,
45
+ `cond_in_channels`, `inpaint_masked_input`) are baked into the trained
46
+ weights and read automatically from the safetensors metadata — they are
47
+ not exposed as node inputs because changing them would just cause load
48
+ errors.
49
+
50
+ ### Inpainting (4-channel) weights
51
+
52
+ If the loaded weights were trained with `--lllite_cond_in_channels=4`
53
+ (inpaint mode), the node also requires a `MASK` input. The mask convention
54
+ matches the sd-scripts training/inference code:
55
+
56
+ * `white` (1.0) = inpaint area (the region the model should fill)
57
+ * `black` (0.0) = keep
58
+
59
+ The mask is resized to match the control image (nearest-neighbor),
60
+ binarized at 0.5, and concatenated with the RGB control image as a 4th
61
+ channel (rescaled to `[-1, +1]` to match the RGB range). When the weights
62
+ were trained with `--lllite_inpaint_masked_input`, the RGB channels are
63
+ also zeroed inside the mask region before concatenation — this is read
64
+ from the weights metadata and applied automatically.
65
+
66
+ 3-channel weights continue to work with no mask input; if a mask is
67
+ connected to a 3-channel LLLite the node logs a warning and ignores it.
68
+ A 4-channel weight without a mask raises a `ValueError` rather than
69
+ silently substituting an empty mask.
70
+
71
+ ### Cascading multiple LLLite nodes
72
+
73
+ Multiple **Apply Anima ControlNet-LLLite** nodes can be chained on the same
74
+ `MODEL` to apply more than one LLLite at the same time (e.g. a pose LLLite
75
+ and a depth LLLite, or several inpaint LLLites with different conditions).
76
+ Just feed the output `MODEL` of one node into the `model` input of the next.
77
+
78
+ ComfyUI's `model_options` has a single `model_function_wrapper` slot, so two
79
+ nodes that each install a wrapper would normally cause the outer one to
80
+ silently overwrite the inner one. To avoid this, each node captures the
81
+ previously-installed wrapper before cloning and delegates to it from inside
82
+ its own wrapper, so wrappers stack instead of replacing each other. This is
83
+ controlled by the `preserve_wrapper` toggle (default `True`); turn it off to
84
+ get the legacy single-wrapper behavior, or to deliberately replace an
85
+ upstream wrapper.
86
+
87
+ Notes when cascading:
88
+
89
+ * Each node has its own `start_percent` / `end_percent` window — when a
90
+ node's window is inactive it is a pass-through to the next wrapper, so
91
+ you can stage different LLLites across different parts of the schedule.
92
+ * `strength` is per-node and they add independently in the LLLite output;
93
+ there is no global normalization, so very high combined strengths can
94
+ over-saturate the same way a single high `strength` would.
95
+ * The pattern is compatible with other well-behaved wrapper-installing
96
+ nodes (e.g. `ChromaRadianceOptions`) provided they follow the same
97
+ delegate-to-previous-wrapper convention.
98
+
99
+ ## How it works
100
+
101
+ * Discovers the LLLite target Linears under each Anima DiT block according to
102
+ the `target_atomics` recorded in the weight metadata:
103
+ * `self_attn_q_pre` → self-attention `q_proj`
104
+ * `self_attn_kv_pre` → self-attention `k_proj` + `v_proj`
105
+ * `cross_attn_q_pre` → cross-attention `q_proj`
106
+ * `mlp_fc1_pre` → `GPT2FeedForward.layer1` (the MLP fc1)
107
+
108
+ The LLM-Adapter sub-tree and `output_proj` are always skipped.
109
+ * On each sampling step the wrapper monkey-patches those Linears with the
110
+ LLLite forward, runs `apply_model`, and restores the originals — so the
111
+ patch never leaks across model clones.
112
+ * The control image is resized to `latent_HW * 8` once per resolution, then
113
+ embedded by the v2 `conditioning1` trunk (Conv 4×4 s=4 → Conv 3×3 s=1 →
114
+ Conv 4×4 s=4 with GroupNorm/SiLU, optional ResBlocks, optional ASPP, 1×1
115
+ projection, LayerNorm) to a per-token feature map matching the DiT token
116
+ grid. For 4-channel (inpaint) weights, the mask is resized with
117
+ nearest-neighbor, binarized, rescaled to `[-1, +1]`, and concatenated as
118
+ the 4th channel of the cond image before this trunk.
119
+ * Each LLLite module applies the v2 forward: `down → silu → concat with
120
+ (cond + per-module depth-embedding) → mid → FiLM(γ, β) → silu → up`,
121
+ added to the original Linear input.
122
+ * CFG is supported: `cond_emb` is broadcast to match the runtime batch size.
123
+
124
+ ## Weight format (v2, named keys)
125
+
126
+ The state dict is in the v2 self-describing format. Each LLLite module's
127
+ weights are prefixed by the target Linear's full path, so the file alone
128
+ identifies which Linear each tensor belongs to:
129
+
130
+ ```
131
+ lllite_conditioning1.{conv1,conv2,conv3,norm1,...,proj,out_norm,...}.{weight,bias}
132
+ lllite_dit_blocks_{i}_self_attn_q_proj.down.{weight,bias}
133
+ lllite_dit_blocks_{i}_self_attn_q_proj.mid.{weight,bias}
134
+ lllite_dit_blocks_{i}_self_attn_q_proj.cond_to_film.{weight,bias}
135
+ lllite_dit_blocks_{i}_self_attn_q_proj.up.{weight,bias}
136
+ lllite_dit_blocks_{i}_self_attn_q_proj.depth_embed
137
+ ...
138
+ ```
139
+
140
+ The expected safetensors metadata keys are:
141
+
142
+ * `lllite.version` (= `"2"`)
143
+ * `lllite.cond_emb_dim`, `lllite.mlp_dim`
144
+ * `lllite.cond_dim`, `lllite.cond_resblocks`
145
+ * `lllite.use_aspp`, `lllite.aspp_dilations`
146
+ * `lllite.target_atomics` (canonical, comma-separated atomic specifiers) —
147
+ falls back to `lllite.target_layers` for older v2 snapshots
148
+ * `lllite.cond_in_channels` (`"3"` standard / `"4"` inpaint; defaults to `3`)
149
+ * `lllite.inpaint_masked_input` (`"true"` / `"false"`; defaults to `false`,
150
+ only meaningful when `cond_in_channels=4`)
151
+
152
+ **Legacy weights with `lllite_modules.{i}.*` keys (the pre-v2 format) are
153
+ rejected on load.** Re-train against the current sd-scripts codebase.
154
+
155
+ ## Credits
156
+
157
+ * LLLite design and Anima training implementation: kohya-ss
158
+ * Adapted for ComfyUI from `sd-scripts`
159
+ * ComfyUI port written collaboratively with Claude (Anthropic, `claude-opus-4-7`)
custom_nodes/ComfyUI-Anima-LLLite/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+
3
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
custom_nodes/ComfyUI-Anima-LLLite/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (308 Bytes). View file
 
custom_nodes/ComfyUI-Anima-LLLite/__pycache__/control_net_lllite_anima.cpython-312.pyc ADDED
Binary file (27 kB). View file
 
custom_nodes/ComfyUI-Anima-LLLite/__pycache__/nodes.cpython-312.pyc ADDED
Binary file (13.8 kB). View file
 
custom_nodes/ComfyUI-Anima-LLLite/control_net_lllite_anima.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ControlNet-LLLite for Anima (DiT) — ComfyUI port (v2 architecture).
2
+
3
+ Adapted from kohya-ss/sd-scripts. The on-disk weight format is the v2
4
+ named-key format (per-module key prefix = lllite_name, shared encoder under
5
+ ``lllite_conditioning1.*``, depth embedding split per-module as
6
+ ``{name}.depth_embed``); legacy ``lllite_modules.*`` files are rejected.
7
+
8
+ Differences vs. the sd-scripts reference (``networks/control_net_lllite_anima.py``):
9
+ * No dependency on ``library.utils`` — uses stdlib logging.
10
+ * Module discovery filters the LLM-Adapter sub-tree by class identity in
11
+ addition to the path-based check (ComfyUI ships two distinct ``Attention``
12
+ classes that share the bare class name).
13
+ * ``LLLiteModuleDiT`` keeps a ``restore()`` method (and an idempotent
14
+ ``apply_to()``); ComfyUI patches/unpatches the original Linear around
15
+ every sampler call via ``set_model_unet_function_wrapper``.
16
+ * Forward pass casts ``x`` and ``cond_emb`` to the LLLite parameter dtype
17
+ so autocast / mixed-precision flows that hand us a different dtype than
18
+ the LLLite weights still work.
19
+ * CFG batch-size and sequence-length mismatches fall back to identity
20
+ instead of asserting, so a slightly-off cond image cannot abort sampling.
21
+ * The training-side ``AnimaControlNetLLLiteWrapper`` is omitted; ComfyUI
22
+ integrates via ``model_function_wrapper`` in nodes.py instead.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ import os
28
+ from typing import List, Optional, Tuple
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ # Class names of the modules that LLLite injects into. The LLM-Adapter uses
38
+ # a different ``Attention`` class with the same bare name; we filter it by
39
+ # path (``llm_adapter`` in the qualified name) and by the ``is_selfattn``
40
+ # attribute presence.
41
+ TARGET_ATTENTION_CLASS = "Attention"
42
+ TARGET_MLP_CLASS = "GPT2FeedForward"
43
+ LLM_ADAPTER_NAME = "llm_adapter"
44
+
45
+ LLLITE_ARCH_VERSION = "2"
46
+
47
+
48
+ # ----------------------------------------------------------------------------
49
+ # target_layers: atomic specifiers and presets
50
+ # ----------------------------------------------------------------------------
51
+
52
+ ATOMIC_SPECIFIERS: Tuple[str, ...] = (
53
+ "self_attn_q_pre",
54
+ "self_attn_kv_pre",
55
+ "cross_attn_q_pre",
56
+ "mlp_fc1_pre",
57
+ )
58
+
59
+ PRESETS: dict = {
60
+ "self_attn_q": ("self_attn_q_pre",),
61
+ "self_attn_qkv": ("self_attn_q_pre", "self_attn_kv_pre"),
62
+ "self_attn_qkv_cross_q": ("self_attn_q_pre", "self_attn_kv_pre", "cross_attn_q_pre"),
63
+ }
64
+
65
+
66
+ def parse_target_layers(spec: str) -> Tuple[str, ...]:
67
+ """Resolve a ``target_layers`` spec to a canonical atomic tuple.
68
+
69
+ Accepts a preset name (``"self_attn_qkv"``) or a comma-separated list of
70
+ atomic specifiers (``"self_attn_q_pre,mlp_fc1_pre"``). Returns the atomics
71
+ in ``ATOMIC_SPECIFIERS`` order with duplicates removed.
72
+ """
73
+ if not isinstance(spec, str):
74
+ raise TypeError(f"target_layers must be str, got {type(spec).__name__}")
75
+ spec = spec.strip()
76
+ if not spec:
77
+ raise ValueError("target_layers spec is empty")
78
+
79
+ if spec in PRESETS:
80
+ parts = list(PRESETS[spec])
81
+ else:
82
+ parts = [p.strip() for p in spec.split(",") if p.strip()]
83
+ bad = [p for p in parts if p not in ATOMIC_SPECIFIERS]
84
+ if bad:
85
+ raise ValueError(
86
+ f"unknown target_layers atomic specifier(s): {bad}. "
87
+ f"valid atomic={list(ATOMIC_SPECIFIERS)}, presets={list(PRESETS)}"
88
+ )
89
+
90
+ return tuple(a for a in ATOMIC_SPECIFIERS if a in parts)
91
+
92
+
93
+ # ----------------------------------------------------------------------------
94
+ # Conditioning1 trunk (v2)
95
+ # ----------------------------------------------------------------------------
96
+
97
+ def _gn(channels: int) -> nn.GroupNorm:
98
+ g = 8
99
+ while g > 1 and channels % g != 0:
100
+ g //= 2
101
+ return nn.GroupNorm(g, channels)
102
+
103
+
104
+ class _ResBlock(nn.Module):
105
+ def __init__(self, ch: int):
106
+ super().__init__()
107
+ self.norm1 = _gn(ch)
108
+ self.conv1 = nn.Conv2d(ch, ch, kernel_size=3, padding=1)
109
+ self.norm2 = _gn(ch)
110
+ self.conv2 = nn.Conv2d(ch, ch, kernel_size=3, padding=1)
111
+
112
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
113
+ h = self.conv1(F.silu(self.norm1(x)))
114
+ h = self.conv2(F.silu(self.norm2(h)))
115
+ return x + h
116
+
117
+
118
+ ASPP_DEFAULT_DILATIONS: Tuple[int, ...] = (1, 2, 4, 8)
119
+
120
+
121
+ class _ASPP(nn.Module):
122
+ def __init__(self, ch: int, dilations: Tuple[int, ...] = ASPP_DEFAULT_DILATIONS):
123
+ super().__init__()
124
+ assert len(dilations) >= 1, "ASPP needs at least one dilation"
125
+ branches = []
126
+ for d in dilations:
127
+ if d == 1:
128
+ conv = nn.Conv2d(ch, ch, kernel_size=1)
129
+ else:
130
+ conv = nn.Conv2d(ch, ch, kernel_size=3, padding=d, dilation=d)
131
+ branches.append(nn.Sequential(conv, _gn(ch), nn.SiLU()))
132
+ self.branches = nn.ModuleList(branches)
133
+
134
+ self.global_pool = nn.AdaptiveAvgPool2d(1)
135
+ self.global_conv = nn.Sequential(nn.Conv2d(ch, ch, kernel_size=1), _gn(ch), nn.SiLU())
136
+
137
+ n_branches = len(dilations) + 1
138
+ self.proj = nn.Sequential(
139
+ nn.Conv2d(ch * n_branches, ch, kernel_size=1), _gn(ch), nn.SiLU()
140
+ )
141
+
142
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
143
+ h, w = x.shape[-2:]
144
+ outs = [b(x) for b in self.branches]
145
+ g = self.global_conv(self.global_pool(x))
146
+ g = F.interpolate(g, size=(h, w), mode="bilinear", align_corners=False)
147
+ outs.append(g)
148
+ return self.proj(torch.cat(outs, dim=1))
149
+
150
+
151
+ class _Conditioning1(nn.Module):
152
+ def __init__(
153
+ self,
154
+ cond_dim: int,
155
+ cond_emb_dim: int,
156
+ n_resblocks: int,
157
+ use_aspp: bool = False,
158
+ aspp_dilations: Tuple[int, ...] = ASPP_DEFAULT_DILATIONS,
159
+ cond_in_channels: int = 3,
160
+ ):
161
+ super().__init__()
162
+ assert cond_dim % 2 == 0, f"cond_dim must be even, got {cond_dim}"
163
+ assert cond_in_channels >= 1, f"cond_in_channels must be >= 1, got {cond_in_channels}"
164
+ ch_half = cond_dim // 2
165
+
166
+ self.cond_in_channels = cond_in_channels
167
+ self.conv1 = nn.Conv2d(cond_in_channels, ch_half, kernel_size=4, stride=4, padding=0)
168
+ self.norm1 = _gn(ch_half)
169
+ self.conv2 = nn.Conv2d(ch_half, ch_half, kernel_size=3, stride=1, padding=1)
170
+ self.norm2 = _gn(ch_half)
171
+ self.conv3 = nn.Conv2d(ch_half, cond_dim, kernel_size=4, stride=4, padding=0)
172
+ self.norm3 = _gn(cond_dim)
173
+
174
+ self.resblocks = nn.ModuleList([_ResBlock(cond_dim) for _ in range(n_resblocks)])
175
+ self.aspp = _ASPP(cond_dim, aspp_dilations) if use_aspp else None
176
+
177
+ self.proj = nn.Conv2d(cond_dim, cond_emb_dim, kernel_size=1)
178
+ self.out_norm = nn.LayerNorm(cond_emb_dim)
179
+
180
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
181
+ h = F.silu(self.norm1(self.conv1(x)))
182
+ h = F.silu(self.norm2(self.conv2(h)))
183
+ h = F.silu(self.norm3(self.conv3(h)))
184
+ for rb in self.resblocks:
185
+ h = rb(h)
186
+ if self.aspp is not None:
187
+ h = self.aspp(h)
188
+ h = self.proj(h)
189
+ b, c, hh, ww = h.shape
190
+ h = h.view(b, c, hh * ww).permute(0, 2, 1).contiguous()
191
+ h = self.out_norm(h)
192
+ return h
193
+
194
+
195
+ # ----------------------------------------------------------------------------
196
+ # LLLite module (v2: FiLM + SiLU + 5D path + depth embedding)
197
+ # ----------------------------------------------------------------------------
198
+
199
+ class LLLiteModuleDiT(nn.Module):
200
+ def __init__(
201
+ self,
202
+ name: str,
203
+ org_module: nn.Linear,
204
+ cond_emb_dim: int,
205
+ mlp_dim: int,
206
+ dropout: Optional[float] = None,
207
+ multiplier: float = 1.0,
208
+ ):
209
+ super().__init__()
210
+ self.lllite_name = name
211
+ # Wrap in a list so the original Linear is not registered as a submodule
212
+ # and its weights stay out of state_dict.
213
+ self.org_module = [org_module]
214
+ self.cond_emb_dim = cond_emb_dim
215
+ self.mlp_dim = mlp_dim
216
+ self.dropout = dropout
217
+ self.multiplier = multiplier
218
+
219
+ in_dim = org_module.in_features
220
+
221
+ self.down = nn.Linear(in_dim, mlp_dim)
222
+ self.mid = nn.Linear(mlp_dim + cond_emb_dim, mlp_dim)
223
+
224
+ # FiLM: cond_local -> (gamma, beta), zero-init for identity at start.
225
+ self.cond_to_film = nn.Linear(cond_emb_dim, 2 * mlp_dim)
226
+ nn.init.zeros_(self.cond_to_film.weight)
227
+ nn.init.zeros_(self.cond_to_film.bias)
228
+
229
+ self.up = nn.Linear(mlp_dim, in_dim)
230
+ nn.init.zeros_(self.up.weight)
231
+ nn.init.zeros_(self.up.bias)
232
+
233
+ self.cond_emb: Optional[torch.Tensor] = None
234
+ self.org_forward = None
235
+
236
+ # Set by the parent ControlNetLLLiteDiT after construction.
237
+ self.layer_idx: int = -1
238
+ self._depth_embeds_ref: List[nn.Parameter] = []
239
+
240
+ def apply_to(self):
241
+ if self.org_forward is None:
242
+ self.org_forward = self.org_module[0].forward
243
+ self.org_module[0].forward = self.forward
244
+
245
+ def restore(self):
246
+ if self.org_forward is not None:
247
+ self.org_module[0].forward = self.org_forward
248
+ self.org_forward = None
249
+
250
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
251
+ # Input layouts:
252
+ # self/cross attention q/k/v: (B, S, D) — already flattened in the Anima block
253
+ # mlp.layer1: (B, T, H, W, D) — passed un-flattened
254
+ # Flatten the 5D case to 3D for the LLLite path and reshape on exit.
255
+ if self.multiplier == 0.0 or self.cond_emb is None:
256
+ return self.org_forward(x)
257
+
258
+ orig_shape = x.shape
259
+ is_5d = x.dim() == 5
260
+ if is_5d:
261
+ B, T, H, W, D = orig_shape
262
+ x = x.reshape(B, T * H * W, D)
263
+
264
+ cx = self.cond_emb # (B_c, S, cond_emb_dim)
265
+
266
+ # Broadcast cond_emb to the runtime batch (CFG cond+uncond, multi-cond).
267
+ if x.shape[0] != cx.shape[0]:
268
+ if x.shape[0] % cx.shape[0] != 0:
269
+ return self.org_forward(x.reshape(orig_shape) if is_5d else x)
270
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1)
271
+
272
+ if x.shape[1] != cx.shape[1]:
273
+ return self.org_forward(x.reshape(orig_shape) if is_5d else x)
274
+
275
+ # Run the LLLite mini-MLP in its own parameter dtype, then cast the
276
+ # correction back to ``x``'s dtype before adding. Robust to autocast
277
+ # flows where x and LLLite weights have different dtypes.
278
+ param_dtype = self.down.weight.dtype
279
+ x_proc = x if x.dtype == param_dtype else x.to(param_dtype)
280
+ if cx.dtype != param_dtype or cx.device != x.device:
281
+ cx = cx.to(device=x.device, dtype=param_dtype)
282
+
283
+ # Per-module depth embedding (zero-init so it's a no-op at train start).
284
+ if self._depth_embeds_ref:
285
+ depth_e = self._depth_embeds_ref[0][self.layer_idx]
286
+ if depth_e.dtype != param_dtype or depth_e.device != x.device:
287
+ depth_e = depth_e.to(device=x.device, dtype=param_dtype)
288
+ cond_local = cx + depth_e
289
+ else:
290
+ cond_local = cx
291
+
292
+ h = F.silu(self.down(x_proc))
293
+
294
+ gb = self.cond_to_film(cond_local)
295
+ gamma, beta = gb.chunk(2, dim=-1)
296
+
297
+ m = self.mid(torch.cat([cond_local, h], dim=-1))
298
+ m = m * (1 + gamma) + beta
299
+ m = F.silu(m)
300
+
301
+ if self.dropout is not None and self.training:
302
+ m = F.dropout(m, p=self.dropout)
303
+
304
+ out = self.up(m) * self.multiplier
305
+ if out.dtype != x.dtype:
306
+ out = out.to(x.dtype)
307
+
308
+ y = self.org_forward(x + out)
309
+
310
+ if is_5d:
311
+ # org Linear out_features may differ from in_features — recover with -1.
312
+ y = y.reshape(orig_shape[0], orig_shape[1], orig_shape[2], orig_shape[3], -1)
313
+ return y
314
+
315
+
316
+ # ----------------------------------------------------------------------------
317
+ # ControlNetLLLiteDiT
318
+ # ----------------------------------------------------------------------------
319
+
320
+ class ControlNetLLLiteDiT(nn.Module):
321
+ def __init__(
322
+ self,
323
+ dit: nn.Module,
324
+ cond_emb_dim: int = 32,
325
+ mlp_dim: int = 64,
326
+ target_layers: str = "self_attn_q",
327
+ dropout: Optional[float] = None,
328
+ multiplier: float = 1.0,
329
+ cond_dim: int = 64,
330
+ cond_resblocks: int = 1,
331
+ use_aspp: bool = False,
332
+ aspp_dilations: Tuple[int, ...] = ASPP_DEFAULT_DILATIONS,
333
+ cond_in_channels: int = 3,
334
+ inpaint_masked_input: bool = False,
335
+ ):
336
+ super().__init__()
337
+
338
+ atomics = parse_target_layers(target_layers)
339
+
340
+ self.cond_emb_dim = cond_emb_dim
341
+ self.mlp_dim = mlp_dim
342
+ self.target_layers = target_layers
343
+ self.target_atomics = atomics
344
+ self.dropout = dropout
345
+ self.multiplier = multiplier
346
+ self.cond_dim = cond_dim
347
+ self.cond_resblocks = cond_resblocks
348
+ self.use_aspp = use_aspp
349
+ self.aspp_dilations = tuple(aspp_dilations) if use_aspp else ()
350
+ # 4ch (RGB+mask) inpainting metadata. `inpaint_masked_input` records the training-time
351
+ # RGB-masking policy for cond_image preparation; it does not alter the forward pass here.
352
+ self.cond_in_channels = cond_in_channels
353
+ self.inpaint_masked_input = inpaint_masked_input
354
+
355
+ self.conditioning1 = _Conditioning1(
356
+ cond_dim, cond_emb_dim, cond_resblocks,
357
+ use_aspp=use_aspp, aspp_dilations=aspp_dilations,
358
+ cond_in_channels=cond_in_channels,
359
+ )
360
+
361
+ modules = self._create_modules(dit, cond_emb_dim, mlp_dim, atomics, dropout, multiplier)
362
+ self.lllite_modules = nn.ModuleList(modules)
363
+
364
+ n = len(self.lllite_modules)
365
+ self.depth_embeds = nn.Parameter(torch.zeros(n, cond_emb_dim))
366
+ for i, m in enumerate(self.lllite_modules):
367
+ m.layer_idx = i
368
+ m._depth_embeds_ref = [self.depth_embeds]
369
+
370
+ aspp_info = f"aspp={'on' + str(list(self.aspp_dilations)) if use_aspp else 'off'}"
371
+ inpaint_info = (
372
+ f", inpaint=on(masked_input={inpaint_masked_input})" if cond_in_channels != 3 else ""
373
+ )
374
+ logger.info(
375
+ "ControlNet-LLLite (Anima v%s): created %d modules for target=%r "
376
+ "(atomics=%s), cond_in_channels=%d, cond_dim=%d, cond_resblocks=%d, %s, "
377
+ "cond_emb_dim=%d, mlp_dim=%d%s",
378
+ LLLITE_ARCH_VERSION, n, target_layers, list(atomics),
379
+ cond_in_channels, cond_dim, cond_resblocks, aspp_info, cond_emb_dim, mlp_dim,
380
+ inpaint_info,
381
+ )
382
+
383
+ @staticmethod
384
+ def _attn_atomic_match(is_self_attn: bool, child_name: str, atomics: Tuple[str, ...]) -> bool:
385
+ if "output_proj" in child_name:
386
+ return False
387
+ if is_self_attn:
388
+ if child_name == "q_proj":
389
+ return "self_attn_q_pre" in atomics
390
+ if child_name in ("k_proj", "v_proj"):
391
+ return "self_attn_kv_pre" in atomics
392
+ return False
393
+ else:
394
+ if child_name == "q_proj":
395
+ return "cross_attn_q_pre" in atomics
396
+ return False # cross_attn K,V live in text-embedding space
397
+
398
+ def _create_modules(
399
+ self,
400
+ dit: nn.Module,
401
+ cond_emb_dim: int,
402
+ mlp_dim: int,
403
+ atomics: Tuple[str, ...],
404
+ dropout: Optional[float],
405
+ multiplier: float,
406
+ ) -> List[LLLiteModuleDiT]:
407
+ modules: List[LLLiteModuleDiT] = []
408
+ want_mlp_fc1 = "mlp_fc1_pre" in atomics
409
+ any_attn = any(a in atomics for a in ("self_attn_q_pre", "self_attn_kv_pre", "cross_attn_q_pre"))
410
+
411
+ for name, module in dit.named_modules():
412
+ if LLM_ADAPTER_NAME in name:
413
+ continue
414
+ cls = module.__class__.__name__
415
+
416
+ if any_attn and cls == TARGET_ATTENTION_CLASS:
417
+ # The Anima-block Attention exposes is_selfattn; the LLM-Adapter
418
+ # Attention does not — skip the latter even if path filter misses.
419
+ if not hasattr(module, "is_selfattn"):
420
+ continue
421
+ is_self_attn = bool(module.is_selfattn)
422
+ for child_name, child in module.named_children():
423
+ if not isinstance(child, nn.Linear):
424
+ continue
425
+ if not self._attn_atomic_match(is_self_attn, child_name, atomics):
426
+ continue
427
+ full_name = f"lllite_dit.{name}.{child_name}".replace(".", "_")
428
+ modules.append(
429
+ LLLiteModuleDiT(full_name, child, cond_emb_dim, mlp_dim, dropout, multiplier)
430
+ )
431
+
432
+ elif want_mlp_fc1 and cls == TARGET_MLP_CLASS:
433
+ child = getattr(module, "layer1", None)
434
+ if not isinstance(child, nn.Linear):
435
+ continue
436
+ full_name = f"lllite_dit.{name}.layer1".replace(".", "_")
437
+ modules.append(
438
+ LLLiteModuleDiT(full_name, child, cond_emb_dim, mlp_dim, dropout, multiplier)
439
+ )
440
+
441
+ return modules
442
+
443
+ def set_cond_image(self, cond_image: Optional[torch.Tensor]):
444
+ """cond_image: (B, 3, H*16, W*16) in [-1, 1]; ``None`` clears."""
445
+ if cond_image is None:
446
+ for m in self.lllite_modules:
447
+ m.cond_emb = None
448
+ return
449
+ cx = self.conditioning1(cond_image) # (B, S, cond_emb_dim)
450
+ for m in self.lllite_modules:
451
+ m.cond_emb = cx
452
+
453
+ def clear_cond_image(self):
454
+ self.set_cond_image(None)
455
+
456
+ def set_multiplier(self, multiplier: float):
457
+ self.multiplier = multiplier
458
+ for m in self.lllite_modules:
459
+ m.multiplier = multiplier
460
+
461
+ def apply_to(self):
462
+ for m in self.lllite_modules:
463
+ m.apply_to()
464
+
465
+ def restore(self):
466
+ for m in self.lllite_modules:
467
+ m.restore()
468
+
469
+
470
+ # ----------------------------------------------------------------------------
471
+ # Save / load (named-key format; legacy lllite_modules.* is rejected)
472
+ # ----------------------------------------------------------------------------
473
+
474
+ _INTERNAL_MODULES_PREFIX = "lllite_modules."
475
+ _INTERNAL_COND_PREFIX = "conditioning1."
476
+ _INTERNAL_DEPTH_KEY = "depth_embeds"
477
+ _SAVED_COND_PREFIX = "lllite_conditioning1."
478
+ _SAVED_DEPTH_SUFFIX = ".depth_embed"
479
+
480
+
481
+ def _from_saved_state_dict(lllite: "ControlNetLLLiteDiT", weights_sd: dict) -> dict:
482
+ """Rewrite a v2 named-key state dict back to the internal layout."""
483
+ name_to_idx = {m.lllite_name: i for i, m in enumerate(lllite.lllite_modules)}
484
+ n_modules = len(name_to_idx)
485
+ out: dict = {}
486
+ depth_slices: dict = {}
487
+
488
+ for k, v in weights_sd.items():
489
+ if k.startswith(_SAVED_COND_PREFIX):
490
+ out[_INTERNAL_COND_PREFIX + k[len(_SAVED_COND_PREFIX):]] = v
491
+ continue
492
+ if k.endswith(_SAVED_DEPTH_SUFFIX):
493
+ name = k[: -len(_SAVED_DEPTH_SUFFIX)]
494
+ if name in name_to_idx:
495
+ depth_slices[name_to_idx[name]] = v
496
+ continue
497
+ head, dot, tail = k.partition(".")
498
+ if dot and head in name_to_idx:
499
+ out[f"{_INTERNAL_MODULES_PREFIX}{name_to_idx[head]}.{tail}"] = v
500
+ continue
501
+ out[k] = v
502
+
503
+ if depth_slices:
504
+ missing = [i for i in range(n_modules) if i not in depth_slices]
505
+ if missing:
506
+ raise RuntimeError(
507
+ f"depth_embed slices missing for module idx(es) {missing}"
508
+ )
509
+ out[_INTERNAL_DEPTH_KEY] = torch.stack(
510
+ [depth_slices[i] for i in range(n_modules)], dim=0
511
+ )
512
+
513
+ return out
514
+
515
+
516
+ def load_lllite_weights(lllite: ControlNetLLLiteDiT, file: str, strict: bool = False):
517
+ if os.path.splitext(file)[1] == ".safetensors":
518
+ from safetensors.torch import load_file
519
+ weights_sd = load_file(file)
520
+ else:
521
+ weights_sd = torch.load(file, map_location="cpu")
522
+
523
+ if any(k.startswith(_INTERNAL_MODULES_PREFIX) for k in weights_sd):
524
+ raise RuntimeError(
525
+ f"weights at {file} appear to be in a legacy ControlNet-LLLite weight format "
526
+ f"(keys starting with '{_INTERNAL_MODULES_PREFIX}'). The current code uses a "
527
+ f"named-key format (per-module key prefix = lllite_name, e.g. "
528
+ f"'lllite_dit_blocks_0_self_attn_q_proj.down.weight'). Re-train with the current codebase."
529
+ )
530
+
531
+ converted = _from_saved_state_dict(lllite, weights_sd)
532
+ info = lllite.load_state_dict(converted, strict=strict)
533
+ logger.info("loaded LLLite weights from %s: %s", file, info)
534
+ return info
535
+
536
+
537
+ def read_lllite_metadata(file: str) -> dict:
538
+ if os.path.splitext(file)[1] != ".safetensors":
539
+ return {}
540
+ from safetensors import safe_open
541
+ with safe_open(file, framework="pt") as f:
542
+ meta = f.metadata()
543
+ return meta or {}
custom_nodes/ComfyUI-Anima-LLLite/nodes.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ComfyUI node for Anima ControlNet-LLLite.
2
+
3
+ Single LoRA-style node: takes a MODEL, an LLLite weights file, a control IMAGE
4
+ and a strength; returns the patched MODEL. Integration is done via
5
+ ``set_model_unet_function_wrapper`` so the LLLite contribution is fully scoped
6
+ to this model clone — no global monkey-patching that could leak into other
7
+ samplers in the same workflow.
8
+
9
+ Because ``model_function_wrapper`` is a single-slot field on ``model_options``,
10
+ cascading two wrapper-installing nodes would normally cause the outer one to
11
+ silently overwrite the inner one. The node captures any pre-existing wrapper
12
+ before cloning and delegates to it from inside its own wrapper, so multiple
13
+ Anima-LLLite nodes (and other well-behaved wrapper nodes) can be stacked. The
14
+ ``preserve_wrapper`` toggle (default on) controls this delegation, mirroring
15
+ ``ChromaRadianceOptions``.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import os
21
+ from typing import Optional
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+
26
+ import folder_paths
27
+
28
+ from .control_net_lllite_anima import (
29
+ ASPP_DEFAULT_DILATIONS,
30
+ ControlNetLLLiteDiT,
31
+ load_lllite_weights,
32
+ read_lllite_metadata,
33
+ )
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ def _get_inner_dit(model) -> torch.nn.Module:
39
+ """Reach the underlying Anima DiT (nn.Module) from a ComfyUI ModelPatcher."""
40
+ inner = getattr(model, "model", None)
41
+ if inner is None:
42
+ raise RuntimeError("Input MODEL has no .model attribute (not a ModelPatcher?)")
43
+ dit = getattr(inner, "diffusion_model", None)
44
+ if dit is None:
45
+ raise RuntimeError("MODEL.model has no .diffusion_model — not a UNet/DiT model?")
46
+ return dit
47
+
48
+
49
+ def _target_cond_hw(latent_h: int, latent_w: int, patch_spatial: int = 2) -> tuple[int, int]:
50
+ """Return the (H, W) the cond image / mask must be resized to.
51
+
52
+ The LLLite ``conditioning1`` Conv has stride 16, so the cond image must be
53
+ sized to ``latent_HW * 8`` in input pixel space (= ``token_HW * 16`` after
54
+ DiT patchify with patch_spatial=2). The DiT internally pads the latent up
55
+ to a multiple of ``patch_spatial`` (see ``MiniTrainDIT.forward`` →
56
+ ``pad_to_patch_size``), so we mirror that rounding here — otherwise odd
57
+ latent dims (e.g. 1032 px → 129 latent) yield a token-count mismatch that
58
+ silently bypasses every LLLite module.
59
+ """
60
+ padded_h = ((latent_h + patch_spatial - 1) // patch_spatial) * patch_spatial
61
+ padded_w = ((latent_w + patch_spatial - 1) // patch_spatial) * patch_spatial
62
+ return padded_h * 8, padded_w * 8
63
+
64
+
65
+ def _prepare_cond_image(image: torch.Tensor, latent_h: int, latent_w: int,
66
+ device: torch.device, dtype: torch.dtype,
67
+ patch_spatial: int = 2) -> torch.Tensor:
68
+ """ComfyUI IMAGE (B,H,W,3) in [0,1] → (1,3,H*8,W*8) in [-1,1]."""
69
+ if image.ndim == 4 and image.shape[-1] == 3:
70
+ # (B, H, W, 3) -> (B, 3, H, W)
71
+ img = image.permute(0, 3, 1, 2).contiguous()
72
+ else:
73
+ raise ValueError(f"Unexpected cond image shape: {tuple(image.shape)} (expected B,H,W,3)")
74
+
75
+ img = img[:1] # use first frame only
76
+ target_h, target_w = _target_cond_hw(latent_h, latent_w, patch_spatial)
77
+ if img.shape[-2] != target_h or img.shape[-1] != target_w:
78
+ img = F.interpolate(img, size=(target_h, target_w), mode="bicubic", align_corners=False)
79
+ img = img.clamp(0.0, 1.0)
80
+ img = img * 2.0 - 1.0
81
+ return img.to(device=device, dtype=dtype)
82
+
83
+
84
+ def _prepare_mask(mask: torch.Tensor, latent_h: int, latent_w: int,
85
+ device: torch.device, dtype: torch.dtype,
86
+ patch_spatial: int = 2) -> torch.Tensor:
87
+ """ComfyUI MASK (B,H,W) in [0,1] → (1,1,H*8,W*8) binarized at 0.5.
88
+
89
+ Returns the mask in ``{0.0, 1.0}`` (1 = inpaint area, 0 = keep). The caller
90
+ is responsible for the ``*2-1`` rescale before concat with RGB.
91
+ """
92
+ if mask.ndim == 3:
93
+ m = mask.unsqueeze(1) # (B, 1, H, W)
94
+ elif mask.ndim == 4 and mask.shape[1] == 1:
95
+ m = mask
96
+ else:
97
+ raise ValueError(f"Unexpected mask shape: {tuple(mask.shape)} (expected B,H,W or B,1,H,W)")
98
+
99
+ m = m[:1]
100
+ target_h, target_w = _target_cond_hw(latent_h, latent_w, patch_spatial)
101
+ if m.shape[-2] != target_h or m.shape[-1] != target_w:
102
+ m = F.interpolate(m.float(), size=(target_h, target_w), mode="nearest")
103
+ m = (m >= 0.5).to(dtype=dtype)
104
+ return m.to(device=device)
105
+
106
+
107
+ def _build_inpaint_cond_image(rgb_pm1: torch.Tensor, mask01: torch.Tensor,
108
+ masked_input: bool) -> torch.Tensor:
109
+ """rgb_pm1: (1,3,H,W) in [-1,1], mask01: (1,1,H,W) in {0,1}. Returns (1,4,H,W).
110
+
111
+ Mirrors ``_build_inpaint_cond_image`` in the sd-scripts training / inference
112
+ code: the mask channel is rescaled to ``[-1, +1]`` (matches the RGB range),
113
+ and if ``masked_input`` is set the RGB is zeroed where ``mask >= 0.5``.
114
+ """
115
+ if masked_input:
116
+ keep = (mask01 < 0.5).to(rgb_pm1.dtype)
117
+ rgb_pm1 = rgb_pm1 * keep
118
+ mask_pm1 = mask01.to(rgb_pm1.dtype) * 2.0 - 1.0
119
+ return torch.cat([rgb_pm1, mask_pm1], dim=1)
120
+
121
+
122
+ class AnimaLLLiteApply:
123
+ @classmethod
124
+ def INPUT_TYPES(cls):
125
+ return {
126
+ "required": {
127
+ "model": ("MODEL",),
128
+ "lllite_name": (folder_paths.get_filename_list("controlnet"),),
129
+ "image": ("IMAGE",),
130
+ "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
131
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
132
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
133
+ "preserve_wrapper": ("BOOLEAN", {"default": True}),
134
+ },
135
+ "optional": {
136
+ # Required when the loaded weights are 4ch (inpaint). White = inpaint area,
137
+ # black = keep. Mismatch with the weights' cond_in_channels is reported below.
138
+ "mask": ("MASK",),
139
+ },
140
+ }
141
+
142
+ RETURN_TYPES = ("MODEL",)
143
+ FUNCTION = "apply"
144
+ CATEGORY = "loaders"
145
+
146
+ def apply(self, model, lllite_name, image, strength, start_percent, end_percent,
147
+ preserve_wrapper=True, mask=None):
148
+ weights_path = folder_paths.get_full_path("controlnet", lllite_name)
149
+ if weights_path is None or not os.path.isfile(weights_path):
150
+ raise FileNotFoundError(f"LLLite weights not found: {lllite_name}")
151
+
152
+ # Architecture is fully determined by the trained weights — read everything
153
+ # from metadata rather than exposing knobs that would just cause load errors.
154
+ meta = read_lllite_metadata(weights_path)
155
+ ce_dim = int(meta.get("lllite.cond_emb_dim", 32))
156
+ m_dim = int(meta.get("lllite.mlp_dim", 64))
157
+ # v2 records the canonical atomic form under lllite.target_atomics; fall back
158
+ # to the legacy preset key, then to the v1 default.
159
+ tl = meta.get("lllite.target_atomics", meta.get("lllite.target_layers", "self_attn_q"))
160
+ cond_dim = int(meta.get("lllite.cond_dim", 64))
161
+ cond_resblocks = int(meta.get("lllite.cond_resblocks", 1))
162
+ use_aspp = str(meta.get("lllite.use_aspp", "false")).lower() == "true"
163
+ aspp_dilations_meta = meta.get("lllite.aspp_dilations")
164
+ if use_aspp and aspp_dilations_meta:
165
+ aspp_dilations = tuple(int(d) for d in aspp_dilations_meta.split(",") if d.strip())
166
+ else:
167
+ aspp_dilations = ASPP_DEFAULT_DILATIONS
168
+ cond_in_channels = int(meta.get("lllite.cond_in_channels", 3))
169
+ inpaint_masked_input = str(meta.get("lllite.inpaint_masked_input", "false")).lower() == "true"
170
+
171
+ # Mask / cond_in_channels consistency: 4ch weights need a MASK, 3ch weights ignore it.
172
+ if cond_in_channels == 4 and mask is None:
173
+ raise ValueError(
174
+ f"LLLite weights '{lllite_name}' were trained with cond_in_channels=4 "
175
+ f"(inpaint mode) and require a MASK input. Connect a MASK to the node "
176
+ f"(white = inpaint area, black = keep)."
177
+ )
178
+ if cond_in_channels != 4 and mask is not None:
179
+ logger.warning(
180
+ "LLLite weights '%s' are %dch; the provided MASK input will be ignored.",
181
+ lllite_name, cond_in_channels,
182
+ )
183
+ mask = None
184
+
185
+ dit = _get_inner_dit(model)
186
+ patch_spatial = int(getattr(dit, "patch_spatial", 2))
187
+ lllite = ControlNetLLLiteDiT(
188
+ dit,
189
+ cond_emb_dim=ce_dim,
190
+ mlp_dim=m_dim,
191
+ target_layers=tl,
192
+ multiplier=strength,
193
+ cond_dim=cond_dim,
194
+ cond_resblocks=cond_resblocks,
195
+ use_aspp=use_aspp,
196
+ aspp_dilations=aspp_dilations,
197
+ cond_in_channels=cond_in_channels,
198
+ inpaint_masked_input=inpaint_masked_input,
199
+ )
200
+ load_lllite_weights(lllite, weights_path, strict=False)
201
+ lllite.eval().requires_grad_(False)
202
+
203
+ # Convert percent range -> sigma range (start_percent=0 → sigma_max).
204
+ model_sampling = model.get_model_object("model_sampling")
205
+ sigma_start = float(model_sampling.percent_to_sigma(start_percent))
206
+ sigma_end = float(model_sampling.percent_to_sigma(end_percent))
207
+
208
+ # Capture image / mask tensors (cloned to detach from any upstream caching)
209
+ src_image = image.detach().clone()
210
+ src_mask = mask.detach().clone() if mask is not None else None
211
+ is_inpaint = cond_in_channels == 4
212
+
213
+ # Cache for the per-resolution preprocessed cond image (avoids repeat resize)
214
+ cache = {"cond_image_pp": None, "key": None, "lllite_loaded_to": None}
215
+
216
+ # Capture any previously-installed wrapper BEFORE we clone — model_options
217
+ # has a single "model_function_wrapper" slot, so without delegation a second
218
+ # wrapper-installing node would silently no-op the first. Mirrors the
219
+ # ChromaRadianceOptions pattern in comfy_extras/nodes_chroma_radiance.py.
220
+ old_wrapper = model.model_options.get("model_function_wrapper")
221
+
222
+ def _call_next(apply_model, input_x, timestep, c):
223
+ if preserve_wrapper and old_wrapper is not None:
224
+ return old_wrapper(apply_model, {"input": input_x, "timestep": timestep, "c": c})
225
+ return apply_model(input_x, timestep, **c)
226
+
227
+ def wrapper(apply_model, args):
228
+ input_x = args["input"]
229
+ timestep = args["timestep"]
230
+ c = args["c"]
231
+
232
+ # Step-range gate: skip LLLite entirely when current sigma is outside
233
+ # [sigma_end, sigma_start]. percent_to_sigma maps 0.0 → sigma_max,
234
+ # 1.0 → sigma_min, so the active window is sigma_end <= sigma <= sigma_start.
235
+ sigma = float(timestep.max().item())
236
+ if not (sigma_end <= sigma <= sigma_start):
237
+ return _call_next(apply_model, input_x, timestep, c)
238
+
239
+ # Anima latent shape: (B, C, T, H, W) — take spatial dims from the tail.
240
+ latent_h, latent_w = int(input_x.shape[-2]), int(input_x.shape[-1])
241
+ device = input_x.device
242
+ dtype = input_x.dtype
243
+
244
+ # Move LLLite to the runtime device/dtype lazily.
245
+ tag = (device, dtype)
246
+ if cache["lllite_loaded_to"] != tag:
247
+ lllite.to(device=device, dtype=dtype)
248
+ cache["lllite_loaded_to"] = tag
249
+ cache["cond_image_pp"] = None # invalidate
250
+
251
+ key = (latent_h, latent_w, device, dtype)
252
+ if cache["key"] != key or cache["cond_image_pp"] is None:
253
+ rgb = _prepare_cond_image(
254
+ src_image, latent_h, latent_w, device, dtype, patch_spatial
255
+ )
256
+ if is_inpaint:
257
+ mk = _prepare_mask(
258
+ src_mask, latent_h, latent_w, device, dtype, patch_spatial
259
+ )
260
+ cache["cond_image_pp"] = _build_inpaint_cond_image(
261
+ rgb, mk, inpaint_masked_input
262
+ )
263
+ else:
264
+ cache["cond_image_pp"] = rgb
265
+ cache["key"] = key
266
+
267
+ lllite.set_multiplier(strength)
268
+ lllite.set_cond_image(cache["cond_image_pp"])
269
+ lllite.apply_to()
270
+ try:
271
+ return _call_next(apply_model, input_x, timestep, c)
272
+ finally:
273
+ lllite.restore()
274
+ lllite.clear_cond_image()
275
+
276
+ m = model.clone()
277
+ m.set_model_unet_function_wrapper(wrapper)
278
+ return (m,)
279
+
280
+
281
+ NODE_CLASS_MAPPINGS = {
282
+ "AnimaLLLiteApply": AnimaLLLiteApply,
283
+ }
284
+
285
+ NODE_DISPLAY_NAME_MAPPINGS = {
286
+ "AnimaLLLiteApply": "Apply Anima ControlNet-LLLite",
287
+ }
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/.github/workflows/publish.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ - master
8
+ paths:
9
+ - "pyproject.toml"
10
+
11
+ permissions:
12
+ issues: write
13
+
14
+ jobs:
15
+ publish-node:
16
+ name: Publish Custom Node to registry
17
+ runs-on: ubuntu-latest
18
+ if: ${{ github.repository_owner == 'BigStationW' }}
19
+ steps:
20
+ - name: Check out code
21
+ uses: actions/checkout@v4
22
+ with:
23
+ submodules: true
24
+ - name: Publish Custom Node
25
+ uses: Comfy-Org/publish-node-action@v1
26
+ with:
27
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
28
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUi-Scale-Image-to-Total-Pixels-Advanced
2
+ ## 1) Intro
3
+ A more advanced version of the [original node](https://github.com/comfyanonymous/ComfyUI/blob/fe01885acf892de636b1b2743903812099bd42e3/comfy_extras/nodes_post_processing.py#L249)
4
+ - Outputs both width and height
5
+ - Allows you to set the "multiple_of" for the width/height pair (e.g., use 16 for 16-channel VAEs)
6
+ - Set "megapixels = 0" to disable megapixel scaling
7
+
8
+ <img width="720" alt="image" src="https://github.com/user-attachments/assets/c5e7558d-9a19-4f20-bea7-c1bb33be878e" />
9
+
10
+ ## 2) Install
11
+ Navigate to the **ComfyUI/custom_nodes** folder and run the following command in your terminal:
12
+
13
+ ```git clone https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced```
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/__init__.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from PIL import Image
5
+ import math
6
+ import comfy.utils
7
+ import comfy.model_management
8
+ import node_helpers
9
+ import os
10
+
11
+ # Tells ComfyUI to look for JavaScript extensions in a folder named "js"
12
+ WEB_DIRECTORY = "./js"
13
+
14
+ class ImageScaleToTotalPixelsX:
15
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
16
+ resize_modes = ["stretch", "crop", "pad"]
17
+
18
+ @classmethod
19
+ def INPUT_TYPES(s):
20
+ return {
21
+ "required": {
22
+ "image": ("IMAGE",),
23
+ "megapixels": ("FLOAT", {
24
+ "default": 1.0,
25
+ "min": 0.0,
26
+ "max": 16.0,
27
+ "step": 0.01
28
+ }),
29
+ "multiple_of": ("INT", {
30
+ "default": 16,
31
+ "min": 1,
32
+ "max": 128,
33
+ "step": 1
34
+ }),
35
+ "resize_mode": (s.resize_modes, {"default": "crop"}),
36
+ "upscale_method": (s.upscale_methods, {"default": "lanczos"}),
37
+ },
38
+ "optional": {
39
+ "width": ("INT", {"forceInput": True}),
40
+ "height": ("INT", {"forceInput": True}),
41
+ },
42
+ "hidden": {
43
+ "unique_id": "UNIQUE_ID",
44
+ }
45
+ }
46
+
47
+ RETURN_TYPES = ("IMAGE", "INT", "INT")
48
+ RETURN_NAMES = ("image", "width", "height")
49
+ FUNCTION = "upscale"
50
+ CATEGORY = "image/upscaling"
51
+
52
+ # THE MAGIC FIX: This forces ComfyUI to save the "ui" return data into the cache history!
53
+ OUTPUT_NODE = True
54
+
55
+ def upscale(
56
+ self,
57
+ image,
58
+ upscale_method,
59
+ megapixels,
60
+ multiple_of,
61
+ resize_mode,
62
+ unique_id=None,
63
+ width=None,
64
+ height=None
65
+ ):
66
+ _, oh, ow, _ = image.shape
67
+ manual_resolution = width is not None and height is not None
68
+
69
+ if manual_resolution:
70
+ target_width = int(width)
71
+ target_height = int(height)
72
+ elif megapixels == 0:
73
+ target_width = ow
74
+ target_height = oh
75
+ else:
76
+ total = int(megapixels * 1000000)
77
+ scale_by = math.sqrt(total / (ow * oh))
78
+ target_width = round(ow * scale_by)
79
+ target_height = round(oh * scale_by)
80
+
81
+ if multiple_of > 1:
82
+ target_width = target_width - (target_width % multiple_of)
83
+ target_height = target_height - (target_height % multiple_of)
84
+
85
+ target_width = max(multiple_of, target_width)
86
+ target_height = max(multiple_of, target_height)
87
+
88
+ resize_width = target_width
89
+ resize_height = target_height
90
+
91
+ x = y = x2 = y2 = 0
92
+ pad_left = pad_right = pad_top = pad_bottom = 0
93
+
94
+ if resize_mode == "pad":
95
+ ratio = min(target_width / ow, target_height / oh)
96
+ new_width = round(ow * ratio)
97
+ new_height = round(oh * ratio)
98
+
99
+ pad_left = (target_width - new_width) // 2
100
+ pad_right = target_width - new_width - pad_left
101
+ pad_top = (target_height - new_height) // 2
102
+ pad_bottom = target_height - new_height - pad_top
103
+
104
+ resize_width = new_width
105
+ resize_height = new_height
106
+
107
+ elif resize_mode == "crop":
108
+ ratio = max(target_width / ow, target_height / oh)
109
+ new_width = round(ow * ratio)
110
+ new_height = round(oh * ratio)
111
+
112
+ x = (new_width - target_width) // 2
113
+ y = (new_height - target_height) // 2
114
+ x2 = x + target_width
115
+ y2 = y + target_height
116
+
117
+ if x2 > new_width:
118
+ x -= x2 - new_width
119
+ if x < 0:
120
+ x = 0
121
+
122
+ if y2 > new_height:
123
+ y -= y2 - new_height
124
+ if y < 0:
125
+ y = 0
126
+
127
+ resize_width = new_width
128
+ resize_height = new_height
129
+
130
+ samples = image.permute(0, 3, 1, 2)
131
+
132
+ if upscale_method == "lanczos":
133
+ outputs = comfy.utils.lanczos(samples, resize_width, resize_height)
134
+ else:
135
+ outputs = F.interpolate(
136
+ samples,
137
+ size=(resize_height, resize_width),
138
+ mode=upscale_method
139
+ )
140
+
141
+ if resize_mode == "pad":
142
+ if pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0:
143
+ outputs = F.pad(
144
+ outputs,
145
+ (pad_left, pad_right, pad_top, pad_bottom),
146
+ value=0
147
+ )
148
+
149
+ outputs = outputs.permute(0, 2, 3, 1)
150
+
151
+ if resize_mode == "crop":
152
+ if x > 0 or y > 0 or x2 > 0 or y2 > 0:
153
+ outputs = outputs[:, y:y2, x:x2, :]
154
+
155
+ if multiple_of > 1 and (
156
+ outputs.shape[2] % multiple_of != 0 or
157
+ outputs.shape[1] % multiple_of != 0
158
+ ):
159
+ final_width = outputs.shape[2]
160
+ final_height = outputs.shape[1]
161
+
162
+ x = (final_width % multiple_of) // 2
163
+ y = (final_height % multiple_of) // 2
164
+ x2 = final_width - ((final_width % multiple_of) - x)
165
+ y2 = final_height - ((final_height % multiple_of) - y)
166
+
167
+ outputs = outputs[:, y:y2, x:x2, :]
168
+
169
+ outputs = torch.clamp(outputs, 0, 1)
170
+
171
+ final_width = outputs.shape[2]
172
+ final_height = outputs.shape[1]
173
+
174
+ text_label = f"{final_width} x {final_height}"
175
+
176
+ # Returns a dict with "ui". Because OUTPUT_NODE = True, ComfyUI natively broadcasts this!
177
+ return {
178
+ "ui": {"text": [text_label]},
179
+ "result": (outputs, final_width, final_height)
180
+ }
181
+
182
+
183
+ NODE_CLASS_MAPPINGS = {
184
+ "ImageScaleToTotalPixelsX": ImageScaleToTotalPixelsX
185
+ }
186
+
187
+ NODE_DISPLAY_NAME_MAPPINGS = {
188
+ "ImageScaleToTotalPixelsX": "Scale Image to Total Pixels Adv"
189
+ }
190
+
191
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (5.23 kB). View file
 
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/js/resolution_display.js ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+
3
+ const TARGET_CLASS = "ImageScaleToTotalPixelsX";
4
+
5
+ const LABEL_ROW_HEIGHT = 42;
6
+ const LABEL_BOTTOM_PADDING = 10;
7
+ const FALLBACK_WIDGET_GAP = 4;
8
+
9
+ function getNodeId(node) {
10
+ return String(node?.id ?? "");
11
+ }
12
+
13
+ function isTargetNode(node) {
14
+ return node?.comfyClass === TARGET_CLASS || node?.type === TARGET_CLASS;
15
+ }
16
+
17
+ function getDefaultNodeFontSize() {
18
+ return window?.LiteGraph?.NODE_TEXT_SIZE || window?.LiteGraph?.WIDGET_TEXT_SIZE || 16;
19
+ }
20
+
21
+ function getDefaultNodeFontFamily() {
22
+ return window?.LiteGraph?.NODE_TEXT_FONT || "Arial, sans-serif";
23
+ }
24
+
25
+ function getDefaultWidgetHeight() {
26
+ return window?.LiteGraph?.NODE_WIDGET_HEIGHT || 20;
27
+ }
28
+
29
+ function markCanvasDirty(node) {
30
+ if (typeof node?.setDirtyCanvas === "function") {
31
+ node.setDirtyCanvas(true, true);
32
+ } else if (app?.canvas?.setDirty) {
33
+ app.canvas.setDirty(true, true);
34
+ }
35
+ }
36
+
37
+ function getWidgetY(widget) {
38
+ const y = Number(widget?.last_y ?? widget?.y);
39
+ return Number.isFinite(y) ? y : null;
40
+ }
41
+
42
+ function getWidgetHeight(widget) {
43
+ const h = Number(widget?.height);
44
+ return Number.isFinite(h) && h > 0 ? h : getDefaultWidgetHeight();
45
+ }
46
+
47
+ function getDrawableWidgets(node) {
48
+ return (node.widgets || [])
49
+ .map((widget) => {
50
+ const y = getWidgetY(widget);
51
+ if (y === null || y <= 0) return null;
52
+ return { widget, y, height: getWidgetHeight(widget) };
53
+ })
54
+ .filter(Boolean)
55
+ .sort((a, b) => a.y - b.y);
56
+ }
57
+
58
+ function getNaturalWidgetGap(node) {
59
+ const widgets = getDrawableWidgets(node);
60
+ if (widgets.length < 2) return FALLBACK_WIDGET_GAP;
61
+
62
+ const gaps = [];
63
+ for (let i = 0; i < widgets.length - 1; i++) {
64
+ const gap = widgets[i + 1].y - (widgets[i].y + widgets[i].height);
65
+ if (Number.isFinite(gap) && gap >= 0 && gap <= 24) gaps.push(gap);
66
+ }
67
+
68
+ if (!gaps.length) return FALLBACK_WIDGET_GAP;
69
+ gaps.sort((a, b) => a - b);
70
+ return gaps[Math.floor(gaps.length / 2)];
71
+ }
72
+
73
+ function getLastWidgetBottom(node) {
74
+ const widgets = getDrawableWidgets(node);
75
+ if (!widgets.length) return 0;
76
+
77
+ let bottom = 0;
78
+ for (const item of widgets) bottom = Math.max(bottom, item.y + item.height);
79
+ return bottom;
80
+ }
81
+
82
+ function getComputedNodeHeight(node) {
83
+ const currentHeight = Number(node?.size?.[1]) || 0;
84
+ try {
85
+ if (typeof node.computeSize === "function") {
86
+ const computed = node.computeSize();
87
+ if (Number.isFinite(computed?.[1])) return computed[1];
88
+ }
89
+ } catch {
90
+ return currentHeight;
91
+ }
92
+ return currentHeight;
93
+ }
94
+
95
+ function getLabelTop(node) {
96
+ const lastWidgetBottom = getLastWidgetBottom(node);
97
+ if (lastWidgetBottom > 0) return Math.ceil(lastWidgetBottom + getNaturalWidgetGap(node));
98
+ return Math.max(0, getComputedNodeHeight(node) - LABEL_ROW_HEIGHT - LABEL_BOTTOM_PADDING);
99
+ }
100
+
101
+ function ensureLabelSpace(node, forceResize = false) {
102
+ if (!node || !isTargetNode(node)) return;
103
+
104
+ const currentWidth = Number(node.size?.[0]) || 300;
105
+ const currentHeight = Number(node.size?.[1]) || 0;
106
+
107
+ const labelTop = getLabelTop(node);
108
+ const wantedHeight = Math.ceil(labelTop + LABEL_ROW_HEIGHT + LABEL_BOTTOM_PADDING);
109
+
110
+ node._scaleImageTotalPixelsLabelTop = labelTop;
111
+ node._scaleImageTotalPixelsWantedHeight = wantedHeight;
112
+
113
+ if (forceResize || currentHeight < wantedHeight) {
114
+ const newSize = [currentWidth, wantedHeight];
115
+ if (typeof node.setSize === "function") node.setSize(newSize);
116
+ else node.size = newSize;
117
+ markCanvasDirty(node);
118
+ }
119
+ }
120
+
121
+ function getLabelY(node) {
122
+ const labelTop = Number(node._scaleImageTotalPixelsLabelTop) || getLabelTop(node);
123
+ return labelTop + (LABEL_ROW_HEIGHT / 2);
124
+ }
125
+
126
+ function applyLabelToNode(node, text) {
127
+ if (!node) return;
128
+ node._scaleImageTotalPixelsLabel = String(text || "");
129
+ ensureLabelSpace(node, true);
130
+ markCanvasDirty(node);
131
+ }
132
+
133
+ function patchNodeDrawing(node) {
134
+ if (!isTargetNode(node) || node._scaleImageTotalPixelsPatched) return;
135
+
136
+ node._scaleImageTotalPixelsPatched = true;
137
+ const originalOnDrawForeground = node.onDrawForeground;
138
+
139
+ node.onDrawForeground = function(ctx) {
140
+ if (originalOnDrawForeground) originalOnDrawForeground.apply(this, arguments);
141
+
142
+ const text = this._scaleImageTotalPixelsLabel;
143
+ if (!text) return;
144
+
145
+ ensureLabelSpace(this, false);
146
+
147
+ const nodeWidth = Number(this.size?.[0]) || 300;
148
+ const x = nodeWidth / 2;
149
+ const y = getLabelY(this);
150
+
151
+ ctx.save();
152
+ ctx.font = `700 ${getDefaultNodeFontSize()}px ${getDefaultNodeFontFamily()}`;
153
+ ctx.textAlign = "center";
154
+ ctx.textBaseline = "middle";
155
+ ctx.fillStyle = "#ffffff";
156
+ ctx.fillText(text, x, y);
157
+ ctx.restore();
158
+ };
159
+ }
160
+
161
+ app.registerExtension({
162
+ name: "scale_image_to_total_pixels_adv.resolution_label",
163
+
164
+ async nodeCreated(node) {
165
+ if (!isTargetNode(node)) return;
166
+ patchNodeDrawing(node);
167
+
168
+ // This handles NATIVE ComfyUI updates (both new generations and Cache History Hits)
169
+ const originalOnExecuted = node.onExecuted;
170
+ node.onExecuted = function(message) {
171
+ if (originalOnExecuted) originalOnExecuted.apply(this, arguments);
172
+
173
+ if (message && message.text) {
174
+ applyLabelToNode(this, message.text[0]);
175
+ }
176
+ };
177
+
178
+ requestAnimationFrame(() => {
179
+ ensureLabelSpace(node, false);
180
+ markCanvasDirty(node);
181
+ });
182
+
183
+ setTimeout(() => {
184
+ ensureLabelSpace(node, false);
185
+ markCanvasDirty(node);
186
+ }, 100);
187
+ },
188
+ });
custom_nodes/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/pyproject.toml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "scale-image-to-total-pixels-advanced"
3
+ description = "A more advanced version of the original ImageScaleToTotalPixels node"
4
+ version = "1.0.0"
5
+ license = {file = "LICENSE"}
6
+ # classifiers = [
7
+ # # For OS-independent nodes (works on all operating systems)
8
+ # "Operating System :: OS Independent",
9
+ #
10
+ # # OR for OS-specific nodes, specify the supported systems:
11
+ # "Operating System :: Microsoft :: Windows", # Windows specific
12
+ # "Operating System :: POSIX :: Linux", # Linux specific
13
+ # "Operating System :: MacOS", # macOS specific
14
+ #
15
+ # # GPU Accelerator support. Pick the ones that are supported by your extension.
16
+ # "Environment :: GPU :: NVIDIA CUDA", # NVIDIA CUDA support
17
+ # "Environment :: GPU :: AMD ROCm", # AMD ROCm support
18
+ # "Environment :: GPU :: Intel Arc", # Intel Arc support
19
+ # "Environment :: NPU :: Huawei Ascend", # Huawei Ascend support
20
+ # "Environment :: GPU :: Apple Metal", # Apple Metal support
21
+ # ]
22
+
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced"
26
+ # Used by Comfy Registry https://registry.comfy.org
27
+ Documentation = "https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/wiki"
28
+ "Bug Tracker" = "https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced/issues"
29
+
30
+ [tool.comfy]
31
+ PublisherId = "bigstationw"
32
+ DisplayName = "ComfyUi-Scale-Image-to-Total-Pixels-Advanced"
33
+ Icon = ""
34
+ includes = []
35
+ # "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
36
+
custom_nodes/ComfyUi-Untwisting-RoPE/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/.github/workflows/publish.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ - master
8
+ paths:
9
+ - "pyproject.toml"
10
+
11
+ permissions:
12
+ issues: write
13
+
14
+ jobs:
15
+ publish-node:
16
+ name: Publish Custom Node to registry
17
+ runs-on: ubuntu-latest
18
+ if: ${{ github.repository_owner == 'BigStationW' }}
19
+ steps:
20
+ - name: Check out code
21
+ uses: actions/checkout@v4
22
+ with:
23
+ submodules: true
24
+ - name: Publish Custom Node
25
+ uses: Comfy-Org/publish-node-action@v1
26
+ with:
27
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
28
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/anima_1.jpg ADDED

Git LFS Details

  • SHA256: f3bd6fe5a5163594bc9b8e078a54a8b245f33de121ecfaed25b4ddcbb478c154
  • Pointer size: 131 Bytes
  • Size of remote file: 967 kB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_1.jpg ADDED

Git LFS Details

  • SHA256: 4c3d72f3514e230b75731a7dd6d721f27d5ed8c8e26b72d1853046c699b416e9
  • Pointer size: 132 Bytes
  • Size of remote file: 1.34 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_10.jpg ADDED

Git LFS Details

  • SHA256: 66015749566729719b35219db8a879a0f42053435140f38e409fee60bd402111
  • Pointer size: 132 Bytes
  • Size of remote file: 1.79 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_2.jpg ADDED

Git LFS Details

  • SHA256: b5aab5da7acfd010930575cde895d1dfc5a42299686738b2fca4455e9094d0ae
  • Pointer size: 131 Bytes
  • Size of remote file: 871 kB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_3.jpg ADDED

Git LFS Details

  • SHA256: 2b5be73d7b982ad86a9970ce464356d1bf891babb91741563c35b7275109fde2
  • Pointer size: 132 Bytes
  • Size of remote file: 1.11 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_4.jpg ADDED

Git LFS Details

  • SHA256: 68c08887ceac12f15e22e7cf90aa73d9e82873e9adb4d5d0dbcbb8cd21f6967a
  • Pointer size: 132 Bytes
  • Size of remote file: 1.25 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_5.jpg ADDED

Git LFS Details

  • SHA256: 83378da379ef6b47a64f11a8f7db6951b3a7d0caa7c891ff33d908bdb5b31b1d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.03 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_6.jpg ADDED

Git LFS Details

  • SHA256: bc43f22f1a8c7e8b94880b7be567822db6ee826b9e2f1749dfbbc7b5c49538a8
  • Pointer size: 132 Bytes
  • Size of remote file: 1.07 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_7.jpg ADDED

Git LFS Details

  • SHA256: a9b631ee488864d28bf1ee9b06b111da7ecd2daa4f1d07353104f87e06767e7d
  • Pointer size: 131 Bytes
  • Size of remote file: 830 kB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_8.jpg ADDED

Git LFS Details

  • SHA256: 21508eb99bd17014b043259aeb4484a15afb9e9af1406f9648cbcdd3220e9ba8
  • Pointer size: 132 Bytes
  • Size of remote file: 1.25 MB
custom_nodes/ComfyUi-Untwisting-RoPE/Examples/z_image_turbo_9.jpg ADDED

Git LFS Details

  • SHA256: dc14268bb02689ece6826347b09d84f3ec05fcaf9212bec0ed1022873e075a15
  • Pointer size: 132 Bytes
  • Size of remote file: 1 MB
custom_nodes/ComfyUi-Untwisting-RoPE/README.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUi-Untwisting-RoPE (Training-Free Style Transfer)
2
+
3
+ This is a ComfyUi implementation of [Untwisting RoPE: Frequency Control for Shared Attention in DiTs](https://arxiv.org/abs/2602.05013)
4
+
5
+ https://untwisting-rope.github.io/
6
+
7
+ <img width="1280" alt="Image 4" src="https://github.com/user-attachments/assets/ea4b7f49-45b0-4812-845b-0bd58824f27c" />
8
+
9
+
10
+ You can see more examples [here](https://github.com/BigStationW/ComfyUi-Untwisting-RoPE/tree/main/Examples).
11
+
12
+ ## Supported models
13
+ - Z-image and Z-image turbo
14
+ - Anima
15
+ - The whole flux2 family
16
+
17
+ ## Installation
18
+
19
+ Navigate to the **ComfyUI\custom_nodes** folder, [open cmd](https://www.youtube.com/watch?v=bgSSJQolR0E&t=47s) and run:
20
+
21
+ ```bash
22
+ git clone https://github.com/BigStationW/ComfyUi-Untwisting-RoPE
23
+ ```
24
+ Restart ComfyUI after installation.
25
+
26
+ ## Usage
27
+
28
+ - Here's [some workflows](https://github.com/BigStationW/ComfyUi-Untwisting-RoPE/tree/main/workflows) for those interested.
29
+ - You also need these custom nodes to make those workflows work.
30
+
31
+ https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced
32
+
33
+ https://github.com/BigStationW/ComfyUi-TextEncodeEditAdvanced
34
+
35
+ Don't hesitate to consult [the documentation](https://github.com/BigStationW/ComfyUi-Untwisting-RoPE/tree/main/documentation) to better understand this repository.
custom_nodes/ComfyUi-Untwisting-RoPE/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
custom_nodes/ComfyUi-Untwisting-RoPE/__pycache__/__init__.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6168d439e8ecb51cb8e1636efe5e6fcf2d750e93d7eaf279d51ed3559d08ecb
3
+ size 131108
custom_nodes/ComfyUi-Untwisting-RoPE/__pycache__/verbose_prints.cpython-312.pyc ADDED
Binary file (48.2 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/documentation/parameters.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-Untwisting-RoPE: Parameters section
2
+
3
+ ## RF Inversion Node
4
+
5
+ RF Inversion builds a noisy trajectory on the reference image, so the model sees a properly noise-matched version of the reference image at every denoising step.
6
+
7
+ | Parameter | Default | Description |
8
+ |-----------|---------|-------------|
9
+ | `reference_latent` | — | The clean reference image latent that the inversion trajectory is built from. |
10
+ | `ref_conditioning` | *(optional)* | Text conditioning associated with the reference image. In practice, it's better to put the target conditioning to it. |
11
+ | `rf_mode` | `rf_gamma_rk2` | Selects the ODE solver used to build the noisy reference trajectory: `linear` (no model calls -> random noise), `rf_gamma` (Euler), `rf_gamma_rk2` (Runge-Kutta midpoint), or `fireflow` [(FireFlow recurrence)](https://arxiv.org/abs/2412.07517?utm_source=chatgpt.com). |
12
+ | `gamma` | `0.50` | Blends weight between model velocity and prior velocity (0 = pure prior / straight path, 1 = pure model); only used by `rf_gamma` and `rf_gamma_rk2`. |
13
+ | `gamma_curve` | `2.00` | Applies a bell-shaped schedule to `gamma` across the sigma range, concentrating model influence toward mid-noise levels; 0 disables the curve. |
14
+ | `norm_strength` | `1.00` | After each RF step, blends the latent's mean/std toward the linear target to prevent feature drift; 0 = off, 1 = full correction. |
15
+ | `pmi_alpha` | `0.50` | [PMI (Proximal-Mean Inversion)](https://arxiv.org/abs/2602.11850) smooths out the velocity estimation by using a running mean across steps, 0 disables PMI. |
16
+
17
+ ---
18
+
19
+ ## Untwisting RoPE Node
20
+
21
+ Untwisting RoPE patches the model's attention layers to let the target image attend to the reference image's keys and values (KV) and then rescales RoPE frequencies to enable style transfer without any training.
22
+
23
+ | Parameter | Default | Description |
24
+ |-----------|---------|-------------|
25
+ | `rf_inversion` | *(optional)* | Fetches the inverted noisy latents created by the `RF Inversion node`. |
26
+ | `beta` | `50.00` | Controls the steepness of the frequency scale curve. Higher values prevent the model from copying the reference image too closely. |
27
+ | `high_scale` | `1.05` | Scale applied to high-frequency components. The higher the value, the more the final image will resemble the structure of the reference image.|
28
+ | `low_scale` | `3.0` | Scale applied to low-frequency components. Controls the strength of the style image. |
29
+ | `adain_strength` | `0.50` | [AdaIN (Arbitrary Style Transfer in Real-time with Adaptive Instance Normalization)](https://arxiv.org/abs/1703.06868) aligns the target style statistics toward the reference. |
30
+ | `blocks` | `0-999` | Block indices to which the reference attention patch is applied. |
custom_nodes/ComfyUi-Untwisting-RoPE/documentation/unofficial_extensions.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unofficial Extensions
2
+
3
+ These options are experimental and are not part of the original Untwisting RoPE paper.
4
+
5
+ ## `adain_on_v`
6
+
7
+ Extends AdaIN alignment from attention `Q/K` to also include `V`.
8
+
9
+ This can help ensure that the final image has a color scheme similar to that of the reference image.
10
+
11
+ ## `post_attention_adain`
12
+
13
+ Matches the target attention output statistics to the reference attention output.
14
+
15
+ This is borrowed from the [feature-injection idea in ConsiStory](https://arxiv.org/abs/2402.03286).
16
+
17
+ Unlike ConsiStory, this implementation does not use masks or spatial correspondence maps. It uses a simpler global AdaIN match.
18
+
19
+ ## `axis0_rope_mode`
20
+
21
+ The paper recommends setting the RoPE's axis 0 to a value equal to `low_scale` (uniform across all frequencies) for the only model they tested which was flux.1-dev. Perhaps this method works very well for that specific model, but for other models such as Z-Image Turbo, the result can be disastrous. It ends up amplifying the signal too much.
22
+
23
+ <img width="720" alt="combined_image" src="https://github.com/user-attachments/assets/21fd928d-6e8e-4827-8095-40fa534de95d" />
24
+
25
+
26
+ You have three choices:
27
+ - `default` -> As the paper intended
28
+ - `match_axes` -> axis0 ends up behaving exactly like the other axes (best results).
29
+ - `constant` -> You set up your own `axis0_rope_scale` value
custom_nodes/ComfyUi-Untwisting-RoPE/models/__init__.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auto-discovered model architecture adapters for UntwistingRoPE.
2
+
3
+ The top-level node code imports this package only. Every model-specific name,
4
+ module lookup, and optional preprocessing routine should live in an adapter module in this folder.
5
+
6
+ Architecture recognition is intentionally metadata-only: adapters are selected
7
+ from ComfyUI's loaded MODEL metadata (``model.model_config`` and
8
+ ``model.model_config.unet_config``), never from diffusion-module shape probes.
9
+
10
+ Drop-in adapter rule:
11
+ Create ``models/new_model.py`` and expose at least:
12
+ ARCHITECTURE = "new_model"
13
+ DISPLAY_NAME = "New Model"
14
+ def matches_model(model_info: dict) -> bool: ...
15
+ def find_diffusion_model(model_patcher): ...
16
+
17
+ Optional hooks are discovered automatically when present:
18
+ default_runtime_cfg(dm=None) -> dict
19
+ prepare_reference_conditioning(...)
20
+ patch_attention_modules(dm, stats, helpers=None)
21
+ is_joint_attention(module) -> bool
22
+ is_attention_name(name, min_layer=0, max_layer=999) -> bool
23
+ uses_reference_branch_kv() -> bool
24
+
25
+ No edit to this registry is needed for a new adapter module. If more than one
26
+ adapter matches the same ComfyUI model metadata, that is a plugin bug and the
27
+ registry raises an explicit error instead of guessing an order.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import importlib
33
+ import pkgutil
34
+ from types import ModuleType
35
+ from typing import Any
36
+
37
+ CONFIG_KEY = "untwisting_rope"
38
+
39
+ _IMPORT_ERRORS: dict[str, str] = {}
40
+
41
+
42
+ _MODEL_ROOT_PATHS = (
43
+ "",
44
+ "model",
45
+ "model.model",
46
+ "inner_model",
47
+ "model.inner_model",
48
+ "wrapped",
49
+ "model.wrapped",
50
+ )
51
+
52
+
53
+ def _plain_value(value: Any) -> Any:
54
+ """Return a debug-safe scalar while preserving metadata adapters match on."""
55
+ if value is None or isinstance(value, (str, int, float, bool)):
56
+ return value
57
+ if isinstance(value, (tuple, list)):
58
+ return [_plain_value(v) for v in value]
59
+ if isinstance(value, dict):
60
+ return {str(k): _plain_value(v) for k, v in value.items()}
61
+ try:
62
+ return str(value)
63
+ except Exception:
64
+ return repr(type(value))
65
+
66
+
67
+ def _plain_dict(value: Any) -> dict[str, Any]:
68
+ if not isinstance(value, dict):
69
+ return {}
70
+ return {str(k): _plain_value(v) for k, v in value.items()}
71
+
72
+
73
+ def _get_attr_path(root: Any, attr_path: str) -> tuple[Any, bool]:
74
+ obj = root
75
+ for part in attr_path.split("."):
76
+ if obj is None or not hasattr(obj, part):
77
+ return None, False
78
+ try:
79
+ obj = getattr(obj, part)
80
+ except Exception:
81
+ return None, False
82
+ return obj, True
83
+
84
+
85
+ def _iter_model_roots(model_patcher: Any) -> tuple[tuple[str, Any], ...]:
86
+ """Yield common ComfyUI wrapper layers until a BaseModel metadata object is found."""
87
+ roots: list[tuple[str, Any]] = []
88
+ seen: set[int] = set()
89
+ for path in _MODEL_ROOT_PATHS:
90
+ if path:
91
+ obj, ok = _get_attr_path(model_patcher, path)
92
+ if not ok:
93
+ continue
94
+ else:
95
+ obj = model_patcher
96
+ if obj is None or id(obj) in seen:
97
+ continue
98
+ seen.add(id(obj))
99
+ roots.append((path or "self", obj))
100
+ return tuple(roots)
101
+
102
+
103
+ def _put_type(info: dict[str, Any], prefix: str, obj: Any) -> None:
104
+ if obj is None:
105
+ return
106
+ cls = type(obj)
107
+ info.setdefault(f"{prefix}_class", cls.__name__)
108
+ info.setdefault(f"{prefix}_module", getattr(cls, "__module__", ""))
109
+
110
+
111
+ def _merge_unet_config(info: dict[str, Any], unet_config: Any) -> None:
112
+ cfg = _plain_dict(unet_config)
113
+ if not cfg:
114
+ return
115
+ info.setdefault("unet_config", cfg)
116
+ for key, value in cfg.items():
117
+ info.setdefault(key, value)
118
+ info.setdefault(f"unet_config.{key}", value)
119
+
120
+
121
+ def build_model_info(model_patcher: Any, base_info: dict[str, Any] | None = None) -> dict[str, Any]:
122
+ """
123
+ Build an identity dictionary from ComfyUI's loaded MODEL metadata only.
124
+
125
+ ComfyUI ``BaseModel`` stores the selected ``supported_models`` instance on
126
+ ``model.model_config`` and its official config on
127
+ ``model.model_config.unet_config``. Adapter selection uses only that
128
+ metadata; there is no architecture inference from diffusion-module shape.
129
+ """
130
+ destination = base_info if isinstance(base_info, dict) else None
131
+ info: dict[str, Any] = dict(destination or {})
132
+
133
+ for path, root in _iter_model_roots(model_patcher):
134
+ model_config = getattr(root, "model_config", None)
135
+ if model_config is None:
136
+ continue
137
+
138
+ info["has_comfy_model_config"] = True
139
+ info.setdefault("model_config_path", path)
140
+ _put_type(info, "model_config", model_config)
141
+ _merge_unet_config(info, getattr(model_config, "unet_config", None))
142
+
143
+ latent_format = getattr(model_config, "latent_format", None)
144
+ if latent_format is not None:
145
+ _put_type(info, "latent_format", latent_format)
146
+
147
+ for attr in ("memory_usage_factor", "manual_cast_dtype"):
148
+ if hasattr(model_config, attr):
149
+ try:
150
+ info.setdefault(attr, _plain_value(getattr(model_config, attr)))
151
+ except Exception:
152
+ pass
153
+ break
154
+
155
+ if destination is not None:
156
+ destination.clear()
157
+ destination.update(info)
158
+ return destination
159
+ return info
160
+
161
+
162
+ def _is_adapter_module(module: ModuleType) -> bool:
163
+ """Return True when a discovered module exposes the metadata adapter API."""
164
+ return (
165
+ callable(getattr(module, "matches_model", None))
166
+ and callable(getattr(module, "find_diffusion_model", None))
167
+ )
168
+
169
+
170
+ def _load_adapters() -> tuple[ModuleType, ...]:
171
+ """Import every non-private Python module in this package as an adapter."""
172
+ adapters: list[ModuleType] = []
173
+ _IMPORT_ERRORS.clear()
174
+
175
+ package_path = __path__ # type: ignore[name-defined]
176
+ package_name = __name__
177
+
178
+ for module_info in pkgutil.iter_modules(package_path):
179
+ name = module_info.name
180
+ if name.startswith("_"):
181
+ continue
182
+ if module_info.ispkg:
183
+ continue
184
+
185
+ qualified_name = f"{package_name}.{name}"
186
+ try:
187
+ module = importlib.import_module(qualified_name)
188
+ except Exception as exc:
189
+ _IMPORT_ERRORS[name] = repr(exc)
190
+ continue
191
+
192
+ if _is_adapter_module(module):
193
+ adapters.append(module)
194
+
195
+ adapters.sort(key=lambda module: str(getattr(module, "ARCHITECTURE", module.__name__)))
196
+ return tuple(adapters)
197
+
198
+
199
+ # Loaded once at package import. A freshly added adapter file is picked up on the
200
+ # next Python/ComfyUI reload, which is the normal plugin-development workflow.
201
+ REGISTERED_ADAPTERS = _load_adapters()
202
+
203
+
204
+ def refresh() -> tuple[ModuleType, ...]:
205
+ """Reload the adapter list after files are added during a live session."""
206
+ global REGISTERED_ADAPTERS
207
+ REGISTERED_ADAPTERS = _load_adapters()
208
+ return REGISTERED_ADAPTERS
209
+
210
+
211
+ def identify(model_patcher: Any, model_info: dict[str, Any] | None = None) -> ModuleType:
212
+ """Return the unique adapter selected by ComfyUI MODEL metadata."""
213
+ model_info = build_model_info(model_patcher, model_info)
214
+
215
+ matched_adapters: list[ModuleType] = []
216
+ match_errors: dict[str, str] = {}
217
+
218
+ for adapter in REGISTERED_ADAPTERS:
219
+ matches = getattr(adapter, "matches_model", None)
220
+ if not callable(matches):
221
+ continue
222
+ try:
223
+ if matches(model_info):
224
+ matched_adapters.append(adapter)
225
+ except Exception as exc:
226
+ match_errors[adapter_key(adapter)] = repr(exc)
227
+
228
+ if len(matched_adapters) == 1:
229
+ return matched_adapters[0]
230
+
231
+ summary = ", ".join(
232
+ f"{key}={model_info.get(key)!r}"
233
+ for key in ("model_config_class", "model_config_module", "image_model", "dim")
234
+ if key in model_info
235
+ ) or "no ComfyUI model_config metadata found"
236
+
237
+ details = ""
238
+ if _IMPORT_ERRORS:
239
+ details += " Adapter import errors: " + "; ".join(
240
+ f"{name}: {error}" for name, error in sorted(_IMPORT_ERRORS.items())
241
+ )
242
+ if match_errors:
243
+ details += " Adapter match errors: " + "; ".join(
244
+ f"{name}: {error}" for name, error in sorted(match_errors.items())
245
+ )
246
+
247
+ if matched_adapters:
248
+ matched = ", ".join(adapter_key(adapter) for adapter in matched_adapters)
249
+ raise RuntimeError(
250
+ "Multiple adapters matched the same ComfyUI MODEL metadata "
251
+ f"({summary}): {matched}. Adapter metadata matches must be unique."
252
+ f"{details}"
253
+ )
254
+
255
+ raise RuntimeError(
256
+ "Could not resolve a supported diffusion architecture from ComfyUI MODEL metadata "
257
+ f"({summary}).{details}"
258
+ )
259
+
260
+
261
+ def adapter_label(adapter: Any) -> str:
262
+ return str(getattr(adapter, "DISPLAY_NAME", getattr(adapter, "ARCHITECTURE", type(adapter).__name__)))
263
+
264
+
265
+ def adapter_key(adapter: Any) -> str:
266
+ return str(getattr(adapter, "ARCHITECTURE", type(adapter).__name__))
267
+
268
+
269
+ __all__ = [
270
+ "CONFIG_KEY",
271
+ "REGISTERED_ADAPTERS",
272
+ "refresh",
273
+ "build_model_info",
274
+ "identify",
275
+ "adapter_key",
276
+ "adapter_label",
277
+ ]
custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (12.3 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/anima.cpython-312.pyc ADDED
Binary file (22.9 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/flux2.cpython-312.pyc ADDED
Binary file (36.9 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/models/__pycache__/zimage.cpython-312.pyc ADDED
Binary file (17.4 kB). View file
 
custom_nodes/ComfyUi-Untwisting-RoPE/models/_template.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ _template.py — Architecture Adapter Template
3
+ =============================================
4
+ Copy this file, rename it (e.g. my_model.py), and fill in every section marked
5
+ TODO. Remove all TODO comments and placeholder raises before shipping.
6
+
7
+ HOW AN ADAPTER FITS IN
8
+ -----------------------
9
+ The host node (the ComfyUI node or __init__.py) is model-neutral. It:
10
+ 1. Calls matches_model() on every loaded model to select the right adapter.
11
+ 2. Calls find_diffusion_model() to unwrap the raw diffusion module.
12
+ 3. Calls default_runtime_cfg() to get architecture-specific config fields.
13
+ 4. Calls prepare_reference_conditioning() to preprocess reference latents/embeds.
14
+ 5. Calls patch_attention_modules() to inject the reference-branch logic.
15
+
16
+ Your adapter file owns ALL architecture-specific knowledge. The host supplies
17
+ only generic helpers (math utilities, config keys) through the `helpers` dict.
18
+
19
+ CONVENTIONS SEEN ACROSS ALL ADAPTERS
20
+ --------------------------------------
21
+ - Every public function raises RuntimeError (never silently falls back) in strict mode.
22
+ - patch_attention_modules() saves and restores the original forward before patching,
23
+ so the patch is idempotent when called twice.
24
+ - The patched forward checks cfg["enabled"] first; when False it calls orig unchanged.
25
+ - Batch layout is always [target_batch | reference_batch | optional_uncond_batch].
26
+ - stats is a live object: increment stats.attn_calls etc. if the attribute exists.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Standard library / torch imports
33
+ # ---------------------------------------------------------------------------
34
+ import traceback
35
+ import types
36
+ from typing import Any, Optional, Tuple
37
+
38
+ import torch
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # TODO: import any ComfyUI math helpers your architecture needs.
42
+ # Examples from real adapters:
43
+ # from comfy.ldm.flux.math import apply_rope, attention as flux_attention
44
+ # from comfy.ldm.modules.attention import optimized_attention_masked
45
+ # ---------------------------------------------------------------------------
46
+
47
+
48
+ # ===========================================================================
49
+ # SECTION 1 — IDENTITY
50
+ # ===========================================================================
51
+
52
+ # Short machine-readable tag; stored in cfg["architecture"] at runtime.
53
+ # Must be unique across all adapters in the project.
54
+ ARCHITECTURE: str = "my_model" # TODO: replace with your architecture name
55
+
56
+ # Human-readable label used in log messages and error strings.
57
+ DISPLAY_NAME: str = "My Model" # TODO: replace with your display name
58
+
59
+ # Name(s) of the ComfyUI supported_models class that identifies this architecture.
60
+ # Found in comfy/supported_models.py. Use a set if multiple variants share one adapter
61
+ # (e.g. ZImage uses {"ZImage", "ZImagePixelSpace", "Lumina2"}).
62
+ # Use a plain string constant (COMFY_MODEL_CONFIG_CLASS) when there is exactly one.
63
+ SUPPORTED_MODEL_CONFIG_CLASSES: set[str] = {"MyModelClass"} # TODO
64
+
65
+ # The config key written into transformer_options so patched forwards can find
66
+ # their runtime config. Must match what the host node writes.
67
+ CONFIG_KEY: str = "untwisting_rope" # change only if your host node uses a different key
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Candidate attribute paths to unwrap the raw diffusion module from whatever
71
+ # wrapper ComfyUI has placed around it. Tried in order; first hit wins.
72
+ # This list is identical across all existing adapters — keep it unless ComfyUI
73
+ # ever adds a new wrapper layer.
74
+ # ---------------------------------------------------------------------------
75
+ _DIFFUSION_ATTR_PATHS: tuple[str, ...] = (
76
+ "model.diffusion_model",
77
+ "model.model.diffusion_model",
78
+ "inner_model.diffusion_model",
79
+ "model.inner_model.diffusion_model",
80
+ "diffusion_model",
81
+ )
82
+
83
+
84
+ # ===========================================================================
85
+ # SECTION 2 — SAFE ATTRIBUTE HELPERS (copy verbatim, no need to modify)
86
+ # ===========================================================================
87
+
88
+ def _get_attr_path(root: Any, attr_path: str) -> tuple[Any, bool]:
89
+ """Walk a dotted attribute path safely. Returns (value, True) or (None, False)."""
90
+ obj = root
91
+ for part in attr_path.split("."):
92
+ if obj is None or not hasattr(obj, part):
93
+ return None, False
94
+ try:
95
+ obj = getattr(obj, part)
96
+ except Exception:
97
+ return None, False
98
+ return obj, True
99
+
100
+
101
+ def _safe_int(value: Any, default: int | None = None) -> int | None:
102
+ try:
103
+ return int(value)
104
+ except Exception:
105
+ return default
106
+
107
+
108
+ def _coerce_bool(value: Any) -> bool:
109
+ if isinstance(value, str):
110
+ return value.strip().lower() in ("1", "true", "yes", "on", "y", "t")
111
+ return bool(value)
112
+
113
+
114
+ def _coerce_strength01(value: Any, default: float = 0.0) -> float:
115
+ """Parse and validate a [0, 1] float strength parameter."""
116
+ try:
117
+ strength = float(value)
118
+ except Exception as exc:
119
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].") from exc
120
+ if not torch.isfinite(torch.tensor(strength)):
121
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].")
122
+ if not 0.0 <= strength <= 1.0:
123
+ raise ValueError(f"Invalid strength value {strength!r}; expected value in [0, 1].")
124
+ return strength
125
+
126
+
127
+ def _lerp(a: float, b: float, t: float) -> float:
128
+ return float(a + (b - a) * t)
129
+
130
+
131
+ def _adain(target: torch.Tensor, style: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
132
+ """Instance-normalise target to match style statistics (seq-dim = dim 1)."""
133
+ t_mean = target.mean(dim=1, keepdim=True)
134
+ s_mean = style.mean(dim=1, keepdim=True)
135
+ t_std = target.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
136
+ s_std = style.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
137
+ return (target - t_mean) / t_std * s_std + s_mean
138
+
139
+
140
+ # ===========================================================================
141
+ # SECTION 3 — REQUIRED HOOKS (called by the host node)
142
+ # ===========================================================================
143
+
144
+ def matches_model(model_info: dict[str, Any]) -> bool:
145
+ """Return True iff this adapter handles the loaded model.
146
+
147
+ The host iterates all registered adapters and calls this on each.
148
+ model_info is a dict produced by ComfyUI with at least:
149
+ - "model_config_class": str (name of the class in supported_models.py)
150
+ - "unet_config": dict (raw unet config, varies per model)
151
+
152
+ Keep the implementation simple: only trust model_config_class.
153
+ """
154
+ return str(model_info.get("model_config_class", "")) in SUPPORTED_MODEL_CONFIG_CLASSES
155
+
156
+
157
+ def is_model_identity(model_info: dict[str, Any]) -> bool:
158
+ """Backward-compatible alias kept for older callers. Do not remove."""
159
+ return matches_model(model_info)
160
+
161
+
162
+ def find_diffusion_model(model_patcher: Any) -> Any:
163
+ """Unwrap and return the raw diffusion module from a ComfyUI ModelPatcher.
164
+
165
+ Tries each path in _DIFFUSION_ATTR_PATHS in order.
166
+ Raises RuntimeError (never returns None) — the host relies on this guarantee.
167
+ """
168
+ for path in _DIFFUSION_ATTR_PATHS:
169
+ obj, ok = _get_attr_path(model_patcher, path)
170
+ if ok and obj is not None:
171
+ return obj
172
+ raise RuntimeError(f"Could not find ComfyUI BaseModel.diffusion_model for {DISPLAY_NAME}.")
173
+
174
+
175
+ # ===========================================================================
176
+ # SECTION 4 — ARCHITECTURE-SPECIFIC PARAMETER READERS
177
+ # ===========================================================================
178
+ # These are called by default_runtime_cfg() below.
179
+ # Add or remove functions to match what your model exposes.
180
+
181
+ def _axes_dims_from_dm(dm: Any) -> list[int]:
182
+ """Read the RoPE axis dimensions from the diffusion module.
183
+
184
+ TODO: adapt to your model's actual attribute layout.
185
+
186
+ FLUX.2 example:
187
+ params = dm.params
188
+ return list(params.axes_dim)
189
+
190
+ Anima example (derived from head_dim):
191
+ hd = int(dm.blocks[0].self_attn.head_dim)
192
+ dim_h = (hd // 6) * 2
193
+ return [hd - 2*dim_h, dim_h, dim_h]
194
+
195
+ Z-Image example:
196
+ return list(dm.axes_dims)
197
+ """
198
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement _axes_dims_from_dm().")
199
+
200
+
201
+ def _head_dim_from_dm(dm: Any) -> int:
202
+ """Read head_dim from the diffusion module.
203
+
204
+ TODO: adapt to your model's actual attribute layout.
205
+
206
+ FLUX.2 example:
207
+ return dm.params.hidden_size // dm.params.num_heads
208
+
209
+ Anima example:
210
+ return int(dm.blocks[0].self_attn.head_dim)
211
+ """
212
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement _head_dim_from_dm().")
213
+
214
+
215
+ # ===========================================================================
216
+ # SECTION 5 — RUNTIME CONFIG
217
+ # ===========================================================================
218
+
219
+ def default_runtime_cfg(dm: Any | None = None) -> dict[str, Any]:
220
+ """Return architecture-specific fields merged into the main runtime config.
221
+
222
+ The host calls this once per generation run and stores the result under
223
+ transformer_options[CONFIG_KEY]. Always include "architecture".
224
+
225
+ If your model needs head_dim or axes_dims at patch time, read them here and
226
+ store them in cfg so the patched forward doesn't have to re-read them.
227
+
228
+ For simple architectures that don't need dm at all, set dm=None and ignore it
229
+ (see Z-Image, which only populates cfg["architecture"]).
230
+ """
231
+ cfg: dict[str, Any] = {"architecture": ARCHITECTURE}
232
+
233
+ if dm is None:
234
+ # TODO: decide whether your adapter requires dm or not.
235
+ # If it does, raise here. If not, return cfg as-is.
236
+ return cfg
237
+
238
+ # TODO: populate architecture-specific fields, for example:
239
+ # cfg["head_dim"] = _head_dim_from_dm(dm)
240
+ # cfg["axes_dims"] = _axes_dims_from_dm(dm)
241
+ #
242
+ # For models whose attention sees only image tokens (no text prefix),
243
+ # also set the AdaIN image-token range so the generic helper knows where
244
+ # image tokens live in the sequence:
245
+ # cfg["target_qk_adain_ranges"] = [(0, 2 ** 31 - 1)] # clamped at runtime
246
+
247
+ return cfg
248
+
249
+
250
+ # ===========================================================================
251
+ # SECTION 6 — MODULE IDENTIFICATION HELPERS
252
+ # ===========================================================================
253
+ # These let the host (and patch_attention_modules) locate which submodules to patch.
254
+
255
+ def is_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
256
+ """Return True iff `name` is a module path that should be patched.
257
+
258
+ TODO: replace the body with your architecture's naming scheme.
259
+
260
+ Naming scheme examples:
261
+ Anima — "blocks.N.self_attn" → parts = ["blocks", N, "self_attn"]
262
+ FLUX.2 — "double_blocks.N.img_attn" / "single_blocks.N"
263
+ Z-Image — "layers.N.attention" / "noise_refiner.N.attention"
264
+ """
265
+ parts = str(name).split(".")
266
+ # TODO: validate parts length, prefix, suffix, and numeric index.
267
+ # Example for "blocks.N.self_attn":
268
+ # if len(parts) != 3: return False
269
+ # if parts[0] != "blocks" or parts[2] != "self_attn": return False
270
+ # try:
271
+ # idx = int(parts[1])
272
+ # except Exception:
273
+ # return False
274
+ # return min_layer <= idx <= max_layer
275
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement is_attention_name().")
276
+
277
+
278
+ def is_attention_module(module: Any) -> bool:
279
+ """Return True iff `module` is a patchable attention object.
280
+
281
+ Check for the specific attributes your patched forward will actually use.
282
+ This guards against patching the wrong module if ComfyUI renames things.
283
+
284
+ TODO: fill in the attribute names your forward accesses on `self`.
285
+
286
+ Anima example:
287
+ required = ("q_proj", "k_proj", "v_proj", "attn_op", "n_heads", "head_dim", ...)
288
+ return all(hasattr(module, a) for a in required)
289
+ """
290
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement is_attention_module().")
291
+
292
+
293
+ def block_index_from_name(name: str) -> int:
294
+ """Extract the integer block index from a module name. Used for active_blocks filtering.
295
+
296
+ TODO: implement for your naming scheme.
297
+
298
+ Anima example: "blocks.3.self_attn" → 3
299
+ FLUX.2 example: "double_blocks.7.img_attn" → 7
300
+ """
301
+ parts = str(name).split(".")
302
+ # TODO: find and return the integer layer index.
303
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement block_index_from_name().")
304
+
305
+
306
+ # ===========================================================================
307
+ # SECTION 7 — REFERENCE CONDITIONING PRE-PROCESSING (optional)
308
+ # ===========================================================================
309
+
310
+ def prepare_reference_conditioning(
311
+ ref_conditioning: Any,
312
+ dm: Any,
313
+ device: Any,
314
+ dtype: Any,
315
+ stats: Any,
316
+ label: str = "",
317
+ helpers: dict[str, Any] | None = None,
318
+ ) -> tuple[Any, str]:
319
+ """Pre-process the reference conditioning before the generation loop.
320
+
321
+ Most adapters return (ref_conditioning, "not-applicable") unchanged.
322
+ Only override if your architecture requires a forward pass on dm to convert
323
+ raw embeddings before they can be used as reference conditioning
324
+ (see anima.py for a real example that calls dm.preprocess_text_embeds()).
325
+
326
+ Returns:
327
+ (processed_conditioning, status_string)
328
+ """
329
+ # TODO: if your model needs preprocessing, implement it here.
330
+ # Otherwise leave this as-is.
331
+ return ref_conditioning, "not-applicable"
332
+
333
+
334
+ # ===========================================================================
335
+ # SECTION 8 — ATTENTION MODULE PATCHING (core of the adapter)
336
+ # ===========================================================================
337
+
338
+ def patch_attention_modules(
339
+ dm: Any,
340
+ stats: Any,
341
+ helpers: dict[str, Any] | None = None,
342
+ ) -> tuple[int, int, int, list[str]]:
343
+ """Monkey-patch every attention module in dm with the reference-injection forward.
344
+
345
+ Parameters
346
+ ----------
347
+ dm Raw diffusion module returned by find_diffusion_model().
348
+ stats Live stats object. Increment stats.attn_calls etc. when the attribute exists.
349
+ helpers Dict of callable helpers provided by the host node. Required helpers differ
350
+ per adapter — declare what you need and raise if they're missing.
351
+
352
+ Returns
353
+ -------
354
+ (matched, installed, restored, patched_names)
355
+ matched — number of modules that matched is_attention_name + is_attention_module
356
+ installed — number of modules that received a new patched forward
357
+ restored — number of modules whose previous patch was replaced/restored
358
+ patched_names — list of module name strings that were patched
359
+ """
360
+ helpers = helpers or {}
361
+
362
+ # ------------------------------------------------------------------
363
+ # TODO: declare the helpers your patched forward needs and validate them.
364
+ # Common helpers supplied by the host:
365
+ # "lerp" — _lerp(a, b, t) -> float
366
+ # "cross_batch_adain_qk" — AdaIN on Q/K across target/ref batches
367
+ # "build_frequency_scale_vector" — builds per-head RoPE scale vector
368
+ # "config_key" — transformer_options key for this adapter's cfg
369
+ # "patch_context_refiner_mask_modules" — Z-Image specific
370
+ # "patch_patchify_and_embed" — Z-Image specific
371
+ # ------------------------------------------------------------------
372
+ required_helpers: tuple[str, ...] = (
373
+ "lerp",
374
+ "cross_batch_adain_qk",
375
+ "build_frequency_scale_vector",
376
+ # TODO: add any others your forward needs
377
+ )
378
+ missing = [name for name in required_helpers if not callable(helpers.get(name))]
379
+ if missing:
380
+ raise RuntimeError(f"{DISPLAY_NAME} adapter missing required helper(s): {missing}")
381
+
382
+ lerp = helpers["lerp"]
383
+ cross_batch_adain_qk = helpers["cross_batch_adain_qk"]
384
+ build_frequency_scale_vector = helpers["build_frequency_scale_vector"]
385
+ config_key = str(helpers.get("config_key", CONFIG_KEY))
386
+
387
+ matched = 0
388
+ installed = 0
389
+ restored = 0
390
+ patched_names: list[str] = []
391
+
392
+ for name, module in dm.named_modules():
393
+ # ---- filter to patchable targets ----
394
+ if not is_attention_name(name, 0, 999):
395
+ continue
396
+ if not is_attention_module(module):
397
+ continue
398
+
399
+ matched += 1
400
+ patched_names.append(name)
401
+
402
+ # ---- idempotent save/restore of the original forward ----
403
+ # Always restore first so repeated calls don't chain-wrap.
404
+ _ORIG_FWD_ATTR = "_untwist_orig_forward" # TODO: use a unique attr name per adapter
405
+ if hasattr(module, _ORIG_FWD_ATTR):
406
+ module.forward = getattr(module, _ORIG_FWD_ATTR)
407
+ restored += 1
408
+ else:
409
+ setattr(module, _ORIG_FWD_ATTR, module.forward)
410
+ original_forward = getattr(module, _ORIG_FWD_ATTR)
411
+
412
+ # ----------------------------------------------------------------
413
+ # Build the patched forward.
414
+ # Use a factory (make_forward) to close over `orig` and `module_name`
415
+ # so each module gets its own closure — a plain lambda in a loop
416
+ # would capture the loop variable by reference.
417
+ # ----------------------------------------------------------------
418
+ def make_forward(orig, module_name: str):
419
+
420
+ # TODO: adjust the signature to match your module's actual forward signature.
421
+ # Examples:
422
+ # Anima — (self, x, context=None, rope_emb=None, transformer_options={})
423
+ # Z-Image — (self, x, x_mask, freqs_cis, transformer_options={})
424
+ # FLUX.2 double — (self, img, txt, vec, pe, attn_mask=None, ..., transformer_options={})
425
+ def patched_forward(self, x, transformer_options={}):
426
+
427
+ # ---- fast-path: adapter disabled ----
428
+ cfg = (
429
+ transformer_options.get(config_key)
430
+ if isinstance(transformer_options, dict) else None
431
+ )
432
+ if not cfg or not cfg.get("enabled"):
433
+ # TODO: pass the correct arguments to orig() for your architecture.
434
+ return orig(x, transformer_options=transformer_options)
435
+
436
+ # ---- validate batch layout ----
437
+ target_bsz = int(cfg.get("cross_batch_target_batch", 0))
438
+ if target_bsz <= 0:
439
+ raise RuntimeError(
440
+ f"{DISPLAY_NAME} Untwisting enabled in {module_name}, "
441
+ f"but cross_batch_target_batch={target_bsz}."
442
+ )
443
+ if not torch.is_tensor(x) or x.ndim != 3:
444
+ raise RuntimeError(
445
+ f"{DISPLAY_NAME} Untwisting expected x as [B,S,C] tensor in "
446
+ f"{module_name}; got {type(x).__name__} ndim={getattr(x,'ndim',None)}."
447
+ )
448
+
449
+ bsz, seqlen, _ = x.shape
450
+ if bsz < target_bsz * 2:
451
+ raise RuntimeError(
452
+ f"{DISPLAY_NAME} Untwisting expected ≥ target+reference batches in "
453
+ f"{module_name}; bsz={bsz}, target_bsz={target_bsz}."
454
+ )
455
+
456
+ # ---- active_blocks gate ----
457
+ # block_index comes from transformer_options["block_index"] if the host
458
+ # sets it, otherwise derive it from the module name.
459
+ block_idx = int(transformer_options.get("block_index", block_index_from_name(module_name)))
460
+ active_blocks = cfg.get("active_blocks", set())
461
+ if active_blocks and block_idx not in active_blocks:
462
+ return orig(x, transformer_options=transformer_options)
463
+
464
+ try:
465
+ if hasattr(stats, "attn_calls"):
466
+ stats.attn_calls += 1
467
+ if hasattr(stats, "adapter_attn_calls"):
468
+ stats.adapter_attn_calls += 1
469
+
470
+ # --------------------------------------------------------
471
+ # TODO: implement your QKV extraction.
472
+ # The exact code depends on your model. Common patterns:
473
+ #
474
+ # Pattern A — dedicated proj layers (Anima style):
475
+ # q, k, v = self.compute_qkv(x, context, rope_emb=rope_emb)
476
+ #
477
+ # Pattern B — fused QKV linear (Z-Image / Lumina style):
478
+ # xq, xk, xv = torch.split(self.qkv(x), [...], dim=-1)
479
+ # xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
480
+ # ...
481
+ # xq = self.q_norm(xq); xk = self.k_norm(xk)
482
+ #
483
+ # Pattern C — FLUX single-block fused linear1:
484
+ # qkv, mlp = torch.split(self.linear1(normed_x), [...], dim=-1)
485
+ # q, k, v = qkv.view(...).permute(2, 0, 3, 1, 4)
486
+ # --------------------------------------------------------
487
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement QKV extraction in patched_forward.")
488
+
489
+ # --------------------------------------------------------
490
+ # TODO: determine the image-token slice within the sequence.
491
+ # Architecture-specific:
492
+ #
493
+ # Anima: entire sequence is image tokens → (0, seqlen)
494
+ # Z-Image noise_refiner: entire sequence → (0, seqlen)
495
+ # Z-Image main layers: read from cfg["ref_real_ranges"][0]
496
+ # FLUX double-stream: read from transformer_options["img_slice"]
497
+ # --------------------------------------------------------
498
+ img_s, img_e = 0, seqlen # TODO: replace with correct slice
499
+
500
+ # --------------------------------------------------------
501
+ # Pre-RoPE AdaIN on Q/K (and optionally V) image tokens.
502
+ # Leave these lines as-is if using [B,S,H,D] layout.
503
+ # For [B,H,S,D] (FLUX) see flux2.py _flux_adain_qkv_for_image_range.
504
+ # --------------------------------------------------------
505
+ a = float(cfg.get("adain_strength", 0.0))
506
+ apply_adain = cfg.get("apply_adain", False) and a > 0.0
507
+ if apply_adain:
508
+ # TODO: replace q, k (and optionally v) with AdaIN-adjusted versions.
509
+ # Example for [B,S,H,D] layout:
510
+ # q, k = cross_batch_adain_qk(q, k, cfg, target_bsz, a)
511
+ pass
512
+
513
+ # --------------------------------------------------------
514
+ # TODO: apply RoPE if your architecture uses it.
515
+ # Example for Z-Image / FLUX:
516
+ # q, k = apply_rope(q, k, freqs_cis)
517
+ # Anima applies RoPE inside compute_qkv already.
518
+ # --------------------------------------------------------
519
+
520
+ # --------------------------------------------------------
521
+ # Build the frequency-scale vector for reference K injection.
522
+ # The scale_vec de-emphasises high-frequency (positional) info
523
+ # from the reference K so it doesn't over-constrain the layout.
524
+ # --------------------------------------------------------
525
+ progress = float(cfg.get("progress", 0.0))
526
+ high_scale = lerp(cfg["high_scale_start"], cfg["high_scale_end"], progress)
527
+ low_scale = lerp(cfg["low_scale_start"], cfg["low_scale_end"], progress)
528
+ beta = float(cfg.get("beta", 2.0))
529
+
530
+ # TODO: replace self.head_dim with the correct attribute for your model.
531
+ head_dim = int(self.head_dim)
532
+ scale_vec = build_frequency_scale_vector(
533
+ head_dim,
534
+ cfg.get("axes_dims") or getattr(dm, "axes_dims", []),
535
+ high_scale, low_scale, beta,
536
+ # TODO: use q.device / q.dtype, or k.device / k.dtype
537
+ x.device, x.dtype,
538
+ runtime_cfg=cfg,
539
+ )
540
+ # Shape for broadcasting — adjust to match your q/k layout:
541
+ # [B,S,H,D] → scale_vec.view(1, 1, 1, head_dim)
542
+ # [B,H,S,D] → scale_vec.view(1, 1, 1, head_dim)
543
+ scale_vec = scale_vec.view(1, 1, 1, head_dim) # TODO: check layout
544
+
545
+ # --------------------------------------------------------
546
+ # TARGET STREAM
547
+ # Concatenate target K/V with scaled reference K/V so the
548
+ # target denoising step can "see" the reference image.
549
+ # --------------------------------------------------------
550
+ # TODO: adapt slicing to your actual q/k/v tensor shapes.
551
+ # The example below assumes [B, S, H, D] layout.
552
+ #
553
+ # ref_k = k[target_bsz:target_bsz*2, img_s:img_e] * scale_vec
554
+ # ref_v = v[target_bsz:target_bsz*2, img_s:img_e]
555
+ # k_t_full = torch.cat([k[:target_bsz], ref_k], dim=1)
556
+ # v_t_full = torch.cat([v[:target_bsz], ref_v], dim=1)
557
+ # out_t = <your_attention_op>(q[:target_bsz], k_t_full, v_t_full, ...)
558
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement target stream attention.")
559
+
560
+ # --------------------------------------------------------
561
+ # REFERENCE STREAM
562
+ # Reference attends only to itself — no injection.
563
+ # --------------------------------------------------------
564
+ # out_r = <your_attention_op>(q[target_bsz:target_bsz*2],
565
+ # k[target_bsz:target_bsz*2],
566
+ # v[target_bsz:target_bsz*2], ...)
567
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement reference stream attention.")
568
+
569
+ # --------------------------------------------------------
570
+ # POST-ATTENTION AdaIN (optional)
571
+ # --------------------------------------------------------
572
+ post_a = _coerce_strength01(cfg.get("post_attention_adain_strength", 0.0))
573
+ if post_a > 0.0:
574
+ # TODO: blend out_t image tokens toward out_r statistics.
575
+ # out_t_adain = _adain(out_t[:, img_s:img_e], out_r[:, img_s:img_e])
576
+ # out_t[:, img_s:img_e] = out_t[:, img_s:img_e] * (1-post_a) + out_t_adain * post_a
577
+ pass
578
+
579
+ # --------------------------------------------------------
580
+ # EXTRA BATCHES (uncond / classifier-free guidance negative)
581
+ # --------------------------------------------------------
582
+ outs = [out_t, out_r]
583
+ if bsz > target_bsz * 2:
584
+ # out_e = <your_attention_op>(q[target_bsz*2:], k[target_bsz*2:], v[target_bsz*2:], ...)
585
+ # outs.append(out_e)
586
+ raise NotImplementedError(f"{DISPLAY_NAME}: implement extra (uncond) batch attention.")
587
+
588
+ final_out = torch.cat(outs, dim=0)
589
+
590
+ # --------------------------------------------------------
591
+ # TODO: apply output projection if your architecture requires it.
592
+ # Anima: return self.output_dropout(self.output_proj(final_out))
593
+ # Z-Image: return self.out(final_out)
594
+ # FLUX double-block: proj is applied outside this module
595
+ # --------------------------------------------------------
596
+ return final_out
597
+
598
+ except Exception as exc:
599
+ if hasattr(stats, "adapter_attn_failures"):
600
+ stats.adapter_attn_failures += 1
601
+ raise RuntimeError(
602
+ f"{DISPLAY_NAME} adapter patch failed in {module_name}; "
603
+ f"strict mode refuses to call original forward after patch failure: {exc}"
604
+ ) from exc
605
+
606
+ return patched_forward
607
+
608
+ module.forward = types.MethodType(make_forward(original_forward, name), module)
609
+ # Optional: mark module so callers can detect active patches.
610
+ setattr(module, "_untwist_adapter_active", True)
611
+ installed += 1
612
+
613
+ if installed <= 0:
614
+ raise RuntimeError(
615
+ f"{DISPLAY_NAME} adapter patch failed: no compatible attention modules were installed."
616
+ )
617
+
618
+ return matched, installed, restored, patched_names
619
+
620
+
621
+ # ===========================================================================
622
+ # SECTION 9 — CAPABILITY FLAGS
623
+ # ===========================================================================
624
+
625
+ def uses_reference_branch_kv() -> bool:
626
+ """Return True if this adapter injects reference K/V into the target stream.
627
+
628
+ All existing adapters return False here because reference K/V injection is
629
+ handled inside patch_attention_modules() directly. Return True only if
630
+ your adapter exposes an additional hook-based KV injection path.
631
+ """
632
+ return False
633
+
634
+
635
+ # ===========================================================================
636
+ # SECTION 10 — OPTIONAL DIAGNOSTICS
637
+ # ===========================================================================
638
+
639
+ def describe_match(model_info: dict[str, Any]) -> str:
640
+ """Human-readable string summarising why this adapter matched (for logging).
641
+
642
+ Optional — implement only if your host node calls it.
643
+ """
644
+ model_config_class = str(model_info.get("model_config_class", ""))
645
+ supported = ", ".join(sorted(SUPPORTED_MODEL_CONFIG_CLASSES))
646
+ return (
647
+ f"{DISPLAY_NAME}: model_config_class={model_config_class!r}, "
648
+ f"supported_classes={{{supported}}}"
649
+ )
650
+
651
+
652
+ # ===========================================================================
653
+ # SECTION 11 — __all__
654
+ # ===========================================================================
655
+ # Keep in sync with every public symbol you export.
656
+
657
+ __all__ = [
658
+ "ARCHITECTURE",
659
+ "DISPLAY_NAME",
660
+ "SUPPORTED_MODEL_CONFIG_CLASSES",
661
+ "CONFIG_KEY",
662
+ "matches_model",
663
+ "is_model_identity",
664
+ "find_diffusion_model",
665
+ "default_runtime_cfg",
666
+ "is_attention_name",
667
+ "is_attention_module",
668
+ "block_index_from_name",
669
+ "prepare_reference_conditioning",
670
+ "patch_attention_modules",
671
+ "uses_reference_branch_kv",
672
+ "describe_match",
673
+ ]
custom_nodes/ComfyUi-Untwisting-RoPE/models/anima.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, List
4
+
5
+ ARCHITECTURE = "anima"
6
+ DISPLAY_NAME = "Anima"
7
+
8
+ # ComfyUI BaseModel stores the selected supported-model instance on
9
+ # model.model_config. Anima is declared as comfy.supported_models.Anima.
10
+ COMFY_MODEL_CONFIG_CLASS = "Anima"
11
+ DIFFUSION_ATTR_PATHS = (
12
+ "model.diffusion_model",
13
+ "model.model.diffusion_model",
14
+ "inner_model.diffusion_model",
15
+ "model.inner_model.diffusion_model",
16
+ "diffusion_model",
17
+ )
18
+
19
+
20
+ def matches_model(model_info: dict[str, Any]) -> bool:
21
+ """Select Anima only from ComfyUI's explicit MODEL metadata."""
22
+ return str(model_info.get("model_config_class", "")) == COMFY_MODEL_CONFIG_CLASS
23
+
24
+
25
+ def is_model_identity(model_info: dict[str, Any]) -> bool:
26
+ """Backward-compatible alias for older callers."""
27
+ return matches_model(model_info)
28
+
29
+
30
+ def _get_attr_path(root: Any, attr_path: str) -> tuple[Any, bool]:
31
+ obj = root
32
+ for part in attr_path.split("."):
33
+ if obj is None or not hasattr(obj, part):
34
+ return None, False
35
+ try:
36
+ obj = getattr(obj, part)
37
+ except Exception:
38
+ return None, False
39
+ return obj, True
40
+
41
+
42
+ def find_diffusion_model(model_patcher: Any) -> Any:
43
+ """Return ComfyUI BaseModel.diffusion_model after metadata selected this adapter."""
44
+ for path in DIFFUSION_ATTR_PATHS:
45
+ obj, ok = _get_attr_path(model_patcher, path)
46
+ if ok and obj is not None:
47
+ return obj
48
+ raise RuntimeError("Could not find ComfyUI BaseModel.diffusion_model for Anima.")
49
+
50
+
51
+ def is_self_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
52
+ """Anima self-attention modules are named blocks.N.self_attn."""
53
+ parts = str(name).split(".")
54
+ if len(parts) != 3:
55
+ return False
56
+ if parts[0] != "blocks" or parts[2] != "self_attn":
57
+ return False
58
+ try:
59
+ idx = int(parts[1])
60
+ except Exception:
61
+ return False
62
+ return int(min_layer) <= idx <= int(max_layer)
63
+
64
+
65
+ def block_index_from_name(name: str) -> int:
66
+ parts = str(name).split(".")
67
+ if len(parts) >= 2 and parts[0] == "blocks":
68
+ return int(parts[1])
69
+ raise ValueError(f"Invalid Anima block name {name!r}; expected blocks.<index>.*")
70
+
71
+
72
+ def is_attention_module(module: Any) -> bool:
73
+ required_attrs = (
74
+ "q_proj", "k_proj", "v_proj", "q_norm", "k_norm", "v_norm",
75
+ "output_proj", "output_dropout", "attn_op", "n_heads", "head_dim",
76
+ "compute_qkv", "compute_attention", "forward", "is_selfattn",
77
+ )
78
+ return all(hasattr(module, attr) for attr in required_attrs)
79
+
80
+
81
+ def axes_dims_from_head_dim(head_dim: int) -> List[int]:
82
+ """ComfyUI Cosmos VideoRopePosition3DEmb uses [temporal, height, width] chunks."""
83
+ hd = int(head_dim)
84
+ if hd <= 0:
85
+ raise RuntimeError(f"Anima axes-dims lookup failed: invalid head_dim={head_dim!r}.")
86
+ dim_h = (hd // 6) * 2
87
+ dim_w = dim_h
88
+ dim_t = hd - 2 * dim_h
89
+ axes = [dim_t, dim_h, dim_w]
90
+ if sum(axes) != hd or any(v <= 0 for v in axes):
91
+ raise RuntimeError(f"Anima axes-dims lookup failed: could not split head_dim={hd} into positive [T,H,W] axes.")
92
+ return axes
93
+
94
+
95
+ def default_runtime_cfg(dm: Any | None = None) -> dict[str, Any]:
96
+ """Architecture-specific cfg fields merged into the main runtime cfg."""
97
+ if dm is None:
98
+ raise RuntimeError("Anima default_runtime_cfg failed: diffusion model is None; cannot read head_dim.")
99
+
100
+ try:
101
+ blocks = getattr(dm, "blocks")
102
+ except Exception as exc:
103
+ raise RuntimeError("Anima default_runtime_cfg failed: diffusion model has no blocks attribute; cannot read head_dim.") from exc
104
+
105
+ try:
106
+ first_block = blocks[0]
107
+ except Exception as exc:
108
+ raise RuntimeError("Anima default_runtime_cfg failed: diffusion model blocks[0] is unavailable; cannot read head_dim.") from exc
109
+
110
+ try:
111
+ self_attn = getattr(first_block, "self_attn")
112
+ except Exception as exc:
113
+ raise RuntimeError("Anima default_runtime_cfg failed: blocks[0] has no self_attn; cannot read head_dim.") from exc
114
+
115
+ try:
116
+ head_dim = int(getattr(self_attn, "head_dim"))
117
+ except Exception as exc:
118
+ raise RuntimeError("Anima default_runtime_cfg failed: blocks[0].self_attn.head_dim is missing or not an integer.") from exc
119
+
120
+ if head_dim <= 0:
121
+ raise RuntimeError(f"Anima default_runtime_cfg failed: invalid blocks[0].self_attn.head_dim={head_dim!r}.")
122
+
123
+ cfg: dict[str, Any] = {"architecture": ARCHITECTURE}
124
+ cfg["head_dim"] = head_dim
125
+ cfg["axes_dims"] = axes_dims_from_head_dim(head_dim)
126
+
127
+ # Anima self-attention receives only latent/image tokens as [B, T*H*W, D].
128
+ # There is no patchify hook to populate target_real_range, so the attention
129
+ # patch clamps this intentionally huge range to the sequence length.
130
+ cfg["target_qk_adain_ranges"] = [(0, 2 ** 31 - 1)]
131
+ return cfg
132
+
133
+ # Adapter-owned optional reference-conditioning preprocessing and attention patch.
134
+ # Keeping this here is what lets the top-level __init__.py stay model-neutral.
135
+
136
+ import traceback
137
+ import types
138
+ import torch
139
+ from typing import Optional, Tuple
140
+
141
+
142
+ def _coerce_bool(value: Any) -> bool:
143
+ if isinstance(value, str):
144
+ return value.strip().lower() in ("1", "true", "yes", "on", "y", "t")
145
+ return bool(value)
146
+
147
+
148
+ def _first_tensor_in_conditioning_entry(entry: Any) -> Tuple[Optional[torch.Tensor], dict[str, Any]]:
149
+ meta: dict[str, Any] = {}
150
+ if torch.is_tensor(entry):
151
+ return entry, meta
152
+ if isinstance(entry, dict):
153
+ meta.update(entry)
154
+ for key in ("c_crossattn", "crossattn", "conditioning", "cond", "context", "cap_feats"):
155
+ value = entry.get(key)
156
+ if torch.is_tensor(value):
157
+ return value, meta
158
+ for value in entry.values():
159
+ if torch.is_tensor(value) and value.ndim >= 2:
160
+ return value, meta
161
+ return None, meta
162
+ if isinstance(entry, (list, tuple)):
163
+ cond: Optional[torch.Tensor] = None
164
+ for item in entry:
165
+ if torch.is_tensor(item) and cond is None:
166
+ cond = item
167
+ elif isinstance(item, dict):
168
+ meta.update(item)
169
+ if cond is not None:
170
+ return cond, meta
171
+ for item in entry:
172
+ cond, nested_meta = _first_tensor_in_conditioning_entry(item)
173
+ if nested_meta:
174
+ meta.update(nested_meta)
175
+ if cond is not None:
176
+ return cond, nested_meta
177
+ return None, meta
178
+
179
+
180
+ def _extract_reference_conditioning(ref_conditioning: Any) -> Tuple[Optional[torch.Tensor], dict[str, Any]]:
181
+ if ref_conditioning is None:
182
+ return None, {}
183
+ if torch.is_tensor(ref_conditioning) or isinstance(ref_conditioning, dict):
184
+ return _first_tensor_in_conditioning_entry(ref_conditioning)
185
+ if isinstance(ref_conditioning, (list, tuple)):
186
+ merged_meta: dict[str, Any] = {}
187
+ for entry in ref_conditioning:
188
+ cond, meta = _first_tensor_in_conditioning_entry(entry)
189
+ if meta:
190
+ merged_meta.update(meta)
191
+ if cond is not None:
192
+ return cond, merged_meta
193
+ return None, merged_meta
194
+ return None, {}
195
+
196
+
197
+ def _tensor_batch_ids_like(value: Any, device) -> Optional[torch.Tensor]:
198
+ if value is None:
199
+ return None
200
+ if torch.is_tensor(value):
201
+ ids = value.detach().to(device=device)
202
+ else:
203
+ ids = torch.as_tensor(value, device=device)
204
+ if ids.ndim == 1:
205
+ ids = ids.unsqueeze(0)
206
+ elif ids.ndim > 2:
207
+ ids = ids.reshape(ids.shape[0], -1)
208
+ return ids.long()
209
+
210
+
211
+ def _tensor_t5_weights_like(value: Any, like: torch.Tensor) -> Optional[torch.Tensor]:
212
+ if value is None:
213
+ return None
214
+ if torch.is_tensor(value):
215
+ w = value.detach().to(device=like.device, dtype=like.dtype)
216
+ else:
217
+ w = torch.as_tensor(value, device=like.device, dtype=like.dtype)
218
+ if w.ndim == 1:
219
+ w = w.unsqueeze(0).unsqueeze(-1)
220
+ elif w.ndim == 2:
221
+ w = w.unsqueeze(-1)
222
+ return w
223
+
224
+
225
+ def prepare_reference_conditioning(
226
+ ref_conditioning: Any,
227
+ dm: Any,
228
+ device,
229
+ dtype,
230
+ stats: Any = None,
231
+ label: str = "",
232
+ helpers: dict[str, Any] | None = None,
233
+ ) -> Tuple[Any, str]:
234
+ prefix = (helpers or {}).get("prefix", "[UntwistingRoPE]")
235
+ if ref_conditioning is None:
236
+ raise RuntimeError("Anima reference conditioning preprocessing was requested, but ref_conditioning is None.")
237
+ if dm is None or not hasattr(dm, "preprocess_text_embeds"):
238
+ raise RuntimeError("Anima reference conditioning preprocessing requires dm.preprocess_text_embeds, but it is missing.")
239
+
240
+ ref_cond, ref_meta = _extract_reference_conditioning(ref_conditioning)
241
+ if ref_cond is None:
242
+ raise RuntimeError("Anima reference conditioning preprocessing could not find a tensor in ref_conditioning.")
243
+
244
+ try:
245
+ ref_shape_before = tuple(ref_cond.shape)
246
+ ref_cond_b = ref_cond.detach()
247
+ if ref_cond_b.ndim == 2:
248
+ ref_cond_b = ref_cond_b.unsqueeze(0)
249
+
250
+ # Already in the final cross-attention shape. Keep it unchanged.
251
+ if ref_cond_b.ndim >= 3 and int(ref_cond_b.shape[1]) == 512:
252
+ return ref_conditioning, f"already-final-{tuple(ref_cond_b.shape)}"
253
+
254
+ t5xxl_ids = ref_meta.get("t5xxl_ids", None)
255
+ if t5xxl_ids is None:
256
+ raise RuntimeError(
257
+ f"Anima reference conditioning is not 512 tokens and has no t5xxl_ids; "
258
+ f"cannot run preprocess_text_embeds. shape={ref_shape_before}"
259
+ )
260
+
261
+ ref_cond_b = ref_cond_b.to(device=device, dtype=dtype)
262
+ ids = _tensor_batch_ids_like(t5xxl_ids, device=device)
263
+ if ids is None:
264
+ raise RuntimeError(f"Anima reference conditioning has t5xxl_ids, but conversion returned None. shape={ref_shape_before}")
265
+
266
+ weights = _tensor_t5_weights_like(ref_meta.get("t5xxl_weights", None), ref_cond_b)
267
+
268
+ with torch.inference_mode():
269
+ processed = dm.preprocess_text_embeds(ref_cond_b, ids, t5xxl_weights=weights)
270
+ processed = processed.to(device=device, dtype=dtype).detach()
271
+
272
+ out_meta = dict(ref_meta)
273
+ out_meta["num_tokens"] = int(processed.shape[1]) if processed.ndim >= 2 else 0
274
+ out_meta["untwist_adapter_preprocessed"] = True
275
+ out = [[processed, out_meta]]
276
+
277
+ status = f"preprocessed-ref-conditioning {ref_shape_before}->{tuple(processed.shape)}"
278
+ return out, status
279
+ except Exception as exc:
280
+ raise RuntimeError(f"Anima reference conditioning preprocess failed; strict mode refuses to reuse original conditioning after preprocessing failure: {exc}") from exc
281
+
282
+
283
+ def patch_attention_modules(dm: Any, stats: Any, helpers: dict[str, Any] | None = None):
284
+ helpers = helpers or {}
285
+ prefix = helpers.get("prefix", "[UntwistingRoPE]")
286
+ config_key = helpers.get("config_key", "untwisting_rope")
287
+ lerp = helpers["lerp"]
288
+ cross_batch_adain_qk = helpers["cross_batch_adain_qk"]
289
+ build_frequency_scale_vector = helpers["build_frequency_scale_vector"]
290
+
291
+ matched = installed = restored = 0
292
+ patched_names: list[str] = []
293
+
294
+ for name, module in dm.named_modules():
295
+ if not is_self_attention_name(name, 0, 999):
296
+ continue
297
+ if not is_attention_module(module):
298
+ continue
299
+ if not bool(getattr(module, "is_selfattn", False)):
300
+ continue
301
+
302
+ matched += 1
303
+ patched_names.append(name)
304
+ block_idx_for_module = block_index_from_name(name)
305
+
306
+ if hasattr(module, "_untwist_orig_adapter_forward"):
307
+ module.forward = module._untwist_orig_adapter_forward
308
+ restored += 1
309
+ else:
310
+ module._untwist_orig_adapter_forward = module.forward
311
+ original_forward = module._untwist_orig_adapter_forward
312
+
313
+ def make_forward(orig, module_name, module_block_idx):
314
+ def patched_forward(self, x, context=None, rope_emb=None, transformer_options={}):
315
+ cfg = (
316
+ transformer_options.get(config_key)
317
+ if isinstance(transformer_options, dict) else None
318
+ )
319
+ if not cfg or not cfg.get("enabled"):
320
+ return orig(x, context, rope_emb=rope_emb, transformer_options=transformer_options)
321
+ if context is not None:
322
+ raise RuntimeError(f"Anima Untwisting enabled in {module_name}, but received cross-attention context; expected self-attention only.")
323
+ if not bool(getattr(self, "is_selfattn", False)):
324
+ raise RuntimeError(f"Anima Untwisting enabled in {module_name}, but module is_selfattn is false.")
325
+
326
+ block_idx = int(module_block_idx)
327
+ active_blocks = cfg.get("active_blocks", None)
328
+ if active_blocks is not None and len(active_blocks) > 0 and block_idx not in active_blocks:
329
+ return orig(x, context, rope_emb=rope_emb, transformer_options=transformer_options)
330
+
331
+ target_bsz = int(cfg.get("cross_batch_target_batch", 0))
332
+ if target_bsz <= 0:
333
+ raise RuntimeError(f"Anima Untwisting enabled in {module_name}, but cross_batch_target_batch={target_bsz}.")
334
+ if not torch.is_tensor(x) or x.ndim != 3:
335
+ raise RuntimeError(f"Anima Untwisting expected x as [B,S,C] tensor in {module_name}; got {type(x).__name__} with ndim={getattr(x, 'ndim', None)}.")
336
+
337
+ bsz, seqlen, _ = x.shape
338
+ if bsz < target_bsz * 2:
339
+ raise RuntimeError(f"Anima Untwisting expected at least target+reference batches in {module_name}; bsz={bsz}, target_bsz={target_bsz}.")
340
+
341
+ try:
342
+ if hasattr(stats, "adapter_attn_calls"):
343
+ stats.adapter_attn_calls += 1
344
+ q, k, v = self.compute_qkv(x, context, rope_emb=rope_emb)
345
+
346
+ progress = float(cfg.get("progress", 0.0))
347
+ high_scale = lerp(cfg["high_scale_start"], cfg["high_scale_end"], progress)
348
+ low_scale = lerp(cfg["low_scale_start"], cfg["low_scale_end"], progress)
349
+ beta = float(cfg.get("beta", 2.0))
350
+
351
+ if cfg.get("apply_adain") and float(cfg.get("adain_strength", 0)) > 0:
352
+ q, k = q.clone(), k.clone()
353
+ q, k = cross_batch_adain_qk(q, k, cfg, target_bsz, float(cfg["adain_strength"]))
354
+
355
+ try:
356
+ head_dim = int(self.head_dim)
357
+ except Exception as exc:
358
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: self.head_dim is missing or not an integer.") from exc
359
+ if head_dim <= 0:
360
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: invalid self.head_dim={head_dim!r}.")
361
+
362
+ if "head_dim" not in cfg:
363
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: runtime cfg is missing required head_dim.")
364
+ try:
365
+ cfg_head_dim = int(cfg["head_dim"])
366
+ except Exception as exc:
367
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: runtime cfg head_dim is not an integer: {cfg.get('head_dim')!r}.") from exc
368
+ if cfg_head_dim <= 0:
369
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: runtime cfg has invalid head_dim={cfg_head_dim!r}.")
370
+ if cfg_head_dim != head_dim:
371
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: cfg head_dim={cfg_head_dim} does not match self.head_dim={head_dim}.")
372
+
373
+ if "axes_dims" not in cfg:
374
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: runtime cfg is missing required axes_dims.")
375
+ try:
376
+ axes_dims = [int(v) for v in cfg["axes_dims"]]
377
+ except Exception as exc:
378
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: runtime cfg axes_dims is invalid: {cfg.get('axes_dims')!r}.") from exc
379
+ if sum(axes_dims) != head_dim or any(v <= 0 for v in axes_dims):
380
+ raise RuntimeError(f"Anima Untwisting failed in {module_name}: axes_dims={axes_dims!r} does not split head_dim={head_dim}.")
381
+
382
+ scale_vec = build_frequency_scale_vector(
383
+ head_dim, axes_dims,
384
+ high_scale, low_scale, beta,
385
+ k.device, k.dtype,
386
+ runtime_cfg=cfg,
387
+ ).view(1, 1, 1, head_dim)
388
+
389
+ q_t = q[:target_bsz]
390
+ k_t = torch.cat([k[:target_bsz], k[target_bsz:target_bsz * 2] * scale_vec], dim=1)
391
+ v_t = torch.cat([v[:target_bsz], v[target_bsz:target_bsz * 2]], dim=1)
392
+ out_t = self.attn_op(q_t, k_t, v_t, transformer_options=transformer_options)
393
+
394
+ q_r = q[target_bsz:target_bsz * 2]
395
+ k_r = k[target_bsz:target_bsz * 2]
396
+ v_r = v[target_bsz:target_bsz * 2]
397
+ out_r = self.attn_op(q_r, k_r, v_r, transformer_options=transformer_options)
398
+
399
+ outs = [out_t, out_r]
400
+ if bsz > target_bsz * 2:
401
+ outs.append(self.attn_op(
402
+ q[target_bsz * 2:],
403
+ k[target_bsz * 2:],
404
+ v[target_bsz * 2:],
405
+ transformer_options=transformer_options,
406
+ ))
407
+
408
+ out = torch.cat(outs, dim=0)
409
+ return self.output_dropout(self.output_proj(out))
410
+ except Exception as exc:
411
+ if hasattr(stats, "adapter_attn_failures"):
412
+ stats.adapter_attn_failures += 1
413
+ raise RuntimeError(f"Anima adapter self-attn patch failed in {module_name}; strict mode refuses to call the original forward after patch failure: {exc}") from exc
414
+ return patched_forward
415
+
416
+ module.forward = types.MethodType(make_forward(original_forward, name, block_idx_for_module), module)
417
+ setattr(module, "_untwist_adapter_active", True)
418
+ installed += 1
419
+
420
+ if installed <= 0:
421
+ raise RuntimeError("Anima adapter patch failed: no compatible self-attention modules were installed.")
422
+ return matched, installed, restored, patched_names
423
+
424
+
425
+ def uses_reference_branch_kv() -> bool:
426
+ return False
custom_nodes/ComfyUi-Untwisting-RoPE/models/flux2.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import traceback
4
+ import types
5
+ from typing import Any, Iterable, List, Optional, Tuple
6
+
7
+ import torch
8
+ from comfy.ldm.flux.math import apply_rope, attention as flux_attention
9
+ from comfy.ldm.modules.attention import optimized_attention_masked
10
+
11
+
12
+ # ---------------------------------------------------------------------------
13
+ # Required adapter identity
14
+ # ---------------------------------------------------------------------------
15
+
16
+ ARCHITECTURE = "flux2"
17
+ DISPLAY_NAME = "FLUX.2"
18
+
19
+ # Strict ComfyUI supported_models class names only.
20
+ SUPPORTED_MODEL_CONFIG_CLASSES: set[str] = {"Flux2"}
21
+
22
+ _DIFFUSION_ATTR_PATHS = (
23
+ "model.diffusion_model",
24
+ "model.model.diffusion_model",
25
+ "inner_model.diffusion_model",
26
+ "model.inner_model.diffusion_model",
27
+ "diffusion_model",
28
+ )
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Safe metadata / lookup helpers
33
+ # ---------------------------------------------------------------------------
34
+
35
+ def _get_attr_path(root: Any, attr_path: str) -> tuple[Any, bool]:
36
+ obj = root
37
+ for part in attr_path.split("."):
38
+ if obj is None or not hasattr(obj, part):
39
+ return None, False
40
+ try:
41
+ obj = getattr(obj, part)
42
+ except Exception:
43
+ return None, False
44
+ return obj, True
45
+
46
+
47
+ def _safe_int(value: Any, default: int | None = None) -> int | None:
48
+ try:
49
+ return int(value)
50
+ except Exception:
51
+ return default
52
+
53
+
54
+ def _sequence_of_ints(value: Any) -> list[int]:
55
+ if not isinstance(value, (list, tuple)):
56
+ return []
57
+ out: list[int] = []
58
+ for item in value:
59
+ i = _safe_int(item)
60
+ if i is None:
61
+ return []
62
+ out.append(i)
63
+ return out
64
+
65
+
66
+ def _coerce_bool(value: Any) -> bool:
67
+ if isinstance(value, str):
68
+ return value.strip().lower() in ("1", "true", "yes", "on", "y", "t")
69
+ return bool(value)
70
+
71
+
72
+ def _coerce_strength01(value: Any, default: float = 0.0) -> float:
73
+ try:
74
+ strength = float(value)
75
+ except Exception as exc:
76
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].") from exc
77
+ if not torch.isfinite(torch.tensor(strength)):
78
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].")
79
+ if not 0.0 <= strength <= 1.0:
80
+ raise ValueError(f"Invalid strength value {strength!r}; expected value in [0, 1].")
81
+ return strength
82
+
83
+
84
+ def _lerp(a: float, b: float, t: float) -> float:
85
+ return float(a + (b - a) * t)
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Required hooks
90
+ # ---------------------------------------------------------------------------
91
+
92
+ def matches_model(model_info: dict[str, Any]) -> bool:
93
+ """Select FLUX.2 only from ComfyUI's explicit MODEL metadata."""
94
+ return str(model_info.get("model_config_class", "")) in SUPPORTED_MODEL_CONFIG_CLASSES
95
+
96
+
97
+ def is_model_identity(model_info: dict[str, Any]) -> bool:
98
+ """Backward-compatible alias for older callers."""
99
+ return matches_model(model_info)
100
+
101
+
102
+ def find_diffusion_model(model_patcher: Any) -> Any:
103
+ """Return ComfyUI BaseModel.diffusion_model after metadata selected this adapter."""
104
+ for path in _DIFFUSION_ATTR_PATHS:
105
+ obj, ok = _get_attr_path(model_patcher, path)
106
+ if ok and obj is not None:
107
+ return obj
108
+ raise RuntimeError(f"Could not find ComfyUI BaseModel.diffusion_model for {DISPLAY_NAME}.")
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Runtime config helpers
113
+ # ---------------------------------------------------------------------------
114
+
115
+ def axes_dims_from_dm(dm: Any | None) -> list[int]:
116
+ """Read FLUX.2 RoPE axes from the already-selected ComfyUI diffusion module."""
117
+ if dm is None:
118
+ raise RuntimeError("FLUX.2 axes_dims lookup failed: diffusion module is None.")
119
+ params = getattr(dm, "params", None)
120
+ if params is None:
121
+ raise RuntimeError("FLUX.2 axes_dims lookup failed: dm.params is missing.")
122
+ axes = _sequence_of_ints(getattr(params, "axes_dim", None))
123
+ if not axes:
124
+ raise RuntimeError("FLUX.2 axes_dims lookup failed: dm.params.axes_dim is missing or invalid.")
125
+ return axes
126
+
127
+
128
+ def head_dim_from_dm(dm: Any | None) -> int:
129
+ """Read FLUX.2 head_dim from explicit diffusion-module params after selection."""
130
+ if dm is None:
131
+ raise RuntimeError("FLUX.2 head_dim lookup failed: diffusion module is None.")
132
+ params = getattr(dm, "params", None)
133
+ if params is None:
134
+ raise RuntimeError("FLUX.2 head_dim lookup failed: dm.params is missing.")
135
+ hidden = _safe_int(getattr(params, "hidden_size", None))
136
+ heads = _safe_int(getattr(params, "num_heads", None))
137
+ if hidden is None or heads is None or heads <= 0:
138
+ raise RuntimeError(f"FLUX.2 head_dim lookup failed: hidden_size={hidden}, num_heads={heads}.")
139
+ if hidden % heads != 0:
140
+ raise RuntimeError(f"FLUX.2 head_dim lookup failed: hidden_size={hidden} is not divisible by num_heads={heads}.")
141
+ return hidden // heads
142
+
143
+
144
+ def default_runtime_cfg(dm: Any | None = None) -> dict[str, Any]:
145
+ """Architecture-specific config merged into transformer_options."""
146
+ cfg: dict[str, Any] = {"architecture": ARCHITECTURE}
147
+
148
+ cfg["axes_dims"] = axes_dims_from_dm(dm)
149
+ cfg["head_dim"] = head_dim_from_dm(dm)
150
+
151
+ return cfg
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # FLUX.2 patch-target helpers
156
+ # ---------------------------------------------------------------------------
157
+
158
+ def _index_in_range(parts: list[str], min_layer: int, max_layer: int) -> bool:
159
+ if len(parts) < 2:
160
+ return False
161
+ idx = _safe_int(parts[1])
162
+ if idx is None:
163
+ return False
164
+ return int(min_layer) <= idx <= int(max_layer)
165
+
166
+
167
+ def is_double_stream_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
168
+ """FLUX.2 double-stream attention modules are double_blocks.N.{img_attn,txt_attn}."""
169
+ parts = str(name).split(".")
170
+ if len(parts) != 3:
171
+ return False
172
+ if parts[0] != "double_blocks" or parts[2] not in {"img_attn", "txt_attn"}:
173
+ return False
174
+ return _index_in_range(parts, min_layer, max_layer)
175
+
176
+
177
+ def is_single_stream_block_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
178
+ """FLUX.2 single-stream injection must target the whole single_blocks.N block."""
179
+ parts = str(name).split(".")
180
+ if len(parts) != 2:
181
+ return False
182
+ if parts[0] != "single_blocks":
183
+ return False
184
+ return _index_in_range(parts, min_layer, max_layer)
185
+
186
+
187
+ def is_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
188
+ """Names a verified FLUX.2 target after metadata selected this adapter."""
189
+ return (
190
+ is_double_stream_attention_name(name, min_layer, max_layer)
191
+ or is_single_stream_block_name(name, min_layer, max_layer)
192
+ )
193
+
194
+
195
+ def block_index_from_name(name: str) -> int:
196
+ parts = str(name).split(".")
197
+ if parts and parts[0] in {"double_blocks", "single_blocks"} and len(parts) >= 2:
198
+ idx = _safe_int(parts[1], -1)
199
+ return -1 if idx is None else idx
200
+ return -1
201
+
202
+
203
+ def stream_kind_from_name(name: str) -> str:
204
+ if is_single_stream_block_name(name):
205
+ return "single"
206
+ if is_double_stream_attention_name(name):
207
+ suffix = str(name).split(".")[-1]
208
+ return "double_img" if suffix == "img_attn" else "double_txt"
209
+ return "unknown"
210
+
211
+
212
+ def is_flux2_self_attention_module(module: Any) -> bool:
213
+ """Predicate for ComfyUI FLUX SelfAttention modules after metadata selection."""
214
+ required_attrs = ("qkv", "norm", "proj", "num_heads")
215
+ return all(hasattr(module, attr) for attr in required_attrs) and callable(getattr(module, "forward", None))
216
+
217
+
218
+ def is_flux2_single_stream_block(module: Any) -> bool:
219
+ """Predicate for ComfyUI FLUX SingleStreamBlock modules after metadata selection."""
220
+ required_attrs = ("linear1", "linear2", "norm", "hidden_size", "num_heads")
221
+ return all(hasattr(module, attr) for attr in required_attrs) and callable(getattr(module, "forward", None))
222
+
223
+
224
+ def is_joint_attention(module: Any) -> bool:
225
+ """Compatibility predicate for adapter-aware callers."""
226
+ return is_flux2_self_attention_module(module) or is_flux2_single_stream_block(module)
227
+
228
+
229
+ def iter_flux2_patch_targets(dm: Any, min_layer: int = 0, max_layer: int = 999):
230
+ """Yield (name, module, stream_kind, block_index) for verified FLUX.2 targets."""
231
+ for name, module in dm.named_modules():
232
+ if not is_attention_name(name, min_layer, max_layer):
233
+ continue
234
+ if is_single_stream_block_name(name, min_layer, max_layer):
235
+ if not is_flux2_single_stream_block(module):
236
+ continue
237
+ elif not is_flux2_self_attention_module(module):
238
+ continue
239
+ yield name, module, stream_kind_from_name(name), block_index_from_name(name)
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # Local reusable math/AdaIN helpers for the adapter-owned patch
244
+ # ---------------------------------------------------------------------------
245
+
246
+ def _adain(target: torch.Tensor, style: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
247
+ t_mean = target.mean(dim=1, keepdim=True)
248
+ s_mean = style.mean(dim=1, keepdim=True)
249
+ t_std = target.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
250
+ s_std = style.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
251
+ return (target - t_mean) / t_std * s_std + s_mean
252
+
253
+
254
+ def _local_cross_batch_adain_qk(*_args, **_kwargs):
255
+ raise RuntimeError("FLUX.2 missing required helper cross_batch_adain_qk; strict mode requires the top-level helper.")
256
+
257
+
258
+ def _local_build_frequency_scale_vector(*_args, **_kwargs):
259
+ raise RuntimeError("FLUX.2 missing required helper build_frequency_scale_vector; strict mode requires the top-level helper.")
260
+
261
+
262
+ def _flux_kv_heads_if_needed(k: torch.Tensor, v: torch.Tensor, q_heads: int) -> tuple[torch.Tensor, torch.Tensor]:
263
+ """Expand KV heads for FLUX tensors in [B,H,S,D] layout."""
264
+ kv = int(k.shape[1])
265
+ qh = int(q_heads)
266
+ if kv == qh:
267
+ return k, v
268
+ if qh % kv != 0:
269
+ raise RuntimeError(f"Cannot expand FLUX KV heads: q={qh}, kv={kv}")
270
+ n = qh // kv
271
+ k = k.unsqueeze(2).repeat(1, 1, n, 1, 1).flatten(1, 2)
272
+ v = v.unsqueeze(2).repeat(1, 1, n, 1, 1).flatten(1, 2)
273
+ return k, v
274
+
275
+
276
+ def _flux_append_ref_padding_to_mask(mask: Any, target_bsz: int, ref_len: int):
277
+ """Append valid additive-mask slots for injected reference K/V tokens."""
278
+ if mask is None:
279
+ return None
280
+ if ref_len <= 0:
281
+ raise RuntimeError(f"Cannot append FLUX reference padding: ref_len={ref_len}.")
282
+ mask_t = mask[:target_bsz]
283
+ if mask_t.ndim < 2:
284
+ raise RuntimeError(f"Cannot append FLUX reference padding: mask ndim={mask_t.ndim}, expected >=2.")
285
+ padding = torch.zeros(
286
+ (*mask_t.shape[:-1], int(ref_len)),
287
+ device=mask_t.device,
288
+ dtype=mask_t.dtype,
289
+ )
290
+ return torch.cat([mask_t, padding], dim=-1)
291
+
292
+
293
+ def _flux_slice_mask(mask: Any, start: int, end: int):
294
+ if mask is None:
295
+ return None
296
+ return mask[int(start): int(end)]
297
+
298
+
299
+ def _flux_adain_qkv_for_image_range(q, k, v, cfg, target_bsz: int, image_range, cross_batch_adain_qk):
300
+ """Run AdaIN on FLUX [B,H,S,D] tensors over image tokens."""
301
+ if not cfg.get("apply_adain") or float(cfg.get("adain_strength", 0.0)) <= 0.0:
302
+ return q, k, v
303
+
304
+ s, e = int(image_range[0]), int(image_range[1])
305
+ if e <= s:
306
+ return q, k, v
307
+
308
+ # Existing helper expects [B,S,H,D]. FLUX attention uses [B,H,S,D].
309
+ q_sh = q.movedim(1, 2).clone()
310
+ k_sh = k.movedim(1, 2).clone()
311
+ v_sh = v.movedim(1, 2).clone() if _coerce_bool(cfg.get("adain_on_v", False)) else None
312
+
313
+ cfg_local = dict(cfg)
314
+ cfg_local["target_qk_adain_ranges"] = [(s, e)]
315
+ out = cross_batch_adain_qk(
316
+ q_sh, k_sh, cfg_local, target_bsz, float(cfg["adain_strength"]), xv=v_sh
317
+ )
318
+
319
+ if v_sh is not None:
320
+ q_sh, k_sh, v_sh = out
321
+ v = v_sh.movedim(1, 2)
322
+ else:
323
+ q_sh, k_sh = out
324
+ return q_sh.movedim(1, 2), k_sh.movedim(1, 2), v
325
+
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # Optional conditioning / patch hooks
329
+ # ---------------------------------------------------------------------------
330
+
331
+ def prepare_reference_conditioning(
332
+ ref_conditioning: Any,
333
+ dm: Any,
334
+ device: Any,
335
+ dtype: Any,
336
+ stats: Any = None,
337
+ label: str = "",
338
+ helpers: dict[str, Any] | None = None,
339
+ ) -> tuple[Any, str]:
340
+ """FLUX.2 reference conditioning does not need adapter preprocessing here."""
341
+ return ref_conditioning, "not-applicable"
342
+
343
+
344
+ def patch_attention_modules(
345
+ dm: Any,
346
+ stats: Any,
347
+ helpers: dict[str, Any] | None = None,
348
+ ) -> tuple[int, int, int, list[str]]:
349
+ """Patch ComfyUI FLUX/FLUX.2 DoubleStreamBlock and SingleStreamBlock forwards.
350
+
351
+ This architecture-specific implementation intentionally lives in the adapter
352
+ file. The top-level node only supplies generic helpers through ``helpers``.
353
+ """
354
+ helpers = helpers or {}
355
+ prefix = str(helpers.get("prefix", "[UntwistingRoPE]"))
356
+ config_key = str(helpers.get("config_key", "untwisting_rope"))
357
+
358
+ required_helpers = ("lerp", "cross_batch_adain_qk", "build_frequency_scale_vector")
359
+ missing = [name for name in required_helpers if not callable(helpers.get(name))]
360
+ if missing:
361
+ raise RuntimeError(f"{DISPLAY_NAME} adapter missing required helper(s): {missing}")
362
+
363
+ lerp = helpers["lerp"]
364
+ cross_batch_adain_qk = helpers["cross_batch_adain_qk"]
365
+ build_frequency_scale_vector = helpers["build_frequency_scale_vector"]
366
+
367
+ try:
368
+ from comfy.ldm.flux.layers import apply_mod
369
+ except Exception as exc:
370
+ raise RuntimeError(f"{prefix} Could not import FLUX layers.apply_mod: {exc}")
371
+
372
+ def _verbose_enabled() -> bool:
373
+ return _coerce_bool(getattr(stats, "verbose", False)) or _coerce_bool(getattr(stats, "rf_verbose", False))
374
+
375
+ def _reference_attention(
376
+ q: torch.Tensor,
377
+ k: torch.Tensor,
378
+ v: torch.Tensor,
379
+ pe: torch.Tensor,
380
+ attn_mask: Any,
381
+ transformer_options: dict[str, Any],
382
+ image_range: tuple[int, int],
383
+ module_name: str,
384
+ ) -> torch.Tensor:
385
+ """FLUX attention replacement for ComfyUI tensors in [B,H,S,D]."""
386
+ try:
387
+ cfg = (
388
+ transformer_options.get(config_key)
389
+ if isinstance(transformer_options, dict) else None
390
+ )
391
+ if not cfg or not cfg.get("enabled"):
392
+ return flux_attention(q, k, v, pe=pe, mask=attn_mask, transformer_options=transformer_options)
393
+
394
+ target_bsz = int(cfg.get("cross_batch_target_batch", 0))
395
+ if target_bsz <= 0:
396
+ raise RuntimeError(f"{DISPLAY_NAME} Untwisting enabled in {module_name}, but cross_batch_target_batch={target_bsz}.")
397
+ if q.ndim != 4 or k.ndim != 4 or v.ndim != 4:
398
+ raise RuntimeError(f"{DISPLAY_NAME} Untwisting expected q/k/v as [B,H,S,D] tensors in {module_name}; got q.ndim={q.ndim}, k.ndim={k.ndim}, v.ndim={v.ndim}.")
399
+
400
+ bsz, q_heads, seqlen, head_dim = q.shape
401
+ if bsz < target_bsz * 2:
402
+ raise RuntimeError(f"{DISPLAY_NAME} Untwisting expected at least target+reference batches in {module_name}; bsz={bsz}, target_bsz={target_bsz}.")
403
+
404
+ block_idx = int(transformer_options.get("block_index", -1))
405
+ active_blocks = cfg.get("active_blocks", set())
406
+ if active_blocks and block_idx not in active_blocks:
407
+ return flux_attention(q, k, v, pe=pe, mask=attn_mask, transformer_options=transformer_options)
408
+
409
+ img_s, img_e = int(image_range[0]), int(image_range[1])
410
+ img_s = max(0, min(img_s, int(seqlen)))
411
+ img_e = max(img_s, min(img_e, int(seqlen)))
412
+ if img_e <= img_s:
413
+ raise RuntimeError(f"{DISPLAY_NAME} Untwisting has an empty image token range in {module_name}: {(img_s, img_e)} for seqlen={seqlen}.")
414
+
415
+ if hasattr(stats, "attn_calls"):
416
+ stats.attn_calls += 1
417
+ if hasattr(stats, "adapter_attn_calls"):
418
+ stats.adapter_attn_calls += 1
419
+
420
+ q, k, v = _flux_adain_qkv_for_image_range(
421
+ q, k, v, cfg, target_bsz, (img_s, img_e), cross_batch_adain_qk
422
+ )
423
+
424
+ # Apply RoPE before appending reference K/V, matching ComfyUI's FLUX attention path.
425
+ q, k = apply_rope(q, k, pe)
426
+
427
+ progress = float(cfg.get("progress", 0.0))
428
+ high_scale = lerp(cfg["high_scale_start"], cfg["high_scale_end"], progress)
429
+ low_scale = lerp(cfg["low_scale_start"], cfg["low_scale_end"], progress)
430
+ beta = float(cfg.get("beta", 2.0))
431
+ scale_vec = build_frequency_scale_vector(
432
+ int(head_dim),
433
+ cfg.get("axes_dims") or axes_dims_from_dm(dm),
434
+ high_scale,
435
+ low_scale,
436
+ beta,
437
+ k.device,
438
+ k.dtype,
439
+ runtime_cfg=cfg,
440
+ ).view(1, 1, 1, int(head_dim))
441
+
442
+ ref_k = k[target_bsz:target_bsz * 2, :, img_s:img_e, :] * scale_vec
443
+ ref_v = v[target_bsz:target_bsz * 2, :, img_s:img_e, :]
444
+ ref_len = int(ref_k.shape[2])
445
+ if ref_len <= 0:
446
+ raise RuntimeError(f"{DISPLAY_NAME} Untwisting produced empty reference K/V in {module_name}; image_range={(img_s, img_e)}.")
447
+
448
+ q_t = q[:target_bsz]
449
+ k_t = torch.cat([k[:target_bsz], ref_k], dim=2)
450
+ v_t = torch.cat([v[:target_bsz], ref_v], dim=2)
451
+ k_t, v_t = _flux_kv_heads_if_needed(k_t, v_t, int(q_heads))
452
+ mask_t = _flux_append_ref_padding_to_mask(attn_mask, target_bsz, ref_len)
453
+
454
+ out_t = optimized_attention_masked(
455
+ q_t, k_t, v_t, int(q_heads), mask_t,
456
+ skip_reshape=True, transformer_options=transformer_options,
457
+ )
458
+
459
+ q_r = q[target_bsz:target_bsz * 2]
460
+ k_r = k[target_bsz:target_bsz * 2]
461
+ v_r = v[target_bsz:target_bsz * 2]
462
+ k_r, v_r = _flux_kv_heads_if_needed(k_r, v_r, int(q_heads))
463
+ mask_r = _flux_slice_mask(attn_mask, target_bsz, target_bsz * 2)
464
+ out_r = optimized_attention_masked(
465
+ q_r, k_r, v_r, int(q_heads), mask_r,
466
+ skip_reshape=True, transformer_options=transformer_options,
467
+ )
468
+
469
+ post_a = _coerce_strength01(cfg.get("post_attention_adain_strength", 0.0))
470
+ if post_a > 0.0:
471
+ out_t_adain = _adain(out_t, out_r, eps=1e-6)
472
+ out_t = out_t * (1.0 - post_a) + out_t_adain * post_a
473
+
474
+ outs = [out_t, out_r]
475
+ if bsz > target_bsz * 2:
476
+ q_e = q[target_bsz * 2:]
477
+ k_e = k[target_bsz * 2:]
478
+ v_e = v[target_bsz * 2:]
479
+ k_e, v_e = _flux_kv_heads_if_needed(k_e, v_e, int(q_heads))
480
+ mask_e = _flux_slice_mask(attn_mask, target_bsz * 2, bsz)
481
+ outs.append(optimized_attention_masked(
482
+ q_e, k_e, v_e, int(q_heads), mask_e,
483
+ skip_reshape=True, transformer_options=transformer_options,
484
+ ))
485
+
486
+ return torch.cat(outs, dim=0)
487
+ except Exception as exc:
488
+ if hasattr(stats, "adapter_attn_failures"):
489
+ stats.adapter_attn_failures += 1
490
+ raise RuntimeError(f"{DISPLAY_NAME} attention patch failed in {module_name}; strict mode refuses to call original attention after patch failure: {exc}") from exc
491
+
492
+ matched = installed = restored = 0
493
+ patched_names: List[str] = []
494
+
495
+ # Double-stream blocks: joint attention over [txt, img] happens inside the block.
496
+ for idx, block in enumerate(getattr(dm, "double_blocks", []) or []):
497
+ if not all(hasattr(block, attr) for attr in ("img_attn", "txt_attn", "img_norm1", "txt_norm1")):
498
+ continue
499
+ matched += 1
500
+ name = f"double_blocks.{idx}"
501
+ patched_names.append(name)
502
+
503
+ if hasattr(block, "_untwist_orig_flux2_forward"):
504
+ block.forward = block._untwist_orig_flux2_forward
505
+ restored += 1
506
+ else:
507
+ block._untwist_orig_flux2_forward = block.forward
508
+ original_forward = block._untwist_orig_flux2_forward
509
+
510
+ def make_double_forward(orig, module_name):
511
+ def patched_double_forward(
512
+ self,
513
+ img,
514
+ txt,
515
+ vec,
516
+ pe,
517
+ attn_mask=None,
518
+ modulation_dims_img=None,
519
+ modulation_dims_txt=None,
520
+ transformer_options={},
521
+ ):
522
+ try:
523
+ if self.modulation:
524
+ img_mod1, img_mod2 = self.img_mod(vec)
525
+ txt_mod1, txt_mod2 = self.txt_mod(vec)
526
+ else:
527
+ (img_mod1, img_mod2), (txt_mod1, txt_mod2) = vec
528
+
529
+ transformer_patches = transformer_options.get("patches", {})
530
+ extra_options = transformer_options.copy()
531
+
532
+ img_modulated = self.img_norm1(img)
533
+ img_modulated = apply_mod(img_modulated, (1 + img_mod1.scale), img_mod1.shift, modulation_dims_img)
534
+ img_qkv = self.img_attn.qkv(img_modulated)
535
+ del img_modulated
536
+ img_q, img_k, img_v = img_qkv.view(
537
+ img_qkv.shape[0], img_qkv.shape[1], 3, self.num_heads, -1
538
+ ).permute(2, 0, 3, 1, 4)
539
+ del img_qkv
540
+ img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
541
+
542
+ txt_modulated = self.txt_norm1(txt)
543
+ txt_modulated = apply_mod(txt_modulated, (1 + txt_mod1.scale), txt_mod1.shift, modulation_dims_txt)
544
+ txt_qkv = self.txt_attn.qkv(txt_modulated)
545
+ del txt_modulated
546
+ txt_q, txt_k, txt_v = txt_qkv.view(
547
+ txt_qkv.shape[0], txt_qkv.shape[1], 3, self.num_heads, -1
548
+ ).permute(2, 0, 3, 1, 4)
549
+ del txt_qkv
550
+ txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
551
+
552
+ q = torch.cat((txt_q, img_q), dim=2)
553
+ del txt_q, img_q
554
+ k = torch.cat((txt_k, img_k), dim=2)
555
+ del txt_k, img_k
556
+ v = torch.cat((txt_v, img_v), dim=2)
557
+ del txt_v, img_v
558
+
559
+ img_start = int(txt.shape[1])
560
+ img_end = int(q.shape[2])
561
+ extra_options["img_slice"] = [img_start, img_end]
562
+
563
+ if "attn1_patch" in transformer_patches:
564
+ for patch in transformer_patches["attn1_patch"]:
565
+ out = patch(q, k, v, pe=pe, attn_mask=attn_mask, extra_options=extra_options)
566
+ q = out.get("q", q)
567
+ k = out.get("k", k)
568
+ v = out.get("v", v)
569
+ pe = out.get("pe", pe)
570
+ attn_mask = out.get("attn_mask", attn_mask)
571
+
572
+ attn = _reference_attention(
573
+ q, k, v, pe, attn_mask, transformer_options,
574
+ (img_start, img_end), module_name,
575
+ )
576
+ del q, k, v
577
+
578
+ if "attn1_output_patch" in transformer_patches:
579
+ for patch in transformer_patches["attn1_output_patch"]:
580
+ attn = patch(attn, extra_options)
581
+
582
+ txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1]:]
583
+
584
+ img += apply_mod(self.img_attn.proj(img_attn), img_mod1.gate, None, modulation_dims_img)
585
+ del img_attn
586
+ img += apply_mod(
587
+ self.img_mlp(apply_mod(self.img_norm2(img), (1 + img_mod2.scale), img_mod2.shift, modulation_dims_img)),
588
+ img_mod2.gate,
589
+ None,
590
+ modulation_dims_img,
591
+ )
592
+
593
+ txt += apply_mod(self.txt_attn.proj(txt_attn), txt_mod1.gate, None, modulation_dims_txt)
594
+ del txt_attn
595
+ txt += apply_mod(
596
+ self.txt_mlp(apply_mod(self.txt_norm2(txt), (1 + txt_mod2.scale), txt_mod2.shift, modulation_dims_txt)),
597
+ txt_mod2.gate,
598
+ None,
599
+ modulation_dims_txt,
600
+ )
601
+
602
+ if txt.dtype == torch.float16 and not torch.isfinite(txt).all():
603
+ raise RuntimeError(f"{DISPLAY_NAME} double block produced non-finite txt tensor in {module_name}; strict mode refuses nan_to_num repair.")
604
+
605
+ return img, txt
606
+ except Exception as exc:
607
+ if hasattr(stats, "adapter_attn_failures"):
608
+ stats.adapter_attn_failures += 1
609
+ raise RuntimeError(f"{DISPLAY_NAME} double block patch failed in {module_name}; strict mode refuses to call original forward after patch failure: {exc}") from exc
610
+ return patched_double_forward
611
+
612
+ block.forward = types.MethodType(make_double_forward(original_forward, name), block)
613
+ setattr(block, "_untwist_flux2_active", True)
614
+ installed += 1
615
+
616
+ # Single-stream blocks: Q/K/V are produced inside the block, no child attn module.
617
+ for idx, block in enumerate(getattr(dm, "single_blocks", []) or []):
618
+ if not all(hasattr(block, attr) for attr in ("linear1", "linear2", "norm", "hidden_size", "num_heads")):
619
+ continue
620
+ matched += 1
621
+ name = f"single_blocks.{idx}"
622
+ patched_names.append(name)
623
+
624
+ if hasattr(block, "_untwist_orig_flux2_forward"):
625
+ block.forward = block._untwist_orig_flux2_forward
626
+ restored += 1
627
+ else:
628
+ block._untwist_orig_flux2_forward = block.forward
629
+ original_forward = block._untwist_orig_flux2_forward
630
+
631
+ def make_single_forward(orig, module_name):
632
+ def patched_single_forward(
633
+ self,
634
+ x,
635
+ vec,
636
+ pe,
637
+ attn_mask=None,
638
+ modulation_dims=None,
639
+ transformer_options={},
640
+ ):
641
+ try:
642
+ if self.modulation:
643
+ mod, _ = self.modulation(vec)
644
+ else:
645
+ mod = vec
646
+
647
+ transformer_patches = transformer_options.get("patches", {})
648
+ extra_options = transformer_options.copy()
649
+
650
+ qkv, mlp = torch.split(
651
+ self.linear1(apply_mod(self.pre_norm(x), (1 + mod.scale), mod.shift, modulation_dims)),
652
+ [3 * self.hidden_size, self.mlp_hidden_dim_first],
653
+ dim=-1,
654
+ )
655
+ q, k, v = qkv.view(
656
+ qkv.shape[0], qkv.shape[1], 3, self.num_heads, -1
657
+ ).permute(2, 0, 3, 1, 4)
658
+ del qkv
659
+ q, k = self.norm(q, k, v)
660
+
661
+ if "attn1_patch" in transformer_patches:
662
+ for patch in transformer_patches["attn1_patch"]:
663
+ out = patch(q, k, v, pe=pe, attn_mask=attn_mask, extra_options=extra_options)
664
+ q = out.get("q", q)
665
+ k = out.get("k", k)
666
+ v = out.get("v", v)
667
+ pe = out.get("pe", pe)
668
+ attn_mask = out.get("attn_mask", attn_mask)
669
+
670
+ img_slice = transformer_options.get("img_slice", None)
671
+ if isinstance(img_slice, (list, tuple)) and len(img_slice) >= 2:
672
+ image_range = (int(img_slice[0]), int(img_slice[1]))
673
+ else:
674
+ image_range = (0, int(q.shape[2]))
675
+
676
+ attn = _reference_attention(
677
+ q, k, v, pe, attn_mask, transformer_options,
678
+ image_range, module_name,
679
+ )
680
+ del q, k, v
681
+
682
+ if "attn1_output_patch" in transformer_patches:
683
+ for patch in transformer_patches["attn1_output_patch"]:
684
+ attn = patch(attn, extra_options)
685
+
686
+ if self.yak_mlp:
687
+ mlp = self.mlp_act(mlp[..., self.mlp_hidden_dim_first // 2:]) * mlp[..., :self.mlp_hidden_dim_first // 2]
688
+ else:
689
+ mlp = self.mlp_act(mlp)
690
+
691
+ output = self.linear2(torch.cat((attn, mlp), 2))
692
+ x += apply_mod(output, mod.gate, None, modulation_dims)
693
+
694
+ if x.dtype == torch.float16 and not torch.isfinite(x).all():
695
+ raise RuntimeError(f"{DISPLAY_NAME} single block produced non-finite tensor in {module_name}; strict mode refuses nan_to_num repair.")
696
+
697
+ return x
698
+ except Exception as exc:
699
+ if hasattr(stats, "adapter_attn_failures"):
700
+ stats.adapter_attn_failures += 1
701
+ raise RuntimeError(f"{DISPLAY_NAME} single block patch failed in {module_name}; strict mode refuses to call original forward after patch failure: {exc}") from exc
702
+ return patched_single_forward
703
+
704
+ block.forward = types.MethodType(make_single_forward(original_forward, name), block)
705
+ setattr(block, "_untwist_flux2_active", True)
706
+ installed += 1
707
+
708
+ if installed <= 0:
709
+ raise RuntimeError(f"{DISPLAY_NAME} adapter patch failed: no compatible double/single stream modules were installed.")
710
+ return matched, installed, restored, patched_names
711
+
712
+
713
+ def uses_reference_branch_kv() -> bool:
714
+ return False
715
+
716
+
717
+ # ---------------------------------------------------------------------------
718
+ # Diagnostics
719
+ # ---------------------------------------------------------------------------
720
+
721
+ def describe_match(model_info: dict[str, Any]) -> str:
722
+ model_config_class = str(model_info.get("model_config_class", ""))
723
+ unet_config = model_info.get("unet_config", {})
724
+ image_model = ""
725
+ if isinstance(unet_config, dict):
726
+ image_model = str(unet_config.get("image_model", ""))
727
+ else:
728
+ image_model = str(model_info.get("image_model", ""))
729
+
730
+ supported = ", ".join(sorted(SUPPORTED_MODEL_CONFIG_CLASSES))
731
+ return (
732
+ f"{DISPLAY_NAME}: model_config_class={model_config_class!r}, "
733
+ f"image_model={image_model!r}, supported_classes={{{supported}}}"
734
+ )
735
+
736
+
737
+ __all__ = [
738
+ "ARCHITECTURE",
739
+ "DISPLAY_NAME",
740
+ "SUPPORTED_MODEL_CONFIG_CLASSES",
741
+ "matches_model",
742
+ "is_model_identity",
743
+ "find_diffusion_model",
744
+ "default_runtime_cfg",
745
+ "axes_dims_from_dm",
746
+ "head_dim_from_dm",
747
+ "is_attention_name",
748
+ "is_double_stream_attention_name",
749
+ "is_single_stream_block_name",
750
+ "block_index_from_name",
751
+ "stream_kind_from_name",
752
+ "is_flux2_self_attention_module",
753
+ "is_flux2_single_stream_block",
754
+ "is_joint_attention",
755
+ "iter_flux2_patch_targets",
756
+ "prepare_reference_conditioning",
757
+ "patch_attention_modules",
758
+ "uses_reference_branch_kv",
759
+ "describe_match",
760
+ ]
custom_nodes/ComfyUi-Untwisting-RoPE/models/supported_models.txt ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ From ComfyUI\comfy\supported_models.py (5/26/2026)
2
+
3
+ ACEStep
4
+ ACEStep15
5
+ Anima
6
+ AuraFlow
7
+ Chroma
8
+ ChromaRadiance
9
+ CogVideoX_I2V
10
+ CogVideoX_Inpaint
11
+ CogVideoX_T2V
12
+ CosmosI2V
13
+ CosmosI2VPredict2
14
+ CosmosT2IPredict2
15
+ CosmosT2V
16
+ ErnieImage
17
+ Flux
18
+ Flux2
19
+ FluxInpaint
20
+ FluxSchnell
21
+ GenmoMochi
22
+ HiDream
23
+ HiDreamO1
24
+ Hunyuan3Dv2
25
+ Hunyuan3Dv2_1
26
+ Hunyuan3Dv2mini
27
+ HunyuanDiT
28
+ HunyuanDiT1
29
+ HunyuanImage21
30
+ HunyuanImage21Refiner
31
+ HunyuanVideo
32
+ HunyuanVideo15
33
+ HunyuanVideo15_SR_Distilled
34
+ HunyuanVideoI2V
35
+ HunyuanVideoSkyreelsI2V
36
+ Kandinsky5
37
+ Kandinsky5Image
38
+ KOALA_1B
39
+ KOALA_700M
40
+ LongCatImage
41
+ LotusD
42
+ LTXAV
43
+ LTXV
44
+ Lumina2
45
+ Omnigen2
46
+ PiD
47
+ PixArtAlpha
48
+ PixArtSigma
49
+ PixelDiTT2I
50
+ QwenImage
51
+ RT_DETR_v4
52
+ SAM3
53
+ SAM31
54
+ SD15
55
+ SD15_instructpix2pix
56
+ SD20
57
+ SD21UnclipH
58
+ SD21UnclipL
59
+ SD3
60
+ SD_X4Upscaler
61
+ SDXL
62
+ SDXL_instructpix2pix
63
+ SDXLRefiner
64
+ Segmind_Vega
65
+ SSD1B
66
+ Stable_Cascade_B
67
+ Stable_Cascade_C
68
+ Stable_Zero123
69
+ StableAudio
70
+ SV3D_p
71
+ SV3D_u
72
+ SVD_img2vid
73
+ WAN21_Camera
74
+ WAN21_CausalAR_T2V
75
+ WAN21_FlowRVS
76
+ WAN21_FunControl2V
77
+ WAN21_HuMo
78
+ WAN21_I2V
79
+ WAN21_SCAIL
80
+ WAN21_T2V
81
+ WAN21_Vace
82
+ WAN22_Animate
83
+ WAN22_Camera
84
+ WAN22_S2V
85
+ WAN22_T2V
86
+ WAN22_WanDancer
87
+ ZImage
88
+ ZImagePixelSpace
custom_nodes/ComfyUi-Untwisting-RoPE/models/zimage.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ import types
5
+ from typing import Any
6
+ from comfy.ldm.flux.math import apply_rope
7
+ from comfy.ldm.modules.attention import optimized_attention_masked
8
+
9
+ ARCHITECTURE = "zimage"
10
+ DISPLAY_NAME = "Z-Image"
11
+ CONFIG_KEY = "untwisting_rope"
12
+
13
+ # Support all Lumina-2 NextDiT variants defined in supported_models.py
14
+ SUPPORTED_MODEL_CONFIG_CLASSES = {"ZImage", "ZImagePixelSpace", "Lumina2"}
15
+ DIFFUSION_ATTR_PATHS = (
16
+ "model.diffusion_model",
17
+ "model.model.diffusion_model",
18
+ "inner_model.diffusion_model",
19
+ "model.inner_model.diffusion_model",
20
+ "diffusion_model",
21
+ )
22
+
23
+ def matches_model(model_info: dict[str, Any]) -> bool:
24
+ return str(model_info.get("model_config_class", "")) in SUPPORTED_MODEL_CONFIG_CLASSES
25
+
26
+ def _get_attr_path(root: Any, attr_path: str) -> tuple[Any, bool]:
27
+ obj = root
28
+ for part in attr_path.split("."):
29
+ if obj is None or not hasattr(obj, part):
30
+ return None, False
31
+ try:
32
+ obj = getattr(obj, part)
33
+ except Exception:
34
+ return None, False
35
+ return obj, True
36
+
37
+ def find_diffusion_model(model_patcher: Any) -> Any:
38
+ for path in DIFFUSION_ATTR_PATHS:
39
+ obj, ok = _get_attr_path(model_patcher, path)
40
+ if ok and obj is not None:
41
+ return obj
42
+ raise RuntimeError("Could not find ComfyUI BaseModel.diffusion_model for Z-Image.")
43
+
44
+ def is_joint_attention(module: Any) -> bool:
45
+ return (
46
+ hasattr(module, "qkv") and hasattr(module, "out")
47
+ and hasattr(module, "q_norm") and hasattr(module, "k_norm")
48
+ and hasattr(module, "n_local_heads") and hasattr(module, "n_local_kv_heads")
49
+ and hasattr(module, "head_dim")
50
+ and callable(getattr(module, "forward", None))
51
+ )
52
+
53
+ def is_main_layers_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
54
+ """Z-Image uses both layers.N and noise_refiner.N"""
55
+ parts = str(name).split(".")
56
+ if len(parts) != 3:
57
+ return False
58
+ if parts[2] != "attention":
59
+ return False
60
+ if parts[0] not in ("layers", "noise_refiner"):
61
+ return False
62
+ try:
63
+ idx = int(parts[1])
64
+ except Exception:
65
+ return False
66
+ return int(min_layer) <= idx <= int(max_layer)
67
+
68
+ def default_runtime_cfg(dm: Any | None = None) -> dict[str, Any]:
69
+ return {"architecture": ARCHITECTURE}
70
+
71
+ def is_attention_name(name: str, min_layer: int = 0, max_layer: int = 999) -> bool:
72
+ return is_main_layers_attention_name(name, min_layer, max_layer)
73
+
74
+ def prepare_reference_conditioning(ref_conditioning: Any, dm: Any, device: Any, dtype: Any, stats: Any, label: str = "", helpers: dict[str, Any] | None = None):
75
+ return ref_conditioning, "not-applicable"
76
+
77
+ def _adain(target: torch.Tensor, style: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
78
+ t_mean = target.mean(dim=1, keepdim=True)
79
+ s_mean = style.mean(dim=1, keepdim=True)
80
+ t_std = target.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
81
+ s_std = style.float().var(dim=1, keepdim=True, unbiased=False).add(eps).sqrt().to(target.dtype)
82
+ return (target - t_mean) / t_std * s_std + s_mean
83
+
84
+ def _coerce_strength01(value: Any, default: float = 0.0) -> float:
85
+ try:
86
+ strength = float(value)
87
+ except Exception as exc:
88
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].") from exc
89
+ if not torch.isfinite(torch.tensor(strength)):
90
+ raise ValueError(f"Invalid strength value {value!r}; expected a finite float in [0, 1].")
91
+ if not 0.0 <= strength <= 1.0:
92
+ raise ValueError(f"Invalid strength value {strength!r}; expected value in [0, 1].")
93
+ return strength
94
+
95
+ def _lerp(a: float, b: float, t: float) -> float:
96
+ return float(a + (b - a) * t)
97
+
98
+ def patch_attention_modules(dm: Any, stats: Any, helpers: dict[str, Any] | None = None):
99
+ helpers = helpers or {}
100
+
101
+ required_helpers = (
102
+ "patch_context_refiner_mask_modules",
103
+ "patch_patchify_and_embed",
104
+ "build_frequency_scale_vector",
105
+ )
106
+ missing = [name for name in required_helpers if not callable(helpers.get(name))]
107
+ if missing:
108
+ raise RuntimeError(f"Z-Image adapter missing required helper(s): {missing}")
109
+
110
+ # Apply context refiner and patchify patches so cfg['ref_real_ranges'] populates correctly.
111
+ helpers["patch_context_refiner_mask_modules"](dm, stats)
112
+ helpers["patch_patchify_and_embed"](dm, stats)
113
+
114
+ build_frequency_scale_vector = helpers["build_frequency_scale_vector"]
115
+
116
+ matched = installed = restored = 0
117
+ patched_names = []
118
+
119
+ for name, module in dm.named_modules():
120
+ if not is_main_layers_attention_name(name, 0, 999):
121
+ continue
122
+ if not is_joint_attention(module):
123
+ continue
124
+
125
+ matched += 1
126
+ patched_names.append(name)
127
+
128
+ if hasattr(module, "_untwist_orig_forward"):
129
+ module.forward = module._untwist_orig_forward
130
+ restored += 1
131
+ else:
132
+ module._untwist_orig_forward = module.forward
133
+
134
+ original_forward = module._untwist_orig_forward
135
+
136
+ def make_forward(orig, module_name):
137
+ def patched_forward(self, x, x_mask, freqs_cis, transformer_options={}):
138
+ cfg = transformer_options.get(CONFIG_KEY) if isinstance(transformer_options, dict) else None
139
+ if not cfg or not cfg.get("enabled"):
140
+ return orig(x, x_mask, freqs_cis, transformer_options=transformer_options)
141
+
142
+ target_bsz = int(cfg.get("cross_batch_target_batch", 0))
143
+ if target_bsz <= 0:
144
+ raise RuntimeError(f"Z-Image Untwisting enabled in {module_name}, but cross_batch_target_batch={target_bsz}.")
145
+
146
+ if not torch.is_tensor(x) or x.ndim != 3:
147
+ raise RuntimeError(f"Z-Image Untwisting expected x as [B,S,C] tensor in {module_name}; got {type(x).__name__} with ndim={getattr(x, 'ndim', None)}.")
148
+
149
+ bsz, seqlen, _ = x.shape
150
+ if bsz < target_bsz * 2:
151
+ raise RuntimeError(f"Z-Image Untwisting expected at least target+reference batches in {module_name}; bsz={bsz}, target_bsz={target_bsz}.")
152
+
153
+ block_idx = int(transformer_options.get("block_index", -1))
154
+ active_blocks = cfg.get("active_blocks", set())
155
+ if active_blocks and block_idx not in active_blocks:
156
+ return orig(x, x_mask, freqs_cis, transformer_options=transformer_options)
157
+
158
+ # Fix for Z-Image: noise_refiner runs only on image. Main layers run on text+image.
159
+ is_noise_refiner = "noise_refiner" in module_name
160
+ if is_noise_refiner:
161
+ img_s, img_e = 0, seqlen
162
+ else:
163
+ ref_ranges = cfg.get("ref_real_ranges", [])
164
+ if not ref_ranges:
165
+ raise RuntimeError(f"Z-Image Untwisting enabled in {module_name}, but cfg['ref_real_ranges'] is missing. patchify_and_embed did not populate the image token range.")
166
+ img_s, img_e = ref_ranges[0]
167
+
168
+ img_s = max(0, min(img_s, seqlen))
169
+ img_e = max(img_s, min(img_e, seqlen))
170
+
171
+ if img_e <= img_s:
172
+ raise RuntimeError(f"Z-Image Untwisting has an empty image token range in {module_name}: {(img_s, img_e)} for seqlen={seqlen}.")
173
+
174
+ if hasattr(stats, "attn_calls"):
175
+ stats.attn_calls += 1
176
+
177
+ xq, xk, xv = torch.split(
178
+ self.qkv(x),
179
+ [
180
+ self.n_local_heads * self.head_dim,
181
+ self.n_local_kv_heads * self.head_dim,
182
+ self.n_local_kv_heads * self.head_dim,
183
+ ],
184
+ dim=-1,
185
+ )
186
+ xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
187
+ xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
188
+ xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
189
+
190
+ xq = self.q_norm(xq)
191
+ xk = self.k_norm(xk)
192
+
193
+ # Pre-RoPE AdaIN
194
+ a = float(cfg.get("adain_strength", 0.0))
195
+ apply_adain = cfg.get("apply_adain", False) and a > 0.0
196
+ if apply_adain:
197
+ q_t = xq[:target_bsz, img_s:img_e]
198
+ k_t = xk[:target_bsz, img_s:img_e]
199
+ q_r = xq[target_bsz:target_bsz*2, img_s:img_e]
200
+ k_r = xk[target_bsz:target_bsz*2, img_s:img_e]
201
+
202
+ xq[:target_bsz, img_s:img_e] = q_t * (1 - a) + _adain(q_t, q_r) * a
203
+ xk[:target_bsz, img_s:img_e] = k_t * (1 - a) + _adain(k_t, k_r) * a
204
+
205
+ if cfg.get("adain_on_v", False):
206
+ v_t = xv[:target_bsz, img_s:img_e]
207
+ v_r = xv[target_bsz:target_bsz*2, img_s:img_e]
208
+ xv[:target_bsz, img_s:img_e] = v_t * (1 - a) + _adain(v_t, v_r) * a
209
+
210
+ xq, xk = apply_rope(xq, xk, freqs_cis)
211
+
212
+ # Untwisting RoPE Frequencies
213
+ progress = float(cfg.get("progress", 0.0))
214
+ high_scale = _lerp(cfg["high_scale_start"], cfg["high_scale_end"], progress)
215
+ low_scale = _lerp(cfg["low_scale_start"], cfg["low_scale_end"], progress)
216
+ beta = float(cfg.get("beta", 2.0))
217
+
218
+ scale_vec = build_frequency_scale_vector(
219
+ self.head_dim,
220
+ cfg.get("axes_dims") or getattr(dm, "axes_dims", []),
221
+ high_scale, low_scale, beta,
222
+ xk.device, xk.dtype,
223
+ runtime_cfg=cfg
224
+ ).view(1, 1, 1, self.head_dim)
225
+
226
+ ref_k = xk[target_bsz:target_bsz*2, img_s:img_e] * scale_vec
227
+ ref_v = xv[target_bsz:target_bsz*2, img_s:img_e]
228
+
229
+ n_rep = self.n_local_heads // self.n_local_kv_heads
230
+ def expand_kv(k_tensor, v_tensor):
231
+ if self.n_local_kv_heads <= 0:
232
+ raise RuntimeError(f"Z-Image Untwisting invalid KV head count in {module_name}: n_local_kv_heads={self.n_local_kv_heads}.")
233
+ if self.n_local_heads % self.n_local_kv_heads != 0:
234
+ raise RuntimeError(f"Z-Image Untwisting cannot expand KV heads in {module_name}: q_heads={self.n_local_heads}, kv_heads={self.n_local_kv_heads}.")
235
+ n_rep_local = self.n_local_heads // self.n_local_kv_heads
236
+ if n_rep_local < 1:
237
+ raise RuntimeError(f"Z-Image Untwisting invalid KV repeat factor in {module_name}: n_rep={n_rep_local}.")
238
+ k_tensor = k_tensor.unsqueeze(3).repeat(1, 1, 1, n_rep_local, 1).flatten(2, 3)
239
+ v_tensor = v_tensor.unsqueeze(3).repeat(1, 1, 1, n_rep_local, 1).flatten(2, 3)
240
+ return k_tensor, v_tensor
241
+
242
+ # TARGET STREAM
243
+ k_t_full = torch.cat([xk[:target_bsz], ref_k], dim=1)
244
+ v_t_full = torch.cat([xv[:target_bsz], ref_v], dim=1)
245
+ k_t_full, v_t_full = expand_kv(k_t_full, v_t_full)
246
+
247
+ xq_t = xq[:target_bsz]
248
+
249
+ mask_t = x_mask[:target_bsz] if x_mask is not None else None
250
+ if mask_t is not None:
251
+ ref_len = img_e - img_s
252
+ if mask_t.ndim < 2:
253
+ raise RuntimeError(f"Z-Image Untwisting cannot append reference mask in {module_name}: mask ndim={mask_t.ndim}, expected >=2.")
254
+ pad = torch.zeros((*mask_t.shape[:-1], ref_len), device=mask_t.device, dtype=mask_t.dtype)
255
+ mask_t = torch.cat([mask_t, pad], dim=-1)
256
+
257
+ out_t = optimized_attention_masked(
258
+ xq_t.movedim(1, 2), k_t_full.movedim(1, 2), v_t_full.movedim(1, 2),
259
+ self.n_local_heads, mask_t, skip_reshape=True, transformer_options=transformer_options
260
+ )
261
+
262
+ # REFERENCE STREAM
263
+ xq_r = xq[target_bsz:target_bsz*2]
264
+ xk_r, xv_r = expand_kv(xk[target_bsz:target_bsz*2], xv[target_bsz:target_bsz*2])
265
+ mask_r = x_mask[target_bsz:target_bsz*2] if x_mask is not None else None
266
+
267
+ out_r = optimized_attention_masked(
268
+ xq_r.movedim(1, 2), xk_r.movedim(1, 2), xv_r.movedim(1, 2),
269
+ self.n_local_heads, mask_r, skip_reshape=True, transformer_options=transformer_options
270
+ )
271
+
272
+ # POST-ATTENTION AdaIN
273
+ post_a = _coerce_strength01(cfg.get("post_attention_adain_strength", 0.0))
274
+ if post_a > 0.0:
275
+ out_t_adain = _adain(out_t[:, img_s:img_e], out_r[:, img_s:img_e], eps=1e-6)
276
+ out_t[:, img_s:img_e] = out_t[:, img_s:img_e] * (1.0 - post_a) + out_t_adain * post_a
277
+
278
+ outs = [out_t, out_r]
279
+
280
+ # EXTRA BATCHES (uncond)
281
+ if bsz > target_bsz * 2:
282
+ xq_e = xq[target_bsz*2:]
283
+ xk_e, xv_e = expand_kv(xk[target_bsz*2:], xv[target_bsz*2:])
284
+ mask_e = x_mask[target_bsz*2:] if x_mask is not None else None
285
+ out_e = optimized_attention_masked(
286
+ xq_e.movedim(1, 2), xk_e.movedim(1, 2), xv_e.movedim(1, 2),
287
+ self.n_local_heads, mask_e, skip_reshape=True, transformer_options=transformer_options
288
+ )
289
+ outs.append(out_e)
290
+
291
+ final_out = torch.cat(outs, dim=0)
292
+ return self.out(final_out)
293
+
294
+ return patched_forward
295
+
296
+ module.forward = types.MethodType(make_forward(original_forward, name), module)
297
+ installed += 1
298
+
299
+ if installed <= 0:
300
+ raise RuntimeError("Z-Image adapter patch failed: no compatible attention modules were installed.")
301
+ return matched, installed, restored, patched_names
302
+
303
+ def uses_reference_branch_kv() -> bool:
304
+ return False
custom_nodes/ComfyUi-Untwisting-RoPE/pyproject.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "untwistingrope"
3
+ description = "A ComfyUI custom node for Untwisting RoPE."
4
+ version = "1.0.0"
5
+ license = {file = "LICENSE"}
6
+
7
+ [project.urls]
8
+ Repository = "https://github.com/BigStationW/ComfyUi-Untwisting-RoPE"
9
+ Documentation = "https://github.com/BigStationW/ComfyUi-Untwisting-RoPE/wiki"
10
+ "Bug Tracker" = "https://github.com/BigStationW/ComfyUi-Untwisting-RoPE/issues"
11
+
12
+ [tool.comfy]
13
+ PublisherId = "bigstationw"
14
+ DisplayName = "ComfyUi-Untwisting-RoPE"
15
+ Icon = ""
16
+ includes = []
17
+ # "requires-comfyui" = ">=1.0.0"
custom_nodes/ComfyUi-Untwisting-RoPE/verbose_prints.py ADDED
@@ -0,0 +1,812 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import time
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ import torch
8
+
9
+ _PREFIX = '[UntwistingRoPE]'
10
+ _RF_PREFIX = '[RFInversion]'
11
+
12
+ def _rf_prefix(stats: Optional[Any] = None) -> str:
13
+ if stats is None:
14
+ return _RF_PREFIX
15
+ prefix = getattr(stats, 'rf_prefix', None)
16
+ if prefix is None:
17
+ return _RF_PREFIX
18
+ if not isinstance(prefix, str) or not prefix:
19
+ raise RuntimeError(f'Invalid RF prefix on stats: {prefix!r}')
20
+ return prefix
21
+
22
+ def _coerce_bool(value: Any) -> bool:
23
+ """Robust boolean parsing for ComfyUI values that may arrive as bools or strings."""
24
+ if isinstance(value, str):
25
+ return value.strip().lower() in ('1', 'true', 'yes', 'on', 'y', 't')
26
+ return bool(value)
27
+
28
+ class _RuntimeStats:
29
+ def __init__(self, verbose: bool = False, rf_verbose: bool = False) -> None:
30
+ # verbose controls UntwistingRoPE patch/attention logs.
31
+ # rf_verbose controls RFInversion trajectory/wrapper logs.
32
+ self.verbose: bool = _coerce_bool(verbose)
33
+ self.rf_verbose: bool = _coerce_bool(rf_verbose)
34
+ self.rf_prefix: str = _RF_PREFIX
35
+ self.wrapper_calls: int = 0
36
+ self.patchify_calls: int = 0
37
+ self.attn_calls: int = 0
38
+ self.context_refiner_calls: int = 0
39
+ self.adapter_attn_calls: int = 0
40
+ self.adapter_attn_failures: int = 0
41
+
42
+ self.rf_sigma_cache: Dict[float, torch.Tensor] = {}
43
+ self.rf_eps: Optional[torch.Tensor] = None
44
+ self.rf_prev_z: Optional[torch.Tensor] = None
45
+ self.rf_prev_sigma: Optional[float] = None
46
+ self.rf_step_count: int = 0
47
+ self.rf_run_count: int = 0
48
+ self.rf_sampler_sigmas: Optional[List[float]] = None
49
+ self.rf_schedule_built: bool = False
50
+
51
+ self.fixed_noise: Optional[torch.Tensor] = None
52
+
53
+ self.scale_vec_logged: bool = False
54
+ self.joint_mask_logged: bool = False
55
+
56
+ # Parameterization detection: tracks whether apply_model is x0 or velocity
57
+ self.parameterization: str = 'unknown'
58
+
59
+ def _vprint(stats: Optional[_RuntimeStats], *args, **kwargs) -> None:
60
+ if stats is not None and _coerce_bool(getattr(stats, 'verbose', False)):
61
+ print(*args, **kwargs)
62
+
63
+ def _rf_vprint(stats: Optional[_RuntimeStats], *args, **kwargs) -> None:
64
+ if stats is not None and _coerce_bool(getattr(stats, 'rf_verbose', False)):
65
+ print(*args, **kwargs)
66
+
67
+ def _rf_tensor_summary(name: str, value: Any) -> str:
68
+ """Compact tensor diagnostic string safe for dtype/device/empty tensors."""
69
+ if not torch.is_tensor(value):
70
+ return f'{name}=<{type(value).__name__}>'
71
+ try:
72
+ shape = tuple(int(v) for v in value.shape)
73
+ base = f'{name}: shape={shape} dtype={value.dtype} device={value.device}'
74
+ if value.numel() == 0:
75
+ return base + ' empty'
76
+ vf = value.detach().float()
77
+ return (
78
+ f'{base} mean={float(vf.mean().item()):.6f} '
79
+ f'std={float(vf.std(unbiased=False).item()):.6f} '
80
+ f'min={float(vf.min().item()):.6f} max={float(vf.max().item()):.6f}'
81
+ )
82
+ except Exception as exc:
83
+ raise RuntimeError(f'{_RF_PREFIX} tensor summary failed for {name}; strict mode refuses to hide diagnostic failure: {exc}') from exc
84
+
85
+ def _rf_sequence_summary(name: str, seq: Any, max_items: int = 8) -> str:
86
+ values = _coerce_sigma_sequence(seq)
87
+ if values is None:
88
+ return f'{name}=<none/invalid>'
89
+ head = ', '.join(f'{v:.6f}' for v in values[:max_items])
90
+ tail = ', '.join(f'{v:.6f}' for v in values[-max_items:])
91
+ if len(values) <= max_items * 2:
92
+ body = ', '.join(f'{v:.6f}' for v in values)
93
+ else:
94
+ body = f'{head}, ..., {tail}'
95
+ return f'{name}: count={len(values)} min={min(values):.6f} max={max(values):.6f} values=[{body}]'
96
+
97
+ def _rf_brief_obj(obj: Any, depth: int = 0) -> str:
98
+ """Small structural summary for conditioning/debug dictionaries."""
99
+ if torch.is_tensor(obj):
100
+ return f'Tensor{tuple(obj.shape)}:{obj.dtype}:{obj.device}'
101
+ if obj is None:
102
+ return 'None'
103
+ if depth >= 2:
104
+ return type(obj).__name__
105
+ if isinstance(obj, dict):
106
+ items = []
107
+ for idx, (k, v) in enumerate(obj.items()):
108
+ if idx >= 12:
109
+ items.append('...')
110
+ break
111
+ items.append(f'{k}={_rf_brief_obj(v, depth + 1)}')
112
+ return '{' + ', '.join(items) + '}'
113
+ if isinstance(obj, (list, tuple)):
114
+ items = []
115
+ for idx, v in enumerate(obj):
116
+ if idx >= 8:
117
+ items.append('...')
118
+ break
119
+ items.append(_rf_brief_obj(v, depth + 1))
120
+ return f'{type(obj).__name__}[{len(obj)}](' + ', '.join(items) + ')'
121
+ return f'{type(obj).__name__}({repr(obj)[:80]})'
122
+
123
+ def _rf_tensor_stats(value: Any) -> Dict[str, Any]:
124
+ """Numerical health stats used only for RF diagnostics."""
125
+ out: Dict[str, Any] = {
126
+ 'is_tensor': torch.is_tensor(value),
127
+ 'finite': False,
128
+ 'numel': 0,
129
+ 'nan_count': None,
130
+ 'inf_count': None,
131
+ 'mean': None,
132
+ 'std': None,
133
+ 'min': None,
134
+ 'max': None,
135
+ 'max_abs': None,
136
+ }
137
+ if not torch.is_tensor(value):
138
+ return out
139
+ try:
140
+ x = value.detach().float()
141
+ out['numel'] = int(x.numel())
142
+ if x.numel() == 0:
143
+ out['finite'] = True
144
+ return out
145
+ finite = torch.isfinite(x)
146
+ out['finite'] = bool(finite.all().item())
147
+ out['nan_count'] = int(torch.isnan(x).sum().item())
148
+ out['inf_count'] = int(torch.isinf(x).sum().item())
149
+ xf = x[finite]
150
+ if xf.numel() == 0:
151
+ return out
152
+ out['mean'] = float(xf.mean().item())
153
+ out['std'] = float(xf.std(unbiased=False).item())
154
+ out['min'] = float(xf.min().item())
155
+ out['max'] = float(xf.max().item())
156
+ out['max_abs'] = float(xf.abs().max().item())
157
+ except Exception as exc:
158
+ raise RuntimeError(f'{_RF_PREFIX} tensor stats failed; strict mode refuses to hide diagnostic failure: {exc}') from exc
159
+ return out
160
+
161
+ def _rf_scalar_fmt(value: Any, digits: int = 6) -> str:
162
+ try:
163
+ if value is None:
164
+ return 'n/a'
165
+ value = float(value)
166
+ if not math.isfinite(value):
167
+ return str(value)
168
+ return f'{value:.{digits}f}'
169
+ except Exception as exc:
170
+ raise RuntimeError(f'{_RF_PREFIX} scalar formatting failed for value={value!r}: {exc}') from exc
171
+
172
+ def _rf_tensor_mae(a: Any, b: Any) -> Optional[float]:
173
+ if not (torch.is_tensor(a) and torch.is_tensor(b)):
174
+ return None
175
+ try:
176
+ aa = a.detach().float().to(device='cpu')
177
+ bb = b.detach().float().to(device='cpu')
178
+ if aa.shape != bb.shape or aa.numel() == 0:
179
+ return None
180
+ return float((aa - bb).abs().mean().item())
181
+ except Exception as exc:
182
+ raise RuntimeError(f'{_RF_PREFIX} tensor MAE failed; strict mode refuses to hide diagnostic failure: {exc}') from exc
183
+
184
+ def _rf_tensor_rmse(a: Any, b: Any) -> Optional[float]:
185
+ if not (torch.is_tensor(a) and torch.is_tensor(b)):
186
+ return None
187
+ try:
188
+ aa = a.detach().float().to(device='cpu')
189
+ bb = b.detach().float().to(device='cpu')
190
+ if aa.shape != bb.shape or aa.numel() == 0:
191
+ return None
192
+ return float((aa - bb).pow(2).mean().sqrt().item())
193
+ except Exception as exc:
194
+ raise RuntimeError(f'{_RF_PREFIX} tensor RMSE failed; strict mode refuses to hide diagnostic failure: {exc}') from exc
195
+
196
+ def _rf_tensor_cosine(a: Any, b: Any) -> Optional[float]:
197
+ if not (torch.is_tensor(a) and torch.is_tensor(b)):
198
+ return None
199
+ try:
200
+ aa = a.detach().float().flatten().to(device='cpu')
201
+ bb = b.detach().float().flatten().to(device='cpu')
202
+ if aa.shape != bb.shape or aa.numel() == 0:
203
+ return None
204
+ denom = aa.norm() * bb.norm()
205
+ if float(denom.item()) <= 1e-12:
206
+ return None
207
+ return float(torch.dot(aa, bb).div(denom).item())
208
+ except Exception as exc:
209
+ raise RuntimeError(f'{_RF_PREFIX} tensor cosine failed; strict mode refuses to hide diagnostic failure: {exc}') from exc
210
+
211
+ def _rf_diagnostic_level(summary: Dict[str, Any]) -> str:
212
+ """Return a conservative numerical-health classification for the RF trajectory."""
213
+ if not summary.get('finite_all', False):
214
+ return 'FAIL'
215
+ final_std = summary.get('final_std')
216
+ final_max_abs = summary.get('final_max_abs')
217
+ final_eps_std_ratio = summary.get('final_eps_std_ratio')
218
+
219
+ # These thresholds are intentionally broad and only detect numerical collapse/divergence,
220
+ # not subjective image quality or semantic faithfulness.
221
+ try:
222
+ if final_std is not None and float(final_std) < 0.05:
223
+ return 'FAIL'
224
+ if final_std is not None and float(final_std) > 20.0:
225
+ return 'FAIL'
226
+ if final_max_abs is not None and float(final_max_abs) > 100.0:
227
+ return 'FAIL'
228
+ if final_eps_std_ratio is not None and (
229
+ float(final_eps_std_ratio) < 0.25 or float(final_eps_std_ratio) > 4.0
230
+ ):
231
+ return 'WARN'
232
+ except Exception as exc:
233
+ raise RuntimeError(f'{_RF_PREFIX} diagnostic-level calculation failed; strict mode refuses to downgrade to WARN: {exc}') from exc
234
+ return 'PASS'
235
+
236
+ def _rf_stability_summary(
237
+ ref_clean: torch.Tensor,
238
+ eps: torch.Tensor,
239
+ cache: Dict[float, torch.Tensor],
240
+ sigmas: List[float],
241
+ ) -> Dict[str, Any]:
242
+ """Collect explicit RF trajectory sanity metrics without changing sampling."""
243
+ keys = sorted(float(k) for k in cache.keys() if isinstance(k, (int, float)))
244
+ summary: Dict[str, Any] = {
245
+ 'cache_items': len(cache),
246
+ 'sigmas': len(sigmas or []),
247
+ 'first_sigma': keys[0] if keys else None,
248
+ 'last_sigma': keys[-1] if keys else None,
249
+ 'finite_all': True,
250
+ 'level': 'WARN',
251
+ 'warnings': [],
252
+ }
253
+ if not keys:
254
+ summary['finite_all'] = False
255
+ summary['warnings'].append('cache_empty')
256
+ summary['level'] = 'FAIL'
257
+ return summary
258
+
259
+ stds: List[float] = []
260
+ max_abs_values: List[float] = []
261
+ bad_keys: List[float] = []
262
+ prev_tensor: Optional[torch.Tensor] = None
263
+ dz_values: List[float] = []
264
+
265
+ for k in keys:
266
+ t = cache.get(k)
267
+ st = _rf_tensor_stats(t)
268
+ if not st.get('finite', False):
269
+ bad_keys.append(k)
270
+ summary['finite_all'] = False
271
+ if st.get('std') is not None:
272
+ stds.append(float(st['std']))
273
+ if st.get('max_abs') is not None:
274
+ max_abs_values.append(float(st['max_abs']))
275
+ if torch.is_tensor(prev_tensor) and torch.is_tensor(t) and prev_tensor.shape == t.shape:
276
+ try:
277
+ dz_values.append(float((t.detach().float() - prev_tensor.detach().float()).abs().mean().item()))
278
+ except Exception as exc:
279
+ raise RuntimeError(f'{_RF_PREFIX} Δz diagnostic failed; strict mode refuses to skip it: {exc}') from exc
280
+ prev_tensor = t if torch.is_tensor(t) else None
281
+
282
+ first = cache.get(keys[0])
283
+ final = cache.get(keys[-1])
284
+ first_stats = _rf_tensor_stats(first)
285
+ final_stats = _rf_tensor_stats(final)
286
+ eps_stats = _rf_tensor_stats(eps)
287
+ ref_stats = _rf_tensor_stats(ref_clean)
288
+
289
+ summary.update({
290
+ 'bad_sigma_keys': bad_keys[:16],
291
+ 'std_min': min(stds) if stds else None,
292
+ 'std_max': max(stds) if stds else None,
293
+ 'max_abs_max': max(max_abs_values) if max_abs_values else None,
294
+ 'dz_mean': (sum(dz_values) / len(dz_values)) if dz_values else None,
295
+ 'dz_max': max(dz_values) if dz_values else None,
296
+ 'ref_std': ref_stats.get('std'),
297
+ 'eps_std': eps_stats.get('std'),
298
+ 'first_std': first_stats.get('std'),
299
+ 'final_std': final_stats.get('std'),
300
+ 'final_mean': final_stats.get('mean'),
301
+ 'final_min': final_stats.get('min'),
302
+ 'final_max': final_stats.get('max'),
303
+ 'final_max_abs': final_stats.get('max_abs'),
304
+ 'first_vs_ref_mae': _rf_tensor_mae(first, ref_clean),
305
+ 'final_vs_eps_mae': _rf_tensor_mae(final, eps),
306
+ 'final_vs_eps_rmse': _rf_tensor_rmse(final, eps),
307
+ 'final_vs_eps_cosine': _rf_tensor_cosine(final, eps),
308
+ })
309
+
310
+ try:
311
+ eps_std = summary.get('eps_std')
312
+ final_std = summary.get('final_std')
313
+ if eps_std is not None and float(eps_std) > 1e-12 and final_std is not None:
314
+ summary['final_eps_std_ratio'] = float(final_std) / float(eps_std)
315
+ else:
316
+ summary['final_eps_std_ratio'] = None
317
+ except Exception as exc:
318
+ raise RuntimeError(f'{_RF_PREFIX} final/eps std-ratio diagnostic failed; strict mode refuses to hide it: {exc}') from exc
319
+
320
+ if bad_keys:
321
+ summary['warnings'].append('nonfinite_values')
322
+ if summary.get('first_vs_ref_mae') is not None and float(summary['first_vs_ref_mae']) > 1e-4:
323
+ summary['warnings'].append('cache_sigma0_not_reference')
324
+ summary['level'] = _rf_diagnostic_level(summary)
325
+ return summary
326
+
327
+ def _rf_print_stability_summary(summary: Dict[str, Any]) -> None:
328
+ level = summary.get('level', 'WARN')
329
+ print(f'{_RF_PREFIX} RF numerical sanity: {level}')
330
+ print(
331
+ f'{_RF_PREFIX} cache_items={summary.get("cache_items")} '
332
+ f'sigmas={summary.get("sigmas")} '
333
+ f'first_sigma={_rf_scalar_fmt(summary.get("first_sigma"))} '
334
+ f'last_sigma={_rf_scalar_fmt(summary.get("last_sigma"))} '
335
+ f'finite_all={summary.get("finite_all")}'
336
+ )
337
+ print(
338
+ f'{_RF_PREFIX} std: ref={_rf_scalar_fmt(summary.get("ref_std"))} '
339
+ f'first={_rf_scalar_fmt(summary.get("first_std"))} '
340
+ f'final={_rf_scalar_fmt(summary.get("final_std"))} '
341
+ f'eps={_rf_scalar_fmt(summary.get("eps_std"))} '
342
+ f'final/eps={_rf_scalar_fmt(summary.get("final_eps_std_ratio"))} '
343
+ f'range=[{_rf_scalar_fmt(summary.get("std_min"))}, {_rf_scalar_fmt(summary.get("std_max"))}]'
344
+ )
345
+ print(
346
+ f'{_RF_PREFIX} final: mean={_rf_scalar_fmt(summary.get("final_mean"))} '
347
+ f'min={_rf_scalar_fmt(summary.get("final_min"))} '
348
+ f'max={_rf_scalar_fmt(summary.get("final_max"))} '
349
+ f'max_abs={_rf_scalar_fmt(summary.get("final_max_abs"))} '
350
+ f'max_abs_over_path={_rf_scalar_fmt(summary.get("max_abs_max"))}'
351
+ )
352
+ print(
353
+ f'{_RF_PREFIX} deltas: mean|Δz|={_rf_scalar_fmt(summary.get("dz_mean"))} '
354
+ f'max|Δz|={_rf_scalar_fmt(summary.get("dz_max"))} '
355
+ f'first_vs_ref_mae={_rf_scalar_fmt(summary.get("first_vs_ref_mae"))} '
356
+ f'final_vs_eps_mae={_rf_scalar_fmt(summary.get("final_vs_eps_mae"))} '
357
+ f'final_vs_eps_rmse={_rf_scalar_fmt(summary.get("final_vs_eps_rmse"))} '
358
+ f'final_vs_eps_cos={_rf_scalar_fmt(summary.get("final_vs_eps_cosine"))}'
359
+ )
360
+ warnings = summary.get('warnings') or []
361
+ if warnings:
362
+ print(f'{_RF_PREFIX} warnings={warnings} bad_sigma_keys={summary.get("bad_sigma_keys", [])}')
363
+ if level != 'PASS':
364
+ print(
365
+ f'{_RF_PREFIX} ⚠ RF numerical sanity did not PASS. This is a diagnostic flag only; '
366
+ f'it means inspect the printed stats and the generated image before trusting the run.'
367
+ )
368
+ else:
369
+ print(
370
+ f'{_RF_PREFIX} RF numerical sanity PASS only means no obvious numeric collapse/divergence; '
371
+ f'it does not prove visual/semantic quality.'
372
+ )
373
+
374
+ def _rf_model_identity(model_patcher: Any) -> Dict[str, Any]:
375
+ """Best-effort model identity diagnostics; never used for math decisions."""
376
+ base = getattr(model_patcher, 'model', model_patcher)
377
+ diffusion_model = getattr(base, 'diffusion_model', None)
378
+ model_config = getattr(base, 'model_config', None)
379
+ unet_config = getattr(model_config, 'unet_config', None)
380
+ if not isinstance(unet_config, dict):
381
+ unet_config = {}
382
+ model_type = getattr(base, 'model_type', None)
383
+ model_sampling = getattr(base, 'model_sampling', None)
384
+ latent_format = getattr(base, 'latent_format', None)
385
+ info = {
386
+ 'base_class': type(base).__name__ if base is not None else 'None',
387
+ 'diffusion_class': type(diffusion_model).__name__ if diffusion_model is not None else 'None',
388
+ 'diffusion_module': getattr(type(diffusion_model), '__module__', '') if diffusion_model is not None else '',
389
+ 'model_type': getattr(model_type, 'name', str(model_type)),
390
+ 'model_sampling_class': type(model_sampling).__name__ if model_sampling is not None else 'None',
391
+ 'latent_format_class': type(latent_format).__name__ if latent_format is not None else 'None',
392
+ 'image_model': unet_config.get('image_model', None),
393
+ 'in_channels': unet_config.get('in_channels', None),
394
+ 'out_channels': unet_config.get('out_channels', None),
395
+ }
396
+ return info
397
+
398
+ def _rf_print_model_identity(prefix: str, info: Dict[str, Any]) -> None:
399
+ print(
400
+ f'{prefix} model_info: base={info.get("base_class")} '
401
+ f'diffusion={info.get("diffusion_module")}.{info.get("diffusion_class")} '
402
+ f'image_model={info.get("image_model")} adapter={info.get("architecture_name", info.get("architecture", "unknown"))}\n'
403
+ f'{prefix} model_type={info.get("model_type")} '
404
+ f'sampling={info.get("model_sampling_class")} '
405
+ f'latent_format={info.get("latent_format_class")} '
406
+ f'in_channels={info.get("in_channels")} out_channels={info.get("out_channels")}'
407
+ )
408
+
409
+ def _rf_step_iterator(num_steps: int):
410
+ """Plain RF step iterator.
411
+
412
+ Do not use tqdm/model_trange here because that refreshes a single terminal
413
+ line. RF inversion wants persistent per-step console lines, while still
414
+ keeping the preview callback independent.
415
+ """
416
+ return range(max(0, int(num_steps)))
417
+
418
+ def _rf_format_duration(seconds: float) -> str:
419
+ seconds_i = int(max(0, round(float(seconds))))
420
+ minutes, seconds_i = divmod(seconds_i, 60)
421
+ hours, minutes = divmod(minutes, 60)
422
+ if hours > 0:
423
+ return f'{hours:d}:{minutes:02d}:{seconds_i:02d}'
424
+ return f'{minutes:02d}:{seconds_i:02d}'
425
+
426
+ def _rf_progress_snapshot(step_i: int, total_steps: int, start_time: float, persistent: bool = False) -> None:
427
+ total_steps = max(1, int(total_steps))
428
+ step_i = max(0, min(int(step_i), total_steps))
429
+
430
+ elapsed = max(0.0, time.time() - float(start_time))
431
+ frac = step_i / total_steps
432
+
433
+ bar_width = 70
434
+ filled = int(round(bar_width * frac))
435
+ bar = '█' * filled + ' ' * (bar_width - filled)
436
+
437
+ percent = int(round(frac * 100.0))
438
+ rate = step_i / elapsed if elapsed > 1e-9 else 0.0
439
+ remaining = max(0.0, (total_steps - step_i) / rate) if step_i > 0 and rate > 1e-9 else 0.0
440
+ rate_text = f'{rate:.2f}it/s' if rate >= 1.0 else f'{(1.0 / max(rate, 1e-9)):.2f}s/it'
441
+
442
+ line = (
443
+ f'RF inversion: {percent:3d}%|{bar}| '
444
+ f'{step_i}/{total_steps} '
445
+ f'[{_rf_format_duration(elapsed)}<{_rf_format_duration(remaining)}, {rate_text}]'
446
+ )
447
+
448
+ end = '\n' if persistent or step_i >= total_steps else '\r'
449
+ print(line, end=end, flush=True)
450
+
451
+ def _normalize_sigma_float(value: Any) -> Optional[float]:
452
+ if torch.is_tensor(value):
453
+ v = float(value.detach().float().mean().item())
454
+ else:
455
+ v = float(value)
456
+ if not math.isfinite(v):
457
+ raise ValueError(f'Invalid sigma/timestep value {value!r}: not finite.')
458
+ if 0.0 <= v <= 1.0:
459
+ return max(0.0, min(1.0, v))
460
+ if 1.0 < v <= 1000.0:
461
+ return max(0.0, min(1.0, v / 1000.0))
462
+ raise ValueError(f'Invalid sigma/timestep value {value!r}; expected [0,1] sigma or [1,1000] timestep.')
463
+
464
+ def _coerce_sigma_sequence(value: Any) -> Optional[List[float]]:
465
+ """Convert a scheduler sigma/timestep list into normalized [0,1] floats.
466
+
467
+ Strict mode: malformed schedules raise instead of returning None. A missing
468
+ value still returns None so callers can distinguish "not provided" from
469
+ "provided but broken".
470
+ """
471
+ if value is None:
472
+ return None
473
+ if torch.is_tensor(value):
474
+ flat = value.detach().float().flatten().tolist()
475
+ elif isinstance(value, (list, tuple)):
476
+ flat = []
477
+ for item in value:
478
+ if torch.is_tensor(item):
479
+ flat.extend(item.detach().float().flatten().tolist())
480
+ elif isinstance(item, (int, float)):
481
+ flat.append(float(item))
482
+ else:
483
+ raise ValueError(f'Invalid sigma sequence item {item!r}; expected tensor/int/float.')
484
+ else:
485
+ raise ValueError(f'Invalid sigma sequence type {type(value).__name__}; expected tensor/list/tuple.')
486
+
487
+ out: List[float] = [_normalize_sigma_float(item) for item in flat]
488
+ if len(out) < 2:
489
+ raise ValueError(f'Invalid sigma sequence; expected at least 2 values, got {len(out)}.')
490
+ dedup: List[float] = []
491
+ for sigma in out:
492
+ if not dedup or abs(dedup[-1] - sigma) > 1e-6:
493
+ dedup.append(sigma)
494
+ if len(dedup) < 2:
495
+ raise ValueError(f'Invalid sigma sequence; deduplicated length is {len(dedup)}.')
496
+ return dedup
497
+
498
+ def _rf_print_sampler_capture(verbose_flag: Any, found: Any, run_count: Any) -> None:
499
+ if not _coerce_bool(verbose_flag):
500
+ return
501
+ print(
502
+ f'{_RF_PREFIX} RFInversion sampler_sample: captured {len(found)} sigmas '
503
+ f'run={run_count} seed=42'
504
+ )
505
+
506
+
507
+ def _rf_print_build_requested(
508
+ verbose_flag: Any,
509
+ sampler_sigmas: Any,
510
+ target_b: int,
511
+ rf_cond_mode: str,
512
+ cache_key: str,
513
+ rf_ref_clean: Any,
514
+ rf_kwargs: Any,
515
+ ) -> None:
516
+ if not _coerce_bool(verbose_flag):
517
+ return
518
+ print(f'{_RF_PREFIX} RF build requested from RFInversion wrapper')
519
+ print(f'{_RF_PREFIX} {_rf_sequence_summary("sampler_sigmas", sampler_sigmas)}')
520
+ print(f'{_RF_PREFIX} target_b={target_b} cond_mode={rf_cond_mode} cache_key={str(cache_key)[:12]}')
521
+ print(f'{_RF_PREFIX} rf_ref_clean: {_rf_tensor_summary("rf_ref_clean", rf_ref_clean)}')
522
+ print(f'{_RF_PREFIX} rf_kwargs summary: {_rf_brief_obj(rf_kwargs)}')
523
+
524
+
525
+ def _rf_print_persistent_cache_hit(verbose_flag: Any, cache_key: str, built_cache: Any) -> None:
526
+ if _coerce_bool(verbose_flag):
527
+ print(f'{_RF_PREFIX} RF persistent cache HIT key={str(cache_key)[:12]} cache_items={len(built_cache)}')
528
+
529
+
530
+ def _rf_print_persistent_cache_miss(verbose_flag: Any, cache_key: str) -> None:
531
+ if _coerce_bool(verbose_flag):
532
+ print(f'{_RF_PREFIX} RF persistent cache MISS key={str(cache_key)[:12]} → building now')
533
+
534
+
535
+ def _rf_print_build_complete(
536
+ verbose_flag: Any,
537
+ built_cache: Any,
538
+ sorted_sigmas: Any,
539
+ eps: Any,
540
+ rf_sanity: Dict[str, Any],
541
+ ) -> None:
542
+ if not _coerce_bool(verbose_flag):
543
+ return
544
+ print(
545
+ f'{_RF_PREFIX} RF build complete: cache_items={len(built_cache)} '
546
+ f'built_sigmas={len(sorted_sigmas)} eps={_rf_tensor_summary("eps", eps)}'
547
+ )
548
+ _rf_print_stability_summary(rf_sanity)
549
+
550
+
551
+ def _rf_print_direct_fallback(verbose_flag: Any, sigma: float) -> None:
552
+ raise RuntimeError(
553
+ f'{_RF_PREFIX} No sampler sigmas captured; direct one-step RF path is disabled for σ={float(sigma):.6f}'
554
+ )
555
+
556
+
557
+ def _rf_print_traceback(verbose_flag: Any, trace_text: str) -> None:
558
+ if _coerce_bool(verbose_flag) and trace_text:
559
+ print(trace_text)
560
+
561
+
562
+ def _rf_print_prepared(
563
+ verbose_flag: Any,
564
+ rf_mode: str,
565
+ gamma: float,
566
+ gamma_curve: float,
567
+ norm_strength: float,
568
+ pmi_alpha: float,
569
+ model_info: Dict[str, Any],
570
+ ) -> None:
571
+ if not _coerce_bool(verbose_flag):
572
+ return
573
+ print(f'\n{_RF_PREFIX} ═══════════════════════════════════════')
574
+ print(f'{_RF_PREFIX} RF INVERSION PREPARED')
575
+ print(f'{_RF_PREFIX} ═══════════════════════════════════════')
576
+ print(f'{_RF_PREFIX} mode : {rf_mode}')
577
+ print(f'{_RF_PREFIX} gamma : {float(gamma):.4f}')
578
+ print(f'{_RF_PREFIX} gamma_curve : {float(gamma_curve):.3f}')
579
+ print(f'{_RF_PREFIX} norm_strength : {float(norm_strength):.3f}')
580
+ print(f'{_RF_PREFIX} pmi_alpha : {float(pmi_alpha):.3f}')
581
+ print(f'{_RF_PREFIX} seed : 42 (internal fixed noise seed)')
582
+ print(f'{_RF_PREFIX} schedule : captured from sampler at runtime; no SIGMAS input')
583
+ print(f'{_RF_PREFIX} output : normal LATENT with RF metadata')
584
+ print(f'{_RF_PREFIX} wrapper : standalone RF cache builder installed on MODEL')
585
+ print(f'{_RF_PREFIX} diagnostics : verbose=True prints per-call/cache/conditioning details')
586
+ _rf_print_model_identity(f'{_RF_PREFIX} RFInversion', model_info)
587
+ print(f'{_RF_PREFIX} ═══════════════════════════════════════\n')
588
+
589
+
590
+
591
+ def _untwist_format_scale_value(value: Any) -> str:
592
+ """Format one scale value for compact debug logs without noisy trailing zeros."""
593
+ value_f = float(value)
594
+ if not math.isfinite(value_f):
595
+ raise ValueError(f'Invalid RoPE scale value {value!r}: not finite.')
596
+ text = f'{value_f:.6f}'.rstrip('0').rstrip('.')
597
+ return text if text else '0'
598
+
599
+
600
+ def _untwist_scale_range(values: Any) -> str:
601
+ """Return a compact [first ... last] summary from a 1D scale tensor/list."""
602
+ if torch.is_tensor(values):
603
+ if values.numel() <= 0:
604
+ raise ValueError('Cannot summarize empty RoPE scale tensor.')
605
+ flat = values.detach().float().flatten().to(device='cpu')
606
+ else:
607
+ flat = torch.as_tensor(values, dtype=torch.float32).flatten()
608
+ if flat.numel() <= 0:
609
+ raise ValueError('Cannot summarize empty RoPE scale values.')
610
+ first = _untwist_format_scale_value(float(flat[0].item()))
611
+ last = _untwist_format_scale_value(float(flat[-1].item()))
612
+ return f'[{first} ... {last}]'
613
+
614
+
615
+ _AXIS0_ROPE_MODES = {'default', 'match_axes', 'constant'}
616
+
617
+ def _untwist_coerce_axis0_rope_mode(value: Any = None, legacy_scale: Any = None) -> str:
618
+ """Mirror the main node's axis-0 RoPE mode normalization for debug output."""
619
+ if value is None:
620
+ if legacy_scale is not None:
621
+ legacy_f = float(legacy_scale)
622
+ return 'default' if legacy_f < 0.0 else 'constant'
623
+ return 'default'
624
+
625
+ mode = str(value or 'default').strip().lower().replace('-', '_').replace(' ', '_')
626
+ aliases = {
627
+ 'legacy': 'default',
628
+ 'low': 'default',
629
+ 'low_scale': 'default',
630
+ 'match_axis1': 'match_axes',
631
+ 'match_axis_1': 'match_axes',
632
+ 'match_axis_1_plus': 'match_axes',
633
+ 'match_axes_1plus': 'match_axes',
634
+ 'same_as_axes': 'match_axes',
635
+ 'same_as_axis1': 'match_axes',
636
+ 'override': 'constant',
637
+ 'fixed': 'constant',
638
+ }
639
+ mode = aliases.get(mode, mode)
640
+ if mode not in _AXIS0_ROPE_MODES:
641
+ raise ValueError(f'Invalid axis0_rope_mode={value!r}; expected one of {sorted(_AXIS0_ROPE_MODES)}.')
642
+ return mode
643
+
644
+ def _untwist_coerce_axis0_rope_scale(value: Any, default: float = 0.0) -> float:
645
+ """Debug-side formatting clamp: axis0_rope_scale is non-negative now."""
646
+ value_f = float(value)
647
+ if not math.isfinite(value_f):
648
+ raise ValueError(f'Invalid axis0_rope_scale={value!r}: not finite.')
649
+ if value_f < 0.0:
650
+ raise ValueError(f'Invalid axis0_rope_scale={value_f!r}; expected non-negative value.')
651
+ return value_f
652
+
653
+
654
+ def _untwist_print_rope_scale_debug(
655
+ stats: Optional[_RuntimeStats],
656
+ cfg: Dict[str, Any],
657
+ module_name: str,
658
+ scale_vec: Any,
659
+ ) -> None:
660
+ """Print one compact RoPE scale-vector snapshot per UntwistingRoPE model call."""
661
+ if not _coerce_bool(getattr(stats, 'verbose', False)):
662
+ return
663
+ if not isinstance(cfg, dict) or cfg.get('_rope_scale_debug_printed', False):
664
+ return
665
+ if not cfg.get('enabled', False) or int(cfg.get('cross_batch_target_batch', 0)) <= 0:
666
+ return
667
+
668
+ cfg['_rope_scale_debug_printed'] = True
669
+
670
+ try:
671
+ if not torch.is_tensor(scale_vec):
672
+ scale_vec = torch.as_tensor(scale_vec)
673
+ flat = scale_vec.detach().flatten()
674
+ head_dim = int(flat.numel())
675
+ axes_dims = [int(x) for x in (cfg.get('axes_dims') or [])]
676
+ if not axes_dims or sum(axes_dims) != head_dim:
677
+ axes_dims = [head_dim]
678
+
679
+ if len(axes_dims) >= 2:
680
+ axis0_dim = max(0, min(int(axes_dims[0]), head_dim))
681
+ axis0 = flat[:axis0_dim]
682
+ axis1_plus = flat[axis0_dim:]
683
+ else:
684
+ axis0 = flat
685
+ axis1_plus = flat.new_empty((0,))
686
+
687
+ progress = float(cfg.get('progress', 0.0))
688
+ sigma = float(cfg.get('sigma', 0.0))
689
+ low_scale = float(cfg.get('_debug_low_scale', 0.0))
690
+ high_scale = float(cfg.get('_debug_high_scale', 0.0))
691
+ axis0_rope_mode = _untwist_coerce_axis0_rope_mode(
692
+ cfg.get('axis0_rope_mode', None),
693
+ legacy_scale=cfg.get('axis0_rope_scale', None),
694
+ )
695
+ axis0_rope_scale = _untwist_coerce_axis0_rope_scale(
696
+ cfg.get('axis0_rope_scale', 0.0), default=0.0
697
+ )
698
+
699
+ print(f'{_PREFIX} progress={progress:.6f} sigma={sigma:.6f}')
700
+ print(f'{_PREFIX} low_scale={low_scale:.6f} high_scale={high_scale:.6f}')
701
+ print(f'{_PREFIX} axis0={_untwist_scale_range(axis0)}')
702
+ print(f'{_PREFIX} axis1+={_untwist_scale_range(axis1_plus)}')
703
+ except Exception as exc:
704
+ raise RuntimeError(f'{_PREFIX} RoPE scale debug print failed; strict mode refuses to hide debug failure: {exc}') from exc
705
+
706
+
707
+ def _untwist_print_rope_scale_debug_from_cfg(
708
+ stats: Optional[_RuntimeStats],
709
+ cfg: Dict[str, Any],
710
+ module_name: str,
711
+ device: Any,
712
+ dtype: Any,
713
+ build_frequency_scale_vector: Any,
714
+ ) -> None:
715
+ """Strict RoPE debug print for adapter attention paths.
716
+
717
+ The actual scale-vector builder stays in the main module and is passed in here
718
+ so verbose_prints owns the formatting/printing without creating import cycles.
719
+ """
720
+ if not isinstance(cfg, dict) or cfg.get('_rope_scale_debug_printed', False):
721
+ return
722
+ if not callable(build_frequency_scale_vector):
723
+ raise RuntimeError('RoPE scale debug requires callable build_frequency_scale_vector.')
724
+ try:
725
+ head_dim = int(cfg.get('head_dim', 0))
726
+ if head_dim <= 0:
727
+ raise RuntimeError(f'RoPE scale debug requires positive head_dim, got {head_dim}.')
728
+
729
+ progress = float(cfg.get('progress', 0.0))
730
+ high_start = float(cfg['high_scale_start'])
731
+ high_end = float(cfg['high_scale_end'])
732
+ low_start = float(cfg['low_scale_start'])
733
+ low_end = float(cfg['low_scale_end'])
734
+ high_scale = high_start + (high_end - high_start) * progress
735
+ low_scale = low_start + (low_end - low_start) * progress
736
+ beta = float(cfg.get('beta', 2.0))
737
+
738
+ cfg['_debug_high_scale'] = float(high_scale)
739
+ cfg['_debug_low_scale'] = float(low_scale)
740
+
741
+ scale_vec = build_frequency_scale_vector(
742
+ head_dim,
743
+ cfg.get('axes_dims') or [],
744
+ high_scale,
745
+ low_scale,
746
+ beta,
747
+ device,
748
+ dtype,
749
+ runtime_cfg=cfg,
750
+ )
751
+ _untwist_print_rope_scale_debug(stats, cfg, module_name, scale_vec)
752
+ except Exception as exc:
753
+ raise RuntimeError(f'{_PREFIX} RoPE scale debug failed; strict mode refuses to hide failure: {exc}') from exc
754
+
755
+ def _untwist_print_patch_complete(stats: Optional[_RuntimeStats], rf_active: bool, adapter: Any) -> None:
756
+ _vprint(stats, f'\n{_PREFIX} ═══════════════════════════════════════')
757
+ _vprint(stats, f'{_PREFIX} PATCH COMPLETE')
758
+ if rf_active:
759
+ _vprint(stats, f'{_PREFIX} RF input : LATENT from RFInversion')
760
+ _vprint(stats, f'{_PREFIX} RF schedule : captured internally by RFInversion model wrapper')
761
+ _vprint(stats, f'{_PREFIX} RF preview : emitted while building inversion trajectory')
762
+ uses_kv = getattr(adapter, 'uses_reference_branch_kv', lambda: False)
763
+ if bool(uses_kv()):
764
+ _vprint(stats, f'{_PREFIX} K/V : reference branch contributes K and V; only K is untwisted')
765
+ else:
766
+ _vprint(stats, f'{_PREFIX} RF input : not connected')
767
+ _vprint(stats, f'{_PREFIX} Mode : target-only attention patch')
768
+ _vprint(stats, f'{_PREFIX} Output: target prediction returned unchanged')
769
+ _vprint(stats, f'{_PREFIX} ═══════════════════════════════════════\n')
770
+
771
+ __all__ = [
772
+ '_PREFIX',
773
+ '_RF_PREFIX',
774
+ '_rf_prefix',
775
+ '_coerce_bool',
776
+ '_RuntimeStats',
777
+ '_vprint',
778
+ '_rf_vprint',
779
+ '_rf_tensor_summary',
780
+ '_rf_sequence_summary',
781
+ '_rf_brief_obj',
782
+ '_rf_tensor_stats',
783
+ '_rf_scalar_fmt',
784
+ '_rf_tensor_mae',
785
+ '_rf_tensor_rmse',
786
+ '_rf_tensor_cosine',
787
+ '_rf_diagnostic_level',
788
+ '_rf_stability_summary',
789
+ '_rf_print_stability_summary',
790
+ '_rf_model_identity',
791
+ '_rf_print_model_identity',
792
+ '_rf_step_iterator',
793
+ '_rf_format_duration',
794
+ '_rf_progress_snapshot',
795
+ '_normalize_sigma_float',
796
+ '_coerce_sigma_sequence',
797
+ '_rf_print_sampler_capture',
798
+ '_rf_print_build_requested',
799
+ '_rf_print_persistent_cache_hit',
800
+ '_rf_print_persistent_cache_miss',
801
+ '_rf_print_build_complete',
802
+ '_rf_print_direct_fallback',
803
+ '_rf_print_traceback',
804
+ '_rf_print_prepared',
805
+ '_untwist_format_scale_value',
806
+ '_untwist_scale_range',
807
+ '_untwist_coerce_axis0_rope_mode',
808
+ '_untwist_coerce_axis0_rope_scale',
809
+ '_untwist_print_rope_scale_debug',
810
+ '_untwist_print_rope_scale_debug_from_cfg',
811
+ '_untwist_print_patch_complete',
812
+ ]
custom_nodes/ComfyUi-Untwisting-RoPE/workflows/workflow_anima.json ADDED
@@ -0,0 +1,1290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "44259803-f9d6-4eb1-a94a-75b8213649d0",
3
+ "revision": 0,
4
+ "last_node_id": 635,
5
+ "last_link_id": 1561,
6
+ "nodes": [
7
+ {
8
+ "id": 333,
9
+ "type": "VAEEncode",
10
+ "pos": [
11
+ 612.9416976790988,
12
+ 1242.853274396352
13
+ ],
14
+ "size": [
15
+ 140,
16
+ 46
17
+ ],
18
+ "flags": {},
19
+ "order": 17,
20
+ "mode": 0,
21
+ "inputs": [
22
+ {
23
+ "name": "pixels",
24
+ "type": "IMAGE",
25
+ "link": 749
26
+ },
27
+ {
28
+ "name": "vae",
29
+ "type": "VAE",
30
+ "link": 1550
31
+ }
32
+ ],
33
+ "outputs": [
34
+ {
35
+ "name": "LATENT",
36
+ "type": "LATENT",
37
+ "links": [
38
+ 1526
39
+ ]
40
+ }
41
+ ],
42
+ "properties": {
43
+ "cnr_id": "comfy-core",
44
+ "ver": "0.21.0",
45
+ "Node name for S&R": "VAEEncode"
46
+ },
47
+ "widgets_values": []
48
+ },
49
+ {
50
+ "id": 619,
51
+ "type": "Note",
52
+ "pos": [
53
+ 261.6234944497743,
54
+ 980.8806213289101
55
+ ],
56
+ "size": [
57
+ 289.0740052806825,
58
+ 112.57343506692268
59
+ ],
60
+ "flags": {},
61
+ "order": 0,
62
+ "mode": 0,
63
+ "inputs": [],
64
+ "outputs": [],
65
+ "properties": {},
66
+ "widgets_values": [
67
+ "https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced"
68
+ ],
69
+ "color": "#c09430",
70
+ "bgcolor": "rgba(24,24,27,.9)"
71
+ },
72
+ {
73
+ "id": 614,
74
+ "type": "Note",
75
+ "pos": [
76
+ 938.3272357908905,
77
+ 1489.0086428159627
78
+ ],
79
+ "size": [
80
+ 303.65604311050856,
81
+ 116.00450279158758
82
+ ],
83
+ "flags": {},
84
+ "order": 1,
85
+ "mode": 0,
86
+ "inputs": [],
87
+ "outputs": [],
88
+ "properties": {},
89
+ "widgets_values": [
90
+ "You can create two CLIP Text Encode (one for the reference and one for the target), but personally, I find that using the target prompt for both yields better results."
91
+ ],
92
+ "color": "#c09430",
93
+ "bgcolor": "rgba(24,24,27,.9)"
94
+ },
95
+ {
96
+ "id": 622,
97
+ "type": "SamplerCustomAdvanced",
98
+ "pos": [
99
+ 1847.301918707523,
100
+ 1554.3864451535942
101
+ ],
102
+ "size": [
103
+ 293.89992513107234,
104
+ 456.72464032296625
105
+ ],
106
+ "flags": {},
107
+ "order": 23,
108
+ "mode": 0,
109
+ "inputs": [
110
+ {
111
+ "name": "noise",
112
+ "type": "NOISE",
113
+ "link": 1543
114
+ },
115
+ {
116
+ "name": "guider",
117
+ "type": "GUIDER",
118
+ "link": 1544
119
+ },
120
+ {
121
+ "name": "sampler",
122
+ "type": "SAMPLER",
123
+ "link": 1545
124
+ },
125
+ {
126
+ "name": "sigmas",
127
+ "type": "SIGMAS",
128
+ "link": 1546
129
+ },
130
+ {
131
+ "name": "latent_image",
132
+ "type": "LATENT",
133
+ "link": 1547
134
+ }
135
+ ],
136
+ "outputs": [
137
+ {
138
+ "name": "output",
139
+ "type": "LATENT",
140
+ "links": [
141
+ 1548
142
+ ]
143
+ },
144
+ {
145
+ "name": "denoised_output",
146
+ "type": "LATENT",
147
+ "links": null
148
+ }
149
+ ],
150
+ "properties": {
151
+ "cnr_id": "comfy-core",
152
+ "ver": "0.21.1",
153
+ "Node name for S&R": "SamplerCustomAdvanced"
154
+ },
155
+ "widgets_values": []
156
+ },
157
+ {
158
+ "id": 617,
159
+ "type": "PreviewImage",
160
+ "pos": [
161
+ 2439.855735728809,
162
+ 1482.3290866342313
163
+ ],
164
+ "size": [
165
+ 554.574171917292,
166
+ 515.9512940840721
167
+ ],
168
+ "flags": {},
169
+ "order": 25,
170
+ "mode": 0,
171
+ "inputs": [
172
+ {
173
+ "name": "images",
174
+ "type": "IMAGE",
175
+ "link": 1540
176
+ }
177
+ ],
178
+ "outputs": [],
179
+ "properties": {
180
+ "cnr_id": "comfy-core",
181
+ "ver": "0.21.1",
182
+ "Node name for S&R": "PreviewImage"
183
+ },
184
+ "widgets_values": []
185
+ },
186
+ {
187
+ "id": 262,
188
+ "type": "VAEDecode",
189
+ "pos": [
190
+ 2196.558250513236,
191
+ 1538.8662956572043
192
+ ],
193
+ "size": [
194
+ 140,
195
+ 62.2083101328426
196
+ ],
197
+ "flags": {},
198
+ "order": 24,
199
+ "mode": 0,
200
+ "inputs": [
201
+ {
202
+ "name": "samples",
203
+ "type": "LATENT",
204
+ "link": 1548
205
+ },
206
+ {
207
+ "name": "vae",
208
+ "type": "VAE",
209
+ "link": 1551
210
+ }
211
+ ],
212
+ "outputs": [
213
+ {
214
+ "name": "IMAGE",
215
+ "type": "IMAGE",
216
+ "links": [
217
+ 1540
218
+ ]
219
+ }
220
+ ],
221
+ "properties": {
222
+ "cnr_id": "comfy-core",
223
+ "ver": "0.21.0",
224
+ "Node name for S&R": "VAEDecode"
225
+ },
226
+ "widgets_values": []
227
+ },
228
+ {
229
+ "id": 615,
230
+ "type": "Note",
231
+ "pos": [
232
+ 806.2680068432485,
233
+ 995.1907751912114
234
+ ],
235
+ "size": [
236
+ 289.0740052806825,
237
+ 112.57343506692268
238
+ ],
239
+ "flags": {},
240
+ "order": 2,
241
+ "mode": 0,
242
+ "inputs": [],
243
+ "outputs": [],
244
+ "properties": {},
245
+ "widgets_values": [
246
+ "The quality of the style transfer depends largely on the quality of the RF inversion. These settings work well, but feel free to try other values."
247
+ ],
248
+ "color": "#c09430",
249
+ "bgcolor": "rgba(24,24,27,.9)"
250
+ },
251
+ {
252
+ "id": 265,
253
+ "type": "ImageScaleToTotalPixelsX",
254
+ "pos": [
255
+ 246.99230874069832,
256
+ 1164.5446997368606
257
+ ],
258
+ "size": [
259
+ 306.5982421875,
260
+ 220.0000000000001
261
+ ],
262
+ "flags": {},
263
+ "order": 16,
264
+ "mode": 0,
265
+ "inputs": [
266
+ {
267
+ "name": "image",
268
+ "type": "IMAGE",
269
+ "link": 1560
270
+ },
271
+ {
272
+ "name": "width",
273
+ "shape": 7,
274
+ "type": "INT",
275
+ "link": null
276
+ },
277
+ {
278
+ "name": "height",
279
+ "shape": 7,
280
+ "type": "INT",
281
+ "link": null
282
+ }
283
+ ],
284
+ "outputs": [
285
+ {
286
+ "name": "image",
287
+ "type": "IMAGE",
288
+ "links": [
289
+ 749
290
+ ]
291
+ },
292
+ {
293
+ "name": "width",
294
+ "type": "INT",
295
+ "links": [
296
+ 566
297
+ ]
298
+ },
299
+ {
300
+ "name": "height",
301
+ "type": "INT",
302
+ "links": [
303
+ 567
304
+ ]
305
+ }
306
+ ],
307
+ "properties": {
308
+ "cnr_id": "scale-image-to-total-pixels-advanced",
309
+ "ver": "dd4135f4ee6dcd71443e2935ceb5c037e3f23230",
310
+ "Node name for S&R": "ImageScaleToTotalPixelsX"
311
+ },
312
+ "widgets_values": [
313
+ 1.05,
314
+ 16,
315
+ "crop",
316
+ "lanczos"
317
+ ]
318
+ },
319
+ {
320
+ "id": 603,
321
+ "type": "RFInversion",
322
+ "pos": [
323
+ 812.2907721832939,
324
+ 1175.3247940381746
325
+ ],
326
+ "size": [
327
+ 273.3614812972471,
328
+ 240.5904011287812
329
+ ],
330
+ "flags": {},
331
+ "order": 19,
332
+ "mode": 0,
333
+ "inputs": [
334
+ {
335
+ "name": "model",
336
+ "type": "MODEL",
337
+ "link": 1549
338
+ },
339
+ {
340
+ "name": "reference_latent",
341
+ "type": "LATENT",
342
+ "link": 1526
343
+ },
344
+ {
345
+ "name": "ref_conditioning",
346
+ "shape": 7,
347
+ "type": "CONDITIONING",
348
+ "link": 1535
349
+ }
350
+ ],
351
+ "outputs": [
352
+ {
353
+ "name": "model",
354
+ "type": "MODEL",
355
+ "links": [
356
+ 1554
357
+ ]
358
+ },
359
+ {
360
+ "name": "rf_inversion",
361
+ "type": "LATENT",
362
+ "links": [
363
+ 1555
364
+ ]
365
+ }
366
+ ],
367
+ "properties": {
368
+ "cnr_id": "untwistingrope",
369
+ "ver": "c9136fcced444ea84778a25a37a2b45371ea06a5",
370
+ "Node name for S&R": "RFInversion"
371
+ },
372
+ "widgets_values": [
373
+ "rf_gamma_rk2",
374
+ 0.5,
375
+ 2,
376
+ 1,
377
+ 0.5,
378
+ false
379
+ ]
380
+ },
381
+ {
382
+ "id": 624,
383
+ "type": "VAELoader",
384
+ "pos": [
385
+ 343.5487552133242,
386
+ 1455.5114014578749
387
+ ],
388
+ "size": [
389
+ 307.59114583333337,
390
+ 88.88020833333334
391
+ ],
392
+ "flags": {},
393
+ "order": 3,
394
+ "mode": 0,
395
+ "inputs": [],
396
+ "outputs": [
397
+ {
398
+ "name": "VAE",
399
+ "type": "VAE",
400
+ "links": [
401
+ 1550,
402
+ 1551
403
+ ]
404
+ }
405
+ ],
406
+ "properties": {
407
+ "cnr_id": "comfy-core",
408
+ "ver": "0.3.40",
409
+ "Node name for S&R": "VAELoader",
410
+ "enableTabs": false,
411
+ "tabWidth": 65,
412
+ "tabXOffset": 10,
413
+ "hasSecondTab": false,
414
+ "secondTabText": "Send Back",
415
+ "secondTabOffset": 80,
416
+ "secondTabWidth": 65,
417
+ "models": [
418
+ {
419
+ "name": "qwen_image_vae.safetensors",
420
+ "url": "https://huggingface.co/circlestone-labs/Anima/resolve/main/split_files/vae/qwen_image_vae.safetensors",
421
+ "directory": "vae"
422
+ }
423
+ ]
424
+ },
425
+ "widgets_values": [
426
+ "Qwen2D_VAE.safetensors"
427
+ ]
428
+ },
429
+ {
430
+ "id": 623,
431
+ "type": "UNETLoader",
432
+ "pos": [
433
+ 333.6339242269637,
434
+ 1611.902839934744
435
+ ],
436
+ "size": [
437
+ 307.59114583333337,
438
+ 117.76041666666667
439
+ ],
440
+ "flags": {},
441
+ "order": 4,
442
+ "mode": 0,
443
+ "inputs": [],
444
+ "outputs": [
445
+ {
446
+ "name": "MODEL",
447
+ "type": "MODEL",
448
+ "links": [
449
+ 1549
450
+ ]
451
+ }
452
+ ],
453
+ "properties": {
454
+ "cnr_id": "comfy-core",
455
+ "ver": "0.11.0",
456
+ "Node name for S&R": "UNETLoader",
457
+ "enableTabs": false,
458
+ "tabWidth": 65,
459
+ "tabXOffset": 10,
460
+ "hasSecondTab": false,
461
+ "secondTabText": "Send Back",
462
+ "secondTabOffset": 80,
463
+ "secondTabWidth": 65,
464
+ "models": [
465
+ {
466
+ "name": "anima-preview2.safetensors",
467
+ "url": "https://huggingface.co/circlestone-labs/Anima/resolve/main/split_files/diffusion_models/anima-preview2.safetensors",
468
+ "directory": "diffusion_models"
469
+ }
470
+ ]
471
+ },
472
+ "widgets_values": [
473
+ "Anima\\anima_baseV10.safetensors",
474
+ "default"
475
+ ]
476
+ },
477
+ {
478
+ "id": 625,
479
+ "type": "CLIPLoader",
480
+ "pos": [
481
+ 479.6000939299869,
482
+ 1819.195312232384
483
+ ],
484
+ "size": [
485
+ 270,
486
+ 106
487
+ ],
488
+ "flags": {},
489
+ "order": 5,
490
+ "mode": 0,
491
+ "inputs": [],
492
+ "outputs": [
493
+ {
494
+ "name": "CLIP",
495
+ "type": "CLIP",
496
+ "links": [
497
+ 1552,
498
+ 1553
499
+ ]
500
+ }
501
+ ],
502
+ "properties": {
503
+ "cnr_id": "comfy-core",
504
+ "ver": "0.19.5",
505
+ "Node name for S&R": "CLIPLoader"
506
+ },
507
+ "widgets_values": [
508
+ "qwen_3_06b_base.safetensors",
509
+ "stable_diffusion",
510
+ "default"
511
+ ]
512
+ },
513
+ {
514
+ "id": 259,
515
+ "type": "CLIPTextEncode",
516
+ "pos": [
517
+ 884.8078958977934,
518
+ 1934.8940610315733
519
+ ],
520
+ "size": [
521
+ 400,
522
+ 200
523
+ ],
524
+ "flags": {},
525
+ "order": 15,
526
+ "mode": 0,
527
+ "inputs": [
528
+ {
529
+ "name": "clip",
530
+ "type": "CLIP",
531
+ "link": 1553
532
+ }
533
+ ],
534
+ "outputs": [
535
+ {
536
+ "name": "CONDITIONING",
537
+ "type": "CONDITIONING",
538
+ "links": [
539
+ 1400
540
+ ]
541
+ }
542
+ ],
543
+ "properties": {
544
+ "cnr_id": "comfy-core",
545
+ "ver": "0.21.0",
546
+ "Node name for S&R": "CLIPTextEncode"
547
+ },
548
+ "widgets_values": [
549
+ ""
550
+ ]
551
+ },
552
+ {
553
+ "id": 607,
554
+ "type": "CLIPTextEncode",
555
+ "pos": [
556
+ 887.9401977810033,
557
+ 1654.9431345297862
558
+ ],
559
+ "size": [
560
+ 400,
561
+ 200
562
+ ],
563
+ "flags": {},
564
+ "order": 14,
565
+ "mode": 0,
566
+ "inputs": [
567
+ {
568
+ "name": "clip",
569
+ "type": "CLIP",
570
+ "link": 1552
571
+ }
572
+ ],
573
+ "outputs": [
574
+ {
575
+ "name": "CONDITIONING",
576
+ "type": "CONDITIONING",
577
+ "links": [
578
+ 1534,
579
+ 1535
580
+ ]
581
+ }
582
+ ],
583
+ "properties": {
584
+ "cnr_id": "comfy-core",
585
+ "ver": "0.21.0",
586
+ "Node name for S&R": "CLIPTextEncode"
587
+ },
588
+ "widgets_values": [
589
+ "a woman with blonde hair and blue eyes plays piano. "
590
+ ]
591
+ },
592
+ {
593
+ "id": 167,
594
+ "type": "RandomNoise",
595
+ "pos": [
596
+ 1453.8112402046313,
597
+ 1759.8929403547274
598
+ ],
599
+ "size": [
600
+ 302.7450866699219,
601
+ 82
602
+ ],
603
+ "flags": {},
604
+ "order": 6,
605
+ "mode": 0,
606
+ "inputs": [],
607
+ "outputs": [
608
+ {
609
+ "name": "NOISE",
610
+ "type": "NOISE",
611
+ "links": [
612
+ 1543
613
+ ]
614
+ }
615
+ ],
616
+ "properties": {
617
+ "cnr_id": "comfy-core",
618
+ "ver": "0.3.76",
619
+ "Node name for S&R": "RandomNoise"
620
+ },
621
+ "widgets_values": [
622
+ 42,
623
+ "fixed"
624
+ ]
625
+ },
626
+ {
627
+ "id": 282,
628
+ "type": "EmptySD3LatentImage",
629
+ "pos": [
630
+ 1466.2563372831864,
631
+ 2087.849767719435
632
+ ],
633
+ "size": [
634
+ 260,
635
+ 168
636
+ ],
637
+ "flags": {},
638
+ "order": 18,
639
+ "mode": 0,
640
+ "inputs": [
641
+ {
642
+ "name": "width",
643
+ "type": "INT",
644
+ "widget": {
645
+ "name": "width"
646
+ },
647
+ "link": 566
648
+ },
649
+ {
650
+ "name": "height",
651
+ "type": "INT",
652
+ "widget": {
653
+ "name": "height"
654
+ },
655
+ "link": 567
656
+ }
657
+ ],
658
+ "outputs": [
659
+ {
660
+ "name": "LATENT",
661
+ "type": "LATENT",
662
+ "slot_index": 0,
663
+ "links": [
664
+ 1547
665
+ ]
666
+ }
667
+ ],
668
+ "properties": {
669
+ "cnr_id": "comfy-core",
670
+ "ver": "0.3.64",
671
+ "Node name for S&R": "EmptySD3LatentImage",
672
+ "enableTabs": false,
673
+ "tabWidth": 65,
674
+ "tabXOffset": 10,
675
+ "hasSecondTab": false,
676
+ "secondTabText": "Send Back",
677
+ "secondTabOffset": 80,
678
+ "secondTabWidth": 65
679
+ },
680
+ "widgets_values": [
681
+ 1024,
682
+ 1024,
683
+ 1
684
+ ]
685
+ },
686
+ {
687
+ "id": 229,
688
+ "type": "KSamplerSelect",
689
+ "pos": [
690
+ 1456.4620283066233,
691
+ 1616.1519503142572
692
+ ],
693
+ "size": [
694
+ 315,
695
+ 58
696
+ ],
697
+ "flags": {},
698
+ "order": 7,
699
+ "mode": 0,
700
+ "inputs": [],
701
+ "outputs": [
702
+ {
703
+ "name": "SAMPLER",
704
+ "type": "SAMPLER",
705
+ "links": [
706
+ 1545
707
+ ]
708
+ }
709
+ ],
710
+ "properties": {
711
+ "cnr_id": "comfy-core",
712
+ "ver": "0.5.0",
713
+ "Node name for S&R": "KSamplerSelect"
714
+ },
715
+ "widgets_values": [
716
+ "euler_ancestral"
717
+ ]
718
+ },
719
+ {
720
+ "id": 632,
721
+ "type": "LoadImage",
722
+ "pos": [
723
+ -151.78054847035042,
724
+ 1170.4638609274066
725
+ ],
726
+ "size": [
727
+ 282.798828125,
728
+ 314.00000000000006
729
+ ],
730
+ "flags": {},
731
+ "order": 8,
732
+ "mode": 0,
733
+ "inputs": [],
734
+ "outputs": [
735
+ {
736
+ "name": "IMAGE",
737
+ "type": "IMAGE",
738
+ "links": [
739
+ 1560
740
+ ]
741
+ },
742
+ {
743
+ "name": "MASK",
744
+ "type": "MASK",
745
+ "links": null
746
+ }
747
+ ],
748
+ "properties": {
749
+ "cnr_id": "comfy-core",
750
+ "ver": "0.21.1",
751
+ "Node name for S&R": "LoadImage"
752
+ },
753
+ "widgets_values": [
754
+ "pasted_image_20260523_071531.png",
755
+ "image"
756
+ ]
757
+ },
758
+ {
759
+ "id": 559,
760
+ "type": "CFGGuider",
761
+ "pos": [
762
+ 1488.7568419576453,
763
+ 1274.0013593262165
764
+ ],
765
+ "size": [
766
+ 270,
767
+ 98
768
+ ],
769
+ "flags": {},
770
+ "order": 21,
771
+ "mode": 0,
772
+ "inputs": [
773
+ {
774
+ "name": "model",
775
+ "type": "MODEL",
776
+ "link": 1556
777
+ },
778
+ {
779
+ "name": "positive",
780
+ "type": "CONDITIONING",
781
+ "link": 1534
782
+ },
783
+ {
784
+ "name": "negative",
785
+ "type": "CONDITIONING",
786
+ "link": 1400
787
+ }
788
+ ],
789
+ "outputs": [
790
+ {
791
+ "name": "GUIDER",
792
+ "type": "GUIDER",
793
+ "links": [
794
+ 1544
795
+ ]
796
+ }
797
+ ],
798
+ "properties": {
799
+ "cnr_id": "comfy-core",
800
+ "ver": "0.21.1",
801
+ "Node name for S&R": "CFGGuider"
802
+ },
803
+ "widgets_values": [
804
+ 3.5
805
+ ]
806
+ },
807
+ {
808
+ "id": 633,
809
+ "type": "Note",
810
+ "pos": [
811
+ 1461.3244363397027,
812
+ 1438.0275721087457
813
+ ],
814
+ "size": [
815
+ 303.65604311050856,
816
+ 116.00450279158758
817
+ ],
818
+ "flags": {},
819
+ "order": 9,
820
+ "mode": 0,
821
+ "inputs": [],
822
+ "outputs": [],
823
+ "properties": {},
824
+ "widgets_values": [
825
+ "I strongly recommend using only ancestral samplers, adding noise during the process really helps eliminate some transfer style artifacts."
826
+ ],
827
+ "color": "#c09430",
828
+ "bgcolor": "rgba(24,24,27,.9)"
829
+ },
830
+ {
831
+ "id": 628,
832
+ "type": "UntwistingRoPE",
833
+ "pos": [
834
+ 1140.890297847114,
835
+ 1138.3888731422762
836
+ ],
837
+ "size": [
838
+ 270,
839
+ 270
840
+ ],
841
+ "flags": {},
842
+ "order": 20,
843
+ "mode": 0,
844
+ "inputs": [
845
+ {
846
+ "name": "model",
847
+ "type": "MODEL",
848
+ "link": 1554
849
+ },
850
+ {
851
+ "name": "rf_inversion",
852
+ "shape": 7,
853
+ "type": "LATENT",
854
+ "link": 1555
855
+ },
856
+ {
857
+ "name": "unofficial_extensions",
858
+ "shape": 7,
859
+ "type": "UNTWISTING_ROPE_EXTENSIONS",
860
+ "link": 1561
861
+ }
862
+ ],
863
+ "outputs": [
864
+ {
865
+ "name": "model",
866
+ "type": "MODEL",
867
+ "links": [
868
+ 1556,
869
+ 1557
870
+ ]
871
+ }
872
+ ],
873
+ "properties": {
874
+ "cnr_id": "untwistingrope",
875
+ "ver": "9fb6a19e82077dc54ddb120f202d474d01497cf7",
876
+ "Node name for S&R": "UntwistingRoPE"
877
+ },
878
+ "widgets_values": [
879
+ 25,
880
+ 0,
881
+ 0.5,
882
+ 0.9,
883
+ 1.5,
884
+ 0.5,
885
+ "0-999",
886
+ true
887
+ ]
888
+ },
889
+ {
890
+ "id": 31,
891
+ "type": "BasicScheduler",
892
+ "pos": [
893
+ 1452.58439981301,
894
+ 1915.0486390017527
895
+ ],
896
+ "size": [
897
+ 270,
898
+ 106
899
+ ],
900
+ "flags": {},
901
+ "order": 22,
902
+ "mode": 0,
903
+ "inputs": [
904
+ {
905
+ "name": "model",
906
+ "type": "MODEL",
907
+ "link": 1557
908
+ }
909
+ ],
910
+ "outputs": [
911
+ {
912
+ "name": "SIGMAS",
913
+ "type": "SIGMAS",
914
+ "links": [
915
+ 1546
916
+ ]
917
+ }
918
+ ],
919
+ "properties": {
920
+ "cnr_id": "comfy-core",
921
+ "ver": "0.3.75",
922
+ "Node name for S&R": "BasicScheduler"
923
+ },
924
+ "widgets_values": [
925
+ "simple",
926
+ 35,
927
+ 1
928
+ ]
929
+ },
930
+ {
931
+ "id": 630,
932
+ "type": "UntwistingRoPE",
933
+ "pos": [
934
+ 1734.581064872837,
935
+ 907.5607111277825
936
+ ],
937
+ "size": [
938
+ 350.3369627518091,
939
+ 270
940
+ ],
941
+ "flags": {},
942
+ "order": 10,
943
+ "mode": 0,
944
+ "inputs": [
945
+ {
946
+ "name": "model",
947
+ "type": "MODEL",
948
+ "link": null
949
+ },
950
+ {
951
+ "name": "rf_inversion",
952
+ "shape": 7,
953
+ "type": "LATENT",
954
+ "link": null
955
+ },
956
+ {
957
+ "name": "unofficial_extensions",
958
+ "shape": 7,
959
+ "type": "UNTWISTING_ROPE_EXTENSIONS",
960
+ "link": null
961
+ }
962
+ ],
963
+ "outputs": [
964
+ {
965
+ "name": "model",
966
+ "type": "MODEL",
967
+ "links": null
968
+ }
969
+ ],
970
+ "title": "Untwisting RoPE (Settings for Anima Turbo)",
971
+ "properties": {
972
+ "cnr_id": "untwistingrope",
973
+ "ver": "9fb6a19e82077dc54ddb120f202d474d01497cf7",
974
+ "Node name for S&R": "UntwistingRoPE"
975
+ },
976
+ "widgets_values": [
977
+ 50,
978
+ 1,
979
+ 0,
980
+ 1,
981
+ 1.5,
982
+ 0.5,
983
+ "0-999",
984
+ true
985
+ ]
986
+ },
987
+ {
988
+ "id": 635,
989
+ "type": "Note",
990
+ "pos": [
991
+ 753.1231290811004,
992
+ 573.9575664535129
993
+ ],
994
+ "size": [
995
+ 285.24835336919455,
996
+ 126.58960944919556
997
+ ],
998
+ "flags": {},
999
+ "order": 11,
1000
+ "mode": 0,
1001
+ "inputs": [],
1002
+ "outputs": [],
1003
+ "properties": {},
1004
+ "widgets_values": [
1005
+ "Some additional methods not included in the paper, intended to further improve the results. These can be bypassed/removed."
1006
+ ],
1007
+ "color": "#c09430",
1008
+ "bgcolor": "rgba(24,24,27,.9)"
1009
+ },
1010
+ {
1011
+ "id": 611,
1012
+ "type": "Note",
1013
+ "pos": [
1014
+ 1135.9170901232549,
1015
+ 950.1203098736455
1016
+ ],
1017
+ "size": [
1018
+ 285.24835336919455,
1019
+ 126.58960944919556
1020
+ ],
1021
+ "flags": {},
1022
+ "order": 12,
1023
+ "mode": 0,
1024
+ "inputs": [],
1025
+ "outputs": [],
1026
+ "properties": {},
1027
+ "widgets_values": [
1028
+ "The only relevant values to change are :\n\n- high_scale: \n- low_scale_end: (between 1.0 and 1.5)"
1029
+ ],
1030
+ "color": "#c09430",
1031
+ "bgcolor": "rgba(24,24,27,.9)"
1032
+ },
1033
+ {
1034
+ "id": 634,
1035
+ "type": "UnofficialExtensions",
1036
+ "pos": [
1037
+ 736.8516248256913,
1038
+ 767.4503476211383
1039
+ ],
1040
+ "size": [
1041
+ 332.76171875,
1042
+ 130
1043
+ ],
1044
+ "flags": {},
1045
+ "order": 13,
1046
+ "mode": 0,
1047
+ "inputs": [],
1048
+ "outputs": [
1049
+ {
1050
+ "name": "unofficial_extensions",
1051
+ "type": "UNTWISTING_ROPE_EXTENSIONS",
1052
+ "links": [
1053
+ 1561
1054
+ ]
1055
+ }
1056
+ ],
1057
+ "properties": {
1058
+ "cnr_id": "untwistingrope",
1059
+ "ver": "ec08050c160633dc890972120598e2912ce26870",
1060
+ "Node name for S&R": "UnofficialExtensions"
1061
+ },
1062
+ "widgets_values": [
1063
+ false,
1064
+ 0.5,
1065
+ "match_axes",
1066
+ 1
1067
+ ]
1068
+ }
1069
+ ],
1070
+ "links": [
1071
+ [
1072
+ 566,
1073
+ 265,
1074
+ 1,
1075
+ 282,
1076
+ 0,
1077
+ "INT"
1078
+ ],
1079
+ [
1080
+ 567,
1081
+ 265,
1082
+ 2,
1083
+ 282,
1084
+ 1,
1085
+ "INT"
1086
+ ],
1087
+ [
1088
+ 749,
1089
+ 265,
1090
+ 0,
1091
+ 333,
1092
+ 0,
1093
+ "IMAGE"
1094
+ ],
1095
+ [
1096
+ 1400,
1097
+ 259,
1098
+ 0,
1099
+ 559,
1100
+ 2,
1101
+ "CONDITIONING"
1102
+ ],
1103
+ [
1104
+ 1526,
1105
+ 333,
1106
+ 0,
1107
+ 603,
1108
+ 1,
1109
+ "LATENT"
1110
+ ],
1111
+ [
1112
+ 1534,
1113
+ 607,
1114
+ 0,
1115
+ 559,
1116
+ 1,
1117
+ "CONDITIONING"
1118
+ ],
1119
+ [
1120
+ 1535,
1121
+ 607,
1122
+ 0,
1123
+ 603,
1124
+ 2,
1125
+ "CONDITIONING"
1126
+ ],
1127
+ [
1128
+ 1540,
1129
+ 262,
1130
+ 0,
1131
+ 617,
1132
+ 0,
1133
+ "IMAGE"
1134
+ ],
1135
+ [
1136
+ 1543,
1137
+ 167,
1138
+ 0,
1139
+ 622,
1140
+ 0,
1141
+ "NOISE"
1142
+ ],
1143
+ [
1144
+ 1544,
1145
+ 559,
1146
+ 0,
1147
+ 622,
1148
+ 1,
1149
+ "GUIDER"
1150
+ ],
1151
+ [
1152
+ 1545,
1153
+ 229,
1154
+ 0,
1155
+ 622,
1156
+ 2,
1157
+ "SAMPLER"
1158
+ ],
1159
+ [
1160
+ 1546,
1161
+ 31,
1162
+ 0,
1163
+ 622,
1164
+ 3,
1165
+ "SIGMAS"
1166
+ ],
1167
+ [
1168
+ 1547,
1169
+ 282,
1170
+ 0,
1171
+ 622,
1172
+ 4,
1173
+ "LATENT"
1174
+ ],
1175
+ [
1176
+ 1548,
1177
+ 622,
1178
+ 0,
1179
+ 262,
1180
+ 0,
1181
+ "LATENT"
1182
+ ],
1183
+ [
1184
+ 1549,
1185
+ 623,
1186
+ 0,
1187
+ 603,
1188
+ 0,
1189
+ "MODEL"
1190
+ ],
1191
+ [
1192
+ 1550,
1193
+ 624,
1194
+ 0,
1195
+ 333,
1196
+ 1,
1197
+ "VAE"
1198
+ ],
1199
+ [
1200
+ 1551,
1201
+ 624,
1202
+ 0,
1203
+ 262,
1204
+ 1,
1205
+ "VAE"
1206
+ ],
1207
+ [
1208
+ 1552,
1209
+ 625,
1210
+ 0,
1211
+ 607,
1212
+ 0,
1213
+ "CLIP"
1214
+ ],
1215
+ [
1216
+ 1553,
1217
+ 625,
1218
+ 0,
1219
+ 259,
1220
+ 0,
1221
+ "CLIP"
1222
+ ],
1223
+ [
1224
+ 1554,
1225
+ 603,
1226
+ 0,
1227
+ 628,
1228
+ 0,
1229
+ "MODEL"
1230
+ ],
1231
+ [
1232
+ 1555,
1233
+ 603,
1234
+ 1,
1235
+ 628,
1236
+ 1,
1237
+ "LATENT"
1238
+ ],
1239
+ [
1240
+ 1556,
1241
+ 628,
1242
+ 0,
1243
+ 559,
1244
+ 0,
1245
+ "MODEL"
1246
+ ],
1247
+ [
1248
+ 1557,
1249
+ 628,
1250
+ 0,
1251
+ 31,
1252
+ 0,
1253
+ "MODEL"
1254
+ ],
1255
+ [
1256
+ 1560,
1257
+ 632,
1258
+ 0,
1259
+ 265,
1260
+ 0,
1261
+ "IMAGE"
1262
+ ],
1263
+ [
1264
+ 1561,
1265
+ 634,
1266
+ 0,
1267
+ 628,
1268
+ 2,
1269
+ "UNTWISTING_ROPE_EXTENSIONS"
1270
+ ]
1271
+ ],
1272
+ "groups": [],
1273
+ "config": {},
1274
+ "extra": {
1275
+ "ds": {
1276
+ "scale": 0.5559917313492722,
1277
+ "offset": [
1278
+ -62.29068115768874,
1279
+ -429.91256004902806
1280
+ ]
1281
+ },
1282
+ "frontendVersion": "1.44.19",
1283
+ "workflowRendererVersion": "LG",
1284
+ "VHS_latentpreview": false,
1285
+ "VHS_latentpreviewrate": 0,
1286
+ "VHS_MetadataImage": true,
1287
+ "VHS_KeepIntermediate": true
1288
+ },
1289
+ "version": 0.4
1290
+ }
custom_nodes/ComfyUi-Untwisting-RoPE/workflows/workflow_flux2_klein_4b.json ADDED
@@ -0,0 +1,1448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "44259803-f9d6-4eb1-a94a-75b8213649d0",
3
+ "revision": 0,
4
+ "last_node_id": 633,
5
+ "last_link_id": 1565,
6
+ "nodes": [
7
+ {
8
+ "id": 333,
9
+ "type": "VAEEncode",
10
+ "pos": [
11
+ 612.9416976790988,
12
+ 1242.853274396352
13
+ ],
14
+ "size": [
15
+ 140,
16
+ 46
17
+ ],
18
+ "flags": {},
19
+ "order": 21,
20
+ "mode": 0,
21
+ "inputs": [
22
+ {
23
+ "name": "pixels",
24
+ "type": "IMAGE",
25
+ "link": 749
26
+ },
27
+ {
28
+ "name": "vae",
29
+ "type": "VAE",
30
+ "link": 750
31
+ }
32
+ ],
33
+ "outputs": [
34
+ {
35
+ "name": "LATENT",
36
+ "type": "LATENT",
37
+ "links": [
38
+ 1526
39
+ ]
40
+ }
41
+ ],
42
+ "properties": {
43
+ "cnr_id": "comfy-core",
44
+ "ver": "0.21.0",
45
+ "Node name for S&R": "VAEEncode"
46
+ },
47
+ "widgets_values": []
48
+ },
49
+ {
50
+ "id": 559,
51
+ "type": "CFGGuider",
52
+ "pos": [
53
+ 1509.2008112031247,
54
+ 1315.8267637570477
55
+ ],
56
+ "size": [
57
+ 270,
58
+ 98
59
+ ],
60
+ "flags": {},
61
+ "order": 24,
62
+ "mode": 0,
63
+ "inputs": [
64
+ {
65
+ "name": "model",
66
+ "type": "MODEL",
67
+ "link": 1551
68
+ },
69
+ {
70
+ "name": "positive",
71
+ "type": "CONDITIONING",
72
+ "link": 1564
73
+ },
74
+ {
75
+ "name": "negative",
76
+ "type": "CONDITIONING",
77
+ "link": 1400
78
+ }
79
+ ],
80
+ "outputs": [
81
+ {
82
+ "name": "GUIDER",
83
+ "type": "GUIDER",
84
+ "links": [
85
+ 1544
86
+ ]
87
+ }
88
+ ],
89
+ "properties": {
90
+ "cnr_id": "comfy-core",
91
+ "ver": "0.21.1",
92
+ "Node name for S&R": "CFGGuider"
93
+ },
94
+ "widgets_values": [
95
+ 1
96
+ ]
97
+ },
98
+ {
99
+ "id": 616,
100
+ "type": "Note",
101
+ "pos": [
102
+ 1472.1181965831133,
103
+ 1506.4408653175178
104
+ ],
105
+ "size": [
106
+ 303.65604311050856,
107
+ 116.00450279158758
108
+ ],
109
+ "flags": {},
110
+ "order": 0,
111
+ "mode": 0,
112
+ "inputs": [],
113
+ "outputs": [],
114
+ "properties": {},
115
+ "widgets_values": [
116
+ "I strongly recommend using only ancestral samplers, adding noise during the process really helps eliminate some transfer style artifacts."
117
+ ],
118
+ "color": "#c09430",
119
+ "bgcolor": "rgba(24,24,27,.9)"
120
+ },
121
+ {
122
+ "id": 229,
123
+ "type": "KSamplerSelect",
124
+ "pos": [
125
+ 1465.8802446070147,
126
+ 1668.9757189509317
127
+ ],
128
+ "size": [
129
+ 315,
130
+ 58
131
+ ],
132
+ "flags": {},
133
+ "order": 1,
134
+ "mode": 0,
135
+ "inputs": [],
136
+ "outputs": [
137
+ {
138
+ "name": "SAMPLER",
139
+ "type": "SAMPLER",
140
+ "links": [
141
+ 1545
142
+ ]
143
+ }
144
+ ],
145
+ "properties": {
146
+ "cnr_id": "comfy-core",
147
+ "ver": "0.5.0",
148
+ "Node name for S&R": "KSamplerSelect"
149
+ },
150
+ "widgets_values": [
151
+ "euler_ancestral"
152
+ ]
153
+ },
154
+ {
155
+ "id": 167,
156
+ "type": "RandomNoise",
157
+ "pos": [
158
+ 1462.0009592796698,
159
+ 1802.4795320303917
160
+ ],
161
+ "size": [
162
+ 302.7450866699219,
163
+ 82
164
+ ],
165
+ "flags": {},
166
+ "order": 2,
167
+ "mode": 0,
168
+ "inputs": [],
169
+ "outputs": [
170
+ {
171
+ "name": "NOISE",
172
+ "type": "NOISE",
173
+ "links": [
174
+ 1543
175
+ ]
176
+ }
177
+ ],
178
+ "properties": {
179
+ "cnr_id": "comfy-core",
180
+ "ver": "0.3.76",
181
+ "Node name for S&R": "RandomNoise"
182
+ },
183
+ "widgets_values": [
184
+ 42,
185
+ "fixed"
186
+ ]
187
+ },
188
+ {
189
+ "id": 614,
190
+ "type": "Note",
191
+ "pos": [
192
+ 938.3272357908905,
193
+ 1489.0086428159627
194
+ ],
195
+ "size": [
196
+ 303.65604311050856,
197
+ 116.00450279158758
198
+ ],
199
+ "flags": {},
200
+ "order": 3,
201
+ "mode": 0,
202
+ "inputs": [],
203
+ "outputs": [],
204
+ "properties": {},
205
+ "widgets_values": [
206
+ "You can create two CLIP Text Encode (one for the reference and one for the target), but personally, I find that using the target prompt for both yields better results."
207
+ ],
208
+ "color": "#c09430",
209
+ "bgcolor": "rgba(24,24,27,.9)"
210
+ },
211
+ {
212
+ "id": 622,
213
+ "type": "SamplerCustomAdvanced",
214
+ "pos": [
215
+ 1847.301918707523,
216
+ 1554.3864451535942
217
+ ],
218
+ "size": [
219
+ 293.89992513107234,
220
+ 456.72464032296625
221
+ ],
222
+ "flags": {},
223
+ "order": 26,
224
+ "mode": 0,
225
+ "inputs": [
226
+ {
227
+ "name": "noise",
228
+ "type": "NOISE",
229
+ "link": 1543
230
+ },
231
+ {
232
+ "name": "guider",
233
+ "type": "GUIDER",
234
+ "link": 1544
235
+ },
236
+ {
237
+ "name": "sampler",
238
+ "type": "SAMPLER",
239
+ "link": 1545
240
+ },
241
+ {
242
+ "name": "sigmas",
243
+ "type": "SIGMAS",
244
+ "link": 1546
245
+ },
246
+ {
247
+ "name": "latent_image",
248
+ "type": "LATENT",
249
+ "link": 1547
250
+ }
251
+ ],
252
+ "outputs": [
253
+ {
254
+ "name": "output",
255
+ "type": "LATENT",
256
+ "links": [
257
+ 1548
258
+ ]
259
+ },
260
+ {
261
+ "name": "denoised_output",
262
+ "type": "LATENT",
263
+ "links": null
264
+ }
265
+ ],
266
+ "properties": {
267
+ "cnr_id": "comfy-core",
268
+ "ver": "0.21.1",
269
+ "Node name for S&R": "SamplerCustomAdvanced"
270
+ },
271
+ "widgets_values": []
272
+ },
273
+ {
274
+ "id": 617,
275
+ "type": "PreviewImage",
276
+ "pos": [
277
+ 2439.855735728809,
278
+ 1482.3290866342313
279
+ ],
280
+ "size": [
281
+ 554.574171917292,
282
+ 515.9512940840721
283
+ ],
284
+ "flags": {},
285
+ "order": 28,
286
+ "mode": 0,
287
+ "inputs": [
288
+ {
289
+ "name": "images",
290
+ "type": "IMAGE",
291
+ "link": 1540
292
+ }
293
+ ],
294
+ "outputs": [],
295
+ "properties": {
296
+ "cnr_id": "comfy-core",
297
+ "ver": "0.21.1",
298
+ "Node name for S&R": "PreviewImage"
299
+ },
300
+ "widgets_values": []
301
+ },
302
+ {
303
+ "id": 262,
304
+ "type": "VAEDecode",
305
+ "pos": [
306
+ 2196.558250513236,
307
+ 1538.8662956572043
308
+ ],
309
+ "size": [
310
+ 140,
311
+ 62.2083101328426
312
+ ],
313
+ "flags": {},
314
+ "order": 27,
315
+ "mode": 0,
316
+ "inputs": [
317
+ {
318
+ "name": "samples",
319
+ "type": "LATENT",
320
+ "link": 1548
321
+ },
322
+ {
323
+ "name": "vae",
324
+ "type": "VAE",
325
+ "link": 507
326
+ }
327
+ ],
328
+ "outputs": [
329
+ {
330
+ "name": "IMAGE",
331
+ "type": "IMAGE",
332
+ "links": [
333
+ 1540
334
+ ]
335
+ }
336
+ ],
337
+ "properties": {
338
+ "cnr_id": "comfy-core",
339
+ "ver": "0.21.0",
340
+ "Node name for S&R": "VAEDecode"
341
+ },
342
+ "widgets_values": []
343
+ },
344
+ {
345
+ "id": 615,
346
+ "type": "Note",
347
+ "pos": [
348
+ 806.2680068432485,
349
+ 995.1907751912114
350
+ ],
351
+ "size": [
352
+ 289.0740052806825,
353
+ 112.57343506692268
354
+ ],
355
+ "flags": {},
356
+ "order": 4,
357
+ "mode": 0,
358
+ "inputs": [],
359
+ "outputs": [],
360
+ "properties": {},
361
+ "widgets_values": [
362
+ "The quality of the style transfer depends largely on the quality of the RF inversion. These settings work well, but feel free to try other values."
363
+ ],
364
+ "color": "#c09430",
365
+ "bgcolor": "rgba(24,24,27,.9)"
366
+ },
367
+ {
368
+ "id": 282,
369
+ "type": "EmptySD3LatentImage",
370
+ "pos": [
371
+ 1495.1427323629832,
372
+ 2118.3711928088187
373
+ ],
374
+ "size": [
375
+ 260,
376
+ 168
377
+ ],
378
+ "flags": {},
379
+ "order": 19,
380
+ "mode": 0,
381
+ "inputs": [
382
+ {
383
+ "name": "width",
384
+ "type": "INT",
385
+ "widget": {
386
+ "name": "width"
387
+ },
388
+ "link": 1558
389
+ },
390
+ {
391
+ "name": "height",
392
+ "type": "INT",
393
+ "widget": {
394
+ "name": "height"
395
+ },
396
+ "link": 1559
397
+ }
398
+ ],
399
+ "outputs": [
400
+ {
401
+ "name": "LATENT",
402
+ "type": "LATENT",
403
+ "slot_index": 0,
404
+ "links": [
405
+ 1547
406
+ ]
407
+ }
408
+ ],
409
+ "properties": {
410
+ "cnr_id": "comfy-core",
411
+ "ver": "0.3.64",
412
+ "Node name for S&R": "EmptySD3LatentImage",
413
+ "enableTabs": false,
414
+ "tabWidth": 65,
415
+ "tabXOffset": 10,
416
+ "hasSecondTab": false,
417
+ "secondTabText": "Send Back",
418
+ "secondTabOffset": 80,
419
+ "secondTabWidth": 65
420
+ },
421
+ "widgets_values": [
422
+ 1024,
423
+ 1024,
424
+ 1
425
+ ]
426
+ },
427
+ {
428
+ "id": 603,
429
+ "type": "RFInversion",
430
+ "pos": [
431
+ 812.2907721832939,
432
+ 1175.3247940381746
433
+ ],
434
+ "size": [
435
+ 273.3614812972471,
436
+ 240.5904011287812
437
+ ],
438
+ "flags": {},
439
+ "order": 22,
440
+ "mode": 0,
441
+ "inputs": [
442
+ {
443
+ "name": "model",
444
+ "type": "MODEL",
445
+ "link": 1528
446
+ },
447
+ {
448
+ "name": "reference_latent",
449
+ "type": "LATENT",
450
+ "link": 1526
451
+ },
452
+ {
453
+ "name": "ref_conditioning",
454
+ "shape": 7,
455
+ "type": "CONDITIONING",
456
+ "link": 1563
457
+ }
458
+ ],
459
+ "outputs": [
460
+ {
461
+ "name": "model",
462
+ "type": "MODEL",
463
+ "links": [
464
+ 1549
465
+ ]
466
+ },
467
+ {
468
+ "name": "rf_inversion",
469
+ "type": "LATENT",
470
+ "links": [
471
+ 1550
472
+ ]
473
+ }
474
+ ],
475
+ "properties": {
476
+ "cnr_id": "untwistingrope",
477
+ "ver": "c9136fcced444ea84778a25a37a2b45371ea06a5",
478
+ "Node name for S&R": "RFInversion",
479
+ "aux_id": "BigStationW/ComfyUi-Untwisting-RoPE"
480
+ },
481
+ "widgets_values": [
482
+ "rf_gamma_rk2",
483
+ 0.5,
484
+ 2,
485
+ 1,
486
+ 0.5,
487
+ false
488
+ ]
489
+ },
490
+ {
491
+ "id": 625,
492
+ "type": "UnofficialExtensions",
493
+ "pos": [
494
+ 756.9930458838446,
495
+ 752.5776369801828
496
+ ],
497
+ "size": [
498
+ 332.76171875,
499
+ 82
500
+ ],
501
+ "flags": {},
502
+ "order": 5,
503
+ "mode": 0,
504
+ "inputs": [],
505
+ "outputs": [
506
+ {
507
+ "name": "unofficial_extensions",
508
+ "type": "UNTWISTING_ROPE_EXTENSIONS",
509
+ "links": [
510
+ 1553
511
+ ]
512
+ }
513
+ ],
514
+ "properties": {
515
+ "cnr_id": "untwistingrope",
516
+ "ver": "ec08050c160633dc890972120598e2912ce26870",
517
+ "Node name for S&R": "UnofficialExtensions"
518
+ },
519
+ "widgets_values": [
520
+ false,
521
+ 0.5
522
+ ]
523
+ },
524
+ {
525
+ "id": 31,
526
+ "type": "BasicScheduler",
527
+ "pos": [
528
+ 1485.7528126778984,
529
+ 1963.3681052602142
530
+ ],
531
+ "size": [
532
+ 270,
533
+ 106
534
+ ],
535
+ "flags": {},
536
+ "order": 25,
537
+ "mode": 0,
538
+ "inputs": [
539
+ {
540
+ "name": "model",
541
+ "type": "MODEL",
542
+ "link": 1552
543
+ }
544
+ ],
545
+ "outputs": [
546
+ {
547
+ "name": "SIGMAS",
548
+ "type": "SIGMAS",
549
+ "links": [
550
+ 1546
551
+ ]
552
+ }
553
+ ],
554
+ "properties": {
555
+ "cnr_id": "comfy-core",
556
+ "ver": "0.3.75",
557
+ "Node name for S&R": "BasicScheduler"
558
+ },
559
+ "widgets_values": [
560
+ "simple",
561
+ 8,
562
+ 1
563
+ ]
564
+ },
565
+ {
566
+ "id": 626,
567
+ "type": "Note",
568
+ "pos": [
569
+ 790.77580514417,
570
+ 563.2699666343891
571
+ ],
572
+ "size": [
573
+ 285.24835336919455,
574
+ 126.58960944919556
575
+ ],
576
+ "flags": {},
577
+ "order": 6,
578
+ "mode": 0,
579
+ "inputs": [],
580
+ "outputs": [],
581
+ "properties": {},
582
+ "widgets_values": [
583
+ "Some additional methods not included in the paper, intended to further improve the results. These can be bypassed/removed."
584
+ ],
585
+ "color": "#c09430",
586
+ "bgcolor": "rgba(24,24,27,.9)"
587
+ },
588
+ {
589
+ "id": 630,
590
+ "type": "ImageScaleToTotalPixelsX",
591
+ "pos": [
592
+ 207.89817918424777,
593
+ 2011.1821978225
594
+ ],
595
+ "size": [
596
+ 306.5982421875,
597
+ 220.0000000000001
598
+ ],
599
+ "flags": {},
600
+ "order": 15,
601
+ "mode": 0,
602
+ "inputs": [
603
+ {
604
+ "name": "image",
605
+ "type": "IMAGE",
606
+ "link": 1555
607
+ },
608
+ {
609
+ "name": "width",
610
+ "shape": 7,
611
+ "type": "INT",
612
+ "link": null
613
+ },
614
+ {
615
+ "name": "height",
616
+ "shape": 7,
617
+ "type": "INT",
618
+ "link": null
619
+ }
620
+ ],
621
+ "outputs": [
622
+ {
623
+ "name": "image",
624
+ "type": "IMAGE",
625
+ "links": [
626
+ 1560
627
+ ]
628
+ },
629
+ {
630
+ "name": "width",
631
+ "type": "INT",
632
+ "links": [
633
+ 1556,
634
+ 1558
635
+ ]
636
+ },
637
+ {
638
+ "name": "height",
639
+ "type": "INT",
640
+ "links": [
641
+ 1557,
642
+ 1559
643
+ ]
644
+ }
645
+ ],
646
+ "properties": {
647
+ "aux_id": "BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced",
648
+ "ver": "dd4135f4ee6dcd71443e2935ceb5c037e3f23230",
649
+ "Node name for S&R": "ImageScaleToTotalPixelsX",
650
+ "cnr_id": "scale-image-to-total-pixels-advanced"
651
+ },
652
+ "widgets_values": [
653
+ 1.05,
654
+ 16,
655
+ "crop",
656
+ "lanczos"
657
+ ]
658
+ },
659
+ {
660
+ "id": 261,
661
+ "type": "VAELoader",
662
+ "pos": [
663
+ 401.8293929216277,
664
+ 1468.6068452940938
665
+ ],
666
+ "size": [
667
+ 270,
668
+ 58
669
+ ],
670
+ "flags": {},
671
+ "order": 7,
672
+ "mode": 0,
673
+ "inputs": [],
674
+ "outputs": [
675
+ {
676
+ "name": "VAE",
677
+ "type": "VAE",
678
+ "links": [
679
+ 507,
680
+ 750,
681
+ 1561
682
+ ]
683
+ }
684
+ ],
685
+ "properties": {
686
+ "cnr_id": "comfy-core",
687
+ "ver": "0.21.0",
688
+ "Node name for S&R": "VAELoader"
689
+ },
690
+ "widgets_values": [
691
+ "flux2-vae.safetensors"
692
+ ]
693
+ },
694
+ {
695
+ "id": 612,
696
+ "type": "LoadImage",
697
+ "pos": [
698
+ -102.84151691065208,
699
+ 1161.3938579968244
700
+ ],
701
+ "size": [
702
+ 282.798828125,
703
+ 314.00000000000006
704
+ ],
705
+ "flags": {},
706
+ "order": 8,
707
+ "mode": 0,
708
+ "inputs": [],
709
+ "outputs": [
710
+ {
711
+ "name": "IMAGE",
712
+ "type": "IMAGE",
713
+ "links": [
714
+ 1539
715
+ ]
716
+ },
717
+ {
718
+ "name": "MASK",
719
+ "type": "MASK",
720
+ "links": null
721
+ }
722
+ ],
723
+ "title": "STYLE IMAGE",
724
+ "properties": {
725
+ "cnr_id": "comfy-core",
726
+ "ver": "0.21.1",
727
+ "Node name for S&R": "LoadImage"
728
+ },
729
+ "widgets_values": [
730
+ "image (13).png",
731
+ "image"
732
+ ]
733
+ },
734
+ {
735
+ "id": 629,
736
+ "type": "LoadImage",
737
+ "pos": [
738
+ -140.0907890196538,
739
+ 1973.6047431935674
740
+ ],
741
+ "size": [
742
+ 282.798828125,
743
+ 314.00000000000006
744
+ ],
745
+ "flags": {},
746
+ "order": 9,
747
+ "mode": 0,
748
+ "inputs": [],
749
+ "outputs": [
750
+ {
751
+ "name": "IMAGE",
752
+ "type": "IMAGE",
753
+ "links": [
754
+ 1555
755
+ ]
756
+ },
757
+ {
758
+ "name": "MASK",
759
+ "type": "MASK",
760
+ "links": null
761
+ }
762
+ ],
763
+ "title": "IMAGE INPUT",
764
+ "properties": {
765
+ "cnr_id": "comfy-core",
766
+ "ver": "0.21.1",
767
+ "Node name for S&R": "LoadImage"
768
+ },
769
+ "widgets_values": [
770
+ "image (23).png",
771
+ "image"
772
+ ]
773
+ },
774
+ {
775
+ "id": 259,
776
+ "type": "CLIPTextEncode",
777
+ "pos": [
778
+ 863.7412348286646,
779
+ 1921.0253244980258
780
+ ],
781
+ "size": [
782
+ 400,
783
+ 200
784
+ ],
785
+ "flags": {},
786
+ "order": 17,
787
+ "mode": 0,
788
+ "inputs": [
789
+ {
790
+ "name": "clip",
791
+ "type": "CLIP",
792
+ "link": 1542
793
+ }
794
+ ],
795
+ "outputs": [
796
+ {
797
+ "name": "CONDITIONING",
798
+ "type": "CONDITIONING",
799
+ "links": [
800
+ 1400
801
+ ]
802
+ }
803
+ ],
804
+ "properties": {
805
+ "cnr_id": "comfy-core",
806
+ "ver": "0.21.0",
807
+ "Node name for S&R": "CLIPTextEncode"
808
+ },
809
+ "widgets_values": [
810
+ ""
811
+ ]
812
+ },
813
+ {
814
+ "id": 607,
815
+ "type": "CLIPTextEncode",
816
+ "pos": [
817
+ 887.9401977810033,
818
+ 1654.9431345297862
819
+ ],
820
+ "size": [
821
+ 400,
822
+ 200
823
+ ],
824
+ "flags": {},
825
+ "order": 16,
826
+ "mode": 0,
827
+ "inputs": [
828
+ {
829
+ "name": "clip",
830
+ "type": "CLIP",
831
+ "link": 1541
832
+ }
833
+ ],
834
+ "outputs": [
835
+ {
836
+ "name": "CONDITIONING",
837
+ "type": "CONDITIONING",
838
+ "links": [
839
+ 1562
840
+ ]
841
+ }
842
+ ],
843
+ "properties": {
844
+ "cnr_id": "comfy-core",
845
+ "ver": "0.21.0",
846
+ "Node name for S&R": "CLIPTextEncode"
847
+ },
848
+ "widgets_values": [
849
+ "Turn this image into an anime-style drawing."
850
+ ]
851
+ },
852
+ {
853
+ "id": 619,
854
+ "type": "Note",
855
+ "pos": [
856
+ 261.6234944497743,
857
+ 980.8806213289101
858
+ ],
859
+ "size": [
860
+ 289.0740052806825,
861
+ 112.57343506692268
862
+ ],
863
+ "flags": {},
864
+ "order": 10,
865
+ "mode": 0,
866
+ "inputs": [],
867
+ "outputs": [],
868
+ "properties": {},
869
+ "widgets_values": [
870
+ "https://github.com/BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced"
871
+ ],
872
+ "color": "#c09430",
873
+ "bgcolor": "rgba(24,24,27,.9)"
874
+ },
875
+ {
876
+ "id": 631,
877
+ "type": "ConditioningAddImageReference",
878
+ "pos": [
879
+ 892.3358430516128,
880
+ 2359.6616107399786
881
+ ],
882
+ "size": [
883
+ 330.421484375,
884
+ 138
885
+ ],
886
+ "flags": {},
887
+ "order": 20,
888
+ "mode": 0,
889
+ "inputs": [
890
+ {
891
+ "name": "conditioning",
892
+ "type": "CONDITIONING",
893
+ "link": 1562
894
+ },
895
+ {
896
+ "name": "vae",
897
+ "shape": 7,
898
+ "type": "VAE",
899
+ "link": 1561
900
+ },
901
+ {
902
+ "name": "image1",
903
+ "shape": 7,
904
+ "type": "IMAGE",
905
+ "link": 1560
906
+ },
907
+ {
908
+ "name": "image2",
909
+ "shape": 7,
910
+ "type": "IMAGE",
911
+ "link": null
912
+ },
913
+ {
914
+ "name": "image3",
915
+ "shape": 7,
916
+ "type": "IMAGE",
917
+ "link": null
918
+ }
919
+ ],
920
+ "outputs": [
921
+ {
922
+ "name": "CONDITIONING",
923
+ "type": "CONDITIONING",
924
+ "links": [
925
+ 1563,
926
+ 1564
927
+ ]
928
+ }
929
+ ],
930
+ "properties": {
931
+ "cnr_id": "textencodeeditadvanced",
932
+ "ver": "1.0.1",
933
+ "Node name for S&R": "ConditioningAddImageReference"
934
+ },
935
+ "widgets_values": [
936
+ "1"
937
+ ]
938
+ },
939
+ {
940
+ "id": 632,
941
+ "type": "Note",
942
+ "pos": [
943
+ 912.6467429880594,
944
+ 2186.9547075194696
945
+ ],
946
+ "size": [
947
+ 289.0740052806825,
948
+ 112.57343506692268
949
+ ],
950
+ "flags": {},
951
+ "order": 11,
952
+ "mode": 0,
953
+ "inputs": [],
954
+ "outputs": [],
955
+ "properties": {},
956
+ "widgets_values": [
957
+ "https://github.com/BigStationW/ComfyUi-TextEncodeEditAdvanced\n\nTo get a regular text to image framework, set max_images_allowed = 0"
958
+ ],
959
+ "color": "#c09430",
960
+ "bgcolor": "rgba(24,24,27,.9)"
961
+ },
962
+ {
963
+ "id": 611,
964
+ "type": "Note",
965
+ "pos": [
966
+ 1145.1572733432688,
967
+ 902.1563553466156
968
+ ],
969
+ "size": [
970
+ 279.1044491449052,
971
+ 190.5600226272877
972
+ ],
973
+ "flags": {},
974
+ "order": 12,
975
+ "mode": 0,
976
+ "inputs": [],
977
+ "outputs": [],
978
+ "properties": {},
979
+ "widgets_values": [
980
+ "The untwisting RoPE paper suggests patching only the single blocks on flux 1.\n\nFor flux 2 (e.g Klein 4b), the blocks are:\n- Double blocks: 0-4\n- Single blocks: 5-24\n\nPersonally, I find that it works best when all the blocks are enabled, therefore the default values range is 0-999"
981
+ ],
982
+ "color": "#c09430",
983
+ "bgcolor": "rgba(24,24,27,.9)"
984
+ },
985
+ {
986
+ "id": 601,
987
+ "type": "UNETLoader",
988
+ "pos": [
989
+ 318.4707979380336,
990
+ 1596.0524486504232
991
+ ],
992
+ "size": [
993
+ 420.10165345254075,
994
+ 102.39426790580865
995
+ ],
996
+ "flags": {},
997
+ "order": 13,
998
+ "mode": 0,
999
+ "inputs": [],
1000
+ "outputs": [
1001
+ {
1002
+ "name": "MODEL",
1003
+ "type": "MODEL",
1004
+ "links": [
1005
+ 1528
1006
+ ]
1007
+ }
1008
+ ],
1009
+ "properties": {
1010
+ "cnr_id": "comfy-core",
1011
+ "ver": "0.22.0",
1012
+ "Node name for S&R": "UNETLoader"
1013
+ },
1014
+ "widgets_values": [
1015
+ "Flux Klein\\flux-2-klein-4b.safetensors",
1016
+ "default"
1017
+ ]
1018
+ },
1019
+ {
1020
+ "id": 618,
1021
+ "type": "CLIPLoader",
1022
+ "pos": [
1023
+ 455.9699324836801,
1024
+ 1791.462131053674
1025
+ ],
1026
+ "size": [
1027
+ 270,
1028
+ 106
1029
+ ],
1030
+ "flags": {},
1031
+ "order": 14,
1032
+ "mode": 0,
1033
+ "inputs": [],
1034
+ "outputs": [
1035
+ {
1036
+ "name": "CLIP",
1037
+ "type": "CLIP",
1038
+ "links": [
1039
+ 1541,
1040
+ 1542
1041
+ ]
1042
+ }
1043
+ ],
1044
+ "properties": {
1045
+ "cnr_id": "comfy-core",
1046
+ "ver": "0.21.1",
1047
+ "Node name for S&R": "CLIPLoader"
1048
+ },
1049
+ "widgets_values": [
1050
+ "qwen_3_4b.safetensors",
1051
+ "flux2",
1052
+ "default"
1053
+ ]
1054
+ },
1055
+ {
1056
+ "id": 623,
1057
+ "type": "UntwistingRoPE",
1058
+ "pos": [
1059
+ 1136.956054943152,
1060
+ 1171.7011951213472
1061
+ ],
1062
+ "size": [
1063
+ 270,
1064
+ 270
1065
+ ],
1066
+ "flags": {},
1067
+ "order": 23,
1068
+ "mode": 0,
1069
+ "inputs": [
1070
+ {
1071
+ "name": "model",
1072
+ "type": "MODEL",
1073
+ "link": 1549
1074
+ },
1075
+ {
1076
+ "name": "rf_inversion",
1077
+ "shape": 7,
1078
+ "type": "LATENT",
1079
+ "link": 1550
1080
+ },
1081
+ {
1082
+ "name": "unofficial_extensions",
1083
+ "shape": 7,
1084
+ "type": "UNTWISTING_ROPE_EXTENSIONS",
1085
+ "link": 1553
1086
+ }
1087
+ ],
1088
+ "outputs": [
1089
+ {
1090
+ "name": "model",
1091
+ "type": "MODEL",
1092
+ "links": [
1093
+ 1551,
1094
+ 1552
1095
+ ]
1096
+ }
1097
+ ],
1098
+ "properties": {
1099
+ "cnr_id": "untwistingrope",
1100
+ "ver": "9fb6a19e82077dc54ddb120f202d474d01497cf7",
1101
+ "Node name for S&R": "UntwistingRoPE"
1102
+ },
1103
+ "widgets_values": [
1104
+ 10,
1105
+ 0.9,
1106
+ 0,
1107
+ 1,
1108
+ 5,
1109
+ 0.5,
1110
+ "0-999",
1111
+ true
1112
+ ]
1113
+ },
1114
+ {
1115
+ "id": 265,
1116
+ "type": "ImageScaleToTotalPixelsX",
1117
+ "pos": [
1118
+ 246.99230874069832,
1119
+ 1164.5446997368606
1120
+ ],
1121
+ "size": [
1122
+ 306.5982421875,
1123
+ 220.0000000000001
1124
+ ],
1125
+ "flags": {},
1126
+ "order": 18,
1127
+ "mode": 0,
1128
+ "inputs": [
1129
+ {
1130
+ "name": "image",
1131
+ "type": "IMAGE",
1132
+ "link": 1539
1133
+ },
1134
+ {
1135
+ "name": "width",
1136
+ "shape": 7,
1137
+ "type": "INT",
1138
+ "link": 1556
1139
+ },
1140
+ {
1141
+ "name": "height",
1142
+ "shape": 7,
1143
+ "type": "INT",
1144
+ "link": 1557
1145
+ }
1146
+ ],
1147
+ "outputs": [
1148
+ {
1149
+ "name": "image",
1150
+ "type": "IMAGE",
1151
+ "links": [
1152
+ 749
1153
+ ]
1154
+ },
1155
+ {
1156
+ "name": "width",
1157
+ "type": "INT",
1158
+ "links": []
1159
+ },
1160
+ {
1161
+ "name": "height",
1162
+ "type": "INT",
1163
+ "links": []
1164
+ }
1165
+ ],
1166
+ "properties": {
1167
+ "aux_id": "BigStationW/ComfyUi-Scale-Image-to-Total-Pixels-Advanced",
1168
+ "ver": "dd4135f4ee6dcd71443e2935ceb5c037e3f23230",
1169
+ "Node name for S&R": "ImageScaleToTotalPixelsX",
1170
+ "cnr_id": "scale-image-to-total-pixels-advanced"
1171
+ },
1172
+ "widgets_values": [
1173
+ 1.05,
1174
+ 16,
1175
+ "crop",
1176
+ "lanczos"
1177
+ ]
1178
+ }
1179
+ ],
1180
+ "links": [
1181
+ [
1182
+ 507,
1183
+ 261,
1184
+ 0,
1185
+ 262,
1186
+ 1,
1187
+ "VAE"
1188
+ ],
1189
+ [
1190
+ 749,
1191
+ 265,
1192
+ 0,
1193
+ 333,
1194
+ 0,
1195
+ "IMAGE"
1196
+ ],
1197
+ [
1198
+ 750,
1199
+ 261,
1200
+ 0,
1201
+ 333,
1202
+ 1,
1203
+ "VAE"
1204
+ ],
1205
+ [
1206
+ 1400,
1207
+ 259,
1208
+ 0,
1209
+ 559,
1210
+ 2,
1211
+ "CONDITIONING"
1212
+ ],
1213
+ [
1214
+ 1526,
1215
+ 333,
1216
+ 0,
1217
+ 603,
1218
+ 1,
1219
+ "LATENT"
1220
+ ],
1221
+ [
1222
+ 1528,
1223
+ 601,
1224
+ 0,
1225
+ 603,
1226
+ 0,
1227
+ "MODEL"
1228
+ ],
1229
+ [
1230
+ 1539,
1231
+ 612,
1232
+ 0,
1233
+ 265,
1234
+ 0,
1235
+ "IMAGE"
1236
+ ],
1237
+ [
1238
+ 1540,
1239
+ 262,
1240
+ 0,
1241
+ 617,
1242
+ 0,
1243
+ "IMAGE"
1244
+ ],
1245
+ [
1246
+ 1541,
1247
+ 618,
1248
+ 0,
1249
+ 607,
1250
+ 0,
1251
+ "CLIP"
1252
+ ],
1253
+ [
1254
+ 1542,
1255
+ 618,
1256
+ 0,
1257
+ 259,
1258
+ 0,
1259
+ "CLIP"
1260
+ ],
1261
+ [
1262
+ 1543,
1263
+ 167,
1264
+ 0,
1265
+ 622,
1266
+ 0,
1267
+ "NOISE"
1268
+ ],
1269
+ [
1270
+ 1544,
1271
+ 559,
1272
+ 0,
1273
+ 622,
1274
+ 1,
1275
+ "GUIDER"
1276
+ ],
1277
+ [
1278
+ 1545,
1279
+ 229,
1280
+ 0,
1281
+ 622,
1282
+ 2,
1283
+ "SAMPLER"
1284
+ ],
1285
+ [
1286
+ 1546,
1287
+ 31,
1288
+ 0,
1289
+ 622,
1290
+ 3,
1291
+ "SIGMAS"
1292
+ ],
1293
+ [
1294
+ 1547,
1295
+ 282,
1296
+ 0,
1297
+ 622,
1298
+ 4,
1299
+ "LATENT"
1300
+ ],
1301
+ [
1302
+ 1548,
1303
+ 622,
1304
+ 0,
1305
+ 262,
1306
+ 0,
1307
+ "LATENT"
1308
+ ],
1309
+ [
1310
+ 1549,
1311
+ 603,
1312
+ 0,
1313
+ 623,
1314
+ 0,
1315
+ "MODEL"
1316
+ ],
1317
+ [
1318
+ 1550,
1319
+ 603,
1320
+ 1,
1321
+ 623,
1322
+ 1,
1323
+ "LATENT"
1324
+ ],
1325
+ [
1326
+ 1551,
1327
+ 623,
1328
+ 0,
1329
+ 559,
1330
+ 0,
1331
+ "MODEL"
1332
+ ],
1333
+ [
1334
+ 1552,
1335
+ 623,
1336
+ 0,
1337
+ 31,
1338
+ 0,
1339
+ "MODEL"
1340
+ ],
1341
+ [
1342
+ 1553,
1343
+ 625,
1344
+ 0,
1345
+ 623,
1346
+ 2,
1347
+ "UNTWISTING_ROPE_EXTENSIONS"
1348
+ ],
1349
+ [
1350
+ 1555,
1351
+ 629,
1352
+ 0,
1353
+ 630,
1354
+ 0,
1355
+ "IMAGE"
1356
+ ],
1357
+ [
1358
+ 1556,
1359
+ 630,
1360
+ 1,
1361
+ 265,
1362
+ 1,
1363
+ "INT"
1364
+ ],
1365
+ [
1366
+ 1557,
1367
+ 630,
1368
+ 2,
1369
+ 265,
1370
+ 2,
1371
+ "INT"
1372
+ ],
1373
+ [
1374
+ 1558,
1375
+ 630,
1376
+ 1,
1377
+ 282,
1378
+ 0,
1379
+ "INT"
1380
+ ],
1381
+ [
1382
+ 1559,
1383
+ 630,
1384
+ 2,
1385
+ 282,
1386
+ 1,
1387
+ "INT"
1388
+ ],
1389
+ [
1390
+ 1560,
1391
+ 630,
1392
+ 0,
1393
+ 631,
1394
+ 2,
1395
+ "IMAGE"
1396
+ ],
1397
+ [
1398
+ 1561,
1399
+ 261,
1400
+ 0,
1401
+ 631,
1402
+ 1,
1403
+ "VAE"
1404
+ ],
1405
+ [
1406
+ 1562,
1407
+ 607,
1408
+ 0,
1409
+ 631,
1410
+ 0,
1411
+ "CONDITIONING"
1412
+ ],
1413
+ [
1414
+ 1563,
1415
+ 631,
1416
+ 0,
1417
+ 603,
1418
+ 2,
1419
+ "CONDITIONING"
1420
+ ],
1421
+ [
1422
+ 1564,
1423
+ 631,
1424
+ 0,
1425
+ 559,
1426
+ 1,
1427
+ "CONDITIONING"
1428
+ ]
1429
+ ],
1430
+ "groups": [],
1431
+ "config": {},
1432
+ "extra": {
1433
+ "ds": {
1434
+ "scale": 0.3138428376721038,
1435
+ "offset": [
1436
+ 850.689295917384,
1437
+ -637.5162532732992
1438
+ ]
1439
+ },
1440
+ "frontendVersion": "1.44.19",
1441
+ "workflowRendererVersion": "LG",
1442
+ "VHS_latentpreview": false,
1443
+ "VHS_latentpreviewrate": 0,
1444
+ "VHS_MetadataImage": true,
1445
+ "VHS_KeepIntermediate": true
1446
+ },
1447
+ "version": 0.4
1448
+ }